_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
89b9a1949b01eda6db3d2d7cf484286b9f9081dd392709e74361537207ec3bb8
zjhmale/Ntha
Encoding.hs
-- | Prviding some Z3 encoding for certain language constructs Require a Class . SMT context to work module Ntha.Z3.Encoding ( -- ** Heterogenous list, a hack to encode different "term" into a list -- Used to encode function argument list HeteroList(..), -- ** encode function application encodeApp, -- ** encode datatype definition encodeDataType ) where import Ntha.Z3.Class import Z3.Monad hiding (mkMap, App) data HeteroList where Cons :: forall a. (Z3Sorted a, Z3Encoded a) => a -> HeteroList -> HeteroList Nil :: HeteroList instance Eq HeteroList where Nil == Nil = True Cons _ h1 == Cons _ h2 = h1 == h2 _ == _ = False mapH :: (forall a. (Z3Sorted a, Z3Encoded a) => a -> b) -> HeteroList -> [b] mapH _ Nil = [] mapH f (Cons a l) = f a : mapH f l encodeApp :: SMT m e => String -> HeteroList -> Sort -> m e AST encodeApp fname args retSort = do paramSorts <- sequence $ mapH sort args sym <- mkStringSymbol fname decl <- mkFuncDecl sym paramSorts retSort argASTs <- sequence $ mapH encode args mkApp decl argASTs encodeDataType :: SMT m e => Z3Sorted ty => (String, [(String, [(String, ty)])]) -> m e Sort encodeDataType (tyName, alts) = do constrs <- mapM (\(consName, fields) -> do consSym <- mkStringSymbol consName -- recognizer. e.g. is_None None = True, is_None (Some _) = False recogSym <- mkStringSymbol ("is_" ++ consName) flds <- flip mapM fields $ \(fldName, fldTy) -> do symFld <- mkStringSymbol fldName s <- sort fldTy return (symFld, Just s, -1) -- XXX: non-rec mkConstructor consSym recogSym flds ) alts sym <- mkStringSymbol tyName mkDatatype sym constrs
null
https://raw.githubusercontent.com/zjhmale/Ntha/dc47fafddf67cf821c90c5cd72566de67d996238/src/Ntha/Z3/Encoding.hs
haskell
| ** Heterogenous list, a hack to encode different "term" into a list Used to encode function argument list ** encode function application ** encode datatype definition recognizer. e.g. is_None None = True, is_None (Some _) = False XXX: non-rec
Prviding some Z3 encoding for certain language constructs Require a Class . SMT context to work module Ntha.Z3.Encoding ( HeteroList(..), encodeApp, encodeDataType ) where import Ntha.Z3.Class import Z3.Monad hiding (mkMap, App) data HeteroList where Cons :: forall a. (Z3Sorted a, Z3Encoded a) => a -> HeteroList -> HeteroList Nil :: HeteroList instance Eq HeteroList where Nil == Nil = True Cons _ h1 == Cons _ h2 = h1 == h2 _ == _ = False mapH :: (forall a. (Z3Sorted a, Z3Encoded a) => a -> b) -> HeteroList -> [b] mapH _ Nil = [] mapH f (Cons a l) = f a : mapH f l encodeApp :: SMT m e => String -> HeteroList -> Sort -> m e AST encodeApp fname args retSort = do paramSorts <- sequence $ mapH sort args sym <- mkStringSymbol fname decl <- mkFuncDecl sym paramSorts retSort argASTs <- sequence $ mapH encode args mkApp decl argASTs encodeDataType :: SMT m e => Z3Sorted ty => (String, [(String, [(String, ty)])]) -> m e Sort encodeDataType (tyName, alts) = do constrs <- mapM (\(consName, fields) -> do consSym <- mkStringSymbol consName recogSym <- mkStringSymbol ("is_" ++ consName) flds <- flip mapM fields $ \(fldName, fldTy) -> do symFld <- mkStringSymbol fldName s <- sort fldTy mkConstructor consSym recogSym flds ) alts sym <- mkStringSymbol tyName mkDatatype sym constrs
7bbbdde091da34897c3711256d4c2d670aaa7181d7e4924363f89807e086fbdb
gfngfn/SATySFi
type.ml
type t = | TyCon0 of { cname: string; sname: string } cname = name , sname = SATySFi name | TyCon1 of { cname: string; sname: string; t: t } | Product of { ts: t list } | Fun of { dom: t; cod: t } | TyVar of { name: string } | Forall of { var: string; t: t } let none_precedence = 0 let fun_precedence = 10 let prod_precedence = 20 let tapply_precedence = 30 let to_s ~arrow ~prod_open ~prod_sep ~prod_close ~tycon0 ~tycon1 ~tyvar ~forall ppf t = let maybe_paren ~outer_prec self f = if outer_prec > self then begin Format.fprintf ppf "(" end; f (); if outer_prec > self then begin Format.fprintf ppf ")" end in let rec to_s outer_prec ppf = function | TyCon0 {cname; sname} -> tycon0 ~cname ~sname ppf | TyCon1 {cname; sname; t} -> maybe_paren ~outer_prec tapply_precedence (fun () -> tycon1 ~cname ~sname ppf (to_s @@ tapply_precedence + 1) t) | Product {ts} -> maybe_paren ~outer_prec prod_precedence (fun () -> Format.fprintf ppf "%s" prod_open; ts |> List.iteri (fun i t -> Format.fprintf ppf "%s%a" (if i > 0 then prod_sep else "") (to_s @@ prod_precedence + 1) t); Format.fprintf ppf "%s" prod_close) | Fun {dom; cod} -> maybe_paren ~outer_prec fun_precedence (fun () -> (Format.fprintf ppf "%a %s %a" (to_s @@ fun_precedence + 1) dom arrow (to_s fun_precedence) cod)) | TyVar {name} -> tyvar ~name ppf | Forall {var; t} -> forall ~var ppf (to_s outer_prec) t in to_s none_precedence ppf t let to_string t = let tycon0 ~cname:_ ~sname ppf = Format.fprintf ppf "%s" sname in let tycon1 ~cname:_ ~sname ppf pp t = Format.fprintf ppf "%a %s" pp t sname in let tyvar ~name ppf = Format.fprintf ppf "'%s" name in let forall ~var:_ ppf pp t = pp ppf t in Format.asprintf "%a" (to_s ~arrow:"->" ~prod_open:"" ~prod_sep:" * " ~prod_close:"" ~tycon0 ~tycon1 ~tyvar ~forall) t let to_code t = let tycon0 ~cname ~sname:_ ppf = Format.fprintf ppf "%s" cname in let tycon1 ~cname ~sname:_ ppf pp t = Format.fprintf ppf "%s %a" cname pp t in let tyvar ~name ppf = Format.fprintf ppf "%s" name in let forall ~var ppf pp body = Format.fprintf ppf "(let %s = ~@@ (PolyBound(BoundID.fresh UniversalKind ())) in (%a))" var pp body in Format.asprintf "~%% (%a)" (to_s ~arrow:"@->" ~prod_open:"tPROD [" ~prod_sep:"; " ~prod_close:"]" ~tycon0 ~tycon1 ~tyvar ~forall) t let tPROD ts = Product {ts} let (@->) dom cod = Fun {dom; cod} let forall var f = Forall {var; t = f (TyVar {name = var})} let tycon0 cname sname = TyCon0 {cname; sname} let tycon1 cname sname t = TyCon1 {cname; sname; t} let tU = tycon0 "tU" "unit" let tI = tycon0 "tI" "int" let tFL = tycon0 "tFL" "float" let tB = tycon0 "tB" "bool" let tLN = tycon0 "tLN" "length" let tS = tycon0 "tS" "string" let tIT = tycon0 "tIT" "inline-text" let tBT = tycon0 "tBT" "block-text" let tIB = tycon0 "tIB" "inline-boxes" let tBB = tycon0 "tBB" "block-boxes" let tCTX = tycon0 "tCTX" "context" let tTCTX = tycon0 "tTCTX" "text-info" let tPATH = tycon0 "tPATH" "path" let tPRP = tycon0 "tPRP" "pre-path" let tDOC = tycon0 "tDOC" "document" let tMATH = tycon0 "tMATH" "math" let tGR = tycon0 "tGR" "graphics" let tIMG = tycon0 "tIMG" "image" let tRE = tycon0 "tRE" "regexp" let tIPOS = tycon0 "tIPOS" "input-position" let tITMZ = tycon0 "tITMZ" "itemize" let tSCR = tycon0 "tSCR" "script" let tLANG = tycon0 "tLANG" "language" let tCLR = tycon0 "tCLR" "color" let tPG = tycon0 "tPG" "page" let tMATHCLS = tycon0 "tMATHCLS" "math-class" let tMCCLS = tycon0 "tMCCLS" "math-char-class" let tCELL = tycon0 "tCELL" "cell" let tMCSTY = tycon0 "tMCSTY" "math-char-style" let tPAREN = tycon0 "tPAREN" "paren" let tPBINFO = tycon0 "tPBINFO" "page-break-info" let tPAGECONT = tycon0 "tPAGECONT" "page-content-scheme" let tPAGEPARTS = tycon0 "tPAGEPARTS" "page-parts" let tPT = tycon0 "tPT" "point" let tPADS = tycon0 "tPADS" "paddings" let tDECOSET = tycon0 "tDECOSET" "deco-set" let tFONT = tycon0 "tFONT" "font" let tDECO = tycon0 "tDECO" "deco" let tIGR = tycon0 "tIGR" "inline-graphics" let tIGRO = tycon0 "tIGRO" "inline-graphics-outer" let tDOCINFODIC = tycon0 "tDOCINFODIC" "document-information-dictionary" let tL = tycon1 "tL" "list" let tR = tycon1 "tR" "ref" let tOPT = tycon1 "tOPT" "option" let tCODE = tycon1 "tCODE" "code" let tICMD = tycon1 "tICMD" "cmd" let tPCINFO = tPBINFO let tRULESF = tL tLN @-> tL tLN @-> tL tGR let tPAGECONTF = tPBINFO @-> tPAGECONT let tPAGEPARTSF = tPCINFO @-> tPAGEPARTS let tDASH = tPROD [tLN; tLN; tLN] let mckf = tLN @-> tLN @-> tLN
null
https://raw.githubusercontent.com/gfngfn/SATySFi/8a1b1fbefae9c6958d06ee64218619e00ef0afc7/tools/gencode/type.ml
ocaml
type t = | TyCon0 of { cname: string; sname: string } cname = name , sname = SATySFi name | TyCon1 of { cname: string; sname: string; t: t } | Product of { ts: t list } | Fun of { dom: t; cod: t } | TyVar of { name: string } | Forall of { var: string; t: t } let none_precedence = 0 let fun_precedence = 10 let prod_precedence = 20 let tapply_precedence = 30 let to_s ~arrow ~prod_open ~prod_sep ~prod_close ~tycon0 ~tycon1 ~tyvar ~forall ppf t = let maybe_paren ~outer_prec self f = if outer_prec > self then begin Format.fprintf ppf "(" end; f (); if outer_prec > self then begin Format.fprintf ppf ")" end in let rec to_s outer_prec ppf = function | TyCon0 {cname; sname} -> tycon0 ~cname ~sname ppf | TyCon1 {cname; sname; t} -> maybe_paren ~outer_prec tapply_precedence (fun () -> tycon1 ~cname ~sname ppf (to_s @@ tapply_precedence + 1) t) | Product {ts} -> maybe_paren ~outer_prec prod_precedence (fun () -> Format.fprintf ppf "%s" prod_open; ts |> List.iteri (fun i t -> Format.fprintf ppf "%s%a" (if i > 0 then prod_sep else "") (to_s @@ prod_precedence + 1) t); Format.fprintf ppf "%s" prod_close) | Fun {dom; cod} -> maybe_paren ~outer_prec fun_precedence (fun () -> (Format.fprintf ppf "%a %s %a" (to_s @@ fun_precedence + 1) dom arrow (to_s fun_precedence) cod)) | TyVar {name} -> tyvar ~name ppf | Forall {var; t} -> forall ~var ppf (to_s outer_prec) t in to_s none_precedence ppf t let to_string t = let tycon0 ~cname:_ ~sname ppf = Format.fprintf ppf "%s" sname in let tycon1 ~cname:_ ~sname ppf pp t = Format.fprintf ppf "%a %s" pp t sname in let tyvar ~name ppf = Format.fprintf ppf "'%s" name in let forall ~var:_ ppf pp t = pp ppf t in Format.asprintf "%a" (to_s ~arrow:"->" ~prod_open:"" ~prod_sep:" * " ~prod_close:"" ~tycon0 ~tycon1 ~tyvar ~forall) t let to_code t = let tycon0 ~cname ~sname:_ ppf = Format.fprintf ppf "%s" cname in let tycon1 ~cname ~sname:_ ppf pp t = Format.fprintf ppf "%s %a" cname pp t in let tyvar ~name ppf = Format.fprintf ppf "%s" name in let forall ~var ppf pp body = Format.fprintf ppf "(let %s = ~@@ (PolyBound(BoundID.fresh UniversalKind ())) in (%a))" var pp body in Format.asprintf "~%% (%a)" (to_s ~arrow:"@->" ~prod_open:"tPROD [" ~prod_sep:"; " ~prod_close:"]" ~tycon0 ~tycon1 ~tyvar ~forall) t let tPROD ts = Product {ts} let (@->) dom cod = Fun {dom; cod} let forall var f = Forall {var; t = f (TyVar {name = var})} let tycon0 cname sname = TyCon0 {cname; sname} let tycon1 cname sname t = TyCon1 {cname; sname; t} let tU = tycon0 "tU" "unit" let tI = tycon0 "tI" "int" let tFL = tycon0 "tFL" "float" let tB = tycon0 "tB" "bool" let tLN = tycon0 "tLN" "length" let tS = tycon0 "tS" "string" let tIT = tycon0 "tIT" "inline-text" let tBT = tycon0 "tBT" "block-text" let tIB = tycon0 "tIB" "inline-boxes" let tBB = tycon0 "tBB" "block-boxes" let tCTX = tycon0 "tCTX" "context" let tTCTX = tycon0 "tTCTX" "text-info" let tPATH = tycon0 "tPATH" "path" let tPRP = tycon0 "tPRP" "pre-path" let tDOC = tycon0 "tDOC" "document" let tMATH = tycon0 "tMATH" "math" let tGR = tycon0 "tGR" "graphics" let tIMG = tycon0 "tIMG" "image" let tRE = tycon0 "tRE" "regexp" let tIPOS = tycon0 "tIPOS" "input-position" let tITMZ = tycon0 "tITMZ" "itemize" let tSCR = tycon0 "tSCR" "script" let tLANG = tycon0 "tLANG" "language" let tCLR = tycon0 "tCLR" "color" let tPG = tycon0 "tPG" "page" let tMATHCLS = tycon0 "tMATHCLS" "math-class" let tMCCLS = tycon0 "tMCCLS" "math-char-class" let tCELL = tycon0 "tCELL" "cell" let tMCSTY = tycon0 "tMCSTY" "math-char-style" let tPAREN = tycon0 "tPAREN" "paren" let tPBINFO = tycon0 "tPBINFO" "page-break-info" let tPAGECONT = tycon0 "tPAGECONT" "page-content-scheme" let tPAGEPARTS = tycon0 "tPAGEPARTS" "page-parts" let tPT = tycon0 "tPT" "point" let tPADS = tycon0 "tPADS" "paddings" let tDECOSET = tycon0 "tDECOSET" "deco-set" let tFONT = tycon0 "tFONT" "font" let tDECO = tycon0 "tDECO" "deco" let tIGR = tycon0 "tIGR" "inline-graphics" let tIGRO = tycon0 "tIGRO" "inline-graphics-outer" let tDOCINFODIC = tycon0 "tDOCINFODIC" "document-information-dictionary" let tL = tycon1 "tL" "list" let tR = tycon1 "tR" "ref" let tOPT = tycon1 "tOPT" "option" let tCODE = tycon1 "tCODE" "code" let tICMD = tycon1 "tICMD" "cmd" let tPCINFO = tPBINFO let tRULESF = tL tLN @-> tL tLN @-> tL tGR let tPAGECONTF = tPBINFO @-> tPAGECONT let tPAGEPARTSF = tPCINFO @-> tPAGEPARTS let tDASH = tPROD [tLN; tLN; tLN] let mckf = tLN @-> tLN @-> tLN
ed7a8247eae0e267ad4c97067c0b8e8724e253bd1abd96d209a1b53aba510244
ocamllabs/ocaml-modular-implicits
typemod.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , 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 Q Public License version 1.0 . (* *) (***********************************************************************) (* Type-checking of the module language *) open Types open Format val type_module: Env.t -> Parsetree.module_expr -> Typedtree.module_expr val type_structure: Env.t -> Parsetree.structure -> Location.t -> Typedtree.structure * Types.signature * Env.t val type_toplevel_phrase: Env.t -> Parsetree.structure -> Typedtree.structure * Types.signature * Env.t val type_implementation: string -> string -> string -> Env.t -> Parsetree.structure -> Typedtree.structure * Typedtree.module_coercion val type_interface: Env.t -> Parsetree.signature -> Typedtree.signature val transl_signature: Env.t -> Parsetree.signature -> Typedtree.signature val check_nongen_schemes: Env.t -> Typedtree.structure_item list -> unit val type_open_: ?toplevel:bool -> Asttypes.open_flag -> Env.t -> Location.t -> Longident.t Asttypes.loc -> Path.t * Env.t val simplify_signature: signature -> signature val save_signature: string -> Typedtree.signature -> string -> string -> Env.t -> Types.signature_item list -> unit val package_units: Env.t -> string list -> string -> string -> Typedtree.module_coercion type error = Cannot_apply of module_type | Not_included of Includemod.error list | 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.error list | Repeated_name of string * string | Non_generalizable of type_expr | Non_generalizable_class of Ident.t * class_declaration | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | With_need_typeconstr | 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 | Argument_mismatch of Types.module_parameter * Parsetree.module_argument exception Error of Location.t * Env.t * error exception Error_forward of Location.error val report_error: Env.t -> formatter -> error -> unit
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/typing/typemod.mli
ocaml
********************************************************************* OCaml ********************************************************************* Type-checking of the module language
, 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 Q Public License version 1.0 . open Types open Format val type_module: Env.t -> Parsetree.module_expr -> Typedtree.module_expr val type_structure: Env.t -> Parsetree.structure -> Location.t -> Typedtree.structure * Types.signature * Env.t val type_toplevel_phrase: Env.t -> Parsetree.structure -> Typedtree.structure * Types.signature * Env.t val type_implementation: string -> string -> string -> Env.t -> Parsetree.structure -> Typedtree.structure * Typedtree.module_coercion val type_interface: Env.t -> Parsetree.signature -> Typedtree.signature val transl_signature: Env.t -> Parsetree.signature -> Typedtree.signature val check_nongen_schemes: Env.t -> Typedtree.structure_item list -> unit val type_open_: ?toplevel:bool -> Asttypes.open_flag -> Env.t -> Location.t -> Longident.t Asttypes.loc -> Path.t * Env.t val simplify_signature: signature -> signature val save_signature: string -> Typedtree.signature -> string -> string -> Env.t -> Types.signature_item list -> unit val package_units: Env.t -> string list -> string -> string -> Typedtree.module_coercion type error = Cannot_apply of module_type | Not_included of Includemod.error list | 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.error list | Repeated_name of string * string | Non_generalizable of type_expr | Non_generalizable_class of Ident.t * class_declaration | Non_generalizable_module of module_type | Implementation_is_required of string | Interface_not_compiled of string | Not_allowed_in_functor_body | With_need_typeconstr | 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 | Argument_mismatch of Types.module_parameter * Parsetree.module_argument exception Error of Location.t * Env.t * error exception Error_forward of Location.error val report_error: Env.t -> formatter -> error -> unit
f17399fc9f2e422492b96620688c277a83f58c08cdbb84f455b431d0abb9ae5e
brendanhay/terrafomo
Types.hs
-- This module was auto-generated. If it is modified, it will not be overwritten. -- | Module : . Bitbucket . Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.Bitbucket.Types where import Data . Text ( Text ) import Terrafomo -- import Formatting (Format, (%)) import Terrafomo . Bitbucket . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-bitbucket/src/Terrafomo/Bitbucket/Types.hs
haskell
This module was auto-generated. If it is modified, it will not be overwritten. | Stability : auto-generated import Formatting (Format, (%))
Module : . Bitbucket . Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.Bitbucket.Types where import Data . Text ( Text ) import Terrafomo import Terrafomo . Bitbucket . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
20afa1141ea2bbe4e8fff8857066955edd8d71c4e1723a492371277e4c8ca2a4
chaoxu/fancy-walks
48.hs
powMod :: Integer -> Integer -> Integer -> Integer powMod m _ 0 = 1 powMod m a p = (`mod` m) $ if p `mod` 2 == 1 then x*x*a else x*x where x = powMod m a (p `div` 2) m = 10^10 norm str | length str > 10 = norm $ tail str norm str | length str < 10 = norm $ '0':str norm str = str problem_48 = norm $ show $ sum $ map (\n -> powMod m n n) [1..1000] main = putStrLn problem_48
null
https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/48.hs
haskell
powMod :: Integer -> Integer -> Integer -> Integer powMod m _ 0 = 1 powMod m a p = (`mod` m) $ if p `mod` 2 == 1 then x*x*a else x*x where x = powMod m a (p `div` 2) m = 10^10 norm str | length str > 10 = norm $ tail str norm str | length str < 10 = norm $ '0':str norm str = str problem_48 = norm $ show $ sum $ map (\n -> powMod m n n) [1..1000] main = putStrLn problem_48
4a4fafe306b14c3d243cdfded9890e45fda3dc660d879f93ff1ead6195301e04
pa-ba/compdata-param
Annotation.hs
# LANGUAGE TypeOperators , MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , Rank2Types , GADTs , ScopedTypeVariables # UndecidableInstances, Rank2Types, GADTs, ScopedTypeVariables #-} -------------------------------------------------------------------------------- -- | Module : Data . Comp . . Annotation Copyright : ( c ) 2010 - 2011 , -- License : BSD3 Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC Extensions ) -- -- This module defines annotations on signatures. -- -------------------------------------------------------------------------------- module Data.Comp.Param.Annotation ( (:&:) (..), (:*:) (..), DistAnn (..), RemA (..), liftA, liftA', stripA, propAnn, propAnnM, ann, project' ) where import Data.Comp.Param.Difunctor import Data.Comp.Param.Term import Data.Comp.Param.Sum import Data.Comp.Param.Ops import Data.Comp.Param.Algebra import Control.Monad {-| Transform a function with a domain constructed from a functor to a function with a domain constructed with the same functor, but with an additional annotation. -} liftA :: (RemA s s') => (s' a b -> t) -> s a b -> t liftA f v = f (remA v) {-| Transform a function with a domain constructed from a functor to a function with a domain constructed with the same functor, but with an additional annotation. -} liftA' :: (DistAnn s' p s, Difunctor s') => (s' a b -> Cxt h s' c d) -> s a b -> Cxt h s c d liftA' f v = let (v',p) = projectA v in ann p (f v') | Strip the annotations from a term over a functor with annotations . stripA :: (RemA g f, Difunctor g) => CxtFun g f stripA = appSigFun remA | Lift a term homomorphism over signatures and @g@ to a term homomorphism over the same signatures , but extended with annotations . over the same signatures, but extended with annotations. -} propAnn :: (DistAnn f p f', DistAnn g p g', Difunctor g) => Hom f g -> Hom f' g' propAnn hom f' = ann p (hom f) where (f,p) = projectA f' | Lift a monadic term homomorphism over signatures and @g@ to a monadic term homomorphism over the same signatures , but extended with annotations . term homomorphism over the same signatures, but extended with annotations. -} propAnnM :: (DistAnn f p f', DistAnn g p g', Difunctor g, Monad m) => HomM m f g -> HomM m f' g' propAnnM hom f' = liftM (ann p) (hom f) where (f,p) = projectA f' {-| Annotate each node of a term with a constant value. -} ann :: (DistAnn f p g, Difunctor f) => p -> CxtFun f g ann c = appSigFun (injectA c) {-| This function is similar to 'project' but applies to signatures with an annotation which is then ignored. -} project' :: (RemA f f', s :<: f') => Cxt h f a b -> Maybe (s a (Cxt h f a b)) project' (In x) = proj $ remA x project' _ = Nothing
null
https://raw.githubusercontent.com/pa-ba/compdata-param/5d6b0afa95a27fd3233f86e5efc6e6a6080f4236/src/Data/Comp/Param/Annotation.hs
haskell
------------------------------------------------------------------------------ | License : BSD3 Stability : experimental This module defines annotations on signatures. ------------------------------------------------------------------------------ | Transform a function with a domain constructed from a functor to a function with a domain constructed with the same functor, but with an additional annotation. | Transform a function with a domain constructed from a functor to a function with a domain constructed with the same functor, but with an additional annotation. | Annotate each node of a term with a constant value. | This function is similar to 'project' but applies to signatures with an annotation which is then ignored.
# LANGUAGE TypeOperators , MultiParamTypeClasses , FlexibleInstances , UndecidableInstances , Rank2Types , GADTs , ScopedTypeVariables # UndecidableInstances, Rank2Types, GADTs, ScopedTypeVariables #-} Module : Data . Comp . . Annotation Copyright : ( c ) 2010 - 2011 , Maintainer : < > Portability : non - portable ( GHC Extensions ) module Data.Comp.Param.Annotation ( (:&:) (..), (:*:) (..), DistAnn (..), RemA (..), liftA, liftA', stripA, propAnn, propAnnM, ann, project' ) where import Data.Comp.Param.Difunctor import Data.Comp.Param.Term import Data.Comp.Param.Sum import Data.Comp.Param.Ops import Data.Comp.Param.Algebra import Control.Monad liftA :: (RemA s s') => (s' a b -> t) -> s a b -> t liftA f v = f (remA v) liftA' :: (DistAnn s' p s, Difunctor s') => (s' a b -> Cxt h s' c d) -> s a b -> Cxt h s c d liftA' f v = let (v',p) = projectA v in ann p (f v') | Strip the annotations from a term over a functor with annotations . stripA :: (RemA g f, Difunctor g) => CxtFun g f stripA = appSigFun remA | Lift a term homomorphism over signatures and @g@ to a term homomorphism over the same signatures , but extended with annotations . over the same signatures, but extended with annotations. -} propAnn :: (DistAnn f p f', DistAnn g p g', Difunctor g) => Hom f g -> Hom f' g' propAnn hom f' = ann p (hom f) where (f,p) = projectA f' | Lift a monadic term homomorphism over signatures and @g@ to a monadic term homomorphism over the same signatures , but extended with annotations . term homomorphism over the same signatures, but extended with annotations. -} propAnnM :: (DistAnn f p f', DistAnn g p g', Difunctor g, Monad m) => HomM m f g -> HomM m f' g' propAnnM hom f' = liftM (ann p) (hom f) where (f,p) = projectA f' ann :: (DistAnn f p g, Difunctor f) => p -> CxtFun f g ann c = appSigFun (injectA c) project' :: (RemA f f', s :<: f') => Cxt h f a b -> Maybe (s a (Cxt h f a b)) project' (In x) = proj $ remA x project' _ = Nothing
5f52f095cd30b1370b4e7d3d4e8e5ec2cd1ea9274128eb3c54f497cc6fef5c52
nuprl/gradual-typing-performance
checked-cell.rkt
#lang typed/racket (require typed/racket/gui) (require/typed htdp/error [tp-error ((U Symbol String) String Any * -> Nothing)]) (require/typed mzlib/pconvert [print-convert (Any -> String)] [constructor-style-printing (Parameter Any)] [booleans-as-true/false (Parameter Any)] [abbreviate-cons-as-list (Parameter Any)]) (provide checked-cell% Checked-Cell%) (define-type (Checked-Cell% X) (Class (init-field [value0 X] [ok? (X -> Boolean)]) (init [display (Option String) #:optional]) (field [value X] [pb (Option (Instance Pasteboard%))]) [set ((U Symbol String) X -> Any)] [get (-> X)])) (: checked - cell% : Checked - Cell% ) -- Asumu -- why does this line fail ? (define checked-cell% (class object% #:forall (X) (init-field [value0 : X] [ok? : (X -> Boolean)]) (init [display : (Option String) #f]) ; a string is the name of the state display window (field [value : X (coerce "the initial expression" value0 #t)] [pb : (U False (Instance Pasteboard%)) (let ([display display]) (if (boolean? display) #f (let* ([f (new frame% [label display][width 400][height 400])] [p (new pasteboard%)] [e (new editor-canvas% [parent f] [editor p] [style '(hide-hscroll hide-vscroll)])]) (send f show #t) p)))]) (private [show-state : (-> Void)]) (define (show-state) (define xbox #f) ;; x coordinate (throw away) (define ybox ((inst box Real) 0)) ;; y coordinate for next snip (define s (pretty-format (parameterize ([constructor-style-printing #t] [booleans-as-true/false #t] [abbreviate-cons-as-list #t ;; is this beginner or beginner+quote #; (let ([o (open-output-string)]) (print '(1) o) (regexp-match #rx"list" (get-output-string o)))]) (print-convert value)) 40)) ;; turn s into lines and display them in pb (let ([pb (assert pb)] [value value]) (send pb erase) (if (is-a? value snip%) (send pb insert (cast value (Instance Snip%)) 0 0) (parameterize ([current-input-port (open-input-string s)]) (ann (let read-all () (define nxt (read-line)) (unless (eof-object? nxt) (let ([s (make-object string-snip% nxt)]) (send pb insert s 0 (unbox ybox)) (send pb get-snip-location s xbox ybox #t) (read-all)))) Void))))) ;; Symbol Any -> ok? (private [coerce : (case-> ((U String Symbol) X -> X) ((U String Symbol) X Any -> X))]) (define (coerce tag nw [say-evaluated-to #f]) (let ([b (ok? nw)]) (unless (boolean? b) (tp-error 'check-with "the test function ~a is expected to return a boolean, but it returned ~v" (object-name ok?) b)) (unless b (define check-with-name (let ([n (symbol->string (assert (object-name ok?) symbol?))]) (if (regexp-match "check-with" n) "handler" n))) (tp-error 'check-with "~a ~a ~v, which fails to pass check-with's ~a test" tag (if say-evaluated-to "evaluated to" "returned") nw check-with-name)) nw)) ;; Symbol Any -> Void ;; effect: set value to v if distinct, also display it if pb exists (public (set : ((U Symbol String) X -> Any))) (define (set tag v) (define nw (coerce tag v)) this is the old " optimization " for not triggering draw ;; when the world doesn't change ;if (equal? value nw) ; #t (begin (set! value nw) (when pb (show-state)) #f)) ;; -> ok? (public (get : (-> X))) (define (get) value) (super-new) (when pb (show-state)))) ( define c ( new checked - cell% [ msg " World " ] [ value0 1 ] [ ok ? positive ? ] ) ) ( send c set " tick " 10 )
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/2htdp/private/checked-cell.rkt
racket
a string is the name of the state display window x coordinate (throw away) y coordinate for next snip is this beginner or beginner+quote turn s into lines and display them in pb Symbol Any -> ok? Symbol Any -> Void effect: set value to v if distinct, also display it if pb exists when the world doesn't change if (equal? value nw) #t -> ok?
#lang typed/racket (require typed/racket/gui) (require/typed htdp/error [tp-error ((U Symbol String) String Any * -> Nothing)]) (require/typed mzlib/pconvert [print-convert (Any -> String)] [constructor-style-printing (Parameter Any)] [booleans-as-true/false (Parameter Any)] [abbreviate-cons-as-list (Parameter Any)]) (provide checked-cell% Checked-Cell%) (define-type (Checked-Cell% X) (Class (init-field [value0 X] [ok? (X -> Boolean)]) (init [display (Option String) #:optional]) (field [value X] [pb (Option (Instance Pasteboard%))]) [set ((U Symbol String) X -> Any)] [get (-> X)])) (: checked - cell% : Checked - Cell% ) -- Asumu -- why does this line fail ? (define checked-cell% (class object% #:forall (X) (init-field [value0 : X] [ok? : (X -> Boolean)]) (field [value : X (coerce "the initial expression" value0 #t)] [pb : (U False (Instance Pasteboard%)) (let ([display display]) (if (boolean? display) #f (let* ([f (new frame% [label display][width 400][height 400])] [p (new pasteboard%)] [e (new editor-canvas% [parent f] [editor p] [style '(hide-hscroll hide-vscroll)])]) (send f show #t) p)))]) (private [show-state : (-> Void)]) (define (show-state) (define s (pretty-format (parameterize ([constructor-style-printing #t] [booleans-as-true/false #t] [abbreviate-cons-as-list #t (let ([o (open-output-string)]) (print '(1) o) (regexp-match #rx"list" (get-output-string o)))]) (print-convert value)) 40)) (let ([pb (assert pb)] [value value]) (send pb erase) (if (is-a? value snip%) (send pb insert (cast value (Instance Snip%)) 0 0) (parameterize ([current-input-port (open-input-string s)]) (ann (let read-all () (define nxt (read-line)) (unless (eof-object? nxt) (let ([s (make-object string-snip% nxt)]) (send pb insert s 0 (unbox ybox)) (send pb get-snip-location s xbox ybox #t) (read-all)))) Void))))) (private [coerce : (case-> ((U String Symbol) X -> X) ((U String Symbol) X Any -> X))]) (define (coerce tag nw [say-evaluated-to #f]) (let ([b (ok? nw)]) (unless (boolean? b) (tp-error 'check-with "the test function ~a is expected to return a boolean, but it returned ~v" (object-name ok?) b)) (unless b (define check-with-name (let ([n (symbol->string (assert (object-name ok?) symbol?))]) (if (regexp-match "check-with" n) "handler" n))) (tp-error 'check-with "~a ~a ~v, which fails to pass check-with's ~a test" tag (if say-evaluated-to "evaluated to" "returned") nw check-with-name)) nw)) (public (set : ((U Symbol String) X -> Any))) (define (set tag v) (define nw (coerce tag v)) this is the old " optimization " for not triggering draw (begin (set! value nw) (when pb (show-state)) #f)) (public (get : (-> X))) (define (get) value) (super-new) (when pb (show-state)))) ( define c ( new checked - cell% [ msg " World " ] [ value0 1 ] [ ok ? positive ? ] ) ) ( send c set " tick " 10 )
87c738f821df591892df029ccb61e6690698a6a07800be42f447542277e11d49
rubenbarroso/EOPL
5-4-4.scm
This is 5-4-4.scm : flat methods (let ((time-stamp "Time-stamp: <2001-02-24 10:31:05 dfried>")) (eopl:printf "5-4-4.scm - flat methods ~a~%" (substring time-stamp 13 29))) ;;;;;;;;;;;;;;;; classes ;;;;;;;;;;;;;;;; (define-datatype class class? (a-class (class-name symbol?) (super-name symbol?) (field-length integer?) (field-ids (list-of symbol?)) (methods method-environment?))) ;;;; constructing classes (define elaborate-class-decls! (lambda (c-decls) (initialize-class-env!) (for-each elaborate-class-decl! c-decls))) (define elaborate-class-decl! (lambda (c-decl) (let ((super-name (class-decl->super-name c-decl))) (let ((field-ids (append (class-name->field-ids super-name) (class-decl->field-ids c-decl)))) (add-to-class-env! (a-class (class-decl->class-name c-decl) super-name (length field-ids) field-ids (roll-up-method-decls c-decl super-name field-ids))))))) ^ 5 - 4 - 4 ; ; ; This may change for second printing . (define roll-up-method-decls (lambda (c-decl super-name field-ids) (merge-methods (class-name->methods super-name) (map (lambda (m-decl) (a-method m-decl super-name field-ids)) (class-decl->method-decls c-decl))))) ^ 5 - 4 - 4 (define merge-methods (lambda (super-methods methods) (cond ((null? super-methods) methods) (else (let ((overriding-method (lookup-method (method->method-name (car super-methods)) methods))) (if (method? overriding-method) (cons overriding-method (merge-methods (cdr super-methods) (remove-method overriding-method methods))) (cons (car super-methods) (merge-methods (cdr super-methods) methods)))))))) (define remove-method (lambda (method methods) (remv method methods))) (define remv (lambda (x lst) (cond ((null? lst) '()) ((eqv? (car lst) x) (remv x (cdr lst))) (else (cons (car lst) (remv x (cdr lst))))))) ;;;;;;;;;;;;;;;; objects ;;;;;;;;;;;;;;;; ;; an object is now just a single part, with a vector representing the ;; managed storage for the all the fields. (define-datatype object object? (an-object (class-name symbol?) (fields vector?))) (define new-object (lambda (class-name) (an-object class-name (make-vector (class-name->field-length class-name))))) ;;;;;;;;;;;;;;;; methods ;;;;;;;;;;;;;;;; (define-datatype method method? (a-method (m-decl method-decl?) (s-name symbol?) (field-ids (list-of symbol?)))) (define find-method-and-apply ^ 5 - 4 - 4 : no more loop (let ((method (lookup-method m-name (class-name->methods host-name)))) (if (method? method) (apply-method method host-name self args) (eopl:error 'find-method-and-apply "No method for name ~s" m-name))))) (define apply-method (lambda (method host-name self args) (eval-expression (method->body method) (extend-env (cons '%super (cons 'self (method->ids method))) (cons 5 - 4 - 4 (cons self args)) (extend-env-refs (method->field-ids method) (object->fields self) (empty-env)))))) (define rib-find-position (lambda (name symbols) (list-find-last-position name symbols))) ;;;;;;;;;;;;;;;; method environments ;;;;;;;;;;;;;;;; (define method-environment? (list-of method?)) ^ 5 - 4 method - decl = > method (lambda (m-name methods) (cond ((null? methods) #f) ((eqv? m-name (method->method-name (car methods))) (car methods)) (else (lookup-method m-name (cdr methods)))))) ;;;;;;;;;;;;;;;; class environments ;;;;;;;;;;;;;;;; ;;; we'll use the list of classes (not class decls) (define the-class-env '()) (define initialize-class-env! (lambda () (set! the-class-env '()))) (define add-to-class-env! (lambda (class) (set! the-class-env (cons class the-class-env)))) (define lookup-class (lambda (name) (let loop ((env the-class-env)) (cond ((null? env) (eopl:error 'lookup-class "Unknown class ~s" name)) ((eqv? (class->class-name (car env)) name) (car env)) (else (loop (cdr env))))))) ;;;;;;;;;;;;;;;; selectors ;;;;;;;;;;;;;;;; (define class->class-name (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) class-name)))) (define class->super-name (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) super-name)))) (define class->field-length (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) field-length)))) (define class->field-ids (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) field-ids)))) (define class->methods (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) methods)))) (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->fields (lambda (obj) (cases object obj (an-object (class-decl fields) fields)))) (define object->class-decl (lambda (obj) (lookup-class (object->class-name obj)))) (define object->field-ids (lambda (object) (class->field-ids (object->class-decl object)))) (define class-name->super-name (lambda (class-name) (class->super-name (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (if (eqv? class-name 'object) '() (class->field-ids (lookup-class class-name))))) (define class-name->methods (lambda (class-name) (if (eqv? class-name 'object) '() (class->methods (lookup-class class-name))))) (define class-name->field-length (lambda (class-name) (if (eqv? class-name 'object) 0 (class->field-length (lookup-class class-name))))) (define method->method-decl (lambda (meth) (cases method meth (a-method (meth-decl super-name field-ids) meth-decl)))) (define method->super-name (lambda (meth) (cases method meth (a-method (meth-decl super-name field-ids) super-name)))) (define method->field-ids (lambda (meth) (cases method meth (a-method (method-decl super-name field-ids) field-ids)))) (define method->method-name (lambda (method) (method-decl->method-name (method->method-decl method)))) (define method->body (lambda (method) (method-decl->body (method->method-decl method)))) (define method->ids (lambda (method) (method-decl->ids (method->method-decl method))))
null
https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/interps/5-4-4.scm
scheme
classes ;;;;;;;;;;;;;;;; constructing classes ; ; This may change for second printing . objects ;;;;;;;;;;;;;;;; an object is now just a single part, with a vector representing the managed storage for the all the fields. methods ;;;;;;;;;;;;;;;; method environments ;;;;;;;;;;;;;;;; class environments ;;;;;;;;;;;;;;;; we'll use the list of classes (not class decls) selectors ;;;;;;;;;;;;;;;;
This is 5-4-4.scm : flat methods (let ((time-stamp "Time-stamp: <2001-02-24 10:31:05 dfried>")) (eopl:printf "5-4-4.scm - flat methods ~a~%" (substring time-stamp 13 29))) (define-datatype class class? (a-class (class-name symbol?) (super-name symbol?) (field-length integer?) (field-ids (list-of symbol?)) (methods method-environment?))) (define elaborate-class-decls! (lambda (c-decls) (initialize-class-env!) (for-each elaborate-class-decl! c-decls))) (define elaborate-class-decl! (lambda (c-decl) (let ((super-name (class-decl->super-name c-decl))) (let ((field-ids (append (class-name->field-ids super-name) (class-decl->field-ids c-decl)))) (add-to-class-env! (a-class (class-decl->class-name c-decl) super-name (length field-ids) field-ids (roll-up-method-decls c-decl super-name field-ids))))))) (define roll-up-method-decls (lambda (c-decl super-name field-ids) (merge-methods (class-name->methods super-name) (map (lambda (m-decl) (a-method m-decl super-name field-ids)) (class-decl->method-decls c-decl))))) ^ 5 - 4 - 4 (define merge-methods (lambda (super-methods methods) (cond ((null? super-methods) methods) (else (let ((overriding-method (lookup-method (method->method-name (car super-methods)) methods))) (if (method? overriding-method) (cons overriding-method (merge-methods (cdr super-methods) (remove-method overriding-method methods))) (cons (car super-methods) (merge-methods (cdr super-methods) methods)))))))) (define remove-method (lambda (method methods) (remv method methods))) (define remv (lambda (x lst) (cond ((null? lst) '()) ((eqv? (car lst) x) (remv x (cdr lst))) (else (cons (car lst) (remv x (cdr lst))))))) (define-datatype object object? (an-object (class-name symbol?) (fields vector?))) (define new-object (lambda (class-name) (an-object class-name (make-vector (class-name->field-length class-name))))) (define-datatype method method? (a-method (m-decl method-decl?) (s-name symbol?) (field-ids (list-of symbol?)))) (define find-method-and-apply ^ 5 - 4 - 4 : no more loop (let ((method (lookup-method m-name (class-name->methods host-name)))) (if (method? method) (apply-method method host-name self args) (eopl:error 'find-method-and-apply "No method for name ~s" m-name))))) (define apply-method (lambda (method host-name self args) (eval-expression (method->body method) (extend-env (cons '%super (cons 'self (method->ids method))) (cons 5 - 4 - 4 (cons self args)) (extend-env-refs (method->field-ids method) (object->fields self) (empty-env)))))) (define rib-find-position (lambda (name symbols) (list-find-last-position name symbols))) (define method-environment? (list-of method?)) ^ 5 - 4 method - decl = > method (lambda (m-name methods) (cond ((null? methods) #f) ((eqv? m-name (method->method-name (car methods))) (car methods)) (else (lookup-method m-name (cdr methods)))))) (define the-class-env '()) (define initialize-class-env! (lambda () (set! the-class-env '()))) (define add-to-class-env! (lambda (class) (set! the-class-env (cons class the-class-env)))) (define lookup-class (lambda (name) (let loop ((env the-class-env)) (cond ((null? env) (eopl:error 'lookup-class "Unknown class ~s" name)) ((eqv? (class->class-name (car env)) name) (car env)) (else (loop (cdr env))))))) (define class->class-name (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) class-name)))) (define class->super-name (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) super-name)))) (define class->field-length (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) field-length)))) (define class->field-ids (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) field-ids)))) (define class->methods (lambda (c-struct) (cases class c-struct (a-class (class-name super-name field-length field-ids methods) methods)))) (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->class-name (lambda (obj) (cases object obj (an-object (class-name fields) class-name)))) (define object->fields (lambda (obj) (cases object obj (an-object (class-decl fields) fields)))) (define object->class-decl (lambda (obj) (lookup-class (object->class-name obj)))) (define object->field-ids (lambda (object) (class->field-ids (object->class-decl object)))) (define class-name->super-name (lambda (class-name) (class->super-name (lookup-class class-name)))) (define class-name->field-ids (lambda (class-name) (if (eqv? class-name 'object) '() (class->field-ids (lookup-class class-name))))) (define class-name->methods (lambda (class-name) (if (eqv? class-name 'object) '() (class->methods (lookup-class class-name))))) (define class-name->field-length (lambda (class-name) (if (eqv? class-name 'object) 0 (class->field-length (lookup-class class-name))))) (define method->method-decl (lambda (meth) (cases method meth (a-method (meth-decl super-name field-ids) meth-decl)))) (define method->super-name (lambda (meth) (cases method meth (a-method (meth-decl super-name field-ids) super-name)))) (define method->field-ids (lambda (meth) (cases method meth (a-method (method-decl super-name field-ids) field-ids)))) (define method->method-name (lambda (method) (method-decl->method-name (method->method-decl method)))) (define method->body (lambda (method) (method-decl->body (method->method-decl method)))) (define method->ids (lambda (method) (method-decl->ids (method->method-decl method))))
3f13cd0540dbd12b93b467f9ad26c62c3103f8c14279f78a7f994d8ce2a10f7a
dgiot/dgiot
emqx_mod_rewrite_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved . %% 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 %% %% -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. %%-------------------------------------------------------------------- -module(emqx_mod_rewrite_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("emqx/include/emqx_mqtt.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(RULES, [{rewrite, pub, <<"x/#">>,<<"^x/y/(.+)$">>,<<"z/y/$1">>}, {rewrite, sub, <<"y/+/z/#">>,<<"^y/(.+)/z/(.+)$">>,<<"y/z/$2">>} ]). all() -> emqx_ct:all(?MODULE). init_per_suite(Config) -> emqx_ct_helpers:boot_modules(all), emqx_ct_helpers:start_apps([emqx_modules]), %% Ensure all the modules unloaded. ok = emqx_modules:unload(), Config. end_per_suite(_Config) -> emqx_ct_helpers:stop_apps([emqx_modules]). %% Test case for emqx_mod_write t_mod_rewrite(_Config) -> ok = emqx_mod_rewrite:load(?RULES), {ok, C} = emqtt:start_link([{clientid, <<"rewrite_client">>}]), {ok, _} = emqtt:connect(C), PubOrigTopics = [<<"x/y/2">>, <<"x/1/2">>], PubDestTopics = [<<"z/y/2">>, <<"x/1/2">>], SubOrigTopics = [<<"y/a/z/b">>, <<"y/def">>], SubDestTopics = [<<"y/z/b">>, <<"y/def">>], %% Sub Rules {ok, _Props, _} = emqtt:subscribe(C, [{Topic, ?QOS_1} || Topic <- SubOrigTopics]), timer:sleep(100), Subscriptions = emqx_broker:subscriptions(<<"rewrite_client">>), ?assertEqual(SubDestTopics, [Topic || {Topic, _SubOpts} <- Subscriptions]), RecvTopics1 = [begin ok = emqtt:publish(C, Topic, <<"payload">>), {ok, #{topic := RecvTopic}} = receive_publish(100), RecvTopic end || Topic <- SubDestTopics], ?assertEqual(SubDestTopics, RecvTopics1), {ok, _, _} = emqtt:unsubscribe(C, SubOrigTopics), timer:sleep(100), ?assertEqual([], emqx_broker:subscriptions(<<"rewrite_client">>)), %% Pub Rules {ok, _Props, _} = emqtt:subscribe(C, [{Topic, ?QOS_1} || Topic <- PubDestTopics]), RecvTopics2 = [begin ok = emqtt:publish(C, Topic, <<"payload">>), {ok, #{topic := RecvTopic}} = receive_publish(100), RecvTopic end || Topic <- PubOrigTopics], ?assertEqual(PubDestTopics, RecvTopics2), {ok, _, _} = emqtt:unsubscribe(C, PubDestTopics), ok = emqtt:disconnect(C), ok = emqx_mod_rewrite:unload(?RULES). t_rewrite_rule(_Config) -> {PubRules, SubRules} = emqx_mod_rewrite:compile(?RULES), ?assertEqual(<<"z/y/2">>, emqx_mod_rewrite:match_and_rewrite(<<"x/y/2">>, PubRules)), ?assertEqual(<<"x/1/2">>, emqx_mod_rewrite:match_and_rewrite(<<"x/1/2">>, PubRules)), ?assertEqual(<<"y/z/b">>, emqx_mod_rewrite:match_and_rewrite(<<"y/a/z/b">>, SubRules)), ?assertEqual(<<"y/def">>, emqx_mod_rewrite:match_and_rewrite(<<"y/def">>, SubRules)). %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- receive_publish(Timeout) -> receive {publish, Publish} -> {ok, Publish} after Timeout -> {error, timeout} end.
null
https://raw.githubusercontent.com/dgiot/dgiot/c9f2f78af71692ba532e4806621b611db2afe0c9/lib-ce/emqx_modules/test/emqx_mod_rewrite_SUITE.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. -------------------------------------------------------------------- Ensure all the modules unloaded. Test case for emqx_mod_write Sub Rules Pub Rules -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_mod_rewrite_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("emqx/include/emqx_mqtt.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(RULES, [{rewrite, pub, <<"x/#">>,<<"^x/y/(.+)$">>,<<"z/y/$1">>}, {rewrite, sub, <<"y/+/z/#">>,<<"^y/(.+)/z/(.+)$">>,<<"y/z/$2">>} ]). all() -> emqx_ct:all(?MODULE). init_per_suite(Config) -> emqx_ct_helpers:boot_modules(all), emqx_ct_helpers:start_apps([emqx_modules]), ok = emqx_modules:unload(), Config. end_per_suite(_Config) -> emqx_ct_helpers:stop_apps([emqx_modules]). t_mod_rewrite(_Config) -> ok = emqx_mod_rewrite:load(?RULES), {ok, C} = emqtt:start_link([{clientid, <<"rewrite_client">>}]), {ok, _} = emqtt:connect(C), PubOrigTopics = [<<"x/y/2">>, <<"x/1/2">>], PubDestTopics = [<<"z/y/2">>, <<"x/1/2">>], SubOrigTopics = [<<"y/a/z/b">>, <<"y/def">>], SubDestTopics = [<<"y/z/b">>, <<"y/def">>], {ok, _Props, _} = emqtt:subscribe(C, [{Topic, ?QOS_1} || Topic <- SubOrigTopics]), timer:sleep(100), Subscriptions = emqx_broker:subscriptions(<<"rewrite_client">>), ?assertEqual(SubDestTopics, [Topic || {Topic, _SubOpts} <- Subscriptions]), RecvTopics1 = [begin ok = emqtt:publish(C, Topic, <<"payload">>), {ok, #{topic := RecvTopic}} = receive_publish(100), RecvTopic end || Topic <- SubDestTopics], ?assertEqual(SubDestTopics, RecvTopics1), {ok, _, _} = emqtt:unsubscribe(C, SubOrigTopics), timer:sleep(100), ?assertEqual([], emqx_broker:subscriptions(<<"rewrite_client">>)), {ok, _Props, _} = emqtt:subscribe(C, [{Topic, ?QOS_1} || Topic <- PubDestTopics]), RecvTopics2 = [begin ok = emqtt:publish(C, Topic, <<"payload">>), {ok, #{topic := RecvTopic}} = receive_publish(100), RecvTopic end || Topic <- PubOrigTopics], ?assertEqual(PubDestTopics, RecvTopics2), {ok, _, _} = emqtt:unsubscribe(C, PubDestTopics), ok = emqtt:disconnect(C), ok = emqx_mod_rewrite:unload(?RULES). t_rewrite_rule(_Config) -> {PubRules, SubRules} = emqx_mod_rewrite:compile(?RULES), ?assertEqual(<<"z/y/2">>, emqx_mod_rewrite:match_and_rewrite(<<"x/y/2">>, PubRules)), ?assertEqual(<<"x/1/2">>, emqx_mod_rewrite:match_and_rewrite(<<"x/1/2">>, PubRules)), ?assertEqual(<<"y/z/b">>, emqx_mod_rewrite:match_and_rewrite(<<"y/a/z/b">>, SubRules)), ?assertEqual(<<"y/def">>, emqx_mod_rewrite:match_and_rewrite(<<"y/def">>, SubRules)). Internal functions receive_publish(Timeout) -> receive {publish, Publish} -> {ok, Publish} after Timeout -> {error, timeout} end.
0b33cbeab78a7c77b0a14cc06deb7e897cf19710ef714aeaab9ddaae23ee49e4
dcastro/haskell-flatbuffers
DecodeVectors.hs
# LANGUAGE TypeApplications # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE LambdaCase # # OPTIONS_GHC -Wno - incomplete - patterns # HLINT ignore " Avoid lambda " HLINT ignore " Use > = > " module DecodeVectors where import Control.Monad import Criterion import Data.Functor ( (<&>) ) import Data.Int import qualified Data.List as L import qualified Data.Text as T import FlatBuffers import qualified FlatBuffers.Vector as Vec import FlatBuffers.Vector ( index, unsafeIndex ) import Types n :: Num a => a n = 10000 groups :: [Benchmark] groups = [ bgroup ("decode vectors (" <> show @Int n <> " elements)") [ bgroup "toList" [ bench "word8" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsA , bench "word16" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsB , bench "word32" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsC , bench "word64" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsD , bench "int8" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsE , bench "int16" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsF , bench "int32" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsG , bench "int64" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsH , bench "float" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsI , bench "double" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsJ , bench "bool" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsK , bench "string" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsL , bench "struct" $ nf (\(Right (Just vec)) -> Vec.toList vec >>= traverse structWithOneIntX) $ vectorsTable >>= vectorsM , bench "table" $ nf (\(Right (Just vec)) -> Vec.toList vec >>= traverse pairTableX) $ vectorsTable >>= vectorsN , bench "union" $ nf (\(Right (Just vec)) -> do list <- Vec.toList vec forM list $ \case Union (WeaponUnionSword sword) -> swordTableX sword Union (WeaponUnionAxe axe) -> axeTableX axe ) $ vectorsTable >>= vectorsO ] , bgroup "unsafeIndex" [ bench "word8" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsA , bench "int32" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsG , bench "struct" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i >>= structWithOneIntX) ) $ vectorsTable >>= vectorsM , bench "string" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsL ] , bgroup "index" [ bench "word8" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsA , bench "int32" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsG , bench "struct" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i >>= structWithOneIntX) ) $ vectorsTable >>= vectorsM , bench "string" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsL ] ] ] mkNumList :: Num a => Int32 -> [a] mkNumList len = fromIntegral <$> [1 .. len] mkNumVec :: (Num a, Vec.WriteVectorElement a) => Maybe (Vec.WriteVector a) mkNumVec = Just (Vec.fromList n (mkNumList n)) vectorsTable :: Either ReadError (Table Vectors) vectorsTable = decode . encode $ vectors mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec (Just . Vec.fromList n . L.replicate n $ True) (Just . Vec.fromList n $ [1..n] <&> \i -> T.take (i `rem` 15) "abcghjkel;jhgx") (Just . Vec.fromList n . fmap structWithOneInt $ mkNumList n) (Just . Vec.fromList n . fmap (\i -> pairTable (Just i) (Just i)) $ mkNumList n) (Just . Vec.fromList n . fmap mkUnion $ mkNumList n ) where mkUnion i = if odd i then weaponUnionSword (swordTable (Just i)) else weaponUnionAxe (axeTable (Just i))
null
https://raw.githubusercontent.com/dcastro/haskell-flatbuffers/cea6a75109de109ae906741ee73cbb0f356a8e0d/bench/DecodeVectors.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications # # LANGUAGE LambdaCase # # OPTIONS_GHC -Wno - incomplete - patterns # HLINT ignore " Avoid lambda " HLINT ignore " Use > = > " module DecodeVectors where import Control.Monad import Criterion import Data.Functor ( (<&>) ) import Data.Int import qualified Data.List as L import qualified Data.Text as T import FlatBuffers import qualified FlatBuffers.Vector as Vec import FlatBuffers.Vector ( index, unsafeIndex ) import Types n :: Num a => a n = 10000 groups :: [Benchmark] groups = [ bgroup ("decode vectors (" <> show @Int n <> " elements)") [ bgroup "toList" [ bench "word8" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsA , bench "word16" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsB , bench "word32" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsC , bench "word64" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsD , bench "int8" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsE , bench "int16" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsF , bench "int32" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsG , bench "int64" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsH , bench "float" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsI , bench "double" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsJ , bench "bool" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsK , bench "string" $ nf (\(Right (Just vec)) -> Vec.toList vec ) $ vectorsTable >>= vectorsL , bench "struct" $ nf (\(Right (Just vec)) -> Vec.toList vec >>= traverse structWithOneIntX) $ vectorsTable >>= vectorsM , bench "table" $ nf (\(Right (Just vec)) -> Vec.toList vec >>= traverse pairTableX) $ vectorsTable >>= vectorsN , bench "union" $ nf (\(Right (Just vec)) -> do list <- Vec.toList vec forM list $ \case Union (WeaponUnionSword sword) -> swordTableX sword Union (WeaponUnionAxe axe) -> axeTableX axe ) $ vectorsTable >>= vectorsO ] , bgroup "unsafeIndex" [ bench "word8" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsA , bench "int32" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsG , bench "struct" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i >>= structWithOneIntX) ) $ vectorsTable >>= vectorsM , bench "string" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `unsafeIndex` i) ) $ vectorsTable >>= vectorsL ] , bgroup "index" [ bench "word8" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsA , bench "int32" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsG , bench "struct" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i >>= structWithOneIntX) ) $ vectorsTable >>= vectorsM , bench "string" $ nf (\(Right (Just vec)) -> forM [0..(n-1)] (\i -> vec `index` i) ) $ vectorsTable >>= vectorsL ] ] ] mkNumList :: Num a => Int32 -> [a] mkNumList len = fromIntegral <$> [1 .. len] mkNumVec :: (Num a, Vec.WriteVectorElement a) => Maybe (Vec.WriteVector a) mkNumVec = Just (Vec.fromList n (mkNumList n)) vectorsTable :: Either ReadError (Table Vectors) vectorsTable = decode . encode $ vectors mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec mkNumVec (Just . Vec.fromList n . L.replicate n $ True) (Just . Vec.fromList n $ [1..n] <&> \i -> T.take (i `rem` 15) "abcghjkel;jhgx") (Just . Vec.fromList n . fmap structWithOneInt $ mkNumList n) (Just . Vec.fromList n . fmap (\i -> pairTable (Just i) (Just i)) $ mkNumList n) (Just . Vec.fromList n . fmap mkUnion $ mkNumList n ) where mkUnion i = if odd i then weaponUnionSword (swordTable (Just i)) else weaponUnionAxe (axeTable (Just i))
9907a35bf8ffe24d8bef537e2d9e6a0e8d0db02fa649af6a0703bfad4e708a1d
input-output-hk/rscoin-haskell
Main.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE DeriveGeneric # # LANGUAGE RecordWildCards # {-# LANGUAGE TypeOperators #-} module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Async (forConcurrently) import Control.Monad (forM_, replicateM, void) import Data.Maybe (fromMaybe) import Data.String (IsString) import Data.Time.Units (Second) import Formatting (build, int, sformat, (%)) import System.IO.Temp (withSystemTempDirectory) -- workaround to make stylish-haskell work :( import Options.Generic import Serokell.Util.Bench (ElapsedTime, measureTime_) import Serokell.Util.Concurrent (threadDelay) import RSCoin.Core (Address, ContextArgument (CADefault), PublicKey, SecretKey, Severity (..), defaultPeriodDelta, initLoggerByName, initLogging, keyGen, logInfo, mintetteLoggerName, nakedLoggerName, runRealModeUntrusted) import Bench.RSCoin.FilePathUtils (tempBenchDirectory) import Bench.RSCoin.Local.InfraThreads (addMintette, bankThread, mintetteThread, notaryThread) import Bench.RSCoin.UserCommons (benchUserTransactions, finishBankPeriod, initializeBank, initializeUser, userThread) data BenchOptions = BenchOptions { users :: Int <?> "number of users" , transactions :: Maybe Word <?> "number of transactions per user" , mintettes :: Int <?> "number of mintettes" , severity :: Maybe Severity <?> "severity for global logger" , period :: Maybe Word <?> "period delta (seconds)" } deriving (Generic, Show) instance ParseField Word instance ParseField Severity instance ParseFields Severity instance ParseRecord Severity instance ParseRecord BenchOptions type KeyPairList = [(SecretKey, PublicKey)] bankHost :: IsString s => s bankHost = "127.0.0.1" generateMintetteKeys :: Word -> IO KeyPairList generateMintetteKeys = flip replicateM keyGen . fromIntegral runMintettes :: FilePath -> KeyPairList -> IO () runMintettes benchDir secretKeys = forM_ (zip [1..] secretKeys) $ \(mintetteId, (secretKey, publicKey)) -> do void $ forkIO $ mintetteThread mintetteId benchDir secretKey logInfo $ sformat ("Starting mintette number:" % int) mintetteId threadDelay (1 :: Second) addMintette mintetteId publicKey establishNotary :: FilePath -> IO () establishNotary benchDir = do logInfo "Running notary..." _ <- forkIO $ notaryThread benchDir logInfo "Notary is launched" threadDelay (2 :: Second) establishBank :: FilePath -> Second -> IO () establishBank benchDir periodDelta = do logInfo "Running bank..." _ <- forkIO $ bankThread periodDelta benchDir logInfo "Bank is launched" threadDelay (2 :: Second) establishMintettes :: FilePath -> Word -> IO () establishMintettes benchDir mintettesNumber = do keyPairs <- generateMintetteKeys mintettesNumber logInfo $ sformat ("Running" % int % " mintettes…") mintettesNumber runMintettes benchDir keyPairs runRealModeUntrusted mintetteLoggerName CADefault finishBankPeriod logInfo $ sformat (int % " mintettes are launched") mintettesNumber threadDelay (2 :: Second) initializeUsers :: FilePath -> [Word] -> IO [Address] initializeUsers benchDir userIds = do let initUserAction = userThread benchDir initializeUser logInfo $ sformat ("Initializing " % int % " users…") $ length userIds mapM initUserAction userIds initializeSuperUser :: Word -> FilePath -> [Address] -> IO () initializeSuperUser txNum benchDir userAddresses = do let bankId = 0 userThread benchDir (const $ initializeBank txNum userAddresses) bankId runTransactions :: Word -> FilePath -> [Word] -> IO ElapsedTime runTransactions txNum benchDir userIds = do let benchUserAction = userThread benchDir $ benchUserTransactions txNum logInfo "Running transactions…" measureTime_ $ forConcurrently userIds benchUserAction main :: IO () main = do BenchOptions{..} <- getRecord "rscoin-user-bench" let mintettesNumber = fromIntegral $ unHelpful mintettes userNumber = unHelpful users txNum = fromMaybe 1000 $ unHelpful transactions globalSeverity = fromMaybe Error $ unHelpful severity periodDelta = fromMaybe defaultPeriodDelta $ fromIntegral <$> unHelpful period withSystemTempDirectory tempBenchDirectory $ \benchDir -> do initLogging globalSeverity initLoggerByName Info nakedLoggerName establishNotary benchDir establishBank benchDir periodDelta establishMintettes benchDir mintettesNumber let userIds = [1 .. fromIntegral userNumber] userAddresses <- initializeUsers benchDir userIds initializeSuperUser txNum benchDir userAddresses logInfo . sformat ("Elapsed time: " % build) =<< runTransactions txNum benchDir userIds
null
https://raw.githubusercontent.com/input-output-hk/rscoin-haskell/109d8f6f226e9d0b360fcaac14c5a90da112a810/bench/Local/Main.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # workaround to make stylish-haskell work :(
# LANGUAGE DeriveGeneric # # LANGUAGE RecordWildCards # module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Async (forConcurrently) import Control.Monad (forM_, replicateM, void) import Data.Maybe (fromMaybe) import Data.String (IsString) import Data.Time.Units (Second) import Formatting (build, int, sformat, (%)) import System.IO.Temp (withSystemTempDirectory) import Options.Generic import Serokell.Util.Bench (ElapsedTime, measureTime_) import Serokell.Util.Concurrent (threadDelay) import RSCoin.Core (Address, ContextArgument (CADefault), PublicKey, SecretKey, Severity (..), defaultPeriodDelta, initLoggerByName, initLogging, keyGen, logInfo, mintetteLoggerName, nakedLoggerName, runRealModeUntrusted) import Bench.RSCoin.FilePathUtils (tempBenchDirectory) import Bench.RSCoin.Local.InfraThreads (addMintette, bankThread, mintetteThread, notaryThread) import Bench.RSCoin.UserCommons (benchUserTransactions, finishBankPeriod, initializeBank, initializeUser, userThread) data BenchOptions = BenchOptions { users :: Int <?> "number of users" , transactions :: Maybe Word <?> "number of transactions per user" , mintettes :: Int <?> "number of mintettes" , severity :: Maybe Severity <?> "severity for global logger" , period :: Maybe Word <?> "period delta (seconds)" } deriving (Generic, Show) instance ParseField Word instance ParseField Severity instance ParseFields Severity instance ParseRecord Severity instance ParseRecord BenchOptions type KeyPairList = [(SecretKey, PublicKey)] bankHost :: IsString s => s bankHost = "127.0.0.1" generateMintetteKeys :: Word -> IO KeyPairList generateMintetteKeys = flip replicateM keyGen . fromIntegral runMintettes :: FilePath -> KeyPairList -> IO () runMintettes benchDir secretKeys = forM_ (zip [1..] secretKeys) $ \(mintetteId, (secretKey, publicKey)) -> do void $ forkIO $ mintetteThread mintetteId benchDir secretKey logInfo $ sformat ("Starting mintette number:" % int) mintetteId threadDelay (1 :: Second) addMintette mintetteId publicKey establishNotary :: FilePath -> IO () establishNotary benchDir = do logInfo "Running notary..." _ <- forkIO $ notaryThread benchDir logInfo "Notary is launched" threadDelay (2 :: Second) establishBank :: FilePath -> Second -> IO () establishBank benchDir periodDelta = do logInfo "Running bank..." _ <- forkIO $ bankThread periodDelta benchDir logInfo "Bank is launched" threadDelay (2 :: Second) establishMintettes :: FilePath -> Word -> IO () establishMintettes benchDir mintettesNumber = do keyPairs <- generateMintetteKeys mintettesNumber logInfo $ sformat ("Running" % int % " mintettes…") mintettesNumber runMintettes benchDir keyPairs runRealModeUntrusted mintetteLoggerName CADefault finishBankPeriod logInfo $ sformat (int % " mintettes are launched") mintettesNumber threadDelay (2 :: Second) initializeUsers :: FilePath -> [Word] -> IO [Address] initializeUsers benchDir userIds = do let initUserAction = userThread benchDir initializeUser logInfo $ sformat ("Initializing " % int % " users…") $ length userIds mapM initUserAction userIds initializeSuperUser :: Word -> FilePath -> [Address] -> IO () initializeSuperUser txNum benchDir userAddresses = do let bankId = 0 userThread benchDir (const $ initializeBank txNum userAddresses) bankId runTransactions :: Word -> FilePath -> [Word] -> IO ElapsedTime runTransactions txNum benchDir userIds = do let benchUserAction = userThread benchDir $ benchUserTransactions txNum logInfo "Running transactions…" measureTime_ $ forConcurrently userIds benchUserAction main :: IO () main = do BenchOptions{..} <- getRecord "rscoin-user-bench" let mintettesNumber = fromIntegral $ unHelpful mintettes userNumber = unHelpful users txNum = fromMaybe 1000 $ unHelpful transactions globalSeverity = fromMaybe Error $ unHelpful severity periodDelta = fromMaybe defaultPeriodDelta $ fromIntegral <$> unHelpful period withSystemTempDirectory tempBenchDirectory $ \benchDir -> do initLogging globalSeverity initLoggerByName Info nakedLoggerName establishNotary benchDir establishBank benchDir periodDelta establishMintettes benchDir mintettesNumber let userIds = [1 .. fromIntegral userNumber] userAddresses <- initializeUsers benchDir userIds initializeSuperUser txNum benchDir userAddresses logInfo . sformat ("Elapsed time: " % build) =<< runTransactions txNum benchDir userIds
a46135f683d1dccc00e1286a58a7c740f5c653ed5140586ac914b3f0b15d0c94
tarides/dune-release
vcs.mli
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * VCS repositories . * { 1 VCS } open Rresult * { 1 : vcsops Version control system repositories } module Tag : sig type t val pp : t Fmt.t val equal : t -> t -> bool (** [equal a b] returns [true] if [a] and [b] are the same tag. No check whether these commits point to the same data is done. *) val to_string : t -> string (** [to_string v] returns the [string] representation of the tag. *) val of_string : string -> t (** [of_string v] reads the specified [v] without any validation. This should be done only in rare cases, for most usages it is better to derive a [Tag.t] from a [Version.t] via [Version.to_tag]. *) end type commit_ish = string * The type for symbols resolving to a commit . The module uses [ " HEAD " ] for specifying the current checkout ; use this symbol even if the underlying VCS is [ ` Hg ] . specifying the current checkout; use this symbol even if the underlying VCS is [`Hg]. *) module Tag_or_commit_ish : sig type t = Tag of Tag.t | Commit_ish of commit_ish end type t (** The type for version control systems repositories. *) val cmd : t -> Bos.Cmd.t * [ cmd r ] is the base VCS command to use to act on [ r ] . { b Warning } Prefer the functions below to remain VCS independent . {b Warning} Prefer the functions below to remain VCS independent. *) val get : ?dir:Fpath.t -> unit -> (t, R.msg) result * [ get ( ) ] looks for a VCS repository in working directory [ dir ] ( not the repository directory like [ .git ] , default is guessed automatically ) . Returns an error if no VCS was found . repository directory like [.git], default is guessed automatically). Returns an error if no VCS was found. *) val run_git_quiet : dry_run:bool -> ?force:bool -> t -> Bos_setup.Cmd.t -> (unit, R.msg) result val run_git_string : dry_run:bool -> ?force:bool -> default:string * Bos.OS.Cmd.run_status -> t -> Bos_setup.Cmd.t -> (string, R.msg) result * { 1 : state Repository state } val is_dirty : t -> (bool, R.msg) result * [ r ] is [ Ok true ] iff the working tree of [ r ] has uncommitted changes . changes. *) val commit_id : ?dirty:bool -> ?commit_ish:commit_ish -> t -> (commit_ish, R.msg) result * [ commit_id r ] is the object name ( identifier ) of [ commit_ish ] ( defaults to [ " HEAD " ] ) . If [ commit_ish ] is [ " HEAD " ] and [ dirty ] is [ true ] ( default ) an indicator is appended to the identifier if the working tree is dirty . [commit_ish] (defaults to ["HEAD"]). If [commit_ish] is ["HEAD"] and [dirty] is [true] (default) an indicator is appended to the identifier if the working tree is dirty. *) val commit_ptime_s : dry_run:bool -> ?commit_ish:Tag_or_commit_ish.t -> t -> (int64, R.msg) result * [ commit_ptime_s t ] is the POSIX time in seconds of commit [ commit_ish ] ( defaults to [ " HEAD " ] ) of repository [ r ] . [commit_ish] (defaults to ["HEAD"]) of repository [r]. *) val describe : ?dirty:bool -> ?commit_ish:commit_ish -> t -> (string, R.msg) result * [ describe r ] identifies [ commit_ish ] ( defaults to [ " HEAD " ] ) using tags from the repository [ r ] . If [ commit_ish ] is [ " HEAD " ] and [ dirty ] is [ true ] ( default ) an indicator is appended to the identifier if the working tree is dirty . ["HEAD"]) using tags from the repository [r]. If [commit_ish] is ["HEAD"] and [dirty] is [true] (default) an indicator is appended to the identifier if the working tree is dirty. *) val get_tag : t -> (Tag.t, R.msg) result val tag_exists : dry_run:bool -> t -> Tag.t -> bool val tag_points_to : t -> Tag.t -> string option val branch_exists : dry_run:bool -> t -> commit_ish -> bool * { 1 : ops Repository operations } val clone : dry_run:bool -> ?force:bool -> ?branch:string -> dir:Fpath.t -> t -> (unit, R.msg) result * [ clone ~dir r ] clones [ r ] in directory [ dir ] . val checkout : dry_run:bool -> ?branch:commit_ish -> t -> commit_ish:Tag_or_commit_ish.t -> (unit, R.msg) result (** [checkout r ~branch commit_ish] checks out [commit_ish]. Checks out in a new branch [branch] if provided. *) val change_branch : dry_run:bool -> branch:string -> t -> (unit, R.msg) result * [ change_branch ~branch r ] moves the head to an existing branch [ branch ] . val tag : dry_run:bool -> ?force:bool -> ?sign:bool -> ?msg:string -> ?commit_ish:string -> t -> Tag.t -> (unit, R.msg) result * [ tag r ~force ~sign ~msg t ] tags [ commit_ish ] with [ t ] and message [ msg ] ( if unspecified the VCS should prompt ) . if [ sign ] is [ true ] ( defaults to [ false ] ) signs the tag ( [ ` Git ] repos only ) . If [ force ] is [ true ] ( default to [ false ] ) does n't fail if the tag already exists . message [msg] (if unspecified the VCS should prompt). if [sign] is [true] (defaults to [false]) signs the tag ([`Git] repos only). If [force] is [true] (default to [false]) doesn't fail if the tag already exists. *) val delete_tag : dry_run:bool -> t -> Tag.t -> (unit, R.msg) result (** [delete_tag r t] deletes tag [t] in repo [r]. *) val ls_remote : dry_run:bool -> t -> ?kind:[ `Branch | `Tag | `All ] -> ?filter:string -> string -> ((string * string) list, R.msg) result (** [ls_remote ~dry_run t ?filter upstream] queries the remote server [upstream] and returns the result as a list of pairs [commit_hash, ref_name]. [filter] filters results by matching on ref names, the default is no filtering. [kind] filters results on their kind (branch or tag), the default is [`All]. Only implemented for Git. *) val submodule_update : dry_run:bool -> t -> (unit, R.msg) result (** [submodule r] pulls in all submodules in [r]. Only works for git repositories *) val git_escape_tag : string -> Tag.t (** Exposed for tests. *) val escape_tag : t -> string -> Tag.t val git_unescape_tag : Tag.t -> string (** Exposed for tests. *) val unescape_tag : t -> Tag.t -> string --------------------------------------------------------------------------- Copyright ( c ) 2016 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 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 . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli 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. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/tarides/dune-release/6bfed0f299b82c0931c78d4e216fd0efedff0673/lib/vcs.mli
ocaml
* [equal a b] returns [true] if [a] and [b] are the same tag. No check whether these commits point to the same data is done. * [to_string v] returns the [string] representation of the tag. * [of_string v] reads the specified [v] without any validation. This should be done only in rare cases, for most usages it is better to derive a [Tag.t] from a [Version.t] via [Version.to_tag]. * The type for version control systems repositories. * [checkout r ~branch commit_ish] checks out [commit_ish]. Checks out in a new branch [branch] if provided. * [delete_tag r t] deletes tag [t] in repo [r]. * [ls_remote ~dry_run t ?filter upstream] queries the remote server [upstream] and returns the result as a list of pairs [commit_hash, ref_name]. [filter] filters results by matching on ref names, the default is no filtering. [kind] filters results on their kind (branch or tag), the default is [`All]. Only implemented for Git. * [submodule r] pulls in all submodules in [r]. Only works for git repositories * Exposed for tests. * Exposed for tests.
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * VCS repositories . * { 1 VCS } open Rresult * { 1 : vcsops Version control system repositories } module Tag : sig type t val pp : t Fmt.t val equal : t -> t -> bool val to_string : t -> string val of_string : string -> t end type commit_ish = string * The type for symbols resolving to a commit . The module uses [ " HEAD " ] for specifying the current checkout ; use this symbol even if the underlying VCS is [ ` Hg ] . specifying the current checkout; use this symbol even if the underlying VCS is [`Hg]. *) module Tag_or_commit_ish : sig type t = Tag of Tag.t | Commit_ish of commit_ish end type t val cmd : t -> Bos.Cmd.t * [ cmd r ] is the base VCS command to use to act on [ r ] . { b Warning } Prefer the functions below to remain VCS independent . {b Warning} Prefer the functions below to remain VCS independent. *) val get : ?dir:Fpath.t -> unit -> (t, R.msg) result * [ get ( ) ] looks for a VCS repository in working directory [ dir ] ( not the repository directory like [ .git ] , default is guessed automatically ) . Returns an error if no VCS was found . repository directory like [.git], default is guessed automatically). Returns an error if no VCS was found. *) val run_git_quiet : dry_run:bool -> ?force:bool -> t -> Bos_setup.Cmd.t -> (unit, R.msg) result val run_git_string : dry_run:bool -> ?force:bool -> default:string * Bos.OS.Cmd.run_status -> t -> Bos_setup.Cmd.t -> (string, R.msg) result * { 1 : state Repository state } val is_dirty : t -> (bool, R.msg) result * [ r ] is [ Ok true ] iff the working tree of [ r ] has uncommitted changes . changes. *) val commit_id : ?dirty:bool -> ?commit_ish:commit_ish -> t -> (commit_ish, R.msg) result * [ commit_id r ] is the object name ( identifier ) of [ commit_ish ] ( defaults to [ " HEAD " ] ) . If [ commit_ish ] is [ " HEAD " ] and [ dirty ] is [ true ] ( default ) an indicator is appended to the identifier if the working tree is dirty . [commit_ish] (defaults to ["HEAD"]). If [commit_ish] is ["HEAD"] and [dirty] is [true] (default) an indicator is appended to the identifier if the working tree is dirty. *) val commit_ptime_s : dry_run:bool -> ?commit_ish:Tag_or_commit_ish.t -> t -> (int64, R.msg) result * [ commit_ptime_s t ] is the POSIX time in seconds of commit [ commit_ish ] ( defaults to [ " HEAD " ] ) of repository [ r ] . [commit_ish] (defaults to ["HEAD"]) of repository [r]. *) val describe : ?dirty:bool -> ?commit_ish:commit_ish -> t -> (string, R.msg) result * [ describe r ] identifies [ commit_ish ] ( defaults to [ " HEAD " ] ) using tags from the repository [ r ] . If [ commit_ish ] is [ " HEAD " ] and [ dirty ] is [ true ] ( default ) an indicator is appended to the identifier if the working tree is dirty . ["HEAD"]) using tags from the repository [r]. If [commit_ish] is ["HEAD"] and [dirty] is [true] (default) an indicator is appended to the identifier if the working tree is dirty. *) val get_tag : t -> (Tag.t, R.msg) result val tag_exists : dry_run:bool -> t -> Tag.t -> bool val tag_points_to : t -> Tag.t -> string option val branch_exists : dry_run:bool -> t -> commit_ish -> bool * { 1 : ops Repository operations } val clone : dry_run:bool -> ?force:bool -> ?branch:string -> dir:Fpath.t -> t -> (unit, R.msg) result * [ clone ~dir r ] clones [ r ] in directory [ dir ] . val checkout : dry_run:bool -> ?branch:commit_ish -> t -> commit_ish:Tag_or_commit_ish.t -> (unit, R.msg) result val change_branch : dry_run:bool -> branch:string -> t -> (unit, R.msg) result * [ change_branch ~branch r ] moves the head to an existing branch [ branch ] . val tag : dry_run:bool -> ?force:bool -> ?sign:bool -> ?msg:string -> ?commit_ish:string -> t -> Tag.t -> (unit, R.msg) result * [ tag r ~force ~sign ~msg t ] tags [ commit_ish ] with [ t ] and message [ msg ] ( if unspecified the VCS should prompt ) . if [ sign ] is [ true ] ( defaults to [ false ] ) signs the tag ( [ ` Git ] repos only ) . If [ force ] is [ true ] ( default to [ false ] ) does n't fail if the tag already exists . message [msg] (if unspecified the VCS should prompt). if [sign] is [true] (defaults to [false]) signs the tag ([`Git] repos only). If [force] is [true] (default to [false]) doesn't fail if the tag already exists. *) val delete_tag : dry_run:bool -> t -> Tag.t -> (unit, R.msg) result val ls_remote : dry_run:bool -> t -> ?kind:[ `Branch | `Tag | `All ] -> ?filter:string -> string -> ((string * string) list, R.msg) result val submodule_update : dry_run:bool -> t -> (unit, R.msg) result val git_escape_tag : string -> Tag.t val escape_tag : t -> string -> Tag.t val git_unescape_tag : Tag.t -> string val unescape_tag : t -> Tag.t -> string --------------------------------------------------------------------------- Copyright ( c ) 2016 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 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 . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli 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. ---------------------------------------------------------------------------*)
46aac79715189ca649cb864edb81eee43950102129e7c27cd788280385d6445d
fjvallarino/monomer
TestUtil.hs
| Module : Monomer . TestUtil Copyright : ( c ) 2018 License : BSD-3 - Clause ( see the LICENSE file ) Maintainer : Stability : experimental Portability : non - portable Helper functions for testing Monomer widgets . Module : Monomer.TestUtil Copyright : (c) 2018 Francisco Vallarino License : BSD-3-Clause (see the LICENSE file) Maintainer : Stability : experimental Portability : non-portable Helper functions for testing Monomer widgets. -} # LANGUAGE FlexibleContexts # module Monomer.TestUtil where import Control.Concurrent (newMVar) import Control.Concurrent.STM.TChan (newTChanIO) import Control.Lens ((&), (^.), (.~), (.=), (+~)) import Control.Monad.State import Data.Default import Data.Maybe import Data.Text (Text) import Data.Sequence (Seq) import System.Environment (lookupEnv) import System.IO.Unsafe (unsafePerformIO) import Test.Hspec (Expectation, pendingWith) import qualified Data.ByteString as BS import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Data.Sequence as Seq import Monomer.Core import Monomer.Event import Monomer.Graphics import Monomer.Main.Handlers import Monomer.Main.Types import Monomer.Main.Util import qualified Monomer.Lens as L data InitWidget = WInit | WInitKeepFirst | WNoInit deriving (Eq, Show) testW :: Double testW = 640 testH :: Double testH = 480 testWindowSize :: Size testWindowSize = Size testW testH testWindowRect :: Rect testWindowRect = Rect 0 0 testW testH mockTextMetrics :: Double -> Font -> FontSize -> TextMetrics mockTextMetrics scale font fontSize = TextMetrics { _txmAsc = 15, _txmDesc = 5, _txmLineH = 20, _txmLowerX = 10 } mockTextSize :: Maybe Double -> Double -> Font -> FontSize -> FontSpace -> Text -> Size mockTextSize mw scale font (FontSize fs) spaceH text = Size width height where w = fromMaybe fs mw + unFontSpace spaceH width = fromIntegral (T.length text) * w height = 20 mockGlyphsPos :: Maybe Double -> Double -> Font -> FontSize -> FontSpace -> Text -> Seq GlyphPos mockGlyphsPos mw scale font (FontSize fs) spaceH text = glyphs where w = fromMaybe fs mw + unFontSpace spaceH chars = Seq.fromList $ T.unpack text mkGlyph idx chr = GlyphPos { _glpGlyph = chr, _glpX = fromIntegral idx * w, _glpXMin = fromIntegral idx * w, _glpXMax = (fromIntegral idx + 1) * w, _glpYMin = 0, _glpYMax = 10, _glpW = w, _glpH = 10 } glyphs = Seq.mapWithIndex mkGlyph chars mockRenderText :: Point -> Font -> FontSize -> FontSpace -> Text -> IO () mockRenderText point font size spaceH text = return () mockRenderer :: Renderer mockRenderer = Renderer { beginFrame = \w h -> return (), endFrame = return (), -- Path beginPath = return (), closePath = return (), -- Context management saveContext = return (), restoreContext = return (), -- Overlays createOverlay = \overlay -> return (), renderOverlays = return (), Raw tasks createRawTask = \task -> return (), renderRawTasks = return (), -- Raw overlays createRawOverlay = \overlay -> return (), renderRawOverlays = return (), -- Scissor operations intersectScissor = \rect -> return (), -- Translation setTranslation = \point -> return (), -- Scale setScale = \point -> return (), -- Rotation setRotation = \angle -> return (), Global Alpha setGlobalAlpha = \alpha -> return (), -- Path Winding setPathWinding = \winding -> return (), -- Strokes stroke = return (), setStrokeColor = \color -> return (), setStrokeWidth = \width -> return (), setStrokeLinearGradient = \p1 p2 c1 c2 -> return (), setStrokeRadialGradient = \p1 a1 a2 c1 c2 -> return (), setStrokeBoxGradient = \a r f c1 c2 -> return (), setStrokeImagePattern = \n1 p1 s1 w1 h1 -> return (), -- Fill fill = return (), setFillColor = \color -> return (), setFillLinearGradient = \p1 p2 c1 c2 -> return (), setFillRadialGradient = \p1 a1 a2 c1 c2 -> return (), setFillBoxGradient = \a r f c1 c2 -> return (), setFillImagePattern = \n1 p1 s1 w1 h1 -> return (), -- Drawing moveTo = \point -> return (), renderLine = \p1 p2 -> return (), renderLineTo = \point -> return (), renderRect = \rect -> return (), renderRoundedRect = \rect r1 r2 r3 r4 -> return (), renderArc = \center radius angleStart angleEnd winding -> return (), renderQuadTo = \p1 p2 -> return (), renderBezierTo = \p1 p2 p3 -> return (), renderEllipse = \rect -> return (), -- Text renderText = mockRenderText, -- Image getImage = const . return $ Just $ ImageDef "test" def BS.empty [], addImage = \name size imgData flags -> return (), updateImage = \name size imgData -> return (), deleteImage = \name -> return () } mockFontManager :: FontManager mockFontManager = FontManager { computeTextMetrics = mockTextMetrics 1, computeTextMetrics_ = mockTextMetrics, computeTextSize = mockTextSize (Just 10) 1, computeTextSize_ = mockTextSize (Just 10), computeGlyphsPos = mockGlyphsPos (Just 10) 1, computeGlyphsPos_ = mockGlyphsPos (Just 10) } mockWenv :: s -> WidgetEnv s e mockWenv model = WidgetEnv { _weOs = "Mac OS X", _weDpr = 2, _weIsGhci = False, _weAppStartTs = 0, _weFontManager = mockFontManager, _weFindBranchByPath = const Seq.empty, _weMainButton = BtnLeft, _weContextButton = BtnRight, _weTheme = def, _weWindowSize = testWindowSize, _weWidgetShared = unsafePerformIO (newMVar M.empty), _weWidgetKeyMap = M.empty, _weHoveredPath = Nothing, _weFocusedPath = emptyPath, _weOverlayPath = Nothing, _weDragStatus = Nothing, _weMainBtnPress = Nothing, _weCursor = Nothing, _weModel = model, _weInputStatus = def, _weTimestamp = 0, _weThemeChanged = False, _weInTopLayer = const True, _weLayoutDirection = LayoutNone, _weViewport = Rect 0 0 testW testH, _weOffset = def } mockWenvEvtUnit :: s -> WidgetEnv s () mockWenvEvtUnit model = mockWenv model nodeInit :: (Eq s) => WidgetEnv s e -> WidgetNode s e -> WidgetNode s e nodeInit wenv node = nodeHandleEventRoot wenv [] node nodeMerge :: WidgetEnv s e -> WidgetNode s e -> WidgetNode s e -> WidgetNode s e nodeMerge wenv node oldNode = resNode where newNode = node & L.info . L.path .~ oldNode ^. L.info . L.path WidgetResult resNode _ = widgetMerge (newNode^. L.widget) wenv newNode oldNode nodeGetSizeReq :: WidgetEnv s e -> WidgetNode s e -> (SizeReq, SizeReq) nodeGetSizeReq wenv node = (sizeReqW, sizeReqH) where WidgetResult node2 _ = widgetInit (node ^. L.widget) wenv node sizeReqW = node2 ^. L.info . L.sizeReqW sizeReqH = node2 ^. L.info . L.sizeReqH nodeResize :: WidgetEnv s e -> WidgetNode s e -> Rect -> WidgetNode s e nodeResize wenv node viewport = result ^. L.node where resizeCheck = const True widget = node ^. L.widget result = widgetResize widget wenv node viewport resizeCheck nodeHandleEventCtx :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> MonomerCtx s e nodeHandleEventCtx wenv evts node = ctx where ctx = nodeHandleEventCtx_ wenv WInit evts node nodeHandleEventCtx_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> MonomerCtx s e nodeHandleEventCtx_ wenv init evts node = ctx where ctx = snd $ nodeHandleEvents wenv init evts node nodeHandleEventModel :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> s nodeHandleEventModel wenv evts node = model where model = nodeHandleEventModel_ wenv WInit evts node nodeHandleEventModel_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> s nodeHandleEventModel_ wenv init evts node = _weModel wenv2 where (wenv2, _, _) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventRoot :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> WidgetNode s e nodeHandleEventRoot wenv evts node = newRoot where newRoot = nodeHandleEventRoot_ wenv WInit evts node nodeHandleEventRoot_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> WidgetNode s e nodeHandleEventRoot_ wenv init evts node = newRoot where (_, newRoot, _) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventReqs :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq (WidgetRequest s e) nodeHandleEventReqs wenv evts node = reqs where reqs = nodeHandleEventReqs_ wenv WInit evts node nodeHandleEventReqs_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> Seq (WidgetRequest s e) nodeHandleEventReqs_ wenv init evts node = reqs where (_, _, reqs) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventEvts :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq e nodeHandleEventEvts wenv evts node = newEvts where newEvts = nodeHandleEventEvts_ wenv WInit evts node nodeHandleEventEvts_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> Seq e nodeHandleEventEvts_ wenv init evts node = eventsFromReqs reqs where (_, _, reqs) = fst $ nodeHandleEvents wenv init evts node nodeHandleEvents :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleEvents wenv init evts node = result where result = nodeHandleEventsSteps wenv init [evts] node nodeHandleEventsSteps :: (Eq s) => WidgetEnv s e -> InitWidget -> [[SystemEvent]] -> WidgetNode s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleEventsSteps wenv init eventSteps node = result where steps = case init of WInit -> tail $ nodeHandleEvents_ wenv init eventSteps node WInitKeepFirst -> nodeHandleEvents_ wenv WInit eventSteps node _ -> nodeHandleEvents_ wenv init eventSteps node result = foldl1 stepper steps stepper step1 step2 = result where ((_, _, reqs1), _) = step1 ((wenv2, root2, reqs2), ctx2) = step2 result = ((wenv2, root2, reqs1 <> reqs2), ctx2) nodeHandleEvents_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [[SystemEvent]] -> WidgetNode s e -> [(HandlerStep s e, MonomerCtx s e)] nodeHandleEvents_ wenv init evtsG node = unsafePerformIO $ do -- Do NOT test code involving SDL Window functions channel <- liftIO newTChanIO fmap fst $ flip runStateT (monomerCtx channel) $ do L.inputStatus .= wenv ^. L.inputStatus handleResourcesInit stepA <- if init == WInit then do handleWidgetInit wenv pathReadyRoot else return (wenv, pathReadyRoot, Seq.empty) ctxA <- get let (wenvA, nodeA, reqsA) = stepA let resizeCheck = const True let resizeRes = widgetResize (nodeA ^. L.widget) wenv nodeA vp resizeCheck step <- handleWidgetResult wenvA True resizeRes ctx <- get let (wenvr, rootr, reqsr) = step (_, _, steps) <- foldM runStep (wenvr, rootr, [(step, ctx)]) evtsG return $ if init == WInit then (stepA, ctxA) : reverse steps else reverse steps where winSize = _weWindowSize wenv vp = Rect 0 0 (_sW winSize) (_sH winSize) dpr = 1 epr = 1 model = _weModel wenv monomerCtx channel = initMonomerCtx undefined channel winSize dpr epr model pathReadyRoot = node & L.info . L.path .~ rootPath & L.info . L.widgetId .~ WidgetId (wenv ^. L.timestamp) rootPath runStep (wenv, root, accum) evts = do let newWenv = wenv & L.timestamp +~ 1 step <- handleSystemEvents newWenv root evts ctx <- get let (wenv2, root2, reqs2) = step return (wenv2, root2, (step, ctx) : accum) nodeHandleResult :: (Eq s) => WidgetEnv s e -> WidgetResult s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleResult wenv result = unsafePerformIO $ do channel <- liftIO newTChanIO let winSize = _weWindowSize wenv let dpr = 1 let epr = 1 let model = _weModel wenv -- Do NOT test code involving SDL Window functions let monomerCtx = initMonomerCtx undefined channel winSize dpr epr model flip runStateT monomerCtx $ do L.inputStatus .= wenv ^. L.inputStatus handleResourcesInit handleWidgetResult wenv True result roundRectUnits :: Rect -> Rect roundRectUnits (Rect x y w h) = Rect nx ny nw nh where nx = fromIntegral (round x) ny = fromIntegral (round y) nw = fromIntegral (round w) nh = fromIntegral (round h) useVideoSubSystem :: IO Bool useVideoSubSystem = do (== Just "1") <$> lookupEnv "USE_SDL_VIDEO_SUBSYSTEM" testInVideoSubSystem :: Expectation -> Expectation testInVideoSubSystem expectation = do useVideo <- useVideoSubSystem if useVideo then expectation else pendingWith "SDL Video sub system not initialized. Skipping."
null
https://raw.githubusercontent.com/fjvallarino/monomer/5b90aebae9f8d1d6c11265750823c016fdd3d785/test/unit/Monomer/TestUtil.hs
haskell
Path Context management Overlays Raw overlays Scissor operations Translation Scale Rotation Path Winding Strokes Fill Drawing Text Image Do NOT test code involving SDL Window functions Do NOT test code involving SDL Window functions
| Module : Monomer . TestUtil Copyright : ( c ) 2018 License : BSD-3 - Clause ( see the LICENSE file ) Maintainer : Stability : experimental Portability : non - portable Helper functions for testing Monomer widgets . Module : Monomer.TestUtil Copyright : (c) 2018 Francisco Vallarino License : BSD-3-Clause (see the LICENSE file) Maintainer : Stability : experimental Portability : non-portable Helper functions for testing Monomer widgets. -} # LANGUAGE FlexibleContexts # module Monomer.TestUtil where import Control.Concurrent (newMVar) import Control.Concurrent.STM.TChan (newTChanIO) import Control.Lens ((&), (^.), (.~), (.=), (+~)) import Control.Monad.State import Data.Default import Data.Maybe import Data.Text (Text) import Data.Sequence (Seq) import System.Environment (lookupEnv) import System.IO.Unsafe (unsafePerformIO) import Test.Hspec (Expectation, pendingWith) import qualified Data.ByteString as BS import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Data.Sequence as Seq import Monomer.Core import Monomer.Event import Monomer.Graphics import Monomer.Main.Handlers import Monomer.Main.Types import Monomer.Main.Util import qualified Monomer.Lens as L data InitWidget = WInit | WInitKeepFirst | WNoInit deriving (Eq, Show) testW :: Double testW = 640 testH :: Double testH = 480 testWindowSize :: Size testWindowSize = Size testW testH testWindowRect :: Rect testWindowRect = Rect 0 0 testW testH mockTextMetrics :: Double -> Font -> FontSize -> TextMetrics mockTextMetrics scale font fontSize = TextMetrics { _txmAsc = 15, _txmDesc = 5, _txmLineH = 20, _txmLowerX = 10 } mockTextSize :: Maybe Double -> Double -> Font -> FontSize -> FontSpace -> Text -> Size mockTextSize mw scale font (FontSize fs) spaceH text = Size width height where w = fromMaybe fs mw + unFontSpace spaceH width = fromIntegral (T.length text) * w height = 20 mockGlyphsPos :: Maybe Double -> Double -> Font -> FontSize -> FontSpace -> Text -> Seq GlyphPos mockGlyphsPos mw scale font (FontSize fs) spaceH text = glyphs where w = fromMaybe fs mw + unFontSpace spaceH chars = Seq.fromList $ T.unpack text mkGlyph idx chr = GlyphPos { _glpGlyph = chr, _glpX = fromIntegral idx * w, _glpXMin = fromIntegral idx * w, _glpXMax = (fromIntegral idx + 1) * w, _glpYMin = 0, _glpYMax = 10, _glpW = w, _glpH = 10 } glyphs = Seq.mapWithIndex mkGlyph chars mockRenderText :: Point -> Font -> FontSize -> FontSpace -> Text -> IO () mockRenderText point font size spaceH text = return () mockRenderer :: Renderer mockRenderer = Renderer { beginFrame = \w h -> return (), endFrame = return (), beginPath = return (), closePath = return (), saveContext = return (), restoreContext = return (), createOverlay = \overlay -> return (), renderOverlays = return (), Raw tasks createRawTask = \task -> return (), renderRawTasks = return (), createRawOverlay = \overlay -> return (), renderRawOverlays = return (), intersectScissor = \rect -> return (), setTranslation = \point -> return (), setScale = \point -> return (), setRotation = \angle -> return (), Global Alpha setGlobalAlpha = \alpha -> return (), setPathWinding = \winding -> return (), stroke = return (), setStrokeColor = \color -> return (), setStrokeWidth = \width -> return (), setStrokeLinearGradient = \p1 p2 c1 c2 -> return (), setStrokeRadialGradient = \p1 a1 a2 c1 c2 -> return (), setStrokeBoxGradient = \a r f c1 c2 -> return (), setStrokeImagePattern = \n1 p1 s1 w1 h1 -> return (), fill = return (), setFillColor = \color -> return (), setFillLinearGradient = \p1 p2 c1 c2 -> return (), setFillRadialGradient = \p1 a1 a2 c1 c2 -> return (), setFillBoxGradient = \a r f c1 c2 -> return (), setFillImagePattern = \n1 p1 s1 w1 h1 -> return (), moveTo = \point -> return (), renderLine = \p1 p2 -> return (), renderLineTo = \point -> return (), renderRect = \rect -> return (), renderRoundedRect = \rect r1 r2 r3 r4 -> return (), renderArc = \center radius angleStart angleEnd winding -> return (), renderQuadTo = \p1 p2 -> return (), renderBezierTo = \p1 p2 p3 -> return (), renderEllipse = \rect -> return (), renderText = mockRenderText, getImage = const . return $ Just $ ImageDef "test" def BS.empty [], addImage = \name size imgData flags -> return (), updateImage = \name size imgData -> return (), deleteImage = \name -> return () } mockFontManager :: FontManager mockFontManager = FontManager { computeTextMetrics = mockTextMetrics 1, computeTextMetrics_ = mockTextMetrics, computeTextSize = mockTextSize (Just 10) 1, computeTextSize_ = mockTextSize (Just 10), computeGlyphsPos = mockGlyphsPos (Just 10) 1, computeGlyphsPos_ = mockGlyphsPos (Just 10) } mockWenv :: s -> WidgetEnv s e mockWenv model = WidgetEnv { _weOs = "Mac OS X", _weDpr = 2, _weIsGhci = False, _weAppStartTs = 0, _weFontManager = mockFontManager, _weFindBranchByPath = const Seq.empty, _weMainButton = BtnLeft, _weContextButton = BtnRight, _weTheme = def, _weWindowSize = testWindowSize, _weWidgetShared = unsafePerformIO (newMVar M.empty), _weWidgetKeyMap = M.empty, _weHoveredPath = Nothing, _weFocusedPath = emptyPath, _weOverlayPath = Nothing, _weDragStatus = Nothing, _weMainBtnPress = Nothing, _weCursor = Nothing, _weModel = model, _weInputStatus = def, _weTimestamp = 0, _weThemeChanged = False, _weInTopLayer = const True, _weLayoutDirection = LayoutNone, _weViewport = Rect 0 0 testW testH, _weOffset = def } mockWenvEvtUnit :: s -> WidgetEnv s () mockWenvEvtUnit model = mockWenv model nodeInit :: (Eq s) => WidgetEnv s e -> WidgetNode s e -> WidgetNode s e nodeInit wenv node = nodeHandleEventRoot wenv [] node nodeMerge :: WidgetEnv s e -> WidgetNode s e -> WidgetNode s e -> WidgetNode s e nodeMerge wenv node oldNode = resNode where newNode = node & L.info . L.path .~ oldNode ^. L.info . L.path WidgetResult resNode _ = widgetMerge (newNode^. L.widget) wenv newNode oldNode nodeGetSizeReq :: WidgetEnv s e -> WidgetNode s e -> (SizeReq, SizeReq) nodeGetSizeReq wenv node = (sizeReqW, sizeReqH) where WidgetResult node2 _ = widgetInit (node ^. L.widget) wenv node sizeReqW = node2 ^. L.info . L.sizeReqW sizeReqH = node2 ^. L.info . L.sizeReqH nodeResize :: WidgetEnv s e -> WidgetNode s e -> Rect -> WidgetNode s e nodeResize wenv node viewport = result ^. L.node where resizeCheck = const True widget = node ^. L.widget result = widgetResize widget wenv node viewport resizeCheck nodeHandleEventCtx :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> MonomerCtx s e nodeHandleEventCtx wenv evts node = ctx where ctx = nodeHandleEventCtx_ wenv WInit evts node nodeHandleEventCtx_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> MonomerCtx s e nodeHandleEventCtx_ wenv init evts node = ctx where ctx = snd $ nodeHandleEvents wenv init evts node nodeHandleEventModel :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> s nodeHandleEventModel wenv evts node = model where model = nodeHandleEventModel_ wenv WInit evts node nodeHandleEventModel_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> s nodeHandleEventModel_ wenv init evts node = _weModel wenv2 where (wenv2, _, _) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventRoot :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> WidgetNode s e nodeHandleEventRoot wenv evts node = newRoot where newRoot = nodeHandleEventRoot_ wenv WInit evts node nodeHandleEventRoot_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> WidgetNode s e nodeHandleEventRoot_ wenv init evts node = newRoot where (_, newRoot, _) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventReqs :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq (WidgetRequest s e) nodeHandleEventReqs wenv evts node = reqs where reqs = nodeHandleEventReqs_ wenv WInit evts node nodeHandleEventReqs_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> Seq (WidgetRequest s e) nodeHandleEventReqs_ wenv init evts node = reqs where (_, _, reqs) = fst $ nodeHandleEvents wenv init evts node nodeHandleEventEvts :: (Eq s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq e nodeHandleEventEvts wenv evts node = newEvts where newEvts = nodeHandleEventEvts_ wenv WInit evts node nodeHandleEventEvts_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> Seq e nodeHandleEventEvts_ wenv init evts node = eventsFromReqs reqs where (_, _, reqs) = fst $ nodeHandleEvents wenv init evts node nodeHandleEvents :: (Eq s) => WidgetEnv s e -> InitWidget -> [SystemEvent] -> WidgetNode s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleEvents wenv init evts node = result where result = nodeHandleEventsSteps wenv init [evts] node nodeHandleEventsSteps :: (Eq s) => WidgetEnv s e -> InitWidget -> [[SystemEvent]] -> WidgetNode s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleEventsSteps wenv init eventSteps node = result where steps = case init of WInit -> tail $ nodeHandleEvents_ wenv init eventSteps node WInitKeepFirst -> nodeHandleEvents_ wenv WInit eventSteps node _ -> nodeHandleEvents_ wenv init eventSteps node result = foldl1 stepper steps stepper step1 step2 = result where ((_, _, reqs1), _) = step1 ((wenv2, root2, reqs2), ctx2) = step2 result = ((wenv2, root2, reqs1 <> reqs2), ctx2) nodeHandleEvents_ :: (Eq s) => WidgetEnv s e -> InitWidget -> [[SystemEvent]] -> WidgetNode s e -> [(HandlerStep s e, MonomerCtx s e)] nodeHandleEvents_ wenv init evtsG node = unsafePerformIO $ do channel <- liftIO newTChanIO fmap fst $ flip runStateT (monomerCtx channel) $ do L.inputStatus .= wenv ^. L.inputStatus handleResourcesInit stepA <- if init == WInit then do handleWidgetInit wenv pathReadyRoot else return (wenv, pathReadyRoot, Seq.empty) ctxA <- get let (wenvA, nodeA, reqsA) = stepA let resizeCheck = const True let resizeRes = widgetResize (nodeA ^. L.widget) wenv nodeA vp resizeCheck step <- handleWidgetResult wenvA True resizeRes ctx <- get let (wenvr, rootr, reqsr) = step (_, _, steps) <- foldM runStep (wenvr, rootr, [(step, ctx)]) evtsG return $ if init == WInit then (stepA, ctxA) : reverse steps else reverse steps where winSize = _weWindowSize wenv vp = Rect 0 0 (_sW winSize) (_sH winSize) dpr = 1 epr = 1 model = _weModel wenv monomerCtx channel = initMonomerCtx undefined channel winSize dpr epr model pathReadyRoot = node & L.info . L.path .~ rootPath & L.info . L.widgetId .~ WidgetId (wenv ^. L.timestamp) rootPath runStep (wenv, root, accum) evts = do let newWenv = wenv & L.timestamp +~ 1 step <- handleSystemEvents newWenv root evts ctx <- get let (wenv2, root2, reqs2) = step return (wenv2, root2, (step, ctx) : accum) nodeHandleResult :: (Eq s) => WidgetEnv s e -> WidgetResult s e -> (HandlerStep s e, MonomerCtx s e) nodeHandleResult wenv result = unsafePerformIO $ do channel <- liftIO newTChanIO let winSize = _weWindowSize wenv let dpr = 1 let epr = 1 let model = _weModel wenv let monomerCtx = initMonomerCtx undefined channel winSize dpr epr model flip runStateT monomerCtx $ do L.inputStatus .= wenv ^. L.inputStatus handleResourcesInit handleWidgetResult wenv True result roundRectUnits :: Rect -> Rect roundRectUnits (Rect x y w h) = Rect nx ny nw nh where nx = fromIntegral (round x) ny = fromIntegral (round y) nw = fromIntegral (round w) nh = fromIntegral (round h) useVideoSubSystem :: IO Bool useVideoSubSystem = do (== Just "1") <$> lookupEnv "USE_SDL_VIDEO_SUBSYSTEM" testInVideoSubSystem :: Expectation -> Expectation testInVideoSubSystem expectation = do useVideo <- useVideoSubSystem if useVideo then expectation else pendingWith "SDL Video sub system not initialized. Skipping."
015844242529d74f1f330bf4fc4454a673b54dccb2719328e0e55c90b906cbe8
patperry/hs-linear-algebra
Vector.hs
module Vector ( tests_Vector ) where import Data.AEq import Debug.Trace import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck hiding ( vector ) import qualified Test.QuickCheck as QC import Numeric.LinearAlgebra.Vector( Vector ) import qualified Numeric.LinearAlgebra.Vector as V import Test.QuickCheck.LinearAlgebra( TestElem(..), Dim(..), Assocs(..), VectorPair(..) ) import qualified Test.QuickCheck.LinearAlgebra as Test import Typed tests_Vector = testGroup "Vector" [ testPropertyI "dim/fromList" prop_dim_fromList , testPropertyI "at/fromList" prop_at_fromList , testPropertyI "zero" prop_zero , testPropertyI "constant" prop_constant , testPropertyI "indices" prop_indices , testPropertyI "elems" prop_elems , testPropertyI "assocs" prop_assocs , testPropertyI "update" prop_update , testPropertyI "accum" prop_accum , testPropertyI "map" prop_map , testPropertyI "zipWith" prop_zipWith , testPropertyI "concat" prop_concat , testPropertyI "slice" prop_slice , testPropertyI "splitAt" prop_splitAt , testPropertyDZ "sumAbs" prop_sumAbs prop_sumAbs , testPropertyDZ "norm2" prop_norm2 prop_norm2 , testPropertyDZ "whichMaxAbs1" prop_whichMaxAbs1 prop_whichMaxAbs1 , testPropertyDZ "whichMaxAbs2" prop_whichMaxAbs1 prop_whichMaxAbs2 , testPropertyDZ "dot" prop_dot prop_dot , testPropertyDZ "kronecker" prop_kronecker prop_kronecker , testPropertyDZ "add" prop_add prop_add , testPropertyDZ "addWithScale" prop_addWithScale prop_addWithScale , testPropertyDZ "sub" prop_sub prop_sub , testPropertyDZ "scale" prop_scale prop_scale , testPropertyDZ "mul" prop_mul prop_mul , testPropertyDZ "negate" prop_negate prop_negate , testPropertyDZ "conjugate" prop_conjugate prop_conjugate , testPropertyDZ "abs" prop_abs prop_abs , testPropertyDZ "signum" prop_signum prop_signum , testPropertyDZ "div" prop_div prop_div , testPropertyDZ "recip" prop_recip prop_recip , testPropertyDZ "sqrt" prop_sqrt prop_sqrt , testPropertyDZ "exp" prop_exp prop_exp , testPropertyDZ "log" prop_log prop_log , testPropertyDZ "pow" prop_pow prop_pow , testPropertyDZ "sin" prop_sin prop_sin , testPropertyDZ "cos" prop_cos prop_cos , testPropertyDZ "tan" prop_tan prop_tan , testPropertyDZ "asin" prop_asin prop_asin , testPropertyDZ "acos" prop_acos prop_acos , testPropertyDZ "atan" prop_atan prop_atan , testPropertyDZ "sinh" prop_sinh prop_sinh , testPropertyDZ "cosh" prop_cosh prop_cosh , testPropertyDZ "tanh" prop_tanh prop_tanh , testPropertyDZ "asinh" prop_asinh prop_asinh , testPropertyDZ "acosh" prop_acosh prop_acosh , testPropertyDZ "atanh" prop_atanh prop_atanh ] ------------------------- Vector Construction ------------------------------ prop_dim_fromList t (Dim n) = forAll (QC.vector n) $ \es -> let x = typed t $ V.fromList n es in V.dim x == n prop_at_fromList t (Dim n) = forAll (QC.vector n) $ \es -> let x = typed t $ V.fromList n es in and [ V.at x i === e | (i,e) <- zip [ 0..n-1 ] es ] prop_zero t (Dim n) = let x = typed t $ V.zero n in x === V.fromList n (replicate n 0) prop_constant t (Dim n) e = V.constant n e === V.fromList n (replicate n e) where _ = typed t [e] -------------------------- Accessing Vectors ------------------------------ prop_indices t x = V.indices x === [ 0..((V.dim x) - 1) ] where _ = immutableVector x _ = typed t x prop_elems t x = V.elems x === [ V.at x i | i <- V.indices x ] where _ = typed t x prop_assocs t x = V.assocs x === zip (V.indices x) (V.elems x) where _ = typed t x ------------------------- Incremental Updates ------------------------------ prop_update t (Assocs n ies) = forAll (typed t `fmap` Test.vector n) $ \x -> let x' = V.update x ies is = V.indices x is1 = (fst . unzip) ies is0 = [ i | i <- is, i `notElem` is1 ] in and $ [ V.at x' i `elem` [ e | (i',e) <- ies, i' == i ] | i <- is1 ] ++ [ V.at x' i === V.at x i | i <- is0 ] prop_accum t (Blind f) (Assocs n ies) = forAll (typed t `fmap` Test.vector n) $ \x -> let x' = V.accum f x ies in x' === V.fromList n [ foldl f e [ e' | (i',e') <- ies, i' == i] | (i,e) <- V.assocs x ] where _ = typed t $ (snd . unzip) ies -------------------------- Derived Vectors ------------------------------ prop_map t (Blind f) x = V.map f x === V.fromList (V.dim x) (map f $ V.elems x) where _ = typed t x _ = typed t $ V.map f x prop_zipWith t (Blind f) (VectorPair x y) = V.zipWith f x y === (V.fromList (V.dim x) $ zipWith f (V.elems x) (V.elems y)) where _ = typed t x _ = typed t y _ = typed t $ V.zipWith f x y prop_concat t xs = V.elems (V.concat xs) === concatMap V.elems xs where _ = typed t $ head xs ------------------------------ Vector Views-- -------------------------------- prop_slice t x = forAll (choose (0,n)) $ \n' -> forAll (choose (0,n-n')) $ \o -> V.slice o n' x === V.fromList n' (take n' $ drop o $ es) where n = V.dim x es = V.elems x _ = typed t x prop_splitAt t x = forAll (choose (0,n)) $ \k -> V.splitAt k x === (V.fromList k $ take k es, V.fromList (n-k) $ drop k es) where n = V.dim x es = V.elems x _ = typed t x -------------------------- Num Vector Operations -------------------------- prop_add t (VectorPair x y) = x `V.add` y === V.zipWith (+) x y where _ = typed t x prop_addWithScale t alpha (VectorPair x y) = V.addWithScale alpha x y ~== V.add (V.scale alpha x) y where _ = typed t x prop_sub t (VectorPair x y) = x `V.sub` y === V.zipWith (-) x y where _ = typed t x prop_scale t k x = V.scale k x ~== V.map (k*) x where _ = typed t x prop_mul t (VectorPair x y) = x `V.mul` y === V.zipWith (*) x y where _ = typed t x prop_negate t x = V.negate x === V.map negate x where _ = typed t x prop_conjugate t x = V.conjugate x === V.map conjugate x where _ = typed t x prop_abs t x = V.abs x === V.map abs x where _ = typed t x prop_signum t x = V.signum x === V.map signum x where _ = typed t x -------------------- Fractional Vector Operations ------------------------ prop_div t (VectorPair x y) = x `V.div` y ~== V.zipWith (/) x y where _ = typed t x prop_recip t x = V.recip x ~== V.map (1/) x where _ = typed t x -------------------- Floating Vector Operations ------------------------ prop_exp t x = V.exp x ~== V.map exp x where _ = typed t x prop_sqrt t x = V.sqrt x ~== V.map sqrt x where _ = typed t x prop_log t x = V.log x ~== V.map log x where _ = typed t x prop_pow t (VectorPair x y) = x `V.pow` y ~== V.zipWith (**) x y where _ = typed t x prop_sin t x = V.sin x ~== V.map sin x where _ = typed t x prop_cos t x = V.cos x ~== V.map cos x where _ = typed t x prop_tan t x = V.tan x ~== V.map tan x where _ = typed t x prop_asin t x = trace ( show ( V.asin x ) + + " \n " + + ( show $ V.map asin x ) ) $ V.asin x ~== V.map asin x where _ = typed t x prop_acos t x = V.acos x ~== V.map acos x where _ = typed t x prop_atan t x = V.atan x ~== V.map atan x where _ = typed t x prop_sinh t x = V.sinh x ~== V.map sinh x where _ = typed t x prop_cosh t x = V.cosh x ~== V.map cosh x where _ = typed t x prop_tanh t x = V.tanh x ~== V.map tanh x where _ = typed t x prop_asinh t x = trace ( show ( V.asinh x ) + + " \n " + + ( show $ V.map asinh x ) ) $ V.asinh x ~== V.map asinh x where _ = typed t x prop_acosh t x = V.acosh x ~== V.map acosh x where _ = typed t x prop_atanh t x = V.atanh x ~== V.map atanh x where _ = typed t x -------------------------- Vector Properties --------------------------------- prop_sumAbs t x = V.sumAbs x ~== (sum $ map norm1 $ V.elems x) where _ = typed t x prop_norm2 t x = V.norm2 x ~== (sqrt $ sum $ map (^^2) $ map norm $ V.elems x) where _ = typed t x prop_whichMaxAbs1 t x = (V.dim x > 0) && all (not . isNaN) (map norm1 $ V.elems x) ==> V.at x i === e where (i,e) = V.whichMaxAbs x _ = typed t x prop_whichMaxAbs2 t x = (V.dim x > 0) && all (not . isNaN) (map norm1 $ V.elems x) ==> all (<= norm1 e) $ map norm1 (V.elems x) where (_,e) = V.whichMaxAbs x _ = typed t x prop_dot t (VectorPair x y) = V.dot x y ~== sum (V.elems (x * conj y)) where conj = V.conjugate (*) = V.mul _ = typed t x prop_kronecker t x y = x `V.kronecker` y ~== V.fromList (V.dim x * V.dim y) [ e*f | e <- V.elems x, f <- V.elems y ] where _ = typed t x
null
https://raw.githubusercontent.com/patperry/hs-linear-algebra/887939175e03687b12eabe2fce5904b494242a1a/tests/Vector.hs
haskell
----------------------- Vector Construction ------------------------------ ------------------------ Accessing Vectors ------------------------------ ----------------------- Incremental Updates ------------------------------ ------------------------ Derived Vectors ------------------------------ ---------------------------- Vector Views-- -------------------------------- ------------------------ Num Vector Operations -------------------------- ------------------ Fractional Vector Operations ------------------------ ------------------ Floating Vector Operations ------------------------ ------------------------ Vector Properties ---------------------------------
module Vector ( tests_Vector ) where import Data.AEq import Debug.Trace import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck hiding ( vector ) import qualified Test.QuickCheck as QC import Numeric.LinearAlgebra.Vector( Vector ) import qualified Numeric.LinearAlgebra.Vector as V import Test.QuickCheck.LinearAlgebra( TestElem(..), Dim(..), Assocs(..), VectorPair(..) ) import qualified Test.QuickCheck.LinearAlgebra as Test import Typed tests_Vector = testGroup "Vector" [ testPropertyI "dim/fromList" prop_dim_fromList , testPropertyI "at/fromList" prop_at_fromList , testPropertyI "zero" prop_zero , testPropertyI "constant" prop_constant , testPropertyI "indices" prop_indices , testPropertyI "elems" prop_elems , testPropertyI "assocs" prop_assocs , testPropertyI "update" prop_update , testPropertyI "accum" prop_accum , testPropertyI "map" prop_map , testPropertyI "zipWith" prop_zipWith , testPropertyI "concat" prop_concat , testPropertyI "slice" prop_slice , testPropertyI "splitAt" prop_splitAt , testPropertyDZ "sumAbs" prop_sumAbs prop_sumAbs , testPropertyDZ "norm2" prop_norm2 prop_norm2 , testPropertyDZ "whichMaxAbs1" prop_whichMaxAbs1 prop_whichMaxAbs1 , testPropertyDZ "whichMaxAbs2" prop_whichMaxAbs1 prop_whichMaxAbs2 , testPropertyDZ "dot" prop_dot prop_dot , testPropertyDZ "kronecker" prop_kronecker prop_kronecker , testPropertyDZ "add" prop_add prop_add , testPropertyDZ "addWithScale" prop_addWithScale prop_addWithScale , testPropertyDZ "sub" prop_sub prop_sub , testPropertyDZ "scale" prop_scale prop_scale , testPropertyDZ "mul" prop_mul prop_mul , testPropertyDZ "negate" prop_negate prop_negate , testPropertyDZ "conjugate" prop_conjugate prop_conjugate , testPropertyDZ "abs" prop_abs prop_abs , testPropertyDZ "signum" prop_signum prop_signum , testPropertyDZ "div" prop_div prop_div , testPropertyDZ "recip" prop_recip prop_recip , testPropertyDZ "sqrt" prop_sqrt prop_sqrt , testPropertyDZ "exp" prop_exp prop_exp , testPropertyDZ "log" prop_log prop_log , testPropertyDZ "pow" prop_pow prop_pow , testPropertyDZ "sin" prop_sin prop_sin , testPropertyDZ "cos" prop_cos prop_cos , testPropertyDZ "tan" prop_tan prop_tan , testPropertyDZ "asin" prop_asin prop_asin , testPropertyDZ "acos" prop_acos prop_acos , testPropertyDZ "atan" prop_atan prop_atan , testPropertyDZ "sinh" prop_sinh prop_sinh , testPropertyDZ "cosh" prop_cosh prop_cosh , testPropertyDZ "tanh" prop_tanh prop_tanh , testPropertyDZ "asinh" prop_asinh prop_asinh , testPropertyDZ "acosh" prop_acosh prop_acosh , testPropertyDZ "atanh" prop_atanh prop_atanh ] prop_dim_fromList t (Dim n) = forAll (QC.vector n) $ \es -> let x = typed t $ V.fromList n es in V.dim x == n prop_at_fromList t (Dim n) = forAll (QC.vector n) $ \es -> let x = typed t $ V.fromList n es in and [ V.at x i === e | (i,e) <- zip [ 0..n-1 ] es ] prop_zero t (Dim n) = let x = typed t $ V.zero n in x === V.fromList n (replicate n 0) prop_constant t (Dim n) e = V.constant n e === V.fromList n (replicate n e) where _ = typed t [e] prop_indices t x = V.indices x === [ 0..((V.dim x) - 1) ] where _ = immutableVector x _ = typed t x prop_elems t x = V.elems x === [ V.at x i | i <- V.indices x ] where _ = typed t x prop_assocs t x = V.assocs x === zip (V.indices x) (V.elems x) where _ = typed t x prop_update t (Assocs n ies) = forAll (typed t `fmap` Test.vector n) $ \x -> let x' = V.update x ies is = V.indices x is1 = (fst . unzip) ies is0 = [ i | i <- is, i `notElem` is1 ] in and $ [ V.at x' i `elem` [ e | (i',e) <- ies, i' == i ] | i <- is1 ] ++ [ V.at x' i === V.at x i | i <- is0 ] prop_accum t (Blind f) (Assocs n ies) = forAll (typed t `fmap` Test.vector n) $ \x -> let x' = V.accum f x ies in x' === V.fromList n [ foldl f e [ e' | (i',e') <- ies, i' == i] | (i,e) <- V.assocs x ] where _ = typed t $ (snd . unzip) ies prop_map t (Blind f) x = V.map f x === V.fromList (V.dim x) (map f $ V.elems x) where _ = typed t x _ = typed t $ V.map f x prop_zipWith t (Blind f) (VectorPair x y) = V.zipWith f x y === (V.fromList (V.dim x) $ zipWith f (V.elems x) (V.elems y)) where _ = typed t x _ = typed t y _ = typed t $ V.zipWith f x y prop_concat t xs = V.elems (V.concat xs) === concatMap V.elems xs where _ = typed t $ head xs prop_slice t x = forAll (choose (0,n)) $ \n' -> forAll (choose (0,n-n')) $ \o -> V.slice o n' x === V.fromList n' (take n' $ drop o $ es) where n = V.dim x es = V.elems x _ = typed t x prop_splitAt t x = forAll (choose (0,n)) $ \k -> V.splitAt k x === (V.fromList k $ take k es, V.fromList (n-k) $ drop k es) where n = V.dim x es = V.elems x _ = typed t x prop_add t (VectorPair x y) = x `V.add` y === V.zipWith (+) x y where _ = typed t x prop_addWithScale t alpha (VectorPair x y) = V.addWithScale alpha x y ~== V.add (V.scale alpha x) y where _ = typed t x prop_sub t (VectorPair x y) = x `V.sub` y === V.zipWith (-) x y where _ = typed t x prop_scale t k x = V.scale k x ~== V.map (k*) x where _ = typed t x prop_mul t (VectorPair x y) = x `V.mul` y === V.zipWith (*) x y where _ = typed t x prop_negate t x = V.negate x === V.map negate x where _ = typed t x prop_conjugate t x = V.conjugate x === V.map conjugate x where _ = typed t x prop_abs t x = V.abs x === V.map abs x where _ = typed t x prop_signum t x = V.signum x === V.map signum x where _ = typed t x prop_div t (VectorPair x y) = x `V.div` y ~== V.zipWith (/) x y where _ = typed t x prop_recip t x = V.recip x ~== V.map (1/) x where _ = typed t x prop_exp t x = V.exp x ~== V.map exp x where _ = typed t x prop_sqrt t x = V.sqrt x ~== V.map sqrt x where _ = typed t x prop_log t x = V.log x ~== V.map log x where _ = typed t x prop_pow t (VectorPair x y) = x `V.pow` y ~== V.zipWith (**) x y where _ = typed t x prop_sin t x = V.sin x ~== V.map sin x where _ = typed t x prop_cos t x = V.cos x ~== V.map cos x where _ = typed t x prop_tan t x = V.tan x ~== V.map tan x where _ = typed t x prop_asin t x = trace ( show ( V.asin x ) + + " \n " + + ( show $ V.map asin x ) ) $ V.asin x ~== V.map asin x where _ = typed t x prop_acos t x = V.acos x ~== V.map acos x where _ = typed t x prop_atan t x = V.atan x ~== V.map atan x where _ = typed t x prop_sinh t x = V.sinh x ~== V.map sinh x where _ = typed t x prop_cosh t x = V.cosh x ~== V.map cosh x where _ = typed t x prop_tanh t x = V.tanh x ~== V.map tanh x where _ = typed t x prop_asinh t x = trace ( show ( V.asinh x ) + + " \n " + + ( show $ V.map asinh x ) ) $ V.asinh x ~== V.map asinh x where _ = typed t x prop_acosh t x = V.acosh x ~== V.map acosh x where _ = typed t x prop_atanh t x = V.atanh x ~== V.map atanh x where _ = typed t x prop_sumAbs t x = V.sumAbs x ~== (sum $ map norm1 $ V.elems x) where _ = typed t x prop_norm2 t x = V.norm2 x ~== (sqrt $ sum $ map (^^2) $ map norm $ V.elems x) where _ = typed t x prop_whichMaxAbs1 t x = (V.dim x > 0) && all (not . isNaN) (map norm1 $ V.elems x) ==> V.at x i === e where (i,e) = V.whichMaxAbs x _ = typed t x prop_whichMaxAbs2 t x = (V.dim x > 0) && all (not . isNaN) (map norm1 $ V.elems x) ==> all (<= norm1 e) $ map norm1 (V.elems x) where (_,e) = V.whichMaxAbs x _ = typed t x prop_dot t (VectorPair x y) = V.dot x y ~== sum (V.elems (x * conj y)) where conj = V.conjugate (*) = V.mul _ = typed t x prop_kronecker t x y = x `V.kronecker` y ~== V.fromList (V.dim x * V.dim y) [ e*f | e <- V.elems x, f <- V.elems y ] where _ = typed t x
256c6628bb6c0cc4465f391bf7baa909b6f2e176d3ec2b48996cea278d42651b
bytekid/mkbtt
proof.ml
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 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 , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 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 TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 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, either version 3 of the License, or (at your * option) any later version. * * TTT2 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 TTT2. If not, see </>. *) (*** OPENS ********************************************************************) open Util;; open Processors;; open Rewritingx;; (*** MODULES ******************************************************************) module C = Complexity;; module F = Format;; module M = Monad;; module O = Option;; module P = Processor;; module S = Status;; module Split = Transformation.Split;; (*** TYPES ********************************************************************) type t = Open | Qed | Processor of P.t * t list;; (*** FUNCTIONS ****************************************************************) let (>>=) = M.(>>=);; (* Constructors *) let unfinished = Open;; let finished = Qed;; let make pr ps = Processor (pr,ps);; let rec append p = function | Open -> p | Qed -> failwith "finished proof object" | Processor (pr,ps) -> Processor (pr,List.map (append p) ps) ;; let merge = let equal p q = match (p,q) with | Processor (pr,_), Processor (pr',_) -> P.equal pr pr' | _, _ -> false in let rec merge p q = match (p,q) with | Open, Open -> Open | Qed, Qed -> Qed | Processor (pr,ps), Processor (pr',qs) -> let combine (ps,qs) p = try let ps = (merge p (List.find (equal p) qs)) :: ps in let compare p = (-) 1 <.> Bool.to_int <.> equal p in let qs = List.remove_all ~c:compare p qs in (ps,qs) with Not_found -> (p :: ps,qs) in if P.equal pr pr' then let (ps,qs) = List.foldl combine ([],qs) ps in Processor (pr,List.rev (List.rev_append qs ps)) else failwith "conflicting proof structures" | _, _ -> failwith "conflicting proof structures" in List.foldl1 merge <?> "empty list" ;; let optimize pr p q = let rec optimize = function | Open -> Open | Qed -> Qed | Processor (pr',ps') -> if P.equal pr pr' then let ip = P.input pr' and op = P.output pr' in let op' = match q with Processor (pr,_) -> P.input pr | _ -> [] in if List.length ip = 1 && List.length op = 1 then if Problem.is_empty (List.hd op) then q else if Problem.is_cp (List.hd ip) then FIXME DELETE ( Format.printf " @\ninput:@\n " ; Problem.fprintf Format.std_formatter ( List.hd ip ) ; Format.printf " @\nnew:@\n " ; Problem.fprintf Format.std_formatter ( List.hd op ' ) ; Format.printf " @\nold:@\n% ! " ; Problem.fprintf Format.std_formatter ( List.hd op ) ; Format.printf " @\n@\n% ! " ; ( Format.printf "@\ninput:@\n"; Problem.fprintf Format.std_formatter (List.hd ip); Format.printf "@\nnew:@\n"; Problem.fprintf Format.std_formatter (List.hd op'); Format.printf "@\nold:@\n%!"; Problem.fprintf Format.std_formatter (List.hd op); Format.printf "@\n@\n%!"; *) match Split.generate [] (List.hd ip) (op' @ op) with | Some proof -> Processor (P.P_split proof,q :: ps') | None -> failwith "illegal input" (* ) *) else failwith "illegal input" else failwith "illegal input" else Processor (pr',List.rev (List.map optimize ps')) in optimize p ;; (* Predicates *) let is_qed = function Qed -> true | _ -> false;; let is_open = function Open -> true | _ -> false;; let is_processor = function Processor _ -> true | _ -> false;; (* Complexity Bounds *) let rec complexity = function | Open -> None | Qed -> Some C.constant | Processor (pr,ps) -> let collect p = flip O.map (complexity p) <.> C.add in let combine c p = O.fold (collect p) None c in let c = List.foldl combine (Some C.constant) ps in O.fold (flip P.complexity pr) None c ;; let critical p = let rec critical r = function | Open | Qed -> r | Processor (pr,ps) -> match List.foldl critical r ps with | None -> None | Some (c,prs) -> let c' = P.complexity C.constant pr in O.map (fun c' -> if C.equal c c' then (c,pr::prs) else if C.(<) c c' then (c',[pr]) else (c,prs)) c' in O.fold (fun (c,prs) -> if C.equal C.constant c || prs = [] then None else Some (c,prs)) None (critical (Some (C.constant,[])) p) ;; (* Printers *) let rec fprintf fmt = function | Open -> M.return (F.fprintf fmt "@[Open@]") | Qed -> M.return (F.fprintf fmt "@[Qed@]") | Processor (pr,ps) -> let fs = List.map (flip fprintf) ps in F.fprintf fmt "@[<1>"; P.fprintf fs fmt pr >>= fun _ -> M.return (F.fprintf fmt "@]") ;; let to_string p = fprintf F.str_formatter p >>= (M.return <.> F.flush_str_formatter) ;; let fprintfx s fmt p = let rec fprintfx dp fmt = function | Open -> M.return (F.fprintf fmt "<open/>") | Qed -> if Status.is_nonterminating s then M.return () else if dp then M.return (F.fprintf fmt "<pIsEmpty/>") else M.return (F.fprintf fmt "<rIsEmpty/>") | Processor (pr,ps) -> let dp = match pr with P.P_dp _ -> true | _ -> dp in let fs = List.map (flip (fprintfx dp)) ps in P.fprintfx s fs fmt pr >>= fun _ -> M.return () in F.fprintf fmt "@{<proof>"; fprintfx false fmt p >>= fun _ -> M.return (F.fprintf fmt "@}") ;; let to_stringx s p = fprintfx s F.str_formatter p >>= (M.return <.> F.flush_str_formatter) ;;
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/ttt2/src/strategy/proof.ml
ocaml
** OPENS ******************************************************************* ** MODULES ***************************************************************** ** TYPES ******************************************************************* ** FUNCTIONS *************************************************************** Constructors ) Predicates Complexity Bounds Printers
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 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 , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 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 TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 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, either version 3 of the License, or (at your * option) any later version. * * TTT2 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 TTT2. If not, see </>. *) open Util;; open Processors;; open Rewritingx;; module C = Complexity;; module F = Format;; module M = Monad;; module O = Option;; module P = Processor;; module S = Status;; module Split = Transformation.Split;; type t = Open | Qed | Processor of P.t * t list;; let (>>=) = M.(>>=);; let unfinished = Open;; let finished = Qed;; let make pr ps = Processor (pr,ps);; let rec append p = function | Open -> p | Qed -> failwith "finished proof object" | Processor (pr,ps) -> Processor (pr,List.map (append p) ps) ;; let merge = let equal p q = match (p,q) with | Processor (pr,_), Processor (pr',_) -> P.equal pr pr' | _, _ -> false in let rec merge p q = match (p,q) with | Open, Open -> Open | Qed, Qed -> Qed | Processor (pr,ps), Processor (pr',qs) -> let combine (ps,qs) p = try let ps = (merge p (List.find (equal p) qs)) :: ps in let compare p = (-) 1 <.> Bool.to_int <.> equal p in let qs = List.remove_all ~c:compare p qs in (ps,qs) with Not_found -> (p :: ps,qs) in if P.equal pr pr' then let (ps,qs) = List.foldl combine ([],qs) ps in Processor (pr,List.rev (List.rev_append qs ps)) else failwith "conflicting proof structures" | _, _ -> failwith "conflicting proof structures" in List.foldl1 merge <?> "empty list" ;; let optimize pr p q = let rec optimize = function | Open -> Open | Qed -> Qed | Processor (pr',ps') -> if P.equal pr pr' then let ip = P.input pr' and op = P.output pr' in let op' = match q with Processor (pr,_) -> P.input pr | _ -> [] in if List.length ip = 1 && List.length op = 1 then if Problem.is_empty (List.hd op) then q else if Problem.is_cp (List.hd ip) then FIXME DELETE ( Format.printf " @\ninput:@\n " ; Problem.fprintf Format.std_formatter ( List.hd ip ) ; Format.printf " @\nnew:@\n " ; Problem.fprintf Format.std_formatter ( List.hd op ' ) ; Format.printf " @\nold:@\n% ! " ; Problem.fprintf Format.std_formatter ( List.hd op ) ; Format.printf " @\n@\n% ! " ; ( Format.printf "@\ninput:@\n"; Problem.fprintf Format.std_formatter (List.hd ip); Format.printf "@\nnew:@\n"; Problem.fprintf Format.std_formatter (List.hd op'); Format.printf "@\nold:@\n%!"; Problem.fprintf Format.std_formatter (List.hd op); Format.printf "@\n@\n%!"; *) match Split.generate [] (List.hd ip) (op' @ op) with | Some proof -> Processor (P.P_split proof,q :: ps') | None -> failwith "illegal input" else failwith "illegal input" else failwith "illegal input" else Processor (pr',List.rev (List.map optimize ps')) in optimize p ;; let is_qed = function Qed -> true | _ -> false;; let is_open = function Open -> true | _ -> false;; let is_processor = function Processor _ -> true | _ -> false;; let rec complexity = function | Open -> None | Qed -> Some C.constant | Processor (pr,ps) -> let collect p = flip O.map (complexity p) <.> C.add in let combine c p = O.fold (collect p) None c in let c = List.foldl combine (Some C.constant) ps in O.fold (flip P.complexity pr) None c ;; let critical p = let rec critical r = function | Open | Qed -> r | Processor (pr,ps) -> match List.foldl critical r ps with | None -> None | Some (c,prs) -> let c' = P.complexity C.constant pr in O.map (fun c' -> if C.equal c c' then (c,pr::prs) else if C.(<) c c' then (c',[pr]) else (c,prs)) c' in O.fold (fun (c,prs) -> if C.equal C.constant c || prs = [] then None else Some (c,prs)) None (critical (Some (C.constant,[])) p) ;; let rec fprintf fmt = function | Open -> M.return (F.fprintf fmt "@[Open@]") | Qed -> M.return (F.fprintf fmt "@[Qed@]") | Processor (pr,ps) -> let fs = List.map (flip fprintf) ps in F.fprintf fmt "@[<1>"; P.fprintf fs fmt pr >>= fun _ -> M.return (F.fprintf fmt "@]") ;; let to_string p = fprintf F.str_formatter p >>= (M.return <.> F.flush_str_formatter) ;; let fprintfx s fmt p = let rec fprintfx dp fmt = function | Open -> M.return (F.fprintf fmt "<open/>") | Qed -> if Status.is_nonterminating s then M.return () else if dp then M.return (F.fprintf fmt "<pIsEmpty/>") else M.return (F.fprintf fmt "<rIsEmpty/>") | Processor (pr,ps) -> let dp = match pr with P.P_dp _ -> true | _ -> dp in let fs = List.map (flip (fprintfx dp)) ps in P.fprintfx s fs fmt pr >>= fun _ -> M.return () in F.fprintf fmt "@{<proof>"; fprintfx false fmt p >>= fun _ -> M.return (F.fprintf fmt "@}") ;; let to_stringx s p = fprintfx s F.str_formatter p >>= (M.return <.> F.flush_str_formatter) ;;
861ed13a3777673bb9f25de3b4e8503cf185f9e65738b87b063351148b93f95e
biscuit-auth/biscuit-haskell
Utils.hs
| Module : Auth . Biscuit . Utils Copyright : , 2021 License : MIT Maintainer : Module : Auth.Biscuit.Utils Copyright : © Clément Delafargue, 2021 License : MIT Maintainer : -} module Auth.Biscuit.Utils ( maybeToRight , rightToMaybe ) where -- | Exactly like `maybeToRight` from the `either` package, -- but without the dependency footprint maybeToRight :: b -> Maybe a -> Either b a maybeToRight b = maybe (Left b) Right -- | Exactly like `rightToMaybe` from the `either` package, -- but without the dependency footprint rightToMaybe :: Either b a -> Maybe a rightToMaybe = either (const Nothing) Just
null
https://raw.githubusercontent.com/biscuit-auth/biscuit-haskell/fca1c26c4468f1977ea39b3afea0b45942c736ef/biscuit/src/Auth/Biscuit/Utils.hs
haskell
| Exactly like `maybeToRight` from the `either` package, but without the dependency footprint | Exactly like `rightToMaybe` from the `either` package, but without the dependency footprint
| Module : Auth . Biscuit . Utils Copyright : , 2021 License : MIT Maintainer : Module : Auth.Biscuit.Utils Copyright : © Clément Delafargue, 2021 License : MIT Maintainer : -} module Auth.Biscuit.Utils ( maybeToRight , rightToMaybe ) where maybeToRight :: b -> Maybe a -> Either b a maybeToRight b = maybe (Left b) Right rightToMaybe :: Either b a -> Maybe a rightToMaybe = either (const Nothing) Just
dc23554f963b607129d1af747717dcbf0b633c0988f1be7d54b213664aac626f
marigold-dev/deku
tezos.ml
module Michelson = Michelson module Address = Address module Ticket_id = Ticket_id module Tezos_operation_hash = Tezos_operation_hash
null
https://raw.githubusercontent.com/marigold-dev/deku/21ec2bf05ce688c5b6012be16545175e75403f06/deku-p/src/core/tezos/tezos.ml
ocaml
module Michelson = Michelson module Address = Address module Ticket_id = Ticket_id module Tezos_operation_hash = Tezos_operation_hash
b669fc0577cdda5e9dab4115757e060017d376a49fd773014bf8dd8ad735f17c
schell/editor
Load.hs
# LANGUAGE TypeFamilies # module Graphics.Texture.Load where import Codec.Picture import Graphics.Utils import Graphics.Rendering.OpenGL import Control.Monad (when, unless) import Data.Vector.Storable (unsafeWith, Storable) import Data.Maybe (isNothing) initTexture :: FilePath -- ^ The texture to load. -> Int -- ^ The index of the texture unit to hold the texture in. -> IO (Maybe TextureObject) initTexture file u = do texture Texture2D $= Enabled -- Load our texture or die. mTex <- loadTexture file u unless (isNothing mTex) $ do -- Set the texture params on our bound texture. textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) when (isNothing mTex) $ putStrLn $ "Could not initialize "++ file return mTex loadTexture :: FilePath -> Int -> IO (Maybe TextureObject) loadTexture f u = do putStrLn $ "Loading texture "++f eDynImg <- readImage f case eDynImg of Left note -> do putStrLn $ "Could not load texture '"++f++"'.\nNote: "++note return Nothing Right img -> do -- Get our texture object. tex <- newBoundTexUnit u -- Buffer our texture data. success <- bufferDataIntoBoundTexture img unless success $ putStrLn $ " ("++f++")" return $ Just tex newBoundTexUnit :: Int -> IO TextureObject newBoundTexUnit u = do [tex] <- genObjectNames 1 texture Texture2D $= Enabled activeTexture $= TextureUnit (fromIntegral u) textureBinding Texture2D $= Just tex return tex bufferDataIntoBoundTexture :: DynamicImage -> IO Bool bufferDataIntoBoundTexture dynImg = case dynImg of (ImageRGB8 img) -> unsafeTexImage2D RGB8 RGB img (ImageRGBA8 img) -> unsafeTexImage2D RGBA8 RGBA img _ -> do putStrLn "Texture is not an expected format (expecting RGB8 or RGBA8)." return False unsafeTexImage2D :: (Storable t1, PixelBaseComponent t ~ t1) => PixelInternalFormat -> PixelFormat -> Image t -> IO Bool unsafeTexImage2D rb r (Image w h dat) = do unsafeWith dat $ \ptr -> texImage2D Texture2D -- No proxy NoProxy No mipmaps 0 Internal storage @ rgba8 rb -- Size of the image (TextureSize2D (fromIntegral w) (fromIntegral h)) -- No borders 0 Pixel data in unsigned bytes , rgba order (PixelData r UnsignedByte ptr) printError return True
null
https://raw.githubusercontent.com/schell/editor/0f0d2eb67df19e8285c6aaeeeca96bff3110f68d/src/Graphics/Texture/Load.hs
haskell
^ The texture to load. ^ The index of the texture unit to hold the texture in. Load our texture or die. Set the texture params on our bound texture. Get our texture object. Buffer our texture data. No proxy Size of the image No borders
# LANGUAGE TypeFamilies # module Graphics.Texture.Load where import Codec.Picture import Graphics.Utils import Graphics.Rendering.OpenGL import Control.Monad (when, unless) import Data.Vector.Storable (unsafeWith, Storable) import Data.Maybe (isNothing) -> IO (Maybe TextureObject) initTexture file u = do texture Texture2D $= Enabled mTex <- loadTexture file u unless (isNothing mTex) $ do textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) when (isNothing mTex) $ putStrLn $ "Could not initialize "++ file return mTex loadTexture :: FilePath -> Int -> IO (Maybe TextureObject) loadTexture f u = do putStrLn $ "Loading texture "++f eDynImg <- readImage f case eDynImg of Left note -> do putStrLn $ "Could not load texture '"++f++"'.\nNote: "++note return Nothing Right img -> do tex <- newBoundTexUnit u success <- bufferDataIntoBoundTexture img unless success $ putStrLn $ " ("++f++")" return $ Just tex newBoundTexUnit :: Int -> IO TextureObject newBoundTexUnit u = do [tex] <- genObjectNames 1 texture Texture2D $= Enabled activeTexture $= TextureUnit (fromIntegral u) textureBinding Texture2D $= Just tex return tex bufferDataIntoBoundTexture :: DynamicImage -> IO Bool bufferDataIntoBoundTexture dynImg = case dynImg of (ImageRGB8 img) -> unsafeTexImage2D RGB8 RGB img (ImageRGBA8 img) -> unsafeTexImage2D RGBA8 RGBA img _ -> do putStrLn "Texture is not an expected format (expecting RGB8 or RGBA8)." return False unsafeTexImage2D :: (Storable t1, PixelBaseComponent t ~ t1) => PixelInternalFormat -> PixelFormat -> Image t -> IO Bool unsafeTexImage2D rb r (Image w h dat) = do unsafeWith dat $ \ptr -> texImage2D Texture2D NoProxy No mipmaps 0 Internal storage @ rgba8 rb (TextureSize2D (fromIntegral w) (fromIntegral h)) 0 Pixel data in unsigned bytes , rgba order (PixelData r UnsignedByte ptr) printError return True
570750be8851dac7d74a62efe96726d64f9a1c7a46e6b279d386ab3cdb06fea3
Bogdanp/racket-gui-easy
operator.rkt
#lang racket/base (require (for-syntax racket/base) syntax/parse/define "observable.rkt") (provide define/obs @ := λ:= <~ λ<~ ~>) (define-syntax-parser define/obs [(_ name:id init-expr:expr) #'(define name (let ([e init-expr]) (if (obs? e) (obs-rename e 'name) (obs e #:name 'name))))]) (define (@ v) (if (obs? v) v (obs v))) (define (:= o v) (o . <~ . (λ (_) v))) (define ((λ:= o [f values]) v) (o . := . (f v))) (define (<~ o f) (obs-update! o f)) (define (~> o f) (obs-map o f)) (define (λ<~ o f) (λ () (<~ o f)))
null
https://raw.githubusercontent.com/Bogdanp/racket-gui-easy/50e187f84a8c163e00caca337152e28a67979fcf/gui-easy-lib/gui/easy/operator.rkt
racket
#lang racket/base (require (for-syntax racket/base) syntax/parse/define "observable.rkt") (provide define/obs @ := λ:= <~ λ<~ ~>) (define-syntax-parser define/obs [(_ name:id init-expr:expr) #'(define name (let ([e init-expr]) (if (obs? e) (obs-rename e 'name) (obs e #:name 'name))))]) (define (@ v) (if (obs? v) v (obs v))) (define (:= o v) (o . <~ . (λ (_) v))) (define ((λ:= o [f values]) v) (o . := . (f v))) (define (<~ o f) (obs-update! o f)) (define (~> o f) (obs-map o f)) (define (λ<~ o f) (λ () (<~ o f)))
15ffcf1176892a14fa32147886070e8691455860e8215b68b0b0368d763a2c2a
typeclasses/dsv
AttoView.hs
module DSV.AttoView ( attoByteStringView ) where import DSV.AttoParser import DSV.ByteString import DSV.Validation import DSV.ViewType attoparsec import qualified Data.Attoparsec.ByteString as A attoByteStringView :: e -> AttoParser a -> View e ByteString a attoByteStringView e p = View $ \bs -> case A.parseOnly (p <* A.endOfInput) bs of Left _ -> Failure e Right x -> Success x
null
https://raw.githubusercontent.com/typeclasses/dsv/ae4eb823e27e4c569c4f9b097441985cf865fbab/dsv/library/DSV/AttoView.hs
haskell
module DSV.AttoView ( attoByteStringView ) where import DSV.AttoParser import DSV.ByteString import DSV.Validation import DSV.ViewType attoparsec import qualified Data.Attoparsec.ByteString as A attoByteStringView :: e -> AttoParser a -> View e ByteString a attoByteStringView e p = View $ \bs -> case A.parseOnly (p <* A.endOfInput) bs of Left _ -> Failure e Right x -> Success x
f94b56f8cc52c4dd4d5d51be5fb07838a542dda58df429503b661fb9277d6dde
galdor/tungsten
binary.lisp
(in-package :core) ;;; It would be nice to implement floating point decoding and encoding the right way . But the right way is very tricky , so we let the FFI layer ( and ;;; therefore the CPU) do all the work. Another advantage is that we let the implementation handle special values such as NaN or infinity ; meaning that binary coding and FFI layer will be consistent . ;;; ;;; We cannot depend on the ffi system because it would cause a circular ;;; dependency, but code duplication is minimal, and it is not as if there was dozens of implementations to support . (define-condition unknown-binary-type (error) ((type :initarg :type)) (:report (lambda (condition stream) (with-slots (type) condition (format stream "Unknown binary type ~S." type))))) (defmacro define-binref-integer-functions (type-size signed-p endianness) (let* ((nb-octets type-size) (nb-bits (* nb-octets 8)) (suffix (format nil "~:[U~;~]INT~D~@[~A~]" signed-p nb-bits (case endianness (:big-endian "BE") (:little-endian "LE")))) (read-function (intern (concatenate 'string "BINREF-READ/" suffix))) (write-function (intern (concatenate 'string "BINREF-WRITE/" suffix)))) `(progn (declaim (ftype (function (octet-vector (integer 0)) (,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits)) ,read-function) (inline ,read-function)) (defun ,read-function (octets offset) (declare (type octet-vector octets) (type (integer 0) offset)) (let ((value 0)) ,@(let (forms) (dotimes (i nb-octets (nreverse forms)) (push `(setf (ldb (byte 8 ,(if (eq endianness :big-endian) (* (- nb-octets i 1) 8) (* i 8))) value) (aref octets (+ offset ,i))) forms))) ,(if signed-p `(if (logbitp ,(1- nb-bits) value) (- value ,(ash 1 nb-bits)) value) 'value))) (declaim (ftype (function ((,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits) octet-vector (integer 0))) ,write-function) (inline ,write-function)) (defun ,write-function (value octets offset) (declare (type (,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits) value) (type octet-vector octets) (type (integer 0) offset)) (let ((unsigned-value ,(if signed-p `(if (< value 0) (+ value ,(ash 1 nb-bits)) value) 'value))) ,@(let (forms) (dotimes (i nb-octets (nreverse forms)) (push `(setf (aref octets (+ offset ,i)) (ldb (byte 8 ,(if (eq endianness :big-endian) (* (- nb-octets i 1) 8) (* i 8))) unsigned-value)) forms))) ,(when signed-p `(when (< value 0) (setf (ldb (byte 1 7) (aref octets ,(if (eq endianness :big-endian) `offset `(+ offset ,(1- nb-octets))))) 1))) value))))) (defmacro define-binref-float-functions (type type-size endianness) (let* ((nb-octets type-size) (nb-bits (* nb-octets 8)) (suffix (format nil "FLOAT~D~A" nb-bits (case endianness (:big-endian "BE") (:little-endian "LE")))) (read-function (intern (concatenate 'string "BINREF-READ/" suffix))) (write-function (intern (concatenate 'string "BINREF-WRITE/" suffix)))) `(progn (declaim (ftype (function (octet-vector (integer 0)) ,type) ,read-function) (inline ,read-function)) (defun ,read-function (octets offset) (declare (type octet-vector octets) (type (integer 0) offset)) ;; We have to copy the octet vector because we may have to write it ;; to swap and it can be read-only (e.g. #(1 2 3 4)). (let ((octets (subseq octets offset (+ offset ,type-size)))) (unless (eq *endianness* ,endianness) (dotimes (i ,(/ type-size 2)) (rotatef (aref octets (+ offset i)) (aref octets (+ offset (- ,type-size i 1)))))) (read-binary-float octets offset ,type-size))) (declaim (ftype (function (,type octet-vector (integer 0))) ,write-function) (inline ,write-function)) (defun ,write-function (value octets offset) (declare (type ,type value) (type octet-vector octets) (type (integer 0) offset)) (write-binary-float value octets offset ,type-size) (unless (eq *endianness* ,endianness) (dotimes (i ,(/ type-size 2)) (rotatef (aref octets (+ offset i)) (aref octets (+ offset (- ,type-size i 1)))))) value)))) (declaim (inline read-binary-float)) (defun read-binary-float (octets offset size) (declare (type octet-vector octets) (type (integer 0) offset) (type (member 4 8) size)) #+sbcl (sb-sys:with-pinned-objects (octets) (let ((%octets (sb-sys:vector-sap octets))) (ecase size (4 (sb-sys:sap-ref-single %octets offset)) (8 (sb-sys:sap-ref-double %octets offset))))) #+ccl (ccl:with-pointer-to-ivector (%octets octets) (ecase size (4 (ccl::%get-single-float %octets offset)) (8 (ccl::%get-double-float %octets offset)))) #-(or sbcl ccl) (unsupported-feature "binary float reading")) (declaim (inline write-binary-float)) (defun write-binary-float (value octets offset size) (declare (type float value) (type octet-vector octets) (type (integer 0) offset) (type (member 4 8) size)) #+sbcl (sb-sys:with-pinned-objects (octets) (let ((%octets (sb-sys:vector-sap octets))) (ecase size (4 (setf (sb-sys:sap-ref-single %octets offset) value)) (8 (setf (sb-sys:sap-ref-double %octets offset) value))))) #+ccl (ccl:with-pointer-to-ivector (%octets octets) (ecase size (4 (ccl::%set-single-float %octets offset value)) (8 (ccl::%set-double-float %octets offset value)))) #-(or sbcl ccl) (unsupported-feature "binary float writing")) (define-binref-integer-functions 1 t nil) (define-binref-integer-functions 1 nil nil) (define-binref-integer-functions 2 t :big-endian) (define-binref-integer-functions 2 nil :big-endian) (define-binref-integer-functions 2 t :little-endian) (define-binref-integer-functions 2 nil :little-endian) (define-binref-integer-functions 4 t :big-endian) (define-binref-integer-functions 4 nil :big-endian) (define-binref-integer-functions 4 t :little-endian) (define-binref-integer-functions 4 nil :little-endian) (define-binref-integer-functions 8 t :big-endian) (define-binref-integer-functions 8 nil :big-endian) (define-binref-integer-functions 8 t :little-endian) (define-binref-integer-functions 8 nil :little-endian) (define-binref-float-functions single-float 4 :big-endian) (define-binref-float-functions single-float 4 :little-endian) (define-binref-float-functions double-float 8 :big-endian) (define-binref-float-functions double-float 8 :little-endian) (defun binref-read-function (type) (case type (:int8 'binref-read/int8) (:uint8 'binref-read/uint8) (:int16be 'binref-read/int16be) (:int16le 'binref-read/int16le) (:uint16be 'binref-read/uint16be) (:uint16le 'binref-read/uint16le) (:int32be 'binref-read/int32be) (:int32le 'binref-read/int32le) (:uint32be 'binref-read/uint32be) (:uint32le 'binref-read/uint32le) (:int64be 'binref-read/int64be) (:int64le 'binref-read/int64le) (:uint64be 'binref-read/uint64be) (:uint64le 'binref-read/uint64le) (:float32be 'binref-read/float32be) (:float32le 'binref-read/float32le) (:float64be 'binref-read/float64be) (:float64le 'binref-read/float64le) (t (error 'unknown-binary-type :type type)))) (defun binref-write-function (type) (ecase type (:int8 'binref-write/int8) (:uint8 'binref-write/uint8) (:int16be 'binref-write/int16be) (:int16le 'binref-write/int16le) (:uint16be 'binref-write/uint16be) (:uint16le 'binref-write/uint16le) (:int32be 'binref-write/int32be) (:int32le 'binref-write/int32le) (:uint32be 'binref-write/uint32be) (:uint32le 'binref-write/uint32le) (:int64be 'binref-write/int64be) (:int64le 'binref-write/int64le) (:uint64be 'binref-write/uint64be) (:uint64le 'binref-write/uint64le) (:float32be 'binref-write/float32be) (:float32le 'binref-write/float32le) (:float64be 'binref-write/float64be) (:float64le 'binref-write/float64le) (t (error 'unknown-binary-type :type type)))) (defun binref-type-size (type) (ecase type ((:int8 :uint8) 1) ((:int16be :int16le :uint16be :uint16le) 2) ((:int32be :int32le :uint32be :uint32le :float32be :float32le) 4) ((:int64be :int64le :uint64be :uint64le :float64be :float64le) 8) (t (error 'unknown-binary-type :type type)))) (defun binref (type octets &optional (offset 0)) (declare (type keyword type) (type octet-vector octets)) (funcall (binref-read-function type) octets offset)) (define-compiler-macro binref (&whole form type octets &optional (offset 0)) (if (constantp type) (let ((octets-var (gensym "OCTETS-")) (offset-var (gensym "OFFSET-"))) `(let* ((,octets-var ,octets) (,offset-var ,offset)) (,(binref-read-function type) ,octets-var ,offset-var))) form)) (defsetf binref (type octets &optional (offset 0)) (value) (if (constantp type) (let ((octets-var (gensym "OCTETS-")) (offset-var (gensym "OFFSET-"))) `(let* ((,octets-var ,octets) (,offset-var ,offset)) (,(binref-write-function type) ,value ,octets-var ,offset-var))) `(funcall (binref-write-function ,type) ,value ,octets ,offset)))
null
https://raw.githubusercontent.com/galdor/tungsten/5d6e71fb89af32ab3994c5b2daf8b902a5447447/tungsten-core/src/binary.lisp
lisp
It would be nice to implement floating point decoding and encoding the therefore the CPU) do all the work. Another advantage is that we let the meaning that We cannot depend on the ffi system because it would cause a circular dependency, but code duplication is minimal, and it is not as if there was We have to copy the octet vector because we may have to write it to swap and it can be read-only (e.g. #(1 2 3 4)).
(in-package :core) right way . But the right way is very tricky , so we let the FFI layer ( and binary coding and FFI layer will be consistent . dozens of implementations to support . (define-condition unknown-binary-type (error) ((type :initarg :type)) (:report (lambda (condition stream) (with-slots (type) condition (format stream "Unknown binary type ~S." type))))) (defmacro define-binref-integer-functions (type-size signed-p endianness) (let* ((nb-octets type-size) (nb-bits (* nb-octets 8)) (suffix (format nil "~:[U~;~]INT~D~@[~A~]" signed-p nb-bits (case endianness (:big-endian "BE") (:little-endian "LE")))) (read-function (intern (concatenate 'string "BINREF-READ/" suffix))) (write-function (intern (concatenate 'string "BINREF-WRITE/" suffix)))) `(progn (declaim (ftype (function (octet-vector (integer 0)) (,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits)) ,read-function) (inline ,read-function)) (defun ,read-function (octets offset) (declare (type octet-vector octets) (type (integer 0) offset)) (let ((value 0)) ,@(let (forms) (dotimes (i nb-octets (nreverse forms)) (push `(setf (ldb (byte 8 ,(if (eq endianness :big-endian) (* (- nb-octets i 1) 8) (* i 8))) value) (aref octets (+ offset ,i))) forms))) ,(if signed-p `(if (logbitp ,(1- nb-bits) value) (- value ,(ash 1 nb-bits)) value) 'value))) (declaim (ftype (function ((,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits) octet-vector (integer 0))) ,write-function) (inline ,write-function)) (defun ,write-function (value octets offset) (declare (type (,(if signed-p 'signed-byte 'unsigned-byte) ,nb-bits) value) (type octet-vector octets) (type (integer 0) offset)) (let ((unsigned-value ,(if signed-p `(if (< value 0) (+ value ,(ash 1 nb-bits)) value) 'value))) ,@(let (forms) (dotimes (i nb-octets (nreverse forms)) (push `(setf (aref octets (+ offset ,i)) (ldb (byte 8 ,(if (eq endianness :big-endian) (* (- nb-octets i 1) 8) (* i 8))) unsigned-value)) forms))) ,(when signed-p `(when (< value 0) (setf (ldb (byte 1 7) (aref octets ,(if (eq endianness :big-endian) `offset `(+ offset ,(1- nb-octets))))) 1))) value))))) (defmacro define-binref-float-functions (type type-size endianness) (let* ((nb-octets type-size) (nb-bits (* nb-octets 8)) (suffix (format nil "FLOAT~D~A" nb-bits (case endianness (:big-endian "BE") (:little-endian "LE")))) (read-function (intern (concatenate 'string "BINREF-READ/" suffix))) (write-function (intern (concatenate 'string "BINREF-WRITE/" suffix)))) `(progn (declaim (ftype (function (octet-vector (integer 0)) ,type) ,read-function) (inline ,read-function)) (defun ,read-function (octets offset) (declare (type octet-vector octets) (type (integer 0) offset)) (let ((octets (subseq octets offset (+ offset ,type-size)))) (unless (eq *endianness* ,endianness) (dotimes (i ,(/ type-size 2)) (rotatef (aref octets (+ offset i)) (aref octets (+ offset (- ,type-size i 1)))))) (read-binary-float octets offset ,type-size))) (declaim (ftype (function (,type octet-vector (integer 0))) ,write-function) (inline ,write-function)) (defun ,write-function (value octets offset) (declare (type ,type value) (type octet-vector octets) (type (integer 0) offset)) (write-binary-float value octets offset ,type-size) (unless (eq *endianness* ,endianness) (dotimes (i ,(/ type-size 2)) (rotatef (aref octets (+ offset i)) (aref octets (+ offset (- ,type-size i 1)))))) value)))) (declaim (inline read-binary-float)) (defun read-binary-float (octets offset size) (declare (type octet-vector octets) (type (integer 0) offset) (type (member 4 8) size)) #+sbcl (sb-sys:with-pinned-objects (octets) (let ((%octets (sb-sys:vector-sap octets))) (ecase size (4 (sb-sys:sap-ref-single %octets offset)) (8 (sb-sys:sap-ref-double %octets offset))))) #+ccl (ccl:with-pointer-to-ivector (%octets octets) (ecase size (4 (ccl::%get-single-float %octets offset)) (8 (ccl::%get-double-float %octets offset)))) #-(or sbcl ccl) (unsupported-feature "binary float reading")) (declaim (inline write-binary-float)) (defun write-binary-float (value octets offset size) (declare (type float value) (type octet-vector octets) (type (integer 0) offset) (type (member 4 8) size)) #+sbcl (sb-sys:with-pinned-objects (octets) (let ((%octets (sb-sys:vector-sap octets))) (ecase size (4 (setf (sb-sys:sap-ref-single %octets offset) value)) (8 (setf (sb-sys:sap-ref-double %octets offset) value))))) #+ccl (ccl:with-pointer-to-ivector (%octets octets) (ecase size (4 (ccl::%set-single-float %octets offset value)) (8 (ccl::%set-double-float %octets offset value)))) #-(or sbcl ccl) (unsupported-feature "binary float writing")) (define-binref-integer-functions 1 t nil) (define-binref-integer-functions 1 nil nil) (define-binref-integer-functions 2 t :big-endian) (define-binref-integer-functions 2 nil :big-endian) (define-binref-integer-functions 2 t :little-endian) (define-binref-integer-functions 2 nil :little-endian) (define-binref-integer-functions 4 t :big-endian) (define-binref-integer-functions 4 nil :big-endian) (define-binref-integer-functions 4 t :little-endian) (define-binref-integer-functions 4 nil :little-endian) (define-binref-integer-functions 8 t :big-endian) (define-binref-integer-functions 8 nil :big-endian) (define-binref-integer-functions 8 t :little-endian) (define-binref-integer-functions 8 nil :little-endian) (define-binref-float-functions single-float 4 :big-endian) (define-binref-float-functions single-float 4 :little-endian) (define-binref-float-functions double-float 8 :big-endian) (define-binref-float-functions double-float 8 :little-endian) (defun binref-read-function (type) (case type (:int8 'binref-read/int8) (:uint8 'binref-read/uint8) (:int16be 'binref-read/int16be) (:int16le 'binref-read/int16le) (:uint16be 'binref-read/uint16be) (:uint16le 'binref-read/uint16le) (:int32be 'binref-read/int32be) (:int32le 'binref-read/int32le) (:uint32be 'binref-read/uint32be) (:uint32le 'binref-read/uint32le) (:int64be 'binref-read/int64be) (:int64le 'binref-read/int64le) (:uint64be 'binref-read/uint64be) (:uint64le 'binref-read/uint64le) (:float32be 'binref-read/float32be) (:float32le 'binref-read/float32le) (:float64be 'binref-read/float64be) (:float64le 'binref-read/float64le) (t (error 'unknown-binary-type :type type)))) (defun binref-write-function (type) (ecase type (:int8 'binref-write/int8) (:uint8 'binref-write/uint8) (:int16be 'binref-write/int16be) (:int16le 'binref-write/int16le) (:uint16be 'binref-write/uint16be) (:uint16le 'binref-write/uint16le) (:int32be 'binref-write/int32be) (:int32le 'binref-write/int32le) (:uint32be 'binref-write/uint32be) (:uint32le 'binref-write/uint32le) (:int64be 'binref-write/int64be) (:int64le 'binref-write/int64le) (:uint64be 'binref-write/uint64be) (:uint64le 'binref-write/uint64le) (:float32be 'binref-write/float32be) (:float32le 'binref-write/float32le) (:float64be 'binref-write/float64be) (:float64le 'binref-write/float64le) (t (error 'unknown-binary-type :type type)))) (defun binref-type-size (type) (ecase type ((:int8 :uint8) 1) ((:int16be :int16le :uint16be :uint16le) 2) ((:int32be :int32le :uint32be :uint32le :float32be :float32le) 4) ((:int64be :int64le :uint64be :uint64le :float64be :float64le) 8) (t (error 'unknown-binary-type :type type)))) (defun binref (type octets &optional (offset 0)) (declare (type keyword type) (type octet-vector octets)) (funcall (binref-read-function type) octets offset)) (define-compiler-macro binref (&whole form type octets &optional (offset 0)) (if (constantp type) (let ((octets-var (gensym "OCTETS-")) (offset-var (gensym "OFFSET-"))) `(let* ((,octets-var ,octets) (,offset-var ,offset)) (,(binref-read-function type) ,octets-var ,offset-var))) form)) (defsetf binref (type octets &optional (offset 0)) (value) (if (constantp type) (let ((octets-var (gensym "OCTETS-")) (offset-var (gensym "OFFSET-"))) `(let* ((,octets-var ,octets) (,offset-var ,offset)) (,(binref-write-function type) ,value ,octets-var ,offset-var))) `(funcall (binref-write-function ,type) ,value ,octets ,offset)))
3e62a33850ae7b3ff8f1c3e28ce577011bf405ea06aa549d18d9e31f773f869e
BillHallahan/G2
Trivial.hs
module Trivial where {-@ f :: Int -> Int @-} f :: Int -> Int f 0 = 0 f _ = die 0 {-@ die :: {x:Int | false} -> a @-} die :: Int -> a die x = error "die"
null
https://raw.githubusercontent.com/BillHallahan/G2/21c648d38c380041a9036d0e375ec1d54120f6b4/tests_lh/Liquid/Trivial.hs
haskell
@ f :: Int -> Int @ @ die :: {x:Int | false} -> a @
module Trivial where f :: Int -> Int f 0 = 0 f _ = die 0 die :: Int -> a die x = error "die"
ba3d0fea5e99d1357455daedd63e4b8ca0bc1ef1f17c247918b735ca996f40fa
TrustInSoft/tis-kernel
pdgIndex.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 , version 2.1 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** *) open Cil_types exception AddError exception CallStatement exception Not_equal let is_call_stmt stmt = match stmt.skind with Instr (Call _) -> true | _ -> false module Signature = struct type in_key = InCtrl | InNum of int | InImpl of Locations.Zone.t type out_key = OutRet | OutLoc of Locations.Zone.t type key = In of in_key | Out of out_key type 'info t = { in_ctrl : 'info option ; in_params : (int * 'info) list ; (** implicit inputs : Maybe we should use [Lmap_bitwise.Make_bitwise] ? but that would make things a lot more complicated... :-? *) in_implicits : (Locations.Zone.t * 'info) list ; out_ret : 'info option ; outputs : (Locations.Zone.t * 'info) list } module Str_descr = struct open Structural_descr let in_key = t_sum [| [| p_int |]; [| Locations.Zone.packed_descr |] |] let out_key = t_sum [| [| Locations.Zone.packed_descr |] |] let key = t_sum [| [| pack in_key |]; [| pack out_key |] |] let t d_info = t_record [| pack (t_option d_info); pack (t_list (t_tuple [| p_int; pack d_info |])); pack (t_list (t_tuple [| Locations.Zone.packed_descr; pack d_info |])); pack (t_option d_info); pack (t_list (t_tuple [| Locations.Zone.packed_descr; pack d_info |])); |] end let empty = { in_ctrl = None ; in_params = [] ; in_implicits = [] ; out_ret = None; outputs = [] } let in_key n = In (InNum n) let in_impl_key loc = In (InImpl loc) let in_top_key = in_impl_key (Locations.Zone.top) let in_ctrl_key = In InCtrl let out_ret_key = Out OutRet let out_key out = Out (OutLoc out) let mk_undef_in_key loc = InImpl loc let copy sgn = sgn (** InCtrl < InNum < InImpl *) let cmp_in_key k1 k2 = match k1, k2 with | (InImpl z1), (InImpl z2) when Locations.Zone.equal z1 z2 -> 0 | (InImpl _), (InImpl _) -> raise Not_equal | (InImpl _), _ -> 1 | _, (InImpl _) -> -1 | InNum n1, InNum n2 -> n1 - n2 | (InNum _), _ -> 1 | _, (InNum _) -> -1 | InCtrl, InCtrl -> 0 * OutRet < OutLoc let cmp_out_key k1 k2 = match k1, k2 with | OutRet, OutRet -> 0 | OutRet, (OutLoc _) -> -1 | (OutLoc _), OutRet -> 1 | OutLoc l1, OutLoc l2 when Locations.Zone.equal l1 l2 -> 0 | OutLoc _, OutLoc _ -> raise Not_equal let equal_out_key k1 k2 = try (0 = cmp_out_key k1 k2) with Not_equal -> false (** add a mapping between [num] and [info] in [lst]. * if we already have something for [num], use function [merge] *) let add_in_list lst num info merge = let new_e = (num, info) in let rec add_to_l l = match l with [] -> [new_e] | (ne, old_e) as e :: tl -> if ne = num then let e = merge old_e info in (num, e)::tl else if ne < num then e :: (add_to_l tl) else new_e :: l in add_to_l lst let add_loc l_loc loc info merge = let rec add lst = match lst with | [] -> [(loc, info)] | (l, e)::tl -> if Locations.Zone.equal l loc then let new_e = merge e info in (loc, new_e)::tl else begin if ( Locations.Zone.intersects l loc ) then begin " [ pdg ] implicit inputs intersect : % a and % a\n " Locations.Zone.pretty l Locations.Zone.pretty loc ; assert false end ; if (Locations.Zone.intersects l loc) then begin Format.printf "[pdg] implicit inputs intersect : %a and %a\n" Locations.Zone.pretty l Locations.Zone.pretty loc; assert false end; *) (l, e)::(add tl) end in add l_loc let add_replace replace _old_e new_e = if replace then new_e else raise AddError let add_input sgn n info ~replace = { sgn with in_params = add_in_list sgn.in_params n info (add_replace replace) } let add_impl_input sgn loc info ~replace = { sgn with in_implicits = add_loc sgn.in_implicits loc info (add_replace replace) } let add_output sgn loc info ~replace = { sgn with outputs = add_loc sgn.outputs loc info (add_replace replace) } let add_in_ctrl sgn info ~replace = let new_info = match sgn.in_ctrl with | None -> info | Some old -> add_replace replace old info in { sgn with in_ctrl = Some new_info } let add_out_ret sgn info ~replace = let new_info = match sgn.out_ret with | None -> info | Some old -> add_replace replace old info in { sgn with out_ret = Some new_info } let add_info sgn key info ~replace = match key with | In InCtrl -> add_in_ctrl sgn info ~replace | In (InNum n) -> add_input sgn n info ~replace | In (InImpl loc) -> add_impl_input sgn loc info ~replace | Out OutRet -> add_out_ret sgn info ~replace | Out (OutLoc k) -> add_output sgn k info ~replace let find_input sgn n = try no input 0 : use List.assoc n sgn.in_params with Not_found -> raise Not_found let find_output sgn out_key = let rec find l = match l with | [] -> raise Not_found | (loc, e)::tl -> if Locations.Zone.equal out_key loc then e else find tl in find sgn.outputs let find_out_ret sgn = match sgn.out_ret with | Some i -> i | None -> raise Not_found let find_in_ctrl sgn = match sgn.in_ctrl with | Some i -> i | None -> raise Not_found * try to find an exact match with loc . * we should n't try to find a zone that we do n't have ... * we shouldn't try to find a zone that we don't have... *) let find_implicit_input sgn loc = let rec find l = match l with | [] -> raise Not_found | (in_loc, e)::tl -> if Locations.Zone.equal in_loc loc then e else find tl in find sgn.in_implicits let find_in_top sgn = find_implicit_input sgn Locations.Zone.top let find_in_info sgn in_key = match in_key with | InCtrl -> find_in_ctrl sgn | (InNum n) -> find_input sgn n | (InImpl loc) -> find_implicit_input sgn loc let find_out_info sgn out_key = match out_key with | OutRet -> find_out_ret sgn | (OutLoc k) -> find_output sgn k let find_info sgn key = match key with | In in_key -> find_in_info sgn in_key | Out out_key -> find_out_info sgn out_key let fold_outputs f acc sgn = List.fold_left f acc sgn.outputs let fold_all_outputs f acc sgn = let acc = match sgn.out_ret with | None -> acc | Some info -> f acc (OutRet, info) in List.fold_left (fun acc (k, i) -> f acc ((OutLoc k), i)) acc sgn.outputs let fold_num_inputs f acc sgn = List.fold_left f acc sgn.in_params let fold_impl_inputs f acc sgn = List.fold_left f acc sgn.in_implicits let fold_matching_impl_inputs loc f acc sgn = let test acc (in_loc, info) = if (Locations.Zone.intersects in_loc loc) then f acc (in_loc, info) else acc in List.fold_left test acc sgn.in_implicits let fold_all_inputs f acc sgn = let acc = match sgn.in_ctrl with | None -> acc | Some info -> f acc (InCtrl, info) in let acc = fold_num_inputs (fun acc (n, info) -> f acc ((InNum n), info)) acc sgn in fold_impl_inputs (fun acc (l, info) -> f acc ((InImpl l), info)) acc sgn let fold f acc sgn = let acc = fold_all_inputs (fun acc (n, info) -> f acc (In n, info)) acc sgn in fold_all_outputs (fun acc (n, info) -> f acc (Out n, info)) acc sgn let iter f sgn = fold (fun () v -> f v) () sgn let merge sgn1 sgn2 merge_info = let merge_elem lst (k, info) = add_in_list lst k info merge_info in let inputs = fold_num_inputs merge_elem sgn1.in_params sgn2 in let outputs = fold_outputs merge_elem sgn1.outputs sgn2 in let in_ctrl = match sgn1.in_ctrl, sgn2.in_ctrl with | None, _ -> sgn2.in_ctrl | _, None -> sgn1.in_ctrl | Some i1, Some i2 -> Some (merge_info i1 i2) in assert (sgn1.in_implicits = [] && sgn2.in_implicits = []); let out_ret = match sgn1.out_ret, sgn2.out_ret with | None, _ -> sgn2.out_ret | _, None -> sgn1.out_ret | Some i1, Some i2 -> Some (merge_info i1 i2) in { in_ctrl = in_ctrl; in_params = inputs ; in_implicits = [] ; out_ret = out_ret ; outputs = outputs } let pretty_in_key fmt key = match key with | (InNum n) -> Format.fprintf fmt "In%d" n | InCtrl -> Format.fprintf fmt "InCtrl" | InImpl loc -> Format.fprintf fmt "@[<hv 1>In(%a)@]" Locations.Zone.pretty loc let pretty_out_key fmt key = match key with | OutRet -> Format.fprintf fmt "OutRet" | OutLoc loc -> Format.fprintf fmt "@[<hv 1>Out(%a)@]" Locations.Zone.pretty loc let pretty_key fmt key = match key with | In in_key -> pretty_in_key fmt in_key | Out key -> pretty_out_key fmt key let pretty pp fmt sgn = Pretty_utils.pp_iter ~pre:"@[<v>" ~suf:"@]" ~sep:"@," iter (fun fmt (k,i) -> Format.fprintf fmt "@[<hv>(%a:@ %a)@]" pretty_key k pp i) fmt sgn end module Key = struct type key = | SigKey of Signature.key (** input/output nodes of the function *) | VarDecl of Cil_types.varinfo (** local, parameter or global variable definition *) | Stmt of Cil_types.stmt (** simple statement (not call) excluding its label (stmt.id) *) | CallStmt of Cil_types.stmt (** call statement *) | Label of stmt * Cil_types.label (** Labels are considered as function elements by themselves. *) | SigCallKey of Cil_types.stmt * Signature.key (** Key for an element of a call (input or output). * The call is identified by the statement. *) let entry_point = SigKey (Signature.in_ctrl_key) let top_input = SigKey (Signature.in_top_key) let param_key num_in = SigKey (Signature.in_key num_in) let implicit_in_key loc = SigKey (Signature.in_impl_key loc) let output_key = SigKey (Signature.out_ret_key) (** this is for the nodes inside undefined functions *) let out_from_key loc = SigKey (Signature.out_key loc) let decl_var_key var = VarDecl var let label_key label_stmt label : key = Label (label_stmt,label) let call_key call = CallStmt call let stmt_key stmt = if is_call_stmt stmt then call_key stmt else Stmt stmt let call_input_key call n = SigCallKey (call, (Signature.in_key n)) let call_outret_key call = SigCallKey (call, (Signature.out_ret_key)) let call_output_key call loc = SigCallKey (call, (Signature.out_key loc)) let call_ctrl_key call = SigCallKey (call, (Signature.in_ctrl_key)) let call_topin_key call = SigCallKey (call, (Signature.in_top_key)) let call_from_id call_id = call_id let stmt key = match key with | SigCallKey (call, _) -> Some call | CallStmt call -> Some call | Stmt stmt -> Some stmt | Label (stmt, _) -> Some stmt | _ -> None (* see PrintPdg.pretty_key : can't be here because it uses Db... *) let pretty_node fmt k = let print_stmt fmt s = match s.skind with | Switch (exp,_,_,_) | If (exp,_,_,_) -> Printer.pp_exp fmt exp | Loop _ -> Format.pp_print_string fmt "while(1)" | Block _ -> Format.pp_print_string fmt "block" | Goto _ | Break _ | Continue _ | Return _ | Instr _ | Throw _ -> Format.fprintf fmt "@[<h 1>%a@]" (Printer.without_annot Printer.pp_stmt) s | UnspecifiedSequence _ -> Format.pp_print_string fmt "unspecified sequence" | TryExcept _ | TryFinally _ | TryCatch _ -> Format.pp_print_string fmt "ERROR" in match k with | CallStmt call -> let call = call_from_id call in Format.fprintf fmt "Call%d : %a" call.sid print_stmt call | Stmt s -> print_stmt fmt s | Label (_,l) -> Printer.pp_label fmt l | VarDecl v -> Format.fprintf fmt "VarDecl : %a" Printer.pp_varinfo v | SigKey k -> Signature.pretty_key fmt k | SigCallKey (call, sgn) -> let call = call_from_id call in Format.fprintf fmt "Call%d-%a : %a" call.sid Signature.pretty_key sgn print_stmt call include Datatype.Make (struct include Datatype.Serializable_undefined type t = key let name = "PdgIndex.Key" open Cil_datatype let reprs = List.fold_left (fun acc v -> List.fold_left (fun acc s -> Stmt s :: acc) (VarDecl v :: acc) Stmt.reprs) [] Varinfo.reprs open Structural_descr let structural_descr = let p_key = pack Signature.Str_descr.key in t_sum [| [| p_key |]; [| Varinfo.packed_descr |]; [| Stmt.packed_descr |]; [| Cil_datatype.Stmt.packed_descr |]; [| Cil_datatype.Stmt.packed_descr; Label.packed_descr |]; [| Cil_datatype.Stmt.packed_descr; p_key |]; |] let rehash = Datatype.identity let pretty = pretty_node let mem_project = Datatype.never_any_project end) end [ Key ] restricted to [ Stmt ] , [ VarDecl ] and [ Label ] constructors . Hash tables are built upon this type , and we currently have no full hash / equality function for [ Key.t ] . are built upon this type, and we currently have no full hash/equality function for [Key.t]. *) module RKey = struct include Key let hash = function | Key.VarDecl v -> 17 * Cil_datatype.Varinfo.hash v | Key.Stmt s -> 29 * Cil_datatype.Stmt.hash s | Key.Label (s, _l) -> Intentionnaly buggy : ignore the label and consider only the statement . There seems to be bug in the pdg , only one ' case : ' per statement is present . This avoids removing the other ' case ' clauses ( see tests / slicing / switch.c There seems to be bug in the pdg, only one 'case :' per statement is present. This avoids removing the other 'case' clauses (see tests/slicing/switch.c *) 7 * l | _ -> assert false let equal k1 k2 = match k1, k2 with | Key.VarDecl v1, Key.VarDecl v2 -> Cil_datatype.Varinfo.equal v1 v2 | Key.Stmt s1, Key.Stmt s2 -> Cil_datatype.Stmt.equal s1 s2 | Key.Label (s1, _l1), Key.Label (s2, _l2) -> (* See [hash] above *) Cil_datatype.Stmt.equal s1 s2 (* && Cil_datatype.Label.equal l1 l2 *) | _ -> false end module H = struct include Hashtbl.Make(RKey) let structural_descr = Structural_descr.t_hashtbl_unchanged_hashs (Descr.str RKey.descr) end module FctIndex = struct type ('node_info, 'call_info) t = { (** inputs and ouputs of the function *) mutable sgn : 'node_info Signature.t ; (** calls signatures *) mutable calls : (Cil_types.stmt * ('call_info option * 'node_info Signature.t)) list ; (** everything else *) other : 'node_info H.t } open Structural_descr let t_descr ~ni:d_ninfo ~ci:d_cinfo = t_record [| pack (Signature.Str_descr.t d_ninfo); pack (t_list (t_tuple [| Cil_datatype.Stmt.packed_descr; pack (t_tuple [| pack (t_option d_cinfo); pack (Signature.Str_descr.t d_ninfo); |]) |])); pack (H.structural_descr d_ninfo); |] let sgn idx = idx.sgn let create nb = { sgn = Signature.empty; calls = []; other = H.create nb } let copy idx = { sgn = Signature.copy idx.sgn; calls = idx.calls; other = H.copy idx.other } let merge_info_calls calls1 calls2 merge_a merge_b = let merge_info (b1, sgn1) (b2, sgn2) = let b = match b1, b2 with None, _ -> b2 | _, None -> b1 | Some b1, Some b2 -> Some (merge_b b1 b2) in let sgn = Signature.merge sgn1 sgn2 merge_a in (b, sgn) in let rec merge l1 l2 = match l1, l2 with | [], _ -> l2 | _, [] -> l1 | ((call1, info1) as c1) :: tl1, ((call2, info2) as c2) :: tl2 -> let id1 = call1.sid in let id2 = call2.sid in if id1 = id2 then let info = merge_info info1 info2 in (call1, info) :: (merge tl1 tl2) else if id1 < id2 then c1 :: (merge tl1 l2) else c2 :: (merge l1 tl2) in merge calls1 calls2 let merge idx1 idx2 merge_a merge_b = let sgn = Signature.merge idx1.sgn idx2.sgn merge_a in let table = H.copy idx1.other in let add k a2 = let a = try let a1 = H.find table k in merge_a a1 a2 with Not_found -> a2 in H.replace table k a in H.iter add idx2.other; let calls = merge_info_calls idx1.calls idx2.calls merge_a merge_b in {sgn = sgn; calls = calls; other = table} let add_info_call idx call e ~replace = let sid = call.sid in let rec add l = match l with | [] -> [(call, (Some e, Signature.empty))] | ((call1, (_e1, sgn1)) as c1) :: tl -> let sid1 = call1.sid in if sid = sid1 then (if replace then (call, (Some e, sgn1)) :: tl else raise AddError) else if sid < sid1 then (call, (Some e, Signature.empty)) :: l else c1 :: (add tl) in idx.calls <- add idx.calls let add_info_call_key idx key = match key with | Key.CallStmt call -> add_info_call idx call | _ -> assert false let add_info_sig_call calls call k e replace = let new_sgn old = Signature.add_info old k e ~replace in let rec add l = match l with | [] -> [(call, (None, new_sgn Signature.empty))] | ((call1, (e1, sgn1)) as c1) :: tl -> let sid = call.sid in let sid1 = call1.sid in if sid = sid1 then (call, (e1, new_sgn sgn1)) :: tl else if sid < sid1 then (call, (None, new_sgn Signature.empty)) :: l else (c1 :: (add tl)) in add calls let find_call idx call = let rec find l = match l with | [] -> raise Not_found | (call1, e1) :: tl -> let sid = call.sid in let sid1 = call1.sid in if sid = sid1 then e1 else if sid < sid1 then raise Not_found else find tl in find idx.calls let find_call_key idx key = match key with | Key.CallStmt call -> find_call idx call | _ -> assert false let find_info_call idx call = let (e1, _sgn1) = find_call idx call in match e1 with Some e -> e | None -> raise Not_found let find_info_call_key idx key = match key with | Key.CallStmt call -> find_info_call idx call | _ -> assert false let find_info_sig_call idx call k = let (_e1, sgn1) = find_call idx call in Signature.find_info sgn1 k let find_all_info_sig_call idx call = let (_e1, sgn1) = find_call idx call in Signature.fold (fun l (_k,i) -> i::l) [] sgn1 let add_replace idx key e replace = let hfct = if replace then H.replace else H.add in match key with | Key.SigKey k -> idx.sgn <- Signature.add_info idx.sgn k e ~replace | Key.CallStmt _ -> raise CallStatement (* see add_info_call *) | Key.SigCallKey (call, k) -> idx.calls <- add_info_sig_call idx.calls call k e replace | Key.VarDecl _ | Key.Stmt _ | Key.Label _ -> hfct idx.other key e let add idx key e = add_replace idx key e false let add_or_replace idx key e = add_replace idx key e true let length idx = H.length idx.other let find_info idx key = match key with | Key.SigKey k -> Signature.find_info idx.sgn k | Key.CallStmt _ -> raise CallStatement (* see find_info_call *) | Key.SigCallKey (call, k) -> find_info_sig_call idx call k | Key.VarDecl _ | Key.Stmt _ | Key.Label _ -> begin try H.find idx.other key with Not_found -> raise Not_found end let find_all idx key = match key with | Key.CallStmt call -> find_all_info_sig_call idx call | _ -> let info = find_info idx key in [info] let find_label idx lab = let collect k info res = match k with | Key.Label (_,k_lab) -> if Cil_datatype.Label.equal k_lab lab then info :: res else res | _ -> res in let infos = H.fold collect idx.other [] in match infos with info :: [] -> info | [] -> raise Not_found | _ -> assert false let fold_calls f idx acc = let process acc (call, (_i, _sgn as i_sgn)) = f call i_sgn acc in List.fold_left process acc idx.calls let fold f idx acc = let acc = Signature.fold (fun acc (k, info) -> f (Key.SigKey k) info acc) acc idx.sgn in let acc = H.fold (fun k info acc -> f k info acc) idx.other acc in List.fold_left (fun acc (call, (_, sgn)) -> Signature.fold (fun acc (k, info) -> f (Key.SigCallKey (call, k)) info acc) acc sgn) acc idx.calls end (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/pdg_types/pdgIndex.ml
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ * * implicit inputs : Maybe we should use [Lmap_bitwise.Make_bitwise] ? but that would make things a lot more complicated... :-? * InCtrl < InNum < InImpl * add a mapping between [num] and [info] in [lst]. * if we already have something for [num], use function [merge] * input/output nodes of the function * local, parameter or global variable definition * simple statement (not call) excluding its label (stmt.id) * call statement * Labels are considered as function elements by themselves. * Key for an element of a call (input or output). * The call is identified by the statement. * this is for the nodes inside undefined functions see PrintPdg.pretty_key : can't be here because it uses Db... See [hash] above && Cil_datatype.Label.equal l1 l2 * inputs and ouputs of the function * calls signatures * everything else see add_info_call see find_info_call Local Variables: compile-command: "make -C ../../.." End:
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types exception AddError exception CallStatement exception Not_equal let is_call_stmt stmt = match stmt.skind with Instr (Call _) -> true | _ -> false module Signature = struct type in_key = InCtrl | InNum of int | InImpl of Locations.Zone.t type out_key = OutRet | OutLoc of Locations.Zone.t type key = In of in_key | Out of out_key type 'info t = { in_ctrl : 'info option ; in_params : (int * 'info) list ; in_implicits : (Locations.Zone.t * 'info) list ; out_ret : 'info option ; outputs : (Locations.Zone.t * 'info) list } module Str_descr = struct open Structural_descr let in_key = t_sum [| [| p_int |]; [| Locations.Zone.packed_descr |] |] let out_key = t_sum [| [| Locations.Zone.packed_descr |] |] let key = t_sum [| [| pack in_key |]; [| pack out_key |] |] let t d_info = t_record [| pack (t_option d_info); pack (t_list (t_tuple [| p_int; pack d_info |])); pack (t_list (t_tuple [| Locations.Zone.packed_descr; pack d_info |])); pack (t_option d_info); pack (t_list (t_tuple [| Locations.Zone.packed_descr; pack d_info |])); |] end let empty = { in_ctrl = None ; in_params = [] ; in_implicits = [] ; out_ret = None; outputs = [] } let in_key n = In (InNum n) let in_impl_key loc = In (InImpl loc) let in_top_key = in_impl_key (Locations.Zone.top) let in_ctrl_key = In InCtrl let out_ret_key = Out OutRet let out_key out = Out (OutLoc out) let mk_undef_in_key loc = InImpl loc let copy sgn = sgn let cmp_in_key k1 k2 = match k1, k2 with | (InImpl z1), (InImpl z2) when Locations.Zone.equal z1 z2 -> 0 | (InImpl _), (InImpl _) -> raise Not_equal | (InImpl _), _ -> 1 | _, (InImpl _) -> -1 | InNum n1, InNum n2 -> n1 - n2 | (InNum _), _ -> 1 | _, (InNum _) -> -1 | InCtrl, InCtrl -> 0 * OutRet < OutLoc let cmp_out_key k1 k2 = match k1, k2 with | OutRet, OutRet -> 0 | OutRet, (OutLoc _) -> -1 | (OutLoc _), OutRet -> 1 | OutLoc l1, OutLoc l2 when Locations.Zone.equal l1 l2 -> 0 | OutLoc _, OutLoc _ -> raise Not_equal let equal_out_key k1 k2 = try (0 = cmp_out_key k1 k2) with Not_equal -> false let add_in_list lst num info merge = let new_e = (num, info) in let rec add_to_l l = match l with [] -> [new_e] | (ne, old_e) as e :: tl -> if ne = num then let e = merge old_e info in (num, e)::tl else if ne < num then e :: (add_to_l tl) else new_e :: l in add_to_l lst let add_loc l_loc loc info merge = let rec add lst = match lst with | [] -> [(loc, info)] | (l, e)::tl -> if Locations.Zone.equal l loc then let new_e = merge e info in (loc, new_e)::tl else begin if ( Locations.Zone.intersects l loc ) then begin " [ pdg ] implicit inputs intersect : % a and % a\n " Locations.Zone.pretty l Locations.Zone.pretty loc ; assert false end ; if (Locations.Zone.intersects l loc) then begin Format.printf "[pdg] implicit inputs intersect : %a and %a\n" Locations.Zone.pretty l Locations.Zone.pretty loc; assert false end; *) (l, e)::(add tl) end in add l_loc let add_replace replace _old_e new_e = if replace then new_e else raise AddError let add_input sgn n info ~replace = { sgn with in_params = add_in_list sgn.in_params n info (add_replace replace) } let add_impl_input sgn loc info ~replace = { sgn with in_implicits = add_loc sgn.in_implicits loc info (add_replace replace) } let add_output sgn loc info ~replace = { sgn with outputs = add_loc sgn.outputs loc info (add_replace replace) } let add_in_ctrl sgn info ~replace = let new_info = match sgn.in_ctrl with | None -> info | Some old -> add_replace replace old info in { sgn with in_ctrl = Some new_info } let add_out_ret sgn info ~replace = let new_info = match sgn.out_ret with | None -> info | Some old -> add_replace replace old info in { sgn with out_ret = Some new_info } let add_info sgn key info ~replace = match key with | In InCtrl -> add_in_ctrl sgn info ~replace | In (InNum n) -> add_input sgn n info ~replace | In (InImpl loc) -> add_impl_input sgn loc info ~replace | Out OutRet -> add_out_ret sgn info ~replace | Out (OutLoc k) -> add_output sgn k info ~replace let find_input sgn n = try no input 0 : use List.assoc n sgn.in_params with Not_found -> raise Not_found let find_output sgn out_key = let rec find l = match l with | [] -> raise Not_found | (loc, e)::tl -> if Locations.Zone.equal out_key loc then e else find tl in find sgn.outputs let find_out_ret sgn = match sgn.out_ret with | Some i -> i | None -> raise Not_found let find_in_ctrl sgn = match sgn.in_ctrl with | Some i -> i | None -> raise Not_found * try to find an exact match with loc . * we should n't try to find a zone that we do n't have ... * we shouldn't try to find a zone that we don't have... *) let find_implicit_input sgn loc = let rec find l = match l with | [] -> raise Not_found | (in_loc, e)::tl -> if Locations.Zone.equal in_loc loc then e else find tl in find sgn.in_implicits let find_in_top sgn = find_implicit_input sgn Locations.Zone.top let find_in_info sgn in_key = match in_key with | InCtrl -> find_in_ctrl sgn | (InNum n) -> find_input sgn n | (InImpl loc) -> find_implicit_input sgn loc let find_out_info sgn out_key = match out_key with | OutRet -> find_out_ret sgn | (OutLoc k) -> find_output sgn k let find_info sgn key = match key with | In in_key -> find_in_info sgn in_key | Out out_key -> find_out_info sgn out_key let fold_outputs f acc sgn = List.fold_left f acc sgn.outputs let fold_all_outputs f acc sgn = let acc = match sgn.out_ret with | None -> acc | Some info -> f acc (OutRet, info) in List.fold_left (fun acc (k, i) -> f acc ((OutLoc k), i)) acc sgn.outputs let fold_num_inputs f acc sgn = List.fold_left f acc sgn.in_params let fold_impl_inputs f acc sgn = List.fold_left f acc sgn.in_implicits let fold_matching_impl_inputs loc f acc sgn = let test acc (in_loc, info) = if (Locations.Zone.intersects in_loc loc) then f acc (in_loc, info) else acc in List.fold_left test acc sgn.in_implicits let fold_all_inputs f acc sgn = let acc = match sgn.in_ctrl with | None -> acc | Some info -> f acc (InCtrl, info) in let acc = fold_num_inputs (fun acc (n, info) -> f acc ((InNum n), info)) acc sgn in fold_impl_inputs (fun acc (l, info) -> f acc ((InImpl l), info)) acc sgn let fold f acc sgn = let acc = fold_all_inputs (fun acc (n, info) -> f acc (In n, info)) acc sgn in fold_all_outputs (fun acc (n, info) -> f acc (Out n, info)) acc sgn let iter f sgn = fold (fun () v -> f v) () sgn let merge sgn1 sgn2 merge_info = let merge_elem lst (k, info) = add_in_list lst k info merge_info in let inputs = fold_num_inputs merge_elem sgn1.in_params sgn2 in let outputs = fold_outputs merge_elem sgn1.outputs sgn2 in let in_ctrl = match sgn1.in_ctrl, sgn2.in_ctrl with | None, _ -> sgn2.in_ctrl | _, None -> sgn1.in_ctrl | Some i1, Some i2 -> Some (merge_info i1 i2) in assert (sgn1.in_implicits = [] && sgn2.in_implicits = []); let out_ret = match sgn1.out_ret, sgn2.out_ret with | None, _ -> sgn2.out_ret | _, None -> sgn1.out_ret | Some i1, Some i2 -> Some (merge_info i1 i2) in { in_ctrl = in_ctrl; in_params = inputs ; in_implicits = [] ; out_ret = out_ret ; outputs = outputs } let pretty_in_key fmt key = match key with | (InNum n) -> Format.fprintf fmt "In%d" n | InCtrl -> Format.fprintf fmt "InCtrl" | InImpl loc -> Format.fprintf fmt "@[<hv 1>In(%a)@]" Locations.Zone.pretty loc let pretty_out_key fmt key = match key with | OutRet -> Format.fprintf fmt "OutRet" | OutLoc loc -> Format.fprintf fmt "@[<hv 1>Out(%a)@]" Locations.Zone.pretty loc let pretty_key fmt key = match key with | In in_key -> pretty_in_key fmt in_key | Out key -> pretty_out_key fmt key let pretty pp fmt sgn = Pretty_utils.pp_iter ~pre:"@[<v>" ~suf:"@]" ~sep:"@," iter (fun fmt (k,i) -> Format.fprintf fmt "@[<hv>(%a:@ %a)@]" pretty_key k pp i) fmt sgn end module Key = struct type key = | SigKey of Signature.key | VarDecl of Cil_types.varinfo | Stmt of Cil_types.stmt | CallStmt of Cil_types.stmt | Label of stmt * Cil_types.label | SigCallKey of Cil_types.stmt * Signature.key let entry_point = SigKey (Signature.in_ctrl_key) let top_input = SigKey (Signature.in_top_key) let param_key num_in = SigKey (Signature.in_key num_in) let implicit_in_key loc = SigKey (Signature.in_impl_key loc) let output_key = SigKey (Signature.out_ret_key) let out_from_key loc = SigKey (Signature.out_key loc) let decl_var_key var = VarDecl var let label_key label_stmt label : key = Label (label_stmt,label) let call_key call = CallStmt call let stmt_key stmt = if is_call_stmt stmt then call_key stmt else Stmt stmt let call_input_key call n = SigCallKey (call, (Signature.in_key n)) let call_outret_key call = SigCallKey (call, (Signature.out_ret_key)) let call_output_key call loc = SigCallKey (call, (Signature.out_key loc)) let call_ctrl_key call = SigCallKey (call, (Signature.in_ctrl_key)) let call_topin_key call = SigCallKey (call, (Signature.in_top_key)) let call_from_id call_id = call_id let stmt key = match key with | SigCallKey (call, _) -> Some call | CallStmt call -> Some call | Stmt stmt -> Some stmt | Label (stmt, _) -> Some stmt | _ -> None let pretty_node fmt k = let print_stmt fmt s = match s.skind with | Switch (exp,_,_,_) | If (exp,_,_,_) -> Printer.pp_exp fmt exp | Loop _ -> Format.pp_print_string fmt "while(1)" | Block _ -> Format.pp_print_string fmt "block" | Goto _ | Break _ | Continue _ | Return _ | Instr _ | Throw _ -> Format.fprintf fmt "@[<h 1>%a@]" (Printer.without_annot Printer.pp_stmt) s | UnspecifiedSequence _ -> Format.pp_print_string fmt "unspecified sequence" | TryExcept _ | TryFinally _ | TryCatch _ -> Format.pp_print_string fmt "ERROR" in match k with | CallStmt call -> let call = call_from_id call in Format.fprintf fmt "Call%d : %a" call.sid print_stmt call | Stmt s -> print_stmt fmt s | Label (_,l) -> Printer.pp_label fmt l | VarDecl v -> Format.fprintf fmt "VarDecl : %a" Printer.pp_varinfo v | SigKey k -> Signature.pretty_key fmt k | SigCallKey (call, sgn) -> let call = call_from_id call in Format.fprintf fmt "Call%d-%a : %a" call.sid Signature.pretty_key sgn print_stmt call include Datatype.Make (struct include Datatype.Serializable_undefined type t = key let name = "PdgIndex.Key" open Cil_datatype let reprs = List.fold_left (fun acc v -> List.fold_left (fun acc s -> Stmt s :: acc) (VarDecl v :: acc) Stmt.reprs) [] Varinfo.reprs open Structural_descr let structural_descr = let p_key = pack Signature.Str_descr.key in t_sum [| [| p_key |]; [| Varinfo.packed_descr |]; [| Stmt.packed_descr |]; [| Cil_datatype.Stmt.packed_descr |]; [| Cil_datatype.Stmt.packed_descr; Label.packed_descr |]; [| Cil_datatype.Stmt.packed_descr; p_key |]; |] let rehash = Datatype.identity let pretty = pretty_node let mem_project = Datatype.never_any_project end) end [ Key ] restricted to [ Stmt ] , [ VarDecl ] and [ Label ] constructors . Hash tables are built upon this type , and we currently have no full hash / equality function for [ Key.t ] . are built upon this type, and we currently have no full hash/equality function for [Key.t]. *) module RKey = struct include Key let hash = function | Key.VarDecl v -> 17 * Cil_datatype.Varinfo.hash v | Key.Stmt s -> 29 * Cil_datatype.Stmt.hash s | Key.Label (s, _l) -> Intentionnaly buggy : ignore the label and consider only the statement . There seems to be bug in the pdg , only one ' case : ' per statement is present . This avoids removing the other ' case ' clauses ( see tests / slicing / switch.c There seems to be bug in the pdg, only one 'case :' per statement is present. This avoids removing the other 'case' clauses (see tests/slicing/switch.c *) 7 * l | _ -> assert false let equal k1 k2 = match k1, k2 with | Key.VarDecl v1, Key.VarDecl v2 -> Cil_datatype.Varinfo.equal v1 v2 | Key.Stmt s1, Key.Stmt s2 -> Cil_datatype.Stmt.equal s1 s2 | Key.Label (s1, _l1), Key.Label (s2, _l2) -> | _ -> false end module H = struct include Hashtbl.Make(RKey) let structural_descr = Structural_descr.t_hashtbl_unchanged_hashs (Descr.str RKey.descr) end module FctIndex = struct type ('node_info, 'call_info) t = { mutable sgn : 'node_info Signature.t ; mutable calls : (Cil_types.stmt * ('call_info option * 'node_info Signature.t)) list ; other : 'node_info H.t } open Structural_descr let t_descr ~ni:d_ninfo ~ci:d_cinfo = t_record [| pack (Signature.Str_descr.t d_ninfo); pack (t_list (t_tuple [| Cil_datatype.Stmt.packed_descr; pack (t_tuple [| pack (t_option d_cinfo); pack (Signature.Str_descr.t d_ninfo); |]) |])); pack (H.structural_descr d_ninfo); |] let sgn idx = idx.sgn let create nb = { sgn = Signature.empty; calls = []; other = H.create nb } let copy idx = { sgn = Signature.copy idx.sgn; calls = idx.calls; other = H.copy idx.other } let merge_info_calls calls1 calls2 merge_a merge_b = let merge_info (b1, sgn1) (b2, sgn2) = let b = match b1, b2 with None, _ -> b2 | _, None -> b1 | Some b1, Some b2 -> Some (merge_b b1 b2) in let sgn = Signature.merge sgn1 sgn2 merge_a in (b, sgn) in let rec merge l1 l2 = match l1, l2 with | [], _ -> l2 | _, [] -> l1 | ((call1, info1) as c1) :: tl1, ((call2, info2) as c2) :: tl2 -> let id1 = call1.sid in let id2 = call2.sid in if id1 = id2 then let info = merge_info info1 info2 in (call1, info) :: (merge tl1 tl2) else if id1 < id2 then c1 :: (merge tl1 l2) else c2 :: (merge l1 tl2) in merge calls1 calls2 let merge idx1 idx2 merge_a merge_b = let sgn = Signature.merge idx1.sgn idx2.sgn merge_a in let table = H.copy idx1.other in let add k a2 = let a = try let a1 = H.find table k in merge_a a1 a2 with Not_found -> a2 in H.replace table k a in H.iter add idx2.other; let calls = merge_info_calls idx1.calls idx2.calls merge_a merge_b in {sgn = sgn; calls = calls; other = table} let add_info_call idx call e ~replace = let sid = call.sid in let rec add l = match l with | [] -> [(call, (Some e, Signature.empty))] | ((call1, (_e1, sgn1)) as c1) :: tl -> let sid1 = call1.sid in if sid = sid1 then (if replace then (call, (Some e, sgn1)) :: tl else raise AddError) else if sid < sid1 then (call, (Some e, Signature.empty)) :: l else c1 :: (add tl) in idx.calls <- add idx.calls let add_info_call_key idx key = match key with | Key.CallStmt call -> add_info_call idx call | _ -> assert false let add_info_sig_call calls call k e replace = let new_sgn old = Signature.add_info old k e ~replace in let rec add l = match l with | [] -> [(call, (None, new_sgn Signature.empty))] | ((call1, (e1, sgn1)) as c1) :: tl -> let sid = call.sid in let sid1 = call1.sid in if sid = sid1 then (call, (e1, new_sgn sgn1)) :: tl else if sid < sid1 then (call, (None, new_sgn Signature.empty)) :: l else (c1 :: (add tl)) in add calls let find_call idx call = let rec find l = match l with | [] -> raise Not_found | (call1, e1) :: tl -> let sid = call.sid in let sid1 = call1.sid in if sid = sid1 then e1 else if sid < sid1 then raise Not_found else find tl in find idx.calls let find_call_key idx key = match key with | Key.CallStmt call -> find_call idx call | _ -> assert false let find_info_call idx call = let (e1, _sgn1) = find_call idx call in match e1 with Some e -> e | None -> raise Not_found let find_info_call_key idx key = match key with | Key.CallStmt call -> find_info_call idx call | _ -> assert false let find_info_sig_call idx call k = let (_e1, sgn1) = find_call idx call in Signature.find_info sgn1 k let find_all_info_sig_call idx call = let (_e1, sgn1) = find_call idx call in Signature.fold (fun l (_k,i) -> i::l) [] sgn1 let add_replace idx key e replace = let hfct = if replace then H.replace else H.add in match key with | Key.SigKey k -> idx.sgn <- Signature.add_info idx.sgn k e ~replace | Key.SigCallKey (call, k) -> idx.calls <- add_info_sig_call idx.calls call k e replace | Key.VarDecl _ | Key.Stmt _ | Key.Label _ -> hfct idx.other key e let add idx key e = add_replace idx key e false let add_or_replace idx key e = add_replace idx key e true let length idx = H.length idx.other let find_info idx key = match key with | Key.SigKey k -> Signature.find_info idx.sgn k | Key.SigCallKey (call, k) -> find_info_sig_call idx call k | Key.VarDecl _ | Key.Stmt _ | Key.Label _ -> begin try H.find idx.other key with Not_found -> raise Not_found end let find_all idx key = match key with | Key.CallStmt call -> find_all_info_sig_call idx call | _ -> let info = find_info idx key in [info] let find_label idx lab = let collect k info res = match k with | Key.Label (_,k_lab) -> if Cil_datatype.Label.equal k_lab lab then info :: res else res | _ -> res in let infos = H.fold collect idx.other [] in match infos with info :: [] -> info | [] -> raise Not_found | _ -> assert false let fold_calls f idx acc = let process acc (call, (_i, _sgn as i_sgn)) = f call i_sgn acc in List.fold_left process acc idx.calls let fold f idx acc = let acc = Signature.fold (fun acc (k, info) -> f (Key.SigKey k) info acc) acc idx.sgn in let acc = H.fold (fun k info acc -> f k info acc) idx.other acc in List.fold_left (fun acc (call, (_, sgn)) -> Signature.fold (fun acc (k, info) -> f (Key.SigCallKey (call, k)) info acc) acc sgn) acc idx.calls end
346c9e1e85d676452276ac54afc0ec062e77de3a6d5f73e37903bbd0e428ffa1
lep/jhcr
Ast.hs
{-# LANGUAGE GADTs #-} # LANGUAGE StandaloneDeriving # # LANGUAGE DeriveGeneric # # LANGUAGE InstanceSigs # module Jass.Ast ( Ast (..) , Expr , Stmt , LVar , VarDef , Toplevel , Programm , Name , Type , Lit , Constant (..) , fmap, foldMap, traverse , s2i, s2r, rawcode2int , eliminateElseIfs , isGlobal, isLocal, isFunction, isOp ) where import Prelude hiding (fmap, foldMap, traverse) import Data.Composeable import qualified Data.Foldable as F import qualified Data.Functor as F import qualified Data.Traversable as T import Control.Applicative import Control.Arrow import Unsafe.Coerce import Data.Int import Data.Char import Data.Hashable import GHC.Generics import Data.Binary data Expr data Stmt data LVar data VarDef data Toplevel data Programm data Constant = Const | Normal deriving (Eq, Ord, Show, Generic) instance Binary Constant instance Hashable Constant type Name = String type Type = String type Lit = String data Ast var a where Programm :: [Ast var Toplevel] -> Ast var Programm Native :: Constant -> var -> [(Type, var)] -> Type -> Ast var Toplevel Function :: Constant -> var -> [(Type, var)] -> Type -> [Ast var Stmt] -> Ast var Toplevel Global :: Ast var VarDef -> Ast var Toplevel Typedef :: Type -> Type -> Ast var Toplevel Set :: Ast var LVar -> Ast var Expr -> Ast var Stmt Local :: Ast var VarDef -> Ast var Stmt If :: Ast var Expr -> [Ast var Stmt] -> [(Ast var Expr, [Ast var Stmt])] -> Maybe [Ast var Stmt] -> Ast var Stmt Loop :: [Ast var Stmt] -> Ast var Stmt Exitwhen :: Ast var Expr -> Ast var Stmt Return :: Maybe (Ast var Expr) -> Ast var Stmt Call :: var -> [Ast var Expr] -> Ast var a Var :: Ast var LVar -> Ast var Expr Int :: Lit -> Ast var Expr Rawcode :: Lit -> Ast var Expr Real :: Lit -> Ast var Expr Bool :: Bool -> Ast var Expr String :: Lit -> Ast var Expr Code :: var -> Ast var Expr Null :: Ast var Expr AVar :: var -> Ast var Expr -> Ast var LVar SVar :: var -> Ast var LVar ADef :: var -> Type -> Ast var VarDef SDef :: Constant -> var -> Type -> Maybe (Ast var Expr) -> Ast var VarDef deriving instance Show var => Show (Ast var a) deriving instance Eq var => Eq (Ast var a) instance Hashable var => Hashable (Ast var a) where hashWithSalt salt x = hashWithSalt salt $ hash x hash x = case x of Programm p -> hashWithSalt 1 p Native c v args ret -> hashWithSalt 2 [hash c, hash v, hash args, hash ret] Function c v args ret body -> hashWithSalt 3 [hash c, hash v, hash args, hash ret, hash body] Global vdef -> hashWithSalt 4 vdef Typedef a b -> hashWithSalt 5 [hash a, hash b] Set lvar expr -> hashWithSalt 6 [hash lvar, hash expr] Local vdef -> hashWithSalt 7 vdef If cond tb elseifs eb -> hashWithSalt 8 [hash cond, hash tb, hash elseifs, hash eb] Loop body -> hashWithSalt 9 body Exitwhen expr -> hashWithSalt 10 expr Return expr -> hashWithSalt 11 expr Call v args -> hashWithSalt 12 [hash v, hash args] Var lvar -> hashWithSalt 13 lvar Int i -> hashWithSalt 14 i Real r -> hashWithSalt 15 r Bool b -> hashWithSalt 16 b Rawcode r -> hashWithSalt 17 r String s -> hashWithSalt 18 s Code c -> hashWithSalt 19 c Null -> hashWithSalt 20 () AVar v idx -> hashWithSalt 21 [hash v, hash idx] SVar v -> hashWithSalt 22 v ADef v ty -> hashWithSalt 23 [hash v, hash ty] SDef c v ty init -> hashWithSalt 24 [hash c, hash v, hash ty, hash init] instance Compose (Ast var) where compose f a = case a of Programm toplvl -> Programm <$> T.traverse f toplvl Function c n a r body -> Function c n a r <$> T.traverse f body Global var -> Global <$> f var Set x y -> Set <$> f x <*> f y Local x -> Local <$> f x If e tb elseifs eb -> If <$> f e <*> T.traverse f tb <*> T.traverse composeEIf elseifs <*> T.traverse (T.traverse f) eb where composeEIf (cond, block) = (,) <$> f cond <*> T.traverse f block Loop b -> Loop <$> T.traverse f b Exitwhen cond -> Exitwhen <$> f cond Return (Just e) -> Return . Just <$> f e Call n args -> Call <$> pure n <*> T.traverse f args Var lvar -> Var <$> f lvar AVar n ix -> AVar <$> pure n <*> f ix SDef c n t (Just e) -> SDef c n t . Just <$> f e x -> pure x newtype FAst a var = FAst { getAst :: Ast var a } instance Functor (FAst a) where fmap f x = FAst $ case getAst x of Programm prog -> Programm (map (getAst . F.fmap f . FAst) prog) Native c name args ret -> Native c (f name) (map (second f) args) ret Function c name args ret body -> Function c (f name) (map (second f) args) ret (map (getAst . F.fmap f . FAst) body) Global vdef -> Global ((getAst . F.fmap f . FAst) vdef) Set lvar expr -> Set ((getAst . F.fmap f . FAst) lvar) ((getAst . F.fmap f . FAst) expr) Local vdef -> Local ((getAst . F.fmap f . FAst) vdef) If e ib ei eb -> If ((getAst . F.fmap f . FAst) e) (map (getAst . F.fmap f . FAst) ib) (map ((getAst . F.fmap f . FAst) *** (map (getAst . F.fmap f . FAst))) ei) (F.fmap (map (getAst . F.fmap f . FAst)) eb) Loop body -> Loop (map (getAst . F.fmap f . FAst) body) Exitwhen expr -> Exitwhen ((getAst . F.fmap f . FAst) expr) Return expr -> Return (F.fmap (getAst . F.fmap f . FAst) expr) Call name args -> Call (f name) (map (getAst . F.fmap f . FAst) args) Var lvar -> Var ((getAst . F.fmap f . FAst) lvar) AVar v idx -> AVar (f v) ((getAst . F.fmap f . FAst) idx) SVar v -> SVar (f v) Code v -> Code (f v) ADef v typ -> ADef (f v) typ SDef c v typ expr -> SDef c (f v) typ (F.fmap (getAst . F.fmap f . FAst) expr) _ -> unsafeCoerce x {- where f' :: Ast a r -> Ast b r f' = getAst . F.fmap f . FAst -} instance Foldable (FAst r) where foldMap :: Monoid m => (a -> m) -> FAst r a -> m foldMap f x = case getAst x of Programm prog -> F.foldMap (F.foldMap f . FAst) prog Native c name args ret -> f name <> F.foldMap (f . snd) args Function c name args ret body -> f name <> F.foldMap (f . snd) args <> F.foldMap (F.foldMap f . FAst) body Global vdef -> (F.foldMap f . FAst) vdef Set lvar expr -> (F.foldMap f . FAst) lvar <> (F.foldMap f . FAst) expr Local vdef -> (F.foldMap f . FAst) vdef If e ib ei eb -> (F.foldMap f . FAst) e <> F.foldMap (F.foldMap f . FAst) ib <> F.foldMap (uncurry (<>) . ((F.foldMap f . FAst) *** F.foldMap (F.foldMap f . FAst))) ei <> F.foldMap (F.foldMap (F.foldMap f . FAst)) eb Loop body -> F.foldMap (F.foldMap f . FAst) body Exitwhen expr -> (F.foldMap f . FAst) expr Return expr -> F.foldMap (F.foldMap f . FAst) expr Call name args -> f name <> F.foldMap (F.foldMap f . FAst) args Var lvar -> (F.foldMap f . FAst) lvar Code v -> f v AVar v idx -> f v <> (F.foldMap f . FAst) idx SVar v -> f v ADef v typ -> f v SDef c v typ expr -> f v <> F.foldMap (F.foldMap f . FAst) expr _ -> mempty where f ' : : Monoid m = > Ast a r - > m f ' = ( F.foldMap f . FAst ) where f' :: Monoid m => Ast a r -> m f' = (F.foldMap f . FAst) -} instance Traversable (FAst r) where traverse :: Applicative f => (a -> f b) -> FAst r a -> f (FAst r b) traverse f x = F.fmap FAst $ case getAst x of Programm prog -> Programm <$> T.traverse (F.fmap getAst . T.traverse f . FAst) prog Native c name args ret -> Native c <$> f name <*> T.traverse (fTypeAndName f) args <*> pure ret Function c name args ret body -> Function c <$> f name <*> T.traverse (fTypeAndName f) args <*> pure ret <*> T.traverse (F.fmap getAst . T.traverse f . FAst) body Global vdef -> Global <$> (F.fmap getAst . T.traverse f . FAst) vdef Set lvar expr -> Set <$> (F.fmap getAst . T.traverse f . FAst) lvar <*> (F.fmap getAst . T.traverse f . FAst) expr Local vdef -> Local <$> (F.fmap getAst . T.traverse f . FAst) vdef If e ib ei eb -> If <$> (F.fmap getAst . T.traverse f . FAst) e <*> T.traverse (F.fmap getAst . T.traverse f . FAst) ib <*> T.traverse (\(c, b) -> (,) <$> (F.fmap getAst . T.traverse f . FAst) c <*> T.traverse (F.fmap getAst . T.traverse f . FAst) b) ei <*> T.traverse (T.traverse (F.fmap getAst . T.traverse f . FAst)) eb Loop body -> Loop <$> T.traverse (F.fmap getAst . T.traverse f . FAst) body Exitwhen cond -> Exitwhen <$> (F.fmap getAst . T.traverse f . FAst) cond Return expr -> Return <$> T.traverse (F.fmap getAst . T.traverse f . FAst) expr Var lvar -> Var <$> (F.fmap getAst . T.traverse f . FAst) lvar Call name args -> Call <$> f name <*> T.traverse (F.fmap getAst . T.traverse f . FAst) args Code name -> Code <$> f name AVar v idx -> AVar <$> f v <*> (F.fmap getAst . T.traverse f . FAst) idx SVar v -> SVar <$> f v ADef v typ -> ADef <$> f v <*> pure typ SDef c v typ expr -> SDef c <$> f v <*> pure typ <*> T.traverse (F.fmap getAst . T.traverse f . FAst) expr n -> pure $ unsafeCoerce n where fTypeAndName f (ty, n) = sequenceA (ty, f n) {- where f' = (F.fmap getAst . T.traverse f . FAst) -} fmap :: (a -> b) -> Ast a r -> Ast b r fmap f = getAst . F.fmap f . FAst foldMap :: Monoid m => (a -> m) -> Ast a r -> m foldMap f = F.foldMap f . FAst traverse :: Applicative f => (a -> f b) -> Ast a r -> f (Ast b r) traverse f = F.fmap getAst . T.traverse f . FAst s2i :: Lit -> Int32 s2i = go where go ('-':s) = negate $ go s go ('+':s) = go s go ('$':s) = read $ "0x" <> s go s = read s s2r :: Lit -> Float s2r = go where go ('-':s) = negate $ go s go ('+':s) = go s go s = read $ "0" <> s <> "0" rawcode2int :: Lit -> Int32 rawcode2int = foldl (\acc word -> acc*256 + fromIntegral (ord word)) 0 eliminateElseIfs :: Ast v Stmt -> Ast v Stmt eliminateElseIfs (If cond tb eis eb) = If cond tb [] $ foldr (\(cond, body) elem -> Just [If cond body [] elem]) eb eis eliminateElseIfs x = x isGlobal :: Ast a Toplevel -> Bool isGlobal Global{} = True isGlobal _ = False isLocal :: Ast a Stmt -> Bool isLocal Local{} = True isLocal _ = False isFunction :: Ast a Toplevel -> Bool isFunction Function{} = True isFunction _ = False isOp x = x `elem` ["and", "or", "not" , "+", "-", "*", "/", "%" , "==", "!=", "<=", ">=", "<", ">" ]
null
https://raw.githubusercontent.com/lep/jhcr/4a1da99439a688824db37f28c1e69ec3985fbb30/Jass/Ast.hs
haskell
# LANGUAGE GADTs # where f' :: Ast a r -> Ast b r f' = getAst . F.fmap f . FAst where f' = (F.fmap getAst . T.traverse f . FAst)
# LANGUAGE StandaloneDeriving # # LANGUAGE DeriveGeneric # # LANGUAGE InstanceSigs # module Jass.Ast ( Ast (..) , Expr , Stmt , LVar , VarDef , Toplevel , Programm , Name , Type , Lit , Constant (..) , fmap, foldMap, traverse , s2i, s2r, rawcode2int , eliminateElseIfs , isGlobal, isLocal, isFunction, isOp ) where import Prelude hiding (fmap, foldMap, traverse) import Data.Composeable import qualified Data.Foldable as F import qualified Data.Functor as F import qualified Data.Traversable as T import Control.Applicative import Control.Arrow import Unsafe.Coerce import Data.Int import Data.Char import Data.Hashable import GHC.Generics import Data.Binary data Expr data Stmt data LVar data VarDef data Toplevel data Programm data Constant = Const | Normal deriving (Eq, Ord, Show, Generic) instance Binary Constant instance Hashable Constant type Name = String type Type = String type Lit = String data Ast var a where Programm :: [Ast var Toplevel] -> Ast var Programm Native :: Constant -> var -> [(Type, var)] -> Type -> Ast var Toplevel Function :: Constant -> var -> [(Type, var)] -> Type -> [Ast var Stmt] -> Ast var Toplevel Global :: Ast var VarDef -> Ast var Toplevel Typedef :: Type -> Type -> Ast var Toplevel Set :: Ast var LVar -> Ast var Expr -> Ast var Stmt Local :: Ast var VarDef -> Ast var Stmt If :: Ast var Expr -> [Ast var Stmt] -> [(Ast var Expr, [Ast var Stmt])] -> Maybe [Ast var Stmt] -> Ast var Stmt Loop :: [Ast var Stmt] -> Ast var Stmt Exitwhen :: Ast var Expr -> Ast var Stmt Return :: Maybe (Ast var Expr) -> Ast var Stmt Call :: var -> [Ast var Expr] -> Ast var a Var :: Ast var LVar -> Ast var Expr Int :: Lit -> Ast var Expr Rawcode :: Lit -> Ast var Expr Real :: Lit -> Ast var Expr Bool :: Bool -> Ast var Expr String :: Lit -> Ast var Expr Code :: var -> Ast var Expr Null :: Ast var Expr AVar :: var -> Ast var Expr -> Ast var LVar SVar :: var -> Ast var LVar ADef :: var -> Type -> Ast var VarDef SDef :: Constant -> var -> Type -> Maybe (Ast var Expr) -> Ast var VarDef deriving instance Show var => Show (Ast var a) deriving instance Eq var => Eq (Ast var a) instance Hashable var => Hashable (Ast var a) where hashWithSalt salt x = hashWithSalt salt $ hash x hash x = case x of Programm p -> hashWithSalt 1 p Native c v args ret -> hashWithSalt 2 [hash c, hash v, hash args, hash ret] Function c v args ret body -> hashWithSalt 3 [hash c, hash v, hash args, hash ret, hash body] Global vdef -> hashWithSalt 4 vdef Typedef a b -> hashWithSalt 5 [hash a, hash b] Set lvar expr -> hashWithSalt 6 [hash lvar, hash expr] Local vdef -> hashWithSalt 7 vdef If cond tb elseifs eb -> hashWithSalt 8 [hash cond, hash tb, hash elseifs, hash eb] Loop body -> hashWithSalt 9 body Exitwhen expr -> hashWithSalt 10 expr Return expr -> hashWithSalt 11 expr Call v args -> hashWithSalt 12 [hash v, hash args] Var lvar -> hashWithSalt 13 lvar Int i -> hashWithSalt 14 i Real r -> hashWithSalt 15 r Bool b -> hashWithSalt 16 b Rawcode r -> hashWithSalt 17 r String s -> hashWithSalt 18 s Code c -> hashWithSalt 19 c Null -> hashWithSalt 20 () AVar v idx -> hashWithSalt 21 [hash v, hash idx] SVar v -> hashWithSalt 22 v ADef v ty -> hashWithSalt 23 [hash v, hash ty] SDef c v ty init -> hashWithSalt 24 [hash c, hash v, hash ty, hash init] instance Compose (Ast var) where compose f a = case a of Programm toplvl -> Programm <$> T.traverse f toplvl Function c n a r body -> Function c n a r <$> T.traverse f body Global var -> Global <$> f var Set x y -> Set <$> f x <*> f y Local x -> Local <$> f x If e tb elseifs eb -> If <$> f e <*> T.traverse f tb <*> T.traverse composeEIf elseifs <*> T.traverse (T.traverse f) eb where composeEIf (cond, block) = (,) <$> f cond <*> T.traverse f block Loop b -> Loop <$> T.traverse f b Exitwhen cond -> Exitwhen <$> f cond Return (Just e) -> Return . Just <$> f e Call n args -> Call <$> pure n <*> T.traverse f args Var lvar -> Var <$> f lvar AVar n ix -> AVar <$> pure n <*> f ix SDef c n t (Just e) -> SDef c n t . Just <$> f e x -> pure x newtype FAst a var = FAst { getAst :: Ast var a } instance Functor (FAst a) where fmap f x = FAst $ case getAst x of Programm prog -> Programm (map (getAst . F.fmap f . FAst) prog) Native c name args ret -> Native c (f name) (map (second f) args) ret Function c name args ret body -> Function c (f name) (map (second f) args) ret (map (getAst . F.fmap f . FAst) body) Global vdef -> Global ((getAst . F.fmap f . FAst) vdef) Set lvar expr -> Set ((getAst . F.fmap f . FAst) lvar) ((getAst . F.fmap f . FAst) expr) Local vdef -> Local ((getAst . F.fmap f . FAst) vdef) If e ib ei eb -> If ((getAst . F.fmap f . FAst) e) (map (getAst . F.fmap f . FAst) ib) (map ((getAst . F.fmap f . FAst) *** (map (getAst . F.fmap f . FAst))) ei) (F.fmap (map (getAst . F.fmap f . FAst)) eb) Loop body -> Loop (map (getAst . F.fmap f . FAst) body) Exitwhen expr -> Exitwhen ((getAst . F.fmap f . FAst) expr) Return expr -> Return (F.fmap (getAst . F.fmap f . FAst) expr) Call name args -> Call (f name) (map (getAst . F.fmap f . FAst) args) Var lvar -> Var ((getAst . F.fmap f . FAst) lvar) AVar v idx -> AVar (f v) ((getAst . F.fmap f . FAst) idx) SVar v -> SVar (f v) Code v -> Code (f v) ADef v typ -> ADef (f v) typ SDef c v typ expr -> SDef c (f v) typ (F.fmap (getAst . F.fmap f . FAst) expr) _ -> unsafeCoerce x instance Foldable (FAst r) where foldMap :: Monoid m => (a -> m) -> FAst r a -> m foldMap f x = case getAst x of Programm prog -> F.foldMap (F.foldMap f . FAst) prog Native c name args ret -> f name <> F.foldMap (f . snd) args Function c name args ret body -> f name <> F.foldMap (f . snd) args <> F.foldMap (F.foldMap f . FAst) body Global vdef -> (F.foldMap f . FAst) vdef Set lvar expr -> (F.foldMap f . FAst) lvar <> (F.foldMap f . FAst) expr Local vdef -> (F.foldMap f . FAst) vdef If e ib ei eb -> (F.foldMap f . FAst) e <> F.foldMap (F.foldMap f . FAst) ib <> F.foldMap (uncurry (<>) . ((F.foldMap f . FAst) *** F.foldMap (F.foldMap f . FAst))) ei <> F.foldMap (F.foldMap (F.foldMap f . FAst)) eb Loop body -> F.foldMap (F.foldMap f . FAst) body Exitwhen expr -> (F.foldMap f . FAst) expr Return expr -> F.foldMap (F.foldMap f . FAst) expr Call name args -> f name <> F.foldMap (F.foldMap f . FAst) args Var lvar -> (F.foldMap f . FAst) lvar Code v -> f v AVar v idx -> f v <> (F.foldMap f . FAst) idx SVar v -> f v ADef v typ -> f v SDef c v typ expr -> f v <> F.foldMap (F.foldMap f . FAst) expr _ -> mempty where f ' : : Monoid m = > Ast a r - > m f ' = ( F.foldMap f . FAst ) where f' :: Monoid m => Ast a r -> m f' = (F.foldMap f . FAst) -} instance Traversable (FAst r) where traverse :: Applicative f => (a -> f b) -> FAst r a -> f (FAst r b) traverse f x = F.fmap FAst $ case getAst x of Programm prog -> Programm <$> T.traverse (F.fmap getAst . T.traverse f . FAst) prog Native c name args ret -> Native c <$> f name <*> T.traverse (fTypeAndName f) args <*> pure ret Function c name args ret body -> Function c <$> f name <*> T.traverse (fTypeAndName f) args <*> pure ret <*> T.traverse (F.fmap getAst . T.traverse f . FAst) body Global vdef -> Global <$> (F.fmap getAst . T.traverse f . FAst) vdef Set lvar expr -> Set <$> (F.fmap getAst . T.traverse f . FAst) lvar <*> (F.fmap getAst . T.traverse f . FAst) expr Local vdef -> Local <$> (F.fmap getAst . T.traverse f . FAst) vdef If e ib ei eb -> If <$> (F.fmap getAst . T.traverse f . FAst) e <*> T.traverse (F.fmap getAst . T.traverse f . FAst) ib <*> T.traverse (\(c, b) -> (,) <$> (F.fmap getAst . T.traverse f . FAst) c <*> T.traverse (F.fmap getAst . T.traverse f . FAst) b) ei <*> T.traverse (T.traverse (F.fmap getAst . T.traverse f . FAst)) eb Loop body -> Loop <$> T.traverse (F.fmap getAst . T.traverse f . FAst) body Exitwhen cond -> Exitwhen <$> (F.fmap getAst . T.traverse f . FAst) cond Return expr -> Return <$> T.traverse (F.fmap getAst . T.traverse f . FAst) expr Var lvar -> Var <$> (F.fmap getAst . T.traverse f . FAst) lvar Call name args -> Call <$> f name <*> T.traverse (F.fmap getAst . T.traverse f . FAst) args Code name -> Code <$> f name AVar v idx -> AVar <$> f v <*> (F.fmap getAst . T.traverse f . FAst) idx SVar v -> SVar <$> f v ADef v typ -> ADef <$> f v <*> pure typ SDef c v typ expr -> SDef c <$> f v <*> pure typ <*> T.traverse (F.fmap getAst . T.traverse f . FAst) expr n -> pure $ unsafeCoerce n where fTypeAndName f (ty, n) = sequenceA (ty, f n) fmap :: (a -> b) -> Ast a r -> Ast b r fmap f = getAst . F.fmap f . FAst foldMap :: Monoid m => (a -> m) -> Ast a r -> m foldMap f = F.foldMap f . FAst traverse :: Applicative f => (a -> f b) -> Ast a r -> f (Ast b r) traverse f = F.fmap getAst . T.traverse f . FAst s2i :: Lit -> Int32 s2i = go where go ('-':s) = negate $ go s go ('+':s) = go s go ('$':s) = read $ "0x" <> s go s = read s s2r :: Lit -> Float s2r = go where go ('-':s) = negate $ go s go ('+':s) = go s go s = read $ "0" <> s <> "0" rawcode2int :: Lit -> Int32 rawcode2int = foldl (\acc word -> acc*256 + fromIntegral (ord word)) 0 eliminateElseIfs :: Ast v Stmt -> Ast v Stmt eliminateElseIfs (If cond tb eis eb) = If cond tb [] $ foldr (\(cond, body) elem -> Just [If cond body [] elem]) eb eis eliminateElseIfs x = x isGlobal :: Ast a Toplevel -> Bool isGlobal Global{} = True isGlobal _ = False isLocal :: Ast a Stmt -> Bool isLocal Local{} = True isLocal _ = False isFunction :: Ast a Toplevel -> Bool isFunction Function{} = True isFunction _ = False isOp x = x `elem` ["and", "or", "not" , "+", "-", "*", "/", "%" , "==", "!=", "<=", ">=", "<", ">" ]
8abf8fbf1766c332022a10baabaf89ab255bfab80082e1c319bb5feef516e1db
JeffreyBenjaminBrown/hode
Util.hs
# LANGUAGE ScopedTypeVariables # module Hode.UI.Util ( unEitherSt -- ^ Either String St -> St -> St , emptySubgraphBuffer -- ^ Buffer , bufferFrom_viewQuery -- ^ ViewQuery -> Buffer , buffer_from_exprRowTree -- ^ PTree ViewExprNode -- -> Either String Buffer , viewFork_fromViewForkType -- ^ ViewForkType -> ViewFork , exprRow_fromQuery -- ^ ViewQuery -> ExprRow , exprRow_from_viewExprNode' -- ^ St -> ViewExprNode - > Either ^ ViewExprNode - > ^ ViewOptions ) where import qualified Data.List.PointedList as P import Data.Map (Map) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Lens.Micro import Hode.Brick import Hode.Hash.Lookup import Hode.Hash.Types import Hode.PTree.Initial import Hode.Qseq.Types (Var(..)) import Hode.Rslt.Types import Hode.UI.Types.Names import Hode.UI.Types.State import Hode.UI.Types.Views import Hode.UI.Window import Hode.Util.Misc unEitherSt :: St -> Either String St -> St unEitherSt old (Left s) = old & showError s unEitherSt _ (Right new) = new & optionalWindows %~ S.delete Error emptySubgraphBuffer :: Buffer emptySubgraphBuffer = bufferFrom_viewQuery $ QueryView $ "Empty search buffer. " ++ "(Run a search to populate it with a view of your graph.)" bufferFrom_viewQuery :: ViewQuery -> Buffer bufferFrom_viewQuery vq = Buffer { _bufferExprRowTree = pTreeLeaf $ exprRow_fromQuery vq } | TODO : handle ` VMember`s and ` VCenterRole`s too . buffer_from_exprRowTree :: PTree ExprRow -> Either String Buffer buffer_from_exprRowTree ptbr = prefixLeft "buffer_from_exprRowTree:" $ do let (br :: ExprRow) = ptbr ^. pTreeLabel ve :: ViewExpr <- case br ^. viewExprNode of VenExpr x -> Right x _ -> Left $ "called from a non-VenExpr." Right $ Buffer { _bufferExprRowTree = PTree { _pTreeLabel = exprRow_fromQuery . QueryView $ unColorString $ ve ^. viewExpr_String , _pTreeHasFocus = False , _pMTrees = P.fromList [ptbr] } } viewFork_fromViewForkType :: ViewForkType -> ViewFork viewFork_fromViewForkType vft = ViewFork { _viewForkCenter = Nothing , _viewForkSortTplt = Nothing , _viewForkType = vft } exprRow_fromQuery :: ViewQuery -> ExprRow exprRow_fromQuery = exprRow_from_viewExprNode . VenFork . viewFork_fromViewForkType . VFQuery exprRow_from_viewExprNode' :: St -> ViewExprNode -> Either String ExprRow exprRow_from_viewExprNode' st n@(VenExpr (ViewExpr a _ _)) = prefixLeft "exprRow_from_viewExprNode':" $ do let r = st ^. appRslt hs = st ^. columnHExprs sub :: Map Var Addr = M.singleton VarRowNode a matches :: Map HExpr (Set Addr) <- let f h = (h, hExprToAddrs r sub h) in ifLefts_map $ M.fromList $ map f hs let matchCounts :: Map HExpr Int = M.map S.size matches Right $ ExprRow { _viewExprNode = n , _numColumnProps = matchCounts , _boolProps = BoolProps { _inSortGroup = False , _selected = False } , _otherProps = OtherProps { _folded = False , _childSort = Nothing } } exprRow_from_viewExprNode' _ n = Right $ exprRow_from_viewExprNode n exprRow_from_viewExprNode :: ViewExprNode -> ExprRow exprRow_from_viewExprNode n = ExprRow { _viewExprNode = n , _numColumnProps = mempty , _boolProps = BoolProps { _inSortGroup = False , _selected = False } , _otherProps = OtherProps { _folded = False , _childSort = Nothing } } defaulViewOptions :: ViewOptions defaulViewOptions = ViewOptions { _viewOpt_ShowAddresses = False , _viewOpt_ShowAsAddresses = False , _viewOpt_WrapLength = 60 }
null
https://raw.githubusercontent.com/JeffreyBenjaminBrown/hode/79a54a6796fa01570cde6903b398675c42954e62/hode-ui/Hode/UI/Util.hs
haskell
^ Either String St -> St -> St ^ Buffer ^ ViewQuery -> Buffer ^ PTree ViewExprNode -> Either String Buffer ^ ViewForkType -> ViewFork ^ ViewQuery -> ExprRow ^ St -> ViewExprNode
# LANGUAGE ScopedTypeVariables # module Hode.UI.Util ( - > Either ^ ViewExprNode - > ^ ViewOptions ) where import qualified Data.List.PointedList as P import Data.Map (Map) import qualified Data.Map as M import Data.Set (Set) import qualified Data.Set as S import Lens.Micro import Hode.Brick import Hode.Hash.Lookup import Hode.Hash.Types import Hode.PTree.Initial import Hode.Qseq.Types (Var(..)) import Hode.Rslt.Types import Hode.UI.Types.Names import Hode.UI.Types.State import Hode.UI.Types.Views import Hode.UI.Window import Hode.Util.Misc unEitherSt :: St -> Either String St -> St unEitherSt old (Left s) = old & showError s unEitherSt _ (Right new) = new & optionalWindows %~ S.delete Error emptySubgraphBuffer :: Buffer emptySubgraphBuffer = bufferFrom_viewQuery $ QueryView $ "Empty search buffer. " ++ "(Run a search to populate it with a view of your graph.)" bufferFrom_viewQuery :: ViewQuery -> Buffer bufferFrom_viewQuery vq = Buffer { _bufferExprRowTree = pTreeLeaf $ exprRow_fromQuery vq } | TODO : handle ` VMember`s and ` VCenterRole`s too . buffer_from_exprRowTree :: PTree ExprRow -> Either String Buffer buffer_from_exprRowTree ptbr = prefixLeft "buffer_from_exprRowTree:" $ do let (br :: ExprRow) = ptbr ^. pTreeLabel ve :: ViewExpr <- case br ^. viewExprNode of VenExpr x -> Right x _ -> Left $ "called from a non-VenExpr." Right $ Buffer { _bufferExprRowTree = PTree { _pTreeLabel = exprRow_fromQuery . QueryView $ unColorString $ ve ^. viewExpr_String , _pTreeHasFocus = False , _pMTrees = P.fromList [ptbr] } } viewFork_fromViewForkType :: ViewForkType -> ViewFork viewFork_fromViewForkType vft = ViewFork { _viewForkCenter = Nothing , _viewForkSortTplt = Nothing , _viewForkType = vft } exprRow_fromQuery :: ViewQuery -> ExprRow exprRow_fromQuery = exprRow_from_viewExprNode . VenFork . viewFork_fromViewForkType . VFQuery exprRow_from_viewExprNode' :: St -> ViewExprNode -> Either String ExprRow exprRow_from_viewExprNode' st n@(VenExpr (ViewExpr a _ _)) = prefixLeft "exprRow_from_viewExprNode':" $ do let r = st ^. appRslt hs = st ^. columnHExprs sub :: Map Var Addr = M.singleton VarRowNode a matches :: Map HExpr (Set Addr) <- let f h = (h, hExprToAddrs r sub h) in ifLefts_map $ M.fromList $ map f hs let matchCounts :: Map HExpr Int = M.map S.size matches Right $ ExprRow { _viewExprNode = n , _numColumnProps = matchCounts , _boolProps = BoolProps { _inSortGroup = False , _selected = False } , _otherProps = OtherProps { _folded = False , _childSort = Nothing } } exprRow_from_viewExprNode' _ n = Right $ exprRow_from_viewExprNode n exprRow_from_viewExprNode :: ViewExprNode -> ExprRow exprRow_from_viewExprNode n = ExprRow { _viewExprNode = n , _numColumnProps = mempty , _boolProps = BoolProps { _inSortGroup = False , _selected = False } , _otherProps = OtherProps { _folded = False , _childSort = Nothing } } defaulViewOptions :: ViewOptions defaulViewOptions = ViewOptions { _viewOpt_ShowAddresses = False , _viewOpt_ShowAsAddresses = False , _viewOpt_WrapLength = 60 }
582295ffd61c438481f13f5b08021129830045ccd6884af71eae5227c498a1e6
Perry961002/SICP
exa1.3.4-prodedure-as-the-return-value.scm
(load "Chap1\\example\\exa1.3.3-Process-as-general-method.scm") 平均阻尼过程 , 返回求一个过程f在某一处的平均阻尼过程 (define (average-damp f) (lambda (x) (/ (+ x (f x)) 2))) (define (sqrt1 x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) ;--------------------------------------------------------------------- 牛顿法 (define dx 0.00001) ;得到g的导数, 返回g的导函数过程 (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) ;将g(x) = 0 ==> f(x) = x - g(x) / Dg(x) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) 牛顿法找g根据猜测值guess得到的零点 (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) (define (sqrt2 x) (newtons-method (lambda (y) (- (* y y) x)) 1.0)) ;-------------------------------------------------------------- 抽象和第一级过程 从一种函数g出发 , (define (fixed-point-transform g transform guess) (fixed-point (transform g) guess))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap1/example/exa1.3.4-prodedure-as-the-return-value.scm
scheme
--------------------------------------------------------------------- 得到g的导数, 返回g的导函数过程 将g(x) = 0 ==> f(x) = x - g(x) / Dg(x) --------------------------------------------------------------
(load "Chap1\\example\\exa1.3.3-Process-as-general-method.scm") 平均阻尼过程 , 返回求一个过程f在某一处的平均阻尼过程 (define (average-damp f) (lambda (x) (/ (+ x (f x)) 2))) (define (sqrt1 x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) 牛顿法 (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) 牛顿法找g根据猜测值guess得到的零点 (define (newtons-method g guess) (fixed-point (newton-transform g) guess)) (define (sqrt2 x) (newtons-method (lambda (y) (- (* y y) x)) 1.0)) 抽象和第一级过程 从一种函数g出发 , (define (fixed-point-transform g transform guess) (fixed-point (transform g) guess))
d74d61681f3cd1b8e4610a0d9ab00716861fb48a65cad45828ebba8d3f26b725
lipas-liikuntapaikat/lipas
handler_test.clj
(ns lipas.backend.handler-test (:require [cheshire.core :as j] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.test :refer [deftest testing is] :as t] [cognitect.transit :as transit] [dk.ative.docjure.spreadsheet :as excel] [lipas.backend.config :as config] [lipas.backend.core :as core] [lipas.backend.email :as email] [lipas.backend.jwt :as jwt] [lipas.backend.system :as system] [lipas.schema.core] [lipas.seed :as seed] [lipas.utils :as utils] [ring.mock.request :as mock]) (:import java.util.Base64 [java.io ByteArrayInputStream ByteArrayOutputStream])) (def <-json #(j/parse-string (slurp %) true)) (def ->json j/generate-string) (defn ->transit [x] (let [out (ByteArrayOutputStream. 4096) writer (transit/writer out :json)] (transit/write writer x) (.toString out))) (defn <-transit [in] (let [reader (transit/reader in :json)] (transit/read reader))) (defn ->base64 "Encodes a string as base64." [s] (.encodeToString (Base64/getEncoder) (.getBytes s))) (defn auth-header "Adds Authorization header to the request with base64 encoded \"Basic user:pass\" value." [req user passwd] (mock/header req "Authorization" (str "Basic " (->base64 (str user ":" passwd))))) (defn token-header [req token] (mock/header req "Authorization" (str "Token " token))) (def config (-> config/default-config (select-keys [:db :app :search :mailchimp]) (assoc-in [:app :emailer] (email/->TestEmailer)))) (def system (system/start-system! config)) (def db (:db system)) (def app (:app system)) (def search (:search system)) (defn gen-user ([] (gen-user {:db? false :admin? false :status "active"})) ([{:keys [db? admin? status] :or {admin? false status "active"}}] (let [user (-> (gen/generate (s/gen :lipas/user)) (assoc :password (str (gensym)) :status status) (assoc-in [:permissions :admin?] admin?))] (if db? (do (core/add-user! db user) (assoc user :id (:id (core/get-user db (:email user))))) user)))) (deftest register-user-test (let [user (gen-user) resp (app (-> (mock/request :post "/api/actions/register") (mock/content-type "application/json") (mock/body (->json user))))] (is (= 201 (:status resp))))) (deftest register-user-conflict-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/register") (mock/content-type "application/json") (mock/body (->json user)))) body (<-json (:body resp))] (is (= 409 (:status resp))) (is (= "username-conflict" (:type body))))) (deftest login-failure-test (let [resp (app (-> (mock/request :post "/api/actions/login") (mock/content-type "application/json") (auth-header "this" "fails")))] (is (= (:status resp) 401)))) (deftest login-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/login") (mock/content-type "application/json") (auth-header (:username user) (:password user)))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (= (:email user) (:email body))))) (deftest refresh-login-test (let [user (gen-user {:db? true}) token1 (jwt/create-token user :terse? true) _ (Thread/sleep 1000) ; to see effect between timestamps resp (app (-> (mock/request :get "/api/actions/refresh-login") (mock/content-type "application/json") (token-header token1))) body (<-json (:body resp)) token2 (:token body) exp-old (:exp (jwt/unsign token1)) exp-new (:exp (jwt/unsign token2))] (is (= 200 (:status resp))) (is (> exp-new exp-old)))) ;; TODO how to test side-effects? (sending email) (deftest request-password-reset-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/request-password-reset") (mock/content-type "application/json") (mock/body (->json (select-keys user [:email])))))] (is (= 200 (:status resp))))) (deftest request-password-reset-email-not-found-test (let [resp (app (-> (mock/request :post "/api/actions/request-password-reset") (mock/content-type "application/json") (mock/body (->json {:email ""})))) body (<-json (:body resp))] (is (= 404 (:status resp))) (is (= "email-not-found" (:type body))))) (deftest reset-password-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) resp (app (-> (mock/request :post "/api/actions/reset-password") (mock/content-type "application/json") (mock/body (->json {:password "blablaba"})) (token-header token)))] (is (= 200 (:status resp))))) (deftest reset-password-expired-token-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true :valid-seconds 0) _ (Thread/sleep 100) ; make sure token expires resp (app (-> (mock/request :post "/api/actions/reset-password") (mock/content-type "application/json") (mock/body (->json {:password "blablaba"})) (token-header token)))] (is (= 401 (:status resp))))) (deftest send-magic-link-requires-admin-test (let [admin (gen-user {:db? true :admin? false}) user (-> (gen-user {:db? false}) (dissoc :password :id)) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/send-magic-link") (mock/content-type "application/json") (mock/body (->json {:user user :login-url "" :variant "lipas"})) (token-header token)))] (is (= 403 (:status resp))))) (deftest update-user-permissions-test ;; Updating permissions has side-effect of publshing drafts the user ;; has done earlier to sites where permissions are now being ;; granted (let [admin (gen-user {:db? true :admin? true}) user (gen-user {:db? true}) ;; Add 'draft' which is expected to get publshed as side-effect event-date (utils/timestamp) draft? true site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :event-date event-date) (assoc :status "active") (assoc :lipas-id 123)) _ (core/upsert-sports-site!* db user site draft?) perms {:admin? true} token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-permissions") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :permissions perms :login-url ""})) (token-header token))) site-log (->> (core/get-sports-site-history db 123) (utils/index-by :event-date))] (is (= 200 (:status resp))) (is (= perms (-> (core/get-user db (:email user)) :permissions))) (is (= "active" (:status (get site-log event-date)))))) (deftest update-user-permissions-requires-admin-test (let [user (gen-user {:db? true :admin? false}) token (jwt/create-token user) resp (app (-> (mock/request :post "/api/actions/update-user-permissions") (mock/content-type "application/json") (mock/body (-> user (select-keys [:id :permissions]) (assoc :login-url "") ->json)) (token-header token)))] (is (= 403 (:status resp))))) (deftest update-user-data-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) user-data (gen/generate (s/gen :lipas.user/user-data)) resp (app (-> (mock/request :post "/api/actions/update-user-data") (mock/content-type "application/json") (mock/body (->json user-data)) (token-header token))) user-data2 (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= user-data user-data2)))) (deftest update-user-status-test (let [admin (gen-user {:db? true :admin? true}) user (gen-user {:db? true :status "active"}) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-status") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :status "archived"})) (token-header token))) user2 (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= "archived" (:status user2))))) (deftest update-user-status-requires-admin-test (let [admin (gen-user {:db? true :admin? false}) user (gen-user {:db? true :status "active"}) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-status") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :status "archived"})) (token-header token)))] (is (= 403 (:status resp))))) (deftest send-magic-link-test (let [admin (gen-user {:db? true :admin? true}) user (-> (gen-user {:db? false}) (dissoc :password :id)) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/send-magic-link") (mock/content-type "application/json") (mock/body (->json {:user user :login-url "" :variant "lipas"})) (token-header token)))] (is (= 200 (:status resp))))) (deftest order-magic-link-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/order-magic-link") (mock/content-type "application/json") (mock/body (->json {:email (:email user) :login-url "" :variant "lipas"}))))] (is (= 200 (:status resp))))) (deftest order-magic-link-login-url-whitelist-test (let [resp (app (-> (mock/request :post "/api/actions/order-magic-link") (mock/content-type "application/json") (mock/body (->json {:email (:email "") :login-url "-attacker.fi" :variant "lipas"}))))] (is (= 400 (:status resp))))) (deftest upsert-sports-site-draft-test (let [user (gen-user {:db? true}) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active") (dissoc :lipas-id)) resp (app (-> (mock/request :post "/api/sports-sites?draft=true") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 201 (:status resp))))) (deftest upsert-invalid-sports-site-test (let [user (gen-user {:db? true}) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "kebab") (dissoc :lipas-id)) resp (app (-> (mock/request :post "/api/sports-sites?draft=true") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 400 (:status resp))))) (deftest upsert-sports-site-no-permissions-test (let [user (gen-user) _ (as-> user $ (dissoc $ :permissions) (core/add-user! db $)) user (core/get-user db (:email user)) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) resp (app (-> (mock/request :post "/api/sports-sites") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 403 (:status resp))))) (deftest get-sports-sites-by-type-code-test (let [user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc :status "active")) _ (core/upsert-sports-site!* db user site) resp (app (-> (mock/request :get "/api/sports-sites/type/3110") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-sites body)))) (deftest get-sports-sites-yearly-by-type-code-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc :status "active") (assoc :event-date "2018-01-01T00:00:00.000Z")) rev2 (assoc rev1 :event-date "2018-02-01T00:00:00.000Z") rev3 (assoc rev1 :event-date "2017-01-01T00:00:00.000Z") _ (core/upsert-sports-site!* db user rev1) _ (core/upsert-sports-site!* db user rev2) _ (core/upsert-sports-site!* db user rev3) id (:lipas-id rev1) resp (app (-> (mock/request :get "/api/sports-sites/type/3110?revs=yearly") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (= #{"2018-02-01T00:00:00.000Z" "2017-01-01T00:00:00.000Z"} (-> (group-by :lipas-id body) (get id) (as-> $ (into #{} (map :event-date) $))))))) (deftest get-sports-sites-by-type-code-localized-test (let [user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc-in [:admin] "state") (assoc :status "active")) _ (core/upsert-sports-site!* db user site) resp (app (-> (mock/request :get "/api/sports-sites/type/3110?lang=fi") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) ;; Note returned entities are not valid according to specs! (is (= "Valtio" (->> body (filter #(= (:lipas-id site) (:lipas-id %))) first :admin))))) (deftest get-sports-site-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) _ (core/upsert-sports-site!* db user rev1) lipas-id (:lipas-id rev1) resp (app (-> (mock/request :get (str "/api/sports-sites/" lipas-id)) (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-site body)))) (deftest get-non-existing-sports-site-test (let [lipas-id 9999999999 resp (app (-> (mock/request :get (str "/api/sports-sites/" lipas-id)) (mock/content-type "application/json")))] (is (= 404 (:status resp))))) (deftest get-sports-site-history-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) rev2 (-> rev1 (assoc :event-date (gen/generate (s/gen :lipas/timestamp))) (assoc :name "Kissalan kuulahalli")) _ (core/upsert-sports-site!* db user rev1) _ (core/upsert-sports-site!* db user rev2) lipas-id (:lipas-id rev1) resp (app (-> (mock/request :get (str "/api/sports-sites/history/" lipas-id)) (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-sites body)))) (deftest search-test (let [site (gen/generate (s/gen :lipas/sports-site)) lipas-id (:lipas-id site) name (:name site) _ (core/index! search site :sync) resp (app (-> (mock/request :post "/api/actions/search") (mock/content-type "application/json") (mock/body (->json {:query {:bool {:must [{:query_string {:query name}}]}}})))) body (<-json (:body resp)) sites (map :_source (-> body :hits :hits))] (is (= 200 (:status resp))) (is (some? (first (filter (comp #{lipas-id} :lipas-id) sites)))) (is (s/valid? :lipas/sports-sites sites)))) (comment (<-json (:body (app (-> (mock/request :post "/api/actions/search") (mock/content-type "application/json") (mock/body (->json {:query {:bool {:must [{:query_string {:query (str 258083685)}}]}}}))))))) (deftest sports-sites-report-test (let [site (gen/generate (s/gen :lipas/sports-site)) _ (core/index! search site :sync) path "/api/actions/create-sports-sites-report" resp (app (-> (mock/request :post path) (mock/content-type "application/json") (mock/body (->json {:search-query {:query {:bool {:must [{:query_string {:query "*"}}]}}} :fields ["lipas-id" "name" "location.city.city-code"] :locale :fi})))) body (:body resp) wb (excel/load-workbook body) header-1 (excel/read-cell (->> wb (excel/select-sheet "lipas") (excel/select-cell "A1")))] (is (= 200 (:status resp))) (is (= "Lipas-id" header-1)))) (deftest finance-report-test (let [_ (seed/seed-city-data! db) path "/api/actions/create-finance-report" resp (app (-> (mock/request :post path) (mock/content-type "application/json") (mock/body (->json {:city-codes [275 972]})))) body (-> resp :body <-json)] (is (= 200 (:status resp))) (is (contains? body :country-averages)) (is (= '(:275 :972) (-> body :data-points keys))))) (deftest calculate-stats-test (let [_ (seed/seed-city-data! db) user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active") (assoc-in [:location :city :city-code] 275) (assoc-in [:properties :area-m2] 100)) _ (core/upsert-sports-site!* db user site) _ (core/index! search site :sync) path "/api/actions/calculate-stats" resp (app (-> (mock/request :post path) (mock/content-type "application/transit+json") (mock/header "Accept" "application/transit+json") (mock/body (->transit {:city-codes [275 972]})))) body (-> resp :body <-transit)] (is (= 200 (:status resp))) (is (number? (get-in body [275 :area-m2-pc]))))) (deftest create-energy-report-test (let [resp (app (-> (mock/request :post "/api/actions/create-energy-report") (mock/content-type "application/json") (mock/body (->json {:type-code 3110 :year 2017}))))] (is (= 200 (:status resp))))) (deftest add-reminder-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) reminder (gen/generate (s/gen :lipas/new-reminder)) resp (app (-> (mock/request :post "/api/actions/add-reminder") (mock/content-type "application/json") (mock/body (->json reminder)) (token-header token))) body (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= "pending" (:status body))))) (deftest update-reminder-status-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) reminder (gen/generate (s/gen :lipas/new-reminder)) resp1 (app (-> (mock/request :post "/api/actions/add-reminder") (mock/content-type "application/json") (mock/body (->json reminder)) (token-header token))) id (-> resp1 :body <-json :id) resp2 (app (-> (mock/request :post "/api/actions/update-reminder-status") (mock/content-type "application/json") (mock/body (->json {:id id :status "canceled"})) (token-header token)))] (is (= 200 (:status resp1))) (is (= 200 (:status resp2))))) (comment (t/run-tests *ns*))
null
https://raw.githubusercontent.com/lipas-liikuntapaikat/lipas/779934b723ec1e0cf52d6a7778b0b7e9f5d15c6b/webapp/test/clj/lipas/backend/handler_test.clj
clojure
to see effect between timestamps TODO how to test side-effects? (sending email) make sure token expires Updating permissions has side-effect of publshing drafts the user has done earlier to sites where permissions are now being granted Add 'draft' which is expected to get publshed as side-effect Note returned entities are not valid according to specs!
(ns lipas.backend.handler-test (:require [cheshire.core :as j] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.test :refer [deftest testing is] :as t] [cognitect.transit :as transit] [dk.ative.docjure.spreadsheet :as excel] [lipas.backend.config :as config] [lipas.backend.core :as core] [lipas.backend.email :as email] [lipas.backend.jwt :as jwt] [lipas.backend.system :as system] [lipas.schema.core] [lipas.seed :as seed] [lipas.utils :as utils] [ring.mock.request :as mock]) (:import java.util.Base64 [java.io ByteArrayInputStream ByteArrayOutputStream])) (def <-json #(j/parse-string (slurp %) true)) (def ->json j/generate-string) (defn ->transit [x] (let [out (ByteArrayOutputStream. 4096) writer (transit/writer out :json)] (transit/write writer x) (.toString out))) (defn <-transit [in] (let [reader (transit/reader in :json)] (transit/read reader))) (defn ->base64 "Encodes a string as base64." [s] (.encodeToString (Base64/getEncoder) (.getBytes s))) (defn auth-header "Adds Authorization header to the request with base64 encoded \"Basic user:pass\" value." [req user passwd] (mock/header req "Authorization" (str "Basic " (->base64 (str user ":" passwd))))) (defn token-header [req token] (mock/header req "Authorization" (str "Token " token))) (def config (-> config/default-config (select-keys [:db :app :search :mailchimp]) (assoc-in [:app :emailer] (email/->TestEmailer)))) (def system (system/start-system! config)) (def db (:db system)) (def app (:app system)) (def search (:search system)) (defn gen-user ([] (gen-user {:db? false :admin? false :status "active"})) ([{:keys [db? admin? status] :or {admin? false status "active"}}] (let [user (-> (gen/generate (s/gen :lipas/user)) (assoc :password (str (gensym)) :status status) (assoc-in [:permissions :admin?] admin?))] (if db? (do (core/add-user! db user) (assoc user :id (:id (core/get-user db (:email user))))) user)))) (deftest register-user-test (let [user (gen-user) resp (app (-> (mock/request :post "/api/actions/register") (mock/content-type "application/json") (mock/body (->json user))))] (is (= 201 (:status resp))))) (deftest register-user-conflict-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/register") (mock/content-type "application/json") (mock/body (->json user)))) body (<-json (:body resp))] (is (= 409 (:status resp))) (is (= "username-conflict" (:type body))))) (deftest login-failure-test (let [resp (app (-> (mock/request :post "/api/actions/login") (mock/content-type "application/json") (auth-header "this" "fails")))] (is (= (:status resp) 401)))) (deftest login-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/login") (mock/content-type "application/json") (auth-header (:username user) (:password user)))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (= (:email user) (:email body))))) (deftest refresh-login-test (let [user (gen-user {:db? true}) token1 (jwt/create-token user :terse? true) resp (app (-> (mock/request :get "/api/actions/refresh-login") (mock/content-type "application/json") (token-header token1))) body (<-json (:body resp)) token2 (:token body) exp-old (:exp (jwt/unsign token1)) exp-new (:exp (jwt/unsign token2))] (is (= 200 (:status resp))) (is (> exp-new exp-old)))) (deftest request-password-reset-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/request-password-reset") (mock/content-type "application/json") (mock/body (->json (select-keys user [:email])))))] (is (= 200 (:status resp))))) (deftest request-password-reset-email-not-found-test (let [resp (app (-> (mock/request :post "/api/actions/request-password-reset") (mock/content-type "application/json") (mock/body (->json {:email ""})))) body (<-json (:body resp))] (is (= 404 (:status resp))) (is (= "email-not-found" (:type body))))) (deftest reset-password-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) resp (app (-> (mock/request :post "/api/actions/reset-password") (mock/content-type "application/json") (mock/body (->json {:password "blablaba"})) (token-header token)))] (is (= 200 (:status resp))))) (deftest reset-password-expired-token-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true :valid-seconds 0) resp (app (-> (mock/request :post "/api/actions/reset-password") (mock/content-type "application/json") (mock/body (->json {:password "blablaba"})) (token-header token)))] (is (= 401 (:status resp))))) (deftest send-magic-link-requires-admin-test (let [admin (gen-user {:db? true :admin? false}) user (-> (gen-user {:db? false}) (dissoc :password :id)) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/send-magic-link") (mock/content-type "application/json") (mock/body (->json {:user user :login-url "" :variant "lipas"})) (token-header token)))] (is (= 403 (:status resp))))) (deftest update-user-permissions-test (let [admin (gen-user {:db? true :admin? true}) user (gen-user {:db? true}) event-date (utils/timestamp) draft? true site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :event-date event-date) (assoc :status "active") (assoc :lipas-id 123)) _ (core/upsert-sports-site!* db user site draft?) perms {:admin? true} token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-permissions") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :permissions perms :login-url ""})) (token-header token))) site-log (->> (core/get-sports-site-history db 123) (utils/index-by :event-date))] (is (= 200 (:status resp))) (is (= perms (-> (core/get-user db (:email user)) :permissions))) (is (= "active" (:status (get site-log event-date)))))) (deftest update-user-permissions-requires-admin-test (let [user (gen-user {:db? true :admin? false}) token (jwt/create-token user) resp (app (-> (mock/request :post "/api/actions/update-user-permissions") (mock/content-type "application/json") (mock/body (-> user (select-keys [:id :permissions]) (assoc :login-url "") ->json)) (token-header token)))] (is (= 403 (:status resp))))) (deftest update-user-data-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) user-data (gen/generate (s/gen :lipas.user/user-data)) resp (app (-> (mock/request :post "/api/actions/update-user-data") (mock/content-type "application/json") (mock/body (->json user-data)) (token-header token))) user-data2 (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= user-data user-data2)))) (deftest update-user-status-test (let [admin (gen-user {:db? true :admin? true}) user (gen-user {:db? true :status "active"}) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-status") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :status "archived"})) (token-header token))) user2 (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= "archived" (:status user2))))) (deftest update-user-status-requires-admin-test (let [admin (gen-user {:db? true :admin? false}) user (gen-user {:db? true :status "active"}) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/update-user-status") (mock/content-type "application/json") (mock/body (->json {:id (:id user) :status "archived"})) (token-header token)))] (is (= 403 (:status resp))))) (deftest send-magic-link-test (let [admin (gen-user {:db? true :admin? true}) user (-> (gen-user {:db? false}) (dissoc :password :id)) token (jwt/create-token admin) resp (app (-> (mock/request :post "/api/actions/send-magic-link") (mock/content-type "application/json") (mock/body (->json {:user user :login-url "" :variant "lipas"})) (token-header token)))] (is (= 200 (:status resp))))) (deftest order-magic-link-test (let [user (gen-user {:db? true}) resp (app (-> (mock/request :post "/api/actions/order-magic-link") (mock/content-type "application/json") (mock/body (->json {:email (:email user) :login-url "" :variant "lipas"}))))] (is (= 200 (:status resp))))) (deftest order-magic-link-login-url-whitelist-test (let [resp (app (-> (mock/request :post "/api/actions/order-magic-link") (mock/content-type "application/json") (mock/body (->json {:email (:email "") :login-url "-attacker.fi" :variant "lipas"}))))] (is (= 400 (:status resp))))) (deftest upsert-sports-site-draft-test (let [user (gen-user {:db? true}) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active") (dissoc :lipas-id)) resp (app (-> (mock/request :post "/api/sports-sites?draft=true") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 201 (:status resp))))) (deftest upsert-invalid-sports-site-test (let [user (gen-user {:db? true}) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "kebab") (dissoc :lipas-id)) resp (app (-> (mock/request :post "/api/sports-sites?draft=true") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 400 (:status resp))))) (deftest upsert-sports-site-no-permissions-test (let [user (gen-user) _ (as-> user $ (dissoc $ :permissions) (core/add-user! db $)) user (core/get-user db (:email user)) token (jwt/create-token user) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) resp (app (-> (mock/request :post "/api/sports-sites") (mock/content-type "application/json") (mock/body (->json site)) (token-header token)))] (is (= 403 (:status resp))))) (deftest get-sports-sites-by-type-code-test (let [user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc :status "active")) _ (core/upsert-sports-site!* db user site) resp (app (-> (mock/request :get "/api/sports-sites/type/3110") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-sites body)))) (deftest get-sports-sites-yearly-by-type-code-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc :status "active") (assoc :event-date "2018-01-01T00:00:00.000Z")) rev2 (assoc rev1 :event-date "2018-02-01T00:00:00.000Z") rev3 (assoc rev1 :event-date "2017-01-01T00:00:00.000Z") _ (core/upsert-sports-site!* db user rev1) _ (core/upsert-sports-site!* db user rev2) _ (core/upsert-sports-site!* db user rev3) id (:lipas-id rev1) resp (app (-> (mock/request :get "/api/sports-sites/type/3110?revs=yearly") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (= #{"2018-02-01T00:00:00.000Z" "2017-01-01T00:00:00.000Z"} (-> (group-by :lipas-id body) (get id) (as-> $ (into #{} (map :event-date) $))))))) (deftest get-sports-sites-by-type-code-localized-test (let [user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc-in [:type :type-code] 3110) (assoc-in [:admin] "state") (assoc :status "active")) _ (core/upsert-sports-site!* db user site) resp (app (-> (mock/request :get "/api/sports-sites/type/3110?lang=fi") (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (= "Valtio" (->> body (filter #(= (:lipas-id site) (:lipas-id %))) first :admin))))) (deftest get-sports-site-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) _ (core/upsert-sports-site!* db user rev1) lipas-id (:lipas-id rev1) resp (app (-> (mock/request :get (str "/api/sports-sites/" lipas-id)) (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-site body)))) (deftest get-non-existing-sports-site-test (let [lipas-id 9999999999 resp (app (-> (mock/request :get (str "/api/sports-sites/" lipas-id)) (mock/content-type "application/json")))] (is (= 404 (:status resp))))) (deftest get-sports-site-history-test (let [user (gen-user {:db? true :admin? true}) rev1 (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active")) rev2 (-> rev1 (assoc :event-date (gen/generate (s/gen :lipas/timestamp))) (assoc :name "Kissalan kuulahalli")) _ (core/upsert-sports-site!* db user rev1) _ (core/upsert-sports-site!* db user rev2) lipas-id (:lipas-id rev1) resp (app (-> (mock/request :get (str "/api/sports-sites/history/" lipas-id)) (mock/content-type "application/json"))) body (<-json (:body resp))] (is (= 200 (:status resp))) (is (s/valid? :lipas/sports-sites body)))) (deftest search-test (let [site (gen/generate (s/gen :lipas/sports-site)) lipas-id (:lipas-id site) name (:name site) _ (core/index! search site :sync) resp (app (-> (mock/request :post "/api/actions/search") (mock/content-type "application/json") (mock/body (->json {:query {:bool {:must [{:query_string {:query name}}]}}})))) body (<-json (:body resp)) sites (map :_source (-> body :hits :hits))] (is (= 200 (:status resp))) (is (some? (first (filter (comp #{lipas-id} :lipas-id) sites)))) (is (s/valid? :lipas/sports-sites sites)))) (comment (<-json (:body (app (-> (mock/request :post "/api/actions/search") (mock/content-type "application/json") (mock/body (->json {:query {:bool {:must [{:query_string {:query (str 258083685)}}]}}}))))))) (deftest sports-sites-report-test (let [site (gen/generate (s/gen :lipas/sports-site)) _ (core/index! search site :sync) path "/api/actions/create-sports-sites-report" resp (app (-> (mock/request :post path) (mock/content-type "application/json") (mock/body (->json {:search-query {:query {:bool {:must [{:query_string {:query "*"}}]}}} :fields ["lipas-id" "name" "location.city.city-code"] :locale :fi})))) body (:body resp) wb (excel/load-workbook body) header-1 (excel/read-cell (->> wb (excel/select-sheet "lipas") (excel/select-cell "A1")))] (is (= 200 (:status resp))) (is (= "Lipas-id" header-1)))) (deftest finance-report-test (let [_ (seed/seed-city-data! db) path "/api/actions/create-finance-report" resp (app (-> (mock/request :post path) (mock/content-type "application/json") (mock/body (->json {:city-codes [275 972]})))) body (-> resp :body <-json)] (is (= 200 (:status resp))) (is (contains? body :country-averages)) (is (= '(:275 :972) (-> body :data-points keys))))) (deftest calculate-stats-test (let [_ (seed/seed-city-data! db) user (gen-user {:db? true :admin? true}) site (-> (gen/generate (s/gen :lipas/sports-site)) (assoc :status "active") (assoc-in [:location :city :city-code] 275) (assoc-in [:properties :area-m2] 100)) _ (core/upsert-sports-site!* db user site) _ (core/index! search site :sync) path "/api/actions/calculate-stats" resp (app (-> (mock/request :post path) (mock/content-type "application/transit+json") (mock/header "Accept" "application/transit+json") (mock/body (->transit {:city-codes [275 972]})))) body (-> resp :body <-transit)] (is (= 200 (:status resp))) (is (number? (get-in body [275 :area-m2-pc]))))) (deftest create-energy-report-test (let [resp (app (-> (mock/request :post "/api/actions/create-energy-report") (mock/content-type "application/json") (mock/body (->json {:type-code 3110 :year 2017}))))] (is (= 200 (:status resp))))) (deftest add-reminder-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) reminder (gen/generate (s/gen :lipas/new-reminder)) resp (app (-> (mock/request :post "/api/actions/add-reminder") (mock/content-type "application/json") (mock/body (->json reminder)) (token-header token))) body (-> resp :body <-json)] (is (= 200 (:status resp))) (is (= "pending" (:status body))))) (deftest update-reminder-status-test (let [user (gen-user {:db? true}) token (jwt/create-token user :terse? true) reminder (gen/generate (s/gen :lipas/new-reminder)) resp1 (app (-> (mock/request :post "/api/actions/add-reminder") (mock/content-type "application/json") (mock/body (->json reminder)) (token-header token))) id (-> resp1 :body <-json :id) resp2 (app (-> (mock/request :post "/api/actions/update-reminder-status") (mock/content-type "application/json") (mock/body (->json {:id id :status "canceled"})) (token-header token)))] (is (= 200 (:status resp1))) (is (= 200 (:status resp2))))) (comment (t/run-tests *ns*))
2446c24c72d234267c3421545f21e3c8531d67f2299768bfa68e31f5311015a3
danidiaz/really-small-backpack-example
Intermediate2.hs
module Intermediate2 (bazAsString) where import Intermediate1 (barAsString) bazAsString :: String bazAsString = "****** " ++ barAsString ++ " plus baz"
null
https://raw.githubusercontent.com/danidiaz/really-small-backpack-example/7b21ec1e2166995cc67375651d5883517d82c07b/lesson8-transitively-indefinite-packages/lib-intermediate2/Intermediate2.hs
haskell
module Intermediate2 (bazAsString) where import Intermediate1 (barAsString) bazAsString :: String bazAsString = "****** " ++ barAsString ++ " plus baz"
72c826e29f1fe6e990087a366faccb17e26c2fe060e7636b170e99cb9223b81e
openvstorage/alba
fragment_helper.ml
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude open Slice open Nsm_model open Encryption open Gcrypt open Lwt.Infix let get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id = deterministic iv for fragment encryption this way we get security without needing to store the iv in the manifest / recovery info concatenate object_id chunk_id fragment_id | > encrypt AES key CBC | > take last block deterministic iv for fragment encryption this way we get security without needing to store the iv in the manifest / recovery info concatenate object_id chunk_id fragment_id |> encrypt AES key CBC |> take last block *) let fragment_id = if ignore_fragment_id then 0 else fragment_id in let s = serialize (Llio.tuple3_to Llio.string_to Llio.int_to Llio.int_to) (object_id, chunk_id, fragment_id) in let block_len = 16 in let bs = let x = Lwt_bytes.of_string s in finalize (fun () -> Padding.pad (Bigstring_slice.wrap_bigstring x) block_len) (fun () -> Lwt_bytes.unsafe_destroy x) in Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.encrypt cipher bs) >>= fun () -> let res = Str.last_chars (Lwt_bytes.to_string bs) block_len in Lwt.return res let hard_coded_iv = "\192\157V\025\215,(\236\017\226\209E\205v\159\\" let () = assert (String.length hard_coded_iv = 16) (* consumes the input and returns a big_array *) let maybe_encrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id plain = let open Encryption in match encryption with | NoEncryption -> Lwt.return (plain, None) | AlgoWithKey (AES (CBC, L256) as algo, key) -> verify_key_length algo key; let block_len = block_length algo in let bs = finalize (fun () -> Padding.pad (Bigstring_slice.wrap_bigstring plain) block_len) (fun () -> Lwt_bytes.unsafe_destroy plain) in get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id >>= fun iv -> Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.set_iv cipher iv; Cipher.encrypt cipher bs) >>= fun () -> Lwt.return (bs, None) | AlgoWithKey (AES (CTR, L256) as algo, key) -> verify_key_length algo key; let iv = get_random_string 16 in TODO this is not optimal for security of the encryption ! let iv = hard_coded_iv in Cipher.with_t_lwt key Cipher.AES256 Cipher.CTR [] (fun cipher -> Cipher.set_ctr cipher iv; Cipher.encrypt cipher plain) >>= fun () -> Lwt.return (plain, Some iv) (* consumes the input and returns a bigstring_slice *) let maybe_decrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id ~fragment_ctr data = let open Encryption in match encryption with | NoEncryption -> Lwt.return (Bigstring_slice.wrap_bigstring data) | AlgoWithKey (algo, key) -> let decrypt mode set_iv_ctr = Encryption.verify_key_length algo key; Cipher.with_t_lwt key Cipher.AES256 mode [] (fun cipher -> set_iv_ctr cipher; Cipher.decrypt_detached cipher data 0 (Lwt_bytes.length data) ) in begin match algo with | AES (CBC, L256) -> get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id >>= fun iv -> decrypt Cipher.CBC (fun h -> Cipher.set_iv h iv) >>= fun () -> Lwt.return (Padding.unpad data) | AES (CTR, L256) -> decrypt Cipher.CTR (fun h -> Cipher.set_ctr h (Option.get_some fragment_ctr)) >>= fun () -> Lwt.return (Bigstring_slice.wrap_bigstring data) end let maybe_partial_decrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id ~fragment_ctr (data, offset, length) ~fragment_offset = let open Encryption in match encryption with | NoEncryption -> Lwt.return () | AlgoWithKey (algo, key) -> begin match algo with | AES (CBC, _) -> Lwt.fail_with "can't do partial decrypt for AES CBC" | AES (CTR, L256) -> Cipher.(with_t_lwt key AES256 CTR [] (fun handle -> set_ctr_with_offset handle (Option.get_some fragment_ctr) fragment_offset; decrypt_detached handle data offset length)) end (* returns a new bigarray *) let maybe_compress compression fragment_data = let open Lwt.Infix in Compressors.compress compression fragment_data >>= fun r -> Lwt_log.debug_f "compression: %s (%i => %i)" ([%show: Compression.t] compression) (Bigstring_slice.length fragment_data) (Lwt_bytes.length r) >>= fun () -> Lwt.return r let maybe_decompress compression compressed = let open Lwt.Infix in let compressed_length = Bigstring_slice.length compressed in Compressors.decompress compression compressed >>= fun r -> Lwt_log.debug_f "decompression: %s (%i => %i)" ([%show: Compression.t] compression) compressed_length (Lwt_bytes.length r) >>= fun () -> Lwt.return r let verify fragment_data checksum = let () = Lwt_log.ign_debug_f ">>> verify fragment_data %i bytes @ %nX <<<" (Lwt_bytes.length fragment_data) (Lwt_bytes.raw_address fragment_data) in let algo = Checksum.algo_of checksum in let hash = Hashes.make_hash algo in hash # update_lwt_bytes_detached fragment_data 0 (Lwt_bytes.length fragment_data) >>= fun () -> let checksum2 = hash # final () in Lwt.return (checksum2 = checksum) let verify' fragment_data checksum = let algo = Checksum.algo_of checksum in let hash = Hashes.make_hash algo in let open Slice in hash # update_substring fragment_data.buf fragment_data.offset fragment_data.length; let checksum2 = hash # final () in Lwt.return (checksum2 = checksum) (* returns a new big_array *) let pack_fragment (fragment : Bigstring_slice.t) ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id compression encryption checksum_algo = with_timing_lwt (fun () -> maybe_compress compression fragment >>= fun compressed -> maybe_encrypt ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id encryption compressed) >>= fun (t_compress_encrypt, (final_data, fragment_ctr)) -> with_timing_lwt (fun () -> let hash = Hashes.make_hash checksum_algo in hash # update_lwt_bytes_detached final_data 0 (Lwt_bytes.length final_data) >>= fun () -> Lwt.return (hash # final ())) >>= fun (t_hash, checksum) -> Lwt.return (final_data, t_compress_encrypt, t_hash, checksum, fragment_ctr) let chunk_to_data_fragments ~chunk ~chunk_size ~k = let fragment_size = chunk_size / k in let data_fragments = let rec inner acc = function | 0 -> acc | n -> let fragment = let pos = (n-1) * fragment_size in Bigstring_slice.from_bigstring chunk pos fragment_size in inner (fragment :: acc) (n - 1) in inner [] k in data_fragments (* The lifetime of the returned data fragments is determined by the lifetime of the passed in chunk. The returned coding fragments are freshly created and should thus be freed by the consumer of this function. *) let chunk_to_fragments_ec ~chunk ~chunk_size ~k ~m ~w' = let fragment_size = chunk_size / k in Lwt_log.debug_f "chunk_to_fragments: chunk @ %nX chunk_size = %i ; fragment_size = %i" (Lwt_bytes.raw_address chunk) chunk_size fragment_size >>= fun () -> assert (chunk_size mod (Fragment_size_helper.fragment_multiple * k) = 0); let data_fragments = chunk_to_data_fragments ~chunk ~chunk_size ~k in let coding_fragments = let rec inner acc = function | 0 -> acc | n -> let fragment = let msg = Printf.sprintf "coding_fragment:%i" n in Bigstring_slice.create ~msg fragment_size in inner (fragment :: acc) (n - 1) in inner [] m in Erasure.encode ~k ~m ~w:w' data_fragments coding_fragments fragment_size >>= fun () -> Lwt.return (data_fragments, coding_fragments) returns new bigarrays * replication ( k=1 ) is a bit special though * replication (k=1) is a bit special though *) let chunk_to_packed_fragments ~object_id ~chunk_id ~chunk ~chunk_size ~k ~m ~w' ~compression ~encryption ~fragment_checksum_algo = if k = 1 then begin let fragment = Bigstring_slice.wrap_bigstring chunk in pack_fragment fragment ~object_id ~chunk_id ~fragment_id:0 ~ignore_fragment_id:true compression encryption fragment_checksum_algo >>= fun (packed, f1, f2, cs, ctr) -> let rec build_result acc = function | 0 -> acc | n -> let fragment_id = n - 1 in let acc' = (fragment_id, fragment, (packed, f1, f2, cs, ctr)) :: acc in build_result acc' (n-1) in Lwt.return ([ fragment; ], build_result [] (k+m)) end else begin chunk_to_fragments_ec ~chunk ~chunk_size ~k ~m ~w' >>= fun (data_fragments, coding_fragments) -> Lwt.finalize (fun () -> let all_fragments = List.append data_fragments coding_fragments in Lwt_list.mapi_p (fun fragment_id fragment -> pack_fragment fragment ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id:false compression encryption fragment_checksum_algo >>= fun (packed, f1, f2, cs, ctr) -> Lwt.return (fragment_id, fragment, (packed, f1, f2, cs, ctr))) all_fragments >>= fun packed_fragments -> Lwt.return (data_fragments, packed_fragments)) (fun () -> List.iter (fun bss -> Lwt_bytes.unsafe_destroy ~msg:"chunk_to_packed_fragments cleanup coding_fragments" bss.Bigstring_slice.bs) coding_fragments; Lwt.return ()) end
null
https://raw.githubusercontent.com/openvstorage/alba/459bd459335138d6b282d332fcff53a1b4300c29/ocaml/src/fragment_helper.ml
ocaml
consumes the input and returns a big_array consumes the input and returns a bigstring_slice returns a new bigarray returns a new big_array The lifetime of the returned data fragments is determined by the lifetime of the passed in chunk. The returned coding fragments are freshly created and should thus be freed by the consumer of this function.
Copyright ( C ) iNuron - This file is part of Open vStorage . For license information , see < LICENSE.txt > Copyright (C) iNuron - This file is part of Open vStorage. For license information, see <LICENSE.txt> *) open! Prelude open Slice open Nsm_model open Encryption open Gcrypt open Lwt.Infix let get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id = deterministic iv for fragment encryption this way we get security without needing to store the iv in the manifest / recovery info concatenate object_id chunk_id fragment_id | > encrypt AES key CBC | > take last block deterministic iv for fragment encryption this way we get security without needing to store the iv in the manifest / recovery info concatenate object_id chunk_id fragment_id |> encrypt AES key CBC |> take last block *) let fragment_id = if ignore_fragment_id then 0 else fragment_id in let s = serialize (Llio.tuple3_to Llio.string_to Llio.int_to Llio.int_to) (object_id, chunk_id, fragment_id) in let block_len = 16 in let bs = let x = Lwt_bytes.of_string s in finalize (fun () -> Padding.pad (Bigstring_slice.wrap_bigstring x) block_len) (fun () -> Lwt_bytes.unsafe_destroy x) in Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.encrypt cipher bs) >>= fun () -> let res = Str.last_chars (Lwt_bytes.to_string bs) block_len in Lwt.return res let hard_coded_iv = "\192\157V\025\215,(\236\017\226\209E\205v\159\\" let () = assert (String.length hard_coded_iv = 16) let maybe_encrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id plain = let open Encryption in match encryption with | NoEncryption -> Lwt.return (plain, None) | AlgoWithKey (AES (CBC, L256) as algo, key) -> verify_key_length algo key; let block_len = block_length algo in let bs = finalize (fun () -> Padding.pad (Bigstring_slice.wrap_bigstring plain) block_len) (fun () -> Lwt_bytes.unsafe_destroy plain) in get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id >>= fun iv -> Cipher.with_t_lwt key Cipher.AES256 Cipher.CBC [] (fun cipher -> Cipher.set_iv cipher iv; Cipher.encrypt cipher bs) >>= fun () -> Lwt.return (bs, None) | AlgoWithKey (AES (CTR, L256) as algo, key) -> verify_key_length algo key; let iv = get_random_string 16 in TODO this is not optimal for security of the encryption ! let iv = hard_coded_iv in Cipher.with_t_lwt key Cipher.AES256 Cipher.CTR [] (fun cipher -> Cipher.set_ctr cipher iv; Cipher.encrypt cipher plain) >>= fun () -> Lwt.return (plain, Some iv) let maybe_decrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id ~fragment_ctr data = let open Encryption in match encryption with | NoEncryption -> Lwt.return (Bigstring_slice.wrap_bigstring data) | AlgoWithKey (algo, key) -> let decrypt mode set_iv_ctr = Encryption.verify_key_length algo key; Cipher.with_t_lwt key Cipher.AES256 mode [] (fun cipher -> set_iv_ctr cipher; Cipher.decrypt_detached cipher data 0 (Lwt_bytes.length data) ) in begin match algo with | AES (CBC, L256) -> get_iv key ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id >>= fun iv -> decrypt Cipher.CBC (fun h -> Cipher.set_iv h iv) >>= fun () -> Lwt.return (Padding.unpad data) | AES (CTR, L256) -> decrypt Cipher.CTR (fun h -> Cipher.set_ctr h (Option.get_some fragment_ctr)) >>= fun () -> Lwt.return (Bigstring_slice.wrap_bigstring data) end let maybe_partial_decrypt encryption ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id ~fragment_ctr (data, offset, length) ~fragment_offset = let open Encryption in match encryption with | NoEncryption -> Lwt.return () | AlgoWithKey (algo, key) -> begin match algo with | AES (CBC, _) -> Lwt.fail_with "can't do partial decrypt for AES CBC" | AES (CTR, L256) -> Cipher.(with_t_lwt key AES256 CTR [] (fun handle -> set_ctr_with_offset handle (Option.get_some fragment_ctr) fragment_offset; decrypt_detached handle data offset length)) end let maybe_compress compression fragment_data = let open Lwt.Infix in Compressors.compress compression fragment_data >>= fun r -> Lwt_log.debug_f "compression: %s (%i => %i)" ([%show: Compression.t] compression) (Bigstring_slice.length fragment_data) (Lwt_bytes.length r) >>= fun () -> Lwt.return r let maybe_decompress compression compressed = let open Lwt.Infix in let compressed_length = Bigstring_slice.length compressed in Compressors.decompress compression compressed >>= fun r -> Lwt_log.debug_f "decompression: %s (%i => %i)" ([%show: Compression.t] compression) compressed_length (Lwt_bytes.length r) >>= fun () -> Lwt.return r let verify fragment_data checksum = let () = Lwt_log.ign_debug_f ">>> verify fragment_data %i bytes @ %nX <<<" (Lwt_bytes.length fragment_data) (Lwt_bytes.raw_address fragment_data) in let algo = Checksum.algo_of checksum in let hash = Hashes.make_hash algo in hash # update_lwt_bytes_detached fragment_data 0 (Lwt_bytes.length fragment_data) >>= fun () -> let checksum2 = hash # final () in Lwt.return (checksum2 = checksum) let verify' fragment_data checksum = let algo = Checksum.algo_of checksum in let hash = Hashes.make_hash algo in let open Slice in hash # update_substring fragment_data.buf fragment_data.offset fragment_data.length; let checksum2 = hash # final () in Lwt.return (checksum2 = checksum) let pack_fragment (fragment : Bigstring_slice.t) ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id compression encryption checksum_algo = with_timing_lwt (fun () -> maybe_compress compression fragment >>= fun compressed -> maybe_encrypt ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id encryption compressed) >>= fun (t_compress_encrypt, (final_data, fragment_ctr)) -> with_timing_lwt (fun () -> let hash = Hashes.make_hash checksum_algo in hash # update_lwt_bytes_detached final_data 0 (Lwt_bytes.length final_data) >>= fun () -> Lwt.return (hash # final ())) >>= fun (t_hash, checksum) -> Lwt.return (final_data, t_compress_encrypt, t_hash, checksum, fragment_ctr) let chunk_to_data_fragments ~chunk ~chunk_size ~k = let fragment_size = chunk_size / k in let data_fragments = let rec inner acc = function | 0 -> acc | n -> let fragment = let pos = (n-1) * fragment_size in Bigstring_slice.from_bigstring chunk pos fragment_size in inner (fragment :: acc) (n - 1) in inner [] k in data_fragments let chunk_to_fragments_ec ~chunk ~chunk_size ~k ~m ~w' = let fragment_size = chunk_size / k in Lwt_log.debug_f "chunk_to_fragments: chunk @ %nX chunk_size = %i ; fragment_size = %i" (Lwt_bytes.raw_address chunk) chunk_size fragment_size >>= fun () -> assert (chunk_size mod (Fragment_size_helper.fragment_multiple * k) = 0); let data_fragments = chunk_to_data_fragments ~chunk ~chunk_size ~k in let coding_fragments = let rec inner acc = function | 0 -> acc | n -> let fragment = let msg = Printf.sprintf "coding_fragment:%i" n in Bigstring_slice.create ~msg fragment_size in inner (fragment :: acc) (n - 1) in inner [] m in Erasure.encode ~k ~m ~w:w' data_fragments coding_fragments fragment_size >>= fun () -> Lwt.return (data_fragments, coding_fragments) returns new bigarrays * replication ( k=1 ) is a bit special though * replication (k=1) is a bit special though *) let chunk_to_packed_fragments ~object_id ~chunk_id ~chunk ~chunk_size ~k ~m ~w' ~compression ~encryption ~fragment_checksum_algo = if k = 1 then begin let fragment = Bigstring_slice.wrap_bigstring chunk in pack_fragment fragment ~object_id ~chunk_id ~fragment_id:0 ~ignore_fragment_id:true compression encryption fragment_checksum_algo >>= fun (packed, f1, f2, cs, ctr) -> let rec build_result acc = function | 0 -> acc | n -> let fragment_id = n - 1 in let acc' = (fragment_id, fragment, (packed, f1, f2, cs, ctr)) :: acc in build_result acc' (n-1) in Lwt.return ([ fragment; ], build_result [] (k+m)) end else begin chunk_to_fragments_ec ~chunk ~chunk_size ~k ~m ~w' >>= fun (data_fragments, coding_fragments) -> Lwt.finalize (fun () -> let all_fragments = List.append data_fragments coding_fragments in Lwt_list.mapi_p (fun fragment_id fragment -> pack_fragment fragment ~object_id ~chunk_id ~fragment_id ~ignore_fragment_id:false compression encryption fragment_checksum_algo >>= fun (packed, f1, f2, cs, ctr) -> Lwt.return (fragment_id, fragment, (packed, f1, f2, cs, ctr))) all_fragments >>= fun packed_fragments -> Lwt.return (data_fragments, packed_fragments)) (fun () -> List.iter (fun bss -> Lwt_bytes.unsafe_destroy ~msg:"chunk_to_packed_fragments cleanup coding_fragments" bss.Bigstring_slice.bs) coding_fragments; Lwt.return ()) end
ccd332ed0d519a90042e1496430f5fa156afd2cbc6f06c5326841dc71fd7e2f3
LightTable/LightTable
auto_complete.cljs
(ns lt.plugins.auto-complete "Provide any auto-complete related functionality" (:require [lt.object :as object] [lt.objs.keyboard :as keyboard] [lt.objs.command :as cmd] [lt.util.load :as load] [lt.objs.thread :as thread] [lt.objs.sidebar.command :as scmd] [lt.objs.editor.pool :as pool] [lt.objs.editor :as editor] [lt.objs.context :as ctx] [clojure.string :as string] [lt.util.js :refer [wait]] [lt.util.dom :as dom]) (:require-macros [lt.macros :refer [behavior defui background]])) (defn stream [str] (js/CodeMirror.StringStream. str)) (defn advance [s] (set! (.-start s) (.-pos s))) (defn next* [s] (.next s)) (defn current [s] (.current s)) (defn peek* [s] (.peek s)) (defn skip-space [s] (when (and (peek* s) (re-seq #"\s" (peek* s))) (.eatSpace s) (advance s))) (defn eat-while [s r] (.eatWhile s r)) (defn string->tokens [str pattern] (let [s (stream str) res (js-obj)] (skip-space s) (while (peek* s) (eat-while s pattern) (if-not (empty? (current s)) (do (aset res (current s) true) (advance s)) (do (next* s) (advance s))) (skip-space s)) (into-array (map #(do #js {:completion %}) (js/Object.keys res))))) (def default-pattern #"[\w_$]") (defn get-pattern [ed] (let [mode (editor/inner-mode ed)] (or (:hint-pattern @ed) (aget mode "hint-pattern") default-pattern))) (defn get-token [ed pos] (let [line (editor/line ed (:line pos)) pattern (get-pattern ed) s (stream line) ch (:ch pos)] (skip-space s) (loop [] (eat-while s pattern) (if (and (not (empty? (current s))) (<= (.-start s) ch) (>= (.-pos s) ch)) {:start (.-start s) :end (.-pos s) :line (:line pos) :string (current s)} (if-not (peek* s) {:line (:line pos) :start (:ch pos) :end (:ch pos)} (do (next* s) (advance s) (skip-space s) (recur))))))) (defn non-token-change? [ed ch] (let [pattern (get-pattern ed) text (map str (.-text ch))] (condp = (.-origin ch) "+input" (some #(not (re-seq pattern %)) text) "paste" true false))) (def w (background (fn [obj-id m] (.log js/console "M:" (pr-str obj-id) (pr-str m)) (let [StringStream (-> (js/require (str js/ltpath "/core/node_modules/codemirror/addon/runmode/runmode.node.js")) (.-StringStream)) stream (fn [s] (StringStream. s)) advance (fn [s] (set! (.-start s) (.-pos s))) next* (fn [s] (.next s)) peek* (fn [s] (.peek s)) current (fn [s] (.current s)) skip-space (fn [s] (when (and (peek* s) (re-seq #"\s" (peek* s))) (.eatSpace s) (advance s))) eat-while (fn [s r] (.eatWhile s r)) string->tokens (fn [str pattern] (.log js/console "PATTERN" (pr-str pattern)) (let [s (stream str) pattern (re-pattern pattern) res (js-obj)] (.log js/console "REPATTERN" (pr-str pattern)) (skip-space s) (while (peek* s) (eat-while s pattern) (if-not (empty? (current s)) (do (aset res (current s) true) (advance s)) (do (next* s) (advance s))) (skip-space s)) (into-array (map #(do #js {:completion %}) (js/Object.keys res)))))] (js/_send obj-id :hint-tokens (string->tokens (:string m) (:pattern m))))))) (defn async-hints [this] (when @this (w this {:string (editor/->val this) :pattern (.-source (get-pattern this))}))) (defn text|completion [x] (or (.-text x) (.-completion x))) (defn text+completion [x] (str (.-text x) (.-completion x))) (defn distinct-completions [hints] (let [seen #js {}] (filter (fn [hint] (if (true? (aget seen (.-completion hint))) false (aset seen (.-completion hint) true))) hints))) (declare hinter) (defn remove-long-completions [hints] (filter #(< (.-length (.-completion %)) (:hint-limit @hinter)) hints)) (def hinter (-> (scmd/filter-list {:items (fn [] (when-let [cur (pool/last-active)] (let [token (-> @hinter :starting-token :string)] (->> (if token (remove #(= token (.-completion %)) (object/raise-reduce cur :hints+ [] token)) (object/raise-reduce cur :hints+ [])) remove-long-completions distinct-completions)))) :key text|completion}) (object/add-tags [:hinter]))) (defn on-line-change [line ch] (object/raise hinter :line-change line ch)) (behavior ::set-hint-limit :triggers #{:object.instant} :type :user :desc "Auto-complete: Set maximum length of an autocomplete hint" :params [{:label "Number" :example 1000}] :reaction (fn [this n] (object/merge! this {:hint-limit n}))) (behavior ::textual-hints :triggers #{:hints+} :reaction (fn [this hints] (concat (::hints @this) hints))) (behavior ::escape! :triggers #{:escape!} :reaction (fn [this force?] (let [elem (object/->content this)] (when (:line @this) (js/CodeMirror.off (:line @this) "change" on-line-change)) (ctx/out! [:editor.keys.hinting.active]) (object/merge! this {:active false :selected 0 :ed nil :starting-token nil :token nil :search ""}) (object/raise this :inactive) (when (dom/parent elem) (dom/remove elem))))) (behavior ::select :triggers #{:select} :reaction (fn [this c] (let [token (:token @this) start {:line (:line token) :ch (:start token)} end {:line (:line token) :ch (:end token)}] (object/merge! this {:active false}) (if (.-select c) ((.-select c) (partial editor/replace (:ed @this) start end) c) (editor/replace (:ed @this) start end (.-completion c))) (object/raise this :escape!)))) (behavior ::select-unknown :triggers #{:select-unknown} :reaction (fn [this v] (object/raise this :escape!) (keyboard/passthrough))) (behavior ::line-change :triggers #{:line-change} :reaction (fn [this l c] (when (:active @hinter) (let [pos (editor/->cursor (:ed @this)) token (get-token (:ed @this) pos)] (if (or (non-token-change? (:ed @this) c) (< (:ch pos) (-> @hinter :starting-token :start))) (object/raise hinter :escape!) (do (object/raise hinter :change! (:string token)) (if (= 0 (count (:cur @hinter))) (ctx/out! [:editor.keys.hinting.active :filter-list.input]) (when-not (ctx/in? :editor.keys.hinting.active) (ctx/in! [:filter-list.input] hinter) (ctx/in! [:editor.keys.hinting.active] (:ed @hinter)))) (object/merge! hinter {:token token}))))))) (behavior ::async-hint-tokens :triggers #{:hint-tokens} :reaction (fn [this tokens] (object/merge! this {::hints tokens}))) (behavior ::intra-buffer-string-hints :triggers #{:change} :debounce 400 :reaction (fn [this ch] (when (or (not= (:ed @hinter) this) (not (:active @hinter))) (async-hints this)) )) (defn start-hinting ([this] (start-hinting this nil)) ([this opts] (let [pos (editor/->cursor this) token (get-token this pos) line (editor/line-handle this (:line pos)) elem (object/->content hinter)] (ctx/in! [:editor.keys.hinting.active] this) (object/merge! hinter {:token token :starting-token token :ed this :active true :line line}) (object/raise hinter :change! (:string token)) (object/raise hinter :active) (let [count (count (:cur @hinter))] (cond (= 0 count) (ctx/out! [:editor.keys.hinting.active :filter-list.input]) (and (= 1 count) (:select-single opts)) (object/raise hinter :select! 0) :else (do (js/CodeMirror.on line "change" on-line-change) (dom/append (dom/$ :body) elem) (js/CodeMirror.positionHint (editor/->cm-ed this) elem (:start token)))))))) (behavior ::show-hint :triggers #{:hint} :reaction (fn [this opts] (let [cur (string/trim (editor/get-char this -1)) opts (merge {:select-single true} opts)] (cond (and (:active @hinter) (= (:ed @hinter) this)) (object/raise hinter :select!) (and (empty? cur) (not (:force? opts))) (keyboard/passthrough) (:active @hinter) (do (object/raise hinter :escape!) (start-hinting this)) :else (start-hinting this opts))))) (behavior ::remove-on-scroll-inactive :triggers #{:scroll :inactive} :reaction (fn [this] (when (:active @hinter) (object/raise hinter :escape!)))) (behavior ::remove-on-move-line :triggers #{:move} :reaction (fn [this c] (when (:active @hinter) ;;HACK: line change events are sent *after* cursor move ;;this means that we need to wait for those to fire and then ;;check if we're out of bounds. (wait 0 (fn [] (let [starting (:starting-token @hinter) cur (:token @hinter) cursor (editor/->cursor this)] (when (and starting cur (or (not (<= (:start cur) (:ch cursor) (:end cur))) (not= (:line starting) (:line cursor)))) (object/raise hinter :escape!)))))))) (behavior ::auto-show-on-input :triggers #{:input} :type :user :desc "Auto-complete: Show on change" :reaction (fn [this _ ch] (when-not (non-token-change? this ch) (when-not (and (:active @hinter) (= (:ed @hinter) this)) (object/raise this :hint {:select-single false}))))) (cmd/command {:command :auto-complete.remove :hidden true :desc "Editor: Auto complete hide" :exec (fn [] (when (:active @hinter) (object/raise hinter :escape!)) (keyboard/passthrough))}) (cmd/command {:command :auto-complete :hidden true :desc "Editor: Auto complete" :exec (fn [] (let [ed (pool/last-active)] (if-not (editor/selection? ed) (object/raise ed :hint) (keyboard/passthrough))))}) (cmd/command {:command :auto-complete.force :hidden true :desc "Editor: Force auto complete" :exec (fn [] (let [ed (pool/last-active)] (object/raise ed :hint {:force? true})))}) ;;********************************************************* ;; Mode extensions ;;********************************************************* (behavior ::init :triggers #{:init} :reaction (fn [this] (load/js "core/node_modules/codemirror_addons/show-hint.js" :sync) (js/CodeMirror.extendMode "clojure" (clj->js {:hint-pattern #"[\w\-\>\:\*\$\?\<\!\+\.\/foo]"})) (js/CodeMirror.extendMode "text/x-clojurescript" (clj->js {:hint-pattern #"[\w\-\>\:\*\$\?\<\!\+\.\/foo]"})) (js/CodeMirror.extendMode "css" (clj->js {:hint-pattern #"[\w\.\-\#]"})) ))
null
https://raw.githubusercontent.com/LightTable/LightTable/3760844132a17fb0c9cf3f3b099905865aed7e3b/src/lt/plugins/auto_complete.cljs
clojure
HACK: line change events are sent *after* cursor move this means that we need to wait for those to fire and then check if we're out of bounds. ********************************************************* Mode extensions *********************************************************
(ns lt.plugins.auto-complete "Provide any auto-complete related functionality" (:require [lt.object :as object] [lt.objs.keyboard :as keyboard] [lt.objs.command :as cmd] [lt.util.load :as load] [lt.objs.thread :as thread] [lt.objs.sidebar.command :as scmd] [lt.objs.editor.pool :as pool] [lt.objs.editor :as editor] [lt.objs.context :as ctx] [clojure.string :as string] [lt.util.js :refer [wait]] [lt.util.dom :as dom]) (:require-macros [lt.macros :refer [behavior defui background]])) (defn stream [str] (js/CodeMirror.StringStream. str)) (defn advance [s] (set! (.-start s) (.-pos s))) (defn next* [s] (.next s)) (defn current [s] (.current s)) (defn peek* [s] (.peek s)) (defn skip-space [s] (when (and (peek* s) (re-seq #"\s" (peek* s))) (.eatSpace s) (advance s))) (defn eat-while [s r] (.eatWhile s r)) (defn string->tokens [str pattern] (let [s (stream str) res (js-obj)] (skip-space s) (while (peek* s) (eat-while s pattern) (if-not (empty? (current s)) (do (aset res (current s) true) (advance s)) (do (next* s) (advance s))) (skip-space s)) (into-array (map #(do #js {:completion %}) (js/Object.keys res))))) (def default-pattern #"[\w_$]") (defn get-pattern [ed] (let [mode (editor/inner-mode ed)] (or (:hint-pattern @ed) (aget mode "hint-pattern") default-pattern))) (defn get-token [ed pos] (let [line (editor/line ed (:line pos)) pattern (get-pattern ed) s (stream line) ch (:ch pos)] (skip-space s) (loop [] (eat-while s pattern) (if (and (not (empty? (current s))) (<= (.-start s) ch) (>= (.-pos s) ch)) {:start (.-start s) :end (.-pos s) :line (:line pos) :string (current s)} (if-not (peek* s) {:line (:line pos) :start (:ch pos) :end (:ch pos)} (do (next* s) (advance s) (skip-space s) (recur))))))) (defn non-token-change? [ed ch] (let [pattern (get-pattern ed) text (map str (.-text ch))] (condp = (.-origin ch) "+input" (some #(not (re-seq pattern %)) text) "paste" true false))) (def w (background (fn [obj-id m] (.log js/console "M:" (pr-str obj-id) (pr-str m)) (let [StringStream (-> (js/require (str js/ltpath "/core/node_modules/codemirror/addon/runmode/runmode.node.js")) (.-StringStream)) stream (fn [s] (StringStream. s)) advance (fn [s] (set! (.-start s) (.-pos s))) next* (fn [s] (.next s)) peek* (fn [s] (.peek s)) current (fn [s] (.current s)) skip-space (fn [s] (when (and (peek* s) (re-seq #"\s" (peek* s))) (.eatSpace s) (advance s))) eat-while (fn [s r] (.eatWhile s r)) string->tokens (fn [str pattern] (.log js/console "PATTERN" (pr-str pattern)) (let [s (stream str) pattern (re-pattern pattern) res (js-obj)] (.log js/console "REPATTERN" (pr-str pattern)) (skip-space s) (while (peek* s) (eat-while s pattern) (if-not (empty? (current s)) (do (aset res (current s) true) (advance s)) (do (next* s) (advance s))) (skip-space s)) (into-array (map #(do #js {:completion %}) (js/Object.keys res)))))] (js/_send obj-id :hint-tokens (string->tokens (:string m) (:pattern m))))))) (defn async-hints [this] (when @this (w this {:string (editor/->val this) :pattern (.-source (get-pattern this))}))) (defn text|completion [x] (or (.-text x) (.-completion x))) (defn text+completion [x] (str (.-text x) (.-completion x))) (defn distinct-completions [hints] (let [seen #js {}] (filter (fn [hint] (if (true? (aget seen (.-completion hint))) false (aset seen (.-completion hint) true))) hints))) (declare hinter) (defn remove-long-completions [hints] (filter #(< (.-length (.-completion %)) (:hint-limit @hinter)) hints)) (def hinter (-> (scmd/filter-list {:items (fn [] (when-let [cur (pool/last-active)] (let [token (-> @hinter :starting-token :string)] (->> (if token (remove #(= token (.-completion %)) (object/raise-reduce cur :hints+ [] token)) (object/raise-reduce cur :hints+ [])) remove-long-completions distinct-completions)))) :key text|completion}) (object/add-tags [:hinter]))) (defn on-line-change [line ch] (object/raise hinter :line-change line ch)) (behavior ::set-hint-limit :triggers #{:object.instant} :type :user :desc "Auto-complete: Set maximum length of an autocomplete hint" :params [{:label "Number" :example 1000}] :reaction (fn [this n] (object/merge! this {:hint-limit n}))) (behavior ::textual-hints :triggers #{:hints+} :reaction (fn [this hints] (concat (::hints @this) hints))) (behavior ::escape! :triggers #{:escape!} :reaction (fn [this force?] (let [elem (object/->content this)] (when (:line @this) (js/CodeMirror.off (:line @this) "change" on-line-change)) (ctx/out! [:editor.keys.hinting.active]) (object/merge! this {:active false :selected 0 :ed nil :starting-token nil :token nil :search ""}) (object/raise this :inactive) (when (dom/parent elem) (dom/remove elem))))) (behavior ::select :triggers #{:select} :reaction (fn [this c] (let [token (:token @this) start {:line (:line token) :ch (:start token)} end {:line (:line token) :ch (:end token)}] (object/merge! this {:active false}) (if (.-select c) ((.-select c) (partial editor/replace (:ed @this) start end) c) (editor/replace (:ed @this) start end (.-completion c))) (object/raise this :escape!)))) (behavior ::select-unknown :triggers #{:select-unknown} :reaction (fn [this v] (object/raise this :escape!) (keyboard/passthrough))) (behavior ::line-change :triggers #{:line-change} :reaction (fn [this l c] (when (:active @hinter) (let [pos (editor/->cursor (:ed @this)) token (get-token (:ed @this) pos)] (if (or (non-token-change? (:ed @this) c) (< (:ch pos) (-> @hinter :starting-token :start))) (object/raise hinter :escape!) (do (object/raise hinter :change! (:string token)) (if (= 0 (count (:cur @hinter))) (ctx/out! [:editor.keys.hinting.active :filter-list.input]) (when-not (ctx/in? :editor.keys.hinting.active) (ctx/in! [:filter-list.input] hinter) (ctx/in! [:editor.keys.hinting.active] (:ed @hinter)))) (object/merge! hinter {:token token}))))))) (behavior ::async-hint-tokens :triggers #{:hint-tokens} :reaction (fn [this tokens] (object/merge! this {::hints tokens}))) (behavior ::intra-buffer-string-hints :triggers #{:change} :debounce 400 :reaction (fn [this ch] (when (or (not= (:ed @hinter) this) (not (:active @hinter))) (async-hints this)) )) (defn start-hinting ([this] (start-hinting this nil)) ([this opts] (let [pos (editor/->cursor this) token (get-token this pos) line (editor/line-handle this (:line pos)) elem (object/->content hinter)] (ctx/in! [:editor.keys.hinting.active] this) (object/merge! hinter {:token token :starting-token token :ed this :active true :line line}) (object/raise hinter :change! (:string token)) (object/raise hinter :active) (let [count (count (:cur @hinter))] (cond (= 0 count) (ctx/out! [:editor.keys.hinting.active :filter-list.input]) (and (= 1 count) (:select-single opts)) (object/raise hinter :select! 0) :else (do (js/CodeMirror.on line "change" on-line-change) (dom/append (dom/$ :body) elem) (js/CodeMirror.positionHint (editor/->cm-ed this) elem (:start token)))))))) (behavior ::show-hint :triggers #{:hint} :reaction (fn [this opts] (let [cur (string/trim (editor/get-char this -1)) opts (merge {:select-single true} opts)] (cond (and (:active @hinter) (= (:ed @hinter) this)) (object/raise hinter :select!) (and (empty? cur) (not (:force? opts))) (keyboard/passthrough) (:active @hinter) (do (object/raise hinter :escape!) (start-hinting this)) :else (start-hinting this opts))))) (behavior ::remove-on-scroll-inactive :triggers #{:scroll :inactive} :reaction (fn [this] (when (:active @hinter) (object/raise hinter :escape!)))) (behavior ::remove-on-move-line :triggers #{:move} :reaction (fn [this c] (when (:active @hinter) (wait 0 (fn [] (let [starting (:starting-token @hinter) cur (:token @hinter) cursor (editor/->cursor this)] (when (and starting cur (or (not (<= (:start cur) (:ch cursor) (:end cur))) (not= (:line starting) (:line cursor)))) (object/raise hinter :escape!)))))))) (behavior ::auto-show-on-input :triggers #{:input} :type :user :desc "Auto-complete: Show on change" :reaction (fn [this _ ch] (when-not (non-token-change? this ch) (when-not (and (:active @hinter) (= (:ed @hinter) this)) (object/raise this :hint {:select-single false}))))) (cmd/command {:command :auto-complete.remove :hidden true :desc "Editor: Auto complete hide" :exec (fn [] (when (:active @hinter) (object/raise hinter :escape!)) (keyboard/passthrough))}) (cmd/command {:command :auto-complete :hidden true :desc "Editor: Auto complete" :exec (fn [] (let [ed (pool/last-active)] (if-not (editor/selection? ed) (object/raise ed :hint) (keyboard/passthrough))))}) (cmd/command {:command :auto-complete.force :hidden true :desc "Editor: Force auto complete" :exec (fn [] (let [ed (pool/last-active)] (object/raise ed :hint {:force? true})))}) (behavior ::init :triggers #{:init} :reaction (fn [this] (load/js "core/node_modules/codemirror_addons/show-hint.js" :sync) (js/CodeMirror.extendMode "clojure" (clj->js {:hint-pattern #"[\w\-\>\:\*\$\?\<\!\+\.\/foo]"})) (js/CodeMirror.extendMode "text/x-clojurescript" (clj->js {:hint-pattern #"[\w\-\>\:\*\$\?\<\!\+\.\/foo]"})) (js/CodeMirror.extendMode "css" (clj->js {:hint-pattern #"[\w\.\-\#]"})) ))
a8dba04cc1a56175b81afae7ac3bc75d4083a822b6b8bcc77d3a21c42c1ff827
samply/blaze
arrays_support.clj
(ns blaze.db.impl.arrays-support "Reimplementation of some of `jdk.internal.util/ArraysSupport` functionality") (set! *unchecked-math* :warn-on-boxed) (def ^:const ^long soft-max-array-length (- Integer/MAX_VALUE 8)) (defn- huge-length ^long [^long old-length ^long min-growth] (let [min-length (+ old-length min-growth)] (when (< Integer/MAX_VALUE min-length) (throw (OutOfMemoryError. (format "Required array length %d + %d is too large" old-length (max min-growth min-growth))))) min-length)) (defn new-length "Computes a new array length given an array's current length, a minimum growth amount, and a preferred growth amount. This method is used by objects that contain an array that might need to be grown in order to fulfill some immediate need (the minimum growth amount) but would also like to request more space (the preferred growth amount) in order to accommodate potential future needs. The returned length is usually clamped at the soft maximum length in order to avoid hitting the JVM implementation limit. However, the soft maximum will be exceeded if the minimum growth amount requires it. If the preferred growth amount is less than the minimum growth amount, the minimum growth amount is used as the preferred growth amount. The preferred length is determined by adding the preferred growth amount to the current length. If the preferred length does not exceed the soft maximum length (`soft-max-array-length`) then the preferred length is returned. If the preferred length exceeds the soft maximum, we use the minimum growth amount. The minimum required length is determined by adding the minimum growth amount to the current length. If the minimum required length exceeds `Integer/MAX_VALUE`, then this method throws an `OutOfMemoryError`. Otherwise, this method returns the greater of the soft maximum or the minimum required length." ^long [^long old-length ^long min-growth ^long pref-growth] (let [pref-length (+ old-length (max min-growth pref-growth))] (if (<= pref-length soft-max-array-length) pref-length (huge-length old-length min-growth))))
null
https://raw.githubusercontent.com/samply/blaze/cbf6431a254f347a704f1abe1de4f4fe8a249ac9/modules/db/src/blaze/db/impl/arrays_support.clj
clojure
(ns blaze.db.impl.arrays-support "Reimplementation of some of `jdk.internal.util/ArraysSupport` functionality") (set! *unchecked-math* :warn-on-boxed) (def ^:const ^long soft-max-array-length (- Integer/MAX_VALUE 8)) (defn- huge-length ^long [^long old-length ^long min-growth] (let [min-length (+ old-length min-growth)] (when (< Integer/MAX_VALUE min-length) (throw (OutOfMemoryError. (format "Required array length %d + %d is too large" old-length (max min-growth min-growth))))) min-length)) (defn new-length "Computes a new array length given an array's current length, a minimum growth amount, and a preferred growth amount. This method is used by objects that contain an array that might need to be grown in order to fulfill some immediate need (the minimum growth amount) but would also like to request more space (the preferred growth amount) in order to accommodate potential future needs. The returned length is usually clamped at the soft maximum length in order to avoid hitting the JVM implementation limit. However, the soft maximum will be exceeded if the minimum growth amount requires it. If the preferred growth amount is less than the minimum growth amount, the minimum growth amount is used as the preferred growth amount. The preferred length is determined by adding the preferred growth amount to the current length. If the preferred length does not exceed the soft maximum length (`soft-max-array-length`) then the preferred length is returned. If the preferred length exceeds the soft maximum, we use the minimum growth amount. The minimum required length is determined by adding the minimum growth amount to the current length. If the minimum required length exceeds `Integer/MAX_VALUE`, then this method throws an `OutOfMemoryError`. Otherwise, this method returns the greater of the soft maximum or the minimum required length." ^long [^long old-length ^long min-growth ^long pref-growth] (let [pref-length (+ old-length (max min-growth pref-growth))] (if (<= pref-length soft-max-array-length) pref-length (huge-length old-length min-growth))))
02241836e3c4d88a86dc61ddc9a95ac4bcda67ba8c359ed8a45a2b618d05fcc2
zarkone/stumpwm.d
package.lisp
package.lisp (defpackage #:passwd (:use #:cl :stumpwm-user ))
null
https://raw.githubusercontent.com/zarkone/stumpwm.d/021e51c98a80783df1345826ac9390b44a7d0aae/modules/util/passwd/package.lisp
lisp
package.lisp (defpackage #:passwd (:use #:cl :stumpwm-user ))
47aca2cb51b178d0f1c35fba3498064edf8a1663f72c4c97a39a21d6f1fcf32b
imdea-software/leap
test_unionfind.ml
(***********************************************************************) (* *) LEAP (* *) , IMDEA Software Institute (* *) (* *) Copyright 2011 IMDEA Software Institute (* *) 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 *) (* *) (* -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. *) (* *) (***********************************************************************) module E = Expression let _ = let uf = LeapUnionFind.empty () in let var_t = E.build_global_var "t" E.Int in let var_v = E.build_global_var "v" E.Int in let var_a = E.build_global_var "a" E.Int in let var_b = E.build_global_var "b" E.Int in let var_c = E.build_global_var "c" E.Int in LeapUnionFind.add_new uf var_c; LeapUnionFind.add_new uf var_v; LeapUnionFind.union uf var_t var_a; LeapUnionFind.union uf var_v var_b; LeapUnionFind.union uf var_a var_b; print_endline (LeapUnionFind.to_str E.V.to_str uf); let sets = LeapUnionFind.gen_sets uf in print_endline "Generated sets:"; List.iter (fun s -> print_endline (LeapGenericSet.to_str E.V.to_str s) ) sets
null
https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/tests/test_unionfind.ml
ocaml
********************************************************************* You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************************
LEAP , IMDEA Software Institute Copyright 2011 IMDEA Software Institute Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , module E = Expression let _ = let uf = LeapUnionFind.empty () in let var_t = E.build_global_var "t" E.Int in let var_v = E.build_global_var "v" E.Int in let var_a = E.build_global_var "a" E.Int in let var_b = E.build_global_var "b" E.Int in let var_c = E.build_global_var "c" E.Int in LeapUnionFind.add_new uf var_c; LeapUnionFind.add_new uf var_v; LeapUnionFind.union uf var_t var_a; LeapUnionFind.union uf var_v var_b; LeapUnionFind.union uf var_a var_b; print_endline (LeapUnionFind.to_str E.V.to_str uf); let sets = LeapUnionFind.gen_sets uf in print_endline "Generated sets:"; List.iter (fun s -> print_endline (LeapGenericSet.to_str E.V.to_str s) ) sets
5a39ca2dbf8bdffdc553e4f8fc1d2aea19cb6a6c73ad570cc9c3792191f8cc20
ghc/packages-containers
seq-properties.hs
# LANGUAGE CPP # # LANGUAGE PatternGuards # #include "containers.h" import Data.Sequence.Internal ( Sized (..) , Seq (Seq) , FingerTree(..) , Node(..) , Elem(..) , Digit (..) , node2 , node3 , deep ) import Data.Sequence import Control.Applicative (Applicative(..), liftA2) import Control.Arrow ((***)) import Control.Monad.Trans.State.Strict import Data.Array (listArray) import Data.Foldable (Foldable(foldl, foldl1, foldr, foldr1, foldMap, fold), toList, all, sum, foldl', foldr') import Data.Functor ((<$>), (<$)) import Data.Maybe import Data.Function (on) import Data.Monoid (Monoid(..), All(..), Endo(..), Dual(..)) #if MIN_VERSION_base(4,9,0) import Data.Semigroup (stimes, stimesMonoid) #endif import Data.Traversable (Traversable(traverse), sequenceA) import Prelude hiding ( lookup, null, length, take, drop, splitAt, foldl, foldl1, foldr, foldr1, scanl, scanl1, scanr, scanr1, filter, reverse, replicate, zip, zipWith, zip3, zipWith3, all, sum) import qualified Prelude import qualified Data.List import Test.QuickCheck hiding ((><)) import Test.QuickCheck.Poly #if __GLASGOW_HASKELL__ >= 800 import Test.QuickCheck.Property #endif import Test.QuickCheck.Function import Test.Framework import Test.Framework.Providers.QuickCheck2 import Control.Monad.Zip (MonadZip (..)) import Control.DeepSeq (deepseq) import Control.Monad.Fix (MonadFix (..)) main :: IO () main = defaultMain [ testProperty "fmap" prop_fmap , testProperty "(<$)" prop_constmap , testProperty "foldr" prop_foldr , testProperty "foldr'" prop_foldr' , testProperty "lazy foldr'" prop_lazyfoldr' , testProperty "foldr1" prop_foldr1 , testProperty "foldl" prop_foldl , testProperty "foldl'" prop_foldl' , testProperty "lazy foldl'" prop_lazyfoldl' , testProperty "foldl1" prop_foldl1 , testProperty "(==)" prop_equals , testProperty "compare" prop_compare , testProperty "mappend" prop_mappend , testProperty "singleton" prop_singleton , testProperty "(<|)" prop_cons , testProperty "(|>)" prop_snoc , testProperty "(><)" prop_append , testProperty "fromList" prop_fromList , testProperty "fromFunction" prop_fromFunction , testProperty "fromArray" prop_fromArray , testProperty "replicate" prop_replicate , testProperty "replicateA" prop_replicateA , testProperty "replicateM" prop_replicateM , testProperty "iterateN" prop_iterateN , testProperty "unfoldr" prop_unfoldr , testProperty "unfoldl" prop_unfoldl , testProperty "null" prop_null , testProperty "length" prop_length , testProperty "viewl" prop_viewl , testProperty "viewr" prop_viewr , testProperty "scanl" prop_scanl , testProperty "scanl1" prop_scanl1 , testProperty "scanr" prop_scanr , testProperty "scanr1" prop_scanr1 , testProperty "tails" prop_tails , testProperty "inits" prop_inits , testProperty "takeWhileL" prop_takeWhileL , testProperty "takeWhileR" prop_takeWhileR , testProperty "dropWhileL" prop_dropWhileL , testProperty "dropWhileR" prop_dropWhileR , testProperty "spanl" prop_spanl , testProperty "spanr" prop_spanr , testProperty "breakl" prop_breakl , testProperty "breakr" prop_breakr , testProperty "partition" prop_partition , testProperty "filter" prop_filter , testProperty "sort" prop_sort , testProperty "sortStable" prop_sortStable , testProperty "sortBy" prop_sortBy , testProperty "sortOn" prop_sortOn , testProperty "sortOnStable" prop_sortOnStable , testProperty "unstableSort" prop_unstableSort , testProperty "unstableSortBy" prop_unstableSortBy , testProperty "unstableSortOn" prop_unstableSortOn , testProperty "index" prop_index , testProperty "(!?)" prop_safeIndex , testProperty "adjust" prop_adjust , testProperty "insertAt" prop_insertAt , testProperty "deleteAt" prop_deleteAt , testProperty "update" prop_update , testProperty "take" prop_take , testProperty "drop" prop_drop , testProperty "splitAt" prop_splitAt , testProperty "chunksOf" prop_chunksOf , testProperty "elemIndexL" prop_elemIndexL , testProperty "elemIndicesL" prop_elemIndicesL , testProperty "elemIndexR" prop_elemIndexR , testProperty "elemIndicesR" prop_elemIndicesR , testProperty "findIndexL" prop_findIndexL , testProperty "findIndicesL" prop_findIndicesL , testProperty "findIndexR" prop_findIndexR , testProperty "findIndicesR" prop_findIndicesR , testProperty "foldlWithIndex" prop_foldlWithIndex , testProperty "foldrWithIndex" prop_foldrWithIndex , testProperty "mapWithIndex" prop_mapWithIndex , testProperty "foldMapWithIndex/foldlWithIndex" prop_foldMapWithIndexL , testProperty "foldMapWithIndex/foldrWithIndex" prop_foldMapWithIndexR , testProperty "traverseWithIndex" prop_traverseWithIndex , testProperty "reverse" prop_reverse , testProperty "zip" prop_zip , testProperty "zipWith" prop_zipWith , testProperty "zip3" prop_zip3 , testProperty "zipWith3" prop_zipWith3 , testProperty "zip4" prop_zip4 , testProperty "zipWith4" prop_zipWith4 , testProperty "mzip-naturality" prop_mzipNaturality , testProperty "mzip-preservation" prop_mzipPreservation , testProperty "munzip-lazy" prop_munzipLazy , testProperty "<*>" prop_ap , testProperty "<*> NOINLINE" prop_ap_NOINLINE , testProperty "liftA2" prop_liftA2 , testProperty "*>" prop_then , testProperty "<*" prop_before , testProperty "cycleTaking" prop_cycleTaking , testProperty "intersperse" prop_intersperse , testProperty ">>=" prop_bind , testProperty "mfix" test_mfix #if __GLASGOW_HASKELL__ >= 800 , testProperty "Empty pattern" prop_empty_pat , testProperty "Empty constructor" prop_empty_con , testProperty "Left view pattern" prop_viewl_pat , testProperty "Left view constructor" prop_viewl_con , testProperty "Right view pattern" prop_viewr_pat , testProperty "Right view constructor" prop_viewr_con #endif #if MIN_VERSION_base(4,9,0) , testProperty "stimes" prop_stimes #endif ] ------------------------------------------------------------------------ -- Arbitrary ------------------------------------------------------------------------ instance Arbitrary a => Arbitrary (Seq a) where arbitrary = Seq <$> arbitrary shrink (Seq x) = map Seq (shrink x) instance Arbitrary a => Arbitrary (Elem a) where arbitrary = Elem <$> arbitrary instance (Arbitrary a, Sized a) => Arbitrary (FingerTree a) where arbitrary = sized arb where arb :: (Arbitrary b, Sized b) => Int -> Gen (FingerTree b) arb 0 = return EmptyT arb 1 = Single <$> arbitrary arb n = do pr <- arbitrary sf <- arbitrary let n_pr = Prelude.length (toList pr) let n_sf = Prelude.length (toList sf) adding n ` div ` 7 ensures that n_m > = 0 , and makes more Singles let n_m = max (n `div` 7) ((n - n_pr - n_sf) `div` 3) m <- arb n_m return $ deep pr m sf shrink (Deep _ (One a) EmptyT (One b)) = [Single a, Single b] shrink (Deep _ pr m sf) = [deep pr' m sf | pr' <- shrink pr] ++ [deep pr m' sf | m' <- shrink m] ++ [deep pr m sf' | sf' <- shrink sf] shrink (Single x) = map Single (shrink x) shrink EmptyT = [] instance (Arbitrary a, Sized a) => Arbitrary (Node a) where arbitrary = oneof [ node2 <$> arbitrary <*> arbitrary, node3 <$> arbitrary <*> arbitrary <*> arbitrary] shrink (Node2 _ a b) = [node2 a' b | a' <- shrink a] ++ [node2 a b' | b' <- shrink b] shrink (Node3 _ a b c) = [node2 a b, node2 a c, node2 b c] ++ [node3 a' b c | a' <- shrink a] ++ [node3 a b' c | b' <- shrink b] ++ [node3 a b c' | c' <- shrink c] instance Arbitrary a => Arbitrary (Digit a) where arbitrary = oneof [ One <$> arbitrary, Two <$> arbitrary <*> arbitrary, Three <$> arbitrary <*> arbitrary <*> arbitrary, Four <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary] shrink (One a) = map One (shrink a) shrink (Two a b) = [One a, One b] shrink (Three a b c) = [Two a b, Two a c, Two b c] shrink (Four a b c d) = [Three a b c, Three a b d, Three a c d, Three b c d] ------------------------------------------------------------------------ -- Valid trees ------------------------------------------------------------------------ class Valid a where valid :: a -> Bool instance Valid (Elem a) where valid _ = True instance Valid (Seq a) where valid (Seq xs) = valid xs instance (Sized a, Valid a) => Valid (FingerTree a) where valid EmptyT = True valid (Single x) = valid x valid (Deep s pr m sf) = s == size pr + size m + size sf && valid pr && valid m && valid sf instance (Sized a, Valid a) => Valid (Node a) where valid node = size node == sum (fmap size node) && all valid node instance Valid a => Valid (Digit a) where valid = all valid {-------------------------------------------------------------------- The general plan is to compare each function with a list equivalent. Each operation should produce a valid tree representing the same sequence as produced by its list counterpart on corresponding inputs. (The list versions are often lazier, but these properties ignore strictness.) --------------------------------------------------------------------} -- utilities for partial conversions infix 4 ~= (~=) :: Eq a => Maybe a -> a -> Bool (~=) = maybe (const False) (==) -- Partial conversion of an output sequence to a list. toList' :: Seq a -> Maybe [a] toList' xs | valid xs = Just (toList xs) | otherwise = Nothing toListList' :: Seq (Seq a) -> Maybe [[a]] toListList' xss = toList' xss >>= mapM toList' toListPair' :: (Seq a, Seq b) -> Maybe ([a], [b]) toListPair' (xs, ys) = (,) <$> toList' xs <*> toList' ys -- Extra "polymorphic" test type newtype D = D{ unD :: Integer } deriving ( Eq ) instance Show D where showsPrec n (D x) = showsPrec n x instance Arbitrary D where arbitrary = (D . (+1) . abs) `fmap` arbitrary shrink (D x) = [ D x' | x' <- shrink x, x' > 0 ] instance CoArbitrary D where coarbitrary = coarbitrary . unD -- instances prop_fmap :: Seq Int -> Bool prop_fmap xs = toList' (fmap f xs) ~= map f (toList xs) where f = (+100) prop_constmap :: A -> Seq A -> Bool prop_constmap x xs = toList' (x <$ xs) ~= map (const x) (toList xs) prop_foldr :: Seq A -> Property prop_foldr xs = foldr f z xs === Prelude.foldr f z (toList xs) where f = (:) z = [] prop_foldr' :: Seq A -> Property prop_foldr' xs = foldr' f z xs === foldr' f z (toList xs) where f = (:) z = [] prop_lazyfoldr' :: Seq () -> Property prop_lazyfoldr' xs = not (null xs) ==> foldr' (\e _ -> e) (error "Data.Sequence.foldr': should be lazy in initial accumulator") xs === () prop_foldr1 :: Seq Int -> Property prop_foldr1 xs = not (null xs) ==> foldr1 f xs == Data.List.foldr1 f (toList xs) where f = (-) prop_foldl :: Seq A -> Property prop_foldl xs = foldl f z xs === Prelude.foldl f z (toList xs) where f = flip (:) z = [] prop_foldl' :: Seq A -> Property prop_foldl' xs = foldl' f z xs === foldl' f z (toList xs) where f = flip (:) z = [] prop_lazyfoldl' :: Seq () -> Property prop_lazyfoldl' xs = not (null xs) ==> foldl' (\_ e -> e) (error "Data.Sequence.foldl': should be lazy in initial accumulator") xs === () prop_foldl1 :: Seq Int -> Property prop_foldl1 xs = not (null xs) ==> foldl1 f xs == Data.List.foldl1 f (toList xs) where f = (-) prop_equals :: Seq OrdA -> Seq OrdA -> Bool prop_equals xs ys = (xs == ys) == (toList xs == toList ys) prop_compare :: Seq OrdA -> Seq OrdA -> Bool prop_compare xs ys = compare xs ys == compare (toList xs) (toList ys) prop_mappend :: Seq A -> Seq A -> Bool prop_mappend xs ys = toList' (mappend xs ys) ~= toList xs ++ toList ys -- * Construction {- toList' empty ~= [] -} prop_singleton :: A -> Bool prop_singleton x = toList' (singleton x) ~= [x] prop_cons :: A -> Seq A -> Bool prop_cons x xs = toList' (x <| xs) ~= x : toList xs prop_snoc :: Seq A -> A -> Bool prop_snoc xs x = toList' (xs |> x) ~= toList xs ++ [x] prop_append :: Seq A -> Seq A -> Bool prop_append xs ys = toList' (xs >< ys) ~= toList xs ++ toList ys prop_fromList :: [A] -> Bool prop_fromList xs = toList' (fromList xs) ~= xs prop_fromFunction :: [A] -> Bool prop_fromFunction xs = toList' (fromFunction (Prelude.length xs) (xs!!)) ~= xs prop_fromArray :: [A] -> Bool prop_fromArray xs = toList' (fromArray (listArray (42, 42+Prelude.length xs-1) xs)) ~= xs -- ** Repetition prop_replicate :: NonNegative Int -> A -> Bool prop_replicate (NonNegative m) x = toList' (replicate n x) ~= Prelude.replicate n x where n = m `mod` 10000 prop_replicateA :: NonNegative Int -> Bool prop_replicateA (NonNegative m) = traverse toList' (replicateA n a) ~= sequenceA (Prelude.replicate n a) where n = m `mod` 10000 a = Action 1 0 :: M Int prop_replicateM :: NonNegative Int -> Bool prop_replicateM (NonNegative m) = traverse toList' (replicateM n a) ~= sequence (Prelude.replicate n a) where n = m `mod` 10000 a = Action 1 0 :: M Int -- ** Iterative construction prop_iterateN :: NonNegative Int -> Int -> Bool prop_iterateN (NonNegative m) x = toList' (iterateN n f x) ~= Prelude.take n (Prelude.iterate f x) where n = m `mod` 10000 f = (+1) prop_unfoldr :: [A] -> Bool prop_unfoldr z = toList' (unfoldr f z) ~= Data.List.unfoldr f z where f [] = Nothing f (x:xs) = Just (x, xs) prop_unfoldl :: [A] -> Bool prop_unfoldl z = toList' (unfoldl f z) ~= Data.List.reverse (Data.List.unfoldr (fmap swap . f) z) where f [] = Nothing f (x:xs) = Just (xs, x) swap (x,y) = (y,x) -- * Deconstruction -- ** Queries prop_null :: Seq A -> Bool prop_null xs = null xs == Prelude.null (toList xs) prop_length :: Seq A -> Bool prop_length xs = length xs == Prelude.length (toList xs) -- ** Views prop_viewl :: Seq A -> Bool prop_viewl xs = case viewl xs of EmptyL -> Prelude.null (toList xs) x :< xs' -> valid xs' && toList xs == x : toList xs' prop_viewr :: Seq A -> Bool prop_viewr xs = case viewr xs of EmptyR -> Prelude.null (toList xs) xs' :> x -> valid xs' && toList xs == toList xs' ++ [x] -- * Scans prop_scanl :: [A] -> Seq A -> Bool prop_scanl z xs = toList' (scanl f z xs) ~= Data.List.scanl f z (toList xs) where f = flip (:) prop_scanl1 :: Seq Int -> Property prop_scanl1 xs = not (null xs) ==> toList' (scanl1 f xs) ~= Data.List.scanl1 f (toList xs) where f = (-) prop_scanr :: [A] -> Seq A -> Bool prop_scanr z xs = toList' (scanr f z xs) ~= Data.List.scanr f z (toList xs) where f = (:) prop_scanr1 :: Seq Int -> Property prop_scanr1 xs = not (null xs) ==> toList' (scanr1 f xs) ~= Data.List.scanr1 f (toList xs) where f = (-) -- * Sublists prop_tails :: Seq A -> Bool prop_tails xs = toListList' (tails xs) ~= Data.List.tails (toList xs) prop_inits :: Seq A -> Bool prop_inits xs = toListList' (inits xs) ~= Data.List.inits (toList xs) -- ** Sequential searches -- We use predicates with varying density. prop_takeWhileL :: Positive Int -> Seq Int -> Bool prop_takeWhileL (Positive n) xs = toList' (takeWhileL p xs) ~= Prelude.takeWhile p (toList xs) where p x = x `mod` n == 0 prop_takeWhileR :: Positive Int -> Seq Int -> Bool prop_takeWhileR (Positive n) xs = toList' (takeWhileR p xs) ~= Prelude.reverse (Prelude.takeWhile p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_dropWhileL :: Positive Int -> Seq Int -> Bool prop_dropWhileL (Positive n) xs = toList' (dropWhileL p xs) ~= Prelude.dropWhile p (toList xs) where p x = x `mod` n == 0 prop_dropWhileR :: Positive Int -> Seq Int -> Bool prop_dropWhileR (Positive n) xs = toList' (dropWhileR p xs) ~= Prelude.reverse (Prelude.dropWhile p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_spanl :: Positive Int -> Seq Int -> Bool prop_spanl (Positive n) xs = toListPair' (spanl p xs) ~= Data.List.span p (toList xs) where p x = x `mod` n == 0 prop_spanr :: Positive Int -> Seq Int -> Bool prop_spanr (Positive n) xs = toListPair' (spanr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.span p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_breakl :: Positive Int -> Seq Int -> Bool prop_breakl (Positive n) xs = toListPair' (breakl p xs) ~= Data.List.break p (toList xs) where p x = x `mod` n == 0 prop_breakr :: Positive Int -> Seq Int -> Bool prop_breakr (Positive n) xs = toListPair' (breakr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.break p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_partition :: Positive Int -> Seq Int -> Bool prop_partition (Positive n) xs = toListPair' (partition p xs) ~= Data.List.partition p (toList xs) where p x = x `mod` n == 0 prop_filter :: Positive Int -> Seq Int -> Bool prop_filter (Positive n) xs = toList' (filter p xs) ~= Prelude.filter p (toList xs) where p x = x `mod` n == 0 -- * Sorting prop_sort :: Seq OrdA -> Bool prop_sort xs = toList' (sort xs) ~= Data.List.sort (toList xs) data UnstableOrd = UnstableOrd { ordKey :: OrdA , _ignored :: A } deriving (Show) instance Eq UnstableOrd where x == y = compare x y == EQ instance Ord UnstableOrd where compare (UnstableOrd x _) (UnstableOrd y _) = compare x y instance Arbitrary UnstableOrd where arbitrary = liftA2 UnstableOrd arbitrary arbitrary shrink (UnstableOrd x y) = [ UnstableOrd x' y' | (x',y') <- shrink (x, y) ] prop_sortStable :: Seq UnstableOrd -> Bool prop_sortStable xs = (fmap . fmap) unignore (toList' (sort xs)) ~= fmap unignore (Data.List.sort (toList xs)) where unignore (UnstableOrd x y) = (x, y) prop_sortBy :: Seq (OrdA, B) -> Bool prop_sortBy xs = toList' (sortBy f xs) ~= Data.List.sortBy f (toList xs) where f (x1, _) (x2, _) = compare x1 x2 prop_sortOn :: Fun A OrdB -> Seq A -> Bool prop_sortOn (Fun _ f) xs = toList' (sortOn f xs) ~= listSortOn f (toList xs) where #if MIN_VERSION_base(4,8,0) listSortOn = Data.List.sortOn #else listSortOn k = Data.List.sortBy (compare `on` k) #endif prop_sortOnStable :: Fun A UnstableOrd -> Seq A -> Bool prop_sortOnStable (Fun _ f) xs = toList' (sortOn f xs) ~= listSortOn f (toList xs) where #if MIN_VERSION_base(4,8,0) listSortOn = Data.List.sortOn #else listSortOn k = Data.List.sortBy (compare `on` k) #endif prop_unstableSort :: Seq OrdA -> Bool prop_unstableSort xs = toList' (unstableSort xs) ~= Data.List.sort (toList xs) prop_unstableSortBy :: Seq OrdA -> Bool prop_unstableSortBy xs = toList' (unstableSortBy compare xs) ~= Data.List.sort (toList xs) prop_unstableSortOn :: Fun A OrdB -> Seq A -> Property prop_unstableSortOn (Fun _ f) xs = toList' (unstableSortBy (compare `on` f) xs) === toList' (unstableSortOn f xs) -- * Indexing prop_index :: Seq A -> Property prop_index xs = not (null xs) ==> forAll (choose (0, length xs-1)) $ \ i -> index xs i == toList xs !! i prop_safeIndex :: Seq A -> Property prop_safeIndex xs = forAll (choose (-3, length xs + 3)) $ \i -> ((i < 0 || i >= length xs) .&&. lookup i xs === Nothing) .||. lookup i xs === Just (toList xs !! i) prop_insertAt :: A -> Seq A -> Property prop_insertAt x xs = forAll (choose (-3, length xs + 3)) $ \i -> let res = insertAt i x xs in valid res .&&. res === case splitAt i xs of (front, back) -> front >< x <| back prop_deleteAt :: Seq A -> Property prop_deleteAt xs = forAll (choose (-3, length xs + 3)) $ \i -> let res = deleteAt i xs in valid res .&&. (((0 <= i && i < length xs) .&&. res === case splitAt i xs of (front, back) -> front >< drop 1 back) .||. ((i < 0 || i >= length xs) .&&. res === xs)) prop_adjust :: Int -> Int -> Seq Int -> Bool prop_adjust n i xs = toList' (adjust f i xs) ~= adjustList f i (toList xs) where f = (+n) prop_update :: Int -> A -> Seq A -> Bool prop_update i x xs = toList' (update i x xs) ~= adjustList (const x) i (toList xs) prop_take :: Int -> Seq A -> Bool prop_take n xs = toList' (take n xs) ~= Prelude.take n (toList xs) prop_drop :: Int -> Seq A -> Bool prop_drop n xs = toList' (drop n xs) ~= Prelude.drop n (toList xs) prop_splitAt :: Int -> Seq A -> Bool prop_splitAt n xs = toListPair' (splitAt n xs) ~= Prelude.splitAt n (toList xs) prop_chunksOf :: Seq A -> Property prop_chunksOf xs = forAll (choose (1, length xs + 3)) $ \n -> let chunks = chunksOf n xs in valid chunks .&&. conjoin [valid c .&&. 1 <= length c && length c <= n | c <- toList chunks] .&&. fold chunks === xs adjustList :: (a -> a) -> Int -> [a] -> [a] adjustList f i xs = [if j == i then f x else x | (j, x) <- Prelude.zip [0..] xs] -- ** Indexing with predicates -- The elem* tests have poor coverage, but for find* we use predicates -- of varying density. prop_elemIndexL :: A -> Seq A -> Bool prop_elemIndexL x xs = elemIndexL x xs == Data.List.elemIndex x (toList xs) prop_elemIndicesL :: A -> Seq A -> Bool prop_elemIndicesL x xs = elemIndicesL x xs == Data.List.elemIndices x (toList xs) prop_elemIndexR :: A -> Seq A -> Bool prop_elemIndexR x xs = elemIndexR x xs == listToMaybe (Prelude.reverse (Data.List.elemIndices x (toList xs))) prop_elemIndicesR :: A -> Seq A -> Bool prop_elemIndicesR x xs = elemIndicesR x xs == Prelude.reverse (Data.List.elemIndices x (toList xs)) prop_findIndexL :: Positive Int -> Seq Int -> Bool prop_findIndexL (Positive n) xs = findIndexL p xs == Data.List.findIndex p (toList xs) where p x = x `mod` n == 0 prop_findIndicesL :: Positive Int -> Seq Int -> Bool prop_findIndicesL (Positive n) xs = findIndicesL p xs == Data.List.findIndices p (toList xs) where p x = x `mod` n == 0 prop_findIndexR :: Positive Int -> Seq Int -> Bool prop_findIndexR (Positive n) xs = findIndexR p xs == listToMaybe (Prelude.reverse (Data.List.findIndices p (toList xs))) where p x = x `mod` n == 0 prop_findIndicesR :: Positive Int -> Seq Int -> Bool prop_findIndicesR (Positive n) xs = findIndicesR p xs == Prelude.reverse (Data.List.findIndices p (toList xs)) where p x = x `mod` n == 0 -- * Folds prop_foldlWithIndex :: [(Int, A)] -> Seq A -> Bool prop_foldlWithIndex z xs = foldlWithIndex f z xs == Data.List.foldl (uncurry . f) z (Data.List.zip [0..] (toList xs)) where f ys n y = (n,y):ys prop_foldrWithIndex :: [(Int, A)] -> Seq A -> Bool prop_foldrWithIndex z xs = foldrWithIndex f z xs == Data.List.foldr (uncurry f) z (Data.List.zip [0..] (toList xs)) where f n y ys = (n,y):ys prop_foldMapWithIndexL :: (Fun (B, Int, A) B) -> B -> Seq A -> Bool prop_foldMapWithIndexL (Fun _ f) z t = foldlWithIndex f' z t == appEndo (getDual (foldMapWithIndex (\i -> Dual . Endo . flip (flip f' i)) t)) z where f' b i a = f (b, i, a) prop_foldMapWithIndexR :: (Fun (Int, A, B) B) -> B -> Seq A -> Bool prop_foldMapWithIndexR (Fun _ f) z t = foldrWithIndex f' z t == appEndo (foldMapWithIndex (\i -> Endo . f' i) t) z where f' i a b = f (i, a, b) -- * Transformations prop_mapWithIndex :: Seq A -> Bool prop_mapWithIndex xs = toList' (mapWithIndex f xs) ~= map (uncurry f) (Data.List.zip [0..] (toList xs)) where f = (,) prop_traverseWithIndex :: Seq Int -> Bool prop_traverseWithIndex xs = runState (traverseWithIndex (\i x -> modify ((i,x) :)) xs) [] == runState (sequenceA . mapWithIndex (\i x -> modify ((i,x) :)) $ xs) [] prop_reverse :: Seq A -> Bool prop_reverse xs = toList' (reverse xs) ~= Prelude.reverse (toList xs) * * prop_zip :: Seq A -> Seq B -> Bool prop_zip xs ys = toList' (zip xs ys) ~= Prelude.zip (toList xs) (toList ys) prop_zipWith :: Seq A -> Seq B -> Bool prop_zipWith xs ys = toList' (zipWith f xs ys) ~= Prelude.zipWith f (toList xs) (toList ys) where f = (,) prop_zip3 :: Seq A -> Seq B -> Seq C -> Bool prop_zip3 xs ys zs = toList' (zip3 xs ys zs) ~= Prelude.zip3 (toList xs) (toList ys) (toList zs) prop_zipWith3 :: Seq A -> Seq B -> Seq C -> Bool prop_zipWith3 xs ys zs = toList' (zipWith3 f xs ys zs) ~= Prelude.zipWith3 f (toList xs) (toList ys) (toList zs) where f = (,,) prop_zip4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool prop_zip4 xs ys zs ts = toList' (zip4 xs ys zs ts) ~= Data.List.zip4 (toList xs) (toList ys) (toList zs) (toList ts) prop_zipWith4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool prop_zipWith4 xs ys zs ts = toList' (zipWith4 f xs ys zs ts) ~= Data.List.zipWith4 f (toList xs) (toList ys) (toList zs) (toList ts) where f = (,,,) This comes straight from the MonadZip documentation prop_mzipNaturality :: Fun A C -> Fun B D -> Seq A -> Seq B -> Property prop_mzipNaturality f g sa sb = fmap (apply f *** apply g) (mzip sa sb) === mzip (apply f <$> sa) (apply g <$> sb) This is a slight optimization of the MonadZip preservation -- law that works because sequences don't have any decorations. prop_mzipPreservation :: Fun A B -> Seq A -> Property prop_mzipPreservation f sa = let sb = fmap (apply f) sa in munzip (mzip sa sb) === (sa, sb) -- We want to ensure that -- munzip xs = xs ` seq ` ( fmap fst x , fmap snd x ) -- -- even in the presence of bottoms (alternatives are all balance- -- fragile). prop_munzipLazy :: Seq (Integer, B) -> Bool prop_munzipLazy pairs = deepseq ((`seq` ()) <$> repaired) True where partialpairs = mapWithIndex (\i a -> update i err pairs) pairs firstPieces = fmap (fst . munzip) partialpairs repaired = mapWithIndex (\i s -> update i 10000 s) firstPieces err = error "munzip isn't lazy enough" -- Applicative operations prop_ap :: Seq A -> Seq B -> Bool prop_ap xs ys = toList' ((,) <$> xs <*> ys) ~= ( (,) <$> toList xs <*> toList ys ) prop_ap_NOINLINE :: Seq A -> Seq B -> Bool prop_ap_NOINLINE xs ys = toList' (((,) <$> xs) `apNOINLINE` ys) ~= ( (,) <$> toList xs <*> toList ys ) # NOINLINE apNOINLINE # apNOINLINE :: Seq (a -> b) -> Seq a -> Seq b apNOINLINE fs xs = fs <*> xs prop_liftA2 :: Seq A -> Seq B -> Property prop_liftA2 xs ys = valid q .&&. toList q === liftA2 (,) (toList xs) (toList ys) where q = liftA2 (,) xs ys prop_then :: Seq A -> Seq B -> Bool prop_then xs ys = toList' (xs *> ys) ~= (toList xs *> toList ys) We take only the length of the second sequence because -- the implementation throws the rest away; there's no -- point wasting test cases varying other aspects of that -- argument. prop_before :: Seq A -> NonNegative Int -> Bool prop_before xs (NonNegative lys) = toList' (xs <* ys) ~= (toList xs <* toList ys) where ys = replicate lys () prop_intersperse :: A -> Seq A -> Bool prop_intersperse x xs = toList' (intersperse x xs) ~= Data.List.intersperse x (toList xs) prop_cycleTaking :: Int -> Seq A -> Property prop_cycleTaking n xs = (n <= 0 || not (null xs)) ==> toList' (cycleTaking n xs) ~= Data.List.take n (Data.List.cycle (toList xs)) #if __GLASGOW_HASKELL__ >= 800 prop_empty_pat :: Seq A -> Bool prop_empty_pat xs@Empty = null xs prop_empty_pat xs = not (null xs) prop_empty_con :: Bool prop_empty_con = null Empty prop_viewl_pat :: Seq A -> Property prop_viewl_pat xs@(y :<| ys) | z :< zs <- viewl xs = y === z .&&. ys === zs | otherwise = property failed prop_viewl_pat xs = property . liftBool $ null xs prop_viewl_con :: A -> Seq A -> Property prop_viewl_con x xs = x :<| xs === x <| xs prop_viewr_pat :: Seq A -> Property prop_viewr_pat xs@(ys :|> y) | zs :> z <- viewr xs = y === z .&&. ys === zs | otherwise = property failed prop_viewr_pat xs = property . liftBool $ null xs prop_viewr_con :: Seq A -> A -> Property prop_viewr_con xs x = xs :|> x === xs |> x #endif Monad operations prop_bind :: Seq A -> Fun A (Seq B) -> Bool prop_bind xs (Fun _ f) = toList' (xs >>= f) ~= (toList xs >>= toList . f) -- Semigroup operations #if MIN_VERSION_base(4,9,0) prop_stimes :: NonNegative Int -> Seq A -> Property prop_stimes (NonNegative n) s = stimes n s === stimesMonoid n s #endif MonadFix operation It 's exceedingly difficult to construct a proper QuickCheck property for mfix because the function passed to it must be -- lazy. The following property is really just a unit test in -- disguise, and not a terribly meaningful one. test_mfix :: Property test_mfix = toList resS === resL where facty :: (Int -> Int) -> Int -> Int facty _ 0 = 1; facty f n = n * f (n - 1) resS :: Seq Int resS = fmap ($ 12) $ mfix (\f -> fromList [facty f, facty (+1), facty (+2)]) resL :: [Int] resL = fmap ($ 12) $ mfix (\f -> [facty f, facty (+1), facty (+2)]) -- Simple test monad data M a = Action Int a deriving (Eq, Show) instance Functor M where fmap f (Action n x) = Action n (f x) instance Applicative M where pure x = Action 0 x Action m f <*> Action n x = Action (m+n) (f x) instance Monad M where return x = Action 0 x Action m x >>= f = let Action n y = f x in Action (m+n) y instance Foldable M where foldMap f (Action _ x) = f x instance Traversable M where traverse f (Action n x) = Action n <$> f x
null
https://raw.githubusercontent.com/ghc/packages-containers/97fe43c54c5c8a9b93ecf5abd7509e8085b63d41/containers-tests/tests/seq-properties.hs
haskell
---------------------------------------------------------------------- Arbitrary ---------------------------------------------------------------------- ---------------------------------------------------------------------- Valid trees ---------------------------------------------------------------------- ------------------------------------------------------------------- The general plan is to compare each function with a list equivalent. Each operation should produce a valid tree representing the same sequence as produced by its list counterpart on corresponding inputs. (The list versions are often lazier, but these properties ignore strictness.) ------------------------------------------------------------------- utilities for partial conversions Partial conversion of an output sequence to a list. Extra "polymorphic" test type instances * Construction toList' empty ~= [] ** Repetition ** Iterative construction * Deconstruction ** Queries ** Views * Scans * Sublists ** Sequential searches We use predicates with varying density. * Sorting * Indexing ** Indexing with predicates The elem* tests have poor coverage, but for find* we use predicates of varying density. * Folds * Transformations law that works because sequences don't have any decorations. We want to ensure that even in the presence of bottoms (alternatives are all balance- fragile). Applicative operations the implementation throws the rest away; there's no point wasting test cases varying other aspects of that argument. Semigroup operations lazy. The following property is really just a unit test in disguise, and not a terribly meaningful one. Simple test monad
# LANGUAGE CPP # # LANGUAGE PatternGuards # #include "containers.h" import Data.Sequence.Internal ( Sized (..) , Seq (Seq) , FingerTree(..) , Node(..) , Elem(..) , Digit (..) , node2 , node3 , deep ) import Data.Sequence import Control.Applicative (Applicative(..), liftA2) import Control.Arrow ((***)) import Control.Monad.Trans.State.Strict import Data.Array (listArray) import Data.Foldable (Foldable(foldl, foldl1, foldr, foldr1, foldMap, fold), toList, all, sum, foldl', foldr') import Data.Functor ((<$>), (<$)) import Data.Maybe import Data.Function (on) import Data.Monoid (Monoid(..), All(..), Endo(..), Dual(..)) #if MIN_VERSION_base(4,9,0) import Data.Semigroup (stimes, stimesMonoid) #endif import Data.Traversable (Traversable(traverse), sequenceA) import Prelude hiding ( lookup, null, length, take, drop, splitAt, foldl, foldl1, foldr, foldr1, scanl, scanl1, scanr, scanr1, filter, reverse, replicate, zip, zipWith, zip3, zipWith3, all, sum) import qualified Prelude import qualified Data.List import Test.QuickCheck hiding ((><)) import Test.QuickCheck.Poly #if __GLASGOW_HASKELL__ >= 800 import Test.QuickCheck.Property #endif import Test.QuickCheck.Function import Test.Framework import Test.Framework.Providers.QuickCheck2 import Control.Monad.Zip (MonadZip (..)) import Control.DeepSeq (deepseq) import Control.Monad.Fix (MonadFix (..)) main :: IO () main = defaultMain [ testProperty "fmap" prop_fmap , testProperty "(<$)" prop_constmap , testProperty "foldr" prop_foldr , testProperty "foldr'" prop_foldr' , testProperty "lazy foldr'" prop_lazyfoldr' , testProperty "foldr1" prop_foldr1 , testProperty "foldl" prop_foldl , testProperty "foldl'" prop_foldl' , testProperty "lazy foldl'" prop_lazyfoldl' , testProperty "foldl1" prop_foldl1 , testProperty "(==)" prop_equals , testProperty "compare" prop_compare , testProperty "mappend" prop_mappend , testProperty "singleton" prop_singleton , testProperty "(<|)" prop_cons , testProperty "(|>)" prop_snoc , testProperty "(><)" prop_append , testProperty "fromList" prop_fromList , testProperty "fromFunction" prop_fromFunction , testProperty "fromArray" prop_fromArray , testProperty "replicate" prop_replicate , testProperty "replicateA" prop_replicateA , testProperty "replicateM" prop_replicateM , testProperty "iterateN" prop_iterateN , testProperty "unfoldr" prop_unfoldr , testProperty "unfoldl" prop_unfoldl , testProperty "null" prop_null , testProperty "length" prop_length , testProperty "viewl" prop_viewl , testProperty "viewr" prop_viewr , testProperty "scanl" prop_scanl , testProperty "scanl1" prop_scanl1 , testProperty "scanr" prop_scanr , testProperty "scanr1" prop_scanr1 , testProperty "tails" prop_tails , testProperty "inits" prop_inits , testProperty "takeWhileL" prop_takeWhileL , testProperty "takeWhileR" prop_takeWhileR , testProperty "dropWhileL" prop_dropWhileL , testProperty "dropWhileR" prop_dropWhileR , testProperty "spanl" prop_spanl , testProperty "spanr" prop_spanr , testProperty "breakl" prop_breakl , testProperty "breakr" prop_breakr , testProperty "partition" prop_partition , testProperty "filter" prop_filter , testProperty "sort" prop_sort , testProperty "sortStable" prop_sortStable , testProperty "sortBy" prop_sortBy , testProperty "sortOn" prop_sortOn , testProperty "sortOnStable" prop_sortOnStable , testProperty "unstableSort" prop_unstableSort , testProperty "unstableSortBy" prop_unstableSortBy , testProperty "unstableSortOn" prop_unstableSortOn , testProperty "index" prop_index , testProperty "(!?)" prop_safeIndex , testProperty "adjust" prop_adjust , testProperty "insertAt" prop_insertAt , testProperty "deleteAt" prop_deleteAt , testProperty "update" prop_update , testProperty "take" prop_take , testProperty "drop" prop_drop , testProperty "splitAt" prop_splitAt , testProperty "chunksOf" prop_chunksOf , testProperty "elemIndexL" prop_elemIndexL , testProperty "elemIndicesL" prop_elemIndicesL , testProperty "elemIndexR" prop_elemIndexR , testProperty "elemIndicesR" prop_elemIndicesR , testProperty "findIndexL" prop_findIndexL , testProperty "findIndicesL" prop_findIndicesL , testProperty "findIndexR" prop_findIndexR , testProperty "findIndicesR" prop_findIndicesR , testProperty "foldlWithIndex" prop_foldlWithIndex , testProperty "foldrWithIndex" prop_foldrWithIndex , testProperty "mapWithIndex" prop_mapWithIndex , testProperty "foldMapWithIndex/foldlWithIndex" prop_foldMapWithIndexL , testProperty "foldMapWithIndex/foldrWithIndex" prop_foldMapWithIndexR , testProperty "traverseWithIndex" prop_traverseWithIndex , testProperty "reverse" prop_reverse , testProperty "zip" prop_zip , testProperty "zipWith" prop_zipWith , testProperty "zip3" prop_zip3 , testProperty "zipWith3" prop_zipWith3 , testProperty "zip4" prop_zip4 , testProperty "zipWith4" prop_zipWith4 , testProperty "mzip-naturality" prop_mzipNaturality , testProperty "mzip-preservation" prop_mzipPreservation , testProperty "munzip-lazy" prop_munzipLazy , testProperty "<*>" prop_ap , testProperty "<*> NOINLINE" prop_ap_NOINLINE , testProperty "liftA2" prop_liftA2 , testProperty "*>" prop_then , testProperty "<*" prop_before , testProperty "cycleTaking" prop_cycleTaking , testProperty "intersperse" prop_intersperse , testProperty ">>=" prop_bind , testProperty "mfix" test_mfix #if __GLASGOW_HASKELL__ >= 800 , testProperty "Empty pattern" prop_empty_pat , testProperty "Empty constructor" prop_empty_con , testProperty "Left view pattern" prop_viewl_pat , testProperty "Left view constructor" prop_viewl_con , testProperty "Right view pattern" prop_viewr_pat , testProperty "Right view constructor" prop_viewr_con #endif #if MIN_VERSION_base(4,9,0) , testProperty "stimes" prop_stimes #endif ] instance Arbitrary a => Arbitrary (Seq a) where arbitrary = Seq <$> arbitrary shrink (Seq x) = map Seq (shrink x) instance Arbitrary a => Arbitrary (Elem a) where arbitrary = Elem <$> arbitrary instance (Arbitrary a, Sized a) => Arbitrary (FingerTree a) where arbitrary = sized arb where arb :: (Arbitrary b, Sized b) => Int -> Gen (FingerTree b) arb 0 = return EmptyT arb 1 = Single <$> arbitrary arb n = do pr <- arbitrary sf <- arbitrary let n_pr = Prelude.length (toList pr) let n_sf = Prelude.length (toList sf) adding n ` div ` 7 ensures that n_m > = 0 , and makes more Singles let n_m = max (n `div` 7) ((n - n_pr - n_sf) `div` 3) m <- arb n_m return $ deep pr m sf shrink (Deep _ (One a) EmptyT (One b)) = [Single a, Single b] shrink (Deep _ pr m sf) = [deep pr' m sf | pr' <- shrink pr] ++ [deep pr m' sf | m' <- shrink m] ++ [deep pr m sf' | sf' <- shrink sf] shrink (Single x) = map Single (shrink x) shrink EmptyT = [] instance (Arbitrary a, Sized a) => Arbitrary (Node a) where arbitrary = oneof [ node2 <$> arbitrary <*> arbitrary, node3 <$> arbitrary <*> arbitrary <*> arbitrary] shrink (Node2 _ a b) = [node2 a' b | a' <- shrink a] ++ [node2 a b' | b' <- shrink b] shrink (Node3 _ a b c) = [node2 a b, node2 a c, node2 b c] ++ [node3 a' b c | a' <- shrink a] ++ [node3 a b' c | b' <- shrink b] ++ [node3 a b c' | c' <- shrink c] instance Arbitrary a => Arbitrary (Digit a) where arbitrary = oneof [ One <$> arbitrary, Two <$> arbitrary <*> arbitrary, Three <$> arbitrary <*> arbitrary <*> arbitrary, Four <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary] shrink (One a) = map One (shrink a) shrink (Two a b) = [One a, One b] shrink (Three a b c) = [Two a b, Two a c, Two b c] shrink (Four a b c d) = [Three a b c, Three a b d, Three a c d, Three b c d] class Valid a where valid :: a -> Bool instance Valid (Elem a) where valid _ = True instance Valid (Seq a) where valid (Seq xs) = valid xs instance (Sized a, Valid a) => Valid (FingerTree a) where valid EmptyT = True valid (Single x) = valid x valid (Deep s pr m sf) = s == size pr + size m + size sf && valid pr && valid m && valid sf instance (Sized a, Valid a) => Valid (Node a) where valid node = size node == sum (fmap size node) && all valid node instance Valid a => Valid (Digit a) where valid = all valid infix 4 ~= (~=) :: Eq a => Maybe a -> a -> Bool (~=) = maybe (const False) (==) toList' :: Seq a -> Maybe [a] toList' xs | valid xs = Just (toList xs) | otherwise = Nothing toListList' :: Seq (Seq a) -> Maybe [[a]] toListList' xss = toList' xss >>= mapM toList' toListPair' :: (Seq a, Seq b) -> Maybe ([a], [b]) toListPair' (xs, ys) = (,) <$> toList' xs <*> toList' ys newtype D = D{ unD :: Integer } deriving ( Eq ) instance Show D where showsPrec n (D x) = showsPrec n x instance Arbitrary D where arbitrary = (D . (+1) . abs) `fmap` arbitrary shrink (D x) = [ D x' | x' <- shrink x, x' > 0 ] instance CoArbitrary D where coarbitrary = coarbitrary . unD prop_fmap :: Seq Int -> Bool prop_fmap xs = toList' (fmap f xs) ~= map f (toList xs) where f = (+100) prop_constmap :: A -> Seq A -> Bool prop_constmap x xs = toList' (x <$ xs) ~= map (const x) (toList xs) prop_foldr :: Seq A -> Property prop_foldr xs = foldr f z xs === Prelude.foldr f z (toList xs) where f = (:) z = [] prop_foldr' :: Seq A -> Property prop_foldr' xs = foldr' f z xs === foldr' f z (toList xs) where f = (:) z = [] prop_lazyfoldr' :: Seq () -> Property prop_lazyfoldr' xs = not (null xs) ==> foldr' (\e _ -> e) (error "Data.Sequence.foldr': should be lazy in initial accumulator") xs === () prop_foldr1 :: Seq Int -> Property prop_foldr1 xs = not (null xs) ==> foldr1 f xs == Data.List.foldr1 f (toList xs) where f = (-) prop_foldl :: Seq A -> Property prop_foldl xs = foldl f z xs === Prelude.foldl f z (toList xs) where f = flip (:) z = [] prop_foldl' :: Seq A -> Property prop_foldl' xs = foldl' f z xs === foldl' f z (toList xs) where f = flip (:) z = [] prop_lazyfoldl' :: Seq () -> Property prop_lazyfoldl' xs = not (null xs) ==> foldl' (\_ e -> e) (error "Data.Sequence.foldl': should be lazy in initial accumulator") xs === () prop_foldl1 :: Seq Int -> Property prop_foldl1 xs = not (null xs) ==> foldl1 f xs == Data.List.foldl1 f (toList xs) where f = (-) prop_equals :: Seq OrdA -> Seq OrdA -> Bool prop_equals xs ys = (xs == ys) == (toList xs == toList ys) prop_compare :: Seq OrdA -> Seq OrdA -> Bool prop_compare xs ys = compare xs ys == compare (toList xs) (toList ys) prop_mappend :: Seq A -> Seq A -> Bool prop_mappend xs ys = toList' (mappend xs ys) ~= toList xs ++ toList ys prop_singleton :: A -> Bool prop_singleton x = toList' (singleton x) ~= [x] prop_cons :: A -> Seq A -> Bool prop_cons x xs = toList' (x <| xs) ~= x : toList xs prop_snoc :: Seq A -> A -> Bool prop_snoc xs x = toList' (xs |> x) ~= toList xs ++ [x] prop_append :: Seq A -> Seq A -> Bool prop_append xs ys = toList' (xs >< ys) ~= toList xs ++ toList ys prop_fromList :: [A] -> Bool prop_fromList xs = toList' (fromList xs) ~= xs prop_fromFunction :: [A] -> Bool prop_fromFunction xs = toList' (fromFunction (Prelude.length xs) (xs!!)) ~= xs prop_fromArray :: [A] -> Bool prop_fromArray xs = toList' (fromArray (listArray (42, 42+Prelude.length xs-1) xs)) ~= xs prop_replicate :: NonNegative Int -> A -> Bool prop_replicate (NonNegative m) x = toList' (replicate n x) ~= Prelude.replicate n x where n = m `mod` 10000 prop_replicateA :: NonNegative Int -> Bool prop_replicateA (NonNegative m) = traverse toList' (replicateA n a) ~= sequenceA (Prelude.replicate n a) where n = m `mod` 10000 a = Action 1 0 :: M Int prop_replicateM :: NonNegative Int -> Bool prop_replicateM (NonNegative m) = traverse toList' (replicateM n a) ~= sequence (Prelude.replicate n a) where n = m `mod` 10000 a = Action 1 0 :: M Int prop_iterateN :: NonNegative Int -> Int -> Bool prop_iterateN (NonNegative m) x = toList' (iterateN n f x) ~= Prelude.take n (Prelude.iterate f x) where n = m `mod` 10000 f = (+1) prop_unfoldr :: [A] -> Bool prop_unfoldr z = toList' (unfoldr f z) ~= Data.List.unfoldr f z where f [] = Nothing f (x:xs) = Just (x, xs) prop_unfoldl :: [A] -> Bool prop_unfoldl z = toList' (unfoldl f z) ~= Data.List.reverse (Data.List.unfoldr (fmap swap . f) z) where f [] = Nothing f (x:xs) = Just (xs, x) swap (x,y) = (y,x) prop_null :: Seq A -> Bool prop_null xs = null xs == Prelude.null (toList xs) prop_length :: Seq A -> Bool prop_length xs = length xs == Prelude.length (toList xs) prop_viewl :: Seq A -> Bool prop_viewl xs = case viewl xs of EmptyL -> Prelude.null (toList xs) x :< xs' -> valid xs' && toList xs == x : toList xs' prop_viewr :: Seq A -> Bool prop_viewr xs = case viewr xs of EmptyR -> Prelude.null (toList xs) xs' :> x -> valid xs' && toList xs == toList xs' ++ [x] prop_scanl :: [A] -> Seq A -> Bool prop_scanl z xs = toList' (scanl f z xs) ~= Data.List.scanl f z (toList xs) where f = flip (:) prop_scanl1 :: Seq Int -> Property prop_scanl1 xs = not (null xs) ==> toList' (scanl1 f xs) ~= Data.List.scanl1 f (toList xs) where f = (-) prop_scanr :: [A] -> Seq A -> Bool prop_scanr z xs = toList' (scanr f z xs) ~= Data.List.scanr f z (toList xs) where f = (:) prop_scanr1 :: Seq Int -> Property prop_scanr1 xs = not (null xs) ==> toList' (scanr1 f xs) ~= Data.List.scanr1 f (toList xs) where f = (-) prop_tails :: Seq A -> Bool prop_tails xs = toListList' (tails xs) ~= Data.List.tails (toList xs) prop_inits :: Seq A -> Bool prop_inits xs = toListList' (inits xs) ~= Data.List.inits (toList xs) prop_takeWhileL :: Positive Int -> Seq Int -> Bool prop_takeWhileL (Positive n) xs = toList' (takeWhileL p xs) ~= Prelude.takeWhile p (toList xs) where p x = x `mod` n == 0 prop_takeWhileR :: Positive Int -> Seq Int -> Bool prop_takeWhileR (Positive n) xs = toList' (takeWhileR p xs) ~= Prelude.reverse (Prelude.takeWhile p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_dropWhileL :: Positive Int -> Seq Int -> Bool prop_dropWhileL (Positive n) xs = toList' (dropWhileL p xs) ~= Prelude.dropWhile p (toList xs) where p x = x `mod` n == 0 prop_dropWhileR :: Positive Int -> Seq Int -> Bool prop_dropWhileR (Positive n) xs = toList' (dropWhileR p xs) ~= Prelude.reverse (Prelude.dropWhile p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_spanl :: Positive Int -> Seq Int -> Bool prop_spanl (Positive n) xs = toListPair' (spanl p xs) ~= Data.List.span p (toList xs) where p x = x `mod` n == 0 prop_spanr :: Positive Int -> Seq Int -> Bool prop_spanr (Positive n) xs = toListPair' (spanr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.span p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_breakl :: Positive Int -> Seq Int -> Bool prop_breakl (Positive n) xs = toListPair' (breakl p xs) ~= Data.List.break p (toList xs) where p x = x `mod` n == 0 prop_breakr :: Positive Int -> Seq Int -> Bool prop_breakr (Positive n) xs = toListPair' (breakr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.break p (Prelude.reverse (toList xs))) where p x = x `mod` n == 0 prop_partition :: Positive Int -> Seq Int -> Bool prop_partition (Positive n) xs = toListPair' (partition p xs) ~= Data.List.partition p (toList xs) where p x = x `mod` n == 0 prop_filter :: Positive Int -> Seq Int -> Bool prop_filter (Positive n) xs = toList' (filter p xs) ~= Prelude.filter p (toList xs) where p x = x `mod` n == 0 prop_sort :: Seq OrdA -> Bool prop_sort xs = toList' (sort xs) ~= Data.List.sort (toList xs) data UnstableOrd = UnstableOrd { ordKey :: OrdA , _ignored :: A } deriving (Show) instance Eq UnstableOrd where x == y = compare x y == EQ instance Ord UnstableOrd where compare (UnstableOrd x _) (UnstableOrd y _) = compare x y instance Arbitrary UnstableOrd where arbitrary = liftA2 UnstableOrd arbitrary arbitrary shrink (UnstableOrd x y) = [ UnstableOrd x' y' | (x',y') <- shrink (x, y) ] prop_sortStable :: Seq UnstableOrd -> Bool prop_sortStable xs = (fmap . fmap) unignore (toList' (sort xs)) ~= fmap unignore (Data.List.sort (toList xs)) where unignore (UnstableOrd x y) = (x, y) prop_sortBy :: Seq (OrdA, B) -> Bool prop_sortBy xs = toList' (sortBy f xs) ~= Data.List.sortBy f (toList xs) where f (x1, _) (x2, _) = compare x1 x2 prop_sortOn :: Fun A OrdB -> Seq A -> Bool prop_sortOn (Fun _ f) xs = toList' (sortOn f xs) ~= listSortOn f (toList xs) where #if MIN_VERSION_base(4,8,0) listSortOn = Data.List.sortOn #else listSortOn k = Data.List.sortBy (compare `on` k) #endif prop_sortOnStable :: Fun A UnstableOrd -> Seq A -> Bool prop_sortOnStable (Fun _ f) xs = toList' (sortOn f xs) ~= listSortOn f (toList xs) where #if MIN_VERSION_base(4,8,0) listSortOn = Data.List.sortOn #else listSortOn k = Data.List.sortBy (compare `on` k) #endif prop_unstableSort :: Seq OrdA -> Bool prop_unstableSort xs = toList' (unstableSort xs) ~= Data.List.sort (toList xs) prop_unstableSortBy :: Seq OrdA -> Bool prop_unstableSortBy xs = toList' (unstableSortBy compare xs) ~= Data.List.sort (toList xs) prop_unstableSortOn :: Fun A OrdB -> Seq A -> Property prop_unstableSortOn (Fun _ f) xs = toList' (unstableSortBy (compare `on` f) xs) === toList' (unstableSortOn f xs) prop_index :: Seq A -> Property prop_index xs = not (null xs) ==> forAll (choose (0, length xs-1)) $ \ i -> index xs i == toList xs !! i prop_safeIndex :: Seq A -> Property prop_safeIndex xs = forAll (choose (-3, length xs + 3)) $ \i -> ((i < 0 || i >= length xs) .&&. lookup i xs === Nothing) .||. lookup i xs === Just (toList xs !! i) prop_insertAt :: A -> Seq A -> Property prop_insertAt x xs = forAll (choose (-3, length xs + 3)) $ \i -> let res = insertAt i x xs in valid res .&&. res === case splitAt i xs of (front, back) -> front >< x <| back prop_deleteAt :: Seq A -> Property prop_deleteAt xs = forAll (choose (-3, length xs + 3)) $ \i -> let res = deleteAt i xs in valid res .&&. (((0 <= i && i < length xs) .&&. res === case splitAt i xs of (front, back) -> front >< drop 1 back) .||. ((i < 0 || i >= length xs) .&&. res === xs)) prop_adjust :: Int -> Int -> Seq Int -> Bool prop_adjust n i xs = toList' (adjust f i xs) ~= adjustList f i (toList xs) where f = (+n) prop_update :: Int -> A -> Seq A -> Bool prop_update i x xs = toList' (update i x xs) ~= adjustList (const x) i (toList xs) prop_take :: Int -> Seq A -> Bool prop_take n xs = toList' (take n xs) ~= Prelude.take n (toList xs) prop_drop :: Int -> Seq A -> Bool prop_drop n xs = toList' (drop n xs) ~= Prelude.drop n (toList xs) prop_splitAt :: Int -> Seq A -> Bool prop_splitAt n xs = toListPair' (splitAt n xs) ~= Prelude.splitAt n (toList xs) prop_chunksOf :: Seq A -> Property prop_chunksOf xs = forAll (choose (1, length xs + 3)) $ \n -> let chunks = chunksOf n xs in valid chunks .&&. conjoin [valid c .&&. 1 <= length c && length c <= n | c <- toList chunks] .&&. fold chunks === xs adjustList :: (a -> a) -> Int -> [a] -> [a] adjustList f i xs = [if j == i then f x else x | (j, x) <- Prelude.zip [0..] xs] prop_elemIndexL :: A -> Seq A -> Bool prop_elemIndexL x xs = elemIndexL x xs == Data.List.elemIndex x (toList xs) prop_elemIndicesL :: A -> Seq A -> Bool prop_elemIndicesL x xs = elemIndicesL x xs == Data.List.elemIndices x (toList xs) prop_elemIndexR :: A -> Seq A -> Bool prop_elemIndexR x xs = elemIndexR x xs == listToMaybe (Prelude.reverse (Data.List.elemIndices x (toList xs))) prop_elemIndicesR :: A -> Seq A -> Bool prop_elemIndicesR x xs = elemIndicesR x xs == Prelude.reverse (Data.List.elemIndices x (toList xs)) prop_findIndexL :: Positive Int -> Seq Int -> Bool prop_findIndexL (Positive n) xs = findIndexL p xs == Data.List.findIndex p (toList xs) where p x = x `mod` n == 0 prop_findIndicesL :: Positive Int -> Seq Int -> Bool prop_findIndicesL (Positive n) xs = findIndicesL p xs == Data.List.findIndices p (toList xs) where p x = x `mod` n == 0 prop_findIndexR :: Positive Int -> Seq Int -> Bool prop_findIndexR (Positive n) xs = findIndexR p xs == listToMaybe (Prelude.reverse (Data.List.findIndices p (toList xs))) where p x = x `mod` n == 0 prop_findIndicesR :: Positive Int -> Seq Int -> Bool prop_findIndicesR (Positive n) xs = findIndicesR p xs == Prelude.reverse (Data.List.findIndices p (toList xs)) where p x = x `mod` n == 0 prop_foldlWithIndex :: [(Int, A)] -> Seq A -> Bool prop_foldlWithIndex z xs = foldlWithIndex f z xs == Data.List.foldl (uncurry . f) z (Data.List.zip [0..] (toList xs)) where f ys n y = (n,y):ys prop_foldrWithIndex :: [(Int, A)] -> Seq A -> Bool prop_foldrWithIndex z xs = foldrWithIndex f z xs == Data.List.foldr (uncurry f) z (Data.List.zip [0..] (toList xs)) where f n y ys = (n,y):ys prop_foldMapWithIndexL :: (Fun (B, Int, A) B) -> B -> Seq A -> Bool prop_foldMapWithIndexL (Fun _ f) z t = foldlWithIndex f' z t == appEndo (getDual (foldMapWithIndex (\i -> Dual . Endo . flip (flip f' i)) t)) z where f' b i a = f (b, i, a) prop_foldMapWithIndexR :: (Fun (Int, A, B) B) -> B -> Seq A -> Bool prop_foldMapWithIndexR (Fun _ f) z t = foldrWithIndex f' z t == appEndo (foldMapWithIndex (\i -> Endo . f' i) t) z where f' i a b = f (i, a, b) prop_mapWithIndex :: Seq A -> Bool prop_mapWithIndex xs = toList' (mapWithIndex f xs) ~= map (uncurry f) (Data.List.zip [0..] (toList xs)) where f = (,) prop_traverseWithIndex :: Seq Int -> Bool prop_traverseWithIndex xs = runState (traverseWithIndex (\i x -> modify ((i,x) :)) xs) [] == runState (sequenceA . mapWithIndex (\i x -> modify ((i,x) :)) $ xs) [] prop_reverse :: Seq A -> Bool prop_reverse xs = toList' (reverse xs) ~= Prelude.reverse (toList xs) * * prop_zip :: Seq A -> Seq B -> Bool prop_zip xs ys = toList' (zip xs ys) ~= Prelude.zip (toList xs) (toList ys) prop_zipWith :: Seq A -> Seq B -> Bool prop_zipWith xs ys = toList' (zipWith f xs ys) ~= Prelude.zipWith f (toList xs) (toList ys) where f = (,) prop_zip3 :: Seq A -> Seq B -> Seq C -> Bool prop_zip3 xs ys zs = toList' (zip3 xs ys zs) ~= Prelude.zip3 (toList xs) (toList ys) (toList zs) prop_zipWith3 :: Seq A -> Seq B -> Seq C -> Bool prop_zipWith3 xs ys zs = toList' (zipWith3 f xs ys zs) ~= Prelude.zipWith3 f (toList xs) (toList ys) (toList zs) where f = (,,) prop_zip4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool prop_zip4 xs ys zs ts = toList' (zip4 xs ys zs ts) ~= Data.List.zip4 (toList xs) (toList ys) (toList zs) (toList ts) prop_zipWith4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool prop_zipWith4 xs ys zs ts = toList' (zipWith4 f xs ys zs ts) ~= Data.List.zipWith4 f (toList xs) (toList ys) (toList zs) (toList ts) where f = (,,,) This comes straight from the MonadZip documentation prop_mzipNaturality :: Fun A C -> Fun B D -> Seq A -> Seq B -> Property prop_mzipNaturality f g sa sb = fmap (apply f *** apply g) (mzip sa sb) === mzip (apply f <$> sa) (apply g <$> sb) This is a slight optimization of the MonadZip preservation prop_mzipPreservation :: Fun A B -> Seq A -> Property prop_mzipPreservation f sa = let sb = fmap (apply f) sa in munzip (mzip sa sb) === (sa, sb) munzip xs = xs ` seq ` ( fmap fst x , fmap snd x ) prop_munzipLazy :: Seq (Integer, B) -> Bool prop_munzipLazy pairs = deepseq ((`seq` ()) <$> repaired) True where partialpairs = mapWithIndex (\i a -> update i err pairs) pairs firstPieces = fmap (fst . munzip) partialpairs repaired = mapWithIndex (\i s -> update i 10000 s) firstPieces err = error "munzip isn't lazy enough" prop_ap :: Seq A -> Seq B -> Bool prop_ap xs ys = toList' ((,) <$> xs <*> ys) ~= ( (,) <$> toList xs <*> toList ys ) prop_ap_NOINLINE :: Seq A -> Seq B -> Bool prop_ap_NOINLINE xs ys = toList' (((,) <$> xs) `apNOINLINE` ys) ~= ( (,) <$> toList xs <*> toList ys ) # NOINLINE apNOINLINE # apNOINLINE :: Seq (a -> b) -> Seq a -> Seq b apNOINLINE fs xs = fs <*> xs prop_liftA2 :: Seq A -> Seq B -> Property prop_liftA2 xs ys = valid q .&&. toList q === liftA2 (,) (toList xs) (toList ys) where q = liftA2 (,) xs ys prop_then :: Seq A -> Seq B -> Bool prop_then xs ys = toList' (xs *> ys) ~= (toList xs *> toList ys) We take only the length of the second sequence because prop_before :: Seq A -> NonNegative Int -> Bool prop_before xs (NonNegative lys) = toList' (xs <* ys) ~= (toList xs <* toList ys) where ys = replicate lys () prop_intersperse :: A -> Seq A -> Bool prop_intersperse x xs = toList' (intersperse x xs) ~= Data.List.intersperse x (toList xs) prop_cycleTaking :: Int -> Seq A -> Property prop_cycleTaking n xs = (n <= 0 || not (null xs)) ==> toList' (cycleTaking n xs) ~= Data.List.take n (Data.List.cycle (toList xs)) #if __GLASGOW_HASKELL__ >= 800 prop_empty_pat :: Seq A -> Bool prop_empty_pat xs@Empty = null xs prop_empty_pat xs = not (null xs) prop_empty_con :: Bool prop_empty_con = null Empty prop_viewl_pat :: Seq A -> Property prop_viewl_pat xs@(y :<| ys) | z :< zs <- viewl xs = y === z .&&. ys === zs | otherwise = property failed prop_viewl_pat xs = property . liftBool $ null xs prop_viewl_con :: A -> Seq A -> Property prop_viewl_con x xs = x :<| xs === x <| xs prop_viewr_pat :: Seq A -> Property prop_viewr_pat xs@(ys :|> y) | zs :> z <- viewr xs = y === z .&&. ys === zs | otherwise = property failed prop_viewr_pat xs = property . liftBool $ null xs prop_viewr_con :: Seq A -> A -> Property prop_viewr_con xs x = xs :|> x === xs |> x #endif Monad operations prop_bind :: Seq A -> Fun A (Seq B) -> Bool prop_bind xs (Fun _ f) = toList' (xs >>= f) ~= (toList xs >>= toList . f) #if MIN_VERSION_base(4,9,0) prop_stimes :: NonNegative Int -> Seq A -> Property prop_stimes (NonNegative n) s = stimes n s === stimesMonoid n s #endif MonadFix operation It 's exceedingly difficult to construct a proper QuickCheck property for mfix because the function passed to it must be test_mfix :: Property test_mfix = toList resS === resL where facty :: (Int -> Int) -> Int -> Int facty _ 0 = 1; facty f n = n * f (n - 1) resS :: Seq Int resS = fmap ($ 12) $ mfix (\f -> fromList [facty f, facty (+1), facty (+2)]) resL :: [Int] resL = fmap ($ 12) $ mfix (\f -> [facty f, facty (+1), facty (+2)]) data M a = Action Int a deriving (Eq, Show) instance Functor M where fmap f (Action n x) = Action n (f x) instance Applicative M where pure x = Action 0 x Action m f <*> Action n x = Action (m+n) (f x) instance Monad M where return x = Action 0 x Action m x >>= f = let Action n y = f x in Action (m+n) y instance Foldable M where foldMap f (Action _ x) = f x instance Traversable M where traverse f (Action n x) = Action n <$> f x
eb2b9bfed0ff3fe4092ca6ea16e57618848ec7364d03573147f5a9c8e57d00df
bluegraybox/examples
web_test.erl
#!/usr/local/bin/escript %% -*- erlang -*- %%! -smp enable -mode(compile). % for better performance main(_) -> inets:start(), get_url(":8000/newgame"), Tests = [ {"Joe", 4, "4"}, {"Joe", 9, "{invalid_total,13}"}, % bad input {"John", 4, "4"}, {"John", 5, "9"}, {"John", 6, "15"}, {"John", 4, "19"}, {"John", 3, "25"}, % spare {"John", 2, "27"}, {"John", 10, "37"}, {"John", 2, "41"}, % strike {"John", 6, "53"}, % strike %% interleaving players {"Fred", 3, "3"}, {"Dave", 2, "2"}, {"Fred", 4, "7"}, {"Dave", 6, "8"}, {"Fred", 1, "8"}, {"Dave", 7, "15"}, {"Fred", 2, "10"}, {"Dave", 3, "18"}], test(Tests). test(Tests) -> test(Tests, 0, 0). test([], Pass, 0) -> io:format("Passed! (~p tests)~n", [Pass]); test([], Pass, Fail) -> io:format("Failed! Passed ~p, Failed ~p~n", [Pass, Fail]); test([{Player, Roll, Expected} | Tests], Pass, Fail) -> Url = io_lib:format(":8000/add/~s/~p", [Player, Roll]), % io:format("Testing URL: ~s~n", [Url]), case get_url(Url) of Expected -> io:format(". "), test(Tests, Pass + 1, Fail); Actual -> io:format("Fail: expected=~p, actual=~p~n", [Expected, Actual]), test(Tests, Pass, Fail + 1) end. get_url(Url) -> case httpc:request(Url) of {ok, {_Status, _Header, Content}} -> Content; {error, Reason} -> io:format("Error: ~p~n", [Reason]) end.
null
https://raw.githubusercontent.com/bluegraybox/examples/20f238be10e2e987687d7289b2f4897cc7d95abd/bowling/erlang/web_test.erl
erlang
-*- erlang -*- ! -smp enable for better performance bad input spare strike strike interleaving players io:format("Testing URL: ~s~n", [Url]),
#!/usr/local/bin/escript main(_) -> inets:start(), get_url(":8000/newgame"), Tests = [ {"Joe", 4, "4"}, {"John", 4, "4"}, {"John", 5, "9"}, {"John", 6, "15"}, {"John", 4, "19"}, {"John", 2, "27"}, {"John", 10, "37"}, {"Fred", 3, "3"}, {"Dave", 2, "2"}, {"Fred", 4, "7"}, {"Dave", 6, "8"}, {"Fred", 1, "8"}, {"Dave", 7, "15"}, {"Fred", 2, "10"}, {"Dave", 3, "18"}], test(Tests). test(Tests) -> test(Tests, 0, 0). test([], Pass, 0) -> io:format("Passed! (~p tests)~n", [Pass]); test([], Pass, Fail) -> io:format("Failed! Passed ~p, Failed ~p~n", [Pass, Fail]); test([{Player, Roll, Expected} | Tests], Pass, Fail) -> Url = io_lib:format(":8000/add/~s/~p", [Player, Roll]), case get_url(Url) of Expected -> io:format(". "), test(Tests, Pass + 1, Fail); Actual -> io:format("Fail: expected=~p, actual=~p~n", [Expected, Actual]), test(Tests, Pass, Fail + 1) end. get_url(Url) -> case httpc:request(Url) of {ok, {_Status, _Header, Content}} -> Content; {error, Reason} -> io:format("Error: ~p~n", [Reason]) end.
bcab950f388f03a5a243da0ea1f81f03c1820d890cac7aaeb89343a94b2093b4
oakes/clojure-conj-2014
12-hosted.clj
(defscreen hosted-screen :on-show (fn [screen entities] (update! screen :renderer (stage) :camera (orthographic)) (let [ui-skin (skin "skin/uiskin.json") medium-font (skin! ui-skin :get-font "medium-font") medium-style (style :label medium-font (color :white)) small-font (skin! ui-skin :get-font "small-font") small-style (style :label small-font (color :white))] (table [(label "Hosted Languages in Games" medium-style) :row (label (str \newline "Gamedevs traditionally reject GC" \newline "Things have changed in last half-decade" \newline "Many indie games are now made in C# / Java" \newline "Indies have scarce resources, need to ship") small-style)] :align (align :center) :set-fill-parent true))) :on-render (fn [screen entities] (render! screen entities)) :on-resize (fn [screen entities] (height! screen (:height screen))))
null
https://raw.githubusercontent.com/oakes/clojure-conj-2014/575e8eeced02d761f8d278b95906083f03ba9565/12-hosted.clj
clojure
(defscreen hosted-screen :on-show (fn [screen entities] (update! screen :renderer (stage) :camera (orthographic)) (let [ui-skin (skin "skin/uiskin.json") medium-font (skin! ui-skin :get-font "medium-font") medium-style (style :label medium-font (color :white)) small-font (skin! ui-skin :get-font "small-font") small-style (style :label small-font (color :white))] (table [(label "Hosted Languages in Games" medium-style) :row (label (str \newline "Gamedevs traditionally reject GC" \newline "Things have changed in last half-decade" \newline "Many indie games are now made in C# / Java" \newline "Indies have scarce resources, need to ship") small-style)] :align (align :center) :set-fill-parent true))) :on-render (fn [screen entities] (render! screen entities)) :on-resize (fn [screen entities] (height! screen (:height screen))))
835f33d8172d04d8ffbc6ab4e154299cb403b18ae9cb32caea90cb907e4593ef
namin/logically
meta_test.clj
(ns logically.abs.meta_test (:use [logically.abs.meta] :reload) (:use [logically.abs.unif] :reload) (:use [logically.abs.ex_ack] :reload) (:refer-clojure :exclude [==]) (:use [clojure.core.logic :exclude [is] :as l] [clojure.core.logic.nominal :exclude [fresh hash] :as nom]) (:use [clojure.test])) confirms /~mcodish/Tutorial/meta.html (deftest test-ack (is (= (run 3 [q] (fresh [m n] (== q [m n]) (solve* u==-concrete ack-norm-clause [[:ack [:s [:s 0]] n [:s m]]]))) '([[:s [:s 0]] 0] [[:s [:s [:s [:s 0]]]] [:s 0]] [[:s [:s [:s [:s [:s [:s 0]]]]]] [:s [:s 0]]]))) (is (= (run 3 [q] (solve* u==-parity1 ack-norm-clause [[:ack :even :one q]])) '(:odd :odd :odd))))
null
https://raw.githubusercontent.com/namin/logically/49e814e04ff0f5f20efa75122c0b869e400487ac/test/logically/abs/meta_test.clj
clojure
(ns logically.abs.meta_test (:use [logically.abs.meta] :reload) (:use [logically.abs.unif] :reload) (:use [logically.abs.ex_ack] :reload) (:refer-clojure :exclude [==]) (:use [clojure.core.logic :exclude [is] :as l] [clojure.core.logic.nominal :exclude [fresh hash] :as nom]) (:use [clojure.test])) confirms /~mcodish/Tutorial/meta.html (deftest test-ack (is (= (run 3 [q] (fresh [m n] (== q [m n]) (solve* u==-concrete ack-norm-clause [[:ack [:s [:s 0]] n [:s m]]]))) '([[:s [:s 0]] 0] [[:s [:s [:s [:s 0]]]] [:s 0]] [[:s [:s [:s [:s [:s [:s 0]]]]]] [:s [:s 0]]]))) (is (= (run 3 [q] (solve* u==-parity1 ack-norm-clause [[:ack :even :one q]])) '(:odd :odd :odd))))
d73c22abfd7e72459f55793dd5bc64a7399444efd18ac310db38d948d806e9f2
pouyakary/Nota
BinaryOperator.hs
module Language.BackEnd.Evaluator.Nodes.BinaryOperator ( evalBinaryOperator ) where -- ─── IMPORTS ──────────────────────────────────────────────────────────────────── import Data.List import Data.Map ( Map ) import qualified Data.Map as Map import Language.BackEnd.Evaluator.Types import Language.FrontEnd.AST import Model -- ─── EVAL BINARY OPERATORS ────────────────────────────────────────────────────── evalBinaryOperator :: StemEvalSignature evalBinaryOperator ( evalFunc ) ( ASTBinaryOperator op left right ) model = case evalFunc left model of Left leftErr -> Left leftErr Right evaluatedLeft -> case evalFunc right model of Left rightErr -> Left rightErr Right evaluatedRight -> Right result where result = case op of Sum -> evaluatedLeft + evaluatedRight Sub -> evaluatedLeft - evaluatedRight Div -> evaluatedLeft / evaluatedRight Mul -> evaluatedLeft * evaluatedRight Pow -> evaluatedLeft ** evaluatedRight Equ -> if evaluatedLeft == evaluatedRight then 1 else 0 NEq -> if evaluatedLeft /= evaluatedRight then 1 else 0 Mod -> evaluatedLeft `nonIntRem` evaluatedRight -- ─── NON INTEGER REMAINING ────────────────────────────────────────────────────── nonIntRem :: Double -> Double -> Double nonIntRem x y = x - (y * (fromIntegral $ truncate (x/y))) -- ────────────────────────────────────────────────────────────────────────────────
null
https://raw.githubusercontent.com/pouyakary/Nota/d5e29eca7ea34d72835a9708977fa33c030393d1/source/Language/BackEnd/Evaluator/Nodes/BinaryOperator.hs
haskell
─── IMPORTS ──────────────────────────────────────────────────────────────────── ─── EVAL BINARY OPERATORS ────────────────────────────────────────────────────── ─── NON INTEGER REMAINING ────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────
module Language.BackEnd.Evaluator.Nodes.BinaryOperator ( evalBinaryOperator ) where import Data.List import Data.Map ( Map ) import qualified Data.Map as Map import Language.BackEnd.Evaluator.Types import Language.FrontEnd.AST import Model evalBinaryOperator :: StemEvalSignature evalBinaryOperator ( evalFunc ) ( ASTBinaryOperator op left right ) model = case evalFunc left model of Left leftErr -> Left leftErr Right evaluatedLeft -> case evalFunc right model of Left rightErr -> Left rightErr Right evaluatedRight -> Right result where result = case op of Sum -> evaluatedLeft + evaluatedRight Sub -> evaluatedLeft - evaluatedRight Div -> evaluatedLeft / evaluatedRight Mul -> evaluatedLeft * evaluatedRight Pow -> evaluatedLeft ** evaluatedRight Equ -> if evaluatedLeft == evaluatedRight then 1 else 0 NEq -> if evaluatedLeft /= evaluatedRight then 1 else 0 Mod -> evaluatedLeft `nonIntRem` evaluatedRight nonIntRem :: Double -> Double -> Double nonIntRem x y = x - (y * (fromIntegral $ truncate (x/y)))
47a40de6322dbe6a8ba9bdb1810d32d811de2152d6ea4c3602493507f3356f7f
spurious/sagittarius-scheme-mirror
kernel.scm
;;; kernel.scm ;;; Implementation of the sweet-expressions project by readable mailinglist. ;;; Copyright ( C ) 2005 - 2013 by and ;;; This software is released as open source software under the " MIT " license : ;;; ;;; 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. ;;; Warning: For portability use eqv?/memv (not eq?/memq) to compare characters. ;;; A "case" is okay since it uses "eqv?". ;;; This file includes: ;;; - Compatibility layer - macros etc. to try to make it easier to port ;;; this code to different Scheme implementations (to deal with different ;;; module systems, how to override read, getting position info, etc.) ;;; - Re-implementation of "read", beginning with its support procedures. ;;; There is no standard Scheme mechanism to override just *portions* ;;; of read, and we MUST make {} delimiters, so we have to re-implement read. ;;; We also need to get control over # so we know which ones are comments. ;;; If you're modifying a Scheme implementation, just use that instead. ;;; - Curly Infix (c-expression) implementation ;;; - Neoteric expression (n-expression) implementation ;;; - Sweet-expression (t-expression) implementation - Implementation of writers for curly - infix and neoteric expressions - ;;; a "-simple" implementation, and a separate -shared/-cyclic version. ;;; The "-simple" one is separate so that you can use just it. ;;; Note that a lot of the code is in the compatibility layer and ;;; re-implementation of "read"; implementing the new expression languages ;;; is actually pretty easy. ; ----------------------------------------------------------------------------- Compatibility Layer ; ----------------------------------------------------------------------------- ; The compatibility layer is composed of: ; ; (readable-kernel-module-contents (exports ...) body ...) ; - a macro that should package the given body as a module, or whatever your scheme calls it ( chicken eggs ? ) , preferably with one of the following ; names, in order of preference, depending on your Scheme's package naming ; conventions/support ; (readable kernel) ; readable/kernel ; readable-kernel ; sweetimpl - The first element after the module - contents name is a list of exported ; procedures. This module shall never export a macro or syntax, not even ; in the future. ; - If your Scheme requires module contents to be defined inside a top-level module declaration ( unlike where module contents are declared as ; top-level entities after the module declaration) then the other ; procedures below should be defined inside the module context in order ; to reduce user namespace pollution. ; ; (my-peek-char port) ; (my-read-char port) ; - Performs I/O on a "port" object. ; - The algorithm assumes that port objects have the following abilities: ; * The port automatically keeps track of source location information . On R5RS there is no source location ; information that can be attached to objects, so as a ; fallback you can just ignore source location, which ; will make debugging using sweet-expressions more ; difficult. ; - "port" or fake port objects are created by the make-read procedure ; below. ; ; (make-read procedure) - The given procedure accepts exactly 1 argument , a " fake port " that can ; be passed to my-peek-char et al. ; - make-read creates a new procedure that supports your Scheme's reader ; interface. Usually, this means making a new procedure that accepts either 0 or 1 parameters , defaulting to ( current - input - port ) . ; - If your Scheme doesn't keep track of source location information ; automatically with the ports, you may again need to wrap it here. ; - If your Scheme needs a particularly magical incantation to attach ; source information to objects, then you might need to use a weak-key ; table in the attach-sourceinfo procedure below and then use that ; weak-key table to perform the magical incantation. ; ; (invoke-read read port) ; - Accepts a read procedure, which is a (most likely built-in) procedure ; that requires a *real* port, not a fake one. ; - Should unwrap the fake port to a real port, then invoke the given ; read procedure on the actual real port. ; ; (get-sourceinfo port) ; - Given a fake port, constructs some object (which the algorithm treats ; as opaque) to represent the source information at the point that the ; port is currently in. ; ; (attach-sourceinfo pos obj) ; - Attaches the source information pos, as constructed by get-sourceinfo, ; to the given obj. ; - obj can be any valid Scheme object. If your Scheme can only track ; source location for a subset of Scheme object types, then this procedure ; should handle it gracefully. ; - Returns an object with the source information attached - this can be ; the same object, or a different object that should look-and-feel the ; same as the passed-in object. ; - If source information cannot be attached anyway (your Scheme doesn't ; support attaching source information to objects), just return the ; given object. ; ; (replace-read-with f) ; - Replaces your Scheme's current reader. ; - Replace 'read and 'get-datum at the minimum. If your Scheme ; needs any kind of involved magic to handle load and loading ; modules correctly, do it here. ; ; (parse-hash no-indent-read char fake-port) - a procedure that is invoked when an unrecognized , non - R5RS hash ; character combination is encountered in the input port. ; - this procedure is passed a "fake port", as wrapped by the ; make-read procedure above. You should probably use my-read-char ; and my-peek-char in it, or at least unwrap the port (since ; make-read does the wrapping, and you wrote make-read, we assume ; you know how to unwrap the port). ; - if your procedure needs to parse a datum, invoke ; (no-indent-read fake-port). Do NOT use any other read procedure. The no - indent - read procedure accepts exactly one parameter - the fake port ; this procedure was passed in. ; - no-indent-read is either a version of curly-infix-read, or a version of neoteric - read ; this specal version accepts only a fake port . ; It is never a version of sweet-read. You don't normally want to ; call sweet-read, because sweet-read presumes that it's starting ; at the beginning of the line, with indentation processing still ; active. There's no reason either must be true when processing "#". ; - At the start of this procedure, both the # and the character ; after it have been read in. - The procedure returns one of the following : ; #f - the hash-character combination is invalid/not supported. ; (normal value) - the datum has value "value". ; (scomment ()) - the hash-character combination introduced a comment; ; at the return of this procedure with this value, the ; comment has been removed from the input port. ; You can use scomment-result, which has this value. ; (datum-commentw ()) - #; followed by whitespace. ; (abbrev value) - this is an abbreviation for value "value" ; ; hash-pipe-comment-nests? - a Boolean value that specifies whether # | ... | # comments ; should nest. ; ; my-string-foldcase ; - a procedure to perform case-folding to lowercase, as mandated by Unicode . If your implementation does n't have Unicode , define ; this to be string-downcase. Some implementations may also ; interpret "string-downcase" as foldcase anyway. On Guile 2.0 , the define - module part needs to occur separately from ; the rest of the compatibility checks, unfortunately. Sigh. (cond-expand (guile ; define the module ; this ensures that the user's module does not get contaminated with ; our compatibility procedures/macros (define-module (readable kernel))) (else #t)) (cond-expand ; ----------------------------------------------------------------------------- ; Guile Compatibility ; ----------------------------------------------------------------------------- (guile ; properly get bindings (use-modules (guile)) On 1.x defmacro is the only thing supported out - of - the - box . This form still exists in Guile 2.x , fortunately . (defmacro readable-kernel-module-contents (exports . body) `(begin (export ,@exports) ,@body)) Enable R5RS hygenic macro system ( define - syntax ) - guile 1.X does not automatically provide it , but version 1.6 + enable it this way (use-syntax (ice-9 syncase)) was the original development environment , so the algorithm practically acts as if it is in . Needs to be lambdas because otherwise 2.0 acts strangely , ; getting confused on the distinction between compile-time, ; load-time and run-time (apparently, peek-char is not bound ; during load-time). (define (my-peek-char fake-port) (if (eof-object? (car fake-port)) (car fake-port) (let* ((port (car fake-port)) (char (peek-char port))) (if (eof-object? char) (set-car! fake-port char)) char))) (define (my-read-char fake-port) (if (eof-object? (car fake-port)) (car fake-port) (let* ((port (car fake-port)) (char (read-char port))) (if (eof-object? char) (set-car! fake-port char)) char))) (define (make-read f) (lambda args (let ((port (if (null? args) (current-input-port) (car args)))) (f (list port))))) (define (invoke-read read fake-port) (if (eof-object? (car fake-port)) (car fake-port) (read (car fake-port)))) ; create a list with the source information (define (get-sourceinfo fake-port) (if (eof-object? (car fake-port)) #f (let ((port (car fake-port))) (list (port-filename port) (port-line port) (port-column port))))) ; destruct the list and attach, but only to cons cells, since only that is reliably supported across versions . (define (attach-sourceinfo pos obj) (cond ((not pos) obj) ((pair? obj) (set-source-property! obj 'filename (list-ref pos 0)) (set-source-property! obj 'line (list-ref pos 1)) (set-source-property! obj 'column (list-ref pos 2)) obj) (#t obj))) ; To properly hack into 'load and in particular 'use-modules, we need to hack into ' primitive - load . On 1.8 and 2.0 there ; is supposed to be a current-reader fluid that primitive-load ; hooks into, but it seems (unverified) that each use-modules ; creates a new fluid environment, so that this only sticks ; on a per-module basis. But if the project is primarily in ; sweet-expressions, we would prefer to have that hook in ; *all* 'use-modules calls. So our primitive-load uses the ; 'read global variable if current-reader isn't set. (define %sugar-current-load-port #f) ; replace primitive-load (define primitive-load-replaced #f) (define (setup-primitive-load) (cond (primitive-load-replaced (values)) (#t (module-set! (resolve-module '(guile)) 'primitive-load (lambda (filename) (let ((hook (cond ((not %load-hook) #f) ((not (procedure? %load-hook)) (error "%load-hook must be procedure or #f")) (#t %load-hook)))) (cond (hook (hook filename))) (let* ((port (open-input-file filename)) (save-port port)) (define (load-loop) (let* ((the-read (or current - reader does n't exist on 1.6 (if (string=? "1.6" (effective-version)) #f (fluid-ref current-reader)) read)) (form (the-read port))) (cond ((not (eof-object? form)) in only (primitive-eval form) (load-loop))))) (define (swap-ports) (let ((tmp %sugar-current-load-port)) (set! %sugar-current-load-port save-port) (set! save-port tmp))) (dynamic-wind swap-ports load-loop swap-ports) (close-input-port port))))) (set! primitive-load-replaced #t)))) (define (replace-read-with f) (setup-primitive-load) (set! read f)) ; Below implements some guile extensions, basically as guile 2.0. On , # :x is a keyword . Keywords have symbol syntax . ; On Guile 1.6 and 1.8 the only comments are ; and #!..!#, but ; we'll allow more. On Guile 2.0 , # ; ( SRFI-62 ) and # | # | | # | # ( SRFI-30 ) comments exist . On Guile 2.0 , # ' # ` # , # , @ have the R6RS meaning ; on older ; Guile 1.8 and 1.6 there is a #' syntax but we have yet ; to figure out what exactly they do, and since those are becoming ; obsolete, we'll just use the R6RS meaning. (define (parse-hash no-indent-read char fake-port) ; (let* ((ver (effective-version)) ; (c (string-ref ver 0)) ( > = 2 ( and ( not ( char= ? c # \0 ) ) ( not ( char= ? c # \1 ) ) ) ) ) ... ) (cond ((char=? char #\:) ; On Guile 1.6, #: reads characters until it finds non-symbol ; characters. ; On Guile 1.8 and 2.0, #: reads in a datum, and if the ; datum is not a symbol, throws an error. Follow the 1.8/2.0 behavior as it is simpler to implement , and even on 1.6 it is unlikely to cause problems . ; NOTE: This behavior means that #:foo(bar) will cause problems on neoteric and higher tiers . (let ((s (no-indent-read fake-port))) (if (symbol? s) `(normal ,(symbol->keyword s) ) #f))) On Guile 2.0 # ' # ` # , # , @ have the R6RS meaning , handled in generics . Guile 1.6 and 1.8 have different meanings , but we 'll ignore that . ; Guile's #{ }# syntax ((char=? char #\{ ) ; Special symbol, through till ...}# `(normal ,(list->symbol (special-symbol fake-port)))) (#t #f))) ; Return list of characters inside #{...}#, a guile extension. ; presume we've already read the sharp and initial open brace. ; On eof we just end. We could error out instead. TODO : actually conform to 's syntax . Note that 1.x ; and 2.0 have different syntax when spaces, backslashes, and ; control characters get involved. (define (special-symbol port) (cond ((eof-object? (my-peek-char port)) '()) ((eqv? (my-peek-char port) #\}) (my-read-char port) ; consume closing brace (cond ((eof-object? (my-peek-char port)) '(#\})) ((eqv? (my-peek-char port) #\#) (my-read-char port) ; Consume closing sharp. '()) (#t (append '(#\}) (special-symbol port))))) (#t (append (list (my-read-char port)) (special-symbol port))))) (define hash-pipe-comment-nests? #t) (define (my-string-foldcase s) (string-downcase s)) ; Here's how to import SRFI-69 in guile (for hash tables); ; we have to invoke weird magic becuase guile will complain about merely importing a normal SRFI like this ( which I think is a big mistake , but ca n't fix guile 1.8 ): ; WARNING: (guile-user): imported module (srfi srfi-69) ; overrides core binding `make-hash-table' ; WARNING: (guile-user): imported module (srfi srfi-69) ; overrides core binding `hash-table?' (use-modules ((srfi srfi-69) #:select ((make-hash-table . srfi-69-make-hash-table) (hash-table? . srfi-69-hash-table?) hash-table-set! hash-table-update!/default hash-table-ref hash-table-ref/default hash-table-walk hash-table-delete! ))) ; For "any" (use-modules (srfi srfi-1)) ; There's no portable way to walk through other collections like records. has a " type " " type " procedure but is n't portable ( and it 's not in guile 1.8 at least ) . ; We'll leave it in, but stub it out; you can replace this with what your Scheme supports . Perhaps the " large " R7RS can add support ; for walking through arbitrary collections. (define (type-of x) #f) (define (type? x) #f) ) For Sagittarius Scheme added by (sagittarius ;; Use export syntax (define-syntax readable-kernel-module-contents (syntax-rules () ((readable-kernel-module-contents (exports ...) body ...) (begin (export exports ...) body ...)))) (define (my-peek-char port) (peek-char port)) (define (my-read-char port) (read-char port)) (define (make-read f) (lambda args (let ((real-port (if (null? args) (current-input-port) (car args)))) (f real-port)))) ; invoke the given "actual" reader, most likely ; the builtin one, but make sure to unwrap any ; fake ports. (define (invoke-read read port) (read port)) ;; TODO we do have source info thing (define (get-sourceinfo _) #f) (define (attach-sourceinfo _ x) x) (define (replace-read-with f) (error 'replace-read-with "Not supported, use #!reader= instead")) Well for this SRFI do n't use regular expression :-P (define (parse-hash no-indent-read char fake-port) #f) (define hash-pipe-comment-nests? #t) (define my-string-foldcase string-foldcase) ;; hmm what is this? (define (type-of x) #f) (define (type? x) #f) (define (make-hash-table . dummy) (make-eq-hashtable)) (define hash-table? hashtable?) (define hash-table-set! hashtable-set!) (define hash-table-ref hashtable-ref) (define hash-table-ref/default hashtable-ref) (define hash-table-update!/default hashtable-update!) (define (hash-table-walk ht proc) (let-values (((keys values) (hashtable-entries ht))) (do ((len (vector-length keys)) (i 0 (+ i 1))) ((= i len)) (proc (vector-ref keys i) (vector-ref values i))))) (define hash-table-delete! hashtable-delete!) ;; the reference implementation was only for guile... (define-syntax debug-set! (syntax-rules () ((_ bogus ...) (begin)))) (define-syntax catch (syntax-rules () ((_ name thunk handler) (guard (e ((eq? name e) (handler e)) (else (error name "unexpected throw"))) (thunk))))) (define (throw name) (raise name)) (define force-output flush-output-port) ) ; ----------------------------------------------------------------------------- ; R5RS Compatibility ; ----------------------------------------------------------------------------- (else assume R5RS with define - syntax On R6RS , and other Scheme 's , module contents must ; be entirely inside a top-level module structure. ; Use module-contents to support that. On Schemes ; where module declarations are separate top-level ; expressions, we expect module-contents to transform ; to a simple (begin ...), and possibly include ; whatever declares exported stuff on that Scheme. (define-syntax readable-kernel-module-contents (syntax-rules () ((readable-kernel-module-contents exports body ...) (begin body ...)))) ; We use my-* procedures so that the ; "port" automatically keeps track of source position. ; On Schemes where that is not true (e.g. Racket, where ; source information is passed into a reader and the ; reader is supposed to update it by itself) we can wrap ; the port with the source information, and update that ; source information in the my-* procedures. (define (my-peek-char port) (peek-char port)) (define (my-read-char port) (read-char port)) ; this wrapper procedure wraps a reader procedure ; that accepts a "fake" port above, and converts it to an R5RS - compatible procedure . On Schemes ; which support source-information annotation, ; but use a different way of annotating source - information from , this procedure ; should also probably perform that attachment ; on exit from the given inner procedure. (define (make-read f) (lambda args (let ((real-port (if (null? args) (current-input-port) (car args)))) (f real-port)))) ; invoke the given "actual" reader, most likely ; the builtin one, but make sure to unwrap any ; fake ports. (define (invoke-read read port) (read port)) R5RS does n't have any method of extracting ; or attaching source location information. (define (get-sourceinfo _) #f) (define (attach-sourceinfo _ x) x) Not strictly R5RS but we expect at least some Schemes ; to allow this somehow. (define (replace-read-with f) (set! read f)) R5RS has no hash extensions (define (parse-hash no-indent-read char fake-port) #f) Hash - pipe comment is not in R5RS , but support ; it as an extension, and make them nest. (define hash-pipe-comment-nests? #t) ; If your Scheme supports "string-foldcase", use that instead of ; string-downcase: (define (my-string-foldcase s) (string-downcase s)) ; Somehow get SRFI-69 and SRFI-1 )) ; ----------------------------------------------------------------------------- ; Module declaration and useful utilities ; ----------------------------------------------------------------------------- (readable-kernel-module-contents ; exported procedures (; tier read procedures curly-infix-read neoteric-read sweet-read ; set read mode set-read-mode ; replacing the reader replace-read restore-traditional-read enable-curly-infix enable-neoteric enable-sweet ; Various writers. curly-write-simple neoteric-write-simple curly-write curly-write-cyclic curly-write-shared neoteric-write neoteric-write-cyclic neoteric-write-shared) ; Should we fold case of symbols by default? # f means case - sensitive ( R6RS ) ; # t means case - insensitive ( R5RS ) . ; Here we'll set it to be case-sensitive, which is consistent with R6RS and guile , but NOT with R5RS . Most people wo n't notice , I ; _like_ case-sensitivity, and the latest spec is case-sensitive, ; so let's start with #f (case-sensitive). ; This doesn't affect character names; as an extension, We always accept arbitrary case for them , e.g. , # \newline or # \NEWLINE . (define is-foldcase #f) ; special tag to denote comment return from hash-processing ; Define the whitespace characters, in relatively portable ways Presumes ASCII , Latin-1 , Unicode or similar . # \ht aka \t . # \newline aka \n . FORCE it . \r . (define line-tab (integer->char #x000D)) (define form-feed (integer->char #x000C)) (define vertical-tab (integer->char #x000b)) (define space '#\space) ; Period symbol. A symbol starting with "." is not validly readable in R5RS , R6RS , ( except for ; the peculiar identifier "..."); with the R6RS and the print representation of ; string->symbol(".") should be |.| . However, as an extension, this ; Scheme reader accepts "." as a valid identifier initial character, ; in part because guile permits it. ; For portability, use this formulation instead of '. in this ; implementation so other implementations don't balk at it. (define period-symbol (string->symbol ".")) (define line-ending-chars (list linefeed carriage-return)) This definition of whitespace chars is derived from R6RS section 4.2.1 . ; R6RS doesn't explicitly list the #\space character, be sure to include! (define whitespace-chars-ascii (list tab linefeed line-tab form-feed carriage-return #\space)) ; Note that we are NOT trying to support all Unicode whitespace chars. (define whitespace-chars whitespace-chars-ascii) ; If #t, handle some constructs so we can read and print as Common Lisp. (define common-lisp #f) ; If #t, return |...| symbols as-is, including the vertical bars. (define literal-barred-symbol #f) ; Returns a true value (not necessarily #t) (define (char-line-ending? char) (memv char line-ending-chars)) ; Create own version, in case underlying implementation omits some. (define (my-char-whitespace? c) (or (char-whitespace? c) (memv c whitespace-chars))) Consume an end - of - line sequence , ( ' \r ' ' \n ' ? | ' \n ' ) , and nothing else . Do n't try to handle reversed ( LFCR ) ; doing so will make interactive guile use annoying ( EOF wo n't be correctly detected ) due to a guile bug ( in guile before version 2.0.8 , peek - char incorrectly ; *consumes* EOF instead of just peeking). (define (consume-end-of-line port) (let ((c (my-peek-char port))) (cond ((eqv? c carriage-return) (my-read-char port) (if (eqv? (my-peek-char port) linefeed) (my-read-char port))) ((eqv? c linefeed) (my-read-char port))))) (define (consume-to-eol port) ; Consume every non-eol character in the current line. End on EOF or end - of - line char . ; Do NOT consume the end-of-line character(s). (let ((c (my-peek-char port))) (cond ((and (not (eof-object? c)) (not (char-line-ending? c))) (my-read-char port) (consume-to-eol port))))) (define (consume-to-whitespace port) ; Consume to whitespace (let ((c (my-peek-char port))) (cond ((eof-object? c) c) ((my-char-whitespace? c) '()) (#t (my-read-char port) (consume-to-whitespace port))))) (define debugger-output #f) ; Quick utility for debugging. Display marker, show data, return data. (define (debug-show marker data) (cond (debugger-output (display "DEBUG: ") (display marker) (display " = ") (write data) (display "\n"))) data) (define (my-read-delimited-list my-read stop-char port) ; Read the "inside" of a list until its matching stop-char, returning list. ; stop-char needs to be closing paren, closing bracket, or closing brace. This is like read - delimited - list of Common Lisp , but it ; calls the specified reader instead. ; This implements a useful extension: (. b) returns b. This is ; important as an escape for indented expressions, e.g., (. \\) (consume-whitespace port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) (read-error "EOF in middle of list") c) ((char=? c stop-char) (my-read-char port) (attach-sourceinfo pos '())) ((memv c '(#\) #\] #\})) (read-error "Bad closing character") c) (#t (let ((datum (my-read port))) (cond ((and (eq? datum period-symbol) (char=? c #\.)) (let ((datum2 (my-read port))) (consume-whitespace port) (cond ((eof-object? datum2) (read-error "Early eof in (... .)") '()) ((not (eqv? (my-peek-char port) stop-char)) (read-error "Bad closing character after . datum") datum2) (#t (my-read-char port) datum2)))) (#t (attach-sourceinfo pos (cons datum (my-read-delimited-list my-read stop-char port)))))))))) ; ----------------------------------------------------------------------------- ; Read preservation, replacement, and mode setting ; ----------------------------------------------------------------------------- (define default-scheme-read read) (define replace-read replace-read-with) (define (restore-traditional-read) (replace-read-with default-scheme-read)) (define (enable-curly-infix) (if (not (or (eq? read curly-infix-read) (eq? read neoteric-read) (eq? read sweet-read))) (replace-read curly-infix-read))) (define (enable-neoteric) (if (not (or (eq? read neoteric-read) (eq? read sweet-read))) (replace-read neoteric-read))) (define (enable-sweet) (replace-read sweet-read)) (define current-read-mode #f) (define (set-read-mode mode port) ; TODO: Should be per-port (cond ((eq? mode 'common-lisp) (set! common-lisp #t) #t) ((eq? mode 'literal-barred-symbol) (set! literal-barred-symbol #t) #t) added fixes by ((eq? mode 'fold-case) (set! is-foldcase #t) #t) ((eq? mode 'no-fold-case) (set! is-foldcase #f) #t) (#t (display "Warning: Unknown mode") #f))) ; ----------------------------------------------------------------------------- ; Scheme Reader re-implementation ; ----------------------------------------------------------------------------- ; We have to re-implement our own Scheme reader. ; This takes more code than it would otherwise because many ; Scheme readers will not consider [, ], {, and } as delimiters ( they are not required delimiters in R5RS and R6RS ) . ; Thus, we cannot call down to the underlying reader to implement reading ; many types of values such as symbols. ; If your Scheme's "read" also considers [, ], {, and } as ; delimiters (and thus are not consumed when reading symbols, numbers, etc.), ; then underlying-read could be much simpler. ; We WILL call default-scheme-read on string reading (the ending delimiter ; is ", so that is no problem) - this lets us use the implementation's ; string extensions if any. ; Identifying the list of delimiter characters is harder than you'd think. This list is based on R6RS section 4.2.1 , while adding [ ] and { } , ; but removing "#" from the delimiter set. NOTE : R6RS has " # " has a delimiter . However , R5RS does not , and ; R7RS probably will not - ; shows a strong vote AGAINST "#" being a delimiter. ; Having the "#" as a delimiter means that you cannot have "#" embedded ; in a symbol name, which hurts backwards compatibility, and it also breaks implementations like Chicken ( has many such identifiers ) and ; Gambit (which uses this as a namespace separator). ; Thus, this list does NOT have "#" as a delimiter, contravening R6RS ( but consistent with R5RS , probably R7RS , and several implementations ) . Also - R7RS draft 6 has " | " as delimiter , but we currently do n't . (define neoteric-delimiters (append (list #\( #\) #\[ #\] #\{ #\} ; Add [] {} ) ; Could add # \ # or # \| whitespace-chars)) (define (consume-whitespace port) (let ((char (my-peek-char port))) (cond ((eof-object? char)) ((eqv? char #\;) (consume-to-eol port) (consume-whitespace port)) ((my-char-whitespace? char) (my-read-char port) (consume-whitespace port))))) (define (read-until-delim port delims) ; Read characters until eof or a character in "delims" is seen. ; Do not consume the eof or delimiter. ; Returns the list of chars that were read. (let ((c (my-peek-char port))) (cond ((eof-object? c) '()) ((memv c delims) '()) (#t (my-read-char port) (cons c (read-until-delim port delims)))))) (define (read-error message) (display "Error: " (current-error-port)) (display message (current-error-port)) (newline (current-error-port)) extension to flush output on stderr (force-output (current-error-port)) Guile extension , but many Schemes have exceptions (throw 'readable) '()) ; Return the number by reading from port, and prepending starting-lyst. ; Returns #f if it's not a number. (define (read-number port starting-lyst) (string->number (list->string (append starting-lyst (read-until-delim port neoteric-delimiters))))) ; Return list of digits read from port; may be empty. (define (read-digits port) (let ((c (my-peek-char port))) (cond ((memv c digits) (cons (my-read-char port) (read-digits port))) (#t '())))) (define char-name-values ; Includes standard names and guile extensions; see ; '((space #x0020) (newline #x000a) (nl #x000a) (tab #x0009) (nul #x0000) (null #x0000) (alarm #x0007) (backspace #x0008) (linefeed #x000a) (vtab #x000b) (page #x000c) (return #x000d) (esc #x001b) (delete #x007f) ; Additional character names as extensions: (soh #x0001) (stx #x0002) (etx #x0003) (eot #x0004) (enq #x0005) (ack #x0006) (bel #x0007) (bs #x0008) (ht #x0009) (lf #x000a) (vt #x000b) (ff #x000c) (np #x000c) ; new page (cr #x000d) (so #x000e) (si #x000f) (dle #x0010) (dc1 #x0011) (dc2 #x0012) (dc3 #x0013) (dc4 #x0014) (nak #x0015) (syn #x0016) (etb #x0017) (can #x0018) (em #x0019) (sub #x001a) (fs #x001c) (gs #x001d) (rs #x001e) (sp #x0020) (del #x007f) ; Other non-guile names. ; rubout noted in: -lang.org/reference/characters.html ; It's also required by the Common Lisp spec. (rubout #x007f))) (define (process-char port) ; We've read #\ - returns what it represents. (cond ((eof-object? (my-peek-char port)) (my-peek-char port)) (#t Not EOF . Read in the next character , and start acting on it . (let ((c (my-read-char port)) (rest (read-until-delim port neoteric-delimiters))) (cond only one char after # \ - so that 's it ! More than one char ; do a lookup . (let* ((cname (string->symbol (string-downcase (list->string (cons c rest))))) (found (assq cname char-name-values))) (if found (integer->char (cadr found)) (read-error "Invalid character name"))))))))) ; If fold-case is active on this port, return string "s" in folded case. ; Otherwise, just return "s". This is needed to support our ; is-foldcase configuration value when processing symbols. ; TODO: Should be port-specific (define (fold-case-maybe port s) (if is-foldcase (my-string-foldcase s) s)) (define (process-directive dir) (cond ; TODO: These should be specific to the port. ((string-ci=? dir "sweet") (enable-sweet)) ((string-ci=? dir "no-sweet") (restore-traditional-read)) ((string-ci=? dir "curly-infix") (replace-read curly-infix-read)) ((string-ci=? dir "fold-case") (set! is-foldcase #t)) ((string-ci=? dir "no-fold-case") (set! is-foldcase #f)) (#t (display "Warning: Unknown process directive")))) ; Consume characters until "!#" (define (non-nest-comment port) (let ((c (my-read-char port))) (cond ((eof-object? c) (values)) ((char=? c #\!) (let ((c2 (my-peek-char port))) (if (char=? c2 #\#) (begin (my-read-char port) (values)) (non-nest-comment port)))) (#t (non-nest-comment port))))) (define (process-sharp-bang port) (let ((c (my-peek-char port))) (cond SRFI-22 (consume-to-eol port) (consume-end-of-line port) scomment-result) ; Treat as comment. ((memv c '(#\/ #\.)) ; Multi-line, non-nesting #!/ ... !# or #!. ...!# (non-nest-comment port) scomment-result) ; Treat as comment. ((char-alphabetic? c) ; #!directive (process-directive (list->string (read-until-delim port neoteric-delimiters))) scomment-result) ((or (eqv? c carriage-return) (eqv? c #\newline)) ; Extension: Ignore lone #! (consume-to-eol port) (consume-end-of-line port) scomment-result) ; Treat as comment. (#t (read-error "Unsupported #! combination"))))) ; A cons cell always has a unique address (as determined by eq?); ; we'll use this special cell to tag unmatched datum label references. ; An unmatched datum label will have the form ; (cons unmatched-datum-label-tag NUMBER) (define unmatched-datum-label-tag (cons 'unmatched-datum-label-tag 'label)) (define (is-matching-label-tag? number value) (and (pair? value) (eq? (car value) unmatched-datum-label-tag) (eqv? (cdr value) number))) ; Patch up datum, starting at position, ; so that all labels "number" are replaced ; with the value of "replace". Note that this actually OVERWRITES PORTIONS OF A LIST with " set ! " , ; so that we can maintain "eq?"-ness. This is really wonky, ; but datum labels are themselves wonky. ; "skip" is a list of locations that don't need (re)processing; it ; should be a hash table but those aren't portable. (define (patch-datum-label-tail number replace position skip) (let ((new-skip (cons position skip))) (cond ((and (pair? position) (not (eq? (car position) unmatched-datum-label-tag)) (not (memq position skip))) (if (is-matching-label-tag? number (car position)) (set-car! position replace) ; Yes, "set!" !! (patch-datum-label-tail number replace (car position) new-skip)) (if (is-matching-label-tag? number (cdr position)) (set-cdr! position replace) ; Yes, "set!" !! (patch-datum-label-tail number replace (cdr position) new-skip))) ((vector? position) (do ((len (vector-length position)) (k 0 (+ k 1))) ((>= k len) (values)) (let ((x (vector-ref position k))) (if (is-matching-label-tag? number x) (vector-set! position k replace) (patch-datum-label-tail number replace x new-skip))))) (#t (values))))) (define (patch-datum-label number starting-position) (if (is-matching-label-tag? number starting-position) (read-error "Illegal reference as the labelled object itself")) (patch-datum-label-tail number starting-position starting-position '()) starting-position) ; Gobble up the to-gobble characters from port, and return # ungobbled. (define (gobble-chars port to-gobble) (if (null? to-gobble) 0 (cond ((char-ci=? (my-peek-char port) (car to-gobble)) (my-read-char port) (gobble-chars port (cdr to-gobble))) (#t (length to-gobble))))) (define scomment-result '(scomment ())) (define (process-sharp no-indent-read port) ; We've read a # character. Returns what it represents as ; (stopper value); ('normal value) is value, ('scomment ()) is comment. ; Since we have to re-implement process-sharp anyway, ; the vector representation #(...) uses my-read-delimited-list, which in ; turn calls no-indent-read. ; TODO: Create a readtable for this case. (let ((c (my-peek-char port))) (cond If eof , pretend it 's a comment . Extension - treat # EOL as a comment . Note this does NOT consume the EOL ! (#t ; Try out different readers until we find a match. (my-read-char port) (or (and common-lisp (parse-cl no-indent-read c port)) (parse-hash no-indent-read c port) (parse-default no-indent-read c port) (read-error "Invalid #-prefixed string")))))) (define (parse-default no-indent-read c port) (cond ; Nothing special - use generic rules ((char-ci=? c #\t) (if (memv (gobble-chars port '(#\r #\u #\e)) '(0 3)) '(normal #t) (read-error "Incomplete #true"))) ((char-ci=? c #\f) (if (memv (gobble-chars port '(#\a #\l #\s #\e)) '(0 4)) '(normal #f) (read-error "Incomplete #false"))) ((memv c '(#\i #\e #\b #\o #\d #\x #\I #\E #\B #\O #\D #\X)) (let ((num (read-number port (list #\# (char-downcase c))))) (if num `(normal ,num) (read-error "Not a number after number start")))) ((char=? c #\( ) ; Vector. (list 'normal (list->vector (my-read-delimited-list no-indent-read #\) port)))) ((char=? c #\u ) ; u8 Vector. (cond ((not (eqv? (my-read-char port) #\8 )) (read-error "#u must be followed by 8")) ((not (eqv? (my-read-char port) #\( )) (read-error "#u8 must be followed by left paren")) (#t (list 'normal (list->u8vector (my-read-delimited-list no-indent-read #\) port)))))) ((char=? c #\\) (list 'normal (process-char port))) ; Handle #; (item comment). ((char=? c #\;) (if (memv (my-peek-char port) `(#\space #\tab ,linefeed ,carriage-return)) '(datum-commentw ()) (begin (no-indent-read port) ; Read the datum to be consumed. scomment-result))) ; Return comment ; handle nested comments ((char=? c #\|) (nest-comment port) scomment-result) ; Return comment ((char=? c #\!) (process-sharp-bang port)) Datum label , # num # or # num= ... (let* ((my-digits (read-digits port)) (label (string->number (list->string (cons c my-digits))))) (cond ((eqv? (my-peek-char port) #\#) (my-read-char port) (list 'normal (cons unmatched-datum-label-tag label))) ((eqv? (my-peek-char port) #\=) (my-read-char port) (if (my-char-whitespace? (my-peek-char port)) (read-error "#num= followed by whitespace")) (list 'normal (patch-datum-label label (no-indent-read port)))) (#t (read-error "Datum label #NUM requires = or #"))))) ; R6RS abbreviations #' #` #, #,@ ((char=? c #\') '(abbrev syntax)) ((char=? c #\`) '(abbrev quasisyntax)) ((char=? c #\,) (let ((c2 (my-peek-char port))) (cond ((char=? c2 #\@) (my-read-char port) '(abbrev unsyntax-splicing)) (#t '(abbrev unsyntax))))) ((or (char=? c #\space) (char=? c tab)) ; Extension - treat # (space|tab) as a comment to end of line. This is not required by SRFI-105 or , but it 's handy because " # " is a comment - to - EOL in many other languages ( Bourne shells , Perl , , etc . ) (consume-to-eol port) scomment-result) ; Return comment (#t #f))) (define (parse-cl no-indent-read c port) ; These are for Common Lisp; the "unsweeten" program ; can deal with the +++ ones. (cond ; In theory we could just abbreviate this as "function". ; However, this won't work in expressions like (a . #'b). ((char=? c #\') '(abbrev +++SHARP-QUOTE-abbreviation+++)) ((char=? c #\:) '(abbrev +++SHARP-COLON-abbreviation+++)) ((char=? c #\.) '(abbrev +++SHARP-DOT-abbreviation+++)) ((char=? c #\+) '(abbrev +++SHARP-PLUS-abbreviation+++)) ((char=? c #\P) '(abbrev +++SHARP-P-abbreviation+++)) (#t #f))) Translate " x " to Common Lisp representation if we 're printing CL . ; Basically we use a very unusual representation, and then translate it back (define (translate-cl x) (if common-lisp (case x ((quasiquote) '+++CL-QUASIQUOTE-abbreviation+++) ((unquote) '+++CL-UNQUOTE-abbreviation+++) ((unquote-splicing) '+++CL-UNQUOTE-SPLICING-abbreviation+++) (else x)) x)) ; detect #| or |# (define (nest-comment fake-port) (let ((c (my-read-char fake-port))) (cond ((eof-object? c) (values)) ((char=? c #\|) (let ((c2 (my-peek-char fake-port))) (if (char=? c2 #\#) (begin (my-read-char fake-port) (values)) (nest-comment fake-port)))) ((and hash-pipe-comment-nests? (char=? c #\#)) (let ((c2 (my-peek-char fake-port))) (if (char=? c2 #\|) (begin (my-read-char fake-port) (nest-comment fake-port)) (values)) (nest-comment fake-port))) (#t (nest-comment fake-port))))) (define digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)) (define (process-period port) ; We've peeked a period character. Returns what it represents. (my-read-char port) ; Remove . (let ((c (my-peek-char port))) (cond period eof ; return period . End , for some CL code ((memv c digits) ; period digit - it's a number. (let ((num (read-number port (list #\.)))) (if num num (read-error "period digit must be a number")))) (#t ; At this point, Scheme only requires support for "." or "...". ; As an extension we can support them all. (string->symbol (fold-case-maybe port (list->string (cons #\. (read-until-delim port neoteric-delimiters))))))))) Read an inline hex escape ( after \x ) , return the character it represents (define (read-inline-hex-escape port) (let* ((chars (read-until-delim port (append neoteric-delimiters '(#\;)))) (n (string->number (list->string chars) 16))) (if (eqv? #\; (my-peek-char port)) (my-read-char port) (read-error "Unfinished inline hex escape")) (if (not n) (read-error "Bad inline hex escape")) (integer->char n))) ; We're inside |...| ; return the list of characters inside. ; Do NOT call fold-case-maybe, because we always use literal values here. (define (read-symbol-elements port) (let ((c (my-read-char port))) (cond ((eof-object? c) '()) ((eqv? c #\|) '()) ; Expected end of symbol elements ((eqv? c #\\) (let ((c2 (my-read-char port))) (cond ((eof-object? c) '()) ((eqv? c2 #\|) (cons #\| (read-symbol-elements port))) ((eqv? c2 #\\) (cons #\\ (read-symbol-elements port))) ((eqv? c2 #\a) (cons (integer->char #x0007) (read-symbol-elements port))) ((eqv? c2 #\b) (cons (integer->char #x0008) (read-symbol-elements port))) ((eqv? c2 #\t) (cons (integer->char #x0009) (read-symbol-elements port))) ((eqv? c2 #\n) (cons (integer->char #x000a) (read-symbol-elements port))) ((eqv? c2 #\r) (cons (integer->char #x000d) (read-symbol-elements port))) ((eqv? c2 #\f) (cons (integer->char #x000c) ; extension (read-symbol-elements port))) ((eqv? c2 #\v) (cons (integer->char #x000b) ; extension (read-symbol-elements port))) inline hex escape = \x hex - scalar - value ; (cons (read-inline-hex-escape port) (read-symbol-elements port)))))) (#t (cons c (read-symbol-elements port)))))) ; Extension: When reading |...|, *include* the bars in the symbol, so that ; when we print it out later we know that there were bars there originally. (define (read-literal-symbol port) (let ((c (my-read-char port))) (cond ((eof-object? c) (read-error "EOF inside literal symbol")) ((eqv? c #\|) '(#\|)) ; Expected end of symbol elements ((eqv? c #\\) (let ((c2 (my-read-char port))) (if (eof-object? c) (read-error "EOF after \\ in literal symbol") (cons c (cons c2 (read-literal-symbol port)))))) (#t (cons c (read-literal-symbol port)))))) ; Read |...| symbol (like Common Lisp) This is present in R7RS draft 9 . (define (get-barred-symbol port) (my-read-char port) ; Consume the initial vertical bar. (string->symbol (list->string (if literal-barred-symbol (cons #\| (read-literal-symbol port)) (read-symbol-elements port))))) ; This implements a simple Scheme "read" implementation from "port", ; but if it must recurse to read, it will invoke "no-indent-read" ; (a reader that is NOT indentation-sensitive). ; This additional parameter lets us easily implement additional semantics, ; and then call down to this underlying-read procedure when basic reader ; procedureality (implemented here) is needed. ; This lets us implement both a curly-infix-ONLY-read ; as well as a neoteric-read, without duplicating code. (define (underlying-read no-indent-read port) (consume-whitespace port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) c) ((char=? c #\") ; old readers tend to read strings okay, call it. ( guile 1.8 and gauche / gosh 1.8.11 are fine ) (invoke-read default-scheme-read port)) (#t ; attach the source information to the item read-in (attach-sourceinfo pos (cond ((char=? c #\#) (my-read-char port) (let ((rv (process-sharp no-indent-read port))) (cond ((eq? (car rv) 'scomment) (no-indent-read port)) ((eq? (car rv) 'datum-commentw) (no-indent-read port) ; Consume following datum. (no-indent-read port)) ((eq? (car rv) 'normal) (cadr rv)) ((eq? (car rv) 'abbrev) (list (cadr rv) (no-indent-read port))) (#t (read-error "Unknown # sequence"))))) ((char=? c #\.) (process-period port)) ((or (memv c digits) (char=? c #\+) (char=? c #\-)) (let* ((maybe-number (list->string (read-until-delim port neoteric-delimiters))) (as-number (string->number maybe-number))) (if as-number as-number (string->symbol (fold-case-maybe port maybe-number))))) ((char=? c #\') (my-read-char port) (list (attach-sourceinfo pos 'quote) (no-indent-read port))) ((char=? c #\`) (my-read-char port) (list (attach-sourceinfo pos (translate-cl 'quasiquote)) (no-indent-read port))) ((char=? c #\,) (my-read-char port) (cond ((char=? #\@ (my-peek-char port)) (my-read-char port) (list (attach-sourceinfo pos (translate-cl 'unquote-splicing)) (no-indent-read port))) (#t (list (attach-sourceinfo pos (translate-cl 'unquote)) (no-indent-read port))))) ((char=? c #\( ) (my-read-char port) (my-read-delimited-list no-indent-read #\) port)) ((char=? c #\) ) (my-read-char port) (read-error "Closing parenthesis without opening") (underlying-read no-indent-read port)) ((char=? c #\[ ) (my-read-char port) (my-read-delimited-list no-indent-read #\] port)) ((char=? c #\] ) (my-read-char port) (read-error "Closing bracket without opening") (underlying-read no-indent-read port)) ((char=? c #\} ) (my-read-char port) (read-error "Closing brace without opening") (underlying-read no-indent-read port)) ((char=? c #\| ) Read | ... | symbol ( like Common Lisp and R7RS draft 9 ) (get-barred-symbol port)) (#t ; Nothing else. Must be a symbol start. (string->symbol (fold-case-maybe port (list->string (read-until-delim port neoteric-delimiters))))))))))) ; ----------------------------------------------------------------------------- ; Curly Infix ; ----------------------------------------------------------------------------- Return true if has an even # of parameters , and the ( alternating ) ; first parameters are "op". Used to determine if a longer lyst is infix. ; If passed empty list, returns true (so recursion works correctly). (define (even-and-op-prefix? op lyst) (cond ((null? lyst) #t) ((not (pair? lyst)) #f) ((not (equal? op (car lyst))) #f) ; fail - operators not the same ((not (pair? (cdr lyst))) #f) ; Wrong # of parameters or improper (#t (even-and-op-prefix? op (cddr lyst))))) ; recurse. ; Return true if the lyst is in simple infix format ; (and thus should be reordered at read time). (define (simple-infix-list? lyst) (and (pair? lyst) ; Must have list; '() doesn't count. Must have a second argument . Must have a third argument ( we check it ; this way for performance) (even-and-op-prefix? (cadr lyst) (cdr lyst)))) ; true if rest is simple Return alternating parameters in a list ( 1st , 3rd , 5th , etc . ) (define (alternating-parameters lyst) (if (or (null? lyst) (null? (cdr lyst))) lyst (cons (car lyst) (alternating-parameters (cddr lyst))))) ; Not a simple infix list - transform it. Written as a separate procedure ; so that future experiments or SRFIs can easily replace just this piece. (define (transform-mixed-infix lyst) (cons '$nfx$ lyst)) ; Given curly-infix lyst, map it to its final internal format. (define (process-curly lyst) (cond E.G. , map { } to ( ) . ((null? (cdr lyst)) ; Map {a} to a. (car lyst)) ((and (pair? (cdr lyst)) (null? (cddr lyst))) ; Map {a b} to (a b). lyst) ((simple-infix-list? lyst) ; Map {a OP b [OP c...]} to (OP a b [c...]) (cons (cadr lyst) (alternating-parameters lyst))) (#t (transform-mixed-infix lyst)))) (define (curly-infix-read-real no-indent-read port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) c) ((eqv? c #\;) (consume-to-eol port) (curly-infix-read-real no-indent-read port)) ((my-char-whitespace? c) (my-read-char port) (curly-infix-read-real no-indent-read port)) ((eqv? c #\{) (my-read-char port) ; read in as infix (attach-sourceinfo pos (process-curly (my-read-delimited-list neoteric-read-real #\} port)))) (#t (underlying-read no-indent-read port))))) ; Read using curly-infix-read-real (define (curly-infix-read-nocomment port) (curly-infix-read-real curly-infix-read-nocomment port)) ; ----------------------------------------------------------------------------- Neoteric Expressions ; ----------------------------------------------------------------------------- ; Implement neoteric-expression's prefixed (), [], and {}. ; At this point, we have just finished reading some expression, which ; MIGHT be a prefix of some longer expression. Examine the next ; character to be consumed; if it's an opening paren, bracket, or brace, ; then the expression "prefix" is actually a prefix. ; Otherwise, just return the prefix and do not consume that next char. This recurses , to handle formats like ) . (define (neoteric-process-tail port prefix) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) prefix) ((char=? c #\( ) ; Implement f(x) (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (cons prefix (my-read-delimited-list neoteric-read-nocomment #\) port))))) ((char=? c #\[ ) ; Implement f[x] (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (cons (attach-sourceinfo pos '$bracket-apply$) (cons prefix (my-read-delimited-list neoteric-read-nocomment #\] port)))))) ((char=? c #\{ ) ; Implement f{x} (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (let ((tail (process-curly (my-read-delimited-list neoteric-read-nocomment #\} port)))) (if (eqv? tail '()) (list prefix) ; Map f{} to (f), not (f ()). (list prefix tail)))))) (#t prefix)))) ; This is the "real" implementation of neoteric-read. ; It directly implements unprefixed (), [], and {} so we retain control; ; it calls neoteric-process-tail so f(), f[], and f{} are implemented. (define (neoteric-read-real port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port)) (result (cond ((eof-object? c) c) ((char=? c #\( ) (my-read-char port) (attach-sourceinfo pos (my-read-delimited-list neoteric-read-nocomment #\) port))) ((char=? c #\[ ) (my-read-char port) (attach-sourceinfo pos (my-read-delimited-list neoteric-read-nocomment #\] port))) ((char=? c #\{ ) (my-read-char port) (attach-sourceinfo pos (process-curly (my-read-delimited-list neoteric-read-nocomment #\} port)))) ((my-char-whitespace? c) (my-read-char port) (neoteric-read-real port)) ((eqv? c #\;) (consume-to-eol port) (neoteric-read-real port)) (#t (underlying-read neoteric-read-nocomment port))))) (if (eof-object? result) result (neoteric-process-tail port result)))) (define (neoteric-read-nocomment port) (neoteric-read-real port)) ; ----------------------------------------------------------------------------- Sweet Expressions ( this implementation maps to the BNF ) ; ----------------------------------------------------------------------------- ; There is no standard Scheme mechanism to unread multiple characters. ; Therefore, the key productions and some of their supporting procedures ; return both the information on what ended their reading process, ; as well the actual value (if any) they read before whatever stopped them. ; That way, procedures can process the value as read, and then pass on ; the ending information to whatever needs it next. This approach, ; which we call a "non-tokenizing" implementation, implements a tokenizer ; via procedure calls instead of needing a separate tokenizer. ; The ending information can be: ; - "stopper" - this is returned by productions etc. that do NOT ; read past the of a line (outside of paired characters and strings). ; It is 'normal if it ended normally (e.g., at end of line); else it's ; 'sublist-marker ($), 'group-split-marker (\\), 'collecting (<*), ; 'collecting-end (*>), 'scomment (special comments like #|...|#), or ; 'abbrevw (initial abbreviation with whitespace after it). ; - "new-indent" - this is returned by productions etc. that DO read ; past the end of a line. Such productions typically read the ; next line's indent to determine if they should return. ; If they should, they return the new indent so callers can ; determine what to do next. A "*>" should return even though its ; visible indent level is length 0; we handle this by prepending ; all normal indents with "^", and "*>" generates a length-0 indent ; (which is thus shorter than even an indent of 0 characters). (define-syntax let-splitter (syntax-rules () ((let-splitter (full first-value second-value) expr body ...) (let* ((full expr) (first-value (car full)) (second-value (cadr full))) body ...)))) ; Note: If your Lisp has macros, but doesn't support hygenic macros, it 's probably trivial to reimplement this . E.G. , in Common Lisp : ( defmacro let - splitter ( ( full first - value second - value ) expr & rest body ) ; `(let* ((,full ,expr) ( , first - value ( car , full ) ) ( , second - value ( cadr , full ) ) ) ; ,@body)) (define group-split (string->symbol "\\\\")) First character of split symbol . (define non-whitespace-indent #\!) ; Non-whitespace-indent char. (define sublist (string->symbol "$")) First character of sublist symbol . (define (indentation>? indentation1 indentation2) (let ((len1 (string-length indentation1)) (len2 (string-length indentation2))) (and (> len1 len2) (string=? indentation2 (substring indentation1 0 len2))))) ; Does character "c" begin a line comment (;) or end-of-line? # \newline carriage - return ) ) (define (lcomment-eol? c) (or (eof-object? c) (memv c initial-comment-eol))) ; Return #t if char is space or tab. (define (char-hspace? char) (or (eqv? char #\space) (eqv? char tab))) ; Consume 0+ spaces or tabs (define (hspaces port) (cond ; Use "cond" as "when" for portability. ((char-hspace? (my-peek-char port)) (my-read-char port) (hspaces port)))) ; Return #t if char is space, tab, or ! (define (char-ichar? char) (or (eqv? char #\space) (eqv? char tab) (eqv? char non-whitespace-indent))) (define (accumulate-ichar port) (if (char-ichar? (my-peek-char port)) (cons (my-read-char port) (accumulate-ichar port)) '())) (define (consume-ff-vt port) (let ((c (my-peek-char port))) (cond ((or (eqv? c form-feed) (eqv? c vertical-tab)) (my-read-char port) (consume-ff-vt port))))) Do 2 - item append , but report read - error if the LHS is not a proper list . ; Don't use this if the lhs *must* be a list (e.g., if we have (list x)). (define (my-append lhs rhs) (cond ((eq? lhs empty-value) rhs) ((eq? rhs empty-value) lhs) ((list? lhs) (append lhs rhs)) (#t (read-error "Must have proper list on left-hand-side to append data")))) ; Read an n-expression. Returns ('scomment '()) if it's an scomment, ; else returns ('normal n-expr). ; Note: If a *value* begins with #, process any potential neoteric tail, ; so weird constructs beginning with "#" like #f() will still work. (define (n-expr-or-scomment port) (if (eqv? (my-peek-char port) #\#) (let* ((consumed-sharp (my-read-char port)) (result (process-sharp neoteric-read-nocomment port))) (cond ((eq? (car result) 'normal) (list 'normal (neoteric-process-tail port (cadr result)))) ((eq? (car result) 'abbrev) (list 'normal (list (cadr result) (neoteric-read-nocomment port)))) ((pair? result) result) (#t (read-error "Unsupported hash")))) (list 'normal (neoteric-read-nocomment port)))) ; Read an n-expression. Returns ('normal n-expr) in most cases; ; if it's a special marker, the car is the marker name instead of 'normal. Markers only have special meaning if their first character is ; the "normal" character, e.g., {$} is not a sublist. Call " process - sharp " if first char is " # " . (define (n-expr port) (let ((c (my-peek-char port))) (let-splitter (results type expr) (n-expr-or-scomment port) (if (eq? (car results) 'scomment) results (cond ((and (eq? expr sublist) (eqv? c sublist-char)) (list 'sublist-marker '())) ((and (eq? expr group-split) (eqv? c group-split-char)) (list 'group-split-marker '())) ((and (eq? expr '<*) (eqv? c #\<)) (list 'collecting '())) ((and (eq? expr '*>) (eqv? c #\*)) (list 'collecting-end '())) ((and (eq? expr '$$$) (eqv? c #\$)) (read-error "$$$ is reserved")) ((and (eq? expr period-symbol) (eqv? c #\.)) (list 'period-marker '())) (#t results)))))) ; Check if we have abbrev+whitespace. If the current peeked character ; is one of certain whitespace chars, ; return 'abbrevw as the marker and abbrev-procedure as the value ( the cadr ) . Otherwise , return ( ' normal n - expr ) . We do NOT consume the peeked char ( so EOL can be examined later ) . ; Note that this calls the neoteric-read procedure directly, because quoted markers are no longer markers . E.G. , ' $ is just ( quote $ ) . (define (maybe-initial-abbrev port abbrev-procedure) (let ((c (my-peek-char port))) (if (or (char-hspace? c) (eqv? c carriage-return) (eqv? c linefeed)) (list 'abbrevw abbrev-procedure) (list 'normal (list abbrev-procedure (neoteric-read-nocomment port)))))) Read the first n - expr on a line ; handle abbrev+whitespace specially . ; Returns ('normal VALUE) in most cases. (define (n-expr-first port) (case (my-peek-char port) ((#\') (my-read-char port) (maybe-initial-abbrev port 'quote)) ((#\`) (my-read-char port) (maybe-initial-abbrev port (translate-cl 'quasiquote))) ((#\,) (my-read-char port) (if (eqv? (my-peek-char port) #\@) (begin (my-read-char port) (maybe-initial-abbrev port (translate-cl 'unquote-splicing))) (maybe-initial-abbrev port (translate-cl 'unquote)))) ((#\#) (let* ((consumed-sharp (my-read-char port)) (result (process-sharp neoteric-read-nocomment port))) (cond ((eq? (car result) 'normal) (list 'normal (neoteric-process-tail port (cadr result)))) ((eq? (car result) 'abbrev) (maybe-initial-abbrev port (cadr result))) (#t result)))) (else (n-expr port)))) Consume ; -comment ( if there ) , consume EOL , and return new indent . ; Skip ;-comment-only lines; a following indent-only line is empty. (define (get-next-indent port) (consume-to-eol port) (consume-end-of-line port) (let* ((indentation-as-list (cons #\^ (accumulate-ichar port))) (c (my-peek-char port))) (cond ((eqv? c #\;) ; A ;-only line, consume and try again. (get-next-indent port)) ((lcomment-eol? c) ; Indent-only line (if (memv #\! indentation-as-list) (get-next-indent port) "^")) (#t (list->string indentation-as-list))))) ; Implement (scomment hs | datum-commentw hs n-expr hs) (define (skippable stopper port) (cond ((eq? stopper 'scomment) (hspaces port)) ((eq? stopper 'datum-commentw) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (begin (n-expr port) (hspaces port)) (read-error "Datum comment start not followed a datum (EOL instead)"))) (#t (read-error "skippable: Impossible case")))) ; Utility declarations and functions (define empty-value (string-copy "empty-value")) ; Represent no value at all (define (conse x y) ; cons, but handle "empty" values (cond ((eq? y empty-value) x) ((eq? x empty-value) y) (#t (cons x y)))) (define (appende x y) ; append, but handle "empty" values (cond ((eq? y empty-value) x) ((eq? x empty-value) y) (#t (append y)))) (define (list1e x) ; list, but handle "empty" values (if (eq? x empty-value) '() (list x))) (define (list2e x y) ; list, but handle "empty" values (if (eq? x empty-value) y (if (eq? y empty-value) x (list x y)))) If x is a 1 - element list , return ( car x ) , else return x (define (monify x) (cond ((not (pair? x)) x) ((null? (cdr x)) (car x)) (#t x))) ; Return contents (value) of collecting-content. It does *not* report a ; stopper or ending indent, because it is *ONLY* stopped by collecting-end (define (collecting-content port) (let* ((c (my-peek-char port))) (cond ((eof-object? c) (read-error "Collecting tail: EOF before collecting list ended")) ((lcomment-eol? c) (consume-to-eol port) (consume-end-of-line port) (collecting-content port)) ((char-ichar? c) (let* ((indentation (accumulate-ichar port)) (c (my-peek-char port))) (if (lcomment-eol? c) (collecting-content port) (read-error "Collecting tail: Only ; after indent")))) ((or (eqv? c form-feed) (eqv? c vertical-tab)) (consume-ff-vt port) (if (lcomment-eol? (my-peek-char port)) (collecting-content port) (read-error "Collecting tail: FF and VT must be alone on line"))) (#t (let-splitter (it-full-results it-new-indent it-value) (it-expr port "^") (cond ((string=? it-new-indent "") ; Specially compensate for "*>" at the end of a line if it's after something else . This must be interpreted as EOL * > , ; which would cons a () after the result. ; Directly calling list for a non-null it-value has ; the same effect, but is a lot quicker and simpler. (cond ((null? it-value) it-value) ((eq? it-value empty-value) '()) (#t (list it-value)))) (#t (conse it-value (collecting-content port))))))))) ; Skip scomments and error out if we have a normal n-expr, implementing: ; skippable* (n-expr error)? (define (n-expr-error port full) (if (not (eq? (car full) 'normal)) (read-error "BUG! n-expr-error called but stopper not normal")) (if (lcomment-eol? (my-peek-char port)) full ; All done! (let-splitter (n-full-results n-stopper n-value) (n-expr port) (cond ((or (eq? n-stopper 'scomment) (eq? n-stopper 'datum-commentw)) (skippable n-stopper port) (n-expr-error port full)) ((eq? n-stopper 'normal) (read-error "Illegal second value after .")) (#t ; We found a stopper, return it with the value from "full" (list n-stopper (cadr full))))))) ; Returns (stopper value-after-period) (define (post-period port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (pn-full-results pn-stopper pn-value) (n-expr port) (cond ((or (eq? pn-stopper 'scomment) (eq? pn-stopper 'datum-commentw)) (skippable pn-stopper port) (post-period port)) ((eq? pn-stopper 'normal) (hspaces port) (n-expr-error port pn-full-results)) ((eq? pn-stopper 'collecting) (hspaces port) (let ((cl (collecting-content port))) (hspaces port) (n-expr-error port (list 'normal cl)))) ((eq? pn-stopper 'period-marker) (list 'normal period-symbol)) (#t ; Different stopper; respond as empty branch with that stopper (list pn-stopper (list period-symbol))))) (list 'normal period-symbol))) ; Empty branch. ; Returns (stopper computed-value). ; The stopper may be 'normal, 'scomment (special comment), ; 'abbrevw (initial abbreviation), 'sublist-marker, or 'group-split-marker (define (line-exprs port) (let-splitter (basic-full-results basic-special basic-value) (n-expr-first port) (cond ((eq? basic-special 'collecting) (hspaces port) (let* ((cl-results (collecting-content port))) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (rr-full-results rr-stopper rr-value) (rest-of-line port) (list rr-stopper (cons cl-results rr-value))) (list 'normal (list cl-results))))) ((eq? basic-special 'period-marker) (if (char-hspace? (my-peek-char port)) (begin (hspaces port) (let-splitter (ct-full-results ct-stopper ct-value) (post-period port) (list ct-stopper (list ct-value)))) (list 'normal (list period-symbol)))) ((not (eq? basic-special 'normal)) basic-full-results) ((char-hspace? (my-peek-char port)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (br-full-results br-stopper br-value) (rest-of-line port) (list br-stopper (cons basic-value br-value))) (list 'normal (list basic-value)))) (#t (list 'normal (list basic-value)))))) ; Returns (stopper computed-value); stopper may be 'normal, etc. Read in one n - expr , then process based on whether or not it 's special . (define (rest-of-line port) (let-splitter (basic-full-results basic-special basic-value) (n-expr port) (cond ((or (eq? basic-special 'scomment) (eq? basic-special 'datum-commentw)) (skippable basic-special port) (if (not (lcomment-eol? (my-peek-char port))) (rest-of-line port) (list 'normal '()))) ((eq? basic-special 'collecting) (hspaces port) (let* ((cl-results (collecting-content port))) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (rr-full-results rr-stopper rr-value) (rest-of-line port) (list rr-stopper (cons cl-results rr-value))) (list 'normal (list cl-results))))) ((eq? basic-special 'period-marker) (if (char-hspace? (my-peek-char port)) (begin (hspaces port) (post-period port)) ; (list 'normal (list period-symbol)) ; To interpret as |.| (read-error "Cannot end line with '.'"))) ((not (eq? basic-special 'normal)) (list basic-special '())) ((char-hspace? (my-peek-char port)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (br-full-results br-stopper br-value) (rest-of-line port) (list br-stopper (cons basic-value br-value))) (list 'normal (list basic-value)))) (#t (list 'normal (list basic-value)))))) ; Returns (new-indent computed-value) (define (body port starting-indent) (let-splitter (i-full-results i-new-indent i-value) (it-expr port starting-indent) (if (string=? starting-indent i-new-indent) (if (eq? i-value period-symbol) (let-splitter (f-full-results f-new-indent f-value) (it-expr port i-new-indent) (if (not (indentation>? starting-indent f-new-indent)) (read-error "Dedent required after lone . and value line")) (list f-new-indent f-value)) ; final value of improper list (if (eq? i-value empty-value) (body port i-new-indent) (let-splitter (nxt-full-results nxt-new-indent nxt-value) (body port i-new-indent) (list nxt-new-indent (cons i-value nxt-value))))) (list i-new-indent (list1e i-value))))) ; dedent - end list. ; Returns (new-indent computed-value) (define (it-expr-real port starting-indent) (let-splitter (line-full-results line-stopper line-value) (line-exprs port) (if (and (not (null? line-value)) (not (eq? line-stopper 'abbrevw))) Production line - exprs produced at least one n - expression : (cond ((eq? line-stopper 'group-split-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "Cannot follow split with end of line") (list starting-indent (monify line-value)))) ((eq? line-stopper 'sublist-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "EOL illegal immediately after sublist")) (let-splitter (sub-i-full-results sub-i-new-indent sub-i-value) (it-expr port starting-indent) (list sub-i-new-indent (my-append line-value (list sub-i-value))))) ((eq? line-stopper 'collecting-end) ; Note that indent is "", forcing dedent all the way out. (list "" (if (eq? line-value empty-value) '() (monify line-value)))) ((lcomment-eol? (my-peek-char port)) (let ((new-indent (get-next-indent port))) (if (indentation>? new-indent starting-indent) (let-splitter (body-full body-new-indent body-value) (body port new-indent) (list body-new-indent (my-append line-value body-value))) (list new-indent (monify line-value))))) (#t (read-error "Unexpected text after n-expression"))) ; line-exprs begins with something special like GROUP-SPLIT: (cond ((eq? line-stopper 'datum-commentw) (hspaces port) (cond ((not (lcomment-eol? (my-peek-char port))) (let-splitter (is-i-full-results is-i-new-indent is-i-value) (it-expr port starting-indent) (list is-i-new-indent empty-value))) (#t (let ((new-indent (get-next-indent port))) (if (indentation>? new-indent starting-indent) (let-splitter (body-full-results body-new-indent body-value) (body port new-indent) (list body-new-indent empty-value)) (read-error "#;+EOL must be followed by indent")))))) ((or (eq? line-stopper 'group-split-marker) (eq? line-stopper 'scomment)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (it-expr port starting-indent) ; Skip and try again. (let ((new-indent (get-next-indent port))) (cond ((indentation>? new-indent starting-indent) (body port new-indent)) (#t (list new-indent empty-value)))))) ((eq? line-stopper 'sublist-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "EOL illegal immediately after solo sublist")) (let-splitter (is-i-full-results is-i-new-indent is-i-value) (it-expr port starting-indent) (list is-i-new-indent (list1e is-i-value)))) ((eq? line-stopper 'abbrevw) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (let ((new-indent (get-next-indent port))) (if (not (indentation>? new-indent starting-indent)) (read-error "Indent required after abbreviation")) (let-splitter (ab-full-results ab-new-indent ab-value) (body port new-indent) (list ab-new-indent (append (list line-value) ab-value)))) (let-splitter (ai-full-results ai-new-indent ai-value) (it-expr port starting-indent) (list ai-new-indent (list2e line-value ai-value))))) ((eq? line-stopper 'collecting-end) (list "" line-value)) (#t (read-error "Initial line-expression error")))))) ; Read it-expr. This is a wrapper that attaches source info ; and checks for consistent indentation results. (define (it-expr port starting-indent) (let ((pos (get-sourceinfo port))) (let-splitter (results results-indent results-value) (it-expr-real port starting-indent) (if (indentation>? results-indent starting-indent) (read-error "Inconsistent indentation")) (list results-indent (attach-sourceinfo pos results-value))))) (define (initial-indent-expr-tail port) (if (not (memv (my-peek-char port) initial-comment-eol)) (let-splitter (results results-stopper results-value) (n-expr-or-scomment port) (cond ((memq results-stopper '(scomment datum-commentw)) (skippable results-stopper port) (initial-indent-expr-tail port)) Normal n - expr , return one value . (begin (consume-to-eol port) (consume-end-of-line port) empty-value))) ; (t-expr-real port) ; Top level - read a sweet-expression (t-expression). Handle special ; cases, such as initial indent; call it-expr for normal case. (define (t-expr-real port) (let* ((c (my-peek-char port))) (cond Check EOF early ( a bug in guile before 2.0.8 consumes EOF on peek ) ((eof-object? c) c) ((lcomment-eol? c) (consume-to-eol port) (consume-end-of-line port) (t-expr-real port)) ((or (eqv? c form-feed) (eqv? c vertical-tab)) (consume-ff-vt port) (if (not (lcomment-eol? (my-peek-char port))) (read-error "FF and VT must be alone on line in a sweet-expr")) (t-expr-real port)) ((char-ichar? c) ; initial-indent-expr (accumulate-ichar port) ; consume and throw away ichars (initial-indent-expr-tail port)) (#t (let-splitter (results results-indent results-value) (it-expr port "^") (if (string=? results-indent "") (read-error "Closing *> without preceding matching <*") results-value)))))) ; Top level - read a sweet-expression (t-expression). Handle special (define (t-expr port) (let* ((te (t-expr-real port))) (if (eq? te empty-value) (t-expr port) te))) ; Skip until we find a line with 0 indent characters. ; We use this after read error to resync to good input. (define (read-to-unindented-line port) (let* ((c (my-peek-char port))) (cond ((eof-object? c) c) ((char-line-ending? c) (consume-end-of-line port) (if (char-ichar? (my-peek-char port)) (read-to-unindented-line port))) (#t (consume-to-eol port) (consume-end-of-line port) (read-to-unindented-line port))))) ; Call on sweet-expression reader - use guile's nonstandard catch/throw ; so that errors will force a restart. (define (t-expr-catch port) Default guile stack size is FAR too small (debug-set! stack 500000) (catch 'readable (lambda () (t-expr port)) (lambda (key . args) (read-to-unindented-line port) (t-expr-catch port)))) ; ----------------------------------------------------------------------------- ; Write routines ; ----------------------------------------------------------------------------- ; A list with more than this length and no pairs is considered "boring", ; and thus is presumed to NOT be a procedure call or execution sequence. (define boring-length 16) (define special-infix-operators '(and or xor)) (define punct-chars (list #\! #\" #\# #\$ #\% #\& #\' #\( #\) #\* #\+ #\, #\- # \ < # \= # \ > # \ ? # \@ # \ [ # \\ # \ ] # \^ #\_ #\` #\{ #\| #\} #\~)) Returns # t if x is a list with exactly 1 element . Improper lists are # f. (define (list1? x) (and (pair? x) (null? (cdr x)))) Returns # t if x is a list with exactly 2 elements . Improper lists are # f. (define (list2? x) (and (pair? x) (pair? (cdr x)) (null? (cddr x)))) ; Does x contain a list of ONLY punctuation characters? ; An empty list is considered true. (define (contains-only-punctuation? x) (cond ((null? x) #t) ((not (pair? x)) #f) ((memq (car x) punct-chars) (contains-only-punctuation? (cdr x))) (#t #f))) ; Returns #t if x is a symbol that would typically be used in infix position. (define (is-infix-operator? x) (cond ((not (symbol? x)) #f) ((memq x special-infix-operators) #t) (#t (contains-only-punctuation? (string->list (symbol->string x)))))) ; A possibly-improper list is long and boring if its length is at least ; num-to-go long and it's boring (it contains no pairs up to that length). ; A long-and-boring list is almost certainly NOT a function call or a ; body of some executable sequence - it's almost certainly a long ; boring list of data instead. If it is, we want to display it differently. ; This doesn't get stuck on circular lists; it always terminates after ; num-to-go iterations. (define (long-and-boring? x num-to-go) (cond ((pair? (car x)) #f) ((not (pair? (cdr x))) #f) ((<= num-to-go 1) #t) (#t (long-and-boring? (cdr x) (- num-to-go 1))))) (define (list-no-longer-than? x num-to-go) (cond ((not (pair? x)) #f) ((null? (cdr x)) #t) ; This is the last one! ((not (pair? (cdr x))) #f) ((<= num-to-go 0) #f) (#t (list-no-longer-than? (cdr x) (- num-to-go 1))))) ; Return #t if x should be represented using curly-infix notation {...}. (define (represent-as-infix? x) (and (pair? x) At least 2 elements . (is-infix-operator? (car x)) (list-no-longer-than? x 6))) (define (represent-as-inline-infix? x) Must be 3 + elements ; Return #t if x should be represented as a brace suffix (define (represent-as-brace-suffix? x) (represent-as-infix? x)) ; Define an association list mapping the Scheme procedure names which have ; abbreviations ==> the list of characters in their abbreviation (define abbreviations '((quote (#\')) (quasiquote (#\`)) (unquote (#\,)) (unquote-splicing (#\, #\@)) Scheme syntax - rules . Note that this will abbreviate any 2 - element ; list whose car is "syntax", whether you want that or not! (syntax (#\# #\')) (quasisyntax (#\# #\`)) (unsyntax-splicing (#\# #\, #\@) (unsyntax (#\# #\,))))) ; return #t if we should as a traditional abbreviation, e.g., ' (define (represent-as-abbreviation? x) (and (list2? x) (assq (car x) abbreviations))) ; The car(x) is the symbol for an abbreviation; write the abbreviation. (define (write-abbreviation x port) (for-each (lambda (c) (display c port)) (cadr (assq (car x) abbreviations)))) ; Return list x's *contents* represented as a list of characters. ; Each one must use neoteric-expressions, space-separated; ; it will be surrounded by (...) so no indentation processing is relevant. (define (n-write-list-contents x port) (cond ((null? x) (values)) ((pair? x) (n-write-simple (car x) port) (cond ((not (null? (cdr x))) (display " " port) (n-write-list-contents (cdr x) port)))) (#t (display ". " port) (n-write-simple x port)))) (define (c-write-list-contents x port) (cond ((null? x) (values)) ((pair? x) (c-write-simple (car x) port) (cond ((not (null? (cdr x))) (display " " port) (c-write-list-contents (cdr x) port)))) (#t (display ". " port) (c-write-simple x port)))) ; Return tail of an infix expression, as list of chars ; The "op" is the infix operator represented as a list of chars. (define (infix-tail op x port) (cond ((null? x) (display "}" port)) ((pair? x) (display " " port) (n-write-simple op port) (display " " port) (n-write-simple (car x) port) (infix-tail op (cdr x) port)) (#t (display " " port) (n-write-simple x port) (display "}" port)))) ; Return "x" as a list of characters, surrounded by {...}, for use as f{...}. (define (as-brace-suffix x port) (display "{" port) (if (list2? x) (begin (n-write-list-contents x port) (display "}" port)) (begin (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)))) (define (n-write-simple x port) (cond ((pair? x) (cond ((represent-as-abbreviation? x) ; Format 'x (write-abbreviation x port) (n-write-simple (cadr x) port)) ((long-and-boring? x boring-length) ; Format (a b c ...) (display "(" port) (n-write-list-contents x port) (display ")" port)) ((symbol? (car x)) (cond ((represent-as-inline-infix? x) ; Format {a + b} (display "{" port) (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)) ((and (list1? (cdr x)) ; Format f{...} (pair? (cadr x)) (represent-as-infix? (cadr x))) (n-write-simple (car x) port) (as-brace-suffix (cadr x) port)) (#t ; Format f(...) (n-write-simple (car x) port) (display "(" port) (n-write-list-contents (cdr x) port) (display ")" port)))) (#t ; Format (1 2 3 ...) (display "(" port) (n-write-list-contents x port) (display ")" port)))) ((vector? x) (display "#( " port) ; Surround with spaces, easier to implement. (for-each (lambda (v) (n-write-simple v port) (display " " port)) (vector->list x)) (display ")" port)) (#t (write x port)))) ; Default format. (define (c-write-simple x port) (cond ((pair? x) (cond ((represent-as-abbreviation? x) ; Format 'x (write-abbreviation x port) (c-write-simple (cadr x) port)) ((represent-as-inline-infix? x) ; Format {a + b} (display "{" port) (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)) (#t ; Format (1 2 3 ...) (display "(" port) (c-write-list-contents x port) (display ")" port)))) ((vector? x) (display "#( " port) ; Surround with spaces, easier to implement. (for-each (lambda (v) (c-write-simple v port) (display " " port)) (vector->list x)) (display ")" port)) (#t (write x port)))) ; Default format. Front entry - Use default port if none provided . (define (neoteric-write-simple x . rest) (if (pair? rest) (n-write-simple x (car rest)) (n-write-simple x (current-output-port)))) Front entry - Use default port if none provided . (define (curly-write-simple x . rest) (if (pair? rest) (c-write-simple x (car rest)) (c-write-simple x (current-output-port)))) ;; Write routines for cyclic and shared structures, based on srfi-38. The original code was written by in 2009 and placed in the ;; Public Domain. All warranties are disclaimed. Extracted from Chibi Scheme 0.6.1 . ; We need hash tables for an efficient implementation. on 10 April 2013 said : " ... though not part of R7RS - small , SRFI 69 hash tables are fairly pervasive , because they are ; simple, have a reference implementation, and can be built on top of ; R6RS hashtables (which are standard). The only reason they aren't in more Schemes is that as SRFIs go , 69 is a fairly recent one . I would n't ; hesitate to use them." (define (extract-shared-objects x cyclic-only?) (let ((seen (srfi-69-make-hash-table eq?))) ;; find shared references (let find ((x x)) (let ((type (type-of x))) (cond ;; only interested in pairs, vectors and records ((or (pair? x) (vector? x) (and type (type-printer type))) ;; increment the count (hash-table-update!/default seen x (lambda (n) (+ n 1)) 0) walk if this is the first time (cond ((> (hash-table-ref seen x) 1)) ((pair? x) (find (car x)) (find (cdr x))) ((vector? x) (do ((i 0 (+ i 1))) ((= i (vector-length x))) (find (vector-ref x i)))) (else (let ((num-slots (type-num-slots type))) (let lp ((i 0)) (cond ((< i num-slots) (find (slot-ref type x i)) (lp (+ i 1)))))))) ;; delete if this shouldn't count as a shared reference (if (and cyclic-only? (<= (hash-table-ref/default seen x 0) 1)) (hash-table-delete! seen x)))))) ;; extract shared references (let ((res (srfi-69-make-hash-table eq?))) (hash-table-walk seen (lambda (k v) (if (> v 1) (hash-table-set! res k #t)))) res))) (define (advanced-write-with-shared-structure x port cyclic-only? neoteric?) (let ((shared (extract-shared-objects x cyclic-only?)) (count 0)) ; Returns #t if this part is shared. (define (shared-object? x) (let ((type (type-of x))) (if (or (pair? x) (vector? x) (and type (type-printer type))) (let ((index (hash-table-ref/default shared x #f))) (not (not index))) #f))) Check - shared prints # n # or # n= as appropriate . (define (check-shared x prefix cont) (let ((index (hash-table-ref/default shared x #f))) (cond ((integer? index) (display prefix port) (display "#" port) (write index port) (display "#" port)) (else (cond (index (display prefix port) (display "#" port) (write count port) (display "=" port) (hash-table-set! shared x count) (set! count (+ count 1)))) (cont x index))))) (let wr ((x x) (neoteric? neoteric?)) (define (infix-tail/ss op x port) (cond ((null? x) (display "}" port)) ((pair? x) (display " " port) (wr op #t) (display " " port) (wr (car x) #t) ; Always neoteric inside infix list. (infix-tail/ss op (cdr x) port)) (#t (display " . " port) (n-write-simple x port) (display "}" port)))) (check-shared x "" (lambda (x shared?) (cond Check for special formats first . ((and (represent-as-abbreviation? x) (not (shared-object? (cadr x)))) ; Format 'x (write-abbreviation x port) (wr (cadr x) neoteric?)) ((and (represent-as-inline-infix? x) (not (any shared-object? x))) ; Format {a + b} (display "{" port) (wr (cadr x) #t) ; Always neoteric inside {...} (infix-tail/ss (car x) (cddr x) port)) ((and neoteric? (pair? x) (symbol? (car x)) (list1? (cdr x)) (represent-as-infix? (cadr x)) (not (shared-object? (cdr x))) (not (shared-object? (cadr x))) (not (any shared-object? (cadr x)))) ; Format f{...} (wr (car x) neoteric?) (let ((expr (cadr x))) (if (list2? expr) (begin (display "{" port) (wr (car expr) neoteric?) (display " " port) (wr (cadr expr) neoteric?) (display "}" port)) (begin (wr expr neoteric?))))) ((pair? x) ; Some format ending with closing paren - which one is it? (cond ((and neoteric? (symbol? (car x)) (not (long-and-boring? x boring-length)) (not (shared-object? (cdr x)))) ; I don't like the way it looks Neoteric format a(b c ... ) (wr (car x) neoteric?) (display "(" port)) ; ) (#t ; Default format, (a b c ...) (display "(" port) ; ) (wr (car x) neoteric?) (if (not (null? (cdr x))) (display " " port)))) (let lp ((ls (cdr x))) (check-shared ls ". " (lambda (ls shared?) (cond ((null? ls)) ((pair? ls) (cond (shared? (display "(" port) (wr (car ls) neoteric?) (check-shared (cdr ls) ". " (lambda (ls shared?) (if (not (null? ls)) (display " " port)) (lp ls))) (display ")" port)) (else (wr (car ls) neoteric?) (if (not (null? (cdr ls))) (display " " port)) (lp (cdr ls))))) (else (display ". " port) (wr ls neoteric?)))))) (display ")" port)) ((vector? x) (display "#(" port) (let ((len (vector-length x))) (cond ((> len 0) (wr (vector-ref x 0) neoteric?) (do ((i 1 (+ i 1))) ((= i len)) (display " " port) (wr (vector-ref x i) neoteric?))))) (display ")" port)) ((let ((type (type-of x))) (and (type? type) (type-printer type))) => (lambda (printer) (printer x wr port))) (else (write x port)))))))) (define (curly-write-shared x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #f #f)) (define (curly-write-cyclic x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #t #f)) (define (neoteric-write-shared x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #f #t)) (define (neoteric-write-cyclic x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #t #t)) Since we have " cyclic " versions , the -write forms use them : (define neoteric-write neoteric-write-cyclic) (define curly-write curly-write-cyclic) ; ----------------------------------------------------------------------------- ; Exported Interface ; ----------------------------------------------------------------------------- (define curly-infix-read (make-read curly-infix-read-nocomment)) (define neoteric-read (make-read neoteric-read-nocomment)) (define sweet-read (make-read t-expr-catch)) ) ; vim: set expandtab shiftwidth=2 :
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/srfi/%253a110/kernel.scm
scheme
kernel.scm Implementation of the sweet-expressions project by readable mailinglist. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included 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 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Warning: For portability use eqv?/memv (not eq?/memq) to compare characters. A "case" is okay since it uses "eqv?". This file includes: - Compatibility layer - macros etc. to try to make it easier to port this code to different Scheme implementations (to deal with different module systems, how to override read, getting position info, etc.) - Re-implementation of "read", beginning with its support procedures. There is no standard Scheme mechanism to override just *portions* of read, and we MUST make {} delimiters, so we have to re-implement read. We also need to get control over # so we know which ones are comments. If you're modifying a Scheme implementation, just use that instead. - Curly Infix (c-expression) implementation - Neoteric expression (n-expression) implementation - Sweet-expression (t-expression) implementation a "-simple" implementation, and a separate -shared/-cyclic version. The "-simple" one is separate so that you can use just it. Note that a lot of the code is in the compatibility layer and re-implementation of "read"; implementing the new expression languages is actually pretty easy. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- The compatibility layer is composed of: (readable-kernel-module-contents (exports ...) body ...) - a macro that should package the given body as a module, or whatever your names, in order of preference, depending on your Scheme's package naming conventions/support (readable kernel) readable/kernel readable-kernel sweetimpl procedures. This module shall never export a macro or syntax, not even in the future. - If your Scheme requires module contents to be defined inside a top-level top-level entities after the module declaration) then the other procedures below should be defined inside the module context in order to reduce user namespace pollution. (my-peek-char port) (my-read-char port) - Performs I/O on a "port" object. - The algorithm assumes that port objects have the following abilities: * The port automatically keeps track of source location information that can be attached to objects, so as a fallback you can just ignore source location, which will make debugging using sweet-expressions more difficult. - "port" or fake port objects are created by the make-read procedure below. (make-read procedure) be passed to my-peek-char et al. - make-read creates a new procedure that supports your Scheme's reader interface. Usually, this means making a new procedure that accepts - If your Scheme doesn't keep track of source location information automatically with the ports, you may again need to wrap it here. - If your Scheme needs a particularly magical incantation to attach source information to objects, then you might need to use a weak-key table in the attach-sourceinfo procedure below and then use that weak-key table to perform the magical incantation. (invoke-read read port) - Accepts a read procedure, which is a (most likely built-in) procedure that requires a *real* port, not a fake one. - Should unwrap the fake port to a real port, then invoke the given read procedure on the actual real port. (get-sourceinfo port) - Given a fake port, constructs some object (which the algorithm treats as opaque) to represent the source information at the point that the port is currently in. (attach-sourceinfo pos obj) - Attaches the source information pos, as constructed by get-sourceinfo, to the given obj. - obj can be any valid Scheme object. If your Scheme can only track source location for a subset of Scheme object types, then this procedure should handle it gracefully. - Returns an object with the source information attached - this can be the same object, or a different object that should look-and-feel the same as the passed-in object. - If source information cannot be attached anyway (your Scheme doesn't support attaching source information to objects), just return the given object. (replace-read-with f) - Replaces your Scheme's current reader. - Replace 'read and 'get-datum at the minimum. If your Scheme needs any kind of involved magic to handle load and loading modules correctly, do it here. (parse-hash no-indent-read char fake-port) character combination is encountered in the input port. - this procedure is passed a "fake port", as wrapped by the make-read procedure above. You should probably use my-read-char and my-peek-char in it, or at least unwrap the port (since make-read does the wrapping, and you wrote make-read, we assume you know how to unwrap the port). - if your procedure needs to parse a datum, invoke (no-indent-read fake-port). Do NOT use any other read procedure. The this procedure was passed in. - no-indent-read is either a version of curly-infix-read, or a version this specal version accepts only a fake port . It is never a version of sweet-read. You don't normally want to call sweet-read, because sweet-read presumes that it's starting at the beginning of the line, with indentation processing still active. There's no reason either must be true when processing "#". - At the start of this procedure, both the # and the character after it have been read in. #f - the hash-character combination is invalid/not supported. (normal value) - the datum has value "value". (scomment ()) - the hash-character combination introduced a comment; at the return of this procedure with this value, the comment has been removed from the input port. You can use scomment-result, which has this value. (datum-commentw ()) - #; followed by whitespace. (abbrev value) - this is an abbreviation for value "value" hash-pipe-comment-nests? should nest. my-string-foldcase - a procedure to perform case-folding to lowercase, as mandated this to be string-downcase. Some implementations may also interpret "string-downcase" as foldcase anyway. the rest of the compatibility checks, unfortunately. Sigh. define the module this ensures that the user's module does not get contaminated with our compatibility procedures/macros ----------------------------------------------------------------------------- Guile Compatibility ----------------------------------------------------------------------------- properly get bindings getting confused on the distinction between compile-time, load-time and run-time (apparently, peek-char is not bound during load-time). create a list with the source information destruct the list and attach, but only to cons cells, since To properly hack into 'load and in particular 'use-modules, is supposed to be a current-reader fluid that primitive-load hooks into, but it seems (unverified) that each use-modules creates a new fluid environment, so that this only sticks on a per-module basis. But if the project is primarily in sweet-expressions, we would prefer to have that hook in *all* 'use-modules calls. So our primitive-load uses the 'read global variable if current-reader isn't set. replace primitive-load Below implements some guile extensions, basically as guile 2.0. On Guile 1.6 and 1.8 the only comments are ; and #!..!#, but we'll allow more. ( SRFI-62 ) and # | # | | # | # ( SRFI-30 ) comments exist . on older Guile 1.8 and 1.6 there is a #' syntax but we have yet to figure out what exactly they do, and since those are becoming obsolete, we'll just use the R6RS meaning. (let* ((ver (effective-version)) (c (string-ref ver 0)) On Guile 1.6, #: reads characters until it finds non-symbol characters. On Guile 1.8 and 2.0, #: reads in a datum, and if the datum is not a symbol, throws an error. NOTE: This behavior means that #:foo(bar) will cause Guile's #{ }# syntax Special symbol, through till ...}# Return list of characters inside #{...}#, a guile extension. presume we've already read the sharp and initial open brace. On eof we just end. We could error out instead. and 2.0 have different syntax when spaces, backslashes, and control characters get involved. consume closing brace Consume closing sharp. Here's how to import SRFI-69 in guile (for hash tables); we have to invoke weird magic becuase guile will WARNING: (guile-user): imported module (srfi srfi-69) overrides core binding `make-hash-table' WARNING: (guile-user): imported module (srfi srfi-69) overrides core binding `hash-table?' For "any" There's no portable way to walk through other collections like records. We'll leave it in, but stub it out; you can replace this with for walking through arbitrary collections. Use export syntax invoke the given "actual" reader, most likely the builtin one, but make sure to unwrap any fake ports. TODO we do have source info thing hmm what is this? the reference implementation was only for guile... ----------------------------------------------------------------------------- R5RS Compatibility ----------------------------------------------------------------------------- be entirely inside a top-level module structure. Use module-contents to support that. On Schemes where module declarations are separate top-level expressions, we expect module-contents to transform to a simple (begin ...), and possibly include whatever declares exported stuff on that Scheme. We use my-* procedures so that the "port" automatically keeps track of source position. On Schemes where that is not true (e.g. Racket, where source information is passed into a reader and the reader is supposed to update it by itself) we can wrap the port with the source information, and update that source information in the my-* procedures. this wrapper procedure wraps a reader procedure that accepts a "fake" port above, and converts which support source-information annotation, but use a different way of annotating should also probably perform that attachment on exit from the given inner procedure. invoke the given "actual" reader, most likely the builtin one, but make sure to unwrap any fake ports. or attaching source location information. to allow this somehow. it as an extension, and make them nest. If your Scheme supports "string-foldcase", use that instead of string-downcase: Somehow get SRFI-69 and SRFI-1 ----------------------------------------------------------------------------- Module declaration and useful utilities ----------------------------------------------------------------------------- exported procedures tier read procedures set read mode replacing the reader Various writers. Should we fold case of symbols by default? # t means case - insensitive ( R5RS ) . Here we'll set it to be case-sensitive, which is consistent with R6RS _like_ case-sensitivity, and the latest spec is case-sensitive, so let's start with #f (case-sensitive). This doesn't affect character names; as an extension, special tag to denote comment return from hash-processing Define the whitespace characters, in relatively portable ways Period symbol. A symbol starting with "." is not the peculiar identifier "..."); with the string->symbol(".") should be |.| . However, as an extension, this Scheme reader accepts "." as a valid identifier initial character, in part because guile permits it. For portability, use this formulation instead of '. in this implementation so other implementations don't balk at it. R6RS doesn't explicitly list the #\space character, be sure to include! Note that we are NOT trying to support all Unicode whitespace chars. If #t, handle some constructs so we can read and print as Common Lisp. If #t, return |...| symbols as-is, including the vertical bars. Returns a true value (not necessarily #t) Create own version, in case underlying implementation omits some. doing so will make interactive *consumes* EOF instead of just peeking). Consume every non-eol character in the current line. Do NOT consume the end-of-line character(s). Consume to whitespace Quick utility for debugging. Display marker, show data, return data. Read the "inside" of a list until its matching stop-char, returning list. stop-char needs to be closing paren, closing bracket, or closing brace. calls the specified reader instead. This implements a useful extension: (. b) returns b. This is important as an escape for indented expressions, e.g., (. \\) ----------------------------------------------------------------------------- Read preservation, replacement, and mode setting ----------------------------------------------------------------------------- TODO: Should be per-port ----------------------------------------------------------------------------- Scheme Reader re-implementation ----------------------------------------------------------------------------- We have to re-implement our own Scheme reader. This takes more code than it would otherwise because many Scheme readers will not consider [, ], {, and } as delimiters Thus, we cannot call down to the underlying reader to implement reading many types of values such as symbols. If your Scheme's "read" also considers [, ], {, and } as delimiters (and thus are not consumed when reading symbols, numbers, etc.), then underlying-read could be much simpler. We WILL call default-scheme-read on string reading (the ending delimiter is ", so that is no problem) - this lets us use the implementation's string extensions if any. Identifying the list of delimiter characters is harder than you'd think. but removing "#" from the delimiter set. R7RS probably will not - shows a strong vote AGAINST "#" being a delimiter. Having the "#" as a delimiter means that you cannot have "#" embedded in a symbol name, which hurts backwards compatibility, and it also Gambit (which uses this as a namespace separator). Thus, this list does NOT have "#" as a delimiter, contravening R6RS Add [] {} Could add # \ # or # \| ) Read characters until eof or a character in "delims" is seen. Do not consume the eof or delimiter. Returns the list of chars that were read. Return the number by reading from port, and prepending starting-lyst. Returns #f if it's not a number. Return list of digits read from port; may be empty. Includes standard names and guile extensions; see Additional character names as extensions: new page Other non-guile names. rubout noted in: -lang.org/reference/characters.html It's also required by the Common Lisp spec. We've read #\ - returns what it represents. do a lookup . If fold-case is active on this port, return string "s" in folded case. Otherwise, just return "s". This is needed to support our is-foldcase configuration value when processing symbols. TODO: Should be port-specific TODO: These should be specific to the port. Consume characters until "!#" Treat as comment. Multi-line, non-nesting #!/ ... !# or #!. ...!# Treat as comment. #!directive Extension: Ignore lone #! Treat as comment. A cons cell always has a unique address (as determined by eq?); we'll use this special cell to tag unmatched datum label references. An unmatched datum label will have the form (cons unmatched-datum-label-tag NUMBER) Patch up datum, starting at position, so that all labels "number" are replaced with the value of "replace". so that we can maintain "eq?"-ness. This is really wonky, but datum labels are themselves wonky. "skip" is a list of locations that don't need (re)processing; it should be a hash table but those aren't portable. Yes, "set!" !! Yes, "set!" !! Gobble up the to-gobble characters from port, and return # ungobbled. We've read a # character. Returns what it represents as (stopper value); ('normal value) is value, ('scomment ()) is comment. Since we have to re-implement process-sharp anyway, the vector representation #(...) uses my-read-delimited-list, which in turn calls no-indent-read. TODO: Create a readtable for this case. Try out different readers until we find a match. Nothing special - use generic rules Vector. u8 Vector. Handle #; (item comment). ) Read the datum to be consumed. Return comment handle nested comments Return comment R6RS abbreviations #' #` #, #,@ Extension - treat # (space|tab) as a comment to end of line. Return comment These are for Common Lisp; the "unsweeten" program can deal with the +++ ones. In theory we could just abbreviate this as "function". However, this won't work in expressions like (a . #'b). Basically we use a very unusual representation, and then translate it back detect #| or |# We've peeked a period character. Returns what it represents. Remove . return period . period digit - it's a number. At this point, Scheme only requires support for "." or "...". As an extension we can support them all. )))) (my-peek-char port)) We're inside |...| ; return the list of characters inside. Do NOT call fold-case-maybe, because we always use literal values here. Expected end of symbol elements extension extension Extension: When reading |...|, *include* the bars in the symbol, so that when we print it out later we know that there were bars there originally. Expected end of symbol elements Read |...| symbol (like Common Lisp) Consume the initial vertical bar. This implements a simple Scheme "read" implementation from "port", but if it must recurse to read, it will invoke "no-indent-read" (a reader that is NOT indentation-sensitive). This additional parameter lets us easily implement additional semantics, and then call down to this underlying-read procedure when basic reader procedureality (implemented here) is needed. This lets us implement both a curly-infix-ONLY-read as well as a neoteric-read, without duplicating code. old readers tend to read strings okay, call it. attach the source information to the item read-in Consume following datum. Nothing else. Must be a symbol start. ----------------------------------------------------------------------------- Curly Infix ----------------------------------------------------------------------------- first parameters are "op". Used to determine if a longer lyst is infix. If passed empty list, returns true (so recursion works correctly). fail - operators not the same Wrong # of parameters or improper recurse. Return true if the lyst is in simple infix format (and thus should be reordered at read time). Must have list; '() doesn't count. this way for performance) true if rest is simple Not a simple infix list - transform it. Written as a separate procedure so that future experiments or SRFIs can easily replace just this piece. Given curly-infix lyst, map it to its final internal format. Map {a} to a. Map {a b} to (a b). Map {a OP b [OP c...]} to (OP a b [c...]) ) read in as infix Read using curly-infix-read-real ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Implement neoteric-expression's prefixed (), [], and {}. At this point, we have just finished reading some expression, which MIGHT be a prefix of some longer expression. Examine the next character to be consumed; if it's an opening paren, bracket, or brace, then the expression "prefix" is actually a prefix. Otherwise, just return the prefix and do not consume that next char. Implement f(x) Implement f[x] Implement f{x} Map f{} to (f), not (f ()). This is the "real" implementation of neoteric-read. It directly implements unprefixed (), [], and {} so we retain control; it calls neoteric-process-tail so f(), f[], and f{} are implemented. ) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- There is no standard Scheme mechanism to unread multiple characters. Therefore, the key productions and some of their supporting procedures return both the information on what ended their reading process, as well the actual value (if any) they read before whatever stopped them. That way, procedures can process the value as read, and then pass on the ending information to whatever needs it next. This approach, which we call a "non-tokenizing" implementation, implements a tokenizer via procedure calls instead of needing a separate tokenizer. The ending information can be: - "stopper" - this is returned by productions etc. that do NOT read past the of a line (outside of paired characters and strings). It is 'normal if it ended normally (e.g., at end of line); else it's 'sublist-marker ($), 'group-split-marker (\\), 'collecting (<*), 'collecting-end (*>), 'scomment (special comments like #|...|#), or 'abbrevw (initial abbreviation with whitespace after it). - "new-indent" - this is returned by productions etc. that DO read past the end of a line. Such productions typically read the next line's indent to determine if they should return. If they should, they return the new indent so callers can determine what to do next. A "*>" should return even though its visible indent level is length 0; we handle this by prepending all normal indents with "^", and "*>" generates a length-0 indent (which is thus shorter than even an indent of 0 characters). Note: If your Lisp has macros, but doesn't support hygenic macros, `(let* ((,full ,expr) ,@body)) Non-whitespace-indent char. Does character "c" begin a line comment (;) or end-of-line? Return #t if char is space or tab. Consume 0+ spaces or tabs Use "cond" as "when" for portability. Return #t if char is space, tab, or ! Don't use this if the lhs *must* be a list (e.g., if we have (list x)). Read an n-expression. Returns ('scomment '()) if it's an scomment, else returns ('normal n-expr). Note: If a *value* begins with #, process any potential neoteric tail, so weird constructs beginning with "#" like #f() will still work. Read an n-expression. Returns ('normal n-expr) in most cases; if it's a special marker, the car is the marker name instead of 'normal. the "normal" character, e.g., {$} is not a sublist. Check if we have abbrev+whitespace. If the current peeked character is one of certain whitespace chars, return 'abbrevw as the marker and abbrev-procedure Note that this calls the neoteric-read procedure directly, because handle abbrev+whitespace specially . Returns ('normal VALUE) in most cases. -comment ( if there ) , consume EOL , and return new indent . Skip ;-comment-only lines; a following indent-only line is empty. ) ; A ;-only line, consume and try again. Indent-only line Implement (scomment hs | datum-commentw hs n-expr hs) Utility declarations and functions Represent no value at all cons, but handle "empty" values append, but handle "empty" values list, but handle "empty" values list, but handle "empty" values Return contents (value) of collecting-content. It does *not* report a stopper or ending indent, because it is *ONLY* stopped by collecting-end Specially compensate for "*>" at the end of a line if it's which would cons a () after the result. Directly calling list for a non-null it-value has the same effect, but is a lot quicker and simpler. Skip scomments and error out if we have a normal n-expr, implementing: skippable* (n-expr error)? All done! We found a stopper, return it with the value from "full" Returns (stopper value-after-period) Different stopper; respond as empty branch with that stopper Empty branch. Returns (stopper computed-value). The stopper may be 'normal, 'scomment (special comment), 'abbrevw (initial abbreviation), 'sublist-marker, or 'group-split-marker Returns (stopper computed-value); stopper may be 'normal, etc. (list 'normal (list period-symbol)) ; To interpret as |.| Returns (new-indent computed-value) final value of improper list dedent - end list. Returns (new-indent computed-value) Note that indent is "", forcing dedent all the way out. line-exprs begins with something special like GROUP-SPLIT: Skip and try again. Read it-expr. This is a wrapper that attaches source info and checks for consistent indentation results. (t-expr-real port) Top level - read a sweet-expression (t-expression). Handle special cases, such as initial indent; call it-expr for normal case. initial-indent-expr consume and throw away ichars Top level - read a sweet-expression (t-expression). Handle special Skip until we find a line with 0 indent characters. We use this after read error to resync to good input. Call on sweet-expression reader - use guile's nonstandard catch/throw so that errors will force a restart. ----------------------------------------------------------------------------- Write routines ----------------------------------------------------------------------------- A list with more than this length and no pairs is considered "boring", and thus is presumed to NOT be a procedure call or execution sequence. Does x contain a list of ONLY punctuation characters? An empty list is considered true. Returns #t if x is a symbol that would typically be used in infix position. A possibly-improper list is long and boring if its length is at least num-to-go long and it's boring (it contains no pairs up to that length). A long-and-boring list is almost certainly NOT a function call or a body of some executable sequence - it's almost certainly a long boring list of data instead. If it is, we want to display it differently. This doesn't get stuck on circular lists; it always terminates after num-to-go iterations. This is the last one! Return #t if x should be represented using curly-infix notation {...}. Return #t if x should be represented as a brace suffix Define an association list mapping the Scheme procedure names which have abbreviations ==> the list of characters in their abbreviation list whose car is "syntax", whether you want that or not! return #t if we should as a traditional abbreviation, e.g., ' The car(x) is the symbol for an abbreviation; write the abbreviation. Return list x's *contents* represented as a list of characters. Each one must use neoteric-expressions, space-separated; it will be surrounded by (...) so no indentation processing is relevant. Return tail of an infix expression, as list of chars The "op" is the infix operator represented as a list of chars. Return "x" as a list of characters, surrounded by {...}, for use as f{...}. Format 'x Format (a b c ...) Format {a + b} Format f{...} Format f(...) Format (1 2 3 ...) Surround with spaces, easier to implement. Default format. Format 'x Format {a + b} Format (1 2 3 ...) Surround with spaces, easier to implement. Default format. Write routines for cyclic and shared structures, based on srfi-38. Public Domain. All warranties are disclaimed. We need hash tables for an efficient implementation. simple, have a reference implementation, and can be built on top of R6RS hashtables (which are standard). The only reason they aren't in hesitate to use them." find shared references only interested in pairs, vectors and records increment the count delete if this shouldn't count as a shared reference extract shared references Returns #t if this part is shared. Always neoteric inside infix list. Format 'x Format {a + b} Always neoteric inside {...} Format f{...} Some format ending with closing paren - which one is it? I don't like the way it looks ) Default format, (a b c ...) ) ----------------------------------------------------------------------------- Exported Interface ----------------------------------------------------------------------------- vim: set expandtab shiftwidth=2 :
Copyright ( C ) 2005 - 2013 by and This software is released as open source software under the " MIT " license : to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , - Implementation of writers for curly - infix and neoteric expressions - Compatibility Layer scheme calls it ( chicken eggs ? ) , preferably with one of the following - The first element after the module - contents name is a list of exported module declaration ( unlike where module contents are declared as information . On R5RS there is no source location - The given procedure accepts exactly 1 argument , a " fake port " that can either 0 or 1 parameters , defaulting to ( current - input - port ) . - a procedure that is invoked when an unrecognized , non - R5RS hash no - indent - read procedure accepts exactly one parameter - the fake port - The procedure returns one of the following : - a Boolean value that specifies whether # | ... | # comments by Unicode . If your implementation does n't have Unicode , define On Guile 2.0 , the define - module part needs to occur separately from (cond-expand (guile (define-module (readable kernel))) (else #t)) (cond-expand (guile (use-modules (guile)) On 1.x defmacro is the only thing supported out - of - the - box . This form still exists in Guile 2.x , fortunately . (defmacro readable-kernel-module-contents (exports . body) `(begin (export ,@exports) ,@body)) Enable R5RS hygenic macro system ( define - syntax ) - guile 1.X does not automatically provide it , but version 1.6 + enable it this way (use-syntax (ice-9 syncase)) was the original development environment , so the algorithm practically acts as if it is in . Needs to be lambdas because otherwise 2.0 acts strangely , (define (my-peek-char fake-port) (if (eof-object? (car fake-port)) (car fake-port) (let* ((port (car fake-port)) (char (peek-char port))) (if (eof-object? char) (set-car! fake-port char)) char))) (define (my-read-char fake-port) (if (eof-object? (car fake-port)) (car fake-port) (let* ((port (car fake-port)) (char (read-char port))) (if (eof-object? char) (set-car! fake-port char)) char))) (define (make-read f) (lambda args (let ((port (if (null? args) (current-input-port) (car args)))) (f (list port))))) (define (invoke-read read fake-port) (if (eof-object? (car fake-port)) (car fake-port) (read (car fake-port)))) (define (get-sourceinfo fake-port) (if (eof-object? (car fake-port)) #f (let ((port (car fake-port))) (list (port-filename port) (port-line port) (port-column port))))) only that is reliably supported across versions . (define (attach-sourceinfo pos obj) (cond ((not pos) obj) ((pair? obj) (set-source-property! obj 'filename (list-ref pos 0)) (set-source-property! obj 'line (list-ref pos 1)) (set-source-property! obj 'column (list-ref pos 2)) obj) (#t obj))) we need to hack into ' primitive - load . On 1.8 and 2.0 there (define %sugar-current-load-port #f) (define primitive-load-replaced #f) (define (setup-primitive-load) (cond (primitive-load-replaced (values)) (#t (module-set! (resolve-module '(guile)) 'primitive-load (lambda (filename) (let ((hook (cond ((not %load-hook) #f) ((not (procedure? %load-hook)) (error "%load-hook must be procedure or #f")) (#t %load-hook)))) (cond (hook (hook filename))) (let* ((port (open-input-file filename)) (save-port port)) (define (load-loop) (let* ((the-read (or current - reader does n't exist on 1.6 (if (string=? "1.6" (effective-version)) #f (fluid-ref current-reader)) read)) (form (the-read port))) (cond ((not (eof-object? form)) in only (primitive-eval form) (load-loop))))) (define (swap-ports) (let ((tmp %sugar-current-load-port)) (set! %sugar-current-load-port save-port) (set! save-port tmp))) (dynamic-wind swap-ports load-loop swap-ports) (close-input-port port))))) (set! primitive-load-replaced #t)))) (define (replace-read-with f) (setup-primitive-load) (set! read f)) On , # :x is a keyword . Keywords have symbol syntax . (define (parse-hash no-indent-read char fake-port) ( > = 2 ( and ( not ( char= ? c # \0 ) ) ( not ( char= ? c # \1 ) ) ) ) ) ... ) (cond ((char=? char #\:) Follow the 1.8/2.0 behavior as it is simpler to implement , and even on 1.6 it is unlikely to cause problems . problems on neoteric and higher tiers . (let ((s (no-indent-read fake-port))) (if (symbol? s) `(normal ,(symbol->keyword s) ) #f))) On Guile 2.0 # ' # ` # , # , @ have the R6RS meaning , handled in generics . Guile 1.6 and 1.8 have different meanings , but we 'll ignore that . `(normal ,(list->symbol (special-symbol fake-port)))) (#t #f))) TODO : actually conform to 's syntax . Note that 1.x (define (special-symbol port) (cond ((eof-object? (my-peek-char port)) '()) ((eqv? (my-peek-char port) #\}) (cond ((eof-object? (my-peek-char port)) '(#\})) ((eqv? (my-peek-char port) #\#) '()) (#t (append '(#\}) (special-symbol port))))) (#t (append (list (my-read-char port)) (special-symbol port))))) (define hash-pipe-comment-nests? #t) (define (my-string-foldcase s) (string-downcase s)) complain about merely importing a normal SRFI like this ( which I think is a big mistake , but ca n't fix guile 1.8 ): (use-modules ((srfi srfi-69) #:select ((make-hash-table . srfi-69-make-hash-table) (hash-table? . srfi-69-hash-table?) hash-table-set! hash-table-update!/default hash-table-ref hash-table-ref/default hash-table-walk hash-table-delete! ))) (use-modules (srfi srfi-1)) has a " type " " type " procedure but is n't portable ( and it 's not in guile 1.8 at least ) . what your Scheme supports . Perhaps the " large " R7RS can add support (define (type-of x) #f) (define (type? x) #f) ) For Sagittarius Scheme added by (sagittarius (define-syntax readable-kernel-module-contents (syntax-rules () ((readable-kernel-module-contents (exports ...) body ...) (begin (export exports ...) body ...)))) (define (my-peek-char port) (peek-char port)) (define (my-read-char port) (read-char port)) (define (make-read f) (lambda args (let ((real-port (if (null? args) (current-input-port) (car args)))) (f real-port)))) (define (invoke-read read port) (read port)) (define (get-sourceinfo _) #f) (define (attach-sourceinfo _ x) x) (define (replace-read-with f) (error 'replace-read-with "Not supported, use #!reader= instead")) Well for this SRFI do n't use regular expression :-P (define (parse-hash no-indent-read char fake-port) #f) (define hash-pipe-comment-nests? #t) (define my-string-foldcase string-foldcase) (define (type-of x) #f) (define (type? x) #f) (define (make-hash-table . dummy) (make-eq-hashtable)) (define hash-table? hashtable?) (define hash-table-set! hashtable-set!) (define hash-table-ref hashtable-ref) (define hash-table-ref/default hashtable-ref) (define hash-table-update!/default hashtable-update!) (define (hash-table-walk ht proc) (let-values (((keys values) (hashtable-entries ht))) (do ((len (vector-length keys)) (i 0 (+ i 1))) ((= i len)) (proc (vector-ref keys i) (vector-ref values i))))) (define hash-table-delete! hashtable-delete!) (define-syntax debug-set! (syntax-rules () ((_ bogus ...) (begin)))) (define-syntax catch (syntax-rules () ((_ name thunk handler) (guard (e ((eq? name e) (handler e)) (else (error name "unexpected throw"))) (thunk))))) (define (throw name) (raise name)) (define force-output flush-output-port) ) (else assume R5RS with define - syntax On R6RS , and other Scheme 's , module contents must (define-syntax readable-kernel-module-contents (syntax-rules () ((readable-kernel-module-contents exports body ...) (begin body ...)))) (define (my-peek-char port) (peek-char port)) (define (my-read-char port) (read-char port)) it to an R5RS - compatible procedure . On Schemes source - information from , this procedure (define (make-read f) (lambda args (let ((real-port (if (null? args) (current-input-port) (car args)))) (f real-port)))) (define (invoke-read read port) (read port)) R5RS does n't have any method of extracting (define (get-sourceinfo _) #f) (define (attach-sourceinfo _ x) x) Not strictly R5RS but we expect at least some Schemes (define (replace-read-with f) (set! read f)) R5RS has no hash extensions (define (parse-hash no-indent-read char fake-port) #f) Hash - pipe comment is not in R5RS , but support (define hash-pipe-comment-nests? #t) (define (my-string-foldcase s) (string-downcase s)) )) (readable-kernel-module-contents curly-infix-read neoteric-read sweet-read set-read-mode replace-read restore-traditional-read enable-curly-infix enable-neoteric enable-sweet curly-write-simple neoteric-write-simple curly-write curly-write-cyclic curly-write-shared neoteric-write neoteric-write-cyclic neoteric-write-shared) and guile , but NOT with R5RS . Most people wo n't notice , I We always accept arbitrary case for them , e.g. , # \newline or # \NEWLINE . (define is-foldcase #f) Presumes ASCII , Latin-1 , Unicode or similar . # \ht aka \t . # \newline aka \n . FORCE it . \r . (define line-tab (integer->char #x000D)) (define form-feed (integer->char #x000C)) (define vertical-tab (integer->char #x000b)) (define space '#\space) validly readable in R5RS , R6RS , ( except for R6RS and the print representation of (define period-symbol (string->symbol ".")) (define line-ending-chars (list linefeed carriage-return)) This definition of whitespace chars is derived from R6RS section 4.2.1 . (define whitespace-chars-ascii (list tab linefeed line-tab form-feed carriage-return #\space)) (define whitespace-chars whitespace-chars-ascii) (define common-lisp #f) (define literal-barred-symbol #f) (define (char-line-ending? char) (memv char line-ending-chars)) (define (my-char-whitespace? c) (or (char-whitespace? c) (memv c whitespace-chars))) Consume an end - of - line sequence , ( ' \r ' ' \n ' ? | ' \n ' ) , and nothing else . guile use annoying ( EOF wo n't be correctly detected ) due to a guile bug ( in guile before version 2.0.8 , peek - char incorrectly (define (consume-end-of-line port) (let ((c (my-peek-char port))) (cond ((eqv? c carriage-return) (my-read-char port) (if (eqv? (my-peek-char port) linefeed) (my-read-char port))) ((eqv? c linefeed) (my-read-char port))))) (define (consume-to-eol port) End on EOF or end - of - line char . (let ((c (my-peek-char port))) (cond ((and (not (eof-object? c)) (not (char-line-ending? c))) (my-read-char port) (consume-to-eol port))))) (define (consume-to-whitespace port) (let ((c (my-peek-char port))) (cond ((eof-object? c) c) ((my-char-whitespace? c) '()) (#t (my-read-char port) (consume-to-whitespace port))))) (define debugger-output #f) (define (debug-show marker data) (cond (debugger-output (display "DEBUG: ") (display marker) (display " = ") (write data) (display "\n"))) data) (define (my-read-delimited-list my-read stop-char port) This is like read - delimited - list of Common Lisp , but it (consume-whitespace port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) (read-error "EOF in middle of list") c) ((char=? c stop-char) (my-read-char port) (attach-sourceinfo pos '())) ((memv c '(#\) #\] #\})) (read-error "Bad closing character") c) (#t (let ((datum (my-read port))) (cond ((and (eq? datum period-symbol) (char=? c #\.)) (let ((datum2 (my-read port))) (consume-whitespace port) (cond ((eof-object? datum2) (read-error "Early eof in (... .)") '()) ((not (eqv? (my-peek-char port) stop-char)) (read-error "Bad closing character after . datum") datum2) (#t (my-read-char port) datum2)))) (#t (attach-sourceinfo pos (cons datum (my-read-delimited-list my-read stop-char port)))))))))) (define default-scheme-read read) (define replace-read replace-read-with) (define (restore-traditional-read) (replace-read-with default-scheme-read)) (define (enable-curly-infix) (if (not (or (eq? read curly-infix-read) (eq? read neoteric-read) (eq? read sweet-read))) (replace-read curly-infix-read))) (define (enable-neoteric) (if (not (or (eq? read neoteric-read) (eq? read sweet-read))) (replace-read neoteric-read))) (define (enable-sweet) (replace-read sweet-read)) (define current-read-mode #f) (define (set-read-mode mode port) (cond ((eq? mode 'common-lisp) (set! common-lisp #t) #t) ((eq? mode 'literal-barred-symbol) (set! literal-barred-symbol #t) #t) added fixes by ((eq? mode 'fold-case) (set! is-foldcase #t) #t) ((eq? mode 'no-fold-case) (set! is-foldcase #f) #t) (#t (display "Warning: Unknown mode") #f))) ( they are not required delimiters in R5RS and R6RS ) . This list is based on R6RS section 4.2.1 , while adding [ ] and { } , NOTE : R6RS has " # " has a delimiter . However , R5RS does not , and breaks implementations like Chicken ( has many such identifiers ) and ( but consistent with R5RS , probably R7RS , and several implementations ) . Also - R7RS draft 6 has " | " as delimiter , but we currently do n't . (define neoteric-delimiters whitespace-chars)) (define (consume-whitespace port) (let ((char (my-peek-char port))) (cond ((eof-object? char)) (consume-to-eol port) (consume-whitespace port)) ((my-char-whitespace? char) (my-read-char port) (consume-whitespace port))))) (define (read-until-delim port delims) (let ((c (my-peek-char port))) (cond ((eof-object? c) '()) ((memv c delims) '()) (#t (my-read-char port) (cons c (read-until-delim port delims)))))) (define (read-error message) (display "Error: " (current-error-port)) (display message (current-error-port)) (newline (current-error-port)) extension to flush output on stderr (force-output (current-error-port)) Guile extension , but many Schemes have exceptions (throw 'readable) '()) (define (read-number port starting-lyst) (string->number (list->string (append starting-lyst (read-until-delim port neoteric-delimiters))))) (define (read-digits port) (let ((c (my-peek-char port))) (cond ((memv c digits) (cons (my-read-char port) (read-digits port))) (#t '())))) (define char-name-values '((space #x0020) (newline #x000a) (nl #x000a) (tab #x0009) (nul #x0000) (null #x0000) (alarm #x0007) (backspace #x0008) (linefeed #x000a) (vtab #x000b) (page #x000c) (return #x000d) (esc #x001b) (delete #x007f) (soh #x0001) (stx #x0002) (etx #x0003) (eot #x0004) (enq #x0005) (ack #x0006) (bel #x0007) (bs #x0008) (ht #x0009) (lf #x000a) (vt #x000b) (ff #x000c) (cr #x000d) (so #x000e) (si #x000f) (dle #x0010) (dc1 #x0011) (dc2 #x0012) (dc3 #x0013) (dc4 #x0014) (nak #x0015) (syn #x0016) (etb #x0017) (can #x0018) (em #x0019) (sub #x001a) (fs #x001c) (gs #x001d) (rs #x001e) (sp #x0020) (del #x007f) (rubout #x007f))) (define (process-char port) (cond ((eof-object? (my-peek-char port)) (my-peek-char port)) (#t Not EOF . Read in the next character , and start acting on it . (let ((c (my-read-char port)) (rest (read-until-delim port neoteric-delimiters))) (cond only one char after # \ - so that 's it ! (let* ((cname (string->symbol (string-downcase (list->string (cons c rest))))) (found (assq cname char-name-values))) (if found (integer->char (cadr found)) (read-error "Invalid character name"))))))))) (define (fold-case-maybe port s) (if is-foldcase (my-string-foldcase s) s)) (define (process-directive dir) (cond ((string-ci=? dir "sweet") (enable-sweet)) ((string-ci=? dir "no-sweet") (restore-traditional-read)) ((string-ci=? dir "curly-infix") (replace-read curly-infix-read)) ((string-ci=? dir "fold-case") (set! is-foldcase #t)) ((string-ci=? dir "no-fold-case") (set! is-foldcase #f)) (#t (display "Warning: Unknown process directive")))) (define (non-nest-comment port) (let ((c (my-read-char port))) (cond ((eof-object? c) (values)) ((char=? c #\!) (let ((c2 (my-peek-char port))) (if (char=? c2 #\#) (begin (my-read-char port) (values)) (non-nest-comment port)))) (#t (non-nest-comment port))))) (define (process-sharp-bang port) (let ((c (my-peek-char port))) (cond SRFI-22 (consume-to-eol port) (consume-end-of-line port) (non-nest-comment port) (process-directive (list->string (read-until-delim port neoteric-delimiters))) scomment-result) ((or (eqv? c carriage-return) (eqv? c #\newline)) (consume-to-eol port) (consume-end-of-line port) (#t (read-error "Unsupported #! combination"))))) (define unmatched-datum-label-tag (cons 'unmatched-datum-label-tag 'label)) (define (is-matching-label-tag? number value) (and (pair? value) (eq? (car value) unmatched-datum-label-tag) (eqv? (cdr value) number))) Note that this actually OVERWRITES PORTIONS OF A LIST with " set ! " , (define (patch-datum-label-tail number replace position skip) (let ((new-skip (cons position skip))) (cond ((and (pair? position) (not (eq? (car position) unmatched-datum-label-tag)) (not (memq position skip))) (if (is-matching-label-tag? number (car position)) (patch-datum-label-tail number replace (car position) new-skip)) (if (is-matching-label-tag? number (cdr position)) (patch-datum-label-tail number replace (cdr position) new-skip))) ((vector? position) (do ((len (vector-length position)) (k 0 (+ k 1))) ((>= k len) (values)) (let ((x (vector-ref position k))) (if (is-matching-label-tag? number x) (vector-set! position k replace) (patch-datum-label-tail number replace x new-skip))))) (#t (values))))) (define (patch-datum-label number starting-position) (if (is-matching-label-tag? number starting-position) (read-error "Illegal reference as the labelled object itself")) (patch-datum-label-tail number starting-position starting-position '()) starting-position) (define (gobble-chars port to-gobble) (if (null? to-gobble) 0 (cond ((char-ci=? (my-peek-char port) (car to-gobble)) (my-read-char port) (gobble-chars port (cdr to-gobble))) (#t (length to-gobble))))) (define scomment-result '(scomment ())) (define (process-sharp no-indent-read port) (let ((c (my-peek-char port))) (cond If eof , pretend it 's a comment . Extension - treat # EOL as a comment . Note this does NOT consume the EOL ! (my-read-char port) (or (and common-lisp (parse-cl no-indent-read c port)) (parse-hash no-indent-read c port) (parse-default no-indent-read c port) (read-error "Invalid #-prefixed string")))))) (define (parse-default no-indent-read c port) ((char-ci=? c #\t) (if (memv (gobble-chars port '(#\r #\u #\e)) '(0 3)) '(normal #t) (read-error "Incomplete #true"))) ((char-ci=? c #\f) (if (memv (gobble-chars port '(#\a #\l #\s #\e)) '(0 4)) '(normal #f) (read-error "Incomplete #false"))) ((memv c '(#\i #\e #\b #\o #\d #\x #\I #\E #\B #\O #\D #\X)) (let ((num (read-number port (list #\# (char-downcase c))))) (if num `(normal ,num) (read-error "Not a number after number start")))) (list 'normal (list->vector (my-read-delimited-list no-indent-read #\) port)))) (cond ((not (eqv? (my-read-char port) #\8 )) (read-error "#u must be followed by 8")) ((not (eqv? (my-read-char port) #\( )) (read-error "#u8 must be followed by left paren")) (#t (list 'normal (list->u8vector (my-read-delimited-list no-indent-read #\) port)))))) ((char=? c #\\) (list 'normal (process-char port))) (if (memv (my-peek-char port) `(#\space #\tab ,linefeed ,carriage-return)) '(datum-commentw ()) (begin ((char=? c #\|) (nest-comment port) ((char=? c #\!) (process-sharp-bang port)) Datum label , # num # or # num= ... (let* ((my-digits (read-digits port)) (label (string->number (list->string (cons c my-digits))))) (cond ((eqv? (my-peek-char port) #\#) (my-read-char port) (list 'normal (cons unmatched-datum-label-tag label))) ((eqv? (my-peek-char port) #\=) (my-read-char port) (if (my-char-whitespace? (my-peek-char port)) (read-error "#num= followed by whitespace")) (list 'normal (patch-datum-label label (no-indent-read port)))) (#t (read-error "Datum label #NUM requires = or #"))))) ((char=? c #\') '(abbrev syntax)) ((char=? c #\`) '(abbrev quasisyntax)) ((char=? c #\,) (let ((c2 (my-peek-char port))) (cond ((char=? c2 #\@) (my-read-char port) '(abbrev unsyntax-splicing)) (#t '(abbrev unsyntax))))) ((or (char=? c #\space) (char=? c tab)) This is not required by SRFI-105 or , but it 's handy because " # " is a comment - to - EOL in many other languages ( Bourne shells , Perl , , etc . ) (consume-to-eol port) (#t #f))) (define (parse-cl no-indent-read c port) (cond ((char=? c #\') '(abbrev +++SHARP-QUOTE-abbreviation+++)) ((char=? c #\:) '(abbrev +++SHARP-COLON-abbreviation+++)) ((char=? c #\.) '(abbrev +++SHARP-DOT-abbreviation+++)) ((char=? c #\+) '(abbrev +++SHARP-PLUS-abbreviation+++)) ((char=? c #\P) '(abbrev +++SHARP-P-abbreviation+++)) (#t #f))) Translate " x " to Common Lisp representation if we 're printing CL . (define (translate-cl x) (if common-lisp (case x ((quasiquote) '+++CL-QUASIQUOTE-abbreviation+++) ((unquote) '+++CL-UNQUOTE-abbreviation+++) ((unquote-splicing) '+++CL-UNQUOTE-SPLICING-abbreviation+++) (else x)) x)) (define (nest-comment fake-port) (let ((c (my-read-char fake-port))) (cond ((eof-object? c) (values)) ((char=? c #\|) (let ((c2 (my-peek-char fake-port))) (if (char=? c2 #\#) (begin (my-read-char fake-port) (values)) (nest-comment fake-port)))) ((and hash-pipe-comment-nests? (char=? c #\#)) (let ((c2 (my-peek-char fake-port))) (if (char=? c2 #\|) (begin (my-read-char fake-port) (nest-comment fake-port)) (values)) (nest-comment fake-port))) (#t (nest-comment fake-port))))) (define digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)) (define (process-period port) (let ((c (my-peek-char port))) (cond End , for some CL code (let ((num (read-number port (list #\.)))) (if num num (read-error "period digit must be a number")))) (#t (string->symbol (fold-case-maybe port (list->string (cons #\. (read-until-delim port neoteric-delimiters))))))))) Read an inline hex escape ( after \x ) , return the character it represents (define (read-inline-hex-escape port) (n (string->number (list->string chars) 16))) (my-read-char port) (read-error "Unfinished inline hex escape")) (if (not n) (read-error "Bad inline hex escape")) (integer->char n))) (define (read-symbol-elements port) (let ((c (my-read-char port))) (cond ((eof-object? c) '()) ((eqv? c #\\) (let ((c2 (my-read-char port))) (cond ((eof-object? c) '()) ((eqv? c2 #\|) (cons #\| (read-symbol-elements port))) ((eqv? c2 #\\) (cons #\\ (read-symbol-elements port))) ((eqv? c2 #\a) (cons (integer->char #x0007) (read-symbol-elements port))) ((eqv? c2 #\b) (cons (integer->char #x0008) (read-symbol-elements port))) ((eqv? c2 #\t) (cons (integer->char #x0009) (read-symbol-elements port))) ((eqv? c2 #\n) (cons (integer->char #x000a) (read-symbol-elements port))) ((eqv? c2 #\r) (cons (integer->char #x000d) (read-symbol-elements port))) (read-symbol-elements port))) (read-symbol-elements port))) (cons (read-inline-hex-escape port) (read-symbol-elements port)))))) (#t (cons c (read-symbol-elements port)))))) (define (read-literal-symbol port) (let ((c (my-read-char port))) (cond ((eof-object? c) (read-error "EOF inside literal symbol")) ((eqv? c #\\) (let ((c2 (my-read-char port))) (if (eof-object? c) (read-error "EOF after \\ in literal symbol") (cons c (cons c2 (read-literal-symbol port)))))) (#t (cons c (read-literal-symbol port)))))) This is present in R7RS draft 9 . (define (get-barred-symbol port) (string->symbol (list->string (if literal-barred-symbol (cons #\| (read-literal-symbol port)) (read-symbol-elements port))))) (define (underlying-read no-indent-read port) (consume-whitespace port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) c) ((char=? c #\") ( guile 1.8 and gauche / gosh 1.8.11 are fine ) (invoke-read default-scheme-read port)) (#t (attach-sourceinfo pos (cond ((char=? c #\#) (my-read-char port) (let ((rv (process-sharp no-indent-read port))) (cond ((eq? (car rv) 'scomment) (no-indent-read port)) ((eq? (car rv) 'datum-commentw) (no-indent-read port)) ((eq? (car rv) 'normal) (cadr rv)) ((eq? (car rv) 'abbrev) (list (cadr rv) (no-indent-read port))) (#t (read-error "Unknown # sequence"))))) ((char=? c #\.) (process-period port)) ((or (memv c digits) (char=? c #\+) (char=? c #\-)) (let* ((maybe-number (list->string (read-until-delim port neoteric-delimiters))) (as-number (string->number maybe-number))) (if as-number as-number (string->symbol (fold-case-maybe port maybe-number))))) ((char=? c #\') (my-read-char port) (list (attach-sourceinfo pos 'quote) (no-indent-read port))) ((char=? c #\`) (my-read-char port) (list (attach-sourceinfo pos (translate-cl 'quasiquote)) (no-indent-read port))) ((char=? c #\,) (my-read-char port) (cond ((char=? #\@ (my-peek-char port)) (my-read-char port) (list (attach-sourceinfo pos (translate-cl 'unquote-splicing)) (no-indent-read port))) (#t (list (attach-sourceinfo pos (translate-cl 'unquote)) (no-indent-read port))))) ((char=? c #\( ) (my-read-char port) (my-read-delimited-list no-indent-read #\) port)) ((char=? c #\) ) (my-read-char port) (read-error "Closing parenthesis without opening") (underlying-read no-indent-read port)) ((char=? c #\[ ) (my-read-char port) (my-read-delimited-list no-indent-read #\] port)) ((char=? c #\] ) (my-read-char port) (read-error "Closing bracket without opening") (underlying-read no-indent-read port)) ((char=? c #\} ) (my-read-char port) (read-error "Closing brace without opening") (underlying-read no-indent-read port)) ((char=? c #\| ) Read | ... | symbol ( like Common Lisp and R7RS draft 9 ) (get-barred-symbol port)) (string->symbol (fold-case-maybe port (list->string (read-until-delim port neoteric-delimiters))))))))))) Return true if has an even # of parameters , and the ( alternating ) (define (even-and-op-prefix? op lyst) (cond ((null? lyst) #t) ((not (pair? lyst)) #f) (define (simple-infix-list? lyst) (and Must have a second argument . Must have a third argument ( we check it Return alternating parameters in a list ( 1st , 3rd , 5th , etc . ) (define (alternating-parameters lyst) (if (or (null? lyst) (null? (cdr lyst))) lyst (cons (car lyst) (alternating-parameters (cddr lyst))))) (define (transform-mixed-infix lyst) (cons '$nfx$ lyst)) (define (process-curly lyst) (cond E.G. , map { } to ( ) . (car lyst)) lyst) (cons (cadr lyst) (alternating-parameters lyst))) (#t (transform-mixed-infix lyst)))) (define (curly-infix-read-real no-indent-read port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) c) (consume-to-eol port) (curly-infix-read-real no-indent-read port)) ((my-char-whitespace? c) (my-read-char port) (curly-infix-read-real no-indent-read port)) ((eqv? c #\{) (my-read-char port) (attach-sourceinfo pos (process-curly (my-read-delimited-list neoteric-read-real #\} port)))) (#t (underlying-read no-indent-read port))))) (define (curly-infix-read-nocomment port) (curly-infix-read-real curly-infix-read-nocomment port)) Neoteric Expressions This recurses , to handle formats like ) . (define (neoteric-process-tail port prefix) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port))) (cond ((eof-object? c) prefix) (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (cons prefix (my-read-delimited-list neoteric-read-nocomment #\) port))))) (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (cons (attach-sourceinfo pos '$bracket-apply$) (cons prefix (my-read-delimited-list neoteric-read-nocomment #\] port)))))) (my-read-char port) (neoteric-process-tail port (attach-sourceinfo pos (let ((tail (process-curly (my-read-delimited-list neoteric-read-nocomment #\} port)))) (if (eqv? tail '()) (list prefix tail)))))) (#t prefix)))) (define (neoteric-read-real port) (let* ((pos (get-sourceinfo port)) (c (my-peek-char port)) (result (cond ((eof-object? c) c) ((char=? c #\( ) (my-read-char port) (attach-sourceinfo pos (my-read-delimited-list neoteric-read-nocomment #\) port))) ((char=? c #\[ ) (my-read-char port) (attach-sourceinfo pos (my-read-delimited-list neoteric-read-nocomment #\] port))) ((char=? c #\{ ) (my-read-char port) (attach-sourceinfo pos (process-curly (my-read-delimited-list neoteric-read-nocomment #\} port)))) ((my-char-whitespace? c) (my-read-char port) (neoteric-read-real port)) (consume-to-eol port) (neoteric-read-real port)) (#t (underlying-read neoteric-read-nocomment port))))) (if (eof-object? result) result (neoteric-process-tail port result)))) (define (neoteric-read-nocomment port) (neoteric-read-real port)) Sweet Expressions ( this implementation maps to the BNF ) (define-syntax let-splitter (syntax-rules () ((let-splitter (full first-value second-value) expr body ...) (let* ((full expr) (first-value (car full)) (second-value (cadr full))) body ...)))) it 's probably trivial to reimplement this . E.G. , in Common Lisp : ( defmacro let - splitter ( ( full first - value second - value ) expr & rest body ) ( , first - value ( car , full ) ) ( , second - value ( cadr , full ) ) ) (define group-split (string->symbol "\\\\")) First character of split symbol . (define sublist (string->symbol "$")) First character of sublist symbol . (define (indentation>? indentation1 indentation2) (let ((len1 (string-length indentation1)) (len2 (string-length indentation2))) (and (> len1 len2) (string=? indentation2 (substring indentation1 0 len2))))) # \newline carriage - return ) ) (define (lcomment-eol? c) (or (eof-object? c) (memv c initial-comment-eol))) (define (char-hspace? char) (or (eqv? char #\space) (eqv? char tab))) (define (hspaces port) ((char-hspace? (my-peek-char port)) (my-read-char port) (hspaces port)))) (define (char-ichar? char) (or (eqv? char #\space) (eqv? char tab) (eqv? char non-whitespace-indent))) (define (accumulate-ichar port) (if (char-ichar? (my-peek-char port)) (cons (my-read-char port) (accumulate-ichar port)) '())) (define (consume-ff-vt port) (let ((c (my-peek-char port))) (cond ((or (eqv? c form-feed) (eqv? c vertical-tab)) (my-read-char port) (consume-ff-vt port))))) Do 2 - item append , but report read - error if the LHS is not a proper list . (define (my-append lhs rhs) (cond ((eq? lhs empty-value) rhs) ((eq? rhs empty-value) lhs) ((list? lhs) (append lhs rhs)) (#t (read-error "Must have proper list on left-hand-side to append data")))) (define (n-expr-or-scomment port) (if (eqv? (my-peek-char port) #\#) (let* ((consumed-sharp (my-read-char port)) (result (process-sharp neoteric-read-nocomment port))) (cond ((eq? (car result) 'normal) (list 'normal (neoteric-process-tail port (cadr result)))) ((eq? (car result) 'abbrev) (list 'normal (list (cadr result) (neoteric-read-nocomment port)))) ((pair? result) result) (#t (read-error "Unsupported hash")))) (list 'normal (neoteric-read-nocomment port)))) Markers only have special meaning if their first character is Call " process - sharp " if first char is " # " . (define (n-expr port) (let ((c (my-peek-char port))) (let-splitter (results type expr) (n-expr-or-scomment port) (if (eq? (car results) 'scomment) results (cond ((and (eq? expr sublist) (eqv? c sublist-char)) (list 'sublist-marker '())) ((and (eq? expr group-split) (eqv? c group-split-char)) (list 'group-split-marker '())) ((and (eq? expr '<*) (eqv? c #\<)) (list 'collecting '())) ((and (eq? expr '*>) (eqv? c #\*)) (list 'collecting-end '())) ((and (eq? expr '$$$) (eqv? c #\$)) (read-error "$$$ is reserved")) ((and (eq? expr period-symbol) (eqv? c #\.)) (list 'period-marker '())) (#t results)))))) as the value ( the cadr ) . Otherwise , return ( ' normal n - expr ) . We do NOT consume the peeked char ( so EOL can be examined later ) . quoted markers are no longer markers . E.G. , ' $ is just ( quote $ ) . (define (maybe-initial-abbrev port abbrev-procedure) (let ((c (my-peek-char port))) (if (or (char-hspace? c) (eqv? c carriage-return) (eqv? c linefeed)) (list 'abbrevw abbrev-procedure) (list 'normal (list abbrev-procedure (neoteric-read-nocomment port)))))) (define (n-expr-first port) (case (my-peek-char port) ((#\') (my-read-char port) (maybe-initial-abbrev port 'quote)) ((#\`) (my-read-char port) (maybe-initial-abbrev port (translate-cl 'quasiquote))) ((#\,) (my-read-char port) (if (eqv? (my-peek-char port) #\@) (begin (my-read-char port) (maybe-initial-abbrev port (translate-cl 'unquote-splicing))) (maybe-initial-abbrev port (translate-cl 'unquote)))) ((#\#) (let* ((consumed-sharp (my-read-char port)) (result (process-sharp neoteric-read-nocomment port))) (cond ((eq? (car result) 'normal) (list 'normal (neoteric-process-tail port (cadr result)))) ((eq? (car result) 'abbrev) (maybe-initial-abbrev port (cadr result))) (#t result)))) (else (n-expr port)))) (define (get-next-indent port) (consume-to-eol port) (consume-end-of-line port) (let* ((indentation-as-list (cons #\^ (accumulate-ichar port))) (c (my-peek-char port))) (cond (get-next-indent port)) (if (memv #\! indentation-as-list) (get-next-indent port) "^")) (#t (list->string indentation-as-list))))) (define (skippable stopper port) (cond ((eq? stopper 'scomment) (hspaces port)) ((eq? stopper 'datum-commentw) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (begin (n-expr port) (hspaces port)) (read-error "Datum comment start not followed a datum (EOL instead)"))) (#t (read-error "skippable: Impossible case")))) (cond ((eq? y empty-value) x) ((eq? x empty-value) y) (#t (cons x y)))) (cond ((eq? y empty-value) x) ((eq? x empty-value) y) (#t (append y)))) (if (eq? x empty-value) '() (list x))) (if (eq? x empty-value) y (if (eq? y empty-value) x (list x y)))) If x is a 1 - element list , return ( car x ) , else return x (define (monify x) (cond ((not (pair? x)) x) ((null? (cdr x)) (car x)) (#t x))) (define (collecting-content port) (let* ((c (my-peek-char port))) (cond ((eof-object? c) (read-error "Collecting tail: EOF before collecting list ended")) ((lcomment-eol? c) (consume-to-eol port) (consume-end-of-line port) (collecting-content port)) ((char-ichar? c) (let* ((indentation (accumulate-ichar port)) (c (my-peek-char port))) (if (lcomment-eol? c) (collecting-content port) (read-error "Collecting tail: Only ; after indent")))) ((or (eqv? c form-feed) (eqv? c vertical-tab)) (consume-ff-vt port) (if (lcomment-eol? (my-peek-char port)) (collecting-content port) (read-error "Collecting tail: FF and VT must be alone on line"))) (#t (let-splitter (it-full-results it-new-indent it-value) (it-expr port "^") (cond ((string=? it-new-indent "") after something else . This must be interpreted as EOL * > , (cond ((null? it-value) it-value) ((eq? it-value empty-value) '()) (#t (list it-value)))) (#t (conse it-value (collecting-content port))))))))) (define (n-expr-error port full) (if (not (eq? (car full) 'normal)) (read-error "BUG! n-expr-error called but stopper not normal")) (if (lcomment-eol? (my-peek-char port)) (let-splitter (n-full-results n-stopper n-value) (n-expr port) (cond ((or (eq? n-stopper 'scomment) (eq? n-stopper 'datum-commentw)) (skippable n-stopper port) (n-expr-error port full)) ((eq? n-stopper 'normal) (read-error "Illegal second value after .")) (list n-stopper (cadr full))))))) (define (post-period port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (pn-full-results pn-stopper pn-value) (n-expr port) (cond ((or (eq? pn-stopper 'scomment) (eq? pn-stopper 'datum-commentw)) (skippable pn-stopper port) (post-period port)) ((eq? pn-stopper 'normal) (hspaces port) (n-expr-error port pn-full-results)) ((eq? pn-stopper 'collecting) (hspaces port) (let ((cl (collecting-content port))) (hspaces port) (n-expr-error port (list 'normal cl)))) ((eq? pn-stopper 'period-marker) (list 'normal period-symbol)) (list pn-stopper (list period-symbol))))) (define (line-exprs port) (let-splitter (basic-full-results basic-special basic-value) (n-expr-first port) (cond ((eq? basic-special 'collecting) (hspaces port) (let* ((cl-results (collecting-content port))) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (rr-full-results rr-stopper rr-value) (rest-of-line port) (list rr-stopper (cons cl-results rr-value))) (list 'normal (list cl-results))))) ((eq? basic-special 'period-marker) (if (char-hspace? (my-peek-char port)) (begin (hspaces port) (let-splitter (ct-full-results ct-stopper ct-value) (post-period port) (list ct-stopper (list ct-value)))) (list 'normal (list period-symbol)))) ((not (eq? basic-special 'normal)) basic-full-results) ((char-hspace? (my-peek-char port)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (br-full-results br-stopper br-value) (rest-of-line port) (list br-stopper (cons basic-value br-value))) (list 'normal (list basic-value)))) (#t (list 'normal (list basic-value)))))) Read in one n - expr , then process based on whether or not it 's special . (define (rest-of-line port) (let-splitter (basic-full-results basic-special basic-value) (n-expr port) (cond ((or (eq? basic-special 'scomment) (eq? basic-special 'datum-commentw)) (skippable basic-special port) (if (not (lcomment-eol? (my-peek-char port))) (rest-of-line port) (list 'normal '()))) ((eq? basic-special 'collecting) (hspaces port) (let* ((cl-results (collecting-content port))) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (rr-full-results rr-stopper rr-value) (rest-of-line port) (list rr-stopper (cons cl-results rr-value))) (list 'normal (list cl-results))))) ((eq? basic-special 'period-marker) (if (char-hspace? (my-peek-char port)) (begin (hspaces port) (post-period port)) (read-error "Cannot end line with '.'"))) ((not (eq? basic-special 'normal)) (list basic-special '())) ((char-hspace? (my-peek-char port)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let-splitter (br-full-results br-stopper br-value) (rest-of-line port) (list br-stopper (cons basic-value br-value))) (list 'normal (list basic-value)))) (#t (list 'normal (list basic-value)))))) (define (body port starting-indent) (let-splitter (i-full-results i-new-indent i-value) (it-expr port starting-indent) (if (string=? starting-indent i-new-indent) (if (eq? i-value period-symbol) (let-splitter (f-full-results f-new-indent f-value) (it-expr port i-new-indent) (if (not (indentation>? starting-indent f-new-indent)) (read-error "Dedent required after lone . and value line")) (if (eq? i-value empty-value) (body port i-new-indent) (let-splitter (nxt-full-results nxt-new-indent nxt-value) (body port i-new-indent) (list nxt-new-indent (cons i-value nxt-value))))) (define (it-expr-real port starting-indent) (let-splitter (line-full-results line-stopper line-value) (line-exprs port) (if (and (not (null? line-value)) (not (eq? line-stopper 'abbrevw))) Production line - exprs produced at least one n - expression : (cond ((eq? line-stopper 'group-split-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "Cannot follow split with end of line") (list starting-indent (monify line-value)))) ((eq? line-stopper 'sublist-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "EOL illegal immediately after sublist")) (let-splitter (sub-i-full-results sub-i-new-indent sub-i-value) (it-expr port starting-indent) (list sub-i-new-indent (my-append line-value (list sub-i-value))))) ((eq? line-stopper 'collecting-end) (list "" (if (eq? line-value empty-value) '() (monify line-value)))) ((lcomment-eol? (my-peek-char port)) (let ((new-indent (get-next-indent port))) (if (indentation>? new-indent starting-indent) (let-splitter (body-full body-new-indent body-value) (body port new-indent) (list body-new-indent (my-append line-value body-value))) (list new-indent (monify line-value))))) (#t (read-error "Unexpected text after n-expression"))) (cond ((eq? line-stopper 'datum-commentw) (hspaces port) (cond ((not (lcomment-eol? (my-peek-char port))) (let-splitter (is-i-full-results is-i-new-indent is-i-value) (it-expr port starting-indent) (list is-i-new-indent empty-value))) (#t (let ((new-indent (get-next-indent port))) (if (indentation>? new-indent starting-indent) (let-splitter (body-full-results body-new-indent body-value) (body port new-indent) (list body-new-indent empty-value)) (read-error "#;+EOL must be followed by indent")))))) ((or (eq? line-stopper 'group-split-marker) (eq? line-stopper 'scomment)) (hspaces port) (if (not (lcomment-eol? (my-peek-char port))) (let ((new-indent (get-next-indent port))) (cond ((indentation>? new-indent starting-indent) (body port new-indent)) (#t (list new-indent empty-value)))))) ((eq? line-stopper 'sublist-marker) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (read-error "EOL illegal immediately after solo sublist")) (let-splitter (is-i-full-results is-i-new-indent is-i-value) (it-expr port starting-indent) (list is-i-new-indent (list1e is-i-value)))) ((eq? line-stopper 'abbrevw) (hspaces port) (if (lcomment-eol? (my-peek-char port)) (let ((new-indent (get-next-indent port))) (if (not (indentation>? new-indent starting-indent)) (read-error "Indent required after abbreviation")) (let-splitter (ab-full-results ab-new-indent ab-value) (body port new-indent) (list ab-new-indent (append (list line-value) ab-value)))) (let-splitter (ai-full-results ai-new-indent ai-value) (it-expr port starting-indent) (list ai-new-indent (list2e line-value ai-value))))) ((eq? line-stopper 'collecting-end) (list "" line-value)) (#t (read-error "Initial line-expression error")))))) (define (it-expr port starting-indent) (let ((pos (get-sourceinfo port))) (let-splitter (results results-indent results-value) (it-expr-real port starting-indent) (if (indentation>? results-indent starting-indent) (read-error "Inconsistent indentation")) (list results-indent (attach-sourceinfo pos results-value))))) (define (initial-indent-expr-tail port) (if (not (memv (my-peek-char port) initial-comment-eol)) (let-splitter (results results-stopper results-value) (n-expr-or-scomment port) (cond ((memq results-stopper '(scomment datum-commentw)) (skippable results-stopper port) (initial-indent-expr-tail port)) Normal n - expr , return one value . (begin (consume-to-eol port) (consume-end-of-line port) (define (t-expr-real port) (let* ((c (my-peek-char port))) (cond Check EOF early ( a bug in guile before 2.0.8 consumes EOF on peek ) ((eof-object? c) c) ((lcomment-eol? c) (consume-to-eol port) (consume-end-of-line port) (t-expr-real port)) ((or (eqv? c form-feed) (eqv? c vertical-tab)) (consume-ff-vt port) (if (not (lcomment-eol? (my-peek-char port))) (read-error "FF and VT must be alone on line in a sweet-expr")) (t-expr-real port)) (initial-indent-expr-tail port)) (#t (let-splitter (results results-indent results-value) (it-expr port "^") (if (string=? results-indent "") (read-error "Closing *> without preceding matching <*") results-value)))))) (define (t-expr port) (let* ((te (t-expr-real port))) (if (eq? te empty-value) (t-expr port) te))) (define (read-to-unindented-line port) (let* ((c (my-peek-char port))) (cond ((eof-object? c) c) ((char-line-ending? c) (consume-end-of-line port) (if (char-ichar? (my-peek-char port)) (read-to-unindented-line port))) (#t (consume-to-eol port) (consume-end-of-line port) (read-to-unindented-line port))))) (define (t-expr-catch port) Default guile stack size is FAR too small (debug-set! stack 500000) (catch 'readable (lambda () (t-expr port)) (lambda (key . args) (read-to-unindented-line port) (t-expr-catch port)))) (define boring-length 16) (define special-infix-operators '(and or xor)) (define punct-chars (list #\! #\" #\# #\$ #\% #\& #\' #\( #\) #\* #\+ #\, #\- # \ < # \= # \ > # \ ? # \@ # \ [ # \\ # \ ] # \^ #\_ #\` #\{ #\| #\} #\~)) Returns # t if x is a list with exactly 1 element . Improper lists are # f. (define (list1? x) (and (pair? x) (null? (cdr x)))) Returns # t if x is a list with exactly 2 elements . Improper lists are # f. (define (list2? x) (and (pair? x) (pair? (cdr x)) (null? (cddr x)))) (define (contains-only-punctuation? x) (cond ((null? x) #t) ((not (pair? x)) #f) ((memq (car x) punct-chars) (contains-only-punctuation? (cdr x))) (#t #f))) (define (is-infix-operator? x) (cond ((not (symbol? x)) #f) ((memq x special-infix-operators) #t) (#t (contains-only-punctuation? (string->list (symbol->string x)))))) (define (long-and-boring? x num-to-go) (cond ((pair? (car x)) #f) ((not (pair? (cdr x))) #f) ((<= num-to-go 1) #t) (#t (long-and-boring? (cdr x) (- num-to-go 1))))) (define (list-no-longer-than? x num-to-go) (cond ((not (pair? x)) #f) ((not (pair? (cdr x))) #f) ((<= num-to-go 0) #f) (#t (list-no-longer-than? (cdr x) (- num-to-go 1))))) (define (represent-as-infix? x) (and (pair? x) At least 2 elements . (is-infix-operator? (car x)) (list-no-longer-than? x 6))) (define (represent-as-inline-infix? x) Must be 3 + elements (define (represent-as-brace-suffix? x) (represent-as-infix? x)) (define abbreviations '((quote (#\')) (quasiquote (#\`)) (unquote (#\,)) (unquote-splicing (#\, #\@)) Scheme syntax - rules . Note that this will abbreviate any 2 - element (syntax (#\# #\')) (quasisyntax (#\# #\`)) (unsyntax-splicing (#\# #\, #\@) (unsyntax (#\# #\,))))) (define (represent-as-abbreviation? x) (and (list2? x) (assq (car x) abbreviations))) (define (write-abbreviation x port) (for-each (lambda (c) (display c port)) (cadr (assq (car x) abbreviations)))) (define (n-write-list-contents x port) (cond ((null? x) (values)) ((pair? x) (n-write-simple (car x) port) (cond ((not (null? (cdr x))) (display " " port) (n-write-list-contents (cdr x) port)))) (#t (display ". " port) (n-write-simple x port)))) (define (c-write-list-contents x port) (cond ((null? x) (values)) ((pair? x) (c-write-simple (car x) port) (cond ((not (null? (cdr x))) (display " " port) (c-write-list-contents (cdr x) port)))) (#t (display ". " port) (c-write-simple x port)))) (define (infix-tail op x port) (cond ((null? x) (display "}" port)) ((pair? x) (display " " port) (n-write-simple op port) (display " " port) (n-write-simple (car x) port) (infix-tail op (cdr x) port)) (#t (display " " port) (n-write-simple x port) (display "}" port)))) (define (as-brace-suffix x port) (display "{" port) (if (list2? x) (begin (n-write-list-contents x port) (display "}" port)) (begin (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)))) (define (n-write-simple x port) (cond ((pair? x) (cond (write-abbreviation x port) (n-write-simple (cadr x) port)) (display "(" port) (n-write-list-contents x port) (display ")" port)) ((symbol? (car x)) (cond (display "{" port) (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)) (pair? (cadr x)) (represent-as-infix? (cadr x))) (n-write-simple (car x) port) (as-brace-suffix (cadr x) port)) (n-write-simple (car x) port) (display "(" port) (n-write-list-contents (cdr x) port) (display ")" port)))) (display "(" port) (n-write-list-contents x port) (display ")" port)))) ((vector? x) (for-each (lambda (v) (n-write-simple v port) (display " " port)) (vector->list x)) (display ")" port)) (define (c-write-simple x port) (cond ((pair? x) (cond (write-abbreviation x port) (c-write-simple (cadr x) port)) (display "{" port) (n-write-simple (cadr x) port) (infix-tail (car x) (cddr x) port)) (display "(" port) (c-write-list-contents x port) (display ")" port)))) ((vector? x) (for-each (lambda (v) (c-write-simple v port) (display " " port)) (vector->list x)) (display ")" port)) Front entry - Use default port if none provided . (define (neoteric-write-simple x . rest) (if (pair? rest) (n-write-simple x (car rest)) (n-write-simple x (current-output-port)))) Front entry - Use default port if none provided . (define (curly-write-simple x . rest) (if (pair? rest) (c-write-simple x (car rest)) (c-write-simple x (current-output-port)))) The original code was written by in 2009 and placed in the Extracted from Chibi Scheme 0.6.1 . on 10 April 2013 said : " ... though not part of R7RS - small , SRFI 69 hash tables are fairly pervasive , because they are more Schemes is that as SRFIs go , 69 is a fairly recent one . I would n't (define (extract-shared-objects x cyclic-only?) (let ((seen (srfi-69-make-hash-table eq?))) (let find ((x x)) (let ((type (type-of x))) ((or (pair? x) (vector? x) (and type (type-printer type))) (hash-table-update!/default seen x (lambda (n) (+ n 1)) 0) walk if this is the first time (cond ((> (hash-table-ref seen x) 1)) ((pair? x) (find (car x)) (find (cdr x))) ((vector? x) (do ((i 0 (+ i 1))) ((= i (vector-length x))) (find (vector-ref x i)))) (else (let ((num-slots (type-num-slots type))) (let lp ((i 0)) (cond ((< i num-slots) (find (slot-ref type x i)) (lp (+ i 1)))))))) (if (and cyclic-only? (<= (hash-table-ref/default seen x 0) 1)) (hash-table-delete! seen x)))))) (let ((res (srfi-69-make-hash-table eq?))) (hash-table-walk seen (lambda (k v) (if (> v 1) (hash-table-set! res k #t)))) res))) (define (advanced-write-with-shared-structure x port cyclic-only? neoteric?) (let ((shared (extract-shared-objects x cyclic-only?)) (count 0)) (define (shared-object? x) (let ((type (type-of x))) (if (or (pair? x) (vector? x) (and type (type-printer type))) (let ((index (hash-table-ref/default shared x #f))) (not (not index))) #f))) Check - shared prints # n # or # n= as appropriate . (define (check-shared x prefix cont) (let ((index (hash-table-ref/default shared x #f))) (cond ((integer? index) (display prefix port) (display "#" port) (write index port) (display "#" port)) (else (cond (index (display prefix port) (display "#" port) (write count port) (display "=" port) (hash-table-set! shared x count) (set! count (+ count 1)))) (cont x index))))) (let wr ((x x) (neoteric? neoteric?)) (define (infix-tail/ss op x port) (cond ((null? x) (display "}" port)) ((pair? x) (display " " port) (wr op #t) (display " " port) (infix-tail/ss op (cdr x) port)) (#t (display " . " port) (n-write-simple x port) (display "}" port)))) (check-shared x "" (lambda (x shared?) (cond Check for special formats first . ((and (represent-as-abbreviation? x) (not (shared-object? (cadr x)))) (write-abbreviation x port) (wr (cadr x) neoteric?)) ((and (represent-as-inline-infix? x) (not (any shared-object? x))) (display "{" port) (infix-tail/ss (car x) (cddr x) port)) ((and neoteric? (pair? x) (symbol? (car x)) (list1? (cdr x)) (represent-as-infix? (cadr x)) (not (shared-object? (cdr x))) (not (shared-object? (cadr x))) (not (any shared-object? (cadr x)))) (wr (car x) neoteric?) (let ((expr (cadr x))) (if (list2? expr) (begin (display "{" port) (wr (car expr) neoteric?) (display " " port) (wr (cadr expr) neoteric?) (display "}" port)) (begin (wr expr neoteric?))))) ((pair? x) (cond ((and neoteric? (symbol? (car x)) (not (long-and-boring? x boring-length)) Neoteric format a(b c ... ) (wr (car x) neoteric?) (#t (wr (car x) neoteric?) (if (not (null? (cdr x))) (display " " port)))) (let lp ((ls (cdr x))) (check-shared ls ". " (lambda (ls shared?) (cond ((null? ls)) ((pair? ls) (cond (shared? (display "(" port) (wr (car ls) neoteric?) (check-shared (cdr ls) ". " (lambda (ls shared?) (if (not (null? ls)) (display " " port)) (lp ls))) (display ")" port)) (else (wr (car ls) neoteric?) (if (not (null? (cdr ls))) (display " " port)) (lp (cdr ls))))) (else (display ". " port) (wr ls neoteric?)))))) (display ")" port)) ((vector? x) (display "#(" port) (let ((len (vector-length x))) (cond ((> len 0) (wr (vector-ref x 0) neoteric?) (do ((i 1 (+ i 1))) ((= i len)) (display " " port) (wr (vector-ref x i) neoteric?))))) (display ")" port)) ((let ((type (type-of x))) (and (type? type) (type-printer type))) => (lambda (printer) (printer x wr port))) (else (write x port)))))))) (define (curly-write-shared x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #f #f)) (define (curly-write-cyclic x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #t #f)) (define (neoteric-write-shared x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #f #t)) (define (neoteric-write-cyclic x . o) (advanced-write-with-shared-structure x (if (pair? o) (car o) (current-output-port)) #t #t)) Since we have " cyclic " versions , the -write forms use them : (define neoteric-write neoteric-write-cyclic) (define curly-write curly-write-cyclic) (define curly-infix-read (make-read curly-infix-read-nocomment)) (define neoteric-read (make-read neoteric-read-nocomment)) (define sweet-read (make-read t-expr-catch)) )
9542583317ce67e2568c6dd60972694f5b3f14865ae549ac24f497eae11f4ea1
dyzsr/ocaml-selectml
pr7269.ml
(* TEST * expect *) type s = [`A | `B] and sub = [`B];; type +'a t = T : [< `Conj of 'a & sub | `Other of string] -> 'a t;; (* ok *) let f (T (`Other msg) : s t) = print_string msg;; let _ = f (T (`Conj `B) :> s t);; (* warn *) [%%expect{| type s = [ `A | `B ] and sub = [ `B ] type +'a t = T : [< `Conj of 'a & sub | `Other of string ] -> 'a t Line 4, characters 6-47: 4 | let f (T (`Other msg) : s t) = print_string msg;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: T (`Conj _) val f : s t -> unit = <fun> Exception: Match_failure ("", 4, 6). |}];; module M : sig type s type t = T : [< `Conj of int & s | `Other of string] -> t val x : t end = struct type s = int type t = T : [< `Conj of int | `Other of string] -> t let x = T (`Conj 42) end;; let () = M.(match x with T (`Other msg) -> print_string msg);; (* warn *) [%%expect{| module M : sig type s type t = T : [< `Conj of int & s | `Other of string ] -> t val x : t end Line 11, characters 12-59: 11 | let () = M.(match x with T (`Other msg) -> print_string msg);; (* warn *) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: T (`Conj _) Exception: Match_failure ("", 11, 12). |}];; module M : sig type s type elim = { ex : 'a . ([<`Conj of int & s | `Other of string] as 'a) -> unit } val e : elim -> unit end = struct type s = int type elim = { ex : 'a . (([<`Conj of int | `Other of string] as 'a) -> unit) } let e { ex } = ex (`Conj 42 : [`Conj of int]) end;; let () = M.(e { ex = fun (`Other msg) -> print_string msg });; (* warn *) [%%expect{| module M : sig type s type elim = { ex : 'a. ([< `Conj of int & s | `Other of string ] as 'a) -> unit; } val e : elim -> unit end Line 13, characters 21-57: 13 | let () = M.(e { ex = fun (`Other msg) -> print_string msg });; (* warn *) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `Conj _ Exception: Match_failure ("", 13, 21). |}];;
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-gadts/pr7269.ml
ocaml
TEST * expect ok warn warn warn warn warn
type s = [`A | `B] and sub = [`B];; let f (T (`Other msg) : s t) = print_string msg;; [%%expect{| type s = [ `A | `B ] and sub = [ `B ] type +'a t = T : [< `Conj of 'a & sub | `Other of string ] -> 'a t Line 4, characters 6-47: 4 | let f (T (`Other msg) : s t) = print_string msg;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: T (`Conj _) val f : s t -> unit = <fun> Exception: Match_failure ("", 4, 6). |}];; module M : sig type s type t = T : [< `Conj of int & s | `Other of string] -> t val x : t end = struct type s = int type t = T : [< `Conj of int | `Other of string] -> t let x = T (`Conj 42) end;; [%%expect{| module M : sig type s type t = T : [< `Conj of int & s | `Other of string ] -> t val x : t end Line 11, characters 12-59: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: T (`Conj _) Exception: Match_failure ("", 11, 12). |}];; module M : sig type s type elim = { ex : 'a . ([<`Conj of int & s | `Other of string] as 'a) -> unit } val e : elim -> unit end = struct type s = int type elim = { ex : 'a . (([<`Conj of int | `Other of string] as 'a) -> unit) } let e { ex } = ex (`Conj 42 : [`Conj of int]) end;; [%%expect{| module M : sig type s type elim = { ex : 'a. ([< `Conj of int & s | `Other of string ] as 'a) -> unit; } val e : elim -> unit end Line 13, characters 21-57: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `Conj _ Exception: Match_failure ("", 13, 21). |}];;
3542fc57ee0ad3c96446d8e6867e31ce8db7cdf7577b731106a9f52f40911079
s-expressionists/Cleavir
def-use-chains.lisp
(cl:in-package #:cleavir-def-use-chains) ;;; We return a list of def-use chains. Each def-use chain is ;;; represented by a list whose CAR is the DEFINITION (i.e, a CONS of a NODE and a VARIABLE ) , and whose CDR is a list of nodes where the ;;; definition is used. (defun def-use-chains (graph) (let ((reaching-definitions (cleavir-reaching-definitions:reaching-definitions graph)) (def-use-chains (make-hash-table :test #'eq))) (cleavir-graph:with-graph (graph) (cleavir-graph:do-nodes (node) (loop for reaching in (cleavir-reaching-definitions:reaching node reaching-definitions) do (when (cleavir-graph:do-inputs (input nil) (when (eq input (cdr reaching)) (return t))) (push node (gethash reaching def-use-chains)))))) (let ((result '())) (maphash (lambda (definition nodes) (push (cons definition nodes) result)) def-use-chains) result)))
null
https://raw.githubusercontent.com/s-expressionists/Cleavir/e0293780d356a9d563af9abf9317019f608b4e1d/Def-use-chains/def-use-chains.lisp
lisp
We return a list of def-use chains. Each def-use chain is represented by a list whose CAR is the DEFINITION (i.e, a CONS of definition is used.
(cl:in-package #:cleavir-def-use-chains) a NODE and a VARIABLE ) , and whose CDR is a list of nodes where the (defun def-use-chains (graph) (let ((reaching-definitions (cleavir-reaching-definitions:reaching-definitions graph)) (def-use-chains (make-hash-table :test #'eq))) (cleavir-graph:with-graph (graph) (cleavir-graph:do-nodes (node) (loop for reaching in (cleavir-reaching-definitions:reaching node reaching-definitions) do (when (cleavir-graph:do-inputs (input nil) (when (eq input (cdr reaching)) (return t))) (push node (gethash reaching def-use-chains)))))) (let ((result '())) (maphash (lambda (definition nodes) (push (cons definition nodes) result)) def-use-chains) result)))
1ea4a19ce322b511a6bfe0348c0a679812795efeb711fcef49023a6967c6abff
anoma/juvix
Base.hs
module Compilation.Base where import Base import Core.Eval.Base import Data.HashMap.Strict qualified as HashMap import Data.Text.IO qualified as TIO import Juvix.Compiler.Builtins (iniState) import Juvix.Compiler.Core.Data.InfoTable qualified as Core import Juvix.Compiler.Core.Extra import Juvix.Compiler.Core.Info qualified as Info import Juvix.Compiler.Core.Info.NoDisplayInfo import Juvix.Compiler.Core.Pipeline qualified as Core import Juvix.Compiler.Core.Pretty import Juvix.Compiler.Core.Translation.FromInternal.Data qualified as Core import Juvix.Compiler.Pipeline compileAssertion :: Path Abs File -> Path Abs File -> (String -> IO ()) -> Assertion compileAssertion mainFile expectedFile step = do step "Translate to JuvixCore" cwd <- getCurrentDir let entryPoint = defaultEntryPoint cwd mainFile tab' <- (^. Core.coreResultTable) . snd <$> runIO' iniState entryPoint upToCore let tab = Core.toEval tab' case (tab ^. Core.infoMain) >>= ((tab ^. Core.identContext) HashMap.!?) of Just node -> do withTempDir' ( \dirPath -> do let outputFile = dirPath <//> $(mkRelFile "out.out") hout <- openFile (toFilePath outputFile) WriteMode step "Evaluate" r' <- doEval mainFile hout tab node case r' of Left err -> do hClose hout assertFailure (show (pretty err)) Right value -> do unless (Info.member kNoDisplayInfo (getInfo value)) (hPutStrLn hout (ppPrint value)) hClose hout actualOutput <- TIO.readFile (toFilePath outputFile) step "Compare expected and actual program output" expected <- TIO.readFile (toFilePath expectedFile) assertEqDiffText ("Check: EVAL output = " <> toFilePath expectedFile) actualOutput expected ) Nothing -> assertFailure ("No main function registered in: " <> toFilePath mainFile)
null
https://raw.githubusercontent.com/anoma/juvix/c93013229ab84e81298ced674961ff30a39b888b/test/Compilation/Base.hs
haskell
module Compilation.Base where import Base import Core.Eval.Base import Data.HashMap.Strict qualified as HashMap import Data.Text.IO qualified as TIO import Juvix.Compiler.Builtins (iniState) import Juvix.Compiler.Core.Data.InfoTable qualified as Core import Juvix.Compiler.Core.Extra import Juvix.Compiler.Core.Info qualified as Info import Juvix.Compiler.Core.Info.NoDisplayInfo import Juvix.Compiler.Core.Pipeline qualified as Core import Juvix.Compiler.Core.Pretty import Juvix.Compiler.Core.Translation.FromInternal.Data qualified as Core import Juvix.Compiler.Pipeline compileAssertion :: Path Abs File -> Path Abs File -> (String -> IO ()) -> Assertion compileAssertion mainFile expectedFile step = do step "Translate to JuvixCore" cwd <- getCurrentDir let entryPoint = defaultEntryPoint cwd mainFile tab' <- (^. Core.coreResultTable) . snd <$> runIO' iniState entryPoint upToCore let tab = Core.toEval tab' case (tab ^. Core.infoMain) >>= ((tab ^. Core.identContext) HashMap.!?) of Just node -> do withTempDir' ( \dirPath -> do let outputFile = dirPath <//> $(mkRelFile "out.out") hout <- openFile (toFilePath outputFile) WriteMode step "Evaluate" r' <- doEval mainFile hout tab node case r' of Left err -> do hClose hout assertFailure (show (pretty err)) Right value -> do unless (Info.member kNoDisplayInfo (getInfo value)) (hPutStrLn hout (ppPrint value)) hClose hout actualOutput <- TIO.readFile (toFilePath outputFile) step "Compare expected and actual program output" expected <- TIO.readFile (toFilePath expectedFile) assertEqDiffText ("Check: EVAL output = " <> toFilePath expectedFile) actualOutput expected ) Nothing -> assertFailure ("No main function registered in: " <> toFilePath mainFile)
7843a4944adbb49a84ecdf836d0fe50a8932db1e08e7473bdfeba27e8412d13a
SanderSpies/ocaml-gist
marg.ml
open Std (** {1 Flag parsing utils} *) type 'a t = string list -> 'a -> (string list * 'a) type 'a table = (string, 'a t) Hashtbl.t let unit f : 'a t = fun args acc -> (args, (f acc)) let param ptype f : 'a t = fun args acc -> match args with | [] -> failwith ("expects a " ^ ptype ^ " argument") | arg :: args -> args, f arg acc let unit_ignore : 'a t = fun x -> unit (fun x -> x) x let param_ignore = fun x -> param "string" (fun _ x -> x) x let bool f = param "bool" (function | "y" | "Y" | "true" | "True" | "1" -> f true | "n" | "N" | "false" | "False" | "0" -> f false | str -> failwithf "expecting boolean (%s), got %S." "y|Y|true|1 / n|N|false|0" str ) type docstring = string type 'a spec = (string * docstring * 'a t) let rec assoc3 key = function | [] -> raise Not_found | (key', _, value) :: _ when key = key' -> value | _ :: xs -> assoc3 key xs let rec mem_assoc3 key = function | [] -> false | (key', _, _) :: xs -> key = key' || mem_assoc3 key xs let parse_one ~warning global_spec local_spec args global local = match args with | [] -> None | arg :: args -> match Hashtbl.find global_spec arg with | action -> begin match action args global with | (args, global) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> match assoc3 arg local_spec with | action -> begin match action args local with | (args, local) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> None let parse_all ~warning global_spec local_spec = let rec normal_parsing args global local = match parse_one ~warning global_spec local_spec args global local with | Some (args, global, local) -> normal_parsing args global local | None -> match args with | arg :: args -> warning ("unknown flag " ^ arg); resume_parsing args global local | [] -> (global, local) and resume_parsing args global local = let args = match args with | arg :: args when not (Hashtbl.mem global_spec arg || mem_assoc3 arg local_spec) -> args | args -> args in normal_parsing args global local in normal_parsing
null
https://raw.githubusercontent.com/SanderSpies/ocaml-gist/7dc229aebdf51310e8c7dae12df0cb55b5de5a32/ocaml_webworker/merlin_lite/src/utils/marg.ml
ocaml
* {1 Flag parsing utils}
open Std type 'a t = string list -> 'a -> (string list * 'a) type 'a table = (string, 'a t) Hashtbl.t let unit f : 'a t = fun args acc -> (args, (f acc)) let param ptype f : 'a t = fun args acc -> match args with | [] -> failwith ("expects a " ^ ptype ^ " argument") | arg :: args -> args, f arg acc let unit_ignore : 'a t = fun x -> unit (fun x -> x) x let param_ignore = fun x -> param "string" (fun _ x -> x) x let bool f = param "bool" (function | "y" | "Y" | "true" | "True" | "1" -> f true | "n" | "N" | "false" | "False" | "0" -> f false | str -> failwithf "expecting boolean (%s), got %S." "y|Y|true|1 / n|N|false|0" str ) type docstring = string type 'a spec = (string * docstring * 'a t) let rec assoc3 key = function | [] -> raise Not_found | (key', _, value) :: _ when key = key' -> value | _ :: xs -> assoc3 key xs let rec mem_assoc3 key = function | [] -> false | (key', _, _) :: xs -> key = key' || mem_assoc3 key xs let parse_one ~warning global_spec local_spec args global local = match args with | [] -> None | arg :: args -> match Hashtbl.find global_spec arg with | action -> begin match action args global with | (args, global) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> match assoc3 arg local_spec with | action -> begin match action args local with | (args, local) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> None let parse_all ~warning global_spec local_spec = let rec normal_parsing args global local = match parse_one ~warning global_spec local_spec args global local with | Some (args, global, local) -> normal_parsing args global local | None -> match args with | arg :: args -> warning ("unknown flag " ^ arg); resume_parsing args global local | [] -> (global, local) and resume_parsing args global local = let args = match args with | arg :: args when not (Hashtbl.mem global_spec arg || mem_assoc3 arg local_spec) -> args | args -> args in normal_parsing args global local in normal_parsing
1cf5b30bf51bae97af2f2f469bfe515fcebb26772ede9bbf81cbeb8b33d7e3fd
anmonteiro/caqti-eio
testlib.ml
Copyright ( C ) 2015 - -2022 Petter A. Urkedal < > * * This library 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 , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * 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 GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library 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, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * 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 GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) module Sig = Sig let load_uris uris_file = (match open_in uris_file with | exception Sys_error _ -> failwith ("No -u option provided and missing " ^ uris_file) | ic -> let rec loop acc = (match input_line ic with | exception End_of_file -> close_in ic; List.rev acc | ln -> let uri = String.trim ln in if String.length uri = 0 || uri.[0] = '#' then loop acc else loop (Uri.of_string uri :: acc)) in loop []) type common_args = { uris: Uri.t list; tweaks_version: (int * int) option; } let common_args = let open Cmdliner in let uris = let doc = "Database URI(s) to be used for conducting the tests." in Arg.(value @@ opt_all string [] @@ info ~doc ["u"]) in let uris_file = let doc = "File from which to load URI(s) if no -u option is passed." in let env = Cmd.Env.info "CAQTI_TEST_URIS_FILE" in Arg.(value @@ opt file "uris.conf" @@ info ~doc ~env ["U"]) in let log_level_conv = let pp ppf level = Format.pp_print_string ppf (Logs.level_to_string level) in Arg.conv (Logs.level_of_string, pp) in let log_level = let doc = "Log level." in let env = Cmd.Env.info "CAQTI_TEST_LOG_LEVEL" in Arg.(value @@ opt log_level_conv (Some Logs.Info) @@ info ~doc ~env ["log-level"]) in let tweaks_version_conv = let parse s = (match String.split_on_char '.' s with | [a; b] -> (try Ok (int_of_string a, int_of_string b) with | Failure _ -> Error (`Msg "Invalid tweaks version.")) | _ -> Error (`Msg "Invalid tweaks version.")) in let pp ppf (a, b) = Format.fprintf ppf "%d.%d" a b in Arg.conv (parse, pp) in let tweaks_version = let doc = "Enable all tweaks introduced in the given Caqti version, \ specified as MAJOR.MINOR" in let env = Cmd.Env.info "CAQTI_COMPAT_VERSION" in Arg.(value @@ opt (some tweaks_version_conv) (Some (1, 8)) @@ info ~doc ~env ["tweaks-version"]) in let preprocess tweaks_version log_level uris uris_file = Logs.set_level log_level; let uris = (match uris with | [] -> load_uris uris_file | uris -> List.map Uri.of_string uris) in {uris; tweaks_version} in Term.(const preprocess $ tweaks_version $ log_level $ uris $ uris_file) let test_name_of_uri uri = (match Uri.scheme uri with | Some scheme -> scheme | None -> Uri.to_string uri) List.init is available from OCaml 4.6.0 let rec loop acc i = if i < 0 then acc else loop (f i :: acc) (i - 1) in loop [] (n - 1) module Make_alcotest_cli (Platform : Alcotest_engine.Platform.MAKER) (Monad : Alcotest_engine.Monad.S) = struct include Alcotest_engine.V1.Cli.Make (Platform) (Monad) let test_case_sync name speed f = test_case name speed (fun x -> Monad.return (f x)) let run_with_args_dependency ?argv name term make_tests = let tests = (match Cmdliner.Cmd.eval_peek_opts ~version_opt:true ?argv term with | Some arg, _ -> make_tests arg | _ -> []) in run_with_args ?argv name Cmdliner.Term.(const ignore $ term) tests end let () = Random.self_init (); Logs.set_reporter (Logs.format_reporter ()); (* Needed for bytecode since plugins link against C libraries: *) Dynlink.allow_unsafe_modules true
null
https://raw.githubusercontent.com/anmonteiro/caqti-eio/c709dadf22868f3c0e3d296547623d03e1fd1365/vendor/caqti/testlib/testlib.ml
ocaml
Needed for bytecode since plugins link against C libraries:
Copyright ( C ) 2015 - -2022 Petter A. Urkedal < > * * This library 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 , either version 3 of the License , or ( at your * option ) any later version , with the LGPL-3.0 Linking Exception . * * 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 GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library . If not , see * < / > and < > , respectively . * * This library 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, either version 3 of the License, or (at your * option) any later version, with the LGPL-3.0 Linking Exception. * * 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 GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * and the LGPL-3.0 Linking Exception along with this library. If not, see * </> and <>, respectively. *) module Sig = Sig let load_uris uris_file = (match open_in uris_file with | exception Sys_error _ -> failwith ("No -u option provided and missing " ^ uris_file) | ic -> let rec loop acc = (match input_line ic with | exception End_of_file -> close_in ic; List.rev acc | ln -> let uri = String.trim ln in if String.length uri = 0 || uri.[0] = '#' then loop acc else loop (Uri.of_string uri :: acc)) in loop []) type common_args = { uris: Uri.t list; tweaks_version: (int * int) option; } let common_args = let open Cmdliner in let uris = let doc = "Database URI(s) to be used for conducting the tests." in Arg.(value @@ opt_all string [] @@ info ~doc ["u"]) in let uris_file = let doc = "File from which to load URI(s) if no -u option is passed." in let env = Cmd.Env.info "CAQTI_TEST_URIS_FILE" in Arg.(value @@ opt file "uris.conf" @@ info ~doc ~env ["U"]) in let log_level_conv = let pp ppf level = Format.pp_print_string ppf (Logs.level_to_string level) in Arg.conv (Logs.level_of_string, pp) in let log_level = let doc = "Log level." in let env = Cmd.Env.info "CAQTI_TEST_LOG_LEVEL" in Arg.(value @@ opt log_level_conv (Some Logs.Info) @@ info ~doc ~env ["log-level"]) in let tweaks_version_conv = let parse s = (match String.split_on_char '.' s with | [a; b] -> (try Ok (int_of_string a, int_of_string b) with | Failure _ -> Error (`Msg "Invalid tweaks version.")) | _ -> Error (`Msg "Invalid tweaks version.")) in let pp ppf (a, b) = Format.fprintf ppf "%d.%d" a b in Arg.conv (parse, pp) in let tweaks_version = let doc = "Enable all tweaks introduced in the given Caqti version, \ specified as MAJOR.MINOR" in let env = Cmd.Env.info "CAQTI_COMPAT_VERSION" in Arg.(value @@ opt (some tweaks_version_conv) (Some (1, 8)) @@ info ~doc ~env ["tweaks-version"]) in let preprocess tweaks_version log_level uris uris_file = Logs.set_level log_level; let uris = (match uris with | [] -> load_uris uris_file | uris -> List.map Uri.of_string uris) in {uris; tweaks_version} in Term.(const preprocess $ tweaks_version $ log_level $ uris $ uris_file) let test_name_of_uri uri = (match Uri.scheme uri with | Some scheme -> scheme | None -> Uri.to_string uri) List.init is available from OCaml 4.6.0 let rec loop acc i = if i < 0 then acc else loop (f i :: acc) (i - 1) in loop [] (n - 1) module Make_alcotest_cli (Platform : Alcotest_engine.Platform.MAKER) (Monad : Alcotest_engine.Monad.S) = struct include Alcotest_engine.V1.Cli.Make (Platform) (Monad) let test_case_sync name speed f = test_case name speed (fun x -> Monad.return (f x)) let run_with_args_dependency ?argv name term make_tests = let tests = (match Cmdliner.Cmd.eval_peek_opts ~version_opt:true ?argv term with | Some arg, _ -> make_tests arg | _ -> []) in run_with_args ?argv name Cmdliner.Term.(const ignore $ term) tests end let () = Random.self_init (); Logs.set_reporter (Logs.format_reporter ()); Dynlink.allow_unsafe_modules true
7109dd68855c8c892195dc8c18fdcc18015826db897941b7623ad0a64ac6a8e3
digitallyinduced/ihp-forum
Show.hs
module Web.View.Comments.Show where import Web.View.Prelude data ShowView = ShowView { comment :: Comment } instance View ShowView where html ShowView { .. } = [hsx| <h1>Show Comment</h1> |]
null
https://raw.githubusercontent.com/digitallyinduced/ihp-forum/ac36ad4ab5dfe7b3aa85ea92d642aec12e4fa6ad/Web/View/Comments/Show.hs
haskell
module Web.View.Comments.Show where import Web.View.Prelude data ShowView = ShowView { comment :: Comment } instance View ShowView where html ShowView { .. } = [hsx| <h1>Show Comment</h1> |]
50abfa4c0eaf0d29b4dceadfd23268cdc825595b1d539cc0cab7af5219cde72d
robert-strandh/SICL
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-environment (:use #:common-lisp) (:shadow #:get-setf-expansion type) (:shadowing-import-from #:clostrum . #.(loop for symbol being each external-symbol in '#:clostrum unless (member symbol '(clostrum:run-time-environment clostrum:compilation-environment clostrum:function-description clostrum:class-description clostrum:variable-description)) collect (symbol-name symbol))) (:export #:global-environment #:*environment* #:client #:method-combination-template #:base-run-time-environment #:run-time-environment #:evaluation-environment #:compilation-environment #:function-description #:simple-function-description #:make-simple-function-description #:generic-function-description #:make-generic-function-description #:lambda-list #:class-name #:method-class-name #:method-combination-info #:get-setf-expansion #:variable-description #:constant-variable-description #:make-constant-variable-description #:special-variable-description #:make-special-variable-description #:class-description #:make-class-description #:name #:superclass-names #:metaclass-name #:type #:value #:find-method-combination-template #:who-calls-information #:structure-description #:function-cell #:variable-cell #:traced-functions #:map-defined-functions #:map-defined-classes #:map-defined-method-combination-templates #:make-environment-for-file-compilation #:add-call-site . #.(loop for symbol being each external-symbol in '#:clostrum unless (member symbol '(clostrum:run-time-environment clostrum:compilation-environment)) collect (symbol-name symbol))))
null
https://raw.githubusercontent.com/robert-strandh/SICL/59d8fa94811a0eac4ac747333ad9ecd976652c41/Code/Environment-Clostrum/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-environment (:use #:common-lisp) (:shadow #:get-setf-expansion type) (:shadowing-import-from #:clostrum . #.(loop for symbol being each external-symbol in '#:clostrum unless (member symbol '(clostrum:run-time-environment clostrum:compilation-environment clostrum:function-description clostrum:class-description clostrum:variable-description)) collect (symbol-name symbol))) (:export #:global-environment #:*environment* #:client #:method-combination-template #:base-run-time-environment #:run-time-environment #:evaluation-environment #:compilation-environment #:function-description #:simple-function-description #:make-simple-function-description #:generic-function-description #:make-generic-function-description #:lambda-list #:class-name #:method-class-name #:method-combination-info #:get-setf-expansion #:variable-description #:constant-variable-description #:make-constant-variable-description #:special-variable-description #:make-special-variable-description #:class-description #:make-class-description #:name #:superclass-names #:metaclass-name #:type #:value #:find-method-combination-template #:who-calls-information #:structure-description #:function-cell #:variable-cell #:traced-functions #:map-defined-functions #:map-defined-classes #:map-defined-method-combination-templates #:make-environment-for-file-compilation #:add-call-site . #.(loop for symbol being each external-symbol in '#:clostrum unless (member symbol '(clostrum:run-time-environment clostrum:compilation-environment)) collect (symbol-name symbol))))
a62fdce8ee89bbe9ce8479f8b54aa4c966b3fba4665076de50b43069fd6bb56c
stevenvar/OMicroB
int32.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , 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. *) (* *) (**************************************************************************) * 32 - bit integers . This module provides operations on the type [ int32 ] of signed 32 - bit integers . Unlike the built - in [ int ] type , the type [ int32 ] is guaranteed to be exactly 32 - bit wide on all platforms . All arithmetic operations over [ int32 ] are taken modulo 2{^32 } . Performance notice : values of type [ int32 ] occupy more memory space than values of type [ int ] , and arithmetic operations on [ int32 ] are generally slower than those on [ int ] . Use [ int32 ] only when the application requires exact 32 - bit arithmetic . This module provides operations on the type [int32] of signed 32-bit integers. Unlike the built-in [int] type, the type [int32] is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over [int32] are taken modulo 2{^32}. Performance notice: values of type [int32] occupy more memory space than values of type [int], and arithmetic operations on [int32] are generally slower than those on [int]. Use [int32] only when the application requires exact 32-bit arithmetic. *) val zero : int32 * The 32 - bit integer 0 . val one : int32 * The 32 - bit integer 1 . val minus_one : int32 * The 32 - bit integer -1 . external neg : int32 -> int32 = "%int32_neg" (** Unary negation. *) external add : int32 -> int32 -> int32 = "%int32_add" (** Addition. *) external sub : int32 -> int32 -> int32 = "%int32_sub" (** Subtraction. *) external mul : int32 -> int32 -> int32 = "%int32_mul" (** Multiplication. *) external div : int32 -> int32 -> int32 = "%int32_div" * Integer division . Raise [ Division_by_zero ] if the second argument is zero . This division rounds the real quotient of its arguments towards zero , as specified for { ! Stdlib.(/ ) } . argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for {!Stdlib.(/)}. *) external rem : int32 -> int32 -> int32 = "%int32_mod" * Integer remainder . If [ y ] is not zero , the result of [ Int32.rem x y ] satisfies the following property : [ x = Int32.add ( ( Int32.div x y ) y ) ( Int32.rem x y ) ] . If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] . of [Int32.rem x y] satisfies the following property: [x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)]. If [y = 0], [Int32.rem x y] raises [Division_by_zero]. *) val succ : int32 -> int32 (** Successor. [Int32.succ x] is [Int32.add x Int32.one]. *) val pred : int32 -> int32 (** Predecessor. [Int32.pred x] is [Int32.sub x Int32.one]. *) val abs : int32 -> int32 (** Return the absolute value of its argument. *) val max_int : int32 * The greatest representable 32 - bit integer , 2{^31 } - 1 . val min_int : int32 * The smallest representable 32 - bit integer , -2{^31 } . external logand : int32 -> int32 -> int32 = "%int32_and" (** Bitwise logical and. *) external logor : int32 -> int32 -> int32 = "%int32_or" (** Bitwise logical or. *) external logxor : int32 -> int32 -> int32 = "%int32_xor" (** Bitwise logical exclusive or. *) val lognot : int32 -> int32 (** Bitwise logical negation. *) external shift_left : int32 -> int -> int32 = "%int32_lsl" * [ Int32.shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right : int32 -> int -> int32 = "%int32_asr" * [ Int32.shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an arithmetic shift : the sign bit of [ x ] is replicated and inserted in the vacated bits . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . This is an arithmetic shift: the sign bit of [x] is replicated and inserted in the vacated bits. The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right_logical : int32 -> int -> int32 = "%int32_lsr" * [ Int32.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a logical shift : zeroes are inserted in the vacated bits regardless of the sign of [ x ] . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of [x]. The result is unspecified if [y < 0] or [y >= 32]. *) external of_int : int -> int32 = "%int32_of_int" * Convert the given integer ( type [ int ] ) to a 32 - bit integer ( type [ int32 ] ) . (type [int32]). *) external to_int : int32 -> int = "%int32_to_int" * Convert the given 32 - bit integer ( type [ int32 ] ) to an integer ( type [ int ] ) . On 32 - bit platforms , the 32 - bit integer is taken modulo 2{^31 } , i.e. the high - order bit is lost during the conversion . On 64 - bit platforms , the conversion is exact . integer (type [int]). On 32-bit platforms, the 32-bit integer is taken modulo 2{^31}, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. *) external of_float : float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed" [@@unboxed] [@@noalloc] * Convert the given floating - point number to a 32 - bit integer , discarding the fractional part ( truncate towards 0 ) . The result of the conversion is undefined if , after truncation , the number is outside the range \[{!Int32.min_int } , { ! Int32.max_int}\ ] . discarding the fractional part (truncate towards 0). The result of the conversion is undefined if, after truncation, the number is outside the range \[{!Int32.min_int}, {!Int32.max_int}\]. *) external to_float : int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed" [@@unboxed] [@@noalloc] * Convert the given 32 - bit integer to a floating - point number . external of_string : string -> int32 = "caml_int32_of_string" * Convert the given string to a 32 - bit integer . The string is read in decimal ( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively . The [ 0u ] prefix reads the input as an unsigned integer in the range [ [ 0 , 2*Int32.max_int+1 ] ] . If the input exceeds { ! Int32.max_int } it is converted to the signed integer [ Int32.min_int + input - Int32.max_int - 1 ] . The [ _ ] ( underscore ) character can appear anywhere in the string and is ignored . Raise [ Failure " Int32.of_string " ] if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ int32 ] . The string is read in decimal (by default, or if the string begins with [0u]) or in hexadecimal, octal or binary if the string begins with [0x], [0o] or [0b] respectively. The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*Int32.max_int+1]]. If the input exceeds {!Int32.max_int} it is converted to the signed integer [Int32.min_int + input - Int32.max_int - 1]. The [_] (underscore) character can appear anywhere in the string and is ignored. Raise [Failure "Int32.of_string"] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int32]. *) val of_string_opt: string -> int32 option * Same as [ of_string ] , but return [ None ] instead of raising . @since 4.05 @since 4.05 *) val to_string : int32 -> string (** Return the string representation of its argument, in signed decimal. *) external bits_of_float : float -> int32 = "caml_int32_bits_of_float" "caml_int32_bits_of_float_unboxed" [@@unboxed] [@@noalloc] * Return the internal representation of the given float according to the IEEE 754 floating - point ' single format ' bit layout . Bit 31 of the result represents the sign of the float ; bits 30 to 23 represent the ( biased ) exponent ; bits 22 to 0 represent the mantissa . to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. *) external float_of_bits : int32 -> float = "caml_int32_float_of_bits" "caml_int32_float_of_bits_unboxed" [@@unboxed] [@@noalloc] (** Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given [int32]. *) type t = int32 * An alias for the type of 32 - bit integers . val compare: t -> t -> int * The comparison function for 32 - bit integers , with the same specification as { ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ] allows the module [ Int32 ] to be passed as argument to the functors { ! Set . Make } and { ! Map . Make } . {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [Int32] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val equal: t -> t -> bool * The equal function for int32s . @since 4.03.0 @since 4.03.0 *) (**/**)
null
https://raw.githubusercontent.com/stevenvar/OMicroB/e4324d0736ac677b3086741dfdefb0e46775642b/src/stdlib/int32.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Unary negation. * Addition. * Subtraction. * Multiplication. * Successor. [Int32.succ x] is [Int32.add x Int32.one]. * Predecessor. [Int32.pred x] is [Int32.sub x Int32.one]. * Return the absolute value of its argument. * Bitwise logical and. * Bitwise logical or. * Bitwise logical exclusive or. * Bitwise logical negation. * Return the string representation of its argument, in signed decimal. * Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given [int32]. */*
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * 32 - bit integers . This module provides operations on the type [ int32 ] of signed 32 - bit integers . Unlike the built - in [ int ] type , the type [ int32 ] is guaranteed to be exactly 32 - bit wide on all platforms . All arithmetic operations over [ int32 ] are taken modulo 2{^32 } . Performance notice : values of type [ int32 ] occupy more memory space than values of type [ int ] , and arithmetic operations on [ int32 ] are generally slower than those on [ int ] . Use [ int32 ] only when the application requires exact 32 - bit arithmetic . This module provides operations on the type [int32] of signed 32-bit integers. Unlike the built-in [int] type, the type [int32] is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over [int32] are taken modulo 2{^32}. Performance notice: values of type [int32] occupy more memory space than values of type [int], and arithmetic operations on [int32] are generally slower than those on [int]. Use [int32] only when the application requires exact 32-bit arithmetic. *) val zero : int32 * The 32 - bit integer 0 . val one : int32 * The 32 - bit integer 1 . val minus_one : int32 * The 32 - bit integer -1 . external neg : int32 -> int32 = "%int32_neg" external add : int32 -> int32 -> int32 = "%int32_add" external sub : int32 -> int32 -> int32 = "%int32_sub" external mul : int32 -> int32 -> int32 = "%int32_mul" external div : int32 -> int32 -> int32 = "%int32_div" * Integer division . Raise [ Division_by_zero ] if the second argument is zero . This division rounds the real quotient of its arguments towards zero , as specified for { ! Stdlib.(/ ) } . argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for {!Stdlib.(/)}. *) external rem : int32 -> int32 -> int32 = "%int32_mod" * Integer remainder . If [ y ] is not zero , the result of [ Int32.rem x y ] satisfies the following property : [ x = Int32.add ( ( Int32.div x y ) y ) ( Int32.rem x y ) ] . If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] . of [Int32.rem x y] satisfies the following property: [x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)]. If [y = 0], [Int32.rem x y] raises [Division_by_zero]. *) val succ : int32 -> int32 val pred : int32 -> int32 val abs : int32 -> int32 val max_int : int32 * The greatest representable 32 - bit integer , 2{^31 } - 1 . val min_int : int32 * The smallest representable 32 - bit integer , -2{^31 } . external logand : int32 -> int32 -> int32 = "%int32_and" external logor : int32 -> int32 -> int32 = "%int32_or" external logxor : int32 -> int32 -> int32 = "%int32_xor" val lognot : int32 -> int32 external shift_left : int32 -> int -> int32 = "%int32_lsl" * [ Int32.shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right : int32 -> int -> int32 = "%int32_asr" * [ Int32.shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an arithmetic shift : the sign bit of [ x ] is replicated and inserted in the vacated bits . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . This is an arithmetic shift: the sign bit of [x] is replicated and inserted in the vacated bits. The result is unspecified if [y < 0] or [y >= 32]. *) external shift_right_logical : int32 -> int -> int32 = "%int32_lsr" * [ Int32.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a logical shift : zeroes are inserted in the vacated bits regardless of the sign of [ x ] . The result is unspecified if [ y < 0 ] or [ y > = 32 ] . This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of [x]. The result is unspecified if [y < 0] or [y >= 32]. *) external of_int : int -> int32 = "%int32_of_int" * Convert the given integer ( type [ int ] ) to a 32 - bit integer ( type [ int32 ] ) . (type [int32]). *) external to_int : int32 -> int = "%int32_to_int" * Convert the given 32 - bit integer ( type [ int32 ] ) to an integer ( type [ int ] ) . On 32 - bit platforms , the 32 - bit integer is taken modulo 2{^31 } , i.e. the high - order bit is lost during the conversion . On 64 - bit platforms , the conversion is exact . integer (type [int]). On 32-bit platforms, the 32-bit integer is taken modulo 2{^31}, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. *) external of_float : float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed" [@@unboxed] [@@noalloc] * Convert the given floating - point number to a 32 - bit integer , discarding the fractional part ( truncate towards 0 ) . The result of the conversion is undefined if , after truncation , the number is outside the range \[{!Int32.min_int } , { ! Int32.max_int}\ ] . discarding the fractional part (truncate towards 0). The result of the conversion is undefined if, after truncation, the number is outside the range \[{!Int32.min_int}, {!Int32.max_int}\]. *) external to_float : int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed" [@@unboxed] [@@noalloc] * Convert the given 32 - bit integer to a floating - point number . external of_string : string -> int32 = "caml_int32_of_string" * Convert the given string to a 32 - bit integer . The string is read in decimal ( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively . The [ 0u ] prefix reads the input as an unsigned integer in the range [ [ 0 , 2*Int32.max_int+1 ] ] . If the input exceeds { ! Int32.max_int } it is converted to the signed integer [ Int32.min_int + input - Int32.max_int - 1 ] . The [ _ ] ( underscore ) character can appear anywhere in the string and is ignored . Raise [ Failure " Int32.of_string " ] if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ int32 ] . The string is read in decimal (by default, or if the string begins with [0u]) or in hexadecimal, octal or binary if the string begins with [0x], [0o] or [0b] respectively. The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*Int32.max_int+1]]. If the input exceeds {!Int32.max_int} it is converted to the signed integer [Int32.min_int + input - Int32.max_int - 1]. The [_] (underscore) character can appear anywhere in the string and is ignored. Raise [Failure "Int32.of_string"] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int32]. *) val of_string_opt: string -> int32 option * Same as [ of_string ] , but return [ None ] instead of raising . @since 4.05 @since 4.05 *) val to_string : int32 -> string external bits_of_float : float -> int32 = "caml_int32_bits_of_float" "caml_int32_bits_of_float_unboxed" [@@unboxed] [@@noalloc] * Return the internal representation of the given float according to the IEEE 754 floating - point ' single format ' bit layout . Bit 31 of the result represents the sign of the float ; bits 30 to 23 represent the ( biased ) exponent ; bits 22 to 0 represent the mantissa . to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. *) external float_of_bits : int32 -> float = "caml_int32_float_of_bits" "caml_int32_float_of_bits_unboxed" [@@unboxed] [@@noalloc] type t = int32 * An alias for the type of 32 - bit integers . val compare: t -> t -> int * The comparison function for 32 - bit integers , with the same specification as { ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ] allows the module [ Int32 ] to be passed as argument to the functors { ! Set . Make } and { ! Map . Make } . {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [Int32] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val equal: t -> t -> bool * The equal function for int32s . @since 4.03.0 @since 4.03.0 *)
847e3073e66c1f757c472709f90cfb2299b33f491b13ab5122abffed70d12794
froggey/Mezzano
condition.lisp
;;;; The condition/error system. (in-package :mezzano.internals) (defmethod print-object ((object restart) stream) (cond (*print-escape* (print-unreadable-object (object stream :type t :identity t) (write (restart-name object) :stream stream))) (t (report-restart object stream)))) (defparameter *break-on-signals* nil) (defparameter *active-handlers* nil) (defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &rest options) (let ((report (assoc :report options))) `(progn (defclass ,name ,(or parent-types '(condition)) ,slot-specs ,@(remove :report options :key 'car)) ,@(when report (list `(defmethod print-object ((condition ,name) stream) (if *print-escape* (call-next-method) (funcall #',(if (stringp (second report)) `(lambda (condition stream) (declare (ignore condition)) (write-string ,(second report) stream)) (second report)) condition stream))))) ',name))) (define-condition condition (standard-object) () (:report (lambda (condition stream) (format stream "The condition ~S was signalled." (class-name (class-of condition)))))) (define-condition serious-condition (condition) ()) (define-condition simple-condition (condition) ((format-control :initarg :format-control :initform nil :reader simple-condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader simple-condition-format-arguments))) (defmethod print-object ((c simple-condition) s) (cond (*print-escape* (print-unreadable-object (c s :type t :identity t) (format s "~S ~:S" (simple-condition-format-control c) (simple-condition-format-arguments c)))) ((simple-condition-format-control c) (apply #'format s (simple-condition-format-control c) (simple-condition-format-arguments c))) (t (error "No format control for ~S." c)))) (defun make-condition (type &rest slot-initializations) (declare (dynamic-extent slot-initializations)) (apply #'make-instance type slot-initializations)) (deftype condition-designator () '(or symbol string function condition)) (defun coerce-to-condition (default datum arguments) (cond ((symbolp datum) (apply #'make-condition datum arguments)) ((or (stringp datum) (functionp datum)) (make-condition default :format-control datum :format-arguments arguments)) ((typep datum 'condition) (check-type arguments null) datum) (t (error 'type-error :datum default :expected-type 'condition-designator)))) (defun signal (datum &rest arguments) (let ((condition (coerce-to-condition 'simple-condition datum arguments))) (when (and *break-on-signals* (typep condition *break-on-signals*)) (let ((*break-on-signals* nil)) (break "Condition: ~S~%BREAK entered due to *BREAK-ON-SIGNALS*" condition))) (do ((handlers *active-handlers* (rest handlers))) ((endp handlers)) (dolist (h (first handlers)) (when (typep condition (car h)) (let ((*active-handlers* (rest handlers))) (funcall (cdr h) condition)) ;; If a handler in this cluster declines, then no other handler in the cluster will be considered for possible invocation . ( 9.1.4 ) (return)))) nil)) (defun %handler-bind (bindings thunk) (if *active-handlers* ;; There is a barrier here as this would capture the entire stack of handlers ;; not just the ones inside the continuation. ;; This should switch to a mechanism similar to %CATCH, but that is more ;; difficult to handle because of the visibility requirements when calling ;; handlers. (mezzano.delimited-continuations:with-continuation-barrier ('handler-bind) (let ((*active-handlers* (cons bindings *active-handlers*))) (funcall thunk))) (let ((*active-handlers* (cons bindings *active-handlers*))) (funcall thunk)))) (defmacro handler-bind (bindings &body forms) `(%handler-bind (list ,@(mapcar (lambda (binding) (destructuring-bind (type handler) binding `(cons ',type ,handler))) bindings)) (lambda () (progn ,@forms)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun compute-handler-case-forms (clauses) (let ((block-name (gensym)) (condition-var (gensym)) (handler-bind-forms '()) (tagbody-forms '())) (dolist (clause clauses) (destructuring-bind (typespec (&optional var) &body body) clause (let ((tag (gensym))) (push `(,typespec #'(lambda (temp) (setq ,condition-var temp) (go ,tag))) handler-bind-forms) (push `(return-from ,block-name ,(if var `(let ((,var ,condition-var)) ,@body) `(locally ,@body))) tagbody-forms) (push tag tagbody-forms)))) (values (nreverse handler-bind-forms) tagbody-forms block-name condition-var))) ) (defmacro handler-case (expression &rest clauses) (let ((no-error (assoc :no-error clauses))) (if no-error Strip out : no - error clauses . (let ((error-return (make-symbol "error-return")) (normal-return (make-symbol "normal-return"))) `(block ,error-return (multiple-value-call #'(lambda ,(second no-error) ,@(cddr no-error)) (block ,normal-return (return-from ,error-return (handler-case (return-from ,normal-return ,expression) ,@(remove no-error clauses))))))) (multiple-value-bind (handler-bind-forms tagbody-forms block-name condition-var) (compute-handler-case-forms clauses) `(block ,block-name (let ((,condition-var nil)) (declare (ignorable ,condition-var)) (tagbody (handler-bind ,handler-bind-forms (return-from ,block-name ,expression)) ,@tagbody-forms))))))) (defmacro ignore-errors (&body forms) `(handler-case (progn ,@forms) (error (condition) (values nil condition)))) (defmacro log-and-ignore-errors (&body forms) (let ((exit-block (gensym "exit-block"))) `(block ,exit-block ;; Use HANDLER-BIND instead of HANDLER-CASE so that the whole backtrace ;; is caught. (handler-bind ((error (lambda (c) (ignore-errors (let ((*standard-output* *error-output*)) (format *error-output* "~&Error ~A.~%" c) (backtrace))) (return-from ,exit-block (values nil c))))) ,@forms))))
null
https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/system/condition.lisp
lisp
The condition/error system. If a handler in this cluster declines, then no other handler There is a barrier here as this would capture the entire stack of handlers not just the ones inside the continuation. This should switch to a mechanism similar to %CATCH, but that is more difficult to handle because of the visibility requirements when calling handlers. Use HANDLER-BIND instead of HANDLER-CASE so that the whole backtrace is caught.
(in-package :mezzano.internals) (defmethod print-object ((object restart) stream) (cond (*print-escape* (print-unreadable-object (object stream :type t :identity t) (write (restart-name object) :stream stream))) (t (report-restart object stream)))) (defparameter *break-on-signals* nil) (defparameter *active-handlers* nil) (defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &rest options) (let ((report (assoc :report options))) `(progn (defclass ,name ,(or parent-types '(condition)) ,slot-specs ,@(remove :report options :key 'car)) ,@(when report (list `(defmethod print-object ((condition ,name) stream) (if *print-escape* (call-next-method) (funcall #',(if (stringp (second report)) `(lambda (condition stream) (declare (ignore condition)) (write-string ,(second report) stream)) (second report)) condition stream))))) ',name))) (define-condition condition (standard-object) () (:report (lambda (condition stream) (format stream "The condition ~S was signalled." (class-name (class-of condition)))))) (define-condition serious-condition (condition) ()) (define-condition simple-condition (condition) ((format-control :initarg :format-control :initform nil :reader simple-condition-format-control) (format-arguments :initarg :format-arguments :initform nil :reader simple-condition-format-arguments))) (defmethod print-object ((c simple-condition) s) (cond (*print-escape* (print-unreadable-object (c s :type t :identity t) (format s "~S ~:S" (simple-condition-format-control c) (simple-condition-format-arguments c)))) ((simple-condition-format-control c) (apply #'format s (simple-condition-format-control c) (simple-condition-format-arguments c))) (t (error "No format control for ~S." c)))) (defun make-condition (type &rest slot-initializations) (declare (dynamic-extent slot-initializations)) (apply #'make-instance type slot-initializations)) (deftype condition-designator () '(or symbol string function condition)) (defun coerce-to-condition (default datum arguments) (cond ((symbolp datum) (apply #'make-condition datum arguments)) ((or (stringp datum) (functionp datum)) (make-condition default :format-control datum :format-arguments arguments)) ((typep datum 'condition) (check-type arguments null) datum) (t (error 'type-error :datum default :expected-type 'condition-designator)))) (defun signal (datum &rest arguments) (let ((condition (coerce-to-condition 'simple-condition datum arguments))) (when (and *break-on-signals* (typep condition *break-on-signals*)) (let ((*break-on-signals* nil)) (break "Condition: ~S~%BREAK entered due to *BREAK-ON-SIGNALS*" condition))) (do ((handlers *active-handlers* (rest handlers))) ((endp handlers)) (dolist (h (first handlers)) (when (typep condition (car h)) (let ((*active-handlers* (rest handlers))) (funcall (cdr h) condition)) in the cluster will be considered for possible invocation . ( 9.1.4 ) (return)))) nil)) (defun %handler-bind (bindings thunk) (if *active-handlers* (mezzano.delimited-continuations:with-continuation-barrier ('handler-bind) (let ((*active-handlers* (cons bindings *active-handlers*))) (funcall thunk))) (let ((*active-handlers* (cons bindings *active-handlers*))) (funcall thunk)))) (defmacro handler-bind (bindings &body forms) `(%handler-bind (list ,@(mapcar (lambda (binding) (destructuring-bind (type handler) binding `(cons ',type ,handler))) bindings)) (lambda () (progn ,@forms)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun compute-handler-case-forms (clauses) (let ((block-name (gensym)) (condition-var (gensym)) (handler-bind-forms '()) (tagbody-forms '())) (dolist (clause clauses) (destructuring-bind (typespec (&optional var) &body body) clause (let ((tag (gensym))) (push `(,typespec #'(lambda (temp) (setq ,condition-var temp) (go ,tag))) handler-bind-forms) (push `(return-from ,block-name ,(if var `(let ((,var ,condition-var)) ,@body) `(locally ,@body))) tagbody-forms) (push tag tagbody-forms)))) (values (nreverse handler-bind-forms) tagbody-forms block-name condition-var))) ) (defmacro handler-case (expression &rest clauses) (let ((no-error (assoc :no-error clauses))) (if no-error Strip out : no - error clauses . (let ((error-return (make-symbol "error-return")) (normal-return (make-symbol "normal-return"))) `(block ,error-return (multiple-value-call #'(lambda ,(second no-error) ,@(cddr no-error)) (block ,normal-return (return-from ,error-return (handler-case (return-from ,normal-return ,expression) ,@(remove no-error clauses))))))) (multiple-value-bind (handler-bind-forms tagbody-forms block-name condition-var) (compute-handler-case-forms clauses) `(block ,block-name (let ((,condition-var nil)) (declare (ignorable ,condition-var)) (tagbody (handler-bind ,handler-bind-forms (return-from ,block-name ,expression)) ,@tagbody-forms))))))) (defmacro ignore-errors (&body forms) `(handler-case (progn ,@forms) (error (condition) (values nil condition)))) (defmacro log-and-ignore-errors (&body forms) (let ((exit-block (gensym "exit-block"))) `(block ,exit-block (handler-bind ((error (lambda (c) (ignore-errors (let ((*standard-output* *error-output*)) (format *error-output* "~&Error ~A.~%" c) (backtrace))) (return-from ,exit-block (values nil c))))) ,@forms))))
a6471c34a62bc10feb4277d8fb97a7f4de0766b5c5a0de0c2a61adfd804ac8a6
ocaml/dune
dir_contents.ml
open Import we need to convince ocamldep that we do n't depend on the menhir rules module Menhir = struct end open Dune_file open Memo.O let loc_of_dune_file st_dir = Loc.in_file (Path.source (match let open Option.O in let* dune_file = Source_tree.Dir.dune_file st_dir in TODO not really correct . we need to know the [ ( subdir .. ) ] that introduced this Source_tree.Dune_file.path dune_file with | Some s -> s | None -> Path.Source.relative (Source_tree.Dir.path st_dir) "_unknown_")) type t = { kind : kind ; dir : Path.Build.t ; text_files : String.Set.t ; foreign_sources : Foreign_sources.t Memo.Lazy.t ; mlds : (Documentation.t * Path.Build.t list) list Memo.Lazy.t ; coq : Coq_sources.t Memo.Lazy.t ; ml : Ml_sources.t Memo.Lazy.t } and kind = | Standalone | Group_root of t list | Group_part let empty kind ~dir = { kind ; dir ; text_files = String.Set.empty ; ml = Memo.Lazy.of_val Ml_sources.empty ; mlds = Memo.Lazy.of_val [] ; foreign_sources = Memo.Lazy.of_val Foreign_sources.empty ; coq = Memo.Lazy.of_val Coq_sources.empty } type standalone_or_root = { root : t ; subdirs : t list ; rules : Rules.t } type triage = | Standalone_or_root of { directory_targets : Loc.t Path.Build.Map.t ; contents : standalone_or_root Memo.Lazy.t } | Group_part of Path.Build.t let dir t = t.dir let coq t = Memo.Lazy.force t.coq let ocaml t = Memo.Lazy.force t.ml let artifacts t = Memo.Lazy.force t.ml >>= Ml_sources.artifacts let dirs t = match t.kind with | Standalone -> [ t ] | Group_root subs -> t :: subs | Group_part -> Code_error.raise "Dir_contents.dirs called on a group part" [ ("dir", Path.Build.to_dyn t.dir) ] let text_files t = t.text_files let foreign_sources t = Memo.Lazy.force t.foreign_sources let mlds t (doc : Documentation.t) = let+ map = Memo.Lazy.force t.mlds in match List.find_map map ~f:(fun (doc', x) -> Option.some_if (Loc.equal doc.loc doc'.loc) x) with | Some x -> x | None -> Code_error.raise "Dir_contents.mlds" [ ("doc", Loc.to_dyn_hum doc.loc) ; ( "available" , Dyn.(list Loc.to_dyn_hum) (List.map map ~f:(fun ((d : Documentation.t), _) -> d.loc)) ) ] let build_mlds_map stanzas ~dir ~files = let mlds = Memo.lazy_ (fun () -> String.Set.fold files ~init:String.Map.empty ~f:(fun fn acc -> match String.lsplit2 fn ~on:'.' with | Some (s, "mld") -> String.Map.set acc s fn | _ -> acc) |> Memo.return) in Memo.parallel_map stanzas ~f:(function | Documentation doc -> let+ mlds = let+ mlds = Memo.Lazy.force mlds in Ordered_set_lang.Unordered_string.eval doc.mld_files ~standard:mlds ~key:Fun.id ~parse:(fun ~loc s -> match String.Map.find mlds s with | Some s -> s | None -> User_error.raise ~loc [ Pp.textf "%s.mld doesn't exist in %s" s (Path.to_string_maybe_quoted (Path.drop_optional_build_context (Path.build dir))) ]) in Some (doc, List.map (String.Map.values mlds) ~f:(Path.Build.relative dir)) | _ -> Memo.return None) >>| List.filter_opt module rec Load : sig val get : Super_context.t -> dir:Path.Build.t -> t Memo.t val triage : Super_context.t -> dir:Path.Build.t -> triage Memo.t val add_sources_to_expander : Super_context.t -> Expander.t -> Expander.t end = struct let add_sources_to_expander sctx expander = let f ~dir = Load.get sctx ~dir >>= artifacts in Expander.set_lookup_ml_sources expander ~f (* As a side-effect, setup user rules and copy_files rules. *) let load_text_files sctx st_dir stanzas ~dir ~src_dir = let select_deps_files libraries = (* Manually add files generated by the (select ...) dependencies *) List.filter_map libraries ~f:(fun dep -> match (dep : Lib_dep.t) with | Re_export _ | Direct _ -> None | Select s -> Some s.result_fn) in (* Interpret a few stanzas in order to determine the list of files generated by the user. *) let* expander = Super_context.expander sctx ~dir >>| add_sources_to_expander sctx in let+ generated_files = Memo.parallel_map stanzas ~f:(fun stanza -> match (stanza : Stanza.t) with | Coq_stanza.Coqpp.T { modules; _ } -> let+ mlg_files = Coq_sources.mlg_files ~sctx ~dir ~modules in List.rev_map mlg_files ~f:(fun mlg_file -> Path.Build.set_extension mlg_file ~ext:".ml" |> Path.Build.basename) | Coq_stanza.Extraction.T s -> Memo.return (Coq_stanza.Extraction.ml_target_fnames s) | Menhir_stanza.T menhir -> Memo.return (Menhir_stanza.targets menhir) | Rule rule -> ( Simple_rules.user_rule sctx rule ~dir ~expander >>| function | None -> [] | Some targets -> (* CR-someday amokhov: Do not ignore directory targets. *) Path.Build.Set.to_list_map targets.files ~f:Path.Build.basename) | Copy_files def -> let+ ps = Simple_rules.copy_files sctx def ~src_dir ~dir ~expander in Path.Set.to_list_map ps ~f:Path.basename | Generate_sites_module_stanza.T def -> let+ res = Generate_sites_module_rules.setup_rules sctx ~dir def in [ res ] | Library { buildable; _ } | Executables { buildable; _ } -> let select_deps_files = select_deps_files buildable.libraries in let ctypes_files = (* Also manually add files generated by ctypes rules. *) match buildable.ctypes with | None -> [] | Some ctypes -> Ctypes_field.generated_ml_and_c_files ctypes in Memo.return (select_deps_files @ ctypes_files) | Melange_stanzas.Emit.T { libraries; _ } -> let select_deps_files = select_deps_files libraries in Memo.return select_deps_files | _ -> Memo.return []) >>| fun l -> String.Set.of_list (List.concat l) in String.Set.union generated_files (Source_tree.Dir.files st_dir) type result0_here = { t : t ; (* [rules] includes rules for subdirectories too *) rules : Rules.t The [ kind ] of the nodes must be Group_part subdirs : t Path.Build.Map.t } type result0 = | See_above of Path.Build.t | Here of { directory_targets : Loc.t Path.Build.Map.t ; contents : result0_here Memo.Lazy.t } module Key = struct module Super_context = Super_context.As_memo_key type t = Super_context.t * Path.Build.t let to_dyn (sctx, path) = Dyn.Tuple [ Super_context.to_dyn sctx; Path.Build.to_dyn path ] let equal = Tuple.T2.equal Super_context.equal Path.Build.equal let hash = Tuple.T2.hash Super_context.hash Path.Build.hash end let lookup_vlib sctx ~current_dir ~loc ~dir = match Path.Build.equal current_dir dir with | true -> User_error.raise ~loc [ Pp.text "Virtual library and its implementation(s) cannot be defined in \ the same directory" ] | false -> Load.get sctx ~dir >>= ocaml let collect_group ~st_dir ~dir = let rec walk st_dir ~dir ~local = let* status = Dir_status.DB.get ~dir in match status with | Is_component_of_a_group_but_not_the_root { stanzas; group_root = _ } -> let+ l = walk_children st_dir ~dir ~local in Appendable_list.( @ ) (Appendable_list.singleton (dir, List.rev local, st_dir, stanzas)) l | Generated | Source_only _ | Standalone _ | Group_root _ -> Memo.return Appendable_list.empty and walk_children st_dir ~dir ~local = let+ l = Source_tree.Dir.sub_dirs st_dir |> String.Map.to_list |> Memo.parallel_map ~f:(fun (basename, st_dir) -> let* st_dir = Source_tree.Dir.sub_dir_as_t st_dir in let dir = Path.Build.relative dir basename in let local = basename :: local in walk st_dir ~dir ~local) in Appendable_list.concat l in let+ l = walk_children st_dir ~dir ~local:[] in Appendable_list.to_list l let extract_directory_targets ~dir stanzas = List.fold_left stanzas ~init:Path.Build.Map.empty ~f:(fun acc stanza -> match stanza with | Rule { targets = Static { targets = l; _ }; loc = rule_loc; _ } -> List.fold_left l ~init:acc ~f:(fun acc (target, kind) -> let loc = String_with_vars.loc target in match (kind : Targets_spec.Kind.t) with | File -> acc | Directory -> ( match String_with_vars.text_only target with | None -> User_error.raise ~loc [ Pp.text "Variables are not allowed in directory targets." ] | Some target -> let dir_target = Path.Build.relative ~error_loc:loc dir target in if Path.Build.is_descendant dir_target ~of_:dir then (* We ignore duplicates here as duplicates are detected and reported by [Load_rules]. *) Path.Build.Map.set acc dir_target rule_loc else (* This will be checked when we interpret the stanza completely, so just ignore this rule for now. *) acc)) | _ -> acc) let get0_impl (sctx, dir) : result0 Memo.t = let ctx = Super_context.context sctx in let lib_config = (Super_context.context sctx).lib_config in let* status = Dir_status.DB.get ~dir in let human_readable_description () = Pp.textf "Computing directory contents of %s" (Path.to_string_maybe_quoted (Path.build dir)) in match status with | Is_component_of_a_group_but_not_the_root { group_root; stanzas = _ } -> Memo.return (See_above group_root) | Generated | Source_only _ -> Memo.return (Here { directory_targets = Path.Build.Map.empty ; contents = Memo.lazy_ (fun () -> Memo.return { t = empty Standalone ~dir ; rules = Rules.empty ; subdirs = Path.Build.Map.empty }) }) | Standalone (st_dir, d) -> let src_dir = d.dir in let dune_version = Dune_project.dune_version d.project in Memo.return (Here { directory_targets = extract_directory_targets ~dir d.stanzas ; contents = Memo.lazy_ ~human_readable_description (fun () -> let include_subdirs = (Loc.none, Include_subdirs.No) in let+ files, rules = Rules.collect (fun () -> load_text_files sctx st_dir d.stanzas ~src_dir ~dir) in let dirs = [ (dir, [], files) ] in let ml = Memo.lazy_ (fun () -> let lookup_vlib = lookup_vlib sctx ~current_dir:dir in let loc = loc_of_dune_file st_dir in let* scope = Scope.DB.find_by_dir dir in Ml_sources.make d ~dir ~scope ~lib_config ~loc ~include_subdirs ~lookup_vlib ~dirs) in { t = { kind = Standalone ; dir ; text_files = files ; ml ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; foreign_sources = Memo.lazy_ (fun () -> Foreign_sources.make d.stanzas ~dune_version ~lib_config:ctx.lib_config ~dirs |> Memo.return) ; coq = Memo.lazy_ (fun () -> Coq_sources.of_dir d.stanzas ~dir ~include_subdirs ~dirs |> Memo.return) } ; rules ; subdirs = Path.Build.Map.empty }) }) | Group_root (st_dir, qualif_mode, d) -> let loc = loc_of_dune_file st_dir in let include_subdirs = let loc, qualif_mode = qualif_mode in (loc, Include_subdirs.Include qualif_mode) in let* subdirs = collect_group ~st_dir ~dir in let directory_targets = let dirs = (dir, [], st_dir, Some d) :: subdirs in List.fold_left dirs ~init:Path.Build.Map.empty ~f:(fun acc (dir, _, _, d) -> match d with | None -> acc | Some (d : Dune_file.t) -> Path.Build.Map.union acc (extract_directory_targets ~dir d.stanzas) ~f:(fun _ _ x -> Some x)) in let contents = Memo.lazy_ ~human_readable_description (fun () -> let+ (files, (subdirs : (Path.Build.t * _ * _) list)), rules = Rules.collect (fun () -> Memo.fork_and_join (fun () -> load_text_files sctx st_dir d.stanzas ~src_dir:d.dir ~dir) (fun () -> Memo.parallel_map subdirs ~f:(fun (dir, local, st_dir, stanzas) -> let+ files = match stanzas with | None -> Memo.return (Source_tree.Dir.files st_dir) | Some d -> load_text_files sctx st_dir d.stanzas ~src_dir:d.dir ~dir in (dir, local, files)))) in let dirs = (dir, [], files) :: subdirs in let ml = Memo.lazy_ (fun () -> let lookup_vlib = lookup_vlib sctx ~current_dir:dir in let* scope = Scope.DB.find_by_dir dir in Ml_sources.make d ~dir ~scope ~lib_config ~loc ~lookup_vlib ~include_subdirs ~dirs) in let dune_version = Dune_project.dune_version d.project in let foreign_sources = Memo.lazy_ (fun () -> Foreign_sources.make d.stanzas ~dune_version ~lib_config:ctx.lib_config ~dirs |> Memo.return) in let coq = Memo.lazy_ (fun () -> Coq_sources.of_dir d.stanzas ~dir ~dirs ~include_subdirs |> Memo.return) in let subdirs = List.map subdirs ~f:(fun (dir, _local, files) -> { kind = Group_part ; dir ; text_files = files ; ml ; foreign_sources ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; coq }) in let t = { kind = Group_root subdirs ; dir ; text_files = files ; ml ; foreign_sources ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; coq } in { t ; rules ; subdirs = Path.Build.Map.of_list_map_exn subdirs ~f:(fun x -> (x.dir, x)) }) in Memo.return (Here { directory_targets; contents }) let memo0 = Memo.create "dir-contents-get0" get0_impl ~input:(module Key) ~human_readable_description:(fun (_, dir) -> Pp.textf "Computing directory contents of %s" (Path.to_string_maybe_quoted (Path.build dir))) let get sctx ~dir = Memo.exec memo0 (sctx, dir) >>= function | Here { directory_targets = _; contents } -> let+ { t; rules = _; subdirs = _ } = Memo.Lazy.force contents in t | See_above group_root -> ( Memo.exec memo0 (sctx, group_root) >>= function | See_above _ -> assert false | Here { directory_targets = _; contents } -> let+ { t; rules = _; subdirs = _ } = Memo.Lazy.force contents in t) let triage sctx ~dir = Memo.exec memo0 (sctx, dir) >>| function | See_above group_root -> Group_part group_root | Here { directory_targets; contents } -> Standalone_or_root { directory_targets ; contents = Memo.Lazy.map contents ~f:(fun { t; rules; subdirs } -> { root = t; subdirs = Path.Build.Map.values subdirs; rules }) } end include Load let modules_of_lib sctx lib = let info = Lib.info lib in match Lib_info.modules info with | External modules -> Memo.return modules | Local -> let dir = Lib_info.src_dir info |> Path.as_in_build_dir_exn in let* t = get sctx ~dir in let+ ml_sources = ocaml t in let name = Lib.name lib in Some (Ml_sources.modules ml_sources ~for_:(Library name))
null
https://raw.githubusercontent.com/ocaml/dune/d429530c59f13ffdee023bc78ee607ac9850ce96/src/dune_rules/dir_contents.ml
ocaml
As a side-effect, setup user rules and copy_files rules. Manually add files generated by the (select ...) dependencies Interpret a few stanzas in order to determine the list of files generated by the user. CR-someday amokhov: Do not ignore directory targets. Also manually add files generated by ctypes rules. [rules] includes rules for subdirectories too We ignore duplicates here as duplicates are detected and reported by [Load_rules]. This will be checked when we interpret the stanza completely, so just ignore this rule for now.
open Import we need to convince ocamldep that we do n't depend on the menhir rules module Menhir = struct end open Dune_file open Memo.O let loc_of_dune_file st_dir = Loc.in_file (Path.source (match let open Option.O in let* dune_file = Source_tree.Dir.dune_file st_dir in TODO not really correct . we need to know the [ ( subdir .. ) ] that introduced this Source_tree.Dune_file.path dune_file with | Some s -> s | None -> Path.Source.relative (Source_tree.Dir.path st_dir) "_unknown_")) type t = { kind : kind ; dir : Path.Build.t ; text_files : String.Set.t ; foreign_sources : Foreign_sources.t Memo.Lazy.t ; mlds : (Documentation.t * Path.Build.t list) list Memo.Lazy.t ; coq : Coq_sources.t Memo.Lazy.t ; ml : Ml_sources.t Memo.Lazy.t } and kind = | Standalone | Group_root of t list | Group_part let empty kind ~dir = { kind ; dir ; text_files = String.Set.empty ; ml = Memo.Lazy.of_val Ml_sources.empty ; mlds = Memo.Lazy.of_val [] ; foreign_sources = Memo.Lazy.of_val Foreign_sources.empty ; coq = Memo.Lazy.of_val Coq_sources.empty } type standalone_or_root = { root : t ; subdirs : t list ; rules : Rules.t } type triage = | Standalone_or_root of { directory_targets : Loc.t Path.Build.Map.t ; contents : standalone_or_root Memo.Lazy.t } | Group_part of Path.Build.t let dir t = t.dir let coq t = Memo.Lazy.force t.coq let ocaml t = Memo.Lazy.force t.ml let artifacts t = Memo.Lazy.force t.ml >>= Ml_sources.artifacts let dirs t = match t.kind with | Standalone -> [ t ] | Group_root subs -> t :: subs | Group_part -> Code_error.raise "Dir_contents.dirs called on a group part" [ ("dir", Path.Build.to_dyn t.dir) ] let text_files t = t.text_files let foreign_sources t = Memo.Lazy.force t.foreign_sources let mlds t (doc : Documentation.t) = let+ map = Memo.Lazy.force t.mlds in match List.find_map map ~f:(fun (doc', x) -> Option.some_if (Loc.equal doc.loc doc'.loc) x) with | Some x -> x | None -> Code_error.raise "Dir_contents.mlds" [ ("doc", Loc.to_dyn_hum doc.loc) ; ( "available" , Dyn.(list Loc.to_dyn_hum) (List.map map ~f:(fun ((d : Documentation.t), _) -> d.loc)) ) ] let build_mlds_map stanzas ~dir ~files = let mlds = Memo.lazy_ (fun () -> String.Set.fold files ~init:String.Map.empty ~f:(fun fn acc -> match String.lsplit2 fn ~on:'.' with | Some (s, "mld") -> String.Map.set acc s fn | _ -> acc) |> Memo.return) in Memo.parallel_map stanzas ~f:(function | Documentation doc -> let+ mlds = let+ mlds = Memo.Lazy.force mlds in Ordered_set_lang.Unordered_string.eval doc.mld_files ~standard:mlds ~key:Fun.id ~parse:(fun ~loc s -> match String.Map.find mlds s with | Some s -> s | None -> User_error.raise ~loc [ Pp.textf "%s.mld doesn't exist in %s" s (Path.to_string_maybe_quoted (Path.drop_optional_build_context (Path.build dir))) ]) in Some (doc, List.map (String.Map.values mlds) ~f:(Path.Build.relative dir)) | _ -> Memo.return None) >>| List.filter_opt module rec Load : sig val get : Super_context.t -> dir:Path.Build.t -> t Memo.t val triage : Super_context.t -> dir:Path.Build.t -> triage Memo.t val add_sources_to_expander : Super_context.t -> Expander.t -> Expander.t end = struct let add_sources_to_expander sctx expander = let f ~dir = Load.get sctx ~dir >>= artifacts in Expander.set_lookup_ml_sources expander ~f let load_text_files sctx st_dir stanzas ~dir ~src_dir = let select_deps_files libraries = List.filter_map libraries ~f:(fun dep -> match (dep : Lib_dep.t) with | Re_export _ | Direct _ -> None | Select s -> Some s.result_fn) in let* expander = Super_context.expander sctx ~dir >>| add_sources_to_expander sctx in let+ generated_files = Memo.parallel_map stanzas ~f:(fun stanza -> match (stanza : Stanza.t) with | Coq_stanza.Coqpp.T { modules; _ } -> let+ mlg_files = Coq_sources.mlg_files ~sctx ~dir ~modules in List.rev_map mlg_files ~f:(fun mlg_file -> Path.Build.set_extension mlg_file ~ext:".ml" |> Path.Build.basename) | Coq_stanza.Extraction.T s -> Memo.return (Coq_stanza.Extraction.ml_target_fnames s) | Menhir_stanza.T menhir -> Memo.return (Menhir_stanza.targets menhir) | Rule rule -> ( Simple_rules.user_rule sctx rule ~dir ~expander >>| function | None -> [] | Some targets -> Path.Build.Set.to_list_map targets.files ~f:Path.Build.basename) | Copy_files def -> let+ ps = Simple_rules.copy_files sctx def ~src_dir ~dir ~expander in Path.Set.to_list_map ps ~f:Path.basename | Generate_sites_module_stanza.T def -> let+ res = Generate_sites_module_rules.setup_rules sctx ~dir def in [ res ] | Library { buildable; _ } | Executables { buildable; _ } -> let select_deps_files = select_deps_files buildable.libraries in let ctypes_files = match buildable.ctypes with | None -> [] | Some ctypes -> Ctypes_field.generated_ml_and_c_files ctypes in Memo.return (select_deps_files @ ctypes_files) | Melange_stanzas.Emit.T { libraries; _ } -> let select_deps_files = select_deps_files libraries in Memo.return select_deps_files | _ -> Memo.return []) >>| fun l -> String.Set.of_list (List.concat l) in String.Set.union generated_files (Source_tree.Dir.files st_dir) type result0_here = { t : t rules : Rules.t The [ kind ] of the nodes must be Group_part subdirs : t Path.Build.Map.t } type result0 = | See_above of Path.Build.t | Here of { directory_targets : Loc.t Path.Build.Map.t ; contents : result0_here Memo.Lazy.t } module Key = struct module Super_context = Super_context.As_memo_key type t = Super_context.t * Path.Build.t let to_dyn (sctx, path) = Dyn.Tuple [ Super_context.to_dyn sctx; Path.Build.to_dyn path ] let equal = Tuple.T2.equal Super_context.equal Path.Build.equal let hash = Tuple.T2.hash Super_context.hash Path.Build.hash end let lookup_vlib sctx ~current_dir ~loc ~dir = match Path.Build.equal current_dir dir with | true -> User_error.raise ~loc [ Pp.text "Virtual library and its implementation(s) cannot be defined in \ the same directory" ] | false -> Load.get sctx ~dir >>= ocaml let collect_group ~st_dir ~dir = let rec walk st_dir ~dir ~local = let* status = Dir_status.DB.get ~dir in match status with | Is_component_of_a_group_but_not_the_root { stanzas; group_root = _ } -> let+ l = walk_children st_dir ~dir ~local in Appendable_list.( @ ) (Appendable_list.singleton (dir, List.rev local, st_dir, stanzas)) l | Generated | Source_only _ | Standalone _ | Group_root _ -> Memo.return Appendable_list.empty and walk_children st_dir ~dir ~local = let+ l = Source_tree.Dir.sub_dirs st_dir |> String.Map.to_list |> Memo.parallel_map ~f:(fun (basename, st_dir) -> let* st_dir = Source_tree.Dir.sub_dir_as_t st_dir in let dir = Path.Build.relative dir basename in let local = basename :: local in walk st_dir ~dir ~local) in Appendable_list.concat l in let+ l = walk_children st_dir ~dir ~local:[] in Appendable_list.to_list l let extract_directory_targets ~dir stanzas = List.fold_left stanzas ~init:Path.Build.Map.empty ~f:(fun acc stanza -> match stanza with | Rule { targets = Static { targets = l; _ }; loc = rule_loc; _ } -> List.fold_left l ~init:acc ~f:(fun acc (target, kind) -> let loc = String_with_vars.loc target in match (kind : Targets_spec.Kind.t) with | File -> acc | Directory -> ( match String_with_vars.text_only target with | None -> User_error.raise ~loc [ Pp.text "Variables are not allowed in directory targets." ] | Some target -> let dir_target = Path.Build.relative ~error_loc:loc dir target in if Path.Build.is_descendant dir_target ~of_:dir then Path.Build.Map.set acc dir_target rule_loc else acc)) | _ -> acc) let get0_impl (sctx, dir) : result0 Memo.t = let ctx = Super_context.context sctx in let lib_config = (Super_context.context sctx).lib_config in let* status = Dir_status.DB.get ~dir in let human_readable_description () = Pp.textf "Computing directory contents of %s" (Path.to_string_maybe_quoted (Path.build dir)) in match status with | Is_component_of_a_group_but_not_the_root { group_root; stanzas = _ } -> Memo.return (See_above group_root) | Generated | Source_only _ -> Memo.return (Here { directory_targets = Path.Build.Map.empty ; contents = Memo.lazy_ (fun () -> Memo.return { t = empty Standalone ~dir ; rules = Rules.empty ; subdirs = Path.Build.Map.empty }) }) | Standalone (st_dir, d) -> let src_dir = d.dir in let dune_version = Dune_project.dune_version d.project in Memo.return (Here { directory_targets = extract_directory_targets ~dir d.stanzas ; contents = Memo.lazy_ ~human_readable_description (fun () -> let include_subdirs = (Loc.none, Include_subdirs.No) in let+ files, rules = Rules.collect (fun () -> load_text_files sctx st_dir d.stanzas ~src_dir ~dir) in let dirs = [ (dir, [], files) ] in let ml = Memo.lazy_ (fun () -> let lookup_vlib = lookup_vlib sctx ~current_dir:dir in let loc = loc_of_dune_file st_dir in let* scope = Scope.DB.find_by_dir dir in Ml_sources.make d ~dir ~scope ~lib_config ~loc ~include_subdirs ~lookup_vlib ~dirs) in { t = { kind = Standalone ; dir ; text_files = files ; ml ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; foreign_sources = Memo.lazy_ (fun () -> Foreign_sources.make d.stanzas ~dune_version ~lib_config:ctx.lib_config ~dirs |> Memo.return) ; coq = Memo.lazy_ (fun () -> Coq_sources.of_dir d.stanzas ~dir ~include_subdirs ~dirs |> Memo.return) } ; rules ; subdirs = Path.Build.Map.empty }) }) | Group_root (st_dir, qualif_mode, d) -> let loc = loc_of_dune_file st_dir in let include_subdirs = let loc, qualif_mode = qualif_mode in (loc, Include_subdirs.Include qualif_mode) in let* subdirs = collect_group ~st_dir ~dir in let directory_targets = let dirs = (dir, [], st_dir, Some d) :: subdirs in List.fold_left dirs ~init:Path.Build.Map.empty ~f:(fun acc (dir, _, _, d) -> match d with | None -> acc | Some (d : Dune_file.t) -> Path.Build.Map.union acc (extract_directory_targets ~dir d.stanzas) ~f:(fun _ _ x -> Some x)) in let contents = Memo.lazy_ ~human_readable_description (fun () -> let+ (files, (subdirs : (Path.Build.t * _ * _) list)), rules = Rules.collect (fun () -> Memo.fork_and_join (fun () -> load_text_files sctx st_dir d.stanzas ~src_dir:d.dir ~dir) (fun () -> Memo.parallel_map subdirs ~f:(fun (dir, local, st_dir, stanzas) -> let+ files = match stanzas with | None -> Memo.return (Source_tree.Dir.files st_dir) | Some d -> load_text_files sctx st_dir d.stanzas ~src_dir:d.dir ~dir in (dir, local, files)))) in let dirs = (dir, [], files) :: subdirs in let ml = Memo.lazy_ (fun () -> let lookup_vlib = lookup_vlib sctx ~current_dir:dir in let* scope = Scope.DB.find_by_dir dir in Ml_sources.make d ~dir ~scope ~lib_config ~loc ~lookup_vlib ~include_subdirs ~dirs) in let dune_version = Dune_project.dune_version d.project in let foreign_sources = Memo.lazy_ (fun () -> Foreign_sources.make d.stanzas ~dune_version ~lib_config:ctx.lib_config ~dirs |> Memo.return) in let coq = Memo.lazy_ (fun () -> Coq_sources.of_dir d.stanzas ~dir ~dirs ~include_subdirs |> Memo.return) in let subdirs = List.map subdirs ~f:(fun (dir, _local, files) -> { kind = Group_part ; dir ; text_files = files ; ml ; foreign_sources ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; coq }) in let t = { kind = Group_root subdirs ; dir ; text_files = files ; ml ; foreign_sources ; mlds = Memo.lazy_ (fun () -> build_mlds_map d.stanzas ~dir ~files) ; coq } in { t ; rules ; subdirs = Path.Build.Map.of_list_map_exn subdirs ~f:(fun x -> (x.dir, x)) }) in Memo.return (Here { directory_targets; contents }) let memo0 = Memo.create "dir-contents-get0" get0_impl ~input:(module Key) ~human_readable_description:(fun (_, dir) -> Pp.textf "Computing directory contents of %s" (Path.to_string_maybe_quoted (Path.build dir))) let get sctx ~dir = Memo.exec memo0 (sctx, dir) >>= function | Here { directory_targets = _; contents } -> let+ { t; rules = _; subdirs = _ } = Memo.Lazy.force contents in t | See_above group_root -> ( Memo.exec memo0 (sctx, group_root) >>= function | See_above _ -> assert false | Here { directory_targets = _; contents } -> let+ { t; rules = _; subdirs = _ } = Memo.Lazy.force contents in t) let triage sctx ~dir = Memo.exec memo0 (sctx, dir) >>| function | See_above group_root -> Group_part group_root | Here { directory_targets; contents } -> Standalone_or_root { directory_targets ; contents = Memo.Lazy.map contents ~f:(fun { t; rules; subdirs } -> { root = t; subdirs = Path.Build.Map.values subdirs; rules }) } end include Load let modules_of_lib sctx lib = let info = Lib.info lib in match Lib_info.modules info with | External modules -> Memo.return modules | Local -> let dir = Lib_info.src_dir info |> Path.as_in_build_dir_exn in let* t = get sctx ~dir in let+ ml_sources = ocaml t in let name = Lib.name lib in Some (Ml_sources.modules ml_sources ~for_:(Library name))
342919e6c86135c9877fe9dabe5d6ab228dc0312cc84d2fcae5046136dc64e81
Kalimehtar/gir
glib.rkt
#lang racket/base (provide with-g-error raise-g-error) (require "loadlib.rkt" ffi/unsafe) GError (define-struct (exn:fail:g-error exn:fail) ()) (define-syntax-rule (with-g-error (g-error) body ...) (let ([g-error (malloc _pointer)]) body ...)) (define-cstruct _g-error ([domain _uint32] [code _int] [message _string])) (define-gobject* g-quark-to-string (_fun _uint32 -> _string)) (define (make-message g-error) ; g-error = GError** (let ([s (ptr-ref g-error _g-error-pointer)]) (format "GError: ~a: ~a (code ~a)" (g-quark-to-string (g-error-domain s)) (g-error-message s) (g-error-code s)))) (define (raise-g-error g-error) (raise (make-exn:fail:g-error (make-message g-error) (current-continuation-marks))))
null
https://raw.githubusercontent.com/Kalimehtar/gir/a9854262a438070334cfd8ff98cb86dd3803d7e3/gir/glib.rkt
racket
g-error = GError**
#lang racket/base (provide with-g-error raise-g-error) (require "loadlib.rkt" ffi/unsafe) GError (define-struct (exn:fail:g-error exn:fail) ()) (define-syntax-rule (with-g-error (g-error) body ...) (let ([g-error (malloc _pointer)]) body ...)) (define-cstruct _g-error ([domain _uint32] [code _int] [message _string])) (define-gobject* g-quark-to-string (_fun _uint32 -> _string)) (define (make-message g-error) (let ([s (ptr-ref g-error _g-error-pointer)]) (format "GError: ~a: ~a (code ~a)" (g-quark-to-string (g-error-domain s)) (g-error-message s) (g-error-code s)))) (define (raise-g-error g-error) (raise (make-exn:fail:g-error (make-message g-error) (current-continuation-marks))))
b8f320d1a57ea7dca4940618a4d3283bf1f152b0a9319dbb7245536a9cafce87
damballa/parkour
word_count_test.clj
(ns parkour.word-count-test (:require [clojure.test :refer :all] [clojure.string :as str] [clojure.java.io :as io] [clojure.core.reducers :as r] [abracad.avro :as avro] [parkour.mapreduce :as mr] [parkour.fs :as fs] [parkour.io.avro :as mra] [parkour.reducers :as pr] [parkour.conf :as conf] [parkour.util :refer [returning]] [parkour.test-helpers :as th]) (:import [org.apache.hadoop.mapreduce.lib.input TextInputFormat FileInputFormat] [org.apache.hadoop.mapreduce.lib.output FileOutputFormat])) (use-fixtures :once th/config-fixture) (defn wc-mapper {::mr/source-as :vals, ::sink-as :keyvals} [input] (->> (r/mapcat #(str/split % #"\s") input) (r/map #(-> [% 1])))) (defn wc-reducer {::mr/source-as :keyvalgroups, ::mr/sink-as :keyvals} [input] (r/map (pr/mjuxt identity (partial r/reduce +)) input)) (defn run-word-count [inpath outpath] (let [job (mr/job)] (doto job (.setMapperClass (mr/mapper! job #'wc-mapper)) (.setCombinerClass (mr/reducer! job #'wc-reducer)) (.setReducerClass (mr/reducer! job #'wc-reducer)) (.setInputFormatClass TextInputFormat) (mra/set-map-output :string :long) (mra/set-output :string :long) (FileInputFormat/addInputPath (fs/path inpath)) (FileOutputFormat/setOutputPath (fs/path outpath)) (conf/assoc! "jobclient.completion.poll.interval" 100)) (.waitForCompletion job true))) (deftest test-word-count (let [inpath (io/resource "word-count-input.txt") outpath (fs/path "tmp/word-count-output") outfs (fs/path-fs outpath) _ (.delete outfs outpath true) success? (run-word-count inpath outpath) outfile (->> (fs/path outpath "part-*") (fs/path-glob outfs) first io/file)] (is (= true success?)) (is (not (nil? outfile))) (is (= {"apple" 3, "banana" 2, "carrot" 1} (with-open [adf (avro/data-file-reader outfile)] (->> adf seq (into {}))))))) (defn wd-mapper [input] (->> (mr/vals input) (r/mapcat #(str/split % #"\s")) (mr/sink-as :keys))) (defn wd-reducer [input] (->> (mr/keygroups input) (mr/sink-as :keys))) (defn run-word-distinct [inpath outpath] (let [job (mr/job)] (doto job (.setMapperClass (mr/mapper! job #'wd-mapper)) (.setCombinerClass (mr/combiner! job #'wd-reducer)) (.setReducerClass (mr/reducer! job #'wd-reducer)) (.setInputFormatClass TextInputFormat) (mra/set-map-output :string) (mra/set-output :string) (FileInputFormat/addInputPath (fs/path inpath)) (FileOutputFormat/setOutputPath (fs/path outpath)) (th/config)) (.waitForCompletion job true))) (deftest test-word-distinct (let [inpath (io/resource "word-count-input.txt") outpath (fs/path "tmp/word-distinct-output") outfs (fs/path-fs outpath) _ (.delete outfs outpath true) success? (run-word-distinct inpath outpath) outfile (->> (fs/path outpath "part-*") (fs/path-glob outfs) first io/file)] (is (= true success?)) (is (not (nil? outfile))) (is (= ["apple" "banana" "carrot"] (with-open [adf (avro/data-file-reader outfile)] (->> adf seq (into [])))))))
null
https://raw.githubusercontent.com/damballa/parkour/2b3c5e1987e18b4c4284dfd4fcdaba267a4d7fbc/test/parkour/word_count_test.clj
clojure
(ns parkour.word-count-test (:require [clojure.test :refer :all] [clojure.string :as str] [clojure.java.io :as io] [clojure.core.reducers :as r] [abracad.avro :as avro] [parkour.mapreduce :as mr] [parkour.fs :as fs] [parkour.io.avro :as mra] [parkour.reducers :as pr] [parkour.conf :as conf] [parkour.util :refer [returning]] [parkour.test-helpers :as th]) (:import [org.apache.hadoop.mapreduce.lib.input TextInputFormat FileInputFormat] [org.apache.hadoop.mapreduce.lib.output FileOutputFormat])) (use-fixtures :once th/config-fixture) (defn wc-mapper {::mr/source-as :vals, ::sink-as :keyvals} [input] (->> (r/mapcat #(str/split % #"\s") input) (r/map #(-> [% 1])))) (defn wc-reducer {::mr/source-as :keyvalgroups, ::mr/sink-as :keyvals} [input] (r/map (pr/mjuxt identity (partial r/reduce +)) input)) (defn run-word-count [inpath outpath] (let [job (mr/job)] (doto job (.setMapperClass (mr/mapper! job #'wc-mapper)) (.setCombinerClass (mr/reducer! job #'wc-reducer)) (.setReducerClass (mr/reducer! job #'wc-reducer)) (.setInputFormatClass TextInputFormat) (mra/set-map-output :string :long) (mra/set-output :string :long) (FileInputFormat/addInputPath (fs/path inpath)) (FileOutputFormat/setOutputPath (fs/path outpath)) (conf/assoc! "jobclient.completion.poll.interval" 100)) (.waitForCompletion job true))) (deftest test-word-count (let [inpath (io/resource "word-count-input.txt") outpath (fs/path "tmp/word-count-output") outfs (fs/path-fs outpath) _ (.delete outfs outpath true) success? (run-word-count inpath outpath) outfile (->> (fs/path outpath "part-*") (fs/path-glob outfs) first io/file)] (is (= true success?)) (is (not (nil? outfile))) (is (= {"apple" 3, "banana" 2, "carrot" 1} (with-open [adf (avro/data-file-reader outfile)] (->> adf seq (into {}))))))) (defn wd-mapper [input] (->> (mr/vals input) (r/mapcat #(str/split % #"\s")) (mr/sink-as :keys))) (defn wd-reducer [input] (->> (mr/keygroups input) (mr/sink-as :keys))) (defn run-word-distinct [inpath outpath] (let [job (mr/job)] (doto job (.setMapperClass (mr/mapper! job #'wd-mapper)) (.setCombinerClass (mr/combiner! job #'wd-reducer)) (.setReducerClass (mr/reducer! job #'wd-reducer)) (.setInputFormatClass TextInputFormat) (mra/set-map-output :string) (mra/set-output :string) (FileInputFormat/addInputPath (fs/path inpath)) (FileOutputFormat/setOutputPath (fs/path outpath)) (th/config)) (.waitForCompletion job true))) (deftest test-word-distinct (let [inpath (io/resource "word-count-input.txt") outpath (fs/path "tmp/word-distinct-output") outfs (fs/path-fs outpath) _ (.delete outfs outpath true) success? (run-word-distinct inpath outpath) outfile (->> (fs/path outpath "part-*") (fs/path-glob outfs) first io/file)] (is (= true success?)) (is (not (nil? outfile))) (is (= ["apple" "banana" "carrot"] (with-open [adf (avro/data-file-reader outfile)] (->> adf seq (into [])))))))
bbb71b53a24aa211d4ba545596b3a29afc62d9c17c286518def296c35a7c269a
dongcarl/guix
guile.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 , 2013 , 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < > Copyright © 2014 < > Copyright © 2014 , 2016 , 2018 < > Copyright © 2014 , 2017 , 2018 < > Copyright © 2015 , 2017 < > Copyright © 2016 Jan Nieuwenhuizen < > Copyright © 2016 , 2017 < > Copyright © 2016 , 2019 , 2020 < > Copyright © 2017 < > Copyright © 2017 < > Copyright © 2017 , 2019 < > Copyright © 2017 < > Copyright © 2017 , 2018 Amirouche < > Copyright © 2018 < > Copyright © 2018 < > Copyright © 2019 < > Copyright © 2020 , 2021 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu packages guile) #:use-module ((guix licenses) #:prefix license:) #:use-module (gnu packages) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages bdw-gc) #:use-module (gnu packages compression) #:use-module (gnu packages dbm) #:use-module (gnu packages flex) #:use-module (gnu packages gawk) #:use-module (gnu packages gettext) #:use-module (gnu packages gperf) #:use-module (gnu packages hurd) #:use-module (gnu packages libffi) #:use-module (gnu packages libunistring) #:use-module (gnu packages linux) #:use-module (gnu packages m4) #:use-module (gnu packages multiprecision) #:use-module (gnu packages pkg-config) #:use-module (gnu packages readline) #:use-module (gnu packages sqlite) #:use-module (gnu packages texinfo) #:use-module (gnu packages version-control) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix git-download) #:use-module (guix build-system gnu) #:use-module (guix build-system guile) #:use-module (guix deprecation) #:use-module (guix utils) #:use-module (ice-9 match) #:use-module ((srfi srfi-1) #:prefix srfi-1:)) ;;; Commentary: ;;; GNU , and modules and extensions . ;;; ;;; Code: (define-public guile-1.8 (package (name "guile") (version "1.8.8") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0l200a0v7h8bh0cwz6v7hc13ds39cgqsmfrks55b1rbj5vniyiy3")) (patches (search-patches "guile-1.8-cpp-4.5.patch")))) (build-system gnu-build-system) (arguments '(#:configure-flags '("--disable-error-on-warning") ;; Insert a phase before `configure' to patch things up. #:phases (modify-phases %standard-phases (add-before 'configure 'patch-stuff (lambda* (#:key outputs #:allow-other-keys) ;; Add a call to `lt_dladdsearchdir' so that ;; `libguile-readline.so' & co. are in the ;; loader's search path. (substitute* "libguile/dynl.c" (("lt_dlinit.*$" match) (format #f " ~a~% lt_dladdsearchdir(\"~a/lib\");~%" match (assoc-ref outputs "out")))) ;; The usual /bin/sh... (substitute* "ice-9/popen.scm" (("/bin/sh") (which "sh"))) #t))))) When cross - compiling , a native version of itself is needed . (native-inputs (if (%current-target-system) `(("self" ,this-package)) '())) (inputs `(("gawk" ,gawk) ("readline" ,readline))) Since ` ' has " Libs : ... -lgmp -lltdl " , these must be ;; propagated. (propagated-inputs `(("gmp" ,gmp) ("libltdl" ,libltdl))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site"))))) (synopsis "Scheme implementation intended especially for extensions") (description "Guile is the GNU Ubiquitous Intelligent Language for Extensions, the official extension language of the GNU system. It is an implementation of the Scheme language which can be easily embedded in other applications to provide a convenient means of extending the functionality of the application without requiring the source code to be rewritten.") (home-page "/") (license license:lgpl2.0+))) (define-public guile-2.0 (package (name "guile") (version "2.0.14") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "10lxc6l5alf3lzbs3ihnbfy6dfcrsyf8667wa57f26vf4mk2ai78")))) (build-system gnu-build-system) When cross - compiling , a native version of itself is needed . (native-inputs `(,@(if (%current-target-system) `(("self" ,this-package)) '()) ("pkgconfig" ,pkg-config))) (inputs `(("libffi" ,libffi) ,@(libiconv-if-needed) ;; We need Bash when cross-compiling because some of the scripts ;; in bin/ refer to it. Use 'bash-minimal' because we don't need an interactive Bash with and all . ,@(if (target-mingw?) '() `(("bash" ,bash-minimal))))) (propagated-inputs `( ;; These ones aren't normally needed here, but since `libguile-2.0.la' ;; reads `-lltdl -lunistring', adding them here will add the needed ;; `-L' flags. As for why the `.la' file lacks the `-L' flags, see ;; <>. ("libunistring" ,libunistring) ;; Depend on LIBLTDL, not LIBTOOL. That way, we avoid some the extra dependencies that LIBTOOL has , which is helpful during bootstrap . ("libltdl" ,libltdl) The headers and/or ` ' refer to these packages , so they ;; must be propagated. ("bdw-gc" ,libgc) ("gmp" ,gmp))) (outputs '("out" "debug")) (arguments saves 3 MiB #:phases (modify-phases %standard-phases ,@(if (hurd-system?) '((add-after 'unpack 'disable-tests (lambda _ ;; Hangs at: "Running 00-repl-server.test" (rename-file "test-suite/tests/00-repl-server.test" "00-repl-server.test") Sometimes at : " Running 00-socket.test " (rename-file "test-suite/tests/00-socket.test" "00-socket.test") FAIL : srfi-18.test : thread - sleep ! : thread sleeps fractions of a second (rename-file "test-suite/tests/srfi-18.test" "srfi-18.test") ;; failed to remove 't-guild-compile-7215.go.tdL7yC (substitute* "test-suite/standalone/Makefile.in" (("test-guild-compile ") "")) #t))) '()) (add-before 'configure 'pre-configure (lambda* (#:key inputs #:allow-other-keys) Tell ( ice-9 popen ) the file name of Bash . (let ((bash (assoc-ref inputs "bash"))) (substitute* "module/ice-9/popen.scm" ;; If bash is #f allow fallback for user to provide ;; "bash" in PATH. This happens when cross-building to ;; MinGW for which we do not have Bash yet. (("/bin/sh") ,@(if (target-mingw?) '((if bash (string-append bash "/bin/bash") "bash")) '((string-append bash "/bin/bash"))))) #t)))))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/2.0"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/2.0/site-ccache"))))) (synopsis "Scheme implementation intended especially for extensions") (description "Guile is the GNU Ubiquitous Intelligent Language for Extensions, the official extension language of the GNU system. It is an implementation of the Scheme language which can be easily embedded in other applications to provide a convenient means of extending the functionality of the application without requiring the source code to be rewritten.") (home-page "/") (license license:lgpl3+))) (define-public guile-2.2 (package (inherit guile-2.0) (name "guile") (version "2.2.7") (source (origin (method url-fetch) Note : we are limited to one of the compression formats ;; supported by the bootstrap binaries, so no lzip here. (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "013mydzhfswqci6xmyc1ajzd59pfbdak15i0b090nhr9bzm7dxyd")) (modules '((guix build utils))) (patches (search-patches "guile-2.2-skip-oom-test.patch")) ;; Remove the pre-built object files. Instead, build everything ;; from source, at the expense of significantly longer build times ( almost 3 hours on a 4 - core Intel i5 ) . (snippet '(begin (for-each delete-file (find-files "prebuilt" "\\.go$")) #t)))) 20 hours 10 hours ( needed on ARM ; when heavily loaded) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/2.2"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/2.2/site-ccache"))))))) (define-deprecated guile-2.2/bug-fix guile-2.2) (define-public guile-2.2.4 (package (inherit guile-2.2) (version "2.2.4") (source (origin (inherit (package-source guile-2.2)) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "07p3g0v2ba2vlfbfidqzlgbhnzdx46wh2rgc5gszq1mjyx5bks6r")))))) (define-public guile-3.0 This is the latest stable version . (package (inherit guile-2.2) (name "guile") (version "3.0.2") (source (origin (inherit (package-source guile-2.2)) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "12lziar4j27j9whqp2n18427q45y9ghq7gdd8lqhmj1k0lr7vi2k")))) (arguments XXX : JIT - enabled crashes in obscure ways on GNU / . (if (hurd-target?) (substitute-keyword-arguments (package-arguments guile-2.2) ((#:configure-flags flags ''()) `(cons "--disable-jit" ,flags))) (package-arguments guile-2.2))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/3.0"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/3.0/site-ccache" "share/guile/site/3.0"))))))) (define-public guile-3.0-latest ;; TODO: Make this 'guile-3.0' on the next rebuild cycle. (package (inherit guile-3.0) (version "3.0.7") (source (origin (inherit (package-source guile-3.0)) ;preserve snippet (patches '()) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "1dwiwsrpm4f96alfnz6wibq378242z4f16vsxgy1n9r00v3qczgm")))) Build with the bundled mini - GMP to avoid interference with GnuTLS ' own use of GMP via Nettle : < > . Use LIBGC / DISABLE - MUNMAP to work around < > . ;; Remove libltdl, which is no longer used. (propagated-inputs `(("bdw-gc" ,libgc/disable-munmap) ,@(srfi-1:fold srfi-1:alist-delete (package-propagated-inputs guile-3.0) '("gmp" "libltdl" "bdw-gc")))) (arguments (substitute-keyword-arguments (package-arguments guile-3.0) ((#:configure-flags flags ''()) `(cons "--enable-mini-gmp" ,flags)))))) (define-public guile-3.0/libgc-7 ;; Using libgc-7 avoid crashes that can occur, particularly when loading data in to the Guix Data Service : ;; (hidden-package (package (inherit guile-3.0-latest) (propagated-inputs `(("bdw-gc" ,libgc-7) ,@(srfi-1:alist-delete "bdw-gc" (package-propagated-inputs guile-3.0))))))) (define-public guile-3.0/fixed A package of that 's rarely changed . It is the one used in the ;; `base' module, and thus changing it entails a full rebuild. (package (inherit guile-3.0) (properties '((hidden? . #t) ;people should install 'guile-2.2' 20 hours 10 hours ( needed on ARM ; when heavily loaded) (define-public guile-next (let ((version "3.0.5") (revision "0") (commit "91547abf54d5e0795afda2781259ab8923eb527b")) (package (inherit guile-3.0) (name "guile-next") (version (git-version version revision commit)) (source (origin ;; The main goal here is to allow for '--with-branch'. (method git-fetch) (uri (git-reference (url "") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "09i1c77h2shygylfk0av31jsc1my6zjl230b2cx6vyl58q8c0cqy")))) (arguments (substitute-keyword-arguments (package-arguments guile-3.0) ((#:phases phases '%standard-phases) `(modify-phases ,phases (add-before 'check 'skip-failing-tests (lambda _ (substitute* "test-suite/standalone/test-out-of-memory" (("!#") "!#\n\n(exit 77)\n")) (delete-file "test-suite/tests/version.test") #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool) ("flex" ,flex) ("gettext" ,gnu-gettext) ("texinfo" ,texinfo) ("gperf" ,gperf) ,@(package-native-inputs guile-3.0))) (synopsis "Development version of GNU Guile")))) (define* (make-guile-readline guile #:optional (name "guile-readline")) (package (name name) (version (package-version guile)) (source (package-source guile)) (build-system gnu-build-system) (arguments '(#:configure-flags '("--disable-silent-rules") #:phases (modify-phases %standard-phases (add-before 'build 'chdir (lambda* (#:key outputs #:allow-other-keys) (invoke "make" "-C" "libguile" "scmconfig.h") (invoke "make" "-C" "lib") (chdir "guile-readline") (substitute* "Makefile" (("../libguile/libguile-[[:graph:]]+\\.la") ;; Remove dependency on libguile-X.Y.la. "") (("^READLINE_LIBS = (.*)$" _ libs) Link against the provided libguile . (string-append "READLINE_LIBS = " "-lguile-$(GUILE_EFFECTIVE_VERSION) " libs "\n")) (("\\$\\(top_builddir\\)/meta/build-env") Use the provided , not the one from $ ( builddir ) . "") ;; Install modules to the 'site' directories. (("^moddir = .*$") "moddir = $(pkgdatadir)/site/$(GUILE_EFFECTIVE_VERSION)\n") (("^ccachedir = .*$") "ccachedir = $(pkglibdir)/$(GUILE_EFFECTIVE_VERSION)/site-ccache\n")) ;; Load 'guile-readline.so' from the right place. (substitute* "ice-9/readline.scm" (("load-extension \"guile-readline\"") (format #f "load-extension \ (string-append ~s \"/lib/guile/\" (effective-version) \"/extensions/guile-readline\")" (assoc-ref outputs "out")))) #t))))) (home-page (package-home-page guile)) (native-inputs (package-native-inputs guile)) (inputs `(,@(package-inputs guile) ;to placate 'configure' ,@(package-propagated-inputs guile) ("guile" ,guile) ("readline" ,readline))) (synopsis "Line editing support for GNU Guile") (description "This module provides line editing support via the Readline library for GNU@tie{}Guile. Use the @code{(ice-9 readline)} module and call its @code{activate-readline} procedure to enable it.") (license license:gpl3+))) (define-public guile-readline (make-guile-readline guile-3.0)) (define-public guile2.2-readline (make-guile-readline guile-2.2 "guile2.2-readline")) (define (guile-variant-package-name prefix) (lambda (name) "Return NAME with PREFIX instead of \"guile-\", when applicable." (if (string-prefix? "guile-" name) (string-append prefix "-" (string-drop name (string-length "guile-"))) name))) (define package-for-guile-2.0 ;; A procedure that rewrites the dependency tree of the given package to use ;; GUILE-2.0 instead of GUILE-3.0. (package-input-rewriting `((,guile-3.0 . ,guile-2.0)) (guile-variant-package-name "guile2.0") #:deep? #f)) (define package-for-guile-2.2 (package-input-rewriting `((,guile-3.0 . ,guile-2.2)) (guile-variant-package-name "guile2.2") #:deep? #f)) (define-syntax define-deprecated-guile3.0-package (lambda (s) "Define a deprecated package alias for \"guile3.0-something\"." (syntax-case s () ((_ name) (and (identifier? #'name) (string-prefix? "guile3.0-" (symbol->string (syntax->datum #'name)))) (let ((->guile (lambda (str) (let ((base (string-drop str (string-length "guile3.0-")))) (string-append "guile-" base))))) (with-syntax ((package-name (symbol->string (syntax->datum #'name))) (package (datum->syntax #'name (string->symbol (->guile (symbol->string (syntax->datum #'name)))))) (old-name ;; XXX: This is the name generated by ;; 'define-deprecated'. (datum->syntax #'name (symbol-append '% (syntax->datum #'name) '/deprecated)))) #'(begin (define-deprecated name package (deprecated-package package-name package)) (export old-name)))))))) (define-deprecated-guile3.0-package guile3.0-readline) (define-public guile-for-guile-emacs (let ((commit "15ca78482ac0dd2e3eb36dcb31765d8652d7106d") (revision "1")) (package (inherit guile-2.2) (name "guile-for-guile-emacs") (version (git-version "2.1.2" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "git") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "1l7ik4q4zk7vq4m3gnwizc0b64b1mdr31hxqlzxs94xaf2lvi7s2")))) (arguments (substitute-keyword-arguments (package-arguments guile-2.2) ((#:phases phases '%standard-phases) `(modify-phases ,phases (replace 'bootstrap (lambda _ ;; Disable broken tests. ;; TODO: Fix them! (substitute* "test-suite/tests/gc.test" (("\\(pass-if \"after-gc-hook gets called\"" m) (string-append "#;" m))) (substitute* "test-suite/tests/version.test" (("\\(pass-if \"version reporting works\"" m) (string-append "#;" m))) ;; Warning: Unwind-only `out-of-memory' exception; skipping pre-unwind handler. FAIL : test - out - of - memory (substitute* "test-suite/standalone/Makefile.am" (("(check_SCRIPTS|TESTS) \\+= test-out-of-memory") "")) (patch-shebang "build-aux/git-version-gen") (invoke "sh" "autogen.sh") #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool) ("flex" ,flex) ("texinfo" ,texinfo) ("gettext" ,gettext-minimal) ,@(package-native-inputs guile-2.2)))))) ;;; ;;; Extensions. ;;; (define-public guile-json-1 (package (name "guile-json") (version "1.3.2") (home-page "-json") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0m6yzb169r6iz56k3nkncjaiijwi4p0x9ijn1p5ax3s77jklxy9k")))) (build-system gnu-build-system) (arguments `(#:make-flags '("GUILE_AUTO_COMPILE=0"))) ;to prevent guild warnings (native-inputs `(("pkg-config" ,pkg-config) ("guile" ,guile-2.2))) (inputs `(("guile" ,guile-2.2))) (synopsis "JSON module for Guile") (description "Guile-JSON supports parsing and building JSON documents according to the specification. These are the main features: @itemize @item Strictly complies to @uref{, specification}. @item Build JSON documents programmatically via macros. @item Unicode support for strings. @item Allows JSON pretty printing. @end itemize\n") Version 1.2.0 switched to + ( from ) . (license license:gpl3+))) Deprecate the ' guile - json ' alias to force the use ' guile - json-1 ' or ;; 'guile-json-3'. In the future, we may reuse 'guile-json' as an alias for ;; 'guile-json-3'. (define-deprecated guile-json guile-json-1) (export guile-json) (define-public guile2.0-json (package-for-guile-2.0 guile-json-1)) (define-public guile-json-3 ;; This version is incompatible with 1.x; see the 'NEWS' file. (package (inherit guile-json-1) (name "guile-json") (version "3.5.0") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0nj0684qgh6ppkbdyxqfyjwsv2qbyairxpi8fzrhsi3xnc7jn4im")))) (native-inputs `(("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("guile" ,guile-3.0))))) (define-public guile3.0-json (deprecated-package "guile3.0-json" guile-json-3)) (define-public guile-json-4 (package (inherit guile-json-3) (name "guile-json") (version "4.5.2") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0cqr0ljqmzlc2bwrapcsmcgxg147h66mcxf23824ri5i6vn4dc0s")))))) (define-public guile2.2-json (package-for-guile-2.2 guile-json-4)) There are two guile - gdbm packages , one using the FFI and one with ;; direct C bindings, hence the verbose name. (define-public guile-gdbm-ffi (package (name "guile-gdbm-ffi") (version "20120209.fa1d5b6") (source (origin (method git-fetch) (uri (git-reference (url "-gdbm") (commit "fa1d5b6231d0e4d096687b378c025f2148c5f246"))) (file-name (string-append name "-" version "-checkout")) (patches (search-patches "guile-gdbm-ffi-support-gdbm-1.14.patch")) (sha256 (base32 "1j8wrsw7v9w6qkl47xz0rdikg50v16nn6kbs3lgzcymjzpa7babj")))) (build-system guile-build-system) (arguments '(#:phases (modify-phases %standard-phases (add-after 'unpack 'move-examples (lambda* (#:key outputs #:allow-other-keys) ;; Move examples where they belong. (let* ((out (assoc-ref outputs "out")) (doc (string-append out "/share/doc/" (strip-store-file-name out) "/examples"))) (copy-recursively "examples" doc) (delete-file-recursively "examples") #t))) (add-after 'unpack 'set-libgdbm-file-name (lambda* (#:key inputs #:allow-other-keys) (substitute* "gdbm.scm" (("\\(dynamic-link \"libgdbm\"\\)") (format #f "(dynamic-link \"~a/lib/libgdbm.so\")" (assoc-ref inputs "gdbm")))) #t))))) (native-inputs `(("guile" ,guile-3.0))) (inputs `(("gdbm" ,gdbm))) (home-page "-gdbm") (synopsis "Guile bindings to the GDBM library via Guile's FFI") (description "Guile bindings to the GDBM key-value storage system, using Guile's foreign function interface.") (license license:gpl3+))) (define-public guile2.0-gdbm-ffi (package-for-guile-2.0 guile-gdbm-ffi)) (define-public guile2.2-gdbm-ffi (package-for-guile-2.2 guile-gdbm-ffi)) (define-deprecated-guile3.0-package guile3.0-gdbm-ffi) (define-public guile-sqlite3 (package (name "guile-sqlite3") (version "0.1.2") (home-page "-sqlite3/guile-sqlite3.git") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (sha256 (base32 "1nryy9j3bk34i0alkmc9bmqsm0ayz92k1cdf752mvhyjjn8nr928")) (file-name (string-append name "-" version "-checkout")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("guile" ,guile-3.0) ("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-3.0) ("sqlite" ,sqlite))) (synopsis "Access SQLite databases from Guile") (description "This package provides Guile bindings to the SQLite database system.") (license license:gpl3+))) (define-public guile2.0-sqlite3 (package-for-guile-2.0 guile-sqlite3)) (define-public guile2.2-sqlite3 (package-for-guile-2.2 guile-sqlite3)) (define-deprecated-guile3.0-package guile3.0-sqlite3) (define-public guile-bytestructures (package (name "guile-bytestructures") (version "1.0.10") (home-page "-bytestructures") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "14k50jln32kkxv41hvsdgjkkfj6xlv06vc1caz01qkgk1fzh72nk")))) (build-system gnu-build-system) (arguments `(#:make-flags '("GUILE_AUTO_COMPILE=0") ;to prevent guild warnings #:phases (modify-phases %standard-phases (add-after 'install 'install-doc (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (package ,(package-full-name this-package "-")) (doc (string-append out "/share/doc/" package))) (install-file "README.md" doc) #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("guile" ,guile-3.0))) (synopsis "Structured access to bytevector contents for Guile") (description "Guile bytestructures offers a system imitating the type system of the C programming language, to be used on bytevectors. C's type system works on raw memory, and Guile works on bytevectors which are an abstraction over raw memory. It's also more powerful than the C type system, elevating types to first-class status.") (license license:gpl3+) (properties '((upstream-name . "bytestructures"))))) (define-public guile2.0-bytestructures (package-for-guile-2.0 guile-bytestructures)) (define-public guile2.2-bytestructures (package-for-guile-2.2 guile-bytestructures)) (define-deprecated-guile3.0-package guile3.0-bytestructures) (define-public guile-git (package (name "guile-git") (version "0.5.1") (home-page "-git/guile-git.git") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1x3wa6la4j1wcfxyhhjlmd7yp85wwpny0y6lrzpz803i9z5fwagc")))) (build-system gnu-build-system) (arguments `(#:make-flags '("GUILE_AUTO_COMPILE=0"))) ; to prevent guild warnings (native-inputs `(("pkg-config" ,pkg-config) ("autoconf" ,autoconf) ("automake" ,automake) ("texinfo" ,texinfo) ("guile" ,guile-3.0) ("guile-bytestructures" ,guile-bytestructures))) (inputs `(("guile" ,guile-3.0) ("libgit2" ,libgit2))) (propagated-inputs `(("guile-bytestructures" ,guile-bytestructures))) (synopsis "Guile bindings for libgit2") (description "This package provides Guile bindings to libgit2, a library to manipulate repositories of the Git version control system.") (license license:gpl3+))) (define-public guile2.2-git (package-for-guile-2.2 guile-git)) (define-public guile2.0-git (package-for-guile-2.0 guile-git)) (define-deprecated-guile3.0-package guile3.0-git) (define-public guile-zlib (package (name "guile-zlib") (version "0.1.0") (source (origin ;; XXX: Do not use "git-fetch" method here that would create and ;; endless inclusion loop, because this package is used as an extension ;; in the same method. (method url-fetch) (uri (string-append "-zlib/guile-zlib/archive/v" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 content hash : 1ip18nzwnczqyhn9cpzxkm9vzpi5fz5sy96cgjhmp7cwhnkmv6zv (base32 "1safz7rrbdf1d98x3lgx5v74kivpyf9n1v6pdyy22vd0f2sjdir5")))) (build-system gnu-build-system) (arguments '(#:make-flags '("GUILE_AUTO_COMPILE=0"))) ;to prevent guild warnings (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ,@(if (%current-target-system) `(("guile" ,guile-3.0)) ;for 'guild compile' and 'guile-3.0.pc' '()))) (inputs `(("guile" ,guile-3.0) ("zlib" ,zlib))) (synopsis "Guile bindings to zlib") (description "This package provides Guile bindings for zlib, a lossless data-compression library. The bindings are written in pure Scheme by using Guile's foreign function interface.") (home-page "-zlib/guile-zlib") (license license:gpl3+))) (define-public guile2.2-zlib (package-for-guile-2.2 guile-zlib)) (define-public guile-lzlib (package (name "guile-lzlib") (version "0.0.2") (source (origin (method url-fetch) (uri (string-append "-lzlib/guile-lzlib/archive/" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 (base32 "11sggvncyx08ssp1s5xii4d6nskh1qwqihnbpzzvkrs7sivxn8w6")))) (build-system gnu-build-system) (arguments '(#:make-flags '("GUILE_AUTO_COMPILE=0"))) ;to prevent guild warnings (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ,@(if (%current-target-system) `(("guile" ,guile-3.0)) ;for 'guild compile' and 'guile-3.0.pc' '()))) (inputs `(("guile" ,guile-3.0) ("lzlib" ,lzlib))) (synopsis "Guile bindings to lzlib") (description "This package provides Guile bindings for lzlib, a C library for in-memory LZMA compression and decompression. The bindings are written in pure Scheme by using Guile's foreign function interface.") (home-page "-lzlib/guile-lzlib") (license license:gpl3+))) (define-public guile2.2-lzlib (package-for-guile-2.2 guile-lzlib)) (define-public guile-zstd (package (name "guile-zstd") (version "0.1.1") (home-page "-zstd/guile-zstd") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1c8l7829b5yx8wdc0mrhzjfwb6h9hb7cd8dfxcr71a7vlsi86310")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("zstd" ,zstd "lib") ("guile" ,guile-3.0))) (synopsis "GNU Guile bindings to the zstd compression library") (description "This package provides a GNU Guile interface to the zstd (``zstandard'') compression library.") (license license:gpl3+))) ;;; guile.scm ends here
null
https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/guile.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Commentary: Code: Insert a phase before `configure' to patch things up. Add a call to `lt_dladdsearchdir' so that `libguile-readline.so' & co. are in the loader's search path. The usual /bin/sh... propagated. We need Bash when cross-compiling because some of the scripts in bin/ refer to it. Use 'bash-minimal' because we don't need These ones aren't normally needed here, but since `libguile-2.0.la' reads `-lltdl -lunistring', adding them here will add the needed `-L' flags. As for why the `.la' file lacks the `-L' flags, see <>. Depend on LIBLTDL, not LIBTOOL. That way, we avoid some the extra must be propagated. Hangs at: "Running 00-repl-server.test" failed to remove 't-guild-compile-7215.go.tdL7yC If bash is #f allow fallback for user to provide "bash" in PATH. This happens when cross-building to MinGW for which we do not have Bash yet. supported by the bootstrap binaries, so no lzip here. Remove the pre-built object files. Instead, build everything from source, at the expense of significantly longer build when heavily loaded) TODO: Make this 'guile-3.0' on the next rebuild cycle. preserve snippet Remove libltdl, which is no longer used. Using libgc-7 avoid crashes that can occur, particularly when loading `base' module, and thus changing it entails a full rebuild. people should install 'guile-2.2' when heavily loaded) The main goal here is to allow for '--with-branch'. Remove dependency on libguile-X.Y.la. Install modules to the 'site' directories. Load 'guile-readline.so' from the right place. to placate 'configure' A procedure that rewrites the dependency tree of the given package to use GUILE-2.0 instead of GUILE-3.0. XXX: This is the name generated by 'define-deprecated'. Disable broken tests. TODO: Fix them! Warning: Unwind-only `out-of-memory' exception; skipping pre-unwind handler. Extensions. to prevent guild warnings 'guile-json-3'. In the future, we may reuse 'guile-json' as an alias for 'guile-json-3'. This version is incompatible with 1.x; see the 'NEWS' file. direct C bindings, hence the verbose name. Move examples where they belong. to prevent guild warnings to prevent guild warnings XXX: Do not use "git-fetch" method here that would create and endless inclusion loop, because this package is used as an extension in the same method. to prevent guild warnings for 'guild compile' and 'guile-3.0.pc' to prevent guild warnings for 'guild compile' and 'guile-3.0.pc' guile.scm ends here
Copyright © 2012 , 2013 , 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < > Copyright © 2014 < > Copyright © 2014 , 2016 , 2018 < > Copyright © 2014 , 2017 , 2018 < > Copyright © 2015 , 2017 < > Copyright © 2016 Jan Nieuwenhuizen < > Copyright © 2016 , 2017 < > Copyright © 2016 , 2019 , 2020 < > Copyright © 2017 < > Copyright © 2017 < > Copyright © 2017 , 2019 < > Copyright © 2017 < > Copyright © 2017 , 2018 Amirouche < > Copyright © 2018 < > Copyright © 2018 < > Copyright © 2019 < > Copyright © 2020 , 2021 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages guile) #:use-module ((guix licenses) #:prefix license:) #:use-module (gnu packages) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages bdw-gc) #:use-module (gnu packages compression) #:use-module (gnu packages dbm) #:use-module (gnu packages flex) #:use-module (gnu packages gawk) #:use-module (gnu packages gettext) #:use-module (gnu packages gperf) #:use-module (gnu packages hurd) #:use-module (gnu packages libffi) #:use-module (gnu packages libunistring) #:use-module (gnu packages linux) #:use-module (gnu packages m4) #:use-module (gnu packages multiprecision) #:use-module (gnu packages pkg-config) #:use-module (gnu packages readline) #:use-module (gnu packages sqlite) #:use-module (gnu packages texinfo) #:use-module (gnu packages version-control) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix git-download) #:use-module (guix build-system gnu) #:use-module (guix build-system guile) #:use-module (guix deprecation) #:use-module (guix utils) #:use-module (ice-9 match) #:use-module ((srfi srfi-1) #:prefix srfi-1:)) GNU , and modules and extensions . (define-public guile-1.8 (package (name "guile") (version "1.8.8") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.gz")) (sha256 (base32 "0l200a0v7h8bh0cwz6v7hc13ds39cgqsmfrks55b1rbj5vniyiy3")) (patches (search-patches "guile-1.8-cpp-4.5.patch")))) (build-system gnu-build-system) (arguments '(#:configure-flags '("--disable-error-on-warning") #:phases (modify-phases %standard-phases (add-before 'configure 'patch-stuff (lambda* (#:key outputs #:allow-other-keys) (substitute* "libguile/dynl.c" (("lt_dlinit.*$" match) (format #f " ~a~% lt_dladdsearchdir(\"~a/lib\");~%" match (assoc-ref outputs "out")))) (substitute* "ice-9/popen.scm" (("/bin/sh") (which "sh"))) #t))))) When cross - compiling , a native version of itself is needed . (native-inputs (if (%current-target-system) `(("self" ,this-package)) '())) (inputs `(("gawk" ,gawk) ("readline" ,readline))) Since ` ' has " Libs : ... -lgmp -lltdl " , these must be (propagated-inputs `(("gmp" ,gmp) ("libltdl" ,libltdl))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site"))))) (synopsis "Scheme implementation intended especially for extensions") (description "Guile is the GNU Ubiquitous Intelligent Language for Extensions, the official extension language of the GNU system. It is an implementation of the Scheme language which can be easily embedded in other applications to provide a convenient means of extending the functionality of the application without requiring the source code to be rewritten.") (home-page "/") (license license:lgpl2.0+))) (define-public guile-2.0 (package (name "guile") (version "2.0.14") (source (origin (method url-fetch) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "10lxc6l5alf3lzbs3ihnbfy6dfcrsyf8667wa57f26vf4mk2ai78")))) (build-system gnu-build-system) When cross - compiling , a native version of itself is needed . (native-inputs `(,@(if (%current-target-system) `(("self" ,this-package)) '()) ("pkgconfig" ,pkg-config))) (inputs `(("libffi" ,libffi) ,@(libiconv-if-needed) an interactive Bash with and all . ,@(if (target-mingw?) '() `(("bash" ,bash-minimal))))) (propagated-inputs ("libunistring" ,libunistring) dependencies that LIBTOOL has , which is helpful during bootstrap . ("libltdl" ,libltdl) The headers and/or ` ' refer to these packages , so they ("bdw-gc" ,libgc) ("gmp" ,gmp))) (outputs '("out" "debug")) (arguments saves 3 MiB #:phases (modify-phases %standard-phases ,@(if (hurd-system?) '((add-after 'unpack 'disable-tests (lambda _ (rename-file "test-suite/tests/00-repl-server.test" "00-repl-server.test") Sometimes at : " Running 00-socket.test " (rename-file "test-suite/tests/00-socket.test" "00-socket.test") FAIL : srfi-18.test : thread - sleep ! : thread sleeps fractions of a second (rename-file "test-suite/tests/srfi-18.test" "srfi-18.test") (substitute* "test-suite/standalone/Makefile.in" (("test-guild-compile ") "")) #t))) '()) (add-before 'configure 'pre-configure (lambda* (#:key inputs #:allow-other-keys) Tell ( ice-9 popen ) the file name of Bash . (let ((bash (assoc-ref inputs "bash"))) (substitute* "module/ice-9/popen.scm" (("/bin/sh") ,@(if (target-mingw?) '((if bash (string-append bash "/bin/bash") "bash")) '((string-append bash "/bin/bash"))))) #t)))))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/2.0"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/2.0/site-ccache"))))) (synopsis "Scheme implementation intended especially for extensions") (description "Guile is the GNU Ubiquitous Intelligent Language for Extensions, the official extension language of the GNU system. It is an implementation of the Scheme language which can be easily embedded in other applications to provide a convenient means of extending the functionality of the application without requiring the source code to be rewritten.") (home-page "/") (license license:lgpl3+))) (define-public guile-2.2 (package (inherit guile-2.0) (name "guile") (version "2.2.7") (source (origin (method url-fetch) Note : we are limited to one of the compression formats (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "013mydzhfswqci6xmyc1ajzd59pfbdak15i0b090nhr9bzm7dxyd")) (modules '((guix build utils))) (patches (search-patches "guile-2.2-skip-oom-test.patch")) times ( almost 3 hours on a 4 - core Intel i5 ) . (snippet '(begin (for-each delete-file (find-files "prebuilt" "\\.go$")) #t)))) 20 hours 10 hours ( needed on ARM (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/2.2"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/2.2/site-ccache"))))))) (define-deprecated guile-2.2/bug-fix guile-2.2) (define-public guile-2.2.4 (package (inherit guile-2.2) (version "2.2.4") (source (origin (inherit (package-source guile-2.2)) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "07p3g0v2ba2vlfbfidqzlgbhnzdx46wh2rgc5gszq1mjyx5bks6r")))))) (define-public guile-3.0 This is the latest stable version . (package (inherit guile-2.2) (name "guile") (version "3.0.2") (source (origin (inherit (package-source guile-2.2)) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "12lziar4j27j9whqp2n18427q45y9ghq7gdd8lqhmj1k0lr7vi2k")))) (arguments XXX : JIT - enabled crashes in obscure ways on GNU / . (if (hurd-target?) (substitute-keyword-arguments (package-arguments guile-2.2) ((#:configure-flags flags ''()) `(cons "--disable-jit" ,flags))) (package-arguments guile-2.2))) (native-search-paths (list (search-path-specification (variable "GUILE_LOAD_PATH") (files '("share/guile/site/3.0"))) (search-path-specification (variable "GUILE_LOAD_COMPILED_PATH") (files '("lib/guile/3.0/site-ccache" "share/guile/site/3.0"))))))) (define-public guile-3.0-latest (package (inherit guile-3.0) (version "3.0.7") (source (origin (patches '()) (uri (string-append "mirror-" version ".tar.xz")) (sha256 (base32 "1dwiwsrpm4f96alfnz6wibq378242z4f16vsxgy1n9r00v3qczgm")))) Build with the bundled mini - GMP to avoid interference with GnuTLS ' own use of GMP via Nettle : < > . Use LIBGC / DISABLE - MUNMAP to work around < > . (propagated-inputs `(("bdw-gc" ,libgc/disable-munmap) ,@(srfi-1:fold srfi-1:alist-delete (package-propagated-inputs guile-3.0) '("gmp" "libltdl" "bdw-gc")))) (arguments (substitute-keyword-arguments (package-arguments guile-3.0) ((#:configure-flags flags ''()) `(cons "--enable-mini-gmp" ,flags)))))) (define-public guile-3.0/libgc-7 data in to the Guix Data Service : (hidden-package (package (inherit guile-3.0-latest) (propagated-inputs `(("bdw-gc" ,libgc-7) ,@(srfi-1:alist-delete "bdw-gc" (package-propagated-inputs guile-3.0))))))) (define-public guile-3.0/fixed A package of that 's rarely changed . It is the one used in the (package (inherit guile-3.0) 20 hours 10 hours ( needed on ARM (define-public guile-next (let ((version "3.0.5") (revision "0") (commit "91547abf54d5e0795afda2781259ab8923eb527b")) (package (inherit guile-3.0) (name "guile-next") (version (git-version version revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "09i1c77h2shygylfk0av31jsc1my6zjl230b2cx6vyl58q8c0cqy")))) (arguments (substitute-keyword-arguments (package-arguments guile-3.0) ((#:phases phases '%standard-phases) `(modify-phases ,phases (add-before 'check 'skip-failing-tests (lambda _ (substitute* "test-suite/standalone/test-out-of-memory" (("!#") "!#\n\n(exit 77)\n")) (delete-file "test-suite/tests/version.test") #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool) ("flex" ,flex) ("gettext" ,gnu-gettext) ("texinfo" ,texinfo) ("gperf" ,gperf) ,@(package-native-inputs guile-3.0))) (synopsis "Development version of GNU Guile")))) (define* (make-guile-readline guile #:optional (name "guile-readline")) (package (name name) (version (package-version guile)) (source (package-source guile)) (build-system gnu-build-system) (arguments '(#:configure-flags '("--disable-silent-rules") #:phases (modify-phases %standard-phases (add-before 'build 'chdir (lambda* (#:key outputs #:allow-other-keys) (invoke "make" "-C" "libguile" "scmconfig.h") (invoke "make" "-C" "lib") (chdir "guile-readline") (substitute* "Makefile" (("../libguile/libguile-[[:graph:]]+\\.la") "") (("^READLINE_LIBS = (.*)$" _ libs) Link against the provided libguile . (string-append "READLINE_LIBS = " "-lguile-$(GUILE_EFFECTIVE_VERSION) " libs "\n")) (("\\$\\(top_builddir\\)/meta/build-env") Use the provided , not the one from $ ( builddir ) . "") (("^moddir = .*$") "moddir = $(pkgdatadir)/site/$(GUILE_EFFECTIVE_VERSION)\n") (("^ccachedir = .*$") "ccachedir = $(pkglibdir)/$(GUILE_EFFECTIVE_VERSION)/site-ccache\n")) (substitute* "ice-9/readline.scm" (("load-extension \"guile-readline\"") (format #f "load-extension \ (string-append ~s \"/lib/guile/\" (effective-version) \"/extensions/guile-readline\")" (assoc-ref outputs "out")))) #t))))) (home-page (package-home-page guile)) (native-inputs (package-native-inputs guile)) (inputs ,@(package-propagated-inputs guile) ("guile" ,guile) ("readline" ,readline))) (synopsis "Line editing support for GNU Guile") (description "This module provides line editing support via the Readline library for GNU@tie{}Guile. Use the @code{(ice-9 readline)} module and call its @code{activate-readline} procedure to enable it.") (license license:gpl3+))) (define-public guile-readline (make-guile-readline guile-3.0)) (define-public guile2.2-readline (make-guile-readline guile-2.2 "guile2.2-readline")) (define (guile-variant-package-name prefix) (lambda (name) "Return NAME with PREFIX instead of \"guile-\", when applicable." (if (string-prefix? "guile-" name) (string-append prefix "-" (string-drop name (string-length "guile-"))) name))) (define package-for-guile-2.0 (package-input-rewriting `((,guile-3.0 . ,guile-2.0)) (guile-variant-package-name "guile2.0") #:deep? #f)) (define package-for-guile-2.2 (package-input-rewriting `((,guile-3.0 . ,guile-2.2)) (guile-variant-package-name "guile2.2") #:deep? #f)) (define-syntax define-deprecated-guile3.0-package (lambda (s) "Define a deprecated package alias for \"guile3.0-something\"." (syntax-case s () ((_ name) (and (identifier? #'name) (string-prefix? "guile3.0-" (symbol->string (syntax->datum #'name)))) (let ((->guile (lambda (str) (let ((base (string-drop str (string-length "guile3.0-")))) (string-append "guile-" base))))) (with-syntax ((package-name (symbol->string (syntax->datum #'name))) (package (datum->syntax #'name (string->symbol (->guile (symbol->string (syntax->datum #'name)))))) (old-name (datum->syntax #'name (symbol-append '% (syntax->datum #'name) '/deprecated)))) #'(begin (define-deprecated name package (deprecated-package package-name package)) (export old-name)))))))) (define-deprecated-guile3.0-package guile3.0-readline) (define-public guile-for-guile-emacs (let ((commit "15ca78482ac0dd2e3eb36dcb31765d8652d7106d") (revision "1")) (package (inherit guile-2.2) (name "guile-for-guile-emacs") (version (git-version "2.1.2" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "git") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "1l7ik4q4zk7vq4m3gnwizc0b64b1mdr31hxqlzxs94xaf2lvi7s2")))) (arguments (substitute-keyword-arguments (package-arguments guile-2.2) ((#:phases phases '%standard-phases) `(modify-phases ,phases (replace 'bootstrap (lambda _ (substitute* "test-suite/tests/gc.test" (("\\(pass-if \"after-gc-hook gets called\"" m) (string-append "#;" m))) (substitute* "test-suite/tests/version.test" (("\\(pass-if \"version reporting works\"" m) (string-append "#;" m))) FAIL : test - out - of - memory (substitute* "test-suite/standalone/Makefile.am" (("(check_SCRIPTS|TESTS) \\+= test-out-of-memory") "")) (patch-shebang "build-aux/git-version-gen") (invoke "sh" "autogen.sh") #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("libtool" ,libtool) ("flex" ,flex) ("texinfo" ,texinfo) ("gettext" ,gettext-minimal) ,@(package-native-inputs guile-2.2)))))) (define-public guile-json-1 (package (name "guile-json") (version "1.3.2") (home-page "-json") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0m6yzb169r6iz56k3nkncjaiijwi4p0x9ijn1p5ax3s77jklxy9k")))) (build-system gnu-build-system) (arguments (native-inputs `(("pkg-config" ,pkg-config) ("guile" ,guile-2.2))) (inputs `(("guile" ,guile-2.2))) (synopsis "JSON module for Guile") (description "Guile-JSON supports parsing and building JSON documents according to the specification. These are the main features: @itemize @item Strictly complies to @uref{, specification}. @item Build JSON documents programmatically via macros. @item Unicode support for strings. @item Allows JSON pretty printing. @end itemize\n") Version 1.2.0 switched to + ( from ) . (license license:gpl3+))) Deprecate the ' guile - json ' alias to force the use ' guile - json-1 ' or (define-deprecated guile-json guile-json-1) (export guile-json) (define-public guile2.0-json (package-for-guile-2.0 guile-json-1)) (define-public guile-json-3 (package (inherit guile-json-1) (name "guile-json") (version "3.5.0") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0nj0684qgh6ppkbdyxqfyjwsv2qbyairxpi8fzrhsi3xnc7jn4im")))) (native-inputs `(("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("guile" ,guile-3.0))))) (define-public guile3.0-json (deprecated-package "guile3.0-json" guile-json-3)) (define-public guile-json-4 (package (inherit guile-json-3) (name "guile-json") (version "4.5.2") (source (origin (method url-fetch) (uri (string-append "mirror-json/guile-json-" version ".tar.gz")) (sha256 (base32 "0cqr0ljqmzlc2bwrapcsmcgxg147h66mcxf23824ri5i6vn4dc0s")))))) (define-public guile2.2-json (package-for-guile-2.2 guile-json-4)) There are two guile - gdbm packages , one using the FFI and one with (define-public guile-gdbm-ffi (package (name "guile-gdbm-ffi") (version "20120209.fa1d5b6") (source (origin (method git-fetch) (uri (git-reference (url "-gdbm") (commit "fa1d5b6231d0e4d096687b378c025f2148c5f246"))) (file-name (string-append name "-" version "-checkout")) (patches (search-patches "guile-gdbm-ffi-support-gdbm-1.14.patch")) (sha256 (base32 "1j8wrsw7v9w6qkl47xz0rdikg50v16nn6kbs3lgzcymjzpa7babj")))) (build-system guile-build-system) (arguments '(#:phases (modify-phases %standard-phases (add-after 'unpack 'move-examples (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (doc (string-append out "/share/doc/" (strip-store-file-name out) "/examples"))) (copy-recursively "examples" doc) (delete-file-recursively "examples") #t))) (add-after 'unpack 'set-libgdbm-file-name (lambda* (#:key inputs #:allow-other-keys) (substitute* "gdbm.scm" (("\\(dynamic-link \"libgdbm\"\\)") (format #f "(dynamic-link \"~a/lib/libgdbm.so\")" (assoc-ref inputs "gdbm")))) #t))))) (native-inputs `(("guile" ,guile-3.0))) (inputs `(("gdbm" ,gdbm))) (home-page "-gdbm") (synopsis "Guile bindings to the GDBM library via Guile's FFI") (description "Guile bindings to the GDBM key-value storage system, using Guile's foreign function interface.") (license license:gpl3+))) (define-public guile2.0-gdbm-ffi (package-for-guile-2.0 guile-gdbm-ffi)) (define-public guile2.2-gdbm-ffi (package-for-guile-2.2 guile-gdbm-ffi)) (define-deprecated-guile3.0-package guile3.0-gdbm-ffi) (define-public guile-sqlite3 (package (name "guile-sqlite3") (version "0.1.2") (home-page "-sqlite3/guile-sqlite3.git") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (sha256 (base32 "1nryy9j3bk34i0alkmc9bmqsm0ayz92k1cdf752mvhyjjn8nr928")) (file-name (string-append name "-" version "-checkout")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("guile" ,guile-3.0) ("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-3.0) ("sqlite" ,sqlite))) (synopsis "Access SQLite databases from Guile") (description "This package provides Guile bindings to the SQLite database system.") (license license:gpl3+))) (define-public guile2.0-sqlite3 (package-for-guile-2.0 guile-sqlite3)) (define-public guile2.2-sqlite3 (package-for-guile-2.2 guile-sqlite3)) (define-deprecated-guile3.0-package guile3.0-sqlite3) (define-public guile-bytestructures (package (name "guile-bytestructures") (version "1.0.10") (home-page "-bytestructures") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "14k50jln32kkxv41hvsdgjkkfj6xlv06vc1caz01qkgk1fzh72nk")))) (build-system gnu-build-system) (arguments #:phases (modify-phases %standard-phases (add-after 'install 'install-doc (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (package ,(package-full-name this-package "-")) (doc (string-append out "/share/doc/" package))) (install-file "README.md" doc) #t)))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("guile" ,guile-3.0))) (synopsis "Structured access to bytevector contents for Guile") (description "Guile bytestructures offers a system imitating the type system of the C programming language, to be used on bytevectors. C's type system works on raw memory, and Guile works on bytevectors which are an abstraction over raw memory. It's also more powerful than the C type system, elevating types to first-class status.") (license license:gpl3+) (properties '((upstream-name . "bytestructures"))))) (define-public guile2.0-bytestructures (package-for-guile-2.0 guile-bytestructures)) (define-public guile2.2-bytestructures (package-for-guile-2.2 guile-bytestructures)) (define-deprecated-guile3.0-package guile3.0-bytestructures) (define-public guile-git (package (name "guile-git") (version "0.5.1") (home-page "-git/guile-git.git") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1x3wa6la4j1wcfxyhhjlmd7yp85wwpny0y6lrzpz803i9z5fwagc")))) (build-system gnu-build-system) (arguments (native-inputs `(("pkg-config" ,pkg-config) ("autoconf" ,autoconf) ("automake" ,automake) ("texinfo" ,texinfo) ("guile" ,guile-3.0) ("guile-bytestructures" ,guile-bytestructures))) (inputs `(("guile" ,guile-3.0) ("libgit2" ,libgit2))) (propagated-inputs `(("guile-bytestructures" ,guile-bytestructures))) (synopsis "Guile bindings for libgit2") (description "This package provides Guile bindings to libgit2, a library to manipulate repositories of the Git version control system.") (license license:gpl3+))) (define-public guile2.2-git (package-for-guile-2.2 guile-git)) (define-public guile2.0-git (package-for-guile-2.0 guile-git)) (define-deprecated-guile3.0-package guile3.0-git) (define-public guile-zlib (package (name "guile-zlib") (version "0.1.0") (source (origin (method url-fetch) (uri (string-append "-zlib/guile-zlib/archive/v" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 content hash : 1ip18nzwnczqyhn9cpzxkm9vzpi5fz5sy96cgjhmp7cwhnkmv6zv (base32 "1safz7rrbdf1d98x3lgx5v74kivpyf9n1v6pdyy22vd0f2sjdir5")))) (build-system gnu-build-system) (arguments '(#:make-flags (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ,@(if (%current-target-system) '()))) (inputs `(("guile" ,guile-3.0) ("zlib" ,zlib))) (synopsis "Guile bindings to zlib") (description "This package provides Guile bindings for zlib, a lossless data-compression library. The bindings are written in pure Scheme by using Guile's foreign function interface.") (home-page "-zlib/guile-zlib") (license license:gpl3+))) (define-public guile2.2-zlib (package-for-guile-2.2 guile-zlib)) (define-public guile-lzlib (package (name "guile-lzlib") (version "0.0.2") (source (origin (method url-fetch) (uri (string-append "-lzlib/guile-lzlib/archive/" version ".tar.gz")) (file-name (string-append name "-" version ".tar.gz")) (sha256 (base32 "11sggvncyx08ssp1s5xii4d6nskh1qwqihnbpzzvkrs7sivxn8w6")))) (build-system gnu-build-system) (arguments '(#:make-flags (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ,@(if (%current-target-system) '()))) (inputs `(("guile" ,guile-3.0) ("lzlib" ,lzlib))) (synopsis "Guile bindings to lzlib") (description "This package provides Guile bindings for lzlib, a C library for in-memory LZMA compression and decompression. The bindings are written in pure Scheme by using Guile's foreign function interface.") (home-page "-lzlib/guile-lzlib") (license license:gpl3+))) (define-public guile2.2-lzlib (package-for-guile-2.2 guile-lzlib)) (define-public guile-zstd (package (name "guile-zstd") (version "0.1.1") (home-page "-zstd/guile-zstd") (source (origin (method git-fetch) (uri (git-reference (url home-page) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1c8l7829b5yx8wdc0mrhzjfwb6h9hb7cd8dfxcr71a7vlsi86310")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("pkg-config" ,pkg-config) ("guile" ,guile-3.0))) (inputs `(("zstd" ,zstd "lib") ("guile" ,guile-3.0))) (synopsis "GNU Guile bindings to the zstd compression library") (description "This package provides a GNU Guile interface to the zstd (``zstandard'') compression library.") (license license:gpl3+)))
c9c049468b9c28fdb2b21638ad628293d304731b86efd42902b9700cf47a4fb4
manuel-serrano/bigloo
pgp_decode.scm
;*=====================================================================*/ * ... /bigloo / bigloo / api / openpgp / src / Llib / pgp_decode.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : We d Aug 18 10:24:37 2010 * / * Last change : Thu Jul 1 09:25:36 2021 ( serrano ) * / * Copyright : 2010 - 21 , . * / ;* ------------------------------------------------------------- */ ;* OpenPGP decode */ ;* ------------------------------------------------------------- */ ;* See rfc4880 for technical details: */ ;* */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __openpgp-decode (library crypto) (import __openpgp-util __openpgp-port-util __openpgp-packets __openpgp-human __openpgp-s2k __openpgp-conversion __openpgp-enums __openpgp-error) (export (decode-packets::pair-nil p::input-port ignore-bad-packets::bool) (decode-s2k p::input-port) (decode-mpi::bignum p::input-port))) ;*---------------------------------------------------------------------*/ ;* decode-packet-length-v3 ... */ ;* ------------------------------------------------------------- */ ;* #page-21 */ ;*---------------------------------------------------------------------*/ (define (decode-packet-length-v3 p packet-tag) (let ((length-type (bit-and packet-tag #x03))) (case length-type one octet length . (values (safe-read-octet p) #f)) two octet length . (values (decode-scalar p 2) #f)) four - octet length . (values (decode-scalar p 4) #f)) ((3) ;; indeterminate length. (values #f #t))))) ;*---------------------------------------------------------------------*/ ;* decode-package-length-v4 ... */ ;* ------------------------------------------------------------- */ ;* #page-24 */ ;*---------------------------------------------------------------------*/ (define (decode-packet-length-v4 p) ;; returns <length, partial-length?> (let ((length-octet (safe-read-octet p))) the length type is encoded in the two most significant bits of the ;; length octet. However, the spec uses integer-values (and not ;; bit-operations) and we therefore do the same. (cond one - octet length . (values length-octet #f)) two - octet length . (let* ((fst (bit-lsh (-fx length-octet 192) 8)) (second (safe-read-octet p)) (len (+fx+ fst second 192))) (values len #f))) partial body length . len - header is 1 byte . (let ((len (bit-lsh 1 (bit-and length-octet #x1F)))) (values len #t))) 5 - octet length . (let ((len (decode-scalar p 4))) (values len #f)))))) for v3 : partial ? is always # f. len might me # f ;; for v4: len is always given. if 'partial?' then the message is chunked. (define (content-pipe-port p len partial?) (cond ((not len) ;; v3. In theory it should be clear when the content is finished. p) ((not partial?) (length-limited-pipe-port p len)) (else (let ((pp (length-limited-pipe-port p len)) (partial? #t)) (open-input-procedure (lambda () (let ((str (read-chars 256 pp))) (cond ((and partial? (eof-object? str)) (receive (len p?) (decode-packet-length-v4 p) (set! partial? p?) (set! pp (length-limited-pipe-port p len)) (let ((str (read-chars 256 pp))) (unless (eof-object? str) str)))) ((eof-object? str) #f) (else str))))))))) ;*---------------------------------------------------------------------*/ ;* decode-packet ... */ ;* ------------------------------------------------------------- */ ;* #page-17 */ ;*---------------------------------------------------------------------*/ (define (decode-packet p::input-port ignore-bad-packets::bool) (define (decode-packet-v3 packet-tag p) (trace-item "old package format") (let ((content-tag-byte (bit-and #x0F (bit-rsh packet-tag 2)))) (when (zerofx? content-tag-byte) (openpgp-error "decode-content-tag" "invalid tag" 0)) (multiple-value-bind (len partial?) (decode-packet-length-v3 p packet-tag) (values (byte->content-tag content-tag-byte) len partial?)))) (define (decode-packet-v4 packet-tag p) (trace-item "new package format") (let ((content-tag-byte (bit-and packet-tag #x3F))) (multiple-value-bind (len partial?) (decode-packet-length-v4 p) (values (byte->content-tag content-tag-byte) len partial?)))) (with-trace 'pgp "decode-packet" (let ((packet-tag (safe-read-octet p))) (if (zerofx? (bit-and #x80 packet-tag)) (unless ignore-bad-packets (openpgp-error "decode-packet" "bad packet" packet-tag)) (begin (trace-item "offset=" (-fx (input-port-position p) 1) "/" (input-port-length p)) (trace-item "packet-tag=" packet-tag " (0x" (integer->string packet-tag 16) ")") (multiple-value-bind (content-tag len partial?) (if (zerofx? (bit-and #x40 packet-tag)) ;; old packet format (decode-packet-v3 packet-tag p) (decode-packet-v4 packet-tag p)) (trace-item "content-tag=" content-tag " [" (content-tag->human-readable content-tag) "]") (trace-item "len=" len " partial=" partial?) (let ((cpp (content-pipe-port p len partial?))) (case content-tag ((public-key-encrypted-session-key) (decode-public-key-encrypted-session-key cpp)) ((signature) (decode-signature cpp)) ((symmetric-key-encrypted-session-key) (decode-symmetric-key-encrypted-session-key cpp)) ((one-pass-signature) (decode-one-pass-signature cpp)) ((secret-key) (decode-secret-key cpp)) ((public-key) (decode-public-key cpp)) ((secret-subkey) (decode-secret-subkey cpp)) ((compressed) (decode-compressed-data cpp ignore-bad-packets)) ((symmetrically-encrypted) (decode-symmetrically-encrypted-data cpp)) ((marker) (decode-marker cpp)) ;; should be ignored ((literal) (decode-literal-data cpp)) ((trust) (decode-trust cpp)) ((ID) (decode-user-id cpp)) ((public-subkey) (decode-public-subkey cpp)) ((user-attribute) (decode-user-attribute cpp)) ((mdc-symmetrically-encrypted) (decode-mdc-sym-encrypted cpp)) ((mdc) (decode-mdc cpp)) (else (let* ((tmp (read-string p)) (len (string-length tmp))) (trace-item "remaining length=" len) (trace-item "str=" (str->hex-string (substring tmp 0 (min 10 len))))) (openpgp-error "decode-packet" "Unknown content-tag" content-tag)))))))))) ;*---------------------------------------------------------------------*/ ;* decode-packets ... */ ;*---------------------------------------------------------------------*/ (define (decode-packets p::input-port ignore-bad-packets) (with-trace 'pgp "decode-packets" (let loop () (let ((c (peek-char p))) (if (eof-object? c) '() (let ((packet (decode-packet p ignore-bad-packets))) (trace-item "packet=" (typeof packet)) (if packet (cons packet (loop)) '()))))))) ;*---------------------------------------------------------------------*/ ;* decode-s2k ... */ ;*---------------------------------------------------------------------*/ (define (decode-s2k p::input-port) (with-trace 'pgp "decode-s2k" (let* ((s2k-algo-byte (safe-read-octet p)) (s2k-algo (byte->s2k-algo s2k-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte))) (trace-item "s2k-algo: " s2k-algo-byte " " (s2k-algo->human-readable s2k-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (case s2k-algo ((simple) (make-s2k s2k-algo hash-algo #f #f)) ((salted) (let ((salt (safe-read-octets (s2k-salt-length) p))) (trace-item "salt: " (str->hex-string salt)) (make-s2k s2k-algo hash-algo salt #f))) ((iterated) (let* ((salt (safe-read-octets (s2k-salt-length) p)) (encoded-count (safe-read-char p)) (count (octet->iterated-salted-s2k-count encoded-count))) (trace-item "salt: " (str->hex-string salt)) (trace-item "count: " count " (" (char->integer encoded-count) ")") (make-s2k s2k-algo hash-algo salt count))) (else (openpgp-error "decode-s2k" "unknown s2k algorithm" s2k-algo)))))) (define (decode-time::date p::input-port #!optional (treat-0-as-present? #f)) (let ((n (decode-scalar p 4))) (if (and treat-0-as-present? (zerofx? n)) (current-date) (seconds->date n)))) (define (decode-mpi::bignum p::input-port) (with-trace 'pgp "decode-mpi" (let* ((nb-bits (decode-scalar p 2)) (nb-octets (/fx (+fx nb-bits 7) 8))) (trace-item "reading mpi of " nb-bits " bits (" nb-octets " octets)") (let loop ((i 0) (n #z0)) (cond ((=fx i nb-octets) n) (else (loop (+fx i 1) (+bx (*bx n #z256) (fixnum->bignum (safe-read-octet p)))))))))) (define (decode-scalar::long p::input-port len::long) (with-trace 'pgp "decode-scalar" (trace-item "len=" len) (let loop ((i 0) (n 0)) (cond ((=fx i len) n) (else (let ((o (safe-read-octet p))) (trace-item "o=" o) (loop (+fx i 1) (+fx (*fx n 256) o)))))))) ;; ---------------------------------------------------------------------------- 5.1 Public - Key Encrypted Session Key Packets ( Tag 1 ) ;; ---------------------------------------------------------------------------- (define (decode-public-key-encrypted-session-key cpp) (with-trace 'pgp "decode-public-key-encrypted-session-key" (let* ((version (safe-read-octet cpp)) (id (safe-read-octets 8 cpp)) (algo-byte (safe-read-octet cpp)) (algo (byte->public-key-algo algo-byte)) (secret-data (read-string cpp)) (kp (open-input-string secret-data))) (when (not (or (=fx version 2) (=fx version 3))) (openpgp-error "public key encrypted session key" "don't know how to decode a packet of this version" version)) (trace-item "version: " version) (trace-item "id: " (str->hex-string id)) (trace-item "algo: " algo " " (public-key-algo->human-readable algo)) (trace-item "secret-data: " (str->hex-string secret-data)) (case algo ((rsa-encrypt/sign rsa-encrypt) (let* ((m**e (decode-mpi kp))) (trace-item "RSA-m**e: " m**e) (instantiate::PGP-Public-Key-Encrypted-Session-Key-Packet (version version) (id id) (algo algo) (encrypted-session-key m**e)))) ((elgamal-encrypt elgamal-encrypt/sign) (let* ((g**k (decode-mpi kp)) (dummy (trace-item "g**k done")) (m*y**k (decode-mpi kp))) (trace-item "ElGamal-g**k: " g**k) (trace-item "ElGamal-m*y**k: " m*y**k) (instantiate::PGP-Public-Key-Encrypted-Session-Key-Packet (version version) (id id) (algo algo) (encrypted-session-key (cons g**k m*y**k))))) (else (openpgp-error "encrypted session key" "Can't read encrypted-session key with this public algo." (cons algo-byte (public-key-algo->human-readable algo)))))))) ;; ---------------------------------------------------------------------------- 5.2 Signature Packet ( Tag 2 ) ;; ---------------------------------------------------------------------------- (define (decode-signature p::input-port) (with-trace 'pgp "decode-signature" (let ((version (safe-read-octet p))) (trace-item "Signature version: " version) (case version ((3) (decode-signature-v3 p)) ((4) (decode-signature-v4 p version)) (else (openpgp-error "decode-signature" "Can't decode signatures of this version" version)))))) ;; ---------- 5.2.2 Version 3 Signature Packet Format ;; ---------------------------------------------------------------------------- (define (decode-signature-v3 p::input-port) (with-trace 'pgp "decode-signature-v3" must be 5 (hashed-str (safe-read-octets hashed-len p)) (hashed-str-p (open-input-string hashed-str)) (signature-type-byte (safe-read-octet hashed-str-p)) (signature-type (byte->signature-type signature-type-byte)) (creation-time (decode-time hashed-str-p)) (key-id (safe-read-octets 8 p)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) (left-hash (safe-read-octets 2 p))) (when (not (=fx hashed-len 5)) (openpgp-error "decode-signature-v3" "hashed len must be = 5" hashed-len)) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "creation-time: " creation-time) (trace-item "key-id: " (str->hex-string key-id)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "hashed-str: " (str->hex-string hashed-str)) (trace-item "left-hash: " (str->hex-string left-hash)) (let ((key-data (case public-key-algo ((rsa-encrypt/sign rsa-sign) (let ((m**d (decode-mpi p))) (trace-item "RSA m**d: " m**d) m**d)) DSA (let* ((r (decode-mpi p)) (s (decode-mpi p))) (trace-item "DSA r: " r) (trace-item "DSA s: " s) (cons r s))) (else (openpgp-error "decode-signature" "public key algorithm not implemented for signature" (public-key-algo->human-readable public-key-algo)))))) (instantiate::PGP-Signature-v3-Packet (version 3) (signature-type signature-type) (creation-date creation-time) (issuer key-id) (public-key-algo public-key-algo) (hash-algo hash-algo) (signature key-data) (signed-packet-prefix hashed-str) (hash-trailer "") (left-hash left-hash)))))) ;; ---------- 5.2.3 Version 4 Signature Packet Format ;; ---------------------------------------------------------------------------- ------ 5.2.3.1 Signature Subpacket Specification (define (decode-sub-packet p::input-port) (define (preferences->list str converter) (let loop ((i 0) (rev-res '())) (if (=fx i (string-length str)) (reverse! rev-res) (loop (+fx i 1) (cons (converter (char->integer (string-ref str i))) rev-res))))) (with-trace 'pgp "decode-sub-packet" (receive (len partial?) (decode-packet-length-v4 p) (when partial? (openpgp-error "decode-sub-package" "sub-packages must not have partial lengths" #f)) ;(trace-item "sub-packet of length: " len) (let* ((type-w/-critical (safe-read-octet p)) (type-byte (bit-and #x7F type-w/-critical)) (type (byte->subpacket-type type-byte)) (critical? (not (zerofx? (bit-and #x80 type-w/-critical))))) (trace-item "sub-packet of type: " type-byte " " (subpacket-type->human-readable type)) (trace-item "sub-packet is critical?: " critical?) (trace-item "type=" type) (trace-item "len=" len) ;; currently the following (case type ((creation-time) (let ((t (decode-time p))) (trace-item "Date: " t) (instantiate::PGP-Signature-Sub-Creation-Time (critical? critical?) (creation-date t)))) ((expiration-time) (let ((t (decode-time p))) (trace-item "Date: " t) (instantiate::PGP-Signature-Sub-Expiration-Time (critical? critical?) (expiration-date t)))) ((exportable?) (let ((exportable? (=fx 1 (safe-read-octet p)))) (trace-item "Exportable?: " exportable?) (instantiate::PGP-Signature-Sub-Exportable (critical? critical?) (exportable? exportable?)))) ((trust) (let* ((level (safe-read-octet p)) (trust (safe-read-octet p))) (trace-item "Level/Trust: " level "/" trust) (instantiate::PGP-Signature-Sub-Trust (critical? critical?) (level level) (amount trust)))) TODO ( ( 6 ) ' regular - expression ) ((revocable?) (let ((revocable? (=fx 1 (safe-read-octet p)))) (instantiate::PGP-Signature-Sub-Revocable (critical? critical?) (revocable? revocable?)))) ((key-expiration-time) (let ((t (decode-scalar p 4))) (trace-item "expiration-time: " t) (instantiate::PGP-Signature-Sub-Key-Expiration-Time (critical? critical?) (expiration-time t)))) ((placeholder) ;; placeholder for backward compatibility (let ((tmp (safe-read-octets (-fx len 1) p))) (trace-item "generic: " (str->hex-string tmp)) (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data tmp)))) ((preferred-symmetric) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->symmetric-key-algo))) (trace-item "preferred symmetrics: " (map symmetric-key-algo->human-readable prefs)) (instantiate::PGP-Signature-Sub-Preferred-Symmetric (critical? critical?) (algos prefs)))) ((revocation-key) (let* ((class (safe-read-octet p)) (sensitive? (not (zerofx? (bit-and #x40 class)))) (algid (safe-read-octet p)) (fingerprint (safe-read-octets 20 p))) (trace-item "class: " class) (trace-item "sensitive?: " sensitive?) (trace-item "algid: " algid) (trace-item "finger-print: " (str->hex-string fingerprint)) (when (zerofx? (bit-and #x80 class)) (openpgp-error "decode-signature-sub-packet" "revocation-key signature must have bit 0x80 set" (format "0x~x" class))) (instantiate::PGP-Signature-Sub-Revocation (critical? critical?) (clazz class) (sensitive? sensitive?) (algid algid) (fingerprint fingerprint)))) ((issuer-ID) (let ((id (safe-read-octets 8 p))) (trace-item "Id: " (str->hex-string id)) (instantiate::PGP-Signature-Sub-ID (critical? critical?) (key-id id)))) ((notation) (let* ((flags (safe-read-octets 4 p)) (name-len (decode-scalar p 2)) (value-len (decode-scalar p 2)) (name-data (safe-read-octets name-len p)) (value-data (safe-read-octets value-len p))) (trace-item "flags: " flags) (trace-item "name: " name-data) (trace-item "value: " value-data) (instantiate::PGP-Signature-Sub-Notation (critical? critical?) (flags flags) (name name-data) (value value-data)))) ((preferred-hash) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->hash-algo))) (trace-item "Preferred Hash-algo: " (map hash-algo->human-readable prefs)) (instantiate::PGP-Signature-Sub-Preferred-Hash (critical? critical?) (algos prefs)))) ((preferred-compression) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->compression-algo))) (trace-item "Preferred Compression algo id: " (map compression-algo->byte prefs)) (trace-item "Preferred Compression algo name: " (map (lambda (p) (format "~s [~s]" p (compression-algo->human-readable p))) prefs)) (instantiate::PGP-Signature-Sub-Preferred-Compression (critical? critical?) (algos prefs)))) TODO ( ( key - server - prefs ) ; ; preferred key server preferences ((preferred-key-server) (let ((key-server (safe-read-octets (-fx len 1) p))) (trace-item "Preferred Key-server:" key-server) (instantiate::PGP-Signature-Sub-Preferred-Key-Server (critical? critical?) (server key-server)))) ((primary-id?) (let ((prim-id? (not (=fx 0 (safe-read-octet p))))) (trace-item "Primary Id?: " prim-id?) (instantiate::PGP-Signature-Sub-Primary-ID (critical? critical?) (primary? prim-id?)))) ((policy) (let ((policy (safe-read-octets (-fx len 1) p))) (trace-item "Policy: " policy) (instantiate::PGP-Signature-Sub-Policy (critical? critical?) (url policy)))) TODO ( ( key - flags ) ; ; key flags ((signer-ID) (let ((id (safe-read-octets (-fx len 1) p))) (trace-item "Signer id: " id) (instantiate::PGP-Signature-Sub-Signer-ID (critical? critical?) (id id)))) ((revocation-reason) (let* ((code-byte (safe-read-octet p)) (code (byte->revocation-code code-byte)) (reason (safe-read-octets (-fx len 2) p))) (trace-item "Revocation code: " code-byte " " (revocation-code->human-readable code)) (trace-item "Reason: " reason) (instantiate::PGP-Signature-Sub-Revocation-Reason (critical? critical?) (code code) (reason reason)))) ((issuer-fpr) (trace-item "Issuer fingerprint") (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data (safe-read-octets (-fx len 1) p)))) (else (trace-item "Generic") (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data (safe-read-octets (-fx len 1) p))))))))) (define (decode-sub-packets p::input-port) (with-trace 'pgp "decode-sub-packets" (let loop ((packets '())) (let ((c (peek-char p))) (trace-item "i=" (input-port-position p) "/" (input-port-length p)) (if (eof-object? c) (reverse! packets) (let ((sub-packet (decode-sub-packet p))) (loop (cons sub-packet packets)))))))) ;; -------- 5.2.3 (define (decode-signature-v4 p::input-port version) (define (find-creation-date sps) (let ((pkt (any (lambda (pkt) (and (isa? pkt PGP-Signature-Sub-Creation-Time) pkt)) sps))) (when (not pkt) (openpgp-error "decode-signature-v4" "invalid signature. Can't find obligatory creation-time sub-packet" #f)) (with-access::PGP-Signature-Sub-Creation-Time pkt (creation-date) creation-date))) (define (find-issuer sps) (let ((pkt (any (lambda (pkt) (and (isa? pkt PGP-Signature-Sub-ID) pkt)) sps))) (when (not pkt) (openpgp-error "decode-signature-v4" "invalid signature. Can't find obligatory issuer id sub-packet" #f)) (with-access::PGP-Signature-Sub-ID pkt (key-id) key-id))) (with-trace 'pgp "decode-signature-v4" (let* ((signature-type-byte (safe-read-octet p)) (signature-type (byte->signature-type signature-type-byte)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) ;; spd = sub-packet-data (hashed-spd-len-str (safe-read-octets 2 p)) (hashed-spd-len (scalar->fixnum hashed-spd-len-str)) (hashed-spd (safe-read-octets hashed-spd-len p)) (dumm1 (trace-item "*- decoding hashed subpackets=" (string-for-read hashed-spd))) (sps1 (decode-sub-packets (open-input-string hashed-spd))) (creation-date (find-creation-date sps1)) (dumm2 (trace-item "creation-date=" creation-date)) (unhashed-spd-len (decode-scalar p 2)) (dumm1 (trace-item "*- decoding unhashed subpackets")) (sps2 (decode-sub-packets (length-limited-pipe-port p unhashed-spd-len))) (sps1+sps2 (append sps2 sps1)) (issuer (find-issuer sps1+sps2)) (left-hash (safe-read-octets 2 p))) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "hashed-subpacket-data: " (str->hex-string hashed-spd)) ; (trace-item "sps1:") ; (for-each (lambda (sp) ; (with-access::PGP-Signature-Sub-Packet sp (type) ; (trace-item " " (subpacket-type->human-readable type) ; " " sp))) ; sps1) ( trace - item " sps2 : " ) ; (for-each (lambda (sp) ; (with-access::PGP-Signature-Sub-Packet sp (type) ; (trace-item " " (subpacket-type->human-readable type) ; " " sp))) sps2 ) (trace-item "left-hash: " (str->hex-string left-hash)) (let* ((signed-packet-prefix-len (+fx 6 hashed-spd-len)) (signed-packet-prefix (make-string signed-packet-prefix-len)) (hash-trailer (make-string 6))) (string-set! signed-packet-prefix 0 (integer->char-ur version)) (string-set! signed-packet-prefix 1 (integer->char-ur signature-type-byte)) (string-set! signed-packet-prefix 2 (integer->char-ur public-key-algo-byte)) (string-set! signed-packet-prefix 3 (integer->char-ur hash-algo-byte)) (blit-string! hashed-spd-len-str 0 signed-packet-prefix 4 2) (blit-string! hashed-spd 0 signed-packet-prefix 6 hashed-spd-len) trailer magic ... ( see 5.2.4 , page 31 of RFC2440 ) (string-set! hash-trailer 0 (integer->char-ur version)) (string-set! hash-trailer 1 (integer->char-ur #xFF)) (blit-string! (fixnum->scalar signed-packet-prefix-len 4) 0 hash-trailer 2 4) (trace-item "signed-packet-prefix: " (str->hex-string signed-packet-prefix)) (trace-item "hash-trailer: " (str->hex-string hash-trailer)) (let ((key-data (case public-key-algo ((rsa-encrypt/sign rsa-sign) (let ((m**d (decode-mpi p))) (trace-item "RSA m**d: " m**d) m**d)) ((dsa) (let* ((r (decode-mpi p)) (s (decode-mpi p))) (trace-item "DSA r: " r) (trace-item "DSA s: " s) (cons r s))) (else (openpgp-error "decode-signature" "public key algorithm not implemented" (list public-key-algo-byte (public-key-algo->human-readable public-key-algo))))))) (instantiate::PGP-Signature-v4-Packet (version 4) (signature-type signature-type) (creation-date creation-date) (issuer issuer) (public-key-algo public-key-algo) (hash-algo hash-algo) (signature key-data) (signed-packet-prefix signed-packet-prefix) (hash-trailer hash-trailer) (left-hash left-hash) (secure-sub-packets sps1) (insecure-sub-packets sps2))))))) ;; ---------------------------------------------------------------------------- 5.3 Symmetric - Key Encrypted Session - Key Packets ( Tag 3 ) ;; ---------------------------------------------------------------------------- (define (decode-symmetric-key-encrypted-session-key cpp) (let* ((version (safe-read-octet cpp)) (symmetric-algo-byte (safe-read-octet cpp)) (symmetric-algo (byte->symmetric-key-algo symmetric-algo-byte)) (s2k (decode-s2k cpp)) (encrypted-session-key (read-string cpp))) (instantiate::PGP-Symmetric-Key-Encrypted-Session-Key-Packet (version version) (algo symmetric-algo) (s2k s2k) (encrypted-session-key (if (string-null? encrypted-session-key) #f encrypted-session-key))))) ;; ---------------------------------------------------------------------------- 5.4 One - Pass Signature Packets ( Tag 4 ) ;; ---------------------------------------------------------------------------- (define (decode-one-pass-signature p::input-port) (with-trace 'pgp "decode-one-pass-signature" (let* ((version (safe-read-octet p)) (signature-type-byte (safe-read-octet p)) (signature-type (byte->signature-type signature-type-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (id (safe-read-octets 8 p)) (nested-signature? (zerofx? (safe-read-octet p)))) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "id: " (str->hex-string id)) (trace-item "nested-sig?: " nested-signature?) (instantiate::PGP-One-Pass-Signature-Packet (version version) (signature-type signature-type) (issuer id) (public-key-algo public-key-algo) (hash-algo hash-algo) (contains-nested-sig? nested-signature?))))) ;; ---------------------------------------------------------------------------- 5.5 Key Material Packet ;; ---------------------------------------------------------------------------- ;; ---------- 5.5.1.1 Public Key Packet ;; ---------------------------------------------------------------------------- (define make-public-rsa-key (lambda (m e) (instantiate::Rsa-Key (modulus m) (exponent e)))) (define make-public-dsa-key (lambda (p q g y) (instantiate::Dsa-Key (p p) (q q) (g g) (y y)))) (define make-public-elgamal-key (lambda (p g y) (instantiate::ElGamal-Key (p p) (g g) (y y)))) (define *dummy-date* (current-date)) (define (decode-public-key p::input-port) (let* ((version (safe-read-octet p)) (kp (instantiate::PGP-Public-Key-Packet (version version) (algo 'not-yet-set) (creation-date *dummy-date*) ;; typing. (valid-days #f) (key #f)))) (case version ((2 3 4) 'ok) (else (openpgp-error "decode-public-key" "version of public key file not supported" version))) (decode/fill-key kp version p) kp)) (define (decode/fill-key kp::PGP-Key-Packet version p::input-port) (with-trace 'pgp "decode/fill-key" (let ((cd (decode-time p))) (trace-item "creation-date: " cd) (with-access::PGP-Key-Packet kp (creation-date) (set! creation-date cd))) (when (or (=fx version 2) (=fx version 3)) (let ((vd (decode-scalar p 2))) ;; if 0 indefinite (trace-item "valid days: " vd) (with-access::PGP-Key-Packet kp (valid-days) (set! valid-days vd)))) (let* ((algo-byte (safe-read-octet p)) (algo (byte->public-key-algo algo-byte))) (when (and (or (=fx version 2) (=fx version 3)) (not (or (eq? algo 'rsa-encrypt/sign) (eq? algo 'rsa-encrypt) (eq? algo 'rsa-sign)))) (openpgp-error "decode key v3" "only RSA is supported for version 3 keys" (public-key-algo->human-readable algo))) (trace-item "algo: " algo " " (public-key-algo->human-readable algo)) (with-access::PGP-Key-Packet kp ((kalgo algo)) (set! kalgo algo)) (case algo ((rsa-encrypt/sign rsa-encrypt rsa-sign) (let* ((modulus (decode-mpi p)) (exponent (decode-mpi p)) (k (make-public-rsa-key modulus exponent))) (trace-item "modulus: " modulus) (trace-item "exponent: " exponent) (with-access::PGP-Key-Packet kp (key) (set! key k)))) DSA (let* ((port p) (p (decode-mpi port)) (q (decode-mpi port)) (g (decode-mpi port)) (y (decode-mpi port)) (k (make-public-dsa-key p q g y))) (trace-item "p: " p) (trace-item "q: " q) (trace-item "g: " g) (trace-item "y: " y) (with-access::PGP-Key-Packet kp (key) (set! key k)))) ((elgamal-encrypt elgamal-encrypt/sign) (let* ((port p) (p (decode-mpi port)) (g (decode-mpi port)) (y (decode-mpi port)) (k (make-public-elgamal-key p g y))) (trace-item "p: " p) (trace-item "g: " g) (trace-item "y: " y) (with-access::PGP-Key-Packet kp (key) (set! key k)))) (else (openpgp-error "decode-key" "public key algorithm must be RSA, DSA or ElGamal" (public-key-algo->human-readable algo))))))) ;; ---------- ;; 5.5.1.2 Public Subkey Packet ;; ---------------------------------------------------------------------------- (define (decode-public-subkey cpp) (let ((p (decode-public-key cpp))) (with-access::PGP-Public-Key-Packet p (subkey?) (set! subkey? #t)) p)) ;; ---------- 5.5.1.3 Secret Key Packet ;; ---------------------------------------------------------------------------- (define (decode-secret-key cpp::input-port) (with-trace 'pgp "decode-secreate-key" (let* ((version (safe-read-octet cpp)) (kp (instantiate::PGP-Secret-Key-Packet (version version) (algo 'not-yet-set) (creation-date *dummy-date*) (valid-days #f) (key #f) (password-protected-secret-key-data "")))) (case version ((3 4) (decode/fill-key kp version cpp)) (else (openpgp-error "decode-secret-key" "version incompatible with this implementation" version))) (let ((secret-data (read-string cpp))) (trace-item "secret data: " (str->hex-string secret-data)) (with-access::PGP-Secret-Key-Packet kp (password-protected-secret-key-data) (set! password-protected-secret-key-data secret-data)) kp)))) ;; ---------- 5.5.1.4 Secret Subkey Packet ;; ---------------------------------------------------------------------------- (define (decode-secret-subkey cpp) (let ((p (decode-secret-key cpp))) (with-access::PGP-Secret-Key-Packet p (subkey?) (set! subkey? #t)) p)) ;; ---------------------------------------------------------------------------- 5.6 Compressed Data Packet ;; ---------------------------------------------------------------------------- (define (decode-compressed-data cpp ignore-bad-packets::bool) ;; note: we discard the compression-packet and return the uncompressed ;; packet. Maybe this is not intended in which case we could insert a new ;; 'Compression-Packet'. (with-trace 'pgp "decode-compressed-data" (let* ((algo-byte (safe-read-octet cpp)) (algo (byte->compression-algo algo-byte))) (trace-item "Compression Algorithm: " algo " " (compression-algo->human-readable algo)) (case algo ((uncompressed) (decode-packet cpp ignore-bad-packets)) ((ZIP) (let ((pz (port->inflate-port cpp))) (unwind-protect (instantiate::PGP-Compressed-Packet (packets (decode-packets pz ignore-bad-packets))) (close-input-port pz)))) ;; TODO: fix compression ((ZLIB) (let ((pz (port->zlib-port cpp))) (unwind-protect (instantiate::PGP-Compressed-Packet (packets (decode-packets pz ignore-bad-packets))) (close-input-port pz)))) (else (openpgp-error "decode compressed" "Can't decompresse data" algo)))))) ;; ---------------------------------------------------------------------------- 5.7 Symmetrically Encrypted Data Packet ( Tag 9 ) ;; ---------------------------------------------------------------------------- (define (decode-symmetrically-encrypted-data cpp) (instantiate::PGP-Symmetrically-Encrypted-Packet (data (read-string cpp)))) ;; ---------------------------------------------------------------------------- 5.8 Marker Packet ( Obsolete Literal Packet ) ( Tag 10 ) ;; ---------------------------------------------------------------------------- (define (decode-marker cpp) (let* ((p (safe-read-octet cpp)) (g (safe-read-octet cpp)) (p2 (safe-read-octet cpp))) (unless (and (=fx p #x50) (=fx g #x47) (=fx p2 #x50) (eof-object? (peek-char cpp))) (openpgp-error "decode-marker" "bad marker packet" #f)) (instantiate::PGP-Marker-Packet))) ;; ---------------------------------------------------------------------------- 5.9 Literal Data Packet ( Tag 11 ) ;; ---------------------------------------------------------------------------- (define (decode-literal-data p::input-port) (with-trace 'pgp "decode-literal-data" (let* ((format-byte (safe-read-octet p)) (format (byte->literal-format format-byte)) (file-len (safe-read-octet p)) (file-name (safe-read-octets file-len p)) (sensitive? (string=? file-name "_CONSOLE")) (creation-date (decode-time p #t)) (data (read-string p))) (trace-item "format: " format-byte " " (literal-format->human-readable format)) (trace-item "file: " file-name) (trace-item "creation-date: " creation-date) (trace-item "data: \n-------\n" data "\n---------\n") (instantiate::PGP-Literal-Packet (format format) (for-your-eyes-only? sensitive?) (file-name (and (not sensitive?) file-name)) (creation-date creation-date) (data data))))) ;; ---------------------------------------------------------------------------- 5.10 Trust Packet ( Tag 12 ) ;; ---------------------------------------------------------------------------- (define (decode-trust cpp) (read-string cpp) (warning "ignoring trust packet") (instantiate::PGP-Trust-Packet)) ;; ---------------------------------------------------------------------------- 5.11 User ID Packet ( Tag 13 ) ;; ---------------------------------------------------------------------------- (define (decode-user-id cpp) (with-trace 'pgp "decode-user-id" (let ((user-id (read-string cpp))) (trace-item "User ID: " user-id) (instantiate::PGP-ID-Packet (data user-id))))) ;; ---------------------------------------------------------------------------- 5.12 User ID Packet ( Tag 17 ) ;; ---------------------------------------------------------------------------- (define (decode-user-attribute cpp) (with-trace 'pgp "decode-user-attribute" (let ((user-attr (read-string cpp))) (trace-item "User ATTR: " (string-for-read user-attr)) (instantiate::PGP-Attribute-Packet (data user-attr))))) ;; ---------------------------------------------------------------------------- 5.13 Sym . Encrypted Integrity Protected Data Packet ( Tag 18 ) ;; ---------------------------------------------------------------------------- (define (decode-mdc-sym-encrypted cpp) (with-trace 'pgp "decode-mdc-sym-encrypted" (trace-item "cpp=" cpp) (let* ((version (safe-read-octet cpp)) (data (read-string cpp))) (trace-item "version: " version) (trace-item "len: " (string-length data)) (instantiate::PGP-MDC-Symmetrically-Encrypted-Packet (version version) (data data))))) ;; ---------------------------------------------------------------------------- 5.14 Modification Detection Code Packet ( Tag 19 ) ;; ---------------------------------------------------------------------------- (define (decode-mdc cpp) (with-trace 'pgp "decode-mdc" (let ((str (read-string cpp))) (when (not (=fx (string-length str) 20)) (openpgp-error 'decode-mdc "Bad Modification Detection Code Packet" #f)) (trace-item "sha1 mdc: " (str->hex-string str)) (instantiate::PGP-MDC-Packet (hash str)))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/fdeac39af72d5119d01818815b0f395f2907d6da/api/openpgp/src/Llib/pgp_decode.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * OpenPGP decode */ * ------------------------------------------------------------- */ * See rfc4880 for technical details: */ * */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * decode-packet-length-v3 ... */ * ------------------------------------------------------------- */ * #page-21 */ *---------------------------------------------------------------------*/ indeterminate length. *---------------------------------------------------------------------*/ * decode-package-length-v4 ... */ * ------------------------------------------------------------- */ * #page-24 */ *---------------------------------------------------------------------*/ returns <length, partial-length?> length octet. However, the spec uses integer-values (and not bit-operations) and we therefore do the same. for v4: len is always given. if 'partial?' then the message is chunked. v3. In theory it should be clear when the content is finished. *---------------------------------------------------------------------*/ * decode-packet ... */ * ------------------------------------------------------------- */ * #page-17 */ *---------------------------------------------------------------------*/ old packet format should be ignored *---------------------------------------------------------------------*/ * decode-packets ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * decode-s2k ... */ *---------------------------------------------------------------------*/ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------- ---------------------------------------------------------------------------- ---------- ---------------------------------------------------------------------------- (trace-item "sub-packet of length: " len) currently the following placeholder for backward compatibility ; preferred key server preferences ; key flags -------- 5.2.3 spd = sub-packet-data (trace-item "sps1:") (for-each (lambda (sp) (with-access::PGP-Signature-Sub-Packet sp (type) (trace-item " " (subpacket-type->human-readable type) " " sp))) sps1) (for-each (lambda (sp) (with-access::PGP-Signature-Sub-Packet sp (type) (trace-item " " (subpacket-type->human-readable type) " " sp))) ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------- ---------------------------------------------------------------------------- typing. if 0 indefinite ---------- 5.5.1.2 Public Subkey Packet ---------------------------------------------------------------------------- ---------- ---------------------------------------------------------------------------- ---------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- note: we discard the compression-packet and return the uncompressed packet. Maybe this is not intended in which case we could insert a new 'Compression-Packet'. TODO: fix compression ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------------------
* ... /bigloo / bigloo / api / openpgp / src / Llib / pgp_decode.scm * / * Author : * / * Creation : We d Aug 18 10:24:37 2010 * / * Last change : Thu Jul 1 09:25:36 2021 ( serrano ) * / * Copyright : 2010 - 21 , . * / (module __openpgp-decode (library crypto) (import __openpgp-util __openpgp-port-util __openpgp-packets __openpgp-human __openpgp-s2k __openpgp-conversion __openpgp-enums __openpgp-error) (export (decode-packets::pair-nil p::input-port ignore-bad-packets::bool) (decode-s2k p::input-port) (decode-mpi::bignum p::input-port))) (define (decode-packet-length-v3 p packet-tag) (let ((length-type (bit-and packet-tag #x03))) (case length-type one octet length . (values (safe-read-octet p) #f)) two octet length . (values (decode-scalar p 2) #f)) four - octet length . (values (decode-scalar p 4) #f)) (values #f #t))))) (define (decode-packet-length-v4 p) (let ((length-octet (safe-read-octet p))) the length type is encoded in the two most significant bits of the (cond one - octet length . (values length-octet #f)) two - octet length . (let* ((fst (bit-lsh (-fx length-octet 192) 8)) (second (safe-read-octet p)) (len (+fx+ fst second 192))) (values len #f))) partial body length . len - header is 1 byte . (let ((len (bit-lsh 1 (bit-and length-octet #x1F)))) (values len #t))) 5 - octet length . (let ((len (decode-scalar p 4))) (values len #f)))))) for v3 : partial ? is always # f. len might me # f (define (content-pipe-port p len partial?) (cond ((not len) p) ((not partial?) (length-limited-pipe-port p len)) (else (let ((pp (length-limited-pipe-port p len)) (partial? #t)) (open-input-procedure (lambda () (let ((str (read-chars 256 pp))) (cond ((and partial? (eof-object? str)) (receive (len p?) (decode-packet-length-v4 p) (set! partial? p?) (set! pp (length-limited-pipe-port p len)) (let ((str (read-chars 256 pp))) (unless (eof-object? str) str)))) ((eof-object? str) #f) (else str))))))))) (define (decode-packet p::input-port ignore-bad-packets::bool) (define (decode-packet-v3 packet-tag p) (trace-item "old package format") (let ((content-tag-byte (bit-and #x0F (bit-rsh packet-tag 2)))) (when (zerofx? content-tag-byte) (openpgp-error "decode-content-tag" "invalid tag" 0)) (multiple-value-bind (len partial?) (decode-packet-length-v3 p packet-tag) (values (byte->content-tag content-tag-byte) len partial?)))) (define (decode-packet-v4 packet-tag p) (trace-item "new package format") (let ((content-tag-byte (bit-and packet-tag #x3F))) (multiple-value-bind (len partial?) (decode-packet-length-v4 p) (values (byte->content-tag content-tag-byte) len partial?)))) (with-trace 'pgp "decode-packet" (let ((packet-tag (safe-read-octet p))) (if (zerofx? (bit-and #x80 packet-tag)) (unless ignore-bad-packets (openpgp-error "decode-packet" "bad packet" packet-tag)) (begin (trace-item "offset=" (-fx (input-port-position p) 1) "/" (input-port-length p)) (trace-item "packet-tag=" packet-tag " (0x" (integer->string packet-tag 16) ")") (multiple-value-bind (content-tag len partial?) (if (zerofx? (bit-and #x40 packet-tag)) (decode-packet-v3 packet-tag p) (decode-packet-v4 packet-tag p)) (trace-item "content-tag=" content-tag " [" (content-tag->human-readable content-tag) "]") (trace-item "len=" len " partial=" partial?) (let ((cpp (content-pipe-port p len partial?))) (case content-tag ((public-key-encrypted-session-key) (decode-public-key-encrypted-session-key cpp)) ((signature) (decode-signature cpp)) ((symmetric-key-encrypted-session-key) (decode-symmetric-key-encrypted-session-key cpp)) ((one-pass-signature) (decode-one-pass-signature cpp)) ((secret-key) (decode-secret-key cpp)) ((public-key) (decode-public-key cpp)) ((secret-subkey) (decode-secret-subkey cpp)) ((compressed) (decode-compressed-data cpp ignore-bad-packets)) ((symmetrically-encrypted) (decode-symmetrically-encrypted-data cpp)) ((marker) ((literal) (decode-literal-data cpp)) ((trust) (decode-trust cpp)) ((ID) (decode-user-id cpp)) ((public-subkey) (decode-public-subkey cpp)) ((user-attribute) (decode-user-attribute cpp)) ((mdc-symmetrically-encrypted) (decode-mdc-sym-encrypted cpp)) ((mdc) (decode-mdc cpp)) (else (let* ((tmp (read-string p)) (len (string-length tmp))) (trace-item "remaining length=" len) (trace-item "str=" (str->hex-string (substring tmp 0 (min 10 len))))) (openpgp-error "decode-packet" "Unknown content-tag" content-tag)))))))))) (define (decode-packets p::input-port ignore-bad-packets) (with-trace 'pgp "decode-packets" (let loop () (let ((c (peek-char p))) (if (eof-object? c) '() (let ((packet (decode-packet p ignore-bad-packets))) (trace-item "packet=" (typeof packet)) (if packet (cons packet (loop)) '()))))))) (define (decode-s2k p::input-port) (with-trace 'pgp "decode-s2k" (let* ((s2k-algo-byte (safe-read-octet p)) (s2k-algo (byte->s2k-algo s2k-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte))) (trace-item "s2k-algo: " s2k-algo-byte " " (s2k-algo->human-readable s2k-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (case s2k-algo ((simple) (make-s2k s2k-algo hash-algo #f #f)) ((salted) (let ((salt (safe-read-octets (s2k-salt-length) p))) (trace-item "salt: " (str->hex-string salt)) (make-s2k s2k-algo hash-algo salt #f))) ((iterated) (let* ((salt (safe-read-octets (s2k-salt-length) p)) (encoded-count (safe-read-char p)) (count (octet->iterated-salted-s2k-count encoded-count))) (trace-item "salt: " (str->hex-string salt)) (trace-item "count: " count " (" (char->integer encoded-count) ")") (make-s2k s2k-algo hash-algo salt count))) (else (openpgp-error "decode-s2k" "unknown s2k algorithm" s2k-algo)))))) (define (decode-time::date p::input-port #!optional (treat-0-as-present? #f)) (let ((n (decode-scalar p 4))) (if (and treat-0-as-present? (zerofx? n)) (current-date) (seconds->date n)))) (define (decode-mpi::bignum p::input-port) (with-trace 'pgp "decode-mpi" (let* ((nb-bits (decode-scalar p 2)) (nb-octets (/fx (+fx nb-bits 7) 8))) (trace-item "reading mpi of " nb-bits " bits (" nb-octets " octets)") (let loop ((i 0) (n #z0)) (cond ((=fx i nb-octets) n) (else (loop (+fx i 1) (+bx (*bx n #z256) (fixnum->bignum (safe-read-octet p)))))))))) (define (decode-scalar::long p::input-port len::long) (with-trace 'pgp "decode-scalar" (trace-item "len=" len) (let loop ((i 0) (n 0)) (cond ((=fx i len) n) (else (let ((o (safe-read-octet p))) (trace-item "o=" o) (loop (+fx i 1) (+fx (*fx n 256) o)))))))) 5.1 Public - Key Encrypted Session Key Packets ( Tag 1 ) (define (decode-public-key-encrypted-session-key cpp) (with-trace 'pgp "decode-public-key-encrypted-session-key" (let* ((version (safe-read-octet cpp)) (id (safe-read-octets 8 cpp)) (algo-byte (safe-read-octet cpp)) (algo (byte->public-key-algo algo-byte)) (secret-data (read-string cpp)) (kp (open-input-string secret-data))) (when (not (or (=fx version 2) (=fx version 3))) (openpgp-error "public key encrypted session key" "don't know how to decode a packet of this version" version)) (trace-item "version: " version) (trace-item "id: " (str->hex-string id)) (trace-item "algo: " algo " " (public-key-algo->human-readable algo)) (trace-item "secret-data: " (str->hex-string secret-data)) (case algo ((rsa-encrypt/sign rsa-encrypt) (let* ((m**e (decode-mpi kp))) (trace-item "RSA-m**e: " m**e) (instantiate::PGP-Public-Key-Encrypted-Session-Key-Packet (version version) (id id) (algo algo) (encrypted-session-key m**e)))) ((elgamal-encrypt elgamal-encrypt/sign) (let* ((g**k (decode-mpi kp)) (dummy (trace-item "g**k done")) (m*y**k (decode-mpi kp))) (trace-item "ElGamal-g**k: " g**k) (trace-item "ElGamal-m*y**k: " m*y**k) (instantiate::PGP-Public-Key-Encrypted-Session-Key-Packet (version version) (id id) (algo algo) (encrypted-session-key (cons g**k m*y**k))))) (else (openpgp-error "encrypted session key" "Can't read encrypted-session key with this public algo." (cons algo-byte (public-key-algo->human-readable algo)))))))) 5.2 Signature Packet ( Tag 2 ) (define (decode-signature p::input-port) (with-trace 'pgp "decode-signature" (let ((version (safe-read-octet p))) (trace-item "Signature version: " version) (case version ((3) (decode-signature-v3 p)) ((4) (decode-signature-v4 p version)) (else (openpgp-error "decode-signature" "Can't decode signatures of this version" version)))))) 5.2.2 Version 3 Signature Packet Format (define (decode-signature-v3 p::input-port) (with-trace 'pgp "decode-signature-v3" must be 5 (hashed-str (safe-read-octets hashed-len p)) (hashed-str-p (open-input-string hashed-str)) (signature-type-byte (safe-read-octet hashed-str-p)) (signature-type (byte->signature-type signature-type-byte)) (creation-time (decode-time hashed-str-p)) (key-id (safe-read-octets 8 p)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) (left-hash (safe-read-octets 2 p))) (when (not (=fx hashed-len 5)) (openpgp-error "decode-signature-v3" "hashed len must be = 5" hashed-len)) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "creation-time: " creation-time) (trace-item "key-id: " (str->hex-string key-id)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "hashed-str: " (str->hex-string hashed-str)) (trace-item "left-hash: " (str->hex-string left-hash)) (let ((key-data (case public-key-algo ((rsa-encrypt/sign rsa-sign) (let ((m**d (decode-mpi p))) (trace-item "RSA m**d: " m**d) m**d)) DSA (let* ((r (decode-mpi p)) (s (decode-mpi p))) (trace-item "DSA r: " r) (trace-item "DSA s: " s) (cons r s))) (else (openpgp-error "decode-signature" "public key algorithm not implemented for signature" (public-key-algo->human-readable public-key-algo)))))) (instantiate::PGP-Signature-v3-Packet (version 3) (signature-type signature-type) (creation-date creation-time) (issuer key-id) (public-key-algo public-key-algo) (hash-algo hash-algo) (signature key-data) (signed-packet-prefix hashed-str) (hash-trailer "") (left-hash left-hash)))))) 5.2.3 Version 4 Signature Packet Format ------ 5.2.3.1 Signature Subpacket Specification (define (decode-sub-packet p::input-port) (define (preferences->list str converter) (let loop ((i 0) (rev-res '())) (if (=fx i (string-length str)) (reverse! rev-res) (loop (+fx i 1) (cons (converter (char->integer (string-ref str i))) rev-res))))) (with-trace 'pgp "decode-sub-packet" (receive (len partial?) (decode-packet-length-v4 p) (when partial? (openpgp-error "decode-sub-package" "sub-packages must not have partial lengths" #f)) (let* ((type-w/-critical (safe-read-octet p)) (type-byte (bit-and #x7F type-w/-critical)) (type (byte->subpacket-type type-byte)) (critical? (not (zerofx? (bit-and #x80 type-w/-critical))))) (trace-item "sub-packet of type: " type-byte " " (subpacket-type->human-readable type)) (trace-item "sub-packet is critical?: " critical?) (trace-item "type=" type) (trace-item "len=" len) (case type ((creation-time) (let ((t (decode-time p))) (trace-item "Date: " t) (instantiate::PGP-Signature-Sub-Creation-Time (critical? critical?) (creation-date t)))) ((expiration-time) (let ((t (decode-time p))) (trace-item "Date: " t) (instantiate::PGP-Signature-Sub-Expiration-Time (critical? critical?) (expiration-date t)))) ((exportable?) (let ((exportable? (=fx 1 (safe-read-octet p)))) (trace-item "Exportable?: " exportable?) (instantiate::PGP-Signature-Sub-Exportable (critical? critical?) (exportable? exportable?)))) ((trust) (let* ((level (safe-read-octet p)) (trust (safe-read-octet p))) (trace-item "Level/Trust: " level "/" trust) (instantiate::PGP-Signature-Sub-Trust (critical? critical?) (level level) (amount trust)))) TODO ( ( 6 ) ' regular - expression ) ((revocable?) (let ((revocable? (=fx 1 (safe-read-octet p)))) (instantiate::PGP-Signature-Sub-Revocable (critical? critical?) (revocable? revocable?)))) ((key-expiration-time) (let ((t (decode-scalar p 4))) (trace-item "expiration-time: " t) (instantiate::PGP-Signature-Sub-Key-Expiration-Time (critical? critical?) (expiration-time t)))) (let ((tmp (safe-read-octets (-fx len 1) p))) (trace-item "generic: " (str->hex-string tmp)) (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data tmp)))) ((preferred-symmetric) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->symmetric-key-algo))) (trace-item "preferred symmetrics: " (map symmetric-key-algo->human-readable prefs)) (instantiate::PGP-Signature-Sub-Preferred-Symmetric (critical? critical?) (algos prefs)))) ((revocation-key) (let* ((class (safe-read-octet p)) (sensitive? (not (zerofx? (bit-and #x40 class)))) (algid (safe-read-octet p)) (fingerprint (safe-read-octets 20 p))) (trace-item "class: " class) (trace-item "sensitive?: " sensitive?) (trace-item "algid: " algid) (trace-item "finger-print: " (str->hex-string fingerprint)) (when (zerofx? (bit-and #x80 class)) (openpgp-error "decode-signature-sub-packet" "revocation-key signature must have bit 0x80 set" (format "0x~x" class))) (instantiate::PGP-Signature-Sub-Revocation (critical? critical?) (clazz class) (sensitive? sensitive?) (algid algid) (fingerprint fingerprint)))) ((issuer-ID) (let ((id (safe-read-octets 8 p))) (trace-item "Id: " (str->hex-string id)) (instantiate::PGP-Signature-Sub-ID (critical? critical?) (key-id id)))) ((notation) (let* ((flags (safe-read-octets 4 p)) (name-len (decode-scalar p 2)) (value-len (decode-scalar p 2)) (name-data (safe-read-octets name-len p)) (value-data (safe-read-octets value-len p))) (trace-item "flags: " flags) (trace-item "name: " name-data) (trace-item "value: " value-data) (instantiate::PGP-Signature-Sub-Notation (critical? critical?) (flags flags) (name name-data) (value value-data)))) ((preferred-hash) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->hash-algo))) (trace-item "Preferred Hash-algo: " (map hash-algo->human-readable prefs)) (instantiate::PGP-Signature-Sub-Preferred-Hash (critical? critical?) (algos prefs)))) ((preferred-compression) (let ((prefs (preferences->list (safe-read-octets (-fx len 1) p) byte->compression-algo))) (trace-item "Preferred Compression algo id: " (map compression-algo->byte prefs)) (trace-item "Preferred Compression algo name: " (map (lambda (p) (format "~s [~s]" p (compression-algo->human-readable p))) prefs)) (instantiate::PGP-Signature-Sub-Preferred-Compression (critical? critical?) (algos prefs)))) ((preferred-key-server) (let ((key-server (safe-read-octets (-fx len 1) p))) (trace-item "Preferred Key-server:" key-server) (instantiate::PGP-Signature-Sub-Preferred-Key-Server (critical? critical?) (server key-server)))) ((primary-id?) (let ((prim-id? (not (=fx 0 (safe-read-octet p))))) (trace-item "Primary Id?: " prim-id?) (instantiate::PGP-Signature-Sub-Primary-ID (critical? critical?) (primary? prim-id?)))) ((policy) (let ((policy (safe-read-octets (-fx len 1) p))) (trace-item "Policy: " policy) (instantiate::PGP-Signature-Sub-Policy (critical? critical?) (url policy)))) ((signer-ID) (let ((id (safe-read-octets (-fx len 1) p))) (trace-item "Signer id: " id) (instantiate::PGP-Signature-Sub-Signer-ID (critical? critical?) (id id)))) ((revocation-reason) (let* ((code-byte (safe-read-octet p)) (code (byte->revocation-code code-byte)) (reason (safe-read-octets (-fx len 2) p))) (trace-item "Revocation code: " code-byte " " (revocation-code->human-readable code)) (trace-item "Reason: " reason) (instantiate::PGP-Signature-Sub-Revocation-Reason (critical? critical?) (code code) (reason reason)))) ((issuer-fpr) (trace-item "Issuer fingerprint") (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data (safe-read-octets (-fx len 1) p)))) (else (trace-item "Generic") (instantiate::PGP-Signature-Sub-Generic (critical? critical?) (type type) (data (safe-read-octets (-fx len 1) p))))))))) (define (decode-sub-packets p::input-port) (with-trace 'pgp "decode-sub-packets" (let loop ((packets '())) (let ((c (peek-char p))) (trace-item "i=" (input-port-position p) "/" (input-port-length p)) (if (eof-object? c) (reverse! packets) (let ((sub-packet (decode-sub-packet p))) (loop (cons sub-packet packets)))))))) (define (decode-signature-v4 p::input-port version) (define (find-creation-date sps) (let ((pkt (any (lambda (pkt) (and (isa? pkt PGP-Signature-Sub-Creation-Time) pkt)) sps))) (when (not pkt) (openpgp-error "decode-signature-v4" "invalid signature. Can't find obligatory creation-time sub-packet" #f)) (with-access::PGP-Signature-Sub-Creation-Time pkt (creation-date) creation-date))) (define (find-issuer sps) (let ((pkt (any (lambda (pkt) (and (isa? pkt PGP-Signature-Sub-ID) pkt)) sps))) (when (not pkt) (openpgp-error "decode-signature-v4" "invalid signature. Can't find obligatory issuer id sub-packet" #f)) (with-access::PGP-Signature-Sub-ID pkt (key-id) key-id))) (with-trace 'pgp "decode-signature-v4" (let* ((signature-type-byte (safe-read-octet p)) (signature-type (byte->signature-type signature-type-byte)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) (hashed-spd-len-str (safe-read-octets 2 p)) (hashed-spd-len (scalar->fixnum hashed-spd-len-str)) (hashed-spd (safe-read-octets hashed-spd-len p)) (dumm1 (trace-item "*- decoding hashed subpackets=" (string-for-read hashed-spd))) (sps1 (decode-sub-packets (open-input-string hashed-spd))) (creation-date (find-creation-date sps1)) (dumm2 (trace-item "creation-date=" creation-date)) (unhashed-spd-len (decode-scalar p 2)) (dumm1 (trace-item "*- decoding unhashed subpackets")) (sps2 (decode-sub-packets (length-limited-pipe-port p unhashed-spd-len))) (sps1+sps2 (append sps2 sps1)) (issuer (find-issuer sps1+sps2)) (left-hash (safe-read-octets 2 p))) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "hashed-subpacket-data: " (str->hex-string hashed-spd)) ( trace - item " sps2 : " ) sps2 ) (trace-item "left-hash: " (str->hex-string left-hash)) (let* ((signed-packet-prefix-len (+fx 6 hashed-spd-len)) (signed-packet-prefix (make-string signed-packet-prefix-len)) (hash-trailer (make-string 6))) (string-set! signed-packet-prefix 0 (integer->char-ur version)) (string-set! signed-packet-prefix 1 (integer->char-ur signature-type-byte)) (string-set! signed-packet-prefix 2 (integer->char-ur public-key-algo-byte)) (string-set! signed-packet-prefix 3 (integer->char-ur hash-algo-byte)) (blit-string! hashed-spd-len-str 0 signed-packet-prefix 4 2) (blit-string! hashed-spd 0 signed-packet-prefix 6 hashed-spd-len) trailer magic ... ( see 5.2.4 , page 31 of RFC2440 ) (string-set! hash-trailer 0 (integer->char-ur version)) (string-set! hash-trailer 1 (integer->char-ur #xFF)) (blit-string! (fixnum->scalar signed-packet-prefix-len 4) 0 hash-trailer 2 4) (trace-item "signed-packet-prefix: " (str->hex-string signed-packet-prefix)) (trace-item "hash-trailer: " (str->hex-string hash-trailer)) (let ((key-data (case public-key-algo ((rsa-encrypt/sign rsa-sign) (let ((m**d (decode-mpi p))) (trace-item "RSA m**d: " m**d) m**d)) ((dsa) (let* ((r (decode-mpi p)) (s (decode-mpi p))) (trace-item "DSA r: " r) (trace-item "DSA s: " s) (cons r s))) (else (openpgp-error "decode-signature" "public key algorithm not implemented" (list public-key-algo-byte (public-key-algo->human-readable public-key-algo))))))) (instantiate::PGP-Signature-v4-Packet (version 4) (signature-type signature-type) (creation-date creation-date) (issuer issuer) (public-key-algo public-key-algo) (hash-algo hash-algo) (signature key-data) (signed-packet-prefix signed-packet-prefix) (hash-trailer hash-trailer) (left-hash left-hash) (secure-sub-packets sps1) (insecure-sub-packets sps2))))))) 5.3 Symmetric - Key Encrypted Session - Key Packets ( Tag 3 ) (define (decode-symmetric-key-encrypted-session-key cpp) (let* ((version (safe-read-octet cpp)) (symmetric-algo-byte (safe-read-octet cpp)) (symmetric-algo (byte->symmetric-key-algo symmetric-algo-byte)) (s2k (decode-s2k cpp)) (encrypted-session-key (read-string cpp))) (instantiate::PGP-Symmetric-Key-Encrypted-Session-Key-Packet (version version) (algo symmetric-algo) (s2k s2k) (encrypted-session-key (if (string-null? encrypted-session-key) #f encrypted-session-key))))) 5.4 One - Pass Signature Packets ( Tag 4 ) (define (decode-one-pass-signature p::input-port) (with-trace 'pgp "decode-one-pass-signature" (let* ((version (safe-read-octet p)) (signature-type-byte (safe-read-octet p)) (signature-type (byte->signature-type signature-type-byte)) (hash-algo-byte (safe-read-octet p)) (hash-algo (byte->hash-algo hash-algo-byte)) (public-key-algo-byte (safe-read-octet p)) (public-key-algo (byte->public-key-algo public-key-algo-byte)) (id (safe-read-octets 8 p)) (nested-signature? (zerofx? (safe-read-octet p)))) (trace-item "signature type: " signature-type-byte " " (signature-type->human-readable signature-type)) (trace-item "public-key-algo: " public-key-algo-byte " " (public-key-algo->human-readable public-key-algo)) (trace-item "hash-algo: " hash-algo-byte " " (hash-algo->human-readable hash-algo)) (trace-item "id: " (str->hex-string id)) (trace-item "nested-sig?: " nested-signature?) (instantiate::PGP-One-Pass-Signature-Packet (version version) (signature-type signature-type) (issuer id) (public-key-algo public-key-algo) (hash-algo hash-algo) (contains-nested-sig? nested-signature?))))) 5.5 Key Material Packet 5.5.1.1 Public Key Packet (define make-public-rsa-key (lambda (m e) (instantiate::Rsa-Key (modulus m) (exponent e)))) (define make-public-dsa-key (lambda (p q g y) (instantiate::Dsa-Key (p p) (q q) (g g) (y y)))) (define make-public-elgamal-key (lambda (p g y) (instantiate::ElGamal-Key (p p) (g g) (y y)))) (define *dummy-date* (current-date)) (define (decode-public-key p::input-port) (let* ((version (safe-read-octet p)) (kp (instantiate::PGP-Public-Key-Packet (version version) (algo 'not-yet-set) (valid-days #f) (key #f)))) (case version ((2 3 4) 'ok) (else (openpgp-error "decode-public-key" "version of public key file not supported" version))) (decode/fill-key kp version p) kp)) (define (decode/fill-key kp::PGP-Key-Packet version p::input-port) (with-trace 'pgp "decode/fill-key" (let ((cd (decode-time p))) (trace-item "creation-date: " cd) (with-access::PGP-Key-Packet kp (creation-date) (set! creation-date cd))) (when (or (=fx version 2) (=fx version 3)) (trace-item "valid days: " vd) (with-access::PGP-Key-Packet kp (valid-days) (set! valid-days vd)))) (let* ((algo-byte (safe-read-octet p)) (algo (byte->public-key-algo algo-byte))) (when (and (or (=fx version 2) (=fx version 3)) (not (or (eq? algo 'rsa-encrypt/sign) (eq? algo 'rsa-encrypt) (eq? algo 'rsa-sign)))) (openpgp-error "decode key v3" "only RSA is supported for version 3 keys" (public-key-algo->human-readable algo))) (trace-item "algo: " algo " " (public-key-algo->human-readable algo)) (with-access::PGP-Key-Packet kp ((kalgo algo)) (set! kalgo algo)) (case algo ((rsa-encrypt/sign rsa-encrypt rsa-sign) (let* ((modulus (decode-mpi p)) (exponent (decode-mpi p)) (k (make-public-rsa-key modulus exponent))) (trace-item "modulus: " modulus) (trace-item "exponent: " exponent) (with-access::PGP-Key-Packet kp (key) (set! key k)))) DSA (let* ((port p) (p (decode-mpi port)) (q (decode-mpi port)) (g (decode-mpi port)) (y (decode-mpi port)) (k (make-public-dsa-key p q g y))) (trace-item "p: " p) (trace-item "q: " q) (trace-item "g: " g) (trace-item "y: " y) (with-access::PGP-Key-Packet kp (key) (set! key k)))) ((elgamal-encrypt elgamal-encrypt/sign) (let* ((port p) (p (decode-mpi port)) (g (decode-mpi port)) (y (decode-mpi port)) (k (make-public-elgamal-key p g y))) (trace-item "p: " p) (trace-item "g: " g) (trace-item "y: " y) (with-access::PGP-Key-Packet kp (key) (set! key k)))) (else (openpgp-error "decode-key" "public key algorithm must be RSA, DSA or ElGamal" (public-key-algo->human-readable algo))))))) (define (decode-public-subkey cpp) (let ((p (decode-public-key cpp))) (with-access::PGP-Public-Key-Packet p (subkey?) (set! subkey? #t)) p)) 5.5.1.3 Secret Key Packet (define (decode-secret-key cpp::input-port) (with-trace 'pgp "decode-secreate-key" (let* ((version (safe-read-octet cpp)) (kp (instantiate::PGP-Secret-Key-Packet (version version) (algo 'not-yet-set) (creation-date *dummy-date*) (valid-days #f) (key #f) (password-protected-secret-key-data "")))) (case version ((3 4) (decode/fill-key kp version cpp)) (else (openpgp-error "decode-secret-key" "version incompatible with this implementation" version))) (let ((secret-data (read-string cpp))) (trace-item "secret data: " (str->hex-string secret-data)) (with-access::PGP-Secret-Key-Packet kp (password-protected-secret-key-data) (set! password-protected-secret-key-data secret-data)) kp)))) 5.5.1.4 Secret Subkey Packet (define (decode-secret-subkey cpp) (let ((p (decode-secret-key cpp))) (with-access::PGP-Secret-Key-Packet p (subkey?) (set! subkey? #t)) p)) 5.6 Compressed Data Packet (define (decode-compressed-data cpp ignore-bad-packets::bool) (with-trace 'pgp "decode-compressed-data" (let* ((algo-byte (safe-read-octet cpp)) (algo (byte->compression-algo algo-byte))) (trace-item "Compression Algorithm: " algo " " (compression-algo->human-readable algo)) (case algo ((uncompressed) (decode-packet cpp ignore-bad-packets)) ((ZIP) (let ((pz (port->inflate-port cpp))) (unwind-protect (instantiate::PGP-Compressed-Packet (packets (decode-packets pz ignore-bad-packets))) (close-input-port pz)))) ((ZLIB) (let ((pz (port->zlib-port cpp))) (unwind-protect (instantiate::PGP-Compressed-Packet (packets (decode-packets pz ignore-bad-packets))) (close-input-port pz)))) (else (openpgp-error "decode compressed" "Can't decompresse data" algo)))))) 5.7 Symmetrically Encrypted Data Packet ( Tag 9 ) (define (decode-symmetrically-encrypted-data cpp) (instantiate::PGP-Symmetrically-Encrypted-Packet (data (read-string cpp)))) 5.8 Marker Packet ( Obsolete Literal Packet ) ( Tag 10 ) (define (decode-marker cpp) (let* ((p (safe-read-octet cpp)) (g (safe-read-octet cpp)) (p2 (safe-read-octet cpp))) (unless (and (=fx p #x50) (=fx g #x47) (=fx p2 #x50) (eof-object? (peek-char cpp))) (openpgp-error "decode-marker" "bad marker packet" #f)) (instantiate::PGP-Marker-Packet))) 5.9 Literal Data Packet ( Tag 11 ) (define (decode-literal-data p::input-port) (with-trace 'pgp "decode-literal-data" (let* ((format-byte (safe-read-octet p)) (format (byte->literal-format format-byte)) (file-len (safe-read-octet p)) (file-name (safe-read-octets file-len p)) (sensitive? (string=? file-name "_CONSOLE")) (creation-date (decode-time p #t)) (data (read-string p))) (trace-item "format: " format-byte " " (literal-format->human-readable format)) (trace-item "file: " file-name) (trace-item "creation-date: " creation-date) (trace-item "data: \n-------\n" data "\n---------\n") (instantiate::PGP-Literal-Packet (format format) (for-your-eyes-only? sensitive?) (file-name (and (not sensitive?) file-name)) (creation-date creation-date) (data data))))) 5.10 Trust Packet ( Tag 12 ) (define (decode-trust cpp) (read-string cpp) (warning "ignoring trust packet") (instantiate::PGP-Trust-Packet)) 5.11 User ID Packet ( Tag 13 ) (define (decode-user-id cpp) (with-trace 'pgp "decode-user-id" (let ((user-id (read-string cpp))) (trace-item "User ID: " user-id) (instantiate::PGP-ID-Packet (data user-id))))) 5.12 User ID Packet ( Tag 17 ) (define (decode-user-attribute cpp) (with-trace 'pgp "decode-user-attribute" (let ((user-attr (read-string cpp))) (trace-item "User ATTR: " (string-for-read user-attr)) (instantiate::PGP-Attribute-Packet (data user-attr))))) 5.13 Sym . Encrypted Integrity Protected Data Packet ( Tag 18 ) (define (decode-mdc-sym-encrypted cpp) (with-trace 'pgp "decode-mdc-sym-encrypted" (trace-item "cpp=" cpp) (let* ((version (safe-read-octet cpp)) (data (read-string cpp))) (trace-item "version: " version) (trace-item "len: " (string-length data)) (instantiate::PGP-MDC-Symmetrically-Encrypted-Packet (version version) (data data))))) 5.14 Modification Detection Code Packet ( Tag 19 ) (define (decode-mdc cpp) (with-trace 'pgp "decode-mdc" (let ((str (read-string cpp))) (when (not (=fx (string-length str) 20)) (openpgp-error 'decode-mdc "Bad Modification Detection Code Packet" #f)) (trace-item "sha1 mdc: " (str->hex-string str)) (instantiate::PGP-MDC-Packet (hash str)))))
744fc4dcda9aa27fad9465f45ce9b0dfb4d15c5799a286ada245d8e21f4643d0
luminus-framework/examples
env.clj
(ns multi-client-ws-http-kit.env (:require [selmer.parser :as parser] [clojure.tools.logging :as log] [multi-client-ws-http-kit.dev-middleware :refer [wrap-dev]])) (def defaults {:init (fn [] (parser/cache-off!) (log/info "\n-=[multi-client-ws-http-kit started successfully using the development profile]=-")) :stop (fn [] (log/info "\n-=[multi-client-ws-http-kit has shut down successfully]=-")) :middleware wrap-dev})
null
https://raw.githubusercontent.com/luminus-framework/examples/cbeee2fef8f457a6a6bac2cae0b640370ae2499b/multi-client-ws-http-kit/env/dev/clj/multi_client_ws_http_kit/env.clj
clojure
(ns multi-client-ws-http-kit.env (:require [selmer.parser :as parser] [clojure.tools.logging :as log] [multi-client-ws-http-kit.dev-middleware :refer [wrap-dev]])) (def defaults {:init (fn [] (parser/cache-off!) (log/info "\n-=[multi-client-ws-http-kit started successfully using the development profile]=-")) :stop (fn [] (log/info "\n-=[multi-client-ws-http-kit has shut down successfully]=-")) :middleware wrap-dev})
8ab76b5c93ae153ba24b64902ec4f0e3cce4880c4aad00d85e7c0d621800ae3e
exoscale/clojure-kubernetes-client
v1_ceph_fs_persistent_volume_source.clj
(ns clojure-kubernetes-client.specs.v1-ceph-fs-persistent-volume-source (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-secret-reference :refer :all] ) (:import (java.io File))) (declare v1-ceph-fs-persistent-volume-source-data v1-ceph-fs-persistent-volume-source) (def v1-ceph-fs-persistent-volume-source-data { (ds/req :monitors) (s/coll-of string?) (ds/opt :path) string? (ds/opt :readOnly) boolean? (ds/opt :secretFile) string? (ds/opt :secretRef) v1-secret-reference (ds/opt :user) string? }) (def v1-ceph-fs-persistent-volume-source (ds/spec {:name ::v1-ceph-fs-persistent-volume-source :spec v1-ceph-fs-persistent-volume-source-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_ceph_fs_persistent_volume_source.clj
clojure
(ns clojure-kubernetes-client.specs.v1-ceph-fs-persistent-volume-source (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-secret-reference :refer :all] ) (:import (java.io File))) (declare v1-ceph-fs-persistent-volume-source-data v1-ceph-fs-persistent-volume-source) (def v1-ceph-fs-persistent-volume-source-data { (ds/req :monitors) (s/coll-of string?) (ds/opt :path) string? (ds/opt :readOnly) boolean? (ds/opt :secretFile) string? (ds/opt :secretRef) v1-secret-reference (ds/opt :user) string? }) (def v1-ceph-fs-persistent-volume-source (ds/spec {:name ::v1-ceph-fs-persistent-volume-source :spec v1-ceph-fs-persistent-volume-source-data}))
a8f3a8dff6e2307f6f679fce60030d03c0a9bf83cc73567d3e152ead5fa1e4f8
emqx/mria
mria_autoclean.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2019 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved . %% 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 %% %% -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. %%-------------------------------------------------------------------- -module(mria_autoclean). -include("mria.hrl"). -export([init/0, check/1]). -record(autoclean, {expiry, timer}). -type(autoclean() :: #autoclean{}). -export_type([autoclean/0]). init() -> case application:get_env(mria, cluster_autoclean) of {ok, Expiry} -> timer_backoff(#autoclean{expiry = Expiry}); undefined -> undefined end. timer_backoff(State = #autoclean{expiry = Expiry}) -> TRef = mria_node_monitor:run_after(Expiry div 4, autoclean), State#autoclean{timer = TRef}. check(State = #autoclean{expiry = Expiry}) -> [maybe_clean(Member, Expiry) || Member <- mria_membership:members(down)], timer_backoff(State). maybe_clean(#member{node = Node, ltime = LTime}, Expiry) -> case expired(LTime, Expiry) of true -> mria:force_leave(Node); false -> ok end. expired(LTime, Expiry) -> timer:now_diff(erlang:timestamp(), LTime) div 1000 > Expiry.
null
https://raw.githubusercontent.com/emqx/mria/3d3b4e2a4da140ad72f85e466ea8cbdbb1f8f72b/src/mria_autoclean.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software 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. --------------------------------------------------------------------
Copyright ( c ) 2019 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(mria_autoclean). -include("mria.hrl"). -export([init/0, check/1]). -record(autoclean, {expiry, timer}). -type(autoclean() :: #autoclean{}). -export_type([autoclean/0]). init() -> case application:get_env(mria, cluster_autoclean) of {ok, Expiry} -> timer_backoff(#autoclean{expiry = Expiry}); undefined -> undefined end. timer_backoff(State = #autoclean{expiry = Expiry}) -> TRef = mria_node_monitor:run_after(Expiry div 4, autoclean), State#autoclean{timer = TRef}. check(State = #autoclean{expiry = Expiry}) -> [maybe_clean(Member, Expiry) || Member <- mria_membership:members(down)], timer_backoff(State). maybe_clean(#member{node = Node, ltime = LTime}, Expiry) -> case expired(LTime, Expiry) of true -> mria:force_leave(Node); false -> ok end. expired(LTime, Expiry) -> timer:now_diff(erlang:timestamp(), LTime) div 1000 > Expiry.
4e891d6ec69057b28f126d3f4c87857ca16f4b0941391b61238c91dc1cda96be
threatgrid/ctim
schema_version_test.cljc
(ns ctim.schemas.schema-version-test (:require #?(:clj [clojure.test :refer [deftest is testing use-fixtures]] :cljs [cljs.test :refer-macros [deftest is testing]]) [ctim.schemas.judgement :as j] [ctim.examples.judgements :as e] [flanders.schema :as fs] [schema.core :as s])) (deftest schema-version-test (testing "an arbitrary schema version string is allowed" (is (s/validate (fs/->schema j/Judgement) (assoc e/judgement-minimal :schema_version "foo")))))
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/schemas/schema_version_test.cljc
clojure
(ns ctim.schemas.schema-version-test (:require #?(:clj [clojure.test :refer [deftest is testing use-fixtures]] :cljs [cljs.test :refer-macros [deftest is testing]]) [ctim.schemas.judgement :as j] [ctim.examples.judgements :as e] [flanders.schema :as fs] [schema.core :as s])) (deftest schema-version-test (testing "an arbitrary schema version string is allowed" (is (s/validate (fs/->schema j/Judgement) (assoc e/judgement-minimal :schema_version "foo")))))
f1eb6d64b848f587a32274891b258c53be28c1093ecdce0889c5f50daab30baa
rizo/snowflake-os
queue.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ I d : queue.mli , v 1.16 2002 - 06 - 27 08:48:26 xleroy Exp $ * First - in first - out queues . This module implements queues ( FIFOs ) , with in - place modification . This module implements queues (FIFOs), with in-place modification. *) type 'a t (** The type of queues containing elements of type ['a]. *) exception Empty * Raised when { ! Queue.take } or { ! } is applied to an empty queue . val create : unit -> 'a t (** Return a new queue, initially empty. *) val add : 'a -> 'a t -> unit (** [add x q] adds the element [x] at the end of the queue [q]. *) val push : 'a -> 'a t -> unit (** [push] is a synonym for [add]. *) val take : 'a t -> 'a * [ take q ] removes and returns the first element in queue [ q ] , or raises [ Empty ] if the queue is empty . or raises [Empty] if the queue is empty. *) val pop : 'a t -> 'a (** [pop] is a synonym for [take]. *) val peek : 'a t -> 'a * [ peek q ] returns the first element in queue [ q ] , without removing it from the queue , or raises [ Empty ] if the queue is empty . it from the queue, or raises [Empty] if the queue is empty. *) val top : 'a t -> 'a (** [top] is a synonym for [peek]. *) val clear : 'a t -> unit (** Discard all elements from a queue. *) val copy : 'a t -> 'a t (** Return a copy of the given queue. *) val is_empty : 'a t -> bool (** Return [true] if the given queue is empty, [false] otherwise. *) val length : 'a t -> int (** Return the number of elements in a queue. *) val iter : ('a -> unit) -> 'a t -> unit (** [iter f q] applies [f] in turn to all elements of [q], from the least recently entered to the most recently entered. The queue itself is unchanged. *) val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b (** [fold f accu q] is equivalent to [List.fold_left f accu l], where [l] is the list of [q]'s elements. The queue remains unchanged. *) val transfer : 'a t -> 'a t -> unit * [ transfer q1 q2 ] adds all of [ q1 ] 's elements at the end of the queue [ q2 ] , then clears [ q1 ] . It is equivalent to the sequence [ iter ( fun x - > add x q2 ) q1 ; clear q1 ] , but runs in constant time . the queue [q2], then clears [q1]. It is equivalent to the sequence [iter (fun x -> add x q2) q1; clear q1], but runs in constant time. *)
null
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/libraries/stdlib/queue.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* * The type of queues containing elements of type ['a]. * Return a new queue, initially empty. * [add x q] adds the element [x] at the end of the queue [q]. * [push] is a synonym for [add]. * [pop] is a synonym for [take]. * [top] is a synonym for [peek]. * Discard all elements from a queue. * Return a copy of the given queue. * Return [true] if the given queue is empty, [false] otherwise. * Return the number of elements in a queue. * [iter f q] applies [f] in turn to all elements of [q], from the least recently entered to the most recently entered. The queue itself is unchanged. * [fold f accu q] is equivalent to [List.fold_left f accu l], where [l] is the list of [q]'s elements. The queue remains unchanged.
, 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 Library General Public License , with $ I d : queue.mli , v 1.16 2002 - 06 - 27 08:48:26 xleroy Exp $ * First - in first - out queues . This module implements queues ( FIFOs ) , with in - place modification . This module implements queues (FIFOs), with in-place modification. *) type 'a t exception Empty * Raised when { ! Queue.take } or { ! } is applied to an empty queue . val create : unit -> 'a t val add : 'a -> 'a t -> unit val push : 'a -> 'a t -> unit val take : 'a t -> 'a * [ take q ] removes and returns the first element in queue [ q ] , or raises [ Empty ] if the queue is empty . or raises [Empty] if the queue is empty. *) val pop : 'a t -> 'a val peek : 'a t -> 'a * [ peek q ] returns the first element in queue [ q ] , without removing it from the queue , or raises [ Empty ] if the queue is empty . it from the queue, or raises [Empty] if the queue is empty. *) val top : 'a t -> 'a val clear : 'a t -> unit val copy : 'a t -> 'a t val is_empty : 'a t -> bool val length : 'a t -> int val iter : ('a -> unit) -> 'a t -> unit val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b val transfer : 'a t -> 'a t -> unit * [ transfer q1 q2 ] adds all of [ q1 ] 's elements at the end of the queue [ q2 ] , then clears [ q1 ] . It is equivalent to the sequence [ iter ( fun x - > add x q2 ) q1 ; clear q1 ] , but runs in constant time . the queue [q2], then clears [q1]. It is equivalent to the sequence [iter (fun x -> add x q2) q1; clear q1], but runs in constant time. *)
b4cfb471b3ff87f06c2dbe0cb1de6cf1b2896a4e942007730e1c2d6ea22b6886
mirage/ocaml-cohttp
connection.ml
exception Retry (** Raised on failed requests that may be safely retried - even on non-idempotent requests. Raised for example on timeout or connection suhtdown by remote end. *) module Make (Net : S.Net) : S.Connection with module Net = Net = struct module Net = Net module IO = Net.IO module Response = Make.Response (IO) module Request = Make.Request (IO) module Header = Cohttp.Header open IO let src = Logs.Src.create "cohttp.lwt.client" ~doc:"Cohttp Lwt client" module Log = (val Logs.src_log src : Logs.LOG) exception Retry = Retry type state = | Connecting of (IO.ic * IO.oc) Lwt.t (* Waiting for the TCP handshake / TLS connection setup *) | Full of (IO.ic * IO.oc) " full - duplex " . May send requests , may be waiting for responses / EOF . | Closing of (IO.ic * IO.oc) (* still in "full-duplex", but no new requests may be queued. * Will shutdown oc as soon as the last request went out. *) | Half of IO.ic (* oc has been closed, waiting for outstanding responses on ic. *) | Closed | Failed of exn [@@warning "-37"] (* enable warning when -conduit/pull/319 is released *) type req_resr = { uri : Uri.t; meth : Cohttp.Code.meth; headers : Header.t; body : Body.t; res_r : (Response.t * Body.t) Lwt.u; } type persistent = [ `True | `False | `Unknown ] type t = { mutable state : state; mutable persistent : persistent; keep alive + Chunked supported ? - > essentially HTTP 1.1 in_flight : req_resr Queue.t (* writer handles and fails this queue *); waiting : req_resr Queue.t (* reader handles and fails this queue *); condition : unit Lwt_condition.t (* watching queues *); finalise : t -> unit Lwt.t; } let length connection = Queue.length connection.in_flight + Queue.length connection.waiting let notify connection = Lwt_condition.wait connection.condition let queue_fail connection q e = Queue.iter (fun { res_r; _ } -> Lwt.wakeup_later_exn res_r e) q; Queue.clear q; Lwt_condition.broadcast_exn connection.condition e let close_with state connection = match connection.state with | Connecting channels -> connection.state <- state; Lwt.cancel channels; Lwt.on_success channels (fun (ic, oc) -> Net.close ic oc); Lwt_condition.broadcast connection.condition () | Closing (ic, oc) | Full (ic, oc) -> connection.state <- state; Net.close ic oc; Lwt_condition.broadcast connection.condition () | Half ic -> connection.state <- state; Net.close_in ic; Lwt_condition.broadcast connection.condition () | Closed | Failed _ -> () let close = close_with Closed let shutdown connection = match connection.state with | Connecting channels -> Lwt.async @@ fun () -> channels >>= fun channels -> connection.state <- Closing channels; Lwt.return_unit | Full channels -> connection.state <- Closing channels | Closing _ | Half _ | Closed | Failed _ -> () let is_closed connection = match connection.state with | Full _ -> false | Connecting _ -> false | Closing _ | Half _ -> true | Closed | Failed _ -> true let rec reader connection = match connection.state with | Connecting _ | Failed _ -> assert false | Closed -> Lwt.return_unit | Full (ic, _) | Closing (ic, _) | Half ic -> ( Response.read ic >>= fun res -> match res with | `Ok res -> if connection.persistent = `Unknown && Response.version res = `HTTP_1_1 && not (Header.mem (Response.headers res) "Connection") then connection.persistent <- `True; (* don't take from queue yet, because body may still be in flight *) let { meth; res_r; _ } = Queue.peek connection.in_flight in A response header to a HEAD request is indistinguishable from a * response header to a GET request . Therefore look at the method . * response header to a GET request. Therefore look at the method. *) (if match Response.has_body res with | _ when meth = `HEAD -> false | `No -> false | `Yes | `Unknown -> true then ( let stream = Body.create_stream Response.read_body_chunk (Response.make_body_reader res ic) in (* finalise could run in a thread different from the lwt main thread. * You may therefore not call into Lwt from a finaliser. *) let closed = ref false in Gc.finalise_last (fun () -> if not !closed then Log.warn (fun m -> m "Body not consumed, leaking stream! Refer to \ -cohttp/issues/730 \ for additional details")) stream; Lwt.wakeup_later res_r (res, Body.of_stream stream); Lwt_stream.closed stream >>= fun () -> closed := true; Lwt.return_unit) else ( Lwt.wakeup_later res_r (res, `Empty); Lwt.return_unit)) >>= fun () -> Queue.take connection.in_flight |> ignore; Lwt_condition.broadcast connection.condition (); if connection.persistent = `False then ( close_with Closed connection; Lwt.return_unit) else reader connection | `Eof -> close_with Closed connection; connection.finalise connection >>= fun () -> queue_fail connection connection.in_flight Retry; Lwt.return_unit | `Invalid reason -> let e = Failure ("Cohttp_lwt failed to read response: " ^ reason) in close_with (Failed e) connection; connection.finalise connection >>= fun () -> queue_fail connection connection.in_flight e; Lwt.return_unit) let call connection ?headers ?(body = `Empty) meth uri = let headers = match headers with Some h -> h | None -> Header.init () in match connection.state with | Connecting _ | Full _ -> let res, res_r = Lwt.wait () in Queue.push { uri; meth; headers; body; res_r } connection.waiting; Lwt_condition.broadcast connection.condition (); res | Closing _ | Half _ | Closed | Failed _ -> Lwt.fail Retry let rec writer connection = match connection.state with | Full _ when Queue.is_empty connection.waiting || not (Queue.is_empty connection.in_flight || connection.persistent = `True) -> Lwt.try_bind (fun () -> Lwt_condition.wait connection.condition) (fun _ -> writer connection) (fun _ -> writer connection) | Closing (_ic, _oc) when Queue.is_empty connection.waiting -> (* uncomment when -conduit/pull/319 is released *) Net.close_out oc ; connection.state < - Half ic ; Net.close_out oc; connection.state <- Half ic; *) Lwt.return_unit | Full (ic, oc) | Closing (ic, oc) -> let ({ uri; meth; headers; body; res_r } as work) = Queue.take connection.waiting in select encoding based on ( 1st ) header or ( 2nd ) body (match Header.get_transfer_encoding headers with | Unknown -> ( match Body.transfer_encoding body with | Fixed _ as e -> Lwt.return (e, body) | Chunked as e when connection.persistent = `True -> Lwt.return (e, body) | Chunked (* connection.persistent <> `True *) -> (* We don't know yet whether chunked encoding is supported. * Therefore use fixed length encoding. *) Body.length body >>= fun (length, body) -> Lwt.return (Cohttp.Transfer.Fixed length, body) | Unknown -> assert false) | e -> Lwt.return (e, body)) >>= fun (encoding, body) -> let headers = if match connection.state with | _ when connection.persistent = `False -> true | Closing _ when Queue.is_empty connection.waiting -> true | _ -> false then Header.add_unless_exists headers "Connection" "close" else headers in let req = Request.make ~encoding ~meth ~headers uri in Queue.push work connection.in_flight; Lwt.catch (fun () -> (* try *) Request.write (fun writer -> Body.write_body (Request.write_body writer) body) req oc) (fun e -> (* with *) (* uncomment when -conduit/pull/319 is released *) ( try Net.close_out oc with _ - > ( ) ) ; connection.state < - Half ic ; (try Net.close_out oc with _ -> ()); connection.state <- Half ic; *) connection.state <- Closing (ic, oc); Lwt.wakeup_later_exn res_r e; queue_fail connection connection.waiting Retry; Lwt.return_unit) >>= fun () -> if connection.persistent = `False then ( (* uncomment when -conduit/pull/319 is released *) Net.close_out oc ; connection.state < - Half ic ; Net.close_out oc; connection.state <- Half ic; *) connection.state <- Closing (ic, oc); queue_fail connection connection.waiting Retry; Lwt.return_unit) else writer connection | Closed -> queue_fail connection connection.waiting Retry; Lwt.return_unit | Failed e -> queue_fail connection connection.waiting e; Lwt.return_unit | Half _ -> Lwt.return_unit | Connecting _ -> assert false let create ?(finalise = fun _ -> Lwt.return_unit) ?persistent ?(ctx = Net.default_ctx) endp = let persistent = match persistent with | None -> `Unknown | Some true -> `True | Some false -> `False in let channels = Net.connect_endp ~ctx endp >>= fun (_, ic, oc) -> return (ic, oc) in let connection = { finalise; in_flight = Queue.create (); waiting = Queue.create (); state = Connecting channels; condition = Lwt_condition.create (); persistent; } in Lwt.on_any channels (fun channels -> connection.state <- Full channels; Lwt.async (fun () -> reader connection); Lwt.async (fun () -> writer connection)) (fun e -> connection.state <- Failed e); connection let connect ?finalise ?persistent ?ctx uri = let connection = create ?finalise ?persistent ?ctx uri in match connection.state with | Connecting channels -> channels >>= fun _ -> Lwt.return connection | _ -> Lwt.return connection end
null
https://raw.githubusercontent.com/mirage/ocaml-cohttp/628d8716b22bb7933863dd584673745c974707be/cohttp-lwt/src/connection.ml
ocaml
* Raised on failed requests that may be safely retried - even on non-idempotent requests. Raised for example on timeout or connection suhtdown by remote end. Waiting for the TCP handshake / TLS connection setup still in "full-duplex", but no new requests may be queued. * Will shutdown oc as soon as the last request went out. oc has been closed, waiting for outstanding responses on ic. enable warning when -conduit/pull/319 is released writer handles and fails this queue reader handles and fails this queue watching queues don't take from queue yet, because body may still be in flight finalise could run in a thread different from the lwt main thread. * You may therefore not call into Lwt from a finaliser. uncomment when -conduit/pull/319 is released connection.persistent <> `True We don't know yet whether chunked encoding is supported. * Therefore use fixed length encoding. try with uncomment when -conduit/pull/319 is released uncomment when -conduit/pull/319 is released
exception Retry module Make (Net : S.Net) : S.Connection with module Net = Net = struct module Net = Net module IO = Net.IO module Response = Make.Response (IO) module Request = Make.Request (IO) module Header = Cohttp.Header open IO let src = Logs.Src.create "cohttp.lwt.client" ~doc:"Cohttp Lwt client" module Log = (val Logs.src_log src : Logs.LOG) exception Retry = Retry type state = | Connecting of (IO.ic * IO.oc) Lwt.t | Full of (IO.ic * IO.oc) " full - duplex " . May send requests , may be waiting for responses / EOF . | Closing of (IO.ic * IO.oc) | Half of IO.ic | Closed | Failed of exn [@@warning "-37"] type req_resr = { uri : Uri.t; meth : Cohttp.Code.meth; headers : Header.t; body : Body.t; res_r : (Response.t * Body.t) Lwt.u; } type persistent = [ `True | `False | `Unknown ] type t = { mutable state : state; mutable persistent : persistent; keep alive + Chunked supported ? - > essentially HTTP 1.1 finalise : t -> unit Lwt.t; } let length connection = Queue.length connection.in_flight + Queue.length connection.waiting let notify connection = Lwt_condition.wait connection.condition let queue_fail connection q e = Queue.iter (fun { res_r; _ } -> Lwt.wakeup_later_exn res_r e) q; Queue.clear q; Lwt_condition.broadcast_exn connection.condition e let close_with state connection = match connection.state with | Connecting channels -> connection.state <- state; Lwt.cancel channels; Lwt.on_success channels (fun (ic, oc) -> Net.close ic oc); Lwt_condition.broadcast connection.condition () | Closing (ic, oc) | Full (ic, oc) -> connection.state <- state; Net.close ic oc; Lwt_condition.broadcast connection.condition () | Half ic -> connection.state <- state; Net.close_in ic; Lwt_condition.broadcast connection.condition () | Closed | Failed _ -> () let close = close_with Closed let shutdown connection = match connection.state with | Connecting channels -> Lwt.async @@ fun () -> channels >>= fun channels -> connection.state <- Closing channels; Lwt.return_unit | Full channels -> connection.state <- Closing channels | Closing _ | Half _ | Closed | Failed _ -> () let is_closed connection = match connection.state with | Full _ -> false | Connecting _ -> false | Closing _ | Half _ -> true | Closed | Failed _ -> true let rec reader connection = match connection.state with | Connecting _ | Failed _ -> assert false | Closed -> Lwt.return_unit | Full (ic, _) | Closing (ic, _) | Half ic -> ( Response.read ic >>= fun res -> match res with | `Ok res -> if connection.persistent = `Unknown && Response.version res = `HTTP_1_1 && not (Header.mem (Response.headers res) "Connection") then connection.persistent <- `True; let { meth; res_r; _ } = Queue.peek connection.in_flight in A response header to a HEAD request is indistinguishable from a * response header to a GET request . Therefore look at the method . * response header to a GET request. Therefore look at the method. *) (if match Response.has_body res with | _ when meth = `HEAD -> false | `No -> false | `Yes | `Unknown -> true then ( let stream = Body.create_stream Response.read_body_chunk (Response.make_body_reader res ic) in let closed = ref false in Gc.finalise_last (fun () -> if not !closed then Log.warn (fun m -> m "Body not consumed, leaking stream! Refer to \ -cohttp/issues/730 \ for additional details")) stream; Lwt.wakeup_later res_r (res, Body.of_stream stream); Lwt_stream.closed stream >>= fun () -> closed := true; Lwt.return_unit) else ( Lwt.wakeup_later res_r (res, `Empty); Lwt.return_unit)) >>= fun () -> Queue.take connection.in_flight |> ignore; Lwt_condition.broadcast connection.condition (); if connection.persistent = `False then ( close_with Closed connection; Lwt.return_unit) else reader connection | `Eof -> close_with Closed connection; connection.finalise connection >>= fun () -> queue_fail connection connection.in_flight Retry; Lwt.return_unit | `Invalid reason -> let e = Failure ("Cohttp_lwt failed to read response: " ^ reason) in close_with (Failed e) connection; connection.finalise connection >>= fun () -> queue_fail connection connection.in_flight e; Lwt.return_unit) let call connection ?headers ?(body = `Empty) meth uri = let headers = match headers with Some h -> h | None -> Header.init () in match connection.state with | Connecting _ | Full _ -> let res, res_r = Lwt.wait () in Queue.push { uri; meth; headers; body; res_r } connection.waiting; Lwt_condition.broadcast connection.condition (); res | Closing _ | Half _ | Closed | Failed _ -> Lwt.fail Retry let rec writer connection = match connection.state with | Full _ when Queue.is_empty connection.waiting || not (Queue.is_empty connection.in_flight || connection.persistent = `True) -> Lwt.try_bind (fun () -> Lwt_condition.wait connection.condition) (fun _ -> writer connection) (fun _ -> writer connection) | Closing (_ic, _oc) when Queue.is_empty connection.waiting -> Net.close_out oc ; connection.state < - Half ic ; Net.close_out oc; connection.state <- Half ic; *) Lwt.return_unit | Full (ic, oc) | Closing (ic, oc) -> let ({ uri; meth; headers; body; res_r } as work) = Queue.take connection.waiting in select encoding based on ( 1st ) header or ( 2nd ) body (match Header.get_transfer_encoding headers with | Unknown -> ( match Body.transfer_encoding body with | Fixed _ as e -> Lwt.return (e, body) | Chunked as e when connection.persistent = `True -> Lwt.return (e, body) Body.length body >>= fun (length, body) -> Lwt.return (Cohttp.Transfer.Fixed length, body) | Unknown -> assert false) | e -> Lwt.return (e, body)) >>= fun (encoding, body) -> let headers = if match connection.state with | _ when connection.persistent = `False -> true | Closing _ when Queue.is_empty connection.waiting -> true | _ -> false then Header.add_unless_exists headers "Connection" "close" else headers in let req = Request.make ~encoding ~meth ~headers uri in Queue.push work connection.in_flight; Lwt.catch (fun () -> Request.write (fun writer -> Body.write_body (Request.write_body writer) body) req oc) (fun e -> ( try Net.close_out oc with _ - > ( ) ) ; connection.state < - Half ic ; (try Net.close_out oc with _ -> ()); connection.state <- Half ic; *) connection.state <- Closing (ic, oc); Lwt.wakeup_later_exn res_r e; queue_fail connection connection.waiting Retry; Lwt.return_unit) >>= fun () -> if connection.persistent = `False then ( Net.close_out oc ; connection.state < - Half ic ; Net.close_out oc; connection.state <- Half ic; *) connection.state <- Closing (ic, oc); queue_fail connection connection.waiting Retry; Lwt.return_unit) else writer connection | Closed -> queue_fail connection connection.waiting Retry; Lwt.return_unit | Failed e -> queue_fail connection connection.waiting e; Lwt.return_unit | Half _ -> Lwt.return_unit | Connecting _ -> assert false let create ?(finalise = fun _ -> Lwt.return_unit) ?persistent ?(ctx = Net.default_ctx) endp = let persistent = match persistent with | None -> `Unknown | Some true -> `True | Some false -> `False in let channels = Net.connect_endp ~ctx endp >>= fun (_, ic, oc) -> return (ic, oc) in let connection = { finalise; in_flight = Queue.create (); waiting = Queue.create (); state = Connecting channels; condition = Lwt_condition.create (); persistent; } in Lwt.on_any channels (fun channels -> connection.state <- Full channels; Lwt.async (fun () -> reader connection); Lwt.async (fun () -> writer connection)) (fun e -> connection.state <- Failed e); connection let connect ?finalise ?persistent ?ctx uri = let connection = create ?finalise ?persistent ?ctx uri in match connection.state with | Connecting channels -> channels >>= fun _ -> Lwt.return connection | _ -> Lwt.return connection end
a15f41655e9470d796a2b4624b0cea9ed723cf076720a9ec4719dd7e875ad387
ocaml-multicore/parafuzz
test1.mli
external mycallback1 : ('a -> 'b) -> 'a -> 'b = "mycallback1" external mycallback2 : ('a -> 'b -> 'c) -> 'a -> 'b -> 'c = "mycallback2" external mycallback3 : ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'c -> 'd = "mycallback3" external mycallback4 : ('a -> 'b -> 'c -> 'd -> 'e) -> 'a -> 'b -> 'c -> 'd -> 'e = "mycallback4" val tak : int * int * int -> int val tak2 : int -> int * int -> int val tak3 : int -> int -> int -> int val tak4 : int -> int -> int -> int -> int val raise_exit : unit -> unit val trapexit : unit -> int external mypushroot : 'a -> ('b -> 'c) -> 'b -> 'a = "mypushroot" external mycamlparam : 'a -> ('b -> 'c) -> 'b -> 'a = "mycamlparam" val tripwire : (string -> (unit -> int) -> unit -> 'a) -> 'a val sighandler : 'a -> unit external unix_getpid : unit -> int = "unix_getpid" [@@noalloc] external unix_kill : int -> int -> unit = "unix_kill" [@@noalloc] val callbacksig : unit -> string
null
https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/testsuite/tests/callback/test1.mli
ocaml
external mycallback1 : ('a -> 'b) -> 'a -> 'b = "mycallback1" external mycallback2 : ('a -> 'b -> 'c) -> 'a -> 'b -> 'c = "mycallback2" external mycallback3 : ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'c -> 'd = "mycallback3" external mycallback4 : ('a -> 'b -> 'c -> 'd -> 'e) -> 'a -> 'b -> 'c -> 'd -> 'e = "mycallback4" val tak : int * int * int -> int val tak2 : int -> int * int -> int val tak3 : int -> int -> int -> int val tak4 : int -> int -> int -> int -> int val raise_exit : unit -> unit val trapexit : unit -> int external mypushroot : 'a -> ('b -> 'c) -> 'b -> 'a = "mypushroot" external mycamlparam : 'a -> ('b -> 'c) -> 'b -> 'a = "mycamlparam" val tripwire : (string -> (unit -> int) -> unit -> 'a) -> 'a val sighandler : 'a -> unit external unix_getpid : unit -> int = "unix_getpid" [@@noalloc] external unix_kill : int -> int -> unit = "unix_kill" [@@noalloc] val callbacksig : unit -> string
fa5b78550a0e829960392d669a100675d37522477f1a2ae98f6aa8b85b5e2516
zachallaun/datomic-cljs
macros.clj
(ns datomic-cljs.macros) (defmacro >!x "The same as (do (>! c val) (close! c))" [c val] `(let [c# ~c] (cljs.core.async/>! c# ~val) (cljs.core.async/close! c#))) (defmacro <? "Takes a value from a core.async channel, throwing the value if it is a js/Error." [c] `(let [val# (cljs.core.async/<! ~c)] (if (instance? js/Error val#) (throw val#) val#)))
null
https://raw.githubusercontent.com/zachallaun/datomic-cljs/a2accf1d999b7d6a554a9322f52b230eae1b58b3/src/datomic_cljs/macros.clj
clojure
(ns datomic-cljs.macros) (defmacro >!x "The same as (do (>! c val) (close! c))" [c val] `(let [c# ~c] (cljs.core.async/>! c# ~val) (cljs.core.async/close! c#))) (defmacro <? "Takes a value from a core.async channel, throwing the value if it is a js/Error." [c] `(let [val# (cljs.core.async/<! ~c)] (if (instance? js/Error val#) (throw val#) val#)))
f4bb88b7410a217c8427c30949512495d924bcfbb70272d0e0e984efc1bbd5db
kupl/VeriSmart-public
makeCfg.ml
open Lang open Options let nodesof : cfg -> node list = fun g -> G.fold_vertex (fun x l -> x :: l) g.graph [] (* unconditionally add edges *) let add_edge : node -> node -> cfg -> cfg = fun n1 n2 g -> {g with graph = G.add_edge g.graph n1 n2} let remove_edge : node -> node -> cfg -> cfg = fun n1 n2 g -> {g with graph = G.remove_edge g.graph n1 n2} let add_node : node -> cfg -> cfg = fun n g -> {g with graph = G.add_vertex g.graph n} let remove_node : node -> cfg -> cfg = fun n g -> { g with graph = G.remove_vertex g.graph n; stmt_map = BatMap.remove n g.stmt_map; outpreds_of_lh = BatSet.remove n g.outpreds_of_lh; lh_set = BatSet.remove n g.lh_set; lx_set = BatSet.remove n g.lx_set; continue_set = BatSet.remove n g.continue_set; break_set = BatSet.remove n g.break_set; } let fold_node f g acc = G.fold_vertex f g.graph acc let fold_edges f g acc = G.fold_edges f g.graph acc let find_stmt : node -> cfg -> stmt = fun n g -> try if n = Node.ENTRY || n = Node.EXIT then Skip else BatMap.find n g.stmt_map with _ -> raise (Failure ("No stmt found in the given node " ^ Node.to_string n)) let is_undef_call : FuncMap.t -> stmt -> bool = fun fmap stmt -> match stmt with | _ when is_external_call stmt -> false | Call (lvop,e,args,ethop,gasop,loc,_) when FuncMap.is_undef e (List.map get_type_exp args) fmap -> true | _ -> false let is_internal_call : FuncMap.t -> id list -> stmt -> bool = fun fmap cnames stmt -> match stmt with | _ when is_external_call stmt -> false | Call (lvop,e,args,ethop,gasop,loc,_) when is_undef_call fmap stmt -> false | Call (_,Lv (Var (f,_)),_,_,_,_,_) -> true | Call (_,Lv (MemberAccess (Lv (Var (x,_)),_,_,_)),_,_,_,_,_) when List.mem x cnames -> true | _ -> false let is_internal_call_node : FuncMap.t -> id list -> node -> cfg -> bool = fun fmap cnames n g -> is_internal_call fmap cnames (find_stmt n g) let is_external_call_node : node -> cfg -> bool = fun n g -> is_external_call (find_stmt n g) let add_stmt : node -> stmt -> cfg -> cfg = fun n s g -> {g with stmt_map = BatMap.add n s g.stmt_map} let add_node_stmt : node -> stmt -> cfg -> cfg = fun n s g -> g |> add_node n |> add_stmt n s let pred : node -> cfg -> node list = fun n g -> G.pred g.graph n let succ : node -> cfg -> node list = fun n g -> G.succ g.graph n let rec has_break_cont : stmt -> bool = fun s -> match s with | Assign _ | Decl _ -> false | Seq (s1,s2) -> has_break_cont s1 || has_break_cont s2 | Call _ -> false | Skip -> false | If (e,s1,s2,_) -> has_break_cont s1 || has_break_cont s2 | While _ -> false (* must consider outer loop only. *) | Break | Continue -> true | Return _ | Throw -> false | Assume _ | Assert _ | Assembly _ -> false | PlaceHolder -> assert false | Unchecked (lst,_) -> assert false let rec trans : stmt -> node option -> node option -> (node * cfg) -> (node * cfg) lhop : header of dominant loop , lxop : exit of dominant loop , n : interface node match stmt with | Seq (s,While (e,s')) when has_break_cont s -> (* do-while with 'Break' or 'Continue' in loop-body *) let lh = Node.make () in let lx = Node.make () in let (n1,g1) = trans s (Some lh) (Some lx) (n,g) in let g2 = g1 |> add_node_stmt lh Skip |> add_edge n1 lh in let (n3,g3) = trans (Assume (e, dummy_loc)) (Some lh) (Some lx) (lh,g2) in let (n4,g4) = trans s' (Some lh) (Some lx) (n3,g3) in let g5 = add_edge n4 lh g4 in let (n6,g6) = trans (Assume (UnOp (LNot,e,EType Bool), dummy_loc)) lhop lxop (lh,g5) in let g7 = g6 |> add_node_stmt lx Skip |> add_edge n6 lx in let preds_of_lh = BatSet.of_list (pred lh g2) in let _ = assert (BatSet.mem n1 preds_of_lh) in let g8 = {g7 with outpreds_of_lh = BatSet.union preds_of_lh g7.outpreds_of_lh; lh_set = BatSet.add lh g7.lh_set; lx_set = BatSet.add lx g7.lx_set} in (lx, g8) | Seq (s1,s2) -> trans s2 lhop lxop (trans s1 lhop lxop (n,g)) | If (e,s1,s2,_) -> let loc = match e with BinOp (_,_,_,einfo) -> einfo.eloc | _ -> dummy_loc in let (tn,g1) = trans (Assume (e, loc)) lhop lxop (n,g) in (* tn: true branch assume node *) let (tbn,g2) = trans s1 lhop lxop (tn,g1) in let (fn,g3) = trans (Assume (UnOp (LNot,e,EType Bool), loc)) lhop lxop (n,g2) in (* fn: false branch assume node *) let (fbn,g4) = trans s2 lhop lxop (fn,g3) in let join = Node.make () in let g5 = g4 |> add_node_stmt join Skip |> add_edge tbn join |> add_edge fbn join in (join, g5) | While (e,s) -> let lh = Node.make () in node i d : lh + 1 let g1 = g |> add_node_stmt lh Skip |> add_edge n lh in node i d : lh + 2 let (n3,g3) = trans s (Some lh) (Some lx) (n2,g2) in let g4 = add_edge n3 lh g3 in let (n5,g5) = trans (Assume (UnOp (LNot,e,EType Bool), dummy_loc)) lhop lxop (lh,g4) in let g6 = g5 |> add_node_stmt lx Skip |> add_edge n5 lx in let g7 = {g6 with outpreds_of_lh = BatSet.add n g6.outpreds_of_lh; lh_set = BatSet.add lh g6.lh_set; lx_set = BatSet.add lx g6.lx_set} in (lx, g7) | Break -> let lx = (match lxop with Some lx -> lx | None -> raise (Failure "Loop exit should exist")) in let n' = Node.make () in let g' = g |> add_node_stmt n' Skip |> add_edge n n' |> add_edge n' lx in (n', {g' with break_set = BatSet.add n' g'.break_set}) | Continue -> let lh = (match lhop with Some lh -> lh | None -> raise (Failure "Loop header should exist")) in let n' = Node.make () in let g' = g |> add_node_stmt n' Skip |> add_edge n n' |> add_edge n' lh in (n', {g' with continue_set = BatSet.add n' g'.continue_set}) | Return (eop,_) -> let n' = Node.make () in (Node.exit, g |> add_node_stmt n' stmt |> add_edge n n' |> add_edge n' Node.exit) | Assume (BinOp (LAnd,e1,e2,_), loc) -> let (n1,g1) = trans (Assume (e1,loc)) lhop lxop (n,g) in let (n2,g2) = trans (Assume (e2,loc)) lhop lxop (n1,g1) in (n2,g2) | Assume (BinOp (LOr,e1,e2,einfo), loc) -> let (n1,g1) = trans (Assume (e1,loc)) lhop lxop (n,g) in let neg = Assume (BinOp (LAnd, UnOp (LNot,e1,EType Bool), e2, einfo), loc) in let (n2,g2) = trans neg lhop lxop (n,g1) in (* should be n, not n1 *) let join = Node.make () in (join, g2 |> add_node_stmt join Skip |> add_edge n1 join |> add_edge n2 join) | Assume (UnOp (LNot, UnOp (LNot,e,t1), t2), loc) -> (* !!e -> e *) let stmt' = Assume (e,loc) in trans stmt' lhop lxop (n,g) | Assume (UnOp (LNot, BinOp (LAnd,e1,e2,einfo), t), loc) -> (* !(e1 && e2) -> !e1 || !e2 *) let _ = assert (is_bool t) in let stmt' = Assume (BinOp (LOr, UnOp (LNot,e1,t), UnOp (LNot,e2,t), einfo), loc) in trans stmt' lhop lxop (n,g) | Assume (UnOp (LNot, BinOp (LOr,e1,e2,einfo), t), loc) -> (* !(e1 || e2) -> !e1 && !e2 *) let _ = assert (is_bool t) in let stmt' = Assume (BinOp (LAnd, UnOp (LNot,e1,t), UnOp (LNot,e2,t), einfo), loc) in trans stmt' lhop lxop (n,g) | Assume (e,loc) -> (* assumed to be an atomic predicate *) let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') | Assert (e,_,loc) -> (* assumed to be an atomic predicate *) let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') | _ -> let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') (* disconnect edges starting from * either of * an exit, exception (throw or revert), continue, break *) let disconnect : cfg -> cfg = fun g -> fold_edges (fun n1 n2 acc -> if Node.equal n1 Node.exit then remove_edge n1 n2 acc else if is_exception_node n1 acc then acc |> remove_edge n1 n2 |> add_edge n1 Node.exit else (* normalize so that every function has exit node at the end. *) if is_continue_node n1 acc && not (is_loophead n2 acc) then remove_edge n1 n2 acc else if is_break_node n1 acc && not (is_loopexit n2 acc) then remove_edge n1 n2 acc else acc ) g g let remove_unreach : cfg -> cfg = fun g -> let onestep g nodes = BatSet.fold (fun n acc -> BatSet.union (BatSet.of_list (succ n g)) acc) nodes nodes in let reachable = Vocab.fix (onestep g) (BatSet.singleton Node.entry) in fold_node (fun n acc -> if BatSet.mem n reachable then acc else remove_node n acc ) g g (* remove spurious loopheader *) let inspect_lh : cfg -> cfg = fun g -> fold_node (fun n acc -> if is_loophead n acc then if List.length (pred n acc) = 1 then (* only precondition exists *) {acc with lh_set = BatSet.remove n acc.lh_set} else if List.length (pred n acc) >=2 then acc else raise (Failure "should not exist") else acc ) g g let unroll : cfg -> cfg = fun g -> let next_node n = (match n with | Node.ENTRY | Node.EXIT -> raise (Failure "invalid input") | Node.Node id -> Node.Node (id+1)) in let (untargeted_lhs, g) = fold_edges (fun n1 n2 (tbd_lhs,acc) -> if is_loophead n2 acc then if is_outer_pred_of_lh n1 acc then (tbd_lhs,acc) else let acc' = remove_edge n1 n2 acc in (* given a loopheader id 'n', its corresponding * loopexit id is 'n+1'. * See 'trans' function *) let loopexit = next_node n2 in let acc'' = add_edge n1 loopexit acc' in (BatSet.add n2 tbd_lhs, acc'') else (tbd_lhs, acc) ) g (BatSet.empty,g) in let g = {g with lh_set = BatSet.diff g.lh_set untargeted_lhs} in let _ = assert (not (has_loop g)) in g let rec double_loop : stmt -> stmt = fun stmt -> match stmt with | Assign _ | Decl _ -> stmt | Seq (s1,s2) -> Seq (double_loop s1, double_loop s2) | Call _ | Skip -> stmt | If (e,s1,s2,i) -> If (e, double_loop s1, double_loop s2, i) (* While (e) {s} -> * While (e) {s}; While (e) {s} -> * unroll each while-loop once. *) | While (e,s) -> let s' = double_loop s in Seq (While (e,s'), While (e,s')) | Break | Continue | Return _ | Throw | Assume _ | Assert _ | Assembly _ | PlaceHolder -> stmt | Unchecked (lst,loc) -> assert false let convert : stmt -> cfg = fun stmt -> let stmt = match !Options.mode with "exploit" -> double_loop stmt | _ -> stmt in let (n,g) = trans stmt None None (Node.entry, Lang.empty_cfg) in let g = add_edge n Node.exit g in let g = disconnect g in let g = remove_unreach g in let g = inspect_lh g in let g = match !Options.mode with "exploit" -> unroll g | _ -> g in g let run : pgm -> pgm = fun pgm -> List.map (fun contract -> let funcs = get_funcs contract in let funcs' = List.map (fun func -> let body = get_body func in let g = convert body in let g = {g with signature = get_fkey func} in update_finfo {(get_finfo func) with cfg = g} func ) funcs in update_funcs funcs' contract ) pgm
null
https://raw.githubusercontent.com/kupl/VeriSmart-public/99be7ba88b61994f1ed4c0d3a8e6a6db0f790431/src/pre/makeCfg.ml
ocaml
unconditionally add edges must consider outer loop only. do-while with 'Break' or 'Continue' in loop-body tn: true branch assume node fn: false branch assume node should be n, not n1 !!e -> e !(e1 && e2) -> !e1 || !e2 !(e1 || e2) -> !e1 && !e2 assumed to be an atomic predicate assumed to be an atomic predicate disconnect edges starting from * either of * an exit, exception (throw or revert), continue, break normalize so that every function has exit node at the end. remove spurious loopheader only precondition exists given a loopheader id 'n', its corresponding * loopexit id is 'n+1'. * See 'trans' function While (e) {s} -> * While (e) {s}; While (e) {s} -> * unroll each while-loop once.
open Lang open Options let nodesof : cfg -> node list = fun g -> G.fold_vertex (fun x l -> x :: l) g.graph [] let add_edge : node -> node -> cfg -> cfg = fun n1 n2 g -> {g with graph = G.add_edge g.graph n1 n2} let remove_edge : node -> node -> cfg -> cfg = fun n1 n2 g -> {g with graph = G.remove_edge g.graph n1 n2} let add_node : node -> cfg -> cfg = fun n g -> {g with graph = G.add_vertex g.graph n} let remove_node : node -> cfg -> cfg = fun n g -> { g with graph = G.remove_vertex g.graph n; stmt_map = BatMap.remove n g.stmt_map; outpreds_of_lh = BatSet.remove n g.outpreds_of_lh; lh_set = BatSet.remove n g.lh_set; lx_set = BatSet.remove n g.lx_set; continue_set = BatSet.remove n g.continue_set; break_set = BatSet.remove n g.break_set; } let fold_node f g acc = G.fold_vertex f g.graph acc let fold_edges f g acc = G.fold_edges f g.graph acc let find_stmt : node -> cfg -> stmt = fun n g -> try if n = Node.ENTRY || n = Node.EXIT then Skip else BatMap.find n g.stmt_map with _ -> raise (Failure ("No stmt found in the given node " ^ Node.to_string n)) let is_undef_call : FuncMap.t -> stmt -> bool = fun fmap stmt -> match stmt with | _ when is_external_call stmt -> false | Call (lvop,e,args,ethop,gasop,loc,_) when FuncMap.is_undef e (List.map get_type_exp args) fmap -> true | _ -> false let is_internal_call : FuncMap.t -> id list -> stmt -> bool = fun fmap cnames stmt -> match stmt with | _ when is_external_call stmt -> false | Call (lvop,e,args,ethop,gasop,loc,_) when is_undef_call fmap stmt -> false | Call (_,Lv (Var (f,_)),_,_,_,_,_) -> true | Call (_,Lv (MemberAccess (Lv (Var (x,_)),_,_,_)),_,_,_,_,_) when List.mem x cnames -> true | _ -> false let is_internal_call_node : FuncMap.t -> id list -> node -> cfg -> bool = fun fmap cnames n g -> is_internal_call fmap cnames (find_stmt n g) let is_external_call_node : node -> cfg -> bool = fun n g -> is_external_call (find_stmt n g) let add_stmt : node -> stmt -> cfg -> cfg = fun n s g -> {g with stmt_map = BatMap.add n s g.stmt_map} let add_node_stmt : node -> stmt -> cfg -> cfg = fun n s g -> g |> add_node n |> add_stmt n s let pred : node -> cfg -> node list = fun n g -> G.pred g.graph n let succ : node -> cfg -> node list = fun n g -> G.succ g.graph n let rec has_break_cont : stmt -> bool = fun s -> match s with | Assign _ | Decl _ -> false | Seq (s1,s2) -> has_break_cont s1 || has_break_cont s2 | Call _ -> false | Skip -> false | If (e,s1,s2,_) -> has_break_cont s1 || has_break_cont s2 | Break | Continue -> true | Return _ | Throw -> false | Assume _ | Assert _ | Assembly _ -> false | PlaceHolder -> assert false | Unchecked (lst,_) -> assert false let rec trans : stmt -> node option -> node option -> (node * cfg) -> (node * cfg) lhop : header of dominant loop , lxop : exit of dominant loop , n : interface node match stmt with | Seq (s,While (e,s')) when has_break_cont s -> let lh = Node.make () in let lx = Node.make () in let (n1,g1) = trans s (Some lh) (Some lx) (n,g) in let g2 = g1 |> add_node_stmt lh Skip |> add_edge n1 lh in let (n3,g3) = trans (Assume (e, dummy_loc)) (Some lh) (Some lx) (lh,g2) in let (n4,g4) = trans s' (Some lh) (Some lx) (n3,g3) in let g5 = add_edge n4 lh g4 in let (n6,g6) = trans (Assume (UnOp (LNot,e,EType Bool), dummy_loc)) lhop lxop (lh,g5) in let g7 = g6 |> add_node_stmt lx Skip |> add_edge n6 lx in let preds_of_lh = BatSet.of_list (pred lh g2) in let _ = assert (BatSet.mem n1 preds_of_lh) in let g8 = {g7 with outpreds_of_lh = BatSet.union preds_of_lh g7.outpreds_of_lh; lh_set = BatSet.add lh g7.lh_set; lx_set = BatSet.add lx g7.lx_set} in (lx, g8) | Seq (s1,s2) -> trans s2 lhop lxop (trans s1 lhop lxop (n,g)) | If (e,s1,s2,_) -> let loc = match e with BinOp (_,_,_,einfo) -> einfo.eloc | _ -> dummy_loc in let (tbn,g2) = trans s1 lhop lxop (tn,g1) in let (fbn,g4) = trans s2 lhop lxop (fn,g3) in let join = Node.make () in let g5 = g4 |> add_node_stmt join Skip |> add_edge tbn join |> add_edge fbn join in (join, g5) | While (e,s) -> let lh = Node.make () in node i d : lh + 1 let g1 = g |> add_node_stmt lh Skip |> add_edge n lh in node i d : lh + 2 let (n3,g3) = trans s (Some lh) (Some lx) (n2,g2) in let g4 = add_edge n3 lh g3 in let (n5,g5) = trans (Assume (UnOp (LNot,e,EType Bool), dummy_loc)) lhop lxop (lh,g4) in let g6 = g5 |> add_node_stmt lx Skip |> add_edge n5 lx in let g7 = {g6 with outpreds_of_lh = BatSet.add n g6.outpreds_of_lh; lh_set = BatSet.add lh g6.lh_set; lx_set = BatSet.add lx g6.lx_set} in (lx, g7) | Break -> let lx = (match lxop with Some lx -> lx | None -> raise (Failure "Loop exit should exist")) in let n' = Node.make () in let g' = g |> add_node_stmt n' Skip |> add_edge n n' |> add_edge n' lx in (n', {g' with break_set = BatSet.add n' g'.break_set}) | Continue -> let lh = (match lhop with Some lh -> lh | None -> raise (Failure "Loop header should exist")) in let n' = Node.make () in let g' = g |> add_node_stmt n' Skip |> add_edge n n' |> add_edge n' lh in (n', {g' with continue_set = BatSet.add n' g'.continue_set}) | Return (eop,_) -> let n' = Node.make () in (Node.exit, g |> add_node_stmt n' stmt |> add_edge n n' |> add_edge n' Node.exit) | Assume (BinOp (LAnd,e1,e2,_), loc) -> let (n1,g1) = trans (Assume (e1,loc)) lhop lxop (n,g) in let (n2,g2) = trans (Assume (e2,loc)) lhop lxop (n1,g1) in (n2,g2) | Assume (BinOp (LOr,e1,e2,einfo), loc) -> let (n1,g1) = trans (Assume (e1,loc)) lhop lxop (n,g) in let neg = Assume (BinOp (LAnd, UnOp (LNot,e1,EType Bool), e2, einfo), loc) in let join = Node.make () in (join, g2 |> add_node_stmt join Skip |> add_edge n1 join |> add_edge n2 join) let stmt' = Assume (e,loc) in trans stmt' lhop lxop (n,g) let _ = assert (is_bool t) in let stmt' = Assume (BinOp (LOr, UnOp (LNot,e1,t), UnOp (LNot,e2,t), einfo), loc) in trans stmt' lhop lxop (n,g) let _ = assert (is_bool t) in let stmt' = Assume (BinOp (LAnd, UnOp (LNot,e1,t), UnOp (LNot,e2,t), einfo), loc) in trans stmt' lhop lxop (n,g) let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') | _ -> let n' = Node.make () in let g' = g |> add_node_stmt n' stmt |> add_edge n n' in (n',g') let disconnect : cfg -> cfg = fun g -> fold_edges (fun n1 n2 acc -> if Node.equal n1 Node.exit then remove_edge n1 n2 acc else if is_exception_node n1 acc then if is_continue_node n1 acc && not (is_loophead n2 acc) then remove_edge n1 n2 acc else if is_break_node n1 acc && not (is_loopexit n2 acc) then remove_edge n1 n2 acc else acc ) g g let remove_unreach : cfg -> cfg = fun g -> let onestep g nodes = BatSet.fold (fun n acc -> BatSet.union (BatSet.of_list (succ n g)) acc) nodes nodes in let reachable = Vocab.fix (onestep g) (BatSet.singleton Node.entry) in fold_node (fun n acc -> if BatSet.mem n reachable then acc else remove_node n acc ) g g let inspect_lh : cfg -> cfg = fun g -> fold_node (fun n acc -> if is_loophead n acc then {acc with lh_set = BatSet.remove n acc.lh_set} else if List.length (pred n acc) >=2 then acc else raise (Failure "should not exist") else acc ) g g let unroll : cfg -> cfg = fun g -> let next_node n = (match n with | Node.ENTRY | Node.EXIT -> raise (Failure "invalid input") | Node.Node id -> Node.Node (id+1)) in let (untargeted_lhs, g) = fold_edges (fun n1 n2 (tbd_lhs,acc) -> if is_loophead n2 acc then if is_outer_pred_of_lh n1 acc then (tbd_lhs,acc) else let acc' = remove_edge n1 n2 acc in let loopexit = next_node n2 in let acc'' = add_edge n1 loopexit acc' in (BatSet.add n2 tbd_lhs, acc'') else (tbd_lhs, acc) ) g (BatSet.empty,g) in let g = {g with lh_set = BatSet.diff g.lh_set untargeted_lhs} in let _ = assert (not (has_loop g)) in g let rec double_loop : stmt -> stmt = fun stmt -> match stmt with | Assign _ | Decl _ -> stmt | Seq (s1,s2) -> Seq (double_loop s1, double_loop s2) | Call _ | Skip -> stmt | If (e,s1,s2,i) -> If (e, double_loop s1, double_loop s2, i) | While (e,s) -> let s' = double_loop s in Seq (While (e,s'), While (e,s')) | Break | Continue | Return _ | Throw | Assume _ | Assert _ | Assembly _ | PlaceHolder -> stmt | Unchecked (lst,loc) -> assert false let convert : stmt -> cfg = fun stmt -> let stmt = match !Options.mode with "exploit" -> double_loop stmt | _ -> stmt in let (n,g) = trans stmt None None (Node.entry, Lang.empty_cfg) in let g = add_edge n Node.exit g in let g = disconnect g in let g = remove_unreach g in let g = inspect_lh g in let g = match !Options.mode with "exploit" -> unroll g | _ -> g in g let run : pgm -> pgm = fun pgm -> List.map (fun contract -> let funcs = get_funcs contract in let funcs' = List.map (fun func -> let body = get_body func in let g = convert body in let g = {g with signature = get_fkey func} in update_finfo {(get_finfo func) with cfg = g} func ) funcs in update_funcs funcs' contract ) pgm
73f3e03198a6c9525fd4952b47bf24d4241eadbd1fcc781cf9e2860a9aa6f6c7
ml4tp/tcoq
csymtable.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) Created by for as part of the bytecode - based reduction machine , Oct 2004 bytecode-based reduction machine, Oct 2004 *) Bug fix # 1419 by , Mar 2007 (* This file manages the table of global symbols for the bytecode machine *) open Util open Names open Term open Vm open Cemitcodes open Cbytecodes open Declarations open Pre_env open Cbytegen external tcode_of_code : emitcodes -> int -> tcode = "coq_tcode_of_code" external eval_tcode : tcode -> values array -> values = "coq_eval_tcode" (*******************) Linkage du code (*******************) (* Table des globaux *) (* [global_data] contient les valeurs des constantes globales (axiomes,definitions), les annotations des switch et les structured constant *) external global_data : unit -> values array = "get_coq_global_data" (* [realloc_global_data n] augmente de n la taille de [global_data] *) external realloc_global_data : int -> unit = "realloc_coq_global_data" let check_global_data n = if n >= Array.length (global_data()) then realloc_global_data n let num_global = ref 0 let set_global v = let n = !num_global in check_global_data n; (global_data()).(n) <- v; incr num_global; n table pour les structured_constant et les annotations let rec eq_structured_constant c1 c2 = match c1, c2 with | Const_sorts s1, Const_sorts s2 -> Sorts.equal s1 s2 | Const_sorts _, _ -> false | Const_ind i1, Const_ind i2 -> eq_ind i1 i2 | Const_ind _, _ -> false | Const_proj p1, Const_proj p2 -> Constant.equal p1 p2 | Const_proj _, _ -> false | Const_b0 t1, Const_b0 t2 -> Int.equal t1 t2 | Const_b0 _, _ -> false | Const_bn (t1, a1), Const_bn (t2, a2) -> Int.equal t1 t2 && Array.equal eq_structured_constant a1 a2 | Const_bn _, _ -> false | Const_univ_level l1 , Const_univ_level l2 -> Univ.eq_levels l1 l2 | Const_univ_level _ , _ -> false | Const_type u1 , Const_type u2 -> Univ.Universe.equal u1 u2 | Const_type _ , _ -> false let rec hash_structured_constant c = let open Hashset.Combine in match c with | Const_sorts s -> combinesmall 1 (Sorts.hash s) | Const_ind i -> combinesmall 2 (ind_hash i) | Const_proj p -> combinesmall 3 (Constant.hash p) | Const_b0 t -> combinesmall 4 (Int.hash t) | Const_bn (t, a) -> let fold h c = combine h (hash_structured_constant c) in let h = Array.fold_left fold 0 a in combinesmall 5 (combine (Int.hash t) h) | Const_univ_level l -> combinesmall 6 (Univ.Level.hash l) | Const_type u -> combinesmall 7 (Univ.Universe.hash u) module SConstTable = Hashtbl.Make (struct type t = structured_constant let equal = eq_structured_constant let hash = hash_structured_constant end) let eq_annot_switch asw1 asw2 = let eq_ci ci1 ci2 = eq_ind ci1.ci_ind ci2.ci_ind && Int.equal ci1.ci_npar ci2.ci_npar && Array.equal Int.equal ci1.ci_cstr_ndecls ci2.ci_cstr_ndecls in let eq_rlc (i1, j1) (i2, j2) = Int.equal i1 i2 && Int.equal j1 j2 in eq_ci asw1.ci asw2.ci && Array.equal eq_rlc asw1.rtbl asw2.rtbl && (asw1.tailcall : bool) == asw2.tailcall let hash_annot_switch asw = let open Hashset.Combine in let h1 = Constr.case_info_hash asw.ci in let h2 = Array.fold_left (fun h (t, i) -> combine3 h t i) 0 asw.rtbl in let h3 = if asw.tailcall then 1 else 0 in combine3 h1 h2 h3 module AnnotTable = Hashtbl.Make (struct type t = annot_switch let equal = eq_annot_switch let hash = hash_annot_switch end) let str_cst_tbl : int SConstTable.t = SConstTable.create 31 let annot_tbl : int AnnotTable.t = AnnotTable.create 31 ( annot_switch * int ) (*************************************************************) (*** Mise a jour des valeurs des variables et des constantes *) (*************************************************************) exception NotEvaluated let key rk = match !rk with | None -> raise NotEvaluated | Some k -> try CEphemeron.get k with CEphemeron.InvalidKey -> raise NotEvaluated (************************) (* traduction des patch *) slot_for _ * , calcul la , la place dans la table global , rend sa position dans la table dans la table global, rend sa position dans la table *) let slot_for_str_cst key = try SConstTable.find str_cst_tbl key with Not_found -> let n = set_global (val_of_str_const key) in SConstTable.add str_cst_tbl key n; n let slot_for_annot key = try AnnotTable.find annot_tbl key with Not_found -> let n = set_global (val_of_annot_switch key) in AnnotTable.add annot_tbl key n; n let rec slot_for_getglobal env kn = let (cb,(_,rk)) = lookup_constant_key kn env in try key rk with NotEvaluated -> (* Pp.msgnl(str"not yet evaluated");*) let pos = match cb.const_body_code with | None -> set_global (val_of_constant kn) | Some code -> match Cemitcodes.force code with | BCdefined(code,pl,fv) -> let v = eval_to_patch env (code,pl,fv) in set_global v | BCalias kn' -> slot_for_getglobal env kn' | BCconstant -> set_global (val_of_constant kn) in Pp.msgnl(str"value stored at : " + + int pos ) ; rk := Some (CEphemeron.create pos); pos and slot_for_fv env fv = let fill_fv_cache cache id v_of_id env_of_id b = let v,d = match b with | None -> v_of_id id, Id.Set.empty | Some c -> val_of_constr (env_of_id id env) c, Environ.global_vars_set (Environ.env_of_pre_env env) c in build_lazy_val cache (v, d); v in let val_of_rel i = val_of_rel (nb_rel env - i) in let idfun _ x = x in match fv with | FVnamed id -> let nv = Pre_env.lookup_named_val id env in begin match force_lazy_val nv with | None -> let open Context.Named in let open Declaration in env |> Pre_env.lookup_named id |> get_value |> fill_fv_cache nv id val_of_named idfun | Some (v, _) -> v end | FVrel i -> let rv = Pre_env.lookup_rel_val i env in begin match force_lazy_val rv with | None -> let open Context.Rel in let open Declaration in env.env_rel_context |> lookup i |> get_value |> fill_fv_cache rv i val_of_rel env_of_rel | Some (v, _) -> v end | FVuniv_var idu -> assert false and eval_to_patch env (buff,pl,fv) = let patch = function | Reloc_annot a, pos -> (pos, slot_for_annot a) | Reloc_const sc, pos -> (pos, slot_for_str_cst sc) | Reloc_getglobal kn, pos -> (pos, slot_for_getglobal env kn) in let patches = List.map_left patch pl in let buff = patch_int buff patches in let vm_env = Array.map (slot_for_fv env) fv in let tc = tcode_of_code buff (length buff) in eval_tcode tc vm_env and val_of_constr env c = match compile true env c with | Some v -> eval_to_patch env (to_memory v) | None -> assert false let set_transparent_const kn = () (* !?! *) let set_opaque_const kn = () (* !?! *)
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/kernel/csymtable.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** This file manages the table of global symbols for the bytecode machine ***************** ***************** Table des globaux [global_data] contient les valeurs des constantes globales (axiomes,definitions), les annotations des switch et les structured constant [realloc_global_data n] augmente de n la taille de [global_data] *********************************************************** ** Mise a jour des valeurs des variables et des constantes *********************************************************** ********************** traduction des patch Pp.msgnl(str"not yet evaluated"); !?! !?!
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Created by for as part of the bytecode - based reduction machine , Oct 2004 bytecode-based reduction machine, Oct 2004 *) Bug fix # 1419 by , Mar 2007 open Util open Names open Term open Vm open Cemitcodes open Cbytecodes open Declarations open Pre_env open Cbytegen external tcode_of_code : emitcodes -> int -> tcode = "coq_tcode_of_code" external eval_tcode : tcode -> values array -> values = "coq_eval_tcode" Linkage du code external global_data : unit -> values array = "get_coq_global_data" external realloc_global_data : int -> unit = "realloc_coq_global_data" let check_global_data n = if n >= Array.length (global_data()) then realloc_global_data n let num_global = ref 0 let set_global v = let n = !num_global in check_global_data n; (global_data()).(n) <- v; incr num_global; n table pour les structured_constant et les annotations let rec eq_structured_constant c1 c2 = match c1, c2 with | Const_sorts s1, Const_sorts s2 -> Sorts.equal s1 s2 | Const_sorts _, _ -> false | Const_ind i1, Const_ind i2 -> eq_ind i1 i2 | Const_ind _, _ -> false | Const_proj p1, Const_proj p2 -> Constant.equal p1 p2 | Const_proj _, _ -> false | Const_b0 t1, Const_b0 t2 -> Int.equal t1 t2 | Const_b0 _, _ -> false | Const_bn (t1, a1), Const_bn (t2, a2) -> Int.equal t1 t2 && Array.equal eq_structured_constant a1 a2 | Const_bn _, _ -> false | Const_univ_level l1 , Const_univ_level l2 -> Univ.eq_levels l1 l2 | Const_univ_level _ , _ -> false | Const_type u1 , Const_type u2 -> Univ.Universe.equal u1 u2 | Const_type _ , _ -> false let rec hash_structured_constant c = let open Hashset.Combine in match c with | Const_sorts s -> combinesmall 1 (Sorts.hash s) | Const_ind i -> combinesmall 2 (ind_hash i) | Const_proj p -> combinesmall 3 (Constant.hash p) | Const_b0 t -> combinesmall 4 (Int.hash t) | Const_bn (t, a) -> let fold h c = combine h (hash_structured_constant c) in let h = Array.fold_left fold 0 a in combinesmall 5 (combine (Int.hash t) h) | Const_univ_level l -> combinesmall 6 (Univ.Level.hash l) | Const_type u -> combinesmall 7 (Univ.Universe.hash u) module SConstTable = Hashtbl.Make (struct type t = structured_constant let equal = eq_structured_constant let hash = hash_structured_constant end) let eq_annot_switch asw1 asw2 = let eq_ci ci1 ci2 = eq_ind ci1.ci_ind ci2.ci_ind && Int.equal ci1.ci_npar ci2.ci_npar && Array.equal Int.equal ci1.ci_cstr_ndecls ci2.ci_cstr_ndecls in let eq_rlc (i1, j1) (i2, j2) = Int.equal i1 i2 && Int.equal j1 j2 in eq_ci asw1.ci asw2.ci && Array.equal eq_rlc asw1.rtbl asw2.rtbl && (asw1.tailcall : bool) == asw2.tailcall let hash_annot_switch asw = let open Hashset.Combine in let h1 = Constr.case_info_hash asw.ci in let h2 = Array.fold_left (fun h (t, i) -> combine3 h t i) 0 asw.rtbl in let h3 = if asw.tailcall then 1 else 0 in combine3 h1 h2 h3 module AnnotTable = Hashtbl.Make (struct type t = annot_switch let equal = eq_annot_switch let hash = hash_annot_switch end) let str_cst_tbl : int SConstTable.t = SConstTable.create 31 let annot_tbl : int AnnotTable.t = AnnotTable.create 31 ( annot_switch * int ) exception NotEvaluated let key rk = match !rk with | None -> raise NotEvaluated | Some k -> try CEphemeron.get k with CEphemeron.InvalidKey -> raise NotEvaluated slot_for _ * , calcul la , la place dans la table global , rend sa position dans la table dans la table global, rend sa position dans la table *) let slot_for_str_cst key = try SConstTable.find str_cst_tbl key with Not_found -> let n = set_global (val_of_str_const key) in SConstTable.add str_cst_tbl key n; n let slot_for_annot key = try AnnotTable.find annot_tbl key with Not_found -> let n = set_global (val_of_annot_switch key) in AnnotTable.add annot_tbl key n; n let rec slot_for_getglobal env kn = let (cb,(_,rk)) = lookup_constant_key kn env in try key rk with NotEvaluated -> let pos = match cb.const_body_code with | None -> set_global (val_of_constant kn) | Some code -> match Cemitcodes.force code with | BCdefined(code,pl,fv) -> let v = eval_to_patch env (code,pl,fv) in set_global v | BCalias kn' -> slot_for_getglobal env kn' | BCconstant -> set_global (val_of_constant kn) in Pp.msgnl(str"value stored at : " + + int pos ) ; rk := Some (CEphemeron.create pos); pos and slot_for_fv env fv = let fill_fv_cache cache id v_of_id env_of_id b = let v,d = match b with | None -> v_of_id id, Id.Set.empty | Some c -> val_of_constr (env_of_id id env) c, Environ.global_vars_set (Environ.env_of_pre_env env) c in build_lazy_val cache (v, d); v in let val_of_rel i = val_of_rel (nb_rel env - i) in let idfun _ x = x in match fv with | FVnamed id -> let nv = Pre_env.lookup_named_val id env in begin match force_lazy_val nv with | None -> let open Context.Named in let open Declaration in env |> Pre_env.lookup_named id |> get_value |> fill_fv_cache nv id val_of_named idfun | Some (v, _) -> v end | FVrel i -> let rv = Pre_env.lookup_rel_val i env in begin match force_lazy_val rv with | None -> let open Context.Rel in let open Declaration in env.env_rel_context |> lookup i |> get_value |> fill_fv_cache rv i val_of_rel env_of_rel | Some (v, _) -> v end | FVuniv_var idu -> assert false and eval_to_patch env (buff,pl,fv) = let patch = function | Reloc_annot a, pos -> (pos, slot_for_annot a) | Reloc_const sc, pos -> (pos, slot_for_str_cst sc) | Reloc_getglobal kn, pos -> (pos, slot_for_getglobal env kn) in let patches = List.map_left patch pl in let buff = patch_int buff patches in let vm_env = Array.map (slot_for_fv env) fv in let tc = tcode_of_code buff (length buff) in eval_tcode tc vm_env and val_of_constr env c = match compile true env c with | Some v -> eval_to_patch env (to_memory v) | None -> assert false
8a79b98f6cdf139cb11207841e51658c2503207ffc3a6b50be1bc44aee8860f1
sigxcpu76/transcode-server
ffmpeg.erl
-module(ffmpeg). -include("commons.hrl").
null
https://raw.githubusercontent.com/sigxcpu76/transcode-server/8b5e5bd9c672ab22486c9853d8e6ec749745ec12/src/util/ffmpeg.erl
erlang
-module(ffmpeg). -include("commons.hrl").
d7a4a4012dc6a3793278519bfd2ab0436fe9d854eb48229091e6fc6db5c80098
dhleong/wish
compiler.cljs
(ns wish.sheets.compiler (:require [wish-engine.model :as engine-model])) (defn sheet-items [engine items] (reduce-kv (fn [m id item] (if-let [apply-fn (:! item)] (-> m (assoc-in [id :!] (engine-model/eval-source-form engine nil apply-fn)) (assoc-in [id :!-raw] apply-fn)) m)) items items))
null
https://raw.githubusercontent.com/dhleong/wish/9036f9da3706bfcc1e4b4736558b6f7309f53b7b/src/cljs/wish/sheets/compiler.cljs
clojure
(ns wish.sheets.compiler (:require [wish-engine.model :as engine-model])) (defn sheet-items [engine items] (reduce-kv (fn [m id item] (if-let [apply-fn (:! item)] (-> m (assoc-in [id :!] (engine-model/eval-source-form engine nil apply-fn)) (assoc-in [id :!-raw] apply-fn)) m)) items items))
705aa93ef9dfd6c414119529a2335f45d8fb953534c9e8ab57d22dc95977b034
glondu/belenios
belenios_worker.ml
(**************************************************************************) (* BELENIOS *) (* *) Copyright © 2023 - 2023 Inria (* *) (* This program is free software: you can redistribute it and/or modify *) it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the (* License, or (at your option) any later version, with the additional *) exemption that compiling , linking , and/or using OpenSSL is allowed . (* *) (* 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 *) (* Affero General Public License for more details. *) (* *) You should have received a copy of the GNU Affero General Public (* License along with this program. If not, see *) (* </>. *) (**************************************************************************) open Js_of_ocaml open Belenios_core.Serializable_j open Belenios_core.Common open Belenios_js.Common open Belenios_js.Messages let handle_shuffle {election; ciphertexts} = let election = Js.to_string election in let ciphertexts = Js.to_string ciphertexts in let module W = Belenios.Election.Make (struct let raw_election = election end) (Random) () in let ciphertexts = nh_ciphertexts_of_string W.(sread G.of_string) ciphertexts in let nballots = if Array.length ciphertexts > 0 then Array.length ciphertexts.(0) else 0 in let threshold = 5 in let@ () = fun cont -> if nballots > threshold then ( let sub = Array.map (fun x -> Array.sub x 0 threshold) ciphertexts in let start = new%js Js.date_now in let _ = W.E.shuffle_ciphertexts sub in let stop = new%js Js.date_now in let delta = (stop##valueOf -. start##valueOf) /. 1000. in let eta = int_of_float (ceil (float_of_int nballots *. delta /. float_of_int threshold)) in Worker.post_message (ShuffleEstimate eta); cont () ) else cont () in W.E.shuffle_ciphertexts ciphertexts |> string_of_shuffle W.(swrite G.to_string) |> (fun r -> Worker.post_message (ShuffleResult (Js.string r))) let handle_request = function | Shuffle r -> handle_shuffle r let () = Worker.set_onmessage handle_request
null
https://raw.githubusercontent.com/glondu/belenios/a1f9e4cc8c9aa823f3d0f9ba1e21b8c700cd5522/src/web/clients/worker/belenios_worker.ml
ocaml
************************************************************************ BELENIOS This program is free software: you can redistribute it and/or modify License, or (at your option) any later version, with the additional 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 Affero General Public License for more details. License along with this program. If not, see </>. ************************************************************************
Copyright © 2023 - 2023 Inria it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the exemption that compiling , linking , and/or using OpenSSL is allowed . You should have received a copy of the GNU Affero General Public open Js_of_ocaml open Belenios_core.Serializable_j open Belenios_core.Common open Belenios_js.Common open Belenios_js.Messages let handle_shuffle {election; ciphertexts} = let election = Js.to_string election in let ciphertexts = Js.to_string ciphertexts in let module W = Belenios.Election.Make (struct let raw_election = election end) (Random) () in let ciphertexts = nh_ciphertexts_of_string W.(sread G.of_string) ciphertexts in let nballots = if Array.length ciphertexts > 0 then Array.length ciphertexts.(0) else 0 in let threshold = 5 in let@ () = fun cont -> if nballots > threshold then ( let sub = Array.map (fun x -> Array.sub x 0 threshold) ciphertexts in let start = new%js Js.date_now in let _ = W.E.shuffle_ciphertexts sub in let stop = new%js Js.date_now in let delta = (stop##valueOf -. start##valueOf) /. 1000. in let eta = int_of_float (ceil (float_of_int nballots *. delta /. float_of_int threshold)) in Worker.post_message (ShuffleEstimate eta); cont () ) else cont () in W.E.shuffle_ciphertexts ciphertexts |> string_of_shuffle W.(swrite G.to_string) |> (fun r -> Worker.post_message (ShuffleResult (Js.string r))) let handle_request = function | Shuffle r -> handle_shuffle r let () = Worker.set_onmessage handle_request
f66eb62ad606d13df45bc885b749b079a0b31a5ec56053c6a4050dcdf497642b
xh4/web-toolkit
package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- Toolchain DEFPACKAGE. ;;; ;;; 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. ;;; (uiop:define-package #:cffi-toolchain (:mix #:asdf #:uiop #:common-lisp) (:import-from #:asdf/bundle #:link-op #:bundle-pathname-type #:bundle-type #:gather-operation #:gather-type) (:export ;; Variables #:*cc* #:*cc-flags* #:*ld* #:*ld-exe-flags* #:*ld-dll-flags* #:*linkkit-start* #:*linkkit-end* ;; Functions from c-toolchain #:make-c-file-name #:make-o-file-name #:make-so-file-name #:make-exe-file-name #:parse-command-flags #:parse-command-flags-list #:invoke #:invoke-build #:cc-compile #:link-static-library #:link-shared-library #:link-executable #:link-lisp-executable ;; ASDF classes #:c-file #:o-file #:static-runtime-op #:static-image-op #:static-program-op ))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cffi_0.20.1/toolchain/package.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- package.lisp --- Toolchain DEFPACKAGE. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be 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. Variables Functions from c-toolchain ASDF classes
files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (uiop:define-package #:cffi-toolchain (:mix #:asdf #:uiop #:common-lisp) (:import-from #:asdf/bundle #:link-op #:bundle-pathname-type #:bundle-type #:gather-operation #:gather-type) (:export #:*cc* #:*cc-flags* #:*ld* #:*ld-exe-flags* #:*ld-dll-flags* #:*linkkit-start* #:*linkkit-end* #:make-c-file-name #:make-o-file-name #:make-so-file-name #:make-exe-file-name #:parse-command-flags #:parse-command-flags-list #:invoke #:invoke-build #:cc-compile #:link-static-library #:link-shared-library #:link-executable #:link-lisp-executable #:c-file #:o-file #:static-runtime-op #:static-image-op #:static-program-op ))
27eedd30c18d4a547342360b259de4bb3a404f284358e1a3281839b42bfebefb
coopernurse/cis194
Week4.hs
module Cis194.Hw.Week4 where fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' _ = 0 fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) fun2' :: Integer -> Integer fun2' _ = 0 data Tree a = Leaf | Node Integer (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: [a] -> Tree a foldTree _ = Leaf xor :: [Bool] -> Bool xor _ = False map' :: (a -> b) -> [a] -> [b] map' _ _ = [] sieveSundaram :: Integer -> [Integer] sieveSundaram _ = []
null
https://raw.githubusercontent.com/coopernurse/cis194/592f0ae06cf606d1c2fbe0d055a1e4b67dfc2d0f/src/Cis194/Hw/Week4.hs
haskell
module Cis194.Hw.Week4 where fun1 :: [Integer] -> Integer fun1 [] = 1 fun1 (x:xs) | even x = (x - 2) * fun1 xs | otherwise = fun1 xs fun1' :: [Integer] -> Integer fun1' _ = 0 fun2 :: Integer -> Integer fun2 1 = 0 fun2 n | even n = n + fun2 (n `div` 2) | otherwise = fun2 (3 * n + 1) fun2' :: Integer -> Integer fun2' _ = 0 data Tree a = Leaf | Node Integer (Tree a) a (Tree a) deriving (Show, Eq) foldTree :: [a] -> Tree a foldTree _ = Leaf xor :: [Bool] -> Bool xor _ = False map' :: (a -> b) -> [a] -> [b] map' _ _ = [] sieveSundaram :: Integer -> [Integer] sieveSundaram _ = []
9fbfafabf6dbad6645ffe3aecbaf12914c26a9d0e10d06980e610a0b9e773db9
sdiehl/write-you-a-haskell
interp.hs
-- Traditional call-by-value interpreter. data Expr = Var Int | Lam Expr | App Expr Expr | Lit Int | Prim PrimOp Expr Expr deriving Show data Value = VInt Int | VClosure Expr Env deriving Show data PrimOp = Add | Mul deriving Show type Env = [Value] eval :: Env -> Expr -> Value eval env term = case term of Var n -> env !! n Lam a -> VClosure a env App a b -> let VClosure c env' = eval env a in let v = eval env b in eval (v : env') c Lit n -> VInt n Prim p a b -> (evalPrim p) (eval env a) (eval env b) evalPrim :: PrimOp -> Value -> Value -> Value evalPrim Add (VInt a) (VInt b) = VInt (a + b) evalPrim Mul (VInt a) (VInt b) = VInt (a + b) emptyEnv :: Env emptyEnv = [] ( \x y - > x + y ) 10 20 test :: Value test = eval emptyEnv $ App (App (Lam (Lam (Prim Add (Var 0) (Var 1)))) (Lit 10)) (Lit 20)
null
https://raw.githubusercontent.com/sdiehl/write-you-a-haskell/ae73485e045ef38f50846b62bd91777a9943d1f7/chapter6/interp.hs
haskell
Traditional call-by-value interpreter.
data Expr = Var Int | Lam Expr | App Expr Expr | Lit Int | Prim PrimOp Expr Expr deriving Show data Value = VInt Int | VClosure Expr Env deriving Show data PrimOp = Add | Mul deriving Show type Env = [Value] eval :: Env -> Expr -> Value eval env term = case term of Var n -> env !! n Lam a -> VClosure a env App a b -> let VClosure c env' = eval env a in let v = eval env b in eval (v : env') c Lit n -> VInt n Prim p a b -> (evalPrim p) (eval env a) (eval env b) evalPrim :: PrimOp -> Value -> Value -> Value evalPrim Add (VInt a) (VInt b) = VInt (a + b) evalPrim Mul (VInt a) (VInt b) = VInt (a + b) emptyEnv :: Env emptyEnv = [] ( \x y - > x + y ) 10 20 test :: Value test = eval emptyEnv $ App (App (Lam (Lam (Prim Add (Var 0) (Var 1)))) (Lit 10)) (Lit 20)
58c02221b6060faa06a1d776514a0aad8023a90204322ab897286db65dddba96
wotbrew/relic
app.cljs
(ns examples.cljidle.app "Clojure Idle is a meme idle game to demonstrate the use of relic in the browser." (:require [com.wotbrew.relic :as rel] [reagent.dom :as rdom] [reagent.core :as r])) ;; ---- ;; reference data (def seed-state "This is the seed data for our database." {:Player [{:money 0, :wealth 0, :completed 0}] :Project [{:name "Install Clojure", :base-reward 10.0 :base-difficulty 10}]}) (def projects "The list of possible projects, an element is selected at random every time you complete a project." [{:name "Bug fix", :base-difficulty 10, :base-reward 10} {:name "Feature Request", :base-difficulty 15, :base-reward 20} {:name "Demo", :base-difficulty 25, :base-reward 15} {:name "Documentation", :base-difficulty 30, :base-reward 20} {:name "Improve tests", :base-difficulty 20, :base-reward 25}]) (def improvements "The list of possible improvements, to generate parens and $$$." [{:name "Mechanical key grease" :clicks 1 :base-cost 10} {:name "(repeatedly #(write-code))" :pps 0.1 :base-cost 30} {:name "(repeatedly #(future (write-code)))" :pps 1.0 :base-cost 400} {:name "Write a component library" :pps 2.0 :base-cost 1500} {:name "Encourage coffee donations" :base-cost 25000 :passive-income 100.0} {:name "Babashka lambda functions" :pps 20.0 :base-cost 100000} {:name "Invest in a startup" :base-cost 500000 :passive-income 1000.0} {:name "Buy Nubank" :base-cost 3000000 :pps 200.0} {:name "Rich Hickey cloning vats" :base-cost 90000000 :pps 2000.0}]) (def upgrades "The list of possible upgrades, to improve your improvements." [{:name "Switch color theme" :cost 1 :pps-mul 2.0} {:name "Re-watch simple made easy" :cost 100 :pps-mul 2.0} {:name "Fresh init.el" :cost 1000 :pps-mul 2.0} {:name "Go to the conj" :cost 10000 :pps-mul 4.0} {:name "Switch editor" :cost 20000 :pps-mul 4.0} {:name "Learn transducers" :pps-mul 8.0 :cost 400000} {:name "Macros that write macros" :pps-mul 16.0 :cost 8000000}]) ;; ----- ;; essential state and constraints (def PlayerSchema "The player table will hold some counters" [[:from :Player] [:check ;; the amount of money we have to spend [number? :money] [<= 0 :money] ;; the amount of money we have to spend + in assets [number? :wealth] [<= 0 :wealth] ;; the number of projects completed [nat-int? :completed]]]) (defn exactly-one-row "Returns a constraint for query 'q', that ensures exactly one row exists." [q] [[:from q] [:agg [] [:n count]] [:check [= :n 1]]]) (def ExactlyOnePlayer (exactly-one-row :Player)) (def ProjectSchema "The product table will hold the project being worked on." [[:from :Project] [:check ;; the name of the project [string? :name] ;; used to determine the reward for completion [number? :base-reward] [pos? :base-reward] ;; used to determine how many parens are needed to complete the project [number? :base-difficulty] [pos? :base-difficulty]]]) (def ExactlyOneProject (exactly-one-row :Project)) (def WatchSchema "Watch is going to be used by our reagent integration to invalid reagent atoms as query results change." [[:from :Watch] [:constrain [:check [some? :q] [some? :ratom]] only one row per : q , reuse the same atom if it is the same query . [:unique :q]]]) (def EffectSchema "Effect handlers are callbacks that will be invoked by our reagent integration when rows are added/deleted to a query. f will be called like this (f db added deleted)." [[:from :Effect] [:constrain [:check [some? :key] [some? :q] [fn? :f]] only one effect per : key , so we can remove them later [:unique :key]]]) (def PlayerUpgradeSchema "Upgrades are purchased by inserting a row into the :Upgrade table." [[:from :Upgrade] [:constrain [:check [contains? (set (map :name upgrades)) :name]] [:unique :name]]]) (def PlayerImprovementSchema "Improvements are purchased by inserting or updating a row into the :Improvement table, with a :name and :qty. " [[:from :Improvement] [:constrain [:check [contains? (set (map :name improvements)) :name] [number? :qty] [pos? :qty]] [:unique :name]]]) ;; ---- ;; derived data (defn- project-scale-factor [completed-projects] (+ 1 (long (/ completed-projects 5)))) (def ProjectScale [[:from :Player] [:select [:project-scale-factor [project-scale-factor :completed]]]]) (def Project [[:from :Project] [:join ProjectScale] [:select :name :progress ;; scale the reward / difficulty with the number of completed projects ;; so number goes up. [:reward [* :project-scale-factor :base-reward]] [:difficulty [* :project-scale-factor :base-difficulty]] ;; [:finished [>= :progress :difficulty]]]]) (def Upgrade [[:const upgrades] [:join :Player] [:select :name :cost [:affordable [<= :cost :money]] [:unlocked [some? [rel/sel1 :Upgrade {:name :name}]]] [:show [:and [not :unlocked] [<= :cost [* :wealth 2]]]] [:active-pps-mul [:if :unlocked :pps-mul]]]]) (def ParenMultiplier [[:from Upgrade] [:agg [] [:pps-mul [rel/sum :active-pps-mul]]] [:select [:pps-mul [max 1.0 :pps-mul]]]]) (defn- improvement-description [im] (cond (:pps im) (str "+" (.toFixed (:unit-pps im) 2) " parens per second") (:clicks im) (str "+" (:clicks im) " parens per click") (:passive-income im) (str "+$" (:passive-income im) " per second"))) (defn improvement-cost [base-cost qty] (+ base-cost (* 0.1 base-cost qty))) (def Improvement [[:const improvements] [:join :Player {} ParenMultiplier {}] [:left-join :Improvement {:name :name}] [:extend [:cost [improvement-cost :base-cost :qty]] [:show [<= :cost [* :wealth 2]]] [:affordable [<= :cost :money]] [:qty [:or :qty 0]] [:unit-pps [:? * :pps-mul :pps]] [:active-pps [:? * :qty :unit-pps]] [:active-passive-income [:? * :qty :passive-income]] [:click-boost [:? * :qty :clicks]] [:desc improvement-description]]]) (def ShownImprovement [[:from Improvement] [:where :show] [:sort [:base-cost :asc]]]) (def ShownUpgrade [[:from Upgrade] [:where :show] [:sort [:cost :asc]]]) (def Stats [[:from Improvement] [:union Upgrade] [:agg [] [:pps [rel/sum :active-pps]] [:income [rel/sum :active-passive-income]] [:click-boost [rel/sum :click-boost]]]]) ;; ---- ;; here we materialize just the constraints (def state (atom (-> {} (rel/transact seed-state) (rel/mat WatchSchema EffectSchema PlayerSchema ProjectSchema ExactlyOnePlayer ExactlyOneProject PlayerImprovementSchema PlayerUpgradeSchema)))) ;; ---- ;; our reagent integration ;; using :Watch and :Effect (defn- fire-signals! [db changes] (let [feedback (volatile! [])] (reduce-kv (fn [_ q {:keys [added deleted]}] (when (or (seq added) (seq deleted)) (doseq [{:keys [ratom]} (rel/q db [[:from :Watch] [:where [= :q [:_ q]]]])] (reset! ratom (rel/q db q))) (doseq [{:keys [f]} (rel/q db [[:from :Effect] [:where [= :q [:_ q]]]])] (when-some [tx (f db added deleted)] (vswap! feedback conj tx))))) nil changes) (not-empty @feedback))) (defn t! "Queues a transaction, fires any associated signals if their dependencies change." [& tx] (loop [tx tx] (let [{:keys [db changes]} (apply rel/track-transact @state tx)] (reset! state db) (let [feedback (fire-signals! db changes)] (when (seq feedback) (recur feedback))))) nil) (defn listen! [k q f] (swap! state rel/watch q) (t! [:insert-or-replace :Effect {:q q, :key k, :f f}])) (defn q! "Returns a reagent derefable for the results of query `q`. Optionally supply a function to apply to the results. e.g (q! :Customer first) " ([q] (q! q identity)) ([q f] (let [new-atom (r/atom nil) _ (t! [:insert-ignore :Watch {:q q, :ratom new-atom}]) db (swap! state rel/watch q) {:keys [ratom]} (rel/row db :Watch [= :q [:_ q]]) _ (if (identical? ratom new-atom) (let [new (rel/q db q)] (reset! ratom new)))] (r/track (fn [] (f @ratom)))))) ;; --- ;; event handlers (listen! ::on-project-completed-issue-reward (conj Project [:where :finished]) (fn [_ added] (when-some [{:keys [reward]} (first added)] (list [:replace-all :Project (rand-nth projects)] [:update :Player {:money [+ :money reward] :wealth [+ :wealth reward] :completed [inc :completed]}])))) ;; --- ;; transactions (defn progress ([] (progress 1.0)) ([n] (progress n 0.0)) ([parens income] (list [:update :Project {:progress [+ :progress parens]}] (when (and income (pos? income)) [:update :Player {:money [+ :money income] :wealth [+ :wealth income]}])))) (defn buy [improvement-name] (fn [db] (let [{:keys [affordable name cost]} (rel/row db Improvement [= :name improvement-name])] (when affordable (list [:insert-or-update :Improvement {:qty [inc :qty]} {:name name :qty 1}] [:update :Player {:money [- :money cost]}]))))) (defn unlock [upgrade-name] (fn [db] (let [{:keys [affordable cost]} (rel/row db Upgrade [= :name upgrade-name])] (when affordable (list [:insert-ignore :Upgrade {:name upgrade-name}] [:update :Player {:money [- :money cost]}]))))) ;; ---- ;; reagent code (defn project [] (let [p (q! Project first)] (fn [] [:table.table [:tbody [:tr [:th "Project"] [:td (:name @p)]] [:tr [:th "Progress"] [:td (long (:progress @p 0)) "/" (:difficulty @p)]] [:tr [:th "Reward"] [:td "$" (:reward @p)]]]]))) (defn paren [] (let [clicks (q! Stats first)] (fn [] [:button.button {:style {:width "96px" :height "96px"} :on-click #(t! (progress (+ 1 (:click-boost @clicks))))} "()"]))) (defn money [] (let [player (q! :Player first)] (fn [] [:span "$" (.toFixed (:money @player 0) 2)]))) (defn pps [] (let [ti (q! Stats first)] (fn [] [:span (.toFixed (:pps @ti 0) 2) " parens per second"]))) (defn status [] [:table.table.is-fullwidth [:thead [:tr [:th [paren]] [:th [money]] [:th [pps]]]]]) (defn improvement-list [] [] (let [im (q! ShownImprovement)] (fn [] [:table.table [:tbody (for [im @im] ^{:key (:name im)} [:tr [:th (:name im)] [:th (:qty im)] [:td (:desc im)] [:td "$" (.toFixed (:cost im 0) 2)] [:td (if (:affordable im) [:button.button {:on-click #(t! (buy (:name im)))} "Buy"] [:button.button {:disabled true} "Buy"])]])]]))) (defn upgrade-list [] (let [up (q! ShownUpgrade)] (fn [] [:table.table [:tbody (for [up @up] ^{:key (:name up)} [:tr [:th (:name up)] [:td (:desc up)] [:td "$" (:cost up)] [:td (if (:affordable up) [:button.button {:on-click #(t! (unlock (:name up)))} "Unlock"] [:button.button {:disabled true} "Unlock"])]])]]))) (defn app [] (fn [] [:section.section [:div.container [:div.columns [:div.column [status]] [:div.column [project]]] [:div.columns [:div.column [improvement-list]] [:div.column [upgrade-list]]]]])) (defn tick! [] (let [db @state {:keys [pps income]} (rel/row db Stats)] (when pps (t! (progress pps income)) (let [db @state] (set! (.-title js/document) (str "CLJ IDLE $" (.toFixed (:money (rel/row db :Player) 0) 2))))))) (defn init [] (when-not (.-cljidleTicking js/window) (.setInterval js/window (fn [] (tick!)) 1000) (set! (.-cljidleTicking js/window) true)) (rdom/render [app] (js/document.getElementById "app"))) (init) (comment (t! (progress 0 100)) (init) ,)
null
https://raw.githubusercontent.com/wotbrew/relic/a75d4791bdee22e5841456055b425a904d5d0d6c/dev/examples/cljidle/app.cljs
clojure
---- reference data ----- essential state and constraints the amount of money we have to spend the amount of money we have to spend + in assets the number of projects completed the name of the project used to determine the reward for completion used to determine how many parens are needed to complete the project ---- derived data scale the reward / difficulty with the number of completed projects so number goes up. ---- here we materialize just the constraints ---- our reagent integration using :Watch and :Effect --- event handlers --- transactions ---- reagent code
(ns examples.cljidle.app "Clojure Idle is a meme idle game to demonstrate the use of relic in the browser." (:require [com.wotbrew.relic :as rel] [reagent.dom :as rdom] [reagent.core :as r])) (def seed-state "This is the seed data for our database." {:Player [{:money 0, :wealth 0, :completed 0}] :Project [{:name "Install Clojure", :base-reward 10.0 :base-difficulty 10}]}) (def projects "The list of possible projects, an element is selected at random every time you complete a project." [{:name "Bug fix", :base-difficulty 10, :base-reward 10} {:name "Feature Request", :base-difficulty 15, :base-reward 20} {:name "Demo", :base-difficulty 25, :base-reward 15} {:name "Documentation", :base-difficulty 30, :base-reward 20} {:name "Improve tests", :base-difficulty 20, :base-reward 25}]) (def improvements "The list of possible improvements, to generate parens and $$$." [{:name "Mechanical key grease" :clicks 1 :base-cost 10} {:name "(repeatedly #(write-code))" :pps 0.1 :base-cost 30} {:name "(repeatedly #(future (write-code)))" :pps 1.0 :base-cost 400} {:name "Write a component library" :pps 2.0 :base-cost 1500} {:name "Encourage coffee donations" :base-cost 25000 :passive-income 100.0} {:name "Babashka lambda functions" :pps 20.0 :base-cost 100000} {:name "Invest in a startup" :base-cost 500000 :passive-income 1000.0} {:name "Buy Nubank" :base-cost 3000000 :pps 200.0} {:name "Rich Hickey cloning vats" :base-cost 90000000 :pps 2000.0}]) (def upgrades "The list of possible upgrades, to improve your improvements." [{:name "Switch color theme" :cost 1 :pps-mul 2.0} {:name "Re-watch simple made easy" :cost 100 :pps-mul 2.0} {:name "Fresh init.el" :cost 1000 :pps-mul 2.0} {:name "Go to the conj" :cost 10000 :pps-mul 4.0} {:name "Switch editor" :cost 20000 :pps-mul 4.0} {:name "Learn transducers" :pps-mul 8.0 :cost 400000} {:name "Macros that write macros" :pps-mul 16.0 :cost 8000000}]) (def PlayerSchema "The player table will hold some counters" [[:from :Player] [:check [number? :money] [<= 0 :money] [number? :wealth] [<= 0 :wealth] [nat-int? :completed]]]) (defn exactly-one-row "Returns a constraint for query 'q', that ensures exactly one row exists." [q] [[:from q] [:agg [] [:n count]] [:check [= :n 1]]]) (def ExactlyOnePlayer (exactly-one-row :Player)) (def ProjectSchema "The product table will hold the project being worked on." [[:from :Project] [:check [string? :name] [number? :base-reward] [pos? :base-reward] [number? :base-difficulty] [pos? :base-difficulty]]]) (def ExactlyOneProject (exactly-one-row :Project)) (def WatchSchema "Watch is going to be used by our reagent integration to invalid reagent atoms as query results change." [[:from :Watch] [:constrain [:check [some? :q] [some? :ratom]] only one row per : q , reuse the same atom if it is the same query . [:unique :q]]]) (def EffectSchema "Effect handlers are callbacks that will be invoked by our reagent integration when rows are added/deleted to a query. f will be called like this (f db added deleted)." [[:from :Effect] [:constrain [:check [some? :key] [some? :q] [fn? :f]] only one effect per : key , so we can remove them later [:unique :key]]]) (def PlayerUpgradeSchema "Upgrades are purchased by inserting a row into the :Upgrade table." [[:from :Upgrade] [:constrain [:check [contains? (set (map :name upgrades)) :name]] [:unique :name]]]) (def PlayerImprovementSchema "Improvements are purchased by inserting or updating a row into the :Improvement table, with a :name and :qty. " [[:from :Improvement] [:constrain [:check [contains? (set (map :name improvements)) :name] [number? :qty] [pos? :qty]] [:unique :name]]]) (defn- project-scale-factor [completed-projects] (+ 1 (long (/ completed-projects 5)))) (def ProjectScale [[:from :Player] [:select [:project-scale-factor [project-scale-factor :completed]]]]) (def Project [[:from :Project] [:join ProjectScale] [:select :name :progress [:reward [* :project-scale-factor :base-reward]] [:difficulty [* :project-scale-factor :base-difficulty]] [:finished [>= :progress :difficulty]]]]) (def Upgrade [[:const upgrades] [:join :Player] [:select :name :cost [:affordable [<= :cost :money]] [:unlocked [some? [rel/sel1 :Upgrade {:name :name}]]] [:show [:and [not :unlocked] [<= :cost [* :wealth 2]]]] [:active-pps-mul [:if :unlocked :pps-mul]]]]) (def ParenMultiplier [[:from Upgrade] [:agg [] [:pps-mul [rel/sum :active-pps-mul]]] [:select [:pps-mul [max 1.0 :pps-mul]]]]) (defn- improvement-description [im] (cond (:pps im) (str "+" (.toFixed (:unit-pps im) 2) " parens per second") (:clicks im) (str "+" (:clicks im) " parens per click") (:passive-income im) (str "+$" (:passive-income im) " per second"))) (defn improvement-cost [base-cost qty] (+ base-cost (* 0.1 base-cost qty))) (def Improvement [[:const improvements] [:join :Player {} ParenMultiplier {}] [:left-join :Improvement {:name :name}] [:extend [:cost [improvement-cost :base-cost :qty]] [:show [<= :cost [* :wealth 2]]] [:affordable [<= :cost :money]] [:qty [:or :qty 0]] [:unit-pps [:? * :pps-mul :pps]] [:active-pps [:? * :qty :unit-pps]] [:active-passive-income [:? * :qty :passive-income]] [:click-boost [:? * :qty :clicks]] [:desc improvement-description]]]) (def ShownImprovement [[:from Improvement] [:where :show] [:sort [:base-cost :asc]]]) (def ShownUpgrade [[:from Upgrade] [:where :show] [:sort [:cost :asc]]]) (def Stats [[:from Improvement] [:union Upgrade] [:agg [] [:pps [rel/sum :active-pps]] [:income [rel/sum :active-passive-income]] [:click-boost [rel/sum :click-boost]]]]) (def state (atom (-> {} (rel/transact seed-state) (rel/mat WatchSchema EffectSchema PlayerSchema ProjectSchema ExactlyOnePlayer ExactlyOneProject PlayerImprovementSchema PlayerUpgradeSchema)))) (defn- fire-signals! [db changes] (let [feedback (volatile! [])] (reduce-kv (fn [_ q {:keys [added deleted]}] (when (or (seq added) (seq deleted)) (doseq [{:keys [ratom]} (rel/q db [[:from :Watch] [:where [= :q [:_ q]]]])] (reset! ratom (rel/q db q))) (doseq [{:keys [f]} (rel/q db [[:from :Effect] [:where [= :q [:_ q]]]])] (when-some [tx (f db added deleted)] (vswap! feedback conj tx))))) nil changes) (not-empty @feedback))) (defn t! "Queues a transaction, fires any associated signals if their dependencies change." [& tx] (loop [tx tx] (let [{:keys [db changes]} (apply rel/track-transact @state tx)] (reset! state db) (let [feedback (fire-signals! db changes)] (when (seq feedback) (recur feedback))))) nil) (defn listen! [k q f] (swap! state rel/watch q) (t! [:insert-or-replace :Effect {:q q, :key k, :f f}])) (defn q! "Returns a reagent derefable for the results of query `q`. Optionally supply a function to apply to the results. e.g (q! :Customer first) " ([q] (q! q identity)) ([q f] (let [new-atom (r/atom nil) _ (t! [:insert-ignore :Watch {:q q, :ratom new-atom}]) db (swap! state rel/watch q) {:keys [ratom]} (rel/row db :Watch [= :q [:_ q]]) _ (if (identical? ratom new-atom) (let [new (rel/q db q)] (reset! ratom new)))] (r/track (fn [] (f @ratom)))))) (listen! ::on-project-completed-issue-reward (conj Project [:where :finished]) (fn [_ added] (when-some [{:keys [reward]} (first added)] (list [:replace-all :Project (rand-nth projects)] [:update :Player {:money [+ :money reward] :wealth [+ :wealth reward] :completed [inc :completed]}])))) (defn progress ([] (progress 1.0)) ([n] (progress n 0.0)) ([parens income] (list [:update :Project {:progress [+ :progress parens]}] (when (and income (pos? income)) [:update :Player {:money [+ :money income] :wealth [+ :wealth income]}])))) (defn buy [improvement-name] (fn [db] (let [{:keys [affordable name cost]} (rel/row db Improvement [= :name improvement-name])] (when affordable (list [:insert-or-update :Improvement {:qty [inc :qty]} {:name name :qty 1}] [:update :Player {:money [- :money cost]}]))))) (defn unlock [upgrade-name] (fn [db] (let [{:keys [affordable cost]} (rel/row db Upgrade [= :name upgrade-name])] (when affordable (list [:insert-ignore :Upgrade {:name upgrade-name}] [:update :Player {:money [- :money cost]}]))))) (defn project [] (let [p (q! Project first)] (fn [] [:table.table [:tbody [:tr [:th "Project"] [:td (:name @p)]] [:tr [:th "Progress"] [:td (long (:progress @p 0)) "/" (:difficulty @p)]] [:tr [:th "Reward"] [:td "$" (:reward @p)]]]]))) (defn paren [] (let [clicks (q! Stats first)] (fn [] [:button.button {:style {:width "96px" :height "96px"} :on-click #(t! (progress (+ 1 (:click-boost @clicks))))} "()"]))) (defn money [] (let [player (q! :Player first)] (fn [] [:span "$" (.toFixed (:money @player 0) 2)]))) (defn pps [] (let [ti (q! Stats first)] (fn [] [:span (.toFixed (:pps @ti 0) 2) " parens per second"]))) (defn status [] [:table.table.is-fullwidth [:thead [:tr [:th [paren]] [:th [money]] [:th [pps]]]]]) (defn improvement-list [] [] (let [im (q! ShownImprovement)] (fn [] [:table.table [:tbody (for [im @im] ^{:key (:name im)} [:tr [:th (:name im)] [:th (:qty im)] [:td (:desc im)] [:td "$" (.toFixed (:cost im 0) 2)] [:td (if (:affordable im) [:button.button {:on-click #(t! (buy (:name im)))} "Buy"] [:button.button {:disabled true} "Buy"])]])]]))) (defn upgrade-list [] (let [up (q! ShownUpgrade)] (fn [] [:table.table [:tbody (for [up @up] ^{:key (:name up)} [:tr [:th (:name up)] [:td (:desc up)] [:td "$" (:cost up)] [:td (if (:affordable up) [:button.button {:on-click #(t! (unlock (:name up)))} "Unlock"] [:button.button {:disabled true} "Unlock"])]])]]))) (defn app [] (fn [] [:section.section [:div.container [:div.columns [:div.column [status]] [:div.column [project]]] [:div.columns [:div.column [improvement-list]] [:div.column [upgrade-list]]]]])) (defn tick! [] (let [db @state {:keys [pps income]} (rel/row db Stats)] (when pps (t! (progress pps income)) (let [db @state] (set! (.-title js/document) (str "CLJ IDLE $" (.toFixed (:money (rel/row db :Player) 0) 2))))))) (defn init [] (when-not (.-cljidleTicking js/window) (.setInterval js/window (fn [] (tick!)) 1000) (set! (.-cljidleTicking js/window) true)) (rdom/render [app] (js/document.getElementById "app"))) (init) (comment (t! (progress 0 100)) (init) ,)
b80379cb8bf628321d122a3e99f65edfc5a4057887b88bdcdeda59dde6f13c7a
meamy/feynman
Symbolic.hs
| Module : Symbolic Description : Symbolic verification based on path sums Copyright : ( c ) , 2020 Maintainer : Stability : experimental Portability : portable Module : Symbolic Description : Symbolic verification based on path sums Copyright : (c) Matthew Amy, 2020 Maintainer : Stability : experimental Portability : portable -} module Feynman.Verification.Symbolic where import Data.List import Data.Map (Map, (!)) import qualified Data.Map as Map import Control.Monad.State.Lazy import Data.Semigroup import Data.Set (Set) import qualified Data.Set as Set import Feynman.Core import Feynman.Algebra.Base import Feynman.Algebra.Polynomial.Multilinear import Feynman.Algebra.Pathsum.Balanced hiding (dagger) {------------------------------------ Path sum actions ------------------------------------} -- | Context for computing path sums of circuits type Context = Map ID Int -- | Retrieve the path sum representation of a primitive gate primitiveAction :: Primitive -> Pathsum DMod2 primitiveAction gate = case gate of H _ -> hgate X _ -> xgate Y _ -> ygate Z _ -> zgate CNOT _ _ -> cxgate CZ _ _ -> czgate S _ -> sgate Sinv _ -> sdggate T _ -> tgate Tinv _ -> tdggate Swap _ _ -> swapgate Rz theta _ -> rzgate $ fromDyadic $ discretize theta Rx theta _ -> hgate * rzgate (fromDyadic $ discretize theta) * hgate Ry theta _ -> rzgate (fromDyadic $ discretize theta) * hgate * rzgate (fromDyadic $ discretize theta) * hgate Uninterp _ _ -> error "Uninterpreted gates not supported" -- | Find the relevant index or allocate one for the given qubit findOrAlloc :: ID -> State Context Int findOrAlloc x = do result <- gets $ Map.lookup x case result of Just i -> return i Nothing -> gets Map.size >>= \i -> modify (Map.insert x i) >> return i -- | Apply a circuit to a state applyCircuit :: Pathsum DMod2 -> [Primitive] -> State Context (Pathsum DMod2) applyCircuit = foldM absorbGate where absorbGate sop gate = do args <- mapM findOrAlloc $ getArgs gate nOut <- gets Map.size let sop' = sop <> identity (nOut - outDeg sop) let g = embed (primitiveAction gate) (nOut - length args) ((Map.fromList $ zip [0..] args)!) ((Map.fromList $ zip [0..] args)!) return $ sop' .> g -- | Create an initial state given a set of variables and inputs makeInitial :: [ID] -> [ID] -> State Context ([SBool ID]) makeInitial vars inputs = fmap Map.elems $ foldM go Map.empty vars where go st x = do i <- findOrAlloc x if elem x inputs then return $ Map.insert i (ofVar x) st else return $ Map.insert i 0 st -- | Compute the path sum action of a primitive circuit computeAction :: [Primitive] -> State Context (Pathsum DMod2) computeAction xs = do n <- gets Map.size applyCircuit (identity n) xs -- | Shortcut for computing an action in the empty context simpleAction :: [Primitive] -> Pathsum DMod2 simpleAction = (flip evalState) Map.empty . computeAction -- | Shortcut for computing an action in a linear context sopAction :: [ID] -> [Primitive] -> Pathsum DMod2 sopAction ids = (flip evalState) (Map.fromList $ zip ids [0..]) . computeAction -- | Shortcut for computing an action in a context computeActionInCtx :: [Primitive] -> Context -> Pathsum DMod2 computeActionInCtx xs = evalState (computeAction xs) -- | Shortcut for computing an action given a set of variables and inputs complexAction :: [ID] -> [ID] -> [Primitive] -> Pathsum DMod2 complexAction vars inputs circ = evalState st Map.empty where st = do init <- makeInitial vars inputs action <- computeAction circ return $ ket init .> action {------------------------------------ Verification methods ------------------------------------} -- | The return type of verification queries data Result = Identity | NotIdentity String | Inconclusive (Pathsum DMod2) deriving (Show) -- These really need to be packaged up in a logic rather than separate -- functions. Doing this for now until a better solution can be found. -- Realistically this could also be done "application side" by composing -- with relevant path sums. validate :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validate global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 return $ ket st .> action .> bra st sop = f . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in case sop of Triv -> Identity HHKill _ p -> NotIdentity . show $ getSolution p _ -> Inconclusive sop validateExperimental :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validateExperimental global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 return $ action sop = f . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in case sop of Triv -> Identity HHKill _ p -> NotIdentity . show $ getSolution p _ -> if isIdentity sop then Identity else NotIdentity "By explicit computation" postselectAll :: [ID] -> State Context (Pathsum DMod2) postselectAll xs = do args <- mapM findOrAlloc xs nOut <- gets Map.size return $ embed (bra $ map (\_ -> 0) args) (nOut - length args) ((Map.fromList $ zip [0..] args)!) ((Map.fromList $ zip [0..] args)!) validateWithPost :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validateWithPost global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 post <- postselectAll (vars \\ inputs) return $ ket st .> action .> post sop = f . dropAmplitude . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in if sop == ket (map ofVar . filter (`elem` inputs) $ vars) then Identity else case sop of HHKill _ p -> NotIdentity . show $ getSolution p _ -> Inconclusive sop
null
https://raw.githubusercontent.com/meamy/feynman/6aa7f9b1e24400329350f7589382b9040b55b556/src/Feynman/Verification/Symbolic.hs
haskell
----------------------------------- Path sum actions ----------------------------------- | Context for computing path sums of circuits | Retrieve the path sum representation of a primitive gate | Find the relevant index or allocate one for the given qubit | Apply a circuit to a state | Create an initial state given a set of variables and inputs | Compute the path sum action of a primitive circuit | Shortcut for computing an action in the empty context | Shortcut for computing an action in a linear context | Shortcut for computing an action in a context | Shortcut for computing an action given a set of variables and inputs ----------------------------------- Verification methods ----------------------------------- | The return type of verification queries These really need to be packaged up in a logic rather than separate functions. Doing this for now until a better solution can be found. Realistically this could also be done "application side" by composing with relevant path sums.
| Module : Symbolic Description : Symbolic verification based on path sums Copyright : ( c ) , 2020 Maintainer : Stability : experimental Portability : portable Module : Symbolic Description : Symbolic verification based on path sums Copyright : (c) Matthew Amy, 2020 Maintainer : Stability : experimental Portability : portable -} module Feynman.Verification.Symbolic where import Data.List import Data.Map (Map, (!)) import qualified Data.Map as Map import Control.Monad.State.Lazy import Data.Semigroup import Data.Set (Set) import qualified Data.Set as Set import Feynman.Core import Feynman.Algebra.Base import Feynman.Algebra.Polynomial.Multilinear import Feynman.Algebra.Pathsum.Balanced hiding (dagger) type Context = Map ID Int primitiveAction :: Primitive -> Pathsum DMod2 primitiveAction gate = case gate of H _ -> hgate X _ -> xgate Y _ -> ygate Z _ -> zgate CNOT _ _ -> cxgate CZ _ _ -> czgate S _ -> sgate Sinv _ -> sdggate T _ -> tgate Tinv _ -> tdggate Swap _ _ -> swapgate Rz theta _ -> rzgate $ fromDyadic $ discretize theta Rx theta _ -> hgate * rzgate (fromDyadic $ discretize theta) * hgate Ry theta _ -> rzgate (fromDyadic $ discretize theta) * hgate * rzgate (fromDyadic $ discretize theta) * hgate Uninterp _ _ -> error "Uninterpreted gates not supported" findOrAlloc :: ID -> State Context Int findOrAlloc x = do result <- gets $ Map.lookup x case result of Just i -> return i Nothing -> gets Map.size >>= \i -> modify (Map.insert x i) >> return i applyCircuit :: Pathsum DMod2 -> [Primitive] -> State Context (Pathsum DMod2) applyCircuit = foldM absorbGate where absorbGate sop gate = do args <- mapM findOrAlloc $ getArgs gate nOut <- gets Map.size let sop' = sop <> identity (nOut - outDeg sop) let g = embed (primitiveAction gate) (nOut - length args) ((Map.fromList $ zip [0..] args)!) ((Map.fromList $ zip [0..] args)!) return $ sop' .> g makeInitial :: [ID] -> [ID] -> State Context ([SBool ID]) makeInitial vars inputs = fmap Map.elems $ foldM go Map.empty vars where go st x = do i <- findOrAlloc x if elem x inputs then return $ Map.insert i (ofVar x) st else return $ Map.insert i 0 st computeAction :: [Primitive] -> State Context (Pathsum DMod2) computeAction xs = do n <- gets Map.size applyCircuit (identity n) xs simpleAction :: [Primitive] -> Pathsum DMod2 simpleAction = (flip evalState) Map.empty . computeAction sopAction :: [ID] -> [Primitive] -> Pathsum DMod2 sopAction ids = (flip evalState) (Map.fromList $ zip ids [0..]) . computeAction computeActionInCtx :: [Primitive] -> Context -> Pathsum DMod2 computeActionInCtx xs = evalState (computeAction xs) complexAction :: [ID] -> [ID] -> [Primitive] -> Pathsum DMod2 complexAction vars inputs circ = evalState st Map.empty where st = do init <- makeInitial vars inputs action <- computeAction circ return $ ket init .> action data Result = Identity | NotIdentity String | Inconclusive (Pathsum DMod2) deriving (Show) validate :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validate global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 return $ ket st .> action .> bra st sop = f . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in case sop of Triv -> Identity HHKill _ p -> NotIdentity . show $ getSolution p _ -> Inconclusive sop validateExperimental :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validateExperimental global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 return $ action sop = f . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in case sop of Triv -> Identity HHKill _ p -> NotIdentity . show $ getSolution p _ -> if isIdentity sop then Identity else NotIdentity "By explicit computation" postselectAll :: [ID] -> State Context (Pathsum DMod2) postselectAll xs = do args <- mapM findOrAlloc xs nOut <- gets Map.size return $ embed (bra $ map (\_ -> 0) args) (nOut - length args) ((Map.fromList $ zip [0..] args)!) ((Map.fromList $ zip [0..] args)!) validateWithPost :: Bool -> [ID] -> [ID] -> [Primitive] -> [Primitive] -> Result validateWithPost global vars inputs c1 c2 = let sopWithContext = do st <- makeInitial vars inputs action <- computeAction $ c1 ++ dagger c2 post <- postselectAll (vars \\ inputs) return $ ket st .> action .> post sop = f . dropAmplitude . grind $ evalState sopWithContext Map.empty where f = if global then dropGlobalPhase else id in if sop == ket (map ofVar . filter (`elem` inputs) $ vars) then Identity else case sop of HHKill _ p -> NotIdentity . show $ getSolution p _ -> Inconclusive sop
6d3984cf9ac38d4f994a7ed79c8f1ba8e902fc24de24189512609ac40b0724d4
Apress/common-lisp-condition-system
debugger.lisp
;;;; t/debugger.lisp (in-package #:portable-condition-system/test) (defun run-debugger-command (command input-string &optional condition &rest args) (with-input-from-string (input input-string) (with-output-to-string (output) (let ((stream (make-two-way-stream input output))) (apply #'portable-condition-system::run-debugger-command command stream condition args))))) (deftest debugger.eval.1 (run-debugger-command :eval "(+ 2 2)") "4") (deftest debugger.eval.2 (let ((*package* (find-package '#:portable-condition-system/test))) (handler-case (run-debugger-command :eval "(error \"42\")") (error () 'good))) good) (deftest debugger.report.1 (let ((*package* (find-package :keyword)) (condition (make-condition 'condition))) (run-debugger-command :report "" condition)) ";; Debugger level 0 entered on PORTABLE-CONDITION-SYSTEM:CONDITION: ;; Condition PORTABLE-CONDITION-SYSTEM:CONDITION was signaled. ") (deftest debugger.report.2 (let ((*package* (find-package :keyword)) (portable-condition-system::*debug-level* 42) (condition (make-condition 'type-error :datum 42 :expected-type :keyword))) (run-debugger-command :report "" condition)) Debugger level 42 entered on PORTABLE - CONDITION - SYSTEM : TYPE - ERROR : ;; The value ;; 42 ;; is not of type : KEYWORD . ") (deftest debugger.report.3 (let* ((*package* (find-package :keyword)) (error-fn (lambda (&rest args) (declare (ignore args)) (error "Error reporting condition"))) (condition (make-condition 'simple-condition :format-control error-fn))) (run-debugger-command :report "" condition)) ";; Debugger level 0 entered on PORTABLE-CONDITION-SYSTEM:SIMPLE-CONDITION: ;; #<error while reporting condition> ") (defvar *debugger.condition* (make-condition 'condition)) (deftest debugger.condition.1 (eqt (first (portable-condition-system::run-debugger-command :condition nil *debugger.condition*)) *debugger.condition*) t) (deftest debugger.abort.1 (run-debugger-command :abort "") ";; There is no active ABORT restart. ") (deftest debugger.abort.2 (restart-case (run-debugger-command :abort "") (abort () 'good)) good) (deftest debugger.q.1 (run-debugger-command :q "") ";; There is no active ABORT restart. ") (deftest debugger.q.2 (restart-case (run-debugger-command :q "") (abort () 'good)) good) (deftest debugger.continue.1 (run-debugger-command :continue "") ";; There is no active CONTINUE restart. ") (deftest debugger.continue.2 (restart-case (run-debugger-command :continue "") (continue () 'good)) good) (deftest debugger.c.1 (run-debugger-command :c "") ";; There is no active CONTINUE restart. ") (deftest debugger.c.2 (restart-case (run-debugger-command :c "") (continue () 'good)) good) (deftest debugger.restarts.1 (run-debugger-command :restarts "" (make-condition 'condition)) ";; No available restarts. ") (deftest debugger.restarts.2 (restart-case (run-debugger-command :restarts "" (make-condition 'condition)) (abort () :report "Abort.") (retry () :report "Retry.") (fail () :report "Fail.")) ";; Available restarts: ;; 0: [ABORT] Abort. 1 : [ RETRY ] Retry . 2 : [ FAIL ] Fail . ") (deftest debugger.restarts.3 (restart-case (run-debugger-command :restarts "" (make-condition 'condition)) (abort () :report (lambda (stream) (declare (ignore stream)) (error "Error reporting restart")))) ";; Available restarts: ;; 0: [ABORT] #<error while reporting restart> ") (deftest debugger.restart.1 (run-debugger-command :restart "" (make-condition 'condition) 0) ";; There is no restart with number 0. ") (deftest debugger.restart.2 (restart-case (run-debugger-command :restart "" (make-condition 'condition) 1) (abort () 'bad) (retry () 'good) (fail () 'ugly)) good) (deftest debugger.help.1 (run-debugger-command :help "") This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - ;; ;; Available debugger commands: ;; :HELP Show this text. : EVAL < form > Evaluate a form typed after the : EVAL command . ;; :REPORT Report the condition the debugger was invoked with. ;; :CONDITION Return the condition the debugger was invoked with. : Print available restarts . ;; :RESTART <n>, <n> Invoke a restart with the given number. ;; ;; Any non-keyword non-integer form is evaluated. ") (deftest debugger.help.2 (restart-case (run-debugger-command :help "") (abort ()) (continue ())) This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - ;; ;; Available debugger commands: ;; :HELP Show this text. : EVAL < form > Evaluate a form typed after the : EVAL command . ;; :REPORT Report the condition the debugger was invoked with. ;; :CONDITION Return the condition the debugger was invoked with. : Print available restarts . ;; :RESTART <n>, <n> Invoke a restart with the given number. : , : Q Invoke an ABORT restart . ;; :CONTINUE, :C Invoke a CONTINUE restart. ;; ;; Any non-keyword non-integer form is evaluated. ") (deftest debugger.help.3 (let* ((condition (make-condition 'simple-condition :format-control "Bar")) (hook (lambda (condition stream) (format stream "~&;; :FOO ~A~%" condition))) (portable-condition-system::*help-hooks* (list hook))) (run-debugger-command :help "" condition)) This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - ;; ;; Available debugger commands: ;; :HELP Show this text. : EVAL < form > Evaluate a form typed after the : EVAL command . ;; :REPORT Report the condition the debugger was invoked with. ;; :CONDITION Return the condition the debugger was invoked with. : Print available restarts . ;; :RESTART <n>, <n> Invoke a restart with the given number. : FOO Bar ;; ;; Any non-keyword non-integer form is evaluated. ") (defun run-repl-command (input-string &optional condition) (with-input-from-string (input input-string) (with-output-to-string (output) (let ((stream (make-two-way-stream input output))) (portable-condition-system::read-eval-print-command stream condition))))) (deftest debugger.repl.1 (run-repl-command "(+ 2 2)") #.(format nil "[0] Debug> ~%4")) (deftest debugger.repl.2 (run-repl-command ":eval (+ 2 2)") #.(format nil "[0] Debug> ~%4"))
null
https://raw.githubusercontent.com/Apress/common-lisp-condition-system/7f4533e20d6397a59ca5bbfdc139b3389a135c34/Sources%20-%20PCS/t/debugger.lisp
lisp
t/debugger.lisp Debugger level 0 entered on PORTABLE-CONDITION-SYSTEM:CONDITION: Condition PORTABLE-CONDITION-SYSTEM:CONDITION was signaled. The value 42 is not of type Debugger level 0 entered on PORTABLE-CONDITION-SYSTEM:SIMPLE-CONDITION: #<error while reporting condition> There is no active ABORT restart. There is no active ABORT restart. There is no active CONTINUE restart. There is no active CONTINUE restart. No available restarts. Available restarts: 0: [ABORT] Abort. Available restarts: 0: [ABORT] #<error while reporting restart> There is no restart with number 0. Available debugger commands: :HELP Show this text. :REPORT Report the condition the debugger was invoked with. :CONDITION Return the condition the debugger was invoked with. :RESTART <n>, <n> Invoke a restart with the given number. Any non-keyword non-integer form is evaluated. Available debugger commands: :HELP Show this text. :REPORT Report the condition the debugger was invoked with. :CONDITION Return the condition the debugger was invoked with. :RESTART <n>, <n> Invoke a restart with the given number. :CONTINUE, :C Invoke a CONTINUE restart. Any non-keyword non-integer form is evaluated. Available debugger commands: :HELP Show this text. :REPORT Report the condition the debugger was invoked with. :CONDITION Return the condition the debugger was invoked with. :RESTART <n>, <n> Invoke a restart with the given number. Any non-keyword non-integer form is evaluated.
(in-package #:portable-condition-system/test) (defun run-debugger-command (command input-string &optional condition &rest args) (with-input-from-string (input input-string) (with-output-to-string (output) (let ((stream (make-two-way-stream input output))) (apply #'portable-condition-system::run-debugger-command command stream condition args))))) (deftest debugger.eval.1 (run-debugger-command :eval "(+ 2 2)") "4") (deftest debugger.eval.2 (let ((*package* (find-package '#:portable-condition-system/test))) (handler-case (run-debugger-command :eval "(error \"42\")") (error () 'good))) good) (deftest debugger.report.1 (let ((*package* (find-package :keyword)) (condition (make-condition 'condition))) (run-debugger-command :report "" condition)) ") (deftest debugger.report.2 (let ((*package* (find-package :keyword)) (portable-condition-system::*debug-level* 42) (condition (make-condition 'type-error :datum 42 :expected-type :keyword))) (run-debugger-command :report "" condition)) Debugger level 42 entered on PORTABLE - CONDITION - SYSTEM : TYPE - ERROR : : KEYWORD . ") (deftest debugger.report.3 (let* ((*package* (find-package :keyword)) (error-fn (lambda (&rest args) (declare (ignore args)) (error "Error reporting condition"))) (condition (make-condition 'simple-condition :format-control error-fn))) (run-debugger-command :report "" condition)) ") (defvar *debugger.condition* (make-condition 'condition)) (deftest debugger.condition.1 (eqt (first (portable-condition-system::run-debugger-command :condition nil *debugger.condition*)) *debugger.condition*) t) (deftest debugger.abort.1 (run-debugger-command :abort "") ") (deftest debugger.abort.2 (restart-case (run-debugger-command :abort "") (abort () 'good)) good) (deftest debugger.q.1 (run-debugger-command :q "") ") (deftest debugger.q.2 (restart-case (run-debugger-command :q "") (abort () 'good)) good) (deftest debugger.continue.1 (run-debugger-command :continue "") ") (deftest debugger.continue.2 (restart-case (run-debugger-command :continue "") (continue () 'good)) good) (deftest debugger.c.1 (run-debugger-command :c "") ") (deftest debugger.c.2 (restart-case (run-debugger-command :c "") (continue () 'good)) good) (deftest debugger.restarts.1 (run-debugger-command :restarts "" (make-condition 'condition)) ") (deftest debugger.restarts.2 (restart-case (run-debugger-command :restarts "" (make-condition 'condition)) (abort () :report "Abort.") (retry () :report "Retry.") (fail () :report "Fail.")) 1 : [ RETRY ] Retry . 2 : [ FAIL ] Fail . ") (deftest debugger.restarts.3 (restart-case (run-debugger-command :restarts "" (make-condition 'condition)) (abort () :report (lambda (stream) (declare (ignore stream)) (error "Error reporting restart")))) ") (deftest debugger.restart.1 (run-debugger-command :restart "" (make-condition 'condition) 0) ") (deftest debugger.restart.2 (restart-case (run-debugger-command :restart "" (make-condition 'condition) 1) (abort () 'bad) (retry () 'good) (fail () 'ugly)) good) (deftest debugger.help.1 (run-debugger-command :help "") This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - : EVAL < form > Evaluate a form typed after the : EVAL command . : Print available restarts . ") (deftest debugger.help.2 (restart-case (run-debugger-command :help "") (abort ()) (continue ())) This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - : EVAL < form > Evaluate a form typed after the : EVAL command . : Print available restarts . : , : Q Invoke an ABORT restart . ") (deftest debugger.help.3 (let* ((condition (make-condition 'simple-condition :format-control "Bar")) (hook (lambda (condition stream) (format stream "~&;; :FOO ~A~%" condition))) (portable-condition-system::*help-hooks* (list hook))) (run-debugger-command :help "" condition)) This is the standard debugger of the Portable Condition System . The debugger read - eval - print loop supports the standard REPL variables : * * * * * * + + + + + + / // /// - : EVAL < form > Evaluate a form typed after the : EVAL command . : Print available restarts . : FOO Bar ") (defun run-repl-command (input-string &optional condition) (with-input-from-string (input input-string) (with-output-to-string (output) (let ((stream (make-two-way-stream input output))) (portable-condition-system::read-eval-print-command stream condition))))) (deftest debugger.repl.1 (run-repl-command "(+ 2 2)") #.(format nil "[0] Debug> ~%4")) (deftest debugger.repl.2 (run-repl-command ":eval (+ 2 2)") #.(format nil "[0] Debug> ~%4"))
a89c31907b49f38c0c2d4d10def1d0927d94e74b9c706cf95804f55ebc01ae16
dzaporozhets/clojure-web-application
crypt.clj
(ns sample.crypt (:require [clojurewerkz.scrypt.core :as sc])) (defn encrypt [string] (sc/encrypt string 16384 8 1)) (defn verify [string encrypted] (boolean (if (and string encrypted) (sc/verify string encrypted))))
null
https://raw.githubusercontent.com/dzaporozhets/clojure-web-application/8d813fc95080a8ebc9532c0a4067f540f7f91553/src/sample/crypt.clj
clojure
(ns sample.crypt (:require [clojurewerkz.scrypt.core :as sc])) (defn encrypt [string] (sc/encrypt string 16384 8 1)) (defn verify [string encrypted] (boolean (if (and string encrypted) (sc/verify string encrypted))))
f0269552f51e64c4677bd1a5dfb8a174becd34feeed6a48b61efb3a237edb04d
dbuenzli/topkg
topkg_vcs.mli
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * VCS repositories . See { ! . Vcs } for documentation . See {!Topkg.Vcs} for documentation. *) * { 1 VCS } open Topkg_result type kind = [ `Git | `Hg ] val pp_kind : Format.formatter -> kind -> unit type commit_ish = string type t val kind : t -> kind val dir : t -> Topkg_fpath.t val find : ?dir:Topkg_fpath.t -> unit -> t option result val get : ?dir:Topkg_fpath.t -> unit -> t result val cmd : t -> Topkg_cmd.t val pp : Format.formatter -> t -> unit val is_dirty : t -> bool result val not_dirty : t -> unit result val file_is_dirty : t -> Topkg_fpath.t -> bool result val head : ?dirty:bool -> t -> string result val commit_id : ?dirty:bool -> ?commit_ish:string -> t -> string result val commit_ptime_s : ?commit_ish:commit_ish -> t -> int result val describe : ?dirty:bool -> ?commit_ish:string -> t -> string result val tags : t -> string list result val changes : ?until:string -> t -> after:string -> (string * string) list result val tracked_files : ?tree_ish:string -> t -> Topkg_fpath.t list result val clone : t -> dir:Topkg_fpath.t -> unit result val checkout : ?branch:string -> t -> commit_ish:string -> unit result val commit_files : ?msg:string -> t -> Topkg_fpath.t list -> unit result val delete_tag : t -> string -> unit result val tag : ?force:bool -> ?sign:bool -> ?msg:string -> ?commit_ish:string -> t -> string -> unit result --------------------------------------------------------------------------- Copyright ( c ) 2016 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 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 . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli 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. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/topkg/ea1e0981a18ce4160ec21e8a73f67cb748059671/src/topkg_vcs.mli
ocaml
--------------------------------------------------------------------------- Copyright ( c ) 2016 . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) * VCS repositories . See { ! . Vcs } for documentation . See {!Topkg.Vcs} for documentation. *) * { 1 VCS } open Topkg_result type kind = [ `Git | `Hg ] val pp_kind : Format.formatter -> kind -> unit type commit_ish = string type t val kind : t -> kind val dir : t -> Topkg_fpath.t val find : ?dir:Topkg_fpath.t -> unit -> t option result val get : ?dir:Topkg_fpath.t -> unit -> t result val cmd : t -> Topkg_cmd.t val pp : Format.formatter -> t -> unit val is_dirty : t -> bool result val not_dirty : t -> unit result val file_is_dirty : t -> Topkg_fpath.t -> bool result val head : ?dirty:bool -> t -> string result val commit_id : ?dirty:bool -> ?commit_ish:string -> t -> string result val commit_ptime_s : ?commit_ish:commit_ish -> t -> int result val describe : ?dirty:bool -> ?commit_ish:string -> t -> string result val tags : t -> string list result val changes : ?until:string -> t -> after:string -> (string * string) list result val tracked_files : ?tree_ish:string -> t -> Topkg_fpath.t list result val clone : t -> dir:Topkg_fpath.t -> unit result val checkout : ?branch:string -> t -> commit_ish:string -> unit result val commit_files : ?msg:string -> t -> Topkg_fpath.t list -> unit result val delete_tag : t -> string -> unit result val tag : ?force:bool -> ?sign:bool -> ?msg:string -> ?commit_ish:string -> t -> string -> unit result --------------------------------------------------------------------------- Copyright ( c ) 2016 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 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 . --------------------------------------------------------------------------- Copyright (c) 2016 Daniel C. Bünzli 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. ---------------------------------------------------------------------------*)
f8ff9c20aa5dda9517fb9804c921c9ab9726d1ba2883449c3c429a3fa989ce64
Soostone/uri-bytestring
QQ.hs
# LANGUAGE CPP # {-# LANGUAGE GADTs #-} # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # module URI.ByteString.QQ ( uri, relativeRef, ) where import Data.ByteString.Char8 import Instances.TH.Lift () import Language.Haskell.TH.Quote import URI.ByteString -- | Allows uri literals via QuasiQuotes language extension. -- -- >>> {-# LANGUAGE QuasiQuotes #-} -- >>> stackage :: URI -- >>> stackage = [uri||] uri :: QuasiQuoter uri = QuasiQuoter { quoteExp = \s -> let parsedURI = either (\err -> error $ show err) id (parseURI laxURIParserOptions (pack s)) in [|parsedURI|], quotePat = error "Not implemented.", quoteType = error "Not implemented.", quoteDec = error "Not implemented." } ------------------------------------------------------------------------------- -- | Allows relative ref literals via QuasiQuotes language extension. -- -- >>> {-# LANGUAGE QuasiQuotes #-} > > > ref : : RelativeRef -- >>> ref = [relativeRef|/foo?bar=baz#quux|] relativeRef :: QuasiQuoter relativeRef = QuasiQuoter { quoteExp = \s -> let parsedURI = either (\err -> error $ show err) id (parseRelativeRef laxURIParserOptions (pack s)) in [|parsedURI|], quotePat = error "Not implemented.", quoteType = error "Not implemented.", quoteDec = error "Not implemented." }
null
https://raw.githubusercontent.com/Soostone/uri-bytestring/1c0134cb4a15a9740d5a54807f331f511a52d1d8/src/URI/ByteString/QQ.hs
haskell
# LANGUAGE GADTs # | Allows uri literals via QuasiQuotes language extension. >>> {-# LANGUAGE QuasiQuotes #-} >>> stackage :: URI >>> stackage = [uri||] ----------------------------------------------------------------------------- | Allows relative ref literals via QuasiQuotes language extension. >>> {-# LANGUAGE QuasiQuotes #-} >>> ref = [relativeRef|/foo?bar=baz#quux|]
# LANGUAGE CPP # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # module URI.ByteString.QQ ( uri, relativeRef, ) where import Data.ByteString.Char8 import Instances.TH.Lift () import Language.Haskell.TH.Quote import URI.ByteString uri :: QuasiQuoter uri = QuasiQuoter { quoteExp = \s -> let parsedURI = either (\err -> error $ show err) id (parseURI laxURIParserOptions (pack s)) in [|parsedURI|], quotePat = error "Not implemented.", quoteType = error "Not implemented.", quoteDec = error "Not implemented." } > > > ref : : RelativeRef relativeRef :: QuasiQuoter relativeRef = QuasiQuoter { quoteExp = \s -> let parsedURI = either (\err -> error $ show err) id (parseRelativeRef laxURIParserOptions (pack s)) in [|parsedURI|], quotePat = error "Not implemented.", quoteType = error "Not implemented.", quoteDec = error "Not implemented." }
fb57d42212d5eb5b2f49f6e9709a8f917c823fe4d463ee46d1b4b5eb9a1221aa
latacora/recidiffist-cli
project.clj
(defproject recidiffist-cli "0.2.0-SNAPSHOT" :description "Diffs for structured data, from the CLI" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/tools.cli "0.4.1"] [cheshire "5.8.1"] [recidiffist "0.11.0"]] :main ^:skip-aot recidiffist-cli.core :target-path "target/%s" :native-image {:name "recidiffist" :opts ["--verbose"]} :profiles {:uberjar {:aot :all :native-image {:opts ["--verbose" "--no-fallback" "-Dclojure.compiler.direct-linking=true" "-H:+ReportExceptionStackTraces" "--report-unsupported-elements-at-runtime" "--initialize-at-build-time"]}}} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]])
null
https://raw.githubusercontent.com/latacora/recidiffist-cli/0dd4d88332eea0a7f5cc9d53905be97abe4d8af8/project.clj
clojure
(defproject recidiffist-cli "0.2.0-SNAPSHOT" :description "Diffs for structured data, from the CLI" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.10.0"] [org.clojure/tools.cli "0.4.1"] [cheshire "5.8.1"] [recidiffist "0.11.0"]] :main ^:skip-aot recidiffist-cli.core :target-path "target/%s" :native-image {:name "recidiffist" :opts ["--verbose"]} :profiles {:uberjar {:aot :all :native-image {:opts ["--verbose" "--no-fallback" "-Dclojure.compiler.direct-linking=true" "-H:+ReportExceptionStackTraces" "--report-unsupported-elements-at-runtime" "--initialize-at-build-time"]}}} :deploy-repositories [["releases" :clojars] ["snapshots" :clojars]])
234385857504d818245110bb2021ed79f92d91e097981c7b7b428e2edc3da979
babashka/babashka
udp_test.clj
(ns babashka.udp-test (:require [babashka.test-utils :as tu] [clojure.test :refer [deftest is]]) (:import [java.io StringWriter] [java.net DatagramPacket DatagramSocket])) (set! *warn-on-reflection* true) (deftest udp-test (let [server (DatagramSocket. 8125) sw (StringWriter.) fut (future (let [buf (byte-array 1024) packet (DatagramPacket. buf 1024) _ (.receive server packet) non-zero-bytes (filter #(not (zero? %)) (.getData packet)) non-zero-bytes (byte-array non-zero-bytes)] (binding [*out* sw] (println (String. non-zero-bytes "UTF-8")))))] (while (not (realized? fut)) (tu/bb nil "-e" "(load-file (io/file \"test-resources\" \"babashka\" \"statsd.clj\"))" "-e" "(require '[statsd-client :as c])" "-e" "(c/increment :foo)")) (is (= ":foo:1|c\n" (tu/normalize (str sw))))))
null
https://raw.githubusercontent.com/babashka/babashka/35e2cd9d057cef8a634d409c51ce78763d5ed56e/test/babashka/udp_test.clj
clojure
(ns babashka.udp-test (:require [babashka.test-utils :as tu] [clojure.test :refer [deftest is]]) (:import [java.io StringWriter] [java.net DatagramPacket DatagramSocket])) (set! *warn-on-reflection* true) (deftest udp-test (let [server (DatagramSocket. 8125) sw (StringWriter.) fut (future (let [buf (byte-array 1024) packet (DatagramPacket. buf 1024) _ (.receive server packet) non-zero-bytes (filter #(not (zero? %)) (.getData packet)) non-zero-bytes (byte-array non-zero-bytes)] (binding [*out* sw] (println (String. non-zero-bytes "UTF-8")))))] (while (not (realized? fut)) (tu/bb nil "-e" "(load-file (io/file \"test-resources\" \"babashka\" \"statsd.clj\"))" "-e" "(require '[statsd-client :as c])" "-e" "(c/increment :foo)")) (is (= ":foo:1|c\n" (tu/normalize (str sw))))))
5ef52db5b276cf4393f4bcdf22b593625b9d93211466f782bf40c7ac43591bb2
tarides/opam-monorepo
list.ml
include ListLabels
null
https://raw.githubusercontent.com/tarides/opam-monorepo/5b70c915f30fa3d8eb312fadf978b5f1aa9ab5b3/stdext/list.ml
ocaml
include ListLabels
762a937c136455e7ded14e443784e47ca864a7faf11608852b9b8d13c331cea9
kit-ty-kate/visitors
VisitorsRuntimeBootstrap.cppo.ml
type 'a option = | None | Some of 'a and 'a ref = { mutable contents: 'a } #if OCAML_VERSION >= (4, 03, 0) and 'a list = | Nil | Cons of 'a * 'a list and ('a, 'b) result = | Ok of 'a | Error of 'b #endif [@@deriving visitors { variety = "iter"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "map"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "endo"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "reduce"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "mapreduce"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "iter2"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "map2"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "reduce2"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "mapreduce2"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] } ]
null
https://raw.githubusercontent.com/kit-ty-kate/visitors/fc53cc486178781e0b1e581eced98e07facb7d29/test/VisitorsRuntimeBootstrap.cppo.ml
ocaml
type 'a option = | None | Some of 'a and 'a ref = { mutable contents: 'a } #if OCAML_VERSION >= (4, 03, 0) and 'a list = | Nil | Cons of 'a * 'a list and ('a, 'b) result = | Ok of 'a | Error of 'b #endif [@@deriving visitors { variety = "iter"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "map"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "endo"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "reduce"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "mapreduce"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "iter2"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "map2"; public = []; polymorphic = true; data = false; nude = true }, visitors { variety = "reduce2"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] }, visitors { variety = "mapreduce2"; public = []; polymorphic = true; data = false; nude = true; ancestors = ["VisitorsRuntime.monoid"] } ]
143910eb81057b5f7823451e98e459abf305afe0b0e4de5402751db05f98d958
baryluk/ex11
swFlashButton.erl
-module(swFlashButton). Copyright ( C ) 2004 by ( ) %% All rights reserved. %% The copyright holder hereby grants the rights of usage, distribution %% and modification of this software to everyone and for any purpose, as %% long as this license and the copyright notice above are preserved and %% not modified. There is no warranty for this software. Create : 2004 - 01 - 01 by -export([make/9]). -import(ex11_lib, [eChangeGC/2, eConfigureWindow/2,reply/2, ePolyFillRectangle/3, ePolyText8/5,eUnmapWindow/1,eMapWindow/1, mkRectangle/4,rpc/2,sleep/1,xCreateGC/2, xClearArea/1,xColor/2, xDo/2,xFlush/1,xVar/2]). -include("sw.hrl"). %% State = {Fun,Expose,In} make(Parent, X, Y, Width, Ht, Border, C1, C2, Str) -> spawn_link(fun() -> init(Parent, X, Y, Width, Ht, Border, C1, C2, Str) end). init(Parent, X, Y, Width, Ht, Border, C1, C2, Str) -> Display = rpc(Parent, display), Attach = rpc(Parent, mountPoint), Wargs = #win{x=X, y=Y, border=Border,width=Width,ht=Ht,color=C1, type=button, parent=Attach, mask = ?EVENT_EXPOSURE bor ?EVENT_BUTTON_PRESS bor ?EVENT_ENTER_WINDOW bor ?EVENT_LEAVE_WINDOW }, Wargs1 = sw:mkWindow(Display, Parent, Wargs), Win = Wargs1#win.win, C1x = xColor(Display, C1), C2x = xColor(Display, C2), GC = xCreateGC(Display, [{function,copy}, {line_width,1}, {line_style,solid}, {foreground, C1x}]), %% on expose we just set the text B = [ePolyText8(Win, xVar(Display, sysFontId), 10, 18, Str)], %% On Enter we change to C2 Enter = fun() -> xDo(Display, eChangeGC(GC, [{foreground,C2x}])), xDo(Display, ePolyFillRectangle(Win, GC, [mkRectangle(0,0,Width, Ht)])), xDo(Display, B), xFlush(Display) end, Leave = fun() -> xDo(Display, eChangeGC(GC, [{foreground,C1x}])), xDo(Display, ePolyFillRectangle(Win, GC, [mkRectangle(0,0,Width, Ht)])), xDo(Display, B), xFlush(Display) end, loop(Display, fun(_) -> void end, fun() -> void end, fun() -> void end, Enter,Leave, Wargs1). loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs) -> receive {event,_,expose,_} -> Leave(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event,_,enterNotify,_} -> Enter(), FunE(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event,_,leaveNotify,_} -> Leave(), FunL(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event, _, buttonPress, X} -> flash(Display, Wargs#win.win,Leave), Fun(X), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {onClick, Fun1} -> loop(Display, Fun1, FunE, FunL, Enter,Leave,Wargs); {onEnter, Fun1} -> loop(Display, Fun, Fun1, FunL, Enter,Leave,Wargs); {onLeave, Fun1} -> loop(Display, Fun, FunE, Fun1, Enter,Leave,Wargs); Other -> Wargs1 = sw:generic(Other, Display, Wargs), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs1) end. flash(Display, Win, Draw) -> spawn(fun() -> xDo(Display, xClearArea(Win)), xFlush(Display), sleep(200), Draw(), xFlush(Display) end).
null
https://raw.githubusercontent.com/baryluk/ex11/be8abc64ab9fb50611f93d6631fc33ffdee08fdb/widgets/swFlashButton.erl
erlang
All rights reserved. The copyright holder hereby grants the rights of usage, distribution and modification of this software to everyone and for any purpose, as long as this license and the copyright notice above are preserved and not modified. There is no warranty for this software. State = {Fun,Expose,In} on expose we just set the text On Enter we change to C2
-module(swFlashButton). Copyright ( C ) 2004 by ( ) Create : 2004 - 01 - 01 by -export([make/9]). -import(ex11_lib, [eChangeGC/2, eConfigureWindow/2,reply/2, ePolyFillRectangle/3, ePolyText8/5,eUnmapWindow/1,eMapWindow/1, mkRectangle/4,rpc/2,sleep/1,xCreateGC/2, xClearArea/1,xColor/2, xDo/2,xFlush/1,xVar/2]). -include("sw.hrl"). make(Parent, X, Y, Width, Ht, Border, C1, C2, Str) -> spawn_link(fun() -> init(Parent, X, Y, Width, Ht, Border, C1, C2, Str) end). init(Parent, X, Y, Width, Ht, Border, C1, C2, Str) -> Display = rpc(Parent, display), Attach = rpc(Parent, mountPoint), Wargs = #win{x=X, y=Y, border=Border,width=Width,ht=Ht,color=C1, type=button, parent=Attach, mask = ?EVENT_EXPOSURE bor ?EVENT_BUTTON_PRESS bor ?EVENT_ENTER_WINDOW bor ?EVENT_LEAVE_WINDOW }, Wargs1 = sw:mkWindow(Display, Parent, Wargs), Win = Wargs1#win.win, C1x = xColor(Display, C1), C2x = xColor(Display, C2), GC = xCreateGC(Display, [{function,copy}, {line_width,1}, {line_style,solid}, {foreground, C1x}]), B = [ePolyText8(Win, xVar(Display, sysFontId), 10, 18, Str)], Enter = fun() -> xDo(Display, eChangeGC(GC, [{foreground,C2x}])), xDo(Display, ePolyFillRectangle(Win, GC, [mkRectangle(0,0,Width, Ht)])), xDo(Display, B), xFlush(Display) end, Leave = fun() -> xDo(Display, eChangeGC(GC, [{foreground,C1x}])), xDo(Display, ePolyFillRectangle(Win, GC, [mkRectangle(0,0,Width, Ht)])), xDo(Display, B), xFlush(Display) end, loop(Display, fun(_) -> void end, fun() -> void end, fun() -> void end, Enter,Leave, Wargs1). loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs) -> receive {event,_,expose,_} -> Leave(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event,_,enterNotify,_} -> Enter(), FunE(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event,_,leaveNotify,_} -> Leave(), FunL(), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {event, _, buttonPress, X} -> flash(Display, Wargs#win.win,Leave), Fun(X), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs); {onClick, Fun1} -> loop(Display, Fun1, FunE, FunL, Enter,Leave,Wargs); {onEnter, Fun1} -> loop(Display, Fun, Fun1, FunL, Enter,Leave,Wargs); {onLeave, Fun1} -> loop(Display, Fun, FunE, Fun1, Enter,Leave,Wargs); Other -> Wargs1 = sw:generic(Other, Display, Wargs), loop(Display, Fun, FunE, FunL, Enter,Leave,Wargs1) end. flash(Display, Win, Draw) -> spawn(fun() -> xDo(Display, xClearArea(Win)), xFlush(Display), sleep(200), Draw(), xFlush(Display) end).
d95b3380546cfb3c7ff829169bad1eefbe263bfbbd5ec32eb2725bde8d07e6ad
Eduap-com/WordMat
rat3e.lisp
-*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The data in this file contains enhancments. ;;;;; ;;; ;;;;; Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ; ;;; All rights reserved ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( c ) Copyright 1982 Massachusetts Institute of Technology ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (macsyma-module rat3e) This is the rational function package part 5 . ;; It includes the conversion and top-level routines used ;; by the rest of the functions. (declare-top (special intbs* alflag var dosimp alc $myoptions vlist scanmapp radlist expsumsplit *ratsimp* mplc* $ratsimpexpons $expop $expon $negdistrib $gcd)) (defmvar genvar nil "List of gensyms used to point to kernels from within polynomials. The values cell and property lists of these symbols are used to store various information.") (defmvar genpairs nil) (defmvar varlist nil "List of kernels") (defmvar *fnewvarsw nil) (defmvar *ratweights nil) (defvar *ratsimp* nil) (defmvar factorresimp nil "If `t' resimplifies factor(x-y) to x-y") ;; User level global variables. (defmvar $keepfloat nil "If `t' floating point coeffs are not converted to rationals") (defmvar $factorflag nil "If `t' constant factor of polynomial is also factored") (defmvar $dontfactor '((mlist))) (defmvar $norepeat t) (defmvar $ratweights '((mlist simp))) (defmvar $ratfac nil "If `t' cre-forms are kept factored") (defmvar $algebraic nil) (defmvar $ratvars '((mlist simp))) (defmvar $facexpand t) (declare-top (special evp $infeval)) (defun mrateval (x) (let ((varlist (caddar x))) (cond ((and evp $infeval) (meval ($ratdisrep x))) ((or evp (and $float $keepfloat) (not (alike varlist (mapcar #'meval varlist)))) (ratf (meval ($ratdisrep x)))) (t x)))) (defprop mrat mrateval mfexpr*) (defmfun $ratnumer (x) (cond ((mbagp x) (cons (car x) (mapcar '$ratnumer (cdr x)))) (t (setq x (taychk2rat x)) (cons (car x) (cons (cadr x) 1))))) (defmfun $ratdenom (x) (cond ((mbagp x) (cons (car x) (mapcar '$ratdenom (cdr x)))) (t (setq x (taychk2rat x)) (cons (car x) (cons (cddr x) 1))))) (defun taychk2rat (x) (cond ((and ($ratp x) (member 'trunc (cdar x) :test #'eq)) ($taytorat x)) (t ($rat x)))) (defmvar tellratlist nil) (defun tellratdisp (x) (pdisrep+ (trdisp1 (cdr x) (car x)))) (defun trdisp1 (p var) (cond ((null p) nil) (t (cons (pdisrep* (if (mtimesp (cadr p)) (copy-list (cadr p)) (cadr p)) ;prevents clobbering p (pdisrep! (car p) var)) (trdisp1 (cddr p) var))))) (defmfun $untellrat (&rest args) (dolist (x args) (if (setq x (assol x tellratlist)) (setq tellratlist (remove x tellratlist :test #'equal)))) (cons '(mlist) (mapcar #'tellratdisp tellratlist))) (defmfun $tellrat (&rest args) (mapc #'tellrat1 args) (unless (null args) (add2lnc 'tellratlist $myoptions)) (cons '(mlist) (mapcar #'tellratdisp tellratlist))) (defun tellrat1 (x &aux varlist genvar $algebraic $ratfac algvar) (setq x ($totaldisrep x)) (and (not (atom x)) (eq (caar x) 'mequal) (newvar (cadr x))) (newvar (setq x (meqhk x))) (unless varlist (merror (intl:gettext "tellrat: argument must be a polynomial; found: ~M") x)) (setq algvar (car (last varlist))) (setq x (p-terms (primpart (cadr (ratrep* x))))) (unless (equal (pt-lc x) 1) (merror (intl:gettext "tellrat: minimal polynomial must be monic."))) (do ((p (pt-red x) (pt-red p))) ((ptzerop p)) (setf (pt-lc p) (pdis (pt-lc p)))) (setq algvar (cons algvar x)) (if (setq x (assol (car algvar) tellratlist)) (setq tellratlist (remove x tellratlist :test #'equal))) (push algvar tellratlist)) (defmfun $printvarlist () (cons '(mlist) (copy-tree varlist))) (defmfun $showratvars (e) (cons '(mlist simp) (cond (($ratp e) (if (member 'trunc (cdar e) :test #'eq) (setq e ($taytorat e))) (caddar (minimize-varlist e))) (t (let (varlist) (lnewvar e) varlist))))) (defmfun $ratvars (&rest args) (add2lnc '$ratvars $myoptions) (setq $ratvars (cons '(mlist simp) (setq varlist (mapfr1 args varlist))))) (defun mapfr1 (l varlist) (mapcar #'(lambda (z) (fr1 z varlist)) l)) (defmvar inratsimp nil) (defmfun $fullratsimp (exp &rest argl) (prog (exp1) loop (setq exp1 (simplify (apply #'$ratsimp (cons exp argl)))) (when (alike1 exp exp1) (return exp)) (setq exp exp1) (go loop))) (defun fullratsimp (l) (let (($expop 0) ($expon 0) (inratsimp t) $ratsimpexpons) (when (not ($ratp l)) ;; Not a mrat expression. Remove the special representation. (setq l (specrepcheck l))) (setq l ($totaldisrep l)) (fr1 l varlist))) (defmfun $totaldisrep (l) (cond ((atom l) l) ((not (among 'mrat l)) l) ((eq (caar l) 'mrat) (ratdisrep l)) (t (cons (delete 'ratsimp (car l) :test #'eq) (mapcar '$totaldisrep (cdr l)))))) VARLIST HAS MAIN VARIABLE AT END (defun joinvarlist (cdrl) (mapc #'(lambda (z) (unless (memalike z varlist) (push z varlist))) (reverse (mapfr1 cdrl nil)))) (defmfun $rat (e &rest vars) (cond ((not (null vars)) (let (varlist) (joinvarlist vars) (lnewvar e) (rat0 e))) (t (lnewvar e) (rat0 e)))) (defun rat0 (exp) ;SIMP FLAGS? (if (mbagp exp) (cons (car exp) (mapcar #'rat0 (cdr exp))) (ratf exp))) (defmfun $ratsimp (e &rest vars) (cond ((not (null vars)) (let (varlist) (joinvarlist vars) (fullratsimp e))) (t (fullratsimp e)))) ;; $RATSIMP, $FULLRATSIMP and $RAT allow for optional extra ;; arguments specifying the VARLIST. ;;;PSQFR HAS NOT BEEN CHANGED TO MAKE USE OF THE SQFR FLAGS YET (defmfun $sqfr (x) (let ((varlist (cdr $ratvars)) genvar $keepfloat $ratfac) (sublis '((factored . sqfred) (irreducible . sqfr)) (ffactor x #'psqfr)))) (declare-top (special fn)) (defun whichfn (p) (cond ((and (mexptp p) (integerp (caddr p))) (list '(mexpt) (whichfn (cadr p)) (caddr p))) ((mtimesp p) (cons '(mtimes) (mapcar #'whichfn (cdr p)))) (fn (ffactor p #'pfactor)) (t (factoralg p)))) (declare-top (special var)) (defmvar adn* 1 "common denom for algebraic coefficients") (defun factoralg (p) (prog (alc ans adn* $gcd) (setq $gcd '$algebraic) (when (or (atom p) (numberp p)) (return p)) (setq adn* 1) (when (and (not $nalgfac) (not intbs*)) (setq intbs* (findibase minpoly*))) (setq algfac* t) (setq ans (ffactor p #'pfactor)) (cond ((eq (caar ans) 'mplus) (return p)) (mplc* (setq ans (albk ans)))) (if (and (not alc) (equal 1 adn*)) (return ans)) (setq ans (partition ans (car (last varlist)) 1)) (return (mul (let ((dosimp t)) (mul `((rat) 1 ,adn*) (car ans) (if alc (pdis alc) 1))) (cdr ans))))) (defun albk (p) ;to undo monicizing subst (let ((alpha (pdis alpha)) ($ratfac t)) (declare (special alpha)) ;; don't multiply them back out assumes * is int alpha p))) (defmfun $gfactor (p &aux (gauss t)) (when ($ratp p) (setq p ($ratdisrep p))) (setq p ($factor (subst '%i '$%i p) '((mplus) 1 ((mexpt) %i 2)))) (setq p (sublis '((factored . gfactored) (irreducible . irreducibleg)) p)) (let (($expop 0) ($expon 0) $negdistrib) (maxima-substitute '$%i '%i p))) (defmfun $factor (e &optional (mp nil mp?)) (let ($intfaclim (varlist (cdr $ratvars)) genvar ans) (setq ans (if mp? (factor e mp) (factor e))) (if (and factorresimp $negdistrib (mtimesp ans) (null (cdddr ans)) (equal (cadr ans) -1) (mplusp (caddr ans))) (let (($expop 0) ($expon 0)) ($multthru ans)) ans))) (defun factor (e &optional (mp nil mp?)) (let ((tellratlist nil) (varlist varlist) (genvar nil) ($gcd $gcd) ($negdistrib $negdistrib)) (prog (fn var mm* mplc* intbs* alflag minpoly* alpha p algfac* $keepfloat $algebraic cargs) (declare (special cargs fn alpha)) (unless (member $gcd *gcdl* :test #'eq) (setq $gcd (car *gcdl*))) (let ($ratfac) (setq p e mm* 1 cargs (if mp? (list mp) nil)) (when (symbolp p) (return p)) (when ($numberp p) (return (let (($factorflag (not scanmapp))) (factornumber p)))) (when (mbagp p) (return (cons (car p) (mapcar #'(lambda (x) (apply #'factor (cons x cargs))) (cdr p))))) (cond (mp? (setq alpha (meqhk mp)) (newvar alpha) (setq minpoly* (cadr (ratrep* alpha))) (when (or (pcoefp minpoly*) (not (univar (cdr minpoly*))) (< (cadr minpoly*) 2)) (merror (intl:gettext "factor: second argument must be a nonlinear, univariate polynomial; found: ~M") alpha)) (setq alpha (pdis (list (car minpoly*) 1 1)) mm* (cadr minpoly*)) (unless (equal (caddr minpoly*) 1) (setq mplc* (caddr minpoly*)) (setq minpoly* (pmonz minpoly*)) (setq p (maxima-substitute (div alpha mplc*) alpha p))) (setq $algebraic t) ($tellrat(pdis minpoly*)) (setq algfac* t)) (t (setq fn t))) (unless scanmapp (setq p (let (($ratfac t)) (sratsimp p)))) (newvar p) (when (symbolp p) (return p)) (when (numberp p) (return (let (($factorflag (not scanmapp))) (factornumber p)))) (setq $negdistrib nil) (setq p (let ($factorflag ($ratexpand $facexpand)) (whichfn p)))) (setq p (let (($expop 0) ($expon 0)) (simplify p))) (cond ((mnump p) (return (factornumber p))) ((atom p) (return p))) (and $ratfac (not $factorflag) ($ratp e) (return ($rat p))) (and $factorflag (mtimesp p) (mnump (cadr p)) (setq alpha (factornumber (cadr p))) (cond ((alike1 alpha (cadr p))) ((mtimesp alpha) (setq p (cons (car p) (append (cdr alpha) (cddr p))))) (t (setq p (cons (car p) (cons alpha (cddr p))))))) (when (null (member 'factored (car p) :test #'eq)) (setq p (cons (append (car p) '(factored)) (cdr p)))) (return p)))) (defun factornumber (n) (setq n (nretfactor1 (nratfact (cdr ($rat n))))) (cond ((cdr n) (cons '(mtimes simp factored) (if (equal (car n) -1) (cons (car n) (nreverse (cdr n))) (nreverse n)))) ((atom (car n)) (car n)) (t (cons (cons (caaar n) '(simp factored)) (cdar n))))) (defun nratfact (x) (cond ((equal (cdr x) 1) (cfactor (car x))) ((equal (car x) 1) (revsign (cfactor (cdr x)))) (t (nconc (cfactor (car x)) (revsign (cfactor (cdr x))))))) ;;; FOR LISTS OF JUST NUMBERS (defun nretfactor1 (l) (cond ((null l) nil) ((equal (cadr l) 1) (cons (car l) (nretfactor1 (cddr l)))) (t (cons (if (equal (cadr l) -1) (list '(rat simp) 1 (car l)) (list '(mexpt simp) (car l) (cadr l))) (nretfactor1 (cddr l)))))) (declare-top (unspecial var)) (defmfun $polymod (p &optional (m 0 m?)) (let ((modulus modulus)) (when m? (setq modulus m) (when (or (not (integerp modulus)) (zerop modulus)) (merror (intl:gettext "polymod: modulus must be a nonzero integer; found: ~M") modulus))) (when (minusp modulus) (setq modulus (abs modulus))) (mod1 p))) (defun mod1 (e) (if (mbagp e) (cons (car e) (mapcar 'mod1 (cdr e))) (let (formflag) (newvar e) (setq formflag ($ratp e) e (ratrep* e)) (setq e (cons (car e) (ratreduce (pmod (cadr e)) (pmod (cddr e))))) (cond (formflag e) (t (ratdisrep e)))))) (defmfun $divide (x y &rest vars) (prog (h varlist tt ty formflag $ratfac) (when (and ($ratp x) (setq formflag t) (integerp (cadr x)) (equal (cddr x) 1)) (setq x (cadr x))) (when (and ($ratp y) (setq formflag t) (integerp (cadr y)) (equal (cddr y) 1)) (setq y (cadr y))) (when (and (integerp x) (integerp y)) (when (zerop y) (merror (intl:gettext "divide: Quotient by zero"))) (return (cons '(mlist) (multiple-value-list (truncate x y))))) (setq varlist vars) (mapc #'newvar (reverse (cdr $ratvars))) (newvar y) (newvar x) (setq x (ratrep* x)) (setq h (car x)) (setq x (cdr x)) (setq y (cdr (ratrep* y))) (cond ((and (equal (setq tt (cdr x)) 1) (equal (cdr y) 1)) (setq x (pdivide (car x) (car y)))) (t (setq ty (cdr y)) (setq x (ptimes (car x) (cdr y))) (setq x (pdivide x (car y))) (setq x (list (ratqu (car x) tt) (ratqu (cadr x) (ptimes tt ty)))))) (setq h (list '(mlist) (cons h (car x)) (cons h (cadr x)))) (return (if formflag h ($totaldisrep h))))) (defmfun $quotient (&rest args) (cadr (apply '$divide args))) (defmfun $remainder (&rest args) (caddr (apply '$divide args))) (defmfun $gcd (x y &rest vars) (prog (h varlist genvar $keepfloat formflag) (setq formflag ($ratp x)) (and ($ratp y) (setq formflag t)) (setq varlist vars) (dolist (v varlist) (when (numberp v) (improper-arg-err v '$gcd))) (newvar x) (newvar y) (when (and ($ratp x) ($ratp y) (equal (car x) (car y))) (setq genvar (car (last (car x))) h (car x) x (cdr x) y (cdr y)) (go on)) (setq x (ratrep* x)) (setq h (car x)) (setq x (cdr x)) (setq y (cdr (ratrep* y))) on (setq x (cons (pgcd (car x) (car y)) (plcm (cdr x) (cdr y)))) (setq h (cons h x)) (return (if formflag h (ratdisrep h))))) (defmfun $content (x &rest vars) (prog (y h varlist formflag) (setq formflag ($ratp x)) (setq varlist vars) (newvar x) (desetq (h x . y) (ratrep* x)) (unless (atom x) ( CAR X ) = > corresponding to apparent main var . MAIN - GENVAR = > corresponding to the genuine main var . (let ((main-genvar (nth (1- (length varlist)) genvar))) (unless (eq (car x) main-genvar) (setq x `(,main-genvar 0 ,x))))) (setq x (rcontent x) y (cons 1 y)) (setq h (list '(mlist) (cons h (rattimes (car x) y nil)) (cons h (cadr x)))) (return (if formflag h ($totaldisrep h))))) (defun pget (gen) (cons gen '(1 1))) (defun m$exp? (x) (and (mexptp x) (eq (cadr x) '$%e))) (defun algp ($x) (algpchk $x nil)) (defun algpget ($x) (algpchk $x t)) (defun algpchk ($x mpflag &aux temp) (cond ((eq $x '$%i) '(2 -1)) ((eq $x '$%phi) '(2 1 1 -1 0 -1)) ((radfunp $x nil) (if (not mpflag) t (let ((r (prep1 (cadr $x)))) INTEGRAL ALG . QUANT . ? (list (caddr (caddr $x)) (car r))) (*ratsimp* (setq radlist (cons $x radlist)) nil))))) ((not $algebraic) nil) ((and (m$exp? $x) (mtimesp (setq temp (caddr $x))) (equal (cddr temp) '($%i $%pi)) (ratnump (setq temp (cadr temp)))) (if mpflag (primcyclo (* 2 (caddr temp))) t)) ((not mpflag) (assolike $x tellratlist)) ((setq temp (copy-list (assolike $x tellratlist))) (do ((p temp (cddr p))) ((null p)) (rplaca (cdr p) (car (prep1 (cadr p))))) (setq temp (cond ((ptzerop (pt-red temp)) (list (pt-le temp) (pzero))) ((zerop (pt-le (pt-red temp))) (list (pt-le temp) (pminus (pt-lc (pt-red temp))))) (t temp))) (if (and (= (pt-le temp) 1) (setq $x (assol $x genpairs))) (rplacd $x (cons (cadr temp) 1))) temp))) (defun radfunp (x funcflag) ;FUNCFLAG -> TEST FOR ALG FUNCTION NOT NUMBER (cond ((atom x) nil) ((not (eq (caar x) 'mexpt)) nil) ((not (ratnump (caddr x))) nil) (funcflag (not (numberp (cadr x)))) (t t))) (defun ratsetup (vl gl) (ratsetup1 vl gl) (ratsetup2 vl gl)) (defun ratsetup1 (vl gl) (and $ratwtlvl (mapc #'(lambda (v g) (setq v (assolike v *ratweights)) (if v (putprop g v '$ratweight) (remprop g '$ratweight))) vl gl))) (defun ratsetup2 (vl gl) (when $algebraic (mapc #'(lambda (g) (remprop g 'algord)) gl) (mapl #'(lambda (v lg) (cond ((setq v (algpget (car v))) (algordset v lg) (putprop (car lg) v 'tellrat)) (t (remprop (car lg) 'tellrat)))) vl gl)) (and $ratfac (let ($ratfac) (mapc #'(lambda (v g) (if (mplusp v) (putprop g (car (prep1 v)) 'unhacked) (remprop g 'unhacked))) vl gl)))) (defun porder (p) (if (pcoefp p) 0 (valget (car p)))) (defun algordset (x gl) (do ((p x (cddr p)) (mv 0)) ((null p) (do ((l gl (cdr l))) ((or (null l) (> (valget (car l)) mv))) (putprop (car l) t 'algord))) (setq mv (max mv (porder (cadr p)))))) (defun gensym-readable (name) (cond ((symbolp name) (gensym (string-trim "$" (string name)))) (t (setq name (aformat nil "~:M" name)) (if name (gensym name) (gensym))))) (defun orderpointer (l) (loop for v in l for i below (- (length l) (length genvar)) collecting (gensym-readable v) into tem finally (setq genvar (nconc tem genvar)) (return (prenumber genvar 1)))) (defun creatsym (n) (dotimes (i n) (push (gensym) genvar))) (defun prenumber (v n) (do ((vl v (cdr vl)) (i n (1+ i))) ((null vl) nil) (setf (symbol-value (car vl)) i))) (defun rget (genv) (cons (if (and $ratwtlvl (or (fixnump $ratwtlvl) (merror (intl:gettext "rat: 'ratwtlvl' must be an integer; found: ~M") $ratwtlvl)) (> (or (get genv '$ratweight) -1) $ratwtlvl)) (pzero) (pget genv)) 1)) (defun ratrep (x varl) (setq varlist varl) (ratrep* x)) (defun ratrep* (x) (let (genpairs) (orderpointer varlist) (ratsetup1 varlist genvar) (mapc #'(lambda (y z) (push (cons y (rget z)) genpairs)) varlist genvar) (ratsetup2 varlist genvar) (xcons (prep1 x) ; PREP1 changes VARLIST (list* 'mrat 'simp varlist genvar ; when $RATFAC is T. (if (and (not (atom x)) (member 'irreducible (cdar x) :test #'eq)) '(irreducible)))))) (defvar *withinratf* nil) (defun ratf (l) (prog (u *withinratf*) (setq *withinratf* t) (when (eq '%% (catch 'ratf (newvar l))) (setq *withinratf* nil) (return (srf l))) (setq u (catch 'ratf (ratrep* l))) ; for truncation routines (return (or u (prog2 (setq *withinratf* nil) (srf l)))))) (defun prep1 (x &aux temp) (cond ((floatp x) (cond ($keepfloat (cons x 1.0)) ((prepfloat x)))) ((integerp x) (cons (cmod x) 1)) ((rationalp x) (if (null modulus) (cons (numerator x) (denominator x)) (cquotient (numerator x) (denominator x)))) ((atom x) (cond ((assolike x genpairs)) (t (newsym x)))) ((and $ratfac (assolike x genpairs))) ((eq (caar x) 'mplus) (cond ($ratfac (setq x (mapcar #'prep1 (cdr x))) (cond ((every #'frpoly? x) (cons (mfacpplus (mapl #'(lambda (x) (rplaca x (caar x))) x)) 1)) (t (do ((a (car x) (facrplus a (car l))) (l (cdr x) (cdr l))) ((null l) a))))) (t (do ((a (prep1 (cadr x)) (ratplus a (prep1 (car l)))) (l (cddr x) (cdr l))) ((null l) a))))) ((eq (caar x) 'mtimes) (do ((a (savefactors (prep1 (cadr x))) (rattimes a (savefactors (prep1 (car l))) sw)) (l (cddr x) (cdr l)) (sw (not (and $norepeat (member 'ratsimp (cdar x) :test #'eq))))) ((null l) a))) ((eq (caar x) 'mexpt) (newvarmexpt x (caddr x) t)) ((eq (caar x) 'mquotient) (ratquotient (savefactors (prep1 (cadr x))) (savefactors (prep1 (caddr x))))) ((eq (caar x) 'mminus) (ratminus (prep1 (cadr x)))) ((eq (caar x) 'rat) (cond (modulus (cons (cquotient (cmod (cadr x)) (cmod (caddr x))) 1)) (t (cons (cadr x) (caddr x))))) ((eq (caar x) 'bigfloat)(bigfloat2rat x)) ((eq (caar x) 'mrat) (cond ((and *withinratf* (member 'trunc (car x) :test #'eq)) (throw 'ratf nil)) ((catch 'compatvl (progn (setq temp (compatvarl (caddar x) varlist (cadddr (car x)) genvar)) t)) (cond ((member 'trunc (car x) :test #'eq) (cdr ($taytorat x))) ((and (not $keepfloat) (or (pfloatp (cadr x)) (pfloatp (cddr x)))) (cdr (ratrep* ($ratdisrep x)))) ((sublis temp (cdr x))))) (t (cdr (ratrep* ($ratdisrep x)))))) ((assolike x genpairs)) (t (setq x (littlefr1 x)) (cond ((assolike x genpairs)) (t (newsym x)))))) (defun putonvlist (x) (push x vlist) (and $algebraic (setq x (assolike x tellratlist)) (mapc 'newvar1 x))) (setq expsumsplit t) ;CONTROLS SPLITTING SUMS IN EXPONS (defun newvarmexpt (x e flag) ;; WHEN FLAG IS T, CALL RETURNS RATFORM (prog (topexp) (when (and (integerp e) (not flag)) (return (newvar1 (cadr x)))) (setq topexp 1) top (cond ;; X=B^N FOR N A NUMBER ((integerp e) (setq topexp (* topexp e)) (setq x (cadr x))) ((atom e) nil) ;; X=B^(P/Q) FOR P AND Q INTEGERS ((eq (caar e) 'rat) (cond ((or (minusp (cadr e)) (> (cadr e) 1)) (setq topexp (* topexp (cadr e))) (setq x (list '(mexpt) (cadr x) (list '(rat) 1 (caddr e)))))) (cond ((or flag (numberp (cadr x)) )) (*ratsimp* (cond ((memalike x radlist) (return nil)) (t (setq radlist (cons x radlist)) (return (newvar1 (cadr x))))) ) ($algebraic (newvar1 (cadr x))))) ;; X=B^(A*C) ((eq (caar e) 'mtimes) (cond ((or ;; X=B^(N *C) (and (atom (cadr e)) (integerp (cadr e)) (setq topexp (* topexp (cadr e))) (setq e (cddr e))) ;; X=B^(P/Q *C) (and (not (atom (cadr e))) (eq (caaadr e) 'rat) (not (equal 1 (cadadr e))) (setq topexp (* topexp (cadadr e))) (setq e (cons (list '(rat) 1 (caddr (cadr e))) (cddr e))))) (setq x (list '(mexpt) (cadr x) (setq e (simplify (cons '(mtimes) e))))) (go top)))) ;; X=B^(A+C) ((and (eq (caar e) 'mplus) expsumsplit) ;SWITCH CONTROLS SPLITTING EXPONENT x ;SUMS (cons '(mtimes) (mapcar #'(lambda (ll) (list '(mexpt) (cadr x) (simplify (list '(mtimes) topexp ll)))) (cdr e)))) (cond (flag (return (prep1 x))) (t (return (newvar1 x)))))) (cond (flag nil) ((equal 1 topexp) (cond ((or (atom x) (not (eq (caar x) 'mexpt))) (newvar1 x)) ((or (memalike x varlist) (memalike x vlist)) nil) (t (cond ((or (atom x) (null *fnewvarsw)) (putonvlist x)) (t (setq x (littlefr1 x)) (mapc #'newvar1 (cdr x)) (or (memalike x vlist) (memalike x varlist) (putonvlist x))))))) (t (newvar1 x))) (return (cond ((null flag) nil) ((equal 1 topexp) (cond ((and (not (atom x)) (eq (caar x) 'mexpt)) (cond ((assolike x genpairs)) ;; *** SHOULD ONLY GET HERE IF CALLED FROM FR1. *FNEWVARSW=NIL (t (setq x (littlefr1 x)) (cond ((assolike x genpairs)) (t (newsym x)))))) (t (prep1 x)))) (t (ratexpt (prep1 x) topexp)))))) (defun newvar1 (x) (cond ((numberp x) nil) ((memalike x varlist) nil) ((memalike x vlist) nil) ((atom x) (putonvlist x)) ((member (caar x) '(mplus mtimes rat mdifference mquotient mminus bigfloat) :test #'eq) (mapc #'newvar1 (cdr x))) ((eq (caar x) 'mexpt) (newvarmexpt x (caddr x) nil)) ((eq (caar x) 'mrat) (and *withinratf* (member 'trunc (cdddar x) :test #'eq) (throw 'ratf '%%)) (cond ($ratfac (mapc 'newvar3 (caddar x))) (t (mapc #'newvar1 (reverse (caddar x)))))) (t (cond (*fnewvarsw (setq x (littlefr1 x)) (mapc #'newvar1 (cdr x)) (or (memalike x vlist) (memalike x varlist) (putonvlist x))) (t (putonvlist x)))))) (defun newvar3 (x) (or (memalike x vlist) (memalike x varlist) (putonvlist x))) (defun fr1 (x varlist) ;put radicands on initial varlist? (prog (genvar $norepeat *ratsimp* radlist vlist nvarlist ovarlist genpairs) (newvar1 x) (setq nvarlist (mapcar #'fr-args vlist)) (cond ((not *ratsimp*) ;*ratsimp* not set for initial varlist (setq varlist (nconc (sortgreat vlist) varlist)) (return (rdis (cdr (ratrep* x)))))) (setq ovarlist (nconc vlist varlist) vlist nil) (mapc #'newvar1 nvarlist) ;*RATSIMP*=T PUTS RADICANDS ON VLIST RADICALS ON RADLIST varlist (nconc (sortgreat vlist) (radsort radlist) varlist)) (orderpointer varlist) (setq genpairs (mapcar #'(lambda (x y) (cons x (rget y))) varlist genvar)) (let (($algebraic $algebraic) ($ratalgdenom $ratalgdenom) radlist) (and (not $algebraic) (some #'algpget varlist) ;NEEDS *RATSIMP*=T (setq $algebraic t $ratalgdenom nil)) (ratsetup varlist genvar) (setq genpairs (mapcar #'(lambda (x y) (cons x (prep1 y))) ovarlist nvarlist)) (setq x (rdis (prep1 x))) (cond (radlist ;rational radicands (setq *ratsimp* nil) (setq x (ratsimp (simplify x) nil nil))))) (return x))) (defun ratsimp (x varlist genvar) ($ratdisrep (ratf x))) (defun littlefr1 (x) (cons (remove 'simp (car x) :test #'eq) (mapfr1 (cdr x) nil))) ;;IF T RATSIMP FACTORS RADICANDS AND LOGANDS (defmvar fr-factor nil) (defun fr-args (x) ;SIMP (A/B)^N TO A^N/B^N ? (cond ((atom x) (when (eq x '$%i) (setq *ratsimp* t)) ;indicates algebraic present x) (t (setq *ratsimp* t) ;FLAG TO CHANGED ELMT. (simplify (zp (cons (remove 'simp (car x) :test #'eq) (if (or (radfunp x nil) (eq (caar x) '%log)) (cons (if fr-factor (factor (cadr x)) (fr1 (cadr x) varlist)) (cddr x)) (let (modulus) (mapfr1 (cdr x) varlist))))))))) ;;SIMPLIFY MEXPT'S & RATEXPAND EXPONENT (defun zp (x) (if (and (mexptp x) (not (atom (caddr x)))) (list (car x) (cadr x) (let ((varlist varlist) *ratsimp*) ($ratexpand (caddr x)))) x)) (defun newsym (e) (prog (g p) (when (setq g (assolike e genpairs)) (return g)) (setq g (gensym-readable e)) (putprop g e 'disrep) (push e varlist) (push (cons e (rget g)) genpairs) (valput g (if genvar (1- (valget (car genvar))) 1)) (push g genvar) (when (setq p (and $algebraic (algpget e))) (algordset p genvar) (putprop g p 'tellrat)) (return (rget g)))) ;; Any program which calls RATF on ;; a floating point number but does not wish to see "RAT replaced ..." message , must bind $ RATPRINT to NIL . (defmvar $ratprint t) (defmvar $ratepsilon 2e-15) ;; This control of conversion from float to rational appears to be explained ;; nowhere. - RJF (defun maxima-rationalize (x) (cond ((not (floatp x)) x) Handle denormalized floats -- see maxima - discuss 2021 - 04 - 27 and bug 3777 ((and (not (= x 0.0)) (< (abs x) COMMON-LISP:LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT)) (let ((r ($rationalize x))) (cons (cadr r) (caddr r)))) ((< x 0.0) (setq x (ration1 (* -1.0 x))) (rplaca x (* -1 (car x)))) (t (ration1 x)))) (defun ration1 (x) (let ((rateps (if (not (floatp $ratepsilon)) ($float $ratepsilon) $ratepsilon))) (or (and (zerop x) (cons 0 1)) (prog (y a) (return I ( ) think this is computing a continued fraction ;; expansion of the given float. ;; FIXME ? CMUCL used to use this routine for its ;; RATIONALIZE function, but there were known bugs in ;; that implementation, where the result was not very ;; accurate. Unfortunately, I can't find the example that demonstrates this . In any case , CMUCL replaced it with an algorithm based on the code in Clisp , which ;; was much better. (do ((xx x (setq y (/ 1.0 (- xx (float a x))))) (num (setq a (floor x)) (+ (* (setq a (floor y)) num) onum)) (den 1 (+ (* a den) oden)) (onum 1 num) (oden 0 den)) ((or (zerop (- xx (float a x))) (and (not (zerop den)) (not (> (abs (/ (- x (/ (float num x) (float den x))) x)) rateps)))) (cons num den)))))))) (defun prepfloat (f) (cond (modulus (merror (intl:gettext "rat: can't rationalize ~M when modulus = ~M") f modulus)) ($ratprint (mtell (intl:gettext "~&rat: replaced ~A by") f))) (setq f (maxima-rationalize f)) (when $ratprint (mtell " ~A/~A = ~A~%" (car f) (cdr f) (fpcofrat1 (car f) (cdr f)))) f) (defun pdisrep (p) (if (atom p) p (pdisrep+ (pdisrep2 (cdr p) (get (car p) 'disrep))))) (defun pdisrep! (n var) (cond ((zerop n) 1) ((equal n 1) (cond ((atom var) var) ((or (eq (caar var) 'mtimes) (eq (caar var) 'mplus)) (copy-list var)) (t var))) (t (list '(mexpt ratsimp) var n)))) (defun pdisrep+ (p) (cond ((null (cdr p)) (car p)) (t (let ((a (last p))) (cond ((mplusp (car a)) (rplacd a (cddar a)) (rplaca a (cadar a)))) (cons '(mplus ratsimp) p))))) (defun pdisrep* (a b) (cond ((equal a 1) b) ((equal b 1) a) (t (cons '(mtimes ratsimp) (nconc (pdisrep*chk a) (pdisrep*chk b)))))) (defun pdisrep*chk (a) (if (mtimesp a) (cdr a) (ncons a))) (defun pdisrep2 (p var) (cond ((null p) nil) ($ratexpand (pdisrep2expand p var)) (t (do ((l () (cons (pdisrep* (pdisrep (cadr p)) (pdisrep! (car p) var)) l)) (p p (cddr p))) ((null p) (nreverse l)))))) ;; IF $RATEXPAND IS TRUE, (X+1)*(Y+1) WILL DISPLAY AS XY + Y + X + 1 OTHERWISE , AS ( X+1)Y + X + 1 (defmvar $ratexpand nil) (defmfun $ratexpand (x) (if (mbagp x) (cons (car x) (mapcar '$ratexpand (cdr x))) (let (($ratexpand t) ($ratfac nil)) (ratdisrep (ratf x))))) (defun pdisrep*expand (a b) (cond ((equal a 1) (list b)) ((equal b 1) (list a)) ((or (atom a) (not (eq (caar a) 'mplus))) (list (cons (quote (mtimes ratsimp)) (nconc (pdisrep*chk a) (pdisrep*chk b))))) (t (mapcar #'(lambda (z) (if (equal z 1) b (cons '(mtimes ratsimp) (nconc (pdisrep*chk z) (pdisrep*chk b))))) (cdr a))))) (defun pdisrep2expand (p var) (cond ((null p) nil) (t (nconc (pdisrep*expand (pdisrep (cadr p)) (pdisrep! (car p) var)) (pdisrep2expand (cddr p) var))))) (defmvar $ratdenomdivide t) (defmfun $ratdisrep (x) (cond ((mbagp x) Distribute over lists , equations , and matrices . (cons (car x) (mapcar #'$ratdisrep (cdr x)))) ((not ($ratp x)) x) (t (setq x (ratdisrepd x)) (if (and (not (atom x)) (member 'trunc (cdar x) :test #'eq)) (cons (delete 'trunc (copy-list (car x)) :count 1 :test #'eq) (cdr x)) x)))) RATDISREPD is needed by . - JPG (defun ratdisrepd (x) (mapc #'(lambda (y z) (putprop y z (quote disrep))) (cadddr (car x)) (caddar x)) (let ((varlist (caddar x))) (if (member 'trunc (car x) :test #'eq) (srdisrep x) (cdisrep (cdr x))))) (defun cdisrep (x &aux n d sign) (cond ((pzerop (car x)) 0) ((or (equal 1 (cdr x)) (floatp (cdr x))) (pdisrep (car x))) (t (setq sign (cond ($ratexpand (setq n (pdisrep (car x))) 1) ((pminusp (car x)) (setq n (pdisrep (pminus (car x)))) -1) (t (setq n (pdisrep (car x))) 1))) (setq d (pdisrep (cdr x))) (cond ((and (numberp n) (numberp d)) (list '(rat) (* sign n) d)) ((and $ratdenomdivide $ratexpand (not (atom n)) (eq (caar n) 'mplus)) (fancydis n d)) ((numberp d) (list '(mtimes ratsimp) (list '(rat) sign d) n)) ((equal sign -1) (cons '(mtimes ratsimp) (cond ((numberp n) (list (* n -1) (list '(mexpt ratsimp) d -1))) (t (list sign n (list '(mexpt ratsimp) d -1)))))) ((equal n 1) (list '(mexpt ratsimp) d -1)) (t (list '(mtimes ratsimp) n (list '(mexpt ratsimp) d -1))))))) ;; FANCYDIS GOES THROUGH EACH TERM AND DIVIDES IT BY THE DENOMINATOR. (defun fancydis (n d) (setq d (simplify (list '(mexpt) d -1))) (simplify (cons '(mplus) (mapcar #'(lambda (z) ($ratdisrep (ratf (list '(mtimes) z d)))) (cdr n))))) (defun compatvarl (a b c d) (cond ((null a) nil) ((or (null b) (null c) (null d)) (throw 'compatvl nil)) ((alike1 (car a) (car b)) (setq a (compatvarl (cdr a) (cdr b) (cdr c) (cdr d))) (if (eq (car c) (car d)) a (cons (cons (car c) (car d)) a))) (t (compatvarl a (cdr b) c (cdr d))))) (defun newvar (l &aux vlist) (newvar1 l) (setq varlist (nconc (sortgreat vlist) varlist))) (defun sortgreat (l) FIXME consider a total order function with # ' sort (defun fnewvar (l &aux (*fnewvarsw t)) (newvar l)) (defun nestlev (exp) (if (atom exp) 0 (do ((m (nestlev (cadr exp)) (max m (nestlev (car l)))) (l (cddr exp) (cdr l))) ((null l) (1+ m))))) (defun radsort (l) (sort l #'(lambda (a b) (let ((na (nestlev a)) (nb (nestlev b))) (cond ((< na nb) t) ((> na nb) nil) (t (great b a))))))) THIS IS THE END OF THE NEW RATIONAL FUNCTION PACKAGE PART 5 ;; IT INCLUDES THE CONVERSION AND TOP-LEVEL ROUTINES USED ;; BY THE REST OF THE FUNCTIONS.
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/src/rat3e.lisp
lisp
Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ; The data in this file contains enhancments. ;;;;; ;;;;; ; ; ; ; All rights reserved ;;;;; ; ; It includes the conversion and top-level routines used by the rest of the functions. User level global variables. prevents clobbering p Not a mrat expression. Remove the special representation. SIMP FLAGS? $RATSIMP, $FULLRATSIMP and $RAT allow for optional extra arguments specifying the VARLIST. PSQFR HAS NOT BEEN CHANGED TO MAKE USE OF THE SQFR FLAGS YET to undo monicizing subst don't multiply them back out FOR LISTS OF JUST NUMBERS FUNCFLAG -> TEST FOR ALG FUNCTION NOT NUMBER PREP1 changes VARLIST when $RATFAC is T. for truncation routines CONTROLS SPLITTING SUMS IN EXPONS WHEN FLAG IS T, CALL RETURNS RATFORM X=B^N FOR N A NUMBER X=B^(P/Q) FOR P AND Q INTEGERS X=B^(A*C) X=B^(N *C) X=B^(P/Q *C) X=B^(A+C) SWITCH CONTROLS SUMS *** SHOULD ONLY GET HERE IF CALLED FROM FR1. *FNEWVARSW=NIL put radicands on initial varlist? *ratsimp* not set for initial varlist *RATSIMP*=T PUTS RADICANDS ON VLIST NEEDS *RATSIMP*=T rational radicands IF T RATSIMP FACTORS RADICANDS AND LOGANDS SIMP (A/B)^N TO A^N/B^N ? indicates algebraic present FLAG TO CHANGED ELMT. SIMPLIFY MEXPT'S & RATEXPAND EXPONENT Any program which calls RATF on a floating point number but does not wish to see "RAT replaced ..." This control of conversion from float to rational appears to be explained nowhere. - RJF expansion of the given float. RATIONALIZE function, but there were known bugs in that implementation, where the result was not very accurate. Unfortunately, I can't find the example was much better. IF $RATEXPAND IS TRUE, (X+1)*(Y+1) WILL DISPLAY AS FANCYDIS GOES THROUGH EACH TERM AND DIVIDES IT BY THE DENOMINATOR. IT INCLUDES THE CONVERSION AND TOP-LEVEL ROUTINES USED BY THE REST OF THE FUNCTIONS.
(in-package :maxima) (macsyma-module rat3e) This is the rational function package part 5 . (declare-top (special intbs* alflag var dosimp alc $myoptions vlist scanmapp radlist expsumsplit *ratsimp* mplc* $ratsimpexpons $expop $expon $negdistrib $gcd)) (defmvar genvar nil "List of gensyms used to point to kernels from within polynomials. The values cell and property lists of these symbols are used to store various information.") (defmvar genpairs nil) (defmvar varlist nil "List of kernels") (defmvar *fnewvarsw nil) (defmvar *ratweights nil) (defvar *ratsimp* nil) (defmvar factorresimp nil "If `t' resimplifies factor(x-y) to x-y") (defmvar $keepfloat nil "If `t' floating point coeffs are not converted to rationals") (defmvar $factorflag nil "If `t' constant factor of polynomial is also factored") (defmvar $dontfactor '((mlist))) (defmvar $norepeat t) (defmvar $ratweights '((mlist simp))) (defmvar $ratfac nil "If `t' cre-forms are kept factored") (defmvar $algebraic nil) (defmvar $ratvars '((mlist simp))) (defmvar $facexpand t) (declare-top (special evp $infeval)) (defun mrateval (x) (let ((varlist (caddar x))) (cond ((and evp $infeval) (meval ($ratdisrep x))) ((or evp (and $float $keepfloat) (not (alike varlist (mapcar #'meval varlist)))) (ratf (meval ($ratdisrep x)))) (t x)))) (defprop mrat mrateval mfexpr*) (defmfun $ratnumer (x) (cond ((mbagp x) (cons (car x) (mapcar '$ratnumer (cdr x)))) (t (setq x (taychk2rat x)) (cons (car x) (cons (cadr x) 1))))) (defmfun $ratdenom (x) (cond ((mbagp x) (cons (car x) (mapcar '$ratdenom (cdr x)))) (t (setq x (taychk2rat x)) (cons (car x) (cons (cddr x) 1))))) (defun taychk2rat (x) (cond ((and ($ratp x) (member 'trunc (cdar x) :test #'eq)) ($taytorat x)) (t ($rat x)))) (defmvar tellratlist nil) (defun tellratdisp (x) (pdisrep+ (trdisp1 (cdr x) (car x)))) (defun trdisp1 (p var) (cond ((null p) nil) (t (cons (pdisrep* (if (mtimesp (cadr p)) (copy-list (cadr p)) (pdisrep! (car p) var)) (trdisp1 (cddr p) var))))) (defmfun $untellrat (&rest args) (dolist (x args) (if (setq x (assol x tellratlist)) (setq tellratlist (remove x tellratlist :test #'equal)))) (cons '(mlist) (mapcar #'tellratdisp tellratlist))) (defmfun $tellrat (&rest args) (mapc #'tellrat1 args) (unless (null args) (add2lnc 'tellratlist $myoptions)) (cons '(mlist) (mapcar #'tellratdisp tellratlist))) (defun tellrat1 (x &aux varlist genvar $algebraic $ratfac algvar) (setq x ($totaldisrep x)) (and (not (atom x)) (eq (caar x) 'mequal) (newvar (cadr x))) (newvar (setq x (meqhk x))) (unless varlist (merror (intl:gettext "tellrat: argument must be a polynomial; found: ~M") x)) (setq algvar (car (last varlist))) (setq x (p-terms (primpart (cadr (ratrep* x))))) (unless (equal (pt-lc x) 1) (merror (intl:gettext "tellrat: minimal polynomial must be monic."))) (do ((p (pt-red x) (pt-red p))) ((ptzerop p)) (setf (pt-lc p) (pdis (pt-lc p)))) (setq algvar (cons algvar x)) (if (setq x (assol (car algvar) tellratlist)) (setq tellratlist (remove x tellratlist :test #'equal))) (push algvar tellratlist)) (defmfun $printvarlist () (cons '(mlist) (copy-tree varlist))) (defmfun $showratvars (e) (cons '(mlist simp) (cond (($ratp e) (if (member 'trunc (cdar e) :test #'eq) (setq e ($taytorat e))) (caddar (minimize-varlist e))) (t (let (varlist) (lnewvar e) varlist))))) (defmfun $ratvars (&rest args) (add2lnc '$ratvars $myoptions) (setq $ratvars (cons '(mlist simp) (setq varlist (mapfr1 args varlist))))) (defun mapfr1 (l varlist) (mapcar #'(lambda (z) (fr1 z varlist)) l)) (defmvar inratsimp nil) (defmfun $fullratsimp (exp &rest argl) (prog (exp1) loop (setq exp1 (simplify (apply #'$ratsimp (cons exp argl)))) (when (alike1 exp exp1) (return exp)) (setq exp exp1) (go loop))) (defun fullratsimp (l) (let (($expop 0) ($expon 0) (inratsimp t) $ratsimpexpons) (when (not ($ratp l)) (setq l (specrepcheck l))) (setq l ($totaldisrep l)) (fr1 l varlist))) (defmfun $totaldisrep (l) (cond ((atom l) l) ((not (among 'mrat l)) l) ((eq (caar l) 'mrat) (ratdisrep l)) (t (cons (delete 'ratsimp (car l) :test #'eq) (mapcar '$totaldisrep (cdr l)))))) VARLIST HAS MAIN VARIABLE AT END (defun joinvarlist (cdrl) (mapc #'(lambda (z) (unless (memalike z varlist) (push z varlist))) (reverse (mapfr1 cdrl nil)))) (defmfun $rat (e &rest vars) (cond ((not (null vars)) (let (varlist) (joinvarlist vars) (lnewvar e) (rat0 e))) (t (lnewvar e) (rat0 e)))) (if (mbagp exp) (cons (car exp) (mapcar #'rat0 (cdr exp))) (ratf exp))) (defmfun $ratsimp (e &rest vars) (cond ((not (null vars)) (let (varlist) (joinvarlist vars) (fullratsimp e))) (t (fullratsimp e)))) (defmfun $sqfr (x) (let ((varlist (cdr $ratvars)) genvar $keepfloat $ratfac) (sublis '((factored . sqfred) (irreducible . sqfr)) (ffactor x #'psqfr)))) (declare-top (special fn)) (defun whichfn (p) (cond ((and (mexptp p) (integerp (caddr p))) (list '(mexpt) (whichfn (cadr p)) (caddr p))) ((mtimesp p) (cons '(mtimes) (mapcar #'whichfn (cdr p)))) (fn (ffactor p #'pfactor)) (t (factoralg p)))) (declare-top (special var)) (defmvar adn* 1 "common denom for algebraic coefficients") (defun factoralg (p) (prog (alc ans adn* $gcd) (setq $gcd '$algebraic) (when (or (atom p) (numberp p)) (return p)) (setq adn* 1) (when (and (not $nalgfac) (not intbs*)) (setq intbs* (findibase minpoly*))) (setq algfac* t) (setq ans (ffactor p #'pfactor)) (cond ((eq (caar ans) 'mplus) (return p)) (mplc* (setq ans (albk ans)))) (if (and (not alc) (equal 1 adn*)) (return ans)) (setq ans (partition ans (car (last varlist)) 1)) (return (mul (let ((dosimp t)) (mul `((rat) 1 ,adn*) (car ans) (if alc (pdis alc) 1))) (cdr ans))))) (let ((alpha (pdis alpha)) ($ratfac t)) (declare (special alpha)) assumes * is int alpha p))) (defmfun $gfactor (p &aux (gauss t)) (when ($ratp p) (setq p ($ratdisrep p))) (setq p ($factor (subst '%i '$%i p) '((mplus) 1 ((mexpt) %i 2)))) (setq p (sublis '((factored . gfactored) (irreducible . irreducibleg)) p)) (let (($expop 0) ($expon 0) $negdistrib) (maxima-substitute '$%i '%i p))) (defmfun $factor (e &optional (mp nil mp?)) (let ($intfaclim (varlist (cdr $ratvars)) genvar ans) (setq ans (if mp? (factor e mp) (factor e))) (if (and factorresimp $negdistrib (mtimesp ans) (null (cdddr ans)) (equal (cadr ans) -1) (mplusp (caddr ans))) (let (($expop 0) ($expon 0)) ($multthru ans)) ans))) (defun factor (e &optional (mp nil mp?)) (let ((tellratlist nil) (varlist varlist) (genvar nil) ($gcd $gcd) ($negdistrib $negdistrib)) (prog (fn var mm* mplc* intbs* alflag minpoly* alpha p algfac* $keepfloat $algebraic cargs) (declare (special cargs fn alpha)) (unless (member $gcd *gcdl* :test #'eq) (setq $gcd (car *gcdl*))) (let ($ratfac) (setq p e mm* 1 cargs (if mp? (list mp) nil)) (when (symbolp p) (return p)) (when ($numberp p) (return (let (($factorflag (not scanmapp))) (factornumber p)))) (when (mbagp p) (return (cons (car p) (mapcar #'(lambda (x) (apply #'factor (cons x cargs))) (cdr p))))) (cond (mp? (setq alpha (meqhk mp)) (newvar alpha) (setq minpoly* (cadr (ratrep* alpha))) (when (or (pcoefp minpoly*) (not (univar (cdr minpoly*))) (< (cadr minpoly*) 2)) (merror (intl:gettext "factor: second argument must be a nonlinear, univariate polynomial; found: ~M") alpha)) (setq alpha (pdis (list (car minpoly*) 1 1)) mm* (cadr minpoly*)) (unless (equal (caddr minpoly*) 1) (setq mplc* (caddr minpoly*)) (setq minpoly* (pmonz minpoly*)) (setq p (maxima-substitute (div alpha mplc*) alpha p))) (setq $algebraic t) ($tellrat(pdis minpoly*)) (setq algfac* t)) (t (setq fn t))) (unless scanmapp (setq p (let (($ratfac t)) (sratsimp p)))) (newvar p) (when (symbolp p) (return p)) (when (numberp p) (return (let (($factorflag (not scanmapp))) (factornumber p)))) (setq $negdistrib nil) (setq p (let ($factorflag ($ratexpand $facexpand)) (whichfn p)))) (setq p (let (($expop 0) ($expon 0)) (simplify p))) (cond ((mnump p) (return (factornumber p))) ((atom p) (return p))) (and $ratfac (not $factorflag) ($ratp e) (return ($rat p))) (and $factorflag (mtimesp p) (mnump (cadr p)) (setq alpha (factornumber (cadr p))) (cond ((alike1 alpha (cadr p))) ((mtimesp alpha) (setq p (cons (car p) (append (cdr alpha) (cddr p))))) (t (setq p (cons (car p) (cons alpha (cddr p))))))) (when (null (member 'factored (car p) :test #'eq)) (setq p (cons (append (car p) '(factored)) (cdr p)))) (return p)))) (defun factornumber (n) (setq n (nretfactor1 (nratfact (cdr ($rat n))))) (cond ((cdr n) (cons '(mtimes simp factored) (if (equal (car n) -1) (cons (car n) (nreverse (cdr n))) (nreverse n)))) ((atom (car n)) (car n)) (t (cons (cons (caaar n) '(simp factored)) (cdar n))))) (defun nratfact (x) (cond ((equal (cdr x) 1) (cfactor (car x))) ((equal (car x) 1) (revsign (cfactor (cdr x)))) (t (nconc (cfactor (car x)) (revsign (cfactor (cdr x))))))) (defun nretfactor1 (l) (cond ((null l) nil) ((equal (cadr l) 1) (cons (car l) (nretfactor1 (cddr l)))) (t (cons (if (equal (cadr l) -1) (list '(rat simp) 1 (car l)) (list '(mexpt simp) (car l) (cadr l))) (nretfactor1 (cddr l)))))) (declare-top (unspecial var)) (defmfun $polymod (p &optional (m 0 m?)) (let ((modulus modulus)) (when m? (setq modulus m) (when (or (not (integerp modulus)) (zerop modulus)) (merror (intl:gettext "polymod: modulus must be a nonzero integer; found: ~M") modulus))) (when (minusp modulus) (setq modulus (abs modulus))) (mod1 p))) (defun mod1 (e) (if (mbagp e) (cons (car e) (mapcar 'mod1 (cdr e))) (let (formflag) (newvar e) (setq formflag ($ratp e) e (ratrep* e)) (setq e (cons (car e) (ratreduce (pmod (cadr e)) (pmod (cddr e))))) (cond (formflag e) (t (ratdisrep e)))))) (defmfun $divide (x y &rest vars) (prog (h varlist tt ty formflag $ratfac) (when (and ($ratp x) (setq formflag t) (integerp (cadr x)) (equal (cddr x) 1)) (setq x (cadr x))) (when (and ($ratp y) (setq formflag t) (integerp (cadr y)) (equal (cddr y) 1)) (setq y (cadr y))) (when (and (integerp x) (integerp y)) (when (zerop y) (merror (intl:gettext "divide: Quotient by zero"))) (return (cons '(mlist) (multiple-value-list (truncate x y))))) (setq varlist vars) (mapc #'newvar (reverse (cdr $ratvars))) (newvar y) (newvar x) (setq x (ratrep* x)) (setq h (car x)) (setq x (cdr x)) (setq y (cdr (ratrep* y))) (cond ((and (equal (setq tt (cdr x)) 1) (equal (cdr y) 1)) (setq x (pdivide (car x) (car y)))) (t (setq ty (cdr y)) (setq x (ptimes (car x) (cdr y))) (setq x (pdivide x (car y))) (setq x (list (ratqu (car x) tt) (ratqu (cadr x) (ptimes tt ty)))))) (setq h (list '(mlist) (cons h (car x)) (cons h (cadr x)))) (return (if formflag h ($totaldisrep h))))) (defmfun $quotient (&rest args) (cadr (apply '$divide args))) (defmfun $remainder (&rest args) (caddr (apply '$divide args))) (defmfun $gcd (x y &rest vars) (prog (h varlist genvar $keepfloat formflag) (setq formflag ($ratp x)) (and ($ratp y) (setq formflag t)) (setq varlist vars) (dolist (v varlist) (when (numberp v) (improper-arg-err v '$gcd))) (newvar x) (newvar y) (when (and ($ratp x) ($ratp y) (equal (car x) (car y))) (setq genvar (car (last (car x))) h (car x) x (cdr x) y (cdr y)) (go on)) (setq x (ratrep* x)) (setq h (car x)) (setq x (cdr x)) (setq y (cdr (ratrep* y))) on (setq x (cons (pgcd (car x) (car y)) (plcm (cdr x) (cdr y)))) (setq h (cons h x)) (return (if formflag h (ratdisrep h))))) (defmfun $content (x &rest vars) (prog (y h varlist formflag) (setq formflag ($ratp x)) (setq varlist vars) (newvar x) (desetq (h x . y) (ratrep* x)) (unless (atom x) ( CAR X ) = > corresponding to apparent main var . MAIN - GENVAR = > corresponding to the genuine main var . (let ((main-genvar (nth (1- (length varlist)) genvar))) (unless (eq (car x) main-genvar) (setq x `(,main-genvar 0 ,x))))) (setq x (rcontent x) y (cons 1 y)) (setq h (list '(mlist) (cons h (rattimes (car x) y nil)) (cons h (cadr x)))) (return (if formflag h ($totaldisrep h))))) (defun pget (gen) (cons gen '(1 1))) (defun m$exp? (x) (and (mexptp x) (eq (cadr x) '$%e))) (defun algp ($x) (algpchk $x nil)) (defun algpget ($x) (algpchk $x t)) (defun algpchk ($x mpflag &aux temp) (cond ((eq $x '$%i) '(2 -1)) ((eq $x '$%phi) '(2 1 1 -1 0 -1)) ((radfunp $x nil) (if (not mpflag) t (let ((r (prep1 (cadr $x)))) INTEGRAL ALG . QUANT . ? (list (caddr (caddr $x)) (car r))) (*ratsimp* (setq radlist (cons $x radlist)) nil))))) ((not $algebraic) nil) ((and (m$exp? $x) (mtimesp (setq temp (caddr $x))) (equal (cddr temp) '($%i $%pi)) (ratnump (setq temp (cadr temp)))) (if mpflag (primcyclo (* 2 (caddr temp))) t)) ((not mpflag) (assolike $x tellratlist)) ((setq temp (copy-list (assolike $x tellratlist))) (do ((p temp (cddr p))) ((null p)) (rplaca (cdr p) (car (prep1 (cadr p))))) (setq temp (cond ((ptzerop (pt-red temp)) (list (pt-le temp) (pzero))) ((zerop (pt-le (pt-red temp))) (list (pt-le temp) (pminus (pt-lc (pt-red temp))))) (t temp))) (if (and (= (pt-le temp) 1) (setq $x (assol $x genpairs))) (rplacd $x (cons (cadr temp) 1))) temp))) (cond ((atom x) nil) ((not (eq (caar x) 'mexpt)) nil) ((not (ratnump (caddr x))) nil) (funcflag (not (numberp (cadr x)))) (t t))) (defun ratsetup (vl gl) (ratsetup1 vl gl) (ratsetup2 vl gl)) (defun ratsetup1 (vl gl) (and $ratwtlvl (mapc #'(lambda (v g) (setq v (assolike v *ratweights)) (if v (putprop g v '$ratweight) (remprop g '$ratweight))) vl gl))) (defun ratsetup2 (vl gl) (when $algebraic (mapc #'(lambda (g) (remprop g 'algord)) gl) (mapl #'(lambda (v lg) (cond ((setq v (algpget (car v))) (algordset v lg) (putprop (car lg) v 'tellrat)) (t (remprop (car lg) 'tellrat)))) vl gl)) (and $ratfac (let ($ratfac) (mapc #'(lambda (v g) (if (mplusp v) (putprop g (car (prep1 v)) 'unhacked) (remprop g 'unhacked))) vl gl)))) (defun porder (p) (if (pcoefp p) 0 (valget (car p)))) (defun algordset (x gl) (do ((p x (cddr p)) (mv 0)) ((null p) (do ((l gl (cdr l))) ((or (null l) (> (valget (car l)) mv))) (putprop (car l) t 'algord))) (setq mv (max mv (porder (cadr p)))))) (defun gensym-readable (name) (cond ((symbolp name) (gensym (string-trim "$" (string name)))) (t (setq name (aformat nil "~:M" name)) (if name (gensym name) (gensym))))) (defun orderpointer (l) (loop for v in l for i below (- (length l) (length genvar)) collecting (gensym-readable v) into tem finally (setq genvar (nconc tem genvar)) (return (prenumber genvar 1)))) (defun creatsym (n) (dotimes (i n) (push (gensym) genvar))) (defun prenumber (v n) (do ((vl v (cdr vl)) (i n (1+ i))) ((null vl) nil) (setf (symbol-value (car vl)) i))) (defun rget (genv) (cons (if (and $ratwtlvl (or (fixnump $ratwtlvl) (merror (intl:gettext "rat: 'ratwtlvl' must be an integer; found: ~M") $ratwtlvl)) (> (or (get genv '$ratweight) -1) $ratwtlvl)) (pzero) (pget genv)) 1)) (defun ratrep (x varl) (setq varlist varl) (ratrep* x)) (defun ratrep* (x) (let (genpairs) (orderpointer varlist) (ratsetup1 varlist genvar) (mapc #'(lambda (y z) (push (cons y (rget z)) genpairs)) varlist genvar) (ratsetup2 varlist genvar) (if (and (not (atom x)) (member 'irreducible (cdar x) :test #'eq)) '(irreducible)))))) (defvar *withinratf* nil) (defun ratf (l) (prog (u *withinratf*) (setq *withinratf* t) (when (eq '%% (catch 'ratf (newvar l))) (setq *withinratf* nil) (return (srf l))) (return (or u (prog2 (setq *withinratf* nil) (srf l)))))) (defun prep1 (x &aux temp) (cond ((floatp x) (cond ($keepfloat (cons x 1.0)) ((prepfloat x)))) ((integerp x) (cons (cmod x) 1)) ((rationalp x) (if (null modulus) (cons (numerator x) (denominator x)) (cquotient (numerator x) (denominator x)))) ((atom x) (cond ((assolike x genpairs)) (t (newsym x)))) ((and $ratfac (assolike x genpairs))) ((eq (caar x) 'mplus) (cond ($ratfac (setq x (mapcar #'prep1 (cdr x))) (cond ((every #'frpoly? x) (cons (mfacpplus (mapl #'(lambda (x) (rplaca x (caar x))) x)) 1)) (t (do ((a (car x) (facrplus a (car l))) (l (cdr x) (cdr l))) ((null l) a))))) (t (do ((a (prep1 (cadr x)) (ratplus a (prep1 (car l)))) (l (cddr x) (cdr l))) ((null l) a))))) ((eq (caar x) 'mtimes) (do ((a (savefactors (prep1 (cadr x))) (rattimes a (savefactors (prep1 (car l))) sw)) (l (cddr x) (cdr l)) (sw (not (and $norepeat (member 'ratsimp (cdar x) :test #'eq))))) ((null l) a))) ((eq (caar x) 'mexpt) (newvarmexpt x (caddr x) t)) ((eq (caar x) 'mquotient) (ratquotient (savefactors (prep1 (cadr x))) (savefactors (prep1 (caddr x))))) ((eq (caar x) 'mminus) (ratminus (prep1 (cadr x)))) ((eq (caar x) 'rat) (cond (modulus (cons (cquotient (cmod (cadr x)) (cmod (caddr x))) 1)) (t (cons (cadr x) (caddr x))))) ((eq (caar x) 'bigfloat)(bigfloat2rat x)) ((eq (caar x) 'mrat) (cond ((and *withinratf* (member 'trunc (car x) :test #'eq)) (throw 'ratf nil)) ((catch 'compatvl (progn (setq temp (compatvarl (caddar x) varlist (cadddr (car x)) genvar)) t)) (cond ((member 'trunc (car x) :test #'eq) (cdr ($taytorat x))) ((and (not $keepfloat) (or (pfloatp (cadr x)) (pfloatp (cddr x)))) (cdr (ratrep* ($ratdisrep x)))) ((sublis temp (cdr x))))) (t (cdr (ratrep* ($ratdisrep x)))))) ((assolike x genpairs)) (t (setq x (littlefr1 x)) (cond ((assolike x genpairs)) (t (newsym x)))))) (defun putonvlist (x) (push x vlist) (and $algebraic (setq x (assolike x tellratlist)) (mapc 'newvar1 x))) (defun newvarmexpt (x e flag) (prog (topexp) (when (and (integerp e) (not flag)) (return (newvar1 (cadr x)))) (setq topexp 1) top (cond ((integerp e) (setq topexp (* topexp e)) (setq x (cadr x))) ((atom e) nil) ((eq (caar e) 'rat) (cond ((or (minusp (cadr e)) (> (cadr e) 1)) (setq topexp (* topexp (cadr e))) (setq x (list '(mexpt) (cadr x) (list '(rat) 1 (caddr e)))))) (cond ((or flag (numberp (cadr x)) )) (*ratsimp* (cond ((memalike x radlist) (return nil)) (t (setq radlist (cons x radlist)) (return (newvar1 (cadr x))))) ) ($algebraic (newvar1 (cadr x))))) ((eq (caar e) 'mtimes) (cond ((or (and (atom (cadr e)) (integerp (cadr e)) (setq topexp (* topexp (cadr e))) (setq e (cddr e))) (and (not (atom (cadr e))) (eq (caaadr e) 'rat) (not (equal 1 (cadadr e))) (setq topexp (* topexp (cadadr e))) (setq e (cons (list '(rat) 1 (caddr (cadr e))) (cddr e))))) (setq x (list '(mexpt) (cadr x) (setq e (simplify (cons '(mtimes) e))))) (go top)))) SPLITTING EXPONENT (cons '(mtimes) (mapcar #'(lambda (ll) (list '(mexpt) (cadr x) (simplify (list '(mtimes) topexp ll)))) (cdr e)))) (cond (flag (return (prep1 x))) (t (return (newvar1 x)))))) (cond (flag nil) ((equal 1 topexp) (cond ((or (atom x) (not (eq (caar x) 'mexpt))) (newvar1 x)) ((or (memalike x varlist) (memalike x vlist)) nil) (t (cond ((or (atom x) (null *fnewvarsw)) (putonvlist x)) (t (setq x (littlefr1 x)) (mapc #'newvar1 (cdr x)) (or (memalike x vlist) (memalike x varlist) (putonvlist x))))))) (t (newvar1 x))) (return (cond ((null flag) nil) ((equal 1 topexp) (cond ((and (not (atom x)) (eq (caar x) 'mexpt)) (cond ((assolike x genpairs)) (t (setq x (littlefr1 x)) (cond ((assolike x genpairs)) (t (newsym x)))))) (t (prep1 x)))) (t (ratexpt (prep1 x) topexp)))))) (defun newvar1 (x) (cond ((numberp x) nil) ((memalike x varlist) nil) ((memalike x vlist) nil) ((atom x) (putonvlist x)) ((member (caar x) '(mplus mtimes rat mdifference mquotient mminus bigfloat) :test #'eq) (mapc #'newvar1 (cdr x))) ((eq (caar x) 'mexpt) (newvarmexpt x (caddr x) nil)) ((eq (caar x) 'mrat) (and *withinratf* (member 'trunc (cdddar x) :test #'eq) (throw 'ratf '%%)) (cond ($ratfac (mapc 'newvar3 (caddar x))) (t (mapc #'newvar1 (reverse (caddar x)))))) (t (cond (*fnewvarsw (setq x (littlefr1 x)) (mapc #'newvar1 (cdr x)) (or (memalike x vlist) (memalike x varlist) (putonvlist x))) (t (putonvlist x)))))) (defun newvar3 (x) (or (memalike x vlist) (memalike x varlist) (putonvlist x))) (prog (genvar $norepeat *ratsimp* radlist vlist nvarlist ovarlist genpairs) (newvar1 x) (setq nvarlist (mapcar #'fr-args vlist)) (setq varlist (nconc (sortgreat vlist) varlist)) (return (rdis (cdr (ratrep* x)))))) (setq ovarlist (nconc vlist varlist) vlist nil) RADICALS ON RADLIST varlist (nconc (sortgreat vlist) (radsort radlist) varlist)) (orderpointer varlist) (setq genpairs (mapcar #'(lambda (x y) (cons x (rget y))) varlist genvar)) (let (($algebraic $algebraic) ($ratalgdenom $ratalgdenom) radlist) (and (not $algebraic) (setq $algebraic t $ratalgdenom nil)) (ratsetup varlist genvar) (setq genpairs (mapcar #'(lambda (x y) (cons x (prep1 y))) ovarlist nvarlist)) (setq x (rdis (prep1 x))) (setq *ratsimp* nil) (setq x (ratsimp (simplify x) nil nil))))) (return x))) (defun ratsimp (x varlist genvar) ($ratdisrep (ratf x))) (defun littlefr1 (x) (cons (remove 'simp (car x) :test #'eq) (mapfr1 (cdr x) nil))) (defmvar fr-factor nil) (cond ((atom x) x) (simplify (zp (cons (remove 'simp (car x) :test #'eq) (if (or (radfunp x nil) (eq (caar x) '%log)) (cons (if fr-factor (factor (cadr x)) (fr1 (cadr x) varlist)) (cddr x)) (let (modulus) (mapfr1 (cdr x) varlist))))))))) (defun zp (x) (if (and (mexptp x) (not (atom (caddr x)))) (list (car x) (cadr x) (let ((varlist varlist) *ratsimp*) ($ratexpand (caddr x)))) x)) (defun newsym (e) (prog (g p) (when (setq g (assolike e genpairs)) (return g)) (setq g (gensym-readable e)) (putprop g e 'disrep) (push e varlist) (push (cons e (rget g)) genpairs) (valput g (if genvar (1- (valget (car genvar))) 1)) (push g genvar) (when (setq p (and $algebraic (algpget e))) (algordset p genvar) (putprop g p 'tellrat)) (return (rget g)))) message , must bind $ RATPRINT to NIL . (defmvar $ratprint t) (defmvar $ratepsilon 2e-15) (defun maxima-rationalize (x) (cond ((not (floatp x)) x) Handle denormalized floats -- see maxima - discuss 2021 - 04 - 27 and bug 3777 ((and (not (= x 0.0)) (< (abs x) COMMON-LISP:LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT)) (let ((r ($rationalize x))) (cons (cadr r) (caddr r)))) ((< x 0.0) (setq x (ration1 (* -1.0 x))) (rplaca x (* -1 (car x)))) (t (ration1 x)))) (defun ration1 (x) (let ((rateps (if (not (floatp $ratepsilon)) ($float $ratepsilon) $ratepsilon))) (or (and (zerop x) (cons 0 1)) (prog (y a) (return I ( ) think this is computing a continued fraction FIXME ? CMUCL used to use this routine for its that demonstrates this . In any case , CMUCL replaced it with an algorithm based on the code in Clisp , which (do ((xx x (setq y (/ 1.0 (- xx (float a x))))) (num (setq a (floor x)) (+ (* (setq a (floor y)) num) onum)) (den 1 (+ (* a den) oden)) (onum 1 num) (oden 0 den)) ((or (zerop (- xx (float a x))) (and (not (zerop den)) (not (> (abs (/ (- x (/ (float num x) (float den x))) x)) rateps)))) (cons num den)))))))) (defun prepfloat (f) (cond (modulus (merror (intl:gettext "rat: can't rationalize ~M when modulus = ~M") f modulus)) ($ratprint (mtell (intl:gettext "~&rat: replaced ~A by") f))) (setq f (maxima-rationalize f)) (when $ratprint (mtell " ~A/~A = ~A~%" (car f) (cdr f) (fpcofrat1 (car f) (cdr f)))) f) (defun pdisrep (p) (if (atom p) p (pdisrep+ (pdisrep2 (cdr p) (get (car p) 'disrep))))) (defun pdisrep! (n var) (cond ((zerop n) 1) ((equal n 1) (cond ((atom var) var) ((or (eq (caar var) 'mtimes) (eq (caar var) 'mplus)) (copy-list var)) (t var))) (t (list '(mexpt ratsimp) var n)))) (defun pdisrep+ (p) (cond ((null (cdr p)) (car p)) (t (let ((a (last p))) (cond ((mplusp (car a)) (rplacd a (cddar a)) (rplaca a (cadar a)))) (cons '(mplus ratsimp) p))))) (defun pdisrep* (a b) (cond ((equal a 1) b) ((equal b 1) a) (t (cons '(mtimes ratsimp) (nconc (pdisrep*chk a) (pdisrep*chk b)))))) (defun pdisrep*chk (a) (if (mtimesp a) (cdr a) (ncons a))) (defun pdisrep2 (p var) (cond ((null p) nil) ($ratexpand (pdisrep2expand p var)) (t (do ((l () (cons (pdisrep* (pdisrep (cadr p)) (pdisrep! (car p) var)) l)) (p p (cddr p))) ((null p) (nreverse l)))))) XY + Y + X + 1 OTHERWISE , AS ( X+1)Y + X + 1 (defmvar $ratexpand nil) (defmfun $ratexpand (x) (if (mbagp x) (cons (car x) (mapcar '$ratexpand (cdr x))) (let (($ratexpand t) ($ratfac nil)) (ratdisrep (ratf x))))) (defun pdisrep*expand (a b) (cond ((equal a 1) (list b)) ((equal b 1) (list a)) ((or (atom a) (not (eq (caar a) 'mplus))) (list (cons (quote (mtimes ratsimp)) (nconc (pdisrep*chk a) (pdisrep*chk b))))) (t (mapcar #'(lambda (z) (if (equal z 1) b (cons '(mtimes ratsimp) (nconc (pdisrep*chk z) (pdisrep*chk b))))) (cdr a))))) (defun pdisrep2expand (p var) (cond ((null p) nil) (t (nconc (pdisrep*expand (pdisrep (cadr p)) (pdisrep! (car p) var)) (pdisrep2expand (cddr p) var))))) (defmvar $ratdenomdivide t) (defmfun $ratdisrep (x) (cond ((mbagp x) Distribute over lists , equations , and matrices . (cons (car x) (mapcar #'$ratdisrep (cdr x)))) ((not ($ratp x)) x) (t (setq x (ratdisrepd x)) (if (and (not (atom x)) (member 'trunc (cdar x) :test #'eq)) (cons (delete 'trunc (copy-list (car x)) :count 1 :test #'eq) (cdr x)) x)))) RATDISREPD is needed by . - JPG (defun ratdisrepd (x) (mapc #'(lambda (y z) (putprop y z (quote disrep))) (cadddr (car x)) (caddar x)) (let ((varlist (caddar x))) (if (member 'trunc (car x) :test #'eq) (srdisrep x) (cdisrep (cdr x))))) (defun cdisrep (x &aux n d sign) (cond ((pzerop (car x)) 0) ((or (equal 1 (cdr x)) (floatp (cdr x))) (pdisrep (car x))) (t (setq sign (cond ($ratexpand (setq n (pdisrep (car x))) 1) ((pminusp (car x)) (setq n (pdisrep (pminus (car x)))) -1) (t (setq n (pdisrep (car x))) 1))) (setq d (pdisrep (cdr x))) (cond ((and (numberp n) (numberp d)) (list '(rat) (* sign n) d)) ((and $ratdenomdivide $ratexpand (not (atom n)) (eq (caar n) 'mplus)) (fancydis n d)) ((numberp d) (list '(mtimes ratsimp) (list '(rat) sign d) n)) ((equal sign -1) (cons '(mtimes ratsimp) (cond ((numberp n) (list (* n -1) (list '(mexpt ratsimp) d -1))) (t (list sign n (list '(mexpt ratsimp) d -1)))))) ((equal n 1) (list '(mexpt ratsimp) d -1)) (t (list '(mtimes ratsimp) n (list '(mexpt ratsimp) d -1))))))) (defun fancydis (n d) (setq d (simplify (list '(mexpt) d -1))) (simplify (cons '(mplus) (mapcar #'(lambda (z) ($ratdisrep (ratf (list '(mtimes) z d)))) (cdr n))))) (defun compatvarl (a b c d) (cond ((null a) nil) ((or (null b) (null c) (null d)) (throw 'compatvl nil)) ((alike1 (car a) (car b)) (setq a (compatvarl (cdr a) (cdr b) (cdr c) (cdr d))) (if (eq (car c) (car d)) a (cons (cons (car c) (car d)) a))) (t (compatvarl a (cdr b) c (cdr d))))) (defun newvar (l &aux vlist) (newvar1 l) (setq varlist (nconc (sortgreat vlist) varlist))) (defun sortgreat (l) FIXME consider a total order function with # ' sort (defun fnewvar (l &aux (*fnewvarsw t)) (newvar l)) (defun nestlev (exp) (if (atom exp) 0 (do ((m (nestlev (cadr exp)) (max m (nestlev (car l)))) (l (cddr exp) (cdr l))) ((null l) (1+ m))))) (defun radsort (l) (sort l #'(lambda (a b) (let ((na (nestlev a)) (nb (nestlev b))) (cond ((< na nb) t) ((> na nb) nil) (t (great b a))))))) THIS IS THE END OF THE NEW RATIONAL FUNCTION PACKAGE PART 5
3ea02e69b6576b84983a72f2d415cd572e1f08bffa6ea78185cc18614ed061ab
freckle/stackctl
AWS.hs
module Stackctl.AWS ( module X ) where import Stackctl.AWS.CloudFormation as X import Stackctl.AWS.Core as X import Stackctl.AWS.EC2 as X import Stackctl.AWS.STS as X
null
https://raw.githubusercontent.com/freckle/stackctl/158d7e43a5127654b7ce92d6a1fa6d33eac1d959/src/Stackctl/AWS.hs
haskell
module Stackctl.AWS ( module X ) where import Stackctl.AWS.CloudFormation as X import Stackctl.AWS.Core as X import Stackctl.AWS.EC2 as X import Stackctl.AWS.STS as X
80974f2705983d397f7263fd1ac937b171782bd8b0d73969ceb0c60336d34809
obfusk/koneko
Test.hs
-- ; { { { 1 -- File : / Test.hs -- Maintainer : FC Stegerman <> Date : 2022 - 02 - 12 -- -- Copyright : Copyright (C) 2022 FC Stegerman Version : v0.0.1 License : + -- -- ; } } } 1 # LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module Koneko.Test ( doctest, doctest', testFiles, testKoneko, testMarkdown, testKoneko_, testMarkdown_, testKonekoFile, testMarkdownFile, testKonekoFile_, testMarkdownFile_ ) where import GHC.IO.Handle (hDuplicate, hDuplicateTo) import Control.Exception (bracket) import Control.Monad (unless, when) import Data.Char (isSpace) import Data.Foldable (foldl', traverse_) import Data.Text (Text) import Prelude hiding (exp, fail) import System.Console.CmdArgs.Verbosity (Verbosity(..), getVerbosity) import System.Directory (getTemporaryDirectory, removeFile) import System.Exit (exitFailure) import System.FilePath (takeExtension) import System.IO (Handle) #if !MIN_VERSION_GLASGOW_HASKELL(8, 8, 1, 0) import Data.Monoid((<>)) #endif import qualified Data.Text as T import qualified Data.Text.IO as T import qualified System.IO as IO import qualified System.IO.Silently as S import Koneko.Data (Context, Stack, emptyStack, initMain) import Koneko.Eval (initContext) import qualified Koneko.Repl as RE data Example = Example { fileName :: FilePath, lineNo :: Int, inputLine :: Text, outputLines :: [Text] } deriving Show type ExampleGroup = [Example] type Examples = [ExampleGroup] doctest :: Verbosity -> [FilePath] -> IO Bool doctest v fs = do ctx <- initContext _testFail <$> testFiles ctx v fs doctest' :: [FilePath] -> IO () doctest' fs = getVerbosity >>= flip doctest fs >>= flip unless exitFailure testFiles :: Context -> Verbosity -> [FilePath] -> IO (Int, Int, Int) testFiles ctx verb files = do r@(t,o,f) <- s <$> traverse process files when (verb /= Quiet) $ do putStrLn "=== Summary ===" putStrLn $ "Files: " ++ show (length files) ++ "." printSummary t o f return r where process fp = do let (what, func) = typAndFunc fp info = fp ++ " (" ++ what ++ ")" when (verb /= Quiet) $ putStrLn $ "=== Testing " ++ info ++ " ===" func ctx verb fp <* when (verb /= Quiet) (putStrLn "") typAndFunc fp = if takeExtension fp == ".md" then ("markdown", testMarkdownFile) else ("koneko" , testKonekoFile ) s = foldl' (\(t,o,f) (t',o',f') -> (t+t',o+o',f+f')) (0,0,0) testKoneko, testMarkdown :: Context -> Verbosity -> FilePath -> [Text] -> IO (Int, Int, Int) testKoneko ctx v fp = testExamples ctx v . parseKoneko fp testMarkdown ctx v fp = testExamples ctx v . parseMarkdown fp testKoneko_, testMarkdown_ :: Context -> Verbosity -> FilePath -> [Text] -> IO Bool testKoneko_ = _test parseKoneko testMarkdown_ = _test parseMarkdown _test :: (FilePath -> [Text] -> Examples) -> Context -> Verbosity -> FilePath -> [Text] -> IO Bool _test f ctx v fp ls = _testFail <$> testExamples ctx v (f fp ls) _testFail :: (Int, Int, Int) -> Bool _testFail (_, _, fail) = fail == 0 testKonekoFile, testMarkdownFile :: Context -> Verbosity -> FilePath -> IO (Int, Int, Int) testKonekoFile = _testFile testKoneko testMarkdownFile = _testFile testMarkdown testKonekoFile_, testMarkdownFile_ :: Context -> Verbosity -> FilePath -> IO Bool testKonekoFile_ = _testFile testKoneko_ testMarkdownFile_ = _testFile testMarkdown_ _testFile :: (Context -> Verbosity -> FilePath -> [Text] -> IO a) -> Context -> Verbosity -> FilePath -> IO a _testFile f ctx v fp = T.readFile fp >>= f ctx v fp . T.lines -- parsing -- parseKoneko, parseMarkdown :: FilePath -> [Text] -> Examples parseKoneko fp = examples fp . knkCommentBlocks [] . zip [1..] parseMarkdown fp = examples fp . mdCodeBlocks [] . zip [1..] examples :: FilePath -> [[(Int, Text)]] -> Examples examples fp = filter (not . null) . map (exampleGroup fp []) TODO exampleGroup :: FilePath -> ExampleGroup -> [(Int, Text)] -> ExampleGroup exampleGroup fileName es ls = if null ls || null ls' then reverse es else exampleGroup fileName (Example{..}:es) ls'' where ls' = dropWhile (not . isPrompt' . snd) ls (e, ls'') = span (isSameExample . snd) $ tail ls' -- safe! e' = map (dropPrefix . snd) e (c,outputLines) = span isCont e' (lineNo, fl) = head ls' -- safe! inputLine = T.concat $ map dropPrompt (dropPrefix fl:c) isSameExample s = maybe False (\x -> not $ isPrompt x || T.null x) $ T.stripPrefix prefix s dropPrefix = T.drop $ T.length prefix dropPrompt = T.drop $ T.length RE.promptText prefix = T.takeWhile isSpace fl isPrompt' = isPrompt . T.dropWhile isSpace isPrompt = T.isPrefixOf RE.promptText TODO TODO knkCommentBlocks :: [[(Int, Text)]] -> [(Int, Text)] -> [[(Int, Text)]] knkCommentBlocks bs ls = if null ls || null ls' then reverse bs else knkCommentBlocks (b':bs) ls'' where ls' = dropWhile (not . isComment) ls (b, ls'') = span isSameComment ls' b' = [ (n,T.drop (T.length prefix) x) | (n,x) <- b ] isComment = T.isPrefixOf ";" . T.dropWhile isSpace . snd isSameComment = T.isPrefixOf prefix . snd prefix = T.takeWhile isSpace (snd $ head ls') <> ";" -- safe! TODO mdCodeBlocks :: [[(Int, Text)]] -> [(Int, Text)] -> [[(Int, Text)]] mdCodeBlocks bs [] = reverse bs mdCodeBlocks bs ls = mdCodeBlocks (b:bs) $ drop 1 ls'' where ls' = dropWhile ((/= mdCodeStart) . snd) ls (b, ls'') = break ((== mdCodeEnd) . snd) $ drop 1 ls' mdCodeStart, mdCodeEnd :: Text mdCodeStart = "```koneko" mdCodeEnd = "```" -- internal -- TODO testExamples :: Context -> Verbosity -> Examples -> IO (Int, Int, Int) testExamples ctx verb ex = do r@(total, ok, fail) <- go 0 0 0 ex when (verb == Loud) $ do putStrLn "=== Summary ===" printSummary total ok fail return r where go total ok fail [] = return (total, ok, fail) go total ok fail (g:gt) = do (t, o, f) <- testExampleGroup ctx verb g go (total+t) (ok+o) (fail+f) gt TODO testExampleGroup :: Context -> Verbosity -> ExampleGroup -> IO (Int, Int, Int) testExampleGroup ctx verb g = do TODO let st = emptyStack; total = length g (ok, fail, _) <- loop 0 0 g ctx st when (verb == Loud) $ do printTTPF total ok fail; putStrLn "" return (total, ok, fail) where loop :: Int -> Int -> ExampleGroup -> Context -> Stack -> IO (Int, Int, Stack) loop ok fail [] _ s = return (ok, fail, s) loop ok fail (e@Example{..}:et) c s = do (out, err, s') <- provide (T.unpack inputLine) $ capture $ repl c s let olines = asLines out; elines = asLines err if compareOutput outputLines olines elines then do when (verb == Loud) $ printSucc e loop (ok+1) fail et c s' else do printFail e olines elines return (ok, fail+1, s') repl = RE.repl' True "" asLines x = let l = T.lines $ T.pack x in if not (null l) && last l == "" then init l else l TODO : " ... " , ... compareOutput :: [Text] -> [Text] -> [Text] -> Bool compareOutput exp got err = if null err then exp' == got else null got && T.isPrefixOf RE.errorText (head err) && exp' == err -- safe! where exp' = [ if l == "<BLANKLINE>" then "" else l | l <- exp ] printSummary :: Int -> Int -> Int -> IO () printSummary total ok fail = do printTTPF total ok fail putStrLn $ "Test " ++ if fail == 0 then "passed." else "failed." printTTPF :: Int -> Int -> Int -> IO () printTTPF total ok fail = putStrLn $ "Total: " ++ (show total) ++ ", Tried: " ++ (show $ ok + fail) ++ ", Passed: " ++ (show ok) ++ ", Failed: " ++ (show fail) ++ "." TODO printSucc :: Example -> IO () printSucc Example{..} = do p "Trying:" ; p $ indent inputLine p "Expecting:"; traverse_ (p . indent) outputLines p "ok" where p = T.putStrLn TODO printFail :: Example -> [Text] -> [Text] -> IO () printFail Example{..} out err = do p $ T.pack $ "File " ++ fileName ++ ", line " ++ show lineNo p "Failed example:" ; p $ indent inputLine p "Expected:" ; traverse_ (p . indent) outputLines p "Got:" ; traverse_ (p . indent) out unless (null err) $ do p "Errors:" ; traverse_ (p . indent) err where p = T.hPutStrLn IO.stderr indent :: Text -> Text indent = (" " <>) -- stdio -- capture :: IO a -> IO (String, String, a) capture act = do (err, (out, x)) <- S.hCapture [IO.stderr] $ S.capture act return (out, err, x) provide :: String -> IO a -> IO a provide = hProvide IO.stdin hProvide :: Handle -> String -> IO a -> IO a hProvide h str act = withTempFile "provide" f where f hTmp = do IO.hPutStr hTmp str; IO.hFlush hTmp IO.hSeek hTmp IO.AbsoluteSeek 0 withRedirect h hTmp act withRedirect :: Handle -> Handle -> IO a -> IO a withRedirect hOrig hRepl act = do buf <- IO.hGetBuffering hOrig bracket redirect (restore buf) $ const act where redirect = do hDup <- hDuplicate hOrig hDuplicateTo hRepl hOrig return hDup restore buf hDup = do hDuplicateTo hDup hOrig IO.hSetBuffering hOrig buf IO.hClose hDup withTempFile :: String -> (Handle -> IO a) -> IO a withTempFile template f = do tmpDir <- getTemporaryDirectory bracket (IO.openTempFile tmpDir template) cleanup (f . snd) where cleanup (tmpFile, h) = IO.hClose h >> removeFile tmpFile -- !!! vim : set tw=70 sw=2 sts=2 = marker :
null
https://raw.githubusercontent.com/obfusk/koneko/fd6bf756d94c574d64d25ac77ceaea6fa1ef873a/src/Koneko/Test.hs
haskell
; { { { 1 Maintainer : FC Stegerman <> Copyright : Copyright (C) 2022 FC Stegerman ; } } } 1 # LANGUAGE OverloadedStrings # parsing -- safe! safe! safe! internal -- safe! stdio -- !!!
File : / Test.hs Date : 2022 - 02 - 12 Version : v0.0.1 License : + # LANGUAGE CPP # # LANGUAGE RecordWildCards # module Koneko.Test ( doctest, doctest', testFiles, testKoneko, testMarkdown, testKoneko_, testMarkdown_, testKonekoFile, testMarkdownFile, testKonekoFile_, testMarkdownFile_ ) where import GHC.IO.Handle (hDuplicate, hDuplicateTo) import Control.Exception (bracket) import Control.Monad (unless, when) import Data.Char (isSpace) import Data.Foldable (foldl', traverse_) import Data.Text (Text) import Prelude hiding (exp, fail) import System.Console.CmdArgs.Verbosity (Verbosity(..), getVerbosity) import System.Directory (getTemporaryDirectory, removeFile) import System.Exit (exitFailure) import System.FilePath (takeExtension) import System.IO (Handle) #if !MIN_VERSION_GLASGOW_HASKELL(8, 8, 1, 0) import Data.Monoid((<>)) #endif import qualified Data.Text as T import qualified Data.Text.IO as T import qualified System.IO as IO import qualified System.IO.Silently as S import Koneko.Data (Context, Stack, emptyStack, initMain) import Koneko.Eval (initContext) import qualified Koneko.Repl as RE data Example = Example { fileName :: FilePath, lineNo :: Int, inputLine :: Text, outputLines :: [Text] } deriving Show type ExampleGroup = [Example] type Examples = [ExampleGroup] doctest :: Verbosity -> [FilePath] -> IO Bool doctest v fs = do ctx <- initContext _testFail <$> testFiles ctx v fs doctest' :: [FilePath] -> IO () doctest' fs = getVerbosity >>= flip doctest fs >>= flip unless exitFailure testFiles :: Context -> Verbosity -> [FilePath] -> IO (Int, Int, Int) testFiles ctx verb files = do r@(t,o,f) <- s <$> traverse process files when (verb /= Quiet) $ do putStrLn "=== Summary ===" putStrLn $ "Files: " ++ show (length files) ++ "." printSummary t o f return r where process fp = do let (what, func) = typAndFunc fp info = fp ++ " (" ++ what ++ ")" when (verb /= Quiet) $ putStrLn $ "=== Testing " ++ info ++ " ===" func ctx verb fp <* when (verb /= Quiet) (putStrLn "") typAndFunc fp = if takeExtension fp == ".md" then ("markdown", testMarkdownFile) else ("koneko" , testKonekoFile ) s = foldl' (\(t,o,f) (t',o',f') -> (t+t',o+o',f+f')) (0,0,0) testKoneko, testMarkdown :: Context -> Verbosity -> FilePath -> [Text] -> IO (Int, Int, Int) testKoneko ctx v fp = testExamples ctx v . parseKoneko fp testMarkdown ctx v fp = testExamples ctx v . parseMarkdown fp testKoneko_, testMarkdown_ :: Context -> Verbosity -> FilePath -> [Text] -> IO Bool testKoneko_ = _test parseKoneko testMarkdown_ = _test parseMarkdown _test :: (FilePath -> [Text] -> Examples) -> Context -> Verbosity -> FilePath -> [Text] -> IO Bool _test f ctx v fp ls = _testFail <$> testExamples ctx v (f fp ls) _testFail :: (Int, Int, Int) -> Bool _testFail (_, _, fail) = fail == 0 testKonekoFile, testMarkdownFile :: Context -> Verbosity -> FilePath -> IO (Int, Int, Int) testKonekoFile = _testFile testKoneko testMarkdownFile = _testFile testMarkdown testKonekoFile_, testMarkdownFile_ :: Context -> Verbosity -> FilePath -> IO Bool testKonekoFile_ = _testFile testKoneko_ testMarkdownFile_ = _testFile testMarkdown_ _testFile :: (Context -> Verbosity -> FilePath -> [Text] -> IO a) -> Context -> Verbosity -> FilePath -> IO a _testFile f ctx v fp = T.readFile fp >>= f ctx v fp . T.lines parseKoneko, parseMarkdown :: FilePath -> [Text] -> Examples parseKoneko fp = examples fp . knkCommentBlocks [] . zip [1..] parseMarkdown fp = examples fp . mdCodeBlocks [] . zip [1..] examples :: FilePath -> [[(Int, Text)]] -> Examples examples fp = filter (not . null) . map (exampleGroup fp []) TODO exampleGroup :: FilePath -> ExampleGroup -> [(Int, Text)] -> ExampleGroup exampleGroup fileName es ls = if null ls || null ls' then reverse es else exampleGroup fileName (Example{..}:es) ls'' where ls' = dropWhile (not . isPrompt' . snd) ls e' = map (dropPrefix . snd) e (c,outputLines) = span isCont e' inputLine = T.concat $ map dropPrompt (dropPrefix fl:c) isSameExample s = maybe False (\x -> not $ isPrompt x || T.null x) $ T.stripPrefix prefix s dropPrefix = T.drop $ T.length prefix dropPrompt = T.drop $ T.length RE.promptText prefix = T.takeWhile isSpace fl isPrompt' = isPrompt . T.dropWhile isSpace isPrompt = T.isPrefixOf RE.promptText TODO TODO knkCommentBlocks :: [[(Int, Text)]] -> [(Int, Text)] -> [[(Int, Text)]] knkCommentBlocks bs ls = if null ls || null ls' then reverse bs else knkCommentBlocks (b':bs) ls'' where ls' = dropWhile (not . isComment) ls (b, ls'') = span isSameComment ls' b' = [ (n,T.drop (T.length prefix) x) | (n,x) <- b ] isComment = T.isPrefixOf ";" . T.dropWhile isSpace . snd isSameComment = T.isPrefixOf prefix . snd TODO mdCodeBlocks :: [[(Int, Text)]] -> [(Int, Text)] -> [[(Int, Text)]] mdCodeBlocks bs [] = reverse bs mdCodeBlocks bs ls = mdCodeBlocks (b:bs) $ drop 1 ls'' where ls' = dropWhile ((/= mdCodeStart) . snd) ls (b, ls'') = break ((== mdCodeEnd) . snd) $ drop 1 ls' mdCodeStart, mdCodeEnd :: Text mdCodeStart = "```koneko" mdCodeEnd = "```" TODO testExamples :: Context -> Verbosity -> Examples -> IO (Int, Int, Int) testExamples ctx verb ex = do r@(total, ok, fail) <- go 0 0 0 ex when (verb == Loud) $ do putStrLn "=== Summary ===" printSummary total ok fail return r where go total ok fail [] = return (total, ok, fail) go total ok fail (g:gt) = do (t, o, f) <- testExampleGroup ctx verb g go (total+t) (ok+o) (fail+f) gt TODO testExampleGroup :: Context -> Verbosity -> ExampleGroup -> IO (Int, Int, Int) testExampleGroup ctx verb g = do TODO let st = emptyStack; total = length g (ok, fail, _) <- loop 0 0 g ctx st when (verb == Loud) $ do printTTPF total ok fail; putStrLn "" return (total, ok, fail) where loop :: Int -> Int -> ExampleGroup -> Context -> Stack -> IO (Int, Int, Stack) loop ok fail [] _ s = return (ok, fail, s) loop ok fail (e@Example{..}:et) c s = do (out, err, s') <- provide (T.unpack inputLine) $ capture $ repl c s let olines = asLines out; elines = asLines err if compareOutput outputLines olines elines then do when (verb == Loud) $ printSucc e loop (ok+1) fail et c s' else do printFail e olines elines return (ok, fail+1, s') repl = RE.repl' True "" asLines x = let l = T.lines $ T.pack x in if not (null l) && last l == "" then init l else l TODO : " ... " , ... compareOutput :: [Text] -> [Text] -> [Text] -> Bool compareOutput exp got err = if null err then exp' == got else null got && where exp' = [ if l == "<BLANKLINE>" then "" else l | l <- exp ] printSummary :: Int -> Int -> Int -> IO () printSummary total ok fail = do printTTPF total ok fail putStrLn $ "Test " ++ if fail == 0 then "passed." else "failed." printTTPF :: Int -> Int -> Int -> IO () printTTPF total ok fail = putStrLn $ "Total: " ++ (show total) ++ ", Tried: " ++ (show $ ok + fail) ++ ", Passed: " ++ (show ok) ++ ", Failed: " ++ (show fail) ++ "." TODO printSucc :: Example -> IO () printSucc Example{..} = do p "Trying:" ; p $ indent inputLine p "Expecting:"; traverse_ (p . indent) outputLines p "ok" where p = T.putStrLn TODO printFail :: Example -> [Text] -> [Text] -> IO () printFail Example{..} out err = do p $ T.pack $ "File " ++ fileName ++ ", line " ++ show lineNo p "Failed example:" ; p $ indent inputLine p "Expected:" ; traverse_ (p . indent) outputLines p "Got:" ; traverse_ (p . indent) out unless (null err) $ do p "Errors:" ; traverse_ (p . indent) err where p = T.hPutStrLn IO.stderr indent :: Text -> Text indent = (" " <>) capture :: IO a -> IO (String, String, a) capture act = do (err, (out, x)) <- S.hCapture [IO.stderr] $ S.capture act return (out, err, x) provide :: String -> IO a -> IO a provide = hProvide IO.stdin hProvide :: Handle -> String -> IO a -> IO a hProvide h str act = withTempFile "provide" f where f hTmp = do IO.hPutStr hTmp str; IO.hFlush hTmp IO.hSeek hTmp IO.AbsoluteSeek 0 withRedirect h hTmp act withRedirect :: Handle -> Handle -> IO a -> IO a withRedirect hOrig hRepl act = do buf <- IO.hGetBuffering hOrig bracket redirect (restore buf) $ const act where redirect = do hDup <- hDuplicate hOrig hDuplicateTo hRepl hOrig return hDup restore buf hDup = do hDuplicateTo hDup hOrig IO.hSetBuffering hOrig buf IO.hClose hDup withTempFile :: String -> (Handle -> IO a) -> IO a withTempFile template f = do tmpDir <- getTemporaryDirectory bracket (IO.openTempFile tmpDir template) cleanup (f . snd) where vim : set tw=70 sw=2 sts=2 = marker :
44f99e0066fd67d564d856cce6d1d42ed66f8efa0221efa972c6a63692cb4070
input-output-hk/ouroboros-network
Parser.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE DisambiguateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TupleSections # {-# LANGUAGE TypeFamilies #-} module Ouroboros.Consensus.Storage.ImmutableDB.Impl.Parser ( BlockSummary (..) , ChunkFileError (..) , parseChunkFile ) where import Codec.CBOR.Decoding (Decoder) import Data.Bifunctor (first) import qualified Data.ByteString.Lazy as Lazy import Data.Functor ((<&>)) import Data.Word (Word64) import qualified Streaming as S import Streaming (Of, Stream) import qualified Streaming.Prelude as S import Ouroboros.Consensus.Block hiding (headerHash) import Ouroboros.Consensus.Util.CBOR (withStreamIncrementalOffsets) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Storage.Common import Ouroboros.Consensus.Storage.FS.API (HasFS) import Ouroboros.Consensus.Storage.FS.CRC import Ouroboros.Consensus.Storage.FS.API.Types (FsPath) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary as Secondary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Types import Ouroboros.Consensus.Storage.Serialisation (DecodeDisk (..), HasBinaryBlockInfo (..)) -- | Information about a block returned by the parser. -- -- The fields of this record are strict to make sure that by evaluating this record to WHNF , we no longer hold on to the entire block . Otherwise , we might -- accidentally keep all blocks in a single file in memory during parsing. data BlockSummary blk = BlockSummary { summaryEntry :: !(Secondary.Entry blk) , summaryBlockNo :: !BlockNo , summarySlotNo :: !SlotNo } -- | Parse the contents of a chunk file. -- * The parser decodes each block in the chunk . When one of them fails to -- decode, a 'ChunkErrRead' error is returned. -- -- * Each block's checksum is checked against its given expected checksum -- (coming from the secondary index). When a checksum doesn't match, a ' ChunkErrCorrupt ' error is returned . When the secondary index is missing or -- corrupt, and there are no or fewer expected checksums, we use the given -- (more expensive) integrity checking function instead of checksum -- comparison. -- -- * We check that each block fits onto the previous one by checking the hashes. -- If not, we return a 'ChunkErrHashMismatch' error. -- -- * An error is returned in the form of: -- -- > 'Maybe' ('ChunkFileError' blk, 'Word64') -- -- The 'Word64' corresponds to the offset in the file where the last valid -- entry ends. Truncating to this offset will remove all invalid data from the -- file and just leave the valid entries before it. Note that we are not using -- 'Either' because the error might occur after some valid entries have been -- parsed successfully, in which case we still want these valid entries, but -- also want to know about the error so we can truncate the file to get rid of -- the unparseable data. -- parseChunkFile :: forall m blk h r. ( IOLike m , GetPrevHash blk , HasBinaryBlockInfo blk , DecodeDisk blk (Lazy.ByteString -> blk) ) => CodecConfig blk -> HasFS m h -> (blk -> Bool) -- ^ Check integrity of the block. 'False' = corrupt. -> FsPath -> [CRC] -> ( Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) -> m r ) -> m r parseChunkFile ccfg hasFS isNotCorrupt fsPath expectedChecksums k = withStreamIncrementalOffsets hasFS decoder fsPath ( k . checkIfHashesLineUp . checkEntries expectedChecksums . fmap (fmap (first ChunkErrRead)) ) where decoder :: forall s. Decoder s (Lazy.ByteString -> (blk, CRC)) decoder = decodeDisk ccfg <&> \mkBlk bs -> let !blk = mkBlk bs !checksum = computeCRC bs in (blk, checksum) -- | Go over the expected checksums and blocks in parallel. Stop with an -- error when a block is corrupt. Yield correct entries along the way. -- -- If there's an expected checksum and it matches the block's checksum, -- then the block is correct. Continue with the next. -- -- If they do not match or if there's no expected checksum in the stream, -- check the integrity of the block (expensive). When corrupt, stop -- parsing blocks and return an error that the block is corrupt. When not -- corrupt, continue with the next. checkEntries :: [CRC] -- ^ Expected checksums -> Stream (Of (Word64, (Word64, (blk, CRC)))) m (Maybe (ChunkFileError blk, Word64)) -- ^ Input stream of blocks (with additional info) -> Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) checkEntries = \expected -> mapAccumS expected updateAcc where updateAcc :: [CRC] -> (Word64, (Word64, (blk, CRC))) -> Either (Maybe (ChunkFileError blk, Word64)) ( (BlockSummary blk, ChainHash blk) , [CRC] ) updateAcc expected blkAndInfo@(offset, (_, (blk, checksum))) = case expected of expectedChecksum:expected' | expectedChecksum == checksum -> Right (entryAndPrevHash, expected') -- No expected entry or a mismatch _ | isNotCorrupt blk -- The (expensive) integrity check passed, so continue -> Right (entryAndPrevHash, drop 1 expected) | otherwise -- The block is corrupt, stop -> Left $ Just (ChunkErrCorrupt (blockPoint blk), offset) where entryAndPrevHash = entryForBlockAndInfo blkAndInfo entryForBlockAndInfo :: (Word64, (Word64, (blk, CRC))) -> (BlockSummary blk, ChainHash blk) entryForBlockAndInfo (offset, (_size, (blk, checksum))) = (blockSummary, prevHash) where -- Don't accidentally hold on to the block! !prevHash = blockPrevHash blk entry = Secondary.Entry { blockOffset = Secondary.BlockOffset offset , headerOffset = Secondary.HeaderOffset headerOffset , headerSize = Secondary.HeaderSize headerSize , checksum = checksum , headerHash = blockHash blk , blockOrEBB = case blockIsEBB blk of Just epoch -> EBB epoch Nothing -> Block (blockSlot blk) } !blockSummary = BlockSummary { summaryEntry = entry , summaryBlockNo = blockNo blk , summarySlotNo = blockSlot blk } BinaryBlockInfo { headerOffset, headerSize } = getBinaryBlockInfo blk checkIfHashesLineUp :: Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) -> Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) checkIfHashesLineUp = mapAccumS0 checkFirst checkNext where -- We pass the hash of the previous block around as the state (@s@). checkFirst x@(BlockSummary { summaryEntry }, _) = Right (x, Secondary.headerHash summaryEntry) checkNext hashOfPrevBlock x@(BlockSummary { summaryEntry }, prevHash) | prevHash == BlockHash hashOfPrevBlock = Right (x, Secondary.headerHash summaryEntry) | otherwise = Left (Just (err, offset)) where err = ChunkErrHashMismatch hashOfPrevBlock prevHash offset = Secondary.unBlockOffset $ Secondary.blockOffset summaryEntry {------------------------------------------------------------------------------- Streaming utilities -------------------------------------------------------------------------------} -- | Thread some state through a 'Stream'. An early return is possible by -- returning 'Left'. mapAccumS :: Monad m => s -- ^ Initial state -> (s -> a -> Either r (b, s)) -> Stream (Of a) m r -> Stream (Of b) m r mapAccumS st0 updateAcc = go st0 where go st input = S.lift (S.next input) >>= \case Left r -> return r Right (a, input') -> case updateAcc st a of Left r -> return r Right (b, st') -> S.yield b *> go st' input' | Variant of ' mapAccumS ' that calls the first function argument on the first element in the stream to construct the initial state . For all elements in the stream after the first one , the second function argument is -- used. mapAccumS0 :: forall m a b r s. Monad m => (a -> Either r (b, s)) -> (s -> a -> Either r (b, s)) -> Stream (Of a) m r -> Stream (Of b) m r mapAccumS0 initAcc updateAcc = mapAccumS Nothing updateAcc' where updateAcc' :: Maybe s -> a -> Either r (b, Maybe s) updateAcc' mbSt = fmap (fmap Just) . maybe initAcc updateAcc mbSt
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/0dcda09b6958205fe362524a7e5ea35dea320196/ouroboros-consensus/src/Ouroboros/Consensus/Storage/ImmutableDB/Impl/Parser.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE NamedFieldPuns # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # | Information about a block returned by the parser. The fields of this record are strict to make sure that by evaluating this accidentally keep all blocks in a single file in memory during parsing. | Parse the contents of a chunk file. decode, a 'ChunkErrRead' error is returned. * Each block's checksum is checked against its given expected checksum (coming from the secondary index). When a checksum doesn't match, a corrupt, and there are no or fewer expected checksums, we use the given (more expensive) integrity checking function instead of checksum comparison. * We check that each block fits onto the previous one by checking the hashes. If not, we return a 'ChunkErrHashMismatch' error. * An error is returned in the form of: > 'Maybe' ('ChunkFileError' blk, 'Word64') The 'Word64' corresponds to the offset in the file where the last valid entry ends. Truncating to this offset will remove all invalid data from the file and just leave the valid entries before it. Note that we are not using 'Either' because the error might occur after some valid entries have been parsed successfully, in which case we still want these valid entries, but also want to know about the error so we can truncate the file to get rid of the unparseable data. ^ Check integrity of the block. 'False' = corrupt. | Go over the expected checksums and blocks in parallel. Stop with an error when a block is corrupt. Yield correct entries along the way. If there's an expected checksum and it matches the block's checksum, then the block is correct. Continue with the next. If they do not match or if there's no expected checksum in the stream, check the integrity of the block (expensive). When corrupt, stop parsing blocks and return an error that the block is corrupt. When not corrupt, continue with the next. ^ Expected checksums ^ Input stream of blocks (with additional info) No expected entry or a mismatch The (expensive) integrity check passed, so continue The block is corrupt, stop Don't accidentally hold on to the block! We pass the hash of the previous block around as the state (@s@). ------------------------------------------------------------------------------ Streaming utilities ------------------------------------------------------------------------------ | Thread some state through a 'Stream'. An early return is possible by returning 'Left'. ^ Initial state used.
# LANGUAGE DisambiguateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE TupleSections # module Ouroboros.Consensus.Storage.ImmutableDB.Impl.Parser ( BlockSummary (..) , ChunkFileError (..) , parseChunkFile ) where import Codec.CBOR.Decoding (Decoder) import Data.Bifunctor (first) import qualified Data.ByteString.Lazy as Lazy import Data.Functor ((<&>)) import Data.Word (Word64) import qualified Streaming as S import Streaming (Of, Stream) import qualified Streaming.Prelude as S import Ouroboros.Consensus.Block hiding (headerHash) import Ouroboros.Consensus.Util.CBOR (withStreamIncrementalOffsets) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Storage.Common import Ouroboros.Consensus.Storage.FS.API (HasFS) import Ouroboros.Consensus.Storage.FS.CRC import Ouroboros.Consensus.Storage.FS.API.Types (FsPath) import qualified Ouroboros.Consensus.Storage.ImmutableDB.Impl.Index.Secondary as Secondary import Ouroboros.Consensus.Storage.ImmutableDB.Impl.Types import Ouroboros.Consensus.Storage.Serialisation (DecodeDisk (..), HasBinaryBlockInfo (..)) record to WHNF , we no longer hold on to the entire block . Otherwise , we might data BlockSummary blk = BlockSummary { summaryEntry :: !(Secondary.Entry blk) , summaryBlockNo :: !BlockNo , summarySlotNo :: !SlotNo } * The parser decodes each block in the chunk . When one of them fails to ' ChunkErrCorrupt ' error is returned . When the secondary index is missing or parseChunkFile :: forall m blk h r. ( IOLike m , GetPrevHash blk , HasBinaryBlockInfo blk , DecodeDisk blk (Lazy.ByteString -> blk) ) => CodecConfig blk -> HasFS m h -> FsPath -> [CRC] -> ( Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) -> m r ) -> m r parseChunkFile ccfg hasFS isNotCorrupt fsPath expectedChecksums k = withStreamIncrementalOffsets hasFS decoder fsPath ( k . checkIfHashesLineUp . checkEntries expectedChecksums . fmap (fmap (first ChunkErrRead)) ) where decoder :: forall s. Decoder s (Lazy.ByteString -> (blk, CRC)) decoder = decodeDisk ccfg <&> \mkBlk bs -> let !blk = mkBlk bs !checksum = computeCRC bs in (blk, checksum) checkEntries :: [CRC] -> Stream (Of (Word64, (Word64, (blk, CRC)))) m (Maybe (ChunkFileError blk, Word64)) -> Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) checkEntries = \expected -> mapAccumS expected updateAcc where updateAcc :: [CRC] -> (Word64, (Word64, (blk, CRC))) -> Either (Maybe (ChunkFileError blk, Word64)) ( (BlockSummary blk, ChainHash blk) , [CRC] ) updateAcc expected blkAndInfo@(offset, (_, (blk, checksum))) = case expected of expectedChecksum:expected' | expectedChecksum == checksum -> Right (entryAndPrevHash, expected') _ | isNotCorrupt blk -> Right (entryAndPrevHash, drop 1 expected) | otherwise -> Left $ Just (ChunkErrCorrupt (blockPoint blk), offset) where entryAndPrevHash = entryForBlockAndInfo blkAndInfo entryForBlockAndInfo :: (Word64, (Word64, (blk, CRC))) -> (BlockSummary blk, ChainHash blk) entryForBlockAndInfo (offset, (_size, (blk, checksum))) = (blockSummary, prevHash) where !prevHash = blockPrevHash blk entry = Secondary.Entry { blockOffset = Secondary.BlockOffset offset , headerOffset = Secondary.HeaderOffset headerOffset , headerSize = Secondary.HeaderSize headerSize , checksum = checksum , headerHash = blockHash blk , blockOrEBB = case blockIsEBB blk of Just epoch -> EBB epoch Nothing -> Block (blockSlot blk) } !blockSummary = BlockSummary { summaryEntry = entry , summaryBlockNo = blockNo blk , summarySlotNo = blockSlot blk } BinaryBlockInfo { headerOffset, headerSize } = getBinaryBlockInfo blk checkIfHashesLineUp :: Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) -> Stream (Of (BlockSummary blk, ChainHash blk)) m (Maybe (ChunkFileError blk, Word64)) checkIfHashesLineUp = mapAccumS0 checkFirst checkNext where checkFirst x@(BlockSummary { summaryEntry }, _) = Right (x, Secondary.headerHash summaryEntry) checkNext hashOfPrevBlock x@(BlockSummary { summaryEntry }, prevHash) | prevHash == BlockHash hashOfPrevBlock = Right (x, Secondary.headerHash summaryEntry) | otherwise = Left (Just (err, offset)) where err = ChunkErrHashMismatch hashOfPrevBlock prevHash offset = Secondary.unBlockOffset $ Secondary.blockOffset summaryEntry mapAccumS :: Monad m -> (s -> a -> Either r (b, s)) -> Stream (Of a) m r -> Stream (Of b) m r mapAccumS st0 updateAcc = go st0 where go st input = S.lift (S.next input) >>= \case Left r -> return r Right (a, input') -> case updateAcc st a of Left r -> return r Right (b, st') -> S.yield b *> go st' input' | Variant of ' mapAccumS ' that calls the first function argument on the first element in the stream to construct the initial state . For all elements in the stream after the first one , the second function argument is mapAccumS0 :: forall m a b r s. Monad m => (a -> Either r (b, s)) -> (s -> a -> Either r (b, s)) -> Stream (Of a) m r -> Stream (Of b) m r mapAccumS0 initAcc updateAcc = mapAccumS Nothing updateAcc' where updateAcc' :: Maybe s -> a -> Either r (b, Maybe s) updateAcc' mbSt = fmap (fmap Just) . maybe initAcc updateAcc mbSt
b4853ad483e4d0b4ad8fe4e1abf27b8b7b7cd789a3728b820cc9ac3c53c9432d
tud-fop/vanda-haskell
Text.hs
----------------------------------------------------------------------------- -- | Copyright : ( c ) 2010 -- License : BSD-style -- Maintainer : < > -- Stability : unknown -- Portability : portable ----------------------------------------------------------------------------- module Vanda.Corpus.Negra.Text ( parseNegra ) where import Control.Arrow ( first ) import qualified Data.Char as C import qualified Data.List as L import qualified Data.Text.Lazy as T import Vanda.Corpus.Negra newtype S = S [(Int, String)] currentLine :: S -> Maybe String currentLine (S ((_, x) : _)) = Just x currentLine _ = Nothing nextState :: S -> S nextState (S (_ : xs)) = S xs nextState s = errorS s "Unexpected end of file" errorS :: S -> String -> a errorS (S ((n, _) : _)) cs = error $ "Parse error on line " ++ show n ++ ": " ++ cs errorS _ cs = error $ "Parse error: " ++ cs parseNegra :: T.Text -> Negra parseNegra = parseLines ( Context $ error "Parse error: Negra format version not defined" ) . S . filter (\ (_, l) -> not (all C.isSpace l || L.isPrefixOf "%%" l)) . zip [1 ..] . map T.unpack . T.lines newtype Context = Context { parseSentence :: S -> ([SentenceData], S) } parseLines :: Context -> S -> Negra parseLines c s = case fmap wordsComment $ currentLine s of Nothing -> Negra [] [] Just (["#FORMAT", version], _) -> case version of "3" -> parseLines c{parseSentence = parseSentenceV3} $ nextState s "4" -> parseLines c{parseSentence = parseSentenceV4} $ nextState s _ -> errorS s "Unknown Negra format version" Just (["#BOT", "WORDTAG"], _) -> parseTableWordtag c $ nextState s Just ("#BOT" : _, _) -> parseLines c $ parseTable $ nextState s Just (["#BOS", num, editorId, date, originId], comment) -> let (sd, s') = parseSentence c $ nextState s in alter (Sentence (read num) (read editorId) date (read originId) comment sd :) (parseLines c s') _ -> errorS s "Expected one of: (optionally followed by %% ⟨comment⟩)\n\ \\t#FORMAT ⟨num⟩\n\ \\t#BOT WORDTAG\n\ \\t#BOT …\n\ \\t#BOS ⟨num⟩ ⟨editor id⟩ ⟨date⟩ ⟨origin id⟩" where alter f ~(Negra ws ss) = Negra ws (f ss) parseTableWordtag :: Context -> S -> Negra parseTableWordtag c s = case fmap (wordsN 3) $ currentLine s of Just ["#EOT", "WORDTAG"] -> alter (const []) $ parseLines c $ nextState s Just [tagId, tag, bound, descr] -> let bound' = case bound of "Y" -> True "N" -> False _ -> errorS s "Expected Y or N" in alter (WordTag (read tagId) tag bound' descr :) $ parseTableWordtag c $ nextState s _ -> errorS s "Expected #EOT WORDTAG or wordtag table data" where alter f ~(Negra ws ss) = Negra (f ws) ss parseTable :: S -> S parseTable s = case fmap words $ currentLine s of Just ("#EOT" : _) -> nextState s _ -> parseTable $ nextState s parseSentenceV3 :: S -> ([SentenceData], S) parseSentenceV3 s = case fmap wordsComment $ currentLine s of Just (w : postag : morphtag : edge : parent : ws, comment) -> let (sd, s') = parseSentenceV3 (nextState s) ctor = case w of ['#'] -> SentenceWord w '#' : cs -> SentenceNode (read cs) _ -> SentenceWord w in ( ctor postag morphtag (Edge edge (read parent)) (parseSecEdges ws s) comment : sd , s' ) Just ("#EOS" : _, _) -> ([], nextState s) _ -> errorS s "Expected #EOS or sentence data in Negra format version 3" parseSentenceV4 :: S -> ([SentenceData], S) parseSentenceV4 s = case fmap wordsComment $ currentLine s of TODO let (sd, s') = parseSentenceV4 (nextState s) ctor = case w of ['#'] -> SentenceWord w '#' : cs -> SentenceNode (read cs) _ -> SentenceWord w in ( ctor postag morphtag (Edge edge (read parent)) (parseSecEdges ws s) comment : sd , s' ) Just ("#EOS" : _, _) -> ([], nextState s) _ -> errorS s "Expected #EOS or sentence data in Negra format version 4" parseSecEdges :: [String] -> S -> [Edge] parseSecEdges [] _ = [] parseSecEdges (l : p : ws) s = Edge l (read p) : parseSecEdges ws s parseSecEdges _ s = errorS s "Expected secondary edge parent" wordsN :: Int -> String -> [String] wordsN 0 s = [dropWhile C.isSpace s] wordsN n s partain : . "" -> [] s' -> w : wordsN (n - 1) s'' partain : . wordsComment :: String -> ([String], Maybe String) wordsComment s partain : . "" -> ([], Nothing) '%' : '%' : cs -> ([], Just cs) s' -> first (w :) $ wordsComment s'' where (w, s'') = partain : .
null
https://raw.githubusercontent.com/tud-fop/vanda-haskell/3214966361b6dbf178155950c94423eee7f9453e/library/Vanda/Corpus/Negra/Text.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Stability : unknown Portability : portable ---------------------------------------------------------------------------
Copyright : ( c ) 2010 Maintainer : < > module Vanda.Corpus.Negra.Text ( parseNegra ) where import Control.Arrow ( first ) import qualified Data.Char as C import qualified Data.List as L import qualified Data.Text.Lazy as T import Vanda.Corpus.Negra newtype S = S [(Int, String)] currentLine :: S -> Maybe String currentLine (S ((_, x) : _)) = Just x currentLine _ = Nothing nextState :: S -> S nextState (S (_ : xs)) = S xs nextState s = errorS s "Unexpected end of file" errorS :: S -> String -> a errorS (S ((n, _) : _)) cs = error $ "Parse error on line " ++ show n ++ ": " ++ cs errorS _ cs = error $ "Parse error: " ++ cs parseNegra :: T.Text -> Negra parseNegra = parseLines ( Context $ error "Parse error: Negra format version not defined" ) . S . filter (\ (_, l) -> not (all C.isSpace l || L.isPrefixOf "%%" l)) . zip [1 ..] . map T.unpack . T.lines newtype Context = Context { parseSentence :: S -> ([SentenceData], S) } parseLines :: Context -> S -> Negra parseLines c s = case fmap wordsComment $ currentLine s of Nothing -> Negra [] [] Just (["#FORMAT", version], _) -> case version of "3" -> parseLines c{parseSentence = parseSentenceV3} $ nextState s "4" -> parseLines c{parseSentence = parseSentenceV4} $ nextState s _ -> errorS s "Unknown Negra format version" Just (["#BOT", "WORDTAG"], _) -> parseTableWordtag c $ nextState s Just ("#BOT" : _, _) -> parseLines c $ parseTable $ nextState s Just (["#BOS", num, editorId, date, originId], comment) -> let (sd, s') = parseSentence c $ nextState s in alter (Sentence (read num) (read editorId) date (read originId) comment sd :) (parseLines c s') _ -> errorS s "Expected one of: (optionally followed by %% ⟨comment⟩)\n\ \\t#FORMAT ⟨num⟩\n\ \\t#BOT WORDTAG\n\ \\t#BOT …\n\ \\t#BOS ⟨num⟩ ⟨editor id⟩ ⟨date⟩ ⟨origin id⟩" where alter f ~(Negra ws ss) = Negra ws (f ss) parseTableWordtag :: Context -> S -> Negra parseTableWordtag c s = case fmap (wordsN 3) $ currentLine s of Just ["#EOT", "WORDTAG"] -> alter (const []) $ parseLines c $ nextState s Just [tagId, tag, bound, descr] -> let bound' = case bound of "Y" -> True "N" -> False _ -> errorS s "Expected Y or N" in alter (WordTag (read tagId) tag bound' descr :) $ parseTableWordtag c $ nextState s _ -> errorS s "Expected #EOT WORDTAG or wordtag table data" where alter f ~(Negra ws ss) = Negra (f ws) ss parseTable :: S -> S parseTable s = case fmap words $ currentLine s of Just ("#EOT" : _) -> nextState s _ -> parseTable $ nextState s parseSentenceV3 :: S -> ([SentenceData], S) parseSentenceV3 s = case fmap wordsComment $ currentLine s of Just (w : postag : morphtag : edge : parent : ws, comment) -> let (sd, s') = parseSentenceV3 (nextState s) ctor = case w of ['#'] -> SentenceWord w '#' : cs -> SentenceNode (read cs) _ -> SentenceWord w in ( ctor postag morphtag (Edge edge (read parent)) (parseSecEdges ws s) comment : sd , s' ) Just ("#EOS" : _, _) -> ([], nextState s) _ -> errorS s "Expected #EOS or sentence data in Negra format version 3" parseSentenceV4 :: S -> ([SentenceData], S) parseSentenceV4 s = case fmap wordsComment $ currentLine s of TODO let (sd, s') = parseSentenceV4 (nextState s) ctor = case w of ['#'] -> SentenceWord w '#' : cs -> SentenceNode (read cs) _ -> SentenceWord w in ( ctor postag morphtag (Edge edge (read parent)) (parseSecEdges ws s) comment : sd , s' ) Just ("#EOS" : _, _) -> ([], nextState s) _ -> errorS s "Expected #EOS or sentence data in Negra format version 4" parseSecEdges :: [String] -> S -> [Edge] parseSecEdges [] _ = [] parseSecEdges (l : p : ws) s = Edge l (read p) : parseSecEdges ws s parseSecEdges _ s = errorS s "Expected secondary edge parent" wordsN :: Int -> String -> [String] wordsN 0 s = [dropWhile C.isSpace s] wordsN n s partain : . "" -> [] s' -> w : wordsN (n - 1) s'' partain : . wordsComment :: String -> ([String], Maybe String) wordsComment s partain : . "" -> ([], Nothing) '%' : '%' : cs -> ([], Just cs) s' -> first (w :) $ wordsComment s'' where (w, s'') = partain : .
9fdb55d8da6e0b5ed46c3f11b96a2b5b03a02d1119d23f8fe66f3110ed1922c9
clojure/core.rrb-vector
transients.cljs
Copyright ( c ) and contributors . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.core.rrb-vector.transients (:refer-clojure :exclude [new-path]) (:require [clojure.core.rrb-vector.nodes :refer [regular? clone node-ranges last-range overflow?]] [clojure.core.rrb-vector.trees :refer [new-path]])) (defn ensure-editable [edit node] (if (identical? (.-edit node) edit) node (let [new-arr (aclone (.-arr node))] (if (== 33 (alength new-arr)) (aset new-arr 32 (aclone (aget new-arr 32)))) (VectorNode. edit new-arr)))) (defn editable-root [root] (let [new-arr (aclone (.-arr root))] (if (== 33 (alength new-arr)) (aset new-arr 32 (aclone (aget new-arr 32)))) (VectorNode. (js-obj) new-arr))) (defn editable-tail [tail] (let [ret (make-array 32)] (array-copy tail 0 ret 0 (alength tail)) ret)) Note 1 : This condition check and exception are a little bit closer to the source of the cause for what was issue CRRBV-20 , added in ;; case there is still some remaining way to cause this condition to ;; occur. Note 2 : In the worst case , when the tree is nearly full , calling ;; overflow? here takes run time O(tree_depth^2) here. That could be made ) . One way would be to call push - tail ! in hopes ;; that it succeeds, but return some distinctive value indicating a ;; failure on the full condition, and create the node via a new-path ;; call at most recent recursive push-tail! call that has an empty ;; slot available. (defn push-tail! [shift cnt root-edit current-node tail-node] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (do (loop [n ret shift shift] (let [arr (.-arr n) subidx (bit-and (bit-shift-right (dec cnt) shift) 0x1f)] (if (== shift 5) (aset arr subidx tail-node) (let [child (aget arr subidx)] (if (nil? child) (aset arr subidx (new-path (.-arr tail-node) root-edit (- shift 5) tail-node)) (let [editable-child (ensure-editable root-edit child)] (aset arr subidx editable-child) (recur editable-child (- shift 5)))))))) ret) (let [arr (.-arr ret) rngs (node-ranges ret) li (dec (aget rngs 32)) cret (if (== shift 5) nil (let [child (ensure-editable root-edit (aget arr li)) ccnt (+ (if (pos? li) (- (aget rngs li) (aget rngs (dec li))) (aget rngs 0)) add 32 elems to account for the ;; new full tail we plan to add to ;; the subtree. 32)] See Note 2 (if-not (overflow? child (- shift 5) ccnt) (push-tail! (- shift 5) ccnt root-edit child tail-node))))] (if cret (do (aset arr li cret) (aset rngs li (+ (aget rngs li) 32)) ret) (do (when (>= li 31) See Note 1 (let [msg (str "Assigning index " (inc li) " of vector" " object array to become a node, when that" " index should only be used for storing" " range arrays.") data {:shift shift, :cnd cnt, :current-node current-node, :tail-node tail-node, :rngs rngs, :li li, :cret cret}] (throw (ex-info msg data)))) (aset arr (inc li) (new-path (.-arr tail-node) root-edit (- shift 5) tail-node)) (aset rngs (inc li) (+ (aget rngs li) 32)) (aset rngs 32 (inc (aget rngs 32))) ret)))))) (defn pop-tail! [shift cnt root-edit current-node] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (let [subidx (bit-and (bit-shift-right (- cnt 2) shift) 0x1f)] (cond (> shift 5) (let [child (pop-tail! (- shift 5) cnt root-edit (aget (.-arr ret) subidx))] (if (and (nil? child) (zero? subidx)) nil (let [arr (.-arr ret)] (aset arr subidx child) ret))) (zero? subidx) nil :else (let [arr (.-arr ret)] (aset arr subidx nil) ret))) (let [rngs (node-ranges ret) subidx (dec (aget rngs 32))] (cond (> shift 5) (let [child (aget (.-arr ret) subidx) child-cnt (if (zero? subidx) (aget rngs 0) (- (aget rngs subidx) (aget rngs (dec subidx)))) new-child (pop-tail! (- shift 5) child-cnt root-edit child)] (cond (and (nil? new-child) (zero? subidx)) nil (regular? child) (let [arr (.-arr ret)] (aset rngs subidx (- (aget rngs subidx) 32)) (aset arr subidx new-child) (if (nil? new-child) (aset rngs 32 (dec (aget rngs 32)))) ret) :else (let [rng (last-range child) diff (- rng (if new-child (last-range new-child) 0)) arr (.-arr ret)] (aset rngs subidx (- (aget rngs subidx) diff)) (aset arr subidx new-child) (if (nil? new-child) (aset rngs 32 (dec (aget rngs 32)))) ret))) (zero? subidx) nil :else (let [arr (.-arr ret) child (aget arr subidx)] (aset arr subidx nil) (aset rngs subidx 0) (aset rngs 32 (dec (aget rngs 32))) ret)))))) (defn do-assoc! [shift root-edit current-node i val] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (loop [shift shift node ret] (if (zero? shift) (let [arr (.-arr node)] (aset arr (bit-and i 0x1f) val)) (let [arr (.-arr node) subidx (bit-and (bit-shift-right i shift) 0x1f) child (ensure-editable root-edit (aget arr subidx))] (aset arr subidx child) (recur (- shift 5) child)))) (let [arr (.-arr ret) rngs (node-ranges ret) subidx (bit-and (bit-shift-right i shift) 0x1f) subidx (loop [subidx subidx] (if (< i (int (aget rngs subidx))) subidx (recur (inc subidx)))) i (if (zero? subidx) i (- i (aget rngs (dec subidx))))] (aset arr subidx (do-assoc! (- shift 5) root-edit (aget arr subidx) i val)))) ret))
null
https://raw.githubusercontent.com/clojure/core.rrb-vector/88c2f814b47c0bbc4092dad82be2ec783ed2961f/src/main/cljs/clojure/core/rrb_vector/transients.cljs
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. case there is still some remaining way to cause this condition to occur. overflow? here takes run time O(tree_depth^2) here. That could be that it succeeds, but return some distinctive value indicating a failure on the full condition, and create the node via a new-path call at most recent recursive push-tail! call that has an empty slot available. new full tail we plan to add to the subtree.
Copyright ( c ) and contributors . All rights reserved . (ns clojure.core.rrb-vector.transients (:refer-clojure :exclude [new-path]) (:require [clojure.core.rrb-vector.nodes :refer [regular? clone node-ranges last-range overflow?]] [clojure.core.rrb-vector.trees :refer [new-path]])) (defn ensure-editable [edit node] (if (identical? (.-edit node) edit) node (let [new-arr (aclone (.-arr node))] (if (== 33 (alength new-arr)) (aset new-arr 32 (aclone (aget new-arr 32)))) (VectorNode. edit new-arr)))) (defn editable-root [root] (let [new-arr (aclone (.-arr root))] (if (== 33 (alength new-arr)) (aset new-arr 32 (aclone (aget new-arr 32)))) (VectorNode. (js-obj) new-arr))) (defn editable-tail [tail] (let [ret (make-array 32)] (array-copy tail 0 ret 0 (alength tail)) ret)) Note 1 : This condition check and exception are a little bit closer to the source of the cause for what was issue CRRBV-20 , added in Note 2 : In the worst case , when the tree is nearly full , calling made ) . One way would be to call push - tail ! in hopes (defn push-tail! [shift cnt root-edit current-node tail-node] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (do (loop [n ret shift shift] (let [arr (.-arr n) subidx (bit-and (bit-shift-right (dec cnt) shift) 0x1f)] (if (== shift 5) (aset arr subidx tail-node) (let [child (aget arr subidx)] (if (nil? child) (aset arr subidx (new-path (.-arr tail-node) root-edit (- shift 5) tail-node)) (let [editable-child (ensure-editable root-edit child)] (aset arr subidx editable-child) (recur editable-child (- shift 5)))))))) ret) (let [arr (.-arr ret) rngs (node-ranges ret) li (dec (aget rngs 32)) cret (if (== shift 5) nil (let [child (ensure-editable root-edit (aget arr li)) ccnt (+ (if (pos? li) (- (aget rngs li) (aget rngs (dec li))) (aget rngs 0)) add 32 elems to account for the 32)] See Note 2 (if-not (overflow? child (- shift 5) ccnt) (push-tail! (- shift 5) ccnt root-edit child tail-node))))] (if cret (do (aset arr li cret) (aset rngs li (+ (aget rngs li) 32)) ret) (do (when (>= li 31) See Note 1 (let [msg (str "Assigning index " (inc li) " of vector" " object array to become a node, when that" " index should only be used for storing" " range arrays.") data {:shift shift, :cnd cnt, :current-node current-node, :tail-node tail-node, :rngs rngs, :li li, :cret cret}] (throw (ex-info msg data)))) (aset arr (inc li) (new-path (.-arr tail-node) root-edit (- shift 5) tail-node)) (aset rngs (inc li) (+ (aget rngs li) 32)) (aset rngs 32 (inc (aget rngs 32))) ret)))))) (defn pop-tail! [shift cnt root-edit current-node] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (let [subidx (bit-and (bit-shift-right (- cnt 2) shift) 0x1f)] (cond (> shift 5) (let [child (pop-tail! (- shift 5) cnt root-edit (aget (.-arr ret) subidx))] (if (and (nil? child) (zero? subidx)) nil (let [arr (.-arr ret)] (aset arr subidx child) ret))) (zero? subidx) nil :else (let [arr (.-arr ret)] (aset arr subidx nil) ret))) (let [rngs (node-ranges ret) subidx (dec (aget rngs 32))] (cond (> shift 5) (let [child (aget (.-arr ret) subidx) child-cnt (if (zero? subidx) (aget rngs 0) (- (aget rngs subidx) (aget rngs (dec subidx)))) new-child (pop-tail! (- shift 5) child-cnt root-edit child)] (cond (and (nil? new-child) (zero? subidx)) nil (regular? child) (let [arr (.-arr ret)] (aset rngs subidx (- (aget rngs subidx) 32)) (aset arr subidx new-child) (if (nil? new-child) (aset rngs 32 (dec (aget rngs 32)))) ret) :else (let [rng (last-range child) diff (- rng (if new-child (last-range new-child) 0)) arr (.-arr ret)] (aset rngs subidx (- (aget rngs subidx) diff)) (aset arr subidx new-child) (if (nil? new-child) (aset rngs 32 (dec (aget rngs 32)))) ret))) (zero? subidx) nil :else (let [arr (.-arr ret) child (aget arr subidx)] (aset arr subidx nil) (aset rngs subidx 0) (aset rngs 32 (dec (aget rngs 32))) ret)))))) (defn do-assoc! [shift root-edit current-node i val] (let [ret (ensure-editable root-edit current-node)] (if (regular? ret) (loop [shift shift node ret] (if (zero? shift) (let [arr (.-arr node)] (aset arr (bit-and i 0x1f) val)) (let [arr (.-arr node) subidx (bit-and (bit-shift-right i shift) 0x1f) child (ensure-editable root-edit (aget arr subidx))] (aset arr subidx child) (recur (- shift 5) child)))) (let [arr (.-arr ret) rngs (node-ranges ret) subidx (bit-and (bit-shift-right i shift) 0x1f) subidx (loop [subidx subidx] (if (< i (int (aget rngs subidx))) subidx (recur (inc subidx)))) i (if (zero? subidx) i (- i (aget rngs (dec subidx))))] (aset arr subidx (do-assoc! (- shift 5) root-edit (aget arr subidx) i val)))) ret))
905cf0141ca0070c4c53e42095c418c7cc044df5d1311b10e6132438c10346cc
MinaProtocol/mina
mina_networking.ml
open Core open Async open Mina_base module Sync_ledger = Mina_ledger.Sync_ledger open Mina_block open Network_peer open Network_pool open Pipe_lib let refused_answer_query_string = "Refused to answer_query" exception No_initial_peers type Structured_log_events.t += | Gossip_new_state of { state_hash : State_hash.t } [@@deriving register_event { msg = "Broadcasting new state over gossip net" }] type Structured_log_events.t += | Gossip_transaction_pool_diff of { txns : Transaction_pool.Resource_pool.Diff.t } [@@deriving register_event { msg = "Broadcasting transaction pool diff over gossip net" }] type Structured_log_events.t += | Gossip_snark_pool_diff of { work : Snark_pool.Resource_pool.Diff.compact } [@@deriving register_event { msg = "Broadcasting snark pool diff over gossip net" }] INSTRUCTIONS FOR ADDING A NEW RPC : * - define a new module under the Rpcs module * - add an entry to the Rpcs.rpc GADT definition for the new module ( type ( ' query , ' response ) rpc , below ) * - add the new constructor for Rpcs.rpc to Rpcs.all_of_type_erased_rpc * - add a pattern matching case to Rpcs.implementation_of_rpc mapping the * new constructor to the new module for your RPC * - add a match case to ` match_handler ` , below * - define a new module under the Rpcs module * - add an entry to the Rpcs.rpc GADT definition for the new module (type ('query, 'response) rpc, below) * - add the new constructor for Rpcs.rpc to Rpcs.all_of_type_erased_rpc * - add a pattern matching case to Rpcs.implementation_of_rpc mapping the * new constructor to the new module for your RPC * - add a match case to `match_handler`, below *) module Rpcs = struct for versioning of the types here , see RFC 0012 , and -core/latest/doc/async_rpc_kernel/Async_rpc_kernel/Versioned_rpc/ The " master " types are the ones used internally in the code base . Each version has coercions between their query and response types and the master types . RFC 0012, and -core/latest/doc/async_rpc_kernel/Async_rpc_kernel/Versioned_rpc/ The "master" types are the ones used internally in the code base. Each version has coercions between their query and response types and the master types. *) [%%versioned_rpc module Get_some_initial_peers = struct module Master = struct let name = "get_some_initial_peers" module T = struct type query = unit [@@deriving sexp, yojson] type response = Network_peer.Peer.t list [@@deriving sexp, yojson] end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_some_initial_peers_rpcs_sent let received_counter = Mina_metrics.Network.get_some_initial_peers_rpcs_received let failed_request_counter = Mina_metrics.Network.get_some_initial_peers_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_some_initial_peers_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = unit type response = Network_peer.Peer.Stable.V1.t list let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_staged_ledger_aux_and_pending_coinbases_at_hash = struct module Master = struct let name = "get_staged_ledger_aux_and_pending_coinbases_at_hash" module T = struct type query = State_hash.t type response = ( Staged_ledger.Scan_state.t * Ledger_hash.t * Pending_coinbase.t * Mina_state.Protocol_state.value list ) option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpcs_sent let received_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpcs_received let failed_request_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc_requests_failed let failed_response_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = State_hash.Stable.V1.t type response = ( Staged_ledger.Scan_state.Stable.V2.t * Ledger_hash.Stable.V1.t * Pending_coinbase.Stable.V2.t * Mina_state.Protocol_state.Value.Stable.V2.t list ) option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Answer_sync_ledger_query = struct module Master = struct let name = "answer_sync_ledger_query" module T = struct type query = Ledger_hash.t * Sync_ledger.Query.t type response = Sync_ledger.Answer.t Core.Or_error.t end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.answer_sync_ledger_query_rpcs_sent let received_counter = Mina_metrics.Network.answer_sync_ledger_query_rpcs_received let failed_request_counter = Mina_metrics.Network.answer_sync_ledger_query_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.answer_sync_ledger_query_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = Ledger_hash.Stable.V1.t * Sync_ledger.Query.Stable.V1.t [@@deriving sexp] type response = Sync_ledger.Answer.Stable.V2.t Core.Or_error.Stable.V1.t [@@deriving sexp] let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_chain = struct module Master = struct let name = "get_transition_chain" module T = struct type query = State_hash.t list [@@deriving sexp, to_yojson] type response = Mina_block.t list option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_chain_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_chain_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_chain_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_chain_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = State_hash.Stable.V1.t list [@@deriving sexp] type response = Mina_block.Stable.V2.t list option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_chain_proof = struct module Master = struct let name = "get_transition_chain_proof" module T = struct type query = State_hash.t [@@deriving sexp, to_yojson] type response = (State_hash.t * State_body_hash.t list) option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_chain_proof_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_chain_proof_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_chain_proof_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_chain_proof_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = State_hash.Stable.V1.t [@@deriving sexp] type response = (State_hash.Stable.V1.t * State_body_hash.Stable.V1.t list) option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_knowledge = struct module Master = struct let name = "Get_transition_knowledge" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = State_hash.t list end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_knowledge_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_knowledge_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_knowledge_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_knowledge_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = unit [@@deriving sexp] type response = State_hash.Stable.V1.t list let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_ancestry = struct module Master = struct let name = "get_ancestry" module T = struct * NB : The state hash sent in this query should not be trusted , as it can be forged . This is ok for how this RPC is implented , as we only use the state hash for tie breaking when checking whether or not the proof is worth serving . type query = (Consensus.Data.Consensus_state.Value.t, State_hash.t) With_hash.t [@@deriving sexp, to_yojson] type response = ( Mina_block.t , State_body_hash.t list * Mina_block.t ) Proof_carrying_data.t option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_ancestry_rpcs_sent let received_counter = Mina_metrics.Network.get_ancestry_rpcs_received let failed_request_counter = Mina_metrics.Network.get_ancestry_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_ancestry_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = ( Consensus.Data.Consensus_state.Value.Stable.V1.t , State_hash.Stable.V1.t ) With_hash.Stable.V1.t [@@deriving sexp] type response = ( Mina_block.Stable.V2.t , State_body_hash.Stable.V1.t list * Mina_block.Stable.V2.t ) Proof_carrying_data.Stable.V1.t option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Ban_notify = struct module Master = struct let name = "ban_notify" module T = struct (* banned until this time *) type query = Core.Time.t [@@deriving sexp] type response = unit end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.ban_notify_rpcs_sent let received_counter = Mina_metrics.Network.ban_notify_rpcs_received let failed_request_counter = Mina_metrics.Network.ban_notify_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.ban_notify_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = Core.Time.Stable.V1.t [@@deriving sexp] type response = unit let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_best_tip = struct module Master = struct let name = "get_best_tip" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = ( Mina_block.t , State_body_hash.t list * Mina_block.t ) Proof_carrying_data.t option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_best_tip_rpcs_sent let received_counter = Mina_metrics.Network.get_best_tip_rpcs_received let failed_request_counter = Mina_metrics.Network.get_best_tip_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_best_tip_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = unit [@@deriving sexp] type response = ( Mina_block.Stable.V2.t , State_body_hash.Stable.V1.t list * Mina_block.Stable.V2.t ) Proof_carrying_data.Stable.V1.t option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_node_status = struct module Node_status = struct [%%versioned module Stable = struct module V2 = struct type t = { node_ip_addr : Core.Unix.Inet_addr.Stable.V1.t [@to_yojson fun ip_addr -> `String (Unix.Inet_addr.to_string ip_addr)] [@of_yojson function | `String s -> Ok (Unix.Inet_addr.of_string s) | _ -> Error "expected string"] ; node_peer_id : Network_peer.Peer.Id.Stable.V1.t [@to_yojson fun peer_id -> `String peer_id] [@of_yojson function `String s -> Ok s | _ -> Error "expected string"] ; sync_status : Sync_status.Stable.V1.t ; peers : Network_peer.Peer.Stable.V1.t list ; block_producers : Signature_lib.Public_key.Compressed.Stable.V1.t list ; protocol_state_hash : State_hash.Stable.V1.t ; ban_statuses : ( Network_peer.Peer.Stable.V1.t * Trust_system.Peer_status.Stable.V1.t ) list ; k_block_hashes_and_timestamps : (State_hash.Stable.V1.t * string) list ; git_commit : string ; uptime_minutes : int ; block_height_opt : int option [@default None] } [@@deriving to_yojson, of_yojson] let to_latest = Fn.id end module V1 = struct type t = { node_ip_addr : Core.Unix.Inet_addr.Stable.V1.t [@to_yojson fun ip_addr -> `String (Unix.Inet_addr.to_string ip_addr)] [@of_yojson function | `String s -> Ok (Unix.Inet_addr.of_string s) | _ -> Error "expected string"] ; node_peer_id : Network_peer.Peer.Id.Stable.V1.t [@to_yojson fun peer_id -> `String peer_id] [@of_yojson function `String s -> Ok s | _ -> Error "expected string"] ; sync_status : Sync_status.Stable.V1.t ; peers : Network_peer.Peer.Stable.V1.t list ; block_producers : Signature_lib.Public_key.Compressed.Stable.V1.t list ; protocol_state_hash : State_hash.Stable.V1.t ; ban_statuses : ( Network_peer.Peer.Stable.V1.t * Trust_system.Peer_status.Stable.V1.t ) list ; k_block_hashes_and_timestamps : (State_hash.Stable.V1.t * string) list ; git_commit : string ; uptime_minutes : int } [@@deriving to_yojson, of_yojson] let to_latest status : Latest.t = { node_ip_addr = status.node_ip_addr ; node_peer_id = status.node_peer_id ; sync_status = status.sync_status ; peers = status.peers ; block_producers = status.block_producers ; protocol_state_hash = status.protocol_state_hash ; ban_statuses = status.ban_statuses ; k_block_hashes_and_timestamps = status.k_block_hashes_and_timestamps ; git_commit = status.git_commit ; uptime_minutes = status.uptime_minutes ; block_height_opt = None } end end] end module Master = struct let name = "get_node_status" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = Node_status.t Or_error.t end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_node_status_rpcs_sent let received_counter = Mina_metrics.Network.get_node_status_rpcs_received let failed_request_counter = Mina_metrics.Network.get_node_status_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_node_status_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M let response_to_yojson response = match response with | Ok status -> Node_status.Stable.Latest.to_yojson status | Error err -> `Assoc [ ("error", Error_json.error_to_yojson err) ] include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = unit [@@deriving sexp] type response = Node_status.Stable.V2.t Core_kernel.Or_error.Stable.V1.t let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end module V1 = struct module T = struct type query = unit [@@deriving sexp] type response = Node_status.Stable.V1.t Core_kernel.Or_error.Stable.V1.t let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = function | Error err -> Error err | Ok (status : Node_status.Stable.Latest.t) -> Ok { Node_status.Stable.V1.node_ip_addr = status.node_ip_addr ; node_peer_id = status.node_peer_id ; sync_status = status.sync_status ; peers = status.peers ; block_producers = status.block_producers ; protocol_state_hash = status.protocol_state_hash ; ban_statuses = status.ban_statuses ; k_block_hashes_and_timestamps = status.k_block_hashes_and_timestamps ; git_commit = status.git_commit ; uptime_minutes = status.uptime_minutes } let caller_model_of_response = function | Error err -> Error err | Ok (status : Node_status.Stable.V1.t) -> Ok (Node_status.Stable.V1.to_latest status) end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] type ('query, 'response) rpc = | Get_some_initial_peers : (Get_some_initial_peers.query, Get_some_initial_peers.response) rpc | Get_staged_ledger_aux_and_pending_coinbases_at_hash : ( Get_staged_ledger_aux_and_pending_coinbases_at_hash.query , Get_staged_ledger_aux_and_pending_coinbases_at_hash.response ) rpc | Answer_sync_ledger_query : ( Answer_sync_ledger_query.query , Answer_sync_ledger_query.response ) rpc | Get_transition_chain : (Get_transition_chain.query, Get_transition_chain.response) rpc | Get_transition_knowledge : ( Get_transition_knowledge.query , Get_transition_knowledge.response ) rpc | Get_transition_chain_proof : ( Get_transition_chain_proof.query , Get_transition_chain_proof.response ) rpc | Get_node_status : (Get_node_status.query, Get_node_status.response) rpc | Get_ancestry : (Get_ancestry.query, Get_ancestry.response) rpc | Ban_notify : (Ban_notify.query, Ban_notify.response) rpc | Get_best_tip : (Get_best_tip.query, Get_best_tip.response) rpc type rpc_handler = | Rpc_handler : { rpc : ('q, 'r) rpc ; f : ('q, 'r) Rpc_intf.rpc_fn ; cost : 'q -> int ; budget : int * [ `Per of Time.Span.t ] } -> rpc_handler let implementation_of_rpc : type q r. (q, r) rpc -> (q, r) Rpc_intf.rpc_implementation = function | Get_some_initial_peers -> (module Get_some_initial_peers) | Get_staged_ledger_aux_and_pending_coinbases_at_hash -> (module Get_staged_ledger_aux_and_pending_coinbases_at_hash) | Answer_sync_ledger_query -> (module Answer_sync_ledger_query) | Get_transition_chain -> (module Get_transition_chain) | Get_transition_knowledge -> (module Get_transition_knowledge) | Get_transition_chain_proof -> (module Get_transition_chain_proof) | Get_node_status -> (module Get_node_status) | Get_ancestry -> (module Get_ancestry) | Ban_notify -> (module Ban_notify) | Get_best_tip -> (module Get_best_tip) let match_handler : type q r. rpc_handler -> (q, r) rpc -> do_:((q, r) Rpc_intf.rpc_fn -> 'a) -> 'a option = fun (Rpc_handler { rpc = impl_rpc; f; cost = _; budget = _ }) rpc ~do_ -> match (rpc, impl_rpc) with | Get_some_initial_peers, Get_some_initial_peers -> Some (do_ f) | Get_some_initial_peers, _ -> None | ( Get_staged_ledger_aux_and_pending_coinbases_at_hash , Get_staged_ledger_aux_and_pending_coinbases_at_hash ) -> Some (do_ f) | Get_staged_ledger_aux_and_pending_coinbases_at_hash, _ -> None | Answer_sync_ledger_query, Answer_sync_ledger_query -> Some (do_ f) | Answer_sync_ledger_query, _ -> None | Get_transition_chain, Get_transition_chain -> Some (do_ f) | Get_transition_chain, _ -> None | Get_transition_knowledge, Get_transition_knowledge -> Some (do_ f) | Get_transition_knowledge, _ -> None | Get_transition_chain_proof, Get_transition_chain_proof -> Some (do_ f) | Get_transition_chain_proof, _ -> None | Get_node_status, Get_node_status -> Some (do_ f) | Get_node_status, _ -> None | Get_ancestry, Get_ancestry -> Some (do_ f) | Get_ancestry, _ -> None | Ban_notify, Ban_notify -> Some (do_ f) | Ban_notify, _ -> None | Get_best_tip, Get_best_tip -> Some (do_ f) | Get_best_tip, _ -> None end module Sinks = Sinks module Gossip_net = Gossip_net.Make (Rpcs) module Config = struct type log_gossip_heard = { snark_pool_diff : bool; transaction_pool_diff : bool; new_state : bool } [@@deriving make] type t = { logger : Logger.t ; trust_system : Trust_system.t ; time_controller : Block_time.Controller.t ; consensus_constants : Consensus.Constants.t ; consensus_local_state : Consensus.Data.Local_state.t ; genesis_ledger_hash : Ledger_hash.t ; constraint_constants : Genesis_constants.Constraint_constants.t ; precomputed_values : Precomputed_values.t ; creatable_gossip_net : Gossip_net.Any.creatable ; is_seed : bool ; log_gossip_heard : log_gossip_heard } [@@deriving make] end type t = { logger : Logger.t ; trust_system : Trust_system.t ; gossip_net : Gossip_net.Any.t } [@@deriving fields] let wrap_rpc_data_in_envelope conn data = Envelope.Incoming.wrap_peer ~data ~sender:conn type protocol_version_status = { valid_current : bool; valid_next : bool; matches_daemon : bool } let protocol_version_status t = let header = Mina_block.header t in let valid_current = Protocol_version.is_valid (Header.current_protocol_version header) in let valid_next = Option.for_all (Header.proposed_protocol_version_opt header) ~f:Protocol_version.is_valid in let matches_daemon = Protocol_version.compatible_with_daemon (Header.current_protocol_version header) in { valid_current; valid_next; matches_daemon } let create (config : Config.t) ~sinks ~(get_some_initial_peers : Rpcs.Get_some_initial_peers.query Envelope.Incoming.t -> Rpcs.Get_some_initial_peers.response Deferred.t ) ~(get_staged_ledger_aux_and_pending_coinbases_at_hash : Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash.query Envelope.Incoming.t -> Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash.response Deferred.t ) ~(answer_sync_ledger_query : Rpcs.Answer_sync_ledger_query.query Envelope.Incoming.t -> Rpcs.Answer_sync_ledger_query.response Deferred.t ) ~(get_ancestry : Rpcs.Get_ancestry.query Envelope.Incoming.t -> Rpcs.Get_ancestry.response Deferred.t ) ~(get_best_tip : Rpcs.Get_best_tip.query Envelope.Incoming.t -> Rpcs.Get_best_tip.response Deferred.t ) ~(get_node_status : Rpcs.Get_node_status.query Envelope.Incoming.t -> Rpcs.Get_node_status.response Deferred.t ) ~(get_transition_chain_proof : Rpcs.Get_transition_chain_proof.query Envelope.Incoming.t -> Rpcs.Get_transition_chain_proof.response Deferred.t ) ~(get_transition_chain : Rpcs.Get_transition_chain.query Envelope.Incoming.t -> Rpcs.Get_transition_chain.response Deferred.t ) ~(get_transition_knowledge : Rpcs.Get_transition_knowledge.query Envelope.Incoming.t -> Rpcs.Get_transition_knowledge.response Deferred.t ) = let module Context = struct let logger = config.logger end in let open Context in let run_for_rpc_result conn data ~f action_msg msg_args = let data_in_envelope = wrap_rpc_data_in_envelope conn data in let sender = Envelope.Incoming.sender data_in_envelope in let%bind () = Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions.(Made_request, Some (action_msg, msg_args))) in let%bind result = f data_in_envelope in return (result, sender) in let incr_failed_response = Mina_metrics.Counter.inc_one in let record_unknown_item result sender action_msg msg_args failed_response_counter = let%map () = if Option.is_none result then ( incr_failed_response failed_response_counter ; Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions.(Requested_unknown_item, Some (action_msg, msg_args))) ) else return () in result in let validate_protocol_versions ~rpc_name sender external_transition = let open Trust_system.Actions in let { valid_current; valid_next; matches_daemon } = protocol_version_status external_transition in let%bind () = if valid_current then return () else let actions = ( Sent_invalid_protocol_version , Some ( "$rpc_name: external transition with invalid current protocol \ version" , [ ("rpc_name", `String rpc_name) ; ( "current_protocol_version" , `String (Protocol_version.to_string (Header.current_protocol_version (Mina_block.header external_transition) ) ) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in let%bind () = if valid_next then return () else let actions = ( Sent_invalid_protocol_version , Some ( "$rpc_name: external transition with invalid proposed protocol \ version" , [ ("rpc_name", `String rpc_name) ; ( "proposed_protocol_version" , `String (Protocol_version.to_string (Option.value_exn (Header.proposed_protocol_version_opt (Mina_block.header external_transition) ) ) ) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in let%map () = if matches_daemon then return () else let actions = ( Sent_mismatched_protocol_version , Some ( "$rpc_name: current protocol version in external transition \ does not match daemon current protocol version" , [ ("rpc_name", `String rpc_name) ; ( "current_protocol_version" , `String (Protocol_version.to_string (Header.current_protocol_version (Mina_block.header external_transition) ) ) ) ; ( "daemon_current_protocol_version" , `String Protocol_version.(to_string @@ get_current ()) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in valid_current && valid_next && matches_daemon in each of the passed - in procedures expects an enveloped input , so we wrap the data received via RPC we wrap the data received via RPC *) let get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc conn ~version:_ hash = let action_msg = "Staged ledger and pending coinbases at hash: $hash" in let msg_args = [ ("hash", State_hash.to_yojson hash) ] in let%bind result, sender = run_for_rpc_result conn hash ~f:get_staged_ledger_aux_and_pending_coinbases_at_hash action_msg msg_args in record_unknown_item result sender action_msg msg_args Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash .failed_response_counter in let answer_sync_ledger_query_rpc conn ~version:_ ((hash, query) as sync_query) = let%bind result, sender = run_for_rpc_result conn sync_query ~f:answer_sync_ledger_query "Answer_sync_ledger_query: $query" [ ("query", Sync_ledger.Query.to_yojson query) ] in let%bind () = match result with | Ok _ -> return () | Error err -> (* N.B.: to_string_mach double-quotes the string, don't want that *) incr_failed_response Rpcs.Answer_sync_ledger_query.failed_response_counter ; let err_msg = Error.to_string_hum err in if String.is_prefix err_msg ~prefix:refused_answer_query_string then Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions. ( Requested_unknown_item , Some ( "Sync ledger query with hash: $hash, query: $query, \ with error: $error" , [ ("hash", Ledger_hash.to_yojson hash) ; ( "query" , Syncable_ledger.Query.to_yojson Mina_ledger.Ledger.Addr.to_yojson query ) ; ("error", Error_json.error_to_yojson err) ] ) )) else return () in return result in let md p = [ ("peer", Peer.to_yojson p) ] in let get_ancestry_rpc conn ~version:_ query = [%log debug] "Sending root proof to $peer" ~metadata:(md conn) ; let action_msg = "Get_ancestry query: $query" in let msg_args = [ ("query", Rpcs.Get_ancestry.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_ancestry action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_ancestry.failed_response_counter | Some { proof = _, ext_trans; _ } -> let%map valid_protocol_versions = validate_protocol_versions ~rpc_name:"Get_ancestry" sender ext_trans in if valid_protocol_versions then result else None in let get_some_initial_peers_rpc (conn : Peer.t) ~version:_ () = [%log trace] "Sending some initial peers to $peer" ~metadata:(md conn) ; let action_msg = "Get_some_initial_peers query: $query" in let msg_args = [ ("query", `Assoc []) ] in let%map result, _sender = run_for_rpc_result conn () ~f:get_some_initial_peers action_msg msg_args in if List.is_empty result then incr_failed_response Rpcs.Get_some_initial_peers.failed_response_counter ; result in let get_best_tip_rpc conn ~version:_ () = [%log debug] "Sending best_tip to $peer" ~metadata:(md conn) ; let action_msg = "Get_best_tip. query: $query" in let msg_args = [ ("query", Rpcs.Get_best_tip.query_to_yojson ()) ] in let%bind result, sender = run_for_rpc_result conn () ~f:get_best_tip action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_best_tip.failed_response_counter | Some { data = data_ext_trans; proof = _, proof_ext_trans } -> let%bind valid_data_protocol_versions = validate_protocol_versions ~rpc_name:"Get_best_tip (data)" sender data_ext_trans in let%map valid_proof_protocol_versions = validate_protocol_versions ~rpc_name:"Get_best_tip (proof)" sender proof_ext_trans in if valid_data_protocol_versions && valid_proof_protocol_versions then result else None in let get_transition_chain_proof_rpc conn ~version:_ query = [%log info] "Sending transition_chain_proof to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_chain_proof query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_chain_proof.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_transition_chain_proof action_msg msg_args in record_unknown_item result sender action_msg msg_args Rpcs.Get_transition_chain_proof.failed_response_counter in let get_transition_knowledge_rpc conn ~version:_ query = [%log info] "Sending transition_knowledge to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_knowledge query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_knowledge.query_to_yojson query) ] in let%map result = run_for_rpc_result conn query ~f:get_transition_knowledge action_msg msg_args >>| fst in if List.is_empty result then incr_failed_response Rpcs.Get_transition_knowledge.failed_response_counter ; result in let get_transition_chain_rpc conn ~version:_ query = [%log info] "Sending transition_chain to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_chain query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_chain.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_transition_chain action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_transition_chain.failed_response_counter | Some ext_trans -> let%map valid_protocol_versions = Deferred.List.map ext_trans ~f: (validate_protocol_versions ~rpc_name:"Get_transition_chain" sender ) in if List.for_all valid_protocol_versions ~f:(Bool.equal true) then result else None in let ban_notify_rpc conn ~version:_ ban_until = (* the port in `conn' is an ephemeral port, not of interest *) [%log warn] "Node banned by peer $peer until $ban_until" ~metadata: [ ("peer", Peer.to_yojson conn) ; ( "ban_until" , `String (Time.to_string_abs ~zone:Time.Zone.utc ban_until) ) ] ; (* no computation to do; we're just getting notification *) Deferred.unit in let rpc_handlers = let open Rpcs in let open Time.Span in let unit _ = 1 in [ Rpc_handler { rpc = Get_some_initial_peers ; f = get_some_initial_peers_rpc ; budget = (1, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_staged_ledger_aux_and_pending_coinbases_at_hash ; f = get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc ; budget = (4, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Answer_sync_ledger_query ; f = answer_sync_ledger_query_rpc ; budget = (Int.pow 2 17, `Per minute) (* Not that confident about this one. *) ; cost = unit } ; Rpc_handler { rpc = Get_best_tip ; f = get_best_tip_rpc ; budget = (3, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_ancestry ; f = get_ancestry_rpc ; budget = (5, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_transition_knowledge ; f = get_transition_knowledge_rpc ; budget = (1, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_transition_chain ; f = get_transition_chain_rpc ; budget = (1, `Per second) (* Not that confident about this one. *) ; cost = (fun x -> Int.max 1 (List.length x)) } ; Rpc_handler { rpc = Get_transition_chain_proof ; f = get_transition_chain_proof_rpc ; budget = (3, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Ban_notify ; f = ban_notify_rpc ; budget = (1, `Per minute) ; cost = unit } ] in let%map gossip_net = O1trace.thread "gossip_net" (fun () -> Gossip_net.Any.create config.creatable_gossip_net rpc_handlers (Gossip_net.Message.Any_sinks ((module Sinks), sinks)) ) in The node status RPC is implemented directly in go , serving a string which is periodically updated . This is so that one can make this RPC on a node even if that node is at its connection limit . is periodically updated. This is so that one can make this RPC on a node even if that node is at its connection limit. *) let fake_time = Time.now () in Clock.every' (Time.Span.of_min 1.) (fun () -> O1trace.thread "update_node_status" (fun () -> match%bind get_node_status { data = (); sender = Local; received_at = fake_time } with | Error _ -> Deferred.unit | Ok data -> Gossip_net.Any.set_node_status gossip_net ( Rpcs.Get_node_status.Node_status.to_yojson data |> Yojson.Safe.to_string ) >>| ignore ) ) ; don't_wait_for (Gossip_net.Any.on_first_connect gossip_net ~f:(fun () -> (* After first_connect this list will only be empty if we filtered out all the peers due to mismatched chain id. *) don't_wait_for (let%map initial_peers = Gossip_net.Any.peers gossip_net in if List.is_empty initial_peers && not config.is_seed then ( [%log fatal] "Failed to connect to any initial peers, possible chain id \ mismatch" ; raise No_initial_peers ) ) ) ) ; (* TODO: Think about buffering: I.e., what do we do when too many messages are coming in, or going out. For example, some things you really want to not drop (like your outgoing block announcment). *) { gossip_net; logger = config.logger; trust_system = config.trust_system } (* lift and expose select gossip net functions *) include struct open Gossip_net.Any let lift f { gossip_net; _ } = f gossip_net let peers = lift peers let bandwidth_info = lift bandwidth_info let get_peer_node_status t peer = let open Deferred.Or_error.Let_syntax in let%bind s = get_peer_node_status t.gossip_net peer in Or_error.try_with (fun () -> match Rpcs.Get_node_status.Node_status.of_yojson (Yojson.Safe.from_string s) with | Ok x -> x | Error e -> failwith e ) |> Deferred.return let add_peer = lift add_peer let initial_peers = lift initial_peers let ban_notification_reader = lift ban_notification_reader let random_peers = lift random_peers let query_peer ?heartbeat_timeout ?timeout { gossip_net; _ } = query_peer ?heartbeat_timeout ?timeout gossip_net let query_peer' ?how ?heartbeat_timeout ?timeout { gossip_net; _ } = query_peer' ?how ?heartbeat_timeout ?timeout gossip_net let restart_helper { gossip_net; _ } = restart_helper gossip_net (* these cannot be directly lifted due to the value restriction *) let on_first_connect t = lift on_first_connect t let on_first_high_connectivity t = lift on_first_high_connectivity t let connection_gating_config t = lift connection_gating t let set_connection_gating_config t config = lift set_connection_gating t config end (* TODO: Have better pushback behavior *) let log_gossip logger ~log_msg msg = [%str_log' trace logger] ~metadata:[ ("message", Gossip_net.Message.msg_to_yojson msg) ] log_msg let broadcast_state t state = let msg = With_hash.data state in log_gossip t.logger (Gossip_net.Message.New_state msg) ~log_msg: (Gossip_new_state { state_hash = State_hash.With_state_hashes.state_hash state } ) ; Mina_metrics.(Gauge.inc_one Network.new_state_broadcasted) ; Gossip_net.Any.broadcast_state t.gossip_net msg let broadcast_transaction_pool_diff t diff = log_gossip t.logger (Gossip_net.Message.Transaction_pool_diff diff) ~log_msg:(Gossip_transaction_pool_diff { txns = diff }) ; Mina_metrics.(Gauge.inc_one Network.transaction_pool_diff_broadcasted) ; Gossip_net.Any.broadcast_transaction_pool_diff t.gossip_net diff let broadcast_snark_pool_diff t diff = Mina_metrics.(Gauge.inc_one Network.snark_pool_diff_broadcasted) ; log_gossip t.logger (Gossip_net.Message.Snark_pool_diff diff) ~log_msg: (Gossip_snark_pool_diff { work = Option.value_exn (Snark_pool.Resource_pool.Diff.to_compact diff) } ) ; Gossip_net.Any.broadcast_snark_pool_diff t.gossip_net diff let find_map xs ~f = let open Async in let ds = List.map xs ~f in let filter ~f = Deferred.bind ~f:(fun x -> if f x then return x else Deferred.never ()) in let none_worked = Deferred.bind (Deferred.all ds) ~f:(fun ds -> (* TODO: Validation applicative here *) if List.for_all ds ~f:Or_error.is_error then return (Or_error.error_string "all none") else Deferred.never () ) in Deferred.any (none_worked :: List.map ~f:(filter ~f:Or_error.is_ok) ds) let make_rpc_request ?heartbeat_timeout ?timeout ~rpc ~label t peer input = let open Deferred.Let_syntax in match%map query_peer ?heartbeat_timeout ?timeout t peer.Peer.peer_id rpc input with | Connected { data = Ok (Some response); _ } -> Ok response | Connected { data = Ok None; _ } -> Or_error.errorf !"Peer %{sexp:Network_peer.Peer.Id.t} doesn't have the requested %s" peer.peer_id label | Connected { data = Error e; _ } -> Error e | Failed_to_connect e -> Error (Error.tag e ~tag:"failed-to-connect") let get_transition_chain_proof ?heartbeat_timeout ?timeout t = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_transition_chain_proof ~label:"transition chain proof" t let get_transition_chain ?heartbeat_timeout ?timeout t = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_transition_chain ~label:"chain of transitions" t let get_best_tip ?heartbeat_timeout ?timeout t peer = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_best_tip ~label:"best tip" t peer () let ban_notify t peer banned_until = query_peer t peer.Peer.peer_id Rpcs.Ban_notify banned_until >>| Fn.const (Ok ()) let try_non_preferred_peers (type b) t input peers ~rpc : b Envelope.Incoming.t Deferred.Or_error.t = let max_current_peers = 8 in let rec loop peers num_peers = if num_peers > max_current_peers then return (Or_error.error_string "None of randomly-chosen peers can handle the request" ) else let current_peers, remaining_peers = List.split_n peers num_peers in find_map current_peers ~f:(fun peer -> let%bind response_or_error = query_peer t peer.Peer.peer_id rpc input in match response_or_error with | Connected ({ data = Ok (Some data); _ } as envelope) -> let%bind () = Trust_system.( record t.trust_system t.logger peer Actions. ( Fulfilled_request , Some ("Nonpreferred peer returned valid response", []) )) in return (Ok (Envelope.Incoming.map envelope ~f:(Fn.const data))) | Connected { data = Ok None; _ } -> loop remaining_peers (2 * num_peers) | _ -> loop remaining_peers (2 * num_peers) ) in loop peers 1 let rpc_peer_then_random (type b) t peer_id input ~rpc : b Envelope.Incoming.t Deferred.Or_error.t = let retry () = let%bind peers = random_peers t 8 in try_non_preferred_peers t input peers ~rpc in match%bind query_peer t peer_id rpc input with | Connected { data = Ok (Some response); sender; _ } -> let%bind () = match sender with | Local -> return () | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( Fulfilled_request , Some ("Preferred peer returned valid response", []) )) in return (Ok (Envelope.Incoming.wrap ~data:response ~sender)) | Connected { data = Ok None; sender; _ } -> let%bind () = match sender with | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( No_reply_from_preferred_peer , Some ("When querying preferred peer, got no response", []) )) | Local -> return () in retry () | Connected { data = Error e; sender; _ } -> FIXME # 4094 : determine if more specific actions apply here let%bind () = match sender with | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( Outgoing_connection_error , Some ( "Error while doing RPC" , [ ("error", Error_json.error_to_yojson e) ] ) )) | Local -> return () in retry () | Failed_to_connect _ -> (* Since we couldn't connect, we have no IP to ban. *) retry () let get_staged_ledger_aux_and_pending_coinbases_at_hash t inet_addr input = rpc_peer_then_random t inet_addr input ~rpc:Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash >>|? Envelope.Incoming.data let get_ancestry t inet_addr input = rpc_peer_then_random t inet_addr input ~rpc:Rpcs.Get_ancestry module Sl_downloader = struct module Key = struct module T = struct type t = Ledger_hash.t * Sync_ledger.Query.t [@@deriving hash, compare, sexp, to_yojson] end include T include Comparable.Make (T) include Hashable.Make (T) end include Downloader.Make (Key) (struct type t = unit [@@deriving to_yojson] let download : t = () let worth_retrying () = true end) (struct type t = (Mina_base.Ledger_hash.t * Sync_ledger.Query.t) * Sync_ledger.Answer.t [@@deriving to_yojson] let key = fst end) (Ledger_hash) end let glue_sync_ledger : t -> preferred:Peer.t list -> (Mina_base.Ledger_hash.t * Sync_ledger.Query.t) Pipe_lib.Linear_pipe.Reader.t -> ( Mina_base.Ledger_hash.t * Sync_ledger.Query.t * Sync_ledger.Answer.t Network_peer.Envelope.Incoming.t ) Pipe_lib.Linear_pipe.Writer.t -> unit = fun t ~preferred query_reader response_writer -> let downloader = let heartbeat_timeout = Time_ns.Span.of_sec 20. in let global_stop = Pipe_lib.Linear_pipe.closed query_reader in let knowledge h peer = match%map query_peer ~heartbeat_timeout ~timeout:(Time.Span.of_sec 10.) t peer.Peer.peer_id Rpcs.Answer_sync_ledger_query (h, Num_accounts) with | Connected { data = Ok _; _ } -> `Call (fun (h', _) -> Ledger_hash.equal h' h) | Failed_to_connect _ | Connected { data = Error _; _ } -> `Some [] in let%bind _ = Linear_pipe.values_available query_reader in let root_hash_r, root_hash_w = Broadcast_pipe.create (Option.value_exn (Linear_pipe.peek query_reader) |> fst) in Sl_downloader.create ~preferred ~max_batch_size:100 ~peers:(fun () -> peers t) ~knowledge_context:root_hash_r ~knowledge ~stop:global_stop ~trust_system:t.trust_system ~get:(fun (peer : Peer.t) qs -> List.iter qs ~f:(fun (h, _) -> if not (Ledger_hash.equal h (Broadcast_pipe.Reader.peek root_hash_r)) then don't_wait_for (Broadcast_pipe.Writer.write root_hash_w h) ) ; let%map rs = query_peer' ~how:`Parallel ~heartbeat_timeout ~timeout:(Time.Span.of_sec (Float.of_int (List.length qs) *. 2.)) t peer.peer_id Rpcs.Answer_sync_ledger_query qs in match rs with | Failed_to_connect e -> Error e | Connected res -> ( match res.data with | Error e -> Error e | Ok rs -> ( match List.zip qs rs with | Unequal_lengths -> Or_error.error_string "mismatched lengths" | Ok ps -> Ok (List.filter_map ps ~f:(fun (q, r) -> match r with Ok r -> Some (q, r) | Error _ -> None ) ) ) ) ) in don't_wait_for (let%bind downloader = downloader in Linear_pipe.iter_unordered ~max_concurrency:400 query_reader ~f:(fun q -> match%bind Sl_downloader.Job.result (Sl_downloader.download downloader ~key:q ~attempts:Peer.Map.empty) with | Error _ -> Deferred.unit | Ok (a, _) -> Linear_pipe.write_if_open response_writer (fst q, snd q, { a with data = snd a.data }) ) )
null
https://raw.githubusercontent.com/MinaProtocol/mina/a1185fc7b207cfec2a652ef7f3fdc3d9b2e202ea/src/lib/mina_networking/mina_networking.ml
ocaml
banned until this time N.B.: to_string_mach double-quotes the string, don't want that the port in `conn' is an ephemeral port, not of interest no computation to do; we're just getting notification Not that confident about this one. Not that confident about this one. After first_connect this list will only be empty if we filtered out all the peers due to mismatched chain id. TODO: Think about buffering: I.e., what do we do when too many messages are coming in, or going out. For example, some things you really want to not drop (like your outgoing block announcment). lift and expose select gossip net functions these cannot be directly lifted due to the value restriction TODO: Have better pushback behavior TODO: Validation applicative here Since we couldn't connect, we have no IP to ban.
open Core open Async open Mina_base module Sync_ledger = Mina_ledger.Sync_ledger open Mina_block open Network_peer open Network_pool open Pipe_lib let refused_answer_query_string = "Refused to answer_query" exception No_initial_peers type Structured_log_events.t += | Gossip_new_state of { state_hash : State_hash.t } [@@deriving register_event { msg = "Broadcasting new state over gossip net" }] type Structured_log_events.t += | Gossip_transaction_pool_diff of { txns : Transaction_pool.Resource_pool.Diff.t } [@@deriving register_event { msg = "Broadcasting transaction pool diff over gossip net" }] type Structured_log_events.t += | Gossip_snark_pool_diff of { work : Snark_pool.Resource_pool.Diff.compact } [@@deriving register_event { msg = "Broadcasting snark pool diff over gossip net" }] INSTRUCTIONS FOR ADDING A NEW RPC : * - define a new module under the Rpcs module * - add an entry to the Rpcs.rpc GADT definition for the new module ( type ( ' query , ' response ) rpc , below ) * - add the new constructor for Rpcs.rpc to Rpcs.all_of_type_erased_rpc * - add a pattern matching case to Rpcs.implementation_of_rpc mapping the * new constructor to the new module for your RPC * - add a match case to ` match_handler ` , below * - define a new module under the Rpcs module * - add an entry to the Rpcs.rpc GADT definition for the new module (type ('query, 'response) rpc, below) * - add the new constructor for Rpcs.rpc to Rpcs.all_of_type_erased_rpc * - add a pattern matching case to Rpcs.implementation_of_rpc mapping the * new constructor to the new module for your RPC * - add a match case to `match_handler`, below *) module Rpcs = struct for versioning of the types here , see RFC 0012 , and -core/latest/doc/async_rpc_kernel/Async_rpc_kernel/Versioned_rpc/ The " master " types are the ones used internally in the code base . Each version has coercions between their query and response types and the master types . RFC 0012, and -core/latest/doc/async_rpc_kernel/Async_rpc_kernel/Versioned_rpc/ The "master" types are the ones used internally in the code base. Each version has coercions between their query and response types and the master types. *) [%%versioned_rpc module Get_some_initial_peers = struct module Master = struct let name = "get_some_initial_peers" module T = struct type query = unit [@@deriving sexp, yojson] type response = Network_peer.Peer.t list [@@deriving sexp, yojson] end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_some_initial_peers_rpcs_sent let received_counter = Mina_metrics.Network.get_some_initial_peers_rpcs_received let failed_request_counter = Mina_metrics.Network.get_some_initial_peers_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_some_initial_peers_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = unit type response = Network_peer.Peer.Stable.V1.t list let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_staged_ledger_aux_and_pending_coinbases_at_hash = struct module Master = struct let name = "get_staged_ledger_aux_and_pending_coinbases_at_hash" module T = struct type query = State_hash.t type response = ( Staged_ledger.Scan_state.t * Ledger_hash.t * Pending_coinbase.t * Mina_state.Protocol_state.value list ) option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpcs_sent let received_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpcs_received let failed_request_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc_requests_failed let failed_response_counter = Mina_metrics.Network .get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = State_hash.Stable.V1.t type response = ( Staged_ledger.Scan_state.Stable.V2.t * Ledger_hash.Stable.V1.t * Pending_coinbase.Stable.V2.t * Mina_state.Protocol_state.Value.Stable.V2.t list ) option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Answer_sync_ledger_query = struct module Master = struct let name = "answer_sync_ledger_query" module T = struct type query = Ledger_hash.t * Sync_ledger.Query.t type response = Sync_ledger.Answer.t Core.Or_error.t end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.answer_sync_ledger_query_rpcs_sent let received_counter = Mina_metrics.Network.answer_sync_ledger_query_rpcs_received let failed_request_counter = Mina_metrics.Network.answer_sync_ledger_query_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.answer_sync_ledger_query_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = Ledger_hash.Stable.V1.t * Sync_ledger.Query.Stable.V1.t [@@deriving sexp] type response = Sync_ledger.Answer.Stable.V2.t Core.Or_error.Stable.V1.t [@@deriving sexp] let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_chain = struct module Master = struct let name = "get_transition_chain" module T = struct type query = State_hash.t list [@@deriving sexp, to_yojson] type response = Mina_block.t list option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_chain_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_chain_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_chain_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_chain_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = State_hash.Stable.V1.t list [@@deriving sexp] type response = Mina_block.Stable.V2.t list option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_chain_proof = struct module Master = struct let name = "get_transition_chain_proof" module T = struct type query = State_hash.t [@@deriving sexp, to_yojson] type response = (State_hash.t * State_body_hash.t list) option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_chain_proof_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_chain_proof_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_chain_proof_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_chain_proof_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = State_hash.Stable.V1.t [@@deriving sexp] type response = (State_hash.Stable.V1.t * State_body_hash.Stable.V1.t list) option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_transition_knowledge = struct module Master = struct let name = "Get_transition_knowledge" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = State_hash.t list end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_transition_knowledge_rpcs_sent let received_counter = Mina_metrics.Network.get_transition_knowledge_rpcs_received let failed_request_counter = Mina_metrics.Network.get_transition_knowledge_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_transition_knowledge_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = unit [@@deriving sexp] type response = State_hash.Stable.V1.t list let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_ancestry = struct module Master = struct let name = "get_ancestry" module T = struct * NB : The state hash sent in this query should not be trusted , as it can be forged . This is ok for how this RPC is implented , as we only use the state hash for tie breaking when checking whether or not the proof is worth serving . type query = (Consensus.Data.Consensus_state.Value.t, State_hash.t) With_hash.t [@@deriving sexp, to_yojson] type response = ( Mina_block.t , State_body_hash.t list * Mina_block.t ) Proof_carrying_data.t option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_ancestry_rpcs_sent let received_counter = Mina_metrics.Network.get_ancestry_rpcs_received let failed_request_counter = Mina_metrics.Network.get_ancestry_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_ancestry_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = ( Consensus.Data.Consensus_state.Value.Stable.V1.t , State_hash.Stable.V1.t ) With_hash.Stable.V1.t [@@deriving sexp] type response = ( Mina_block.Stable.V2.t , State_body_hash.Stable.V1.t list * Mina_block.Stable.V2.t ) Proof_carrying_data.Stable.V1.t option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Ban_notify = struct module Master = struct let name = "ban_notify" module T = struct type query = Core.Time.t [@@deriving sexp] type response = unit end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.ban_notify_rpcs_sent let received_counter = Mina_metrics.Network.ban_notify_rpcs_received let failed_request_counter = Mina_metrics.Network.ban_notify_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.ban_notify_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V1 = struct module T = struct type query = Core.Time.Stable.V1.t [@@deriving sexp] type response = unit let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_best_tip = struct module Master = struct let name = "get_best_tip" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = ( Mina_block.t , State_body_hash.t list * Mina_block.t ) Proof_carrying_data.t option end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_best_tip_rpcs_sent let received_counter = Mina_metrics.Network.get_best_tip_rpcs_received let failed_request_counter = Mina_metrics.Network.get_best_tip_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_best_tip_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = unit [@@deriving sexp] type response = ( Mina_block.Stable.V2.t , State_body_hash.Stable.V1.t list * Mina_block.Stable.V2.t ) Proof_carrying_data.Stable.V1.t option let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = ident let caller_model_of_response = ident end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] [%%versioned_rpc module Get_node_status = struct module Node_status = struct [%%versioned module Stable = struct module V2 = struct type t = { node_ip_addr : Core.Unix.Inet_addr.Stable.V1.t [@to_yojson fun ip_addr -> `String (Unix.Inet_addr.to_string ip_addr)] [@of_yojson function | `String s -> Ok (Unix.Inet_addr.of_string s) | _ -> Error "expected string"] ; node_peer_id : Network_peer.Peer.Id.Stable.V1.t [@to_yojson fun peer_id -> `String peer_id] [@of_yojson function `String s -> Ok s | _ -> Error "expected string"] ; sync_status : Sync_status.Stable.V1.t ; peers : Network_peer.Peer.Stable.V1.t list ; block_producers : Signature_lib.Public_key.Compressed.Stable.V1.t list ; protocol_state_hash : State_hash.Stable.V1.t ; ban_statuses : ( Network_peer.Peer.Stable.V1.t * Trust_system.Peer_status.Stable.V1.t ) list ; k_block_hashes_and_timestamps : (State_hash.Stable.V1.t * string) list ; git_commit : string ; uptime_minutes : int ; block_height_opt : int option [@default None] } [@@deriving to_yojson, of_yojson] let to_latest = Fn.id end module V1 = struct type t = { node_ip_addr : Core.Unix.Inet_addr.Stable.V1.t [@to_yojson fun ip_addr -> `String (Unix.Inet_addr.to_string ip_addr)] [@of_yojson function | `String s -> Ok (Unix.Inet_addr.of_string s) | _ -> Error "expected string"] ; node_peer_id : Network_peer.Peer.Id.Stable.V1.t [@to_yojson fun peer_id -> `String peer_id] [@of_yojson function `String s -> Ok s | _ -> Error "expected string"] ; sync_status : Sync_status.Stable.V1.t ; peers : Network_peer.Peer.Stable.V1.t list ; block_producers : Signature_lib.Public_key.Compressed.Stable.V1.t list ; protocol_state_hash : State_hash.Stable.V1.t ; ban_statuses : ( Network_peer.Peer.Stable.V1.t * Trust_system.Peer_status.Stable.V1.t ) list ; k_block_hashes_and_timestamps : (State_hash.Stable.V1.t * string) list ; git_commit : string ; uptime_minutes : int } [@@deriving to_yojson, of_yojson] let to_latest status : Latest.t = { node_ip_addr = status.node_ip_addr ; node_peer_id = status.node_peer_id ; sync_status = status.sync_status ; peers = status.peers ; block_producers = status.block_producers ; protocol_state_hash = status.protocol_state_hash ; ban_statuses = status.ban_statuses ; k_block_hashes_and_timestamps = status.k_block_hashes_and_timestamps ; git_commit = status.git_commit ; uptime_minutes = status.uptime_minutes ; block_height_opt = None } end end] end module Master = struct let name = "get_node_status" module T = struct type query = unit [@@deriving sexp, to_yojson] type response = Node_status.t Or_error.t end module Caller = T module Callee = T end include Master.T let sent_counter = Mina_metrics.Network.get_node_status_rpcs_sent let received_counter = Mina_metrics.Network.get_node_status_rpcs_received let failed_request_counter = Mina_metrics.Network.get_node_status_rpc_requests_failed let failed_response_counter = Mina_metrics.Network.get_node_status_rpc_responses_failed module M = Versioned_rpc.Both_convert.Plain.Make (Master) include M let response_to_yojson response = match response with | Ok status -> Node_status.Stable.Latest.to_yojson status | Error err -> `Assoc [ ("error", Error_json.error_to_yojson err) ] include Perf_histograms.Rpc.Plain.Extend (struct include M include Master end) module V2 = struct module T = struct type query = unit [@@deriving sexp] type response = Node_status.Stable.V2.t Core_kernel.Or_error.Stable.V1.t let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = Fn.id let caller_model_of_response = Fn.id end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end module V1 = struct module T = struct type query = unit [@@deriving sexp] type response = Node_status.Stable.V1.t Core_kernel.Or_error.Stable.V1.t let query_of_caller_model = Fn.id let callee_model_of_query = Fn.id let response_of_callee_model = function | Error err -> Error err | Ok (status : Node_status.Stable.Latest.t) -> Ok { Node_status.Stable.V1.node_ip_addr = status.node_ip_addr ; node_peer_id = status.node_peer_id ; sync_status = status.sync_status ; peers = status.peers ; block_producers = status.block_producers ; protocol_state_hash = status.protocol_state_hash ; ban_statuses = status.ban_statuses ; k_block_hashes_and_timestamps = status.k_block_hashes_and_timestamps ; git_commit = status.git_commit ; uptime_minutes = status.uptime_minutes } let caller_model_of_response = function | Error err -> Error err | Ok (status : Node_status.Stable.V1.t) -> Ok (Node_status.Stable.V1.to_latest status) end module T' = Perf_histograms.Rpc.Plain.Decorate_bin_io (struct include M include Master end) (T) include T' include Register (T') end end] type ('query, 'response) rpc = | Get_some_initial_peers : (Get_some_initial_peers.query, Get_some_initial_peers.response) rpc | Get_staged_ledger_aux_and_pending_coinbases_at_hash : ( Get_staged_ledger_aux_and_pending_coinbases_at_hash.query , Get_staged_ledger_aux_and_pending_coinbases_at_hash.response ) rpc | Answer_sync_ledger_query : ( Answer_sync_ledger_query.query , Answer_sync_ledger_query.response ) rpc | Get_transition_chain : (Get_transition_chain.query, Get_transition_chain.response) rpc | Get_transition_knowledge : ( Get_transition_knowledge.query , Get_transition_knowledge.response ) rpc | Get_transition_chain_proof : ( Get_transition_chain_proof.query , Get_transition_chain_proof.response ) rpc | Get_node_status : (Get_node_status.query, Get_node_status.response) rpc | Get_ancestry : (Get_ancestry.query, Get_ancestry.response) rpc | Ban_notify : (Ban_notify.query, Ban_notify.response) rpc | Get_best_tip : (Get_best_tip.query, Get_best_tip.response) rpc type rpc_handler = | Rpc_handler : { rpc : ('q, 'r) rpc ; f : ('q, 'r) Rpc_intf.rpc_fn ; cost : 'q -> int ; budget : int * [ `Per of Time.Span.t ] } -> rpc_handler let implementation_of_rpc : type q r. (q, r) rpc -> (q, r) Rpc_intf.rpc_implementation = function | Get_some_initial_peers -> (module Get_some_initial_peers) | Get_staged_ledger_aux_and_pending_coinbases_at_hash -> (module Get_staged_ledger_aux_and_pending_coinbases_at_hash) | Answer_sync_ledger_query -> (module Answer_sync_ledger_query) | Get_transition_chain -> (module Get_transition_chain) | Get_transition_knowledge -> (module Get_transition_knowledge) | Get_transition_chain_proof -> (module Get_transition_chain_proof) | Get_node_status -> (module Get_node_status) | Get_ancestry -> (module Get_ancestry) | Ban_notify -> (module Ban_notify) | Get_best_tip -> (module Get_best_tip) let match_handler : type q r. rpc_handler -> (q, r) rpc -> do_:((q, r) Rpc_intf.rpc_fn -> 'a) -> 'a option = fun (Rpc_handler { rpc = impl_rpc; f; cost = _; budget = _ }) rpc ~do_ -> match (rpc, impl_rpc) with | Get_some_initial_peers, Get_some_initial_peers -> Some (do_ f) | Get_some_initial_peers, _ -> None | ( Get_staged_ledger_aux_and_pending_coinbases_at_hash , Get_staged_ledger_aux_and_pending_coinbases_at_hash ) -> Some (do_ f) | Get_staged_ledger_aux_and_pending_coinbases_at_hash, _ -> None | Answer_sync_ledger_query, Answer_sync_ledger_query -> Some (do_ f) | Answer_sync_ledger_query, _ -> None | Get_transition_chain, Get_transition_chain -> Some (do_ f) | Get_transition_chain, _ -> None | Get_transition_knowledge, Get_transition_knowledge -> Some (do_ f) | Get_transition_knowledge, _ -> None | Get_transition_chain_proof, Get_transition_chain_proof -> Some (do_ f) | Get_transition_chain_proof, _ -> None | Get_node_status, Get_node_status -> Some (do_ f) | Get_node_status, _ -> None | Get_ancestry, Get_ancestry -> Some (do_ f) | Get_ancestry, _ -> None | Ban_notify, Ban_notify -> Some (do_ f) | Ban_notify, _ -> None | Get_best_tip, Get_best_tip -> Some (do_ f) | Get_best_tip, _ -> None end module Sinks = Sinks module Gossip_net = Gossip_net.Make (Rpcs) module Config = struct type log_gossip_heard = { snark_pool_diff : bool; transaction_pool_diff : bool; new_state : bool } [@@deriving make] type t = { logger : Logger.t ; trust_system : Trust_system.t ; time_controller : Block_time.Controller.t ; consensus_constants : Consensus.Constants.t ; consensus_local_state : Consensus.Data.Local_state.t ; genesis_ledger_hash : Ledger_hash.t ; constraint_constants : Genesis_constants.Constraint_constants.t ; precomputed_values : Precomputed_values.t ; creatable_gossip_net : Gossip_net.Any.creatable ; is_seed : bool ; log_gossip_heard : log_gossip_heard } [@@deriving make] end type t = { logger : Logger.t ; trust_system : Trust_system.t ; gossip_net : Gossip_net.Any.t } [@@deriving fields] let wrap_rpc_data_in_envelope conn data = Envelope.Incoming.wrap_peer ~data ~sender:conn type protocol_version_status = { valid_current : bool; valid_next : bool; matches_daemon : bool } let protocol_version_status t = let header = Mina_block.header t in let valid_current = Protocol_version.is_valid (Header.current_protocol_version header) in let valid_next = Option.for_all (Header.proposed_protocol_version_opt header) ~f:Protocol_version.is_valid in let matches_daemon = Protocol_version.compatible_with_daemon (Header.current_protocol_version header) in { valid_current; valid_next; matches_daemon } let create (config : Config.t) ~sinks ~(get_some_initial_peers : Rpcs.Get_some_initial_peers.query Envelope.Incoming.t -> Rpcs.Get_some_initial_peers.response Deferred.t ) ~(get_staged_ledger_aux_and_pending_coinbases_at_hash : Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash.query Envelope.Incoming.t -> Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash.response Deferred.t ) ~(answer_sync_ledger_query : Rpcs.Answer_sync_ledger_query.query Envelope.Incoming.t -> Rpcs.Answer_sync_ledger_query.response Deferred.t ) ~(get_ancestry : Rpcs.Get_ancestry.query Envelope.Incoming.t -> Rpcs.Get_ancestry.response Deferred.t ) ~(get_best_tip : Rpcs.Get_best_tip.query Envelope.Incoming.t -> Rpcs.Get_best_tip.response Deferred.t ) ~(get_node_status : Rpcs.Get_node_status.query Envelope.Incoming.t -> Rpcs.Get_node_status.response Deferred.t ) ~(get_transition_chain_proof : Rpcs.Get_transition_chain_proof.query Envelope.Incoming.t -> Rpcs.Get_transition_chain_proof.response Deferred.t ) ~(get_transition_chain : Rpcs.Get_transition_chain.query Envelope.Incoming.t -> Rpcs.Get_transition_chain.response Deferred.t ) ~(get_transition_knowledge : Rpcs.Get_transition_knowledge.query Envelope.Incoming.t -> Rpcs.Get_transition_knowledge.response Deferred.t ) = let module Context = struct let logger = config.logger end in let open Context in let run_for_rpc_result conn data ~f action_msg msg_args = let data_in_envelope = wrap_rpc_data_in_envelope conn data in let sender = Envelope.Incoming.sender data_in_envelope in let%bind () = Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions.(Made_request, Some (action_msg, msg_args))) in let%bind result = f data_in_envelope in return (result, sender) in let incr_failed_response = Mina_metrics.Counter.inc_one in let record_unknown_item result sender action_msg msg_args failed_response_counter = let%map () = if Option.is_none result then ( incr_failed_response failed_response_counter ; Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions.(Requested_unknown_item, Some (action_msg, msg_args))) ) else return () in result in let validate_protocol_versions ~rpc_name sender external_transition = let open Trust_system.Actions in let { valid_current; valid_next; matches_daemon } = protocol_version_status external_transition in let%bind () = if valid_current then return () else let actions = ( Sent_invalid_protocol_version , Some ( "$rpc_name: external transition with invalid current protocol \ version" , [ ("rpc_name", `String rpc_name) ; ( "current_protocol_version" , `String (Protocol_version.to_string (Header.current_protocol_version (Mina_block.header external_transition) ) ) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in let%bind () = if valid_next then return () else let actions = ( Sent_invalid_protocol_version , Some ( "$rpc_name: external transition with invalid proposed protocol \ version" , [ ("rpc_name", `String rpc_name) ; ( "proposed_protocol_version" , `String (Protocol_version.to_string (Option.value_exn (Header.proposed_protocol_version_opt (Mina_block.header external_transition) ) ) ) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in let%map () = if matches_daemon then return () else let actions = ( Sent_mismatched_protocol_version , Some ( "$rpc_name: current protocol version in external transition \ does not match daemon current protocol version" , [ ("rpc_name", `String rpc_name) ; ( "current_protocol_version" , `String (Protocol_version.to_string (Header.current_protocol_version (Mina_block.header external_transition) ) ) ) ; ( "daemon_current_protocol_version" , `String Protocol_version.(to_string @@ get_current ()) ) ] ) ) in Trust_system.record_envelope_sender config.trust_system config.logger sender actions in valid_current && valid_next && matches_daemon in each of the passed - in procedures expects an enveloped input , so we wrap the data received via RPC we wrap the data received via RPC *) let get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc conn ~version:_ hash = let action_msg = "Staged ledger and pending coinbases at hash: $hash" in let msg_args = [ ("hash", State_hash.to_yojson hash) ] in let%bind result, sender = run_for_rpc_result conn hash ~f:get_staged_ledger_aux_and_pending_coinbases_at_hash action_msg msg_args in record_unknown_item result sender action_msg msg_args Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash .failed_response_counter in let answer_sync_ledger_query_rpc conn ~version:_ ((hash, query) as sync_query) = let%bind result, sender = run_for_rpc_result conn sync_query ~f:answer_sync_ledger_query "Answer_sync_ledger_query: $query" [ ("query", Sync_ledger.Query.to_yojson query) ] in let%bind () = match result with | Ok _ -> return () | Error err -> incr_failed_response Rpcs.Answer_sync_ledger_query.failed_response_counter ; let err_msg = Error.to_string_hum err in if String.is_prefix err_msg ~prefix:refused_answer_query_string then Trust_system.( record_envelope_sender config.trust_system config.logger sender Actions. ( Requested_unknown_item , Some ( "Sync ledger query with hash: $hash, query: $query, \ with error: $error" , [ ("hash", Ledger_hash.to_yojson hash) ; ( "query" , Syncable_ledger.Query.to_yojson Mina_ledger.Ledger.Addr.to_yojson query ) ; ("error", Error_json.error_to_yojson err) ] ) )) else return () in return result in let md p = [ ("peer", Peer.to_yojson p) ] in let get_ancestry_rpc conn ~version:_ query = [%log debug] "Sending root proof to $peer" ~metadata:(md conn) ; let action_msg = "Get_ancestry query: $query" in let msg_args = [ ("query", Rpcs.Get_ancestry.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_ancestry action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_ancestry.failed_response_counter | Some { proof = _, ext_trans; _ } -> let%map valid_protocol_versions = validate_protocol_versions ~rpc_name:"Get_ancestry" sender ext_trans in if valid_protocol_versions then result else None in let get_some_initial_peers_rpc (conn : Peer.t) ~version:_ () = [%log trace] "Sending some initial peers to $peer" ~metadata:(md conn) ; let action_msg = "Get_some_initial_peers query: $query" in let msg_args = [ ("query", `Assoc []) ] in let%map result, _sender = run_for_rpc_result conn () ~f:get_some_initial_peers action_msg msg_args in if List.is_empty result then incr_failed_response Rpcs.Get_some_initial_peers.failed_response_counter ; result in let get_best_tip_rpc conn ~version:_ () = [%log debug] "Sending best_tip to $peer" ~metadata:(md conn) ; let action_msg = "Get_best_tip. query: $query" in let msg_args = [ ("query", Rpcs.Get_best_tip.query_to_yojson ()) ] in let%bind result, sender = run_for_rpc_result conn () ~f:get_best_tip action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_best_tip.failed_response_counter | Some { data = data_ext_trans; proof = _, proof_ext_trans } -> let%bind valid_data_protocol_versions = validate_protocol_versions ~rpc_name:"Get_best_tip (data)" sender data_ext_trans in let%map valid_proof_protocol_versions = validate_protocol_versions ~rpc_name:"Get_best_tip (proof)" sender proof_ext_trans in if valid_data_protocol_versions && valid_proof_protocol_versions then result else None in let get_transition_chain_proof_rpc conn ~version:_ query = [%log info] "Sending transition_chain_proof to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_chain_proof query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_chain_proof.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_transition_chain_proof action_msg msg_args in record_unknown_item result sender action_msg msg_args Rpcs.Get_transition_chain_proof.failed_response_counter in let get_transition_knowledge_rpc conn ~version:_ query = [%log info] "Sending transition_knowledge to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_knowledge query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_knowledge.query_to_yojson query) ] in let%map result = run_for_rpc_result conn query ~f:get_transition_knowledge action_msg msg_args >>| fst in if List.is_empty result then incr_failed_response Rpcs.Get_transition_knowledge.failed_response_counter ; result in let get_transition_chain_rpc conn ~version:_ query = [%log info] "Sending transition_chain to $peer" ~metadata:(md conn) ; let action_msg = "Get_transition_chain query: $query" in let msg_args = [ ("query", Rpcs.Get_transition_chain.query_to_yojson query) ] in let%bind result, sender = run_for_rpc_result conn query ~f:get_transition_chain action_msg msg_args in match result with | None -> record_unknown_item result sender action_msg msg_args Rpcs.Get_transition_chain.failed_response_counter | Some ext_trans -> let%map valid_protocol_versions = Deferred.List.map ext_trans ~f: (validate_protocol_versions ~rpc_name:"Get_transition_chain" sender ) in if List.for_all valid_protocol_versions ~f:(Bool.equal true) then result else None in let ban_notify_rpc conn ~version:_ ban_until = [%log warn] "Node banned by peer $peer until $ban_until" ~metadata: [ ("peer", Peer.to_yojson conn) ; ( "ban_until" , `String (Time.to_string_abs ~zone:Time.Zone.utc ban_until) ) ] ; Deferred.unit in let rpc_handlers = let open Rpcs in let open Time.Span in let unit _ = 1 in [ Rpc_handler { rpc = Get_some_initial_peers ; f = get_some_initial_peers_rpc ; budget = (1, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_staged_ledger_aux_and_pending_coinbases_at_hash ; f = get_staged_ledger_aux_and_pending_coinbases_at_hash_rpc ; budget = (4, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Answer_sync_ledger_query ; f = answer_sync_ledger_query_rpc ; budget = ; cost = unit } ; Rpc_handler { rpc = Get_best_tip ; f = get_best_tip_rpc ; budget = (3, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_ancestry ; f = get_ancestry_rpc ; budget = (5, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_transition_knowledge ; f = get_transition_knowledge_rpc ; budget = (1, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Get_transition_chain ; f = get_transition_chain_rpc ; cost = (fun x -> Int.max 1 (List.length x)) } ; Rpc_handler { rpc = Get_transition_chain_proof ; f = get_transition_chain_proof_rpc ; budget = (3, `Per minute) ; cost = unit } ; Rpc_handler { rpc = Ban_notify ; f = ban_notify_rpc ; budget = (1, `Per minute) ; cost = unit } ] in let%map gossip_net = O1trace.thread "gossip_net" (fun () -> Gossip_net.Any.create config.creatable_gossip_net rpc_handlers (Gossip_net.Message.Any_sinks ((module Sinks), sinks)) ) in The node status RPC is implemented directly in go , serving a string which is periodically updated . This is so that one can make this RPC on a node even if that node is at its connection limit . is periodically updated. This is so that one can make this RPC on a node even if that node is at its connection limit. *) let fake_time = Time.now () in Clock.every' (Time.Span.of_min 1.) (fun () -> O1trace.thread "update_node_status" (fun () -> match%bind get_node_status { data = (); sender = Local; received_at = fake_time } with | Error _ -> Deferred.unit | Ok data -> Gossip_net.Any.set_node_status gossip_net ( Rpcs.Get_node_status.Node_status.to_yojson data |> Yojson.Safe.to_string ) >>| ignore ) ) ; don't_wait_for (Gossip_net.Any.on_first_connect gossip_net ~f:(fun () -> don't_wait_for (let%map initial_peers = Gossip_net.Any.peers gossip_net in if List.is_empty initial_peers && not config.is_seed then ( [%log fatal] "Failed to connect to any initial peers, possible chain id \ mismatch" ; raise No_initial_peers ) ) ) ) ; { gossip_net; logger = config.logger; trust_system = config.trust_system } include struct open Gossip_net.Any let lift f { gossip_net; _ } = f gossip_net let peers = lift peers let bandwidth_info = lift bandwidth_info let get_peer_node_status t peer = let open Deferred.Or_error.Let_syntax in let%bind s = get_peer_node_status t.gossip_net peer in Or_error.try_with (fun () -> match Rpcs.Get_node_status.Node_status.of_yojson (Yojson.Safe.from_string s) with | Ok x -> x | Error e -> failwith e ) |> Deferred.return let add_peer = lift add_peer let initial_peers = lift initial_peers let ban_notification_reader = lift ban_notification_reader let random_peers = lift random_peers let query_peer ?heartbeat_timeout ?timeout { gossip_net; _ } = query_peer ?heartbeat_timeout ?timeout gossip_net let query_peer' ?how ?heartbeat_timeout ?timeout { gossip_net; _ } = query_peer' ?how ?heartbeat_timeout ?timeout gossip_net let restart_helper { gossip_net; _ } = restart_helper gossip_net let on_first_connect t = lift on_first_connect t let on_first_high_connectivity t = lift on_first_high_connectivity t let connection_gating_config t = lift connection_gating t let set_connection_gating_config t config = lift set_connection_gating t config end let log_gossip logger ~log_msg msg = [%str_log' trace logger] ~metadata:[ ("message", Gossip_net.Message.msg_to_yojson msg) ] log_msg let broadcast_state t state = let msg = With_hash.data state in log_gossip t.logger (Gossip_net.Message.New_state msg) ~log_msg: (Gossip_new_state { state_hash = State_hash.With_state_hashes.state_hash state } ) ; Mina_metrics.(Gauge.inc_one Network.new_state_broadcasted) ; Gossip_net.Any.broadcast_state t.gossip_net msg let broadcast_transaction_pool_diff t diff = log_gossip t.logger (Gossip_net.Message.Transaction_pool_diff diff) ~log_msg:(Gossip_transaction_pool_diff { txns = diff }) ; Mina_metrics.(Gauge.inc_one Network.transaction_pool_diff_broadcasted) ; Gossip_net.Any.broadcast_transaction_pool_diff t.gossip_net diff let broadcast_snark_pool_diff t diff = Mina_metrics.(Gauge.inc_one Network.snark_pool_diff_broadcasted) ; log_gossip t.logger (Gossip_net.Message.Snark_pool_diff diff) ~log_msg: (Gossip_snark_pool_diff { work = Option.value_exn (Snark_pool.Resource_pool.Diff.to_compact diff) } ) ; Gossip_net.Any.broadcast_snark_pool_diff t.gossip_net diff let find_map xs ~f = let open Async in let ds = List.map xs ~f in let filter ~f = Deferred.bind ~f:(fun x -> if f x then return x else Deferred.never ()) in let none_worked = Deferred.bind (Deferred.all ds) ~f:(fun ds -> if List.for_all ds ~f:Or_error.is_error then return (Or_error.error_string "all none") else Deferred.never () ) in Deferred.any (none_worked :: List.map ~f:(filter ~f:Or_error.is_ok) ds) let make_rpc_request ?heartbeat_timeout ?timeout ~rpc ~label t peer input = let open Deferred.Let_syntax in match%map query_peer ?heartbeat_timeout ?timeout t peer.Peer.peer_id rpc input with | Connected { data = Ok (Some response); _ } -> Ok response | Connected { data = Ok None; _ } -> Or_error.errorf !"Peer %{sexp:Network_peer.Peer.Id.t} doesn't have the requested %s" peer.peer_id label | Connected { data = Error e; _ } -> Error e | Failed_to_connect e -> Error (Error.tag e ~tag:"failed-to-connect") let get_transition_chain_proof ?heartbeat_timeout ?timeout t = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_transition_chain_proof ~label:"transition chain proof" t let get_transition_chain ?heartbeat_timeout ?timeout t = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_transition_chain ~label:"chain of transitions" t let get_best_tip ?heartbeat_timeout ?timeout t peer = make_rpc_request ?heartbeat_timeout ?timeout ~rpc:Rpcs.Get_best_tip ~label:"best tip" t peer () let ban_notify t peer banned_until = query_peer t peer.Peer.peer_id Rpcs.Ban_notify banned_until >>| Fn.const (Ok ()) let try_non_preferred_peers (type b) t input peers ~rpc : b Envelope.Incoming.t Deferred.Or_error.t = let max_current_peers = 8 in let rec loop peers num_peers = if num_peers > max_current_peers then return (Or_error.error_string "None of randomly-chosen peers can handle the request" ) else let current_peers, remaining_peers = List.split_n peers num_peers in find_map current_peers ~f:(fun peer -> let%bind response_or_error = query_peer t peer.Peer.peer_id rpc input in match response_or_error with | Connected ({ data = Ok (Some data); _ } as envelope) -> let%bind () = Trust_system.( record t.trust_system t.logger peer Actions. ( Fulfilled_request , Some ("Nonpreferred peer returned valid response", []) )) in return (Ok (Envelope.Incoming.map envelope ~f:(Fn.const data))) | Connected { data = Ok None; _ } -> loop remaining_peers (2 * num_peers) | _ -> loop remaining_peers (2 * num_peers) ) in loop peers 1 let rpc_peer_then_random (type b) t peer_id input ~rpc : b Envelope.Incoming.t Deferred.Or_error.t = let retry () = let%bind peers = random_peers t 8 in try_non_preferred_peers t input peers ~rpc in match%bind query_peer t peer_id rpc input with | Connected { data = Ok (Some response); sender; _ } -> let%bind () = match sender with | Local -> return () | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( Fulfilled_request , Some ("Preferred peer returned valid response", []) )) in return (Ok (Envelope.Incoming.wrap ~data:response ~sender)) | Connected { data = Ok None; sender; _ } -> let%bind () = match sender with | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( No_reply_from_preferred_peer , Some ("When querying preferred peer, got no response", []) )) | Local -> return () in retry () | Connected { data = Error e; sender; _ } -> FIXME # 4094 : determine if more specific actions apply here let%bind () = match sender with | Remote peer -> Trust_system.( record t.trust_system t.logger peer Actions. ( Outgoing_connection_error , Some ( "Error while doing RPC" , [ ("error", Error_json.error_to_yojson e) ] ) )) | Local -> return () in retry () | Failed_to_connect _ -> retry () let get_staged_ledger_aux_and_pending_coinbases_at_hash t inet_addr input = rpc_peer_then_random t inet_addr input ~rpc:Rpcs.Get_staged_ledger_aux_and_pending_coinbases_at_hash >>|? Envelope.Incoming.data let get_ancestry t inet_addr input = rpc_peer_then_random t inet_addr input ~rpc:Rpcs.Get_ancestry module Sl_downloader = struct module Key = struct module T = struct type t = Ledger_hash.t * Sync_ledger.Query.t [@@deriving hash, compare, sexp, to_yojson] end include T include Comparable.Make (T) include Hashable.Make (T) end include Downloader.Make (Key) (struct type t = unit [@@deriving to_yojson] let download : t = () let worth_retrying () = true end) (struct type t = (Mina_base.Ledger_hash.t * Sync_ledger.Query.t) * Sync_ledger.Answer.t [@@deriving to_yojson] let key = fst end) (Ledger_hash) end let glue_sync_ledger : t -> preferred:Peer.t list -> (Mina_base.Ledger_hash.t * Sync_ledger.Query.t) Pipe_lib.Linear_pipe.Reader.t -> ( Mina_base.Ledger_hash.t * Sync_ledger.Query.t * Sync_ledger.Answer.t Network_peer.Envelope.Incoming.t ) Pipe_lib.Linear_pipe.Writer.t -> unit = fun t ~preferred query_reader response_writer -> let downloader = let heartbeat_timeout = Time_ns.Span.of_sec 20. in let global_stop = Pipe_lib.Linear_pipe.closed query_reader in let knowledge h peer = match%map query_peer ~heartbeat_timeout ~timeout:(Time.Span.of_sec 10.) t peer.Peer.peer_id Rpcs.Answer_sync_ledger_query (h, Num_accounts) with | Connected { data = Ok _; _ } -> `Call (fun (h', _) -> Ledger_hash.equal h' h) | Failed_to_connect _ | Connected { data = Error _; _ } -> `Some [] in let%bind _ = Linear_pipe.values_available query_reader in let root_hash_r, root_hash_w = Broadcast_pipe.create (Option.value_exn (Linear_pipe.peek query_reader) |> fst) in Sl_downloader.create ~preferred ~max_batch_size:100 ~peers:(fun () -> peers t) ~knowledge_context:root_hash_r ~knowledge ~stop:global_stop ~trust_system:t.trust_system ~get:(fun (peer : Peer.t) qs -> List.iter qs ~f:(fun (h, _) -> if not (Ledger_hash.equal h (Broadcast_pipe.Reader.peek root_hash_r)) then don't_wait_for (Broadcast_pipe.Writer.write root_hash_w h) ) ; let%map rs = query_peer' ~how:`Parallel ~heartbeat_timeout ~timeout:(Time.Span.of_sec (Float.of_int (List.length qs) *. 2.)) t peer.peer_id Rpcs.Answer_sync_ledger_query qs in match rs with | Failed_to_connect e -> Error e | Connected res -> ( match res.data with | Error e -> Error e | Ok rs -> ( match List.zip qs rs with | Unequal_lengths -> Or_error.error_string "mismatched lengths" | Ok ps -> Ok (List.filter_map ps ~f:(fun (q, r) -> match r with Ok r -> Some (q, r) | Error _ -> None ) ) ) ) ) in don't_wait_for (let%bind downloader = downloader in Linear_pipe.iter_unordered ~max_concurrency:400 query_reader ~f:(fun q -> match%bind Sl_downloader.Job.result (Sl_downloader.download downloader ~key:q ~attempts:Peer.Map.empty) with | Error _ -> Deferred.unit | Ok (a, _) -> Linear_pipe.write_if_open response_writer (fst q, snd q, { a with data = snd a.data }) ) )
9dc95fc541c5e4579638650e3ce55ada057c13fccebd6fc04da3384c046dc4c7
fortytools/holumbus
DMapReduce.hs
-- ---------------------------------------------------------------------------- | Module : Holumbus . Distribution . DMapReduce Copyright : Copyright ( C ) 2008 License : MIT Maintainer : ( ) Stability : experimental Portability : portable Version : 0.1 Module : Holumbus.Distribution.DMapReduce Copyright : Copyright (C) 2008 Stefan Schmidt License : MIT Maintainer : Stefan Schmidt () Stability : experimental Portability: portable Version : 0.1 -} -- ---------------------------------------------------------------------------- {-# OPTIONS -fglasgow-exts #-} module Holumbus.Distribution.DMapReduce ( * DMapReduce , MapReduce(..) -- * Configuration , DMRMasterConf(..) , defaultMRMasterConfig , DMRWorkerConf(..) , defaultMRWorkerConfig , DMRClientConf(..) , defaultMRClientConfig -- * Creation and Destruction , mkMapReduceMaster , mkMapReduceWorker , mkMapReduceClient ) where import Control.Concurrent import Network import System.Log.Logger import Holumbus.Common.Debug import Holumbus.MapReduce.Types import Holumbus.MapReduce.MapReduce import qualified Holumbus.Distribution.Master as M import qualified Holumbus.Distribution.Master.MasterData as MD import qualified Holumbus.Distribution.Master.MasterPort as MP import qualified Holumbus.Distribution.Worker as W import qualified Holumbus.Distribution.Worker.WorkerData as WD import qualified Holumbus.Distribution.Worker.WorkerPort as WP import qualified Holumbus.FileSystem.FileSystem as FS import Holumbus.Network.Site import Holumbus.Network.Port localLogger :: String localLogger = "Holumbus.Distribution.DMapReduce" -- ---------------------------------------------------------------------------- -- ---------------------------------------------------------------------------- data DMapReduceData = forall m w. (M.MasterClass m, W.WorkerClass w, Debug m, Debug w) => DMapReduceData SiteId MapReduceType m (Maybe w) data DMapReduce = DMapReduce (MVar DMapReduceData) instance Show DMapReduce where show _ = "DMapReduce" -- --------------------------------------------------------------------------- -- Configurations -- --------------------------------------------------------------------------- data DMRMasterConf = DMRMasterConf { msc_StartControlling :: Bool , msc_StreamName :: StreamName , msc_PortNumber :: Maybe PortNumber } defaultMRMasterConfig :: DMRMasterConf defaultMRMasterConfig = DMRMasterConf True "MRMaster" Nothing data DMRWorkerConf = DMRWorkerConf { woc_StreamName :: StreamName , woc_SocketId :: Maybe SocketId } defaultMRWorkerConfig :: DMRWorkerConf defaultMRWorkerConfig = DMRWorkerConf "MRMaster" Nothing data DMRClientConf = DMRClientConf { clc_StreamName :: StreamName , clc_SocketId :: Maybe SocketId } defaultMRClientConfig :: DMRClientConf defaultMRClientConfig = DMRClientConf "MRMaster" Nothing -- --------------------------------------------------------------------------- -- Creation and Destruction -- --------------------------------------------------------------------------- mkMapReduceMaster :: FS.FileSystem -> DMRMasterConf -> IO DMapReduce mkMapReduceMaster fs conf = do sid <- getSiteId infoM localLogger $ "initialising master on site " ++ show sid md <- MD.newMaster fs (msc_StartControlling conf) (msc_StreamName conf) (msc_PortNumber conf) newDMapReduce MRTMaster md (Nothing::Maybe WP.WorkerPort) mkMapReduceWorker :: FS.FileSystem -> ActionMap -> DMRWorkerConf -> IO DMapReduce mkMapReduceWorker fs am conf = do sid <- getSiteId infoM localLogger $ "initialising worker on site " ++ show sid mp <- MP.newMasterPort (woc_StreamName conf) (woc_SocketId conf) wd <- WD.newWorker fs am (woc_StreamName conf) (woc_SocketId conf) newDMapReduce MRTWorker mp (Just wd) mkMapReduceClient :: DMRClientConf -> IO DMapReduce mkMapReduceClient conf = do sid <- getSiteId infoM localLogger $ "initialising map-reduce-client on site " ++ show sid mp <- MP.newMasterPort (clc_StreamName conf) (clc_SocketId conf) newDMapReduce MRTClient mp (Nothing::Maybe WP.WorkerPort) newDMapReduce :: (M.MasterClass m, W.WorkerClass w, Debug m, Debug w) => MapReduceType -> m -> Maybe w -> IO DMapReduce newDMapReduce t m w = do sid <- getSiteId d <- newMVar (DMapReduceData sid t m w) return $ DMapReduce d getMasterRequestPort : : DMapReduce - > IO MSG.MasterRequestPort getMasterRequestPort ( DMapReduce mr ) = withMVar mr $ \(DMapReduceData _ _ m _ ) - > return $ M.getMasterRequestPort m getMasterRequestPort :: DMapReduce -> IO MSG.MasterRequestPort getMasterRequestPort (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> return $ M.getMasterRequestPort m -} -- --------------------------------------------------------------------------- -- public functions -- --------------------------------------------------------------------------- instance Debug DMapReduce where printDebug (DMapReduce mr) = withMVar mr $ \(DMapReduceData s t m w) -> do putStrLn "--------------------------------------------------------" putStrLn "Distribtion - internal data\n" putStrLn "--------------------------------------------------------" putStrLn "SiteId:" putStrLn $ show s putStrLn "Type:" putStrLn $ show t putStrLn "--------------------------------------------------------" putStrLn "Master:" printDebug m putStrLn "--------------------------------------------------------" putStrLn "Worker:" maybe (putStrLn "NOTHING") (\w' -> printDebug w') w putStrLn "--------------------------------------------------------" getDebug (DMapReduce mr) = withMVar mr $ \(DMapReduceData s t m w) -> do let line = "--------------------------------------------------------" tmp <- getDebug m mtmp <- maybe (return "NOTHING") (\w' -> getDebug w') w return (line ++"\n"++ "Distribtion - internal data\n" ++"\n"++line ++"\n"++ "SiteId:" ++"\n"++ show s ++"\n"++ "Type:" ++"\n"++ show t ++"\n"++line ++"\n"++ "Master:" ++"\n"++tmp ++"\n"++line ++"\n"++"Worker:" ++mtmp ++"\n"++line++"\n") instance MapReduce DMapReduce where closeMapReduce (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m w) -> do case w of (Just w') -> W.closeWorker w' (Nothing) -> return () M.closeMaster m getMySiteId (DMapReduce mr) = withMVar mr $ \(DMapReduceData s _ _ _) -> return s getMapReduceType (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ t _ _) -> return t startControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> startControlling m stopControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> stopControlling m isControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> isControlling m doSingleStep (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> doSingleStep m doMapReduceJob ji (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> doMapReduceJob ji m
null
https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/mapreduce/source/Holumbus/Distribution/DMapReduce.hs
haskell
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- # OPTIONS -fglasgow-exts # * Configuration * Creation and Destruction ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- --------------------------------------------------------------------------- Configurations --------------------------------------------------------------------------- --------------------------------------------------------------------------- Creation and Destruction --------------------------------------------------------------------------- --------------------------------------------------------------------------- public functions ---------------------------------------------------------------------------
| Module : Holumbus . Distribution . DMapReduce Copyright : Copyright ( C ) 2008 License : MIT Maintainer : ( ) Stability : experimental Portability : portable Version : 0.1 Module : Holumbus.Distribution.DMapReduce Copyright : Copyright (C) 2008 Stefan Schmidt License : MIT Maintainer : Stefan Schmidt () Stability : experimental Portability: portable Version : 0.1 -} module Holumbus.Distribution.DMapReduce ( * DMapReduce , MapReduce(..) , DMRMasterConf(..) , defaultMRMasterConfig , DMRWorkerConf(..) , defaultMRWorkerConfig , DMRClientConf(..) , defaultMRClientConfig , mkMapReduceMaster , mkMapReduceWorker , mkMapReduceClient ) where import Control.Concurrent import Network import System.Log.Logger import Holumbus.Common.Debug import Holumbus.MapReduce.Types import Holumbus.MapReduce.MapReduce import qualified Holumbus.Distribution.Master as M import qualified Holumbus.Distribution.Master.MasterData as MD import qualified Holumbus.Distribution.Master.MasterPort as MP import qualified Holumbus.Distribution.Worker as W import qualified Holumbus.Distribution.Worker.WorkerData as WD import qualified Holumbus.Distribution.Worker.WorkerPort as WP import qualified Holumbus.FileSystem.FileSystem as FS import Holumbus.Network.Site import Holumbus.Network.Port localLogger :: String localLogger = "Holumbus.Distribution.DMapReduce" data DMapReduceData = forall m w. (M.MasterClass m, W.WorkerClass w, Debug m, Debug w) => DMapReduceData SiteId MapReduceType m (Maybe w) data DMapReduce = DMapReduce (MVar DMapReduceData) instance Show DMapReduce where show _ = "DMapReduce" data DMRMasterConf = DMRMasterConf { msc_StartControlling :: Bool , msc_StreamName :: StreamName , msc_PortNumber :: Maybe PortNumber } defaultMRMasterConfig :: DMRMasterConf defaultMRMasterConfig = DMRMasterConf True "MRMaster" Nothing data DMRWorkerConf = DMRWorkerConf { woc_StreamName :: StreamName , woc_SocketId :: Maybe SocketId } defaultMRWorkerConfig :: DMRWorkerConf defaultMRWorkerConfig = DMRWorkerConf "MRMaster" Nothing data DMRClientConf = DMRClientConf { clc_StreamName :: StreamName , clc_SocketId :: Maybe SocketId } defaultMRClientConfig :: DMRClientConf defaultMRClientConfig = DMRClientConf "MRMaster" Nothing mkMapReduceMaster :: FS.FileSystem -> DMRMasterConf -> IO DMapReduce mkMapReduceMaster fs conf = do sid <- getSiteId infoM localLogger $ "initialising master on site " ++ show sid md <- MD.newMaster fs (msc_StartControlling conf) (msc_StreamName conf) (msc_PortNumber conf) newDMapReduce MRTMaster md (Nothing::Maybe WP.WorkerPort) mkMapReduceWorker :: FS.FileSystem -> ActionMap -> DMRWorkerConf -> IO DMapReduce mkMapReduceWorker fs am conf = do sid <- getSiteId infoM localLogger $ "initialising worker on site " ++ show sid mp <- MP.newMasterPort (woc_StreamName conf) (woc_SocketId conf) wd <- WD.newWorker fs am (woc_StreamName conf) (woc_SocketId conf) newDMapReduce MRTWorker mp (Just wd) mkMapReduceClient :: DMRClientConf -> IO DMapReduce mkMapReduceClient conf = do sid <- getSiteId infoM localLogger $ "initialising map-reduce-client on site " ++ show sid mp <- MP.newMasterPort (clc_StreamName conf) (clc_SocketId conf) newDMapReduce MRTClient mp (Nothing::Maybe WP.WorkerPort) newDMapReduce :: (M.MasterClass m, W.WorkerClass w, Debug m, Debug w) => MapReduceType -> m -> Maybe w -> IO DMapReduce newDMapReduce t m w = do sid <- getSiteId d <- newMVar (DMapReduceData sid t m w) return $ DMapReduce d getMasterRequestPort : : DMapReduce - > IO MSG.MasterRequestPort getMasterRequestPort ( DMapReduce mr ) = withMVar mr $ \(DMapReduceData _ _ m _ ) - > return $ M.getMasterRequestPort m getMasterRequestPort :: DMapReduce -> IO MSG.MasterRequestPort getMasterRequestPort (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> return $ M.getMasterRequestPort m -} instance Debug DMapReduce where printDebug (DMapReduce mr) = withMVar mr $ \(DMapReduceData s t m w) -> do putStrLn "--------------------------------------------------------" putStrLn "Distribtion - internal data\n" putStrLn "--------------------------------------------------------" putStrLn "SiteId:" putStrLn $ show s putStrLn "Type:" putStrLn $ show t putStrLn "--------------------------------------------------------" putStrLn "Master:" printDebug m putStrLn "--------------------------------------------------------" putStrLn "Worker:" maybe (putStrLn "NOTHING") (\w' -> printDebug w') w putStrLn "--------------------------------------------------------" getDebug (DMapReduce mr) = withMVar mr $ \(DMapReduceData s t m w) -> do let line = "--------------------------------------------------------" tmp <- getDebug m mtmp <- maybe (return "NOTHING") (\w' -> getDebug w') w return (line ++"\n"++ "Distribtion - internal data\n" ++"\n"++line ++"\n"++ "SiteId:" ++"\n"++ show s ++"\n"++ "Type:" ++"\n"++ show t ++"\n"++line ++"\n"++ "Master:" ++"\n"++tmp ++"\n"++line ++"\n"++"Worker:" ++mtmp ++"\n"++line++"\n") instance MapReduce DMapReduce where closeMapReduce (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m w) -> do case w of (Just w') -> W.closeWorker w' (Nothing) -> return () M.closeMaster m getMySiteId (DMapReduce mr) = withMVar mr $ \(DMapReduceData s _ _ _) -> return s getMapReduceType (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ t _ _) -> return t startControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> startControlling m stopControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> stopControlling m isControlling (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> isControlling m doSingleStep (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> doSingleStep m doMapReduceJob ji (DMapReduce mr) = withMVar mr $ \(DMapReduceData _ _ m _) -> doMapReduceJob ji m
05b0ef5fb25e76b659368ae8ba5b571ead9e6bc7606344740e4ff3245dc0a123
alanz/ghc-exactprint
Existential.hs
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} # LANGUAGE RecordWildCards # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE FlexibleInstances # -- from -posts/2014-12-19-existential-quantification.html data HashMap k v = HM -- ... -- actual implementation class Hashable v where h :: v -> Int data HashMapM hm = HashMapM { empty :: forall k v . hm k v , lookup :: Hashable k => k -> hm k v -> Maybe v , insert :: Hashable k => k -> v -> hm k v -> hm k v , union :: Hashable k => hm k v -> hm k v -> hm k v } data HashMapE = forall hm . HashMapE (HashMapM hm) -- public mkHashMapE :: Int -> HashMapE mkHashMapE = HashMapE . mkHashMapM -- private mkHashMapM :: Int -> HashMapM HashMap mkHashMapM salt = HashMapM { {- implementation -} } instance Hashable String where type Name = String data Gift = G String giraffe :: Gift giraffe = G "giraffe" addGift :: HashMapM hm -> hm Name Gift -> hm Name Gift addGift mod gifts = let HashMapM{..} = mod in insert "Ollie" giraffe gifts -- ------------------------------- santa'sSecretSalt = undefined sendGiftToOllie = undefined traverse_ = undefined sendGifts = case mkHashMapE santa'sSecretSalt of HashMapE (mod@HashMapM{..}) -> let gifts = addGift mod empty in traverse_ sendGiftToOllie $ lookup "Ollie" gifts
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/Existential.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE GADTs # # LANGUAGE TypeSynonymInstances # from -posts/2014-12-19-existential-quantification.html ... -- actual implementation public private implementation -------------------------------
# LANGUAGE RecordWildCards # # LANGUAGE FlexibleInstances # class Hashable v where h :: v -> Int data HashMapM hm = HashMapM { empty :: forall k v . hm k v , lookup :: Hashable k => k -> hm k v -> Maybe v , insert :: Hashable k => k -> v -> hm k v -> hm k v , union :: Hashable k => hm k v -> hm k v -> hm k v } data HashMapE = forall hm . HashMapE (HashMapM hm) mkHashMapE :: Int -> HashMapE mkHashMapE = HashMapE . mkHashMapM mkHashMapM :: Int -> HashMapM HashMap instance Hashable String where type Name = String data Gift = G String giraffe :: Gift giraffe = G "giraffe" addGift :: HashMapM hm -> hm Name Gift -> hm Name Gift addGift mod gifts = let HashMapM{..} = mod in insert "Ollie" giraffe gifts santa'sSecretSalt = undefined sendGiftToOllie = undefined traverse_ = undefined sendGifts = case mkHashMapE santa'sSecretSalt of HashMapE (mod@HashMapM{..}) -> let gifts = addGift mod empty in traverse_ sendGiftToOllie $ lookup "Ollie" gifts
d4d74f5047453bd30c9b3adec26b43c1dc3a96b20aaec9aa3579e68c12bdc930
8c6794b6/guile-tjit
t-side-exit-16.scm
;; Another nested branches, was showing incorrect result for while. (define (loop n) (let lp ((i n) (acc 0)) (if (= i 0) acc (lp (- i 1) (if (< i 800) (+ (if (< i 400) (+ (if (< i 200) (+ i 3) (+ i 4)) 1) (+ i 2)) 1) (+ i 1)))))) (loop 1000)
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/t-side-exit-16.scm
scheme
Another nested branches, was showing incorrect result for while.
(define (loop n) (let lp ((i n) (acc 0)) (if (= i 0) acc (lp (- i 1) (if (< i 800) (+ (if (< i 400) (+ (if (< i 200) (+ i 3) (+ i 4)) 1) (+ i 2)) 1) (+ i 1)))))) (loop 1000)
c26981c36753d051580b4ecab49c90649d76cbcbf997414ee44e54779f8d268b
potatosalad/erlang-crypto_rsassa_pss
crypto_rsassa_pss_props.erl
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- %% vim: ts=4 sw=4 ft=erlang noet -module(crypto_rsassa_pss_props). -include_lib("public_key/include/public_key.hrl"). -include_lib("proper/include/proper.hrl"). % -compile(export_all). digest_type() -> oneof([md5, sha, sha224, sha256, sha384, sha512, {hmac, md5, <<>>}, {hmac, sha, <<>>}, {hmac, sha224, <<>>}, {hmac, sha256, <<>>}, {hmac, sha384, <<>>}, {hmac, sha512, <<>>}]). salt_size() -> non_neg_integer(). integer(256 , 8192 ) | ( ) . exponent_size() -> return(65537). % pos_integer(). rsa_keypair(ModulusSize) -> ?LET(ExponentSize, exponent_size(), begin case public_key:generate_key({rsa, ModulusSize, ExponentSize}) of PrivateKey=#'RSAPrivateKey'{modulus=Modulus, publicExponent=PublicExponent} -> {PrivateKey, #'RSAPublicKey'{modulus=Modulus, publicExponent=PublicExponent}} end end). %%==================================================================== %% RSASSA-PSS %%==================================================================== rsassa_pss_signer_gen() -> ?LET({DigestType, ModulusSize}, ?SUCHTHAT({DigestType, ModulusSize}, {digest_type(), modulus_size()}, ModulusSize >= (bit_size(do_hash(DigestType, <<>>)) * 2 + 16)), {rsa_keypair(ModulusSize), ModulusSize, DigestType, binary()}). rsassa_pss_signer_with_salt_gen() -> ?LET({DigestType, ModulusSize, SaltSize}, ?SUCHTHAT({DigestType, ModulusSize, SaltSize}, {digest_type(), modulus_size(), salt_size()}, ModulusSize >= (bit_size(do_hash(DigestType, <<>>)) + (SaltSize * 8) + 16)), {rsa_keypair(ModulusSize), ModulusSize, DigestType, binary(SaltSize), binary()}). prop_rsassa_pss_sign_and_verify() -> ?FORALL({{PrivateKey, PublicKey}, _, DigestType, Message}, rsassa_pss_signer_gen(), begin {ok, Signature} = crypto_rsassa_pss:rsassa_pss_sign(DigestType, Message, PrivateKey), crypto_rsassa_pss:rsassa_pss_verify(DigestType, Message, Signature, PublicKey) end). prop_rsassa_pss_sign_and_verify_with_salt() -> ?FORALL({{PrivateKey, PublicKey}, _ModulusSize, DigestType, Salt, Message}, rsassa_pss_signer_with_salt_gen(), begin {ok, Signature} = crypto_rsassa_pss:rsassa_pss_sign(DigestType, Message, Salt, PrivateKey), crypto_rsassa_pss:rsassa_pss_verify(DigestType, Message, Signature, byte_size(Salt), PublicKey) end). %%%------------------------------------------------------------------- Internal functions %%%------------------------------------------------------------------- do_hash(DigestType, PlainText) when is_atom(DigestType) -> crypto:hash(DigestType, PlainText); do_hash({hmac, DigestType, Key}, PlainText) -> crypto:hmac(DigestType, Key, PlainText).
null
https://raw.githubusercontent.com/potatosalad/erlang-crypto_rsassa_pss/283ce9542e5e09d4c18de95b5ef3faf6e6c528a4/test/property_test/crypto_rsassa_pss_props.erl
erlang
vim: ts=4 sw=4 ft=erlang noet -compile(export_all). pos_integer(). ==================================================================== RSASSA-PSS ==================================================================== ------------------------------------------------------------------- -------------------------------------------------------------------
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- -module(crypto_rsassa_pss_props). -include_lib("public_key/include/public_key.hrl"). -include_lib("proper/include/proper.hrl"). digest_type() -> oneof([md5, sha, sha224, sha256, sha384, sha512, {hmac, md5, <<>>}, {hmac, sha, <<>>}, {hmac, sha224, <<>>}, {hmac, sha256, <<>>}, {hmac, sha384, <<>>}, {hmac, sha512, <<>>}]). salt_size() -> non_neg_integer(). integer(256 , 8192 ) | ( ) . rsa_keypair(ModulusSize) -> ?LET(ExponentSize, exponent_size(), begin case public_key:generate_key({rsa, ModulusSize, ExponentSize}) of PrivateKey=#'RSAPrivateKey'{modulus=Modulus, publicExponent=PublicExponent} -> {PrivateKey, #'RSAPublicKey'{modulus=Modulus, publicExponent=PublicExponent}} end end). rsassa_pss_signer_gen() -> ?LET({DigestType, ModulusSize}, ?SUCHTHAT({DigestType, ModulusSize}, {digest_type(), modulus_size()}, ModulusSize >= (bit_size(do_hash(DigestType, <<>>)) * 2 + 16)), {rsa_keypair(ModulusSize), ModulusSize, DigestType, binary()}). rsassa_pss_signer_with_salt_gen() -> ?LET({DigestType, ModulusSize, SaltSize}, ?SUCHTHAT({DigestType, ModulusSize, SaltSize}, {digest_type(), modulus_size(), salt_size()}, ModulusSize >= (bit_size(do_hash(DigestType, <<>>)) + (SaltSize * 8) + 16)), {rsa_keypair(ModulusSize), ModulusSize, DigestType, binary(SaltSize), binary()}). prop_rsassa_pss_sign_and_verify() -> ?FORALL({{PrivateKey, PublicKey}, _, DigestType, Message}, rsassa_pss_signer_gen(), begin {ok, Signature} = crypto_rsassa_pss:rsassa_pss_sign(DigestType, Message, PrivateKey), crypto_rsassa_pss:rsassa_pss_verify(DigestType, Message, Signature, PublicKey) end). prop_rsassa_pss_sign_and_verify_with_salt() -> ?FORALL({{PrivateKey, PublicKey}, _ModulusSize, DigestType, Salt, Message}, rsassa_pss_signer_with_salt_gen(), begin {ok, Signature} = crypto_rsassa_pss:rsassa_pss_sign(DigestType, Message, Salt, PrivateKey), crypto_rsassa_pss:rsassa_pss_verify(DigestType, Message, Signature, byte_size(Salt), PublicKey) end). Internal functions do_hash(DigestType, PlainText) when is_atom(DigestType) -> crypto:hash(DigestType, PlainText); do_hash({hmac, DigestType, Key}, PlainText) -> crypto:hmac(DigestType, Key, PlainText).
4ac57b1e7b11038839b9dacbc08fbda3719f828b10f99279212fc47010166de2
jyh/metaprl
m_ir.ml
doc <:doc< @spelling{CPS IR} @module[M_ir] This module defines the intermediate language for the @emph{M} language. Here is the abstract syntax: @begin[verbatim] (* Values *) v ::= i (integers) | b (booleans) | v (variables) | fun v -> e (functions) | (v1, v2) (pairs) (* Atoms (functional expressions) *) a ::= i (integers) | b (booleans) | v (variables) | a1 op a2 (binary operation) | fun x -> e (unnamed functions) (* Expressions *) e ::= let v = a in e (LetAtom) | f(a) (TailCall) | if a then e1 else e2 (Conditional) | let v = a1.[a2] in e (Subscripting) | a1.[a2] <- a3; e (Assignment) These are eliminated during CPS | let v = f(a) in e (Function application) | return a @end[verbatim] A program is a set of function definitions and an program expressed in a sequent. Each function must be declared, and defined separately. @docoff ---------------------------------------------------------------- @begin[license] Copyright (C) 2003 Jason Hickey, Caltech 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 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Jason Hickey @email{} @end[license] >> doc <:doc< @parents Modules in @MetaPRL are organized in a theory hierarchy. Each theory module extends its parent theories. In this case, the @tt[M_ir] module extends base theories that define generic proof automation. >> extends Base_theory doc docoff open Refiner.Refiner.Term open Refiner.Refiner.TermOp doc <:doc< @terms The IR defines several binary operators for arithmetic and Boolean operations. >> declare AddOp declare SubOp declare MulOp declare DivOp declare LtOp declare LeOp declare EqOp declare NeqOp declare GeOp declare GtOp doc <:doc< @modsubsection{Atoms} Atoms represent expressions that are values: integers, variables, binary operations on atoms, and functions. @tt[AtomFun] is a lambda-abstraction, and @tt[AtomFunVar] is the projection of a function from a recursive function definition (defined below). >> declare AtomFalse declare AtomTrue declare AtomInt[i:n] declare AtomBinop{'op; 'a1; 'a2} declare AtomRelop{'op; 'a1; 'a2} declare AtomFun{x. 'e['x]} declare AtomVar{'v} declare AtomFunVar{'R; 'v} doc <:doc< @modsubsection{Expressions} General expressions are not values. There are several simple kinds of expressions, for conditionals, allocation, function calls, and array operations. >> declare LetAtom{'a; v. 'e['v]} declare If{'a; 'e1; 'e2} declare ArgNil declare ArgCons{'a; 'rest} declare TailCall{'f; 'args} declare Length[i:n] declare AllocTupleNil declare AllocTupleCons{'a; 'rest} declare LetTuple{'length; 'tuple; v. 'e['v]} declare LetSubscript{'a1; 'a2; v. 'e['v]} declare SetSubscript{'a1; 'a2; 'a3; 'e} doc <:doc< Reserve statements are used to specify how much memory may be allocated in a function body. The M_reserve module defines an explicit phase that calculates memory usage and adds reserve statements. In the << Reserve[words:n]{'args; 'e} >> expressions, the @it[words] constant defines how much memory is to be reserved; the @it[args] defines the set of live variables (this information is used by the garbage collector), and @it[e] is the nested expression that performs the allocation. >> declare Reserve[words:n]{'e} declare Reserve[words:n]{'args; 'e} declare ReserveCons{'a; 'rest} declare ReserveNil doc <:doc< @tt[LetApply], @tt[Return] are eliminated during CPS conversion. @tt[LetClosure] is like @tt[LetApply], but it represents a partial application. >> declare LetApply{'f; 'a; v. 'e['v]} declare LetClosure{'a1; 'a2; f. 'e['f]} declare Return{'a} doc <:doc< This is the most problematic part of the description so far . This documentation discusses two possible approaches . This documentation discusses two possible approaches. *) @modsubsection{Recursive values} We need some way to represent mutually recursive functions. The normal way to do this is to define a single recursive function, and use a switch to split the different parts. For this purpose, we define a fixpoint over a record of functions. For example, suppose we define two mutually recursive functions $f$ and $g$: @begin[verbatim] let r2 = fix{r1. record{ field["f"]{lambda{x. (r1.g)(x)}}; field["g"]{lambda{x. (r1.f)(x)}}}} in r2.f(1) @end[verbatim] >> declare LetRec{R1. 'e1['R1]; R2. 'e2['R2]} doc <:doc< The following terms define the set of tagged fields used in the record definition. We require that all the fields be functions. The record construction is recursive. The @tt[Label] term is used for field tags; the @tt[FunDef] defines a new field in the record; and the @tt[EndDef] term terminates the record fields. >> declare Fields{'fields} declare Label[tag:s] declare FunDef{'label; 'exp; 'rest} declare EndDef doc <:doc< To simplify the presentation, we usually project the record fields before each of the field branches so that we can treat functions as if they were variables. >> declare LetFun{'R; 'label; f. 'e['f]} doc <:doc< Include a term representing initialization code. >> declare Initialize{'e} doc <:doc< @modsubsection{Program sequent representation} Programs are represented as sequents: <<sequent{ <declarations>; <definitions> >- exp }>> For now the language is untyped, so each declaration has the form @tt["v = exp"]. A definition is an equality judgment. >> declare exp declare def{'v; 'e} declare compilable{'e} doc docoff (************************************************************************ * Display forms *) (* * Precedences. *) prec prec_var prec prec_mul prec prec_add prec prec_rel prec prec_if prec prec_fun prec prec_let prec prec_comma prec prec_compilable prec prec_mul < prec_var prec prec_add < prec_mul prec prec_rel < prec_add prec prec_let < prec_rel prec prec_if < prec_let prec prec_fun < prec_if prec prec_comma < prec_fun prec prec_compilable < prec_comma (* Some convenient keywords (used in only display forms and do not have a formal meaning). *) declare xlet : Dform declare xin : Dform dform xlet_df : xlet = bf["let"] dform xin_df : xin = bf["in"] (* Atoms *) dform atom_false_df : AtomFalse = `"false" dform atom_false_df : AtomTrue = `"true" dform atom_int_df : AtomInt[i:n] = `"#" slot[i:n] dform atom_var_df : AtomVar{'v} = Mpsymbols!downarrow slot{'v} dform atom_fun_var_df : parens :: "prec"[prec_var] :: AtomFunVar{'R; 'v} = slot{'R} `"." slot{'v} dform atom_binop_add_df : parens :: "prec"[prec_add] :: AtomBinop{AddOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"+ " slot["le"]{'e2} dform atom_binop_sub_df : parens :: "prec"[prec_add] :: AtomBinop{SubOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"- " slot["le"]{'e2} dform atom_binop_mul_df : parens :: "prec"[prec_mul] :: AtomBinop{MulOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"* " slot["le"]{'e2} dform atom_binop_div_df : parens :: "prec"[prec_mul] :: AtomBinop{DivOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"/ " slot["le"]{'e2} dform atom_binop_lt_df : parens :: "prec"[prec_rel] :: AtomRelop{LtOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"< " slot["le"]{'e2} dform atom_binop_le_df : parens :: "prec"[prec_rel] :: AtomRelop{LeOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!le `" " slot["le"]{'e2} dform atom_binop_gt_df : parens :: "prec"[prec_rel] :: AtomRelop{GtOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"> " slot["le"]{'e2} dform atom_binop_ge_df : parens :: "prec"[prec_rel] :: AtomRelop{GeOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!ge `" " slot["le"]{'e2} dform atom_binop_eq_df : parens :: "prec"[prec_rel] :: AtomRelop{EqOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"= " slot["le"]{'e2} dform atom_binop_neq_df : parens :: "prec"[prec_rel] :: AtomRelop{NeqOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!neq `" " slot["le"]{'e2} General / relop dform atom_binop_gen_df : parens :: "prec"[prec_rel] :: AtomRelop{'op; 'e1; 'e2} = slot["lt"]{'e1} `" " slot{'op} `" " slot["le"]{'e2} dform atom_binop_gen_df : parens :: "prec"[prec_rel] :: AtomBinop{'op; 'e1; 'e2} = slot["lt"]{'e1} `" " slot{'op} `" " slot["le"]{'e2} dform atom_fun_df : parens :: "prec"[prec_fun] :: AtomFun{x. 'e} = szone pushm[3] Mpsymbols!lambda Mpsymbols!suba slot{'x} `"." hspace slot{'e} popm ezone (* Expressions *) dform exp_let_atom_df : parens :: "prec"[prec_let] :: LetAtom{'a; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" = "] slot{'a} `" " xin hspace slot["lt"]{'e} popm ezone dform exp_tailcall_df : parens :: "prec"[prec_let] :: TailCall{'f; 'args} = bf["tailcall "] slot{'f} `" " slot{'args} dform arg_cons_df1 : parens :: "prec"[prec_comma] :: ArgCons{'a1; ArgCons{'a2; 'rest}} = slot{'a1} `", " slot["lt"]{ArgCons{'a2; 'rest}} dform arg_cons_df2 : parens :: "prec"[prec_comma] :: ArgCons{'a; ArgNil} = slot{'a} dform arg_cons_df2 : parens :: "prec"[prec_comma] :: ArgCons{'a; 'b} = slot{'a} `" :: " slot{'b} dform arg_nil_df : parens :: "prec"[prec_comma] :: ArgNil = `"" dform exp_if_df : parens :: "prec"[prec_if] :: except_mode[tex] :: If{'a; 'e1; 'e2} = szone pushm[0] pushm[3] bf["if"] `" " slot{'a} `" " bf["then"] hspace slot{'e1} popm hspace pushm[3] bf["else"] hspace slot{'e2} popm popm ezone TEX if dform exp_if_df : parens :: "prec"[prec_if] :: mode[tex] :: If{'a; 'e1; 'e2} = bf["if"] `" " slot{'a} `" " bf["then "] slot{'e1} `" " bf["else "] slot{'e2} (* * Reserve. *) dform reserve_df1 : parens :: "prec"[prec_let] :: Reserve[words:n]{'e} = bf["reserve "] slot[words:n] bf[" words in"] hspace slot["lt"]{'e} dform reserve_df2 : parens :: "prec"[prec_let] :: Reserve[words:n]{'args; 'e} = bf["reserve "] slot[words:n] bf[" words args "] slot{'args} bf[" in"] hspace slot["lt"]{'e} dform reserve_cons_df1 : parens :: "prec"[prec_comma] :: ReserveCons{'a1; ReserveCons{'a2; 'rest}} = slot{'a1} `", " slot["lt"]{ReserveCons{'a2; 'rest}} dform reserve_cons_df2 : parens :: "prec"[prec_comma] :: ReserveCons{'a; ArgNil} = slot{'a} dform reserve_nil_df : parens :: "prec"[prec_comma] :: ReserveNil = `"" doc <:doc< Sequent tag for the M language. >> declare sequent [sequent_arg] { Term : Term >- Term } : Judgment doc docoff dform sequent_arg_df: sequent_arg = subm declare default_extract dform default_extract_df : sequent { <H> >- default_extract } = `"" doc <:doc< @modsubsection{Subscripting.} Tuples are listed in reverse order. >> declare alloc_tuple{'l1; 'l2} : Dform declare alloc_tuple{'l} : Dform doc docoff dform length_df : Length[i:n] = slot[i:n] dform alloc_tuple_start_nil_df : AllocTupleNil = alloc_tuple{nil; AllocTupleNil} dform alloc_tuple_start_cons_df : AllocTupleCons{'a; 'rest} = alloc_tuple{nil; AllocTupleCons{'a; 'rest}} dform alloc_tuple_shift_df : alloc_tuple{'l; AllocTupleCons{'a; 'rest}} = alloc_tuple{cons{'a; 'l}; 'rest} dform alloc_tuple_start_df : alloc_tuple{'l; AllocTupleNil} = szone pushm[1] bf["("] alloc_tuple{'l} bf[")"] popm ezone (* General alloc_tuple *) dform alloc_tuple_start_df : alloc_tuple{'l; 'tl} = szone pushm[1] bf["("] alloc_tuple{'l} `" :: " slot{'tl} bf[")"] popm ezone dform alloc_tuple_nil_df : alloc_tuple{nil} = `"" dform alloc_tuple_cons_nil_df : alloc_tuple{cons{'a; nil}} = slot{'a} dform alloc_tuple_cons_cons_df : alloc_tuple{cons{'a1; cons{'a2; 'l}}} = slot{'a1} bf[","] hspace alloc_tuple{cons{'a2; 'l}} (* * Actual tuple operations. *) dform exp_let_tuple_df : parens :: "prec"[prec_let] :: LetTuple{'length; 'tuple; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" =[length = "] slot{'length} bf["] "] slot{'tuple} `" " xin hspace slot["lt"]{'e} popm ezone dform exp_subscript_df : parens :: "prec"[prec_let] :: LetSubscript{'a1; 'a2; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" = "] slot{'a1} `".[" slot{'a2} `"] " xin hspace slot["lt"]{'e} popm ezone dform exp_set_subscript_df : parens :: "prec"[prec_let] :: SetSubscript{'a1; 'a2; 'a3; 'e} = slot{'a1} `".[" slot{'a2} `"] " leftarrow `" " slot{'a3} `";" hspace slot["lt"]{'e} (* * Functions and application. *) dform exp_let_apply_df : parens :: "prec"[prec_let] :: LetApply{'f; 'a; v. 'e} = szone pushm[3] xlet bf[" apply "] slot{'v} bf[" = "] slot{'f} `"(" slot{'a} `") " xin hspace slot["lt"]{'e} popm ezone dform exp_let_closure_df : parens :: "prec"[prec_let] :: LetClosure{'f; 'a; v. 'e} = szone pushm[3] xlet bf[" closure "] slot{'v} bf[" = "] slot{'f} `"(" slot{'a} `") " xin hspace slot["lt"]{'e} popm ezone dform exp_return_df : Return{'a} = bf["return"] `"(" slot{'a} `")" (* * Recursive functions. *) dform let_rec_df : parens :: "prec"[prec_let] :: LetRec{R1. 'e1; R2. 'e2} = szone pushm[3] xlet bf[" rec "] slot{'R1} `"." hspace 'e1 popm ezone hspace slot{'R2} `"." xin hspace slot["lt"]{'e2} dform fields_df : parens :: "prec"[prec_let] :: Fields{'fields} = szone pushm[0] pushm[2] bf["{ "] slot["lt"]{'fields} popm hspace bf["}"] popm ezone dform fun_def_df : parens :: "prec"[prec_let] :: FunDef{'label; 'e; 'rest} = szone pushm[3] bf["fun "] slot{'label} `" =" hspace slot{'e} popm ezone hspace 'rest dform end_def_df : EndDef = `"" dform label_df : Label[s:s] = `"\"" slot[s:s] `"\"" dform let_fun_def : parens :: "prec"[prec_let] :: LetFun{'R; 'label; f. 'e} = szone pushm[3] xlet bf[" fun "] slot{'f} `" = " slot{'R} `"." slot{'label} `" " xin hspace slot["lt"]{'e} popm ezone (* * Initialization code. *) dform initialize_df : parens :: "prec"[prec_let] :: Initialize{'e} = szone pushm[0] pushm[3] bf["initialization"] hspace slot{'e} popm hspace bf["end"] popm ezone (* * Declarations and definitions. *) dform exp_df : exp = bf["exp"] dform def_df : def{'v; 'e} = slot{'v} bf[" = "] slot{'e} dform compilable_df : "prec"[prec_compilable] :: compilable{'e} = szone pushm[0] pushm[3] bf["compilable"] hspace slot{'e} popm hspace bf["end"] popm ezone (************************************************************************ * ML Helpers *) let fundef_term = << FunDef{'label; 'e; 'rest} >> let fundef_opname = opname_of_term fundef_term let is_fundef_term = is_dep0_dep0_dep0_term fundef_opname let dest_fundef_term = dest_dep0_dep0_dep0_term fundef_opname let mk_fundef_term = mk_dep0_dep0_dep0_term fundef_opname let letrec_term = << LetRec{R1. 'fields['R1]; R2. 'body['R2]} >> let letrec_opname = opname_of_term letrec_term let is_letrec_term = is_dep1_dep1_term letrec_opname let dest_letrec_term = dest_dep1_dep1_term letrec_opname let mk_letrec_term = mk_dep1_dep1_term letrec_opname (* * -*- * Local Variables: * Caml-master: "compile" * End: * -*- *)
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/experimental/compile/m_ir.ml
ocaml
Values Atoms (functional expressions) Expressions *********************************************************************** * Display forms * Precedences. Some convenient keywords (used in only display forms and do not have a formal meaning). Atoms Expressions * Reserve. General alloc_tuple * Actual tuple operations. * Functions and application. * Recursive functions. * Initialization code. * Declarations and definitions. *********************************************************************** * ML Helpers * -*- * Local Variables: * Caml-master: "compile" * End: * -*-
doc <:doc< @spelling{CPS IR} @module[M_ir] This module defines the intermediate language for the @emph{M} language. Here is the abstract syntax: @begin[verbatim] v ::= i (integers) | b (booleans) | v (variables) | fun v -> e (functions) | (v1, v2) (pairs) a ::= i (integers) | b (booleans) | v (variables) | a1 op a2 (binary operation) | fun x -> e (unnamed functions) e ::= let v = a in e (LetAtom) | f(a) (TailCall) | if a then e1 else e2 (Conditional) | let v = a1.[a2] in e (Subscripting) | a1.[a2] <- a3; e (Assignment) These are eliminated during CPS | let v = f(a) in e (Function application) | return a @end[verbatim] A program is a set of function definitions and an program expressed in a sequent. Each function must be declared, and defined separately. @docoff ---------------------------------------------------------------- @begin[license] Copyright (C) 2003 Jason Hickey, Caltech 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 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Jason Hickey @email{} @end[license] >> doc <:doc< @parents Modules in @MetaPRL are organized in a theory hierarchy. Each theory module extends its parent theories. In this case, the @tt[M_ir] module extends base theories that define generic proof automation. >> extends Base_theory doc docoff open Refiner.Refiner.Term open Refiner.Refiner.TermOp doc <:doc< @terms The IR defines several binary operators for arithmetic and Boolean operations. >> declare AddOp declare SubOp declare MulOp declare DivOp declare LtOp declare LeOp declare EqOp declare NeqOp declare GeOp declare GtOp doc <:doc< @modsubsection{Atoms} Atoms represent expressions that are values: integers, variables, binary operations on atoms, and functions. @tt[AtomFun] is a lambda-abstraction, and @tt[AtomFunVar] is the projection of a function from a recursive function definition (defined below). >> declare AtomFalse declare AtomTrue declare AtomInt[i:n] declare AtomBinop{'op; 'a1; 'a2} declare AtomRelop{'op; 'a1; 'a2} declare AtomFun{x. 'e['x]} declare AtomVar{'v} declare AtomFunVar{'R; 'v} doc <:doc< @modsubsection{Expressions} General expressions are not values. There are several simple kinds of expressions, for conditionals, allocation, function calls, and array operations. >> declare LetAtom{'a; v. 'e['v]} declare If{'a; 'e1; 'e2} declare ArgNil declare ArgCons{'a; 'rest} declare TailCall{'f; 'args} declare Length[i:n] declare AllocTupleNil declare AllocTupleCons{'a; 'rest} declare LetTuple{'length; 'tuple; v. 'e['v]} declare LetSubscript{'a1; 'a2; v. 'e['v]} declare SetSubscript{'a1; 'a2; 'a3; 'e} doc <:doc< Reserve statements are used to specify how much memory may be allocated in a function body. The M_reserve module defines an explicit phase that calculates memory usage and adds reserve statements. In the << Reserve[words:n]{'args; 'e} >> expressions, the @it[words] constant defines how much memory is to be reserved; the @it[args] defines the set of live variables (this information is used by the garbage collector), and @it[e] is the nested expression that performs the allocation. >> declare Reserve[words:n]{'e} declare Reserve[words:n]{'args; 'e} declare ReserveCons{'a; 'rest} declare ReserveNil doc <:doc< @tt[LetApply], @tt[Return] are eliminated during CPS conversion. @tt[LetClosure] is like @tt[LetApply], but it represents a partial application. >> declare LetApply{'f; 'a; v. 'e['v]} declare LetClosure{'a1; 'a2; f. 'e['f]} declare Return{'a} doc <:doc< This is the most problematic part of the description so far . This documentation discusses two possible approaches . This documentation discusses two possible approaches. *) @modsubsection{Recursive values} We need some way to represent mutually recursive functions. The normal way to do this is to define a single recursive function, and use a switch to split the different parts. For this purpose, we define a fixpoint over a record of functions. For example, suppose we define two mutually recursive functions $f$ and $g$: @begin[verbatim] let r2 = fix{r1. record{ field["f"]{lambda{x. (r1.g)(x)}}; field["g"]{lambda{x. (r1.f)(x)}}}} in r2.f(1) @end[verbatim] >> declare LetRec{R1. 'e1['R1]; R2. 'e2['R2]} doc <:doc< The following terms define the set of tagged fields used in the record definition. We require that all the fields be functions. The record construction is recursive. The @tt[Label] term is used for field tags; the @tt[FunDef] defines a new field in the record; and the @tt[EndDef] term terminates the record fields. >> declare Fields{'fields} declare Label[tag:s] declare FunDef{'label; 'exp; 'rest} declare EndDef doc <:doc< To simplify the presentation, we usually project the record fields before each of the field branches so that we can treat functions as if they were variables. >> declare LetFun{'R; 'label; f. 'e['f]} doc <:doc< Include a term representing initialization code. >> declare Initialize{'e} doc <:doc< @modsubsection{Program sequent representation} Programs are represented as sequents: <<sequent{ <declarations>; <definitions> >- exp }>> For now the language is untyped, so each declaration has the form @tt["v = exp"]. A definition is an equality judgment. >> declare exp declare def{'v; 'e} declare compilable{'e} doc docoff prec prec_var prec prec_mul prec prec_add prec prec_rel prec prec_if prec prec_fun prec prec_let prec prec_comma prec prec_compilable prec prec_mul < prec_var prec prec_add < prec_mul prec prec_rel < prec_add prec prec_let < prec_rel prec prec_if < prec_let prec prec_fun < prec_if prec prec_comma < prec_fun prec prec_compilable < prec_comma declare xlet : Dform declare xin : Dform dform xlet_df : xlet = bf["let"] dform xin_df : xin = bf["in"] dform atom_false_df : AtomFalse = `"false" dform atom_false_df : AtomTrue = `"true" dform atom_int_df : AtomInt[i:n] = `"#" slot[i:n] dform atom_var_df : AtomVar{'v} = Mpsymbols!downarrow slot{'v} dform atom_fun_var_df : parens :: "prec"[prec_var] :: AtomFunVar{'R; 'v} = slot{'R} `"." slot{'v} dform atom_binop_add_df : parens :: "prec"[prec_add] :: AtomBinop{AddOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"+ " slot["le"]{'e2} dform atom_binop_sub_df : parens :: "prec"[prec_add] :: AtomBinop{SubOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"- " slot["le"]{'e2} dform atom_binop_mul_df : parens :: "prec"[prec_mul] :: AtomBinop{MulOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"* " slot["le"]{'e2} dform atom_binop_div_df : parens :: "prec"[prec_mul] :: AtomBinop{DivOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"/ " slot["le"]{'e2} dform atom_binop_lt_df : parens :: "prec"[prec_rel] :: AtomRelop{LtOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"< " slot["le"]{'e2} dform atom_binop_le_df : parens :: "prec"[prec_rel] :: AtomRelop{LeOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!le `" " slot["le"]{'e2} dform atom_binop_gt_df : parens :: "prec"[prec_rel] :: AtomRelop{GtOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"> " slot["le"]{'e2} dform atom_binop_ge_df : parens :: "prec"[prec_rel] :: AtomRelop{GeOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!ge `" " slot["le"]{'e2} dform atom_binop_eq_df : parens :: "prec"[prec_rel] :: AtomRelop{EqOp; 'e1; 'e2} = slot["lt"]{'e1} " " `"= " slot["le"]{'e2} dform atom_binop_neq_df : parens :: "prec"[prec_rel] :: AtomRelop{NeqOp; 'e1; 'e2} = slot["lt"]{'e1} " " Mpsymbols!neq `" " slot["le"]{'e2} General / relop dform atom_binop_gen_df : parens :: "prec"[prec_rel] :: AtomRelop{'op; 'e1; 'e2} = slot["lt"]{'e1} `" " slot{'op} `" " slot["le"]{'e2} dform atom_binop_gen_df : parens :: "prec"[prec_rel] :: AtomBinop{'op; 'e1; 'e2} = slot["lt"]{'e1} `" " slot{'op} `" " slot["le"]{'e2} dform atom_fun_df : parens :: "prec"[prec_fun] :: AtomFun{x. 'e} = szone pushm[3] Mpsymbols!lambda Mpsymbols!suba slot{'x} `"." hspace slot{'e} popm ezone dform exp_let_atom_df : parens :: "prec"[prec_let] :: LetAtom{'a; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" = "] slot{'a} `" " xin hspace slot["lt"]{'e} popm ezone dform exp_tailcall_df : parens :: "prec"[prec_let] :: TailCall{'f; 'args} = bf["tailcall "] slot{'f} `" " slot{'args} dform arg_cons_df1 : parens :: "prec"[prec_comma] :: ArgCons{'a1; ArgCons{'a2; 'rest}} = slot{'a1} `", " slot["lt"]{ArgCons{'a2; 'rest}} dform arg_cons_df2 : parens :: "prec"[prec_comma] :: ArgCons{'a; ArgNil} = slot{'a} dform arg_cons_df2 : parens :: "prec"[prec_comma] :: ArgCons{'a; 'b} = slot{'a} `" :: " slot{'b} dform arg_nil_df : parens :: "prec"[prec_comma] :: ArgNil = `"" dform exp_if_df : parens :: "prec"[prec_if] :: except_mode[tex] :: If{'a; 'e1; 'e2} = szone pushm[0] pushm[3] bf["if"] `" " slot{'a} `" " bf["then"] hspace slot{'e1} popm hspace pushm[3] bf["else"] hspace slot{'e2} popm popm ezone TEX if dform exp_if_df : parens :: "prec"[prec_if] :: mode[tex] :: If{'a; 'e1; 'e2} = bf["if"] `" " slot{'a} `" " bf["then "] slot{'e1} `" " bf["else "] slot{'e2} dform reserve_df1 : parens :: "prec"[prec_let] :: Reserve[words:n]{'e} = bf["reserve "] slot[words:n] bf[" words in"] hspace slot["lt"]{'e} dform reserve_df2 : parens :: "prec"[prec_let] :: Reserve[words:n]{'args; 'e} = bf["reserve "] slot[words:n] bf[" words args "] slot{'args} bf[" in"] hspace slot["lt"]{'e} dform reserve_cons_df1 : parens :: "prec"[prec_comma] :: ReserveCons{'a1; ReserveCons{'a2; 'rest}} = slot{'a1} `", " slot["lt"]{ReserveCons{'a2; 'rest}} dform reserve_cons_df2 : parens :: "prec"[prec_comma] :: ReserveCons{'a; ArgNil} = slot{'a} dform reserve_nil_df : parens :: "prec"[prec_comma] :: ReserveNil = `"" doc <:doc< Sequent tag for the M language. >> declare sequent [sequent_arg] { Term : Term >- Term } : Judgment doc docoff dform sequent_arg_df: sequent_arg = subm declare default_extract dform default_extract_df : sequent { <H> >- default_extract } = `"" doc <:doc< @modsubsection{Subscripting.} Tuples are listed in reverse order. >> declare alloc_tuple{'l1; 'l2} : Dform declare alloc_tuple{'l} : Dform doc docoff dform length_df : Length[i:n] = slot[i:n] dform alloc_tuple_start_nil_df : AllocTupleNil = alloc_tuple{nil; AllocTupleNil} dform alloc_tuple_start_cons_df : AllocTupleCons{'a; 'rest} = alloc_tuple{nil; AllocTupleCons{'a; 'rest}} dform alloc_tuple_shift_df : alloc_tuple{'l; AllocTupleCons{'a; 'rest}} = alloc_tuple{cons{'a; 'l}; 'rest} dform alloc_tuple_start_df : alloc_tuple{'l; AllocTupleNil} = szone pushm[1] bf["("] alloc_tuple{'l} bf[")"] popm ezone dform alloc_tuple_start_df : alloc_tuple{'l; 'tl} = szone pushm[1] bf["("] alloc_tuple{'l} `" :: " slot{'tl} bf[")"] popm ezone dform alloc_tuple_nil_df : alloc_tuple{nil} = `"" dform alloc_tuple_cons_nil_df : alloc_tuple{cons{'a; nil}} = slot{'a} dform alloc_tuple_cons_cons_df : alloc_tuple{cons{'a1; cons{'a2; 'l}}} = slot{'a1} bf[","] hspace alloc_tuple{cons{'a2; 'l}} dform exp_let_tuple_df : parens :: "prec"[prec_let] :: LetTuple{'length; 'tuple; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" =[length = "] slot{'length} bf["] "] slot{'tuple} `" " xin hspace slot["lt"]{'e} popm ezone dform exp_subscript_df : parens :: "prec"[prec_let] :: LetSubscript{'a1; 'a2; v. 'e} = szone pushm[3] xlet `" " slot{'v} bf[" = "] slot{'a1} `".[" slot{'a2} `"] " xin hspace slot["lt"]{'e} popm ezone dform exp_set_subscript_df : parens :: "prec"[prec_let] :: SetSubscript{'a1; 'a2; 'a3; 'e} = slot{'a1} `".[" slot{'a2} `"] " leftarrow `" " slot{'a3} `";" hspace slot["lt"]{'e} dform exp_let_apply_df : parens :: "prec"[prec_let] :: LetApply{'f; 'a; v. 'e} = szone pushm[3] xlet bf[" apply "] slot{'v} bf[" = "] slot{'f} `"(" slot{'a} `") " xin hspace slot["lt"]{'e} popm ezone dform exp_let_closure_df : parens :: "prec"[prec_let] :: LetClosure{'f; 'a; v. 'e} = szone pushm[3] xlet bf[" closure "] slot{'v} bf[" = "] slot{'f} `"(" slot{'a} `") " xin hspace slot["lt"]{'e} popm ezone dform exp_return_df : Return{'a} = bf["return"] `"(" slot{'a} `")" dform let_rec_df : parens :: "prec"[prec_let] :: LetRec{R1. 'e1; R2. 'e2} = szone pushm[3] xlet bf[" rec "] slot{'R1} `"." hspace 'e1 popm ezone hspace slot{'R2} `"." xin hspace slot["lt"]{'e2} dform fields_df : parens :: "prec"[prec_let] :: Fields{'fields} = szone pushm[0] pushm[2] bf["{ "] slot["lt"]{'fields} popm hspace bf["}"] popm ezone dform fun_def_df : parens :: "prec"[prec_let] :: FunDef{'label; 'e; 'rest} = szone pushm[3] bf["fun "] slot{'label} `" =" hspace slot{'e} popm ezone hspace 'rest dform end_def_df : EndDef = `"" dform label_df : Label[s:s] = `"\"" slot[s:s] `"\"" dform let_fun_def : parens :: "prec"[prec_let] :: LetFun{'R; 'label; f. 'e} = szone pushm[3] xlet bf[" fun "] slot{'f} `" = " slot{'R} `"." slot{'label} `" " xin hspace slot["lt"]{'e} popm ezone dform initialize_df : parens :: "prec"[prec_let] :: Initialize{'e} = szone pushm[0] pushm[3] bf["initialization"] hspace slot{'e} popm hspace bf["end"] popm ezone dform exp_df : exp = bf["exp"] dform def_df : def{'v; 'e} = slot{'v} bf[" = "] slot{'e} dform compilable_df : "prec"[prec_compilable] :: compilable{'e} = szone pushm[0] pushm[3] bf["compilable"] hspace slot{'e} popm hspace bf["end"] popm ezone let fundef_term = << FunDef{'label; 'e; 'rest} >> let fundef_opname = opname_of_term fundef_term let is_fundef_term = is_dep0_dep0_dep0_term fundef_opname let dest_fundef_term = dest_dep0_dep0_dep0_term fundef_opname let mk_fundef_term = mk_dep0_dep0_dep0_term fundef_opname let letrec_term = << LetRec{R1. 'fields['R1]; R2. 'body['R2]} >> let letrec_opname = opname_of_term letrec_term let is_letrec_term = is_dep1_dep1_term letrec_opname let dest_letrec_term = dest_dep1_dep1_term letrec_opname let mk_letrec_term = mk_dep1_dep1_term letrec_opname
6a9900828d5260a68c03f631a85ac466ba718881afda7d5a4c175c159488d06d
tommaisey/aeon
tuple.scm
;; (define-record-type duple ;; (fields p q)) ;; (srfi:define-record-type duple ( make - duple p q ) duple ? ( p duple - p ) ( q duple - q ) ) ;; fst :: (a, b) -> a ;; (define fst car) snd : : ( a , b ) - > b ( define ) ;; (,) :: a -> b -> (a, b) ( define cons ) ;; curry :: ((a, b) -> c) -> a -> b -> c (define curry (lambda (f) (lambda (x y) (f (cons x y))))) ;; uncurry :: (a -> b -> c) -> (a, b) -> c (define uncurry (lambda (f) (lambda (c) (f (car c) (cdr c)))))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rhs/src/data/tuple.scm
scheme
(define-record-type duple (fields p q)) (srfi:define-record-type duple fst :: (a, b) -> a (define fst car) (,) :: a -> b -> (a, b) curry :: ((a, b) -> c) -> a -> b -> c uncurry :: (a -> b -> c) -> (a, b) -> c
( make - duple p q ) duple ? ( p duple - p ) ( q duple - q ) ) snd : : ( a , b ) - > b ( define ) ( define cons ) (define curry (lambda (f) (lambda (x y) (f (cons x y))))) (define uncurry (lambda (f) (lambda (c) (f (car c) (cdr c)))))
120a0249aeb70ee9dfe17dabc34c706f62a30d64025e2e704416b2f1b199d5e2
ghcjs/jsaddle-dom
SVGException.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGException (toString, toString_, pattern SVG_WRONG_TYPE_ERR, pattern SVG_INVALID_VALUE_ERR, pattern SVG_MATRIX_NOT_INVERTABLE, getCode, getName, getMessage, SVGException(..), gTypeSVGException) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGException.toString Mozilla SVGException.toString documentation > toString :: (MonadDOM m, FromJSString result) => SVGException -> m result toString self = liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGException.toString Mozilla SVGException.toString documentation > toString_ :: (MonadDOM m) => SVGException -> m () toString_ self = liftDOM (void (self ^. jsf "toString" ())) pattern SVG_WRONG_TYPE_ERR = 0 pattern SVG_INVALID_VALUE_ERR = 1 pattern SVG_MATRIX_NOT_INVERTABLE = 2 | < -US/docs/Web/API/SVGException.code Mozilla SVGException.code documentation > getCode :: (MonadDOM m) => SVGException -> m Word getCode self = liftDOM (round <$> ((self ^. js "code") >>= valToNumber)) | < -US/docs/Web/API/SVGException.name Mozilla SVGException.name documentation > getName :: (MonadDOM m, FromJSString result) => SVGException -> m result getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGException.message Mozilla SVGException.message documentation > getMessage :: (MonadDOM m, FromJSString result) => SVGException -> m result getMessage self = liftDOM ((self ^. js "message") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGException.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGException (toString, toString_, pattern SVG_WRONG_TYPE_ERR, pattern SVG_INVALID_VALUE_ERR, pattern SVG_MATRIX_NOT_INVERTABLE, getCode, getName, getMessage, SVGException(..), gTypeSVGException) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGException.toString Mozilla SVGException.toString documentation > toString :: (MonadDOM m, FromJSString result) => SVGException -> m result toString self = liftDOM ((self ^. jsf "toString" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGException.toString Mozilla SVGException.toString documentation > toString_ :: (MonadDOM m) => SVGException -> m () toString_ self = liftDOM (void (self ^. jsf "toString" ())) pattern SVG_WRONG_TYPE_ERR = 0 pattern SVG_INVALID_VALUE_ERR = 1 pattern SVG_MATRIX_NOT_INVERTABLE = 2 | < -US/docs/Web/API/SVGException.code Mozilla SVGException.code documentation > getCode :: (MonadDOM m) => SVGException -> m Word getCode self = liftDOM (round <$> ((self ^. js "code") >>= valToNumber)) | < -US/docs/Web/API/SVGException.name Mozilla SVGException.name documentation > getName :: (MonadDOM m, FromJSString result) => SVGException -> m result getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGException.message Mozilla SVGException.message documentation > getMessage :: (MonadDOM m, FromJSString result) => SVGException -> m result getMessage self = liftDOM ((self ^. js "message") >>= fromJSValUnchecked)
d14d5bf1bbf5e165c735ad36eeb5adb48723ffab978ce445a3ab0481acc804d0
Smoltbob/Caml-Est-Belle
tapp.ml
(*let rec phi a b = let rec psi x = x in psi in *) (phi 1 2) (3+4) 5
null
https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/frontend/tests/tapp.ml
ocaml
let rec phi a b = let rec psi x = x in psi in
(phi 1 2) (3+4) 5
3a736047d6a7074b9c2b5f120a258c80149232981f95084e8f4423f8efe0629b
ruricolist/serapeum
octets.lisp
(in-package :serapeum.tests) (def-suite octets :in serapeum) (in-suite octets) ;; (test unoctets ;; (for-all ((n (a-fixnum))) ;; (is (= (unoctets (octets n)) n))))
null
https://raw.githubusercontent.com/ruricolist/serapeum/d98b4863d7cdcb8a1ed8478cc44ab41bdad5635b/tests/octets.lisp
lisp
(test unoctets (for-all ((n (a-fixnum))) (is (= (unoctets (octets n)) n))))
(in-package :serapeum.tests) (def-suite octets :in serapeum) (in-suite octets)
76714ab212085ad0edb8ebbf08e30ef44d70d5ac07617094c94ecea2adc84ac4
reasonml-old/BetterErrors
warning_OptionalArgumentNotErased_2.ml
let eat aNumber ?(withFork=true) = "Hello, world!" let () = print_endline (eat 1 ~withFork:false)
null
https://raw.githubusercontent.com/reasonml-old/BetterErrors/d439b92bfe377689c38fded5d8aa2b151133f25d/tests/warning_OptionalArgumentNotErased/warning_OptionalArgumentNotErased_2.ml
ocaml
let eat aNumber ?(withFork=true) = "Hello, world!" let () = print_endline (eat 1 ~withFork:false)
c2c10a4d11ca438be7e10af6a61c2fcce09d6aba26ea5dbf325d5caa3caa35f8
sebastiaanvisser/ghc-goals
GhcGoals.hs
-- | This module contains a high level interface to the goals -- functionality. Given a file, it takes care of parsing, typechecking -- etc., producing type information on all the goals. module Development.GhcGoals ( goals , goalsWith , getGoals , getGoalsWith , pprGoals ) where import Control.Monad (liftM) import Data.List (sortBy) import Data.Ord (comparing) import GHC ( defaultErrorHandler , depanal , dopt , DynFlag(Opt_PrintExplicitForalls) , getSessionDynFlags , ghcLink , GhcLink(..) , guessTarget , handleSourceError , hscTarget , HscTarget(..) , load , LoadHowMuch(..) , parseModule , printExceptionAndWarnings , runGhc , setSessionDynFlags , setTargets , SuccessFlag(..) , typecheckModule ) import GHC.Paths (libdir) import DynFlags (defaultDynFlags) import MonadUtils (liftIO) import Outputable ( (<+>) , dcolon , empty , hsep , nest , neverQualify , parens , ppr , pprWithCommas , showSDocForUser , text ) import PprTyThing (pprTypeForUser) import Development.GhcGoals.Collector -- | Analyze a file, print type information for all 'undefined's goals :: FilePath -> IO () goals = goalsWith ["undefined"] -- | Analyze a file, print type information for all variables with the -- specified names. goalsWith :: [String] -> FilePath -> IO () goalsWith goals file = getGoalsWith goals file >>= pprGoals -- | Analyze a file, returning type information for all 'undefined's. getGoals :: FilePath -> IO [GoalInfo] getGoals = getGoalsWith ["undefined"] -- | Analyze a file, returning type information for all variables with -- the specified names. getGoalsWith :: [String] -> FilePath -> IO [GoalInfo] getGoalsWith goals file = defaultErrorHandler defaultDynFlags $ runGhc (Just libdir) $ handleSourceError errorHandler $ do dflags <- getSessionDynFlags setSessionDynFlags $ dflags { ghcLink = LinkInMemory , hscTarget = HscNothing -- Interpreted } target <- guessTarget file Nothing setTargets [target] success <- load LoadAllTargets case success of Succeeded -> do (md:mds) <- depanal [] True pm <- parseModule md tcm <- typecheckModule pm return . sortBy (comparing snd3) $ goalsFor tcm goals Failed -> return [] where errorHandler x = printExceptionAndWarnings x >> return [] snd3 :: (a, b, c) -> b snd3 (a, b, c) = b -- | Pretty print information on goals in a style similar to GHCi. pprGoals :: [GoalInfo] -> IO () pprGoals goals = do defaultErrorHandler defaultDynFlags $ runGhc (Just libdir) $ do dflags <- getSessionDynFlags let pefas = dopt Opt_PrintExplicitForalls dflags showWrap (n, s, ts) = showSDocForUser neverQualify $ hsep [ text n , nest 2 (dcolon <+> pprTypeSpecForUser pefas ts) , text " -- Used in" , ppr s] liftIO $ mapM_ (putStrLn . showWrap) goals pprTypeSpecForUser pefas (ts, ty) = (if null ts then empty else parens (pprWithCommas (pprTypeForUser pefas) ts) <+> text "=>") <+> pprTypeForUser pefas ty
null
https://raw.githubusercontent.com/sebastiaanvisser/ghc-goals/cf256c99c4b7e3b569bab3e6c10f0903a7c1eac4/src/Development/GhcGoals.hs
haskell
| This module contains a high level interface to the goals functionality. Given a file, it takes care of parsing, typechecking etc., producing type information on all the goals. | Analyze a file, print type information for all 'undefined's | Analyze a file, print type information for all variables with the specified names. | Analyze a file, returning type information for all 'undefined's. | Analyze a file, returning type information for all variables with the specified names. Interpreted | Pretty print information on goals in a style similar to GHCi.
module Development.GhcGoals ( goals , goalsWith , getGoals , getGoalsWith , pprGoals ) where import Control.Monad (liftM) import Data.List (sortBy) import Data.Ord (comparing) import GHC ( defaultErrorHandler , depanal , dopt , DynFlag(Opt_PrintExplicitForalls) , getSessionDynFlags , ghcLink , GhcLink(..) , guessTarget , handleSourceError , hscTarget , HscTarget(..) , load , LoadHowMuch(..) , parseModule , printExceptionAndWarnings , runGhc , setSessionDynFlags , setTargets , SuccessFlag(..) , typecheckModule ) import GHC.Paths (libdir) import DynFlags (defaultDynFlags) import MonadUtils (liftIO) import Outputable ( (<+>) , dcolon , empty , hsep , nest , neverQualify , parens , ppr , pprWithCommas , showSDocForUser , text ) import PprTyThing (pprTypeForUser) import Development.GhcGoals.Collector goals :: FilePath -> IO () goals = goalsWith ["undefined"] goalsWith :: [String] -> FilePath -> IO () goalsWith goals file = getGoalsWith goals file >>= pprGoals getGoals :: FilePath -> IO [GoalInfo] getGoals = getGoalsWith ["undefined"] getGoalsWith :: [String] -> FilePath -> IO [GoalInfo] getGoalsWith goals file = defaultErrorHandler defaultDynFlags $ runGhc (Just libdir) $ handleSourceError errorHandler $ do dflags <- getSessionDynFlags setSessionDynFlags $ dflags { ghcLink = LinkInMemory } target <- guessTarget file Nothing setTargets [target] success <- load LoadAllTargets case success of Succeeded -> do (md:mds) <- depanal [] True pm <- parseModule md tcm <- typecheckModule pm return . sortBy (comparing snd3) $ goalsFor tcm goals Failed -> return [] where errorHandler x = printExceptionAndWarnings x >> return [] snd3 :: (a, b, c) -> b snd3 (a, b, c) = b pprGoals :: [GoalInfo] -> IO () pprGoals goals = do defaultErrorHandler defaultDynFlags $ runGhc (Just libdir) $ do dflags <- getSessionDynFlags let pefas = dopt Opt_PrintExplicitForalls dflags showWrap (n, s, ts) = showSDocForUser neverQualify $ hsep [ text n , nest 2 (dcolon <+> pprTypeSpecForUser pefas ts) , text " -- Used in" , ppr s] liftIO $ mapM_ (putStrLn . showWrap) goals pprTypeSpecForUser pefas (ts, ty) = (if null ts then empty else parens (pprWithCommas (pprTypeForUser pefas) ts) <+> text "=>") <+> pprTypeForUser pefas ty
1029bdb2a92fec8f9d478258abc4156962aa63338608fa0c6e99b35e0a835d93
Octachron/codept
b.ml
module A = A
null
https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/tests/complex/alias_values/b.ml
ocaml
module A = A
de9267d4ed94036a2038e6e5f5751cbddcf9c30f30f920c2928e8f48d18a72ec
jkvor/emysql
emysql_conn_mgr.erl
Copyright ( c ) 2009 < > < > %% %% 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. -module(emysql_conn_mgr). -behaviour(gen_server). -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). -export([terminate/2, code_change/3]). -export([pools/0, waiting/0, add_pool/1, remove_pool/1, add_connections/2, remove_connections/2, lock_connection/1, wait_for_connection/1, unlock_connection/1, replace_connection/2, find_pool/3]). -include("emysql.hrl"). -record(state, {pools, waiting=queue:new()}). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). pools() -> gen_server:call(?MODULE, pools, infinity). waiting() -> gen_server:call(?MODULE, waiting, infinity). add_pool(Pool) -> do_gen_call({add_pool, Pool}). remove_pool(PoolId) -> do_gen_call({remove_pool, PoolId}). add_connections(PoolId, Conns) when is_atom(PoolId), is_list(Conns) -> do_gen_call({add_connections, PoolId, Conns}). remove_connections(PoolId, Num) when is_atom(PoolId), is_integer(Num) -> do_gen_call({remove_connections, PoolId, Num}). lock_connection(PoolId) when is_atom(PoolId) -> do_gen_call({lock_connection, PoolId}). wait_for_connection(PoolId) when is_atom(PoolId) -> %% try to lock a connection. if no connections are available then %% wait to be notified of the next available connection case lock_connection(PoolId) of unavailable -> gen_server:call(?MODULE, start_wait, infinity), receive {connection, Connection} -> Connection after lock_timeout() -> exit(connection_lock_timeout) end; Connection -> Connection end. unlock_connection(Connection) -> do_gen_call({unlock_connection, Connection}). replace_connection(OldConn, NewConn) -> do_gen_call({replace_connection, OldConn, NewConn}). %% the stateful loop functions of the gen_server never %% want to call exit/1 because it would crash the gen_server. %% instead we want to return error tuples and then throw %% the error once outside of the gen_server process do_gen_call(Msg) -> case gen_server:call(?MODULE, Msg, infinity) of {error, Reason} -> exit(Reason); Result -> Result end. %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> Pools = initialize_pools(), Pools1 = [emysql_conn:open_connections(Pool) || Pool <- Pools], {ok, #state{pools=Pools1}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call(pools, _From, State) -> {reply, State#state.pools, State}; handle_call(waiting, _From, State) -> {reply, State#state.waiting, State}; handle_call({add_pool, Pool}, _From, State) -> case find_pool(Pool#pool.pool_id, State#state.pools, []) of {_, _} -> {reply, {error, pool_already_exists}, State}; undefined -> {reply, ok, State#state{pools = [Pool|State#state.pools]}} end; handle_call({remove_pool, PoolId}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> {reply, Pool, State#state{pools=OtherPools}}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call({add_connections, PoolId, Conns}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> OtherConns = Pool#pool.available, State1 = State#state{ pools = [Pool#pool{available = queue:join(queue:from_list(Conns), OtherConns)}|OtherPools] }, {reply, ok, State1}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call({remove_connections, PoolId, Num}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> case Num > queue:len(Pool#pool.available) of true -> State1 = State#state{pools = [Pool#pool{available = queue:new()}]}, {reply, queue:to_list(Pool#pool.available), State1}; false -> {Conns, OtherConns} = queue:split(Num, Pool#pool.available), State1 = State#state{pools = [Pool#pool{available = OtherConns}|OtherPools]}, {reply, queue:to_list(Conns), State1} end; undefined -> {reply, {error, pool_not_found}, State} end; handle_call(start_wait, {From, _Mref}, State) -> %% place to calling pid at the end of the waiting queue State1 = State#state{ waiting = queue:in(From, State#state.waiting) }, {reply, ok, State1}; handle_call({lock_connection, PoolId}, _From, State) -> find the next available connection in the pool identified by PoolId case find_next_connection_in_pool(State#state.pools, PoolId) of [Pool, OtherPools, Conn, OtherConns] -> NewConn = Conn#connection{locked_at=lists:nth(2, tuple_to_list(now()))}, Locked = gb_trees:enter(NewConn#connection.id, NewConn, Pool#pool.locked), State1 = State#state{pools = [Pool#pool{available=OtherConns, locked=Locked}|OtherPools]}, {reply, NewConn, State1}; Other -> {reply, Other, State} end; handle_call({unlock_connection, Connection}, _From, State) -> {Result, State1} = pass_connection_to_waiting_pid(State, Connection, State#state.waiting), {reply, Result, State1}; handle_call({replace_connection, OldConn, NewConn}, _From, State) -> %% if an error occurs while doing work over a connection then %% the connection must be closed and a new one created in its %% place. The calling process is responsible for creating the %% new connection, closing the old one and replacing it in state. %% This function expects a new, available connection to be %% passed in to serve as the replacement for the old one. case find_pool(OldConn#connection.pool_id, State#state.pools, []) of {Pool, OtherPools} -> Pool1 = Pool#pool{ available = queue:in(NewConn, Pool#pool.available), locked = gb_trees:delete_any(OldConn#connection.id, Pool#pool.locked) }, {reply, ok, State#state{pools=[Pool1|OtherPools]}}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call(_, _From, State) -> {reply, {error, invalid_call}, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- initialize_pools() -> %% if the emysql application values are not present in the config %% file we will initialize and empty set of pools. Otherwise, the %% values defined in the config are used to initialize the state. case application:get_env(emysql, pools) of undefined -> []; {ok, Pools} -> [begin #pool{ pool_id = PoolId, size = proplists:get_value(size, Props, 1), user = proplists:get_value(user, Props), password = proplists:get_value(password, Props), host = proplists:get_value(host, Props), port = proplists:get_value(port, Props), database = proplists:get_value(database, Props), encoding = proplists:get_value(encoding, Props) } end || {PoolId, Props} <- Pools] end. find_pool(_, [], _) -> undefined; find_pool(PoolId, [#pool{pool_id = PoolId} = Pool|Tail], OtherPools) -> {Pool, lists:append(OtherPools, Tail)}; find_pool(PoolId, [Pool|Tail], OtherPools) -> find_pool(PoolId, Tail, [Pool|OtherPools]). find_next_connection_in_pool(Pools, PoolId) -> case find_pool(PoolId, Pools, []) of {Pool, OtherPools} -> case queue:out(Pool#pool.available) of {{value, Conn}, OtherConns} -> [Pool, OtherPools, Conn, OtherConns]; {empty, _} -> unavailable end; undefined -> {error, pool_not_found} end. pass_connection_to_waiting_pid(State, Connection, Waiting) -> %% check if any processes are waiting for a connection case queue:is_empty(Waiting) of true -> %% if no processes are waiting then unlock the connection case find_pool(Connection#connection.pool_id, State#state.pools, []) of {Pool, OtherPools} -> %% find connection in locked tree case gb_trees:lookup(Connection#connection.id, Pool#pool.locked) of {value, Conn} -> %% add it to the available queue and remove from locked tree Pool1 = Pool#pool{ available = queue:in(Conn#connection{locked_at=undefined}, Pool#pool.available), locked = gb_trees:delete_any(Connection#connection.id, Pool#pool.locked) }, {ok, State#state{pools = [Pool1|OtherPools]}}; none -> {{error, connection_not_found}, State} end; undefined -> {{error, pool_not_found}, State} end; false -> %% if the waiting queue is not empty then remove the head of %% the queue and check if that process is still waiting %% for a connection. If so, send the connection. Regardless, %% update the queue in state once the head has been removed. {{value, Pid}, Waiting1} = queue:out(Waiting), case erlang:process_info(Pid, current_function) of {current_function,{emysql_conn_mgr,wait_for_connection,1}} -> erlang:send(Pid, {connection, Connection}), {ok, State#state{waiting = Waiting1}}; _ -> pass_connection_to_waiting_pid(State, Connection, Waiting1) end end. lock_timeout() -> case application:get_env(emysql, lock_timeout) of undefined -> ?LOCK_TIMEOUT; {ok, Timeout} -> Timeout end.
null
https://raw.githubusercontent.com/jkvor/emysql/6f72bc729200024f5940a2c11f15afd2af6f3d11/src/emysql_conn_mgr.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be 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. ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- try to lock a connection. if no connections are available then wait to be notified of the next available connection the stateful loop functions of the gen_server never want to call exit/1 because it would crash the gen_server. instead we want to return error tuples and then throw the error once outside of the gen_server process ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- place to calling pid at the end of the waiting queue if an error occurs while doing work over a connection then the connection must be closed and a new one created in its place. The calling process is responsible for creating the new connection, closing the old one and replacing it in state. This function expects a new, available connection to be passed in to serve as the replacement for the old one. -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- if the emysql application values are not present in the config file we will initialize and empty set of pools. Otherwise, the values defined in the config are used to initialize the state. check if any processes are waiting for a connection if no processes are waiting then unlock the connection find connection in locked tree add it to the available queue and remove from locked tree if the waiting queue is not empty then remove the head of the queue and check if that process is still waiting for a connection. If so, send the connection. Regardless, update the queue in state once the head has been removed.
Copyright ( c ) 2009 < > < > files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , -module(emysql_conn_mgr). -behaviour(gen_server). -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2]). -export([terminate/2, code_change/3]). -export([pools/0, waiting/0, add_pool/1, remove_pool/1, add_connections/2, remove_connections/2, lock_connection/1, wait_for_connection/1, unlock_connection/1, replace_connection/2, find_pool/3]). -include("emysql.hrl"). -record(state, {pools, waiting=queue:new()}). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). pools() -> gen_server:call(?MODULE, pools, infinity). waiting() -> gen_server:call(?MODULE, waiting, infinity). add_pool(Pool) -> do_gen_call({add_pool, Pool}). remove_pool(PoolId) -> do_gen_call({remove_pool, PoolId}). add_connections(PoolId, Conns) when is_atom(PoolId), is_list(Conns) -> do_gen_call({add_connections, PoolId, Conns}). remove_connections(PoolId, Num) when is_atom(PoolId), is_integer(Num) -> do_gen_call({remove_connections, PoolId, Num}). lock_connection(PoolId) when is_atom(PoolId) -> do_gen_call({lock_connection, PoolId}). wait_for_connection(PoolId) when is_atom(PoolId) -> case lock_connection(PoolId) of unavailable -> gen_server:call(?MODULE, start_wait, infinity), receive {connection, Connection} -> Connection after lock_timeout() -> exit(connection_lock_timeout) end; Connection -> Connection end. unlock_connection(Connection) -> do_gen_call({unlock_connection, Connection}). replace_connection(OldConn, NewConn) -> do_gen_call({replace_connection, OldConn, NewConn}). do_gen_call(Msg) -> case gen_server:call(?MODULE, Msg, infinity) of {error, Reason} -> exit(Reason); Result -> Result end. { ok , State , Timeout } | init([]) -> Pools = initialize_pools(), Pools1 = [emysql_conn:open_connections(Pool) || Pool <- Pools], {ok, #state{pools=Pools1}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(pools, _From, State) -> {reply, State#state.pools, State}; handle_call(waiting, _From, State) -> {reply, State#state.waiting, State}; handle_call({add_pool, Pool}, _From, State) -> case find_pool(Pool#pool.pool_id, State#state.pools, []) of {_, _} -> {reply, {error, pool_already_exists}, State}; undefined -> {reply, ok, State#state{pools = [Pool|State#state.pools]}} end; handle_call({remove_pool, PoolId}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> {reply, Pool, State#state{pools=OtherPools}}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call({add_connections, PoolId, Conns}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> OtherConns = Pool#pool.available, State1 = State#state{ pools = [Pool#pool{available = queue:join(queue:from_list(Conns), OtherConns)}|OtherPools] }, {reply, ok, State1}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call({remove_connections, PoolId, Num}, _From, State) -> case find_pool(PoolId, State#state.pools, []) of {Pool, OtherPools} -> case Num > queue:len(Pool#pool.available) of true -> State1 = State#state{pools = [Pool#pool{available = queue:new()}]}, {reply, queue:to_list(Pool#pool.available), State1}; false -> {Conns, OtherConns} = queue:split(Num, Pool#pool.available), State1 = State#state{pools = [Pool#pool{available = OtherConns}|OtherPools]}, {reply, queue:to_list(Conns), State1} end; undefined -> {reply, {error, pool_not_found}, State} end; handle_call(start_wait, {From, _Mref}, State) -> State1 = State#state{ waiting = queue:in(From, State#state.waiting) }, {reply, ok, State1}; handle_call({lock_connection, PoolId}, _From, State) -> find the next available connection in the pool identified by PoolId case find_next_connection_in_pool(State#state.pools, PoolId) of [Pool, OtherPools, Conn, OtherConns] -> NewConn = Conn#connection{locked_at=lists:nth(2, tuple_to_list(now()))}, Locked = gb_trees:enter(NewConn#connection.id, NewConn, Pool#pool.locked), State1 = State#state{pools = [Pool#pool{available=OtherConns, locked=Locked}|OtherPools]}, {reply, NewConn, State1}; Other -> {reply, Other, State} end; handle_call({unlock_connection, Connection}, _From, State) -> {Result, State1} = pass_connection_to_waiting_pid(State, Connection, State#state.waiting), {reply, Result, State1}; handle_call({replace_connection, OldConn, NewConn}, _From, State) -> case find_pool(OldConn#connection.pool_id, State#state.pools, []) of {Pool, OtherPools} -> Pool1 = Pool#pool{ available = queue:in(NewConn, Pool#pool.available), locked = gb_trees:delete_any(OldConn#connection.id, Pool#pool.locked) }, {reply, ok, State#state{pools=[Pool1|OtherPools]}}; undefined -> {reply, {error, pool_not_found}, State} end; handle_call(_, _From, State) -> {reply, {error, invalid_call}, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions initialize_pools() -> case application:get_env(emysql, pools) of undefined -> []; {ok, Pools} -> [begin #pool{ pool_id = PoolId, size = proplists:get_value(size, Props, 1), user = proplists:get_value(user, Props), password = proplists:get_value(password, Props), host = proplists:get_value(host, Props), port = proplists:get_value(port, Props), database = proplists:get_value(database, Props), encoding = proplists:get_value(encoding, Props) } end || {PoolId, Props} <- Pools] end. find_pool(_, [], _) -> undefined; find_pool(PoolId, [#pool{pool_id = PoolId} = Pool|Tail], OtherPools) -> {Pool, lists:append(OtherPools, Tail)}; find_pool(PoolId, [Pool|Tail], OtherPools) -> find_pool(PoolId, Tail, [Pool|OtherPools]). find_next_connection_in_pool(Pools, PoolId) -> case find_pool(PoolId, Pools, []) of {Pool, OtherPools} -> case queue:out(Pool#pool.available) of {{value, Conn}, OtherConns} -> [Pool, OtherPools, Conn, OtherConns]; {empty, _} -> unavailable end; undefined -> {error, pool_not_found} end. pass_connection_to_waiting_pid(State, Connection, Waiting) -> case queue:is_empty(Waiting) of true -> case find_pool(Connection#connection.pool_id, State#state.pools, []) of {Pool, OtherPools} -> case gb_trees:lookup(Connection#connection.id, Pool#pool.locked) of {value, Conn} -> Pool1 = Pool#pool{ available = queue:in(Conn#connection{locked_at=undefined}, Pool#pool.available), locked = gb_trees:delete_any(Connection#connection.id, Pool#pool.locked) }, {ok, State#state{pools = [Pool1|OtherPools]}}; none -> {{error, connection_not_found}, State} end; undefined -> {{error, pool_not_found}, State} end; false -> {{value, Pid}, Waiting1} = queue:out(Waiting), case erlang:process_info(Pid, current_function) of {current_function,{emysql_conn_mgr,wait_for_connection,1}} -> erlang:send(Pid, {connection, Connection}), {ok, State#state{waiting = Waiting1}}; _ -> pass_connection_to_waiting_pid(State, Connection, Waiting1) end end. lock_timeout() -> case application:get_env(emysql, lock_timeout) of undefined -> ?LOCK_TIMEOUT; {ok, Timeout} -> Timeout end.