_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
622e20affa6eac5796a631e40ece7f8268172a561a1b2a0c1f71cbae4a7247bc
Chris00/mesh
discover.ml
module C = Configurator.V1 let configure t = let system_libtriangle = (* Test the presence of the header file. *) C.c_test t ~link_flags:["-ltriangle"] "#include <triangle.h> int main() { return 0; }" in let ccopt, cclib = if system_libtriangle then (* System with libtriangle *) ["-DTRILIBRARY"; "-DEXTERNAL_TEST"; "-DANSI_DECLARATORS"; "-DLIBTRIANGLE"], ["-ltriangle"] else ["-DTRILIBRARY"; "-DEXTERNAL_TEST"; "-DANSI_DECLARATORS"], [] in C.Flags.write_sexp "c_flags.sexp" ccopt; C.Flags.write_sexp "c_library_flags.sexp" cclib let () = C.main ~name:"discover" configure
null
https://raw.githubusercontent.com/Chris00/mesh/a998a3d898b0013517a5f7f6078791b61e6a0fe2/triangle/config/discover.ml
ocaml
Test the presence of the header file. System with libtriangle
module C = Configurator.V1 let configure t = let system_libtriangle = C.c_test t ~link_flags:["-ltriangle"] "#include <triangle.h> int main() { return 0; }" in let ccopt, cclib = if system_libtriangle then ["-DTRILIBRARY"; "-DEXTERNAL_TEST"; "-DANSI_DECLARATORS"; "-DLIBTRIANGLE"], ["-ltriangle"] else ["-DTRILIBRARY"; "-DEXTERNAL_TEST"; "-DANSI_DECLARATORS"], [] in C.Flags.write_sexp "c_flags.sexp" ccopt; C.Flags.write_sexp "c_library_flags.sexp" cclib let () = C.main ~name:"discover" configure
d948ce33b01cfc0fd345bccb23c453ad849a77ea88e6b2250da5c9417fb7d11c
lthms/spatial-sway
workspace_id.ml
type t = Index of int | Name of string type workspace_id = t let decoder = let open Json_decoder in let open Syntax in let+ str = string in match int_of_string_opt str with Some id -> Index id | None -> Name str
null
https://raw.githubusercontent.com/lthms/spatial-sway/7f8430cb34007d71da9b2718027c9e2758ac59ad/lib/sway_ipc_types/workspace_id.ml
ocaml
type t = Index of int | Name of string type workspace_id = t let decoder = let open Json_decoder in let open Syntax in let+ str = string in match int_of_string_opt str with Some id -> Index id | None -> Name str
1c0053a8b66b5c56e70432bdbd92b33f3f93251e820e895ff916930da1516595
fragnix/fragnix
System.Posix.Directory.ByteString.hs
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/Directory/ByteString.hs" #-} # LINE 1 " System / Posix / Directory / ByteString.hsc " # # LANGUAGE CApiFFI # # LINE 2 " System / Posix / Directory / ByteString.hsc " # # LANGUAGE NondecreasingIndentation # # LINE 4 " System / Posix / Directory / ByteString.hsc " # {-# LANGUAGE Safe #-} # LINE 8 " System / Posix / Directory / ByteString.hsc " # ----------------------------------------------------------------------------- -- | Module : System . . Directory . ByteString Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : non-portable (requires POSIX) -- -- String-based POSIX directory support -- ----------------------------------------------------------------------------- # LINE 24 " System / Posix / Directory / ByteString.hsc " # hack copied from System . . Files # LINE 29 " System / Posix / Directory / ByteString.hsc " # module System.Posix.Directory.ByteString ( -- * Creating and removing directories createDirectory, removeDirectory, -- * Reading directories DirStream, openDirStream, readDirStream, rewindDirStream, closeDirStream, DirStreamOffset, # LINE 42 " System / Posix / Directory / ByteString.hsc " # tellDirStream, # LINE 44 " System / Posix / Directory / ByteString.hsc " # # LINE 45 " System / Posix / Directory / ByteString.hsc " # seekDirStream, # LINE 47 " System / Posix / Directory / ByteString.hsc " # -- * The working dirctory getWorkingDirectory, changeWorkingDirectory, changeWorkingDirectoryFd, ) where import System.IO.Error import System.Posix.Types import Foreign import Foreign.C import Data.ByteString.Char8 as BC import System.Posix.Directory.Common import System.Posix.ByteString.FilePath -- | @createDirectory dir mode@ calls @mkdir@ to -- create a new directory, @dir@, with permissions based on -- @mode@. createDirectory :: RawFilePath -> FileMode -> IO () createDirectory name mode = withFilePath name $ \s -> throwErrnoPathIfMinus1Retry_ "createDirectory" name (c_mkdir s mode) POSIX does n't allow ( ) to return , but it does on OS X ( # 5184 ) , so we need the Retry variant here . foreign import ccall unsafe "mkdir" c_mkdir :: CString -> CMode -> IO CInt -- | @openDirStream dir@ calls @opendir@ to obtain a -- directory stream for @dir@. openDirStream :: RawFilePath -> IO DirStream openDirStream name = withFilePath name $ \s -> do dirp <- throwErrnoPathIfNullRetry "openDirStream" name $ c_opendir s return (DirStream dirp) foreign import capi unsafe "HsUnix.h opendir" c_opendir :: CString -> IO (Ptr CDir) -- | @readDirStream dp@ calls @readdir@ to obtain the next directory entry ( @struct dirent@ ) for the open directory stream , and returns the @d_name@ member of that -- structure. readDirStream :: DirStream -> IO RawFilePath readDirStream (DirStream dirp) = alloca $ \ptr_dEnt -> loop ptr_dEnt where loop ptr_dEnt = do resetErrno r <- c_readdir dirp ptr_dEnt if (r == 0) then do dEnt <- peek ptr_dEnt if (dEnt == nullPtr) then return BC.empty else do entry <- (d_name dEnt >>= peekFilePath) c_freeDirEnt dEnt return entry else do errno <- getErrno if (errno == eINTR) then loop ptr_dEnt else do let (Errno eo) = errno if (eo == 0) then return BC.empty else throwErrno "readDirStream" -- traversing directories foreign import ccall unsafe "__hscore_readdir" c_readdir :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt foreign import ccall unsafe "__hscore_free_dirent" c_freeDirEnt :: Ptr CDirent -> IO () foreign import ccall unsafe "__hscore_d_name" d_name :: Ptr CDirent -> IO CString -- | @getWorkingDirectory@ calls @getcwd@ to obtain the name -- of the current working directory. getWorkingDirectory :: IO RawFilePath getWorkingDirectory = go (4096) # LINE 129 " System / Posix / Directory / ByteString.hsc " # where go bytes = do r <- allocaBytes bytes $ \buf -> do buf' <- c_getcwd buf (fromIntegral bytes) if buf' /= nullPtr then do s <- peekFilePath buf return (Just s) else do errno <- getErrno if errno == eRANGE -- we use Nothing to indicate that we should -- try again with a bigger buffer then return Nothing else throwErrno "getWorkingDirectory" maybe (go (2 * bytes)) return r foreign import ccall unsafe "getcwd" c_getcwd :: Ptr CChar -> CSize -> IO (Ptr CChar) -- | @changeWorkingDirectory dir@ calls @chdir@ to change -- the current working directory to @dir@. changeWorkingDirectory :: RawFilePath -> IO () changeWorkingDirectory path = modifyIOError (`ioeSetFileName` (BC.unpack path)) $ withFilePath path $ \s -> throwErrnoIfMinus1Retry_ "changeWorkingDirectory" (c_chdir s) foreign import ccall unsafe "chdir" c_chdir :: CString -> IO CInt removeDirectory :: RawFilePath -> IO () removeDirectory path = modifyIOError (`ioeSetFileName` BC.unpack path) $ withFilePath path $ \s -> throwErrnoIfMinus1Retry_ "removeDirectory" (c_rmdir s) foreign import ccall unsafe "rmdir" c_rmdir :: CString -> IO CInt
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/System.Posix.Directory.ByteString.hs
haskell
# LANGUAGE Haskell2010 # # LINE 1 "dist/dist-sandbox-261cd265/build/System/Posix/Directory/ByteString.hs" # # LANGUAGE Safe # --------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : provisional Portability : non-portable (requires POSIX) String-based POSIX directory support --------------------------------------------------------------------------- * Creating and removing directories * Reading directories * The working dirctory | @createDirectory dir mode@ calls @mkdir@ to create a new directory, @dir@, with permissions based on @mode@. | @openDirStream dir@ calls @opendir@ to obtain a directory stream for @dir@. | @readDirStream dp@ calls @readdir@ to obtain the structure. traversing directories | @getWorkingDirectory@ calls @getcwd@ to obtain the name of the current working directory. we use Nothing to indicate that we should try again with a bigger buffer | @changeWorkingDirectory dir@ calls @chdir@ to change the current working directory to @dir@.
# LINE 1 " System / Posix / Directory / ByteString.hsc " # # LANGUAGE CApiFFI # # LINE 2 " System / Posix / Directory / ByteString.hsc " # # LANGUAGE NondecreasingIndentation # # LINE 4 " System / Posix / Directory / ByteString.hsc " # # LINE 8 " System / Posix / Directory / ByteString.hsc " # Module : System . . Directory . ByteString Copyright : ( c ) The University of Glasgow 2002 # LINE 24 " System / Posix / Directory / ByteString.hsc " # hack copied from System . . Files # LINE 29 " System / Posix / Directory / ByteString.hsc " # module System.Posix.Directory.ByteString ( createDirectory, removeDirectory, DirStream, openDirStream, readDirStream, rewindDirStream, closeDirStream, DirStreamOffset, # LINE 42 " System / Posix / Directory / ByteString.hsc " # tellDirStream, # LINE 44 " System / Posix / Directory / ByteString.hsc " # # LINE 45 " System / Posix / Directory / ByteString.hsc " # seekDirStream, # LINE 47 " System / Posix / Directory / ByteString.hsc " # getWorkingDirectory, changeWorkingDirectory, changeWorkingDirectoryFd, ) where import System.IO.Error import System.Posix.Types import Foreign import Foreign.C import Data.ByteString.Char8 as BC import System.Posix.Directory.Common import System.Posix.ByteString.FilePath createDirectory :: RawFilePath -> FileMode -> IO () createDirectory name mode = withFilePath name $ \s -> throwErrnoPathIfMinus1Retry_ "createDirectory" name (c_mkdir s mode) POSIX does n't allow ( ) to return , but it does on OS X ( # 5184 ) , so we need the Retry variant here . foreign import ccall unsafe "mkdir" c_mkdir :: CString -> CMode -> IO CInt openDirStream :: RawFilePath -> IO DirStream openDirStream name = withFilePath name $ \s -> do dirp <- throwErrnoPathIfNullRetry "openDirStream" name $ c_opendir s return (DirStream dirp) foreign import capi unsafe "HsUnix.h opendir" c_opendir :: CString -> IO (Ptr CDir) next directory entry ( @struct dirent@ ) for the open directory stream , and returns the @d_name@ member of that readDirStream :: DirStream -> IO RawFilePath readDirStream (DirStream dirp) = alloca $ \ptr_dEnt -> loop ptr_dEnt where loop ptr_dEnt = do resetErrno r <- c_readdir dirp ptr_dEnt if (r == 0) then do dEnt <- peek ptr_dEnt if (dEnt == nullPtr) then return BC.empty else do entry <- (d_name dEnt >>= peekFilePath) c_freeDirEnt dEnt return entry else do errno <- getErrno if (errno == eINTR) then loop ptr_dEnt else do let (Errno eo) = errno if (eo == 0) then return BC.empty else throwErrno "readDirStream" foreign import ccall unsafe "__hscore_readdir" c_readdir :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt foreign import ccall unsafe "__hscore_free_dirent" c_freeDirEnt :: Ptr CDirent -> IO () foreign import ccall unsafe "__hscore_d_name" d_name :: Ptr CDirent -> IO CString getWorkingDirectory :: IO RawFilePath getWorkingDirectory = go (4096) # LINE 129 " System / Posix / Directory / ByteString.hsc " # where go bytes = do r <- allocaBytes bytes $ \buf -> do buf' <- c_getcwd buf (fromIntegral bytes) if buf' /= nullPtr then do s <- peekFilePath buf return (Just s) else do errno <- getErrno if errno == eRANGE then return Nothing else throwErrno "getWorkingDirectory" maybe (go (2 * bytes)) return r foreign import ccall unsafe "getcwd" c_getcwd :: Ptr CChar -> CSize -> IO (Ptr CChar) changeWorkingDirectory :: RawFilePath -> IO () changeWorkingDirectory path = modifyIOError (`ioeSetFileName` (BC.unpack path)) $ withFilePath path $ \s -> throwErrnoIfMinus1Retry_ "changeWorkingDirectory" (c_chdir s) foreign import ccall unsafe "chdir" c_chdir :: CString -> IO CInt removeDirectory :: RawFilePath -> IO () removeDirectory path = modifyIOError (`ioeSetFileName` BC.unpack path) $ withFilePath path $ \s -> throwErrnoIfMinus1Retry_ "removeDirectory" (c_rmdir s) foreign import ccall unsafe "rmdir" c_rmdir :: CString -> IO CInt
9c30b42d297acdd3979fad76873e847c064877535e75399a110fd5c8b95929ba
Frama-C/Frama-C-snapshot
warn.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 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 open Locations let warn_locals_escape is_block fundec k locals = let pretty_base = Base.pretty in let pretty_block fmt = Pretty_utils.pp_cond is_block fmt "a block of " in let sv = fundec.svar in Value_parameters.warning ~wkey:Value_parameters.wkey_locals_escaping ~current:true ~once:true "locals %a escaping the scope of %t%a through %a" Base.Hptset.pretty locals pretty_block Printer.pp_varinfo sv pretty_base k let warn_imprecise_lval_read lv loc contents = if Value_parameters.verbose_atleast 1 then let pretty_gm fmt s = let s = Base.SetLattice.(inject (O.remove Base.null s)) in Base.SetLattice.pretty fmt s in let pretty_param fmt param = match param with | Base.SetLattice.Top -> Format.fprintf fmt "is imprecise" | Base.SetLattice.Set s -> Format.fprintf fmt "is a garbled mix of %a" pretty_gm s in let pretty_param_b fmt param = match param with | Base.SetLattice.Top -> Format.fprintf fmt "The contents@ are imprecise" | Base.SetLattice.Set s -> Format.fprintf fmt "It contains@ a garbled@ mix@ of@ %a" pretty_gm s in let something_to_warn = match loc.loc with | Location_Bits.Top _ -> true | Location_Bits.Map _ -> match contents with | Location_Bytes.Top _ -> true | Location_Bytes.Map _ -> false in if something_to_warn then Value_parameters.result ~current:true ~once:true "@[<v>@[Reading left-value %a.@]@ %t%t%t@]" Printer.pp_lval lv (fun fmt -> match loc.loc with | Location_Bits.Top (param,o) when Origin.equal o Origin.top -> Format.fprintf fmt "@[The location %a.@]@ " pretty_param param | Location_Bits.Top (param,orig) -> Format.fprintf fmt "@[The location @[%a@]@ because of@ %a.@]@ " pretty_param param Origin.pretty orig | Location_Bits.Map _ -> match lv with | Mem _, _ -> Format.fprintf fmt "@[The location is @[%a@].@]@ " Location_Bits.pretty loc.loc | Var _, _ -> () ) (fun fmt -> match contents with | Location_Bytes.Top (param,o) when Origin.equal o Origin.top -> Format.fprintf fmt "@[%a.@]" pretty_param_b param | Location_Bytes.Top (param,orig) -> Format.fprintf fmt "@[%a@ because of@ %a.@]" pretty_param_b param Origin.pretty orig | Location_Bytes.Map _ -> ()) Value_util.pp_callstack (* Auxiliary function for [do_assign] below. When computing the result of [lv = exp], warn if the evaluation of [exp] results in an imprecision. [loc_lv] is the location pointed to by [lv]. [exp_val] is the part of the evaluation of [exp] that is imprecise. *) let warn_right_exp_imprecision lv loc_lv exp_val = match exp_val with | Location_Bytes.Top(_topparam,origin) -> Value_parameters.result ~once:true ~current:true "@[<v>@[Assigning imprecise value to %a%t.@]%a%t@]" Printer.pp_lval lv (fun fmt -> match lv with | (Mem _, _) -> Format.fprintf fmt "@ (pointing to %a)" (Locations.pretty_english ~prefix:false) loc_lv | (Var _, _) -> ()) (fun fmt org -> if not (Origin.is_top origin) then Format.fprintf fmt "@ @[The imprecision@ originates@ from@ %a@]" Origin.pretty org) origin Value_util.pp_callstack | Location_Bytes.Map _ -> () (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/domains/cvalue/warn.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. ************************************************************************ Auxiliary function for [do_assign] below. When computing the result of [lv = exp], warn if the evaluation of [exp] results in an imprecision. [loc_lv] is the location pointed to by [lv]. [exp_val] is the part of the evaluation of [exp] that is imprecise. Local Variables: compile-command: "make -C ../../../.." End:
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 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 open Locations let warn_locals_escape is_block fundec k locals = let pretty_base = Base.pretty in let pretty_block fmt = Pretty_utils.pp_cond is_block fmt "a block of " in let sv = fundec.svar in Value_parameters.warning ~wkey:Value_parameters.wkey_locals_escaping ~current:true ~once:true "locals %a escaping the scope of %t%a through %a" Base.Hptset.pretty locals pretty_block Printer.pp_varinfo sv pretty_base k let warn_imprecise_lval_read lv loc contents = if Value_parameters.verbose_atleast 1 then let pretty_gm fmt s = let s = Base.SetLattice.(inject (O.remove Base.null s)) in Base.SetLattice.pretty fmt s in let pretty_param fmt param = match param with | Base.SetLattice.Top -> Format.fprintf fmt "is imprecise" | Base.SetLattice.Set s -> Format.fprintf fmt "is a garbled mix of %a" pretty_gm s in let pretty_param_b fmt param = match param with | Base.SetLattice.Top -> Format.fprintf fmt "The contents@ are imprecise" | Base.SetLattice.Set s -> Format.fprintf fmt "It contains@ a garbled@ mix@ of@ %a" pretty_gm s in let something_to_warn = match loc.loc with | Location_Bits.Top _ -> true | Location_Bits.Map _ -> match contents with | Location_Bytes.Top _ -> true | Location_Bytes.Map _ -> false in if something_to_warn then Value_parameters.result ~current:true ~once:true "@[<v>@[Reading left-value %a.@]@ %t%t%t@]" Printer.pp_lval lv (fun fmt -> match loc.loc with | Location_Bits.Top (param,o) when Origin.equal o Origin.top -> Format.fprintf fmt "@[The location %a.@]@ " pretty_param param | Location_Bits.Top (param,orig) -> Format.fprintf fmt "@[The location @[%a@]@ because of@ %a.@]@ " pretty_param param Origin.pretty orig | Location_Bits.Map _ -> match lv with | Mem _, _ -> Format.fprintf fmt "@[The location is @[%a@].@]@ " Location_Bits.pretty loc.loc | Var _, _ -> () ) (fun fmt -> match contents with | Location_Bytes.Top (param,o) when Origin.equal o Origin.top -> Format.fprintf fmt "@[%a.@]" pretty_param_b param | Location_Bytes.Top (param,orig) -> Format.fprintf fmt "@[%a@ because of@ %a.@]" pretty_param_b param Origin.pretty orig | Location_Bytes.Map _ -> ()) Value_util.pp_callstack let warn_right_exp_imprecision lv loc_lv exp_val = match exp_val with | Location_Bytes.Top(_topparam,origin) -> Value_parameters.result ~once:true ~current:true "@[<v>@[Assigning imprecise value to %a%t.@]%a%t@]" Printer.pp_lval lv (fun fmt -> match lv with | (Mem _, _) -> Format.fprintf fmt "@ (pointing to %a)" (Locations.pretty_english ~prefix:false) loc_lv | (Var _, _) -> ()) (fun fmt org -> if not (Origin.is_top origin) then Format.fprintf fmt "@ @[The imprecision@ originates@ from@ %a@]" Origin.pretty org) origin Value_util.pp_callstack | Location_Bytes.Map _ -> ()
fe86094304581b92b3fdee3e51039fd34c193316bf6959239bf8cda61bba0000
Frama-C/Frama-C-snapshot
register.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 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 open Cil_datatype let rec pp_stmt fmt s = match s.skind with | Instr _ | Return _ | Goto _ | Break _ | Continue _ | TryFinally _ | TryExcept _ | Throw _ | TryCatch _ -> Printer.without_annot Printer.pp_stmt fmt s | If (e, _, _, _) -> Format.fprintf fmt "if(%a) <..>" Printer.pp_exp e | Switch (e, _, _, _) -> Format.fprintf fmt "switch(%a)<..>" Printer.pp_exp e | Loop _ -> Format.fprintf fmt "while (...)" | Block b -> begin match b.bstmts with | [] -> Format.fprintf fmt "<Block {}>" | s :: _ -> Format.fprintf fmt "<Block { %a }>" pp_stmt s end | UnspecifiedSequence _ -> Format.fprintf fmt "TODO" let print_results fmt a = Pretty_utils.pp_list (fun fmt s -> Format.fprintf fmt "@[<hov 2>%a (sid %d): %a@]" Printer.pp_location (Stmt.loc s) s.sid pp_stmt s ) fmt a let compute_from_stmt stmt = let kf = Kernel_function.find_englobing_kf stmt in let skip = Compute_impact.skip () in let reason = Options.Reason.get () in Compute_impact.stmts_impacted ~skip ~reason kf [stmt] let compute_from_nodes kf nodes = let skip = Compute_impact.skip () in let reason = Options.Reason.get () in let r = Compute_impact.nodes_impacted ~skip ~reason kf nodes in Pdg_aux.NS.fold (fun (n, _z) acc -> PdgTypes.NodeSet.add n acc) r PdgTypes.NodeSet.empty let compute_multiple_stmts skip kf ls = Options.debug "computing impact of statement(s) %a" (Pretty_utils.pp_list ~sep:",@ " Stmt.pretty_sid) ls; let reason = Options.Reason.get () in let res, _, _ = Compute_impact.nodes_impacted_by_stmts ~skip ~reason kf ls in let res_nodes = Compute_impact.result_to_nodes res in let res_stmts = Compute_impact.nodes_to_stmts res_nodes in if Options.Print.get () then begin Options.result "@[<v 2>@[impacted statements of stmt(s) %a are:@]@ %a@]" (Pretty_utils.pp_list ~sep:",@ " Stmt.pretty_sid) ls print_results res_stmts end; res_nodes (* Slice on the given list of stmts *) let slice (stmts:stmt list) = Options.feedback ~level:2 "beginning slicing"; let name = "impact slicing" in Slicing.Api.Project.reset_slicing (); let select sel ({ sid = id } as stmt) = let kf = Kernel_function.find_englobing_kf stmt in Options.debug ~level:3 "selecting sid %d (of %s)" id (Kernel_function.get_name kf); Slicing.Api.Select.select_stmt sel ~spare:false stmt kf in let sel = List.fold_left select Slicing.Api.Select.empty_selects stmts in Options.debug ~level:2 "applying slicing request"; Slicing.Api.Request.add_persistent_selection sel; Slicing.Api.Request.apply_all_internal (); Slicing.Api.Slice.remove_uncalled (); let extracted_prj = Slicing.Api.Project.extract name in Options.feedback ~level:2 "slicing done"; extracted_prj let all_pragmas_kf l = List.fold_left (fun acc (s, a) -> match a.annot_content with | APragma (Impact_pragma IPstmt) -> s :: acc | APragma (Impact_pragma (IPexpr _)) -> Options.not_yet_implemented "impact pragmas: expr" | _ -> assert false) [] l let compute_pragmas () = Ast.compute (); let pragmas = ref [] in let visitor = object inherit Visitor.frama_c_inplace as super method! vfunc f = pragmas := []; super#vfunc f method! vstmt_aux s = pragmas := List.map (fun a -> s, a) (Annotations.code_annot ~filter:Logic_utils.is_impact_pragma s) @ !pragmas; Cil.DoChildren end in (* fill [pragmas] with all the pragmas of all the selected functions *) let pragmas = Options.Pragma.fold (fun kf acc -> Pragma option only accept defined functions . let f = Kernel_function.get_definition kf in ignore (Visitor.visitFramacFunction visitor f); if !pragmas != [] then (kf, !pragmas) :: acc else acc) [] in let skip = Compute_impact.skip () in (* compute impact analyses on each kf *) let nodes = List.fold_left (fun nodes (kf, pragmas) -> let pragmas_stmts = all_pragmas_kf pragmas in Pdg_aux.NS.union nodes (compute_multiple_stmts skip kf pragmas_stmts) ) Pdg_aux.NS.empty pragmas in let stmts = Compute_impact.nodes_to_stmts nodes in if Options.Slicing.get () then ignore (slice stmts); stmts; ;; let compute_pragmas = Journal.register "Impact.compute_pragmas" (Datatype.func Datatype.unit (Datatype.list Stmt.ty)) compute_pragmas let from_stmt = Journal.register "Impact.from_stmt" (Datatype.func Stmt.ty (Datatype.list Stmt.ty)) compute_from_stmt let from_nodes = Journal.register "Impact.from_nodes" (Datatype.func2 Kernel_function.ty (Datatype.list PdgTypes.Node.ty) (PdgTypes.NodeSet.ty)) compute_from_nodes let main () = if Options.is_on () then begin Options.feedback "beginning analysis"; assert (not (Options.Pragma.is_empty ())); ignore (compute_pragmas ()); Options.feedback "analysis done" end let () = Db.Main.extend main (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/impact/register.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. ************************************************************************ Slice on the given list of stmts fill [pragmas] with all the pragmas of all the selected functions compute impact analyses on each kf Local Variables: compile-command: "make -C ../../.." End:
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 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 open Cil_datatype let rec pp_stmt fmt s = match s.skind with | Instr _ | Return _ | Goto _ | Break _ | Continue _ | TryFinally _ | TryExcept _ | Throw _ | TryCatch _ -> Printer.without_annot Printer.pp_stmt fmt s | If (e, _, _, _) -> Format.fprintf fmt "if(%a) <..>" Printer.pp_exp e | Switch (e, _, _, _) -> Format.fprintf fmt "switch(%a)<..>" Printer.pp_exp e | Loop _ -> Format.fprintf fmt "while (...)" | Block b -> begin match b.bstmts with | [] -> Format.fprintf fmt "<Block {}>" | s :: _ -> Format.fprintf fmt "<Block { %a }>" pp_stmt s end | UnspecifiedSequence _ -> Format.fprintf fmt "TODO" let print_results fmt a = Pretty_utils.pp_list (fun fmt s -> Format.fprintf fmt "@[<hov 2>%a (sid %d): %a@]" Printer.pp_location (Stmt.loc s) s.sid pp_stmt s ) fmt a let compute_from_stmt stmt = let kf = Kernel_function.find_englobing_kf stmt in let skip = Compute_impact.skip () in let reason = Options.Reason.get () in Compute_impact.stmts_impacted ~skip ~reason kf [stmt] let compute_from_nodes kf nodes = let skip = Compute_impact.skip () in let reason = Options.Reason.get () in let r = Compute_impact.nodes_impacted ~skip ~reason kf nodes in Pdg_aux.NS.fold (fun (n, _z) acc -> PdgTypes.NodeSet.add n acc) r PdgTypes.NodeSet.empty let compute_multiple_stmts skip kf ls = Options.debug "computing impact of statement(s) %a" (Pretty_utils.pp_list ~sep:",@ " Stmt.pretty_sid) ls; let reason = Options.Reason.get () in let res, _, _ = Compute_impact.nodes_impacted_by_stmts ~skip ~reason kf ls in let res_nodes = Compute_impact.result_to_nodes res in let res_stmts = Compute_impact.nodes_to_stmts res_nodes in if Options.Print.get () then begin Options.result "@[<v 2>@[impacted statements of stmt(s) %a are:@]@ %a@]" (Pretty_utils.pp_list ~sep:",@ " Stmt.pretty_sid) ls print_results res_stmts end; res_nodes let slice (stmts:stmt list) = Options.feedback ~level:2 "beginning slicing"; let name = "impact slicing" in Slicing.Api.Project.reset_slicing (); let select sel ({ sid = id } as stmt) = let kf = Kernel_function.find_englobing_kf stmt in Options.debug ~level:3 "selecting sid %d (of %s)" id (Kernel_function.get_name kf); Slicing.Api.Select.select_stmt sel ~spare:false stmt kf in let sel = List.fold_left select Slicing.Api.Select.empty_selects stmts in Options.debug ~level:2 "applying slicing request"; Slicing.Api.Request.add_persistent_selection sel; Slicing.Api.Request.apply_all_internal (); Slicing.Api.Slice.remove_uncalled (); let extracted_prj = Slicing.Api.Project.extract name in Options.feedback ~level:2 "slicing done"; extracted_prj let all_pragmas_kf l = List.fold_left (fun acc (s, a) -> match a.annot_content with | APragma (Impact_pragma IPstmt) -> s :: acc | APragma (Impact_pragma (IPexpr _)) -> Options.not_yet_implemented "impact pragmas: expr" | _ -> assert false) [] l let compute_pragmas () = Ast.compute (); let pragmas = ref [] in let visitor = object inherit Visitor.frama_c_inplace as super method! vfunc f = pragmas := []; super#vfunc f method! vstmt_aux s = pragmas := List.map (fun a -> s, a) (Annotations.code_annot ~filter:Logic_utils.is_impact_pragma s) @ !pragmas; Cil.DoChildren end in let pragmas = Options.Pragma.fold (fun kf acc -> Pragma option only accept defined functions . let f = Kernel_function.get_definition kf in ignore (Visitor.visitFramacFunction visitor f); if !pragmas != [] then (kf, !pragmas) :: acc else acc) [] in let skip = Compute_impact.skip () in let nodes = List.fold_left (fun nodes (kf, pragmas) -> let pragmas_stmts = all_pragmas_kf pragmas in Pdg_aux.NS.union nodes (compute_multiple_stmts skip kf pragmas_stmts) ) Pdg_aux.NS.empty pragmas in let stmts = Compute_impact.nodes_to_stmts nodes in if Options.Slicing.get () then ignore (slice stmts); stmts; ;; let compute_pragmas = Journal.register "Impact.compute_pragmas" (Datatype.func Datatype.unit (Datatype.list Stmt.ty)) compute_pragmas let from_stmt = Journal.register "Impact.from_stmt" (Datatype.func Stmt.ty (Datatype.list Stmt.ty)) compute_from_stmt let from_nodes = Journal.register "Impact.from_nodes" (Datatype.func2 Kernel_function.ty (Datatype.list PdgTypes.Node.ty) (PdgTypes.NodeSet.ty)) compute_from_nodes let main () = if Options.is_on () then begin Options.feedback "beginning analysis"; assert (not (Options.Pragma.is_empty ())); ignore (compute_pragmas ()); Options.feedback "analysis done" end let () = Db.Main.extend main
ff68bb6d735b8b243fce803fc94398fb8807824fda9e86b732584d3370cb6011
ekmett/machines
Type.hs
{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} # LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Type Copyright : ( C ) 2012 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : provisional Portability : rank-2 , GADTs -- ---------------------------------------------------------------------------- module Data.Machine.Type ( -- * Machines MachineT(..) , Step(..) , Machine , runT_ , runT , run , runMachine , encased -- ** Building machines from plans , construct , repeatedly , unfoldPlan , before , preplan -- , sink -- ** Deconstructing machines back into plans , deconstruct , tagDone , finishWith -- * Reshaping machines , fit , fitM , pass , starve , stopped , stepMachine -- * Applicative Machines , Appliance(..) ) where import Control.Applicative import Control.Category import Control.Monad (liftM) import Data.Foldable import Data.Functor.Identity import Data.Machine.Plan import Data.Monoid hiding ((<>)) import Data.Pointed import Data.Profunctor.Unsafe ((#.)) import Data.Semigroup import Prelude hiding ((.),id) ------------------------------------------------------------------------------- Transduction Machines ------------------------------------------------------------------------------- -- | This is the base functor for a 'Machine' or 'MachineT'. -- -- Note: A 'Machine' is usually constructed from 'Plan', so it does not need to be CPS'd. data Step k o r = Stop | Yield o r | forall t. Await (t -> r) (k t) r instance Functor (Step k o) where fmap _ Stop = Stop fmap f (Yield o k) = Yield o (f k) fmap f (Await g kg fg) = Await (f . g) kg (f fg) -- | A 'MachineT' reads from a number of inputs and may yield results before stopping -- with monadic side-effects. newtype MachineT m k o = MachineT { runMachineT :: m (Step k o (MachineT m k o)) } -- | A 'Machine' reads from a number of inputs and may yield results before stopping. -- -- A 'Machine' can be used as a @'MachineT' m@ for any @'Monad' m@. type Machine k o = forall m. Monad m => MachineT m k o -- | @'runMachine' = 'runIdentity' . 'runMachineT'@ runMachine :: MachineT Identity k o -> Step k o (MachineT Identity k o) runMachine = runIdentity . runMachineT -- | Pack a 'Step' of a 'Machine' into a 'Machine'. encased :: Monad m => Step k o (MachineT m k o) -> MachineT m k o encased = MachineT #. return -- | Transform a 'Machine' by looking at a single step of that machine. stepMachine :: Monad m => MachineT m k o -> (Step k o (MachineT m k o) -> MachineT m k' o') -> MachineT m k' o' stepMachine m f = MachineT (runMachineT #. f =<< runMachineT m) instance Monad m => Functor (MachineT m k) where fmap f (MachineT m) = MachineT (liftM f' m) where f' (Yield o xs) = Yield (f o) (f <$> xs) f' (Await k kir e) = Await (fmap f . k) kir (f <$> e) f' Stop = Stop instance Monad m => Pointed (MachineT m k) where point x = repeatedly $ yield x instance Monad m => Semigroup (MachineT m k o) where a <> b = stepMachine a $ \step -> case step of Yield o a' -> encased (Yield o (mappend a' b)) Await k kir e -> encased (Await (\x -> k x <> b) kir (e <> b)) Stop -> b instance Monad m => Monoid (MachineT m k o) where mempty = stopped mappend = (<>) -- | An input type that supports merging requests from multiple machines. class Appliance k where applied :: Monad m => MachineT m k (a -> b) -> MachineT m k a -> MachineT m k b instance (Monad m, Appliance k) => Applicative (MachineT m k) where pure = point (<*>) = applied -- TODO instance Appliance ( Is i ) where applied = appliedTo ( Just mempty ) ( Just mempty ) i d ( flip i d ) where -- applied appliedTo : : Maybe ( Seq i ) - > Maybe ( i - > MachineT m ( Is i ) b , MachineT m ( Is i ) b ) - > Either ( Seq a ) ( Seq b ) - > ( a - > b - > c ) - > ( b - > a - > c ) - > MachineT m ( Is i ) a - > MachineT m ( Is i ) b - > MachineT m ( Is i ) c appliedTo mis blocking ss f g m n = MachineT $ runMachineT m > > = \v - > case v of Stop - > return Stop Yield a k - > case ss of Left as - > Right bs - > case viewl bs of b : < bs ' - > return $ Yield ( f a b ) ( appliedTo mis bs ' f g m n ) runMachine $ appliedTo mis blocking ( singleton a ) g f n m Await ak Refl e - > case mis of Nothing - > runMachine $ appliedTo Nothing blocking bs f g e n Just is - > case viewl is of i : < is ' - > runMachine $ appliedTo ( Just is ' ) blocking bs f g ( ak i ) m EmptyL - > case blocking of Just ( bk , be ) - > Nothing - > runMachine $ appliedTo mis ( Just ( ak , e ) ) | blocking - > return $ Await ( \i - > appliedTo ( Just ( singleton i ) ) False f g ( ak i ) n ) Refl $ | otherwise - > -- TODO instance Appliance (Is i) where applied = appliedTo (Just mempty) (Just mempty) id (flip id) where -- applied appliedTo :: Maybe (Seq i) -> Maybe (i -> MachineT m (Is i) b, MachineT m (Is i) b) -> Either (Seq a) (Seq b) -> (a -> b -> c) -> (b -> a -> c) -> MachineT m (Is i) a -> MachineT m (Is i) b -> MachineT m (Is i) c appliedTo mis blocking ss f g m n = MachineT $ runMachineT m >>= \v -> case v of Stop -> return Stop Yield a k -> case ss of Left as -> Right bs -> case viewl bs of b :< bs' -> return $ Yield (f a b) (appliedTo mis bs' f g m n) EmptyL -> runMachine $ appliedTo mis blocking (singleton a) g f n m Await ak Refl e -> case mis of Nothing -> runMachine $ appliedTo Nothing blocking bs f g e n Just is -> case viewl is of i :< is' -> runMachine $ appliedTo (Just is') blocking bs f g (ak i) m EmptyL -> case blocking of Just (bk, be) -> Nothing -> runMachine $ appliedTo mis (Just (ak, e)) | blocking -> return $ Await (\i -> appliedTo (Just (singleton i)) False f g (ak i) n) Refl $ | otherwise -> -} -- | Stop feeding input into model, taking only the effects. # INLINABLE runT _ # runT_ :: Monad m => MachineT m k b -> m () runT_ m = runMachineT m >>= \v -> case v of Stop -> return () Yield _ k -> runT_ k Await _ _ e -> runT_ e -- | Stop feeding input into model and extract an answer # INLINABLE runT # runT :: Monad m => MachineT m k b -> m [b] runT (MachineT m) = m >>= \v -> case v of Stop -> return [] Yield o k -> liftM (o:) (runT k) Await _ _ e -> runT e -- | Run a pure machine and extract an answer. run :: MachineT Identity k b -> [b] run = runIdentity . runT | This permits toList to be used on a Machine . instance (m ~ Identity) => Foldable (MachineT m k) where foldMap f (MachineT (Identity m)) = go m where go Stop = mempty go (Yield o k) = f o `mappend` foldMap f k go (Await _ _ fg) = foldMap f fg -- | Connect different kinds of machines . -- @'fit ' ' i d ' = ' id'@ fit :: Monad m => (forall a. k a -> k' a) -> MachineT m k o -> MachineT m k' o fit f (MachineT m) = MachineT (liftM f' m) where f' (Yield o k) = Yield o (fit f k) f' Stop = Stop f' (Await g kir h) = Await (fit f . g) (f kir) (fit f h) # INLINE fit # --- | Connect machine transformers over different monads using a monad --- morphism. fitM :: (Monad m, Monad m') => (forall a. m a -> m' a) -> MachineT m k o -> MachineT m' k o fitM f (MachineT m) = MachineT $ f (liftM aux m) where aux Stop = Stop aux (Yield o k) = Yield o (fitM f k) aux (Await g kg gg) = Await (fitM f . g) kg (fitM f gg) # INLINE fitM # -- | Compile a machine to a model. construct :: Monad m => PlanT k o m a -> MachineT m k o construct m = MachineT $ runPlanT m (const (return Stop)) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) {-# INLINE construct #-} -- | Generates a model that runs a machine until it stops, then start it up again. -- -- @'repeatedly' m = 'construct' ('Control.Monad.forever' m)@ repeatedly :: Monad m => PlanT k o m a -> MachineT m k o repeatedly m = r where r = MachineT $ runPlanT m (const (runMachineT r)) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE repeatedly # | Unfold a stateful PlanT into a MachineT. unfoldPlan :: Monad m => s -> (s -> PlanT k o m s) -> MachineT m k o unfoldPlan s0 sp = r s0 where r s = MachineT $ runPlanT (sp s) (\sx -> runMachineT $ r sx) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE unfoldPlan # -- | Evaluate a machine until it stops, and then yield answers according to the supplied model. before :: Monad m => MachineT m k o -> PlanT k o m a -> MachineT m k o before (MachineT n) m = MachineT $ runPlanT m (const n) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE before # -- | Incorporate a 'Plan' into the resulting machine. preplan :: Monad m => PlanT k o m (MachineT m k o) -> MachineT m k o preplan m = MachineT $ runPlanT m runMachineT (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE preplan # -- | Given a handle, ignore all other inputs and just stream input from that handle. -- -- @ -- 'pass' 'id' :: 'Data.Machine.Process.Process' a a -- 'pass' 'Data.Machine.Tee.L' :: 'Data.Machine.Tee.Tee' a b a -- 'pass' 'Data.Machine.Tee.R' :: 'Data.Machine.Tee.Tee' a b b ' pass ' ' Data . Machine . Wye . X ' : : ' Data . Machine . Wye . Wye ' a b a ' pass ' ' Data . Machine . Wye . Y ' : : ' Data . Machine . Wye . Wye ' a b b ' pass ' ' Data . Machine . Wye . Z ' : : ' Data . Machine . Wye . Wye ' a b ( Either a b ) -- @ -- pass :: k o -> Machine k o pass k = loop where loop = encased (Await (\t -> encased (Yield t loop)) k stopped) # INLINE pass # -- | Run a machine with no input until it stops, then behave as another machine. starve :: Monad m => MachineT m k0 b -> MachineT m k b -> MachineT m k b starve m cont = MachineT $ runMachineT m >>= \v -> case v of Stop -> runMachineT cont -- Continue with cont instead of stopping Yield o r -> return $ Yield o (starve r cont) Await _ _ r -> runMachineT (starve r cont) # INLINE starve # -- | This is a stopped 'Machine' stopped :: Machine k b stopped = encased Stop {-# INLINE stopped #-} -------------------------------------------------------------------------------- -- Deconstruction -------------------------------------------------------------------------------- - | Convert a ' Machine ' back into a ' Plan ' . The first value the --- machine yields that is tagged with the 'Left' data constructor is --- used as the return value of the resultant 'Plan'. Machine-yielded - values tagged with ' Right ' are yielded -- sans tag -- by the --- result 'Plan'. This may be used when monadic binding of results is --- required. deconstruct :: Monad m => MachineT m k (Either a o) -> PlanT k o m a deconstruct m = PlanT $ \r y a f -> let aux k = runPlanT (deconstruct k) r y a f in runMachineT m >>= \v -> case v of Stop -> f Yield (Left o) _ -> r o Yield (Right o) k -> y o (aux k) Await g fk h -> a (aux . g) fk (aux h) -- | Use a predicate to mark a yielded value as the terminal value of -- this 'Machine'. This is useful in combination with 'deconstruct' to -- combine 'Plan's. tagDone :: Monad m => (o -> Bool) -> MachineT m k o -> MachineT m k (Either o o) tagDone f = fmap aux where aux x = if f x then Left x else Right x -- | Use a function to produce and mark a yielded value as the -- terminal value of a 'Machine'. All yielded values for which the -- given function returns 'Nothing' are yielded down the pipeline, but the first value for which the function returns a ' Just ' value will -- be returned by a 'Plan' created via 'deconstruct'. finishWith :: Monad m => (o -> Maybe r) -> MachineT m k o -> MachineT m k (Either r o) finishWith f = fmap aux where aux x = maybe (Right x) Left $ f x ------------------------------------------------------------------------------- -- Sink ------------------------------------------------------------------------------- -- | -- A Sink in this model is a ' Data . Machine . Process . Process ' -- ( or ' Data . Machine . Tee . Tee ' , etc ) that produces a single answer . -- -- \"Is that your final answer?\ " sink : : = > ( forall k o m a ) - > MachineT m k a sink m = ( \a - > Yield a Stop ) i d ( Await i d ) Stop -- | -- A Sink in this model is a 'Data.Machine.Process.Process' -- (or 'Data.Machine.Tee.Tee', etc) that produces a single answer. -- -- \"Is that your final answer?\" sink :: Monad m => (forall o. PlanT k o m a) -> MachineT m k a sink m = runPlanT m (\a -> Yield a Stop) id (Await id) Stop -}
null
https://raw.githubusercontent.com/ekmett/machines/58e39c953e7961e22765898d29ce1981f8147804/src/Data/Machine/Type.hs
haskell
# LANGUAGE GADTs # # LANGUAGE Rank2Types # --------------------------------------------------------------------------- | Module : Data.Machine.Type License : BSD-style (see the file LICENSE) Stability : provisional -------------------------------------------------------------------------- * Machines ** Building machines from plans , sink ** Deconstructing machines back into plans * Reshaping machines * Applicative Machines ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | This is the base functor for a 'Machine' or 'MachineT'. Note: A 'Machine' is usually constructed from 'Plan', so it does not need to be CPS'd. | A 'MachineT' reads from a number of inputs and may yield results before stopping with monadic side-effects. | A 'Machine' reads from a number of inputs and may yield results before stopping. A 'Machine' can be used as a @'MachineT' m@ for any @'Monad' m@. | @'runMachine' = 'runIdentity' . 'runMachineT'@ | Pack a 'Step' of a 'Machine' into a 'Machine'. | Transform a 'Machine' by looking at a single step of that machine. | An input type that supports merging requests from multiple machines. TODO applied TODO applied | Stop feeding input into model, taking only the effects. | Stop feeding input into model and extract an answer | Run a pure machine and extract an answer. | - | Connect machine transformers over different monads using a monad - morphism. | Compile a machine to a model. # INLINE construct # | Generates a model that runs a machine until it stops, then start it up again. @'repeatedly' m = 'construct' ('Control.Monad.forever' m)@ | Evaluate a machine until it stops, and then yield answers according to the supplied model. | Incorporate a 'Plan' into the resulting machine. | Given a handle, ignore all other inputs and just stream input from that handle. @ 'pass' 'id' :: 'Data.Machine.Process.Process' a a 'pass' 'Data.Machine.Tee.L' :: 'Data.Machine.Tee.Tee' a b a 'pass' 'Data.Machine.Tee.R' :: 'Data.Machine.Tee.Tee' a b b @ | Run a machine with no input until it stops, then behave as another machine. Continue with cont instead of stopping | This is a stopped 'Machine' # INLINE stopped # ------------------------------------------------------------------------------ Deconstruction ------------------------------------------------------------------------------ - machine yields that is tagged with the 'Left' data constructor is - used as the return value of the resultant 'Plan'. Machine-yielded sans tag -- by the - result 'Plan'. This may be used when monadic binding of results is - required. | Use a predicate to mark a yielded value as the terminal value of this 'Machine'. This is useful in combination with 'deconstruct' to combine 'Plan's. | Use a function to produce and mark a yielded value as the terminal value of a 'Machine'. All yielded values for which the given function returns 'Nothing' are yielded down the pipeline, but be returned by a 'Plan' created via 'deconstruct'. ----------------------------------------------------------------------------- Sink ----------------------------------------------------------------------------- | A Sink in this model is a ' Data . Machine . Process . Process ' ( or ' Data . Machine . Tee . Tee ' , etc ) that produces a single answer . \"Is that your final answer?\ " | A Sink in this model is a 'Data.Machine.Process.Process' (or 'Data.Machine.Tee.Tee', etc) that produces a single answer. \"Is that your final answer?\"
# LANGUAGE TypeOperators # # LANGUAGE FlexibleInstances # Copyright : ( C ) 2012 Maintainer : < > Portability : rank-2 , GADTs module Data.Machine.Type ( MachineT(..) , Step(..) , Machine , runT_ , runT , run , runMachine , encased , construct , repeatedly , unfoldPlan , before , preplan , deconstruct , tagDone , finishWith , fit , fitM , pass , starve , stopped , stepMachine , Appliance(..) ) where import Control.Applicative import Control.Category import Control.Monad (liftM) import Data.Foldable import Data.Functor.Identity import Data.Machine.Plan import Data.Monoid hiding ((<>)) import Data.Pointed import Data.Profunctor.Unsafe ((#.)) import Data.Semigroup import Prelude hiding ((.),id) Transduction Machines data Step k o r = Stop | Yield o r | forall t. Await (t -> r) (k t) r instance Functor (Step k o) where fmap _ Stop = Stop fmap f (Yield o k) = Yield o (f k) fmap f (Await g kg fg) = Await (f . g) kg (f fg) newtype MachineT m k o = MachineT { runMachineT :: m (Step k o (MachineT m k o)) } type Machine k o = forall m. Monad m => MachineT m k o runMachine :: MachineT Identity k o -> Step k o (MachineT Identity k o) runMachine = runIdentity . runMachineT encased :: Monad m => Step k o (MachineT m k o) -> MachineT m k o encased = MachineT #. return stepMachine :: Monad m => MachineT m k o -> (Step k o (MachineT m k o) -> MachineT m k' o') -> MachineT m k' o' stepMachine m f = MachineT (runMachineT #. f =<< runMachineT m) instance Monad m => Functor (MachineT m k) where fmap f (MachineT m) = MachineT (liftM f' m) where f' (Yield o xs) = Yield (f o) (f <$> xs) f' (Await k kir e) = Await (fmap f . k) kir (f <$> e) f' Stop = Stop instance Monad m => Pointed (MachineT m k) where point x = repeatedly $ yield x instance Monad m => Semigroup (MachineT m k o) where a <> b = stepMachine a $ \step -> case step of Yield o a' -> encased (Yield o (mappend a' b)) Await k kir e -> encased (Await (\x -> k x <> b) kir (e <> b)) Stop -> b instance Monad m => Monoid (MachineT m k o) where mempty = stopped mappend = (<>) class Appliance k where applied :: Monad m => MachineT m k (a -> b) -> MachineT m k a -> MachineT m k b instance (Monad m, Appliance k) => Applicative (MachineT m k) where pure = point (<*>) = applied instance Appliance ( Is i ) where applied = appliedTo ( Just mempty ) ( Just mempty ) i d ( flip i d ) where appliedTo : : Maybe ( Seq i ) - > Maybe ( i - > MachineT m ( Is i ) b , MachineT m ( Is i ) b ) - > Either ( Seq a ) ( Seq b ) - > ( a - > b - > c ) - > ( b - > a - > c ) - > MachineT m ( Is i ) a - > MachineT m ( Is i ) b - > MachineT m ( Is i ) c appliedTo mis blocking ss f g m n = MachineT $ runMachineT m > > = \v - > case v of Stop - > return Stop Yield a k - > case ss of Left as - > Right bs - > case viewl bs of b : < bs ' - > return $ Yield ( f a b ) ( appliedTo mis bs ' f g m n ) runMachine $ appliedTo mis blocking ( singleton a ) g f n m Await ak Refl e - > case mis of Nothing - > runMachine $ appliedTo Nothing blocking bs f g e n Just is - > case viewl is of i : < is ' - > runMachine $ appliedTo ( Just is ' ) blocking bs f g ( ak i ) m EmptyL - > case blocking of Just ( bk , be ) - > Nothing - > runMachine $ appliedTo mis ( Just ( ak , e ) ) | blocking - > return $ Await ( \i - > appliedTo ( Just ( singleton i ) ) False f g ( ak i ) n ) Refl $ | otherwise - > instance Appliance (Is i) where applied = appliedTo (Just mempty) (Just mempty) id (flip id) where appliedTo :: Maybe (Seq i) -> Maybe (i -> MachineT m (Is i) b, MachineT m (Is i) b) -> Either (Seq a) (Seq b) -> (a -> b -> c) -> (b -> a -> c) -> MachineT m (Is i) a -> MachineT m (Is i) b -> MachineT m (Is i) c appliedTo mis blocking ss f g m n = MachineT $ runMachineT m >>= \v -> case v of Stop -> return Stop Yield a k -> case ss of Left as -> Right bs -> case viewl bs of b :< bs' -> return $ Yield (f a b) (appliedTo mis bs' f g m n) EmptyL -> runMachine $ appliedTo mis blocking (singleton a) g f n m Await ak Refl e -> case mis of Nothing -> runMachine $ appliedTo Nothing blocking bs f g e n Just is -> case viewl is of i :< is' -> runMachine $ appliedTo (Just is') blocking bs f g (ak i) m EmptyL -> case blocking of Just (bk, be) -> Nothing -> runMachine $ appliedTo mis (Just (ak, e)) | blocking -> return $ Await (\i -> appliedTo (Just (singleton i)) False f g (ak i) n) Refl $ | otherwise -> -} # INLINABLE runT _ # runT_ :: Monad m => MachineT m k b -> m () runT_ m = runMachineT m >>= \v -> case v of Stop -> return () Yield _ k -> runT_ k Await _ _ e -> runT_ e # INLINABLE runT # runT :: Monad m => MachineT m k b -> m [b] runT (MachineT m) = m >>= \v -> case v of Stop -> return [] Yield o k -> liftM (o:) (runT k) Await _ _ e -> runT e run :: MachineT Identity k b -> [b] run = runIdentity . runT | This permits toList to be used on a Machine . instance (m ~ Identity) => Foldable (MachineT m k) where foldMap f (MachineT (Identity m)) = go m where go Stop = mempty go (Yield o k) = f o `mappend` foldMap f k go (Await _ _ fg) = foldMap f fg Connect different kinds of machines . @'fit ' ' i d ' = ' id'@ fit :: Monad m => (forall a. k a -> k' a) -> MachineT m k o -> MachineT m k' o fit f (MachineT m) = MachineT (liftM f' m) where f' (Yield o k) = Yield o (fit f k) f' Stop = Stop f' (Await g kir h) = Await (fit f . g) (f kir) (fit f h) # INLINE fit # fitM :: (Monad m, Monad m') => (forall a. m a -> m' a) -> MachineT m k o -> MachineT m' k o fitM f (MachineT m) = MachineT $ f (liftM aux m) where aux Stop = Stop aux (Yield o k) = Yield o (fitM f k) aux (Await g kg gg) = Await (fitM f . g) kg (fitM f gg) # INLINE fitM # construct :: Monad m => PlanT k o m a -> MachineT m k o construct m = MachineT $ runPlanT m (const (return Stop)) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) repeatedly :: Monad m => PlanT k o m a -> MachineT m k o repeatedly m = r where r = MachineT $ runPlanT m (const (runMachineT r)) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE repeatedly # | Unfold a stateful PlanT into a MachineT. unfoldPlan :: Monad m => s -> (s -> PlanT k o m s) -> MachineT m k o unfoldPlan s0 sp = r s0 where r s = MachineT $ runPlanT (sp s) (\sx -> runMachineT $ r sx) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE unfoldPlan # before :: Monad m => MachineT m k o -> PlanT k o m a -> MachineT m k o before (MachineT n) m = MachineT $ runPlanT m (const n) (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE before # preplan :: Monad m => PlanT k o m (MachineT m k o) -> MachineT m k o preplan m = MachineT $ runPlanT m runMachineT (\o k -> return (Yield o (MachineT k))) (\f k g -> return (Await (MachineT #. f) k (MachineT g))) (return Stop) # INLINE preplan # ' pass ' ' Data . Machine . Wye . X ' : : ' Data . Machine . Wye . Wye ' a b a ' pass ' ' Data . Machine . Wye . Y ' : : ' Data . Machine . Wye . Wye ' a b b ' pass ' ' Data . Machine . Wye . Z ' : : ' Data . Machine . Wye . Wye ' a b ( Either a b ) pass :: k o -> Machine k o pass k = loop where loop = encased (Await (\t -> encased (Yield t loop)) k stopped) # INLINE pass # starve :: Monad m => MachineT m k0 b -> MachineT m k b -> MachineT m k b starve m cont = MachineT $ runMachineT m >>= \v -> case v of Yield o r -> return $ Yield o (starve r cont) Await _ _ r -> runMachineT (starve r cont) # INLINE starve # stopped :: Machine k b stopped = encased Stop - | Convert a ' Machine ' back into a ' Plan ' . The first value the deconstruct :: Monad m => MachineT m k (Either a o) -> PlanT k o m a deconstruct m = PlanT $ \r y a f -> let aux k = runPlanT (deconstruct k) r y a f in runMachineT m >>= \v -> case v of Stop -> f Yield (Left o) _ -> r o Yield (Right o) k -> y o (aux k) Await g fk h -> a (aux . g) fk (aux h) tagDone :: Monad m => (o -> Bool) -> MachineT m k o -> MachineT m k (Either o o) tagDone f = fmap aux where aux x = if f x then Left x else Right x the first value for which the function returns a ' Just ' value will finishWith :: Monad m => (o -> Maybe r) -> MachineT m k o -> MachineT m k (Either r o) finishWith f = fmap aux where aux x = maybe (Right x) Left $ f x sink : : = > ( forall k o m a ) - > MachineT m k a sink m = ( \a - > Yield a Stop ) i d ( Await i d ) Stop sink :: Monad m => (forall o. PlanT k o m a) -> MachineT m k a sink m = runPlanT m (\a -> Yield a Stop) id (Await id) Stop -}
b9367c16bc5cd7f9de895698c8491d1903ad7747079235bf2d77ea427b424617
AbstractMachinesLab/caramel
ast_mapper.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , LexiFi (* *) Copyright 2012 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. *) (* *) (**************************************************************************) * The interface of a -ppx rewriter A -ppx rewriter is a program that accepts a serialized abstract syntax tree and outputs another , possibly modified , abstract syntax tree . This module encapsulates the interface between the compiler and the -ppx rewriters , handling such details as the serialization format , forwarding of command - line flags , and storing state . { ! mapper } allows to implement AST rewriting using open recursion . A typical mapper would be based on { ! default_mapper } , a deep identity mapper , and will fall back on it for handling the syntax it does not modify . For example : { [ open open Parsetree open Ast_mapper let test_mapper argv = { default_mapper with expr = fun mapper expr - > match expr with | { pexp_desc = Pexp_extension ( { txt = " test " } , PStr [ ] ) } - > Ast_helper.Exp.constant ( Const_int 42 ) | other - > default_mapper.expr mapper other ; } let ( ) = register " ppx_test " test_mapper ] } This -ppx rewriter , which replaces [ [ % test ] ] in expressions with the constant [ 42 ] , can be compiled using [ ocamlc -o ppx_test -I + compiler - libs ocamlcommon.cma ppx_test.ml ] . A -ppx rewriter is a program that accepts a serialized abstract syntax tree and outputs another, possibly modified, abstract syntax tree. This module encapsulates the interface between the compiler and the -ppx rewriters, handling such details as the serialization format, forwarding of command-line flags, and storing state. {!mapper} allows to implement AST rewriting using open recursion. A typical mapper would be based on {!default_mapper}, a deep identity mapper, and will fall back on it for handling the syntax it does not modify. For example: {[ open Asttypes open Parsetree open Ast_mapper let test_mapper argv = { default_mapper with expr = fun mapper expr -> match expr with | { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} -> Ast_helper.Exp.constant (Const_int 42) | other -> default_mapper.expr mapper other; } let () = register "ppx_test" test_mapper]} This -ppx rewriter, which replaces [[%test]] in expressions with the constant [42], can be compiled using [ocamlc -o ppx_test -I +compiler-libs ocamlcommon.cma ppx_test.ml]. *) open Parsetree * { 2 A generic Parsetree mapper } type mapper = { attribute: mapper -> attribute -> attribute; attributes: mapper -> attribute list -> attribute list; case: mapper -> case -> case; cases: mapper -> case list -> case list; class_declaration: mapper -> class_declaration -> class_declaration; class_description: mapper -> class_description -> class_description; class_expr: mapper -> class_expr -> class_expr; class_field: mapper -> class_field -> class_field; class_signature: mapper -> class_signature -> class_signature; class_structure: mapper -> class_structure -> class_structure; class_type: mapper -> class_type -> class_type; class_type_declaration: mapper -> class_type_declaration -> class_type_declaration; class_type_field: mapper -> class_type_field -> class_type_field; constructor_declaration: mapper -> constructor_declaration -> constructor_declaration; expr: mapper -> expression -> expression; extension: mapper -> extension -> extension; extension_constructor: mapper -> extension_constructor -> extension_constructor; include_declaration: mapper -> include_declaration -> include_declaration; include_description: mapper -> include_description -> include_description; label_declaration: mapper -> label_declaration -> label_declaration; location: mapper -> Location.t -> Location.t; module_binding: mapper -> module_binding -> module_binding; module_declaration: mapper -> module_declaration -> module_declaration; module_expr: mapper -> module_expr -> module_expr; module_type: mapper -> module_type -> module_type; module_type_declaration: mapper -> module_type_declaration -> module_type_declaration; open_description: mapper -> open_description -> open_description; pat: mapper -> pattern -> pattern; payload: mapper -> payload -> payload; signature: mapper -> signature -> signature; signature_item: mapper -> signature_item -> signature_item; structure: mapper -> structure -> structure; structure_item: mapper -> structure_item -> structure_item; typ: mapper -> core_type -> core_type; type_declaration: mapper -> type_declaration -> type_declaration; type_extension: mapper -> type_extension -> type_extension; type_kind: mapper -> type_kind -> type_kind; value_binding: mapper -> value_binding -> value_binding; value_description: mapper -> value_description -> value_description; with_constraint: mapper -> with_constraint -> with_constraint; } * A mapper record implements one " method " per syntactic category , using an open recursion style : each method takes as its first argument the mapper to be applied to children in the syntax tree . using an open recursion style: each method takes as its first argument the mapper to be applied to children in the syntax tree. *) val default_mapper: mapper (** A default mapper, which implements a "deep identity" mapping. *) * { 2 Apply mappers to compilation units } val tool_name: unit -> string (** Can be used within a ppx preprocessor to know which tool is calling it ["ocamlc"], ["ocamlopt"], ["ocamldoc"], ["ocamldep"], ["ocaml"], ... Some global variables that reflect command-line options are automatically synchronized between the calling tool and the ppx preprocessor: {!Clflags.include_dirs}, {!Config.load_path}, {!Clflags.open_modules}, {!Clflags.for_package}, {!Clflags.debug}. *) val apply: source:string -> target:string -> mapper -> unit (** Apply a mapper (parametrized by the unit name) to a dumped parsetree found in the [source] file and put the result in the [target] file. The [structure] or [signature] field of the mapper is applied to the implementation or interface. *) val run_main: (string list -> mapper) -> unit (** Entry point to call to implement a standalone -ppx rewriter from a mapper, parametrized by the command line arguments. The current unit name can be obtained from {!Location.input_name}. This function implements proper error reporting for uncaught exceptions. *) * { 2 Registration API } val register_function: (string -> (string list -> mapper) -> unit) ref val register: string -> (string list -> mapper) -> unit * Apply the [ register_function ] . The default behavior is to run the mapper immediately , taking arguments from the process command line . This is to support a scenario where a mapper is linked as a stand - alone executable . It is possible to overwrite the [ register_function ] to define " -ppx drivers " , which combine several mappers in a single process . Typically , a driver starts by defining [ register_function ] to a custom implementation , then lets ppx rewriters ( linked statically or dynamically ) register themselves , and then run all or some of them . It is also possible to have -ppx drivers apply rewriters to only specific parts of an AST . The first argument to [ register ] is a symbolic name to be used by the ppx driver . mapper immediately, taking arguments from the process command line. This is to support a scenario where a mapper is linked as a stand-alone executable. It is possible to overwrite the [register_function] to define "-ppx drivers", which combine several mappers in a single process. Typically, a driver starts by defining [register_function] to a custom implementation, then lets ppx rewriters (linked statically or dynamically) register themselves, and then run all or some of them. It is also possible to have -ppx drivers apply rewriters to only specific parts of an AST. The first argument to [register] is a symbolic name to be used by the ppx driver. *) * { 2 Convenience functions to write mappers } val map_opt: ('a -> 'b) -> 'a option -> 'b option val extension_of_error: Location.error -> extension * Encode an error into an ' ocaml.error ' extension node which can be inserted in a generated Parsetree . The compiler will be responsible for reporting the error . inserted in a generated Parsetree. The compiler will be responsible for reporting the error. *) val attribute_of_warning: Location.t -> string -> attribute * Encode a warning message into an ' ocaml.ppwarning ' attribute which can be inserted in a generated Parsetree . The compiler will be responsible for reporting the warning . inserted in a generated Parsetree. The compiler will be responsible for reporting the warning. *) (** {2 Helper functions to call external mappers} *) val add_ppx_context_str: tool_name:string -> Parsetree.structure -> Parsetree.structure (** Extract information from the current environment and encode it into an attribute which is prepended to the list of structure items in order to pass the information to an external processor. *) val add_ppx_context_sig: tool_name:string -> Parsetree.signature -> Parsetree.signature (** Same as [add_ppx_context_str], but for signatures. *) val drop_ppx_context_str: restore:bool -> Parsetree.structure -> Parsetree.structure (** Drop the ocaml.ppx.context attribute from a structure. If [restore] is true, also restore the associated data in the current process. *) val drop_ppx_context_sig: restore:bool -> Parsetree.signature -> Parsetree.signature (** Same as [drop_ppx_context_str], but for signatures. *) * { 2 Cookies } * Cookies are used to pass information from a ppx processor to a further invocation of itself , when called from the OCaml toplevel ( or other tools that support cookies ) . a further invocation of itself, when called from the OCaml toplevel (or other tools that support cookies). *) val set_cookie: string -> Parsetree.expression -> unit val get_cookie: string -> Parsetree.expression option
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/upstream/ocaml_405/parsing/ast_mapper.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. ************************************************************************ * A default mapper, which implements a "deep identity" mapping. * Can be used within a ppx preprocessor to know which tool is calling it ["ocamlc"], ["ocamlopt"], ["ocamldoc"], ["ocamldep"], ["ocaml"], ... Some global variables that reflect command-line options are automatically synchronized between the calling tool and the ppx preprocessor: {!Clflags.include_dirs}, {!Config.load_path}, {!Clflags.open_modules}, {!Clflags.for_package}, {!Clflags.debug}. * Apply a mapper (parametrized by the unit name) to a dumped parsetree found in the [source] file and put the result in the [target] file. The [structure] or [signature] field of the mapper is applied to the implementation or interface. * Entry point to call to implement a standalone -ppx rewriter from a mapper, parametrized by the command line arguments. The current unit name can be obtained from {!Location.input_name}. This function implements proper error reporting for uncaught exceptions. * {2 Helper functions to call external mappers} * Extract information from the current environment and encode it into an attribute which is prepended to the list of structure items in order to pass the information to an external processor. * Same as [add_ppx_context_str], but for signatures. * Drop the ocaml.ppx.context attribute from a structure. If [restore] is true, also restore the associated data in the current process. * Same as [drop_ppx_context_str], but for signatures.
, LexiFi Copyright 2012 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * The interface of a -ppx rewriter A -ppx rewriter is a program that accepts a serialized abstract syntax tree and outputs another , possibly modified , abstract syntax tree . This module encapsulates the interface between the compiler and the -ppx rewriters , handling such details as the serialization format , forwarding of command - line flags , and storing state . { ! mapper } allows to implement AST rewriting using open recursion . A typical mapper would be based on { ! default_mapper } , a deep identity mapper , and will fall back on it for handling the syntax it does not modify . For example : { [ open open Parsetree open Ast_mapper let test_mapper argv = { default_mapper with expr = fun mapper expr - > match expr with | { pexp_desc = Pexp_extension ( { txt = " test " } , PStr [ ] ) } - > Ast_helper.Exp.constant ( Const_int 42 ) | other - > default_mapper.expr mapper other ; } let ( ) = register " ppx_test " test_mapper ] } This -ppx rewriter , which replaces [ [ % test ] ] in expressions with the constant [ 42 ] , can be compiled using [ ocamlc -o ppx_test -I + compiler - libs ocamlcommon.cma ppx_test.ml ] . A -ppx rewriter is a program that accepts a serialized abstract syntax tree and outputs another, possibly modified, abstract syntax tree. This module encapsulates the interface between the compiler and the -ppx rewriters, handling such details as the serialization format, forwarding of command-line flags, and storing state. {!mapper} allows to implement AST rewriting using open recursion. A typical mapper would be based on {!default_mapper}, a deep identity mapper, and will fall back on it for handling the syntax it does not modify. For example: {[ open Asttypes open Parsetree open Ast_mapper let test_mapper argv = { default_mapper with expr = fun mapper expr -> match expr with | { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} -> Ast_helper.Exp.constant (Const_int 42) | other -> default_mapper.expr mapper other; } let () = register "ppx_test" test_mapper]} This -ppx rewriter, which replaces [[%test]] in expressions with the constant [42], can be compiled using [ocamlc -o ppx_test -I +compiler-libs ocamlcommon.cma ppx_test.ml]. *) open Parsetree * { 2 A generic Parsetree mapper } type mapper = { attribute: mapper -> attribute -> attribute; attributes: mapper -> attribute list -> attribute list; case: mapper -> case -> case; cases: mapper -> case list -> case list; class_declaration: mapper -> class_declaration -> class_declaration; class_description: mapper -> class_description -> class_description; class_expr: mapper -> class_expr -> class_expr; class_field: mapper -> class_field -> class_field; class_signature: mapper -> class_signature -> class_signature; class_structure: mapper -> class_structure -> class_structure; class_type: mapper -> class_type -> class_type; class_type_declaration: mapper -> class_type_declaration -> class_type_declaration; class_type_field: mapper -> class_type_field -> class_type_field; constructor_declaration: mapper -> constructor_declaration -> constructor_declaration; expr: mapper -> expression -> expression; extension: mapper -> extension -> extension; extension_constructor: mapper -> extension_constructor -> extension_constructor; include_declaration: mapper -> include_declaration -> include_declaration; include_description: mapper -> include_description -> include_description; label_declaration: mapper -> label_declaration -> label_declaration; location: mapper -> Location.t -> Location.t; module_binding: mapper -> module_binding -> module_binding; module_declaration: mapper -> module_declaration -> module_declaration; module_expr: mapper -> module_expr -> module_expr; module_type: mapper -> module_type -> module_type; module_type_declaration: mapper -> module_type_declaration -> module_type_declaration; open_description: mapper -> open_description -> open_description; pat: mapper -> pattern -> pattern; payload: mapper -> payload -> payload; signature: mapper -> signature -> signature; signature_item: mapper -> signature_item -> signature_item; structure: mapper -> structure -> structure; structure_item: mapper -> structure_item -> structure_item; typ: mapper -> core_type -> core_type; type_declaration: mapper -> type_declaration -> type_declaration; type_extension: mapper -> type_extension -> type_extension; type_kind: mapper -> type_kind -> type_kind; value_binding: mapper -> value_binding -> value_binding; value_description: mapper -> value_description -> value_description; with_constraint: mapper -> with_constraint -> with_constraint; } * A mapper record implements one " method " per syntactic category , using an open recursion style : each method takes as its first argument the mapper to be applied to children in the syntax tree . using an open recursion style: each method takes as its first argument the mapper to be applied to children in the syntax tree. *) val default_mapper: mapper * { 2 Apply mappers to compilation units } val tool_name: unit -> string val apply: source:string -> target:string -> mapper -> unit val run_main: (string list -> mapper) -> unit * { 2 Registration API } val register_function: (string -> (string list -> mapper) -> unit) ref val register: string -> (string list -> mapper) -> unit * Apply the [ register_function ] . The default behavior is to run the mapper immediately , taking arguments from the process command line . This is to support a scenario where a mapper is linked as a stand - alone executable . It is possible to overwrite the [ register_function ] to define " -ppx drivers " , which combine several mappers in a single process . Typically , a driver starts by defining [ register_function ] to a custom implementation , then lets ppx rewriters ( linked statically or dynamically ) register themselves , and then run all or some of them . It is also possible to have -ppx drivers apply rewriters to only specific parts of an AST . The first argument to [ register ] is a symbolic name to be used by the ppx driver . mapper immediately, taking arguments from the process command line. This is to support a scenario where a mapper is linked as a stand-alone executable. It is possible to overwrite the [register_function] to define "-ppx drivers", which combine several mappers in a single process. Typically, a driver starts by defining [register_function] to a custom implementation, then lets ppx rewriters (linked statically or dynamically) register themselves, and then run all or some of them. It is also possible to have -ppx drivers apply rewriters to only specific parts of an AST. The first argument to [register] is a symbolic name to be used by the ppx driver. *) * { 2 Convenience functions to write mappers } val map_opt: ('a -> 'b) -> 'a option -> 'b option val extension_of_error: Location.error -> extension * Encode an error into an ' ocaml.error ' extension node which can be inserted in a generated Parsetree . The compiler will be responsible for reporting the error . inserted in a generated Parsetree. The compiler will be responsible for reporting the error. *) val attribute_of_warning: Location.t -> string -> attribute * Encode a warning message into an ' ocaml.ppwarning ' attribute which can be inserted in a generated Parsetree . The compiler will be responsible for reporting the warning . inserted in a generated Parsetree. The compiler will be responsible for reporting the warning. *) val add_ppx_context_str: tool_name:string -> Parsetree.structure -> Parsetree.structure val add_ppx_context_sig: tool_name:string -> Parsetree.signature -> Parsetree.signature val drop_ppx_context_str: restore:bool -> Parsetree.structure -> Parsetree.structure val drop_ppx_context_sig: restore:bool -> Parsetree.signature -> Parsetree.signature * { 2 Cookies } * Cookies are used to pass information from a ppx processor to a further invocation of itself , when called from the OCaml toplevel ( or other tools that support cookies ) . a further invocation of itself, when called from the OCaml toplevel (or other tools that support cookies). *) val set_cookie: string -> Parsetree.expression -> unit val get_cookie: string -> Parsetree.expression option
5d8652da799fe515504faeca104038a77f7c4a0e323b5ad16b8b94b6342be832
soulomoon/haskell-katas
ScottEncoding.hs
{-# LANGUAGE ScopedTypeVariables, Rank2Types #-} module Kyu1.ScottEncoding where import Prelude hiding (null, length, map, foldl, foldr, take, fst, snd, curry, uncurry, concat, zip, (++)) newtype SMaybe a = SMaybe { runMaybe :: forall b. b -> (a -> b) -> b } newtype SList a = SList { runList :: forall b. b -> (a -> SList a -> b) -> b } newtype SEither a b = SEither { runEither :: forall c. (a -> c) -> (b -> c) -> c } newtype SPair a b = SPair { runPair :: forall c. (a -> b -> c) -> c } toEither :: SEither a b -> Either a b toEither seab = runEither seab Left Right fromEither :: Either a b -> SEither a b fromEither (Left a) = SEither $ \ac bc -> ac a fromEither (Right b) = SEither $ \ac bc -> bc b isLeft :: SEither a b -> Bool isLeft e = case toEither e of Left _ -> True Right _ -> False isRight :: SEither a b -> Bool isRight = not . isLeft partition :: SList (SEither a b) -> SPair (SList a) (SList b) partition = fromPair . foldr (\a (lista, listb)-> case toEither a of Left a -> (cons a lista, listb) Right b -> (lista, cons b listb)) (SList const, SList const) toList :: SList a -> [a] toList mb = runList mb [] (\x rest -> x:toList rest) fromList :: [a] -> SList a fromList [] = SList const fromList (x:xs)= SList $ \_ f -> f x (fromList xs) cons :: a -> SList a -> SList a cons a list = SList $ \_ f -> f a list concat :: SList a -> SList a -> SList a concat x y | null x = y | otherwise = runList x (SList const) (\r rest -> cons r $ concat rest y) null :: SList a -> Bool null mb = case toList mb of [] -> True x:_ -> False length :: SList a -> Int length mb = runList mb 0 (\ x rest -> 1 + length rest) map :: (a -> b) -> SList a -> SList b map g mb | null mb = SList const | otherwise = runList mb (SList const) (\x rest -> cons (g x) $ map g rest) zip :: SList a -> SList b -> SList (SPair a b) zip ma mb = case (toList ma, toList mb) of (x:xs, y:ys) -> cons (fromPair (x, y)) $ zip (fromList xs) (fromList ys) _ -> SList const foldl :: (b -> a -> b) -> b -> SList a -> b foldl f b l = runList l b (\x rest -> foldl f (f b x) rest) foldr :: (a -> b -> b) -> b -> SList a -> b foldr f b l = runList l b (\x rest -> f x (foldr f b rest)) take :: Int -> SList a -> SList a take m list = runList list (SList const) (\x rest -> case m of 0 -> SList const _ -> cons x $ take (m-1) rest) toMaybe :: SMaybe a -> Maybe a toMaybe mb = runMaybe mb Nothing Just fromMaybe :: Maybe a -> SMaybe a fromMaybe (Just a) = SMaybe $ \b f -> f a fromMaybe Nothing = SMaybe const isJust :: SMaybe a -> Bool isJust mb = case toMaybe mb of Just _ -> True Nothing -> False isNothing :: SMaybe a -> Bool isNothing = not . isJust catMaybes :: SList (SMaybe a) -> SList a catMaybes = foldr (\x rest -> case toMaybe x of Nothing -> rest Just x -> cons x rest) (SList const) toPair :: SPair a b -> (a,b) toPair (SPair sp) = sp (\a b -> (a, b)) fromPair :: (a,b) -> SPair a b fromPair (a, b) = SPair (\f -> f a b) fst :: SPair a b -> a fst sp = runPair sp const snd :: SPair a b -> b snd sp = runPair sp (\_ b -> b) swap :: SPair a b -> SPair b a swap sp = fromPair (snd sp, fst sp) curry :: (SPair a b -> c) -> (a -> b -> c) curry f a b = f $ fromPair (a, b) uncurry :: (a -> b -> c) -> (SPair a b -> c) uncurry f sp = f (fst sp) (snd sp)
null
https://raw.githubusercontent.com/soulomoon/haskell-katas/0861338e945e5cbaadf98138cf8f5f24a6ca8bb3/src/Kyu1/ScottEncoding.hs
haskell
# LANGUAGE ScopedTypeVariables, Rank2Types #
module Kyu1.ScottEncoding where import Prelude hiding (null, length, map, foldl, foldr, take, fst, snd, curry, uncurry, concat, zip, (++)) newtype SMaybe a = SMaybe { runMaybe :: forall b. b -> (a -> b) -> b } newtype SList a = SList { runList :: forall b. b -> (a -> SList a -> b) -> b } newtype SEither a b = SEither { runEither :: forall c. (a -> c) -> (b -> c) -> c } newtype SPair a b = SPair { runPair :: forall c. (a -> b -> c) -> c } toEither :: SEither a b -> Either a b toEither seab = runEither seab Left Right fromEither :: Either a b -> SEither a b fromEither (Left a) = SEither $ \ac bc -> ac a fromEither (Right b) = SEither $ \ac bc -> bc b isLeft :: SEither a b -> Bool isLeft e = case toEither e of Left _ -> True Right _ -> False isRight :: SEither a b -> Bool isRight = not . isLeft partition :: SList (SEither a b) -> SPair (SList a) (SList b) partition = fromPair . foldr (\a (lista, listb)-> case toEither a of Left a -> (cons a lista, listb) Right b -> (lista, cons b listb)) (SList const, SList const) toList :: SList a -> [a] toList mb = runList mb [] (\x rest -> x:toList rest) fromList :: [a] -> SList a fromList [] = SList const fromList (x:xs)= SList $ \_ f -> f x (fromList xs) cons :: a -> SList a -> SList a cons a list = SList $ \_ f -> f a list concat :: SList a -> SList a -> SList a concat x y | null x = y | otherwise = runList x (SList const) (\r rest -> cons r $ concat rest y) null :: SList a -> Bool null mb = case toList mb of [] -> True x:_ -> False length :: SList a -> Int length mb = runList mb 0 (\ x rest -> 1 + length rest) map :: (a -> b) -> SList a -> SList b map g mb | null mb = SList const | otherwise = runList mb (SList const) (\x rest -> cons (g x) $ map g rest) zip :: SList a -> SList b -> SList (SPair a b) zip ma mb = case (toList ma, toList mb) of (x:xs, y:ys) -> cons (fromPair (x, y)) $ zip (fromList xs) (fromList ys) _ -> SList const foldl :: (b -> a -> b) -> b -> SList a -> b foldl f b l = runList l b (\x rest -> foldl f (f b x) rest) foldr :: (a -> b -> b) -> b -> SList a -> b foldr f b l = runList l b (\x rest -> f x (foldr f b rest)) take :: Int -> SList a -> SList a take m list = runList list (SList const) (\x rest -> case m of 0 -> SList const _ -> cons x $ take (m-1) rest) toMaybe :: SMaybe a -> Maybe a toMaybe mb = runMaybe mb Nothing Just fromMaybe :: Maybe a -> SMaybe a fromMaybe (Just a) = SMaybe $ \b f -> f a fromMaybe Nothing = SMaybe const isJust :: SMaybe a -> Bool isJust mb = case toMaybe mb of Just _ -> True Nothing -> False isNothing :: SMaybe a -> Bool isNothing = not . isJust catMaybes :: SList (SMaybe a) -> SList a catMaybes = foldr (\x rest -> case toMaybe x of Nothing -> rest Just x -> cons x rest) (SList const) toPair :: SPair a b -> (a,b) toPair (SPair sp) = sp (\a b -> (a, b)) fromPair :: (a,b) -> SPair a b fromPair (a, b) = SPair (\f -> f a b) fst :: SPair a b -> a fst sp = runPair sp const snd :: SPair a b -> b snd sp = runPair sp (\_ b -> b) swap :: SPair a b -> SPair b a swap sp = fromPair (snd sp, fst sp) curry :: (SPair a b -> c) -> (a -> b -> c) curry f a b = f $ fromPair (a, b) uncurry :: (a -> b -> c) -> (SPair a b -> c) uncurry f sp = f (fst sp) (snd sp)
ed2bb5e9d4ca68d2d15c1dd9d364ac274b6e4e3a3d44a36a9c3b11d1390f1e3a
robert-strandh/Cluster
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:cluster.disassembler (:use #:common-lisp) (:local-nicknames (#:c #:cluster)) (:export #:make-interpreter #:make-debug-interpreter #:*x86-table* #:decode-instruction #:decode-sequence #:instruction-descriptor #:start-position))
null
https://raw.githubusercontent.com/robert-strandh/Cluster/370410b1c685f2afd77f959a46ba49923a31a33c/Disassembler/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:cluster.disassembler (:use #:common-lisp) (:local-nicknames (#:c #:cluster)) (:export #:make-interpreter #:make-debug-interpreter #:*x86-table* #:decode-instruction #:decode-sequence #:instruction-descriptor #:start-position))
0f6d7bb0c8da288f24efb96736ff93b4b57ce8c9200079f1250c3043bfb1dd9a
unison-code/unison
MinimalRegisterClassDecl.hs
This file has been generated by specsgen . Do not modify by hand ! module Unison.Target.Minimal.SpecsGen.MinimalRegisterClassDecl (MinimalRegisterClass(..)) where data MinimalRegisterClass = M32 | R32 deriving (Eq, Ord, Read, Show)
null
https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison/src/Unison/Target/Minimal/SpecsGen/MinimalRegisterClassDecl.hs
haskell
This file has been generated by specsgen . Do not modify by hand ! module Unison.Target.Minimal.SpecsGen.MinimalRegisterClassDecl (MinimalRegisterClass(..)) where data MinimalRegisterClass = M32 | R32 deriving (Eq, Ord, Read, Show)
e18e1eeb31ac9d6b694e6e9994a72c6c66a1d27bae61d32faf26f16bbe815272
BillHallahan/G2
Support.hs
# LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module G2.Language.Monad.Support ( StateT , StateM , StateNGT , StateNG , NameGenT , NameGenM , NamingM (..) , ExprEnvM (..) , ExState (..) , FullState (..) , runStateM , execStateM , runNamingM , runNamingT , runExprEnvM , runStateMInNamingM , runStateNG , execStateNG , readRecord , withNG , mapCurrExpr , insertPC , insertPCStateNG , mapMAccumB ) where import Control.Monad.Identity import qualified Control.Monad.State.Lazy as SM import G2.Language.Naming import qualified G2.Language.PathConds as PC import G2.Language.Syntax import G2.Language.Support import G2.Language.TypeClasses | A wrapper for ` State ` , allowing it to be used as a monadic context . type StateT t m a = SM.StateT (State t, Bindings) m a type StateM t a = StateT t Identity a type StateNGT t m a = SM.StateT (State t, NameGen) m a type StateNG t a = StateNGT t Identity a | A wrapper for ` NameGen ` , allowing it to be used as a monadic context . type NameGenT m a = SM.StateT NameGen m a type NameGenM a = NameGenT Identity a | A wrapper for ` ExprEnv ` , allowing it to be used as a monadic context . type EET m a = SM.StateT ExprEnv m a type EEM a = EET Identity a instance SM.MonadState ( State t , Bindings ) ( SM.State ( State t , Bindings ) ) where state f = StateM ( SM.state f ) instance SM.MonadState ( State t , ) ( SM.State ( State t , ) ) where state f = StateNG ( SM.state f ) instance ( SM.State NameGen ) where state f = NameGenM ( SM.state f ) We split the State Monad into two pieces , so we can use it in the initialization stage of G2 ( in this stage , we do not have an entire State . -- See G2.Initialization.Types), or so that we can just use it with smaller -- pieces of a state. class Monad m => NamingM s m | m -> s where nameGen :: m NameGen putNameGen :: NameGen -> m () class Monad m => ExprEnvM s m | m -> s where exprEnv :: m ExprEnv putExprEnv :: ExprEnv -> m () -- | Allows access to certain basic components of a state. class (ExprEnvM s m, NamingM s m) => ExState s m | m -> s where typeEnv :: m TypeEnv putTypeEnv :: TypeEnv -> m () knownValues :: m KnownValues putKnownValues :: KnownValues -> m () typeClasses :: m TypeClasses putTypeClasses :: TypeClasses -> m () Extends ` ExState ` , allowing access to a more complete set of the -- components in the `State`. class ExState s m => FullState s m | m -> s where currExpr :: m CurrExpr putCurrExpr :: CurrExpr -> m () pathConds :: m PathConds putPathConds :: PathConds -> m () inputNames :: m [Name] fixedInputs :: m [Expr] instance Monad m => NamingM NameGen (SM.StateT NameGen m) where nameGen = SM.get putNameGen = SM.put instance Monad m => NamingM (State t, Bindings) (SM.StateT (State t, Bindings) m) where nameGen = readRecord (\(_, b) -> name_gen b) putNameGen = rep_name_genM instance Monad m => NamingM (State t, NameGen) (SM.StateT (State t, NameGen) m) where nameGen = readRecord (\(_, ng) -> ng) putNameGen = rep_name_genNG instance ExprEnvM (State t, Bindings) (SM.State (State t, Bindings)) where exprEnv = readRecord (\(s, _) -> expr_env s) putExprEnv = rep_expr_envM instance ExprEnvM (State t, NameGen) (SM.State (State t, NameGen)) where exprEnv = readRecord (\(s, _) -> expr_env s) putExprEnv = rep_expr_envNG instance ExState (State t, Bindings) (SM.State (State t, Bindings)) where typeEnv = readRecord (\(s, _) -> type_env s) putTypeEnv = rep_type_envM knownValues = readRecord (\(s, _) -> known_values s) putKnownValues = rep_known_valuesM typeClasses = readRecord (\(s, _) -> type_classes s) putTypeClasses = rep_type_classesM instance ExState (State t, NameGen) (SM.State (State t, NameGen)) where typeEnv = readRecord (\(s, _) -> type_env s) putTypeEnv = rep_type_envNG knownValues = readRecord (\(s, _) -> known_values s) putKnownValues = rep_known_valuesNG typeClasses = readRecord (\(s, _) -> type_classes s) putTypeClasses = rep_type_classesNG instance FullState (State t, Bindings) (SM.State (State t, Bindings)) where currExpr = readRecord (\(s, _) -> curr_expr s) putCurrExpr = rep_curr_exprM pathConds = readRecord (\(s, _) -> path_conds s) putPathConds = rep_path_condsM inputNames = readRecord (\(_, b) -> input_names b) fixedInputs = readRecord (\(_,b) -> fixed_inputs b) runStateM :: StateM t a -> State t -> Bindings -> (a, (State t, Bindings)) runStateM s s' b = SM.runState s (s', b) execStateM :: StateM t a -> State t -> Bindings -> (State t, Bindings) execStateM s = (\lh_s b -> snd (runStateM s lh_s b)) runStateNG :: StateNG t a -> State t -> NameGen -> (a, (State t, NameGen)) runStateNG s s' ng = SM.runState s (s', ng) execStateNG :: StateNG t a -> State t -> NameGen -> (State t, NameGen) execStateNG s = (\lh_s ng -> snd (runStateNG s lh_s ng)) runNamingT :: NameGenT m a -> NameGen -> m (a, NameGen) runNamingT s = SM.runStateT s runNamingM :: NameGenM a -> NameGen -> (a, NameGen) runNamingM s = SM.runState s runExprEnvM :: EEM a -> ExprEnv -> (a, ExprEnv) runExprEnvM s = SM.runState s runStateMInNamingM :: (Monad m, NamingM s m) => StateNG t a -> State t -> m (a, State t) runStateMInNamingM m s = do ng <- nameGen let (a, (s', ng')) = runStateNG m s ng putNameGen ng' return (a, s') readRecord :: SM.MonadState s m => (s -> r) -> m r readRecord f = return . f =<< SM.get rep_expr_envM :: ExprEnv -> StateM t () rep_expr_envM eenv = do (s,b) <- SM.get SM.put $ (s {expr_env = eenv}, b) rep_expr_envNG :: ExprEnv -> StateNG t () rep_expr_envNG eenv = do (s,b) <- SM.get SM.put $ (s {expr_env = eenv}, b) rep_type_envM :: TypeEnv -> StateM t () rep_type_envM tenv = do (s,b) <- SM.get SM.put $ (s {type_env = tenv}, b) rep_type_envNG :: TypeEnv -> StateNG t () rep_type_envNG tenv = do (s,b) <- SM.get SM.put $ (s {type_env = tenv}, b) withNG :: NamingM s m => (NameGen -> (a, NameGen)) -> m a withNG f = do ng <- nameGen let (a, ng') = f ng putNameGen ng' return a rep_name_genM :: Monad m => NameGen -> StateT t m () rep_name_genM ng = do (s,b) <- SM.get SM.put $ (s, b {name_gen = ng}) rep_name_genNG :: Monad m => NameGen -> StateNGT t m () rep_name_genNG ng = do (s, _) <- SM.get SM.put $ (s, ng) rep_known_valuesM :: KnownValues -> StateM t () rep_known_valuesM kv = do (s, b) <- SM.get SM.put $ (s {known_values = kv}, b) rep_known_valuesNG :: KnownValues -> StateNG t () rep_known_valuesNG kv = do (s, b) <- SM.get SM.put $ (s {known_values = kv}, b) rep_type_classesM :: TypeClasses -> StateM t () rep_type_classesM tc = do (s, b) <- SM.get SM.put $ (s {type_classes = tc}, b) rep_type_classesNG :: TypeClasses -> StateNG t () rep_type_classesNG tc = do (s, b) <- SM.get SM.put $ (s {type_classes = tc}, b) rep_curr_exprM :: CurrExpr -> StateM t () rep_curr_exprM ce = do (s, b) <- SM.get SM.put $ (s {curr_expr = ce}, b) mapCurrExpr :: FullState s m => (Expr -> m Expr) -> m () mapCurrExpr f = do (CurrExpr er e) <- currExpr e' <- f e putCurrExpr (CurrExpr er e') rep_path_condsM :: PathConds -> StateM t () rep_path_condsM pc = do (s, b) <- SM.get SM.put $ (s {path_conds = pc}, b) insertPC :: FullState s m => PathCond -> m () insertPC pc = do pcs <- pathConds putPathConds $ PC.insert pc pcs insertPCStateNG :: PathCond -> StateNG t () insertPCStateNG pc = do (s@(State { path_conds = pcs }), ng) <- SM.get SM.put (s { path_conds = PC.insert pc pcs}, ng) mapMAccumB :: Monad m => (a -> b -> m (a, c)) -> a -> [b] -> m (a, [c]) mapMAccumB _ a [] = do return (a, []) mapMAccumB f a (x:xs) = do (a', res) <- f a x (a'', res2) <- mapMAccumB f a' xs return $ (a'', res:res2)
null
https://raw.githubusercontent.com/BillHallahan/G2/3bf78e2d413b458b896f16d8bf4abc5edb9eb9b7/src/G2/Language/Monad/Support.hs
haskell
See G2.Initialization.Types), or so that we can just use it with smaller pieces of a state. | Allows access to certain basic components of a state. components in the `State`.
# LANGUAGE FunctionalDependencies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module G2.Language.Monad.Support ( StateT , StateM , StateNGT , StateNG , NameGenT , NameGenM , NamingM (..) , ExprEnvM (..) , ExState (..) , FullState (..) , runStateM , execStateM , runNamingM , runNamingT , runExprEnvM , runStateMInNamingM , runStateNG , execStateNG , readRecord , withNG , mapCurrExpr , insertPC , insertPCStateNG , mapMAccumB ) where import Control.Monad.Identity import qualified Control.Monad.State.Lazy as SM import G2.Language.Naming import qualified G2.Language.PathConds as PC import G2.Language.Syntax import G2.Language.Support import G2.Language.TypeClasses | A wrapper for ` State ` , allowing it to be used as a monadic context . type StateT t m a = SM.StateT (State t, Bindings) m a type StateM t a = StateT t Identity a type StateNGT t m a = SM.StateT (State t, NameGen) m a type StateNG t a = StateNGT t Identity a | A wrapper for ` NameGen ` , allowing it to be used as a monadic context . type NameGenT m a = SM.StateT NameGen m a type NameGenM a = NameGenT Identity a | A wrapper for ` ExprEnv ` , allowing it to be used as a monadic context . type EET m a = SM.StateT ExprEnv m a type EEM a = EET Identity a instance SM.MonadState ( State t , Bindings ) ( SM.State ( State t , Bindings ) ) where state f = StateM ( SM.state f ) instance SM.MonadState ( State t , ) ( SM.State ( State t , ) ) where state f = StateNG ( SM.state f ) instance ( SM.State NameGen ) where state f = NameGenM ( SM.state f ) We split the State Monad into two pieces , so we can use it in the initialization stage of G2 ( in this stage , we do not have an entire State . class Monad m => NamingM s m | m -> s where nameGen :: m NameGen putNameGen :: NameGen -> m () class Monad m => ExprEnvM s m | m -> s where exprEnv :: m ExprEnv putExprEnv :: ExprEnv -> m () class (ExprEnvM s m, NamingM s m) => ExState s m | m -> s where typeEnv :: m TypeEnv putTypeEnv :: TypeEnv -> m () knownValues :: m KnownValues putKnownValues :: KnownValues -> m () typeClasses :: m TypeClasses putTypeClasses :: TypeClasses -> m () Extends ` ExState ` , allowing access to a more complete set of the class ExState s m => FullState s m | m -> s where currExpr :: m CurrExpr putCurrExpr :: CurrExpr -> m () pathConds :: m PathConds putPathConds :: PathConds -> m () inputNames :: m [Name] fixedInputs :: m [Expr] instance Monad m => NamingM NameGen (SM.StateT NameGen m) where nameGen = SM.get putNameGen = SM.put instance Monad m => NamingM (State t, Bindings) (SM.StateT (State t, Bindings) m) where nameGen = readRecord (\(_, b) -> name_gen b) putNameGen = rep_name_genM instance Monad m => NamingM (State t, NameGen) (SM.StateT (State t, NameGen) m) where nameGen = readRecord (\(_, ng) -> ng) putNameGen = rep_name_genNG instance ExprEnvM (State t, Bindings) (SM.State (State t, Bindings)) where exprEnv = readRecord (\(s, _) -> expr_env s) putExprEnv = rep_expr_envM instance ExprEnvM (State t, NameGen) (SM.State (State t, NameGen)) where exprEnv = readRecord (\(s, _) -> expr_env s) putExprEnv = rep_expr_envNG instance ExState (State t, Bindings) (SM.State (State t, Bindings)) where typeEnv = readRecord (\(s, _) -> type_env s) putTypeEnv = rep_type_envM knownValues = readRecord (\(s, _) -> known_values s) putKnownValues = rep_known_valuesM typeClasses = readRecord (\(s, _) -> type_classes s) putTypeClasses = rep_type_classesM instance ExState (State t, NameGen) (SM.State (State t, NameGen)) where typeEnv = readRecord (\(s, _) -> type_env s) putTypeEnv = rep_type_envNG knownValues = readRecord (\(s, _) -> known_values s) putKnownValues = rep_known_valuesNG typeClasses = readRecord (\(s, _) -> type_classes s) putTypeClasses = rep_type_classesNG instance FullState (State t, Bindings) (SM.State (State t, Bindings)) where currExpr = readRecord (\(s, _) -> curr_expr s) putCurrExpr = rep_curr_exprM pathConds = readRecord (\(s, _) -> path_conds s) putPathConds = rep_path_condsM inputNames = readRecord (\(_, b) -> input_names b) fixedInputs = readRecord (\(_,b) -> fixed_inputs b) runStateM :: StateM t a -> State t -> Bindings -> (a, (State t, Bindings)) runStateM s s' b = SM.runState s (s', b) execStateM :: StateM t a -> State t -> Bindings -> (State t, Bindings) execStateM s = (\lh_s b -> snd (runStateM s lh_s b)) runStateNG :: StateNG t a -> State t -> NameGen -> (a, (State t, NameGen)) runStateNG s s' ng = SM.runState s (s', ng) execStateNG :: StateNG t a -> State t -> NameGen -> (State t, NameGen) execStateNG s = (\lh_s ng -> snd (runStateNG s lh_s ng)) runNamingT :: NameGenT m a -> NameGen -> m (a, NameGen) runNamingT s = SM.runStateT s runNamingM :: NameGenM a -> NameGen -> (a, NameGen) runNamingM s = SM.runState s runExprEnvM :: EEM a -> ExprEnv -> (a, ExprEnv) runExprEnvM s = SM.runState s runStateMInNamingM :: (Monad m, NamingM s m) => StateNG t a -> State t -> m (a, State t) runStateMInNamingM m s = do ng <- nameGen let (a, (s', ng')) = runStateNG m s ng putNameGen ng' return (a, s') readRecord :: SM.MonadState s m => (s -> r) -> m r readRecord f = return . f =<< SM.get rep_expr_envM :: ExprEnv -> StateM t () rep_expr_envM eenv = do (s,b) <- SM.get SM.put $ (s {expr_env = eenv}, b) rep_expr_envNG :: ExprEnv -> StateNG t () rep_expr_envNG eenv = do (s,b) <- SM.get SM.put $ (s {expr_env = eenv}, b) rep_type_envM :: TypeEnv -> StateM t () rep_type_envM tenv = do (s,b) <- SM.get SM.put $ (s {type_env = tenv}, b) rep_type_envNG :: TypeEnv -> StateNG t () rep_type_envNG tenv = do (s,b) <- SM.get SM.put $ (s {type_env = tenv}, b) withNG :: NamingM s m => (NameGen -> (a, NameGen)) -> m a withNG f = do ng <- nameGen let (a, ng') = f ng putNameGen ng' return a rep_name_genM :: Monad m => NameGen -> StateT t m () rep_name_genM ng = do (s,b) <- SM.get SM.put $ (s, b {name_gen = ng}) rep_name_genNG :: Monad m => NameGen -> StateNGT t m () rep_name_genNG ng = do (s, _) <- SM.get SM.put $ (s, ng) rep_known_valuesM :: KnownValues -> StateM t () rep_known_valuesM kv = do (s, b) <- SM.get SM.put $ (s {known_values = kv}, b) rep_known_valuesNG :: KnownValues -> StateNG t () rep_known_valuesNG kv = do (s, b) <- SM.get SM.put $ (s {known_values = kv}, b) rep_type_classesM :: TypeClasses -> StateM t () rep_type_classesM tc = do (s, b) <- SM.get SM.put $ (s {type_classes = tc}, b) rep_type_classesNG :: TypeClasses -> StateNG t () rep_type_classesNG tc = do (s, b) <- SM.get SM.put $ (s {type_classes = tc}, b) rep_curr_exprM :: CurrExpr -> StateM t () rep_curr_exprM ce = do (s, b) <- SM.get SM.put $ (s {curr_expr = ce}, b) mapCurrExpr :: FullState s m => (Expr -> m Expr) -> m () mapCurrExpr f = do (CurrExpr er e) <- currExpr e' <- f e putCurrExpr (CurrExpr er e') rep_path_condsM :: PathConds -> StateM t () rep_path_condsM pc = do (s, b) <- SM.get SM.put $ (s {path_conds = pc}, b) insertPC :: FullState s m => PathCond -> m () insertPC pc = do pcs <- pathConds putPathConds $ PC.insert pc pcs insertPCStateNG :: PathCond -> StateNG t () insertPCStateNG pc = do (s@(State { path_conds = pcs }), ng) <- SM.get SM.put (s { path_conds = PC.insert pc pcs}, ng) mapMAccumB :: Monad m => (a -> b -> m (a, c)) -> a -> [b] -> m (a, [c]) mapMAccumB _ a [] = do return (a, []) mapMAccumB f a (x:xs) = do (a', res) <- f a x (a'', res2) <- mapMAccumB f a' xs return $ (a'', res:res2)
2d267a3632c3e3f87c378abeaf73eff5cb9f162ac154a212304fde2575339d90
waldheinz/bling
Progress.hs
module Graphics.Bling.IO.Progress ( (<&>), progressWriter ) where import System.FilePath import Text.Printf import Graphics.Bling.IO.Bitmap import Graphics.Bling.Rendering | allows to combine two progress reporters into a new one . the new -- reporter will request continued operation iff both of the provided -- reporters did so (<&>) :: ProgressReporter -> ProgressReporter -> ProgressReporter (<&>) p1 p2 prog = do r1 <- p1 prog r2 <- p2 prog return $ r1 && r2 -- | a progress reporter which will write every complete rendering pass to -- a separate, numbered file progressWriter :: FilePath -- ^ the basename, will get pass number and extension appended -> ProgressReporter progressWriter baseName (PassDone p img _) = do putStrLn $ "\nWriting " ++ fname ++ "..." writePng img $ fname <.> "png" writeRgbe img $ fname <.> "hdr" return True where fname = baseName ++ "-" ++ printf "%05d" p progressWriter _ _ = return True
null
https://raw.githubusercontent.com/waldheinz/bling/1f338f4b8dbd6a2708cb10787f4a2ac55f66d5a8/src/lib/Graphics/Bling/IO/Progress.hs
haskell
reporter will request continued operation iff both of the provided reporters did so | a progress reporter which will write every complete rendering pass to a separate, numbered file ^ the basename, will get pass number and extension appended
module Graphics.Bling.IO.Progress ( (<&>), progressWriter ) where import System.FilePath import Text.Printf import Graphics.Bling.IO.Bitmap import Graphics.Bling.Rendering | allows to combine two progress reporters into a new one . the new (<&>) :: ProgressReporter -> ProgressReporter -> ProgressReporter (<&>) p1 p2 prog = do r1 <- p1 prog r2 <- p2 prog return $ r1 && r2 progressWriter -> ProgressReporter progressWriter baseName (PassDone p img _) = do putStrLn $ "\nWriting " ++ fname ++ "..." writePng img $ fname <.> "png" writeRgbe img $ fname <.> "hdr" return True where fname = baseName ++ "-" ++ printf "%05d" p progressWriter _ _ = return True
5c140abfc4986c81db9c41d59dc2fdbc94c472bc78c182081c1f935c8d4d9d67
master/ejabberd
node_private.erl
%%% ==================================================================== ` ` The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %%% compliance with the License. You should have received a copy of the %%% Erlang Public License along with this software. If not, it can be %%% retrieved via the world wide web at /. %%% Software distributed under the License is distributed on an " AS IS " %%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %%% the License for the specific language governing rights and limitations %%% under the License. %%% The Initial Developer of the Original Code is ProcessOne . Portions created by ProcessOne are Copyright 2006 - 2012 , ProcessOne All Rights Reserved . '' This software is copyright 2006 - 2012 , ProcessOne . %%% %%% 2006 - 2012 ProcessOne @author > %%% [-one.net/] %%% @version {@vsn}, {@date} {@time} %%% @end %%% ==================================================================== -module(node_private). -author(''). -include("pubsub.hrl"). -include("jlib.hrl"). -behaviour(gen_pubsub_node). %% Note on function definition %% included is all defined plugin function %% it's possible not to define some function at all %% in that case, warning will be generated at compilation %% and function call will fail, %% then mod_pubsub will call function from node_hometree %% (this makes code cleaner, but execution a little bit longer) %% API definition -export([init/3, terminate/2, options/0, features/0, create_node_permission/6, create_node/2, delete_node/1, purge_node/2, subscribe_node/8, unsubscribe_node/4, publish_item/6, delete_item/4, remove_extra_items/3, get_entity_affiliations/2, get_node_affiliations/1, get_affiliation/2, set_affiliation/3, get_entity_subscriptions/2, get_node_subscriptions/1, get_subscriptions/2, set_subscriptions/4, get_pending_nodes/2, get_states/1, get_state/2, set_state/1, get_items/6, get_items/2, get_item/7, get_item/2, set_item/1, get_item_name/3, node_to_path/1, path_to_node/1 ]). init(Host, ServerHost, Opts) -> node_hometree:init(Host, ServerHost, Opts). terminate(Host, ServerHost) -> node_hometree:terminate(Host, ServerHost). options() -> [{deliver_payloads, true}, {notify_config, false}, {notify_delete, false}, {notify_retract, true}, {purge_offline, false}, {persist_items, true}, {max_items, ?MAXITEMS}, {subscribe, true}, {access_model, whitelist}, {roster_groups_allowed, []}, {publish_model, publishers}, {notification_type, headline}, {max_payload_size, ?MAX_PAYLOAD_SIZE}, {send_last_published_item, never}, {deliver_notifications, false}, {presence_based_delivery, false}]. features() -> ["create-nodes", "delete-nodes", "delete-items", "instant-nodes", "outcast-affiliation", "persistent-items", "publish", "purge-nodes", "retract-items", "retrieve-affiliations", "retrieve-items", "retrieve-subscriptions", "subscribe", "subscription-notifications" ]. create_node_permission(Host, ServerHost, Node, ParentNode, Owner, Access) -> node_hometree:create_node_permission(Host, ServerHost, Node, ParentNode, Owner, Access). create_node(NodeId, Owner) -> node_hometree:create_node(NodeId, Owner). delete_node(Removed) -> node_hometree:delete_node(Removed). subscribe_node(NodeId, Sender, Subscriber, AccessModel, SendLast, PresenceSubscription, RosterGroup, Options) -> node_hometree:subscribe_node(NodeId, Sender, Subscriber, AccessModel, SendLast, PresenceSubscription, RosterGroup, Options). unsubscribe_node(NodeId, Sender, Subscriber, SubID) -> node_hometree:unsubscribe_node(NodeId, Sender, Subscriber, SubID). publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload) -> node_hometree:publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload). remove_extra_items(NodeId, MaxItems, ItemIds) -> node_hometree:remove_extra_items(NodeId, MaxItems, ItemIds). delete_item(NodeId, Publisher, PublishModel, ItemId) -> node_hometree:delete_item(NodeId, Publisher, PublishModel, ItemId). purge_node(NodeId, Owner) -> node_hometree:purge_node(NodeId, Owner). get_entity_affiliations(Host, Owner) -> node_hometree:get_entity_affiliations(Host, Owner). get_node_affiliations(NodeId) -> node_hometree:get_node_affiliations(NodeId). get_affiliation(NodeId, Owner) -> node_hometree:get_affiliation(NodeId, Owner). set_affiliation(NodeId, Owner, Affiliation) -> node_hometree:set_affiliation(NodeId, Owner, Affiliation). get_entity_subscriptions(Host, Owner) -> node_hometree:get_entity_subscriptions(Host, Owner). get_node_subscriptions(NodeId) -> node_hometree:get_node_subscriptions(NodeId). get_subscriptions(NodeId, Owner) -> node_hometree:get_subscriptions(NodeId, Owner). set_subscriptions(NodeId, Owner, Subscription, SubId) -> node_hometree:set_subscriptions(NodeId, Owner, Subscription, SubId). get_pending_nodes(Host, Owner) -> node_hometree:get_pending_nodes(Host, Owner). get_states(NodeId) -> node_hometree:get_states(NodeId). get_state(NodeId, JID) -> node_hometree:get_state(NodeId, JID). set_state(State) -> node_hometree:set_state(State). get_items(NodeId, From) -> node_hometree:get_items(NodeId, From). get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) -> node_hometree:get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId). get_item(NodeId, ItemId) -> node_hometree:get_item(NodeId, ItemId). get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) -> node_hometree:get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId). set_item(Item) -> node_hometree:set_item(Item). get_item_name(Host, Node, Id) -> node_hometree:get_item_name(Host, Node, Id). node_to_path(Node) -> node_flat:node_to_path(Node). path_to_node(Path) -> node_flat:path_to_node(Path).
null
https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/mod_pubsub/node_private.erl
erlang
==================================================================== compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved via the world wide web at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. [-one.net/] @version {@vsn}, {@date} {@time} @end ==================================================================== Note on function definition included is all defined plugin function it's possible not to define some function at all in that case, warning will be generated at compilation and function call will fail, then mod_pubsub will call function from node_hometree (this makes code cleaner, but execution a little bit longer) API definition
` ` The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Initial Developer of the Original Code is ProcessOne . Portions created by ProcessOne are Copyright 2006 - 2012 , ProcessOne All Rights Reserved . '' This software is copyright 2006 - 2012 , ProcessOne . 2006 - 2012 ProcessOne @author > -module(node_private). -author(''). -include("pubsub.hrl"). -include("jlib.hrl"). -behaviour(gen_pubsub_node). -export([init/3, terminate/2, options/0, features/0, create_node_permission/6, create_node/2, delete_node/1, purge_node/2, subscribe_node/8, unsubscribe_node/4, publish_item/6, delete_item/4, remove_extra_items/3, get_entity_affiliations/2, get_node_affiliations/1, get_affiliation/2, set_affiliation/3, get_entity_subscriptions/2, get_node_subscriptions/1, get_subscriptions/2, set_subscriptions/4, get_pending_nodes/2, get_states/1, get_state/2, set_state/1, get_items/6, get_items/2, get_item/7, get_item/2, set_item/1, get_item_name/3, node_to_path/1, path_to_node/1 ]). init(Host, ServerHost, Opts) -> node_hometree:init(Host, ServerHost, Opts). terminate(Host, ServerHost) -> node_hometree:terminate(Host, ServerHost). options() -> [{deliver_payloads, true}, {notify_config, false}, {notify_delete, false}, {notify_retract, true}, {purge_offline, false}, {persist_items, true}, {max_items, ?MAXITEMS}, {subscribe, true}, {access_model, whitelist}, {roster_groups_allowed, []}, {publish_model, publishers}, {notification_type, headline}, {max_payload_size, ?MAX_PAYLOAD_SIZE}, {send_last_published_item, never}, {deliver_notifications, false}, {presence_based_delivery, false}]. features() -> ["create-nodes", "delete-nodes", "delete-items", "instant-nodes", "outcast-affiliation", "persistent-items", "publish", "purge-nodes", "retract-items", "retrieve-affiliations", "retrieve-items", "retrieve-subscriptions", "subscribe", "subscription-notifications" ]. create_node_permission(Host, ServerHost, Node, ParentNode, Owner, Access) -> node_hometree:create_node_permission(Host, ServerHost, Node, ParentNode, Owner, Access). create_node(NodeId, Owner) -> node_hometree:create_node(NodeId, Owner). delete_node(Removed) -> node_hometree:delete_node(Removed). subscribe_node(NodeId, Sender, Subscriber, AccessModel, SendLast, PresenceSubscription, RosterGroup, Options) -> node_hometree:subscribe_node(NodeId, Sender, Subscriber, AccessModel, SendLast, PresenceSubscription, RosterGroup, Options). unsubscribe_node(NodeId, Sender, Subscriber, SubID) -> node_hometree:unsubscribe_node(NodeId, Sender, Subscriber, SubID). publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload) -> node_hometree:publish_item(NodeId, Publisher, Model, MaxItems, ItemId, Payload). remove_extra_items(NodeId, MaxItems, ItemIds) -> node_hometree:remove_extra_items(NodeId, MaxItems, ItemIds). delete_item(NodeId, Publisher, PublishModel, ItemId) -> node_hometree:delete_item(NodeId, Publisher, PublishModel, ItemId). purge_node(NodeId, Owner) -> node_hometree:purge_node(NodeId, Owner). get_entity_affiliations(Host, Owner) -> node_hometree:get_entity_affiliations(Host, Owner). get_node_affiliations(NodeId) -> node_hometree:get_node_affiliations(NodeId). get_affiliation(NodeId, Owner) -> node_hometree:get_affiliation(NodeId, Owner). set_affiliation(NodeId, Owner, Affiliation) -> node_hometree:set_affiliation(NodeId, Owner, Affiliation). get_entity_subscriptions(Host, Owner) -> node_hometree:get_entity_subscriptions(Host, Owner). get_node_subscriptions(NodeId) -> node_hometree:get_node_subscriptions(NodeId). get_subscriptions(NodeId, Owner) -> node_hometree:get_subscriptions(NodeId, Owner). set_subscriptions(NodeId, Owner, Subscription, SubId) -> node_hometree:set_subscriptions(NodeId, Owner, Subscription, SubId). get_pending_nodes(Host, Owner) -> node_hometree:get_pending_nodes(Host, Owner). get_states(NodeId) -> node_hometree:get_states(NodeId). get_state(NodeId, JID) -> node_hometree:get_state(NodeId, JID). set_state(State) -> node_hometree:set_state(State). get_items(NodeId, From) -> node_hometree:get_items(NodeId, From). get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) -> node_hometree:get_items(NodeId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId). get_item(NodeId, ItemId) -> node_hometree:get_item(NodeId, ItemId). get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId) -> node_hometree:get_item(NodeId, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, SubId). set_item(Item) -> node_hometree:set_item(Item). get_item_name(Host, Node, Id) -> node_hometree:get_item_name(Host, Node, Id). node_to_path(Node) -> node_flat:node_to_path(Node). path_to_node(Path) -> node_flat:path_to_node(Path).
30de69684ce056df8595a8ebc8020c80367636ffdd1c86bc6362b1bc05678ad9
digital-asset/ghc
T15552.hs
# LANGUAGE DataKinds , ExistentialQuantification , GADTs , PolyKinds , TypeOperators # # LANGUAGE TypeInType , TypeFamilies # module T15552 where import Data.Kind data Elem :: k -> [k] -> Type data EntryOfVal (v :: Type) (kvs :: [Type]) where EntryOfVal :: forall (v :: Type) (kvs :: [Type]) (k :: Type). Elem (k, v) kvs -> EntryOfVal v kvs type family EntryOfValKey (eov :: EntryOfVal v kvs) :: Type type family GetEntryOfVal (eov :: EntryOfVal v kvs) :: Elem (EntryOfValKey eov, v) kvs type family FirstEntryOfVal (v :: Type) (kvs :: [Type]) :: EntryOfVal v kvs where
null
https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/typecheck/should_fail/T15552.hs
haskell
# LANGUAGE DataKinds , ExistentialQuantification , GADTs , PolyKinds , TypeOperators # # LANGUAGE TypeInType , TypeFamilies # module T15552 where import Data.Kind data Elem :: k -> [k] -> Type data EntryOfVal (v :: Type) (kvs :: [Type]) where EntryOfVal :: forall (v :: Type) (kvs :: [Type]) (k :: Type). Elem (k, v) kvs -> EntryOfVal v kvs type family EntryOfValKey (eov :: EntryOfVal v kvs) :: Type type family GetEntryOfVal (eov :: EntryOfVal v kvs) :: Elem (EntryOfValKey eov, v) kvs type family FirstEntryOfVal (v :: Type) (kvs :: [Type]) :: EntryOfVal v kvs where
e7cfe14bffa2213b7c84d849ca46da8f27a350e9abd2e39d43cf0b7de7868304
kowainik/summoner
Template.hs
| Module : Summoner . Template Copyright : ( c ) 2017 - 2022 Kowainik SPDX - License - Identifier : MPL-2.0 Maintainer : < > Stability : Stable Portability : Portable This module contains functions for the project template creation . Module : Summoner.Template Copyright : (c) 2017-2022 Kowainik SPDX-License-Identifier : MPL-2.0 Maintainer : Kowainik <> Stability : Stable Portability : Portable This module contains functions for the Haskell project template creation. -} module Summoner.Template ( createProjectTemplate ) where import Summoner.Settings (Settings (..)) import Summoner.Template.Cabal (cabalFile) import Summoner.Template.Doc (docFiles) import Summoner.Template.GitHub (gitHubFiles) import Summoner.Template.Haskell (haskellFiles) import Summoner.Template.Stack (stackFiles) import Summoner.Tree (TreeFs (..), insertTree) -- | Creating tree structure of the project. createProjectTemplate :: Settings -> TreeFs createProjectTemplate settings@Settings{..} = Dir (toString settingsRepo) (foldr insertTree generatedFiles settingsFiles) where generatedFiles :: [TreeFs] generatedFiles = concat [ cabal , stack , haskell , docs , gitHub ] cabal, stack :: [TreeFs] cabal = [cabalFile settings] stack = memptyIfFalse settingsStack $ stackFiles settings haskell, docs, gitHub :: [TreeFs] haskell = haskellFiles settings docs = docFiles settings gitHub = gitHubFiles settings
null
https://raw.githubusercontent.com/kowainik/summoner/0c03dd0d6ee71c79227974b697f171396d3d09a7/summoner-cli/src/Summoner/Template.hs
haskell
| Creating tree structure of the project.
| Module : Summoner . Template Copyright : ( c ) 2017 - 2022 Kowainik SPDX - License - Identifier : MPL-2.0 Maintainer : < > Stability : Stable Portability : Portable This module contains functions for the project template creation . Module : Summoner.Template Copyright : (c) 2017-2022 Kowainik SPDX-License-Identifier : MPL-2.0 Maintainer : Kowainik <> Stability : Stable Portability : Portable This module contains functions for the Haskell project template creation. -} module Summoner.Template ( createProjectTemplate ) where import Summoner.Settings (Settings (..)) import Summoner.Template.Cabal (cabalFile) import Summoner.Template.Doc (docFiles) import Summoner.Template.GitHub (gitHubFiles) import Summoner.Template.Haskell (haskellFiles) import Summoner.Template.Stack (stackFiles) import Summoner.Tree (TreeFs (..), insertTree) createProjectTemplate :: Settings -> TreeFs createProjectTemplate settings@Settings{..} = Dir (toString settingsRepo) (foldr insertTree generatedFiles settingsFiles) where generatedFiles :: [TreeFs] generatedFiles = concat [ cabal , stack , haskell , docs , gitHub ] cabal, stack :: [TreeFs] cabal = [cabalFile settings] stack = memptyIfFalse settingsStack $ stackFiles settings haskell, docs, gitHub :: [TreeFs] haskell = haskellFiles settings docs = docFiles settings gitHub = gitHubFiles settings
491e3d32699b9488dc41780f2ba2105e42c3dda61aa55dce2e3b0b5153f7846c
tezos/tezos-mirror
test_sc_rollup_encoding.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2022 Nomadic Labs , < > (* *) (* 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. *) (* *) (*****************************************************************************) * Testing ------- Component : Protocol Library Invocation : dune exec src / proto_alpha / lib_protocol / test / pbt / main.exe \ -- -f ' SC rollup encoding ' Subject : SC rollup encoding ------- Component: Protocol Library Invocation: dune exec src/proto_alpha/lib_protocol/test/pbt/main.exe \ -- -f 'SC rollup encoding' Subject: SC rollup encoding *) open Protocol open QCheck2 open Qcheck2_helpers (** {2 Generators} *) let gen_state_hash = let open Gen in let* bytes = bytes_fixed_gen Sc_rollup_repr.State_hash.size in return (Sc_rollup_repr.State_hash.of_bytes_exn bytes) let gen_inbox_level = let open Gen in let* level = map Int32.abs int32 in There is no inbox for level [ 0l ] . let level = if level = 0l then 1l else level in return (Raw_level_repr.of_int32_exn level) let gen_start_level = let open Gen in let* level = map Int32.abs int32 in let start_level = Raw_level_repr.of_int32_exn level in return start_level let gen_commitment_hash = let open Gen in let* bytes = bytes_fixed_gen Sc_rollup_commitment_repr.Hash.size in return (Sc_rollup_commitment_repr.Hash.of_bytes_exn bytes) let gen_number_of_ticks = let open Gen in let open Sc_rollup_repr.Number_of_ticks in let* v = int64_range_gen min_value max_value in return (WithExceptions.Option.get ~loc:__LOC__ (of_value v)) let gen_commitment = let open Gen in let* compressed_state = gen_state_hash and* inbox_level = gen_inbox_level and* predecessor = gen_commitment_hash and* number_of_ticks = gen_number_of_ticks in return Sc_rollup_commitment_repr. {compressed_state; inbox_level; predecessor; number_of_ticks} let gen_versioned_commitment = let open Gen in let* commitment = gen_commitment in return (Sc_rollup_commitment_repr.to_versioned commitment) let gen_player = Gen.oneofl Sc_rollup_game_repr.[Alice; Bob] let gen_inbox level = let open Gen in let gen_msg = small_string ~gen:printable in let* hd = gen_msg in let* tail = small_list gen_msg in let payloads = hd :: tail in let witness_and_inbox = let open Result_syntax in let inbox = Sc_rollup_helpers.dumb_init_repr level in Environment.wrap_tzresult @@ let witness = Sc_rollup_inbox_repr.init_witness_no_history in let witness = Sc_rollup_inbox_repr.add_info_per_level_no_history ~predecessor_timestamp:Time.Protocol.epoch ~predecessor:Block_hash.zero witness in let* input_messages = List.map_e (fun msg -> Sc_rollup_inbox_message_repr.(serialize (External msg))) payloads in let* witness = Sc_rollup_inbox_repr.add_messages_no_history input_messages witness in return (Sc_rollup_inbox_repr.finalize_inbox_level_no_history inbox witness) in return @@ (witness_and_inbox |> function | Ok v -> v | Error e -> Stdlib.failwith (Format.asprintf "%a" Error_monad.pp_print_trace e)) module Index = Dal_slot_index_repr let gen_dal_slots_history () = let open Gen in let open Dal_slot_repr in (* Generate a list of (level * confirmed slot ID). *) let* list = small_list (pair small_nat small_nat) in let list = List.rev_map (fun (level, slot_index) -> let published_level = Raw_level_repr.( (* use succ to avoid having a published_level = 0, as it's the genesis cell's level in the skip list. *) succ @@ try of_int32_exn (Int32.of_int level) with _ -> root) in let index = Index.of_int_opt slot_index |> Option.value ~default:Index.zero in Header.{id = {published_level; index}; commitment = Commitment.zero}) list in let list = (* Sort the list in the right ordering before adding slots to slots_history. *) List.sort_uniq (fun {Header.id = a; _} {id = b; _} -> let c = Raw_level_repr.compare a.published_level b.published_level in if c <> 0 then c else Index.compare a.index b.index) list in History.(add_confirmed_slot_headers_no_cache genesis list) |> function | Ok v -> return v | Error e -> return @@ Stdlib.failwith (Format.asprintf "%a" Error_monad.pp_print_trace @@ Environment.wrap_tztrace e) let gen_inbox_history_proof inbox_level = let open Gen in let* inbox = gen_inbox inbox_level in return (Sc_rollup_inbox_repr.take_snapshot inbox) let gen_tick = let open Gen in let* t = small_nat in match Sc_rollup_tick_repr.of_int t with | None -> assert false | Some r -> return r let gen_dissection_chunk = let open Gen in let* state_hash = opt gen_state_hash in let+ tick = gen_tick in Sc_rollup_dissection_chunk_repr.{state_hash; tick} let gen_dissection = let open Gen in small_list gen_dissection_chunk let gen_game_state = let open Sc_rollup_game_repr in let open Gen in let gen_dissecting = let* dissection = gen_dissection in let+ default_number_of_sections = int_range 4 100 in Dissecting {dissection; default_number_of_sections} in let gen_final_move = let* agreed_start_chunk = gen_dissection_chunk in let+ refuted_stop_chunk = gen_dissection_chunk in Final_move {agreed_start_chunk; refuted_stop_chunk} in oneof [gen_dissecting; gen_final_move] let gen_game = let open Gen in let* turn = gen_player in let* inbox_level = gen_inbox_level in let* start_level = gen_start_level in let* inbox_snapshot = gen_inbox_history_proof inbox_level in let* dal_snapshot = gen_dal_slots_history () in let* game_state = gen_game_state in return Sc_rollup_game_repr. {turn; dal_snapshot; inbox_snapshot; start_level; inbox_level; game_state} let gen_conflict = let open Gen in let other = Sc_rollup_repr.Staker.zero in let* their_commitment = gen_commitment in let* our_commitment = gen_commitment in let* parent_commitment = gen_commitment_hash in return Sc_rollup_refutation_storage. {other; their_commitment; our_commitment; parent_commitment} let gen_rollup = let open QCheck2.Gen in let* bytes = bytes_fixed_gen Sc_rollup_repr.Address.size in return (Sc_rollup_repr.Address.hash_bytes [bytes]) let gen_inbox_message = let open Gen in let open Sc_rollup_inbox_message_repr in let gen_external = let+ s = small_string ~gen:printable in External s in let gen_sol = return (Internal Start_of_level) in let gen_eol = return (Internal End_of_level) in let gen_deposit = (* We won't test the encoding of these values. It's out of scope. *) let payload = Script_repr.unit in let sender = Contract_hash.zero in let source = Signature.Public_key_hash.zero in (* But the encoding of the rollup's address is our problem. *) let+ destination = gen_rollup in Internal (Transfer {payload; sender; source; destination}) in oneof [gen_external; gen_sol; gen_eol; gen_deposit] * { 2 Tests } let test_commitment = test_roundtrip ~count:1_000 ~title:"Sc_rollup_commitment.t" ~gen:gen_commitment ~eq:( = ) Sc_rollup_commitment_repr.encoding let test_versioned_commitment = test_roundtrip ~count:1_000 ~title:"Sc_rollup_commitment.versioned" ~gen:gen_versioned_commitment ~eq:( = ) Sc_rollup_commitment_repr.versioned_encoding let test_game = test_roundtrip ~count:1_000 ~title:"Sc_rollup_game.t" ~gen:gen_game ~eq:Sc_rollup_game_repr.equal Sc_rollup_game_repr.encoding let test_conflict = test_roundtrip ~count:1_000 ~title:"Sc_rollup_refutation_storage.conflict" ~gen:gen_conflict ~eq:( = ) Sc_rollup_refutation_storage.conflict_encoding let test_inbox_message = test_roundtrip ~count:1_000 ~title:"Sc_rollup_inbox_message_repr.t" ~gen:gen_inbox_message ~eq:( = ) Sc_rollup_inbox_message_repr.encoding let tests = [ test_commitment; test_versioned_commitment; test_game; test_conflict; test_inbox_message; ] let () = Alcotest.run "SC rollup encoding" [(Protocol.name ^ ": roundtrip", qcheck_wrap tests)]
null
https://raw.githubusercontent.com/tezos/tezos-mirror/6cce98810919826c01005f2ffbd02a2302aa91bb/src/proto_alpha/lib_protocol/test/pbt/test_sc_rollup_encoding.ml
ocaml
*************************************************************************** Open Source License 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 in all copies or substantial portions of the Software. 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 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * {2 Generators} Generate a list of (level * confirmed slot ID). use succ to avoid having a published_level = 0, as it's the genesis cell's level in the skip list. Sort the list in the right ordering before adding slots to slots_history. We won't test the encoding of these values. It's out of scope. But the encoding of the rollup's address is our problem.
Copyright ( c ) 2022 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING * Testing ------- Component : Protocol Library Invocation : dune exec src / proto_alpha / lib_protocol / test / pbt / main.exe \ -- -f ' SC rollup encoding ' Subject : SC rollup encoding ------- Component: Protocol Library Invocation: dune exec src/proto_alpha/lib_protocol/test/pbt/main.exe \ -- -f 'SC rollup encoding' Subject: SC rollup encoding *) open Protocol open QCheck2 open Qcheck2_helpers let gen_state_hash = let open Gen in let* bytes = bytes_fixed_gen Sc_rollup_repr.State_hash.size in return (Sc_rollup_repr.State_hash.of_bytes_exn bytes) let gen_inbox_level = let open Gen in let* level = map Int32.abs int32 in There is no inbox for level [ 0l ] . let level = if level = 0l then 1l else level in return (Raw_level_repr.of_int32_exn level) let gen_start_level = let open Gen in let* level = map Int32.abs int32 in let start_level = Raw_level_repr.of_int32_exn level in return start_level let gen_commitment_hash = let open Gen in let* bytes = bytes_fixed_gen Sc_rollup_commitment_repr.Hash.size in return (Sc_rollup_commitment_repr.Hash.of_bytes_exn bytes) let gen_number_of_ticks = let open Gen in let open Sc_rollup_repr.Number_of_ticks in let* v = int64_range_gen min_value max_value in return (WithExceptions.Option.get ~loc:__LOC__ (of_value v)) let gen_commitment = let open Gen in let* compressed_state = gen_state_hash and* inbox_level = gen_inbox_level and* predecessor = gen_commitment_hash and* number_of_ticks = gen_number_of_ticks in return Sc_rollup_commitment_repr. {compressed_state; inbox_level; predecessor; number_of_ticks} let gen_versioned_commitment = let open Gen in let* commitment = gen_commitment in return (Sc_rollup_commitment_repr.to_versioned commitment) let gen_player = Gen.oneofl Sc_rollup_game_repr.[Alice; Bob] let gen_inbox level = let open Gen in let gen_msg = small_string ~gen:printable in let* hd = gen_msg in let* tail = small_list gen_msg in let payloads = hd :: tail in let witness_and_inbox = let open Result_syntax in let inbox = Sc_rollup_helpers.dumb_init_repr level in Environment.wrap_tzresult @@ let witness = Sc_rollup_inbox_repr.init_witness_no_history in let witness = Sc_rollup_inbox_repr.add_info_per_level_no_history ~predecessor_timestamp:Time.Protocol.epoch ~predecessor:Block_hash.zero witness in let* input_messages = List.map_e (fun msg -> Sc_rollup_inbox_message_repr.(serialize (External msg))) payloads in let* witness = Sc_rollup_inbox_repr.add_messages_no_history input_messages witness in return (Sc_rollup_inbox_repr.finalize_inbox_level_no_history inbox witness) in return @@ (witness_and_inbox |> function | Ok v -> v | Error e -> Stdlib.failwith (Format.asprintf "%a" Error_monad.pp_print_trace e)) module Index = Dal_slot_index_repr let gen_dal_slots_history () = let open Gen in let open Dal_slot_repr in let* list = small_list (pair small_nat small_nat) in let list = List.rev_map (fun (level, slot_index) -> let published_level = Raw_level_repr.( succ @@ try of_int32_exn (Int32.of_int level) with _ -> root) in let index = Index.of_int_opt slot_index |> Option.value ~default:Index.zero in Header.{id = {published_level; index}; commitment = Commitment.zero}) list in let list = List.sort_uniq (fun {Header.id = a; _} {id = b; _} -> let c = Raw_level_repr.compare a.published_level b.published_level in if c <> 0 then c else Index.compare a.index b.index) list in History.(add_confirmed_slot_headers_no_cache genesis list) |> function | Ok v -> return v | Error e -> return @@ Stdlib.failwith (Format.asprintf "%a" Error_monad.pp_print_trace @@ Environment.wrap_tztrace e) let gen_inbox_history_proof inbox_level = let open Gen in let* inbox = gen_inbox inbox_level in return (Sc_rollup_inbox_repr.take_snapshot inbox) let gen_tick = let open Gen in let* t = small_nat in match Sc_rollup_tick_repr.of_int t with | None -> assert false | Some r -> return r let gen_dissection_chunk = let open Gen in let* state_hash = opt gen_state_hash in let+ tick = gen_tick in Sc_rollup_dissection_chunk_repr.{state_hash; tick} let gen_dissection = let open Gen in small_list gen_dissection_chunk let gen_game_state = let open Sc_rollup_game_repr in let open Gen in let gen_dissecting = let* dissection = gen_dissection in let+ default_number_of_sections = int_range 4 100 in Dissecting {dissection; default_number_of_sections} in let gen_final_move = let* agreed_start_chunk = gen_dissection_chunk in let+ refuted_stop_chunk = gen_dissection_chunk in Final_move {agreed_start_chunk; refuted_stop_chunk} in oneof [gen_dissecting; gen_final_move] let gen_game = let open Gen in let* turn = gen_player in let* inbox_level = gen_inbox_level in let* start_level = gen_start_level in let* inbox_snapshot = gen_inbox_history_proof inbox_level in let* dal_snapshot = gen_dal_slots_history () in let* game_state = gen_game_state in return Sc_rollup_game_repr. {turn; dal_snapshot; inbox_snapshot; start_level; inbox_level; game_state} let gen_conflict = let open Gen in let other = Sc_rollup_repr.Staker.zero in let* their_commitment = gen_commitment in let* our_commitment = gen_commitment in let* parent_commitment = gen_commitment_hash in return Sc_rollup_refutation_storage. {other; their_commitment; our_commitment; parent_commitment} let gen_rollup = let open QCheck2.Gen in let* bytes = bytes_fixed_gen Sc_rollup_repr.Address.size in return (Sc_rollup_repr.Address.hash_bytes [bytes]) let gen_inbox_message = let open Gen in let open Sc_rollup_inbox_message_repr in let gen_external = let+ s = small_string ~gen:printable in External s in let gen_sol = return (Internal Start_of_level) in let gen_eol = return (Internal End_of_level) in let gen_deposit = let payload = Script_repr.unit in let sender = Contract_hash.zero in let source = Signature.Public_key_hash.zero in let+ destination = gen_rollup in Internal (Transfer {payload; sender; source; destination}) in oneof [gen_external; gen_sol; gen_eol; gen_deposit] * { 2 Tests } let test_commitment = test_roundtrip ~count:1_000 ~title:"Sc_rollup_commitment.t" ~gen:gen_commitment ~eq:( = ) Sc_rollup_commitment_repr.encoding let test_versioned_commitment = test_roundtrip ~count:1_000 ~title:"Sc_rollup_commitment.versioned" ~gen:gen_versioned_commitment ~eq:( = ) Sc_rollup_commitment_repr.versioned_encoding let test_game = test_roundtrip ~count:1_000 ~title:"Sc_rollup_game.t" ~gen:gen_game ~eq:Sc_rollup_game_repr.equal Sc_rollup_game_repr.encoding let test_conflict = test_roundtrip ~count:1_000 ~title:"Sc_rollup_refutation_storage.conflict" ~gen:gen_conflict ~eq:( = ) Sc_rollup_refutation_storage.conflict_encoding let test_inbox_message = test_roundtrip ~count:1_000 ~title:"Sc_rollup_inbox_message_repr.t" ~gen:gen_inbox_message ~eq:( = ) Sc_rollup_inbox_message_repr.encoding let tests = [ test_commitment; test_versioned_commitment; test_game; test_conflict; test_inbox_message; ] let () = Alcotest.run "SC rollup encoding" [(Protocol.name ^ ": roundtrip", qcheck_wrap tests)]
40fc08d026aac6fbe00786bf4423f22c05ffc7f371b11bf031bc5b859c8f1569
jimweirich/sicp-study
ex2_75_test.scm
SICP Tests 2.75 (test-case "Ex 2.75 -- To Radians" (assert-in-delta 0.707 (to-rad 45) 0.783)) (test-case "Ex 2.75 -- Data Driven Complex Number" (let ((c (make-from-mag-ang 1 (to-rad 45)))) (assert-equal 1 (c 'magnitude)) (assert-in-delta (to-rad 45) (c 'angle) 0.001) (assert-in-delta 0.707 (c 'real-part) 0.001) (assert-in-delta 0.707 (c 'imag-part) 0.001))) (test-case "Ex 2.75 -- Data Driven Complex Number 2" (let ((c (make-from-mag-ang 1 (to-rad 0)))) (assert-equal 1 (c 'magnitude)) (assert-in-delta (to-rad 0) (c 'angle) 0.001) (assert-in-delta 1 (c 'real-part) 0.001) (assert-in-delta 0 (c 'imag-part) 0.001)))
null
https://raw.githubusercontent.com/jimweirich/sicp-study/bc5190e04ed6ae321107ed6149241f26efc1b8c8/scheme/chapter2/ex2_75_test.scm
scheme
SICP Tests 2.75 (test-case "Ex 2.75 -- To Radians" (assert-in-delta 0.707 (to-rad 45) 0.783)) (test-case "Ex 2.75 -- Data Driven Complex Number" (let ((c (make-from-mag-ang 1 (to-rad 45)))) (assert-equal 1 (c 'magnitude)) (assert-in-delta (to-rad 45) (c 'angle) 0.001) (assert-in-delta 0.707 (c 'real-part) 0.001) (assert-in-delta 0.707 (c 'imag-part) 0.001))) (test-case "Ex 2.75 -- Data Driven Complex Number 2" (let ((c (make-from-mag-ang 1 (to-rad 0)))) (assert-equal 1 (c 'magnitude)) (assert-in-delta (to-rad 0) (c 'angle) 0.001) (assert-in-delta 1 (c 'real-part) 0.001) (assert-in-delta 0 (c 'imag-part) 0.001)))
8de62b20a0e74e9ead5ea80d32a5cc6f9c35d092e3ef5c39db74c572467019ea
cedlemo/OCaml-GI-ctypes-bindings-generator
Combo_box_text.ml
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_combo_box_text_new" (void @-> returning (ptr Widget.t_typ)) let create_with_entry = foreign "gtk_combo_box_text_new_with_entry" (void @-> returning (ptr Widget.t_typ)) let append = foreign "gtk_combo_box_text_append" (t_typ @-> string_opt @-> string @-> returning (void)) let append_text = foreign "gtk_combo_box_text_append_text" (t_typ @-> string @-> returning (void)) let get_active_text = foreign "gtk_combo_box_text_get_active_text" (t_typ @-> returning (string_opt)) let insert = foreign "gtk_combo_box_text_insert" (t_typ @-> int32_t @-> string_opt @-> string @-> returning (void)) let insert_text = foreign "gtk_combo_box_text_insert_text" (t_typ @-> int32_t @-> string @-> returning (void)) let prepend = foreign "gtk_combo_box_text_prepend" (t_typ @-> string_opt @-> string @-> returning (void)) let prepend_text = foreign "gtk_combo_box_text_prepend_text" (t_typ @-> string @-> returning (void)) let remove = foreign "gtk_combo_box_text_remove" (t_typ @-> int32_t @-> returning (void)) let remove_all = foreign "gtk_combo_box_text_remove_all" (t_typ @-> returning (void))
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Combo_box_text.ml
ocaml
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_combo_box_text_new" (void @-> returning (ptr Widget.t_typ)) let create_with_entry = foreign "gtk_combo_box_text_new_with_entry" (void @-> returning (ptr Widget.t_typ)) let append = foreign "gtk_combo_box_text_append" (t_typ @-> string_opt @-> string @-> returning (void)) let append_text = foreign "gtk_combo_box_text_append_text" (t_typ @-> string @-> returning (void)) let get_active_text = foreign "gtk_combo_box_text_get_active_text" (t_typ @-> returning (string_opt)) let insert = foreign "gtk_combo_box_text_insert" (t_typ @-> int32_t @-> string_opt @-> string @-> returning (void)) let insert_text = foreign "gtk_combo_box_text_insert_text" (t_typ @-> int32_t @-> string @-> returning (void)) let prepend = foreign "gtk_combo_box_text_prepend" (t_typ @-> string_opt @-> string @-> returning (void)) let prepend_text = foreign "gtk_combo_box_text_prepend_text" (t_typ @-> string @-> returning (void)) let remove = foreign "gtk_combo_box_text_remove" (t_typ @-> int32_t @-> returning (void)) let remove_all = foreign "gtk_combo_box_text_remove_all" (t_typ @-> returning (void))
2be613487429d5d42bb003b534b08aafab7be02abba31f135a29ff2d09348d08
bbusching/libgit2
object.rkt
#lang racket (require ffi/unsafe "define.rkt" "types.rkt" "buffer.rkt" "utils.rkt") (provide (all-defined-out)) (define-libgit2/dealloc git_object_free (_fun _object -> _void)) (define-libgit2 git_object__size (_fun _git_otype -> _size)) (define-libgit2/alloc git_object_dup (_fun _object _object -> _int) git_object_free) (define-libgit2 git_object_id (_fun _object -> _oid)) (define-libgit2/alloc git_object_lookup (_fun _object _repository _oid _git_otype -> _int) git_object_free) (define-libgit2/alloc git_object_lookup_bypath (_fun _object _object _string _git_otype -> _int) git_object_free) (define-libgit2/alloc git_object_lookup_prefix (_fun _object _repository _oid _size _git_otype -> _int) git_object_free) (define-libgit2 git_object_owner (_fun _object -> _repository)) (define-libgit2/alloc git_object_peel (_fun _object _object _git_otype -> _int) git_object_free) (define-libgit2/check git_object_short_id (_fun _buf _object -> _int)) (define-libgit2 git_object_string2type (_fun _string -> _git_otype)) (define-libgit2 git_object_type (_fun _object -> _git_otype)) (define-libgit2 git_object_type2string (_fun _git_otype -> _string)) (define-libgit2 git_object_typeisloose (_fun _git_otype -> _bool))
null
https://raw.githubusercontent.com/bbusching/libgit2/6d6a007543900eb7a6fbbeba55850288665bdde5/libgit2/include/object.rkt
racket
#lang racket (require ffi/unsafe "define.rkt" "types.rkt" "buffer.rkt" "utils.rkt") (provide (all-defined-out)) (define-libgit2/dealloc git_object_free (_fun _object -> _void)) (define-libgit2 git_object__size (_fun _git_otype -> _size)) (define-libgit2/alloc git_object_dup (_fun _object _object -> _int) git_object_free) (define-libgit2 git_object_id (_fun _object -> _oid)) (define-libgit2/alloc git_object_lookup (_fun _object _repository _oid _git_otype -> _int) git_object_free) (define-libgit2/alloc git_object_lookup_bypath (_fun _object _object _string _git_otype -> _int) git_object_free) (define-libgit2/alloc git_object_lookup_prefix (_fun _object _repository _oid _size _git_otype -> _int) git_object_free) (define-libgit2 git_object_owner (_fun _object -> _repository)) (define-libgit2/alloc git_object_peel (_fun _object _object _git_otype -> _int) git_object_free) (define-libgit2/check git_object_short_id (_fun _buf _object -> _int)) (define-libgit2 git_object_string2type (_fun _string -> _git_otype)) (define-libgit2 git_object_type (_fun _object -> _git_otype)) (define-libgit2 git_object_type2string (_fun _git_otype -> _string)) (define-libgit2 git_object_typeisloose (_fun _git_otype -> _bool))
25c8602afef4e7619f6fceb38d9226b7599f4afcdf83a8e842163864b5fc1396
ucsd-progsys/liquidhaskell
CheckedImp.hs
module CheckedImp where {-@ relational foo ~ foo :: { x1:_ -> _ ~ x2:_ -> _ | x1 = x2 !=> r1 x1 = r2 x2 } @-} foo :: Int -> Int foo = (+1) {-@ relational bar ~ baz :: { _ ~ _ | r1 = r2 } @-} bar, baz :: Int bar = foo 1 baz = foo 1
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/177331c811145dab2606bc442389e0031d7db41b/tests/relational/pos/CheckedImp.hs
haskell
@ relational foo ~ foo :: { x1:_ -> _ ~ x2:_ -> _ | x1 = x2 !=> r1 x1 = r2 x2 } @ @ relational bar ~ baz :: { _ ~ _ | r1 = r2 } @
module CheckedImp where foo :: Int -> Int foo = (+1) bar, baz :: Int bar = foo 1 baz = foo 1
a4e8edbee91720563ac7e26b021137893a7f329cf576450456e7905e10f75715
cmsc430/www
example.rkt
#lang racket (if (zero? 1) (sub1 43) (if (zero? 0) 1024 2048))
null
https://raw.githubusercontent.com/cmsc430/www/0809867532b8ef516029ac38093a145db5b424ea/langs/test-programs/con/example.rkt
racket
#lang racket (if (zero? 1) (sub1 43) (if (zero? 0) 1024 2048))
5337edd1516df0cbae0798e7380d5b27c5425325aa6ab9734769f8b9bf4a1812
LaurentMazare/ocaml-minipy
parse.mli
open Base module Error : sig type t = { message : string ; context : string option } [@@deriving sexp] end val token_to_string : Parser.token -> string val tokens_string : string -> Parser.token list val tokens_file : string -> Parser.token list val parse : ?filename:string -> Stdio.In_channel.t -> (Ast.t, Error.t) Result.t val parse_string : ?filename:string -> string -> (Ast.t, Error.t) Result.t val parse_file : string -> (Ast.t, Error.t) Result.t val ok_exn : ('a, Error.t) Result.t -> 'a
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-minipy/e83d4bfad55819a27195109d401437faa0f65f69/src/parse.mli
ocaml
open Base module Error : sig type t = { message : string ; context : string option } [@@deriving sexp] end val token_to_string : Parser.token -> string val tokens_string : string -> Parser.token list val tokens_file : string -> Parser.token list val parse : ?filename:string -> Stdio.In_channel.t -> (Ast.t, Error.t) Result.t val parse_string : ?filename:string -> string -> (Ast.t, Error.t) Result.t val parse_file : string -> (Ast.t, Error.t) Result.t val ok_exn : ('a, Error.t) Result.t -> 'a
28f7338de6db2c43456d945a8b5ccdbc3b54e266285553cf40480e29493107d9
racket/racket7
recur-handler.rkt
#lang racket/base (require "../port/output-port.rkt" "mode.rkt") (provide set-port-handlers-to-recur!) (define (set-port-handlers-to-recur! port handle) (set-core-output-port-print-handler! port (lambda (e p [mode 0]) (handle e p mode))) (set-core-output-port-write-handler! port (lambda (e p) (handle e p WRITE-MODE))) (set-core-output-port-display-handler! port (lambda (e p) (handle e p DISPLAY-MODE))))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/io/print/recur-handler.rkt
racket
#lang racket/base (require "../port/output-port.rkt" "mode.rkt") (provide set-port-handlers-to-recur!) (define (set-port-handlers-to-recur! port handle) (set-core-output-port-print-handler! port (lambda (e p [mode 0]) (handle e p mode))) (set-core-output-port-write-handler! port (lambda (e p) (handle e p WRITE-MODE))) (set-core-output-port-display-handler! port (lambda (e p) (handle e p DISPLAY-MODE))))
1d81e9f095c230f53140fa51123e46fa151a63c29c9151709d49af057f63c681
bos/rwh
HighestClose.hs
{-- snippet closing --} -- file: HighestClose.hs import qualified Data.ByteString.Lazy.Char8 as L closing = readPrice . (!!4) . L.split ',' {-- /snippet closing --} - snippet - readPrice :: L.ByteString -> Maybe Int readPrice str = case L.readInt str of Nothing -> Nothing Just (dollars,rest) -> case L.readInt (L.tail rest) of Nothing -> Nothing Just (cents,more) -> Just (dollars * 100 + cents) - /snippet - {-- snippet highestClose --} highestClose = maximum . (Nothing:) . map closing . L.lines highestCloseFrom path = do contents <- L.readFile path print (highestClose contents) - /snippet
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch09/HighestClose.hs
haskell
- snippet closing - file: HighestClose.hs - /snippet closing - - snippet highestClose -
import qualified Data.ByteString.Lazy.Char8 as L closing = readPrice . (!!4) . L.split ',' - snippet - readPrice :: L.ByteString -> Maybe Int readPrice str = case L.readInt str of Nothing -> Nothing Just (dollars,rest) -> case L.readInt (L.tail rest) of Nothing -> Nothing Just (cents,more) -> Just (dollars * 100 + cents) - /snippet - highestClose = maximum . (Nothing:) . map closing . L.lines highestCloseFrom path = do contents <- L.readFile path print (highestClose contents) - /snippet
76928ff45982afaa5ebdfee6923237e694d5be71b76d0bdea446bc0d174fbb84
MassD/99
p66_STAR3.ml
Layout a binary tree ( 3 ) . ( hard ) -layout3.gif Yet another layout strategy is shown in the above illustration . The method yields a very compact layout while maintaining a certain symmetry in every node . Find out the rules and write the corresponding predicate . Hint : Consider the horizontal distance between a node and its successor nodes . How tight can you pack together two subtrees to construct the combined binary tree ? This is a difficult problem . Do n't give up too early ! Layout a binary tree (3). (hard) -layout3.gif Yet another layout strategy is shown in the above illustration. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? This is a difficult problem. Don't give up too early! *) The rules are like this : 1 . Assume for any subtree , if root 's x - axis is x , then its left must be at least x-1 ( towards further left ) and right must be at least x+1 ( towards further right ) 2 . On the same level , the diff of Xs of any pair of nodes must be at least 2 ( ( x+1)-(x-1)=2 ) 3 . On the same level , if the diff of two nodes are less than 2 , then left one will move to left and right one will move to right by the same amount until their distance is at least 2 4 . In a tree , for a root , only the right path of its left child and left path of its right child may clash with each other on same levels . Algorithm : 1 . start from the root , assign temporary x to root , then left child x-1 and right child x+1 . The very root at level 0 's x = 0 2 . After tagging the tree like above , we wider the tree 3 . for any root , we wider its left and right , and then check whether left and right clash 4 . For checking the clashes of left and right , basically , we travel along the right path of left and left path of right , see whether on one level , any two nodes ' Xs have distance less than 2 5 . If there are two such nodes , then move the whole left tree to left by shift value , and move the whole right tree to right by shift value 6 . After widering done , we get the left most node 's x , then move the whole tree to right by ( -x ) The rules are like this: 1. Assume for any subtree, if root's x-axis is x, then its left must be at least x-1 (towards further left) and right must be at least x+1 (towards further right) 2. On the same level, the diff of Xs of any pair of nodes must be at least 2 ((x+1)-(x-1)=2) 3. On the same level, if the diff of two nodes are less than 2, then left one will move to left and right one will move to right by the same amount until their distance is at least 2 4. In a tree, for a root, only the right path of its left child and left path of its right child may clash with each other on same levels. Algorithm: 1. start from the root, assign temporary x to root, then left child x-1 and right child x+1. The very root at level 0's x = 0 2. After tagging the tree like above, we wider the tree 3. for any root, we wider its left and right, and then check whether left and right clash 4. For checking the clashes of left and right, basically, we travel along the right path of left and left path of right, see whether on one level, any two nodes' Xs have distance less than 2 5. If there are two such nodes, then move the whole left tree to left by shift value, and move the whole right tree to right by shift value 6. After widering done, we get the left most node's x, then move the whole tree to right by (-x) *) type 'a btree = Empty | Node of 'a * 'a btree * 'a btree type 'a pos_binary_tree = | E (* represents the empty tree *) | N of 'a * int * int * 'a pos_binary_tree * 'a pos_binary_tree let rec tag x = function | Empty -> Empty | Node (k,l,r) -> Node ((k,x), tag (x-1) l, tag (x+1) r) let rec check_clash l r = match l, r with | _, Empty | Empty, _ -> 0 | Node ((k1,x1),_,r1), Node ((k2,x2),l2,_) -> let shift = check_clash r1 l2 in if x1-shift < x2+shift then shift else if x1-shift = x2+shift then shift+1 else (x1-shift)-(x2+shift) let rec shift_move shift = function | Empty -> Empty | Node ((k,x),l,r) -> Node ((k,x+shift),shift_move shift l, shift_move shift r) let rec wider = function | Empty -> Empty | Node ((k,x),l,r) -> let wide_l, wide_r = wider l, wider r in let shift = check_clash wide_l wide_r in Node ((k,x),shift_move (-shift) l, shift_move shift r) let rec min_x = function | Empty -> 0 | Node ((_,x),Empty,_) -> x | Node (_,l,_) -> min_x l let layout3 btree = let rec build shift y = function | Empty -> E | Node ((k,x),l,r) -> N (k, x+shift, y, build shift (y+1) l, build shift (y+1) r) in let wider_btree = tag 0 btree |> wider in build (1-(min_x wider_btree)) 1 wider_btree let bt = Node ('n', Node ('k', Node ('c', Node ('a',Empty, Empty), Node ('e', Node ('d',Empty,Empty), Node ('g',Empty,Empty))), Node ('m',Empty,Empty)), Node ('u', Node ('p',Empty, Node ('q',Empty,Empty)), Empty)) let rec xys = function | E -> [] | N (k,x,y,l,r) -> (k,x,y)::(List.rev_append (xys l) (xys r))
null
https://raw.githubusercontent.com/MassD/99/1d3019eb55b0d621ed1df4132315673dd812b1e1/55-69-binary-tress/p66_STAR3.ml
ocaml
represents the empty tree
Layout a binary tree ( 3 ) . ( hard ) -layout3.gif Yet another layout strategy is shown in the above illustration . The method yields a very compact layout while maintaining a certain symmetry in every node . Find out the rules and write the corresponding predicate . Hint : Consider the horizontal distance between a node and its successor nodes . How tight can you pack together two subtrees to construct the combined binary tree ? This is a difficult problem . Do n't give up too early ! Layout a binary tree (3). (hard) -layout3.gif Yet another layout strategy is shown in the above illustration. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? This is a difficult problem. Don't give up too early! *) The rules are like this : 1 . Assume for any subtree , if root 's x - axis is x , then its left must be at least x-1 ( towards further left ) and right must be at least x+1 ( towards further right ) 2 . On the same level , the diff of Xs of any pair of nodes must be at least 2 ( ( x+1)-(x-1)=2 ) 3 . On the same level , if the diff of two nodes are less than 2 , then left one will move to left and right one will move to right by the same amount until their distance is at least 2 4 . In a tree , for a root , only the right path of its left child and left path of its right child may clash with each other on same levels . Algorithm : 1 . start from the root , assign temporary x to root , then left child x-1 and right child x+1 . The very root at level 0 's x = 0 2 . After tagging the tree like above , we wider the tree 3 . for any root , we wider its left and right , and then check whether left and right clash 4 . For checking the clashes of left and right , basically , we travel along the right path of left and left path of right , see whether on one level , any two nodes ' Xs have distance less than 2 5 . If there are two such nodes , then move the whole left tree to left by shift value , and move the whole right tree to right by shift value 6 . After widering done , we get the left most node 's x , then move the whole tree to right by ( -x ) The rules are like this: 1. Assume for any subtree, if root's x-axis is x, then its left must be at least x-1 (towards further left) and right must be at least x+1 (towards further right) 2. On the same level, the diff of Xs of any pair of nodes must be at least 2 ((x+1)-(x-1)=2) 3. On the same level, if the diff of two nodes are less than 2, then left one will move to left and right one will move to right by the same amount until their distance is at least 2 4. In a tree, for a root, only the right path of its left child and left path of its right child may clash with each other on same levels. Algorithm: 1. start from the root, assign temporary x to root, then left child x-1 and right child x+1. The very root at level 0's x = 0 2. After tagging the tree like above, we wider the tree 3. for any root, we wider its left and right, and then check whether left and right clash 4. For checking the clashes of left and right, basically, we travel along the right path of left and left path of right, see whether on one level, any two nodes' Xs have distance less than 2 5. If there are two such nodes, then move the whole left tree to left by shift value, and move the whole right tree to right by shift value 6. After widering done, we get the left most node's x, then move the whole tree to right by (-x) *) type 'a btree = Empty | Node of 'a * 'a btree * 'a btree type 'a pos_binary_tree = | N of 'a * int * int * 'a pos_binary_tree * 'a pos_binary_tree let rec tag x = function | Empty -> Empty | Node (k,l,r) -> Node ((k,x), tag (x-1) l, tag (x+1) r) let rec check_clash l r = match l, r with | _, Empty | Empty, _ -> 0 | Node ((k1,x1),_,r1), Node ((k2,x2),l2,_) -> let shift = check_clash r1 l2 in if x1-shift < x2+shift then shift else if x1-shift = x2+shift then shift+1 else (x1-shift)-(x2+shift) let rec shift_move shift = function | Empty -> Empty | Node ((k,x),l,r) -> Node ((k,x+shift),shift_move shift l, shift_move shift r) let rec wider = function | Empty -> Empty | Node ((k,x),l,r) -> let wide_l, wide_r = wider l, wider r in let shift = check_clash wide_l wide_r in Node ((k,x),shift_move (-shift) l, shift_move shift r) let rec min_x = function | Empty -> 0 | Node ((_,x),Empty,_) -> x | Node (_,l,_) -> min_x l let layout3 btree = let rec build shift y = function | Empty -> E | Node ((k,x),l,r) -> N (k, x+shift, y, build shift (y+1) l, build shift (y+1) r) in let wider_btree = tag 0 btree |> wider in build (1-(min_x wider_btree)) 1 wider_btree let bt = Node ('n', Node ('k', Node ('c', Node ('a',Empty, Empty), Node ('e', Node ('d',Empty,Empty), Node ('g',Empty,Empty))), Node ('m',Empty,Empty)), Node ('u', Node ('p',Empty, Node ('q',Empty,Empty)), Empty)) let rec xys = function | E -> [] | N (k,x,y,l,r) -> (k,x,y)::(List.rev_append (xys l) (xys r))
aa371e3064354db1d91baf5c53d7262e82ccd21f706fcc11f1ea6568bc29d5d4
kmi/irs
load.lisp
Mode : Lisp ; Package : File created in WebOnto (in-package "OCML") (eval-when (eval load) (ensure-ontology wsmo domain "ocml:library;domains;wsmo;load.lisp" ) (ensure-ontology emergency-gis-situations domain "ocml:library;domains;emergency-gis-situations;load.lisp") (ensure-ontology sgis-spatial domain "ocml:library;domains;sgis-spatial;load.lisp" )) (def-ontology emergency-gis-plume :includes (wsmo sgis-spatial emergency-gis-situations) :type :domain :author "wsmo" :allowed-editors ("vlad" "john" "carlos" "alessio") :files ("emergency-gis-plume" "new" "lilo"))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/emergency-gis-plume/load.lisp
lisp
Package :
File created in WebOnto (in-package "OCML") (eval-when (eval load) (ensure-ontology wsmo domain "ocml:library;domains;wsmo;load.lisp" ) (ensure-ontology emergency-gis-situations domain "ocml:library;domains;emergency-gis-situations;load.lisp") (ensure-ontology sgis-spatial domain "ocml:library;domains;sgis-spatial;load.lisp" )) (def-ontology emergency-gis-plume :includes (wsmo sgis-spatial emergency-gis-situations) :type :domain :author "wsmo" :allowed-editors ("vlad" "john" "carlos" "alessio") :files ("emergency-gis-plume" "new" "lilo"))
fff3670e765912cc93b12cefbc8d2bb3d89b350c8528766c781701562d70d892
aeternity/mnesia_leveled
mnesia_leveled_fallback.erl
%%---------------------------------------------------------------- Copyright ( c ) 2013 - 2016 Klarna AB %% This file is provided to you 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(mnesia_leveled_fallback). -export([run/0]). -define(m(A,B), fun() -> L = ?LINE, case {A,B} of {__X, __X} -> B; Other -> error({badmatch, [Other, {line, L}]}) end end()). run() -> cleanup(), mnesia_leveled_tlib:start_mnesia(reset), mnesia_leveled_tlib:create_table(led), ok = mnesia:backup("bup0.BUP"), [mnesia:dirty_write({t,K,V}) || {K,V} <- [{a,1}, {b,2}, {c,3}]], ok = mnesia:backup("bup1.BUP"), [mnesia:dirty_write({t,K,V}) || {K,V} <- [{d,4}, {e,5}, {f,6}]], ok = mnesia:backup("bup2.BUP"), ct:log("*****************************************~n", []), load_backup("bup0.BUP"), ?m([], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([], mnesia:dirty_index_read(t,2,v)), ct:log("*****************************************~n", []), load_backup("bup1.BUP"), ?m([{t,a,1},{t,b,2},{t,c,3}], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([{t,b,2}], mnesia:dirty_index_read(t,2,v)), ct:log("*****************************************~n", []), load_backup("bup2.BUP"), ?m([{t,a,1},{t,b,2},{t,c,3}, {t,d,4},{t,e,5},{t,f,6}], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([{t,b,2}], mnesia:dirty_index_read(t,2,v)), ?m([{t,e,5}], mnesia:dirty_index_read(t,5,v)), ok. load_backup(BUP) -> mnesia_leveled_tlib:trace( fun() -> ct:log("loading backup ~s~n", [BUP]), ok = mnesia:install_fallback(BUP), ct:log("stopping~n", []), mnesia:stop(), timer:sleep(3000), ct:log("starting~n", []), mnesia:start(), WaitRes = mnesia:wait_for_tables([t], 5000), ct:log("WaitRes = ~p~n", [WaitRes]) end, mods(0) ). cleanup() -> os:cmd("rm *.BUP"). mods(0) -> []; mods(1) -> [ {l, mnesia_leveled}, {g, leveled} ]; mods(2) -> [ %% {l, mnesia_monitor}, {g, mnesia_leveled}, {l, mnesia_bup}, {g, mnesia_lib}, {g, mnesia_schema}, , mnesia_loader } , {g, mnesia_index}, {l, mnesia_tm} ].
null
https://raw.githubusercontent.com/aeternity/mnesia_leveled/11c480b5546ed6087ae688e8596bd596a1f7bdd1/test/mnesia_leveled_fallback.erl
erlang
---------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---------------------------------------------------------------- {l, mnesia_monitor},
Copyright ( c ) 2013 - 2016 Klarna AB This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(mnesia_leveled_fallback). -export([run/0]). -define(m(A,B), fun() -> L = ?LINE, case {A,B} of {__X, __X} -> B; Other -> error({badmatch, [Other, {line, L}]}) end end()). run() -> cleanup(), mnesia_leveled_tlib:start_mnesia(reset), mnesia_leveled_tlib:create_table(led), ok = mnesia:backup("bup0.BUP"), [mnesia:dirty_write({t,K,V}) || {K,V} <- [{a,1}, {b,2}, {c,3}]], ok = mnesia:backup("bup1.BUP"), [mnesia:dirty_write({t,K,V}) || {K,V} <- [{d,4}, {e,5}, {f,6}]], ok = mnesia:backup("bup2.BUP"), ct:log("*****************************************~n", []), load_backup("bup0.BUP"), ?m([], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([], mnesia:dirty_index_read(t,2,v)), ct:log("*****************************************~n", []), load_backup("bup1.BUP"), ?m([{t,a,1},{t,b,2},{t,c,3}], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([{t,b,2}], mnesia:dirty_index_read(t,2,v)), ct:log("*****************************************~n", []), load_backup("bup2.BUP"), ?m([{t,a,1},{t,b,2},{t,c,3}, {t,d,4},{t,e,5},{t,f,6}], mnesia:dirty_match_object(t, {t,'_','_'})), ?m([{t,b,2}], mnesia:dirty_index_read(t,2,v)), ?m([{t,e,5}], mnesia:dirty_index_read(t,5,v)), ok. load_backup(BUP) -> mnesia_leveled_tlib:trace( fun() -> ct:log("loading backup ~s~n", [BUP]), ok = mnesia:install_fallback(BUP), ct:log("stopping~n", []), mnesia:stop(), timer:sleep(3000), ct:log("starting~n", []), mnesia:start(), WaitRes = mnesia:wait_for_tables([t], 5000), ct:log("WaitRes = ~p~n", [WaitRes]) end, mods(0) ). cleanup() -> os:cmd("rm *.BUP"). mods(0) -> []; mods(1) -> [ {l, mnesia_leveled}, {g, leveled} ]; mods(2) -> [ {g, mnesia_leveled}, {l, mnesia_bup}, {g, mnesia_lib}, {g, mnesia_schema}, , mnesia_loader } , {g, mnesia_index}, {l, mnesia_tm} ].
7f0d411bf0ab50f786dc61dea31c4da5b994d152c77f473aa799130867e9d840
ghorn/spatial-math
LibmFfi.hs
# OPTIONS_GHC -Wall # module SpatialMath.LibmFfi ( libm_atan2 , libm_atan2f ) where import Foreign.C.Types ( CDouble(..), CFloat(..) ) foreign import ccall unsafe "math.h atan2" c_atan2 :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "math.h atan2f" c_atan2f :: CFloat -> CFloat -> CFloat libm_atan2 :: Double -> Double -> Double libm_atan2 y x = ret where CDouble ret = c_atan2 (CDouble y) (CDouble x) libm_atan2f :: Float -> Float -> Float libm_atan2f y x = ret where CFloat ret = c_atan2f (CFloat y) (CFloat x)
null
https://raw.githubusercontent.com/ghorn/spatial-math/22afc3e91b6bed7e988da3deae6cfde19383192b/src/SpatialMath/LibmFfi.hs
haskell
# OPTIONS_GHC -Wall # module SpatialMath.LibmFfi ( libm_atan2 , libm_atan2f ) where import Foreign.C.Types ( CDouble(..), CFloat(..) ) foreign import ccall unsafe "math.h atan2" c_atan2 :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "math.h atan2f" c_atan2f :: CFloat -> CFloat -> CFloat libm_atan2 :: Double -> Double -> Double libm_atan2 y x = ret where CDouble ret = c_atan2 (CDouble y) (CDouble x) libm_atan2f :: Float -> Float -> Float libm_atan2f y x = ret where CFloat ret = c_atan2f (CFloat y) (CFloat x)
f339434ef9fc8f5213e6e862fb0f1d18c505d465d8910aa39d7b3e5d6b911fea
savonet/ocaml-mm
fft.ml
open Mm_audio module FFT = Audio.Mono.Analyze.FFT let () = let fname = Sys.argv.(1) in let f = new Audio.IO.Reader.of_wav_file fname in let oss = new Mm_oss.writer f#channels f#sample_rate in Printf.printf "Opened WAV file with %d channels at %dHz.\n%!" f#channels f#sample_rate; let fft_n = 11 in let fft = FFT.init fft_n in let fft_times_per_buf = 4 in let blen = 1 lsl fft_n in let buf = Audio.create f#channels (2 * blen) in let loop = ref true in Graphics.open_graph ""; let i = ref 0 in while !loop do Audio.blit buf blen buf 0 blen; let n = f#read buf blen blen in oss#write buf blen n; for o = 0 to fft_times_per_buf - 1 do let c = FFT.complex_create (Audio.to_mono buf 0 blen) (o * blen / fft_times_per_buf) blen in FFT.Window.cosine c; FFT.fft fft c; for j = 0 to Graphics.size_y () - 1 do let v = Complex.norm c.(j * blen / (2 * Graphics.size_y ())) in let v = int_of_float (v *. 255.) in let color = v lsl 16 in Graphics.set_color color; Graphics.plot !i j done; incr i; if !i >= Graphics.size_x () then i := 0 done; if n = 0 then loop := false done; oss#close; f#close
null
https://raw.githubusercontent.com/savonet/ocaml-mm/f931d881512cf3a74399c261aa5877fb69bfe524/examples/fft.ml
ocaml
open Mm_audio module FFT = Audio.Mono.Analyze.FFT let () = let fname = Sys.argv.(1) in let f = new Audio.IO.Reader.of_wav_file fname in let oss = new Mm_oss.writer f#channels f#sample_rate in Printf.printf "Opened WAV file with %d channels at %dHz.\n%!" f#channels f#sample_rate; let fft_n = 11 in let fft = FFT.init fft_n in let fft_times_per_buf = 4 in let blen = 1 lsl fft_n in let buf = Audio.create f#channels (2 * blen) in let loop = ref true in Graphics.open_graph ""; let i = ref 0 in while !loop do Audio.blit buf blen buf 0 blen; let n = f#read buf blen blen in oss#write buf blen n; for o = 0 to fft_times_per_buf - 1 do let c = FFT.complex_create (Audio.to_mono buf 0 blen) (o * blen / fft_times_per_buf) blen in FFT.Window.cosine c; FFT.fft fft c; for j = 0 to Graphics.size_y () - 1 do let v = Complex.norm c.(j * blen / (2 * Graphics.size_y ())) in let v = int_of_float (v *. 255.) in let color = v lsl 16 in Graphics.set_color color; Graphics.plot !i j done; incr i; if !i >= Graphics.size_x () then i := 0 done; if n = 0 then loop := false done; oss#close; f#close
0148668b119cfd38ee8f6e0271c6424b85c8e055f9db2709f1a84f142cb58d5b
alexander-yakushev/ns-graph
core.clj
(ns ns-graph.core "Generate a namespace dependency graph as an image." (:require [dorothy.core :as dot] [clojure.string :as s] [clojure.java.shell :refer [sh]] [clojure.java.io :as io] [clojure.pprint :refer [pprint]] [clojure.data :refer [diff]] [clojure.string :as str]) (:import java.io.File)) (defn read-ns [file] (with-open [f (-> file io/reader java.io.PushbackReader.)] (binding [*in* f] (let [x (read)] (when (= (first x) 'ns) x))))) #_(read-ns "src/ns_graph.clj") #_(read-ns "build.boot") (defn parse-reference-entry [ref] (if-not (sequential? ref) [ref] (let [ext (loop [[c & r] (rest ref), ns-ext ()] (if (or (keyword? c) (nil? c)) ns-ext (recur r (conj ns-ext (if (sequential? c) (first c) c)))))] (if (empty? ext) [(first ref)] (map #(symbol (str (first ref) \. %)) ext))))) #_(parse-reference-entry 'clojure.pprint) #_(parse-reference-entry '[clojure.pprint :as pp]) #_(parse-reference-entry '[clojure pprint zip]) #_(parse-reference-entry '[clojure.java [io :refer [file]] sh]) (defn parse-ns-subform "Parses references entries under the given `key` in `ns-form`." [ns-form key] (->> ns-form (filter #(and (coll? %) (= key (first %)))) (mapcat rest) (mapcat parse-reference-entry) set)) (defn parse-clojure-file [f include?] (when-let [[_ ns :as ns-form] (read-ns f)] (when (include? ns) {:name ns :type :clojure :clojure-depends (concat (parse-ns-subform ns-form :require) (parse-ns-subform ns-form :use)) :java-depends (parse-ns-subform ns-form :import)}))) #_(parse-clojure-file "/Users/alex/clojure/android/neko/src/clojure/neko/ui/menu.clj" any?) (defn java-get-classname [short-filename content-lines] (let [[_ package] (some #(re-find #"package\s+([\w\._]*)\s*;" %) content-lines) [_ class] (re-matches #"(.+)\.java" short-filename)] (symbol (str package "." class)))) #_(java-get-classname "BoardRenderer.java" (line-seq (io/reader "/home/unlogic/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java"))) (defn java-get-imports [content-lines] (loop [[^String line & r] content-lines imports []] (if line (cond (.startsWith (.trim line) "import static") (when-let [[_ import] (re-find #"import\s+static\s+([\w_\.\*]+)\.(?:[\w_\*]+);" line)] (recur r (conj imports (symbol import)))) (.startsWith (.trim line) "import") (when-let [[_ import] (re-find #"import\s+([\w_\.\*]+);" line)] (recur r (conj imports (symbol import)))) (re-matches #"\s*class\s+[\w_]+" line) imports :else (recur r imports)) imports))) #_(java-get-imports (line-seq (io/reader "/home/unlogic/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java"))) (defn parse-java-file [f include?] (let [contents (line-seq (io/reader f)) cn (java-get-classname (.getName (io/file f)) contents)] (when (include? cn) {:name cn :type :java :clojure-depends [] :java-depends (java-get-imports contents)}))) #_(parse-java-file "/Users/alex/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java" any?) (defn all-clojure-files [root] (->> (file-seq (io/file root)) (filter #(.endsWith (str %) ".clj")))) #_(all-clojure-files "/home/unlogic/clojure/ns-graph/") (defn all-java-files [root] (->> (file-seq (io/file root)) (filter #(.endsWith (str %) ".java")))) #_(all-java-files "/home/unlogic/projects/android/Abalone/") (defn parse-directories "Find all Java and Clojure sources in the given `dirs` and returns a list of parsed structure for each file. Include only namespaces and classes which pass `include?` predicate." [dirs include?] (mapcat (fn [dir] (concat (keep #(parse-clojure-file % include?) (all-clojure-files dir)) (keep #(parse-java-file % include?) (all-java-files dir)))) dirs)) #_(parse-directories ["/Users/alex/clojure/cider-nrepl/"] any?) (defn class-package [classname] (second (re-matches #"(.*)\..+" (name classname)))) (defn short-name [classname] (second (re-matches #".*\.(.+)" (name classname)))) (defn abbrev-name "Abbreviate a dot- and dash- separated string by first letter. Leave the last part intact unless `abbr-last` is true." [string & [abbr-last]] (let [parts (partition-by #{\. \-} string)] (str/join (if abbr-last (map first parts) (concat (map first (butlast parts)) (last parts)))))) #_(abbrev-name "clojure.common.utils") #_(abbrev-name "clojure.dashed-name.foo.bar") #_(abbrev-name "clojure.dashed-name.foo.baz-qux") (defn compress-java-dependencies-to-packages "For case when `only-packages` is enabled, rewrite the parsed data so that only Java packages and links between them remain." [parsed-files] Step 1 : rewrite all Java class names to packages . parsed-files (mapv (fn [{:keys [name type] :as parsed-file}] (if (= type :java) (assoc parsed-file :name (symbol (class-package name)) :type :java-package) parsed-file)) parsed-files) Step 2 : find same Java packages and merge them . parsed-files (->> parsed-files (group-by (juxt :type :name)) (mapv (fn [[[type name] files]] (if (= type :java-package) {:name name :type type :clojure-depends (vec (distinct (apply concat (map :clojure-depends files)))) :java-depends (vec (distinct (apply concat (map :java-depends files))))} (first files))))) Step 3 : replace Java dependencies everywhere with package names . parsed-files (mapv (fn [parsed-file] (update-in parsed-file [:java-depends] #(vec (distinct (map (comp symbol class-package) %))))) parsed-files)] parsed-files)) #_(parse-directories ["/Users/alex/clojure/cider-nrepl/src/"] any?) (defn parsed-files->graph-data [parsed-files only-packages] {:namespaces (set (concat (keep #(when (= (:type %) :clojure) (:name %)) parsed-files) (mapcat :clojure-depends parsed-files))) :classes (if only-packages [] (->> (concat (keep #(when (= (:type %) :java) (:name %)) parsed-files) (mapcat :java-depends parsed-files)) distinct (group-by class-package))) :packages (if only-packages (set (->> (concat (keep #(when (= (:type %) :java-package) (:name %)) parsed-files) (mapcat :java-depends parsed-files)) distinct)) []) :links (set (->> (for [{:keys [name type clojure-depends java-depends]} parsed-files] (concat (for [dep clojure-depends] [[name type] [dep :clojure]]) (for [dep java-depends] [[name type] [dep :java]]))) (apply concat) set))}) #_(time (parsed-files->graph-data (parse-directories ["/Users/alex/clojure/cider-nrepl/"] any?) true)) #_(generate-graph (parsed-files->graph-data (parse-directory "/home/unlogic/clojure/cider-nrepl/" [])) false) (defn safe-name [string] (str (.replaceAll (str string) "(\\.|-|\\$)" "_"))) (defn- matches? [ns-or-class template] (let [lng (dec (count template))] (if (= (.charAt template lng) \*) (.startsWith (str ns-or-class) (subs template 0 lng)) (= template (str ns-or-class))))) (defn generate-graph "Given graph data, generates almost final DOT-file representation." [{:keys [namespaces classes packages links]} title include? own? {:keys [default-color own-color abbrev-ns cluster-lang ns-shape class-shape]}] (let [clojure-nodes (for [x namespaces :when (include? x)] [(keyword (str "clj_" x)) {:label (if (and abbrev-ns (own? x)) (abbrev-name (str x)) (str x)) :shape ns-shape :color (if (own? x) own-color default-color)}]) java-nodes (concat (for [[package classes] classes :let [own (own? (first classes)) package-label (if (and abbrev-ns own) (abbrev-name package true) package) color (if own own-color default-color) classes-nodes (for [x classes :when (include? x)] [(keyword (str "java_" x)) {:label (short-name x) :shape class-shape :color color}])] :when (seq classes-nodes)] (dot/subgraph (str "cluster_" (safe-name package)) (cons {:label package-label, :color color} classes-nodes))) (for [x packages :when (include? x) :let [own (own? x) package-label (str (if (and abbrev-ns own) (abbrev-name (str x)) x) ".*") color (if own own-color default-color)]] [(keyword (str "java_" x)) {:label package-label :shape class-shape :color color}])) edges (for [[[from-name from-type] [to-name to-type]] links :when (and (include? from-name) (include? to-name))] [(keyword (str (if (= from-type :clojure) "clj_" "java_") from-name)) :> (keyword (str (if (= to-type :clojure) "clj_" "java_") to-name))])] (dot/digraph :simple_hierarchy (concat [{:rankdir :LR, :label title}] edges (if cluster-lang [(dot/subgraph :cluster_clojure (cons {:label "clojure"} clojure-nodes))] clojure-nodes) (if cluster-lang [(dot/subgraph :cluster_java (cons {:label "java"} java-nodes))] java-nodes))))) (def ^:private default-boring-opts {:default-color "black" :own-color "blue" :ns-shape "ellipse" :class-shape "hexagon" :title :name-and-opts :name "Default graph" :format "png" :filename "graph" :view nil}) (def ^:private default-interesting-opts {:abbrev-ns false :no-color false :only-own false :only-packages false :cluster-lang false}) (defn graph-title "Returns a string for the graph caption that contains the name, and possibly the configuration." [{:keys [title name] :as opts}] (let [differing-opts (first (diff opts default-interesting-opts))] (if (= title :name) name (format "%s %s" name (with-out-str ((if (= title :name-and-pprint-opts) pprint println) (apply dissoc differing-opts :source-paths (keys default-boring-opts)))))))) (defn depgraph* "Function that generates a namespace dependency graph given the map of options." [opts] (let [{:keys [source-paths format filename debug view include exclude only-own only-packages] :as opts} (merge default-boring-opts default-interesting-opts opts) source-paths (if (coll? source-paths) source-paths [source-paths]) imgfile (if view (File/createTempFile filename (str "." format)) (io/file (str filename "." format))) include? (fn [ns] (or (some (partial matches? ns) include) (not-any? (partial matches? ns) exclude))) all-files (parse-directories source-paths include?) all-files (if only-packages (compress-java-dependencies-to-packages all-files) all-files) graph-data (parsed-files->graph-data all-files only-packages) ;; Set of all processed files is a predicate to check if a file is from ;; own project. own? (set (map :name all-files)) ;; Enhance include? with checking if the namespace/class belongs to the ;; project. include? (if only-own (fn [ns] (or (some (partial matches? ns) include) (and (own? ns) (not-any? (partial matches? ns) exclude)))) include?) title (graph-title opts) graph (-> graph-data (generate-graph title include? own? opts) dot/dot)] (when debug (spit (io/file (str filename ".dot")) graph)) (dot/save! graph imgfile {:format (keyword format)}) (when view (sh view (str imgfile)))))
null
https://raw.githubusercontent.com/alexander-yakushev/ns-graph/608515958701edcd50c9a101d198bf38a16a2339/src/ns_graph/core.clj
clojure
Set of all processed files is a predicate to check if a file is from own project. Enhance include? with checking if the namespace/class belongs to the project.
(ns ns-graph.core "Generate a namespace dependency graph as an image." (:require [dorothy.core :as dot] [clojure.string :as s] [clojure.java.shell :refer [sh]] [clojure.java.io :as io] [clojure.pprint :refer [pprint]] [clojure.data :refer [diff]] [clojure.string :as str]) (:import java.io.File)) (defn read-ns [file] (with-open [f (-> file io/reader java.io.PushbackReader.)] (binding [*in* f] (let [x (read)] (when (= (first x) 'ns) x))))) #_(read-ns "src/ns_graph.clj") #_(read-ns "build.boot") (defn parse-reference-entry [ref] (if-not (sequential? ref) [ref] (let [ext (loop [[c & r] (rest ref), ns-ext ()] (if (or (keyword? c) (nil? c)) ns-ext (recur r (conj ns-ext (if (sequential? c) (first c) c)))))] (if (empty? ext) [(first ref)] (map #(symbol (str (first ref) \. %)) ext))))) #_(parse-reference-entry 'clojure.pprint) #_(parse-reference-entry '[clojure.pprint :as pp]) #_(parse-reference-entry '[clojure pprint zip]) #_(parse-reference-entry '[clojure.java [io :refer [file]] sh]) (defn parse-ns-subform "Parses references entries under the given `key` in `ns-form`." [ns-form key] (->> ns-form (filter #(and (coll? %) (= key (first %)))) (mapcat rest) (mapcat parse-reference-entry) set)) (defn parse-clojure-file [f include?] (when-let [[_ ns :as ns-form] (read-ns f)] (when (include? ns) {:name ns :type :clojure :clojure-depends (concat (parse-ns-subform ns-form :require) (parse-ns-subform ns-form :use)) :java-depends (parse-ns-subform ns-form :import)}))) #_(parse-clojure-file "/Users/alex/clojure/android/neko/src/clojure/neko/ui/menu.clj" any?) (defn java-get-classname [short-filename content-lines] (let [[_ package] (some #(re-find #"package\s+([\w\._]*)\s*;" %) content-lines) [_ class] (re-matches #"(.+)\.java" short-filename)] (symbol (str package "." class)))) #_(java-get-classname "BoardRenderer.java" (line-seq (io/reader "/home/unlogic/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java"))) (defn java-get-imports [content-lines] (loop [[^String line & r] content-lines imports []] (if line (cond (.startsWith (.trim line) "import static") (when-let [[_ import] (re-find #"import\s+static\s+([\w_\.\*]+)\.(?:[\w_\*]+);" line)] (recur r (conj imports (symbol import)))) (.startsWith (.trim line) "import") (when-let [[_ import] (re-find #"import\s+([\w_\.\*]+);" line)] (recur r (conj imports (symbol import)))) (re-matches #"\s*class\s+[\w_]+" line) imports :else (recur r imports)) imports))) #_(java-get-imports (line-seq (io/reader "/home/unlogic/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java"))) (defn parse-java-file [f include?] (let [contents (line-seq (io/reader f)) cn (java-get-classname (.getName (io/file f)) contents)] (when (include? cn) {:name cn :type :java :clojure-depends [] :java-depends (java-get-imports contents)}))) #_(parse-java-file "/Users/alex/projects/android/Abalone/src/com/bytopia/abalone/BoardRenderer.java" any?) (defn all-clojure-files [root] (->> (file-seq (io/file root)) (filter #(.endsWith (str %) ".clj")))) #_(all-clojure-files "/home/unlogic/clojure/ns-graph/") (defn all-java-files [root] (->> (file-seq (io/file root)) (filter #(.endsWith (str %) ".java")))) #_(all-java-files "/home/unlogic/projects/android/Abalone/") (defn parse-directories "Find all Java and Clojure sources in the given `dirs` and returns a list of parsed structure for each file. Include only namespaces and classes which pass `include?` predicate." [dirs include?] (mapcat (fn [dir] (concat (keep #(parse-clojure-file % include?) (all-clojure-files dir)) (keep #(parse-java-file % include?) (all-java-files dir)))) dirs)) #_(parse-directories ["/Users/alex/clojure/cider-nrepl/"] any?) (defn class-package [classname] (second (re-matches #"(.*)\..+" (name classname)))) (defn short-name [classname] (second (re-matches #".*\.(.+)" (name classname)))) (defn abbrev-name "Abbreviate a dot- and dash- separated string by first letter. Leave the last part intact unless `abbr-last` is true." [string & [abbr-last]] (let [parts (partition-by #{\. \-} string)] (str/join (if abbr-last (map first parts) (concat (map first (butlast parts)) (last parts)))))) #_(abbrev-name "clojure.common.utils") #_(abbrev-name "clojure.dashed-name.foo.bar") #_(abbrev-name "clojure.dashed-name.foo.baz-qux") (defn compress-java-dependencies-to-packages "For case when `only-packages` is enabled, rewrite the parsed data so that only Java packages and links between them remain." [parsed-files] Step 1 : rewrite all Java class names to packages . parsed-files (mapv (fn [{:keys [name type] :as parsed-file}] (if (= type :java) (assoc parsed-file :name (symbol (class-package name)) :type :java-package) parsed-file)) parsed-files) Step 2 : find same Java packages and merge them . parsed-files (->> parsed-files (group-by (juxt :type :name)) (mapv (fn [[[type name] files]] (if (= type :java-package) {:name name :type type :clojure-depends (vec (distinct (apply concat (map :clojure-depends files)))) :java-depends (vec (distinct (apply concat (map :java-depends files))))} (first files))))) Step 3 : replace Java dependencies everywhere with package names . parsed-files (mapv (fn [parsed-file] (update-in parsed-file [:java-depends] #(vec (distinct (map (comp symbol class-package) %))))) parsed-files)] parsed-files)) #_(parse-directories ["/Users/alex/clojure/cider-nrepl/src/"] any?) (defn parsed-files->graph-data [parsed-files only-packages] {:namespaces (set (concat (keep #(when (= (:type %) :clojure) (:name %)) parsed-files) (mapcat :clojure-depends parsed-files))) :classes (if only-packages [] (->> (concat (keep #(when (= (:type %) :java) (:name %)) parsed-files) (mapcat :java-depends parsed-files)) distinct (group-by class-package))) :packages (if only-packages (set (->> (concat (keep #(when (= (:type %) :java-package) (:name %)) parsed-files) (mapcat :java-depends parsed-files)) distinct)) []) :links (set (->> (for [{:keys [name type clojure-depends java-depends]} parsed-files] (concat (for [dep clojure-depends] [[name type] [dep :clojure]]) (for [dep java-depends] [[name type] [dep :java]]))) (apply concat) set))}) #_(time (parsed-files->graph-data (parse-directories ["/Users/alex/clojure/cider-nrepl/"] any?) true)) #_(generate-graph (parsed-files->graph-data (parse-directory "/home/unlogic/clojure/cider-nrepl/" [])) false) (defn safe-name [string] (str (.replaceAll (str string) "(\\.|-|\\$)" "_"))) (defn- matches? [ns-or-class template] (let [lng (dec (count template))] (if (= (.charAt template lng) \*) (.startsWith (str ns-or-class) (subs template 0 lng)) (= template (str ns-or-class))))) (defn generate-graph "Given graph data, generates almost final DOT-file representation." [{:keys [namespaces classes packages links]} title include? own? {:keys [default-color own-color abbrev-ns cluster-lang ns-shape class-shape]}] (let [clojure-nodes (for [x namespaces :when (include? x)] [(keyword (str "clj_" x)) {:label (if (and abbrev-ns (own? x)) (abbrev-name (str x)) (str x)) :shape ns-shape :color (if (own? x) own-color default-color)}]) java-nodes (concat (for [[package classes] classes :let [own (own? (first classes)) package-label (if (and abbrev-ns own) (abbrev-name package true) package) color (if own own-color default-color) classes-nodes (for [x classes :when (include? x)] [(keyword (str "java_" x)) {:label (short-name x) :shape class-shape :color color}])] :when (seq classes-nodes)] (dot/subgraph (str "cluster_" (safe-name package)) (cons {:label package-label, :color color} classes-nodes))) (for [x packages :when (include? x) :let [own (own? x) package-label (str (if (and abbrev-ns own) (abbrev-name (str x)) x) ".*") color (if own own-color default-color)]] [(keyword (str "java_" x)) {:label package-label :shape class-shape :color color}])) edges (for [[[from-name from-type] [to-name to-type]] links :when (and (include? from-name) (include? to-name))] [(keyword (str (if (= from-type :clojure) "clj_" "java_") from-name)) :> (keyword (str (if (= to-type :clojure) "clj_" "java_") to-name))])] (dot/digraph :simple_hierarchy (concat [{:rankdir :LR, :label title}] edges (if cluster-lang [(dot/subgraph :cluster_clojure (cons {:label "clojure"} clojure-nodes))] clojure-nodes) (if cluster-lang [(dot/subgraph :cluster_java (cons {:label "java"} java-nodes))] java-nodes))))) (def ^:private default-boring-opts {:default-color "black" :own-color "blue" :ns-shape "ellipse" :class-shape "hexagon" :title :name-and-opts :name "Default graph" :format "png" :filename "graph" :view nil}) (def ^:private default-interesting-opts {:abbrev-ns false :no-color false :only-own false :only-packages false :cluster-lang false}) (defn graph-title "Returns a string for the graph caption that contains the name, and possibly the configuration." [{:keys [title name] :as opts}] (let [differing-opts (first (diff opts default-interesting-opts))] (if (= title :name) name (format "%s %s" name (with-out-str ((if (= title :name-and-pprint-opts) pprint println) (apply dissoc differing-opts :source-paths (keys default-boring-opts)))))))) (defn depgraph* "Function that generates a namespace dependency graph given the map of options." [opts] (let [{:keys [source-paths format filename debug view include exclude only-own only-packages] :as opts} (merge default-boring-opts default-interesting-opts opts) source-paths (if (coll? source-paths) source-paths [source-paths]) imgfile (if view (File/createTempFile filename (str "." format)) (io/file (str filename "." format))) include? (fn [ns] (or (some (partial matches? ns) include) (not-any? (partial matches? ns) exclude))) all-files (parse-directories source-paths include?) all-files (if only-packages (compress-java-dependencies-to-packages all-files) all-files) graph-data (parsed-files->graph-data all-files only-packages) own? (set (map :name all-files)) include? (if only-own (fn [ns] (or (some (partial matches? ns) include) (and (own? ns) (not-any? (partial matches? ns) exclude)))) include?) title (graph-title opts) graph (-> graph-data (generate-graph title include? own? opts) dot/dot)] (when debug (spit (io/file (str filename ".dot")) graph)) (dot/save! graph imgfile {:format (keyword format)}) (when view (sh view (str imgfile)))))
5f8f4c82e3f8f30617368199ed8a73e1803cacf53e41aa706aca5252c8c7b76d
cyverse-archive/DiscoveryEnvironmentBackend
containers_test.clj
(ns metadactyl.containers-test (:use [clojure.test] [metadactyl.containers] [korma.core] [korma.db] [kameleon.entities]) (:require [clojure.string :as string])) ;;; These tests assume that you have a clean instance of the de database running locally on port 5432 . It 's recommended that you ;;; use the de-db and de-db-loader images to get a database running ;;; with docker. (defdb testdb (postgres {:db "de" :user "de" :password "notprod" :host (System/getenv "POSTGRES_PORT_5432_TCP_ADDR") :port (System/getenv "POSTGRES_PORT_5432_TCP_PORT") :delimiters ""})) (def image-info-map (add-image-info {:name "discoenv/de-db" :tag "latest" :url ""})) (deftest image-tests [] (is (not (image? {:name "test" :tag "test"}))) (is (image? {:name "discoenv/de-db" :tag "latest"})) (is (not (nil? (image-id {:name "discoenv/de-db" :tag "latest"})))) (is (= {:name "discoenv/de-db" :tag "latest" :url ""} (dissoc (image-info (image-id {:name "discoenv/de-db" :tag "latest"})) :id)))) (def tool-map (first (select tools (where {:name "notreal"})))) (def settings-map (add-settings {:name "test" :cpu_shares 1024 :memory_limit 2048 :network_mode "bridge" :working_directory "/work" :tools_id (:id tool-map)})) (deftest settings-tests [] (is (not (nil? (:id settings-map)))) (is (= {:name "test" :cpu_shares 1024 :memory_limit 2048 :network_mode "bridge" :working_directory "/work" :tools_id (:id tool-map) :entrypoint nil} (dissoc (settings (:id settings-map)) :id))) (is (settings? (:id settings-map))) (is (tool-has-settings? (:id tool-map)))) (def devices-map (add-device (:id settings-map) {:host_path "/dev/null" :container_path "/dev/yay"})) (deftest devices-tests [] (is (not (nil? (:id devices-map)))) (is (= {:host_path "/dev/null" :container_path "/dev/yay" :container_settings_id (:id settings-map)} (dissoc (device (:id devices-map)) :id))) (is (device? (:id devices-map))) (is (device-mapping? (:id settings-map) "/dev/null" "/dev/yay")) (is (settings-has-device? (:id settings-map) (:id devices-map)))) (def volume-map (add-volume (:id settings-map) {:host_path "/tmp" :container_path "/foo"})) (deftest volumes-tests [] (is (not (nil? (:id volume-map)))) (is (= {:host_path "/tmp" :container_path "/foo" :container_settings_id (:id settings-map)} (dissoc (volume (:id volume-map)) :id))) (is (volume? (:id volume-map))) (is (volume-mapping? (:id settings-map) "/tmp" "/foo")) (is (settings-has-volume? (:id settings-map) (:id volume-map)))) (def volumes-from-map (add-volumes-from (:id settings-map) "test-name")) (defn volumes-from-test [] (is (not (nil? (:id volumes-from-map)))) (is (= {:name "test-name" :container_settings_id (:id settings-map)} (dissoc (volumes-from (:id volumes-from-map)) :id))) (is (volumes-from? (:id volumes-from-map))) (is (volumes-from-mapping? (:id settings-map) "test-name")) (is (settings-has-volumes-from? (:id settings-map) (:id volumes-from-map)))) (def updated-tool (update tools (set-fields {:container_images_id (:id image-info-map)}) (where {:id (:id tool-map)}))) (defn updated-tool-tests [] (is (not (nil? (:id updated-tool)))) (is (= (dissoc image-info-map :id) (tool-image-info (:id updated-tool)))))
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/test/metadactyl/containers_test.clj
clojure
These tests assume that you have a clean instance of the de use the de-db and de-db-loader images to get a database running with docker.
(ns metadactyl.containers-test (:use [clojure.test] [metadactyl.containers] [korma.core] [korma.db] [kameleon.entities]) (:require [clojure.string :as string])) database running locally on port 5432 . It 's recommended that you (defdb testdb (postgres {:db "de" :user "de" :password "notprod" :host (System/getenv "POSTGRES_PORT_5432_TCP_ADDR") :port (System/getenv "POSTGRES_PORT_5432_TCP_PORT") :delimiters ""})) (def image-info-map (add-image-info {:name "discoenv/de-db" :tag "latest" :url ""})) (deftest image-tests [] (is (not (image? {:name "test" :tag "test"}))) (is (image? {:name "discoenv/de-db" :tag "latest"})) (is (not (nil? (image-id {:name "discoenv/de-db" :tag "latest"})))) (is (= {:name "discoenv/de-db" :tag "latest" :url ""} (dissoc (image-info (image-id {:name "discoenv/de-db" :tag "latest"})) :id)))) (def tool-map (first (select tools (where {:name "notreal"})))) (def settings-map (add-settings {:name "test" :cpu_shares 1024 :memory_limit 2048 :network_mode "bridge" :working_directory "/work" :tools_id (:id tool-map)})) (deftest settings-tests [] (is (not (nil? (:id settings-map)))) (is (= {:name "test" :cpu_shares 1024 :memory_limit 2048 :network_mode "bridge" :working_directory "/work" :tools_id (:id tool-map) :entrypoint nil} (dissoc (settings (:id settings-map)) :id))) (is (settings? (:id settings-map))) (is (tool-has-settings? (:id tool-map)))) (def devices-map (add-device (:id settings-map) {:host_path "/dev/null" :container_path "/dev/yay"})) (deftest devices-tests [] (is (not (nil? (:id devices-map)))) (is (= {:host_path "/dev/null" :container_path "/dev/yay" :container_settings_id (:id settings-map)} (dissoc (device (:id devices-map)) :id))) (is (device? (:id devices-map))) (is (device-mapping? (:id settings-map) "/dev/null" "/dev/yay")) (is (settings-has-device? (:id settings-map) (:id devices-map)))) (def volume-map (add-volume (:id settings-map) {:host_path "/tmp" :container_path "/foo"})) (deftest volumes-tests [] (is (not (nil? (:id volume-map)))) (is (= {:host_path "/tmp" :container_path "/foo" :container_settings_id (:id settings-map)} (dissoc (volume (:id volume-map)) :id))) (is (volume? (:id volume-map))) (is (volume-mapping? (:id settings-map) "/tmp" "/foo")) (is (settings-has-volume? (:id settings-map) (:id volume-map)))) (def volumes-from-map (add-volumes-from (:id settings-map) "test-name")) (defn volumes-from-test [] (is (not (nil? (:id volumes-from-map)))) (is (= {:name "test-name" :container_settings_id (:id settings-map)} (dissoc (volumes-from (:id volumes-from-map)) :id))) (is (volumes-from? (:id volumes-from-map))) (is (volumes-from-mapping? (:id settings-map) "test-name")) (is (settings-has-volumes-from? (:id settings-map) (:id volumes-from-map)))) (def updated-tool (update tools (set-fields {:container_images_id (:id image-info-map)}) (where {:id (:id tool-map)}))) (defn updated-tool-tests [] (is (not (nil? (:id updated-tool)))) (is (= (dissoc image-info-map :id) (tool-image-info (:id updated-tool)))))
b42f9c87d3e1ca303c44e4df21cebcca7558ded40113fa5f85c45d75529484fd
HealthSamurai/stresty
dropdown_datepicker.cljc
(ns anti.dropdown-datepicker (:require [stylo.core :refer [c c?]] [anti.click-outside] [anti.date-input :refer [value-format display-format]] [chrono.calendar] [chrono.now] [chrono.core] [zf.core :as zf] [zframes.re-frame :as zrf] [medley.core :as medley])) (def dropdown-class (c :absolute :rounded :flex :leading-relaxed {:box-shadow "0 3px 6px -4px rgba(0,0,0,.12), 0 6px 16px 0 rgba(0,0,0,.08), 0 9px 28px 8px rgba(0,0,0,.05)"} :overflow-hidden [:bg :white] [:z 100] [:w "fit-content"] [:mt "4px"] [:top "100%"] [:left "-1px"] [:right "-1px"])) (def preset-class (c [:px 2] [:py 1] :truncate [:w-min 40] :cursor-default [:hover [:bg :gray-200]])) (def selected-preset-class (c [:bg :blue-100])) (def calendar-class (c [:p 1] :items-center :cursor-default :grid {:grid-template-columns "repeat(7, 1fr)" :justify-items "center"})) (def button-class (c [:w 7] [:h 7] :flex :text-xs :justify-center :items-center :rounded :leading-none :cursor-pointer [:text :gray-500] [:hover [:bg :gray-200]])) (def day-class (c [:w 7] [:h 7] :flex :justify-center :items-center :leading-none :text-xs [:text :gray-500])) (def option-class (c [:w 7] [:h 7] :flex :text-xs :justify-center :items-center :rounded :leading-none)) (def active-option-class (c [:bg :gray-200])) (def selected-option-class (c [:bg :blue-100])) (def disabled-option-class (c [:text :gray-500])) (zrf/reg-sub opened (fn [[_ opts]] (zrf/subscribe [::zf/state opts])) (fn [state _] (get state :opened))) (zrf/reg-sub active (fn [[_ opts]] (zrf/subscribe [::zf/state opts])) (fn [state _] (get state :active))) (zrf/reg-sub calendar (fn [[_ opts]] (zrf/subscribe [active opts])) (fn [active _] (when active (:cal (chrono.calendar/for-month (:year active) (:month active)))))) (zrf/reg-event-fx activate (fn [{:keys [db]} [_ opts value]] {:db (zf/set-state db opts [:active] value)})) (zrf/reg-event-fx reset-active (fn [{:keys [db]} [_ opts]] {:db (zf/set-state db opts [:active] (or (some-> (zf/value db opts) :value (doto prn) (chrono.core/parse value-format)) (dissoc (chrono.now/today) :tz)))})) (zrf/reg-event-fx open (fn [{:keys [db]} [_ opts]] {:dom/focus (zf/get-id opts) :dispatch-n [[reset-active opts]] :db (zf/set-state db opts [:opened] true)})) (zrf/reg-event-fx change-active (fn [{:keys [db]} [_ opts diff]] (let [{:keys [opened active]} (zf/state db opts)] {:dispatch-n [(when (and opened active) [activate opts (chrono.core/+ active diff)]) (when (not opened) [open opts])]}))) (zrf/reg-event-fx close (fn [{:keys [db]} [_ opts]] {:db (zf/set-state db opts [:opened] false)})) (zrf/reg-event-fx select (fn [_ [_ opts value]] {:dom/focus (zf/get-id opts :input) :dispatch-n [[close opts] [::zf/set-value opts {:value (some-> value (chrono.core/format value-format))}]]})) (zrf/reg-event-fx select-preset (fn [_ [_ opts value]] {:dom/focus (zf/get-id opts :input) :dispatch-n [[close opts] [::zf/set-value opts value]]})) (zrf/reg-event-fx search (fn [{:keys [db]} [_ opts value]] (let [{:keys [opened active]} (zf/state db opts) parsed (->> (chrono.core/parse value display-format) (medley/remove-vals zero?))] {:dispatch-n [[activate opts (merge active parsed)] (when-not opened [open opts])]}))) (zrf/reg-event-fx select-active (fn [{:keys [db]} [_ opts]] (let [{:keys [active]} (zf/state db opts)] {:dispatch-n [(when active [select opts active])]}))) (zrf/reg-event-fx toggle-opened (fn [{:keys [db]} [_ opts]] (let [{:keys [opened]} (zf/state db opts)] {:dispatch-n [(if opened [close opts] [open opts])]}))) (zrf/reg-sub presets (fn [[_ opts]] [(zrf/subscribe [::zf/schema opts]) (zrf/subscribe [::zf/state opts])]) (fn [[schema state] _] (:options schema))) (defn dropdown-datepicker [{:keys [opts]}] (let [presets (zrf/subscribe [presets opts]) opened (zrf/subscribe [opened opts]) value (zrf/subscribe [::zf/value opts]) active (zrf/subscribe [active opts]) calendar (zrf/subscribe [calendar opts]) on-wrapper-click (fn [_] (zrf/dispatch [toggle-opened opts])) on-click-outside (fn [_] (zrf/dispatch [close opts])) on-preset-click (fn [date _] (zrf/dispatch [select-preset opts date])) on-option-click (fn [date _] (zrf/dispatch [select opts date])) on-option-mouse-move (fn [date _] (zrf/dispatch [activate opts date])) on-next-year (fn [_] (zrf/dispatch [change-active opts {:year +1}])) on-prev-year (fn [_] (zrf/dispatch [change-active opts {:year -1}])) on-next-month (fn [_] (zrf/dispatch [change-active opts {:month +1}])) on-prev-month (fn [_] (zrf/dispatch [change-active opts {:month -1}]))] (fn [_ & children] (let [presets @presets opened @opened value @value active @active calendar @calendar] [:div {:class (c :relative :inline-block)} (into [:div {:class (c :inline-block :cursor-pointer) :on-click on-wrapper-click}] children) (when opened [anti.click-outside/click-outside {:on-click on-click-outside} [:div {:class (c :absolute [:w 200])} [:div {:class dropdown-class} [:div {:class (c [:py 1])} (for [preset presets] [:div {:key (:value preset) :id (:id preset) :on-click (partial on-preset-click preset) :class [preset-class (when (:anti/selected preset) selected-preset-class)]} (or (:display preset) (pr-str preset))])] [:div {:class calendar-class} [:div {:class button-class :on-click on-prev-year} [:i.far.fa-angle-double-left]] [:div {:class button-class :on-click on-prev-month} [:i.far.fa-angle-left]] [:div {:class (c [:space-x 1] {:grid-column "auto / span 3"})} [:span (get-in chrono.calendar/month-names [(:month active) :short])] [:span (:year active)]] [:div {:class button-class :on-click on-next-month} [:i.far.fa-angle-right]] [:div {:class button-class :on-click on-next-year} [:i.far.fa-angle-double-right]] (for [[_ {day :name}] chrono.calendar/weeks] [:div {:key day :class day-class} (subs day 0 2)]) (for [[index week] (map-indexed vector calendar)] [:<> {:key index} (for [[index date] (map-indexed vector week) :let [alien? (not (:current date)) date (dissoc date :current) active? (= active date) selected? (= value date)]] [:div {:key index :class [option-class (cond selected? selected-option-class active? active-option-class alien? disabled-option-class)] :on-click (partial on-option-click date) :on-mouse-move (when-not (or active? alien?) (partial on-option-mouse-move date))} (:day date)])])]]]])]))))
null
https://raw.githubusercontent.com/HealthSamurai/stresty/130cedde6bf53e07fe25a6b0b13b8bf70846f15a/src-ui/anti/dropdown_datepicker.cljc
clojure
(ns anti.dropdown-datepicker (:require [stylo.core :refer [c c?]] [anti.click-outside] [anti.date-input :refer [value-format display-format]] [chrono.calendar] [chrono.now] [chrono.core] [zf.core :as zf] [zframes.re-frame :as zrf] [medley.core :as medley])) (def dropdown-class (c :absolute :rounded :flex :leading-relaxed {:box-shadow "0 3px 6px -4px rgba(0,0,0,.12), 0 6px 16px 0 rgba(0,0,0,.08), 0 9px 28px 8px rgba(0,0,0,.05)"} :overflow-hidden [:bg :white] [:z 100] [:w "fit-content"] [:mt "4px"] [:top "100%"] [:left "-1px"] [:right "-1px"])) (def preset-class (c [:px 2] [:py 1] :truncate [:w-min 40] :cursor-default [:hover [:bg :gray-200]])) (def selected-preset-class (c [:bg :blue-100])) (def calendar-class (c [:p 1] :items-center :cursor-default :grid {:grid-template-columns "repeat(7, 1fr)" :justify-items "center"})) (def button-class (c [:w 7] [:h 7] :flex :text-xs :justify-center :items-center :rounded :leading-none :cursor-pointer [:text :gray-500] [:hover [:bg :gray-200]])) (def day-class (c [:w 7] [:h 7] :flex :justify-center :items-center :leading-none :text-xs [:text :gray-500])) (def option-class (c [:w 7] [:h 7] :flex :text-xs :justify-center :items-center :rounded :leading-none)) (def active-option-class (c [:bg :gray-200])) (def selected-option-class (c [:bg :blue-100])) (def disabled-option-class (c [:text :gray-500])) (zrf/reg-sub opened (fn [[_ opts]] (zrf/subscribe [::zf/state opts])) (fn [state _] (get state :opened))) (zrf/reg-sub active (fn [[_ opts]] (zrf/subscribe [::zf/state opts])) (fn [state _] (get state :active))) (zrf/reg-sub calendar (fn [[_ opts]] (zrf/subscribe [active opts])) (fn [active _] (when active (:cal (chrono.calendar/for-month (:year active) (:month active)))))) (zrf/reg-event-fx activate (fn [{:keys [db]} [_ opts value]] {:db (zf/set-state db opts [:active] value)})) (zrf/reg-event-fx reset-active (fn [{:keys [db]} [_ opts]] {:db (zf/set-state db opts [:active] (or (some-> (zf/value db opts) :value (doto prn) (chrono.core/parse value-format)) (dissoc (chrono.now/today) :tz)))})) (zrf/reg-event-fx open (fn [{:keys [db]} [_ opts]] {:dom/focus (zf/get-id opts) :dispatch-n [[reset-active opts]] :db (zf/set-state db opts [:opened] true)})) (zrf/reg-event-fx change-active (fn [{:keys [db]} [_ opts diff]] (let [{:keys [opened active]} (zf/state db opts)] {:dispatch-n [(when (and opened active) [activate opts (chrono.core/+ active diff)]) (when (not opened) [open opts])]}))) (zrf/reg-event-fx close (fn [{:keys [db]} [_ opts]] {:db (zf/set-state db opts [:opened] false)})) (zrf/reg-event-fx select (fn [_ [_ opts value]] {:dom/focus (zf/get-id opts :input) :dispatch-n [[close opts] [::zf/set-value opts {:value (some-> value (chrono.core/format value-format))}]]})) (zrf/reg-event-fx select-preset (fn [_ [_ opts value]] {:dom/focus (zf/get-id opts :input) :dispatch-n [[close opts] [::zf/set-value opts value]]})) (zrf/reg-event-fx search (fn [{:keys [db]} [_ opts value]] (let [{:keys [opened active]} (zf/state db opts) parsed (->> (chrono.core/parse value display-format) (medley/remove-vals zero?))] {:dispatch-n [[activate opts (merge active parsed)] (when-not opened [open opts])]}))) (zrf/reg-event-fx select-active (fn [{:keys [db]} [_ opts]] (let [{:keys [active]} (zf/state db opts)] {:dispatch-n [(when active [select opts active])]}))) (zrf/reg-event-fx toggle-opened (fn [{:keys [db]} [_ opts]] (let [{:keys [opened]} (zf/state db opts)] {:dispatch-n [(if opened [close opts] [open opts])]}))) (zrf/reg-sub presets (fn [[_ opts]] [(zrf/subscribe [::zf/schema opts]) (zrf/subscribe [::zf/state opts])]) (fn [[schema state] _] (:options schema))) (defn dropdown-datepicker [{:keys [opts]}] (let [presets (zrf/subscribe [presets opts]) opened (zrf/subscribe [opened opts]) value (zrf/subscribe [::zf/value opts]) active (zrf/subscribe [active opts]) calendar (zrf/subscribe [calendar opts]) on-wrapper-click (fn [_] (zrf/dispatch [toggle-opened opts])) on-click-outside (fn [_] (zrf/dispatch [close opts])) on-preset-click (fn [date _] (zrf/dispatch [select-preset opts date])) on-option-click (fn [date _] (zrf/dispatch [select opts date])) on-option-mouse-move (fn [date _] (zrf/dispatch [activate opts date])) on-next-year (fn [_] (zrf/dispatch [change-active opts {:year +1}])) on-prev-year (fn [_] (zrf/dispatch [change-active opts {:year -1}])) on-next-month (fn [_] (zrf/dispatch [change-active opts {:month +1}])) on-prev-month (fn [_] (zrf/dispatch [change-active opts {:month -1}]))] (fn [_ & children] (let [presets @presets opened @opened value @value active @active calendar @calendar] [:div {:class (c :relative :inline-block)} (into [:div {:class (c :inline-block :cursor-pointer) :on-click on-wrapper-click}] children) (when opened [anti.click-outside/click-outside {:on-click on-click-outside} [:div {:class (c :absolute [:w 200])} [:div {:class dropdown-class} [:div {:class (c [:py 1])} (for [preset presets] [:div {:key (:value preset) :id (:id preset) :on-click (partial on-preset-click preset) :class [preset-class (when (:anti/selected preset) selected-preset-class)]} (or (:display preset) (pr-str preset))])] [:div {:class calendar-class} [:div {:class button-class :on-click on-prev-year} [:i.far.fa-angle-double-left]] [:div {:class button-class :on-click on-prev-month} [:i.far.fa-angle-left]] [:div {:class (c [:space-x 1] {:grid-column "auto / span 3"})} [:span (get-in chrono.calendar/month-names [(:month active) :short])] [:span (:year active)]] [:div {:class button-class :on-click on-next-month} [:i.far.fa-angle-right]] [:div {:class button-class :on-click on-next-year} [:i.far.fa-angle-double-right]] (for [[_ {day :name}] chrono.calendar/weeks] [:div {:key day :class day-class} (subs day 0 2)]) (for [[index week] (map-indexed vector calendar)] [:<> {:key index} (for [[index date] (map-indexed vector week) :let [alien? (not (:current date)) date (dissoc date :current) active? (= active date) selected? (= value date)]] [:div {:key index :class [option-class (cond selected? selected-option-class active? active-option-class alien? disabled-option-class)] :on-click (partial on-option-click date) :on-mouse-move (when-not (or active? alien?) (partial on-option-mouse-move date))} (:day date)])])]]]])]))))
714802fd80968c16846f58f954ed8d21cb1b91ddbd1f3498364b88f2b6905810
ailisp/mcclim-graphic-forms
test.lisp
( in - package : clim - gf ) ;;; ;;; (run-frame-top-level (make-application-frame 'buttons)) ;;; (in-package :clim-gf) (define-application-frame buttons () () (:menu-bar nil) (:layouts (default (vertically (:equalize-width t) (make-pane 'push-button :label "First"))))) (defmethod clim:activate-callback ((button clim:push-button) client gadget-id) (with-slots (output-pane) client (debug-print "hello-world")))
null
https://raw.githubusercontent.com/ailisp/mcclim-graphic-forms/a81cc6ad95a3ce07a41d3fe72e1f2d5369e45149/temp/test.lisp
lisp
(run-frame-top-level (make-application-frame 'buttons))
( in - package : clim - gf ) (in-package :clim-gf) (define-application-frame buttons () () (:menu-bar nil) (:layouts (default (vertically (:equalize-width t) (make-pane 'push-button :label "First"))))) (defmethod clim:activate-callback ((button clim:push-button) client gadget-id) (with-slots (output-pane) client (debug-print "hello-world")))
628e8f58d17d6f9e2bbf812650d56db1c0659464adc46cd060e005c7448f2d48
rabbitmq/khepri
queries.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright © 2021 - 2023 VMware , Inc. or its affiliates . All rights reserved . %% -module(queries). -include_lib("eunit/include/eunit.hrl"). -include("include/khepri.hrl"). -include("src/khepri_machine.hrl"). -include("test/helpers.hrl"). %% khepri:get_root/1 is unexported when compiled without `-DTEST'. -dialyzer(no_missing_calls). query_a_non_existing_node_test() -> S0 = khepri_machine:init(?MACH_PARAMS()), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes(Tree, [foo], #{}), ?assertEqual( {ok, #{}}, Ret). query_an_existing_node_with_no_value_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}}}, Ret). query_an_existing_node_with_value_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo, bar], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_with_matching_condition_test() -> Commands = [#put{path = [foo], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [foo, #if_data_matches{pattern = value}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_with_non_matching_condition_test() -> Commands = [#put{path = [foo], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [foo, #if_data_matches{pattern = other}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{}}, Ret). query_child_nodes_of_a_specific_node_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_name_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_child_nodes_of_a_specific_node_with_condition_on_leaf_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [#if_name_matches{regex = any}, #if_child_list_length{count = {ge, 1}}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}}}, Ret). query_many_nodes_with_condition_on_parent_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_child_list_length{count = {gt, 1}}, #if_name_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret1 = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_list_length => 2}, [foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 2, child_list_length => 1}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret1), Ret2 = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual(Ret1, Ret2). query_many_nodes_recursively_using_regex_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = "o"}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_list_length => 2}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_condition_on_leaf_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}, #if_name_matches{regex = "o"}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_condition_on_self_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [#if_path_matches{regex = any}, #if_data_matches{pattern = '_'}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 2, child_list_length => 1}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_several_star_star_test() -> Commands = [#put{path = [foo, bar, baz, qux], payload = khepri_payload:data(qux_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}, baz, #if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar, baz, qux] => #{data => qux_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_using_relative_path_components_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [?THIS_KHEPRI_NODE, foo, ?PARENT_KHEPRI_NODE, foo, bar], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). include_child_names_in_query_response_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, quux], payload = khepri_payload:data(quux_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo], #{props_to_return => [payload, payload_version, child_list_version, child_names]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_names => [bar, quux]}}}, Ret).
null
https://raw.githubusercontent.com/rabbitmq/khepri/91699e5e0e7224e6cea0841ed05ffc346a115cab/test/queries.erl
erlang
khepri:get_root/1 is unexported when compiled without `-DTEST'.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright © 2021 - 2023 VMware , Inc. or its affiliates . All rights reserved . -module(queries). -include_lib("eunit/include/eunit.hrl"). -include("include/khepri.hrl"). -include("src/khepri_machine.hrl"). -include("test/helpers.hrl"). -dialyzer(no_missing_calls). query_a_non_existing_node_test() -> S0 = khepri_machine:init(?MACH_PARAMS()), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes(Tree, [foo], #{}), ?assertEqual( {ok, #{}}, Ret). query_an_existing_node_with_no_value_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}}}, Ret). query_an_existing_node_with_value_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo, bar], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_with_matching_condition_test() -> Commands = [#put{path = [foo], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [foo, #if_data_matches{pattern = value}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_with_non_matching_condition_test() -> Commands = [#put{path = [foo], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [foo, #if_data_matches{pattern = other}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{}}, Ret). query_child_nodes_of_a_specific_node_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_name_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_child_nodes_of_a_specific_node_with_condition_on_leaf_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [#if_name_matches{regex = any}, #if_child_list_length{count = {ge, 1}}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 1, child_list_length => 1}}}, Ret). query_many_nodes_with_condition_on_parent_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_child_list_length{count = {gt, 1}}, #if_name_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret1 = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_list_length => 2}, [foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 2, child_list_length => 1}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret1), Ret2 = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual(Ret1, Ret2). query_many_nodes_recursively_using_regex_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = "o"}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_list_length => 2}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_condition_on_leaf_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}, #if_name_matches{regex = "o"}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_condition_on_self_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_all{conditions = [#if_path_matches{regex = any}, #if_data_matches{pattern = '_'}]}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => bar_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [foo, youpi] => #{data => youpi_value, payload_version => 1, child_list_version => 1, child_list_length => 0}, [baz] => #{data => baz_value, payload_version => 1, child_list_version => 2, child_list_length => 1}, [baz, pouet] => #{data => pouet_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_many_nodes_recursively_with_several_star_star_test() -> Commands = [#put{path = [foo, bar, baz, qux], payload = khepri_payload:data(qux_value)}, #put{path = [foo, youpi], payload = khepri_payload:data(youpi_value)}, #put{path = [baz], payload = khepri_payload:data(baz_value)}, #put{path = [baz, pouet], payload = khepri_payload:data(pouet_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [#if_path_matches{regex = any}, baz, #if_path_matches{regex = any}], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar, baz, qux] => #{data => qux_value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). query_a_node_using_relative_path_components_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [?THIS_KHEPRI_NODE, foo, ?PARENT_KHEPRI_NODE, foo, bar], #{props_to_return => [payload, payload_version, child_list_version, child_list_length]}), ?assertEqual( {ok, #{[foo, bar] => #{data => value, payload_version => 1, child_list_version => 1, child_list_length => 0}}}, Ret). include_child_names_in_query_response_test() -> Commands = [#put{path = [foo, bar], payload = khepri_payload:data(bar_value)}, #put{path = [foo, quux], payload = khepri_payload:data(quux_value)}], S0 = khepri_machine:init(?MACH_PARAMS(Commands)), Tree = khepri_machine:get_tree(S0), Ret = khepri_tree:find_matching_nodes( Tree, [foo], #{props_to_return => [payload, payload_version, child_list_version, child_names]}), ?assertEqual( {ok, #{[foo] => #{payload_version => 1, child_list_version => 2, child_names => [bar, quux]}}}, Ret).
176cf217d0fb768388b0e8bea56846740429c29ae3d170c0275a53ac40941316
racket/draw
lzw.rkt
#lang racket/base ;;; Translated from Skippy for Common Lisp: ;;; Copyright ( c ) 2006 , All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; I d : lzw.lisp , v 1.11 2007/01/03 22:01:10 xach Exp (provide lzw-decompress) (define (make-input-bitstream bstr) (let ([pos 0] [val 0] [bits 0] [limit (bytes-length bstr)]) (lambda (n) (let loop () (cond [(n . <= . bits) (begin0 (bitwise-and val (sub1 (arithmetic-shift 1 n))) (set! val (arithmetic-shift val (- n))) (set! bits (- bits n)))] [(= pos limit) (add1 (arithmetic-shift 1 n))] [else (set! val (bitwise-ior (arithmetic-shift (bytes-ref bstr pos) bits) val)) (set! pos (add1 pos)) (set! bits (+ 8 bits)) (loop)]))))) (define (read-bits n bstream) (bstream n)) (define (lzw-decompress result-bstr code-size bstr) (let* ((entries (make-vector 4096 -1)) (preds (make-vector 4096 -1)) (clear-code (expt 2 code-size)) (end-of-input (+ clear-code 1)) (next-entry-index (+ clear-code 2)) (compression-size (add1 code-size)) (compression-threshold (* clear-code 2)) (just-emit? #f) (pos 0) (bitstream (make-input-bitstream bstr))) (for ([i (in-range clear-code)]) (vector-set! entries i i)) (letrec ([reset-table (lambda () (vector-fill! preds -1) (for ([i (in-range clear-code 4096)]) (vector-set! entries i -1)) (set! next-entry-index (+ clear-code 2)) (set! compression-size (add1 code-size)) (set! compression-threshold (* clear-code 2)) (set! just-emit? #f))] [root-value (lambda (code) (let loop ([code code]) (let ([pred (vector-ref preds code)]) (if (negative? pred) (vector-ref entries code) (loop pred)))))] [increase-compression-size! (lambda () (cond [(= compression-size 12) ;; 12 is the maximum compression size, so go into ;; "just emit" mode, which doesn't add new entries ;; until a reset (set! just-emit? #t)] [else (set! compression-size (add1 compression-size)) (set! compression-threshold (* compression-threshold 2))]))] [add-entry (lambda (entry pred) (when (>= pred next-entry-index) (error "Corrupt data in LZW stream")) (vector-set! preds next-entry-index pred) (vector-set! entries next-entry-index entry) (let ([result next-entry-index]) (set! next-entry-index (add1 next-entry-index)) (when (>= next-entry-index compression-threshold) (increase-compression-size!)) result))] [code-depth (lambda (code) (let loop ([depth 0] [code code]) (let ([pred (vector-ref preds code)]) (if (negative? pred) depth (loop (add1 depth) pred)))))] [output-code-string (lambda (code) (let ([j pos]) (let ([i (+ pos (code-depth code))]) (set! pos (add1 i)) (if (>= i (bytes-length result-bstr)) (log-warning "Too much input data for image, ignoring extra") (let loop ([code code] [i i]) ( printf " set ~a\n " ( vector - ref entries code ) ) (bytes-set! result-bstr i (vector-ref entries code)) (when (i . > . j) (loop (vector-ref preds code) (sub1 i))))))))]) (let loop ([last-code -1]) (let ([code (read-bits compression-size bitstream)]) ;; (printf "~s: ~s ~s ~s\n" compression-size code clear-code end-of-input) (cond [(= code clear-code) (reset-table) (loop -1)] [(= code end-of-input) (void)] [(or just-emit? (= last-code -1)) (output-code-string code) (loop code)] [else (let ([entry (vector-ref entries code)]) (if (negative? entry) (let ([root (root-value last-code)]) (output-code-string (add-entry root last-code))) (let ([root (root-value code)]) (add-entry root last-code) (output-code-string code)))) (loop code)]))))))
null
https://raw.githubusercontent.com/racket/draw/a6558bdc18438e784c23d452ffd877dac867a7fd/draw-lib/racket/draw/private/lzw.rkt
racket
Translated from Skippy for Common Lisp: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 12 is the maximum compression size, so go into "just emit" mode, which doesn't add new entries until a reset (printf "~s: ~s ~s ~s\n" compression-size code clear-code end-of-input)
#lang racket/base Copyright ( c ) 2006 , All Rights Reserved DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , I d : lzw.lisp , v 1.11 2007/01/03 22:01:10 xach Exp (provide lzw-decompress) (define (make-input-bitstream bstr) (let ([pos 0] [val 0] [bits 0] [limit (bytes-length bstr)]) (lambda (n) (let loop () (cond [(n . <= . bits) (begin0 (bitwise-and val (sub1 (arithmetic-shift 1 n))) (set! val (arithmetic-shift val (- n))) (set! bits (- bits n)))] [(= pos limit) (add1 (arithmetic-shift 1 n))] [else (set! val (bitwise-ior (arithmetic-shift (bytes-ref bstr pos) bits) val)) (set! pos (add1 pos)) (set! bits (+ 8 bits)) (loop)]))))) (define (read-bits n bstream) (bstream n)) (define (lzw-decompress result-bstr code-size bstr) (let* ((entries (make-vector 4096 -1)) (preds (make-vector 4096 -1)) (clear-code (expt 2 code-size)) (end-of-input (+ clear-code 1)) (next-entry-index (+ clear-code 2)) (compression-size (add1 code-size)) (compression-threshold (* clear-code 2)) (just-emit? #f) (pos 0) (bitstream (make-input-bitstream bstr))) (for ([i (in-range clear-code)]) (vector-set! entries i i)) (letrec ([reset-table (lambda () (vector-fill! preds -1) (for ([i (in-range clear-code 4096)]) (vector-set! entries i -1)) (set! next-entry-index (+ clear-code 2)) (set! compression-size (add1 code-size)) (set! compression-threshold (* clear-code 2)) (set! just-emit? #f))] [root-value (lambda (code) (let loop ([code code]) (let ([pred (vector-ref preds code)]) (if (negative? pred) (vector-ref entries code) (loop pred)))))] [increase-compression-size! (lambda () (cond [(= compression-size 12) (set! just-emit? #t)] [else (set! compression-size (add1 compression-size)) (set! compression-threshold (* compression-threshold 2))]))] [add-entry (lambda (entry pred) (when (>= pred next-entry-index) (error "Corrupt data in LZW stream")) (vector-set! preds next-entry-index pred) (vector-set! entries next-entry-index entry) (let ([result next-entry-index]) (set! next-entry-index (add1 next-entry-index)) (when (>= next-entry-index compression-threshold) (increase-compression-size!)) result))] [code-depth (lambda (code) (let loop ([depth 0] [code code]) (let ([pred (vector-ref preds code)]) (if (negative? pred) depth (loop (add1 depth) pred)))))] [output-code-string (lambda (code) (let ([j pos]) (let ([i (+ pos (code-depth code))]) (set! pos (add1 i)) (if (>= i (bytes-length result-bstr)) (log-warning "Too much input data for image, ignoring extra") (let loop ([code code] [i i]) ( printf " set ~a\n " ( vector - ref entries code ) ) (bytes-set! result-bstr i (vector-ref entries code)) (when (i . > . j) (loop (vector-ref preds code) (sub1 i))))))))]) (let loop ([last-code -1]) (let ([code (read-bits compression-size bitstream)]) (cond [(= code clear-code) (reset-table) (loop -1)] [(= code end-of-input) (void)] [(or just-emit? (= last-code -1)) (output-code-string code) (loop code)] [else (let ([entry (vector-ref entries code)]) (if (negative? entry) (let ([root (root-value last-code)]) (output-code-string (add-entry root last-code))) (let ([root (root-value code)]) (add-entry root last-code) (output-code-string code)))) (loop code)]))))))
b4b8fd03bc42c5cefb9639276f2f270e2760cafb23335b814a51f02baa2a2cda
tchoutri/pg-entity
DBT.hs
# LANGUAGE CPP # | Module : Database . PostgreSQL.Entity . DBT Copyright : , 2018 , 2021 License : MIT Maintainer : Stability : stable The ' Database . PostgreSQL.Transact . DBT ' plumbing module to handle database queries and pools Module : Database.PostgreSQL.Entity.DBT Copyright : © Clément Delafargue, 2018 Théophile Choutri, 2021 License : MIT Maintainer : Stability : stable The 'Database.PostgreSQL.Transact.DBT' plumbing module to handle database queries and pools -} module Database.PostgreSQL.Entity.DBT ( mkPool , withPool , execute , executeMany , query , query_ , queryOne , queryOne_ , QueryNature (..) ) where #ifdef PROD #else import Colourista (cyan, red, yellow, formatWith) import Data.ByteString (ByteString) import qualified Database.PostgreSQL.Simple as Simple import System.IO (stdout) import qualified Data.ByteString.Char8 as BS #endif import Control.Monad.IO.Class #if MIN_VERSION_resource_pool(0,3,0) #else import Control.Monad.Trans.Control #endif import Data.Int import Data.Maybe (listToMaybe) import Data.Pool (Pool, createPool, withResource) import Data.Time (NominalDiffTime) import Data.Vector (Vector) import qualified Data.Vector as V import Database.PostgreSQL.Simple as PG (ConnectInfo, Connection, FromRow, Query, ToRow, close, connect) import qualified Database.PostgreSQL.Transact as PGT | Create a Pool Connection with the appropriate parameters @since 0.0.1.0 @since 0.0.1.0 -} mkPool Database access information -> Int -- Number of sub-pools -> NominalDiffTime -- Allowed timeout -> Int -- Number of connections -> IO (Pool Connection) mkPool connectInfo subPools timeout connections = createPool (connect connectInfo) close subPools timeout connections | Run a DBT action with no explicit error handling . This functions is suited for using ' MonadError ' error handling . = = = _ _ Example _ _ > let e1 = E 1 True True > result < - runExceptT @EntityError $ do > withPool pool $ insertEntity e1 > withPool pool $ markForProcessing 1 > case result of > Left err - > print err > Right _ - > putStrLn " Everything went well " See the code in the @example/@ directory on GitHub @since 0.0.1.0 This functions is suited for using 'MonadError' error handling. === __Example__ > let e1 = E 1 True True > result <- runExceptT @EntityError $ do > withPool pool $ insertEntity e1 > withPool pool $ markForProcessing 1 > case result of > Left err -> print err > Right _ -> putStrLn "Everything went well" See the code in the @example/@ directory on GitHub @since 0.0.1.0 -} #if MIN_VERSION_resource_pool(0,3,0) withPool :: (MonadIO m) => Pool Connection -> PGT.DBT IO a -> m a withPool pool action = liftIO $ withResource pool (\conn -> PGT.runDBTSerializable action conn) #else withPool :: (MonadBaseControl IO m) => Pool Connection -> PGT.DBT m a -> m a withPool pool action = withResource pool (\conn -> PGT.runDBTSerializable action conn) #endif | Query wrapper that returns a ' Vector ' of results @since 0.0.1.0 @since 0.0.1.0 -} query :: (ToRow params, FromRow result, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m (Vector result) query queryNature q params = do logQueryFormat queryNature q params V.fromList <$> PGT.query q params | Query wrapper that returns a ' Vector ' of results and does not take an argument @since 0.0.1.0 @since 0.0.1.0 -} query_ :: (FromRow result, MonadIO m) => QueryNature -> Query -> PGT.DBT m (Vector result) query_ queryNature q = do logQueryFormat queryNature q () V.fromList <$> PGT.query_ q | Query wrapper that returns one result . @since 0.0.1.0 @since 0.0.1.0 -} queryOne :: (ToRow params, FromRow result, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m (Maybe result) queryOne queryNature q params = do logQueryFormat queryNature q params listToMaybe <$> PGT.query q params -- | Query wrapper that returns one result and does not take an argument @since 0.0.2.0 @since 0.0.2.0 -} queryOne_ :: (FromRow result, MonadIO m) => QueryNature -> Query -> PGT.DBT m (Maybe result) queryOne_ queryNature q = do logQueryFormat queryNature q () listToMaybe <$> PGT.query_ q | Query wrapper for SQL statements which do not return . @since 0.0.1.0 @since 0.0.1.0 -} execute :: (ToRow params, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m Int64 execute queryNature q params = do logQueryFormat queryNature q params PGT.execute q params {-| Query wrapper for SQL statements that operate on multiple rows which do not return. @since 0.0.2.0 -} executeMany :: (ToRow params, MonadIO m) => QueryNature -> Query -> [params] -> PGT.DBT m Int64 executeMany queryNature q params = do logQueryFormatMany queryNature q params PGT.executeMany q params #ifndef PROD displayColoured :: (MonadIO m) => ByteString -> ByteString -> PGT.DBT m () displayColoured colour text = liftIO $ BS.hPutStrLn stdout (formatWith [colour] text) #endif #ifdef PROD logQueryFormat :: (Monad m) => QueryNature -> Query -> params -> PGT.DBT m () logQueryFormat _ _ _ = pure () #else logQueryFormat :: (ToRow params, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m () logQueryFormat queryNature q params = do msg <- PGT.formatQuery q params case queryNature of Select -> displayColoured cyan msg Update -> displayColoured yellow msg Insert -> displayColoured yellow msg Delete -> displayColoured red msg #endif #ifdef PROD logQueryFormatMany :: (Monad m) => QueryNature -> Query -> [params] -> PGT.DBT m () logQueryFormatMany _ _ _ = pure () #else logQueryFormatMany :: (ToRow params, MonadIO m) => QueryNature -> Query -> [params] -> PGT.DBT m () logQueryFormatMany queryNature q params = do msg <- formatMany q params case queryNature of Select -> displayColoured cyan msg Update -> displayColoured yellow msg Insert -> displayColoured yellow msg Delete -> displayColoured red msg formatMany :: (ToRow q, MonadIO m) => Query -> [q] -> PGT.DBT m ByteString formatMany q xs = PGT.getConnection >>= \conn -> liftIO $ Simple.formatMany conn q xs #endif | This sum type is given to the ' query ' , ' queryOne ' and ' execute ' functions to help with logging . @since 0.0.1.0 with logging. @since 0.0.1.0 -} data QueryNature = Select | Insert | Update | Delete deriving (Eq, Show)
null
https://raw.githubusercontent.com/tchoutri/pg-entity/50d47c9ea9c747b4e352530cd287f98d41035dd4/src/Database/PostgreSQL/Entity/DBT.hs
haskell
Number of sub-pools Allowed timeout Number of connections | Query wrapper for SQL statements that operate on multiple rows which do not return. @since 0.0.2.0
# LANGUAGE CPP # | Module : Database . PostgreSQL.Entity . DBT Copyright : , 2018 , 2021 License : MIT Maintainer : Stability : stable The ' Database . PostgreSQL.Transact . DBT ' plumbing module to handle database queries and pools Module : Database.PostgreSQL.Entity.DBT Copyright : © Clément Delafargue, 2018 Théophile Choutri, 2021 License : MIT Maintainer : Stability : stable The 'Database.PostgreSQL.Transact.DBT' plumbing module to handle database queries and pools -} module Database.PostgreSQL.Entity.DBT ( mkPool , withPool , execute , executeMany , query , query_ , queryOne , queryOne_ , QueryNature (..) ) where #ifdef PROD #else import Colourista (cyan, red, yellow, formatWith) import Data.ByteString (ByteString) import qualified Database.PostgreSQL.Simple as Simple import System.IO (stdout) import qualified Data.ByteString.Char8 as BS #endif import Control.Monad.IO.Class #if MIN_VERSION_resource_pool(0,3,0) #else import Control.Monad.Trans.Control #endif import Data.Int import Data.Maybe (listToMaybe) import Data.Pool (Pool, createPool, withResource) import Data.Time (NominalDiffTime) import Data.Vector (Vector) import qualified Data.Vector as V import Database.PostgreSQL.Simple as PG (ConnectInfo, Connection, FromRow, Query, ToRow, close, connect) import qualified Database.PostgreSQL.Transact as PGT | Create a Pool Connection with the appropriate parameters @since 0.0.1.0 @since 0.0.1.0 -} mkPool Database access information -> IO (Pool Connection) mkPool connectInfo subPools timeout connections = createPool (connect connectInfo) close subPools timeout connections | Run a DBT action with no explicit error handling . This functions is suited for using ' MonadError ' error handling . = = = _ _ Example _ _ > let e1 = E 1 True True > result < - runExceptT @EntityError $ do > withPool pool $ insertEntity e1 > withPool pool $ markForProcessing 1 > case result of > Left err - > print err > Right _ - > putStrLn " Everything went well " See the code in the @example/@ directory on GitHub @since 0.0.1.0 This functions is suited for using 'MonadError' error handling. === __Example__ > let e1 = E 1 True True > result <- runExceptT @EntityError $ do > withPool pool $ insertEntity e1 > withPool pool $ markForProcessing 1 > case result of > Left err -> print err > Right _ -> putStrLn "Everything went well" See the code in the @example/@ directory on GitHub @since 0.0.1.0 -} #if MIN_VERSION_resource_pool(0,3,0) withPool :: (MonadIO m) => Pool Connection -> PGT.DBT IO a -> m a withPool pool action = liftIO $ withResource pool (\conn -> PGT.runDBTSerializable action conn) #else withPool :: (MonadBaseControl IO m) => Pool Connection -> PGT.DBT m a -> m a withPool pool action = withResource pool (\conn -> PGT.runDBTSerializable action conn) #endif | Query wrapper that returns a ' Vector ' of results @since 0.0.1.0 @since 0.0.1.0 -} query :: (ToRow params, FromRow result, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m (Vector result) query queryNature q params = do logQueryFormat queryNature q params V.fromList <$> PGT.query q params | Query wrapper that returns a ' Vector ' of results and does not take an argument @since 0.0.1.0 @since 0.0.1.0 -} query_ :: (FromRow result, MonadIO m) => QueryNature -> Query -> PGT.DBT m (Vector result) query_ queryNature q = do logQueryFormat queryNature q () V.fromList <$> PGT.query_ q | Query wrapper that returns one result . @since 0.0.1.0 @since 0.0.1.0 -} queryOne :: (ToRow params, FromRow result, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m (Maybe result) queryOne queryNature q params = do logQueryFormat queryNature q params listToMaybe <$> PGT.query q params | Query wrapper that returns one result and does not take an argument @since 0.0.2.0 @since 0.0.2.0 -} queryOne_ :: (FromRow result, MonadIO m) => QueryNature -> Query -> PGT.DBT m (Maybe result) queryOne_ queryNature q = do logQueryFormat queryNature q () listToMaybe <$> PGT.query_ q | Query wrapper for SQL statements which do not return . @since 0.0.1.0 @since 0.0.1.0 -} execute :: (ToRow params, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m Int64 execute queryNature q params = do logQueryFormat queryNature q params PGT.execute q params executeMany :: (ToRow params, MonadIO m) => QueryNature -> Query -> [params] -> PGT.DBT m Int64 executeMany queryNature q params = do logQueryFormatMany queryNature q params PGT.executeMany q params #ifndef PROD displayColoured :: (MonadIO m) => ByteString -> ByteString -> PGT.DBT m () displayColoured colour text = liftIO $ BS.hPutStrLn stdout (formatWith [colour] text) #endif #ifdef PROD logQueryFormat :: (Monad m) => QueryNature -> Query -> params -> PGT.DBT m () logQueryFormat _ _ _ = pure () #else logQueryFormat :: (ToRow params, MonadIO m) => QueryNature -> Query -> params -> PGT.DBT m () logQueryFormat queryNature q params = do msg <- PGT.formatQuery q params case queryNature of Select -> displayColoured cyan msg Update -> displayColoured yellow msg Insert -> displayColoured yellow msg Delete -> displayColoured red msg #endif #ifdef PROD logQueryFormatMany :: (Monad m) => QueryNature -> Query -> [params] -> PGT.DBT m () logQueryFormatMany _ _ _ = pure () #else logQueryFormatMany :: (ToRow params, MonadIO m) => QueryNature -> Query -> [params] -> PGT.DBT m () logQueryFormatMany queryNature q params = do msg <- formatMany q params case queryNature of Select -> displayColoured cyan msg Update -> displayColoured yellow msg Insert -> displayColoured yellow msg Delete -> displayColoured red msg formatMany :: (ToRow q, MonadIO m) => Query -> [q] -> PGT.DBT m ByteString formatMany q xs = PGT.getConnection >>= \conn -> liftIO $ Simple.formatMany conn q xs #endif | This sum type is given to the ' query ' , ' queryOne ' and ' execute ' functions to help with logging . @since 0.0.1.0 with logging. @since 0.0.1.0 -} data QueryNature = Select | Insert | Update | Delete deriving (Eq, Show)
26a96368bcbd6aa92bec64e6dd0a041f41288ba9f9df7ac31bf5639dfa6e1757
tree-sitter/haskell-tree-sitter
Test.hs
module Main (main) where import Control.Monad import System.Exit (exitFailure) import System.IO (BufferMode (..), hSetBuffering, stderr, stdout) import qualified TreeSitter.Example import qualified TreeSitter.Strings.Example main :: IO () main = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering results <- sequence [ TreeSitter.Example.tests , TreeSitter.Strings.Example.tests ] unless (and results) exitFailure
null
https://raw.githubusercontent.com/tree-sitter/haskell-tree-sitter/8a5a2b12a3c36a8ca7e117fff04023f1595e04e7/tree-sitter/test/Test.hs
haskell
module Main (main) where import Control.Monad import System.Exit (exitFailure) import System.IO (BufferMode (..), hSetBuffering, stderr, stdout) import qualified TreeSitter.Example import qualified TreeSitter.Strings.Example main :: IO () main = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering results <- sequence [ TreeSitter.Example.tests , TreeSitter.Strings.Example.tests ] unless (and results) exitFailure
892051f41a095d4939daf321cca03d89fd1092bd55e5de667a5101a98bc20097
jhidding/chez-glfw
GL_VERSION_2_1.scm
(library (glfw gl GL_VERSION_2_1) (export glAccum glActiveTexture glAlphaFunc glAreTexturesResident glArrayElement glAttachShader glBegin glBeginQuery glBindAttribLocation glBindBuffer glBindTexture glBitmap glBlendColor glBlendEquation glBlendEquationSeparate glBlendFunc glBlendFuncSeparate glBufferData glBufferSubData glCallList glCallLists glClear glClearAccum glClearColor glClearDepth glClearIndex glClearStencil glClientActiveTexture glClipPlane glColor3b glColor3bv glColor3d glColor3dv glColor3f glColor3fv glColor3i glColor3iv glColor3s glColor3sv glColor3ub glColor3ubv glColor3ui glColor3uiv glColor3us glColor3usv glColor4b glColor4bv glColor4d glColor4dv glColor4f glColor4fv glColor4i glColor4iv glColor4s glColor4sv glColor4ub glColor4ubv glColor4ui glColor4uiv glColor4us glColor4usv glColorMask glColorMaterial glColorPointer glCompileShader glCompressedTexImage1D glCompressedTexImage2D glCompressedTexImage3D glCompressedTexSubImage1D glCompressedTexSubImage2D glCompressedTexSubImage3D glCopyPixels glCopyTexImage1D glCopyTexImage2D glCopyTexSubImage1D glCopyTexSubImage2D glCopyTexSubImage3D glCreateProgram glCreateShader glCullFace glDeleteBuffers glDeleteLists glDeleteProgram glDeleteQueries glDeleteShader glDeleteTextures glDepthFunc glDepthMask glDepthRange glDetachShader glDisable glDisableClientState glDisableVertexAttribArray glDrawArrays glDrawBuffer glDrawBuffers glDrawElements glDrawPixels glDrawRangeElements glEdgeFlag glEdgeFlagPointer glEdgeFlagv glEnable glEnableClientState glEnableVertexAttribArray glEnd glEndList glEndQuery glEvalCoord1d glEvalCoord1dv glEvalCoord1f glEvalCoord1fv glEvalCoord2d glEvalCoord2dv glEvalCoord2f glEvalCoord2fv glEvalMesh1 glEvalMesh2 glEvalPoint1 glEvalPoint2 glFeedbackBuffer glFinish glFlush glFogCoordPointer glFogCoordd glFogCoorddv glFogCoordf glFogCoordfv glFogf glFogfv glFogi glFogiv glFrontFace glFrustum glGenBuffers glGenLists glGenQueries glGenTextures glGetActiveAttrib glGetActiveUniform glGetAttachedShaders glGetAttribLocation glGetBooleanv glGetBufferParameteriv glGetBufferPointerv glGetBufferSubData glGetClipPlane glGetCompressedTexImage glGetDoublev glGetError glGetFloatv glGetIntegerv glGetLightfv glGetLightiv glGetMapdv glGetMapfv glGetMapiv glGetMaterialfv glGetMaterialiv glGetPixelMapfv glGetPixelMapuiv glGetPixelMapusv glGetPointerv glGetPolygonStipple glGetProgramInfoLog glGetProgramiv glGetQueryObjectiv glGetQueryObjectuiv glGetQueryiv glGetShaderInfoLog glGetShaderSource glGetShaderiv glGetString glGetTexEnvfv glGetTexEnviv glGetTexGendv glGetTexGenfv glGetTexGeniv glGetTexImage glGetTexLevelParameterfv glGetTexLevelParameteriv glGetTexParameterfv glGetTexParameteriv glGetUniformLocation glGetUniformfv glGetUniformiv glGetVertexAttribPointerv glGetVertexAttribdv glGetVertexAttribfv glGetVertexAttribiv glHint glIndexMask glIndexPointer glIndexd glIndexdv glIndexf glIndexfv glIndexi glIndexiv glIndexs glIndexsv glIndexub glIndexubv glInitNames glInterleavedArrays glIsBuffer glIsEnabled glIsList glIsProgram glIsQuery glIsShader glIsTexture glLightModelf glLightModelfv glLightModeli glLightModeliv glLightf glLightfv glLighti glLightiv glLineStipple glLineWidth glLinkProgram glListBase glLoadIdentity glLoadMatrixd glLoadMatrixf glLoadName glLoadTransposeMatrixd glLoadTransposeMatrixf glLogicOp glMap1d glMap1f glMap2d glMap2f glMapBuffer glMapGrid1d glMapGrid1f glMapGrid2d glMapGrid2f glMaterialf glMaterialfv glMateriali glMaterialiv glMatrixMode glMultMatrixd glMultMatrixf glMultTransposeMatrixd glMultTransposeMatrixf glMultiDrawArrays glMultiDrawElements glMultiTexCoord1d glMultiTexCoord1dv glMultiTexCoord1f glMultiTexCoord1fv glMultiTexCoord1i glMultiTexCoord1iv glMultiTexCoord1s glMultiTexCoord1sv glMultiTexCoord2d glMultiTexCoord2dv glMultiTexCoord2f glMultiTexCoord2fv glMultiTexCoord2i glMultiTexCoord2iv glMultiTexCoord2s glMultiTexCoord2sv glMultiTexCoord3d glMultiTexCoord3dv glMultiTexCoord3f glMultiTexCoord3fv glMultiTexCoord3i glMultiTexCoord3iv glMultiTexCoord3s glMultiTexCoord3sv glMultiTexCoord4d glMultiTexCoord4dv glMultiTexCoord4f glMultiTexCoord4fv glMultiTexCoord4i glMultiTexCoord4iv glMultiTexCoord4s glMultiTexCoord4sv glNewList glNormal3b glNormal3bv glNormal3d glNormal3dv glNormal3f glNormal3fv glNormal3i glNormal3iv glNormal3s glNormal3sv glNormalPointer glOrtho glPassThrough glPixelMapfv glPixelMapuiv glPixelMapusv glPixelStoref glPixelStorei glPixelTransferf glPixelTransferi glPixelZoom glPointParameterf glPointParameterfv glPointParameteri glPointParameteriv glPointSize glPolygonMode glPolygonOffset glPolygonStipple glPopAttrib glPopClientAttrib glPopMatrix glPopName glPrioritizeTextures glPushAttrib glPushClientAttrib glPushMatrix glPushName glRasterPos2d glRasterPos2dv glRasterPos2f glRasterPos2fv glRasterPos2i glRasterPos2iv glRasterPos2s glRasterPos2sv glRasterPos3d glRasterPos3dv glRasterPos3f glRasterPos3fv glRasterPos3i glRasterPos3iv glRasterPos3s glRasterPos3sv glRasterPos4d glRasterPos4dv glRasterPos4f glRasterPos4fv glRasterPos4i glRasterPos4iv glRasterPos4s glRasterPos4sv glReadBuffer glReadPixels glRectd glRectdv glRectf glRectfv glRecti glRectiv glRects glRectsv glRenderMode glRotated glRotatef glSampleCoverage glScaled glScalef glScissor glSecondaryColor3b glSecondaryColor3bv glSecondaryColor3d glSecondaryColor3dv glSecondaryColor3f glSecondaryColor3fv glSecondaryColor3i glSecondaryColor3iv glSecondaryColor3s glSecondaryColor3sv glSecondaryColor3ub glSecondaryColor3ubv glSecondaryColor3ui glSecondaryColor3uiv glSecondaryColor3us glSecondaryColor3usv glSecondaryColorPointer glSelectBuffer glShadeModel glShaderSource glStencilFunc glStencilFuncSeparate glStencilMask glStencilMaskSeparate glStencilOp glStencilOpSeparate glTexCoord1d glTexCoord1dv glTexCoord1f glTexCoord1fv glTexCoord1i glTexCoord1iv glTexCoord1s glTexCoord1sv glTexCoord2d glTexCoord2dv glTexCoord2f glTexCoord2fv glTexCoord2i glTexCoord2iv glTexCoord2s glTexCoord2sv glTexCoord3d glTexCoord3dv glTexCoord3f glTexCoord3fv glTexCoord3i glTexCoord3iv glTexCoord3s glTexCoord3sv glTexCoord4d glTexCoord4dv glTexCoord4f glTexCoord4fv glTexCoord4i glTexCoord4iv glTexCoord4s glTexCoord4sv glTexCoordPointer glTexEnvf glTexEnvfv glTexEnvi glTexEnviv glTexGend glTexGendv glTexGenf glTexGenfv glTexGeni glTexGeniv glTexImage1D glTexImage2D glTexImage3D glTexParameterf glTexParameterfv glTexParameteri glTexParameteriv glTexSubImage1D glTexSubImage2D glTexSubImage3D glTranslated glTranslatef glUniform1f glUniform1fv glUniform1i glUniform1iv glUniform2f glUniform2fv glUniform2i glUniform2iv glUniform3f glUniform3fv glUniform3i glUniform3iv glUniform4f glUniform4fv glUniform4i glUniform4iv glUniformMatrix2fv glUniformMatrix2x3fv glUniformMatrix2x4fv glUniformMatrix3fv glUniformMatrix3x2fv glUniformMatrix3x4fv glUniformMatrix4fv glUniformMatrix4x2fv glUniformMatrix4x3fv glUnmapBuffer glUseProgram glValidateProgram glVertex2d glVertex2dv glVertex2f glVertex2fv glVertex2i glVertex2iv glVertex2s glVertex2sv glVertex3d glVertex3dv glVertex3f glVertex3fv glVertex3i glVertex3iv glVertex3s glVertex3sv glVertex4d glVertex4dv glVertex4f glVertex4fv glVertex4i glVertex4iv glVertex4s glVertex4sv glVertexAttrib1d glVertexAttrib1dv glVertexAttrib1f glVertexAttrib1fv glVertexAttrib1s glVertexAttrib1sv glVertexAttrib2d glVertexAttrib2dv glVertexAttrib2f glVertexAttrib2fv glVertexAttrib2s glVertexAttrib2sv glVertexAttrib3d glVertexAttrib3dv glVertexAttrib3f glVertexAttrib3fv glVertexAttrib3s glVertexAttrib3sv glVertexAttrib4Nbv glVertexAttrib4Niv glVertexAttrib4Nsv glVertexAttrib4Nub glVertexAttrib4Nubv glVertexAttrib4Nuiv glVertexAttrib4Nusv glVertexAttrib4bv glVertexAttrib4d glVertexAttrib4dv glVertexAttrib4f glVertexAttrib4fv glVertexAttrib4iv glVertexAttrib4s glVertexAttrib4sv glVertexAttrib4ubv glVertexAttrib4uiv glVertexAttrib4usv glVertexAttribPointer glVertexPointer glViewport glWindowPos2d glWindowPos2dv glWindowPos2f glWindowPos2fv glWindowPos2i glWindowPos2iv glWindowPos2s glWindowPos2sv glWindowPos3d glWindowPos3dv glWindowPos3f glWindowPos3fv glWindowPos3i glWindowPos3iv glWindowPos3s glWindowPos3sv GL_2D GL_2_BYTES GL_3D GL_3D_COLOR GL_3D_COLOR_TEXTURE GL_3_BYTES GL_4D_COLOR_TEXTURE GL_4_BYTES GL_ACCUM GL_ACCUM_ALPHA_BITS GL_ACCUM_BLUE_BITS GL_ACCUM_BUFFER_BIT GL_ACCUM_CLEAR_VALUE GL_ACCUM_GREEN_BITS GL_ACCUM_RED_BITS GL_ACTIVE_ATTRIBUTES GL_ACTIVE_ATTRIBUTE_MAX_LENGTH GL_ACTIVE_TEXTURE GL_ACTIVE_UNIFORMS GL_ACTIVE_UNIFORM_MAX_LENGTH GL_ADD GL_ADD_SIGNED GL_ALIASED_LINE_WIDTH_RANGE GL_ALIASED_POINT_SIZE_RANGE GL_ALL_ATTRIB_BITS GL_ALPHA GL_ALPHA12 GL_ALPHA16 GL_ALPHA4 GL_ALPHA8 GL_ALPHA_BIAS GL_ALPHA_BITS GL_ALPHA_SCALE GL_ALPHA_TEST GL_ALPHA_TEST_FUNC GL_ALPHA_TEST_REF GL_ALWAYS GL_AMBIENT GL_AMBIENT_AND_DIFFUSE GL_AND GL_AND_INVERTED GL_AND_REVERSE GL_ARRAY_BUFFER GL_ARRAY_BUFFER_BINDING GL_ATTACHED_SHADERS GL_ATTRIB_STACK_DEPTH GL_AUTO_NORMAL GL_AUX0 GL_AUX1 GL_AUX2 GL_AUX3 GL_AUX_BUFFERS GL_BACK GL_BACK_LEFT GL_BACK_RIGHT GL_BGR GL_BGRA GL_BITMAP GL_BITMAP_TOKEN GL_BLEND GL_BLEND_DST GL_BLEND_DST_ALPHA GL_BLEND_DST_RGB GL_BLEND_EQUATION_ALPHA GL_BLEND_EQUATION_RGB GL_BLEND_SRC GL_BLEND_SRC_ALPHA GL_BLEND_SRC_RGB GL_BLUE GL_BLUE_BIAS GL_BLUE_BITS GL_BLUE_SCALE GL_BOOL GL_BOOL_VEC2 GL_BOOL_VEC3 GL_BOOL_VEC4 GL_BUFFER_ACCESS GL_BUFFER_MAPPED GL_BUFFER_MAP_POINTER GL_BUFFER_SIZE GL_BUFFER_USAGE GL_BYTE GL_C3F_V3F GL_C4F_N3F_V3F GL_C4UB_V2F GL_C4UB_V3F GL_CCW GL_CLAMP GL_CLAMP_TO_BORDER GL_CLAMP_TO_EDGE GL_CLEAR GL_CLIENT_ACTIVE_TEXTURE GL_CLIENT_ALL_ATTRIB_BITS GL_CLIENT_ATTRIB_STACK_DEPTH GL_CLIENT_PIXEL_STORE_BIT GL_CLIENT_VERTEX_ARRAY_BIT GL_CLIP_PLANE0 GL_CLIP_PLANE1 GL_CLIP_PLANE2 GL_CLIP_PLANE3 GL_CLIP_PLANE4 GL_CLIP_PLANE5 GL_COEFF GL_COLOR GL_COLOR_ARRAY GL_COLOR_ARRAY_BUFFER_BINDING GL_COLOR_ARRAY_POINTER GL_COLOR_ARRAY_SIZE GL_COLOR_ARRAY_STRIDE GL_COLOR_ARRAY_TYPE GL_COLOR_BUFFER_BIT GL_COLOR_CLEAR_VALUE GL_COLOR_INDEX GL_COLOR_INDEXES GL_COLOR_LOGIC_OP GL_COLOR_MATERIAL GL_COLOR_MATERIAL_FACE GL_COLOR_MATERIAL_PARAMETER GL_COLOR_SUM GL_COLOR_WRITEMASK GL_COMBINE GL_COMBINE_ALPHA GL_COMBINE_RGB GL_COMPARE_R_TO_TEXTURE GL_COMPILE GL_COMPILE_AND_EXECUTE GL_COMPILE_STATUS GL_COMPRESSED_ALPHA GL_COMPRESSED_INTENSITY GL_COMPRESSED_LUMINANCE GL_COMPRESSED_LUMINANCE_ALPHA GL_COMPRESSED_RGB GL_COMPRESSED_RGBA GL_COMPRESSED_SLUMINANCE GL_COMPRESSED_SLUMINANCE_ALPHA GL_COMPRESSED_SRGB GL_COMPRESSED_SRGB_ALPHA GL_COMPRESSED_TEXTURE_FORMATS GL_CONSTANT GL_CONSTANT_ALPHA GL_CONSTANT_ATTENUATION GL_CONSTANT_COLOR GL_COORD_REPLACE GL_COPY GL_COPY_INVERTED GL_COPY_PIXEL_TOKEN GL_CULL_FACE GL_CULL_FACE_MODE GL_CURRENT_BIT GL_CURRENT_COLOR GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE GL_CURRENT_INDEX GL_CURRENT_NORMAL GL_CURRENT_PROGRAM GL_CURRENT_QUERY GL_CURRENT_RASTER_COLOR GL_CURRENT_RASTER_DISTANCE GL_CURRENT_RASTER_INDEX GL_CURRENT_RASTER_POSITION GL_CURRENT_RASTER_POSITION_VALID GL_CURRENT_RASTER_SECONDARY_COLOR GL_CURRENT_RASTER_TEXTURE_COORDS GL_CURRENT_SECONDARY_COLOR GL_CURRENT_TEXTURE_COORDS GL_CURRENT_VERTEX_ATTRIB GL_CW GL_DECAL GL_DECR GL_DECR_WRAP GL_DELETE_STATUS GL_DEPTH GL_DEPTH_BIAS GL_DEPTH_BITS GL_DEPTH_BUFFER_BIT GL_DEPTH_CLEAR_VALUE GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT16 GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT32 GL_DEPTH_FUNC GL_DEPTH_RANGE GL_DEPTH_SCALE GL_DEPTH_TEST GL_DEPTH_TEXTURE_MODE GL_DEPTH_WRITEMASK GL_DIFFUSE GL_DITHER GL_DOMAIN GL_DONT_CARE GL_DOT3_RGB GL_DOT3_RGBA GL_DOUBLE GL_DOUBLEBUFFER GL_DRAW_BUFFER GL_DRAW_BUFFER0 GL_DRAW_BUFFER1 GL_DRAW_BUFFER10 GL_DRAW_BUFFER11 GL_DRAW_BUFFER12 GL_DRAW_BUFFER13 GL_DRAW_BUFFER14 GL_DRAW_BUFFER15 GL_DRAW_BUFFER2 GL_DRAW_BUFFER3 GL_DRAW_BUFFER4 GL_DRAW_BUFFER5 GL_DRAW_BUFFER6 GL_DRAW_BUFFER7 GL_DRAW_BUFFER8 GL_DRAW_BUFFER9 GL_DRAW_PIXEL_TOKEN GL_DST_ALPHA GL_DST_COLOR GL_DYNAMIC_COPY GL_DYNAMIC_DRAW GL_DYNAMIC_READ GL_EDGE_FLAG GL_EDGE_FLAG_ARRAY GL_EDGE_FLAG_ARRAY_BUFFER_BINDING GL_EDGE_FLAG_ARRAY_POINTER GL_EDGE_FLAG_ARRAY_STRIDE GL_ELEMENT_ARRAY_BUFFER GL_ELEMENT_ARRAY_BUFFER_BINDING GL_EMISSION GL_ENABLE_BIT GL_EQUAL GL_EQUIV GL_EVAL_BIT GL_EXP GL_EXP2 GL_EXTENSIONS GL_EYE_LINEAR GL_EYE_PLANE GL_FALSE GL_FASTEST GL_FEEDBACK GL_FEEDBACK_BUFFER_POINTER GL_FEEDBACK_BUFFER_SIZE GL_FEEDBACK_BUFFER_TYPE GL_FILL GL_FLAT GL_FLOAT GL_FLOAT_MAT2 GL_FLOAT_MAT2x3 GL_FLOAT_MAT2x4 GL_FLOAT_MAT3 GL_FLOAT_MAT3x2 GL_FLOAT_MAT3x4 GL_FLOAT_MAT4 GL_FLOAT_MAT4x2 GL_FLOAT_MAT4x3 GL_FLOAT_VEC2 GL_FLOAT_VEC3 GL_FLOAT_VEC4 GL_FOG GL_FOG_BIT GL_FOG_COLOR GL_FOG_COORD GL_FOG_COORDINATE GL_FOG_COORDINATE_ARRAY GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_TYPE GL_FOG_COORDINATE_SOURCE GL_FOG_COORD_ARRAY GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORD_SRC GL_FOG_DENSITY GL_FOG_END GL_FOG_HINT GL_FOG_INDEX GL_FOG_MODE GL_FOG_START GL_FRAGMENT_DEPTH GL_FRAGMENT_SHADER GL_FRAGMENT_SHADER_DERIVATIVE_HINT GL_FRONT GL_FRONT_AND_BACK GL_FRONT_FACE GL_FRONT_LEFT GL_FRONT_RIGHT GL_FUNC_ADD GL_FUNC_REVERSE_SUBTRACT GL_FUNC_SUBTRACT GL_GENERATE_MIPMAP GL_GENERATE_MIPMAP_HINT GL_GEQUAL GL_GREATER GL_GREEN GL_GREEN_BIAS GL_GREEN_BITS GL_GREEN_SCALE GL_HINT_BIT GL_INCR GL_INCR_WRAP GL_INDEX_ARRAY GL_INDEX_ARRAY_BUFFER_BINDING GL_INDEX_ARRAY_POINTER GL_INDEX_ARRAY_STRIDE GL_INDEX_ARRAY_TYPE GL_INDEX_BITS GL_INDEX_CLEAR_VALUE GL_INDEX_LOGIC_OP GL_INDEX_MODE GL_INDEX_OFFSET GL_INDEX_SHIFT GL_INDEX_WRITEMASK GL_INFO_LOG_LENGTH GL_INT GL_INTENSITY GL_INTENSITY12 GL_INTENSITY16 GL_INTENSITY4 GL_INTENSITY8 GL_INTERPOLATE GL_INT_VEC2 GL_INT_VEC3 GL_INT_VEC4 GL_INVALID_ENUM GL_INVALID_OPERATION GL_INVALID_VALUE GL_INVERT GL_KEEP GL_LEFT GL_LEQUAL GL_LESS GL_LIGHT0 GL_LIGHT1 GL_LIGHT2 GL_LIGHT3 GL_LIGHT4 GL_LIGHT5 GL_LIGHT6 GL_LIGHT7 GL_LIGHTING GL_LIGHTING_BIT GL_LIGHT_MODEL_AMBIENT GL_LIGHT_MODEL_COLOR_CONTROL GL_LIGHT_MODEL_LOCAL_VIEWER GL_LIGHT_MODEL_TWO_SIDE GL_LINE GL_LINEAR GL_LINEAR_ATTENUATION GL_LINEAR_MIPMAP_LINEAR GL_LINEAR_MIPMAP_NEAREST GL_LINES GL_LINE_BIT GL_LINE_LOOP GL_LINE_RESET_TOKEN GL_LINE_SMOOTH GL_LINE_SMOOTH_HINT GL_LINE_STIPPLE GL_LINE_STIPPLE_PATTERN GL_LINE_STIPPLE_REPEAT GL_LINE_STRIP GL_LINE_TOKEN GL_LINE_WIDTH GL_LINE_WIDTH_GRANULARITY GL_LINE_WIDTH_RANGE GL_LINK_STATUS GL_LIST_BASE GL_LIST_BIT GL_LIST_INDEX GL_LIST_MODE GL_LOAD GL_LOGIC_OP GL_LOGIC_OP_MODE GL_LOWER_LEFT GL_LUMINANCE GL_LUMINANCE12 GL_LUMINANCE12_ALPHA12 GL_LUMINANCE12_ALPHA4 GL_LUMINANCE16 GL_LUMINANCE16_ALPHA16 GL_LUMINANCE4 GL_LUMINANCE4_ALPHA4 GL_LUMINANCE6_ALPHA2 GL_LUMINANCE8 GL_LUMINANCE8_ALPHA8 GL_LUMINANCE_ALPHA GL_MAP1_COLOR_4 GL_MAP1_GRID_DOMAIN GL_MAP1_GRID_SEGMENTS GL_MAP1_INDEX GL_MAP1_NORMAL GL_MAP1_TEXTURE_COORD_1 GL_MAP1_TEXTURE_COORD_2 GL_MAP1_TEXTURE_COORD_3 GL_MAP1_TEXTURE_COORD_4 GL_MAP1_VERTEX_3 GL_MAP1_VERTEX_4 GL_MAP2_COLOR_4 GL_MAP2_GRID_DOMAIN GL_MAP2_GRID_SEGMENTS GL_MAP2_INDEX GL_MAP2_NORMAL GL_MAP2_TEXTURE_COORD_1 GL_MAP2_TEXTURE_COORD_2 GL_MAP2_TEXTURE_COORD_3 GL_MAP2_TEXTURE_COORD_4 GL_MAP2_VERTEX_3 GL_MAP2_VERTEX_4 GL_MAP_COLOR GL_MAP_STENCIL GL_MATRIX_MODE GL_MAX GL_MAX_3D_TEXTURE_SIZE GL_MAX_ATTRIB_STACK_DEPTH GL_MAX_CLIENT_ATTRIB_STACK_DEPTH GL_MAX_CLIP_PLANES GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS GL_MAX_CUBE_MAP_TEXTURE_SIZE GL_MAX_DRAW_BUFFERS GL_MAX_ELEMENTS_INDICES GL_MAX_ELEMENTS_VERTICES GL_MAX_EVAL_ORDER GL_MAX_FRAGMENT_UNIFORM_COMPONENTS GL_MAX_LIGHTS GL_MAX_LIST_NESTING GL_MAX_MODELVIEW_STACK_DEPTH GL_MAX_NAME_STACK_DEPTH GL_MAX_PIXEL_MAP_TABLE GL_MAX_PROJECTION_STACK_DEPTH GL_MAX_TEXTURE_COORDS GL_MAX_TEXTURE_IMAGE_UNITS GL_MAX_TEXTURE_LOD_BIAS GL_MAX_TEXTURE_SIZE GL_MAX_TEXTURE_STACK_DEPTH GL_MAX_TEXTURE_UNITS GL_MAX_VARYING_FLOATS GL_MAX_VERTEX_ATTRIBS GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS GL_MAX_VERTEX_UNIFORM_COMPONENTS GL_MAX_VIEWPORT_DIMS GL_MIN GL_MIRRORED_REPEAT GL_MODELVIEW GL_MODELVIEW_MATRIX GL_MODELVIEW_STACK_DEPTH GL_MODULATE GL_MULT GL_MULTISAMPLE GL_MULTISAMPLE_BIT GL_N3F_V3F GL_NAME_STACK_DEPTH GL_NAND GL_NEAREST GL_NEAREST_MIPMAP_LINEAR GL_NEAREST_MIPMAP_NEAREST GL_NEVER GL_NICEST GL_NONE GL_NOOP GL_NOR GL_NORMALIZE GL_NORMAL_ARRAY GL_NORMAL_ARRAY_BUFFER_BINDING GL_NORMAL_ARRAY_POINTER GL_NORMAL_ARRAY_STRIDE GL_NORMAL_ARRAY_TYPE GL_NORMAL_MAP GL_NOTEQUAL GL_NO_ERROR GL_NUM_COMPRESSED_TEXTURE_FORMATS GL_OBJECT_LINEAR GL_OBJECT_PLANE GL_ONE GL_ONE_MINUS_CONSTANT_ALPHA GL_ONE_MINUS_CONSTANT_COLOR GL_ONE_MINUS_DST_ALPHA GL_ONE_MINUS_DST_COLOR GL_ONE_MINUS_SRC_ALPHA GL_ONE_MINUS_SRC_COLOR GL_OPERAND0_ALPHA GL_OPERAND0_RGB GL_OPERAND1_ALPHA GL_OPERAND1_RGB GL_OPERAND2_ALPHA GL_OPERAND2_RGB GL_OR GL_ORDER GL_OR_INVERTED GL_OR_REVERSE GL_OUT_OF_MEMORY GL_PACK_ALIGNMENT GL_PACK_IMAGE_HEIGHT GL_PACK_LSB_FIRST GL_PACK_ROW_LENGTH GL_PACK_SKIP_IMAGES GL_PACK_SKIP_PIXELS GL_PACK_SKIP_ROWS GL_PACK_SWAP_BYTES GL_PASS_THROUGH_TOKEN GL_PERSPECTIVE_CORRECTION_HINT GL_PIXEL_MAP_A_TO_A GL_PIXEL_MAP_A_TO_A_SIZE GL_PIXEL_MAP_B_TO_B GL_PIXEL_MAP_B_TO_B_SIZE GL_PIXEL_MAP_G_TO_G GL_PIXEL_MAP_G_TO_G_SIZE GL_PIXEL_MAP_I_TO_A GL_PIXEL_MAP_I_TO_A_SIZE GL_PIXEL_MAP_I_TO_B GL_PIXEL_MAP_I_TO_B_SIZE GL_PIXEL_MAP_I_TO_G GL_PIXEL_MAP_I_TO_G_SIZE GL_PIXEL_MAP_I_TO_I GL_PIXEL_MAP_I_TO_I_SIZE GL_PIXEL_MAP_I_TO_R GL_PIXEL_MAP_I_TO_R_SIZE GL_PIXEL_MAP_R_TO_R GL_PIXEL_MAP_R_TO_R_SIZE GL_PIXEL_MAP_S_TO_S GL_PIXEL_MAP_S_TO_S_SIZE GL_PIXEL_MODE_BIT GL_PIXEL_PACK_BUFFER GL_PIXEL_PACK_BUFFER_BINDING GL_PIXEL_UNPACK_BUFFER GL_PIXEL_UNPACK_BUFFER_BINDING GL_POINT GL_POINTS GL_POINT_BIT GL_POINT_DISTANCE_ATTENUATION GL_POINT_FADE_THRESHOLD_SIZE GL_POINT_SIZE GL_POINT_SIZE_GRANULARITY GL_POINT_SIZE_MAX GL_POINT_SIZE_MIN GL_POINT_SIZE_RANGE GL_POINT_SMOOTH GL_POINT_SMOOTH_HINT GL_POINT_SPRITE GL_POINT_SPRITE_COORD_ORIGIN GL_POINT_TOKEN GL_POLYGON GL_POLYGON_BIT GL_POLYGON_MODE GL_POLYGON_OFFSET_FACTOR GL_POLYGON_OFFSET_FILL GL_POLYGON_OFFSET_LINE GL_POLYGON_OFFSET_POINT GL_POLYGON_OFFSET_UNITS GL_POLYGON_SMOOTH GL_POLYGON_SMOOTH_HINT GL_POLYGON_STIPPLE GL_POLYGON_STIPPLE_BIT GL_POLYGON_TOKEN GL_POSITION GL_PREVIOUS GL_PRIMARY_COLOR GL_PROJECTION GL_PROJECTION_MATRIX GL_PROJECTION_STACK_DEPTH GL_PROXY_TEXTURE_1D GL_PROXY_TEXTURE_2D GL_PROXY_TEXTURE_3D GL_PROXY_TEXTURE_CUBE_MAP GL_Q GL_QUADRATIC_ATTENUATION GL_QUADS GL_QUAD_STRIP GL_QUERY_COUNTER_BITS GL_QUERY_RESULT GL_QUERY_RESULT_AVAILABLE GL_R GL_R3_G3_B2 GL_READ_BUFFER GL_READ_ONLY GL_READ_WRITE GL_RED GL_RED_BIAS GL_RED_BITS GL_RED_SCALE GL_REFLECTION_MAP GL_RENDER GL_RENDERER GL_RENDER_MODE GL_REPEAT GL_REPLACE GL_RESCALE_NORMAL GL_RETURN GL_RGB GL_RGB10 GL_RGB10_A2 GL_RGB12 GL_RGB16 GL_RGB4 GL_RGB5 GL_RGB5_A1 GL_RGB8 GL_RGBA GL_RGBA12 GL_RGBA16 GL_RGBA2 GL_RGBA4 GL_RGBA8 GL_RGBA_MODE GL_RGB_SCALE GL_RIGHT GL_S GL_SAMPLER_1D GL_SAMPLER_1D_SHADOW GL_SAMPLER_2D GL_SAMPLER_2D_SHADOW GL_SAMPLER_3D GL_SAMPLER_CUBE GL_SAMPLES GL_SAMPLES_PASSED GL_SAMPLE_ALPHA_TO_COVERAGE GL_SAMPLE_ALPHA_TO_ONE GL_SAMPLE_BUFFERS GL_SAMPLE_COVERAGE GL_SAMPLE_COVERAGE_INVERT GL_SAMPLE_COVERAGE_VALUE GL_SCISSOR_BIT GL_SCISSOR_BOX GL_SCISSOR_TEST GL_SECONDARY_COLOR_ARRAY GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING GL_SECONDARY_COLOR_ARRAY_POINTER GL_SECONDARY_COLOR_ARRAY_SIZE GL_SECONDARY_COLOR_ARRAY_STRIDE GL_SECONDARY_COLOR_ARRAY_TYPE GL_SELECT GL_SELECTION_BUFFER_POINTER GL_SELECTION_BUFFER_SIZE GL_SEPARATE_SPECULAR_COLOR GL_SET GL_SHADER_SOURCE_LENGTH GL_SHADER_TYPE GL_SHADE_MODEL GL_SHADING_LANGUAGE_VERSION GL_SHININESS GL_SHORT GL_SINGLE_COLOR GL_SLUMINANCE GL_SLUMINANCE8 GL_SLUMINANCE8_ALPHA8 GL_SLUMINANCE_ALPHA GL_SMOOTH GL_SMOOTH_LINE_WIDTH_GRANULARITY GL_SMOOTH_LINE_WIDTH_RANGE GL_SMOOTH_POINT_SIZE_GRANULARITY GL_SMOOTH_POINT_SIZE_RANGE GL_SOURCE0_ALPHA GL_SOURCE0_RGB GL_SOURCE1_ALPHA GL_SOURCE1_RGB GL_SOURCE2_ALPHA GL_SOURCE2_RGB GL_SPECULAR GL_SPHERE_MAP GL_SPOT_CUTOFF GL_SPOT_DIRECTION GL_SPOT_EXPONENT GL_SRC0_ALPHA GL_SRC0_RGB GL_SRC1_ALPHA GL_SRC1_RGB GL_SRC2_ALPHA GL_SRC2_RGB GL_SRC_ALPHA GL_SRC_ALPHA_SATURATE GL_SRC_COLOR GL_SRGB GL_SRGB8 GL_SRGB8_ALPHA8 GL_SRGB_ALPHA GL_STACK_OVERFLOW GL_STACK_UNDERFLOW GL_STATIC_COPY GL_STATIC_DRAW GL_STATIC_READ GL_STENCIL GL_STENCIL_BACK_FAIL GL_STENCIL_BACK_FUNC GL_STENCIL_BACK_PASS_DEPTH_FAIL GL_STENCIL_BACK_PASS_DEPTH_PASS GL_STENCIL_BACK_REF GL_STENCIL_BACK_VALUE_MASK GL_STENCIL_BACK_WRITEMASK GL_STENCIL_BITS GL_STENCIL_BUFFER_BIT GL_STENCIL_CLEAR_VALUE GL_STENCIL_FAIL GL_STENCIL_FUNC GL_STENCIL_INDEX GL_STENCIL_PASS_DEPTH_FAIL GL_STENCIL_PASS_DEPTH_PASS GL_STENCIL_REF GL_STENCIL_TEST GL_STENCIL_VALUE_MASK GL_STENCIL_WRITEMASK GL_STEREO GL_STREAM_COPY GL_STREAM_DRAW GL_STREAM_READ GL_SUBPIXEL_BITS GL_SUBTRACT GL_T GL_T2F_C3F_V3F GL_T2F_C4F_N3F_V3F GL_T2F_C4UB_V3F GL_T2F_N3F_V3F GL_T2F_V3F GL_T4F_C4F_N3F_V4F GL_T4F_V4F GL_TEXTURE GL_TEXTURE0 GL_TEXTURE1 GL_TEXTURE10 GL_TEXTURE11 GL_TEXTURE12 GL_TEXTURE13 GL_TEXTURE14 GL_TEXTURE15 GL_TEXTURE16 GL_TEXTURE17 GL_TEXTURE18 GL_TEXTURE19 GL_TEXTURE2 GL_TEXTURE20 GL_TEXTURE21 GL_TEXTURE22 GL_TEXTURE23 GL_TEXTURE24 GL_TEXTURE25 GL_TEXTURE26 GL_TEXTURE27 GL_TEXTURE28 GL_TEXTURE29 GL_TEXTURE3 GL_TEXTURE30 GL_TEXTURE31 GL_TEXTURE4 GL_TEXTURE5 GL_TEXTURE6 GL_TEXTURE7 GL_TEXTURE8 GL_TEXTURE9 GL_TEXTURE_1D GL_TEXTURE_2D GL_TEXTURE_3D GL_TEXTURE_ALPHA_SIZE GL_TEXTURE_BASE_LEVEL GL_TEXTURE_BINDING_1D GL_TEXTURE_BINDING_2D GL_TEXTURE_BINDING_3D GL_TEXTURE_BINDING_CUBE_MAP GL_TEXTURE_BIT GL_TEXTURE_BLUE_SIZE GL_TEXTURE_BORDER GL_TEXTURE_BORDER_COLOR GL_TEXTURE_COMPARE_FUNC GL_TEXTURE_COMPARE_MODE GL_TEXTURE_COMPONENTS GL_TEXTURE_COMPRESSED GL_TEXTURE_COMPRESSED_IMAGE_SIZE GL_TEXTURE_COMPRESSION_HINT GL_TEXTURE_COORD_ARRAY GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING GL_TEXTURE_COORD_ARRAY_POINTER GL_TEXTURE_COORD_ARRAY_SIZE GL_TEXTURE_COORD_ARRAY_STRIDE GL_TEXTURE_COORD_ARRAY_TYPE GL_TEXTURE_CUBE_MAP GL_TEXTURE_CUBE_MAP_NEGATIVE_X GL_TEXTURE_CUBE_MAP_NEGATIVE_Y GL_TEXTURE_CUBE_MAP_NEGATIVE_Z GL_TEXTURE_CUBE_MAP_POSITIVE_X GL_TEXTURE_CUBE_MAP_POSITIVE_Y GL_TEXTURE_CUBE_MAP_POSITIVE_Z GL_TEXTURE_DEPTH GL_TEXTURE_DEPTH_SIZE GL_TEXTURE_ENV GL_TEXTURE_ENV_COLOR GL_TEXTURE_ENV_MODE GL_TEXTURE_FILTER_CONTROL GL_TEXTURE_GEN_MODE GL_TEXTURE_GEN_Q GL_TEXTURE_GEN_R GL_TEXTURE_GEN_S GL_TEXTURE_GEN_T GL_TEXTURE_GREEN_SIZE GL_TEXTURE_HEIGHT GL_TEXTURE_INTENSITY_SIZE GL_TEXTURE_INTERNAL_FORMAT GL_TEXTURE_LOD_BIAS GL_TEXTURE_LUMINANCE_SIZE GL_TEXTURE_MAG_FILTER GL_TEXTURE_MATRIX GL_TEXTURE_MAX_LEVEL GL_TEXTURE_MAX_LOD GL_TEXTURE_MIN_FILTER GL_TEXTURE_MIN_LOD GL_TEXTURE_PRIORITY GL_TEXTURE_RED_SIZE GL_TEXTURE_RESIDENT GL_TEXTURE_STACK_DEPTH GL_TEXTURE_WIDTH GL_TEXTURE_WRAP_R GL_TEXTURE_WRAP_S GL_TEXTURE_WRAP_T GL_TRANSFORM_BIT GL_TRANSPOSE_COLOR_MATRIX GL_TRANSPOSE_MODELVIEW_MATRIX GL_TRANSPOSE_PROJECTION_MATRIX GL_TRANSPOSE_TEXTURE_MATRIX GL_TRIANGLES GL_TRIANGLE_FAN GL_TRIANGLE_STRIP GL_TRUE GL_UNPACK_ALIGNMENT GL_UNPACK_IMAGE_HEIGHT GL_UNPACK_LSB_FIRST GL_UNPACK_ROW_LENGTH GL_UNPACK_SKIP_IMAGES GL_UNPACK_SKIP_PIXELS GL_UNPACK_SKIP_ROWS GL_UNPACK_SWAP_BYTES GL_UNSIGNED_BYTE GL_UNSIGNED_BYTE_2_3_3_REV GL_UNSIGNED_BYTE_3_3_2 GL_UNSIGNED_INT GL_UNSIGNED_INT_10_10_10_2 GL_UNSIGNED_INT_2_10_10_10_REV GL_UNSIGNED_INT_8_8_8_8 GL_UNSIGNED_INT_8_8_8_8_REV GL_UNSIGNED_SHORT GL_UNSIGNED_SHORT_1_5_5_5_REV GL_UNSIGNED_SHORT_4_4_4_4 GL_UNSIGNED_SHORT_4_4_4_4_REV GL_UNSIGNED_SHORT_5_5_5_1 GL_UNSIGNED_SHORT_5_6_5 GL_UNSIGNED_SHORT_5_6_5_REV GL_UPPER_LEFT GL_V2F GL_V3F GL_VALIDATE_STATUS GL_VENDOR GL_VERSION GL_VERTEX_ARRAY GL_VERTEX_ARRAY_BUFFER_BINDING GL_VERTEX_ARRAY_POINTER GL_VERTEX_ARRAY_SIZE GL_VERTEX_ARRAY_STRIDE GL_VERTEX_ARRAY_TYPE GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING GL_VERTEX_ATTRIB_ARRAY_ENABLED GL_VERTEX_ATTRIB_ARRAY_NORMALIZED GL_VERTEX_ATTRIB_ARRAY_POINTER GL_VERTEX_ATTRIB_ARRAY_SIZE GL_VERTEX_ATTRIB_ARRAY_STRIDE GL_VERTEX_ATTRIB_ARRAY_TYPE GL_VERTEX_PROGRAM_POINT_SIZE GL_VERTEX_PROGRAM_TWO_SIDE GL_VERTEX_SHADER GL_VIEWPORT GL_VIEWPORT_BIT GL_WEIGHT_ARRAY_BUFFER_BINDING GL_WRITE_ONLY GL_XOR GL_ZERO GL_ZOOM_X GL_ZOOM_Y ) (import (rnrs base(6)) (only (chezscheme) foreign-procedure load-shared-object)) (define libGL (load-shared-object "libGL.so.1")) (define glAccum (foreign-procedure "glAccum" (unsigned-int float) void)) (define glActiveTexture (foreign-procedure "glActiveTexture" (unsigned-int) void)) (define glAlphaFunc (foreign-procedure "glAlphaFunc" (unsigned-int float) void)) (define glAreTexturesResident (foreign-procedure "glAreTexturesResident" (int uptr string) unsigned-8)) (define glArrayElement (foreign-procedure "glArrayElement" (int) void)) (define glAttachShader (foreign-procedure "glAttachShader" (unsigned-int unsigned-int) void)) (define glBegin (foreign-procedure "glBegin" (unsigned-int) void)) (define glBeginQuery (foreign-procedure "glBeginQuery" (unsigned-int unsigned-int) void)) (define glBindAttribLocation (foreign-procedure "glBindAttribLocation" (unsigned-int unsigned-int string) void)) (define glBindBuffer (foreign-procedure "glBindBuffer" (unsigned-int unsigned-int) void)) (define glBindTexture (foreign-procedure "glBindTexture" (unsigned-int unsigned-int) void)) (define glBitmap (foreign-procedure "glBitmap" (int int float float float float string) void)) (define glBlendColor (foreign-procedure "glBlendColor" (float float float float) void)) (define glBlendEquation (foreign-procedure "glBlendEquation" (unsigned-int) void)) (define glBlendEquationSeparate (foreign-procedure "glBlendEquationSeparate" (unsigned-int unsigned-int) void)) (define glBlendFunc (foreign-procedure "glBlendFunc" (unsigned-int unsigned-int) void)) (define glBlendFuncSeparate (foreign-procedure "glBlendFuncSeparate" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glBufferData (foreign-procedure "glBufferData" (unsigned-int ptrdiff_t uptr unsigned-int) void)) (define glBufferSubData (foreign-procedure "glBufferSubData" (unsigned-int ptrdiff_t ptrdiff_t uptr) void)) (define glCallList (foreign-procedure "glCallList" (unsigned-int) void)) (define glCallLists (foreign-procedure "glCallLists" (int unsigned-int uptr) void)) (define glClear (foreign-procedure "glClear" (unsigned-int) void)) (define glClearAccum (foreign-procedure "glClearAccum" (float float float float) void)) (define glClearColor (foreign-procedure "glClearColor" (float float float float) void)) (define glClearDepth (foreign-procedure "glClearDepth" (double) void)) (define glClearIndex (foreign-procedure "glClearIndex" (float) void)) (define glClearStencil (foreign-procedure "glClearStencil" (int) void)) (define glClientActiveTexture (foreign-procedure "glClientActiveTexture" (unsigned-int) void)) (define glClipPlane (foreign-procedure "glClipPlane" (unsigned-int uptr) void)) (define glColor3b (foreign-procedure "glColor3b" (integer-8 integer-8 integer-8) void)) (define glColor3bv (foreign-procedure "glColor3bv" (string) void)) (define glColor3d (foreign-procedure "glColor3d" (double double double) void)) (define glColor3dv (foreign-procedure "glColor3dv" (uptr) void)) (define glColor3f (foreign-procedure "glColor3f" (float float float) void)) (define glColor3fv (foreign-procedure "glColor3fv" (uptr) void)) (define glColor3i (foreign-procedure "glColor3i" (int int int) void)) (define glColor3iv (foreign-procedure "glColor3iv" (uptr) void)) (define glColor3s (foreign-procedure "glColor3s" (short short short) void)) (define glColor3sv (foreign-procedure "glColor3sv" (uptr) void)) (define glColor3ub (foreign-procedure "glColor3ub" (unsigned-8 unsigned-8 unsigned-8) void)) (define glColor3ubv (foreign-procedure "glColor3ubv" (string) void)) (define glColor3ui (foreign-procedure "glColor3ui" (unsigned-int unsigned-int unsigned-int) void)) (define glColor3uiv (foreign-procedure "glColor3uiv" (uptr) void)) (define glColor3us (foreign-procedure "glColor3us" (unsigned-short unsigned-short unsigned-short) void)) (define glColor3usv (foreign-procedure "glColor3usv" (uptr) void)) (define glColor4b (foreign-procedure "glColor4b" (integer-8 integer-8 integer-8 integer-8) void)) (define glColor4bv (foreign-procedure "glColor4bv" (string) void)) (define glColor4d (foreign-procedure "glColor4d" (double double double double) void)) (define glColor4dv (foreign-procedure "glColor4dv" (uptr) void)) (define glColor4f (foreign-procedure "glColor4f" (float float float float) void)) (define glColor4fv (foreign-procedure "glColor4fv" (uptr) void)) (define glColor4i (foreign-procedure "glColor4i" (int int int int) void)) (define glColor4iv (foreign-procedure "glColor4iv" (uptr) void)) (define glColor4s (foreign-procedure "glColor4s" (short short short short) void)) (define glColor4sv (foreign-procedure "glColor4sv" (uptr) void)) (define glColor4ub (foreign-procedure "glColor4ub" (unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glColor4ubv (foreign-procedure "glColor4ubv" (string) void)) (define glColor4ui (foreign-procedure "glColor4ui" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glColor4uiv (foreign-procedure "glColor4uiv" (uptr) void)) (define glColor4us (foreign-procedure "glColor4us" (unsigned-short unsigned-short unsigned-short unsigned-short) void)) (define glColor4usv (foreign-procedure "glColor4usv" (uptr) void)) (define glColorMask (foreign-procedure "glColorMask" (unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glColorMaterial (foreign-procedure "glColorMaterial" (unsigned-int unsigned-int) void)) (define glColorPointer (foreign-procedure "glColorPointer" (int unsigned-int int uptr) void)) (define glCompileShader (foreign-procedure "glCompileShader" (unsigned-int) void)) (define glCompressedTexImage1D (foreign-procedure "glCompressedTexImage1D" (unsigned-int int unsigned-int int int int uptr) void)) (define glCompressedTexImage2D (foreign-procedure "glCompressedTexImage2D" (unsigned-int int unsigned-int int int int int uptr) void)) (define glCompressedTexImage3D (foreign-procedure "glCompressedTexImage3D" (unsigned-int int unsigned-int int int int int int uptr) void)) (define glCompressedTexSubImage1D (foreign-procedure "glCompressedTexSubImage1D" (unsigned-int int int int unsigned-int int uptr) void)) (define glCompressedTexSubImage2D (foreign-procedure "glCompressedTexSubImage2D" (unsigned-int int int int int int unsigned-int int uptr) void)) (define glCompressedTexSubImage3D (foreign-procedure "glCompressedTexSubImage3D" (unsigned-int int int int int int int int unsigned-int int uptr) void)) (define glCopyPixels (foreign-procedure "glCopyPixels" (int int int int unsigned-int) void)) (define glCopyTexImage1D (foreign-procedure "glCopyTexImage1D" (unsigned-int int unsigned-int int int int int) void)) (define glCopyTexImage2D (foreign-procedure "glCopyTexImage2D" (unsigned-int int unsigned-int int int int int int) void)) (define glCopyTexSubImage1D (foreign-procedure "glCopyTexSubImage1D" (unsigned-int int int int int int) void)) (define glCopyTexSubImage2D (foreign-procedure "glCopyTexSubImage2D" (unsigned-int int int int int int int int) void)) (define glCopyTexSubImage3D (foreign-procedure "glCopyTexSubImage3D" (unsigned-int int int int int int int int int) void)) (define glCreateProgram (foreign-procedure "glCreateProgram" () unsigned-int)) (define glCreateShader (foreign-procedure "glCreateShader" (unsigned-int) unsigned-int)) (define glCullFace (foreign-procedure "glCullFace" (unsigned-int) void)) (define glDeleteBuffers (foreign-procedure "glDeleteBuffers" (int uptr) void)) (define glDeleteLists (foreign-procedure "glDeleteLists" (unsigned-int int) void)) (define glDeleteProgram (foreign-procedure "glDeleteProgram" (unsigned-int) void)) (define glDeleteQueries (foreign-procedure "glDeleteQueries" (int uptr) void)) (define glDeleteShader (foreign-procedure "glDeleteShader" (unsigned-int) void)) (define glDeleteTextures (foreign-procedure "glDeleteTextures" (int uptr) void)) (define glDepthFunc (foreign-procedure "glDepthFunc" (unsigned-int) void)) (define glDepthMask (foreign-procedure "glDepthMask" (unsigned-8) void)) (define glDepthRange (foreign-procedure "glDepthRange" (double double) void)) (define glDetachShader (foreign-procedure "glDetachShader" (unsigned-int unsigned-int) void)) (define glDisable (foreign-procedure "glDisable" (unsigned-int) void)) (define glDisableClientState (foreign-procedure "glDisableClientState" (unsigned-int) void)) (define glDisableVertexAttribArray (foreign-procedure "glDisableVertexAttribArray" (unsigned-int) void)) (define glDrawArrays (foreign-procedure "glDrawArrays" (unsigned-int int int) void)) (define glDrawBuffer (foreign-procedure "glDrawBuffer" (unsigned-int) void)) (define glDrawBuffers (foreign-procedure "glDrawBuffers" (int uptr) void)) (define glDrawElements (foreign-procedure "glDrawElements" (unsigned-int int unsigned-int uptr) void)) (define glDrawPixels (foreign-procedure "glDrawPixels" (int int unsigned-int unsigned-int uptr) void)) (define glDrawRangeElements (foreign-procedure "glDrawRangeElements" (unsigned-int unsigned-int unsigned-int int unsigned-int uptr) void)) (define glEdgeFlag (foreign-procedure "glEdgeFlag" (unsigned-8) void)) (define glEdgeFlagPointer (foreign-procedure "glEdgeFlagPointer" (int uptr) void)) (define glEdgeFlagv (foreign-procedure "glEdgeFlagv" (string) void)) (define glEnable (foreign-procedure "glEnable" (unsigned-int) void)) (define glEnableClientState (foreign-procedure "glEnableClientState" (unsigned-int) void)) (define glEnableVertexAttribArray (foreign-procedure "glEnableVertexAttribArray" (unsigned-int) void)) (define glEnd (foreign-procedure "glEnd" () void)) (define glEndList (foreign-procedure "glEndList" () void)) (define glEndQuery (foreign-procedure "glEndQuery" (unsigned-int) void)) (define glEvalCoord1d (foreign-procedure "glEvalCoord1d" (double) void)) (define glEvalCoord1dv (foreign-procedure "glEvalCoord1dv" (uptr) void)) (define glEvalCoord1f (foreign-procedure "glEvalCoord1f" (float) void)) (define glEvalCoord1fv (foreign-procedure "glEvalCoord1fv" (uptr) void)) (define glEvalCoord2d (foreign-procedure "glEvalCoord2d" (double double) void)) (define glEvalCoord2dv (foreign-procedure "glEvalCoord2dv" (uptr) void)) (define glEvalCoord2f (foreign-procedure "glEvalCoord2f" (float float) void)) (define glEvalCoord2fv (foreign-procedure "glEvalCoord2fv" (uptr) void)) (define glEvalMesh1 (foreign-procedure "glEvalMesh1" (unsigned-int int int) void)) (define glEvalMesh2 (foreign-procedure "glEvalMesh2" (unsigned-int int int int int) void)) (define glEvalPoint1 (foreign-procedure "glEvalPoint1" (int) void)) (define glEvalPoint2 (foreign-procedure "glEvalPoint2" (int int) void)) (define glFeedbackBuffer (foreign-procedure "glFeedbackBuffer" (int unsigned-int uptr) void)) (define glFinish (foreign-procedure "glFinish" () void)) (define glFlush (foreign-procedure "glFlush" () void)) (define glFogCoordPointer (foreign-procedure "glFogCoordPointer" (unsigned-int int uptr) void)) (define glFogCoordd (foreign-procedure "glFogCoordd" (double) void)) (define glFogCoorddv (foreign-procedure "glFogCoorddv" (uptr) void)) (define glFogCoordf (foreign-procedure "glFogCoordf" (float) void)) (define glFogCoordfv (foreign-procedure "glFogCoordfv" (uptr) void)) (define glFogf (foreign-procedure "glFogf" (unsigned-int float) void)) (define glFogfv (foreign-procedure "glFogfv" (unsigned-int uptr) void)) (define glFogi (foreign-procedure "glFogi" (unsigned-int int) void)) (define glFogiv (foreign-procedure "glFogiv" (unsigned-int uptr) void)) (define glFrontFace (foreign-procedure "glFrontFace" (unsigned-int) void)) (define glFrustum (foreign-procedure "glFrustum" (double double double double double double) void)) (define glGenBuffers (foreign-procedure "glGenBuffers" (int uptr) void)) (define glGenLists (foreign-procedure "glGenLists" (int) unsigned-int)) (define glGenQueries (foreign-procedure "glGenQueries" (int uptr) void)) (define glGenTextures (foreign-procedure "glGenTextures" (int uptr) void)) (define glGetActiveAttrib (foreign-procedure "glGetActiveAttrib" (unsigned-int unsigned-int int uptr uptr uptr string) void)) (define glGetActiveUniform (foreign-procedure "glGetActiveUniform" (unsigned-int unsigned-int int uptr uptr uptr string) void)) (define glGetAttachedShaders (foreign-procedure "glGetAttachedShaders" (unsigned-int int uptr uptr) void)) (define glGetAttribLocation (foreign-procedure "glGetAttribLocation" (unsigned-int string) int)) (define glGetBooleanv (foreign-procedure "glGetBooleanv" (unsigned-int string) void)) (define glGetBufferParameteriv (foreign-procedure "glGetBufferParameteriv" (unsigned-int unsigned-int uptr) void)) (define glGetBufferPointerv (foreign-procedure "glGetBufferPointerv" (unsigned-int unsigned-int uptr) void)) (define glGetBufferSubData (foreign-procedure "glGetBufferSubData" (unsigned-int ptrdiff_t ptrdiff_t uptr) void)) (define glGetClipPlane (foreign-procedure "glGetClipPlane" (unsigned-int uptr) void)) (define glGetCompressedTexImage (foreign-procedure "glGetCompressedTexImage" (unsigned-int int uptr) void)) (define glGetDoublev (foreign-procedure "glGetDoublev" (unsigned-int uptr) void)) (define glGetError (foreign-procedure "glGetError" () unsigned-int)) (define glGetFloatv (foreign-procedure "glGetFloatv" (unsigned-int uptr) void)) (define glGetIntegerv (foreign-procedure "glGetIntegerv" (unsigned-int uptr) void)) (define glGetLightfv (foreign-procedure "glGetLightfv" (unsigned-int unsigned-int uptr) void)) (define glGetLightiv (foreign-procedure "glGetLightiv" (unsigned-int unsigned-int uptr) void)) (define glGetMapdv (foreign-procedure "glGetMapdv" (unsigned-int unsigned-int uptr) void)) (define glGetMapfv (foreign-procedure "glGetMapfv" (unsigned-int unsigned-int uptr) void)) (define glGetMapiv (foreign-procedure "glGetMapiv" (unsigned-int unsigned-int uptr) void)) (define glGetMaterialfv (foreign-procedure "glGetMaterialfv" (unsigned-int unsigned-int uptr) void)) (define glGetMaterialiv (foreign-procedure "glGetMaterialiv" (unsigned-int unsigned-int uptr) void)) (define glGetPixelMapfv (foreign-procedure "glGetPixelMapfv" (unsigned-int uptr) void)) (define glGetPixelMapuiv (foreign-procedure "glGetPixelMapuiv" (unsigned-int uptr) void)) (define glGetPixelMapusv (foreign-procedure "glGetPixelMapusv" (unsigned-int uptr) void)) (define glGetPointerv (foreign-procedure "glGetPointerv" (unsigned-int uptr) void)) (define glGetPolygonStipple (foreign-procedure "glGetPolygonStipple" (string) void)) (define glGetProgramInfoLog (foreign-procedure "glGetProgramInfoLog" (unsigned-int int uptr string) void)) (define glGetProgramiv (foreign-procedure "glGetProgramiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryObjectiv (foreign-procedure "glGetQueryObjectiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryObjectuiv (foreign-procedure "glGetQueryObjectuiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryiv (foreign-procedure "glGetQueryiv" (unsigned-int unsigned-int uptr) void)) (define glGetShaderInfoLog (foreign-procedure "glGetShaderInfoLog" (unsigned-int int uptr string) void)) (define glGetShaderSource (foreign-procedure "glGetShaderSource" (unsigned-int int uptr string) void)) (define glGetShaderiv (foreign-procedure "glGetShaderiv" (unsigned-int unsigned-int uptr) void)) (define glGetString (foreign-procedure "glGetString" (unsigned-int) string)) (define glGetTexEnvfv (foreign-procedure "glGetTexEnvfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexEnviv (foreign-procedure "glGetTexEnviv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGendv (foreign-procedure "glGetTexGendv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGenfv (foreign-procedure "glGetTexGenfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGeniv (foreign-procedure "glGetTexGeniv" (unsigned-int unsigned-int uptr) void)) (define glGetTexImage (foreign-procedure "glGetTexImage" (unsigned-int int unsigned-int unsigned-int uptr) void)) (define glGetTexLevelParameterfv (foreign-procedure "glGetTexLevelParameterfv" (unsigned-int int unsigned-int uptr) void)) (define glGetTexLevelParameteriv (foreign-procedure "glGetTexLevelParameteriv" (unsigned-int int unsigned-int uptr) void)) (define glGetTexParameterfv (foreign-procedure "glGetTexParameterfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexParameteriv (foreign-procedure "glGetTexParameteriv" (unsigned-int unsigned-int uptr) void)) (define glGetUniformLocation (foreign-procedure "glGetUniformLocation" (unsigned-int string) int)) (define glGetUniformfv (foreign-procedure "glGetUniformfv" (unsigned-int int uptr) void)) (define glGetUniformiv (foreign-procedure "glGetUniformiv" (unsigned-int int uptr) void)) (define glGetVertexAttribPointerv (foreign-procedure "glGetVertexAttribPointerv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribdv (foreign-procedure "glGetVertexAttribdv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribfv (foreign-procedure "glGetVertexAttribfv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribiv (foreign-procedure "glGetVertexAttribiv" (unsigned-int unsigned-int uptr) void)) (define glHint (foreign-procedure "glHint" (unsigned-int unsigned-int) void)) (define glIndexMask (foreign-procedure "glIndexMask" (unsigned-int) void)) (define glIndexPointer (foreign-procedure "glIndexPointer" (unsigned-int int uptr) void)) (define glIndexd (foreign-procedure "glIndexd" (double) void)) (define glIndexdv (foreign-procedure "glIndexdv" (uptr) void)) (define glIndexf (foreign-procedure "glIndexf" (float) void)) (define glIndexfv (foreign-procedure "glIndexfv" (uptr) void)) (define glIndexi (foreign-procedure "glIndexi" (int) void)) (define glIndexiv (foreign-procedure "glIndexiv" (uptr) void)) (define glIndexs (foreign-procedure "glIndexs" (short) void)) (define glIndexsv (foreign-procedure "glIndexsv" (uptr) void)) (define glIndexub (foreign-procedure "glIndexub" (unsigned-8) void)) (define glIndexubv (foreign-procedure "glIndexubv" (string) void)) (define glInitNames (foreign-procedure "glInitNames" () void)) (define glInterleavedArrays (foreign-procedure "glInterleavedArrays" (unsigned-int int uptr) void)) (define glIsBuffer (foreign-procedure "glIsBuffer" (unsigned-int) unsigned-8)) (define glIsEnabled (foreign-procedure "glIsEnabled" (unsigned-int) unsigned-8)) (define glIsList (foreign-procedure "glIsList" (unsigned-int) unsigned-8)) (define glIsProgram (foreign-procedure "glIsProgram" (unsigned-int) unsigned-8)) (define glIsQuery (foreign-procedure "glIsQuery" (unsigned-int) unsigned-8)) (define glIsShader (foreign-procedure "glIsShader" (unsigned-int) unsigned-8)) (define glIsTexture (foreign-procedure "glIsTexture" (unsigned-int) unsigned-8)) (define glLightModelf (foreign-procedure "glLightModelf" (unsigned-int float) void)) (define glLightModelfv (foreign-procedure "glLightModelfv" (unsigned-int uptr) void)) (define glLightModeli (foreign-procedure "glLightModeli" (unsigned-int int) void)) (define glLightModeliv (foreign-procedure "glLightModeliv" (unsigned-int uptr) void)) (define glLightf (foreign-procedure "glLightf" (unsigned-int unsigned-int float) void)) (define glLightfv (foreign-procedure "glLightfv" (unsigned-int unsigned-int uptr) void)) (define glLighti (foreign-procedure "glLighti" (unsigned-int unsigned-int int) void)) (define glLightiv (foreign-procedure "glLightiv" (unsigned-int unsigned-int uptr) void)) (define glLineStipple (foreign-procedure "glLineStipple" (int unsigned-short) void)) (define glLineWidth (foreign-procedure "glLineWidth" (float) void)) (define glLinkProgram (foreign-procedure "glLinkProgram" (unsigned-int) void)) (define glListBase (foreign-procedure "glListBase" (unsigned-int) void)) (define glLoadIdentity (foreign-procedure "glLoadIdentity" () void)) (define glLoadMatrixd (foreign-procedure "glLoadMatrixd" (uptr) void)) (define glLoadMatrixf (foreign-procedure "glLoadMatrixf" (uptr) void)) (define glLoadName (foreign-procedure "glLoadName" (unsigned-int) void)) (define glLoadTransposeMatrixd (foreign-procedure "glLoadTransposeMatrixd" (uptr) void)) (define glLoadTransposeMatrixf (foreign-procedure "glLoadTransposeMatrixf" (uptr) void)) (define glLogicOp (foreign-procedure "glLogicOp" (unsigned-int) void)) (define glMap1d (foreign-procedure "glMap1d" (unsigned-int double double int int uptr) void)) (define glMap1f (foreign-procedure "glMap1f" (unsigned-int float float int int uptr) void)) (define glMap2d (foreign-procedure "glMap2d" (unsigned-int double double int int double double int int uptr) void)) (define glMap2f (foreign-procedure "glMap2f" (unsigned-int float float int int float float int int uptr) void)) (define glMapBuffer (foreign-procedure "glMapBuffer" (unsigned-int unsigned-int) uptr)) (define glMapGrid1d (foreign-procedure "glMapGrid1d" (int double double) void)) (define glMapGrid1f (foreign-procedure "glMapGrid1f" (int float float) void)) (define glMapGrid2d (foreign-procedure "glMapGrid2d" (int double double int double double) void)) (define glMapGrid2f (foreign-procedure "glMapGrid2f" (int float float int float float) void)) (define glMaterialf (foreign-procedure "glMaterialf" (unsigned-int unsigned-int float) void)) (define glMaterialfv (foreign-procedure "glMaterialfv" (unsigned-int unsigned-int uptr) void)) (define glMateriali (foreign-procedure "glMateriali" (unsigned-int unsigned-int int) void)) (define glMaterialiv (foreign-procedure "glMaterialiv" (unsigned-int unsigned-int uptr) void)) (define glMatrixMode (foreign-procedure "glMatrixMode" (unsigned-int) void)) (define glMultMatrixd (foreign-procedure "glMultMatrixd" (uptr) void)) (define glMultMatrixf (foreign-procedure "glMultMatrixf" (uptr) void)) (define glMultTransposeMatrixd (foreign-procedure "glMultTransposeMatrixd" (uptr) void)) (define glMultTransposeMatrixf (foreign-procedure "glMultTransposeMatrixf" (uptr) void)) (define glMultiDrawArrays (foreign-procedure "glMultiDrawArrays" (unsigned-int uptr uptr int) void)) (define glMultiDrawElements (foreign-procedure "glMultiDrawElements" (unsigned-int uptr unsigned-int uptr int) void)) (define glMultiTexCoord1d (foreign-procedure "glMultiTexCoord1d" (unsigned-int double) void)) (define glMultiTexCoord1dv (foreign-procedure "glMultiTexCoord1dv" (unsigned-int uptr) void)) (define glMultiTexCoord1f (foreign-procedure "glMultiTexCoord1f" (unsigned-int float) void)) (define glMultiTexCoord1fv (foreign-procedure "glMultiTexCoord1fv" (unsigned-int uptr) void)) (define glMultiTexCoord1i (foreign-procedure "glMultiTexCoord1i" (unsigned-int int) void)) (define glMultiTexCoord1iv (foreign-procedure "glMultiTexCoord1iv" (unsigned-int uptr) void)) (define glMultiTexCoord1s (foreign-procedure "glMultiTexCoord1s" (unsigned-int short) void)) (define glMultiTexCoord1sv (foreign-procedure "glMultiTexCoord1sv" (unsigned-int uptr) void)) (define glMultiTexCoord2d (foreign-procedure "glMultiTexCoord2d" (unsigned-int double double) void)) (define glMultiTexCoord2dv (foreign-procedure "glMultiTexCoord2dv" (unsigned-int uptr) void)) (define glMultiTexCoord2f (foreign-procedure "glMultiTexCoord2f" (unsigned-int float float) void)) (define glMultiTexCoord2fv (foreign-procedure "glMultiTexCoord2fv" (unsigned-int uptr) void)) (define glMultiTexCoord2i (foreign-procedure "glMultiTexCoord2i" (unsigned-int int int) void)) (define glMultiTexCoord2iv (foreign-procedure "glMultiTexCoord2iv" (unsigned-int uptr) void)) (define glMultiTexCoord2s (foreign-procedure "glMultiTexCoord2s" (unsigned-int short short) void)) (define glMultiTexCoord2sv (foreign-procedure "glMultiTexCoord2sv" (unsigned-int uptr) void)) (define glMultiTexCoord3d (foreign-procedure "glMultiTexCoord3d" (unsigned-int double double double) void)) (define glMultiTexCoord3dv (foreign-procedure "glMultiTexCoord3dv" (unsigned-int uptr) void)) (define glMultiTexCoord3f (foreign-procedure "glMultiTexCoord3f" (unsigned-int float float float) void)) (define glMultiTexCoord3fv (foreign-procedure "glMultiTexCoord3fv" (unsigned-int uptr) void)) (define glMultiTexCoord3i (foreign-procedure "glMultiTexCoord3i" (unsigned-int int int int) void)) (define glMultiTexCoord3iv (foreign-procedure "glMultiTexCoord3iv" (unsigned-int uptr) void)) (define glMultiTexCoord3s (foreign-procedure "glMultiTexCoord3s" (unsigned-int short short short) void)) (define glMultiTexCoord3sv (foreign-procedure "glMultiTexCoord3sv" (unsigned-int uptr) void)) (define glMultiTexCoord4d (foreign-procedure "glMultiTexCoord4d" (unsigned-int double double double double) void)) (define glMultiTexCoord4dv (foreign-procedure "glMultiTexCoord4dv" (unsigned-int uptr) void)) (define glMultiTexCoord4f (foreign-procedure "glMultiTexCoord4f" (unsigned-int float float float float) void)) (define glMultiTexCoord4fv (foreign-procedure "glMultiTexCoord4fv" (unsigned-int uptr) void)) (define glMultiTexCoord4i (foreign-procedure "glMultiTexCoord4i" (unsigned-int int int int int) void)) (define glMultiTexCoord4iv (foreign-procedure "glMultiTexCoord4iv" (unsigned-int uptr) void)) (define glMultiTexCoord4s (foreign-procedure "glMultiTexCoord4s" (unsigned-int short short short short) void)) (define glMultiTexCoord4sv (foreign-procedure "glMultiTexCoord4sv" (unsigned-int uptr) void)) (define glNewList (foreign-procedure "glNewList" (unsigned-int unsigned-int) void)) (define glNormal3b (foreign-procedure "glNormal3b" (integer-8 integer-8 integer-8) void)) (define glNormal3bv (foreign-procedure "glNormal3bv" (string) void)) (define glNormal3d (foreign-procedure "glNormal3d" (double double double) void)) (define glNormal3dv (foreign-procedure "glNormal3dv" (uptr) void)) (define glNormal3f (foreign-procedure "glNormal3f" (float float float) void)) (define glNormal3fv (foreign-procedure "glNormal3fv" (uptr) void)) (define glNormal3i (foreign-procedure "glNormal3i" (int int int) void)) (define glNormal3iv (foreign-procedure "glNormal3iv" (uptr) void)) (define glNormal3s (foreign-procedure "glNormal3s" (short short short) void)) (define glNormal3sv (foreign-procedure "glNormal3sv" (uptr) void)) (define glNormalPointer (foreign-procedure "glNormalPointer" (unsigned-int int uptr) void)) (define glOrtho (foreign-procedure "glOrtho" (double double double double double double) void)) (define glPassThrough (foreign-procedure "glPassThrough" (float) void)) (define glPixelMapfv (foreign-procedure "glPixelMapfv" (unsigned-int int uptr) void)) (define glPixelMapuiv (foreign-procedure "glPixelMapuiv" (unsigned-int int uptr) void)) (define glPixelMapusv (foreign-procedure "glPixelMapusv" (unsigned-int int uptr) void)) (define glPixelStoref (foreign-procedure "glPixelStoref" (unsigned-int float) void)) (define glPixelStorei (foreign-procedure "glPixelStorei" (unsigned-int int) void)) (define glPixelTransferf (foreign-procedure "glPixelTransferf" (unsigned-int float) void)) (define glPixelTransferi (foreign-procedure "glPixelTransferi" (unsigned-int int) void)) (define glPixelZoom (foreign-procedure "glPixelZoom" (float float) void)) (define glPointParameterf (foreign-procedure "glPointParameterf" (unsigned-int float) void)) (define glPointParameterfv (foreign-procedure "glPointParameterfv" (unsigned-int uptr) void)) (define glPointParameteri (foreign-procedure "glPointParameteri" (unsigned-int int) void)) (define glPointParameteriv (foreign-procedure "glPointParameteriv" (unsigned-int uptr) void)) (define glPointSize (foreign-procedure "glPointSize" (float) void)) (define glPolygonMode (foreign-procedure "glPolygonMode" (unsigned-int unsigned-int) void)) (define glPolygonOffset (foreign-procedure "glPolygonOffset" (float float) void)) (define glPolygonStipple (foreign-procedure "glPolygonStipple" (string) void)) (define glPopAttrib (foreign-procedure "glPopAttrib" () void)) (define glPopClientAttrib (foreign-procedure "glPopClientAttrib" () void)) (define glPopMatrix (foreign-procedure "glPopMatrix" () void)) (define glPopName (foreign-procedure "glPopName" () void)) (define glPrioritizeTextures (foreign-procedure "glPrioritizeTextures" (int uptr uptr) void)) (define glPushAttrib (foreign-procedure "glPushAttrib" (unsigned-int) void)) (define glPushClientAttrib (foreign-procedure "glPushClientAttrib" (unsigned-int) void)) (define glPushMatrix (foreign-procedure "glPushMatrix" () void)) (define glPushName (foreign-procedure "glPushName" (unsigned-int) void)) (define glRasterPos2d (foreign-procedure "glRasterPos2d" (double double) void)) (define glRasterPos2dv (foreign-procedure "glRasterPos2dv" (uptr) void)) (define glRasterPos2f (foreign-procedure "glRasterPos2f" (float float) void)) (define glRasterPos2fv (foreign-procedure "glRasterPos2fv" (uptr) void)) (define glRasterPos2i (foreign-procedure "glRasterPos2i" (int int) void)) (define glRasterPos2iv (foreign-procedure "glRasterPos2iv" (uptr) void)) (define glRasterPos2s (foreign-procedure "glRasterPos2s" (short short) void)) (define glRasterPos2sv (foreign-procedure "glRasterPos2sv" (uptr) void)) (define glRasterPos3d (foreign-procedure "glRasterPos3d" (double double double) void)) (define glRasterPos3dv (foreign-procedure "glRasterPos3dv" (uptr) void)) (define glRasterPos3f (foreign-procedure "glRasterPos3f" (float float float) void)) (define glRasterPos3fv (foreign-procedure "glRasterPos3fv" (uptr) void)) (define glRasterPos3i (foreign-procedure "glRasterPos3i" (int int int) void)) (define glRasterPos3iv (foreign-procedure "glRasterPos3iv" (uptr) void)) (define glRasterPos3s (foreign-procedure "glRasterPos3s" (short short short) void)) (define glRasterPos3sv (foreign-procedure "glRasterPos3sv" (uptr) void)) (define glRasterPos4d (foreign-procedure "glRasterPos4d" (double double double double) void)) (define glRasterPos4dv (foreign-procedure "glRasterPos4dv" (uptr) void)) (define glRasterPos4f (foreign-procedure "glRasterPos4f" (float float float float) void)) (define glRasterPos4fv (foreign-procedure "glRasterPos4fv" (uptr) void)) (define glRasterPos4i (foreign-procedure "glRasterPos4i" (int int int int) void)) (define glRasterPos4iv (foreign-procedure "glRasterPos4iv" (uptr) void)) (define glRasterPos4s (foreign-procedure "glRasterPos4s" (short short short short) void)) (define glRasterPos4sv (foreign-procedure "glRasterPos4sv" (uptr) void)) (define glReadBuffer (foreign-procedure "glReadBuffer" (unsigned-int) void)) (define glReadPixels (foreign-procedure "glReadPixels" (int int int int unsigned-int unsigned-int uptr) void)) (define glRectd (foreign-procedure "glRectd" (double double double double) void)) (define glRectdv (foreign-procedure "glRectdv" (uptr uptr) void)) (define glRectf (foreign-procedure "glRectf" (float float float float) void)) (define glRectfv (foreign-procedure "glRectfv" (uptr uptr) void)) (define glRecti (foreign-procedure "glRecti" (int int int int) void)) (define glRectiv (foreign-procedure "glRectiv" (uptr uptr) void)) (define glRects (foreign-procedure "glRects" (short short short short) void)) (define glRectsv (foreign-procedure "glRectsv" (uptr uptr) void)) (define glRenderMode (foreign-procedure "glRenderMode" (unsigned-int) int)) (define glRotated (foreign-procedure "glRotated" (double double double double) void)) (define glRotatef (foreign-procedure "glRotatef" (float float float float) void)) (define glSampleCoverage (foreign-procedure "glSampleCoverage" (float unsigned-8) void)) (define glScaled (foreign-procedure "glScaled" (double double double) void)) (define glScalef (foreign-procedure "glScalef" (float float float) void)) (define glScissor (foreign-procedure "glScissor" (int int int int) void)) (define glSecondaryColor3b (foreign-procedure "glSecondaryColor3b" (integer-8 integer-8 integer-8) void)) (define glSecondaryColor3bv (foreign-procedure "glSecondaryColor3bv" (string) void)) (define glSecondaryColor3d (foreign-procedure "glSecondaryColor3d" (double double double) void)) (define glSecondaryColor3dv (foreign-procedure "glSecondaryColor3dv" (uptr) void)) (define glSecondaryColor3f (foreign-procedure "glSecondaryColor3f" (float float float) void)) (define glSecondaryColor3fv (foreign-procedure "glSecondaryColor3fv" (uptr) void)) (define glSecondaryColor3i (foreign-procedure "glSecondaryColor3i" (int int int) void)) (define glSecondaryColor3iv (foreign-procedure "glSecondaryColor3iv" (uptr) void)) (define glSecondaryColor3s (foreign-procedure "glSecondaryColor3s" (short short short) void)) (define glSecondaryColor3sv (foreign-procedure "glSecondaryColor3sv" (uptr) void)) (define glSecondaryColor3ub (foreign-procedure "glSecondaryColor3ub" (unsigned-8 unsigned-8 unsigned-8) void)) (define glSecondaryColor3ubv (foreign-procedure "glSecondaryColor3ubv" (string) void)) (define glSecondaryColor3ui (foreign-procedure "glSecondaryColor3ui" (unsigned-int unsigned-int unsigned-int) void)) (define glSecondaryColor3uiv (foreign-procedure "glSecondaryColor3uiv" (uptr) void)) (define glSecondaryColor3us (foreign-procedure "glSecondaryColor3us" (unsigned-short unsigned-short unsigned-short) void)) (define glSecondaryColor3usv (foreign-procedure "glSecondaryColor3usv" (uptr) void)) (define glSecondaryColorPointer (foreign-procedure "glSecondaryColorPointer" (int unsigned-int int uptr) void)) (define glSelectBuffer (foreign-procedure "glSelectBuffer" (int uptr) void)) (define glShadeModel (foreign-procedure "glShadeModel" (unsigned-int) void)) (define glShaderSource (foreign-procedure "glShaderSource" (unsigned-int int uptr uptr) void)) (define glStencilFunc (foreign-procedure "glStencilFunc" (unsigned-int int unsigned-int) void)) (define glStencilFuncSeparate (foreign-procedure "glStencilFuncSeparate" (unsigned-int unsigned-int int unsigned-int) void)) (define glStencilMask (foreign-procedure "glStencilMask" (unsigned-int) void)) (define glStencilMaskSeparate (foreign-procedure "glStencilMaskSeparate" (unsigned-int unsigned-int) void)) (define glStencilOp (foreign-procedure "glStencilOp" (unsigned-int unsigned-int unsigned-int) void)) (define glStencilOpSeparate (foreign-procedure "glStencilOpSeparate" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glTexCoord1d (foreign-procedure "glTexCoord1d" (double) void)) (define glTexCoord1dv (foreign-procedure "glTexCoord1dv" (uptr) void)) (define glTexCoord1f (foreign-procedure "glTexCoord1f" (float) void)) (define glTexCoord1fv (foreign-procedure "glTexCoord1fv" (uptr) void)) (define glTexCoord1i (foreign-procedure "glTexCoord1i" (int) void)) (define glTexCoord1iv (foreign-procedure "glTexCoord1iv" (uptr) void)) (define glTexCoord1s (foreign-procedure "glTexCoord1s" (short) void)) (define glTexCoord1sv (foreign-procedure "glTexCoord1sv" (uptr) void)) (define glTexCoord2d (foreign-procedure "glTexCoord2d" (double double) void)) (define glTexCoord2dv (foreign-procedure "glTexCoord2dv" (uptr) void)) (define glTexCoord2f (foreign-procedure "glTexCoord2f" (float float) void)) (define glTexCoord2fv (foreign-procedure "glTexCoord2fv" (uptr) void)) (define glTexCoord2i (foreign-procedure "glTexCoord2i" (int int) void)) (define glTexCoord2iv (foreign-procedure "glTexCoord2iv" (uptr) void)) (define glTexCoord2s (foreign-procedure "glTexCoord2s" (short short) void)) (define glTexCoord2sv (foreign-procedure "glTexCoord2sv" (uptr) void)) (define glTexCoord3d (foreign-procedure "glTexCoord3d" (double double double) void)) (define glTexCoord3dv (foreign-procedure "glTexCoord3dv" (uptr) void)) (define glTexCoord3f (foreign-procedure "glTexCoord3f" (float float float) void)) (define glTexCoord3fv (foreign-procedure "glTexCoord3fv" (uptr) void)) (define glTexCoord3i (foreign-procedure "glTexCoord3i" (int int int) void)) (define glTexCoord3iv (foreign-procedure "glTexCoord3iv" (uptr) void)) (define glTexCoord3s (foreign-procedure "glTexCoord3s" (short short short) void)) (define glTexCoord3sv (foreign-procedure "glTexCoord3sv" (uptr) void)) (define glTexCoord4d (foreign-procedure "glTexCoord4d" (double double double double) void)) (define glTexCoord4dv (foreign-procedure "glTexCoord4dv" (uptr) void)) (define glTexCoord4f (foreign-procedure "glTexCoord4f" (float float float float) void)) (define glTexCoord4fv (foreign-procedure "glTexCoord4fv" (uptr) void)) (define glTexCoord4i (foreign-procedure "glTexCoord4i" (int int int int) void)) (define glTexCoord4iv (foreign-procedure "glTexCoord4iv" (uptr) void)) (define glTexCoord4s (foreign-procedure "glTexCoord4s" (short short short short) void)) (define glTexCoord4sv (foreign-procedure "glTexCoord4sv" (uptr) void)) (define glTexCoordPointer (foreign-procedure "glTexCoordPointer" (int unsigned-int int uptr) void)) (define glTexEnvf (foreign-procedure "glTexEnvf" (unsigned-int unsigned-int float) void)) (define glTexEnvfv (foreign-procedure "glTexEnvfv" (unsigned-int unsigned-int uptr) void)) (define glTexEnvi (foreign-procedure "glTexEnvi" (unsigned-int unsigned-int int) void)) (define glTexEnviv (foreign-procedure "glTexEnviv" (unsigned-int unsigned-int uptr) void)) (define glTexGend (foreign-procedure "glTexGend" (unsigned-int unsigned-int double) void)) (define glTexGendv (foreign-procedure "glTexGendv" (unsigned-int unsigned-int uptr) void)) (define glTexGenf (foreign-procedure "glTexGenf" (unsigned-int unsigned-int float) void)) (define glTexGenfv (foreign-procedure "glTexGenfv" (unsigned-int unsigned-int uptr) void)) (define glTexGeni (foreign-procedure "glTexGeni" (unsigned-int unsigned-int int) void)) (define glTexGeniv (foreign-procedure "glTexGeniv" (unsigned-int unsigned-int uptr) void)) (define glTexImage1D (foreign-procedure "glTexImage1D" (unsigned-int int int int int unsigned-int unsigned-int uptr) void)) (define glTexImage2D (foreign-procedure "glTexImage2D" (unsigned-int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexImage3D (foreign-procedure "glTexImage3D" (unsigned-int int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexParameterf (foreign-procedure "glTexParameterf" (unsigned-int unsigned-int float) void)) (define glTexParameterfv (foreign-procedure "glTexParameterfv" (unsigned-int unsigned-int uptr) void)) (define glTexParameteri (foreign-procedure "glTexParameteri" (unsigned-int unsigned-int int) void)) (define glTexParameteriv (foreign-procedure "glTexParameteriv" (unsigned-int unsigned-int uptr) void)) (define glTexSubImage1D (foreign-procedure "glTexSubImage1D" (unsigned-int int int int unsigned-int unsigned-int uptr) void)) (define glTexSubImage2D (foreign-procedure "glTexSubImage2D" (unsigned-int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexSubImage3D (foreign-procedure "glTexSubImage3D" (unsigned-int int int int int int int int unsigned-int unsigned-int uptr) void)) (define glTranslated (foreign-procedure "glTranslated" (double double double) void)) (define glTranslatef (foreign-procedure "glTranslatef" (float float float) void)) (define glUniform1f (foreign-procedure "glUniform1f" (int float) void)) (define glUniform1fv (foreign-procedure "glUniform1fv" (int int uptr) void)) (define glUniform1i (foreign-procedure "glUniform1i" (int int) void)) (define glUniform1iv (foreign-procedure "glUniform1iv" (int int uptr) void)) (define glUniform2f (foreign-procedure "glUniform2f" (int float float) void)) (define glUniform2fv (foreign-procedure "glUniform2fv" (int int uptr) void)) (define glUniform2i (foreign-procedure "glUniform2i" (int int int) void)) (define glUniform2iv (foreign-procedure "glUniform2iv" (int int uptr) void)) (define glUniform3f (foreign-procedure "glUniform3f" (int float float float) void)) (define glUniform3fv (foreign-procedure "glUniform3fv" (int int uptr) void)) (define glUniform3i (foreign-procedure "glUniform3i" (int int int int) void)) (define glUniform3iv (foreign-procedure "glUniform3iv" (int int uptr) void)) (define glUniform4f (foreign-procedure "glUniform4f" (int float float float float) void)) (define glUniform4fv (foreign-procedure "glUniform4fv" (int int uptr) void)) (define glUniform4i (foreign-procedure "glUniform4i" (int int int int int) void)) (define glUniform4iv (foreign-procedure "glUniform4iv" (int int uptr) void)) (define glUniformMatrix2fv (foreign-procedure "glUniformMatrix2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix2x3fv (foreign-procedure "glUniformMatrix2x3fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix2x4fv (foreign-procedure "glUniformMatrix2x4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3fv (foreign-procedure "glUniformMatrix3fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3x2fv (foreign-procedure "glUniformMatrix3x2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3x4fv (foreign-procedure "glUniformMatrix3x4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4fv (foreign-procedure "glUniformMatrix4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4x2fv (foreign-procedure "glUniformMatrix4x2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4x3fv (foreign-procedure "glUniformMatrix4x3fv" (int int unsigned-8 uptr) void)) (define glUnmapBuffer (foreign-procedure "glUnmapBuffer" (unsigned-int) unsigned-8)) (define glUseProgram (foreign-procedure "glUseProgram" (unsigned-int) void)) (define glValidateProgram (foreign-procedure "glValidateProgram" (unsigned-int) void)) (define glVertex2d (foreign-procedure "glVertex2d" (double double) void)) (define glVertex2dv (foreign-procedure "glVertex2dv" (uptr) void)) (define glVertex2f (foreign-procedure "glVertex2f" (float float) void)) (define glVertex2fv (foreign-procedure "glVertex2fv" (uptr) void)) (define glVertex2i (foreign-procedure "glVertex2i" (int int) void)) (define glVertex2iv (foreign-procedure "glVertex2iv" (uptr) void)) (define glVertex2s (foreign-procedure "glVertex2s" (short short) void)) (define glVertex2sv (foreign-procedure "glVertex2sv" (uptr) void)) (define glVertex3d (foreign-procedure "glVertex3d" (double double double) void)) (define glVertex3dv (foreign-procedure "glVertex3dv" (uptr) void)) (define glVertex3f (foreign-procedure "glVertex3f" (float float float) void)) (define glVertex3fv (foreign-procedure "glVertex3fv" (uptr) void)) (define glVertex3i (foreign-procedure "glVertex3i" (int int int) void)) (define glVertex3iv (foreign-procedure "glVertex3iv" (uptr) void)) (define glVertex3s (foreign-procedure "glVertex3s" (short short short) void)) (define glVertex3sv (foreign-procedure "glVertex3sv" (uptr) void)) (define glVertex4d (foreign-procedure "glVertex4d" (double double double double) void)) (define glVertex4dv (foreign-procedure "glVertex4dv" (uptr) void)) (define glVertex4f (foreign-procedure "glVertex4f" (float float float float) void)) (define glVertex4fv (foreign-procedure "glVertex4fv" (uptr) void)) (define glVertex4i (foreign-procedure "glVertex4i" (int int int int) void)) (define glVertex4iv (foreign-procedure "glVertex4iv" (uptr) void)) (define glVertex4s (foreign-procedure "glVertex4s" (short short short short) void)) (define glVertex4sv (foreign-procedure "glVertex4sv" (uptr) void)) (define glVertexAttrib1d (foreign-procedure "glVertexAttrib1d" (unsigned-int double) void)) (define glVertexAttrib1dv (foreign-procedure "glVertexAttrib1dv" (unsigned-int uptr) void)) (define glVertexAttrib1f (foreign-procedure "glVertexAttrib1f" (unsigned-int float) void)) (define glVertexAttrib1fv (foreign-procedure "glVertexAttrib1fv" (unsigned-int uptr) void)) (define glVertexAttrib1s (foreign-procedure "glVertexAttrib1s" (unsigned-int short) void)) (define glVertexAttrib1sv (foreign-procedure "glVertexAttrib1sv" (unsigned-int uptr) void)) (define glVertexAttrib2d (foreign-procedure "glVertexAttrib2d" (unsigned-int double double) void)) (define glVertexAttrib2dv (foreign-procedure "glVertexAttrib2dv" (unsigned-int uptr) void)) (define glVertexAttrib2f (foreign-procedure "glVertexAttrib2f" (unsigned-int float float) void)) (define glVertexAttrib2fv (foreign-procedure "glVertexAttrib2fv" (unsigned-int uptr) void)) (define glVertexAttrib2s (foreign-procedure "glVertexAttrib2s" (unsigned-int short short) void)) (define glVertexAttrib2sv (foreign-procedure "glVertexAttrib2sv" (unsigned-int uptr) void)) (define glVertexAttrib3d (foreign-procedure "glVertexAttrib3d" (unsigned-int double double double) void)) (define glVertexAttrib3dv (foreign-procedure "glVertexAttrib3dv" (unsigned-int uptr) void)) (define glVertexAttrib3f (foreign-procedure "glVertexAttrib3f" (unsigned-int float float float) void)) (define glVertexAttrib3fv (foreign-procedure "glVertexAttrib3fv" (unsigned-int uptr) void)) (define glVertexAttrib3s (foreign-procedure "glVertexAttrib3s" (unsigned-int short short short) void)) (define glVertexAttrib3sv (foreign-procedure "glVertexAttrib3sv" (unsigned-int uptr) void)) (define glVertexAttrib4Nbv (foreign-procedure "glVertexAttrib4Nbv" (unsigned-int string) void)) (define glVertexAttrib4Niv (foreign-procedure "glVertexAttrib4Niv" (unsigned-int uptr) void)) (define glVertexAttrib4Nsv (foreign-procedure "glVertexAttrib4Nsv" (unsigned-int uptr) void)) (define glVertexAttrib4Nub (foreign-procedure "glVertexAttrib4Nub" (unsigned-int unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glVertexAttrib4Nubv (foreign-procedure "glVertexAttrib4Nubv" (unsigned-int string) void)) (define glVertexAttrib4Nuiv (foreign-procedure "glVertexAttrib4Nuiv" (unsigned-int uptr) void)) (define glVertexAttrib4Nusv (foreign-procedure "glVertexAttrib4Nusv" (unsigned-int uptr) void)) (define glVertexAttrib4bv (foreign-procedure "glVertexAttrib4bv" (unsigned-int string) void)) (define glVertexAttrib4d (foreign-procedure "glVertexAttrib4d" (unsigned-int double double double double) void)) (define glVertexAttrib4dv (foreign-procedure "glVertexAttrib4dv" (unsigned-int uptr) void)) (define glVertexAttrib4f (foreign-procedure "glVertexAttrib4f" (unsigned-int float float float float) void)) (define glVertexAttrib4fv (foreign-procedure "glVertexAttrib4fv" (unsigned-int uptr) void)) (define glVertexAttrib4iv (foreign-procedure "glVertexAttrib4iv" (unsigned-int uptr) void)) (define glVertexAttrib4s (foreign-procedure "glVertexAttrib4s" (unsigned-int short short short short) void)) (define glVertexAttrib4sv (foreign-procedure "glVertexAttrib4sv" (unsigned-int uptr) void)) (define glVertexAttrib4ubv (foreign-procedure "glVertexAttrib4ubv" (unsigned-int string) void)) (define glVertexAttrib4uiv (foreign-procedure "glVertexAttrib4uiv" (unsigned-int uptr) void)) (define glVertexAttrib4usv (foreign-procedure "glVertexAttrib4usv" (unsigned-int uptr) void)) (define glVertexAttribPointer (foreign-procedure "glVertexAttribPointer" (unsigned-int int unsigned-int unsigned-8 int uptr) void)) (define glVertexPointer (foreign-procedure "glVertexPointer" (int unsigned-int int uptr) void)) (define glViewport (foreign-procedure "glViewport" (int int int int) void)) (define glWindowPos2d (foreign-procedure "glWindowPos2d" (double double) void)) (define glWindowPos2dv (foreign-procedure "glWindowPos2dv" (uptr) void)) (define glWindowPos2f (foreign-procedure "glWindowPos2f" (float float) void)) (define glWindowPos2fv (foreign-procedure "glWindowPos2fv" (uptr) void)) (define glWindowPos2i (foreign-procedure "glWindowPos2i" (int int) void)) (define glWindowPos2iv (foreign-procedure "glWindowPos2iv" (uptr) void)) (define glWindowPos2s (foreign-procedure "glWindowPos2s" (short short) void)) (define glWindowPos2sv (foreign-procedure "glWindowPos2sv" (uptr) void)) (define glWindowPos3d (foreign-procedure "glWindowPos3d" (double double double) void)) (define glWindowPos3dv (foreign-procedure "glWindowPos3dv" (uptr) void)) (define glWindowPos3f (foreign-procedure "glWindowPos3f" (float float float) void)) (define glWindowPos3fv (foreign-procedure "glWindowPos3fv" (uptr) void)) (define glWindowPos3i (foreign-procedure "glWindowPos3i" (int int int) void)) (define glWindowPos3iv (foreign-procedure "glWindowPos3iv" (uptr) void)) (define glWindowPos3s (foreign-procedure "glWindowPos3s" (short short short) void)) (define glWindowPos3sv (foreign-procedure "glWindowPos3sv" (uptr) void)) (define GL_2D #x600) (define GL_2_BYTES #x1407) (define GL_3D #x601) (define GL_3D_COLOR #x602) (define GL_3D_COLOR_TEXTURE #x603) (define GL_3_BYTES #x1408) (define GL_4D_COLOR_TEXTURE #x604) (define GL_4_BYTES #x1409) (define GL_ACCUM #x100) (define GL_ACCUM_ALPHA_BITS #xD5B) (define GL_ACCUM_BLUE_BITS #xD5A) (define GL_ACCUM_BUFFER_BIT #x200) (define GL_ACCUM_CLEAR_VALUE #xB80) (define GL_ACCUM_GREEN_BITS #xD59) (define GL_ACCUM_RED_BITS #xD58) (define GL_ACTIVE_ATTRIBUTES #x8B89) (define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH #x8B8A) (define GL_ACTIVE_TEXTURE #x84E0) (define GL_ACTIVE_UNIFORMS #x8B86) (define GL_ACTIVE_UNIFORM_MAX_LENGTH #x8B87) (define GL_ADD #x104) (define GL_ADD_SIGNED #x8574) (define GL_ALIASED_LINE_WIDTH_RANGE #x846E) (define GL_ALIASED_POINT_SIZE_RANGE #x846D) (define GL_ALL_ATTRIB_BITS #xFFFFFFFF) (define GL_ALPHA #x1906) (define GL_ALPHA12 #x803D) (define GL_ALPHA16 #x803E) (define GL_ALPHA4 #x803B) (define GL_ALPHA8 #x803C) (define GL_ALPHA_BIAS #xD1D) (define GL_ALPHA_BITS #xD55) (define GL_ALPHA_SCALE #xD1C) (define GL_ALPHA_TEST #xBC0) (define GL_ALPHA_TEST_FUNC #xBC1) (define GL_ALPHA_TEST_REF #xBC2) (define GL_ALWAYS #x207) (define GL_AMBIENT #x1200) (define GL_AMBIENT_AND_DIFFUSE #x1602) (define GL_AND #x1501) (define GL_AND_INVERTED #x1504) (define GL_AND_REVERSE #x1502) (define GL_ARRAY_BUFFER #x8892) (define GL_ARRAY_BUFFER_BINDING #x8894) (define GL_ATTACHED_SHADERS #x8B85) (define GL_ATTRIB_STACK_DEPTH #xBB0) (define GL_AUTO_NORMAL #xD80) (define GL_AUX0 #x409) (define GL_AUX1 #x40A) (define GL_AUX2 #x40B) (define GL_AUX3 #x40C) (define GL_AUX_BUFFERS #xC00) (define GL_BACK #x405) (define GL_BACK_LEFT #x402) (define GL_BACK_RIGHT #x403) (define GL_BGR #x80E0) (define GL_BGRA #x80E1) (define GL_BITMAP #x1A00) (define GL_BITMAP_TOKEN #x704) (define GL_BLEND #xBE2) (define GL_BLEND_DST #xBE0) (define GL_BLEND_DST_ALPHA #x80CA) (define GL_BLEND_DST_RGB #x80C8) (define GL_BLEND_EQUATION_ALPHA #x883D) (define GL_BLEND_EQUATION_RGB #x8009) (define GL_BLEND_SRC #xBE1) (define GL_BLEND_SRC_ALPHA #x80CB) (define GL_BLEND_SRC_RGB #x80C9) (define GL_BLUE #x1905) (define GL_BLUE_BIAS #xD1B) (define GL_BLUE_BITS #xD54) (define GL_BLUE_SCALE #xD1A) (define GL_BOOL #x8B56) (define GL_BOOL_VEC2 #x8B57) (define GL_BOOL_VEC3 #x8B58) (define GL_BOOL_VEC4 #x8B59) (define GL_BUFFER_ACCESS #x88BB) (define GL_BUFFER_MAPPED #x88BC) (define GL_BUFFER_MAP_POINTER #x88BD) (define GL_BUFFER_SIZE #x8764) (define GL_BUFFER_USAGE #x8765) (define GL_BYTE #x1400) (define GL_C3F_V3F #x2A24) (define GL_C4F_N3F_V3F #x2A26) (define GL_C4UB_V2F #x2A22) (define GL_C4UB_V3F #x2A23) (define GL_CCW #x901) (define GL_CLAMP #x2900) (define GL_CLAMP_TO_BORDER #x812D) (define GL_CLAMP_TO_EDGE #x812F) (define GL_CLEAR #x1500) (define GL_CLIENT_ACTIVE_TEXTURE #x84E1) (define GL_CLIENT_ALL_ATTRIB_BITS #xFFFFFFFF) (define GL_CLIENT_ATTRIB_STACK_DEPTH #xBB1) (define GL_CLIENT_PIXEL_STORE_BIT #x1) (define GL_CLIENT_VERTEX_ARRAY_BIT #x2) (define GL_CLIP_PLANE0 #x3000) (define GL_CLIP_PLANE1 #x3001) (define GL_CLIP_PLANE2 #x3002) (define GL_CLIP_PLANE3 #x3003) (define GL_CLIP_PLANE4 #x3004) (define GL_CLIP_PLANE5 #x3005) (define GL_COEFF #xA00) (define GL_COLOR #x1800) (define GL_COLOR_ARRAY #x8076) (define GL_COLOR_ARRAY_BUFFER_BINDING #x8898) (define GL_COLOR_ARRAY_POINTER #x8090) (define GL_COLOR_ARRAY_SIZE #x8081) (define GL_COLOR_ARRAY_STRIDE #x8083) (define GL_COLOR_ARRAY_TYPE #x8082) (define GL_COLOR_BUFFER_BIT #x4000) (define GL_COLOR_CLEAR_VALUE #xC22) (define GL_COLOR_INDEX #x1900) (define GL_COLOR_INDEXES #x1603) (define GL_COLOR_LOGIC_OP #xBF2) (define GL_COLOR_MATERIAL #xB57) (define GL_COLOR_MATERIAL_FACE #xB55) (define GL_COLOR_MATERIAL_PARAMETER #xB56) (define GL_COLOR_SUM #x8458) (define GL_COLOR_WRITEMASK #xC23) (define GL_COMBINE #x8570) (define GL_COMBINE_ALPHA #x8572) (define GL_COMBINE_RGB #x8571) (define GL_COMPARE_R_TO_TEXTURE #x884E) (define GL_COMPILE #x1300) (define GL_COMPILE_AND_EXECUTE #x1301) (define GL_COMPILE_STATUS #x8B81) (define GL_COMPRESSED_ALPHA #x84E9) (define GL_COMPRESSED_INTENSITY #x84EC) (define GL_COMPRESSED_LUMINANCE #x84EA) (define GL_COMPRESSED_LUMINANCE_ALPHA #x84EB) (define GL_COMPRESSED_RGB #x84ED) (define GL_COMPRESSED_RGBA #x84EE) (define GL_COMPRESSED_SLUMINANCE #x8C4A) (define GL_COMPRESSED_SLUMINANCE_ALPHA #x8C4B) (define GL_COMPRESSED_SRGB #x8C48) (define GL_COMPRESSED_SRGB_ALPHA #x8C49) (define GL_COMPRESSED_TEXTURE_FORMATS #x86A3) (define GL_CONSTANT #x8576) (define GL_CONSTANT_ALPHA #x8003) (define GL_CONSTANT_ATTENUATION #x1207) (define GL_CONSTANT_COLOR #x8001) (define GL_COORD_REPLACE #x8862) (define GL_COPY #x1503) (define GL_COPY_INVERTED #x150C) (define GL_COPY_PIXEL_TOKEN #x706) (define GL_CULL_FACE #xB44) (define GL_CULL_FACE_MODE #xB45) (define GL_CURRENT_BIT #x1) (define GL_CURRENT_COLOR #xB00) (define GL_CURRENT_FOG_COORD #x8453) (define GL_CURRENT_FOG_COORDINATE #x8453) (define GL_CURRENT_INDEX #xB01) (define GL_CURRENT_NORMAL #xB02) (define GL_CURRENT_PROGRAM #x8B8D) (define GL_CURRENT_QUERY #x8865) (define GL_CURRENT_RASTER_COLOR #xB04) (define GL_CURRENT_RASTER_DISTANCE #xB09) (define GL_CURRENT_RASTER_INDEX #xB05) (define GL_CURRENT_RASTER_POSITION #xB07) (define GL_CURRENT_RASTER_POSITION_VALID #xB08) (define GL_CURRENT_RASTER_SECONDARY_COLOR #x845F) (define GL_CURRENT_RASTER_TEXTURE_COORDS #xB06) (define GL_CURRENT_SECONDARY_COLOR #x8459) (define GL_CURRENT_TEXTURE_COORDS #xB03) (define GL_CURRENT_VERTEX_ATTRIB #x8626) (define GL_CW #x900) (define GL_DECAL #x2101) (define GL_DECR #x1E03) (define GL_DECR_WRAP #x8508) (define GL_DELETE_STATUS #x8B80) (define GL_DEPTH #x1801) (define GL_DEPTH_BIAS #xD1F) (define GL_DEPTH_BITS #xD56) (define GL_DEPTH_BUFFER_BIT #x100) (define GL_DEPTH_CLEAR_VALUE #xB73) (define GL_DEPTH_COMPONENT #x1902) (define GL_DEPTH_COMPONENT16 #x81A5) (define GL_DEPTH_COMPONENT24 #x81A6) (define GL_DEPTH_COMPONENT32 #x81A7) (define GL_DEPTH_FUNC #xB74) (define GL_DEPTH_RANGE #xB70) (define GL_DEPTH_SCALE #xD1E) (define GL_DEPTH_TEST #xB71) (define GL_DEPTH_TEXTURE_MODE #x884B) (define GL_DEPTH_WRITEMASK #xB72) (define GL_DIFFUSE #x1201) (define GL_DITHER #xBD0) (define GL_DOMAIN #xA02) (define GL_DONT_CARE #x1100) (define GL_DOT3_RGB #x86AE) (define GL_DOT3_RGBA #x86AF) (define GL_DOUBLE #x140A) (define GL_DOUBLEBUFFER #xC32) (define GL_DRAW_BUFFER #xC01) (define GL_DRAW_BUFFER0 #x8825) (define GL_DRAW_BUFFER1 #x8826) (define GL_DRAW_BUFFER10 #x882F) (define GL_DRAW_BUFFER11 #x8830) (define GL_DRAW_BUFFER12 #x8831) (define GL_DRAW_BUFFER13 #x8832) (define GL_DRAW_BUFFER14 #x8833) (define GL_DRAW_BUFFER15 #x8834) (define GL_DRAW_BUFFER2 #x8827) (define GL_DRAW_BUFFER3 #x8828) (define GL_DRAW_BUFFER4 #x8829) (define GL_DRAW_BUFFER5 #x882A) (define GL_DRAW_BUFFER6 #x882B) (define GL_DRAW_BUFFER7 #x882C) (define GL_DRAW_BUFFER8 #x882D) (define GL_DRAW_BUFFER9 #x882E) (define GL_DRAW_PIXEL_TOKEN #x705) (define GL_DST_ALPHA #x304) (define GL_DST_COLOR #x306) (define GL_DYNAMIC_COPY #x88EA) (define GL_DYNAMIC_DRAW #x88E8) (define GL_DYNAMIC_READ #x88E9) (define GL_EDGE_FLAG #xB43) (define GL_EDGE_FLAG_ARRAY #x8079) (define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING #x889B) (define GL_EDGE_FLAG_ARRAY_POINTER #x8093) (define GL_EDGE_FLAG_ARRAY_STRIDE #x808C) (define GL_ELEMENT_ARRAY_BUFFER #x8893) (define GL_ELEMENT_ARRAY_BUFFER_BINDING #x8895) (define GL_EMISSION #x1600) (define GL_ENABLE_BIT #x2000) (define GL_EQUAL #x202) (define GL_EQUIV #x1509) (define GL_EVAL_BIT #x10000) (define GL_EXP #x800) (define GL_EXP2 #x801) (define GL_EXTENSIONS #x1F03) (define GL_EYE_LINEAR #x2400) (define GL_EYE_PLANE #x2502) (define GL_FALSE #x0) (define GL_FASTEST #x1101) (define GL_FEEDBACK #x1C01) (define GL_FEEDBACK_BUFFER_POINTER #xDF0) (define GL_FEEDBACK_BUFFER_SIZE #xDF1) (define GL_FEEDBACK_BUFFER_TYPE #xDF2) (define GL_FILL #x1B02) (define GL_FLAT #x1D00) (define GL_FLOAT #x1406) (define GL_FLOAT_MAT2 #x8B5A) (define GL_FLOAT_MAT2x3 #x8B65) (define GL_FLOAT_MAT2x4 #x8B66) (define GL_FLOAT_MAT3 #x8B5B) (define GL_FLOAT_MAT3x2 #x8B67) (define GL_FLOAT_MAT3x4 #x8B68) (define GL_FLOAT_MAT4 #x8B5C) (define GL_FLOAT_MAT4x2 #x8B69) (define GL_FLOAT_MAT4x3 #x8B6A) (define GL_FLOAT_VEC2 #x8B50) (define GL_FLOAT_VEC3 #x8B51) (define GL_FLOAT_VEC4 #x8B52) (define GL_FOG #xB60) (define GL_FOG_BIT #x80) (define GL_FOG_COLOR #xB66) (define GL_FOG_COORD #x8451) (define GL_FOG_COORDINATE #x8451) (define GL_FOG_COORDINATE_ARRAY #x8457) (define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING #x889D) (define GL_FOG_COORDINATE_ARRAY_POINTER #x8456) (define GL_FOG_COORDINATE_ARRAY_STRIDE #x8455) (define GL_FOG_COORDINATE_ARRAY_TYPE #x8454) (define GL_FOG_COORDINATE_SOURCE #x8450) (define GL_FOG_COORD_ARRAY #x8457) (define GL_FOG_COORD_ARRAY_BUFFER_BINDING #x889D) (define GL_FOG_COORD_ARRAY_POINTER #x8456) (define GL_FOG_COORD_ARRAY_STRIDE #x8455) (define GL_FOG_COORD_ARRAY_TYPE #x8454) (define GL_FOG_COORD_SRC #x8450) (define GL_FOG_DENSITY #xB62) (define GL_FOG_END #xB64) (define GL_FOG_HINT #xC54) (define GL_FOG_INDEX #xB61) (define GL_FOG_MODE #xB65) (define GL_FOG_START #xB63) (define GL_FRAGMENT_DEPTH #x8452) (define GL_FRAGMENT_SHADER #x8B30) (define GL_FRAGMENT_SHADER_DERIVATIVE_HINT #x8B8B) (define GL_FRONT #x404) (define GL_FRONT_AND_BACK #x408) (define GL_FRONT_FACE #xB46) (define GL_FRONT_LEFT #x400) (define GL_FRONT_RIGHT #x401) (define GL_FUNC_ADD #x8006) (define GL_FUNC_REVERSE_SUBTRACT #x800B) (define GL_FUNC_SUBTRACT #x800A) (define GL_GENERATE_MIPMAP #x8191) (define GL_GENERATE_MIPMAP_HINT #x8192) (define GL_GEQUAL #x206) (define GL_GREATER #x204) (define GL_GREEN #x1904) (define GL_GREEN_BIAS #xD19) (define GL_GREEN_BITS #xD53) (define GL_GREEN_SCALE #xD18) (define GL_HINT_BIT #x8000) (define GL_INCR #x1E02) (define GL_INCR_WRAP #x8507) (define GL_INDEX_ARRAY #x8077) (define GL_INDEX_ARRAY_BUFFER_BINDING #x8899) (define GL_INDEX_ARRAY_POINTER #x8091) (define GL_INDEX_ARRAY_STRIDE #x8086) (define GL_INDEX_ARRAY_TYPE #x8085) (define GL_INDEX_BITS #xD51) (define GL_INDEX_CLEAR_VALUE #xC20) (define GL_INDEX_LOGIC_OP #xBF1) (define GL_INDEX_MODE #xC30) (define GL_INDEX_OFFSET #xD13) (define GL_INDEX_SHIFT #xD12) (define GL_INDEX_WRITEMASK #xC21) (define GL_INFO_LOG_LENGTH #x8B84) (define GL_INT #x1404) (define GL_INTENSITY #x8049) (define GL_INTENSITY12 #x804C) (define GL_INTENSITY16 #x804D) (define GL_INTENSITY4 #x804A) (define GL_INTENSITY8 #x804B) (define GL_INTERPOLATE #x8575) (define GL_INT_VEC2 #x8B53) (define GL_INT_VEC3 #x8B54) (define GL_INT_VEC4 #x8B55) (define GL_INVALID_ENUM #x500) (define GL_INVALID_OPERATION #x502) (define GL_INVALID_VALUE #x501) (define GL_INVERT #x150A) (define GL_KEEP #x1E00) (define GL_LEFT #x406) (define GL_LEQUAL #x203) (define GL_LESS #x201) (define GL_LIGHT0 #x4000) (define GL_LIGHT1 #x4001) (define GL_LIGHT2 #x4002) (define GL_LIGHT3 #x4003) (define GL_LIGHT4 #x4004) (define GL_LIGHT5 #x4005) (define GL_LIGHT6 #x4006) (define GL_LIGHT7 #x4007) (define GL_LIGHTING #xB50) (define GL_LIGHTING_BIT #x40) (define GL_LIGHT_MODEL_AMBIENT #xB53) (define GL_LIGHT_MODEL_COLOR_CONTROL #x81F8) (define GL_LIGHT_MODEL_LOCAL_VIEWER #xB51) (define GL_LIGHT_MODEL_TWO_SIDE #xB52) (define GL_LINE #x1B01) (define GL_LINEAR #x2601) (define GL_LINEAR_ATTENUATION #x1208) (define GL_LINEAR_MIPMAP_LINEAR #x2703) (define GL_LINEAR_MIPMAP_NEAREST #x2701) (define GL_LINES #x1) (define GL_LINE_BIT #x4) (define GL_LINE_LOOP #x2) (define GL_LINE_RESET_TOKEN #x707) (define GL_LINE_SMOOTH #xB20) (define GL_LINE_SMOOTH_HINT #xC52) (define GL_LINE_STIPPLE #xB24) (define GL_LINE_STIPPLE_PATTERN #xB25) (define GL_LINE_STIPPLE_REPEAT #xB26) (define GL_LINE_STRIP #x3) (define GL_LINE_TOKEN #x702) (define GL_LINE_WIDTH #xB21) (define GL_LINE_WIDTH_GRANULARITY #xB23) (define GL_LINE_WIDTH_RANGE #xB22) (define GL_LINK_STATUS #x8B82) (define GL_LIST_BASE #xB32) (define GL_LIST_BIT #x20000) (define GL_LIST_INDEX #xB33) (define GL_LIST_MODE #xB30) (define GL_LOAD #x101) (define GL_LOGIC_OP #xBF1) (define GL_LOGIC_OP_MODE #xBF0) (define GL_LOWER_LEFT #x8CA1) (define GL_LUMINANCE #x1909) (define GL_LUMINANCE12 #x8041) (define GL_LUMINANCE12_ALPHA12 #x8047) (define GL_LUMINANCE12_ALPHA4 #x8046) (define GL_LUMINANCE16 #x8042) (define GL_LUMINANCE16_ALPHA16 #x8048) (define GL_LUMINANCE4 #x803F) (define GL_LUMINANCE4_ALPHA4 #x8043) (define GL_LUMINANCE6_ALPHA2 #x8044) (define GL_LUMINANCE8 #x8040) (define GL_LUMINANCE8_ALPHA8 #x8045) (define GL_LUMINANCE_ALPHA #x190A) (define GL_MAP1_COLOR_4 #xD90) (define GL_MAP1_GRID_DOMAIN #xDD0) (define GL_MAP1_GRID_SEGMENTS #xDD1) (define GL_MAP1_INDEX #xD91) (define GL_MAP1_NORMAL #xD92) (define GL_MAP1_TEXTURE_COORD_1 #xD93) (define GL_MAP1_TEXTURE_COORD_2 #xD94) (define GL_MAP1_TEXTURE_COORD_3 #xD95) (define GL_MAP1_TEXTURE_COORD_4 #xD96) (define GL_MAP1_VERTEX_3 #xD97) (define GL_MAP1_VERTEX_4 #xD98) (define GL_MAP2_COLOR_4 #xDB0) (define GL_MAP2_GRID_DOMAIN #xDD2) (define GL_MAP2_GRID_SEGMENTS #xDD3) (define GL_MAP2_INDEX #xDB1) (define GL_MAP2_NORMAL #xDB2) (define GL_MAP2_TEXTURE_COORD_1 #xDB3) (define GL_MAP2_TEXTURE_COORD_2 #xDB4) (define GL_MAP2_TEXTURE_COORD_3 #xDB5) (define GL_MAP2_TEXTURE_COORD_4 #xDB6) (define GL_MAP2_VERTEX_3 #xDB7) (define GL_MAP2_VERTEX_4 #xDB8) (define GL_MAP_COLOR #xD10) (define GL_MAP_STENCIL #xD11) (define GL_MATRIX_MODE #xBA0) (define GL_MAX #x8008) (define GL_MAX_3D_TEXTURE_SIZE #x8073) (define GL_MAX_ATTRIB_STACK_DEPTH #xD35) (define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH #xD3B) (define GL_MAX_CLIP_PLANES #xD32) (define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS #x8B4D) (define GL_MAX_CUBE_MAP_TEXTURE_SIZE #x851C) (define GL_MAX_DRAW_BUFFERS #x8824) (define GL_MAX_ELEMENTS_INDICES #x80E9) (define GL_MAX_ELEMENTS_VERTICES #x80E8) (define GL_MAX_EVAL_ORDER #xD30) (define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS #x8B49) (define GL_MAX_LIGHTS #xD31) (define GL_MAX_LIST_NESTING #xB31) (define GL_MAX_MODELVIEW_STACK_DEPTH #xD36) (define GL_MAX_NAME_STACK_DEPTH #xD37) (define GL_MAX_PIXEL_MAP_TABLE #xD34) (define GL_MAX_PROJECTION_STACK_DEPTH #xD38) (define GL_MAX_TEXTURE_COORDS #x8871) (define GL_MAX_TEXTURE_IMAGE_UNITS #x8872) (define GL_MAX_TEXTURE_LOD_BIAS #x84FD) (define GL_MAX_TEXTURE_SIZE #xD33) (define GL_MAX_TEXTURE_STACK_DEPTH #xD39) (define GL_MAX_TEXTURE_UNITS #x84E2) (define GL_MAX_VARYING_FLOATS #x8B4B) (define GL_MAX_VERTEX_ATTRIBS #x8869) (define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS #x8B4C) (define GL_MAX_VERTEX_UNIFORM_COMPONENTS #x8B4A) (define GL_MAX_VIEWPORT_DIMS #xD3A) (define GL_MIN #x8007) (define GL_MIRRORED_REPEAT #x8370) (define GL_MODELVIEW #x1700) (define GL_MODELVIEW_MATRIX #xBA6) (define GL_MODELVIEW_STACK_DEPTH #xBA3) (define GL_MODULATE #x2100) (define GL_MULT #x103) (define GL_MULTISAMPLE #x809D) (define GL_MULTISAMPLE_BIT #x20000000) (define GL_N3F_V3F #x2A25) (define GL_NAME_STACK_DEPTH #xD70) (define GL_NAND #x150E) (define GL_NEAREST #x2600) (define GL_NEAREST_MIPMAP_LINEAR #x2702) (define GL_NEAREST_MIPMAP_NEAREST #x2700) (define GL_NEVER #x200) (define GL_NICEST #x1102) (define GL_NONE #x0) (define GL_NOOP #x1505) (define GL_NOR #x1508) (define GL_NORMALIZE #xBA1) (define GL_NORMAL_ARRAY #x8075) (define GL_NORMAL_ARRAY_BUFFER_BINDING #x8897) (define GL_NORMAL_ARRAY_POINTER #x808F) (define GL_NORMAL_ARRAY_STRIDE #x807F) (define GL_NORMAL_ARRAY_TYPE #x807E) (define GL_NORMAL_MAP #x8511) (define GL_NOTEQUAL #x205) (define GL_NO_ERROR #x0) (define GL_NUM_COMPRESSED_TEXTURE_FORMATS #x86A2) (define GL_OBJECT_LINEAR #x2401) (define GL_OBJECT_PLANE #x2501) (define GL_ONE #x1) (define GL_ONE_MINUS_CONSTANT_ALPHA #x8004) (define GL_ONE_MINUS_CONSTANT_COLOR #x8002) (define GL_ONE_MINUS_DST_ALPHA #x305) (define GL_ONE_MINUS_DST_COLOR #x307) (define GL_ONE_MINUS_SRC_ALPHA #x303) (define GL_ONE_MINUS_SRC_COLOR #x301) (define GL_OPERAND0_ALPHA #x8598) (define GL_OPERAND0_RGB #x8590) (define GL_OPERAND1_ALPHA #x8599) (define GL_OPERAND1_RGB #x8591) (define GL_OPERAND2_ALPHA #x859A) (define GL_OPERAND2_RGB #x8592) (define GL_OR #x1507) (define GL_ORDER #xA01) (define GL_OR_INVERTED #x150D) (define GL_OR_REVERSE #x150B) (define GL_OUT_OF_MEMORY #x505) (define GL_PACK_ALIGNMENT #xD05) (define GL_PACK_IMAGE_HEIGHT #x806C) (define GL_PACK_LSB_FIRST #xD01) (define GL_PACK_ROW_LENGTH #xD02) (define GL_PACK_SKIP_IMAGES #x806B) (define GL_PACK_SKIP_PIXELS #xD04) (define GL_PACK_SKIP_ROWS #xD03) (define GL_PACK_SWAP_BYTES #xD00) (define GL_PASS_THROUGH_TOKEN #x700) (define GL_PERSPECTIVE_CORRECTION_HINT #xC50) (define GL_PIXEL_MAP_A_TO_A #xC79) (define GL_PIXEL_MAP_A_TO_A_SIZE #xCB9) (define GL_PIXEL_MAP_B_TO_B #xC78) (define GL_PIXEL_MAP_B_TO_B_SIZE #xCB8) (define GL_PIXEL_MAP_G_TO_G #xC77) (define GL_PIXEL_MAP_G_TO_G_SIZE #xCB7) (define GL_PIXEL_MAP_I_TO_A #xC75) (define GL_PIXEL_MAP_I_TO_A_SIZE #xCB5) (define GL_PIXEL_MAP_I_TO_B #xC74) (define GL_PIXEL_MAP_I_TO_B_SIZE #xCB4) (define GL_PIXEL_MAP_I_TO_G #xC73) (define GL_PIXEL_MAP_I_TO_G_SIZE #xCB3) (define GL_PIXEL_MAP_I_TO_I #xC70) (define GL_PIXEL_MAP_I_TO_I_SIZE #xCB0) (define GL_PIXEL_MAP_I_TO_R #xC72) (define GL_PIXEL_MAP_I_TO_R_SIZE #xCB2) (define GL_PIXEL_MAP_R_TO_R #xC76) (define GL_PIXEL_MAP_R_TO_R_SIZE #xCB6) (define GL_PIXEL_MAP_S_TO_S #xC71) (define GL_PIXEL_MAP_S_TO_S_SIZE #xCB1) (define GL_PIXEL_MODE_BIT #x20) (define GL_PIXEL_PACK_BUFFER #x88EB) (define GL_PIXEL_PACK_BUFFER_BINDING #x88ED) (define GL_PIXEL_UNPACK_BUFFER #x88EC) (define GL_PIXEL_UNPACK_BUFFER_BINDING #x88EF) (define GL_POINT #x1B00) (define GL_POINTS #x0) (define GL_POINT_BIT #x2) (define GL_POINT_DISTANCE_ATTENUATION #x8129) (define GL_POINT_FADE_THRESHOLD_SIZE #x8128) (define GL_POINT_SIZE #xB11) (define GL_POINT_SIZE_GRANULARITY #xB13) (define GL_POINT_SIZE_MAX #x8127) (define GL_POINT_SIZE_MIN #x8126) (define GL_POINT_SIZE_RANGE #xB12) (define GL_POINT_SMOOTH #xB10) (define GL_POINT_SMOOTH_HINT #xC51) (define GL_POINT_SPRITE #x8861) (define GL_POINT_SPRITE_COORD_ORIGIN #x8CA0) (define GL_POINT_TOKEN #x701) (define GL_POLYGON #x9) (define GL_POLYGON_BIT #x8) (define GL_POLYGON_MODE #xB40) (define GL_POLYGON_OFFSET_FACTOR #x8038) (define GL_POLYGON_OFFSET_FILL #x8037) (define GL_POLYGON_OFFSET_LINE #x2A02) (define GL_POLYGON_OFFSET_POINT #x2A01) (define GL_POLYGON_OFFSET_UNITS #x2A00) (define GL_POLYGON_SMOOTH #xB41) (define GL_POLYGON_SMOOTH_HINT #xC53) (define GL_POLYGON_STIPPLE #xB42) (define GL_POLYGON_STIPPLE_BIT #x10) (define GL_POLYGON_TOKEN #x703) (define GL_POSITION #x1203) (define GL_PREVIOUS #x8578) (define GL_PRIMARY_COLOR #x8577) (define GL_PROJECTION #x1701) (define GL_PROJECTION_MATRIX #xBA7) (define GL_PROJECTION_STACK_DEPTH #xBA4) (define GL_PROXY_TEXTURE_1D #x8063) (define GL_PROXY_TEXTURE_2D #x8064) (define GL_PROXY_TEXTURE_3D #x8070) (define GL_PROXY_TEXTURE_CUBE_MAP #x851B) (define GL_Q #x2003) (define GL_QUADRATIC_ATTENUATION #x1209) (define GL_QUADS #x7) (define GL_QUAD_STRIP #x8) (define GL_QUERY_COUNTER_BITS #x8864) (define GL_QUERY_RESULT #x8866) (define GL_QUERY_RESULT_AVAILABLE #x8867) (define GL_R #x2002) (define GL_R3_G3_B2 #x2A10) (define GL_READ_BUFFER #xC02) (define GL_READ_ONLY #x88B8) (define GL_READ_WRITE #x88BA) (define GL_RED #x1903) (define GL_RED_BIAS #xD15) (define GL_RED_BITS #xD52) (define GL_RED_SCALE #xD14) (define GL_REFLECTION_MAP #x8512) (define GL_RENDER #x1C00) (define GL_RENDERER #x1F01) (define GL_RENDER_MODE #xC40) (define GL_REPEAT #x2901) (define GL_REPLACE #x1E01) (define GL_RESCALE_NORMAL #x803A) (define GL_RETURN #x102) (define GL_RGB #x1907) (define GL_RGB10 #x8052) (define GL_RGB10_A2 #x8059) (define GL_RGB12 #x8053) (define GL_RGB16 #x8054) (define GL_RGB4 #x804F) (define GL_RGB5 #x8050) (define GL_RGB5_A1 #x8057) (define GL_RGB8 #x8051) (define GL_RGBA #x1908) (define GL_RGBA12 #x805A) (define GL_RGBA16 #x805B) (define GL_RGBA2 #x8055) (define GL_RGBA4 #x8056) (define GL_RGBA8 #x8058) (define GL_RGBA_MODE #xC31) (define GL_RGB_SCALE #x8573) (define GL_RIGHT #x407) (define GL_S #x2000) (define GL_SAMPLER_1D #x8B5D) (define GL_SAMPLER_1D_SHADOW #x8B61) (define GL_SAMPLER_2D #x8B5E) (define GL_SAMPLER_2D_SHADOW #x8B62) (define GL_SAMPLER_3D #x8B5F) (define GL_SAMPLER_CUBE #x8B60) (define GL_SAMPLES #x80A9) (define GL_SAMPLES_PASSED #x8914) (define GL_SAMPLE_ALPHA_TO_COVERAGE #x809E) (define GL_SAMPLE_ALPHA_TO_ONE #x809F) (define GL_SAMPLE_BUFFERS #x80A8) (define GL_SAMPLE_COVERAGE #x80A0) (define GL_SAMPLE_COVERAGE_INVERT #x80AB) (define GL_SAMPLE_COVERAGE_VALUE #x80AA) (define GL_SCISSOR_BIT #x80000) (define GL_SCISSOR_BOX #xC10) (define GL_SCISSOR_TEST #xC11) (define GL_SECONDARY_COLOR_ARRAY #x845E) (define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING #x889C) (define GL_SECONDARY_COLOR_ARRAY_POINTER #x845D) (define GL_SECONDARY_COLOR_ARRAY_SIZE #x845A) (define GL_SECONDARY_COLOR_ARRAY_STRIDE #x845C) (define GL_SECONDARY_COLOR_ARRAY_TYPE #x845B) (define GL_SELECT #x1C02) (define GL_SELECTION_BUFFER_POINTER #xDF3) (define GL_SELECTION_BUFFER_SIZE #xDF4) (define GL_SEPARATE_SPECULAR_COLOR #x81FA) (define GL_SET #x150F) (define GL_SHADER_SOURCE_LENGTH #x8B88) (define GL_SHADER_TYPE #x8B4F) (define GL_SHADE_MODEL #xB54) (define GL_SHADING_LANGUAGE_VERSION #x8B8C) (define GL_SHININESS #x1601) (define GL_SHORT #x1402) (define GL_SINGLE_COLOR #x81F9) (define GL_SLUMINANCE #x8C46) (define GL_SLUMINANCE8 #x8C47) (define GL_SLUMINANCE8_ALPHA8 #x8C45) (define GL_SLUMINANCE_ALPHA #x8C44) (define GL_SMOOTH #x1D01) (define GL_SMOOTH_LINE_WIDTH_GRANULARITY #xB23) (define GL_SMOOTH_LINE_WIDTH_RANGE #xB22) (define GL_SMOOTH_POINT_SIZE_GRANULARITY #xB13) (define GL_SMOOTH_POINT_SIZE_RANGE #xB12) (define GL_SOURCE0_ALPHA #x8588) (define GL_SOURCE0_RGB #x8580) (define GL_SOURCE1_ALPHA #x8589) (define GL_SOURCE1_RGB #x8581) (define GL_SOURCE2_ALPHA #x858A) (define GL_SOURCE2_RGB #x8582) (define GL_SPECULAR #x1202) (define GL_SPHERE_MAP #x2402) (define GL_SPOT_CUTOFF #x1206) (define GL_SPOT_DIRECTION #x1204) (define GL_SPOT_EXPONENT #x1205) (define GL_SRC0_ALPHA #x8588) (define GL_SRC0_RGB #x8580) (define GL_SRC1_ALPHA #x8589) (define GL_SRC1_RGB #x8581) (define GL_SRC2_ALPHA #x858A) (define GL_SRC2_RGB #x8582) (define GL_SRC_ALPHA #x302) (define GL_SRC_ALPHA_SATURATE #x308) (define GL_SRC_COLOR #x300) (define GL_SRGB #x8C40) (define GL_SRGB8 #x8C41) (define GL_SRGB8_ALPHA8 #x8C43) (define GL_SRGB_ALPHA #x8C42) (define GL_STACK_OVERFLOW #x503) (define GL_STACK_UNDERFLOW #x504) (define GL_STATIC_COPY #x88E6) (define GL_STATIC_DRAW #x88E4) (define GL_STATIC_READ #x88E5) (define GL_STENCIL #x1802) (define GL_STENCIL_BACK_FAIL #x8801) (define GL_STENCIL_BACK_FUNC #x8800) (define GL_STENCIL_BACK_PASS_DEPTH_FAIL #x8802) (define GL_STENCIL_BACK_PASS_DEPTH_PASS #x8803) (define GL_STENCIL_BACK_REF #x8CA3) (define GL_STENCIL_BACK_VALUE_MASK #x8CA4) (define GL_STENCIL_BACK_WRITEMASK #x8CA5) (define GL_STENCIL_BITS #xD57) (define GL_STENCIL_BUFFER_BIT #x400) (define GL_STENCIL_CLEAR_VALUE #xB91) (define GL_STENCIL_FAIL #xB94) (define GL_STENCIL_FUNC #xB92) (define GL_STENCIL_INDEX #x1901) (define GL_STENCIL_PASS_DEPTH_FAIL #xB95) (define GL_STENCIL_PASS_DEPTH_PASS #xB96) (define GL_STENCIL_REF #xB97) (define GL_STENCIL_TEST #xB90) (define GL_STENCIL_VALUE_MASK #xB93) (define GL_STENCIL_WRITEMASK #xB98) (define GL_STEREO #xC33) (define GL_STREAM_COPY #x88E2) (define GL_STREAM_DRAW #x88E0) (define GL_STREAM_READ #x88E1) (define GL_SUBPIXEL_BITS #xD50) (define GL_SUBTRACT #x84E7) (define GL_T #x2001) (define GL_T2F_C3F_V3F #x2A2A) (define GL_T2F_C4F_N3F_V3F #x2A2C) (define GL_T2F_C4UB_V3F #x2A29) (define GL_T2F_N3F_V3F #x2A2B) (define GL_T2F_V3F #x2A27) (define GL_T4F_C4F_N3F_V4F #x2A2D) (define GL_T4F_V4F #x2A28) (define GL_TEXTURE #x1702) (define GL_TEXTURE0 #x84C0) (define GL_TEXTURE1 #x84C1) (define GL_TEXTURE10 #x84CA) (define GL_TEXTURE11 #x84CB) (define GL_TEXTURE12 #x84CC) (define GL_TEXTURE13 #x84CD) (define GL_TEXTURE14 #x84CE) (define GL_TEXTURE15 #x84CF) (define GL_TEXTURE16 #x84D0) (define GL_TEXTURE17 #x84D1) (define GL_TEXTURE18 #x84D2) (define GL_TEXTURE19 #x84D3) (define GL_TEXTURE2 #x84C2) (define GL_TEXTURE20 #x84D4) (define GL_TEXTURE21 #x84D5) (define GL_TEXTURE22 #x84D6) (define GL_TEXTURE23 #x84D7) (define GL_TEXTURE24 #x84D8) (define GL_TEXTURE25 #x84D9) (define GL_TEXTURE26 #x84DA) (define GL_TEXTURE27 #x84DB) (define GL_TEXTURE28 #x84DC) (define GL_TEXTURE29 #x84DD) (define GL_TEXTURE3 #x84C3) (define GL_TEXTURE30 #x84DE) (define GL_TEXTURE31 #x84DF) (define GL_TEXTURE4 #x84C4) (define GL_TEXTURE5 #x84C5) (define GL_TEXTURE6 #x84C6) (define GL_TEXTURE7 #x84C7) (define GL_TEXTURE8 #x84C8) (define GL_TEXTURE9 #x84C9) (define GL_TEXTURE_1D #xDE0) (define GL_TEXTURE_2D #xDE1) (define GL_TEXTURE_3D #x806F) (define GL_TEXTURE_ALPHA_SIZE #x805F) (define GL_TEXTURE_BASE_LEVEL #x813C) (define GL_TEXTURE_BINDING_1D #x8068) (define GL_TEXTURE_BINDING_2D #x8069) (define GL_TEXTURE_BINDING_3D #x806A) (define GL_TEXTURE_BINDING_CUBE_MAP #x8514) (define GL_TEXTURE_BIT #x40000) (define GL_TEXTURE_BLUE_SIZE #x805E) (define GL_TEXTURE_BORDER #x1005) (define GL_TEXTURE_BORDER_COLOR #x1004) (define GL_TEXTURE_COMPARE_FUNC #x884D) (define GL_TEXTURE_COMPARE_MODE #x884C) (define GL_TEXTURE_COMPONENTS #x1003) (define GL_TEXTURE_COMPRESSED #x86A1) (define GL_TEXTURE_COMPRESSED_IMAGE_SIZE #x86A0) (define GL_TEXTURE_COMPRESSION_HINT #x84EF) (define GL_TEXTURE_COORD_ARRAY #x8078) (define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING #x889A) (define GL_TEXTURE_COORD_ARRAY_POINTER #x8092) (define GL_TEXTURE_COORD_ARRAY_SIZE #x8088) (define GL_TEXTURE_COORD_ARRAY_STRIDE #x808A) (define GL_TEXTURE_COORD_ARRAY_TYPE #x8089) (define GL_TEXTURE_CUBE_MAP #x8513) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_X #x8516) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y #x8518) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z #x851A) (define GL_TEXTURE_CUBE_MAP_POSITIVE_X #x8515) (define GL_TEXTURE_CUBE_MAP_POSITIVE_Y #x8517) (define GL_TEXTURE_CUBE_MAP_POSITIVE_Z #x8519) (define GL_TEXTURE_DEPTH #x8071) (define GL_TEXTURE_DEPTH_SIZE #x884A) (define GL_TEXTURE_ENV #x2300) (define GL_TEXTURE_ENV_COLOR #x2201) (define GL_TEXTURE_ENV_MODE #x2200) (define GL_TEXTURE_FILTER_CONTROL #x8500) (define GL_TEXTURE_GEN_MODE #x2500) (define GL_TEXTURE_GEN_Q #xC63) (define GL_TEXTURE_GEN_R #xC62) (define GL_TEXTURE_GEN_S #xC60) (define GL_TEXTURE_GEN_T #xC61) (define GL_TEXTURE_GREEN_SIZE #x805D) (define GL_TEXTURE_HEIGHT #x1001) (define GL_TEXTURE_INTENSITY_SIZE #x8061) (define GL_TEXTURE_INTERNAL_FORMAT #x1003) (define GL_TEXTURE_LOD_BIAS #x8501) (define GL_TEXTURE_LUMINANCE_SIZE #x8060) (define GL_TEXTURE_MAG_FILTER #x2800) (define GL_TEXTURE_MATRIX #xBA8) (define GL_TEXTURE_MAX_LEVEL #x813D) (define GL_TEXTURE_MAX_LOD #x813B) (define GL_TEXTURE_MIN_FILTER #x2801) (define GL_TEXTURE_MIN_LOD #x813A) (define GL_TEXTURE_PRIORITY #x8066) (define GL_TEXTURE_RED_SIZE #x805C) (define GL_TEXTURE_RESIDENT #x8067) (define GL_TEXTURE_STACK_DEPTH #xBA5) (define GL_TEXTURE_WIDTH #x1000) (define GL_TEXTURE_WRAP_R #x8072) (define GL_TEXTURE_WRAP_S #x2802) (define GL_TEXTURE_WRAP_T #x2803) (define GL_TRANSFORM_BIT #x1000) (define GL_TRANSPOSE_COLOR_MATRIX #x84E6) (define GL_TRANSPOSE_MODELVIEW_MATRIX #x84E3) (define GL_TRANSPOSE_PROJECTION_MATRIX #x84E4) (define GL_TRANSPOSE_TEXTURE_MATRIX #x84E5) (define GL_TRIANGLES #x4) (define GL_TRIANGLE_FAN #x6) (define GL_TRIANGLE_STRIP #x5) (define GL_TRUE #x1) (define GL_UNPACK_ALIGNMENT #xCF5) (define GL_UNPACK_IMAGE_HEIGHT #x806E) (define GL_UNPACK_LSB_FIRST #xCF1) (define GL_UNPACK_ROW_LENGTH #xCF2) (define GL_UNPACK_SKIP_IMAGES #x806D) (define GL_UNPACK_SKIP_PIXELS #xCF4) (define GL_UNPACK_SKIP_ROWS #xCF3) (define GL_UNPACK_SWAP_BYTES #xCF0) (define GL_UNSIGNED_BYTE #x1401) (define GL_UNSIGNED_BYTE_2_3_3_REV #x8362) (define GL_UNSIGNED_BYTE_3_3_2 #x8032) (define GL_UNSIGNED_INT #x1405) (define GL_UNSIGNED_INT_10_10_10_2 #x8036) (define GL_UNSIGNED_INT_2_10_10_10_REV #x8368) (define GL_UNSIGNED_INT_8_8_8_8 #x8035) (define GL_UNSIGNED_INT_8_8_8_8_REV #x8367) (define GL_UNSIGNED_SHORT #x1403) (define GL_UNSIGNED_SHORT_1_5_5_5_REV #x8366) (define GL_UNSIGNED_SHORT_4_4_4_4 #x8033) (define GL_UNSIGNED_SHORT_4_4_4_4_REV #x8365) (define GL_UNSIGNED_SHORT_5_5_5_1 #x8034) (define GL_UNSIGNED_SHORT_5_6_5 #x8363) (define GL_UNSIGNED_SHORT_5_6_5_REV #x8364) (define GL_UPPER_LEFT #x8CA2) (define GL_V2F #x2A20) (define GL_V3F #x2A21) (define GL_VALIDATE_STATUS #x8B83) (define GL_VENDOR #x1F00) (define GL_VERSION #x1F02) (define GL_VERTEX_ARRAY #x8074) (define GL_VERTEX_ARRAY_BUFFER_BINDING #x8896) (define GL_VERTEX_ARRAY_POINTER #x808E) (define GL_VERTEX_ARRAY_SIZE #x807A) (define GL_VERTEX_ARRAY_STRIDE #x807C) (define GL_VERTEX_ARRAY_TYPE #x807B) (define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING #x889F) (define GL_VERTEX_ATTRIB_ARRAY_ENABLED #x8622) (define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED #x886A) (define GL_VERTEX_ATTRIB_ARRAY_POINTER #x8645) (define GL_VERTEX_ATTRIB_ARRAY_SIZE #x8623) (define GL_VERTEX_ATTRIB_ARRAY_STRIDE #x8624) (define GL_VERTEX_ATTRIB_ARRAY_TYPE #x8625) (define GL_VERTEX_PROGRAM_POINT_SIZE #x8642) (define GL_VERTEX_PROGRAM_TWO_SIDE #x8643) (define GL_VERTEX_SHADER #x8B31) (define GL_VIEWPORT #xBA2) (define GL_VIEWPORT_BIT #x800) (define GL_WEIGHT_ARRAY_BUFFER_BINDING #x889E) (define GL_WRITE_ONLY #x88B9) (define GL_XOR #x1506) (define GL_ZERO #x0) (define GL_ZOOM_X #xD16) (define GL_ZOOM_Y #xD17) )
null
https://raw.githubusercontent.com/jhidding/chez-glfw/fe53b5d8915c1c0b9f6a07446a0399a430d09851/glfw/gl/GL_VERSION_2_1.scm
scheme
(library (glfw gl GL_VERSION_2_1) (export glAccum glActiveTexture glAlphaFunc glAreTexturesResident glArrayElement glAttachShader glBegin glBeginQuery glBindAttribLocation glBindBuffer glBindTexture glBitmap glBlendColor glBlendEquation glBlendEquationSeparate glBlendFunc glBlendFuncSeparate glBufferData glBufferSubData glCallList glCallLists glClear glClearAccum glClearColor glClearDepth glClearIndex glClearStencil glClientActiveTexture glClipPlane glColor3b glColor3bv glColor3d glColor3dv glColor3f glColor3fv glColor3i glColor3iv glColor3s glColor3sv glColor3ub glColor3ubv glColor3ui glColor3uiv glColor3us glColor3usv glColor4b glColor4bv glColor4d glColor4dv glColor4f glColor4fv glColor4i glColor4iv glColor4s glColor4sv glColor4ub glColor4ubv glColor4ui glColor4uiv glColor4us glColor4usv glColorMask glColorMaterial glColorPointer glCompileShader glCompressedTexImage1D glCompressedTexImage2D glCompressedTexImage3D glCompressedTexSubImage1D glCompressedTexSubImage2D glCompressedTexSubImage3D glCopyPixels glCopyTexImage1D glCopyTexImage2D glCopyTexSubImage1D glCopyTexSubImage2D glCopyTexSubImage3D glCreateProgram glCreateShader glCullFace glDeleteBuffers glDeleteLists glDeleteProgram glDeleteQueries glDeleteShader glDeleteTextures glDepthFunc glDepthMask glDepthRange glDetachShader glDisable glDisableClientState glDisableVertexAttribArray glDrawArrays glDrawBuffer glDrawBuffers glDrawElements glDrawPixels glDrawRangeElements glEdgeFlag glEdgeFlagPointer glEdgeFlagv glEnable glEnableClientState glEnableVertexAttribArray glEnd glEndList glEndQuery glEvalCoord1d glEvalCoord1dv glEvalCoord1f glEvalCoord1fv glEvalCoord2d glEvalCoord2dv glEvalCoord2f glEvalCoord2fv glEvalMesh1 glEvalMesh2 glEvalPoint1 glEvalPoint2 glFeedbackBuffer glFinish glFlush glFogCoordPointer glFogCoordd glFogCoorddv glFogCoordf glFogCoordfv glFogf glFogfv glFogi glFogiv glFrontFace glFrustum glGenBuffers glGenLists glGenQueries glGenTextures glGetActiveAttrib glGetActiveUniform glGetAttachedShaders glGetAttribLocation glGetBooleanv glGetBufferParameteriv glGetBufferPointerv glGetBufferSubData glGetClipPlane glGetCompressedTexImage glGetDoublev glGetError glGetFloatv glGetIntegerv glGetLightfv glGetLightiv glGetMapdv glGetMapfv glGetMapiv glGetMaterialfv glGetMaterialiv glGetPixelMapfv glGetPixelMapuiv glGetPixelMapusv glGetPointerv glGetPolygonStipple glGetProgramInfoLog glGetProgramiv glGetQueryObjectiv glGetQueryObjectuiv glGetQueryiv glGetShaderInfoLog glGetShaderSource glGetShaderiv glGetString glGetTexEnvfv glGetTexEnviv glGetTexGendv glGetTexGenfv glGetTexGeniv glGetTexImage glGetTexLevelParameterfv glGetTexLevelParameteriv glGetTexParameterfv glGetTexParameteriv glGetUniformLocation glGetUniformfv glGetUniformiv glGetVertexAttribPointerv glGetVertexAttribdv glGetVertexAttribfv glGetVertexAttribiv glHint glIndexMask glIndexPointer glIndexd glIndexdv glIndexf glIndexfv glIndexi glIndexiv glIndexs glIndexsv glIndexub glIndexubv glInitNames glInterleavedArrays glIsBuffer glIsEnabled glIsList glIsProgram glIsQuery glIsShader glIsTexture glLightModelf glLightModelfv glLightModeli glLightModeliv glLightf glLightfv glLighti glLightiv glLineStipple glLineWidth glLinkProgram glListBase glLoadIdentity glLoadMatrixd glLoadMatrixf glLoadName glLoadTransposeMatrixd glLoadTransposeMatrixf glLogicOp glMap1d glMap1f glMap2d glMap2f glMapBuffer glMapGrid1d glMapGrid1f glMapGrid2d glMapGrid2f glMaterialf glMaterialfv glMateriali glMaterialiv glMatrixMode glMultMatrixd glMultMatrixf glMultTransposeMatrixd glMultTransposeMatrixf glMultiDrawArrays glMultiDrawElements glMultiTexCoord1d glMultiTexCoord1dv glMultiTexCoord1f glMultiTexCoord1fv glMultiTexCoord1i glMultiTexCoord1iv glMultiTexCoord1s glMultiTexCoord1sv glMultiTexCoord2d glMultiTexCoord2dv glMultiTexCoord2f glMultiTexCoord2fv glMultiTexCoord2i glMultiTexCoord2iv glMultiTexCoord2s glMultiTexCoord2sv glMultiTexCoord3d glMultiTexCoord3dv glMultiTexCoord3f glMultiTexCoord3fv glMultiTexCoord3i glMultiTexCoord3iv glMultiTexCoord3s glMultiTexCoord3sv glMultiTexCoord4d glMultiTexCoord4dv glMultiTexCoord4f glMultiTexCoord4fv glMultiTexCoord4i glMultiTexCoord4iv glMultiTexCoord4s glMultiTexCoord4sv glNewList glNormal3b glNormal3bv glNormal3d glNormal3dv glNormal3f glNormal3fv glNormal3i glNormal3iv glNormal3s glNormal3sv glNormalPointer glOrtho glPassThrough glPixelMapfv glPixelMapuiv glPixelMapusv glPixelStoref glPixelStorei glPixelTransferf glPixelTransferi glPixelZoom glPointParameterf glPointParameterfv glPointParameteri glPointParameteriv glPointSize glPolygonMode glPolygonOffset glPolygonStipple glPopAttrib glPopClientAttrib glPopMatrix glPopName glPrioritizeTextures glPushAttrib glPushClientAttrib glPushMatrix glPushName glRasterPos2d glRasterPos2dv glRasterPos2f glRasterPos2fv glRasterPos2i glRasterPos2iv glRasterPos2s glRasterPos2sv glRasterPos3d glRasterPos3dv glRasterPos3f glRasterPos3fv glRasterPos3i glRasterPos3iv glRasterPos3s glRasterPos3sv glRasterPos4d glRasterPos4dv glRasterPos4f glRasterPos4fv glRasterPos4i glRasterPos4iv glRasterPos4s glRasterPos4sv glReadBuffer glReadPixels glRectd glRectdv glRectf glRectfv glRecti glRectiv glRects glRectsv glRenderMode glRotated glRotatef glSampleCoverage glScaled glScalef glScissor glSecondaryColor3b glSecondaryColor3bv glSecondaryColor3d glSecondaryColor3dv glSecondaryColor3f glSecondaryColor3fv glSecondaryColor3i glSecondaryColor3iv glSecondaryColor3s glSecondaryColor3sv glSecondaryColor3ub glSecondaryColor3ubv glSecondaryColor3ui glSecondaryColor3uiv glSecondaryColor3us glSecondaryColor3usv glSecondaryColorPointer glSelectBuffer glShadeModel glShaderSource glStencilFunc glStencilFuncSeparate glStencilMask glStencilMaskSeparate glStencilOp glStencilOpSeparate glTexCoord1d glTexCoord1dv glTexCoord1f glTexCoord1fv glTexCoord1i glTexCoord1iv glTexCoord1s glTexCoord1sv glTexCoord2d glTexCoord2dv glTexCoord2f glTexCoord2fv glTexCoord2i glTexCoord2iv glTexCoord2s glTexCoord2sv glTexCoord3d glTexCoord3dv glTexCoord3f glTexCoord3fv glTexCoord3i glTexCoord3iv glTexCoord3s glTexCoord3sv glTexCoord4d glTexCoord4dv glTexCoord4f glTexCoord4fv glTexCoord4i glTexCoord4iv glTexCoord4s glTexCoord4sv glTexCoordPointer glTexEnvf glTexEnvfv glTexEnvi glTexEnviv glTexGend glTexGendv glTexGenf glTexGenfv glTexGeni glTexGeniv glTexImage1D glTexImage2D glTexImage3D glTexParameterf glTexParameterfv glTexParameteri glTexParameteriv glTexSubImage1D glTexSubImage2D glTexSubImage3D glTranslated glTranslatef glUniform1f glUniform1fv glUniform1i glUniform1iv glUniform2f glUniform2fv glUniform2i glUniform2iv glUniform3f glUniform3fv glUniform3i glUniform3iv glUniform4f glUniform4fv glUniform4i glUniform4iv glUniformMatrix2fv glUniformMatrix2x3fv glUniformMatrix2x4fv glUniformMatrix3fv glUniformMatrix3x2fv glUniformMatrix3x4fv glUniformMatrix4fv glUniformMatrix4x2fv glUniformMatrix4x3fv glUnmapBuffer glUseProgram glValidateProgram glVertex2d glVertex2dv glVertex2f glVertex2fv glVertex2i glVertex2iv glVertex2s glVertex2sv glVertex3d glVertex3dv glVertex3f glVertex3fv glVertex3i glVertex3iv glVertex3s glVertex3sv glVertex4d glVertex4dv glVertex4f glVertex4fv glVertex4i glVertex4iv glVertex4s glVertex4sv glVertexAttrib1d glVertexAttrib1dv glVertexAttrib1f glVertexAttrib1fv glVertexAttrib1s glVertexAttrib1sv glVertexAttrib2d glVertexAttrib2dv glVertexAttrib2f glVertexAttrib2fv glVertexAttrib2s glVertexAttrib2sv glVertexAttrib3d glVertexAttrib3dv glVertexAttrib3f glVertexAttrib3fv glVertexAttrib3s glVertexAttrib3sv glVertexAttrib4Nbv glVertexAttrib4Niv glVertexAttrib4Nsv glVertexAttrib4Nub glVertexAttrib4Nubv glVertexAttrib4Nuiv glVertexAttrib4Nusv glVertexAttrib4bv glVertexAttrib4d glVertexAttrib4dv glVertexAttrib4f glVertexAttrib4fv glVertexAttrib4iv glVertexAttrib4s glVertexAttrib4sv glVertexAttrib4ubv glVertexAttrib4uiv glVertexAttrib4usv glVertexAttribPointer glVertexPointer glViewport glWindowPos2d glWindowPos2dv glWindowPos2f glWindowPos2fv glWindowPos2i glWindowPos2iv glWindowPos2s glWindowPos2sv glWindowPos3d glWindowPos3dv glWindowPos3f glWindowPos3fv glWindowPos3i glWindowPos3iv glWindowPos3s glWindowPos3sv GL_2D GL_2_BYTES GL_3D GL_3D_COLOR GL_3D_COLOR_TEXTURE GL_3_BYTES GL_4D_COLOR_TEXTURE GL_4_BYTES GL_ACCUM GL_ACCUM_ALPHA_BITS GL_ACCUM_BLUE_BITS GL_ACCUM_BUFFER_BIT GL_ACCUM_CLEAR_VALUE GL_ACCUM_GREEN_BITS GL_ACCUM_RED_BITS GL_ACTIVE_ATTRIBUTES GL_ACTIVE_ATTRIBUTE_MAX_LENGTH GL_ACTIVE_TEXTURE GL_ACTIVE_UNIFORMS GL_ACTIVE_UNIFORM_MAX_LENGTH GL_ADD GL_ADD_SIGNED GL_ALIASED_LINE_WIDTH_RANGE GL_ALIASED_POINT_SIZE_RANGE GL_ALL_ATTRIB_BITS GL_ALPHA GL_ALPHA12 GL_ALPHA16 GL_ALPHA4 GL_ALPHA8 GL_ALPHA_BIAS GL_ALPHA_BITS GL_ALPHA_SCALE GL_ALPHA_TEST GL_ALPHA_TEST_FUNC GL_ALPHA_TEST_REF GL_ALWAYS GL_AMBIENT GL_AMBIENT_AND_DIFFUSE GL_AND GL_AND_INVERTED GL_AND_REVERSE GL_ARRAY_BUFFER GL_ARRAY_BUFFER_BINDING GL_ATTACHED_SHADERS GL_ATTRIB_STACK_DEPTH GL_AUTO_NORMAL GL_AUX0 GL_AUX1 GL_AUX2 GL_AUX3 GL_AUX_BUFFERS GL_BACK GL_BACK_LEFT GL_BACK_RIGHT GL_BGR GL_BGRA GL_BITMAP GL_BITMAP_TOKEN GL_BLEND GL_BLEND_DST GL_BLEND_DST_ALPHA GL_BLEND_DST_RGB GL_BLEND_EQUATION_ALPHA GL_BLEND_EQUATION_RGB GL_BLEND_SRC GL_BLEND_SRC_ALPHA GL_BLEND_SRC_RGB GL_BLUE GL_BLUE_BIAS GL_BLUE_BITS GL_BLUE_SCALE GL_BOOL GL_BOOL_VEC2 GL_BOOL_VEC3 GL_BOOL_VEC4 GL_BUFFER_ACCESS GL_BUFFER_MAPPED GL_BUFFER_MAP_POINTER GL_BUFFER_SIZE GL_BUFFER_USAGE GL_BYTE GL_C3F_V3F GL_C4F_N3F_V3F GL_C4UB_V2F GL_C4UB_V3F GL_CCW GL_CLAMP GL_CLAMP_TO_BORDER GL_CLAMP_TO_EDGE GL_CLEAR GL_CLIENT_ACTIVE_TEXTURE GL_CLIENT_ALL_ATTRIB_BITS GL_CLIENT_ATTRIB_STACK_DEPTH GL_CLIENT_PIXEL_STORE_BIT GL_CLIENT_VERTEX_ARRAY_BIT GL_CLIP_PLANE0 GL_CLIP_PLANE1 GL_CLIP_PLANE2 GL_CLIP_PLANE3 GL_CLIP_PLANE4 GL_CLIP_PLANE5 GL_COEFF GL_COLOR GL_COLOR_ARRAY GL_COLOR_ARRAY_BUFFER_BINDING GL_COLOR_ARRAY_POINTER GL_COLOR_ARRAY_SIZE GL_COLOR_ARRAY_STRIDE GL_COLOR_ARRAY_TYPE GL_COLOR_BUFFER_BIT GL_COLOR_CLEAR_VALUE GL_COLOR_INDEX GL_COLOR_INDEXES GL_COLOR_LOGIC_OP GL_COLOR_MATERIAL GL_COLOR_MATERIAL_FACE GL_COLOR_MATERIAL_PARAMETER GL_COLOR_SUM GL_COLOR_WRITEMASK GL_COMBINE GL_COMBINE_ALPHA GL_COMBINE_RGB GL_COMPARE_R_TO_TEXTURE GL_COMPILE GL_COMPILE_AND_EXECUTE GL_COMPILE_STATUS GL_COMPRESSED_ALPHA GL_COMPRESSED_INTENSITY GL_COMPRESSED_LUMINANCE GL_COMPRESSED_LUMINANCE_ALPHA GL_COMPRESSED_RGB GL_COMPRESSED_RGBA GL_COMPRESSED_SLUMINANCE GL_COMPRESSED_SLUMINANCE_ALPHA GL_COMPRESSED_SRGB GL_COMPRESSED_SRGB_ALPHA GL_COMPRESSED_TEXTURE_FORMATS GL_CONSTANT GL_CONSTANT_ALPHA GL_CONSTANT_ATTENUATION GL_CONSTANT_COLOR GL_COORD_REPLACE GL_COPY GL_COPY_INVERTED GL_COPY_PIXEL_TOKEN GL_CULL_FACE GL_CULL_FACE_MODE GL_CURRENT_BIT GL_CURRENT_COLOR GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE GL_CURRENT_INDEX GL_CURRENT_NORMAL GL_CURRENT_PROGRAM GL_CURRENT_QUERY GL_CURRENT_RASTER_COLOR GL_CURRENT_RASTER_DISTANCE GL_CURRENT_RASTER_INDEX GL_CURRENT_RASTER_POSITION GL_CURRENT_RASTER_POSITION_VALID GL_CURRENT_RASTER_SECONDARY_COLOR GL_CURRENT_RASTER_TEXTURE_COORDS GL_CURRENT_SECONDARY_COLOR GL_CURRENT_TEXTURE_COORDS GL_CURRENT_VERTEX_ATTRIB GL_CW GL_DECAL GL_DECR GL_DECR_WRAP GL_DELETE_STATUS GL_DEPTH GL_DEPTH_BIAS GL_DEPTH_BITS GL_DEPTH_BUFFER_BIT GL_DEPTH_CLEAR_VALUE GL_DEPTH_COMPONENT GL_DEPTH_COMPONENT16 GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT32 GL_DEPTH_FUNC GL_DEPTH_RANGE GL_DEPTH_SCALE GL_DEPTH_TEST GL_DEPTH_TEXTURE_MODE GL_DEPTH_WRITEMASK GL_DIFFUSE GL_DITHER GL_DOMAIN GL_DONT_CARE GL_DOT3_RGB GL_DOT3_RGBA GL_DOUBLE GL_DOUBLEBUFFER GL_DRAW_BUFFER GL_DRAW_BUFFER0 GL_DRAW_BUFFER1 GL_DRAW_BUFFER10 GL_DRAW_BUFFER11 GL_DRAW_BUFFER12 GL_DRAW_BUFFER13 GL_DRAW_BUFFER14 GL_DRAW_BUFFER15 GL_DRAW_BUFFER2 GL_DRAW_BUFFER3 GL_DRAW_BUFFER4 GL_DRAW_BUFFER5 GL_DRAW_BUFFER6 GL_DRAW_BUFFER7 GL_DRAW_BUFFER8 GL_DRAW_BUFFER9 GL_DRAW_PIXEL_TOKEN GL_DST_ALPHA GL_DST_COLOR GL_DYNAMIC_COPY GL_DYNAMIC_DRAW GL_DYNAMIC_READ GL_EDGE_FLAG GL_EDGE_FLAG_ARRAY GL_EDGE_FLAG_ARRAY_BUFFER_BINDING GL_EDGE_FLAG_ARRAY_POINTER GL_EDGE_FLAG_ARRAY_STRIDE GL_ELEMENT_ARRAY_BUFFER GL_ELEMENT_ARRAY_BUFFER_BINDING GL_EMISSION GL_ENABLE_BIT GL_EQUAL GL_EQUIV GL_EVAL_BIT GL_EXP GL_EXP2 GL_EXTENSIONS GL_EYE_LINEAR GL_EYE_PLANE GL_FALSE GL_FASTEST GL_FEEDBACK GL_FEEDBACK_BUFFER_POINTER GL_FEEDBACK_BUFFER_SIZE GL_FEEDBACK_BUFFER_TYPE GL_FILL GL_FLAT GL_FLOAT GL_FLOAT_MAT2 GL_FLOAT_MAT2x3 GL_FLOAT_MAT2x4 GL_FLOAT_MAT3 GL_FLOAT_MAT3x2 GL_FLOAT_MAT3x4 GL_FLOAT_MAT4 GL_FLOAT_MAT4x2 GL_FLOAT_MAT4x3 GL_FLOAT_VEC2 GL_FLOAT_VEC3 GL_FLOAT_VEC4 GL_FOG GL_FOG_BIT GL_FOG_COLOR GL_FOG_COORD GL_FOG_COORDINATE GL_FOG_COORDINATE_ARRAY GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_TYPE GL_FOG_COORDINATE_SOURCE GL_FOG_COORD_ARRAY GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORD_SRC GL_FOG_DENSITY GL_FOG_END GL_FOG_HINT GL_FOG_INDEX GL_FOG_MODE GL_FOG_START GL_FRAGMENT_DEPTH GL_FRAGMENT_SHADER GL_FRAGMENT_SHADER_DERIVATIVE_HINT GL_FRONT GL_FRONT_AND_BACK GL_FRONT_FACE GL_FRONT_LEFT GL_FRONT_RIGHT GL_FUNC_ADD GL_FUNC_REVERSE_SUBTRACT GL_FUNC_SUBTRACT GL_GENERATE_MIPMAP GL_GENERATE_MIPMAP_HINT GL_GEQUAL GL_GREATER GL_GREEN GL_GREEN_BIAS GL_GREEN_BITS GL_GREEN_SCALE GL_HINT_BIT GL_INCR GL_INCR_WRAP GL_INDEX_ARRAY GL_INDEX_ARRAY_BUFFER_BINDING GL_INDEX_ARRAY_POINTER GL_INDEX_ARRAY_STRIDE GL_INDEX_ARRAY_TYPE GL_INDEX_BITS GL_INDEX_CLEAR_VALUE GL_INDEX_LOGIC_OP GL_INDEX_MODE GL_INDEX_OFFSET GL_INDEX_SHIFT GL_INDEX_WRITEMASK GL_INFO_LOG_LENGTH GL_INT GL_INTENSITY GL_INTENSITY12 GL_INTENSITY16 GL_INTENSITY4 GL_INTENSITY8 GL_INTERPOLATE GL_INT_VEC2 GL_INT_VEC3 GL_INT_VEC4 GL_INVALID_ENUM GL_INVALID_OPERATION GL_INVALID_VALUE GL_INVERT GL_KEEP GL_LEFT GL_LEQUAL GL_LESS GL_LIGHT0 GL_LIGHT1 GL_LIGHT2 GL_LIGHT3 GL_LIGHT4 GL_LIGHT5 GL_LIGHT6 GL_LIGHT7 GL_LIGHTING GL_LIGHTING_BIT GL_LIGHT_MODEL_AMBIENT GL_LIGHT_MODEL_COLOR_CONTROL GL_LIGHT_MODEL_LOCAL_VIEWER GL_LIGHT_MODEL_TWO_SIDE GL_LINE GL_LINEAR GL_LINEAR_ATTENUATION GL_LINEAR_MIPMAP_LINEAR GL_LINEAR_MIPMAP_NEAREST GL_LINES GL_LINE_BIT GL_LINE_LOOP GL_LINE_RESET_TOKEN GL_LINE_SMOOTH GL_LINE_SMOOTH_HINT GL_LINE_STIPPLE GL_LINE_STIPPLE_PATTERN GL_LINE_STIPPLE_REPEAT GL_LINE_STRIP GL_LINE_TOKEN GL_LINE_WIDTH GL_LINE_WIDTH_GRANULARITY GL_LINE_WIDTH_RANGE GL_LINK_STATUS GL_LIST_BASE GL_LIST_BIT GL_LIST_INDEX GL_LIST_MODE GL_LOAD GL_LOGIC_OP GL_LOGIC_OP_MODE GL_LOWER_LEFT GL_LUMINANCE GL_LUMINANCE12 GL_LUMINANCE12_ALPHA12 GL_LUMINANCE12_ALPHA4 GL_LUMINANCE16 GL_LUMINANCE16_ALPHA16 GL_LUMINANCE4 GL_LUMINANCE4_ALPHA4 GL_LUMINANCE6_ALPHA2 GL_LUMINANCE8 GL_LUMINANCE8_ALPHA8 GL_LUMINANCE_ALPHA GL_MAP1_COLOR_4 GL_MAP1_GRID_DOMAIN GL_MAP1_GRID_SEGMENTS GL_MAP1_INDEX GL_MAP1_NORMAL GL_MAP1_TEXTURE_COORD_1 GL_MAP1_TEXTURE_COORD_2 GL_MAP1_TEXTURE_COORD_3 GL_MAP1_TEXTURE_COORD_4 GL_MAP1_VERTEX_3 GL_MAP1_VERTEX_4 GL_MAP2_COLOR_4 GL_MAP2_GRID_DOMAIN GL_MAP2_GRID_SEGMENTS GL_MAP2_INDEX GL_MAP2_NORMAL GL_MAP2_TEXTURE_COORD_1 GL_MAP2_TEXTURE_COORD_2 GL_MAP2_TEXTURE_COORD_3 GL_MAP2_TEXTURE_COORD_4 GL_MAP2_VERTEX_3 GL_MAP2_VERTEX_4 GL_MAP_COLOR GL_MAP_STENCIL GL_MATRIX_MODE GL_MAX GL_MAX_3D_TEXTURE_SIZE GL_MAX_ATTRIB_STACK_DEPTH GL_MAX_CLIENT_ATTRIB_STACK_DEPTH GL_MAX_CLIP_PLANES GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS GL_MAX_CUBE_MAP_TEXTURE_SIZE GL_MAX_DRAW_BUFFERS GL_MAX_ELEMENTS_INDICES GL_MAX_ELEMENTS_VERTICES GL_MAX_EVAL_ORDER GL_MAX_FRAGMENT_UNIFORM_COMPONENTS GL_MAX_LIGHTS GL_MAX_LIST_NESTING GL_MAX_MODELVIEW_STACK_DEPTH GL_MAX_NAME_STACK_DEPTH GL_MAX_PIXEL_MAP_TABLE GL_MAX_PROJECTION_STACK_DEPTH GL_MAX_TEXTURE_COORDS GL_MAX_TEXTURE_IMAGE_UNITS GL_MAX_TEXTURE_LOD_BIAS GL_MAX_TEXTURE_SIZE GL_MAX_TEXTURE_STACK_DEPTH GL_MAX_TEXTURE_UNITS GL_MAX_VARYING_FLOATS GL_MAX_VERTEX_ATTRIBS GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS GL_MAX_VERTEX_UNIFORM_COMPONENTS GL_MAX_VIEWPORT_DIMS GL_MIN GL_MIRRORED_REPEAT GL_MODELVIEW GL_MODELVIEW_MATRIX GL_MODELVIEW_STACK_DEPTH GL_MODULATE GL_MULT GL_MULTISAMPLE GL_MULTISAMPLE_BIT GL_N3F_V3F GL_NAME_STACK_DEPTH GL_NAND GL_NEAREST GL_NEAREST_MIPMAP_LINEAR GL_NEAREST_MIPMAP_NEAREST GL_NEVER GL_NICEST GL_NONE GL_NOOP GL_NOR GL_NORMALIZE GL_NORMAL_ARRAY GL_NORMAL_ARRAY_BUFFER_BINDING GL_NORMAL_ARRAY_POINTER GL_NORMAL_ARRAY_STRIDE GL_NORMAL_ARRAY_TYPE GL_NORMAL_MAP GL_NOTEQUAL GL_NO_ERROR GL_NUM_COMPRESSED_TEXTURE_FORMATS GL_OBJECT_LINEAR GL_OBJECT_PLANE GL_ONE GL_ONE_MINUS_CONSTANT_ALPHA GL_ONE_MINUS_CONSTANT_COLOR GL_ONE_MINUS_DST_ALPHA GL_ONE_MINUS_DST_COLOR GL_ONE_MINUS_SRC_ALPHA GL_ONE_MINUS_SRC_COLOR GL_OPERAND0_ALPHA GL_OPERAND0_RGB GL_OPERAND1_ALPHA GL_OPERAND1_RGB GL_OPERAND2_ALPHA GL_OPERAND2_RGB GL_OR GL_ORDER GL_OR_INVERTED GL_OR_REVERSE GL_OUT_OF_MEMORY GL_PACK_ALIGNMENT GL_PACK_IMAGE_HEIGHT GL_PACK_LSB_FIRST GL_PACK_ROW_LENGTH GL_PACK_SKIP_IMAGES GL_PACK_SKIP_PIXELS GL_PACK_SKIP_ROWS GL_PACK_SWAP_BYTES GL_PASS_THROUGH_TOKEN GL_PERSPECTIVE_CORRECTION_HINT GL_PIXEL_MAP_A_TO_A GL_PIXEL_MAP_A_TO_A_SIZE GL_PIXEL_MAP_B_TO_B GL_PIXEL_MAP_B_TO_B_SIZE GL_PIXEL_MAP_G_TO_G GL_PIXEL_MAP_G_TO_G_SIZE GL_PIXEL_MAP_I_TO_A GL_PIXEL_MAP_I_TO_A_SIZE GL_PIXEL_MAP_I_TO_B GL_PIXEL_MAP_I_TO_B_SIZE GL_PIXEL_MAP_I_TO_G GL_PIXEL_MAP_I_TO_G_SIZE GL_PIXEL_MAP_I_TO_I GL_PIXEL_MAP_I_TO_I_SIZE GL_PIXEL_MAP_I_TO_R GL_PIXEL_MAP_I_TO_R_SIZE GL_PIXEL_MAP_R_TO_R GL_PIXEL_MAP_R_TO_R_SIZE GL_PIXEL_MAP_S_TO_S GL_PIXEL_MAP_S_TO_S_SIZE GL_PIXEL_MODE_BIT GL_PIXEL_PACK_BUFFER GL_PIXEL_PACK_BUFFER_BINDING GL_PIXEL_UNPACK_BUFFER GL_PIXEL_UNPACK_BUFFER_BINDING GL_POINT GL_POINTS GL_POINT_BIT GL_POINT_DISTANCE_ATTENUATION GL_POINT_FADE_THRESHOLD_SIZE GL_POINT_SIZE GL_POINT_SIZE_GRANULARITY GL_POINT_SIZE_MAX GL_POINT_SIZE_MIN GL_POINT_SIZE_RANGE GL_POINT_SMOOTH GL_POINT_SMOOTH_HINT GL_POINT_SPRITE GL_POINT_SPRITE_COORD_ORIGIN GL_POINT_TOKEN GL_POLYGON GL_POLYGON_BIT GL_POLYGON_MODE GL_POLYGON_OFFSET_FACTOR GL_POLYGON_OFFSET_FILL GL_POLYGON_OFFSET_LINE GL_POLYGON_OFFSET_POINT GL_POLYGON_OFFSET_UNITS GL_POLYGON_SMOOTH GL_POLYGON_SMOOTH_HINT GL_POLYGON_STIPPLE GL_POLYGON_STIPPLE_BIT GL_POLYGON_TOKEN GL_POSITION GL_PREVIOUS GL_PRIMARY_COLOR GL_PROJECTION GL_PROJECTION_MATRIX GL_PROJECTION_STACK_DEPTH GL_PROXY_TEXTURE_1D GL_PROXY_TEXTURE_2D GL_PROXY_TEXTURE_3D GL_PROXY_TEXTURE_CUBE_MAP GL_Q GL_QUADRATIC_ATTENUATION GL_QUADS GL_QUAD_STRIP GL_QUERY_COUNTER_BITS GL_QUERY_RESULT GL_QUERY_RESULT_AVAILABLE GL_R GL_R3_G3_B2 GL_READ_BUFFER GL_READ_ONLY GL_READ_WRITE GL_RED GL_RED_BIAS GL_RED_BITS GL_RED_SCALE GL_REFLECTION_MAP GL_RENDER GL_RENDERER GL_RENDER_MODE GL_REPEAT GL_REPLACE GL_RESCALE_NORMAL GL_RETURN GL_RGB GL_RGB10 GL_RGB10_A2 GL_RGB12 GL_RGB16 GL_RGB4 GL_RGB5 GL_RGB5_A1 GL_RGB8 GL_RGBA GL_RGBA12 GL_RGBA16 GL_RGBA2 GL_RGBA4 GL_RGBA8 GL_RGBA_MODE GL_RGB_SCALE GL_RIGHT GL_S GL_SAMPLER_1D GL_SAMPLER_1D_SHADOW GL_SAMPLER_2D GL_SAMPLER_2D_SHADOW GL_SAMPLER_3D GL_SAMPLER_CUBE GL_SAMPLES GL_SAMPLES_PASSED GL_SAMPLE_ALPHA_TO_COVERAGE GL_SAMPLE_ALPHA_TO_ONE GL_SAMPLE_BUFFERS GL_SAMPLE_COVERAGE GL_SAMPLE_COVERAGE_INVERT GL_SAMPLE_COVERAGE_VALUE GL_SCISSOR_BIT GL_SCISSOR_BOX GL_SCISSOR_TEST GL_SECONDARY_COLOR_ARRAY GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING GL_SECONDARY_COLOR_ARRAY_POINTER GL_SECONDARY_COLOR_ARRAY_SIZE GL_SECONDARY_COLOR_ARRAY_STRIDE GL_SECONDARY_COLOR_ARRAY_TYPE GL_SELECT GL_SELECTION_BUFFER_POINTER GL_SELECTION_BUFFER_SIZE GL_SEPARATE_SPECULAR_COLOR GL_SET GL_SHADER_SOURCE_LENGTH GL_SHADER_TYPE GL_SHADE_MODEL GL_SHADING_LANGUAGE_VERSION GL_SHININESS GL_SHORT GL_SINGLE_COLOR GL_SLUMINANCE GL_SLUMINANCE8 GL_SLUMINANCE8_ALPHA8 GL_SLUMINANCE_ALPHA GL_SMOOTH GL_SMOOTH_LINE_WIDTH_GRANULARITY GL_SMOOTH_LINE_WIDTH_RANGE GL_SMOOTH_POINT_SIZE_GRANULARITY GL_SMOOTH_POINT_SIZE_RANGE GL_SOURCE0_ALPHA GL_SOURCE0_RGB GL_SOURCE1_ALPHA GL_SOURCE1_RGB GL_SOURCE2_ALPHA GL_SOURCE2_RGB GL_SPECULAR GL_SPHERE_MAP GL_SPOT_CUTOFF GL_SPOT_DIRECTION GL_SPOT_EXPONENT GL_SRC0_ALPHA GL_SRC0_RGB GL_SRC1_ALPHA GL_SRC1_RGB GL_SRC2_ALPHA GL_SRC2_RGB GL_SRC_ALPHA GL_SRC_ALPHA_SATURATE GL_SRC_COLOR GL_SRGB GL_SRGB8 GL_SRGB8_ALPHA8 GL_SRGB_ALPHA GL_STACK_OVERFLOW GL_STACK_UNDERFLOW GL_STATIC_COPY GL_STATIC_DRAW GL_STATIC_READ GL_STENCIL GL_STENCIL_BACK_FAIL GL_STENCIL_BACK_FUNC GL_STENCIL_BACK_PASS_DEPTH_FAIL GL_STENCIL_BACK_PASS_DEPTH_PASS GL_STENCIL_BACK_REF GL_STENCIL_BACK_VALUE_MASK GL_STENCIL_BACK_WRITEMASK GL_STENCIL_BITS GL_STENCIL_BUFFER_BIT GL_STENCIL_CLEAR_VALUE GL_STENCIL_FAIL GL_STENCIL_FUNC GL_STENCIL_INDEX GL_STENCIL_PASS_DEPTH_FAIL GL_STENCIL_PASS_DEPTH_PASS GL_STENCIL_REF GL_STENCIL_TEST GL_STENCIL_VALUE_MASK GL_STENCIL_WRITEMASK GL_STEREO GL_STREAM_COPY GL_STREAM_DRAW GL_STREAM_READ GL_SUBPIXEL_BITS GL_SUBTRACT GL_T GL_T2F_C3F_V3F GL_T2F_C4F_N3F_V3F GL_T2F_C4UB_V3F GL_T2F_N3F_V3F GL_T2F_V3F GL_T4F_C4F_N3F_V4F GL_T4F_V4F GL_TEXTURE GL_TEXTURE0 GL_TEXTURE1 GL_TEXTURE10 GL_TEXTURE11 GL_TEXTURE12 GL_TEXTURE13 GL_TEXTURE14 GL_TEXTURE15 GL_TEXTURE16 GL_TEXTURE17 GL_TEXTURE18 GL_TEXTURE19 GL_TEXTURE2 GL_TEXTURE20 GL_TEXTURE21 GL_TEXTURE22 GL_TEXTURE23 GL_TEXTURE24 GL_TEXTURE25 GL_TEXTURE26 GL_TEXTURE27 GL_TEXTURE28 GL_TEXTURE29 GL_TEXTURE3 GL_TEXTURE30 GL_TEXTURE31 GL_TEXTURE4 GL_TEXTURE5 GL_TEXTURE6 GL_TEXTURE7 GL_TEXTURE8 GL_TEXTURE9 GL_TEXTURE_1D GL_TEXTURE_2D GL_TEXTURE_3D GL_TEXTURE_ALPHA_SIZE GL_TEXTURE_BASE_LEVEL GL_TEXTURE_BINDING_1D GL_TEXTURE_BINDING_2D GL_TEXTURE_BINDING_3D GL_TEXTURE_BINDING_CUBE_MAP GL_TEXTURE_BIT GL_TEXTURE_BLUE_SIZE GL_TEXTURE_BORDER GL_TEXTURE_BORDER_COLOR GL_TEXTURE_COMPARE_FUNC GL_TEXTURE_COMPARE_MODE GL_TEXTURE_COMPONENTS GL_TEXTURE_COMPRESSED GL_TEXTURE_COMPRESSED_IMAGE_SIZE GL_TEXTURE_COMPRESSION_HINT GL_TEXTURE_COORD_ARRAY GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING GL_TEXTURE_COORD_ARRAY_POINTER GL_TEXTURE_COORD_ARRAY_SIZE GL_TEXTURE_COORD_ARRAY_STRIDE GL_TEXTURE_COORD_ARRAY_TYPE GL_TEXTURE_CUBE_MAP GL_TEXTURE_CUBE_MAP_NEGATIVE_X GL_TEXTURE_CUBE_MAP_NEGATIVE_Y GL_TEXTURE_CUBE_MAP_NEGATIVE_Z GL_TEXTURE_CUBE_MAP_POSITIVE_X GL_TEXTURE_CUBE_MAP_POSITIVE_Y GL_TEXTURE_CUBE_MAP_POSITIVE_Z GL_TEXTURE_DEPTH GL_TEXTURE_DEPTH_SIZE GL_TEXTURE_ENV GL_TEXTURE_ENV_COLOR GL_TEXTURE_ENV_MODE GL_TEXTURE_FILTER_CONTROL GL_TEXTURE_GEN_MODE GL_TEXTURE_GEN_Q GL_TEXTURE_GEN_R GL_TEXTURE_GEN_S GL_TEXTURE_GEN_T GL_TEXTURE_GREEN_SIZE GL_TEXTURE_HEIGHT GL_TEXTURE_INTENSITY_SIZE GL_TEXTURE_INTERNAL_FORMAT GL_TEXTURE_LOD_BIAS GL_TEXTURE_LUMINANCE_SIZE GL_TEXTURE_MAG_FILTER GL_TEXTURE_MATRIX GL_TEXTURE_MAX_LEVEL GL_TEXTURE_MAX_LOD GL_TEXTURE_MIN_FILTER GL_TEXTURE_MIN_LOD GL_TEXTURE_PRIORITY GL_TEXTURE_RED_SIZE GL_TEXTURE_RESIDENT GL_TEXTURE_STACK_DEPTH GL_TEXTURE_WIDTH GL_TEXTURE_WRAP_R GL_TEXTURE_WRAP_S GL_TEXTURE_WRAP_T GL_TRANSFORM_BIT GL_TRANSPOSE_COLOR_MATRIX GL_TRANSPOSE_MODELVIEW_MATRIX GL_TRANSPOSE_PROJECTION_MATRIX GL_TRANSPOSE_TEXTURE_MATRIX GL_TRIANGLES GL_TRIANGLE_FAN GL_TRIANGLE_STRIP GL_TRUE GL_UNPACK_ALIGNMENT GL_UNPACK_IMAGE_HEIGHT GL_UNPACK_LSB_FIRST GL_UNPACK_ROW_LENGTH GL_UNPACK_SKIP_IMAGES GL_UNPACK_SKIP_PIXELS GL_UNPACK_SKIP_ROWS GL_UNPACK_SWAP_BYTES GL_UNSIGNED_BYTE GL_UNSIGNED_BYTE_2_3_3_REV GL_UNSIGNED_BYTE_3_3_2 GL_UNSIGNED_INT GL_UNSIGNED_INT_10_10_10_2 GL_UNSIGNED_INT_2_10_10_10_REV GL_UNSIGNED_INT_8_8_8_8 GL_UNSIGNED_INT_8_8_8_8_REV GL_UNSIGNED_SHORT GL_UNSIGNED_SHORT_1_5_5_5_REV GL_UNSIGNED_SHORT_4_4_4_4 GL_UNSIGNED_SHORT_4_4_4_4_REV GL_UNSIGNED_SHORT_5_5_5_1 GL_UNSIGNED_SHORT_5_6_5 GL_UNSIGNED_SHORT_5_6_5_REV GL_UPPER_LEFT GL_V2F GL_V3F GL_VALIDATE_STATUS GL_VENDOR GL_VERSION GL_VERTEX_ARRAY GL_VERTEX_ARRAY_BUFFER_BINDING GL_VERTEX_ARRAY_POINTER GL_VERTEX_ARRAY_SIZE GL_VERTEX_ARRAY_STRIDE GL_VERTEX_ARRAY_TYPE GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING GL_VERTEX_ATTRIB_ARRAY_ENABLED GL_VERTEX_ATTRIB_ARRAY_NORMALIZED GL_VERTEX_ATTRIB_ARRAY_POINTER GL_VERTEX_ATTRIB_ARRAY_SIZE GL_VERTEX_ATTRIB_ARRAY_STRIDE GL_VERTEX_ATTRIB_ARRAY_TYPE GL_VERTEX_PROGRAM_POINT_SIZE GL_VERTEX_PROGRAM_TWO_SIDE GL_VERTEX_SHADER GL_VIEWPORT GL_VIEWPORT_BIT GL_WEIGHT_ARRAY_BUFFER_BINDING GL_WRITE_ONLY GL_XOR GL_ZERO GL_ZOOM_X GL_ZOOM_Y ) (import (rnrs base(6)) (only (chezscheme) foreign-procedure load-shared-object)) (define libGL (load-shared-object "libGL.so.1")) (define glAccum (foreign-procedure "glAccum" (unsigned-int float) void)) (define glActiveTexture (foreign-procedure "glActiveTexture" (unsigned-int) void)) (define glAlphaFunc (foreign-procedure "glAlphaFunc" (unsigned-int float) void)) (define glAreTexturesResident (foreign-procedure "glAreTexturesResident" (int uptr string) unsigned-8)) (define glArrayElement (foreign-procedure "glArrayElement" (int) void)) (define glAttachShader (foreign-procedure "glAttachShader" (unsigned-int unsigned-int) void)) (define glBegin (foreign-procedure "glBegin" (unsigned-int) void)) (define glBeginQuery (foreign-procedure "glBeginQuery" (unsigned-int unsigned-int) void)) (define glBindAttribLocation (foreign-procedure "glBindAttribLocation" (unsigned-int unsigned-int string) void)) (define glBindBuffer (foreign-procedure "glBindBuffer" (unsigned-int unsigned-int) void)) (define glBindTexture (foreign-procedure "glBindTexture" (unsigned-int unsigned-int) void)) (define glBitmap (foreign-procedure "glBitmap" (int int float float float float string) void)) (define glBlendColor (foreign-procedure "glBlendColor" (float float float float) void)) (define glBlendEquation (foreign-procedure "glBlendEquation" (unsigned-int) void)) (define glBlendEquationSeparate (foreign-procedure "glBlendEquationSeparate" (unsigned-int unsigned-int) void)) (define glBlendFunc (foreign-procedure "glBlendFunc" (unsigned-int unsigned-int) void)) (define glBlendFuncSeparate (foreign-procedure "glBlendFuncSeparate" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glBufferData (foreign-procedure "glBufferData" (unsigned-int ptrdiff_t uptr unsigned-int) void)) (define glBufferSubData (foreign-procedure "glBufferSubData" (unsigned-int ptrdiff_t ptrdiff_t uptr) void)) (define glCallList (foreign-procedure "glCallList" (unsigned-int) void)) (define glCallLists (foreign-procedure "glCallLists" (int unsigned-int uptr) void)) (define glClear (foreign-procedure "glClear" (unsigned-int) void)) (define glClearAccum (foreign-procedure "glClearAccum" (float float float float) void)) (define glClearColor (foreign-procedure "glClearColor" (float float float float) void)) (define glClearDepth (foreign-procedure "glClearDepth" (double) void)) (define glClearIndex (foreign-procedure "glClearIndex" (float) void)) (define glClearStencil (foreign-procedure "glClearStencil" (int) void)) (define glClientActiveTexture (foreign-procedure "glClientActiveTexture" (unsigned-int) void)) (define glClipPlane (foreign-procedure "glClipPlane" (unsigned-int uptr) void)) (define glColor3b (foreign-procedure "glColor3b" (integer-8 integer-8 integer-8) void)) (define glColor3bv (foreign-procedure "glColor3bv" (string) void)) (define glColor3d (foreign-procedure "glColor3d" (double double double) void)) (define glColor3dv (foreign-procedure "glColor3dv" (uptr) void)) (define glColor3f (foreign-procedure "glColor3f" (float float float) void)) (define glColor3fv (foreign-procedure "glColor3fv" (uptr) void)) (define glColor3i (foreign-procedure "glColor3i" (int int int) void)) (define glColor3iv (foreign-procedure "glColor3iv" (uptr) void)) (define glColor3s (foreign-procedure "glColor3s" (short short short) void)) (define glColor3sv (foreign-procedure "glColor3sv" (uptr) void)) (define glColor3ub (foreign-procedure "glColor3ub" (unsigned-8 unsigned-8 unsigned-8) void)) (define glColor3ubv (foreign-procedure "glColor3ubv" (string) void)) (define glColor3ui (foreign-procedure "glColor3ui" (unsigned-int unsigned-int unsigned-int) void)) (define glColor3uiv (foreign-procedure "glColor3uiv" (uptr) void)) (define glColor3us (foreign-procedure "glColor3us" (unsigned-short unsigned-short unsigned-short) void)) (define glColor3usv (foreign-procedure "glColor3usv" (uptr) void)) (define glColor4b (foreign-procedure "glColor4b" (integer-8 integer-8 integer-8 integer-8) void)) (define glColor4bv (foreign-procedure "glColor4bv" (string) void)) (define glColor4d (foreign-procedure "glColor4d" (double double double double) void)) (define glColor4dv (foreign-procedure "glColor4dv" (uptr) void)) (define glColor4f (foreign-procedure "glColor4f" (float float float float) void)) (define glColor4fv (foreign-procedure "glColor4fv" (uptr) void)) (define glColor4i (foreign-procedure "glColor4i" (int int int int) void)) (define glColor4iv (foreign-procedure "glColor4iv" (uptr) void)) (define glColor4s (foreign-procedure "glColor4s" (short short short short) void)) (define glColor4sv (foreign-procedure "glColor4sv" (uptr) void)) (define glColor4ub (foreign-procedure "glColor4ub" (unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glColor4ubv (foreign-procedure "glColor4ubv" (string) void)) (define glColor4ui (foreign-procedure "glColor4ui" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glColor4uiv (foreign-procedure "glColor4uiv" (uptr) void)) (define glColor4us (foreign-procedure "glColor4us" (unsigned-short unsigned-short unsigned-short unsigned-short) void)) (define glColor4usv (foreign-procedure "glColor4usv" (uptr) void)) (define glColorMask (foreign-procedure "glColorMask" (unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glColorMaterial (foreign-procedure "glColorMaterial" (unsigned-int unsigned-int) void)) (define glColorPointer (foreign-procedure "glColorPointer" (int unsigned-int int uptr) void)) (define glCompileShader (foreign-procedure "glCompileShader" (unsigned-int) void)) (define glCompressedTexImage1D (foreign-procedure "glCompressedTexImage1D" (unsigned-int int unsigned-int int int int uptr) void)) (define glCompressedTexImage2D (foreign-procedure "glCompressedTexImage2D" (unsigned-int int unsigned-int int int int int uptr) void)) (define glCompressedTexImage3D (foreign-procedure "glCompressedTexImage3D" (unsigned-int int unsigned-int int int int int int uptr) void)) (define glCompressedTexSubImage1D (foreign-procedure "glCompressedTexSubImage1D" (unsigned-int int int int unsigned-int int uptr) void)) (define glCompressedTexSubImage2D (foreign-procedure "glCompressedTexSubImage2D" (unsigned-int int int int int int unsigned-int int uptr) void)) (define glCompressedTexSubImage3D (foreign-procedure "glCompressedTexSubImage3D" (unsigned-int int int int int int int int unsigned-int int uptr) void)) (define glCopyPixels (foreign-procedure "glCopyPixels" (int int int int unsigned-int) void)) (define glCopyTexImage1D (foreign-procedure "glCopyTexImage1D" (unsigned-int int unsigned-int int int int int) void)) (define glCopyTexImage2D (foreign-procedure "glCopyTexImage2D" (unsigned-int int unsigned-int int int int int int) void)) (define glCopyTexSubImage1D (foreign-procedure "glCopyTexSubImage1D" (unsigned-int int int int int int) void)) (define glCopyTexSubImage2D (foreign-procedure "glCopyTexSubImage2D" (unsigned-int int int int int int int int) void)) (define glCopyTexSubImage3D (foreign-procedure "glCopyTexSubImage3D" (unsigned-int int int int int int int int int) void)) (define glCreateProgram (foreign-procedure "glCreateProgram" () unsigned-int)) (define glCreateShader (foreign-procedure "glCreateShader" (unsigned-int) unsigned-int)) (define glCullFace (foreign-procedure "glCullFace" (unsigned-int) void)) (define glDeleteBuffers (foreign-procedure "glDeleteBuffers" (int uptr) void)) (define glDeleteLists (foreign-procedure "glDeleteLists" (unsigned-int int) void)) (define glDeleteProgram (foreign-procedure "glDeleteProgram" (unsigned-int) void)) (define glDeleteQueries (foreign-procedure "glDeleteQueries" (int uptr) void)) (define glDeleteShader (foreign-procedure "glDeleteShader" (unsigned-int) void)) (define glDeleteTextures (foreign-procedure "glDeleteTextures" (int uptr) void)) (define glDepthFunc (foreign-procedure "glDepthFunc" (unsigned-int) void)) (define glDepthMask (foreign-procedure "glDepthMask" (unsigned-8) void)) (define glDepthRange (foreign-procedure "glDepthRange" (double double) void)) (define glDetachShader (foreign-procedure "glDetachShader" (unsigned-int unsigned-int) void)) (define glDisable (foreign-procedure "glDisable" (unsigned-int) void)) (define glDisableClientState (foreign-procedure "glDisableClientState" (unsigned-int) void)) (define glDisableVertexAttribArray (foreign-procedure "glDisableVertexAttribArray" (unsigned-int) void)) (define glDrawArrays (foreign-procedure "glDrawArrays" (unsigned-int int int) void)) (define glDrawBuffer (foreign-procedure "glDrawBuffer" (unsigned-int) void)) (define glDrawBuffers (foreign-procedure "glDrawBuffers" (int uptr) void)) (define glDrawElements (foreign-procedure "glDrawElements" (unsigned-int int unsigned-int uptr) void)) (define glDrawPixels (foreign-procedure "glDrawPixels" (int int unsigned-int unsigned-int uptr) void)) (define glDrawRangeElements (foreign-procedure "glDrawRangeElements" (unsigned-int unsigned-int unsigned-int int unsigned-int uptr) void)) (define glEdgeFlag (foreign-procedure "glEdgeFlag" (unsigned-8) void)) (define glEdgeFlagPointer (foreign-procedure "glEdgeFlagPointer" (int uptr) void)) (define glEdgeFlagv (foreign-procedure "glEdgeFlagv" (string) void)) (define glEnable (foreign-procedure "glEnable" (unsigned-int) void)) (define glEnableClientState (foreign-procedure "glEnableClientState" (unsigned-int) void)) (define glEnableVertexAttribArray (foreign-procedure "glEnableVertexAttribArray" (unsigned-int) void)) (define glEnd (foreign-procedure "glEnd" () void)) (define glEndList (foreign-procedure "glEndList" () void)) (define glEndQuery (foreign-procedure "glEndQuery" (unsigned-int) void)) (define glEvalCoord1d (foreign-procedure "glEvalCoord1d" (double) void)) (define glEvalCoord1dv (foreign-procedure "glEvalCoord1dv" (uptr) void)) (define glEvalCoord1f (foreign-procedure "glEvalCoord1f" (float) void)) (define glEvalCoord1fv (foreign-procedure "glEvalCoord1fv" (uptr) void)) (define glEvalCoord2d (foreign-procedure "glEvalCoord2d" (double double) void)) (define glEvalCoord2dv (foreign-procedure "glEvalCoord2dv" (uptr) void)) (define glEvalCoord2f (foreign-procedure "glEvalCoord2f" (float float) void)) (define glEvalCoord2fv (foreign-procedure "glEvalCoord2fv" (uptr) void)) (define glEvalMesh1 (foreign-procedure "glEvalMesh1" (unsigned-int int int) void)) (define glEvalMesh2 (foreign-procedure "glEvalMesh2" (unsigned-int int int int int) void)) (define glEvalPoint1 (foreign-procedure "glEvalPoint1" (int) void)) (define glEvalPoint2 (foreign-procedure "glEvalPoint2" (int int) void)) (define glFeedbackBuffer (foreign-procedure "glFeedbackBuffer" (int unsigned-int uptr) void)) (define glFinish (foreign-procedure "glFinish" () void)) (define glFlush (foreign-procedure "glFlush" () void)) (define glFogCoordPointer (foreign-procedure "glFogCoordPointer" (unsigned-int int uptr) void)) (define glFogCoordd (foreign-procedure "glFogCoordd" (double) void)) (define glFogCoorddv (foreign-procedure "glFogCoorddv" (uptr) void)) (define glFogCoordf (foreign-procedure "glFogCoordf" (float) void)) (define glFogCoordfv (foreign-procedure "glFogCoordfv" (uptr) void)) (define glFogf (foreign-procedure "glFogf" (unsigned-int float) void)) (define glFogfv (foreign-procedure "glFogfv" (unsigned-int uptr) void)) (define glFogi (foreign-procedure "glFogi" (unsigned-int int) void)) (define glFogiv (foreign-procedure "glFogiv" (unsigned-int uptr) void)) (define glFrontFace (foreign-procedure "glFrontFace" (unsigned-int) void)) (define glFrustum (foreign-procedure "glFrustum" (double double double double double double) void)) (define glGenBuffers (foreign-procedure "glGenBuffers" (int uptr) void)) (define glGenLists (foreign-procedure "glGenLists" (int) unsigned-int)) (define glGenQueries (foreign-procedure "glGenQueries" (int uptr) void)) (define glGenTextures (foreign-procedure "glGenTextures" (int uptr) void)) (define glGetActiveAttrib (foreign-procedure "glGetActiveAttrib" (unsigned-int unsigned-int int uptr uptr uptr string) void)) (define glGetActiveUniform (foreign-procedure "glGetActiveUniform" (unsigned-int unsigned-int int uptr uptr uptr string) void)) (define glGetAttachedShaders (foreign-procedure "glGetAttachedShaders" (unsigned-int int uptr uptr) void)) (define glGetAttribLocation (foreign-procedure "glGetAttribLocation" (unsigned-int string) int)) (define glGetBooleanv (foreign-procedure "glGetBooleanv" (unsigned-int string) void)) (define glGetBufferParameteriv (foreign-procedure "glGetBufferParameteriv" (unsigned-int unsigned-int uptr) void)) (define glGetBufferPointerv (foreign-procedure "glGetBufferPointerv" (unsigned-int unsigned-int uptr) void)) (define glGetBufferSubData (foreign-procedure "glGetBufferSubData" (unsigned-int ptrdiff_t ptrdiff_t uptr) void)) (define glGetClipPlane (foreign-procedure "glGetClipPlane" (unsigned-int uptr) void)) (define glGetCompressedTexImage (foreign-procedure "glGetCompressedTexImage" (unsigned-int int uptr) void)) (define glGetDoublev (foreign-procedure "glGetDoublev" (unsigned-int uptr) void)) (define glGetError (foreign-procedure "glGetError" () unsigned-int)) (define glGetFloatv (foreign-procedure "glGetFloatv" (unsigned-int uptr) void)) (define glGetIntegerv (foreign-procedure "glGetIntegerv" (unsigned-int uptr) void)) (define glGetLightfv (foreign-procedure "glGetLightfv" (unsigned-int unsigned-int uptr) void)) (define glGetLightiv (foreign-procedure "glGetLightiv" (unsigned-int unsigned-int uptr) void)) (define glGetMapdv (foreign-procedure "glGetMapdv" (unsigned-int unsigned-int uptr) void)) (define glGetMapfv (foreign-procedure "glGetMapfv" (unsigned-int unsigned-int uptr) void)) (define glGetMapiv (foreign-procedure "glGetMapiv" (unsigned-int unsigned-int uptr) void)) (define glGetMaterialfv (foreign-procedure "glGetMaterialfv" (unsigned-int unsigned-int uptr) void)) (define glGetMaterialiv (foreign-procedure "glGetMaterialiv" (unsigned-int unsigned-int uptr) void)) (define glGetPixelMapfv (foreign-procedure "glGetPixelMapfv" (unsigned-int uptr) void)) (define glGetPixelMapuiv (foreign-procedure "glGetPixelMapuiv" (unsigned-int uptr) void)) (define glGetPixelMapusv (foreign-procedure "glGetPixelMapusv" (unsigned-int uptr) void)) (define glGetPointerv (foreign-procedure "glGetPointerv" (unsigned-int uptr) void)) (define glGetPolygonStipple (foreign-procedure "glGetPolygonStipple" (string) void)) (define glGetProgramInfoLog (foreign-procedure "glGetProgramInfoLog" (unsigned-int int uptr string) void)) (define glGetProgramiv (foreign-procedure "glGetProgramiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryObjectiv (foreign-procedure "glGetQueryObjectiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryObjectuiv (foreign-procedure "glGetQueryObjectuiv" (unsigned-int unsigned-int uptr) void)) (define glGetQueryiv (foreign-procedure "glGetQueryiv" (unsigned-int unsigned-int uptr) void)) (define glGetShaderInfoLog (foreign-procedure "glGetShaderInfoLog" (unsigned-int int uptr string) void)) (define glGetShaderSource (foreign-procedure "glGetShaderSource" (unsigned-int int uptr string) void)) (define glGetShaderiv (foreign-procedure "glGetShaderiv" (unsigned-int unsigned-int uptr) void)) (define glGetString (foreign-procedure "glGetString" (unsigned-int) string)) (define glGetTexEnvfv (foreign-procedure "glGetTexEnvfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexEnviv (foreign-procedure "glGetTexEnviv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGendv (foreign-procedure "glGetTexGendv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGenfv (foreign-procedure "glGetTexGenfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexGeniv (foreign-procedure "glGetTexGeniv" (unsigned-int unsigned-int uptr) void)) (define glGetTexImage (foreign-procedure "glGetTexImage" (unsigned-int int unsigned-int unsigned-int uptr) void)) (define glGetTexLevelParameterfv (foreign-procedure "glGetTexLevelParameterfv" (unsigned-int int unsigned-int uptr) void)) (define glGetTexLevelParameteriv (foreign-procedure "glGetTexLevelParameteriv" (unsigned-int int unsigned-int uptr) void)) (define glGetTexParameterfv (foreign-procedure "glGetTexParameterfv" (unsigned-int unsigned-int uptr) void)) (define glGetTexParameteriv (foreign-procedure "glGetTexParameteriv" (unsigned-int unsigned-int uptr) void)) (define glGetUniformLocation (foreign-procedure "glGetUniformLocation" (unsigned-int string) int)) (define glGetUniformfv (foreign-procedure "glGetUniformfv" (unsigned-int int uptr) void)) (define glGetUniformiv (foreign-procedure "glGetUniformiv" (unsigned-int int uptr) void)) (define glGetVertexAttribPointerv (foreign-procedure "glGetVertexAttribPointerv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribdv (foreign-procedure "glGetVertexAttribdv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribfv (foreign-procedure "glGetVertexAttribfv" (unsigned-int unsigned-int uptr) void)) (define glGetVertexAttribiv (foreign-procedure "glGetVertexAttribiv" (unsigned-int unsigned-int uptr) void)) (define glHint (foreign-procedure "glHint" (unsigned-int unsigned-int) void)) (define glIndexMask (foreign-procedure "glIndexMask" (unsigned-int) void)) (define glIndexPointer (foreign-procedure "glIndexPointer" (unsigned-int int uptr) void)) (define glIndexd (foreign-procedure "glIndexd" (double) void)) (define glIndexdv (foreign-procedure "glIndexdv" (uptr) void)) (define glIndexf (foreign-procedure "glIndexf" (float) void)) (define glIndexfv (foreign-procedure "glIndexfv" (uptr) void)) (define glIndexi (foreign-procedure "glIndexi" (int) void)) (define glIndexiv (foreign-procedure "glIndexiv" (uptr) void)) (define glIndexs (foreign-procedure "glIndexs" (short) void)) (define glIndexsv (foreign-procedure "glIndexsv" (uptr) void)) (define glIndexub (foreign-procedure "glIndexub" (unsigned-8) void)) (define glIndexubv (foreign-procedure "glIndexubv" (string) void)) (define glInitNames (foreign-procedure "glInitNames" () void)) (define glInterleavedArrays (foreign-procedure "glInterleavedArrays" (unsigned-int int uptr) void)) (define glIsBuffer (foreign-procedure "glIsBuffer" (unsigned-int) unsigned-8)) (define glIsEnabled (foreign-procedure "glIsEnabled" (unsigned-int) unsigned-8)) (define glIsList (foreign-procedure "glIsList" (unsigned-int) unsigned-8)) (define glIsProgram (foreign-procedure "glIsProgram" (unsigned-int) unsigned-8)) (define glIsQuery (foreign-procedure "glIsQuery" (unsigned-int) unsigned-8)) (define glIsShader (foreign-procedure "glIsShader" (unsigned-int) unsigned-8)) (define glIsTexture (foreign-procedure "glIsTexture" (unsigned-int) unsigned-8)) (define glLightModelf (foreign-procedure "glLightModelf" (unsigned-int float) void)) (define glLightModelfv (foreign-procedure "glLightModelfv" (unsigned-int uptr) void)) (define glLightModeli (foreign-procedure "glLightModeli" (unsigned-int int) void)) (define glLightModeliv (foreign-procedure "glLightModeliv" (unsigned-int uptr) void)) (define glLightf (foreign-procedure "glLightf" (unsigned-int unsigned-int float) void)) (define glLightfv (foreign-procedure "glLightfv" (unsigned-int unsigned-int uptr) void)) (define glLighti (foreign-procedure "glLighti" (unsigned-int unsigned-int int) void)) (define glLightiv (foreign-procedure "glLightiv" (unsigned-int unsigned-int uptr) void)) (define glLineStipple (foreign-procedure "glLineStipple" (int unsigned-short) void)) (define glLineWidth (foreign-procedure "glLineWidth" (float) void)) (define glLinkProgram (foreign-procedure "glLinkProgram" (unsigned-int) void)) (define glListBase (foreign-procedure "glListBase" (unsigned-int) void)) (define glLoadIdentity (foreign-procedure "glLoadIdentity" () void)) (define glLoadMatrixd (foreign-procedure "glLoadMatrixd" (uptr) void)) (define glLoadMatrixf (foreign-procedure "glLoadMatrixf" (uptr) void)) (define glLoadName (foreign-procedure "glLoadName" (unsigned-int) void)) (define glLoadTransposeMatrixd (foreign-procedure "glLoadTransposeMatrixd" (uptr) void)) (define glLoadTransposeMatrixf (foreign-procedure "glLoadTransposeMatrixf" (uptr) void)) (define glLogicOp (foreign-procedure "glLogicOp" (unsigned-int) void)) (define glMap1d (foreign-procedure "glMap1d" (unsigned-int double double int int uptr) void)) (define glMap1f (foreign-procedure "glMap1f" (unsigned-int float float int int uptr) void)) (define glMap2d (foreign-procedure "glMap2d" (unsigned-int double double int int double double int int uptr) void)) (define glMap2f (foreign-procedure "glMap2f" (unsigned-int float float int int float float int int uptr) void)) (define glMapBuffer (foreign-procedure "glMapBuffer" (unsigned-int unsigned-int) uptr)) (define glMapGrid1d (foreign-procedure "glMapGrid1d" (int double double) void)) (define glMapGrid1f (foreign-procedure "glMapGrid1f" (int float float) void)) (define glMapGrid2d (foreign-procedure "glMapGrid2d" (int double double int double double) void)) (define glMapGrid2f (foreign-procedure "glMapGrid2f" (int float float int float float) void)) (define glMaterialf (foreign-procedure "glMaterialf" (unsigned-int unsigned-int float) void)) (define glMaterialfv (foreign-procedure "glMaterialfv" (unsigned-int unsigned-int uptr) void)) (define glMateriali (foreign-procedure "glMateriali" (unsigned-int unsigned-int int) void)) (define glMaterialiv (foreign-procedure "glMaterialiv" (unsigned-int unsigned-int uptr) void)) (define glMatrixMode (foreign-procedure "glMatrixMode" (unsigned-int) void)) (define glMultMatrixd (foreign-procedure "glMultMatrixd" (uptr) void)) (define glMultMatrixf (foreign-procedure "glMultMatrixf" (uptr) void)) (define glMultTransposeMatrixd (foreign-procedure "glMultTransposeMatrixd" (uptr) void)) (define glMultTransposeMatrixf (foreign-procedure "glMultTransposeMatrixf" (uptr) void)) (define glMultiDrawArrays (foreign-procedure "glMultiDrawArrays" (unsigned-int uptr uptr int) void)) (define glMultiDrawElements (foreign-procedure "glMultiDrawElements" (unsigned-int uptr unsigned-int uptr int) void)) (define glMultiTexCoord1d (foreign-procedure "glMultiTexCoord1d" (unsigned-int double) void)) (define glMultiTexCoord1dv (foreign-procedure "glMultiTexCoord1dv" (unsigned-int uptr) void)) (define glMultiTexCoord1f (foreign-procedure "glMultiTexCoord1f" (unsigned-int float) void)) (define glMultiTexCoord1fv (foreign-procedure "glMultiTexCoord1fv" (unsigned-int uptr) void)) (define glMultiTexCoord1i (foreign-procedure "glMultiTexCoord1i" (unsigned-int int) void)) (define glMultiTexCoord1iv (foreign-procedure "glMultiTexCoord1iv" (unsigned-int uptr) void)) (define glMultiTexCoord1s (foreign-procedure "glMultiTexCoord1s" (unsigned-int short) void)) (define glMultiTexCoord1sv (foreign-procedure "glMultiTexCoord1sv" (unsigned-int uptr) void)) (define glMultiTexCoord2d (foreign-procedure "glMultiTexCoord2d" (unsigned-int double double) void)) (define glMultiTexCoord2dv (foreign-procedure "glMultiTexCoord2dv" (unsigned-int uptr) void)) (define glMultiTexCoord2f (foreign-procedure "glMultiTexCoord2f" (unsigned-int float float) void)) (define glMultiTexCoord2fv (foreign-procedure "glMultiTexCoord2fv" (unsigned-int uptr) void)) (define glMultiTexCoord2i (foreign-procedure "glMultiTexCoord2i" (unsigned-int int int) void)) (define glMultiTexCoord2iv (foreign-procedure "glMultiTexCoord2iv" (unsigned-int uptr) void)) (define glMultiTexCoord2s (foreign-procedure "glMultiTexCoord2s" (unsigned-int short short) void)) (define glMultiTexCoord2sv (foreign-procedure "glMultiTexCoord2sv" (unsigned-int uptr) void)) (define glMultiTexCoord3d (foreign-procedure "glMultiTexCoord3d" (unsigned-int double double double) void)) (define glMultiTexCoord3dv (foreign-procedure "glMultiTexCoord3dv" (unsigned-int uptr) void)) (define glMultiTexCoord3f (foreign-procedure "glMultiTexCoord3f" (unsigned-int float float float) void)) (define glMultiTexCoord3fv (foreign-procedure "glMultiTexCoord3fv" (unsigned-int uptr) void)) (define glMultiTexCoord3i (foreign-procedure "glMultiTexCoord3i" (unsigned-int int int int) void)) (define glMultiTexCoord3iv (foreign-procedure "glMultiTexCoord3iv" (unsigned-int uptr) void)) (define glMultiTexCoord3s (foreign-procedure "glMultiTexCoord3s" (unsigned-int short short short) void)) (define glMultiTexCoord3sv (foreign-procedure "glMultiTexCoord3sv" (unsigned-int uptr) void)) (define glMultiTexCoord4d (foreign-procedure "glMultiTexCoord4d" (unsigned-int double double double double) void)) (define glMultiTexCoord4dv (foreign-procedure "glMultiTexCoord4dv" (unsigned-int uptr) void)) (define glMultiTexCoord4f (foreign-procedure "glMultiTexCoord4f" (unsigned-int float float float float) void)) (define glMultiTexCoord4fv (foreign-procedure "glMultiTexCoord4fv" (unsigned-int uptr) void)) (define glMultiTexCoord4i (foreign-procedure "glMultiTexCoord4i" (unsigned-int int int int int) void)) (define glMultiTexCoord4iv (foreign-procedure "glMultiTexCoord4iv" (unsigned-int uptr) void)) (define glMultiTexCoord4s (foreign-procedure "glMultiTexCoord4s" (unsigned-int short short short short) void)) (define glMultiTexCoord4sv (foreign-procedure "glMultiTexCoord4sv" (unsigned-int uptr) void)) (define glNewList (foreign-procedure "glNewList" (unsigned-int unsigned-int) void)) (define glNormal3b (foreign-procedure "glNormal3b" (integer-8 integer-8 integer-8) void)) (define glNormal3bv (foreign-procedure "glNormal3bv" (string) void)) (define glNormal3d (foreign-procedure "glNormal3d" (double double double) void)) (define glNormal3dv (foreign-procedure "glNormal3dv" (uptr) void)) (define glNormal3f (foreign-procedure "glNormal3f" (float float float) void)) (define glNormal3fv (foreign-procedure "glNormal3fv" (uptr) void)) (define glNormal3i (foreign-procedure "glNormal3i" (int int int) void)) (define glNormal3iv (foreign-procedure "glNormal3iv" (uptr) void)) (define glNormal3s (foreign-procedure "glNormal3s" (short short short) void)) (define glNormal3sv (foreign-procedure "glNormal3sv" (uptr) void)) (define glNormalPointer (foreign-procedure "glNormalPointer" (unsigned-int int uptr) void)) (define glOrtho (foreign-procedure "glOrtho" (double double double double double double) void)) (define glPassThrough (foreign-procedure "glPassThrough" (float) void)) (define glPixelMapfv (foreign-procedure "glPixelMapfv" (unsigned-int int uptr) void)) (define glPixelMapuiv (foreign-procedure "glPixelMapuiv" (unsigned-int int uptr) void)) (define glPixelMapusv (foreign-procedure "glPixelMapusv" (unsigned-int int uptr) void)) (define glPixelStoref (foreign-procedure "glPixelStoref" (unsigned-int float) void)) (define glPixelStorei (foreign-procedure "glPixelStorei" (unsigned-int int) void)) (define glPixelTransferf (foreign-procedure "glPixelTransferf" (unsigned-int float) void)) (define glPixelTransferi (foreign-procedure "glPixelTransferi" (unsigned-int int) void)) (define glPixelZoom (foreign-procedure "glPixelZoom" (float float) void)) (define glPointParameterf (foreign-procedure "glPointParameterf" (unsigned-int float) void)) (define glPointParameterfv (foreign-procedure "glPointParameterfv" (unsigned-int uptr) void)) (define glPointParameteri (foreign-procedure "glPointParameteri" (unsigned-int int) void)) (define glPointParameteriv (foreign-procedure "glPointParameteriv" (unsigned-int uptr) void)) (define glPointSize (foreign-procedure "glPointSize" (float) void)) (define glPolygonMode (foreign-procedure "glPolygonMode" (unsigned-int unsigned-int) void)) (define glPolygonOffset (foreign-procedure "glPolygonOffset" (float float) void)) (define glPolygonStipple (foreign-procedure "glPolygonStipple" (string) void)) (define glPopAttrib (foreign-procedure "glPopAttrib" () void)) (define glPopClientAttrib (foreign-procedure "glPopClientAttrib" () void)) (define glPopMatrix (foreign-procedure "glPopMatrix" () void)) (define glPopName (foreign-procedure "glPopName" () void)) (define glPrioritizeTextures (foreign-procedure "glPrioritizeTextures" (int uptr uptr) void)) (define glPushAttrib (foreign-procedure "glPushAttrib" (unsigned-int) void)) (define glPushClientAttrib (foreign-procedure "glPushClientAttrib" (unsigned-int) void)) (define glPushMatrix (foreign-procedure "glPushMatrix" () void)) (define glPushName (foreign-procedure "glPushName" (unsigned-int) void)) (define glRasterPos2d (foreign-procedure "glRasterPos2d" (double double) void)) (define glRasterPos2dv (foreign-procedure "glRasterPos2dv" (uptr) void)) (define glRasterPos2f (foreign-procedure "glRasterPos2f" (float float) void)) (define glRasterPos2fv (foreign-procedure "glRasterPos2fv" (uptr) void)) (define glRasterPos2i (foreign-procedure "glRasterPos2i" (int int) void)) (define glRasterPos2iv (foreign-procedure "glRasterPos2iv" (uptr) void)) (define glRasterPos2s (foreign-procedure "glRasterPos2s" (short short) void)) (define glRasterPos2sv (foreign-procedure "glRasterPos2sv" (uptr) void)) (define glRasterPos3d (foreign-procedure "glRasterPos3d" (double double double) void)) (define glRasterPos3dv (foreign-procedure "glRasterPos3dv" (uptr) void)) (define glRasterPos3f (foreign-procedure "glRasterPos3f" (float float float) void)) (define glRasterPos3fv (foreign-procedure "glRasterPos3fv" (uptr) void)) (define glRasterPos3i (foreign-procedure "glRasterPos3i" (int int int) void)) (define glRasterPos3iv (foreign-procedure "glRasterPos3iv" (uptr) void)) (define glRasterPos3s (foreign-procedure "glRasterPos3s" (short short short) void)) (define glRasterPos3sv (foreign-procedure "glRasterPos3sv" (uptr) void)) (define glRasterPos4d (foreign-procedure "glRasterPos4d" (double double double double) void)) (define glRasterPos4dv (foreign-procedure "glRasterPos4dv" (uptr) void)) (define glRasterPos4f (foreign-procedure "glRasterPos4f" (float float float float) void)) (define glRasterPos4fv (foreign-procedure "glRasterPos4fv" (uptr) void)) (define glRasterPos4i (foreign-procedure "glRasterPos4i" (int int int int) void)) (define glRasterPos4iv (foreign-procedure "glRasterPos4iv" (uptr) void)) (define glRasterPos4s (foreign-procedure "glRasterPos4s" (short short short short) void)) (define glRasterPos4sv (foreign-procedure "glRasterPos4sv" (uptr) void)) (define glReadBuffer (foreign-procedure "glReadBuffer" (unsigned-int) void)) (define glReadPixels (foreign-procedure "glReadPixels" (int int int int unsigned-int unsigned-int uptr) void)) (define glRectd (foreign-procedure "glRectd" (double double double double) void)) (define glRectdv (foreign-procedure "glRectdv" (uptr uptr) void)) (define glRectf (foreign-procedure "glRectf" (float float float float) void)) (define glRectfv (foreign-procedure "glRectfv" (uptr uptr) void)) (define glRecti (foreign-procedure "glRecti" (int int int int) void)) (define glRectiv (foreign-procedure "glRectiv" (uptr uptr) void)) (define glRects (foreign-procedure "glRects" (short short short short) void)) (define glRectsv (foreign-procedure "glRectsv" (uptr uptr) void)) (define glRenderMode (foreign-procedure "glRenderMode" (unsigned-int) int)) (define glRotated (foreign-procedure "glRotated" (double double double double) void)) (define glRotatef (foreign-procedure "glRotatef" (float float float float) void)) (define glSampleCoverage (foreign-procedure "glSampleCoverage" (float unsigned-8) void)) (define glScaled (foreign-procedure "glScaled" (double double double) void)) (define glScalef (foreign-procedure "glScalef" (float float float) void)) (define glScissor (foreign-procedure "glScissor" (int int int int) void)) (define glSecondaryColor3b (foreign-procedure "glSecondaryColor3b" (integer-8 integer-8 integer-8) void)) (define glSecondaryColor3bv (foreign-procedure "glSecondaryColor3bv" (string) void)) (define glSecondaryColor3d (foreign-procedure "glSecondaryColor3d" (double double double) void)) (define glSecondaryColor3dv (foreign-procedure "glSecondaryColor3dv" (uptr) void)) (define glSecondaryColor3f (foreign-procedure "glSecondaryColor3f" (float float float) void)) (define glSecondaryColor3fv (foreign-procedure "glSecondaryColor3fv" (uptr) void)) (define glSecondaryColor3i (foreign-procedure "glSecondaryColor3i" (int int int) void)) (define glSecondaryColor3iv (foreign-procedure "glSecondaryColor3iv" (uptr) void)) (define glSecondaryColor3s (foreign-procedure "glSecondaryColor3s" (short short short) void)) (define glSecondaryColor3sv (foreign-procedure "glSecondaryColor3sv" (uptr) void)) (define glSecondaryColor3ub (foreign-procedure "glSecondaryColor3ub" (unsigned-8 unsigned-8 unsigned-8) void)) (define glSecondaryColor3ubv (foreign-procedure "glSecondaryColor3ubv" (string) void)) (define glSecondaryColor3ui (foreign-procedure "glSecondaryColor3ui" (unsigned-int unsigned-int unsigned-int) void)) (define glSecondaryColor3uiv (foreign-procedure "glSecondaryColor3uiv" (uptr) void)) (define glSecondaryColor3us (foreign-procedure "glSecondaryColor3us" (unsigned-short unsigned-short unsigned-short) void)) (define glSecondaryColor3usv (foreign-procedure "glSecondaryColor3usv" (uptr) void)) (define glSecondaryColorPointer (foreign-procedure "glSecondaryColorPointer" (int unsigned-int int uptr) void)) (define glSelectBuffer (foreign-procedure "glSelectBuffer" (int uptr) void)) (define glShadeModel (foreign-procedure "glShadeModel" (unsigned-int) void)) (define glShaderSource (foreign-procedure "glShaderSource" (unsigned-int int uptr uptr) void)) (define glStencilFunc (foreign-procedure "glStencilFunc" (unsigned-int int unsigned-int) void)) (define glStencilFuncSeparate (foreign-procedure "glStencilFuncSeparate" (unsigned-int unsigned-int int unsigned-int) void)) (define glStencilMask (foreign-procedure "glStencilMask" (unsigned-int) void)) (define glStencilMaskSeparate (foreign-procedure "glStencilMaskSeparate" (unsigned-int unsigned-int) void)) (define glStencilOp (foreign-procedure "glStencilOp" (unsigned-int unsigned-int unsigned-int) void)) (define glStencilOpSeparate (foreign-procedure "glStencilOpSeparate" (unsigned-int unsigned-int unsigned-int unsigned-int) void)) (define glTexCoord1d (foreign-procedure "glTexCoord1d" (double) void)) (define glTexCoord1dv (foreign-procedure "glTexCoord1dv" (uptr) void)) (define glTexCoord1f (foreign-procedure "glTexCoord1f" (float) void)) (define glTexCoord1fv (foreign-procedure "glTexCoord1fv" (uptr) void)) (define glTexCoord1i (foreign-procedure "glTexCoord1i" (int) void)) (define glTexCoord1iv (foreign-procedure "glTexCoord1iv" (uptr) void)) (define glTexCoord1s (foreign-procedure "glTexCoord1s" (short) void)) (define glTexCoord1sv (foreign-procedure "glTexCoord1sv" (uptr) void)) (define glTexCoord2d (foreign-procedure "glTexCoord2d" (double double) void)) (define glTexCoord2dv (foreign-procedure "glTexCoord2dv" (uptr) void)) (define glTexCoord2f (foreign-procedure "glTexCoord2f" (float float) void)) (define glTexCoord2fv (foreign-procedure "glTexCoord2fv" (uptr) void)) (define glTexCoord2i (foreign-procedure "glTexCoord2i" (int int) void)) (define glTexCoord2iv (foreign-procedure "glTexCoord2iv" (uptr) void)) (define glTexCoord2s (foreign-procedure "glTexCoord2s" (short short) void)) (define glTexCoord2sv (foreign-procedure "glTexCoord2sv" (uptr) void)) (define glTexCoord3d (foreign-procedure "glTexCoord3d" (double double double) void)) (define glTexCoord3dv (foreign-procedure "glTexCoord3dv" (uptr) void)) (define glTexCoord3f (foreign-procedure "glTexCoord3f" (float float float) void)) (define glTexCoord3fv (foreign-procedure "glTexCoord3fv" (uptr) void)) (define glTexCoord3i (foreign-procedure "glTexCoord3i" (int int int) void)) (define glTexCoord3iv (foreign-procedure "glTexCoord3iv" (uptr) void)) (define glTexCoord3s (foreign-procedure "glTexCoord3s" (short short short) void)) (define glTexCoord3sv (foreign-procedure "glTexCoord3sv" (uptr) void)) (define glTexCoord4d (foreign-procedure "glTexCoord4d" (double double double double) void)) (define glTexCoord4dv (foreign-procedure "glTexCoord4dv" (uptr) void)) (define glTexCoord4f (foreign-procedure "glTexCoord4f" (float float float float) void)) (define glTexCoord4fv (foreign-procedure "glTexCoord4fv" (uptr) void)) (define glTexCoord4i (foreign-procedure "glTexCoord4i" (int int int int) void)) (define glTexCoord4iv (foreign-procedure "glTexCoord4iv" (uptr) void)) (define glTexCoord4s (foreign-procedure "glTexCoord4s" (short short short short) void)) (define glTexCoord4sv (foreign-procedure "glTexCoord4sv" (uptr) void)) (define glTexCoordPointer (foreign-procedure "glTexCoordPointer" (int unsigned-int int uptr) void)) (define glTexEnvf (foreign-procedure "glTexEnvf" (unsigned-int unsigned-int float) void)) (define glTexEnvfv (foreign-procedure "glTexEnvfv" (unsigned-int unsigned-int uptr) void)) (define glTexEnvi (foreign-procedure "glTexEnvi" (unsigned-int unsigned-int int) void)) (define glTexEnviv (foreign-procedure "glTexEnviv" (unsigned-int unsigned-int uptr) void)) (define glTexGend (foreign-procedure "glTexGend" (unsigned-int unsigned-int double) void)) (define glTexGendv (foreign-procedure "glTexGendv" (unsigned-int unsigned-int uptr) void)) (define glTexGenf (foreign-procedure "glTexGenf" (unsigned-int unsigned-int float) void)) (define glTexGenfv (foreign-procedure "glTexGenfv" (unsigned-int unsigned-int uptr) void)) (define glTexGeni (foreign-procedure "glTexGeni" (unsigned-int unsigned-int int) void)) (define glTexGeniv (foreign-procedure "glTexGeniv" (unsigned-int unsigned-int uptr) void)) (define glTexImage1D (foreign-procedure "glTexImage1D" (unsigned-int int int int int unsigned-int unsigned-int uptr) void)) (define glTexImage2D (foreign-procedure "glTexImage2D" (unsigned-int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexImage3D (foreign-procedure "glTexImage3D" (unsigned-int int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexParameterf (foreign-procedure "glTexParameterf" (unsigned-int unsigned-int float) void)) (define glTexParameterfv (foreign-procedure "glTexParameterfv" (unsigned-int unsigned-int uptr) void)) (define glTexParameteri (foreign-procedure "glTexParameteri" (unsigned-int unsigned-int int) void)) (define glTexParameteriv (foreign-procedure "glTexParameteriv" (unsigned-int unsigned-int uptr) void)) (define glTexSubImage1D (foreign-procedure "glTexSubImage1D" (unsigned-int int int int unsigned-int unsigned-int uptr) void)) (define glTexSubImage2D (foreign-procedure "glTexSubImage2D" (unsigned-int int int int int int unsigned-int unsigned-int uptr) void)) (define glTexSubImage3D (foreign-procedure "glTexSubImage3D" (unsigned-int int int int int int int int unsigned-int unsigned-int uptr) void)) (define glTranslated (foreign-procedure "glTranslated" (double double double) void)) (define glTranslatef (foreign-procedure "glTranslatef" (float float float) void)) (define glUniform1f (foreign-procedure "glUniform1f" (int float) void)) (define glUniform1fv (foreign-procedure "glUniform1fv" (int int uptr) void)) (define glUniform1i (foreign-procedure "glUniform1i" (int int) void)) (define glUniform1iv (foreign-procedure "glUniform1iv" (int int uptr) void)) (define glUniform2f (foreign-procedure "glUniform2f" (int float float) void)) (define glUniform2fv (foreign-procedure "glUniform2fv" (int int uptr) void)) (define glUniform2i (foreign-procedure "glUniform2i" (int int int) void)) (define glUniform2iv (foreign-procedure "glUniform2iv" (int int uptr) void)) (define glUniform3f (foreign-procedure "glUniform3f" (int float float float) void)) (define glUniform3fv (foreign-procedure "glUniform3fv" (int int uptr) void)) (define glUniform3i (foreign-procedure "glUniform3i" (int int int int) void)) (define glUniform3iv (foreign-procedure "glUniform3iv" (int int uptr) void)) (define glUniform4f (foreign-procedure "glUniform4f" (int float float float float) void)) (define glUniform4fv (foreign-procedure "glUniform4fv" (int int uptr) void)) (define glUniform4i (foreign-procedure "glUniform4i" (int int int int int) void)) (define glUniform4iv (foreign-procedure "glUniform4iv" (int int uptr) void)) (define glUniformMatrix2fv (foreign-procedure "glUniformMatrix2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix2x3fv (foreign-procedure "glUniformMatrix2x3fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix2x4fv (foreign-procedure "glUniformMatrix2x4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3fv (foreign-procedure "glUniformMatrix3fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3x2fv (foreign-procedure "glUniformMatrix3x2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix3x4fv (foreign-procedure "glUniformMatrix3x4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4fv (foreign-procedure "glUniformMatrix4fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4x2fv (foreign-procedure "glUniformMatrix4x2fv" (int int unsigned-8 uptr) void)) (define glUniformMatrix4x3fv (foreign-procedure "glUniformMatrix4x3fv" (int int unsigned-8 uptr) void)) (define glUnmapBuffer (foreign-procedure "glUnmapBuffer" (unsigned-int) unsigned-8)) (define glUseProgram (foreign-procedure "glUseProgram" (unsigned-int) void)) (define glValidateProgram (foreign-procedure "glValidateProgram" (unsigned-int) void)) (define glVertex2d (foreign-procedure "glVertex2d" (double double) void)) (define glVertex2dv (foreign-procedure "glVertex2dv" (uptr) void)) (define glVertex2f (foreign-procedure "glVertex2f" (float float) void)) (define glVertex2fv (foreign-procedure "glVertex2fv" (uptr) void)) (define glVertex2i (foreign-procedure "glVertex2i" (int int) void)) (define glVertex2iv (foreign-procedure "glVertex2iv" (uptr) void)) (define glVertex2s (foreign-procedure "glVertex2s" (short short) void)) (define glVertex2sv (foreign-procedure "glVertex2sv" (uptr) void)) (define glVertex3d (foreign-procedure "glVertex3d" (double double double) void)) (define glVertex3dv (foreign-procedure "glVertex3dv" (uptr) void)) (define glVertex3f (foreign-procedure "glVertex3f" (float float float) void)) (define glVertex3fv (foreign-procedure "glVertex3fv" (uptr) void)) (define glVertex3i (foreign-procedure "glVertex3i" (int int int) void)) (define glVertex3iv (foreign-procedure "glVertex3iv" (uptr) void)) (define glVertex3s (foreign-procedure "glVertex3s" (short short short) void)) (define glVertex3sv (foreign-procedure "glVertex3sv" (uptr) void)) (define glVertex4d (foreign-procedure "glVertex4d" (double double double double) void)) (define glVertex4dv (foreign-procedure "glVertex4dv" (uptr) void)) (define glVertex4f (foreign-procedure "glVertex4f" (float float float float) void)) (define glVertex4fv (foreign-procedure "glVertex4fv" (uptr) void)) (define glVertex4i (foreign-procedure "glVertex4i" (int int int int) void)) (define glVertex4iv (foreign-procedure "glVertex4iv" (uptr) void)) (define glVertex4s (foreign-procedure "glVertex4s" (short short short short) void)) (define glVertex4sv (foreign-procedure "glVertex4sv" (uptr) void)) (define glVertexAttrib1d (foreign-procedure "glVertexAttrib1d" (unsigned-int double) void)) (define glVertexAttrib1dv (foreign-procedure "glVertexAttrib1dv" (unsigned-int uptr) void)) (define glVertexAttrib1f (foreign-procedure "glVertexAttrib1f" (unsigned-int float) void)) (define glVertexAttrib1fv (foreign-procedure "glVertexAttrib1fv" (unsigned-int uptr) void)) (define glVertexAttrib1s (foreign-procedure "glVertexAttrib1s" (unsigned-int short) void)) (define glVertexAttrib1sv (foreign-procedure "glVertexAttrib1sv" (unsigned-int uptr) void)) (define glVertexAttrib2d (foreign-procedure "glVertexAttrib2d" (unsigned-int double double) void)) (define glVertexAttrib2dv (foreign-procedure "glVertexAttrib2dv" (unsigned-int uptr) void)) (define glVertexAttrib2f (foreign-procedure "glVertexAttrib2f" (unsigned-int float float) void)) (define glVertexAttrib2fv (foreign-procedure "glVertexAttrib2fv" (unsigned-int uptr) void)) (define glVertexAttrib2s (foreign-procedure "glVertexAttrib2s" (unsigned-int short short) void)) (define glVertexAttrib2sv (foreign-procedure "glVertexAttrib2sv" (unsigned-int uptr) void)) (define glVertexAttrib3d (foreign-procedure "glVertexAttrib3d" (unsigned-int double double double) void)) (define glVertexAttrib3dv (foreign-procedure "glVertexAttrib3dv" (unsigned-int uptr) void)) (define glVertexAttrib3f (foreign-procedure "glVertexAttrib3f" (unsigned-int float float float) void)) (define glVertexAttrib3fv (foreign-procedure "glVertexAttrib3fv" (unsigned-int uptr) void)) (define glVertexAttrib3s (foreign-procedure "glVertexAttrib3s" (unsigned-int short short short) void)) (define glVertexAttrib3sv (foreign-procedure "glVertexAttrib3sv" (unsigned-int uptr) void)) (define glVertexAttrib4Nbv (foreign-procedure "glVertexAttrib4Nbv" (unsigned-int string) void)) (define glVertexAttrib4Niv (foreign-procedure "glVertexAttrib4Niv" (unsigned-int uptr) void)) (define glVertexAttrib4Nsv (foreign-procedure "glVertexAttrib4Nsv" (unsigned-int uptr) void)) (define glVertexAttrib4Nub (foreign-procedure "glVertexAttrib4Nub" (unsigned-int unsigned-8 unsigned-8 unsigned-8 unsigned-8) void)) (define glVertexAttrib4Nubv (foreign-procedure "glVertexAttrib4Nubv" (unsigned-int string) void)) (define glVertexAttrib4Nuiv (foreign-procedure "glVertexAttrib4Nuiv" (unsigned-int uptr) void)) (define glVertexAttrib4Nusv (foreign-procedure "glVertexAttrib4Nusv" (unsigned-int uptr) void)) (define glVertexAttrib4bv (foreign-procedure "glVertexAttrib4bv" (unsigned-int string) void)) (define glVertexAttrib4d (foreign-procedure "glVertexAttrib4d" (unsigned-int double double double double) void)) (define glVertexAttrib4dv (foreign-procedure "glVertexAttrib4dv" (unsigned-int uptr) void)) (define glVertexAttrib4f (foreign-procedure "glVertexAttrib4f" (unsigned-int float float float float) void)) (define glVertexAttrib4fv (foreign-procedure "glVertexAttrib4fv" (unsigned-int uptr) void)) (define glVertexAttrib4iv (foreign-procedure "glVertexAttrib4iv" (unsigned-int uptr) void)) (define glVertexAttrib4s (foreign-procedure "glVertexAttrib4s" (unsigned-int short short short short) void)) (define glVertexAttrib4sv (foreign-procedure "glVertexAttrib4sv" (unsigned-int uptr) void)) (define glVertexAttrib4ubv (foreign-procedure "glVertexAttrib4ubv" (unsigned-int string) void)) (define glVertexAttrib4uiv (foreign-procedure "glVertexAttrib4uiv" (unsigned-int uptr) void)) (define glVertexAttrib4usv (foreign-procedure "glVertexAttrib4usv" (unsigned-int uptr) void)) (define glVertexAttribPointer (foreign-procedure "glVertexAttribPointer" (unsigned-int int unsigned-int unsigned-8 int uptr) void)) (define glVertexPointer (foreign-procedure "glVertexPointer" (int unsigned-int int uptr) void)) (define glViewport (foreign-procedure "glViewport" (int int int int) void)) (define glWindowPos2d (foreign-procedure "glWindowPos2d" (double double) void)) (define glWindowPos2dv (foreign-procedure "glWindowPos2dv" (uptr) void)) (define glWindowPos2f (foreign-procedure "glWindowPos2f" (float float) void)) (define glWindowPos2fv (foreign-procedure "glWindowPos2fv" (uptr) void)) (define glWindowPos2i (foreign-procedure "glWindowPos2i" (int int) void)) (define glWindowPos2iv (foreign-procedure "glWindowPos2iv" (uptr) void)) (define glWindowPos2s (foreign-procedure "glWindowPos2s" (short short) void)) (define glWindowPos2sv (foreign-procedure "glWindowPos2sv" (uptr) void)) (define glWindowPos3d (foreign-procedure "glWindowPos3d" (double double double) void)) (define glWindowPos3dv (foreign-procedure "glWindowPos3dv" (uptr) void)) (define glWindowPos3f (foreign-procedure "glWindowPos3f" (float float float) void)) (define glWindowPos3fv (foreign-procedure "glWindowPos3fv" (uptr) void)) (define glWindowPos3i (foreign-procedure "glWindowPos3i" (int int int) void)) (define glWindowPos3iv (foreign-procedure "glWindowPos3iv" (uptr) void)) (define glWindowPos3s (foreign-procedure "glWindowPos3s" (short short short) void)) (define glWindowPos3sv (foreign-procedure "glWindowPos3sv" (uptr) void)) (define GL_2D #x600) (define GL_2_BYTES #x1407) (define GL_3D #x601) (define GL_3D_COLOR #x602) (define GL_3D_COLOR_TEXTURE #x603) (define GL_3_BYTES #x1408) (define GL_4D_COLOR_TEXTURE #x604) (define GL_4_BYTES #x1409) (define GL_ACCUM #x100) (define GL_ACCUM_ALPHA_BITS #xD5B) (define GL_ACCUM_BLUE_BITS #xD5A) (define GL_ACCUM_BUFFER_BIT #x200) (define GL_ACCUM_CLEAR_VALUE #xB80) (define GL_ACCUM_GREEN_BITS #xD59) (define GL_ACCUM_RED_BITS #xD58) (define GL_ACTIVE_ATTRIBUTES #x8B89) (define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH #x8B8A) (define GL_ACTIVE_TEXTURE #x84E0) (define GL_ACTIVE_UNIFORMS #x8B86) (define GL_ACTIVE_UNIFORM_MAX_LENGTH #x8B87) (define GL_ADD #x104) (define GL_ADD_SIGNED #x8574) (define GL_ALIASED_LINE_WIDTH_RANGE #x846E) (define GL_ALIASED_POINT_SIZE_RANGE #x846D) (define GL_ALL_ATTRIB_BITS #xFFFFFFFF) (define GL_ALPHA #x1906) (define GL_ALPHA12 #x803D) (define GL_ALPHA16 #x803E) (define GL_ALPHA4 #x803B) (define GL_ALPHA8 #x803C) (define GL_ALPHA_BIAS #xD1D) (define GL_ALPHA_BITS #xD55) (define GL_ALPHA_SCALE #xD1C) (define GL_ALPHA_TEST #xBC0) (define GL_ALPHA_TEST_FUNC #xBC1) (define GL_ALPHA_TEST_REF #xBC2) (define GL_ALWAYS #x207) (define GL_AMBIENT #x1200) (define GL_AMBIENT_AND_DIFFUSE #x1602) (define GL_AND #x1501) (define GL_AND_INVERTED #x1504) (define GL_AND_REVERSE #x1502) (define GL_ARRAY_BUFFER #x8892) (define GL_ARRAY_BUFFER_BINDING #x8894) (define GL_ATTACHED_SHADERS #x8B85) (define GL_ATTRIB_STACK_DEPTH #xBB0) (define GL_AUTO_NORMAL #xD80) (define GL_AUX0 #x409) (define GL_AUX1 #x40A) (define GL_AUX2 #x40B) (define GL_AUX3 #x40C) (define GL_AUX_BUFFERS #xC00) (define GL_BACK #x405) (define GL_BACK_LEFT #x402) (define GL_BACK_RIGHT #x403) (define GL_BGR #x80E0) (define GL_BGRA #x80E1) (define GL_BITMAP #x1A00) (define GL_BITMAP_TOKEN #x704) (define GL_BLEND #xBE2) (define GL_BLEND_DST #xBE0) (define GL_BLEND_DST_ALPHA #x80CA) (define GL_BLEND_DST_RGB #x80C8) (define GL_BLEND_EQUATION_ALPHA #x883D) (define GL_BLEND_EQUATION_RGB #x8009) (define GL_BLEND_SRC #xBE1) (define GL_BLEND_SRC_ALPHA #x80CB) (define GL_BLEND_SRC_RGB #x80C9) (define GL_BLUE #x1905) (define GL_BLUE_BIAS #xD1B) (define GL_BLUE_BITS #xD54) (define GL_BLUE_SCALE #xD1A) (define GL_BOOL #x8B56) (define GL_BOOL_VEC2 #x8B57) (define GL_BOOL_VEC3 #x8B58) (define GL_BOOL_VEC4 #x8B59) (define GL_BUFFER_ACCESS #x88BB) (define GL_BUFFER_MAPPED #x88BC) (define GL_BUFFER_MAP_POINTER #x88BD) (define GL_BUFFER_SIZE #x8764) (define GL_BUFFER_USAGE #x8765) (define GL_BYTE #x1400) (define GL_C3F_V3F #x2A24) (define GL_C4F_N3F_V3F #x2A26) (define GL_C4UB_V2F #x2A22) (define GL_C4UB_V3F #x2A23) (define GL_CCW #x901) (define GL_CLAMP #x2900) (define GL_CLAMP_TO_BORDER #x812D) (define GL_CLAMP_TO_EDGE #x812F) (define GL_CLEAR #x1500) (define GL_CLIENT_ACTIVE_TEXTURE #x84E1) (define GL_CLIENT_ALL_ATTRIB_BITS #xFFFFFFFF) (define GL_CLIENT_ATTRIB_STACK_DEPTH #xBB1) (define GL_CLIENT_PIXEL_STORE_BIT #x1) (define GL_CLIENT_VERTEX_ARRAY_BIT #x2) (define GL_CLIP_PLANE0 #x3000) (define GL_CLIP_PLANE1 #x3001) (define GL_CLIP_PLANE2 #x3002) (define GL_CLIP_PLANE3 #x3003) (define GL_CLIP_PLANE4 #x3004) (define GL_CLIP_PLANE5 #x3005) (define GL_COEFF #xA00) (define GL_COLOR #x1800) (define GL_COLOR_ARRAY #x8076) (define GL_COLOR_ARRAY_BUFFER_BINDING #x8898) (define GL_COLOR_ARRAY_POINTER #x8090) (define GL_COLOR_ARRAY_SIZE #x8081) (define GL_COLOR_ARRAY_STRIDE #x8083) (define GL_COLOR_ARRAY_TYPE #x8082) (define GL_COLOR_BUFFER_BIT #x4000) (define GL_COLOR_CLEAR_VALUE #xC22) (define GL_COLOR_INDEX #x1900) (define GL_COLOR_INDEXES #x1603) (define GL_COLOR_LOGIC_OP #xBF2) (define GL_COLOR_MATERIAL #xB57) (define GL_COLOR_MATERIAL_FACE #xB55) (define GL_COLOR_MATERIAL_PARAMETER #xB56) (define GL_COLOR_SUM #x8458) (define GL_COLOR_WRITEMASK #xC23) (define GL_COMBINE #x8570) (define GL_COMBINE_ALPHA #x8572) (define GL_COMBINE_RGB #x8571) (define GL_COMPARE_R_TO_TEXTURE #x884E) (define GL_COMPILE #x1300) (define GL_COMPILE_AND_EXECUTE #x1301) (define GL_COMPILE_STATUS #x8B81) (define GL_COMPRESSED_ALPHA #x84E9) (define GL_COMPRESSED_INTENSITY #x84EC) (define GL_COMPRESSED_LUMINANCE #x84EA) (define GL_COMPRESSED_LUMINANCE_ALPHA #x84EB) (define GL_COMPRESSED_RGB #x84ED) (define GL_COMPRESSED_RGBA #x84EE) (define GL_COMPRESSED_SLUMINANCE #x8C4A) (define GL_COMPRESSED_SLUMINANCE_ALPHA #x8C4B) (define GL_COMPRESSED_SRGB #x8C48) (define GL_COMPRESSED_SRGB_ALPHA #x8C49) (define GL_COMPRESSED_TEXTURE_FORMATS #x86A3) (define GL_CONSTANT #x8576) (define GL_CONSTANT_ALPHA #x8003) (define GL_CONSTANT_ATTENUATION #x1207) (define GL_CONSTANT_COLOR #x8001) (define GL_COORD_REPLACE #x8862) (define GL_COPY #x1503) (define GL_COPY_INVERTED #x150C) (define GL_COPY_PIXEL_TOKEN #x706) (define GL_CULL_FACE #xB44) (define GL_CULL_FACE_MODE #xB45) (define GL_CURRENT_BIT #x1) (define GL_CURRENT_COLOR #xB00) (define GL_CURRENT_FOG_COORD #x8453) (define GL_CURRENT_FOG_COORDINATE #x8453) (define GL_CURRENT_INDEX #xB01) (define GL_CURRENT_NORMAL #xB02) (define GL_CURRENT_PROGRAM #x8B8D) (define GL_CURRENT_QUERY #x8865) (define GL_CURRENT_RASTER_COLOR #xB04) (define GL_CURRENT_RASTER_DISTANCE #xB09) (define GL_CURRENT_RASTER_INDEX #xB05) (define GL_CURRENT_RASTER_POSITION #xB07) (define GL_CURRENT_RASTER_POSITION_VALID #xB08) (define GL_CURRENT_RASTER_SECONDARY_COLOR #x845F) (define GL_CURRENT_RASTER_TEXTURE_COORDS #xB06) (define GL_CURRENT_SECONDARY_COLOR #x8459) (define GL_CURRENT_TEXTURE_COORDS #xB03) (define GL_CURRENT_VERTEX_ATTRIB #x8626) (define GL_CW #x900) (define GL_DECAL #x2101) (define GL_DECR #x1E03) (define GL_DECR_WRAP #x8508) (define GL_DELETE_STATUS #x8B80) (define GL_DEPTH #x1801) (define GL_DEPTH_BIAS #xD1F) (define GL_DEPTH_BITS #xD56) (define GL_DEPTH_BUFFER_BIT #x100) (define GL_DEPTH_CLEAR_VALUE #xB73) (define GL_DEPTH_COMPONENT #x1902) (define GL_DEPTH_COMPONENT16 #x81A5) (define GL_DEPTH_COMPONENT24 #x81A6) (define GL_DEPTH_COMPONENT32 #x81A7) (define GL_DEPTH_FUNC #xB74) (define GL_DEPTH_RANGE #xB70) (define GL_DEPTH_SCALE #xD1E) (define GL_DEPTH_TEST #xB71) (define GL_DEPTH_TEXTURE_MODE #x884B) (define GL_DEPTH_WRITEMASK #xB72) (define GL_DIFFUSE #x1201) (define GL_DITHER #xBD0) (define GL_DOMAIN #xA02) (define GL_DONT_CARE #x1100) (define GL_DOT3_RGB #x86AE) (define GL_DOT3_RGBA #x86AF) (define GL_DOUBLE #x140A) (define GL_DOUBLEBUFFER #xC32) (define GL_DRAW_BUFFER #xC01) (define GL_DRAW_BUFFER0 #x8825) (define GL_DRAW_BUFFER1 #x8826) (define GL_DRAW_BUFFER10 #x882F) (define GL_DRAW_BUFFER11 #x8830) (define GL_DRAW_BUFFER12 #x8831) (define GL_DRAW_BUFFER13 #x8832) (define GL_DRAW_BUFFER14 #x8833) (define GL_DRAW_BUFFER15 #x8834) (define GL_DRAW_BUFFER2 #x8827) (define GL_DRAW_BUFFER3 #x8828) (define GL_DRAW_BUFFER4 #x8829) (define GL_DRAW_BUFFER5 #x882A) (define GL_DRAW_BUFFER6 #x882B) (define GL_DRAW_BUFFER7 #x882C) (define GL_DRAW_BUFFER8 #x882D) (define GL_DRAW_BUFFER9 #x882E) (define GL_DRAW_PIXEL_TOKEN #x705) (define GL_DST_ALPHA #x304) (define GL_DST_COLOR #x306) (define GL_DYNAMIC_COPY #x88EA) (define GL_DYNAMIC_DRAW #x88E8) (define GL_DYNAMIC_READ #x88E9) (define GL_EDGE_FLAG #xB43) (define GL_EDGE_FLAG_ARRAY #x8079) (define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING #x889B) (define GL_EDGE_FLAG_ARRAY_POINTER #x8093) (define GL_EDGE_FLAG_ARRAY_STRIDE #x808C) (define GL_ELEMENT_ARRAY_BUFFER #x8893) (define GL_ELEMENT_ARRAY_BUFFER_BINDING #x8895) (define GL_EMISSION #x1600) (define GL_ENABLE_BIT #x2000) (define GL_EQUAL #x202) (define GL_EQUIV #x1509) (define GL_EVAL_BIT #x10000) (define GL_EXP #x800) (define GL_EXP2 #x801) (define GL_EXTENSIONS #x1F03) (define GL_EYE_LINEAR #x2400) (define GL_EYE_PLANE #x2502) (define GL_FALSE #x0) (define GL_FASTEST #x1101) (define GL_FEEDBACK #x1C01) (define GL_FEEDBACK_BUFFER_POINTER #xDF0) (define GL_FEEDBACK_BUFFER_SIZE #xDF1) (define GL_FEEDBACK_BUFFER_TYPE #xDF2) (define GL_FILL #x1B02) (define GL_FLAT #x1D00) (define GL_FLOAT #x1406) (define GL_FLOAT_MAT2 #x8B5A) (define GL_FLOAT_MAT2x3 #x8B65) (define GL_FLOAT_MAT2x4 #x8B66) (define GL_FLOAT_MAT3 #x8B5B) (define GL_FLOAT_MAT3x2 #x8B67) (define GL_FLOAT_MAT3x4 #x8B68) (define GL_FLOAT_MAT4 #x8B5C) (define GL_FLOAT_MAT4x2 #x8B69) (define GL_FLOAT_MAT4x3 #x8B6A) (define GL_FLOAT_VEC2 #x8B50) (define GL_FLOAT_VEC3 #x8B51) (define GL_FLOAT_VEC4 #x8B52) (define GL_FOG #xB60) (define GL_FOG_BIT #x80) (define GL_FOG_COLOR #xB66) (define GL_FOG_COORD #x8451) (define GL_FOG_COORDINATE #x8451) (define GL_FOG_COORDINATE_ARRAY #x8457) (define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING #x889D) (define GL_FOG_COORDINATE_ARRAY_POINTER #x8456) (define GL_FOG_COORDINATE_ARRAY_STRIDE #x8455) (define GL_FOG_COORDINATE_ARRAY_TYPE #x8454) (define GL_FOG_COORDINATE_SOURCE #x8450) (define GL_FOG_COORD_ARRAY #x8457) (define GL_FOG_COORD_ARRAY_BUFFER_BINDING #x889D) (define GL_FOG_COORD_ARRAY_POINTER #x8456) (define GL_FOG_COORD_ARRAY_STRIDE #x8455) (define GL_FOG_COORD_ARRAY_TYPE #x8454) (define GL_FOG_COORD_SRC #x8450) (define GL_FOG_DENSITY #xB62) (define GL_FOG_END #xB64) (define GL_FOG_HINT #xC54) (define GL_FOG_INDEX #xB61) (define GL_FOG_MODE #xB65) (define GL_FOG_START #xB63) (define GL_FRAGMENT_DEPTH #x8452) (define GL_FRAGMENT_SHADER #x8B30) (define GL_FRAGMENT_SHADER_DERIVATIVE_HINT #x8B8B) (define GL_FRONT #x404) (define GL_FRONT_AND_BACK #x408) (define GL_FRONT_FACE #xB46) (define GL_FRONT_LEFT #x400) (define GL_FRONT_RIGHT #x401) (define GL_FUNC_ADD #x8006) (define GL_FUNC_REVERSE_SUBTRACT #x800B) (define GL_FUNC_SUBTRACT #x800A) (define GL_GENERATE_MIPMAP #x8191) (define GL_GENERATE_MIPMAP_HINT #x8192) (define GL_GEQUAL #x206) (define GL_GREATER #x204) (define GL_GREEN #x1904) (define GL_GREEN_BIAS #xD19) (define GL_GREEN_BITS #xD53) (define GL_GREEN_SCALE #xD18) (define GL_HINT_BIT #x8000) (define GL_INCR #x1E02) (define GL_INCR_WRAP #x8507) (define GL_INDEX_ARRAY #x8077) (define GL_INDEX_ARRAY_BUFFER_BINDING #x8899) (define GL_INDEX_ARRAY_POINTER #x8091) (define GL_INDEX_ARRAY_STRIDE #x8086) (define GL_INDEX_ARRAY_TYPE #x8085) (define GL_INDEX_BITS #xD51) (define GL_INDEX_CLEAR_VALUE #xC20) (define GL_INDEX_LOGIC_OP #xBF1) (define GL_INDEX_MODE #xC30) (define GL_INDEX_OFFSET #xD13) (define GL_INDEX_SHIFT #xD12) (define GL_INDEX_WRITEMASK #xC21) (define GL_INFO_LOG_LENGTH #x8B84) (define GL_INT #x1404) (define GL_INTENSITY #x8049) (define GL_INTENSITY12 #x804C) (define GL_INTENSITY16 #x804D) (define GL_INTENSITY4 #x804A) (define GL_INTENSITY8 #x804B) (define GL_INTERPOLATE #x8575) (define GL_INT_VEC2 #x8B53) (define GL_INT_VEC3 #x8B54) (define GL_INT_VEC4 #x8B55) (define GL_INVALID_ENUM #x500) (define GL_INVALID_OPERATION #x502) (define GL_INVALID_VALUE #x501) (define GL_INVERT #x150A) (define GL_KEEP #x1E00) (define GL_LEFT #x406) (define GL_LEQUAL #x203) (define GL_LESS #x201) (define GL_LIGHT0 #x4000) (define GL_LIGHT1 #x4001) (define GL_LIGHT2 #x4002) (define GL_LIGHT3 #x4003) (define GL_LIGHT4 #x4004) (define GL_LIGHT5 #x4005) (define GL_LIGHT6 #x4006) (define GL_LIGHT7 #x4007) (define GL_LIGHTING #xB50) (define GL_LIGHTING_BIT #x40) (define GL_LIGHT_MODEL_AMBIENT #xB53) (define GL_LIGHT_MODEL_COLOR_CONTROL #x81F8) (define GL_LIGHT_MODEL_LOCAL_VIEWER #xB51) (define GL_LIGHT_MODEL_TWO_SIDE #xB52) (define GL_LINE #x1B01) (define GL_LINEAR #x2601) (define GL_LINEAR_ATTENUATION #x1208) (define GL_LINEAR_MIPMAP_LINEAR #x2703) (define GL_LINEAR_MIPMAP_NEAREST #x2701) (define GL_LINES #x1) (define GL_LINE_BIT #x4) (define GL_LINE_LOOP #x2) (define GL_LINE_RESET_TOKEN #x707) (define GL_LINE_SMOOTH #xB20) (define GL_LINE_SMOOTH_HINT #xC52) (define GL_LINE_STIPPLE #xB24) (define GL_LINE_STIPPLE_PATTERN #xB25) (define GL_LINE_STIPPLE_REPEAT #xB26) (define GL_LINE_STRIP #x3) (define GL_LINE_TOKEN #x702) (define GL_LINE_WIDTH #xB21) (define GL_LINE_WIDTH_GRANULARITY #xB23) (define GL_LINE_WIDTH_RANGE #xB22) (define GL_LINK_STATUS #x8B82) (define GL_LIST_BASE #xB32) (define GL_LIST_BIT #x20000) (define GL_LIST_INDEX #xB33) (define GL_LIST_MODE #xB30) (define GL_LOAD #x101) (define GL_LOGIC_OP #xBF1) (define GL_LOGIC_OP_MODE #xBF0) (define GL_LOWER_LEFT #x8CA1) (define GL_LUMINANCE #x1909) (define GL_LUMINANCE12 #x8041) (define GL_LUMINANCE12_ALPHA12 #x8047) (define GL_LUMINANCE12_ALPHA4 #x8046) (define GL_LUMINANCE16 #x8042) (define GL_LUMINANCE16_ALPHA16 #x8048) (define GL_LUMINANCE4 #x803F) (define GL_LUMINANCE4_ALPHA4 #x8043) (define GL_LUMINANCE6_ALPHA2 #x8044) (define GL_LUMINANCE8 #x8040) (define GL_LUMINANCE8_ALPHA8 #x8045) (define GL_LUMINANCE_ALPHA #x190A) (define GL_MAP1_COLOR_4 #xD90) (define GL_MAP1_GRID_DOMAIN #xDD0) (define GL_MAP1_GRID_SEGMENTS #xDD1) (define GL_MAP1_INDEX #xD91) (define GL_MAP1_NORMAL #xD92) (define GL_MAP1_TEXTURE_COORD_1 #xD93) (define GL_MAP1_TEXTURE_COORD_2 #xD94) (define GL_MAP1_TEXTURE_COORD_3 #xD95) (define GL_MAP1_TEXTURE_COORD_4 #xD96) (define GL_MAP1_VERTEX_3 #xD97) (define GL_MAP1_VERTEX_4 #xD98) (define GL_MAP2_COLOR_4 #xDB0) (define GL_MAP2_GRID_DOMAIN #xDD2) (define GL_MAP2_GRID_SEGMENTS #xDD3) (define GL_MAP2_INDEX #xDB1) (define GL_MAP2_NORMAL #xDB2) (define GL_MAP2_TEXTURE_COORD_1 #xDB3) (define GL_MAP2_TEXTURE_COORD_2 #xDB4) (define GL_MAP2_TEXTURE_COORD_3 #xDB5) (define GL_MAP2_TEXTURE_COORD_4 #xDB6) (define GL_MAP2_VERTEX_3 #xDB7) (define GL_MAP2_VERTEX_4 #xDB8) (define GL_MAP_COLOR #xD10) (define GL_MAP_STENCIL #xD11) (define GL_MATRIX_MODE #xBA0) (define GL_MAX #x8008) (define GL_MAX_3D_TEXTURE_SIZE #x8073) (define GL_MAX_ATTRIB_STACK_DEPTH #xD35) (define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH #xD3B) (define GL_MAX_CLIP_PLANES #xD32) (define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS #x8B4D) (define GL_MAX_CUBE_MAP_TEXTURE_SIZE #x851C) (define GL_MAX_DRAW_BUFFERS #x8824) (define GL_MAX_ELEMENTS_INDICES #x80E9) (define GL_MAX_ELEMENTS_VERTICES #x80E8) (define GL_MAX_EVAL_ORDER #xD30) (define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS #x8B49) (define GL_MAX_LIGHTS #xD31) (define GL_MAX_LIST_NESTING #xB31) (define GL_MAX_MODELVIEW_STACK_DEPTH #xD36) (define GL_MAX_NAME_STACK_DEPTH #xD37) (define GL_MAX_PIXEL_MAP_TABLE #xD34) (define GL_MAX_PROJECTION_STACK_DEPTH #xD38) (define GL_MAX_TEXTURE_COORDS #x8871) (define GL_MAX_TEXTURE_IMAGE_UNITS #x8872) (define GL_MAX_TEXTURE_LOD_BIAS #x84FD) (define GL_MAX_TEXTURE_SIZE #xD33) (define GL_MAX_TEXTURE_STACK_DEPTH #xD39) (define GL_MAX_TEXTURE_UNITS #x84E2) (define GL_MAX_VARYING_FLOATS #x8B4B) (define GL_MAX_VERTEX_ATTRIBS #x8869) (define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS #x8B4C) (define GL_MAX_VERTEX_UNIFORM_COMPONENTS #x8B4A) (define GL_MAX_VIEWPORT_DIMS #xD3A) (define GL_MIN #x8007) (define GL_MIRRORED_REPEAT #x8370) (define GL_MODELVIEW #x1700) (define GL_MODELVIEW_MATRIX #xBA6) (define GL_MODELVIEW_STACK_DEPTH #xBA3) (define GL_MODULATE #x2100) (define GL_MULT #x103) (define GL_MULTISAMPLE #x809D) (define GL_MULTISAMPLE_BIT #x20000000) (define GL_N3F_V3F #x2A25) (define GL_NAME_STACK_DEPTH #xD70) (define GL_NAND #x150E) (define GL_NEAREST #x2600) (define GL_NEAREST_MIPMAP_LINEAR #x2702) (define GL_NEAREST_MIPMAP_NEAREST #x2700) (define GL_NEVER #x200) (define GL_NICEST #x1102) (define GL_NONE #x0) (define GL_NOOP #x1505) (define GL_NOR #x1508) (define GL_NORMALIZE #xBA1) (define GL_NORMAL_ARRAY #x8075) (define GL_NORMAL_ARRAY_BUFFER_BINDING #x8897) (define GL_NORMAL_ARRAY_POINTER #x808F) (define GL_NORMAL_ARRAY_STRIDE #x807F) (define GL_NORMAL_ARRAY_TYPE #x807E) (define GL_NORMAL_MAP #x8511) (define GL_NOTEQUAL #x205) (define GL_NO_ERROR #x0) (define GL_NUM_COMPRESSED_TEXTURE_FORMATS #x86A2) (define GL_OBJECT_LINEAR #x2401) (define GL_OBJECT_PLANE #x2501) (define GL_ONE #x1) (define GL_ONE_MINUS_CONSTANT_ALPHA #x8004) (define GL_ONE_MINUS_CONSTANT_COLOR #x8002) (define GL_ONE_MINUS_DST_ALPHA #x305) (define GL_ONE_MINUS_DST_COLOR #x307) (define GL_ONE_MINUS_SRC_ALPHA #x303) (define GL_ONE_MINUS_SRC_COLOR #x301) (define GL_OPERAND0_ALPHA #x8598) (define GL_OPERAND0_RGB #x8590) (define GL_OPERAND1_ALPHA #x8599) (define GL_OPERAND1_RGB #x8591) (define GL_OPERAND2_ALPHA #x859A) (define GL_OPERAND2_RGB #x8592) (define GL_OR #x1507) (define GL_ORDER #xA01) (define GL_OR_INVERTED #x150D) (define GL_OR_REVERSE #x150B) (define GL_OUT_OF_MEMORY #x505) (define GL_PACK_ALIGNMENT #xD05) (define GL_PACK_IMAGE_HEIGHT #x806C) (define GL_PACK_LSB_FIRST #xD01) (define GL_PACK_ROW_LENGTH #xD02) (define GL_PACK_SKIP_IMAGES #x806B) (define GL_PACK_SKIP_PIXELS #xD04) (define GL_PACK_SKIP_ROWS #xD03) (define GL_PACK_SWAP_BYTES #xD00) (define GL_PASS_THROUGH_TOKEN #x700) (define GL_PERSPECTIVE_CORRECTION_HINT #xC50) (define GL_PIXEL_MAP_A_TO_A #xC79) (define GL_PIXEL_MAP_A_TO_A_SIZE #xCB9) (define GL_PIXEL_MAP_B_TO_B #xC78) (define GL_PIXEL_MAP_B_TO_B_SIZE #xCB8) (define GL_PIXEL_MAP_G_TO_G #xC77) (define GL_PIXEL_MAP_G_TO_G_SIZE #xCB7) (define GL_PIXEL_MAP_I_TO_A #xC75) (define GL_PIXEL_MAP_I_TO_A_SIZE #xCB5) (define GL_PIXEL_MAP_I_TO_B #xC74) (define GL_PIXEL_MAP_I_TO_B_SIZE #xCB4) (define GL_PIXEL_MAP_I_TO_G #xC73) (define GL_PIXEL_MAP_I_TO_G_SIZE #xCB3) (define GL_PIXEL_MAP_I_TO_I #xC70) (define GL_PIXEL_MAP_I_TO_I_SIZE #xCB0) (define GL_PIXEL_MAP_I_TO_R #xC72) (define GL_PIXEL_MAP_I_TO_R_SIZE #xCB2) (define GL_PIXEL_MAP_R_TO_R #xC76) (define GL_PIXEL_MAP_R_TO_R_SIZE #xCB6) (define GL_PIXEL_MAP_S_TO_S #xC71) (define GL_PIXEL_MAP_S_TO_S_SIZE #xCB1) (define GL_PIXEL_MODE_BIT #x20) (define GL_PIXEL_PACK_BUFFER #x88EB) (define GL_PIXEL_PACK_BUFFER_BINDING #x88ED) (define GL_PIXEL_UNPACK_BUFFER #x88EC) (define GL_PIXEL_UNPACK_BUFFER_BINDING #x88EF) (define GL_POINT #x1B00) (define GL_POINTS #x0) (define GL_POINT_BIT #x2) (define GL_POINT_DISTANCE_ATTENUATION #x8129) (define GL_POINT_FADE_THRESHOLD_SIZE #x8128) (define GL_POINT_SIZE #xB11) (define GL_POINT_SIZE_GRANULARITY #xB13) (define GL_POINT_SIZE_MAX #x8127) (define GL_POINT_SIZE_MIN #x8126) (define GL_POINT_SIZE_RANGE #xB12) (define GL_POINT_SMOOTH #xB10) (define GL_POINT_SMOOTH_HINT #xC51) (define GL_POINT_SPRITE #x8861) (define GL_POINT_SPRITE_COORD_ORIGIN #x8CA0) (define GL_POINT_TOKEN #x701) (define GL_POLYGON #x9) (define GL_POLYGON_BIT #x8) (define GL_POLYGON_MODE #xB40) (define GL_POLYGON_OFFSET_FACTOR #x8038) (define GL_POLYGON_OFFSET_FILL #x8037) (define GL_POLYGON_OFFSET_LINE #x2A02) (define GL_POLYGON_OFFSET_POINT #x2A01) (define GL_POLYGON_OFFSET_UNITS #x2A00) (define GL_POLYGON_SMOOTH #xB41) (define GL_POLYGON_SMOOTH_HINT #xC53) (define GL_POLYGON_STIPPLE #xB42) (define GL_POLYGON_STIPPLE_BIT #x10) (define GL_POLYGON_TOKEN #x703) (define GL_POSITION #x1203) (define GL_PREVIOUS #x8578) (define GL_PRIMARY_COLOR #x8577) (define GL_PROJECTION #x1701) (define GL_PROJECTION_MATRIX #xBA7) (define GL_PROJECTION_STACK_DEPTH #xBA4) (define GL_PROXY_TEXTURE_1D #x8063) (define GL_PROXY_TEXTURE_2D #x8064) (define GL_PROXY_TEXTURE_3D #x8070) (define GL_PROXY_TEXTURE_CUBE_MAP #x851B) (define GL_Q #x2003) (define GL_QUADRATIC_ATTENUATION #x1209) (define GL_QUADS #x7) (define GL_QUAD_STRIP #x8) (define GL_QUERY_COUNTER_BITS #x8864) (define GL_QUERY_RESULT #x8866) (define GL_QUERY_RESULT_AVAILABLE #x8867) (define GL_R #x2002) (define GL_R3_G3_B2 #x2A10) (define GL_READ_BUFFER #xC02) (define GL_READ_ONLY #x88B8) (define GL_READ_WRITE #x88BA) (define GL_RED #x1903) (define GL_RED_BIAS #xD15) (define GL_RED_BITS #xD52) (define GL_RED_SCALE #xD14) (define GL_REFLECTION_MAP #x8512) (define GL_RENDER #x1C00) (define GL_RENDERER #x1F01) (define GL_RENDER_MODE #xC40) (define GL_REPEAT #x2901) (define GL_REPLACE #x1E01) (define GL_RESCALE_NORMAL #x803A) (define GL_RETURN #x102) (define GL_RGB #x1907) (define GL_RGB10 #x8052) (define GL_RGB10_A2 #x8059) (define GL_RGB12 #x8053) (define GL_RGB16 #x8054) (define GL_RGB4 #x804F) (define GL_RGB5 #x8050) (define GL_RGB5_A1 #x8057) (define GL_RGB8 #x8051) (define GL_RGBA #x1908) (define GL_RGBA12 #x805A) (define GL_RGBA16 #x805B) (define GL_RGBA2 #x8055) (define GL_RGBA4 #x8056) (define GL_RGBA8 #x8058) (define GL_RGBA_MODE #xC31) (define GL_RGB_SCALE #x8573) (define GL_RIGHT #x407) (define GL_S #x2000) (define GL_SAMPLER_1D #x8B5D) (define GL_SAMPLER_1D_SHADOW #x8B61) (define GL_SAMPLER_2D #x8B5E) (define GL_SAMPLER_2D_SHADOW #x8B62) (define GL_SAMPLER_3D #x8B5F) (define GL_SAMPLER_CUBE #x8B60) (define GL_SAMPLES #x80A9) (define GL_SAMPLES_PASSED #x8914) (define GL_SAMPLE_ALPHA_TO_COVERAGE #x809E) (define GL_SAMPLE_ALPHA_TO_ONE #x809F) (define GL_SAMPLE_BUFFERS #x80A8) (define GL_SAMPLE_COVERAGE #x80A0) (define GL_SAMPLE_COVERAGE_INVERT #x80AB) (define GL_SAMPLE_COVERAGE_VALUE #x80AA) (define GL_SCISSOR_BIT #x80000) (define GL_SCISSOR_BOX #xC10) (define GL_SCISSOR_TEST #xC11) (define GL_SECONDARY_COLOR_ARRAY #x845E) (define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING #x889C) (define GL_SECONDARY_COLOR_ARRAY_POINTER #x845D) (define GL_SECONDARY_COLOR_ARRAY_SIZE #x845A) (define GL_SECONDARY_COLOR_ARRAY_STRIDE #x845C) (define GL_SECONDARY_COLOR_ARRAY_TYPE #x845B) (define GL_SELECT #x1C02) (define GL_SELECTION_BUFFER_POINTER #xDF3) (define GL_SELECTION_BUFFER_SIZE #xDF4) (define GL_SEPARATE_SPECULAR_COLOR #x81FA) (define GL_SET #x150F) (define GL_SHADER_SOURCE_LENGTH #x8B88) (define GL_SHADER_TYPE #x8B4F) (define GL_SHADE_MODEL #xB54) (define GL_SHADING_LANGUAGE_VERSION #x8B8C) (define GL_SHININESS #x1601) (define GL_SHORT #x1402) (define GL_SINGLE_COLOR #x81F9) (define GL_SLUMINANCE #x8C46) (define GL_SLUMINANCE8 #x8C47) (define GL_SLUMINANCE8_ALPHA8 #x8C45) (define GL_SLUMINANCE_ALPHA #x8C44) (define GL_SMOOTH #x1D01) (define GL_SMOOTH_LINE_WIDTH_GRANULARITY #xB23) (define GL_SMOOTH_LINE_WIDTH_RANGE #xB22) (define GL_SMOOTH_POINT_SIZE_GRANULARITY #xB13) (define GL_SMOOTH_POINT_SIZE_RANGE #xB12) (define GL_SOURCE0_ALPHA #x8588) (define GL_SOURCE0_RGB #x8580) (define GL_SOURCE1_ALPHA #x8589) (define GL_SOURCE1_RGB #x8581) (define GL_SOURCE2_ALPHA #x858A) (define GL_SOURCE2_RGB #x8582) (define GL_SPECULAR #x1202) (define GL_SPHERE_MAP #x2402) (define GL_SPOT_CUTOFF #x1206) (define GL_SPOT_DIRECTION #x1204) (define GL_SPOT_EXPONENT #x1205) (define GL_SRC0_ALPHA #x8588) (define GL_SRC0_RGB #x8580) (define GL_SRC1_ALPHA #x8589) (define GL_SRC1_RGB #x8581) (define GL_SRC2_ALPHA #x858A) (define GL_SRC2_RGB #x8582) (define GL_SRC_ALPHA #x302) (define GL_SRC_ALPHA_SATURATE #x308) (define GL_SRC_COLOR #x300) (define GL_SRGB #x8C40) (define GL_SRGB8 #x8C41) (define GL_SRGB8_ALPHA8 #x8C43) (define GL_SRGB_ALPHA #x8C42) (define GL_STACK_OVERFLOW #x503) (define GL_STACK_UNDERFLOW #x504) (define GL_STATIC_COPY #x88E6) (define GL_STATIC_DRAW #x88E4) (define GL_STATIC_READ #x88E5) (define GL_STENCIL #x1802) (define GL_STENCIL_BACK_FAIL #x8801) (define GL_STENCIL_BACK_FUNC #x8800) (define GL_STENCIL_BACK_PASS_DEPTH_FAIL #x8802) (define GL_STENCIL_BACK_PASS_DEPTH_PASS #x8803) (define GL_STENCIL_BACK_REF #x8CA3) (define GL_STENCIL_BACK_VALUE_MASK #x8CA4) (define GL_STENCIL_BACK_WRITEMASK #x8CA5) (define GL_STENCIL_BITS #xD57) (define GL_STENCIL_BUFFER_BIT #x400) (define GL_STENCIL_CLEAR_VALUE #xB91) (define GL_STENCIL_FAIL #xB94) (define GL_STENCIL_FUNC #xB92) (define GL_STENCIL_INDEX #x1901) (define GL_STENCIL_PASS_DEPTH_FAIL #xB95) (define GL_STENCIL_PASS_DEPTH_PASS #xB96) (define GL_STENCIL_REF #xB97) (define GL_STENCIL_TEST #xB90) (define GL_STENCIL_VALUE_MASK #xB93) (define GL_STENCIL_WRITEMASK #xB98) (define GL_STEREO #xC33) (define GL_STREAM_COPY #x88E2) (define GL_STREAM_DRAW #x88E0) (define GL_STREAM_READ #x88E1) (define GL_SUBPIXEL_BITS #xD50) (define GL_SUBTRACT #x84E7) (define GL_T #x2001) (define GL_T2F_C3F_V3F #x2A2A) (define GL_T2F_C4F_N3F_V3F #x2A2C) (define GL_T2F_C4UB_V3F #x2A29) (define GL_T2F_N3F_V3F #x2A2B) (define GL_T2F_V3F #x2A27) (define GL_T4F_C4F_N3F_V4F #x2A2D) (define GL_T4F_V4F #x2A28) (define GL_TEXTURE #x1702) (define GL_TEXTURE0 #x84C0) (define GL_TEXTURE1 #x84C1) (define GL_TEXTURE10 #x84CA) (define GL_TEXTURE11 #x84CB) (define GL_TEXTURE12 #x84CC) (define GL_TEXTURE13 #x84CD) (define GL_TEXTURE14 #x84CE) (define GL_TEXTURE15 #x84CF) (define GL_TEXTURE16 #x84D0) (define GL_TEXTURE17 #x84D1) (define GL_TEXTURE18 #x84D2) (define GL_TEXTURE19 #x84D3) (define GL_TEXTURE2 #x84C2) (define GL_TEXTURE20 #x84D4) (define GL_TEXTURE21 #x84D5) (define GL_TEXTURE22 #x84D6) (define GL_TEXTURE23 #x84D7) (define GL_TEXTURE24 #x84D8) (define GL_TEXTURE25 #x84D9) (define GL_TEXTURE26 #x84DA) (define GL_TEXTURE27 #x84DB) (define GL_TEXTURE28 #x84DC) (define GL_TEXTURE29 #x84DD) (define GL_TEXTURE3 #x84C3) (define GL_TEXTURE30 #x84DE) (define GL_TEXTURE31 #x84DF) (define GL_TEXTURE4 #x84C4) (define GL_TEXTURE5 #x84C5) (define GL_TEXTURE6 #x84C6) (define GL_TEXTURE7 #x84C7) (define GL_TEXTURE8 #x84C8) (define GL_TEXTURE9 #x84C9) (define GL_TEXTURE_1D #xDE0) (define GL_TEXTURE_2D #xDE1) (define GL_TEXTURE_3D #x806F) (define GL_TEXTURE_ALPHA_SIZE #x805F) (define GL_TEXTURE_BASE_LEVEL #x813C) (define GL_TEXTURE_BINDING_1D #x8068) (define GL_TEXTURE_BINDING_2D #x8069) (define GL_TEXTURE_BINDING_3D #x806A) (define GL_TEXTURE_BINDING_CUBE_MAP #x8514) (define GL_TEXTURE_BIT #x40000) (define GL_TEXTURE_BLUE_SIZE #x805E) (define GL_TEXTURE_BORDER #x1005) (define GL_TEXTURE_BORDER_COLOR #x1004) (define GL_TEXTURE_COMPARE_FUNC #x884D) (define GL_TEXTURE_COMPARE_MODE #x884C) (define GL_TEXTURE_COMPONENTS #x1003) (define GL_TEXTURE_COMPRESSED #x86A1) (define GL_TEXTURE_COMPRESSED_IMAGE_SIZE #x86A0) (define GL_TEXTURE_COMPRESSION_HINT #x84EF) (define GL_TEXTURE_COORD_ARRAY #x8078) (define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING #x889A) (define GL_TEXTURE_COORD_ARRAY_POINTER #x8092) (define GL_TEXTURE_COORD_ARRAY_SIZE #x8088) (define GL_TEXTURE_COORD_ARRAY_STRIDE #x808A) (define GL_TEXTURE_COORD_ARRAY_TYPE #x8089) (define GL_TEXTURE_CUBE_MAP #x8513) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_X #x8516) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y #x8518) (define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z #x851A) (define GL_TEXTURE_CUBE_MAP_POSITIVE_X #x8515) (define GL_TEXTURE_CUBE_MAP_POSITIVE_Y #x8517) (define GL_TEXTURE_CUBE_MAP_POSITIVE_Z #x8519) (define GL_TEXTURE_DEPTH #x8071) (define GL_TEXTURE_DEPTH_SIZE #x884A) (define GL_TEXTURE_ENV #x2300) (define GL_TEXTURE_ENV_COLOR #x2201) (define GL_TEXTURE_ENV_MODE #x2200) (define GL_TEXTURE_FILTER_CONTROL #x8500) (define GL_TEXTURE_GEN_MODE #x2500) (define GL_TEXTURE_GEN_Q #xC63) (define GL_TEXTURE_GEN_R #xC62) (define GL_TEXTURE_GEN_S #xC60) (define GL_TEXTURE_GEN_T #xC61) (define GL_TEXTURE_GREEN_SIZE #x805D) (define GL_TEXTURE_HEIGHT #x1001) (define GL_TEXTURE_INTENSITY_SIZE #x8061) (define GL_TEXTURE_INTERNAL_FORMAT #x1003) (define GL_TEXTURE_LOD_BIAS #x8501) (define GL_TEXTURE_LUMINANCE_SIZE #x8060) (define GL_TEXTURE_MAG_FILTER #x2800) (define GL_TEXTURE_MATRIX #xBA8) (define GL_TEXTURE_MAX_LEVEL #x813D) (define GL_TEXTURE_MAX_LOD #x813B) (define GL_TEXTURE_MIN_FILTER #x2801) (define GL_TEXTURE_MIN_LOD #x813A) (define GL_TEXTURE_PRIORITY #x8066) (define GL_TEXTURE_RED_SIZE #x805C) (define GL_TEXTURE_RESIDENT #x8067) (define GL_TEXTURE_STACK_DEPTH #xBA5) (define GL_TEXTURE_WIDTH #x1000) (define GL_TEXTURE_WRAP_R #x8072) (define GL_TEXTURE_WRAP_S #x2802) (define GL_TEXTURE_WRAP_T #x2803) (define GL_TRANSFORM_BIT #x1000) (define GL_TRANSPOSE_COLOR_MATRIX #x84E6) (define GL_TRANSPOSE_MODELVIEW_MATRIX #x84E3) (define GL_TRANSPOSE_PROJECTION_MATRIX #x84E4) (define GL_TRANSPOSE_TEXTURE_MATRIX #x84E5) (define GL_TRIANGLES #x4) (define GL_TRIANGLE_FAN #x6) (define GL_TRIANGLE_STRIP #x5) (define GL_TRUE #x1) (define GL_UNPACK_ALIGNMENT #xCF5) (define GL_UNPACK_IMAGE_HEIGHT #x806E) (define GL_UNPACK_LSB_FIRST #xCF1) (define GL_UNPACK_ROW_LENGTH #xCF2) (define GL_UNPACK_SKIP_IMAGES #x806D) (define GL_UNPACK_SKIP_PIXELS #xCF4) (define GL_UNPACK_SKIP_ROWS #xCF3) (define GL_UNPACK_SWAP_BYTES #xCF0) (define GL_UNSIGNED_BYTE #x1401) (define GL_UNSIGNED_BYTE_2_3_3_REV #x8362) (define GL_UNSIGNED_BYTE_3_3_2 #x8032) (define GL_UNSIGNED_INT #x1405) (define GL_UNSIGNED_INT_10_10_10_2 #x8036) (define GL_UNSIGNED_INT_2_10_10_10_REV #x8368) (define GL_UNSIGNED_INT_8_8_8_8 #x8035) (define GL_UNSIGNED_INT_8_8_8_8_REV #x8367) (define GL_UNSIGNED_SHORT #x1403) (define GL_UNSIGNED_SHORT_1_5_5_5_REV #x8366) (define GL_UNSIGNED_SHORT_4_4_4_4 #x8033) (define GL_UNSIGNED_SHORT_4_4_4_4_REV #x8365) (define GL_UNSIGNED_SHORT_5_5_5_1 #x8034) (define GL_UNSIGNED_SHORT_5_6_5 #x8363) (define GL_UNSIGNED_SHORT_5_6_5_REV #x8364) (define GL_UPPER_LEFT #x8CA2) (define GL_V2F #x2A20) (define GL_V3F #x2A21) (define GL_VALIDATE_STATUS #x8B83) (define GL_VENDOR #x1F00) (define GL_VERSION #x1F02) (define GL_VERTEX_ARRAY #x8074) (define GL_VERTEX_ARRAY_BUFFER_BINDING #x8896) (define GL_VERTEX_ARRAY_POINTER #x808E) (define GL_VERTEX_ARRAY_SIZE #x807A) (define GL_VERTEX_ARRAY_STRIDE #x807C) (define GL_VERTEX_ARRAY_TYPE #x807B) (define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING #x889F) (define GL_VERTEX_ATTRIB_ARRAY_ENABLED #x8622) (define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED #x886A) (define GL_VERTEX_ATTRIB_ARRAY_POINTER #x8645) (define GL_VERTEX_ATTRIB_ARRAY_SIZE #x8623) (define GL_VERTEX_ATTRIB_ARRAY_STRIDE #x8624) (define GL_VERTEX_ATTRIB_ARRAY_TYPE #x8625) (define GL_VERTEX_PROGRAM_POINT_SIZE #x8642) (define GL_VERTEX_PROGRAM_TWO_SIDE #x8643) (define GL_VERTEX_SHADER #x8B31) (define GL_VIEWPORT #xBA2) (define GL_VIEWPORT_BIT #x800) (define GL_WEIGHT_ARRAY_BUFFER_BINDING #x889E) (define GL_WRITE_ONLY #x88B9) (define GL_XOR #x1506) (define GL_ZERO #x0) (define GL_ZOOM_X #xD16) (define GL_ZOOM_Y #xD17) )
0288b6a54790423c3eaa8b96654bda52c5df816480d407f1eed7936d1ad3ce28
nirum-lang/nirum
PackageSpec.hs
# LANGUAGE OverloadedLists , OverloadedStrings , QuasiQuotes , ScopedTypeVariables # ScopedTypeVariables #-} module Nirum.PackageSpec where import Data.Either (isLeft, isRight) import Data.Proxy (Proxy (Proxy)) import Data.Text import System.IO.Error (isDoesNotExistError) import Data.Map.Strict (Map) import qualified Data.SemVer as SV import System.FilePath ((</>)) import Test.Hspec.Meta import Text.InterpolatedString.Perl6 (qq) import qualified Text.Parsec.Error as PE import Text.Parsec.Pos (sourceColumn, sourceLine) import Nirum.Constructs.Docs import Nirum.Constructs.Module import Nirum.Constructs.ModulePath (ModulePath) import Nirum.Package hiding (modules, target) import Nirum.Package.Metadata ( Metadata ( Metadata , authors , target , version , description , license , keywords ) , MetadataError (FormatError) , Target (targetName) ) import Nirum.Package.MetadataSpec (DummyTarget (DummyTarget)) import Nirum.Package.ModuleSet ( ImportError (MissingModulePathError) , fromList ) import Nirum.Package.ModuleSetSpec (validModules) import Nirum.Parser (parseFile) import Nirum.Targets.Python (Python (Python)) import Nirum.Targets.Python.CodeGen (minimumRuntime) createPackage :: Target t => Metadata t -> [(ModulePath, Module)] -> Map FilePath Docs -> Package t createPackage metadata' modules' documents' = case fromList modules' of Right ms -> Package metadata' ms documents' Left e -> error $ "errored: " ++ show e createValidPackage :: forall t . Target t => t -> Package t createValidPackage t = createPackage metadata' validModules [] where metadata' :: Metadata t metadata' = Metadata { version = SV.initial , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = t } spec :: Spec spec = do testPackage (Python "nirum-examples" minimumRuntime [] classifiers') testPackage DummyTarget where classifiers' :: [Text] classifiers' = [ "Development Status :: 3 - Alpha" , append "License :: OSI Approved :: " "GNU General Public License v3 or later (GPLv3+)" ] testPackage :: forall t . Target t => t -> Spec testPackage target' = do let targetName' = targetName (Proxy :: Proxy t) validPackage = createValidPackage target' describe [qq|Package (target: $targetName')|] $ do specify "resolveModule" $ do resolveModule ["foo"] validPackage `shouldBe` Just (Module [] $ Just "foo") resolveModule ["foo", "bar"] validPackage `shouldBe` Just (Module [] $ Just "foo.bar") resolveModule ["qux"] validPackage `shouldBe` Just (Module [] $ Just "qux") resolveModule ["baz"] validPackage `shouldBe` Nothing describe "scanPackage" $ do it "returns Package value when all is well" $ do let path = "." </> "examples" package' <- scanPackage' path package' `shouldSatisfy` isRight let Right package = package' Right blockchainM <- parseFile (path </> "blockchain.nrm") Right builtinsM <- parseFile (path </> "builtins.nrm") Right productM <- parseFile (path </> "product.nrm") Right shapesM <- parseFile (path </> "shapes.nrm") Right countriesM <- parseFile (path </> "countries.nrm") Right addressM <- parseFile (path </> "address.nrm") Right pdfServiceM <- parseFile (path </> "pdf-service.nrm") Right geoM <- parseFile (path </> "geo.nrm") let modules = [ (["blockchain"], blockchainM) , (["builtins"], builtinsM) , (["geo"], geoM) , (["product"], productM) , (["shapes"], shapesM) , (["countries"], countriesM) , (["address"], addressM) , (["pdf-service"], pdfServiceM) ] :: [(ModulePath, Module)] let metadata' = Metadata { version = SV.version 0 3 0 [] [] , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = target' } let documents' = [ ( "README.md" , Docs $ Data.Text.concat [ "# Nirum examples\n\nThis directory " , "contains a sample Nirum package.\n" ] ) ] metadata package `shouldBe` metadata' package `shouldBe` createPackage metadata' modules documents' let testDir = "." </> "test" it "returns ScanError if the directory lacks package.toml" $ do scanResult <- scanPackage' $ testDir </> "scan_error" scanResult `shouldSatisfy` isLeft let Left (ScanError filePath ioError') = scanResult filePath `shouldBe` testDir </> "scan_error" </> "package.toml" ioError' `shouldSatisfy` isDoesNotExistError it "returns MetadataError if the package.toml is invalid" $ do scanResult <- scanPackage' $ testDir </> "metadata_error" scanResult `shouldSatisfy` isLeft let Left (MetadataError (FormatError e)) = scanResult sourceLine (PE.errorPos e) `shouldBe` 3 sourceColumn (PE.errorPos e) `shouldBe` 14 it "returns ImportError if a module imports an absent module" $ do scanResult <- scanPackage' $ testDir </> "import_error" scanResult `shouldSatisfy` isLeft let Left (ImportError l) = scanResult l `shouldBe` [MissingModulePathError ["import_error"] ["foo"]] specify "scanModules" $ do let path = "." </> "examples" mods' <- scanModules path mods' `shouldBe` [ (["blockchain"], path </> "blockchain.nrm") , (["builtins"], path </> "builtins.nrm") , (["geo"], path </> "geo.nrm") , (["product"], path </> "product.nrm") , (["shapes"], path </> "shapes.nrm") , (["countries"], path </> "countries.nrm") , (["address"], path </> "address.nrm") , (["pdf-service"], path </> "pdf-service.nrm") ] where scanPackage' :: FilePath -> IO (Either PackageError (Package t)) scanPackage' = scanPackage
null
https://raw.githubusercontent.com/nirum-lang/nirum/4d4488b0524874abc6e693479a5cc70c961bad33/test/Nirum/PackageSpec.hs
haskell
# LANGUAGE OverloadedLists , OverloadedStrings , QuasiQuotes , ScopedTypeVariables # ScopedTypeVariables #-} module Nirum.PackageSpec where import Data.Either (isLeft, isRight) import Data.Proxy (Proxy (Proxy)) import Data.Text import System.IO.Error (isDoesNotExistError) import Data.Map.Strict (Map) import qualified Data.SemVer as SV import System.FilePath ((</>)) import Test.Hspec.Meta import Text.InterpolatedString.Perl6 (qq) import qualified Text.Parsec.Error as PE import Text.Parsec.Pos (sourceColumn, sourceLine) import Nirum.Constructs.Docs import Nirum.Constructs.Module import Nirum.Constructs.ModulePath (ModulePath) import Nirum.Package hiding (modules, target) import Nirum.Package.Metadata ( Metadata ( Metadata , authors , target , version , description , license , keywords ) , MetadataError (FormatError) , Target (targetName) ) import Nirum.Package.MetadataSpec (DummyTarget (DummyTarget)) import Nirum.Package.ModuleSet ( ImportError (MissingModulePathError) , fromList ) import Nirum.Package.ModuleSetSpec (validModules) import Nirum.Parser (parseFile) import Nirum.Targets.Python (Python (Python)) import Nirum.Targets.Python.CodeGen (minimumRuntime) createPackage :: Target t => Metadata t -> [(ModulePath, Module)] -> Map FilePath Docs -> Package t createPackage metadata' modules' documents' = case fromList modules' of Right ms -> Package metadata' ms documents' Left e -> error $ "errored: " ++ show e createValidPackage :: forall t . Target t => t -> Package t createValidPackage t = createPackage metadata' validModules [] where metadata' :: Metadata t metadata' = Metadata { version = SV.initial , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = t } spec :: Spec spec = do testPackage (Python "nirum-examples" minimumRuntime [] classifiers') testPackage DummyTarget where classifiers' :: [Text] classifiers' = [ "Development Status :: 3 - Alpha" , append "License :: OSI Approved :: " "GNU General Public License v3 or later (GPLv3+)" ] testPackage :: forall t . Target t => t -> Spec testPackage target' = do let targetName' = targetName (Proxy :: Proxy t) validPackage = createValidPackage target' describe [qq|Package (target: $targetName')|] $ do specify "resolveModule" $ do resolveModule ["foo"] validPackage `shouldBe` Just (Module [] $ Just "foo") resolveModule ["foo", "bar"] validPackage `shouldBe` Just (Module [] $ Just "foo.bar") resolveModule ["qux"] validPackage `shouldBe` Just (Module [] $ Just "qux") resolveModule ["baz"] validPackage `shouldBe` Nothing describe "scanPackage" $ do it "returns Package value when all is well" $ do let path = "." </> "examples" package' <- scanPackage' path package' `shouldSatisfy` isRight let Right package = package' Right blockchainM <- parseFile (path </> "blockchain.nrm") Right builtinsM <- parseFile (path </> "builtins.nrm") Right productM <- parseFile (path </> "product.nrm") Right shapesM <- parseFile (path </> "shapes.nrm") Right countriesM <- parseFile (path </> "countries.nrm") Right addressM <- parseFile (path </> "address.nrm") Right pdfServiceM <- parseFile (path </> "pdf-service.nrm") Right geoM <- parseFile (path </> "geo.nrm") let modules = [ (["blockchain"], blockchainM) , (["builtins"], builtinsM) , (["geo"], geoM) , (["product"], productM) , (["shapes"], shapesM) , (["countries"], countriesM) , (["address"], addressM) , (["pdf-service"], pdfServiceM) ] :: [(ModulePath, Module)] let metadata' = Metadata { version = SV.version 0 3 0 [] [] , authors = [] , description = Nothing , license = Nothing , keywords = [] , target = target' } let documents' = [ ( "README.md" , Docs $ Data.Text.concat [ "# Nirum examples\n\nThis directory " , "contains a sample Nirum package.\n" ] ) ] metadata package `shouldBe` metadata' package `shouldBe` createPackage metadata' modules documents' let testDir = "." </> "test" it "returns ScanError if the directory lacks package.toml" $ do scanResult <- scanPackage' $ testDir </> "scan_error" scanResult `shouldSatisfy` isLeft let Left (ScanError filePath ioError') = scanResult filePath `shouldBe` testDir </> "scan_error" </> "package.toml" ioError' `shouldSatisfy` isDoesNotExistError it "returns MetadataError if the package.toml is invalid" $ do scanResult <- scanPackage' $ testDir </> "metadata_error" scanResult `shouldSatisfy` isLeft let Left (MetadataError (FormatError e)) = scanResult sourceLine (PE.errorPos e) `shouldBe` 3 sourceColumn (PE.errorPos e) `shouldBe` 14 it "returns ImportError if a module imports an absent module" $ do scanResult <- scanPackage' $ testDir </> "import_error" scanResult `shouldSatisfy` isLeft let Left (ImportError l) = scanResult l `shouldBe` [MissingModulePathError ["import_error"] ["foo"]] specify "scanModules" $ do let path = "." </> "examples" mods' <- scanModules path mods' `shouldBe` [ (["blockchain"], path </> "blockchain.nrm") , (["builtins"], path </> "builtins.nrm") , (["geo"], path </> "geo.nrm") , (["product"], path </> "product.nrm") , (["shapes"], path </> "shapes.nrm") , (["countries"], path </> "countries.nrm") , (["address"], path </> "address.nrm") , (["pdf-service"], path </> "pdf-service.nrm") ] where scanPackage' :: FilePath -> IO (Either PackageError (Package t)) scanPackage' = scanPackage
2e877e608ac1b7aa7aef6bce3f0b09e3298c2bf880b3b77324d4dd64e96cc815
dpiponi/Moodler
nice1.hs
do restart root <- getRoot let out = "out" let keyboard = "keyboard" let trigger = "trigger" adsr74 <- new' "adsr" arpeggiator96 <- new' "arpeggiator" audio_id231 <- new' "audio_id" audio_id233 <- new' "audio_id" audio_id234 <- new' "audio_id" audio_saw7 <- new' "audio_saw" audio_sin8 <- new' "audio_sin" audio_square9 <- new' "audio_square" audio_triangle10 <- new' "audio_triangle" divider419 <- new' "divider" fdn_reverb235 <- new' "fdn_reverb" id100 <- new' "id" id101 <- new' "id" id102 <- new' "id" id103 <- new' "id" id11 <- new' "id" id12 <- new' "id" id13 <- new' "id" id14 <- new' "id" id15 <- new' "id" id16 <- new' "id" id17 <- new' "id" id18 <- new' "id" id190 <- new' "id" id191 <- new' "id" id192 <- new' "id" id193 <- new' "id" id194 <- new' "id" id195 <- new' "id" id236 <- new' "id" id238 <- new' "id" id239 <- new' "id" id97 <- new' "id" id98 <- new' "id" id99 <- new' "id" input19 <- new' "input" input196 <- new' "input" input197 <- new' "input" input198 <- new' "input" input199 <- new' "input" input20 <- new' "input" input200 <- new' "input" input201 <- new' "input" input221 <- new' "input" input232 <- new' "input" input237 <- new' "input" input240 <- new' "input" input241 <- new' "input" input290 <- new' "input" input291 <- new' "input" input311 <- new' "input" input317 <- new' "input" input328 <- new' "input" input68 <- new' "input" input75 <- new' "input" input76 <- new' "input" input77 <- new' "input" input78 <- new' "input" new "input" "keyboard" let keyboard = "keyboard" ladder292 <- new' "ladder" lfo222 <- new' "lfo" lfo318 <- new' "lfo" linear_mix242 <- new' "linear_mix" progression404 <- new' "progression" string_id104 <- new' "string_id" string_id413 <- new' "string_id" string_input105 <- new' "string_input" string_input414 <- new' "string_input" sum21 <- new' "sum" sum280 <- new' "sum" sum286 <- new' "sum" sum293 <- new' "sum" sum4336 <- new' "sum4" new "input" "trigger" let trigger = "trigger" vca243 <- new' "vca" vca310 <- new' "vca" vca327 <- new' "vca" vca67 <- new' "vca" vca92 <- new' "vca" container0 <- container' "panel_keyboard.png" (-684.0,156.0) (Inside root) out1 <- plugout' (keyboard ! "result") (-624.0,180.0) (Outside container0) setColour out1 "#control" out2 <- plugout' (trigger ! "result") (-624.0,132.0) (Outside container0) setColour out2 "#control" container106 <- container' "panel_arpeggiator.png" (-240.0,300.0) (Inside root) container107 <- container' "panel_4x1.png" (0.0,300.0) (Inside container106) in108 <- plugin' (arpeggiator96 ! "pattern") (-21.0,425.0) (Outside container107) setColour in108 "(0, 0, 1)" in109 <- plugin' (arpeggiator96 ! "trigger") (-21.0,375.0) (Outside container107) setColour in109 "#control" in110 <- plugin' (arpeggiator96 ! "reset") (-21.0,325.0) (Outside container107) setColour in110 "#control" in111 <- plugin' (arpeggiator96 ! "root") (-21.0,275.0) (Outside container107) setColour in111 "#control" in112 <- plugin' (arpeggiator96 ! "interval1") (-21.0,225.0) (Outside container107) setColour in112 "#control" in113 <- plugin' (arpeggiator96 ! "interval2") (-21.0,175.0) (Outside container107) setColour in113 "#control" label114 <- label' "arpeggiator" (-25.0,375.0) (Outside container107) out115 <- plugout' (arpeggiator96 ! "result") (20.0,325.0) (Outside container107) setColour out115 "#control" out116 <- plugout' (arpeggiator96 ! "gate") (20.0,275.0) (Outside container107) setColour out116 "#control" in117 <- plugin' (id97 ! "signal") (44.0,127.0) (Inside container106) setColour in117 "#control" in118 <- plugin' (id98 ! "signal") (56.0,367.0) (Inside container106) setColour in118 "#control" out119 <- plugout' (id99 ! "result") (-119.0,355.0) (Inside container106) setColour out119 "#control" out120 <- plugout' (id100 ! "result") (-119.0,295.0) (Inside container106) setColour out120 "#control" out121 <- plugout' (id101 ! "result") (-119.0,247.0) (Inside container106) setColour out121 "#control" out122 <- plugout' (id102 ! "result") (-119.0,187.0) (Inside container106) setColour out122 "#control" out123 <- plugout' (id103 ! "result") (-119.0,403.0) (Inside container106) setColour out123 "#control" out124 <- plugout' (string_id104 ! "result") (-118.0,469.0) (Inside container106) setColour out124 "(0, 0, 1)" in125 <- plugin' (id99 ! "signal") (-324.0,324.0) (Outside container106) setColour in125 "#control" in126 <- plugin' (id100 ! "signal") (-324.0,252.0) (Outside container106) setColour in126 "#control" in127 <- plugin' (id101 ! "signal") (-324.0,216.0) (Outside container106) setColour in127 "#control" in128 <- plugin' (id102 ! "signal") (-324.0,180.0) (Outside container106) setColour in128 "#control" in129 <- plugin' (id103 ! "signal") (-324.0,288.0) (Outside container106) setColour in129 "#control" in130 <- plugin' (string_id104 ! "input") (-312.0,360.0) (Outside container106) setColour in130 "(0, 0, 1)" hide in130 out131 <- plugout' (id97 ! "result") (-156.0,180.0) (Outside container106) setColour out131 "#control" out132 <- plugout' (id98 ! "result") (-156.0,216.0) (Outside container106) setColour out132 "#control" textBox133 <- textBox' (string_input105 ! "result") (-312.0,372.0) (Outside container106) container202 <- container' "panel_knobs.png" (-528.0,-228.0) (Inside root) in203 <- plugin' (id190 ! "signal") (-552.0,-264.0) (Outside container202) setColour in203 "#control" hide in203 in204 <- plugin' (id192 ! "signal") (-504.0,-264.0) (Outside container202) setColour in204 "#control" hide in204 in205 <- plugin' (id193 ! "signal") (-456.0,-264.0) (Outside container202) setColour in205 "#control" hide in205 in206 <- plugin' (id194 ! "signal") (-408.0,-264.0) (Outside container202) setColour in206 "#control" hide in206 in207 <- plugin' (id195 ! "signal") (-648.0,-264.0) (Outside container202) setColour in207 "#control" hide in207 in208 <- plugin' (id191 ! "signal") (-600.0,-264.0) (Outside container202) setColour in208 "#control" hide in208 knob209 <- knob' (input197 ! "result") (-600.0,-228.0) (Outside container202) knob210 <- knob' (input196 ! "result") (-552.0,-228.0) (Outside container202) knob211 <- knob' (input198 ! "result") (-504.0,-228.0) (Outside container202) knob212 <- knob' (input199 ! "result") (-456.0,-228.0) (Outside container202) knob213 <- knob' (input200 ! "result") (-408.0,-228.0) (Outside container202) knob214 <- knob' (input201 ! "result") (-648.0,-228.0) (Outside container202) out215 <- plugout' (id191 ! "result") (-600.0,-264.0) (Outside container202) setColour out215 "#control" out216 <- plugout' (id190 ! "result") (-552.0,-264.0) (Outside container202) setColour out216 "#control" out217 <- plugout' (id192 ! "result") (-504.0,-264.0) (Outside container202) setColour out217 "#control" out218 <- plugout' (id193 ! "result") (-456.0,-264.0) (Outside container202) setColour out218 "#control" out219 <- plugout' (id194 ! "result") (-408.0,-264.0) (Outside container202) setColour out219 "#control" out220 <- plugout' (id195 ! "result") (-648.0,-264.0) (Outside container202) setColour out220 "#control" container22 <- container' "panel_vco2.png" (36.0,120.0) (Inside root) container23 <- container' "panel_3x1.png" (-443.0,115.0) (Inside container22) container24 <- container' "panel_3x1.png" (-62.0,96.0) (Inside container22) container25 <- container' "panel_3x1.png" (54.0,-33.0) (Inside container22) container26 <- container' "panel_3x1.png" (-319.0,129.0) (Inside container22) container27 <- container' "panel_3x1.png" (-454.0,-125.0) (Inside container22) in28 <- plugin' (sum21 ! "signal2") (-464.0,90.0) (Inside container22) setColour in28 "#sample" in29 <- plugin' (sum21 ! "signal1") (-464.0,140.0) (Inside container22) setColour in29 "#sample" in30 <- plugin' (audio_triangle10 ! "freq") (-83.0,121.0) (Inside container22) setColour in30 "#sample" in31 <- plugin' (audio_triangle10 ! "sync") (-83.0,71.0) (Inside container22) setColour in31 "#sample" in32 <- plugin' (audio_saw7 ! "freq") (33.0,-8.0) (Inside container22) setColour in32 "#sample" in33 <- plugin' (audio_saw7 ! "sync") (33.0,-58.0) (Inside container22) setColour in33 "#sample" in34 <- plugin' (audio_sin8 ! "freq") (-340.0,154.0) (Inside container22) setColour in34 "#sample" in35 <- plugin' (audio_sin8 ! "sync") (-340.0,104.0) (Inside container22) setColour in35 "#sample" in36 <- plugin' (audio_square9 ! "pwm") (-475.0,-125.0) (Inside container22) setColour in36 "#sample" in37 <- plugin' (audio_square9 ! "sync") (-475.0,-175.0) (Inside container22) setColour in37 "#sample" in38 <- plugin' (audio_square9 ! "freq") (-475.0,-75.0) (Inside container22) setColour in38 "#sample" in39 <- plugin' (id11 ! "signal") (-381.0,-126.0) (Inside container22) setColour in39 "#sample" in40 <- plugin' (id12 ! "signal") (12.0,98.0) (Inside container22) setColour in40 "#sample" in41 <- plugin' (id13 ! "signal") (125.0,-32.0) (Inside container22) setColour in41 "#sample" in42 <- plugin' (id14 ! "signal") (-184.0,125.0) (Inside container22) setColour in42 "#sample" label43 <- label' "sum" (-468.0,190.0) (Inside container22) label44 <- label' "audio_triangle" (-87.0,171.0) (Inside container22) label45 <- label' "audio_saw" (29.0,42.0) (Inside container22) label46 <- label' "audio_sin" (-344.0,204.0) (Inside container22) label47 <- label' "audio_square" (-479.0,-50.0) (Inside container22) out48 <- plugout' (sum21 ! "result") (-423.0,115.0) (Inside container22) setColour out48 "#sample" out49 <- plugout' (audio_triangle10 ! "result") (-42.0,96.0) (Inside container22) setColour out49 "#sample" out50 <- plugout' (audio_saw7 ! "result") (74.0,-33.0) (Inside container22) setColour out50 "#sample" out51 <- plugout' (audio_sin8 ! "result") (-299.0,129.0) (Inside container22) setColour out51 "#sample" out52 <- plugout' (audio_square9 ! "result") (-434.0,-125.0) (Inside container22) setColour out52 "#sample" out53 <- plugout' (id15 ! "result") (-519.0,89.0) (Inside container22) setColour out53 "#sample" out54 <- plugout' (id16 ! "result") (-520.0,145.0) (Inside container22) setColour out54 "#sample" out55 <- plugout' (id17 ! "result") (-522.0,-125.0) (Inside container22) setColour out55 "#sample" out56 <- plugout' (id18 ! "result") (-521.0,-178.0) (Inside container22) setColour out56 "#sample" in57 <- plugin' (id15 ! "signal") (72.0,156.0) (Outside container22) setColour in57 "#control" in58 <- plugin' (id16 ! "signal") (49.0,200.0) (Outside container22) setColour in58 "#sample" hide in58 in59 <- plugin' (id17 ! "signal") (67.0,123.0) (Outside container22) setColour in59 "#sample" hide in59 in60 <- plugin' (id18 ! "signal") (72.0,84.0) (Outside container22) setColour in60 "#control" knob61 <- knob' (input20 ! "result") (72.0,120.0) (Outside container22) knob62 <- knob' (input19 ! "result") (72.0,192.0) (Outside container22) out63 <- plugout' (id14 ! "result") (12.0,36.0) (Outside container22) setColour out63 "#sample" out64 <- plugout' (id11 ! "result") (84.0,36.0) (Outside container22) setColour out64 "#sample" out65 <- plugout' (id12 ! "result") (12.0,0.0) (Outside container22) setColour out65 "#sample" out66 <- plugout' (id13 ! "result") (84.0,0.0) (Outside container22) setColour out66 "#sample" container223 <- container' "panel_lfo.png" (-624.0,468.0) (Inside root) in224 <- plugin' (lfo222 ! "sync") (-612.0,492.0) (Outside container223) setColour in224 "#control" in225 <- plugin' (lfo222 ! "rate") (-627.0,523.0) (Outside container223) setColour in225 "#control" hide in225 knob226 <- knob' (input221 ! "result") (-612.0,540.0) (Outside container223) out227 <- plugout' (lfo222 ! "triangle") (-636.0,348.0) (Outside container223) setColour out227 "#control" out228 <- plugout' (lfo222 ! "saw") (-576.0,348.0) (Outside container223) setColour out228 "#control" out229 <- plugout' (lfo222 ! "sin_result") (-636.0,384.0) (Outside container223) setColour out229 "#control" out230 <- plugout' (lfo222 ! "square_result") (-576.0,384.0) (Outside container223) setColour out230 "#control" container244 <- container' "panel_reverb.png" (564.0,396.0) (Inside root) container245 <- container' "panel_3x1.png" (1428.0,-936.0) (Inside container244) in246 <- plugin' (vca243 ! "cv") (1407.0,-911.0) (Outside container245) setColour in246 "#control" in247 <- plugin' (vca243 ! "signal") (1407.0,-961.0) (Outside container245) setColour in247 "#sample" label248 <- label' "vca" (1403.0,-861.0) (Outside container245) out249 <- plugout' (vca243 ! "result") (1448.0,-936.0) (Outside container245) setColour out249 "#sample" container250 <- container' "panel_3x1.png" (1296.0,-768.0) (Inside container244) in251 <- plugin' (fdn_reverb235 ! "decay") (1275.0,-718.0) (Outside container250) setColour in251 "#control" hide in251 in252 <- plugin' (fdn_reverb235 ! "hf_decay") (1275.0,-768.0) (Outside container250) setColour in252 "#control" hide in252 in253 <- plugin' (fdn_reverb235 ! "signal") (1275.0,-818.0) (Outside container250) setColour in253 "#sample" label254 <- label' "fdn_reverb" (1271.0,-693.0) (Outside container250) out255 <- plugout' (fdn_reverb235 ! "result") (1316.0,-768.0) (Outside container250) setColour out255 "#sample" container256 <- container' "panel_3x1.png" (1524.0,-756.0) (Inside container244) in257 <- plugin' (linear_mix242 ! "gain") (1503.0,-706.0) (Outside container256) setColour in257 "#control" in258 <- plugin' (linear_mix242 ! "signal1") (1503.0,-756.0) (Outside container256) setColour in258 "#sample" in259 <- plugin' (linear_mix242 ! "signal2") (1503.0,-806.0) (Outside container256) setColour in259 "#sample" label260 <- label' "linear_mix" (1499.0,-681.0) (Outside container256) out261 <- plugout' (linear_mix242 ! "result") (1544.0,-756.0) (Outside container256) setColour out261 "#sample" in262 <- plugin' (audio_id234 ! "signal") (1593.0,-875.0) (Inside container244) setColour in262 "#sample" out263 <- plugout' (audio_id231 ! "result") (1478.0,-611.0) (Inside container244) setColour out263 "#sample" out264 <- plugout' (id236 ! "result") (1333.0,-917.0) (Inside container244) setColour out264 "#control" out265 <- plugout' (id238 ! "result") (1165.0,-725.0) (Inside container244) setColour out265 "#control" out266 <- plugout' (id239 ! "result") (1165.0,-797.0) (Inside container244) setColour out266 "#control" out267 <- plugout' (audio_id233 ! "result") (1370.0,-635.0) (Inside container244) setColour out267 "#sample" in268 <- plugin' (audio_id231 ! "signal") (513.0,301.0) (Outside container244) setColour in268 "#sample" hide in268 in269 <- plugin' (id236 ! "signal") (516.0,348.0) (Outside container244) setColour in269 "#control" hide in269 in270 <- plugin' (id238 ! "signal") (564.0,456.0) (Outside container244) setColour in270 "#control" hide in270 in271 <- plugin' (id239 ! "signal") (516.0,396.0) (Outside container244) setColour in271 "#control" hide in271 in272 <- plugin' (audio_id233 ! "signal") (516.0,492.0) (Outside container244) setColour in272 "#sample" knob273 <- knob' (input237 ! "result") (516.0,348.0) (Outside container244) knob274 <- knob' (input232 ! "result") (516.0,300.0) (Outside container244) knob275 <- knob' (input240 ! "result") (516.0,444.0) (Outside container244) knob276 <- knob' (input241 ! "result") (516.0,396.0) (Outside container244) out277 <- plugout' (audio_id234 ! "result") (612.0,276.0) (Outside container244) setColour out277 "#sample" container278 <- container' "panel_3x1.png" (-384.0,-24.0) (Inside root) in281 <- plugin' (sum280 ! "signal1") (-405.0,1.0) (Outside container278) setColour in281 "#sample" in282 <- plugin' (sum280 ! "signal2") (-405.0,-49.0) (Outside container278) setColour in282 "#sample" label279 <- label' "sum" (-409.0,51.0) (Outside container278) out283 <- plugout' (sum280 ! "result") (-364.0,-24.0) (Outside container278) setColour out283 "#sample" container284 <- container' "panel_3x1.png" (-288.0,-48.0) (Inside root) in287 <- plugin' (sum286 ! "signal1") (-309.0,-23.0) (Outside container284) setColour in287 "#sample" in288 <- plugin' (sum286 ! "signal2") (-309.0,-73.0) (Outside container284) setColour in288 "#sample" label285 <- label' "sum" (-313.0,27.0) (Outside container284) out289 <- plugout' (sum286 ! "result") (-268.0,-48.0) (Outside container284) setColour out289 "#sample" container294 <- container' "panel_ladder.png" (204.0,-180.0) (Inside root) in295 <- plugin' (ladder292 ! "signal") (156.0,-300.0) (Outside container294) setColour in295 "#sample" in296 <- plugin' (sum293 ! "signal1") (241.0,-109.0) (Outside container294) setColour in296 "#sample" hide in296 in297 <- plugin' (sum293 ! "signal2") (204.0,-108.0) (Outside container294) setColour in297 "#control" in298 <- plugin' (ladder292 ! "freq") (215.0,-155.0) (Outside container294) setColour in298 "#sample" hide in298 in299 <- plugin' (ladder292 ! "res") (238.0,-192.0) (Outside container294) setColour in299 "#sample" hide in299 knob300 <- knob' (input290 ! "result") (252.0,-168.0) (Outside container294) setLow knob300 (Just (0.0)) setHigh knob300 (Just (3.999)) knob301 <- knob' (input291 ! "result") (252.0,-108.0) (Outside container294) setLow knob301 (Just (-1.0)) setHigh knob301 (Just (0.7)) out302 <- plugout' (ladder292 ! "result") (252.0,-300.0) (Outside container294) setColour out302 "#sample" out303 <- plugout' (sum293 ! "result") (157.0,-152.0) (Outside container294) setColour out303 "#sample" hide out303 container3 <- container' "panel_out.png" (444.0,24.0) (Inside root) in4 <- plugin' (out ! "left") (420.0,72.0) (Outside container3) setColour in4 "#sample" in5 <- plugin' (out ! "value") (420.0,24.0) (Outside container3) setOutput in5 setColour in5 "#sample" in6 <- plugin' (out ! "right") (420.0,-24.0) (Outside container3) setColour in6 "#sample" container312 <- container' "panel_gain.png" (-132.0,-504.0) (Inside root) in313 <- plugin' (vca310 ! "cv") (-156.0,-504.0) (Outside container312) setColour in313 "#control" hide in313 in314 <- plugin' (vca310 ! "signal") (-192.0,-504.0) (Outside container312) setColour in314 "#sample" knob315 <- knob' (input311 ! "result") (-156.0,-504.0) (Outside container312) out316 <- plugout' (vca310 ! "result") (-72.0,-504.0) (Outside container312) setColour out316 "#sample" container319 <- container' "panel_lfo.png" (-492.0,-456.0) (Inside root) in320 <- plugin' (lfo318 ! "sync") (-480.0,-432.0) (Outside container319) setColour in320 "#control" in321 <- plugin' (lfo318 ! "rate") (-495.0,-401.0) (Outside container319) setColour in321 "#control" hide in321 knob322 <- knob' (input317 ! "result") (-480.0,-384.0) (Outside container319) out323 <- plugout' (lfo318 ! "triangle") (-504.0,-576.0) (Outside container319) setColour out323 "#control" out324 <- plugout' (lfo318 ! "saw") (-444.0,-576.0) (Outside container319) setColour out324 "#control" out325 <- plugout' (lfo318 ! "sin_result") (-504.0,-540.0) (Outside container319) setColour out325 "#control" out326 <- plugout' (lfo318 ! "square_result") (-444.0,-540.0) (Outside container319) setColour out326 "#control" container329 <- container' "panel_gain.png" (-228.0,-576.0) (Inside root) in330 <- plugin' (vca327 ! "cv") (-252.0,-576.0) (Outside container329) setColour in330 "#control" hide in330 in331 <- plugin' (vca327 ! "signal") (-288.0,-576.0) (Outside container329) setColour in331 "#sample" knob332 <- knob' (input328 ! "result") (-252.0,-576.0) (Outside container329) out333 <- plugout' (vca327 ! "result") (-168.0,-576.0) (Outside container329) setColour out333 "#sample" container334 <- container' "panel_4x1.png" (132.0,-480.0) (Inside root) in337 <- plugin' (sum4336 ! "signal1") (111.0,-405.0) (Outside container334) setColour in337 "#sample" in338 <- plugin' (sum4336 ! "signal2") (111.0,-455.0) (Outside container334) setColour in338 "#sample" in339 <- plugin' (sum4336 ! "signal3") (111.0,-505.0) (Outside container334) setColour in339 "#sample" in340 <- plugin' (sum4336 ! "signal4") (111.0,-555.0) (Outside container334) setColour in340 "#sample" label335 <- label' "sum4" (107.0,-405.0) (Outside container334) out341 <- plugout' (sum4336 ! "result") (152.0,-480.0) (Outside container334) setColour out341 "#sample" container402 <- container' "panel_4x1.png" (36.0,444.0) (Inside root) in405 <- plugin' (progression404 ! "pattern") (15.0,519.0) (Outside container402) setColour in405 "(0, 0, 1)" in406 <- plugin' (progression404 ! "root") (15.0,469.0) (Outside container402) setColour in406 "#control" in407 <- plugin' (progression404 ! "trigger") (15.0,419.0) (Outside container402) setColour in407 "#control" in408 <- plugin' (progression404 ! "reset") (15.0,369.0) (Outside container402) setColour in408 "#control" label403 <- label' "progression" (11.0,519.0) (Outside container402) out409 <- plugout' (progression404 ! "sync") (56.0,519.0) (Outside container402) setColour out409 "#control" out410 <- plugout' (progression404 ! "note1") (56.0,469.0) (Outside container402) setColour out410 "#control" out411 <- plugout' (progression404 ! "note2") (56.0,419.0) (Outside container402) setColour out411 "#control" out412 <- plugout' (progression404 ! "note3") (56.0,369.0) (Outside container402) setColour out412 "#control" container415 <- container' "panel_textbox.png" (-228.0,528.0) (Inside root) in416 <- plugin' (string_id413 ! "input") (-240.0,528.0) (Outside container415) setColour in416 "#control" hide in416 out417 <- plugout' (string_id413 ! "result") (-132.0,528.0) (Outside container415) setColour out417 "#control" textBox418 <- textBox' (string_input414 ! "result") (-300.0,528.0) (Outside container415) container420 <- container' "panel_divider.png" (-456.0,468.0) (Inside root) in421 <- plugin' (divider419 ! "gate") (-480.0,492.0) (Outside container420) setColour in421 "#control" out422 <- plugout' (divider419 ! "div32") (-432.0,348.0) (Outside container420) setColour out422 "#control" out423 <- plugout' (divider419 ! "div02") (-432.0,540.0) (Outside container420) setColour out423 "#control" out424 <- plugout' (divider419 ! "div04") (-432.0,492.0) (Outside container420) setColour out424 "#control" out425 <- plugout' (divider419 ! "div08") (-432.0,444.0) (Outside container420) setColour out425 "#control" out426 <- plugout' (divider419 ! "div16") (-432.0,396.0) (Outside container420) setColour out426 "#control" container69 <- container' "panel_gain.png" (276.0,108.0) (Inside root) in70 <- plugin' (vca67 ! "cv") (252.0,108.0) (Outside container69) setColour in70 "#control" hide in70 in71 <- plugin' (vca67 ! "signal") (216.0,108.0) (Outside container69) setColour in71 "#sample" knob72 <- knob' (input68 ! "result") (252.0,108.0) (Outside container69) out73 <- plugout' (vca67 ! "result") (336.0,108.0) (Outside container69) setColour out73 "#sample" container79 <- container' "panel_adsr.png" (-180.0,-204.0) (Inside root) in80 <- plugin' (adsr74 ! "attack") (-208.0,-147.0) (Outside container79) setColour in80 "#sample" hide in80 in81 <- plugin' (adsr74 ! "decay") (-155.0,-130.0) (Outside container79) setColour in81 "#sample" hide in81 in82 <- plugin' (adsr74 ! "sustain") (-155.0,-180.0) (Outside container79) setColour in82 "#sample" hide in82 in83 <- plugin' (adsr74 ! "release") (-155.0,-230.0) (Outside container79) setColour in83 "#sample" hide in83 in84 <- plugin' (adsr74 ! "gate") (-144.0,-276.0) (Outside container79) setColour in84 "#control" knob85 <- knob' (input75 ! "result") (-204.0,-144.0) (Outside container79) setLow knob85 (Just (0.0)) knob86 <- knob' (input76 ! "result") (-144.0,-144.0) (Outside container79) setLow knob86 (Just (0.0)) knob87 <- knob' (input78 ! "result") (-204.0,-192.0) (Outside container79) setLow knob87 (Just (0.0)) knob88 <- knob' (input77 ! "result") (-144.0,-192.0) (Outside container79) setLow knob88 (Just (0.0)) out89 <- plugout' (adsr74 ! "result") (-144.0,-312.0) (Outside container79) setColour out89 "#control" container90 <- container' "panel_3x1.png" (360.0,-144.0) (Inside root) in93 <- plugin' (vca92 ! "cv") (339.0,-119.0) (Outside container90) setColour in93 "#control" in94 <- plugin' (vca92 ! "signal") (339.0,-169.0) (Outside container90) setColour in94 "#sample" label91 <- label' "vca" (335.0,-69.0) (Outside container90) out95 <- plugout' (vca92 ! "result") (380.0,-144.0) (Outside container90) setColour out95 "#sample" cable out124 in108 cable out123 in109 cable out119 in110 cable out120 in111 cable out121 in112 cable out122 in113 cable out115 in117 cable out116 in118 cable out2 in125 cable out410 in126 cable out411 in127 cable out412 in128 cable out230 in129 cable textBox133 in130 cable knob210 in203 cable knob211 in204 cable knob212 in205 cable knob213 in206 cable knob214 in207 cable knob209 in208 cable out53 in28 cable out54 in29 cable out48 in30 cable out56 in31 cable out48 in32 cable out56 in33 cable out48 in34 cable out56 in35 cable out55 in36 cable out56 in37 cable out48 in38 cable out52 in39 cable out49 in40 cable out50 in41 cable out51 in42 cable out131 in57 cable knob62 in58 cable knob61 in59 cable knob226 in225 cable out264 in246 cable out255 in247 cable out265 in251 cable out266 in252 cable out267 in253 cable out263 in257 cable out267 in258 cable out249 in259 cable out261 in262 cable knob274 in268 cable knob273 in269 cable knob275 in270 cable knob276 in271 cable out95 in272 cable out1 in281 cable out220 in282 cable out1 in287 cable out215 in288 cable out66 in295 cable knob301 in296 cable out341 in297 cable out303 in298 cable knob300 in299 cable out73 in5 cable knob315 in313 cable out89 in314 cable knob322 in321 cable knob332 in330 cable out325 in331 cable out131 in337 cable out316 in338 cable out333 in339 cable out417 in405 cable out1 in406 cable out426 in407 cable out2 in408 cable textBox418 in416 cable out230 in421 cable knob72 in70 cable out277 in71 cable knob85 in80 cable knob86 in81 cable knob87 in82 cable knob88 in83 cable out132 in84 cable out89 in93 cable out302 in94 recompile setString textBox133 ("aebdccdb") set knob209 (3.3333335e-2) set knob210 (0.0) set knob211 (0.0) set knob212 (0.0) set knob213 (-4.2050842e-2) set knob214 (-8.333334e-3) set knob61 (0.0) set knob62 (0.0) set knob226 (6.0) set knob273 (4.727709) set knob274 (0.41996497) set knob275 (1.0626922) set knob276 (2.0e-2) set knob300 (1.6330826) set knob301 (0.46105152) set knob315 (4.2856134e-2) set knob322 (0.18982339) set knob332 (0.2527409) setString textBox418 ("i-iv-iio-viio-V") set knob72 (7.0e-2) set knob85 (1.6847253e-2) set knob86 (0.65) set knob87 (0.30396026) set knob88 (0.32829148) return ()
null
https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/saves/nice1.hs
haskell
do restart root <- getRoot let out = "out" let keyboard = "keyboard" let trigger = "trigger" adsr74 <- new' "adsr" arpeggiator96 <- new' "arpeggiator" audio_id231 <- new' "audio_id" audio_id233 <- new' "audio_id" audio_id234 <- new' "audio_id" audio_saw7 <- new' "audio_saw" audio_sin8 <- new' "audio_sin" audio_square9 <- new' "audio_square" audio_triangle10 <- new' "audio_triangle" divider419 <- new' "divider" fdn_reverb235 <- new' "fdn_reverb" id100 <- new' "id" id101 <- new' "id" id102 <- new' "id" id103 <- new' "id" id11 <- new' "id" id12 <- new' "id" id13 <- new' "id" id14 <- new' "id" id15 <- new' "id" id16 <- new' "id" id17 <- new' "id" id18 <- new' "id" id190 <- new' "id" id191 <- new' "id" id192 <- new' "id" id193 <- new' "id" id194 <- new' "id" id195 <- new' "id" id236 <- new' "id" id238 <- new' "id" id239 <- new' "id" id97 <- new' "id" id98 <- new' "id" id99 <- new' "id" input19 <- new' "input" input196 <- new' "input" input197 <- new' "input" input198 <- new' "input" input199 <- new' "input" input20 <- new' "input" input200 <- new' "input" input201 <- new' "input" input221 <- new' "input" input232 <- new' "input" input237 <- new' "input" input240 <- new' "input" input241 <- new' "input" input290 <- new' "input" input291 <- new' "input" input311 <- new' "input" input317 <- new' "input" input328 <- new' "input" input68 <- new' "input" input75 <- new' "input" input76 <- new' "input" input77 <- new' "input" input78 <- new' "input" new "input" "keyboard" let keyboard = "keyboard" ladder292 <- new' "ladder" lfo222 <- new' "lfo" lfo318 <- new' "lfo" linear_mix242 <- new' "linear_mix" progression404 <- new' "progression" string_id104 <- new' "string_id" string_id413 <- new' "string_id" string_input105 <- new' "string_input" string_input414 <- new' "string_input" sum21 <- new' "sum" sum280 <- new' "sum" sum286 <- new' "sum" sum293 <- new' "sum" sum4336 <- new' "sum4" new "input" "trigger" let trigger = "trigger" vca243 <- new' "vca" vca310 <- new' "vca" vca327 <- new' "vca" vca67 <- new' "vca" vca92 <- new' "vca" container0 <- container' "panel_keyboard.png" (-684.0,156.0) (Inside root) out1 <- plugout' (keyboard ! "result") (-624.0,180.0) (Outside container0) setColour out1 "#control" out2 <- plugout' (trigger ! "result") (-624.0,132.0) (Outside container0) setColour out2 "#control" container106 <- container' "panel_arpeggiator.png" (-240.0,300.0) (Inside root) container107 <- container' "panel_4x1.png" (0.0,300.0) (Inside container106) in108 <- plugin' (arpeggiator96 ! "pattern") (-21.0,425.0) (Outside container107) setColour in108 "(0, 0, 1)" in109 <- plugin' (arpeggiator96 ! "trigger") (-21.0,375.0) (Outside container107) setColour in109 "#control" in110 <- plugin' (arpeggiator96 ! "reset") (-21.0,325.0) (Outside container107) setColour in110 "#control" in111 <- plugin' (arpeggiator96 ! "root") (-21.0,275.0) (Outside container107) setColour in111 "#control" in112 <- plugin' (arpeggiator96 ! "interval1") (-21.0,225.0) (Outside container107) setColour in112 "#control" in113 <- plugin' (arpeggiator96 ! "interval2") (-21.0,175.0) (Outside container107) setColour in113 "#control" label114 <- label' "arpeggiator" (-25.0,375.0) (Outside container107) out115 <- plugout' (arpeggiator96 ! "result") (20.0,325.0) (Outside container107) setColour out115 "#control" out116 <- plugout' (arpeggiator96 ! "gate") (20.0,275.0) (Outside container107) setColour out116 "#control" in117 <- plugin' (id97 ! "signal") (44.0,127.0) (Inside container106) setColour in117 "#control" in118 <- plugin' (id98 ! "signal") (56.0,367.0) (Inside container106) setColour in118 "#control" out119 <- plugout' (id99 ! "result") (-119.0,355.0) (Inside container106) setColour out119 "#control" out120 <- plugout' (id100 ! "result") (-119.0,295.0) (Inside container106) setColour out120 "#control" out121 <- plugout' (id101 ! "result") (-119.0,247.0) (Inside container106) setColour out121 "#control" out122 <- plugout' (id102 ! "result") (-119.0,187.0) (Inside container106) setColour out122 "#control" out123 <- plugout' (id103 ! "result") (-119.0,403.0) (Inside container106) setColour out123 "#control" out124 <- plugout' (string_id104 ! "result") (-118.0,469.0) (Inside container106) setColour out124 "(0, 0, 1)" in125 <- plugin' (id99 ! "signal") (-324.0,324.0) (Outside container106) setColour in125 "#control" in126 <- plugin' (id100 ! "signal") (-324.0,252.0) (Outside container106) setColour in126 "#control" in127 <- plugin' (id101 ! "signal") (-324.0,216.0) (Outside container106) setColour in127 "#control" in128 <- plugin' (id102 ! "signal") (-324.0,180.0) (Outside container106) setColour in128 "#control" in129 <- plugin' (id103 ! "signal") (-324.0,288.0) (Outside container106) setColour in129 "#control" in130 <- plugin' (string_id104 ! "input") (-312.0,360.0) (Outside container106) setColour in130 "(0, 0, 1)" hide in130 out131 <- plugout' (id97 ! "result") (-156.0,180.0) (Outside container106) setColour out131 "#control" out132 <- plugout' (id98 ! "result") (-156.0,216.0) (Outside container106) setColour out132 "#control" textBox133 <- textBox' (string_input105 ! "result") (-312.0,372.0) (Outside container106) container202 <- container' "panel_knobs.png" (-528.0,-228.0) (Inside root) in203 <- plugin' (id190 ! "signal") (-552.0,-264.0) (Outside container202) setColour in203 "#control" hide in203 in204 <- plugin' (id192 ! "signal") (-504.0,-264.0) (Outside container202) setColour in204 "#control" hide in204 in205 <- plugin' (id193 ! "signal") (-456.0,-264.0) (Outside container202) setColour in205 "#control" hide in205 in206 <- plugin' (id194 ! "signal") (-408.0,-264.0) (Outside container202) setColour in206 "#control" hide in206 in207 <- plugin' (id195 ! "signal") (-648.0,-264.0) (Outside container202) setColour in207 "#control" hide in207 in208 <- plugin' (id191 ! "signal") (-600.0,-264.0) (Outside container202) setColour in208 "#control" hide in208 knob209 <- knob' (input197 ! "result") (-600.0,-228.0) (Outside container202) knob210 <- knob' (input196 ! "result") (-552.0,-228.0) (Outside container202) knob211 <- knob' (input198 ! "result") (-504.0,-228.0) (Outside container202) knob212 <- knob' (input199 ! "result") (-456.0,-228.0) (Outside container202) knob213 <- knob' (input200 ! "result") (-408.0,-228.0) (Outside container202) knob214 <- knob' (input201 ! "result") (-648.0,-228.0) (Outside container202) out215 <- plugout' (id191 ! "result") (-600.0,-264.0) (Outside container202) setColour out215 "#control" out216 <- plugout' (id190 ! "result") (-552.0,-264.0) (Outside container202) setColour out216 "#control" out217 <- plugout' (id192 ! "result") (-504.0,-264.0) (Outside container202) setColour out217 "#control" out218 <- plugout' (id193 ! "result") (-456.0,-264.0) (Outside container202) setColour out218 "#control" out219 <- plugout' (id194 ! "result") (-408.0,-264.0) (Outside container202) setColour out219 "#control" out220 <- plugout' (id195 ! "result") (-648.0,-264.0) (Outside container202) setColour out220 "#control" container22 <- container' "panel_vco2.png" (36.0,120.0) (Inside root) container23 <- container' "panel_3x1.png" (-443.0,115.0) (Inside container22) container24 <- container' "panel_3x1.png" (-62.0,96.0) (Inside container22) container25 <- container' "panel_3x1.png" (54.0,-33.0) (Inside container22) container26 <- container' "panel_3x1.png" (-319.0,129.0) (Inside container22) container27 <- container' "panel_3x1.png" (-454.0,-125.0) (Inside container22) in28 <- plugin' (sum21 ! "signal2") (-464.0,90.0) (Inside container22) setColour in28 "#sample" in29 <- plugin' (sum21 ! "signal1") (-464.0,140.0) (Inside container22) setColour in29 "#sample" in30 <- plugin' (audio_triangle10 ! "freq") (-83.0,121.0) (Inside container22) setColour in30 "#sample" in31 <- plugin' (audio_triangle10 ! "sync") (-83.0,71.0) (Inside container22) setColour in31 "#sample" in32 <- plugin' (audio_saw7 ! "freq") (33.0,-8.0) (Inside container22) setColour in32 "#sample" in33 <- plugin' (audio_saw7 ! "sync") (33.0,-58.0) (Inside container22) setColour in33 "#sample" in34 <- plugin' (audio_sin8 ! "freq") (-340.0,154.0) (Inside container22) setColour in34 "#sample" in35 <- plugin' (audio_sin8 ! "sync") (-340.0,104.0) (Inside container22) setColour in35 "#sample" in36 <- plugin' (audio_square9 ! "pwm") (-475.0,-125.0) (Inside container22) setColour in36 "#sample" in37 <- plugin' (audio_square9 ! "sync") (-475.0,-175.0) (Inside container22) setColour in37 "#sample" in38 <- plugin' (audio_square9 ! "freq") (-475.0,-75.0) (Inside container22) setColour in38 "#sample" in39 <- plugin' (id11 ! "signal") (-381.0,-126.0) (Inside container22) setColour in39 "#sample" in40 <- plugin' (id12 ! "signal") (12.0,98.0) (Inside container22) setColour in40 "#sample" in41 <- plugin' (id13 ! "signal") (125.0,-32.0) (Inside container22) setColour in41 "#sample" in42 <- plugin' (id14 ! "signal") (-184.0,125.0) (Inside container22) setColour in42 "#sample" label43 <- label' "sum" (-468.0,190.0) (Inside container22) label44 <- label' "audio_triangle" (-87.0,171.0) (Inside container22) label45 <- label' "audio_saw" (29.0,42.0) (Inside container22) label46 <- label' "audio_sin" (-344.0,204.0) (Inside container22) label47 <- label' "audio_square" (-479.0,-50.0) (Inside container22) out48 <- plugout' (sum21 ! "result") (-423.0,115.0) (Inside container22) setColour out48 "#sample" out49 <- plugout' (audio_triangle10 ! "result") (-42.0,96.0) (Inside container22) setColour out49 "#sample" out50 <- plugout' (audio_saw7 ! "result") (74.0,-33.0) (Inside container22) setColour out50 "#sample" out51 <- plugout' (audio_sin8 ! "result") (-299.0,129.0) (Inside container22) setColour out51 "#sample" out52 <- plugout' (audio_square9 ! "result") (-434.0,-125.0) (Inside container22) setColour out52 "#sample" out53 <- plugout' (id15 ! "result") (-519.0,89.0) (Inside container22) setColour out53 "#sample" out54 <- plugout' (id16 ! "result") (-520.0,145.0) (Inside container22) setColour out54 "#sample" out55 <- plugout' (id17 ! "result") (-522.0,-125.0) (Inside container22) setColour out55 "#sample" out56 <- plugout' (id18 ! "result") (-521.0,-178.0) (Inside container22) setColour out56 "#sample" in57 <- plugin' (id15 ! "signal") (72.0,156.0) (Outside container22) setColour in57 "#control" in58 <- plugin' (id16 ! "signal") (49.0,200.0) (Outside container22) setColour in58 "#sample" hide in58 in59 <- plugin' (id17 ! "signal") (67.0,123.0) (Outside container22) setColour in59 "#sample" hide in59 in60 <- plugin' (id18 ! "signal") (72.0,84.0) (Outside container22) setColour in60 "#control" knob61 <- knob' (input20 ! "result") (72.0,120.0) (Outside container22) knob62 <- knob' (input19 ! "result") (72.0,192.0) (Outside container22) out63 <- plugout' (id14 ! "result") (12.0,36.0) (Outside container22) setColour out63 "#sample" out64 <- plugout' (id11 ! "result") (84.0,36.0) (Outside container22) setColour out64 "#sample" out65 <- plugout' (id12 ! "result") (12.0,0.0) (Outside container22) setColour out65 "#sample" out66 <- plugout' (id13 ! "result") (84.0,0.0) (Outside container22) setColour out66 "#sample" container223 <- container' "panel_lfo.png" (-624.0,468.0) (Inside root) in224 <- plugin' (lfo222 ! "sync") (-612.0,492.0) (Outside container223) setColour in224 "#control" in225 <- plugin' (lfo222 ! "rate") (-627.0,523.0) (Outside container223) setColour in225 "#control" hide in225 knob226 <- knob' (input221 ! "result") (-612.0,540.0) (Outside container223) out227 <- plugout' (lfo222 ! "triangle") (-636.0,348.0) (Outside container223) setColour out227 "#control" out228 <- plugout' (lfo222 ! "saw") (-576.0,348.0) (Outside container223) setColour out228 "#control" out229 <- plugout' (lfo222 ! "sin_result") (-636.0,384.0) (Outside container223) setColour out229 "#control" out230 <- plugout' (lfo222 ! "square_result") (-576.0,384.0) (Outside container223) setColour out230 "#control" container244 <- container' "panel_reverb.png" (564.0,396.0) (Inside root) container245 <- container' "panel_3x1.png" (1428.0,-936.0) (Inside container244) in246 <- plugin' (vca243 ! "cv") (1407.0,-911.0) (Outside container245) setColour in246 "#control" in247 <- plugin' (vca243 ! "signal") (1407.0,-961.0) (Outside container245) setColour in247 "#sample" label248 <- label' "vca" (1403.0,-861.0) (Outside container245) out249 <- plugout' (vca243 ! "result") (1448.0,-936.0) (Outside container245) setColour out249 "#sample" container250 <- container' "panel_3x1.png" (1296.0,-768.0) (Inside container244) in251 <- plugin' (fdn_reverb235 ! "decay") (1275.0,-718.0) (Outside container250) setColour in251 "#control" hide in251 in252 <- plugin' (fdn_reverb235 ! "hf_decay") (1275.0,-768.0) (Outside container250) setColour in252 "#control" hide in252 in253 <- plugin' (fdn_reverb235 ! "signal") (1275.0,-818.0) (Outside container250) setColour in253 "#sample" label254 <- label' "fdn_reverb" (1271.0,-693.0) (Outside container250) out255 <- plugout' (fdn_reverb235 ! "result") (1316.0,-768.0) (Outside container250) setColour out255 "#sample" container256 <- container' "panel_3x1.png" (1524.0,-756.0) (Inside container244) in257 <- plugin' (linear_mix242 ! "gain") (1503.0,-706.0) (Outside container256) setColour in257 "#control" in258 <- plugin' (linear_mix242 ! "signal1") (1503.0,-756.0) (Outside container256) setColour in258 "#sample" in259 <- plugin' (linear_mix242 ! "signal2") (1503.0,-806.0) (Outside container256) setColour in259 "#sample" label260 <- label' "linear_mix" (1499.0,-681.0) (Outside container256) out261 <- plugout' (linear_mix242 ! "result") (1544.0,-756.0) (Outside container256) setColour out261 "#sample" in262 <- plugin' (audio_id234 ! "signal") (1593.0,-875.0) (Inside container244) setColour in262 "#sample" out263 <- plugout' (audio_id231 ! "result") (1478.0,-611.0) (Inside container244) setColour out263 "#sample" out264 <- plugout' (id236 ! "result") (1333.0,-917.0) (Inside container244) setColour out264 "#control" out265 <- plugout' (id238 ! "result") (1165.0,-725.0) (Inside container244) setColour out265 "#control" out266 <- plugout' (id239 ! "result") (1165.0,-797.0) (Inside container244) setColour out266 "#control" out267 <- plugout' (audio_id233 ! "result") (1370.0,-635.0) (Inside container244) setColour out267 "#sample" in268 <- plugin' (audio_id231 ! "signal") (513.0,301.0) (Outside container244) setColour in268 "#sample" hide in268 in269 <- plugin' (id236 ! "signal") (516.0,348.0) (Outside container244) setColour in269 "#control" hide in269 in270 <- plugin' (id238 ! "signal") (564.0,456.0) (Outside container244) setColour in270 "#control" hide in270 in271 <- plugin' (id239 ! "signal") (516.0,396.0) (Outside container244) setColour in271 "#control" hide in271 in272 <- plugin' (audio_id233 ! "signal") (516.0,492.0) (Outside container244) setColour in272 "#sample" knob273 <- knob' (input237 ! "result") (516.0,348.0) (Outside container244) knob274 <- knob' (input232 ! "result") (516.0,300.0) (Outside container244) knob275 <- knob' (input240 ! "result") (516.0,444.0) (Outside container244) knob276 <- knob' (input241 ! "result") (516.0,396.0) (Outside container244) out277 <- plugout' (audio_id234 ! "result") (612.0,276.0) (Outside container244) setColour out277 "#sample" container278 <- container' "panel_3x1.png" (-384.0,-24.0) (Inside root) in281 <- plugin' (sum280 ! "signal1") (-405.0,1.0) (Outside container278) setColour in281 "#sample" in282 <- plugin' (sum280 ! "signal2") (-405.0,-49.0) (Outside container278) setColour in282 "#sample" label279 <- label' "sum" (-409.0,51.0) (Outside container278) out283 <- plugout' (sum280 ! "result") (-364.0,-24.0) (Outside container278) setColour out283 "#sample" container284 <- container' "panel_3x1.png" (-288.0,-48.0) (Inside root) in287 <- plugin' (sum286 ! "signal1") (-309.0,-23.0) (Outside container284) setColour in287 "#sample" in288 <- plugin' (sum286 ! "signal2") (-309.0,-73.0) (Outside container284) setColour in288 "#sample" label285 <- label' "sum" (-313.0,27.0) (Outside container284) out289 <- plugout' (sum286 ! "result") (-268.0,-48.0) (Outside container284) setColour out289 "#sample" container294 <- container' "panel_ladder.png" (204.0,-180.0) (Inside root) in295 <- plugin' (ladder292 ! "signal") (156.0,-300.0) (Outside container294) setColour in295 "#sample" in296 <- plugin' (sum293 ! "signal1") (241.0,-109.0) (Outside container294) setColour in296 "#sample" hide in296 in297 <- plugin' (sum293 ! "signal2") (204.0,-108.0) (Outside container294) setColour in297 "#control" in298 <- plugin' (ladder292 ! "freq") (215.0,-155.0) (Outside container294) setColour in298 "#sample" hide in298 in299 <- plugin' (ladder292 ! "res") (238.0,-192.0) (Outside container294) setColour in299 "#sample" hide in299 knob300 <- knob' (input290 ! "result") (252.0,-168.0) (Outside container294) setLow knob300 (Just (0.0)) setHigh knob300 (Just (3.999)) knob301 <- knob' (input291 ! "result") (252.0,-108.0) (Outside container294) setLow knob301 (Just (-1.0)) setHigh knob301 (Just (0.7)) out302 <- plugout' (ladder292 ! "result") (252.0,-300.0) (Outside container294) setColour out302 "#sample" out303 <- plugout' (sum293 ! "result") (157.0,-152.0) (Outside container294) setColour out303 "#sample" hide out303 container3 <- container' "panel_out.png" (444.0,24.0) (Inside root) in4 <- plugin' (out ! "left") (420.0,72.0) (Outside container3) setColour in4 "#sample" in5 <- plugin' (out ! "value") (420.0,24.0) (Outside container3) setOutput in5 setColour in5 "#sample" in6 <- plugin' (out ! "right") (420.0,-24.0) (Outside container3) setColour in6 "#sample" container312 <- container' "panel_gain.png" (-132.0,-504.0) (Inside root) in313 <- plugin' (vca310 ! "cv") (-156.0,-504.0) (Outside container312) setColour in313 "#control" hide in313 in314 <- plugin' (vca310 ! "signal") (-192.0,-504.0) (Outside container312) setColour in314 "#sample" knob315 <- knob' (input311 ! "result") (-156.0,-504.0) (Outside container312) out316 <- plugout' (vca310 ! "result") (-72.0,-504.0) (Outside container312) setColour out316 "#sample" container319 <- container' "panel_lfo.png" (-492.0,-456.0) (Inside root) in320 <- plugin' (lfo318 ! "sync") (-480.0,-432.0) (Outside container319) setColour in320 "#control" in321 <- plugin' (lfo318 ! "rate") (-495.0,-401.0) (Outside container319) setColour in321 "#control" hide in321 knob322 <- knob' (input317 ! "result") (-480.0,-384.0) (Outside container319) out323 <- plugout' (lfo318 ! "triangle") (-504.0,-576.0) (Outside container319) setColour out323 "#control" out324 <- plugout' (lfo318 ! "saw") (-444.0,-576.0) (Outside container319) setColour out324 "#control" out325 <- plugout' (lfo318 ! "sin_result") (-504.0,-540.0) (Outside container319) setColour out325 "#control" out326 <- plugout' (lfo318 ! "square_result") (-444.0,-540.0) (Outside container319) setColour out326 "#control" container329 <- container' "panel_gain.png" (-228.0,-576.0) (Inside root) in330 <- plugin' (vca327 ! "cv") (-252.0,-576.0) (Outside container329) setColour in330 "#control" hide in330 in331 <- plugin' (vca327 ! "signal") (-288.0,-576.0) (Outside container329) setColour in331 "#sample" knob332 <- knob' (input328 ! "result") (-252.0,-576.0) (Outside container329) out333 <- plugout' (vca327 ! "result") (-168.0,-576.0) (Outside container329) setColour out333 "#sample" container334 <- container' "panel_4x1.png" (132.0,-480.0) (Inside root) in337 <- plugin' (sum4336 ! "signal1") (111.0,-405.0) (Outside container334) setColour in337 "#sample" in338 <- plugin' (sum4336 ! "signal2") (111.0,-455.0) (Outside container334) setColour in338 "#sample" in339 <- plugin' (sum4336 ! "signal3") (111.0,-505.0) (Outside container334) setColour in339 "#sample" in340 <- plugin' (sum4336 ! "signal4") (111.0,-555.0) (Outside container334) setColour in340 "#sample" label335 <- label' "sum4" (107.0,-405.0) (Outside container334) out341 <- plugout' (sum4336 ! "result") (152.0,-480.0) (Outside container334) setColour out341 "#sample" container402 <- container' "panel_4x1.png" (36.0,444.0) (Inside root) in405 <- plugin' (progression404 ! "pattern") (15.0,519.0) (Outside container402) setColour in405 "(0, 0, 1)" in406 <- plugin' (progression404 ! "root") (15.0,469.0) (Outside container402) setColour in406 "#control" in407 <- plugin' (progression404 ! "trigger") (15.0,419.0) (Outside container402) setColour in407 "#control" in408 <- plugin' (progression404 ! "reset") (15.0,369.0) (Outside container402) setColour in408 "#control" label403 <- label' "progression" (11.0,519.0) (Outside container402) out409 <- plugout' (progression404 ! "sync") (56.0,519.0) (Outside container402) setColour out409 "#control" out410 <- plugout' (progression404 ! "note1") (56.0,469.0) (Outside container402) setColour out410 "#control" out411 <- plugout' (progression404 ! "note2") (56.0,419.0) (Outside container402) setColour out411 "#control" out412 <- plugout' (progression404 ! "note3") (56.0,369.0) (Outside container402) setColour out412 "#control" container415 <- container' "panel_textbox.png" (-228.0,528.0) (Inside root) in416 <- plugin' (string_id413 ! "input") (-240.0,528.0) (Outside container415) setColour in416 "#control" hide in416 out417 <- plugout' (string_id413 ! "result") (-132.0,528.0) (Outside container415) setColour out417 "#control" textBox418 <- textBox' (string_input414 ! "result") (-300.0,528.0) (Outside container415) container420 <- container' "panel_divider.png" (-456.0,468.0) (Inside root) in421 <- plugin' (divider419 ! "gate") (-480.0,492.0) (Outside container420) setColour in421 "#control" out422 <- plugout' (divider419 ! "div32") (-432.0,348.0) (Outside container420) setColour out422 "#control" out423 <- plugout' (divider419 ! "div02") (-432.0,540.0) (Outside container420) setColour out423 "#control" out424 <- plugout' (divider419 ! "div04") (-432.0,492.0) (Outside container420) setColour out424 "#control" out425 <- plugout' (divider419 ! "div08") (-432.0,444.0) (Outside container420) setColour out425 "#control" out426 <- plugout' (divider419 ! "div16") (-432.0,396.0) (Outside container420) setColour out426 "#control" container69 <- container' "panel_gain.png" (276.0,108.0) (Inside root) in70 <- plugin' (vca67 ! "cv") (252.0,108.0) (Outside container69) setColour in70 "#control" hide in70 in71 <- plugin' (vca67 ! "signal") (216.0,108.0) (Outside container69) setColour in71 "#sample" knob72 <- knob' (input68 ! "result") (252.0,108.0) (Outside container69) out73 <- plugout' (vca67 ! "result") (336.0,108.0) (Outside container69) setColour out73 "#sample" container79 <- container' "panel_adsr.png" (-180.0,-204.0) (Inside root) in80 <- plugin' (adsr74 ! "attack") (-208.0,-147.0) (Outside container79) setColour in80 "#sample" hide in80 in81 <- plugin' (adsr74 ! "decay") (-155.0,-130.0) (Outside container79) setColour in81 "#sample" hide in81 in82 <- plugin' (adsr74 ! "sustain") (-155.0,-180.0) (Outside container79) setColour in82 "#sample" hide in82 in83 <- plugin' (adsr74 ! "release") (-155.0,-230.0) (Outside container79) setColour in83 "#sample" hide in83 in84 <- plugin' (adsr74 ! "gate") (-144.0,-276.0) (Outside container79) setColour in84 "#control" knob85 <- knob' (input75 ! "result") (-204.0,-144.0) (Outside container79) setLow knob85 (Just (0.0)) knob86 <- knob' (input76 ! "result") (-144.0,-144.0) (Outside container79) setLow knob86 (Just (0.0)) knob87 <- knob' (input78 ! "result") (-204.0,-192.0) (Outside container79) setLow knob87 (Just (0.0)) knob88 <- knob' (input77 ! "result") (-144.0,-192.0) (Outside container79) setLow knob88 (Just (0.0)) out89 <- plugout' (adsr74 ! "result") (-144.0,-312.0) (Outside container79) setColour out89 "#control" container90 <- container' "panel_3x1.png" (360.0,-144.0) (Inside root) in93 <- plugin' (vca92 ! "cv") (339.0,-119.0) (Outside container90) setColour in93 "#control" in94 <- plugin' (vca92 ! "signal") (339.0,-169.0) (Outside container90) setColour in94 "#sample" label91 <- label' "vca" (335.0,-69.0) (Outside container90) out95 <- plugout' (vca92 ! "result") (380.0,-144.0) (Outside container90) setColour out95 "#sample" cable out124 in108 cable out123 in109 cable out119 in110 cable out120 in111 cable out121 in112 cable out122 in113 cable out115 in117 cable out116 in118 cable out2 in125 cable out410 in126 cable out411 in127 cable out412 in128 cable out230 in129 cable textBox133 in130 cable knob210 in203 cable knob211 in204 cable knob212 in205 cable knob213 in206 cable knob214 in207 cable knob209 in208 cable out53 in28 cable out54 in29 cable out48 in30 cable out56 in31 cable out48 in32 cable out56 in33 cable out48 in34 cable out56 in35 cable out55 in36 cable out56 in37 cable out48 in38 cable out52 in39 cable out49 in40 cable out50 in41 cable out51 in42 cable out131 in57 cable knob62 in58 cable knob61 in59 cable knob226 in225 cable out264 in246 cable out255 in247 cable out265 in251 cable out266 in252 cable out267 in253 cable out263 in257 cable out267 in258 cable out249 in259 cable out261 in262 cable knob274 in268 cable knob273 in269 cable knob275 in270 cable knob276 in271 cable out95 in272 cable out1 in281 cable out220 in282 cable out1 in287 cable out215 in288 cable out66 in295 cable knob301 in296 cable out341 in297 cable out303 in298 cable knob300 in299 cable out73 in5 cable knob315 in313 cable out89 in314 cable knob322 in321 cable knob332 in330 cable out325 in331 cable out131 in337 cable out316 in338 cable out333 in339 cable out417 in405 cable out1 in406 cable out426 in407 cable out2 in408 cable textBox418 in416 cable out230 in421 cable knob72 in70 cable out277 in71 cable knob85 in80 cable knob86 in81 cable knob87 in82 cable knob88 in83 cable out132 in84 cable out89 in93 cable out302 in94 recompile setString textBox133 ("aebdccdb") set knob209 (3.3333335e-2) set knob210 (0.0) set knob211 (0.0) set knob212 (0.0) set knob213 (-4.2050842e-2) set knob214 (-8.333334e-3) set knob61 (0.0) set knob62 (0.0) set knob226 (6.0) set knob273 (4.727709) set knob274 (0.41996497) set knob275 (1.0626922) set knob276 (2.0e-2) set knob300 (1.6330826) set knob301 (0.46105152) set knob315 (4.2856134e-2) set knob322 (0.18982339) set knob332 (0.2527409) setString textBox418 ("i-iv-iio-viio-V") set knob72 (7.0e-2) set knob85 (1.6847253e-2) set knob86 (0.65) set knob87 (0.30396026) set knob88 (0.32829148) return ()
29a710449330cc5e13cdae462d6fb464c13082f6ee2353b87ec019e0bd2473ec
zotonic/zotonic
validator_base_length.erl
@author < > 2009 - 2017 %% @doc Validator for checking if an input value is within a certain length range Copyright 2009 - 2017 %% 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(validator_base_length). -include_lib("zotonic_core/include/zotonic.hrl"). -export([render_validator/5, validate/5]). render_validator(length, TriggerId, _TargetId, Args, _Context) -> Min = proplists:get_value(minimum, Args), Max = proplists:get_value(maximum, Args), JsObject = z_utils:js_object(z_validation:rename_args(Args)), Script = [<<"z_add_validator(\"">>,TriggerId,<<"\", \"length\", ">>, JsObject, <<");\n">>], {[to_number(Min),to_number(Max)], Script}. , TriggerId , Values , , Context ) - > { ok , AcceptedValue } | { error , Id , Error } %% Error = invalid | novalue | {script, Script} validate(length, Id, Value, [Min,Max], Context) when is_list(Value); is_binary(Value) -> case z_string:len(Value) of 0 -> {{ok, Value}, Context}; Len -> MinOK = (Min == -1 orelse Len >= Min), MaxOK = (Max == -1 orelse Len =< Max), case MinOK andalso MaxOK of true -> {{ok, Value}, Context}; false -> {{error, Id, invalid}, Context} end end. to_number(undefined) -> -1; to_number(N) when is_integer(N) -> N; to_number(N) -> z_convert:to_integer(N).
null
https://raw.githubusercontent.com/zotonic/zotonic/92558e09d4334d16514043c10f66a62c2acb9c6a/apps/zotonic_mod_base/src/validators/validator_base_length.erl
erlang
@doc Validator for checking if an input value is within a certain length range 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. Error = invalid | novalue | {script, Script}
@author < > 2009 - 2017 Copyright 2009 - 2017 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(validator_base_length). -include_lib("zotonic_core/include/zotonic.hrl"). -export([render_validator/5, validate/5]). render_validator(length, TriggerId, _TargetId, Args, _Context) -> Min = proplists:get_value(minimum, Args), Max = proplists:get_value(maximum, Args), JsObject = z_utils:js_object(z_validation:rename_args(Args)), Script = [<<"z_add_validator(\"">>,TriggerId,<<"\", \"length\", ">>, JsObject, <<");\n">>], {[to_number(Min),to_number(Max)], Script}. , TriggerId , Values , , Context ) - > { ok , AcceptedValue } | { error , Id , Error } validate(length, Id, Value, [Min,Max], Context) when is_list(Value); is_binary(Value) -> case z_string:len(Value) of 0 -> {{ok, Value}, Context}; Len -> MinOK = (Min == -1 orelse Len >= Min), MaxOK = (Max == -1 orelse Len =< Max), case MinOK andalso MaxOK of true -> {{ok, Value}, Context}; false -> {{error, Id, invalid}, Context} end end. to_number(undefined) -> -1; to_number(N) when is_integer(N) -> N; to_number(N) -> z_convert:to_integer(N).
05f710ab0a34f817d087eafbb3bfd1675f37f9c72799c33b93196a2198faf993
ejgallego/coq-lsp
rq_document.mli
(************************************************************************) (* Coq Language Server Protocol -- Document *) Copyright 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Copyright 2019 - 2023 Inria -- Dual License LGPL 2.1 / GPL3 + Written by : (************************************************************************) val request : Request.document
null
https://raw.githubusercontent.com/ejgallego/coq-lsp/1881796eb3ed77dc16a8dfc97c547480701b454b/controller/rq_document.mli
ocaml
********************************************************************** Coq Language Server Protocol -- Document **********************************************************************
Copyright 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Copyright 2019 - 2023 Inria -- Dual License LGPL 2.1 / GPL3 + Written by : val request : Request.document
e1433affb0b001cf0f1f1fb302b907b40ff868ffdd14d6793adb8ea5303c84cf
yuriy-chumak/ol
macro.scm
; already loaded when booting. (define-library (lang macro) ; remove make-transformer when it is no longer referred (export macro-expand match make-transformer) (import (scheme base) (srfi 1) (owl list) (owl list-extra) (owl math) (owl io) (owl sort) (lang gensym) (lang env)) (begin ;;; Misc (define (ok exp env) ['ok exp env]) (define (fail reason) ['fail reason]) (define-syntax lets (syntax-rules () ((lets . stuff) (let* . stuff)))) ; TEMP (define symbols-of (define (walk exp found) (cond ((pair? exp) (walk (cdr exp) (walk (car exp) found))) ((and (symbol? exp) (not (has? found exp))) (cons exp found)) (else found))) (lambda (exp) (walk exp null))) ;;; ;;; Basic pattern matching for matching the rule pattern against sexp ;;; (define (? x) #true) (define (match pattern exp) (define (match-pattern pattern exp vals) (cond ((not vals) #false) ((pair? pattern) (if (pair? exp) (match-pattern (car pattern) (car exp) (match-pattern (cdr pattern) (cdr exp) vals)) #false)) ((eq? pattern exp) vals) ((eq? pattern '_) vals) ((function? pattern) (if (pattern exp) (cons exp vals) #false)) (else #false))) (match-pattern pattern exp null)) ;;; ;;; Matching and rewriting based on rewrite rules ;;; ; fixme, there are ffs now ; store nulls to variables in exp (define (init-variables exp literals dict) (fold (λ (dict key) (cons (cons key null) dict)) dict (diff (symbols-of exp) literals))) ;; fixme: we have ffs now (define (push dict key val) (cond ((null? dict) (runtime-error "push: key not in dict: " key)) ((eq? (caar dict) key) (cons (append (car dict) (list val)) (cdr dict))) (else (cons (car dict) (push (cdr dict) key val))))) (define (match-pattern pattern literals form fail) (let loop ((pattern pattern) (form form) (collect? #false) (fail fail) (dictionary null)) (cond ((symbol? pattern) (cond ((eq? pattern '_) ;; wildcard - match anything, leave no binding dictionary) ((has? literals pattern) (if (eq? pattern form) dictionary (fail pattern))) (collect? ;;; append to dictionary (push dictionary pattern form)) (else (let ((binding (getq dictionary pattern))) (if binding (if (equal? (cadr binding) form) dictionary (fail pattern)) (cons (list pattern form) dictionary)))))) ((null? pattern) (if (null? form) dictionary (fail pattern))) ((pair? pattern) (cond ((and (pair? (cdr pattern)) (eq? (cadr pattern) '...)) (let ((dictionary (init-variables (car pattern) literals dictionary))) ; each time a form is matched ; resume matching with a fail cont returning to ; process more (let next ((prev-dict dictionary) (old-form form) (new-dict dictionary) (form form)) (call/cc (lambda (ret) (if (and new-dict (pair? form)) (loop (cddr pattern) form #false (lambda (argh) (ret (next new-dict form (call/cc (lambda (ret) (loop (car pattern) (car form) #true (lambda (x) (ret #false)) new-dict))) (cdr form)))) new-dict) ; no more matches (loop (cddr pattern) (if new-dict form old-form) #false fail (if new-dict new-dict prev-dict)))))))) ((pair? form) (loop (cdr pattern) (cdr form) collect? fail (loop (car pattern) (car form) collect? fail dictionary))) (else (fail form)))) ((equal? pattern form) dictionary) (else (fail form))))) (define (try-pattern pattern literals form) (call/cc (lambda (ret) (match-pattern pattern literals form (lambda (argh) (ret #false)))))) ;; given dictionary resulting from pattern matching, decide how many times an ellipsis rewrite should be done . owl uses minimum repetition of length more than one , so that ;; single matches can be used along with ellipsis matches. (define o (λ (f g) (λ (x) (f (g x))))) (define (repetition-length dict) (let loop ((opts (sort < (map (o length cdr) dict))) (best 0)) (cond ((null? opts) 0 if ellipsis with empty match , or 1 due to ellipsis of lenght 1 or just normal valid bindings best) ((eq? 1 (car opts)) ;; longer repetitions may follow (loop (cdr opts) 1)) (else repetition of length 0 or (car opts))))) pop all bindings of length > 1 (define (pop-ellipsis dict) (map (λ (p) (let ((vals (cdr p))) (if (null? (cdr vals)) p (cons (car p) (cdr vals))))) dict)) (define (rewrite dictionary form) (let loop ((form form)) (cond ((symbol? form) (let ((binding (getq dictionary form))) (if (and binding (pair? (cdr binding))) (cadr binding) form))) ((pair? form) (if (and (pair? (cdr form)) (eq? (cadr form) '...)) (lets ((syms (symbols-of (car form))) (dict (keep (λ (node) (has? syms (car node))) dictionary)) (len (repetition-length dict))) (let rep-loop ((dict dict) (n len)) (if (eq? n 0) (loop (cddr form)) (cons (rewrite dict (car form)) (rep-loop (pop-ellipsis dict) (- n 1)))))) (cons (loop (car form)) (loop (cdr form))))) (else form)))) Intermission ; exp env free -> status exp' free' (define toplevel-syntax-definition? (let ((pattern `(quote syntax-operation add #false (,symbol? ,list? ,list? ,list?)))) ;; -> keyword literals patterns templates (lambda (exp) (match pattern exp)))) (define toplevel-macro-definition? (let ((pattern `(quote macro-operation eval #false (,symbol? ,function?)))) ;; -> name handler (lambda (exp) (match pattern exp)))) fold w/ 2 state variables (define (fold2 op s1 s2 lst) (if (null? lst) (values s1 s2) (lets ((s1 s2 (op s1 s2 (car lst)))) (fold2 op s1 s2 (cdr lst))))) (define (add-fresh-bindings names free dict) (fold2 (λ (free dict name) (values (gensym free) (cons (list name free) dict))) free dict names)) (define (make-transformer literals rules) (λ (form free) (some (λ (rule) rule = ( pattern template ) (let ((dictionary (try-pattern (car rule) literals form))) (if dictionary (let*((free dictionary (add-fresh-bindings (cadr rule) free dictionary)) (new (rewrite dictionary (caddr rule)))) [new free])))) rules))) ; add fresh symbol list -> ((pattern fresh template) ...) (define (make-pattern-list literals patterns templates unbound?) (map (λ (pattern template) (lets ((pattern-symbols (symbols-of pattern)) (template-symbols (symbols-of template)) (fresh-symbols (keep (lambda (x) (and (unbound? x) (not (has? literals x)))) (diff template-symbols pattern-symbols)))) (list pattern fresh-symbols template))) patterns templates)) ;;; Macro expansion in a given env ;;; ; expand all macros top to bottom ; exp env free -> #(exp' free') (define (expand exp env free abort) ; (print "expand: " exp) (define (expand-list exps env free) ; todo: handle 'env' changes (if (null? exps) (values null free) (lets ((this free (expand (car exps) env free abort)) (tail free (expand-list (cdr exps) env free))) (values (cons this tail) free)))) (cond ((null? exp) (values exp free)) ((list? exp) (cond ((symbol? (car exp)) (case (lookup env (car exp)) (['special thing] (case thing ('quote (values exp free)) ('lambda (if (or (null? (cdr exp)) (null? (cddr exp))) ;; todo: use matcher instead (abort (list "Bad lambda: " exp)) (lets ((formals (cadr exp)) (body-exps (cddr exp)) (body (if (and (pair? body-exps) (null? (cdr body-exps))) (car body-exps) (cons 'begin body-exps))) (body free (expand body (env-bind env formals) free abort))) (values (list 'lambda formals body) free)))) ('setq (lets ((value free (expand (caddr exp) env free abort))) (values (list 'setq (cadr exp) value) free))) ('let-eval lref 1 lref 2 lref 3 (env (env-bind env formals)) (definitions free (expand-list definitions env free)) (body free (expand body env free abort))) (values (list 'let-eval formals definitions body) free))) ('ifeq (expand-list exp env free)) ('brae (if (or (null? (cdr exp)) (null? (cddr exp))) (abort (list "Bad brae: " exp)) (lets ((first free (expand (cadr exp) env free abort)) (rest free (expand (caddr exp) env free abort))) (values (list 'brae first rest) free)))) ('values (expand-list exp env free)) ('values-apply (expand-list exp env free)) (else (abort (list "expand: unknown special form: " exp))))) (['bound] (expand-list exp env free)) (['defined value] (expand-list exp env free)) (['undefined] ;; can be a literal (values exp free)) (['syntax transformer] (let ((result (transformer exp free))) (if result (expand (ref result 1) env (ref result 2) abort) (abort exp)))) (['macro transformer] (let ((result (transformer exp env))) (if result (expand (ref result 1) (ref result 2) free abort) (abort exp)))) (else is node ; usually bad module exports, since those are not checked atm (abort (list "expand: rator maps to unknown value " (car exp)))))) (else (expand-list exp env free)))) ((symbol? exp) (case (lookup env exp) (['syntax transformer] (abort (list "Macro being used as a value: " exp))) (['macro transformer] (abort (list "Macro being used as a value: " exp))) (['undefined] ;; this can still be a literal used by a macro (values exp free)) (else (values exp free)))) (else (values exp free)))) ; maybe extend the env if a macro is being defined (define (post-macro-expand exp env fail) (cond ((toplevel-syntax-definition? exp) (let*((rules (lref exp 4)) (keyword (lref rules 0)) (literals (lref rules 1)) (patterns (lref rules 2)) (templates (lref rules 3)) (rules (make-pattern-list literals patterns templates (lambda (sym) (not (env-get-raw env sym #false))))) (transformer (make-transformer (cons keyword literals) rules))) (let ((env (env-set-syntax env keyword transformer))) (ok (list 'quote keyword) env)))) ((toplevel-macro-definition? exp) (let*((body (lref exp 4)) (keyword (car body)) ; name (function (cadr body))) (let ((env (env-set-macro env keyword function))) (ok (list 'quote keyword) env)))) (else (ok exp env)))) ;; bug: exported macros do not preserve bindinds (define (macro-expand exp env) (let*/cc exit ((abort (lambda (why) (exit (fail why)))) (free (gensym exp)) (exp free (expand exp env free abort))) (post-macro-expand exp env abort))) ))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/c9eaa54b37ccd175d962703a2a500ecf74cb6859/lang/macro.scm
scheme
already loaded when booting. remove make-transformer when it is no longer referred Misc TEMP Basic pattern matching for matching the rule pattern against sexp Matching and rewriting based on rewrite rules fixme, there are ffs now store nulls to variables in exp fixme: we have ffs now wildcard - match anything, leave no binding append to dictionary each time a form is matched resume matching with a fail cont returning to process more no more matches given dictionary resulting from pattern matching, decide how many times an ellipsis single matches can be used along with ellipsis matches. longer repetitions may follow exp env free -> status exp' free' -> keyword literals patterns templates -> name handler add fresh symbol list -> ((pattern fresh template) ...) expand all macros top to bottom exp env free -> #(exp' free') (print "expand: " exp) todo: handle 'env' changes todo: use matcher instead can be a literal usually bad module exports, since those are not checked atm this can still be a literal used by a macro maybe extend the env if a macro is being defined name bug: exported macros do not preserve bindinds
(define-library (lang macro) (export macro-expand match make-transformer) (import (scheme base) (srfi 1) (owl list) (owl list-extra) (owl math) (owl io) (owl sort) (lang gensym) (lang env)) (begin (define (ok exp env) ['ok exp env]) (define (fail reason) ['fail reason]) (define symbols-of (define (walk exp found) (cond ((pair? exp) (walk (cdr exp) (walk (car exp) found))) ((and (symbol? exp) (not (has? found exp))) (cons exp found)) (else found))) (lambda (exp) (walk exp null))) (define (? x) #true) (define (match pattern exp) (define (match-pattern pattern exp vals) (cond ((not vals) #false) ((pair? pattern) (if (pair? exp) (match-pattern (car pattern) (car exp) (match-pattern (cdr pattern) (cdr exp) vals)) #false)) ((eq? pattern exp) vals) ((eq? pattern '_) vals) ((function? pattern) (if (pattern exp) (cons exp vals) #false)) (else #false))) (match-pattern pattern exp null)) (define (init-variables exp literals dict) (fold (λ (dict key) (cons (cons key null) dict)) dict (diff (symbols-of exp) literals))) (define (push dict key val) (cond ((null? dict) (runtime-error "push: key not in dict: " key)) ((eq? (caar dict) key) (cons (append (car dict) (list val)) (cdr dict))) (else (cons (car dict) (push (cdr dict) key val))))) (define (match-pattern pattern literals form fail) (let loop ((pattern pattern) (form form) (collect? #false) (fail fail) (dictionary null)) (cond ((symbol? pattern) (cond dictionary) ((has? literals pattern) (if (eq? pattern form) dictionary (fail pattern))) (collect? (push dictionary pattern form)) (else (let ((binding (getq dictionary pattern))) (if binding (if (equal? (cadr binding) form) dictionary (fail pattern)) (cons (list pattern form) dictionary)))))) ((null? pattern) (if (null? form) dictionary (fail pattern))) ((pair? pattern) (cond ((and (pair? (cdr pattern)) (eq? (cadr pattern) '...)) (let ((dictionary (init-variables (car pattern) literals dictionary))) (let next ((prev-dict dictionary) (old-form form) (new-dict dictionary) (form form)) (call/cc (lambda (ret) (if (and new-dict (pair? form)) (loop (cddr pattern) form #false (lambda (argh) (ret (next new-dict form (call/cc (lambda (ret) (loop (car pattern) (car form) #true (lambda (x) (ret #false)) new-dict))) (cdr form)))) new-dict) (loop (cddr pattern) (if new-dict form old-form) #false fail (if new-dict new-dict prev-dict)))))))) ((pair? form) (loop (cdr pattern) (cdr form) collect? fail (loop (car pattern) (car form) collect? fail dictionary))) (else (fail form)))) ((equal? pattern form) dictionary) (else (fail form))))) (define (try-pattern pattern literals form) (call/cc (lambda (ret) (match-pattern pattern literals form (lambda (argh) (ret #false)))))) rewrite should be done . owl uses minimum repetition of length more than one , so that (define o (λ (f g) (λ (x) (f (g x))))) (define (repetition-length dict) (let loop ((opts (sort < (map (o length cdr) dict))) (best 0)) (cond ((null? opts) 0 if ellipsis with empty match , or 1 due to ellipsis of lenght 1 or just normal valid bindings best) ((eq? 1 (car opts)) (loop (cdr opts) 1)) (else repetition of length 0 or (car opts))))) pop all bindings of length > 1 (define (pop-ellipsis dict) (map (λ (p) (let ((vals (cdr p))) (if (null? (cdr vals)) p (cons (car p) (cdr vals))))) dict)) (define (rewrite dictionary form) (let loop ((form form)) (cond ((symbol? form) (let ((binding (getq dictionary form))) (if (and binding (pair? (cdr binding))) (cadr binding) form))) ((pair? form) (if (and (pair? (cdr form)) (eq? (cadr form) '...)) (lets ((syms (symbols-of (car form))) (dict (keep (λ (node) (has? syms (car node))) dictionary)) (len (repetition-length dict))) (let rep-loop ((dict dict) (n len)) (if (eq? n 0) (loop (cddr form)) (cons (rewrite dict (car form)) (rep-loop (pop-ellipsis dict) (- n 1)))))) (cons (loop (car form)) (loop (cdr form))))) (else form)))) Intermission (define toplevel-syntax-definition? (let ((pattern `(quote syntax-operation add #false (,symbol? ,list? ,list? ,list?)))) (lambda (exp) (match pattern exp)))) (define toplevel-macro-definition? (let ((pattern `(quote macro-operation eval #false (,symbol? ,function?)))) (lambda (exp) (match pattern exp)))) fold w/ 2 state variables (define (fold2 op s1 s2 lst) (if (null? lst) (values s1 s2) (lets ((s1 s2 (op s1 s2 (car lst)))) (fold2 op s1 s2 (cdr lst))))) (define (add-fresh-bindings names free dict) (fold2 (λ (free dict name) (values (gensym free) (cons (list name free) dict))) free dict names)) (define (make-transformer literals rules) (λ (form free) (some (λ (rule) rule = ( pattern template ) (let ((dictionary (try-pattern (car rule) literals form))) (if dictionary (let*((free dictionary (add-fresh-bindings (cadr rule) free dictionary)) (new (rewrite dictionary (caddr rule)))) [new free])))) rules))) (define (make-pattern-list literals patterns templates unbound?) (map (λ (pattern template) (lets ((pattern-symbols (symbols-of pattern)) (template-symbols (symbols-of template)) (fresh-symbols (keep (lambda (x) (and (unbound? x) (not (has? literals x)))) (diff template-symbols pattern-symbols)))) (list pattern fresh-symbols template))) patterns templates)) Macro expansion in a given env (define (expand exp env free abort) (if (null? exps) (values null free) (lets ((this free (expand (car exps) env free abort)) (tail free (expand-list (cdr exps) env free))) (values (cons this tail) free)))) (cond ((null? exp) (values exp free)) ((list? exp) (cond ((symbol? (car exp)) (case (lookup env (car exp)) (['special thing] (case thing ('quote (values exp free)) ('lambda (abort (list "Bad lambda: " exp)) (lets ((formals (cadr exp)) (body-exps (cddr exp)) (body (if (and (pair? body-exps) (null? (cdr body-exps))) (car body-exps) (cons 'begin body-exps))) (body free (expand body (env-bind env formals) free abort))) (values (list 'lambda formals body) free)))) ('setq (lets ((value free (expand (caddr exp) env free abort))) (values (list 'setq (cadr exp) value) free))) ('let-eval lref 1 lref 2 lref 3 (env (env-bind env formals)) (definitions free (expand-list definitions env free)) (body free (expand body env free abort))) (values (list 'let-eval formals definitions body) free))) ('ifeq (expand-list exp env free)) ('brae (if (or (null? (cdr exp)) (null? (cddr exp))) (abort (list "Bad brae: " exp)) (lets ((first free (expand (cadr exp) env free abort)) (rest free (expand (caddr exp) env free abort))) (values (list 'brae first rest) free)))) ('values (expand-list exp env free)) ('values-apply (expand-list exp env free)) (else (abort (list "expand: unknown special form: " exp))))) (['bound] (expand-list exp env free)) (['defined value] (expand-list exp env free)) (['undefined] (values exp free)) (['syntax transformer] (let ((result (transformer exp free))) (if result (expand (ref result 1) env (ref result 2) abort) (abort exp)))) (['macro transformer] (let ((result (transformer exp env))) (if result (expand (ref result 1) (ref result 2) free abort) (abort exp)))) (else is node (abort (list "expand: rator maps to unknown value " (car exp)))))) (else (expand-list exp env free)))) ((symbol? exp) (case (lookup env exp) (['syntax transformer] (abort (list "Macro being used as a value: " exp))) (['macro transformer] (abort (list "Macro being used as a value: " exp))) (['undefined] (values exp free)) (else (values exp free)))) (else (values exp free)))) (define (post-macro-expand exp env fail) (cond ((toplevel-syntax-definition? exp) (let*((rules (lref exp 4)) (keyword (lref rules 0)) (literals (lref rules 1)) (patterns (lref rules 2)) (templates (lref rules 3)) (rules (make-pattern-list literals patterns templates (lambda (sym) (not (env-get-raw env sym #false))))) (transformer (make-transformer (cons keyword literals) rules))) (let ((env (env-set-syntax env keyword transformer))) (ok (list 'quote keyword) env)))) ((toplevel-macro-definition? exp) (let*((body (lref exp 4)) (function (cadr body))) (let ((env (env-set-macro env keyword function))) (ok (list 'quote keyword) env)))) (else (ok exp env)))) (define (macro-expand exp env) (let*/cc exit ((abort (lambda (why) (exit (fail why)))) (free (gensym exp)) (exp free (expand exp env free abort))) (post-macro-expand exp env abort))) ))
8cc73c3c8983ac12e13b57941b2e14c29a65a01d16b8954dce568d163e458542
bbc/haskell-workshop
C3TypesAndTypeclasses.hs
module C3TypesAndTypeclasses where -- last, length, and take are all from the standard library, Prelude You can find out the type in ghci with " : t last " , but attempt to answer first -- What is the type of the last function? -- last :: [a] -> a -- What is the type of the length function? -- length :: Foldable t => t a -> Int -- What is the type of the take function? -- take :: Int-> [a] -> [a] -- myConcat :: [a] -> [a] -> [a] myConcat a b = a ++ b -- Can you use type classes to constrain the polymorphic types? -- Make the types polymorphic and use a typeclass constraint -- What happens if you don't use a typeclass constraint? -- What is the type of this function mul : : a = > a - > a - > a mul a b = a * b -- Consider this function hasShowableInside :: Show a => [a] -> Bool hasShowableInside xs = null xs -- Now convert it into a function that checks only whether there are numbers inside hasNumbersInside :: Num a => [a] -> Bool hasNumbersInside xs = not (null xs) -- Write the type signature for this function -- Hint: You will need to use the relevant typeclasses showAndRead :: (Read a, Show a) => a -> a showAndRead a = read (show a)
null
https://raw.githubusercontent.com/bbc/haskell-workshop/475b9bac04167665030d7863798ccd27dfd589d0/jensraaby/exercises/src/C3TypesAndTypeclasses.hs
haskell
last, length, and take are all from the standard library, Prelude What is the type of the last function? last :: [a] -> a What is the type of the length function? length :: Foldable t => t a -> Int What is the type of the take function? take :: Int-> [a] -> [a] myConcat :: [a] -> [a] -> [a] Can you use type classes to constrain the polymorphic types? Make the types polymorphic and use a typeclass constraint What happens if you don't use a typeclass constraint? What is the type of this function Consider this function Now convert it into a function that checks only whether there are numbers inside Write the type signature for this function Hint: You will need to use the relevant typeclasses
module C3TypesAndTypeclasses where You can find out the type in ghci with " : t last " , but attempt to answer first myConcat a b = a ++ b mul : : a = > a - > a - > a mul a b = a * b hasShowableInside :: Show a => [a] -> Bool hasShowableInside xs = null xs hasNumbersInside :: Num a => [a] -> Bool hasNumbersInside xs = not (null xs) showAndRead :: (Read a, Show a) => a -> a showAndRead a = read (show a)
93cb96065cae11443498b1d4a9dcece294c73a670253d22f5429506c25cb845d
elaforge/karya
MidiThru.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt # LANGUAGE CPP # | Implement midi thru by mapping InputNotes to MIDI messages . This is effectively a recreation of the deriver and MIDI performer , but geared to producing a single note immediately rather than deriving and performing an entire score . But since derivation and performance are both very complicated , it 's doomed to be complicated and inaccurate . The rationale is that the performer is oriented around a stream of events when their durations are known , while this must derive a single key , and in real time . However , it 's also due to history ( derivation used to be much simpler ) , and concerns about efficiency , so in the future I 'll probably move towards reusing as much of the deriver and performer as possible . Note that actually much of the deriver is already reused , courtesy of ' Perf.derive_at ' . Also , ' ' may have a shortcut implementation , but for complicated scales falls back on derivation . An implementation that fully reuses deriver and performer is in " Cmd . Instrument . CUtil".insert_expr . This is a very complicated thru and might be too slow . It has to deal with : - Remap input pitch according to scale and control pitch bend range ( done by NoteEntry ) and instrument pb range . This means keeping track of previous note i d and pb val . - Remap addr based on assign to instrument , assigning round - robin . This means keeping track of note ids assigned to addrs and serial numbers for each addr . It 's different from the usual simple thru in that it attempts to assign control messages to a single note . So if the instrument is multiplexed , control changes ( including pitch bend ) will go only to the last sounding key . This also means that controls will not go through at all unless there is a note sounding . It should be possible to reduce latency by bypassing the responder loop and running this in its own thread . It does mean the InputNote work is duplicated and synchronization of state , such as current instrument info , gets more complicated because it has to go through an mvar or something . I should find out what makes the responder so slow . Profile it ! - The sync afterwards : Some mechanism to find out if no Ui . State changes have happened and skip sync . - Marshalling the cmd list : cache the expensive parts . The only changing bit is the focus cmds , so keep those until focus changes . - Duplicate NoteInput conversions . - Instrument is looked up on every msg just for pb_range , so cache that . Effectively , the short - circuit thread is another way to cache this . This is effectively a recreation of the deriver and MIDI performer, but geared to producing a single note immediately rather than deriving and performing an entire score. But since derivation and performance are both very complicated, it's doomed to be complicated and inaccurate. The rationale is that the performer is oriented around a stream of events when their durations are known, while this must derive a single key, and in real time. However, it's also due to history (derivation used to be much simpler), and concerns about efficiency, so in the future I'll probably move towards reusing as much of the deriver and performer as possible. Note that actually much of the deriver is already reused, courtesy of 'Perf.derive_at'. Also, 'Scale.scale_input_to_nn' may have a shortcut implementation, but for complicated scales falls back on derivation. An implementation that fully reuses deriver and performer is in "Cmd.Instrument.CUtil".insert_expr. This is a very complicated thru and might be too slow. It has to deal with: - Remap input pitch according to scale and control pitch bend range (done by NoteEntry) and instrument pb range. This means keeping track of previous note id and pb val. - Remap addr based on addrs assign to instrument, assigning round-robin. This means keeping track of note ids assigned to addrs and serial numbers for each addr. It's different from the usual simple thru in that it attempts to assign control messages to a single note. So if the instrument is multiplexed, control changes (including pitch bend) will go only to the last sounding key. This also means that controls will not go through at all unless there is a note sounding. It should be possible to reduce latency by bypassing the responder loop and running this in its own thread. It does mean the InputNote work is duplicated and synchronization of state, such as current instrument info, gets more complicated because it has to go through an mvar or something. I should find out what makes the responder so slow. Profile it! - The sync afterwards: Some mechanism to find out if no Ui.State changes have happened and skip sync. - Marshalling the cmd list: cache the expensive parts. The only changing bit is the focus cmds, so keep those until focus changes. - Duplicate NoteInput conversions. - Instrument is looked up on every msg just for pb_range, so cache that. Effectively, the short-circuit thread is another way to cache this. -} module Cmd.MidiThru ( cmd_midi_thru, for_instrument , convert_input -- * util , channel_messages #ifdef TESTING , module Cmd.MidiThru #endif ) where import qualified Data.Map as Map import qualified Data.Set as Set import qualified Vivid.OSC as OSC import qualified Util.Log as Log import qualified Util.Seq as Seq import qualified Cmd.Cmd as Cmd import qualified Cmd.EditUtil as EditUtil import qualified Cmd.InputNote as InputNote import Cmd.InputNote (NoteId) import qualified Cmd.Msg as Msg import qualified Cmd.Perf as Perf import qualified Cmd.Selection as Selection import qualified Derive.Attrs as Attrs import qualified Derive.Controls as Controls import qualified Derive.Derive as Derive import qualified Derive.DeriveT as DeriveT import qualified Derive.Scale as Scale import qualified Derive.ScoreT as ScoreT import qualified Instrument.Common as Common import qualified Instrument.Inst as Inst import qualified Midi.Midi as Midi import qualified Perform.Midi.Control as Control import qualified Perform.Midi.Patch as Patch import Perform.Midi.Patch (Addr) import qualified Perform.Pitch as Pitch import qualified Perform.Sc.Patch as Sc.Patch import qualified Perform.Sc.Play as Sc.Play import qualified Ui.Ui as Ui import qualified Ui.UiConfig as UiConfig import Global -- | Send midi thru, addressing it to the given Instrument. -- -- Actually, this handles 'Cmd.ImThru' as well, since it relies on the instrument itself providing the thru function in ' Cmd.inst_thru ' . cmd_midi_thru :: Msg.Msg -> Cmd.CmdId Cmd.Status cmd_midi_thru msg = do input <- case msg of Msg.InputNote input -> return input _ -> Cmd.abort score_inst <- Cmd.abort_unless =<< EditUtil.lookup_instrument attrs <- Cmd.get_instrument_attributes score_inst scale <- Perf.get_scale =<< Selection.track mapM_ Cmd.write_thru =<< for_instrument score_inst scale attrs input return Cmd.Continue for_instrument :: ScoreT.Instrument -> Cmd.ThruFunction for_instrument score_inst scale attrs input = do resolved <- Cmd.get_instrument score_inst let code_of = Common.common_code . Inst.inst_common . Cmd.inst_instrument let flags = Common.common_flags $ Cmd.inst_common resolved case Cmd.inst_thru (code_of resolved) of Nothing | Just (patch, config) <- Cmd.midi_patch resolved -> midi_thru patch config score_inst scale attrs input | Just patch <- Cmd.sc_patch resolved -> osc_thru patch flags score_inst scale attrs input | otherwise -> Cmd.abort Just thru -> thru scale attrs input | This does n't really fit with the name of the module , but OSC thru for -- supercollider is so much simpler than MIDI I can just throw it in here. osc_thru :: Sc.Patch.Patch -> Set Common.Flag -> ScoreT.Instrument -> Cmd.ThruFunction osc_thru patch flags score_inst scale _attrs input = do attrs is used for keyswitches in MIDI , but sc does n't support attrs yet . -- If I do, it'll probably be via string-valued controls. input <- convert_input score_inst scale input (:[]) . Cmd.OscThru <$> input_to_osc patch flags input input_to_osc :: Cmd.M m => Sc.Patch.Patch -> Set Common.Flag -> InputNote.InputNn -> m [OSC.OSC] input_to_osc patch flags = return . \case InputNote.NoteOn note_id nn vel -> Sc.Play.note_on patch triggered (unid note_id) nn vel InputNote.NoteOff note_id _ -> Sc.Play.note_off triggered (unid note_id) InputNote.Control note_id control val -> Sc.Play.set_control patch (unid note_id) control val InputNote.PitchChange note_id nn -> Sc.Play.pitch_change patch (unid note_id) nn where triggered = Common.Triggered `Set.member` flags unid (InputNote.NoteId id) = id | I used to keep track of the previous PitchBend to avoid sending extra ones . -- But it turns out I don't actually know the state of the MIDI channel, so now I always send PitchBend . I 'm not sure why I ever thought it could work . I could still do this by tracking channel state at the Midi . Interface level . -- I actually already do that a bit of tracking with note_tracker, but it's simpler to just always send PitchBend , unless it becomes a problem . midi_thru :: Patch.Patch -> Patch.Config -> ScoreT.Instrument -> Cmd.ThruFunction midi_thru patch config score_inst scale attrs input = do input <- convert_input score_inst scale input let addrs = Patch.config_addrs config if null addrs then return [] else do (input_nn, ks) <- Cmd.require (pretty (Scale.scale_id scale) <> " doesn't have " <> pretty input) =<< input_to_nn score_inst (Patch.patch_attribute_map patch) (Patch.settings#Patch.scale #$ config) attrs input wdev_state <- Cmd.get_wdev_state pb_range <- Cmd.require "no pb range" $ Patch.settings#Patch.pitch_bend_range #$ config maybe (return []) (to_msgs ks) $ input_to_midi pb_range wdev_state addrs input_nn where to_msgs ks (thru_msgs, wdev_state) = do Cmd.modify_wdev_state (const wdev_state) let ks_msgs = concatMap (keyswitch_to_midi thru_msgs) ks return $ map (uncurry Cmd.midi_thru) $ ks_msgs ++ thru_msgs -- | The keyswitch winds up being simultaneous with the note on. Especially -- stupid VSTs like kontakt will sometimes miss a keyswitch if it doesn't have -- enough lead time. There's not much I can do about that, but to avoid making -- the keyswitch too short I hold it down along with the note. keyswitch_to_midi :: [(Midi.WriteDevice, Midi.Message)] -> Patch.Keyswitch -> [(Midi.WriteDevice, Midi.Message)] keyswitch_to_midi msgs ks = case msum (map note_msg msgs) of Nothing -> [] Just (addr, key, is_note_on) -> map (with_addr addr) $ if is_note_on then [Patch.keyswitch_on key ks] else maybe [] (:[]) (Patch.keyswitch_off ks) where note_msg (dev, Midi.ChannelMessage chan msg) = case msg of Midi.NoteOn key _ -> Just ((dev, chan), key, True) Midi.NoteOff key _ -> Just ((dev, chan), key, False) _ -> Nothing note_msg _ = Nothing -- | Realize the Input as a pitch in the given scale. input_to_nn :: Cmd.M m => ScoreT.Instrument -> Patch.AttributeMap -> Maybe Patch.Scale -> Attrs.Attributes -> InputNote.InputNn -> m (Maybe (InputNote.InputNn, [Patch.Keyswitch])) input_to_nn inst attr_map patch_scale attrs = \case InputNote.NoteOn note_id nn vel -> justm (convert nn) $ \(nn, ks) -> return $ Just (InputNote.NoteOn note_id nn vel, ks) InputNote.PitchChange note_id input -> justm (convert input) $ \(nn, _) -> return $ Just (InputNote.PitchChange note_id nn, []) input@(InputNote.NoteOff {}) -> return $ Just (input, ks) where ks = maybe [] (fst . snd) $ Common.lookup_attributes attrs attr_map input@(InputNote.Control {}) -> return $ Just (input, []) where convert nn = do let (result, not_found) = convert_pitch attr_map patch_scale attrs nn when not_found $ Log.warn $ "inst " <> pretty inst <> " doesn't have attrs " <> pretty attrs <> ", understood attrs are: " <> pretty (Common.mapped_attributes attr_map) return result | Convert a keyboard input into the NoteNumber desired by the scale . convert_input :: Cmd.M m => ScoreT.Instrument -> Scale.Scale -> InputNote.Input -> m InputNote.InputNn convert_input inst scale = \case InputNote.NoteOn note_id input vel -> do nn <- convert input return $ InputNote.NoteOn note_id nn vel InputNote.PitchChange note_id input -> InputNote.PitchChange note_id <$> convert input InputNote.NoteOff note_id vel -> return $ InputNote.NoteOff note_id vel InputNote.Control note_id control val -> return $ InputNote.Control note_id control val where convert = convert_input_pitch inst scale convert_input_pitch :: Cmd.M m => ScoreT.Instrument -> Scale.Scale -> Pitch.Input -> m Pitch.NoteNumber convert_input_pitch inst scale input = do (block_id, _, track_id, pos) <- Selection.get_insert -- I ignore _logs, any interesting errors should be in 'result'. (result, _logs) <- Perf.derive_at_exc block_id track_id $ Derive.with_instrument inst $ filter_transposers scale $ Scale.scale_input_to_nn scale pos input case result of Left (Derive.Error _ _ err) -> throw $ pretty err -- This just means the key isn't in the scale, it happens a lot so -- no need to shout about it. Right (Left DeriveT.InvalidInput) -> Cmd.abort Right (Left err) -> throw $ pretty err Right (Right nn) -> return nn where throw = Cmd.throw . (("scale_input_to_nn for " <> pretty input <> ": ") <>) -- | Remove transposers because otherwise the thru pitch doesn't match the -- entered pitch and it's very confusing. However, I retain 'Controls.octave' -- and 'Controls.hz' because those are used to configure a scale, e.g. via -- 'Patch.config_controls', and the pitch is nominally the same. filter_transposers :: Scale.Scale -> Derive.Deriver a -> Derive.Deriver a filter_transposers scale = Derive.with_controls transposers where transposers = zip (filter (`notElem` [Controls.octave, Controls.hz]) (Set.toList (Scale.scale_transposers scale))) (repeat (ScoreT.untyped mempty)) | This is a midi thru version of ' Perform . Midi . Convert.convert_midi_pitch ' . It 's different because it works with a scalar NoteNumber instead of -- a Score.Event with a pitch signal, which makes it hard to share code. convert_pitch :: Patch.AttributeMap -> Maybe Patch.Scale -> Attrs.Attributes -> Pitch.NoteNumber -> (Maybe (Pitch.NoteNumber, [Patch.Keyswitch]), Bool) ^ The is True if the attrs were non - empty but not found . convert_pitch attr_map patch_scale attrs nn = case Common.lookup_attributes attrs attr_map of Nothing -> ((, []) <$> maybe_pitch, attrs /= mempty) Just (_, (keyswitches, maybe_keymap)) -> ( (, keyswitches) <$> maybe maybe_pitch set_keymap maybe_keymap , False ) where maybe_pitch = apply_patch_scale nn apply_patch_scale = maybe Just Patch.convert_scale patch_scale set_keymap (Patch.UnpitchedKeymap key) = Just $ Midi.from_key key set_keymap (Patch.PitchedKeymap low _ low_pitch) = (+ Midi.from_key (low - low_pitch)) <$> maybe_pitch input_to_midi :: Control.PbRange -> Cmd.WriteDeviceState -> [Addr] -> InputNote.InputNn -> Maybe ([(Midi.WriteDevice, Midi.Message)], Cmd.WriteDeviceState) input_to_midi pb_range wdev_state addrs input_nn = case alloc addrs input_nn of (Nothing, _) -> Nothing (Just addr, new_state) -> Just (map (with_addr addr) msgs, state) where (msgs, note_key) = InputNote.to_midi pb_range (Cmd.wdev_note_key wdev_state) input_nn state = merge_state new_state (wdev_state { Cmd.wdev_note_key = note_key }) where alloc = alloc_addr (Cmd.wdev_note_addr wdev_state) (Cmd.wdev_addr_serial wdev_state) (Cmd.wdev_serial wdev_state) merge_state :: Maybe (Map NoteId Addr, Map Addr Cmd.Serial) -> Cmd.WriteDeviceState -> Cmd.WriteDeviceState merge_state new_state old = case new_state of Nothing -> old Just (note_addr, addr_serial) -> old { Cmd.wdev_note_addr = note_addr , Cmd.wdev_addr_serial = addr_serial , Cmd.wdev_serial = Cmd.wdev_serial old + 1 } -- | If the note_id is already playing in an addr, return that one. Otherwise, if it 's not NoteOn or NoteOff , abort . If it is , pick a free addr , and if there is no free one , pick the oldest one . Update the wdev state and assign -- the note id to the addr. alloc_addr :: Map NoteId Addr -> Map Addr Cmd.Serial -> Cmd.Serial ^ allocated to this instrument . -> InputNote.InputNn -> (Maybe Addr, Maybe (Map NoteId Addr, Map Addr Cmd.Serial)) alloc_addr note_addr addr_serial serial addrs input | Just addr <- Map.lookup note_id note_addr, addr `elem` addrs = case input of InputNote.NoteOff _ _ -> (Just addr, unassign addr) _ -> (Just addr, Nothing) | not (new_note input) = (Nothing, Nothing) | Just addr <- oldest = (Just addr, assign addr) | otherwise = (Nothing, Nothing) -- addrs must be null where note_id = InputNote.input_id input new_note (InputNote.NoteOn {}) = True new_note (InputNote.NoteOff {}) = True new_note _ = False assign addr = Just (Map.insert note_id addr note_addr, Map.insert addr serial addr_serial) unassign addr = Just (Map.delete note_id note_addr, Map.insert addr serial addr_serial) -- Always pick the channel with the oldest note, whether or not it's -- allocated. Previously I would try to pick a free one, but reusing -- a free channel led to audible artifacts with long-ringing instruments. oldest = Seq.minimum_on (flip Map.lookup addr_serial) addrs with_addr :: Addr -> Midi.ChannelMessage -> (Midi.WriteDevice, Midi.Message) with_addr (wdev, chan) msg = (wdev, Midi.ChannelMessage chan msg) -- * util | Send ChannelMessages to the ( or just the lowest addr ) of the current instrument . This bypasses all of the WriteDeviceState stuff so it wo n't -- cooperate with addr allocation, but hopefully this won't cause problems for simple uses like keymapped instruments . channel_messages :: Cmd.M m => Maybe ScoreT.Instrument -- ^ use this inst, or -- the one on the selected track if Nothing. -> Bool -> [Midi.ChannelMessage] -> m () channel_messages maybe_inst first_addr msgs = do addrs <- get_addrs maybe_inst let addrs2 = if first_addr then take 1 addrs else addrs sequence_ [ Cmd.midi wdev (Midi.ChannelMessage chan msg) | (wdev, chan) <- addrs2, msg <- msgs ] get_addrs :: Cmd.M m => Maybe ScoreT.Instrument -> m [Addr] get_addrs maybe_inst = do inst <- maybe (Cmd.abort_unless =<< EditUtil.lookup_instrument) return maybe_inst alloc <- Ui.allocation inst <#> Ui.get return $ case UiConfig.alloc_backend <$> alloc of Just (UiConfig.Midi config) -> Patch.config_addrs config _ -> []
null
https://raw.githubusercontent.com/elaforge/karya/a3675ce9cffe03c58bd71619cae4f0eaf0dddabd/Cmd/MidiThru.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt * util | Send midi thru, addressing it to the given Instrument. Actually, this handles 'Cmd.ImThru' as well, since it relies on the supercollider is so much simpler than MIDI I can just throw it in here. If I do, it'll probably be via string-valued controls. But it turns out I don't actually know the state of the MIDI channel, so I actually already do that a bit of tracking with note_tracker, but it's | The keyswitch winds up being simultaneous with the note on. Especially stupid VSTs like kontakt will sometimes miss a keyswitch if it doesn't have enough lead time. There's not much I can do about that, but to avoid making the keyswitch too short I hold it down along with the note. | Realize the Input as a pitch in the given scale. I ignore _logs, any interesting errors should be in 'result'. This just means the key isn't in the scale, it happens a lot so no need to shout about it. | Remove transposers because otherwise the thru pitch doesn't match the entered pitch and it's very confusing. However, I retain 'Controls.octave' and 'Controls.hz' because those are used to configure a scale, e.g. via 'Patch.config_controls', and the pitch is nominally the same. a Score.Event with a pitch signal, which makes it hard to share code. | If the note_id is already playing in an addr, return that one. Otherwise, the note id to the addr. addrs must be null Always pick the channel with the oldest note, whether or not it's allocated. Previously I would try to pick a free one, but reusing a free channel led to audible artifacts with long-ringing instruments. * util cooperate with addr allocation, but hopefully this won't cause problems for ^ use this inst, or the one on the selected track if Nothing.
Copyright 2013 # LANGUAGE CPP # | Implement midi thru by mapping InputNotes to MIDI messages . This is effectively a recreation of the deriver and MIDI performer , but geared to producing a single note immediately rather than deriving and performing an entire score . But since derivation and performance are both very complicated , it 's doomed to be complicated and inaccurate . The rationale is that the performer is oriented around a stream of events when their durations are known , while this must derive a single key , and in real time . However , it 's also due to history ( derivation used to be much simpler ) , and concerns about efficiency , so in the future I 'll probably move towards reusing as much of the deriver and performer as possible . Note that actually much of the deriver is already reused , courtesy of ' Perf.derive_at ' . Also , ' ' may have a shortcut implementation , but for complicated scales falls back on derivation . An implementation that fully reuses deriver and performer is in " Cmd . Instrument . CUtil".insert_expr . This is a very complicated thru and might be too slow . It has to deal with : - Remap input pitch according to scale and control pitch bend range ( done by NoteEntry ) and instrument pb range . This means keeping track of previous note i d and pb val . - Remap addr based on assign to instrument , assigning round - robin . This means keeping track of note ids assigned to addrs and serial numbers for each addr . It 's different from the usual simple thru in that it attempts to assign control messages to a single note . So if the instrument is multiplexed , control changes ( including pitch bend ) will go only to the last sounding key . This also means that controls will not go through at all unless there is a note sounding . It should be possible to reduce latency by bypassing the responder loop and running this in its own thread . It does mean the InputNote work is duplicated and synchronization of state , such as current instrument info , gets more complicated because it has to go through an mvar or something . I should find out what makes the responder so slow . Profile it ! - The sync afterwards : Some mechanism to find out if no Ui . State changes have happened and skip sync . - Marshalling the cmd list : cache the expensive parts . The only changing bit is the focus cmds , so keep those until focus changes . - Duplicate NoteInput conversions . - Instrument is looked up on every msg just for pb_range , so cache that . Effectively , the short - circuit thread is another way to cache this . This is effectively a recreation of the deriver and MIDI performer, but geared to producing a single note immediately rather than deriving and performing an entire score. But since derivation and performance are both very complicated, it's doomed to be complicated and inaccurate. The rationale is that the performer is oriented around a stream of events when their durations are known, while this must derive a single key, and in real time. However, it's also due to history (derivation used to be much simpler), and concerns about efficiency, so in the future I'll probably move towards reusing as much of the deriver and performer as possible. Note that actually much of the deriver is already reused, courtesy of 'Perf.derive_at'. Also, 'Scale.scale_input_to_nn' may have a shortcut implementation, but for complicated scales falls back on derivation. An implementation that fully reuses deriver and performer is in "Cmd.Instrument.CUtil".insert_expr. This is a very complicated thru and might be too slow. It has to deal with: - Remap input pitch according to scale and control pitch bend range (done by NoteEntry) and instrument pb range. This means keeping track of previous note id and pb val. - Remap addr based on addrs assign to instrument, assigning round-robin. This means keeping track of note ids assigned to addrs and serial numbers for each addr. It's different from the usual simple thru in that it attempts to assign control messages to a single note. So if the instrument is multiplexed, control changes (including pitch bend) will go only to the last sounding key. This also means that controls will not go through at all unless there is a note sounding. It should be possible to reduce latency by bypassing the responder loop and running this in its own thread. It does mean the InputNote work is duplicated and synchronization of state, such as current instrument info, gets more complicated because it has to go through an mvar or something. I should find out what makes the responder so slow. Profile it! - The sync afterwards: Some mechanism to find out if no Ui.State changes have happened and skip sync. - Marshalling the cmd list: cache the expensive parts. The only changing bit is the focus cmds, so keep those until focus changes. - Duplicate NoteInput conversions. - Instrument is looked up on every msg just for pb_range, so cache that. Effectively, the short-circuit thread is another way to cache this. -} module Cmd.MidiThru ( cmd_midi_thru, for_instrument , convert_input , channel_messages #ifdef TESTING , module Cmd.MidiThru #endif ) where import qualified Data.Map as Map import qualified Data.Set as Set import qualified Vivid.OSC as OSC import qualified Util.Log as Log import qualified Util.Seq as Seq import qualified Cmd.Cmd as Cmd import qualified Cmd.EditUtil as EditUtil import qualified Cmd.InputNote as InputNote import Cmd.InputNote (NoteId) import qualified Cmd.Msg as Msg import qualified Cmd.Perf as Perf import qualified Cmd.Selection as Selection import qualified Derive.Attrs as Attrs import qualified Derive.Controls as Controls import qualified Derive.Derive as Derive import qualified Derive.DeriveT as DeriveT import qualified Derive.Scale as Scale import qualified Derive.ScoreT as ScoreT import qualified Instrument.Common as Common import qualified Instrument.Inst as Inst import qualified Midi.Midi as Midi import qualified Perform.Midi.Control as Control import qualified Perform.Midi.Patch as Patch import Perform.Midi.Patch (Addr) import qualified Perform.Pitch as Pitch import qualified Perform.Sc.Patch as Sc.Patch import qualified Perform.Sc.Play as Sc.Play import qualified Ui.Ui as Ui import qualified Ui.UiConfig as UiConfig import Global instrument itself providing the thru function in ' Cmd.inst_thru ' . cmd_midi_thru :: Msg.Msg -> Cmd.CmdId Cmd.Status cmd_midi_thru msg = do input <- case msg of Msg.InputNote input -> return input _ -> Cmd.abort score_inst <- Cmd.abort_unless =<< EditUtil.lookup_instrument attrs <- Cmd.get_instrument_attributes score_inst scale <- Perf.get_scale =<< Selection.track mapM_ Cmd.write_thru =<< for_instrument score_inst scale attrs input return Cmd.Continue for_instrument :: ScoreT.Instrument -> Cmd.ThruFunction for_instrument score_inst scale attrs input = do resolved <- Cmd.get_instrument score_inst let code_of = Common.common_code . Inst.inst_common . Cmd.inst_instrument let flags = Common.common_flags $ Cmd.inst_common resolved case Cmd.inst_thru (code_of resolved) of Nothing | Just (patch, config) <- Cmd.midi_patch resolved -> midi_thru patch config score_inst scale attrs input | Just patch <- Cmd.sc_patch resolved -> osc_thru patch flags score_inst scale attrs input | otherwise -> Cmd.abort Just thru -> thru scale attrs input | This does n't really fit with the name of the module , but OSC thru for osc_thru :: Sc.Patch.Patch -> Set Common.Flag -> ScoreT.Instrument -> Cmd.ThruFunction osc_thru patch flags score_inst scale _attrs input = do attrs is used for keyswitches in MIDI , but sc does n't support attrs yet . input <- convert_input score_inst scale input (:[]) . Cmd.OscThru <$> input_to_osc patch flags input input_to_osc :: Cmd.M m => Sc.Patch.Patch -> Set Common.Flag -> InputNote.InputNn -> m [OSC.OSC] input_to_osc patch flags = return . \case InputNote.NoteOn note_id nn vel -> Sc.Play.note_on patch triggered (unid note_id) nn vel InputNote.NoteOff note_id _ -> Sc.Play.note_off triggered (unid note_id) InputNote.Control note_id control val -> Sc.Play.set_control patch (unid note_id) control val InputNote.PitchChange note_id nn -> Sc.Play.pitch_change patch (unid note_id) nn where triggered = Common.Triggered `Set.member` flags unid (InputNote.NoteId id) = id | I used to keep track of the previous PitchBend to avoid sending extra ones . now I always send PitchBend . I 'm not sure why I ever thought it could work . I could still do this by tracking channel state at the Midi . Interface level . simpler to just always send PitchBend , unless it becomes a problem . midi_thru :: Patch.Patch -> Patch.Config -> ScoreT.Instrument -> Cmd.ThruFunction midi_thru patch config score_inst scale attrs input = do input <- convert_input score_inst scale input let addrs = Patch.config_addrs config if null addrs then return [] else do (input_nn, ks) <- Cmd.require (pretty (Scale.scale_id scale) <> " doesn't have " <> pretty input) =<< input_to_nn score_inst (Patch.patch_attribute_map patch) (Patch.settings#Patch.scale #$ config) attrs input wdev_state <- Cmd.get_wdev_state pb_range <- Cmd.require "no pb range" $ Patch.settings#Patch.pitch_bend_range #$ config maybe (return []) (to_msgs ks) $ input_to_midi pb_range wdev_state addrs input_nn where to_msgs ks (thru_msgs, wdev_state) = do Cmd.modify_wdev_state (const wdev_state) let ks_msgs = concatMap (keyswitch_to_midi thru_msgs) ks return $ map (uncurry Cmd.midi_thru) $ ks_msgs ++ thru_msgs keyswitch_to_midi :: [(Midi.WriteDevice, Midi.Message)] -> Patch.Keyswitch -> [(Midi.WriteDevice, Midi.Message)] keyswitch_to_midi msgs ks = case msum (map note_msg msgs) of Nothing -> [] Just (addr, key, is_note_on) -> map (with_addr addr) $ if is_note_on then [Patch.keyswitch_on key ks] else maybe [] (:[]) (Patch.keyswitch_off ks) where note_msg (dev, Midi.ChannelMessage chan msg) = case msg of Midi.NoteOn key _ -> Just ((dev, chan), key, True) Midi.NoteOff key _ -> Just ((dev, chan), key, False) _ -> Nothing note_msg _ = Nothing input_to_nn :: Cmd.M m => ScoreT.Instrument -> Patch.AttributeMap -> Maybe Patch.Scale -> Attrs.Attributes -> InputNote.InputNn -> m (Maybe (InputNote.InputNn, [Patch.Keyswitch])) input_to_nn inst attr_map patch_scale attrs = \case InputNote.NoteOn note_id nn vel -> justm (convert nn) $ \(nn, ks) -> return $ Just (InputNote.NoteOn note_id nn vel, ks) InputNote.PitchChange note_id input -> justm (convert input) $ \(nn, _) -> return $ Just (InputNote.PitchChange note_id nn, []) input@(InputNote.NoteOff {}) -> return $ Just (input, ks) where ks = maybe [] (fst . snd) $ Common.lookup_attributes attrs attr_map input@(InputNote.Control {}) -> return $ Just (input, []) where convert nn = do let (result, not_found) = convert_pitch attr_map patch_scale attrs nn when not_found $ Log.warn $ "inst " <> pretty inst <> " doesn't have attrs " <> pretty attrs <> ", understood attrs are: " <> pretty (Common.mapped_attributes attr_map) return result | Convert a keyboard input into the NoteNumber desired by the scale . convert_input :: Cmd.M m => ScoreT.Instrument -> Scale.Scale -> InputNote.Input -> m InputNote.InputNn convert_input inst scale = \case InputNote.NoteOn note_id input vel -> do nn <- convert input return $ InputNote.NoteOn note_id nn vel InputNote.PitchChange note_id input -> InputNote.PitchChange note_id <$> convert input InputNote.NoteOff note_id vel -> return $ InputNote.NoteOff note_id vel InputNote.Control note_id control val -> return $ InputNote.Control note_id control val where convert = convert_input_pitch inst scale convert_input_pitch :: Cmd.M m => ScoreT.Instrument -> Scale.Scale -> Pitch.Input -> m Pitch.NoteNumber convert_input_pitch inst scale input = do (block_id, _, track_id, pos) <- Selection.get_insert (result, _logs) <- Perf.derive_at_exc block_id track_id $ Derive.with_instrument inst $ filter_transposers scale $ Scale.scale_input_to_nn scale pos input case result of Left (Derive.Error _ _ err) -> throw $ pretty err Right (Left DeriveT.InvalidInput) -> Cmd.abort Right (Left err) -> throw $ pretty err Right (Right nn) -> return nn where throw = Cmd.throw . (("scale_input_to_nn for " <> pretty input <> ": ") <>) filter_transposers :: Scale.Scale -> Derive.Deriver a -> Derive.Deriver a filter_transposers scale = Derive.with_controls transposers where transposers = zip (filter (`notElem` [Controls.octave, Controls.hz]) (Set.toList (Scale.scale_transposers scale))) (repeat (ScoreT.untyped mempty)) | This is a midi thru version of ' Perform . Midi . Convert.convert_midi_pitch ' . It 's different because it works with a scalar NoteNumber instead of convert_pitch :: Patch.AttributeMap -> Maybe Patch.Scale -> Attrs.Attributes -> Pitch.NoteNumber -> (Maybe (Pitch.NoteNumber, [Patch.Keyswitch]), Bool) ^ The is True if the attrs were non - empty but not found . convert_pitch attr_map patch_scale attrs nn = case Common.lookup_attributes attrs attr_map of Nothing -> ((, []) <$> maybe_pitch, attrs /= mempty) Just (_, (keyswitches, maybe_keymap)) -> ( (, keyswitches) <$> maybe maybe_pitch set_keymap maybe_keymap , False ) where maybe_pitch = apply_patch_scale nn apply_patch_scale = maybe Just Patch.convert_scale patch_scale set_keymap (Patch.UnpitchedKeymap key) = Just $ Midi.from_key key set_keymap (Patch.PitchedKeymap low _ low_pitch) = (+ Midi.from_key (low - low_pitch)) <$> maybe_pitch input_to_midi :: Control.PbRange -> Cmd.WriteDeviceState -> [Addr] -> InputNote.InputNn -> Maybe ([(Midi.WriteDevice, Midi.Message)], Cmd.WriteDeviceState) input_to_midi pb_range wdev_state addrs input_nn = case alloc addrs input_nn of (Nothing, _) -> Nothing (Just addr, new_state) -> Just (map (with_addr addr) msgs, state) where (msgs, note_key) = InputNote.to_midi pb_range (Cmd.wdev_note_key wdev_state) input_nn state = merge_state new_state (wdev_state { Cmd.wdev_note_key = note_key }) where alloc = alloc_addr (Cmd.wdev_note_addr wdev_state) (Cmd.wdev_addr_serial wdev_state) (Cmd.wdev_serial wdev_state) merge_state :: Maybe (Map NoteId Addr, Map Addr Cmd.Serial) -> Cmd.WriteDeviceState -> Cmd.WriteDeviceState merge_state new_state old = case new_state of Nothing -> old Just (note_addr, addr_serial) -> old { Cmd.wdev_note_addr = note_addr , Cmd.wdev_addr_serial = addr_serial , Cmd.wdev_serial = Cmd.wdev_serial old + 1 } if it 's not NoteOn or NoteOff , abort . If it is , pick a free addr , and if there is no free one , pick the oldest one . Update the wdev state and assign alloc_addr :: Map NoteId Addr -> Map Addr Cmd.Serial -> Cmd.Serial ^ allocated to this instrument . -> InputNote.InputNn -> (Maybe Addr, Maybe (Map NoteId Addr, Map Addr Cmd.Serial)) alloc_addr note_addr addr_serial serial addrs input | Just addr <- Map.lookup note_id note_addr, addr `elem` addrs = case input of InputNote.NoteOff _ _ -> (Just addr, unassign addr) _ -> (Just addr, Nothing) | not (new_note input) = (Nothing, Nothing) | Just addr <- oldest = (Just addr, assign addr) where note_id = InputNote.input_id input new_note (InputNote.NoteOn {}) = True new_note (InputNote.NoteOff {}) = True new_note _ = False assign addr = Just (Map.insert note_id addr note_addr, Map.insert addr serial addr_serial) unassign addr = Just (Map.delete note_id note_addr, Map.insert addr serial addr_serial) oldest = Seq.minimum_on (flip Map.lookup addr_serial) addrs with_addr :: Addr -> Midi.ChannelMessage -> (Midi.WriteDevice, Midi.Message) with_addr (wdev, chan) msg = (wdev, Midi.ChannelMessage chan msg) | Send ChannelMessages to the ( or just the lowest addr ) of the current instrument . This bypasses all of the WriteDeviceState stuff so it wo n't simple uses like keymapped instruments . -> Bool -> [Midi.ChannelMessage] -> m () channel_messages maybe_inst first_addr msgs = do addrs <- get_addrs maybe_inst let addrs2 = if first_addr then take 1 addrs else addrs sequence_ [ Cmd.midi wdev (Midi.ChannelMessage chan msg) | (wdev, chan) <- addrs2, msg <- msgs ] get_addrs :: Cmd.M m => Maybe ScoreT.Instrument -> m [Addr] get_addrs maybe_inst = do inst <- maybe (Cmd.abort_unless =<< EditUtil.lookup_instrument) return maybe_inst alloc <- Ui.allocation inst <#> Ui.get return $ case UiConfig.alloc_backend <$> alloc of Just (UiConfig.Midi config) -> Patch.config_addrs config _ -> []
138e96c6b98d7991466ebb8e57ebab4bfe12a294c1d46305732eac982b5c46b4
alanz/ghc-exactprint
LinearArrow.hs
# LANGUAGE LinearTypes , DataKinds , UnicodeSyntax # module LinearArrow where import GHC.Types (Multiplicity(One, Many)) n1 :: a %1 -> b n1 = undefined u1 :: a %1 → b u1 = undefined n2 :: a %(Many) -> b n2 = undefined u2 :: a %(Many) → b u2 = undefined m3 :: a ⊸ b m3 = undefined n4 :: a %p -> b n4 = undefined u4 :: a %p → b u4 = undefined
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/103bc706c82300639985a15ba6cf762316352c92/tests/examples/ghc92/LinearArrow.hs
haskell
# LANGUAGE LinearTypes , DataKinds , UnicodeSyntax # module LinearArrow where import GHC.Types (Multiplicity(One, Many)) n1 :: a %1 -> b n1 = undefined u1 :: a %1 → b u1 = undefined n2 :: a %(Many) -> b n2 = undefined u2 :: a %(Many) → b u2 = undefined m3 :: a ⊸ b m3 = undefined n4 :: a %p -> b n4 = undefined u4 :: a %p → b u4 = undefined
eba907bbe024f6c203425e416238497db724005ab8eb430a67ce1afb043d2e88
gedge-platform/gedge-platform
rabbit_registry_class.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2016 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% -module(rabbit_registry_class). -callback added_to_rabbit_registry(atom(), atom()) -> ok. -callback removed_from_rabbit_registry(atom()) -> ok.
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit_common/src/rabbit_registry_class.erl
erlang
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2016 - 2021 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_registry_class). -callback added_to_rabbit_registry(atom(), atom()) -> ok. -callback removed_from_rabbit_registry(atom()) -> ok.
84c27f62dcaebf7f8e844d86a0b1b6a0d57205f75164d5d3f153df1d6013e1c8
korma/Korma
one_to_one.clj
(ns korma.test.integration.one-to-one (:require clojure.string) (:use clojure.test [korma.db :only [defdb h2 default-connection]] [korma.core :only [defentity pk fk belongs-to has-one transform exec-raw insert values select with]])) (defdb mem-db (h2 {:db "mem:one_to_one_test"})) (defentity state (pk :state_id) (transform #(update-in % [:name] clojure.string/capitalize))) (defentity address (pk :address_id) (belongs-to state (fk :id_of_state)) (transform #(update-in % [:street] clojure.string/capitalize))) (defentity user (has-one address (fk :id_of_user))) (def schema ["drop table if exists \"state\";" "drop table if exists \"user\";" "drop table if exists \"address\";" "create table \"state\" (\"state_id\" varchar(20), \"name\" varchar(100));" "create table \"user\" (\"id\" integer primary key, \"name\" varchar(100));" "create table \"address\" (\"address_id\" integer primary key, \"id_of_user\" integer, \"id_of_state\" varchar(20), \"street\" varchar(200), foreign key (\"id_of_user\") references \"user\"(\"id\"), foreign key (\"id_of_state\") references \"state\"(\"state_id\"));"]) (defn- setup-db [] (default-connection mem-db) (dorun (map exec-raw schema)) (insert :state (values [{:state_id "CA" :name "california"} {:state_id "PA" :name "pennsylvania"}])) (insert :user (values [{:id 1 :name "Chris"} {:id 2 :name "Alex"}])) (insert :address (values [{:address_id 101 :street "main street" :id_of_state "CA" :id_of_user 1} {:address_id 102 :street "park street" :id_of_state "PA" :id_of_user 2}]))) (use-fixtures :once (fn [f] (setup-db) (f))) (deftest belongs-to-with-transformer-users-correct-join-keys (is (= [{:id 1 :name "Chris" :address_id 101 :street "Main street" :id_of_state "CA" :id_of_user 1} {:id 2 :name "Alex" :address_id 102 :street "Park street" :id_of_state "PA" :id_of_user 2}] (select user (with address))))) (deftest has-one-with-transformer-users-correct-join-keys (is (= [{:address_id 101 :street "Main street" :id_of_state "CA" :id_of_user 1 :state_id "CA" :name "California"} {:address_id 102 :street "Park street" :id_of_state "PA" :id_of_user 2 :state_id "PA" :name "Pennsylvania"}] (select address (with state)))))
null
https://raw.githubusercontent.com/korma/Korma/6b76592dd54ba2b03c5862701c8d18a8eea8c040/test/korma/test/integration/one_to_one.clj
clojure
" " "])
(ns korma.test.integration.one-to-one (:require clojure.string) (:use clojure.test [korma.db :only [defdb h2 default-connection]] [korma.core :only [defentity pk fk belongs-to has-one transform exec-raw insert values select with]])) (defdb mem-db (h2 {:db "mem:one_to_one_test"})) (defentity state (pk :state_id) (transform #(update-in % [:name] clojure.string/capitalize))) (defentity address (pk :address_id) (belongs-to state (fk :id_of_state)) (transform #(update-in % [:street] clojure.string/capitalize))) (defentity user (has-one address (fk :id_of_user))) (def schema ["drop table if exists \"state\";" "drop table if exists \"user\";" "drop table if exists \"address\";" "create table \"state\" (\"state_id\" varchar(20), "create table \"user\" (\"id\" integer primary key, "create table \"address\" (\"address_id\" integer primary key, \"id_of_user\" integer, \"id_of_state\" varchar(20), \"street\" varchar(200), foreign key (\"id_of_user\") references \"user\"(\"id\"), (defn- setup-db [] (default-connection mem-db) (dorun (map exec-raw schema)) (insert :state (values [{:state_id "CA" :name "california"} {:state_id "PA" :name "pennsylvania"}])) (insert :user (values [{:id 1 :name "Chris"} {:id 2 :name "Alex"}])) (insert :address (values [{:address_id 101 :street "main street" :id_of_state "CA" :id_of_user 1} {:address_id 102 :street "park street" :id_of_state "PA" :id_of_user 2}]))) (use-fixtures :once (fn [f] (setup-db) (f))) (deftest belongs-to-with-transformer-users-correct-join-keys (is (= [{:id 1 :name "Chris" :address_id 101 :street "Main street" :id_of_state "CA" :id_of_user 1} {:id 2 :name "Alex" :address_id 102 :street "Park street" :id_of_state "PA" :id_of_user 2}] (select user (with address))))) (deftest has-one-with-transformer-users-correct-join-keys (is (= [{:address_id 101 :street "Main street" :id_of_state "CA" :id_of_user 1 :state_id "CA" :name "California"} {:address_id 102 :street "Park street" :id_of_state "PA" :id_of_user 2 :state_id "PA" :name "Pennsylvania"}] (select address (with state)))))
9aecbbf5181f4d4b82bb3403bcdb1b0812f915705d3953d12348a26a9d59de7a
diasbruno/cl-bnf
common.lisp
(in-package :cl-bnf-tests) (defun numeric-char-p (char) (and (char-not-lessp char #\0) (char-not-greaterp char #\9)))
null
https://raw.githubusercontent.com/diasbruno/cl-bnf/e545e41519b66aa05c9a441c6c8bb4cff67a9cab/t/common.lisp
lisp
(in-package :cl-bnf-tests) (defun numeric-char-p (char) (and (char-not-lessp char #\0) (char-not-greaterp char #\9)))
a7ef72c6d01b8c0d4781a98e602a37e1e500f8e5cce4fcb858671a44c832bfe9
restyled-io/restyled.io
Metric.hs
module Restyled.Metric ( Metric(..) , Unit(..) , Dimension(..) ) where import Restyled.Prelude data Metric n = Metric { mName :: Text , mValue :: n , mUnit :: Unit , mDimensions :: [Dimension] } instance ToJSON n => ToJSON (Metric n) where toJSON Metric {..} = object [ "MetricName" .= mName , "Value" .= mValue , "Unit" .= mUnit , "Dimensions" .= mDimensions ] data Unit = Count | Percent instance ToJSON Unit where toJSON = \case Count -> String "Count" Percent -> String "Percent" data Dimension = Dimension { dName :: Text , dValue :: Text } instance ToJSON Dimension where toJSON Dimension {..} = object ["Name" .= dName, "Value" .= dValue]
null
https://raw.githubusercontent.com/restyled-io/restyled.io/7b53f3d485a3d805da946aaf359174ea2f1ddf01/src/Restyled/Metric.hs
haskell
module Restyled.Metric ( Metric(..) , Unit(..) , Dimension(..) ) where import Restyled.Prelude data Metric n = Metric { mName :: Text , mValue :: n , mUnit :: Unit , mDimensions :: [Dimension] } instance ToJSON n => ToJSON (Metric n) where toJSON Metric {..} = object [ "MetricName" .= mName , "Value" .= mValue , "Unit" .= mUnit , "Dimensions" .= mDimensions ] data Unit = Count | Percent instance ToJSON Unit where toJSON = \case Count -> String "Count" Percent -> String "Percent" data Dimension = Dimension { dName :: Text , dValue :: Text } instance ToJSON Dimension where toJSON Dimension {..} = object ["Name" .= dName, "Value" .= dValue]
0364f65699fee426f6a5a3589035aefb9dd9b55f2efb73b84b047c145e8d9126
ghc/testsuite
tcrun009.hs
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies # -- !!! Functional dependencies module Main where class Foo a b | a -> b where foo :: a -> b instance Foo [a] (Maybe a) where foo [] = Nothing foo (x:_) = Just x instance Foo (Maybe a) [a] where foo Nothing = [] foo (Just x) = [x] test3:: [a] -> [a] test3 = foo . foo First foo must use the first instance , second must use the second . So we should -- get in effect: test3 (x:xs) = [x] main:: IO () main = print (test3 "foo")
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_run/tcrun009.hs
haskell
!!! Functional dependencies get in effect: test3 (x:xs) = [x]
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies # module Main where class Foo a b | a -> b where foo :: a -> b instance Foo [a] (Maybe a) where foo [] = Nothing foo (x:_) = Just x instance Foo (Maybe a) [a] where foo Nothing = [] foo (Just x) = [x] test3:: [a] -> [a] test3 = foo . foo First foo must use the first instance , second must use the second . So we should main:: IO () main = print (test3 "foo")
9c4437fa2e13896e1a8441bbeaa6e777f56f10987cddf0c6a80772201920ba65
skypher/cl-oauth
service-provider.lisp
(in-package :oauth) (defvar *protocol-version* :1.0) ;;;; Service provider infrastructure ;;;; TODO: need to store application-specific data somewhere. (defun finalize-callback-uri (request-token) "Prepares the callback URI of REQUEST-TOKEN for redirection." (let ((uri (request-token-callback-uri request-token))) (setf (puri:uri-query uri) (concatenate 'string (or (puri:uri-query uri) "") (if (puri:uri-query uri) "&" "") "oauth_token=" (url-encode (token-key request-token)) "&oauth_verifier=" (url-encode (request-token-verification-code request-token)))) uri)) Consumer management (defvar *registered-consumers* (make-hash-table :test #'equalp)) (defmethod register-token ((token consumer-token)) (setf (gethash (token-key token) *registered-consumers*) token) token) (defmethod unregister-token ((token consumer-token)) (remhash (token-key token) *registered-consumers*)) (defun get-consumer-token (key) (gethash key *registered-consumers*)) (defmacro ignore-oauth-errors (&body body) `(handler-case (progn ,@body) (http-error (condition) (values nil condition)))) ;;; signature checking (defun check-signature () (unless (equalp (parameter "oauth_signature_method") "HMAC-SHA1") (raise-error 'bad-request "Signature method not passed or different from HMAC-SHA1")) (let* ((supplied-signature (gethash (request) *signature-cache*)) ;; TODO: do not bluntly ignore all errors. Factor out into GET-TOKEN (consumer-secret (ignore-errors (token-secret (get-consumer-token (parameter "oauth_consumer_key"))))) (token-secret (ignore-errors (token-secret (or (ignore-oauth-errors (get-supplied-request-token)) (ignore-oauth-errors (get-supplied-access-token))))))) (unless supplied-signature (raise-error 'bad-request "This request is not signed")) (unless consumer-secret (raise-error 'unauthorized "Invalid consumer")) ;; now calculate the signature and check for match (let* ((signature-base-string (signature-base-string)) (hmac-key (hmac-key consumer-secret token-secret)) (signature (hmac-sha1 signature-base-string hmac-key)) (encoded-signature (encode-signature signature nil))) (unless (equal encoded-signature supplied-signature) (format t "calculated: ~S / supplied: ~S~%" encoded-signature supplied-signature) (raise-error 'unauthorized "Invalid signature"))) t)) ;;; nonce and timestamp checking (defun check-nonce-and-timestamp (consumer-token) ;; TODO: nonce checking (unless (parameter "oauth_timestamp") (raise-error 'bad-request "Missing Timestamp")) (let ((timestamp (ignore-errors (parse-integer (parameter "oauth_timestamp")))) (nonce (parameter "oauth_nonce"))) (unless timestamp (raise-error 'unauthorized "Malformed Timestamp")) (unless nonce (raise-error 'bad-request "Missing nonce")) (unless (>= timestamp (consumer-token-last-timestamp consumer-token)) (raise-error 'unauthorized "Invalid timestamp")) t)) ;;; version checking (defun check-version () (let ((version (parameter "oauth_version"))) (unless (member version '("1.0" nil) :test #'equalp) (raise-error 'bad-request "Not prepared to handle OAuth version other than 1.0" version)) t)) ;;; verification code checking (defun check-verification-code () (unless (equal (parameter "oauth_verifier") (request-token-verification-code (get-supplied-request-token))) (raise-error 'unauthorized "Invalid verification code")) t) ;;; misc (defun get-supplied-consumer-token () (let ((consumer-key (parameter "oauth_consumer_key"))) (unless consumer-key (raise-error 'bad-request "Consumer key not supplied")) (let ((consumer-token (get-consumer-token consumer-key))) (unless consumer-token (raise-error 'unauthorized "Can't identify Consumer")) consumer-token))) (defun get-supplied-callback-uri (&key allow-oob-callback-p (allow-none (eq *protocol-version* :1.0))) (let ((callback (parameter "oauth_callback"))) (cond ((and (not allow-none) (not callback)) (raise-error 'bad-request "No callback supplied")) ((and (not allow-oob-callback-p) (equal callback "oob")) (raise-error 'bad-request "Not prepared for an OOB callback setup!")) (t callback)))) ;;; request token management (defvar *issued-request-tokens* (make-hash-table :test #'equalp)) (defmethod register-token ((token request-token)) ;; TODO: already registered? (setf (gethash (token-key token) *issued-request-tokens*) token)) (defmethod unregister-token ((token request-token)) (remhash (token-key token) *issued-request-tokens*)) (defun invalidate-request-token (request-token) (remhash (token-key request-token) *issued-request-tokens*)) (defun make-response (alist) "[5.3]" (alist->query-string (mapcar (lambda (cons) (cons (url-encode (car cons)) (url-encode (cdr cons)))) alist) :include-leading-ampersand nil)) (defun request-token-response (request-token &rest additional-parameters) "Respond to a valid request token request. [6.1.2]" (assert (notany #'oauth-parameter-p additional-parameters)) (make-response (append `(("oauth_token" . ,(token-key request-token)) ("oauth_token_secret" . ,(token-secret request-token)) ("oauth_callback_confirmed" . "true")) additional-parameters))) (defun validate-request-token-request (&key (request-token-ctor #'make-request-token) allow-oob-callback-p) "Check whether REQUEST is a valid request token request. Returns the supplied Consumer callback (a PURI:URI) or NIL if the callback is supposed to be transferred oob. [6.1.1]" (protocol-assert (>= (length (normalized-parameters)) (case *protocol-version* callbacks were introduced in 1.0a (1.0 4) (t 6 5)))) (check-version) (check-signature) (let ((consumer-token (get-supplied-consumer-token))) (check-nonce-and-timestamp consumer-token) (let* ((callback-uri (get-supplied-callback-uri :allow-oob-callback-p allow-oob-callback-p :allow-none t)) (request-token (funcall request-token-ctor :consumer consumer-token :callback-uri (when callback-uri (puri:parse-uri callback-uri)) :user-data (remove-oauth-parameters (normalized-parameters))))) (register-token request-token) request-token))) (defun get-supplied-request-token (&key check-verification-code-p) "Utility function that extracts the Consumer-supplied request token from a list of normalized parameters. Guards against non-existing and unknown tokens. Returns the request token on success." ;; TODO: check whether the supplied token matches the Consumer key (let ((request-token-key (parameter "oauth_token"))) check if the Consumer supplied a request token (unless request-token-key (raise-error 'bad-request "Missing request token")) ;; check if the supplied request token is known to us (let ((request-token (gethash request-token-key *issued-request-tokens*))) (unless request-token (raise-error 'unauthorized "Invalid request token")) (when check-verification-code-p (check-verification-code)) ;; everything's looking good request-token))) ;;; access token management (defvar *issued-access-tokens* (make-hash-table :test #'equalp)) (defmethod register-token ((token access-token)) (setf (gethash (token-key token) *issued-access-tokens*) token)) (defmethod unregister-token ((token access-token)) (remhash (token-key token) *issued-access-tokens*)) (defun validate-access-token-request (&key (access-token-ctor #'make-access-token)) ;; no user-supplied parameters allowed here, and the spec forbids duplicate oauth args per section 5 . ;; moreover we don't count the oauth_signature parameter as it isn't ;; part of the normalized parameter list. (protocol-assert (multiple-value-call #'between (length (normalized-parameters)) (case *protocol-version* (1.0 (values 5 6)) (t 6 (values 6 7))))) (format t "foo~%") (protocol-assert (null (remove-oauth-parameters (normalized-parameters)))) (format t "bar~%") (check-version) (check-signature) (let* ((request-token (get-supplied-request-token :check-verification-code-p (not (eq *protocol-version* :1.0)))) (consumer (token-consumer request-token))) (check-nonce-and-timestamp consumer) (let ((access-token (funcall access-token-ctor :consumer consumer))) (register-token access-token) (prog1 access-token (invalidate-request-token request-token))))) (defun access-token-response (access-token &rest additional-parameters) TODO not supported yet (url-encode (alist->query-string `(("oauth_token" . ,(token-key access-token)) ("oauth_token_secret" . ,(token-secret access-token)))))) protected resource access management [ 7 ] (defun get-supplied-access-token () "Utility function that extracts the Consumer-supplied request token from a list of normalized parameters. Guards against non-existing and unknown tokens. Returns the request token on success." ;; TODO: check whether the supplied token matches the Consumer key (let ((access-token-key (parameter "oauth_token"))) (unless access-token-key (raise-error 'bad-request "Missing access token")) ;; check if the supplied access token is known to us (let ((access-token (gethash access-token-key *issued-access-tokens*))) (unless access-token (raise-error 'unauthorized "Invalid access token")) access-token))) (defun validate-access-token () (protocol-assert (>= (length (normalized-parameters)) 6)) (check-version) (check-signature) (let ((consumer-token (get-supplied-consumer-token))) (check-nonce-and-timestamp consumer-token) (let ((access-token (get-supplied-access-token))) (unless (eq consumer-token (token-consumer access-token)) (raise-error 'unauthorized "Access token ~S wasn't issued for Consumer ~S" access-token consumer-token)) t)))
null
https://raw.githubusercontent.com/skypher/cl-oauth/a7a463c8c2e4726ab0853d5b6623349b6428cb89/src/core/service-provider.lisp
lisp
Service provider infrastructure TODO: need to store application-specific data somewhere. signature checking TODO: do not bluntly ignore all errors. Factor out into GET-TOKEN now calculate the signature and check for match nonce and timestamp checking TODO: nonce checking version checking verification code checking misc request token management TODO: already registered? TODO: check whether the supplied token matches the Consumer key check if the supplied request token is known to us everything's looking good access token management no user-supplied parameters allowed here, and the moreover we don't count the oauth_signature parameter as it isn't part of the normalized parameter list. TODO: check whether the supplied token matches the Consumer key check if the supplied access token is known to us
(in-package :oauth) (defvar *protocol-version* :1.0) (defun finalize-callback-uri (request-token) "Prepares the callback URI of REQUEST-TOKEN for redirection." (let ((uri (request-token-callback-uri request-token))) (setf (puri:uri-query uri) (concatenate 'string (or (puri:uri-query uri) "") (if (puri:uri-query uri) "&" "") "oauth_token=" (url-encode (token-key request-token)) "&oauth_verifier=" (url-encode (request-token-verification-code request-token)))) uri)) Consumer management (defvar *registered-consumers* (make-hash-table :test #'equalp)) (defmethod register-token ((token consumer-token)) (setf (gethash (token-key token) *registered-consumers*) token) token) (defmethod unregister-token ((token consumer-token)) (remhash (token-key token) *registered-consumers*)) (defun get-consumer-token (key) (gethash key *registered-consumers*)) (defmacro ignore-oauth-errors (&body body) `(handler-case (progn ,@body) (http-error (condition) (values nil condition)))) (defun check-signature () (unless (equalp (parameter "oauth_signature_method") "HMAC-SHA1") (raise-error 'bad-request "Signature method not passed or different from HMAC-SHA1")) (let* ((supplied-signature (gethash (request) *signature-cache*)) (consumer-secret (ignore-errors (token-secret (get-consumer-token (parameter "oauth_consumer_key"))))) (token-secret (ignore-errors (token-secret (or (ignore-oauth-errors (get-supplied-request-token)) (ignore-oauth-errors (get-supplied-access-token))))))) (unless supplied-signature (raise-error 'bad-request "This request is not signed")) (unless consumer-secret (raise-error 'unauthorized "Invalid consumer")) (let* ((signature-base-string (signature-base-string)) (hmac-key (hmac-key consumer-secret token-secret)) (signature (hmac-sha1 signature-base-string hmac-key)) (encoded-signature (encode-signature signature nil))) (unless (equal encoded-signature supplied-signature) (format t "calculated: ~S / supplied: ~S~%" encoded-signature supplied-signature) (raise-error 'unauthorized "Invalid signature"))) t)) (defun check-nonce-and-timestamp (consumer-token) (unless (parameter "oauth_timestamp") (raise-error 'bad-request "Missing Timestamp")) (let ((timestamp (ignore-errors (parse-integer (parameter "oauth_timestamp")))) (nonce (parameter "oauth_nonce"))) (unless timestamp (raise-error 'unauthorized "Malformed Timestamp")) (unless nonce (raise-error 'bad-request "Missing nonce")) (unless (>= timestamp (consumer-token-last-timestamp consumer-token)) (raise-error 'unauthorized "Invalid timestamp")) t)) (defun check-version () (let ((version (parameter "oauth_version"))) (unless (member version '("1.0" nil) :test #'equalp) (raise-error 'bad-request "Not prepared to handle OAuth version other than 1.0" version)) t)) (defun check-verification-code () (unless (equal (parameter "oauth_verifier") (request-token-verification-code (get-supplied-request-token))) (raise-error 'unauthorized "Invalid verification code")) t) (defun get-supplied-consumer-token () (let ((consumer-key (parameter "oauth_consumer_key"))) (unless consumer-key (raise-error 'bad-request "Consumer key not supplied")) (let ((consumer-token (get-consumer-token consumer-key))) (unless consumer-token (raise-error 'unauthorized "Can't identify Consumer")) consumer-token))) (defun get-supplied-callback-uri (&key allow-oob-callback-p (allow-none (eq *protocol-version* :1.0))) (let ((callback (parameter "oauth_callback"))) (cond ((and (not allow-none) (not callback)) (raise-error 'bad-request "No callback supplied")) ((and (not allow-oob-callback-p) (equal callback "oob")) (raise-error 'bad-request "Not prepared for an OOB callback setup!")) (t callback)))) (defvar *issued-request-tokens* (make-hash-table :test #'equalp)) (defmethod register-token ((token request-token)) (setf (gethash (token-key token) *issued-request-tokens*) token)) (defmethod unregister-token ((token request-token)) (remhash (token-key token) *issued-request-tokens*)) (defun invalidate-request-token (request-token) (remhash (token-key request-token) *issued-request-tokens*)) (defun make-response (alist) "[5.3]" (alist->query-string (mapcar (lambda (cons) (cons (url-encode (car cons)) (url-encode (cdr cons)))) alist) :include-leading-ampersand nil)) (defun request-token-response (request-token &rest additional-parameters) "Respond to a valid request token request. [6.1.2]" (assert (notany #'oauth-parameter-p additional-parameters)) (make-response (append `(("oauth_token" . ,(token-key request-token)) ("oauth_token_secret" . ,(token-secret request-token)) ("oauth_callback_confirmed" . "true")) additional-parameters))) (defun validate-request-token-request (&key (request-token-ctor #'make-request-token) allow-oob-callback-p) "Check whether REQUEST is a valid request token request. Returns the supplied Consumer callback (a PURI:URI) or NIL if the callback is supposed to be transferred oob. [6.1.1]" (protocol-assert (>= (length (normalized-parameters)) (case *protocol-version* callbacks were introduced in 1.0a (1.0 4) (t 6 5)))) (check-version) (check-signature) (let ((consumer-token (get-supplied-consumer-token))) (check-nonce-and-timestamp consumer-token) (let* ((callback-uri (get-supplied-callback-uri :allow-oob-callback-p allow-oob-callback-p :allow-none t)) (request-token (funcall request-token-ctor :consumer consumer-token :callback-uri (when callback-uri (puri:parse-uri callback-uri)) :user-data (remove-oauth-parameters (normalized-parameters))))) (register-token request-token) request-token))) (defun get-supplied-request-token (&key check-verification-code-p) "Utility function that extracts the Consumer-supplied request token from a list of normalized parameters. Guards against non-existing and unknown tokens. Returns the request token on success." (let ((request-token-key (parameter "oauth_token"))) check if the Consumer supplied a request token (unless request-token-key (raise-error 'bad-request "Missing request token")) (let ((request-token (gethash request-token-key *issued-request-tokens*))) (unless request-token (raise-error 'unauthorized "Invalid request token")) (when check-verification-code-p (check-verification-code)) request-token))) (defvar *issued-access-tokens* (make-hash-table :test #'equalp)) (defmethod register-token ((token access-token)) (setf (gethash (token-key token) *issued-access-tokens*) token)) (defmethod unregister-token ((token access-token)) (remhash (token-key token) *issued-access-tokens*)) (defun validate-access-token-request (&key (access-token-ctor #'make-access-token)) spec forbids duplicate oauth args per section 5 . (protocol-assert (multiple-value-call #'between (length (normalized-parameters)) (case *protocol-version* (1.0 (values 5 6)) (t 6 (values 6 7))))) (format t "foo~%") (protocol-assert (null (remove-oauth-parameters (normalized-parameters)))) (format t "bar~%") (check-version) (check-signature) (let* ((request-token (get-supplied-request-token :check-verification-code-p (not (eq *protocol-version* :1.0)))) (consumer (token-consumer request-token))) (check-nonce-and-timestamp consumer) (let ((access-token (funcall access-token-ctor :consumer consumer))) (register-token access-token) (prog1 access-token (invalidate-request-token request-token))))) (defun access-token-response (access-token &rest additional-parameters) TODO not supported yet (url-encode (alist->query-string `(("oauth_token" . ,(token-key access-token)) ("oauth_token_secret" . ,(token-secret access-token)))))) protected resource access management [ 7 ] (defun get-supplied-access-token () "Utility function that extracts the Consumer-supplied request token from a list of normalized parameters. Guards against non-existing and unknown tokens. Returns the request token on success." (let ((access-token-key (parameter "oauth_token"))) (unless access-token-key (raise-error 'bad-request "Missing access token")) (let ((access-token (gethash access-token-key *issued-access-tokens*))) (unless access-token (raise-error 'unauthorized "Invalid access token")) access-token))) (defun validate-access-token () (protocol-assert (>= (length (normalized-parameters)) 6)) (check-version) (check-signature) (let ((consumer-token (get-supplied-consumer-token))) (check-nonce-and-timestamp consumer-token) (let ((access-token (get-supplied-access-token))) (unless (eq consumer-token (token-consumer access-token)) (raise-error 'unauthorized "Access token ~S wasn't issued for Consumer ~S" access-token consumer-token)) t)))
a802a0e524cd35798caefce35299a48f4987e66a5bf9fb005bb6439d3dc18479
hadolint/language-docker
From.hs
module Language.Docker.Parser.From ( parseFrom, ) where import qualified Data.Text as T import Language.Docker.Parser.Prelude import Language.Docker.Syntax parseRegistry :: (?esc :: Char) => Parser Registry parseRegistry = do domain <- someUnless "a domain name" (== '.') void $ char '.' tld <- someUnless "a TLD" (== '/') void $ char '/' return $ Registry (domain <> "." <> tld) parsePlatform :: (?esc :: Char) => Parser Platform parsePlatform = do void $ string "--platform=" p <- someUnless "the platform for the FROM image" (== ' ') requiredWhitespace return p parseBaseImage :: (?esc :: Char) => (Text -> Parser (Maybe Tag)) -> Parser BaseImage parseBaseImage tagParser = do maybePlatform <- (Just <$> try parsePlatform) <|> return Nothing notFollowedBy (string "--") regName <- (Just <$> try parseRegistry) <|> return Nothing name <- someUnless "the image name with a tag" (\c -> c == '@' || c == ':') maybeTag <- tagParser name <|> return Nothing maybeDigest <- (Just <$> try parseDigest) <|> return Nothing maybeAlias <- (Just <$> try (requiredWhitespace *> imageAlias)) <|> return Nothing return $ BaseImage (Image regName name) maybeTag maybeDigest maybeAlias maybePlatform taggedImage :: (?esc :: Char) => Parser BaseImage taggedImage = parseBaseImage tagParser where tagParser _ = do void $ char ':' t <- someUnless "the image tag" (\c -> c == '@' || c == ':') return (Just . Tag $ t) parseDigest :: (?esc :: Char) => Parser Digest parseDigest = do void $ char '@' d <- someUnless "the image digest" (== '@') return $ Digest d untaggedImage :: (?esc :: Char) => Parser BaseImage untaggedImage = parseBaseImage notInvalidTag where notInvalidTag :: Text -> Parser (Maybe Tag) notInvalidTag name = do try (notFollowedBy $ string ":") <?> "no ':' or a valid image tag string (example: " ++ T.unpack name ++ ":valid-tag)" return Nothing imageAlias :: (?esc :: Char) => Parser ImageAlias imageAlias = do void (try (reserved "AS") <?> "'AS' followed by the image alias") aka <- someUnless "the image alias" (== '\n') return $ ImageAlias aka baseImage :: (?esc :: Char) => Parser BaseImage baseImage = try taggedImage <|> untaggedImage parseFrom :: (?esc :: Char) => Parser (Instruction Text) parseFrom = do reserved "FROM" From <$> baseImage
null
https://raw.githubusercontent.com/hadolint/language-docker/7e4bceea394c83ee1fec90263db86fd0e312c48a/src/Language/Docker/Parser/From.hs
haskell
module Language.Docker.Parser.From ( parseFrom, ) where import qualified Data.Text as T import Language.Docker.Parser.Prelude import Language.Docker.Syntax parseRegistry :: (?esc :: Char) => Parser Registry parseRegistry = do domain <- someUnless "a domain name" (== '.') void $ char '.' tld <- someUnless "a TLD" (== '/') void $ char '/' return $ Registry (domain <> "." <> tld) parsePlatform :: (?esc :: Char) => Parser Platform parsePlatform = do void $ string "--platform=" p <- someUnless "the platform for the FROM image" (== ' ') requiredWhitespace return p parseBaseImage :: (?esc :: Char) => (Text -> Parser (Maybe Tag)) -> Parser BaseImage parseBaseImage tagParser = do maybePlatform <- (Just <$> try parsePlatform) <|> return Nothing notFollowedBy (string "--") regName <- (Just <$> try parseRegistry) <|> return Nothing name <- someUnless "the image name with a tag" (\c -> c == '@' || c == ':') maybeTag <- tagParser name <|> return Nothing maybeDigest <- (Just <$> try parseDigest) <|> return Nothing maybeAlias <- (Just <$> try (requiredWhitespace *> imageAlias)) <|> return Nothing return $ BaseImage (Image regName name) maybeTag maybeDigest maybeAlias maybePlatform taggedImage :: (?esc :: Char) => Parser BaseImage taggedImage = parseBaseImage tagParser where tagParser _ = do void $ char ':' t <- someUnless "the image tag" (\c -> c == '@' || c == ':') return (Just . Tag $ t) parseDigest :: (?esc :: Char) => Parser Digest parseDigest = do void $ char '@' d <- someUnless "the image digest" (== '@') return $ Digest d untaggedImage :: (?esc :: Char) => Parser BaseImage untaggedImage = parseBaseImage notInvalidTag where notInvalidTag :: Text -> Parser (Maybe Tag) notInvalidTag name = do try (notFollowedBy $ string ":") <?> "no ':' or a valid image tag string (example: " ++ T.unpack name ++ ":valid-tag)" return Nothing imageAlias :: (?esc :: Char) => Parser ImageAlias imageAlias = do void (try (reserved "AS") <?> "'AS' followed by the image alias") aka <- someUnless "the image alias" (== '\n') return $ ImageAlias aka baseImage :: (?esc :: Char) => Parser BaseImage baseImage = try taggedImage <|> untaggedImage parseFrom :: (?esc :: Char) => Parser (Instruction Text) parseFrom = do reserved "FROM" From <$> baseImage
d0eeb0296444f90d9257ff01424968c08d00c4bd0b7c6c1b33ef96f6208a49b2
mumuki/mulang
LogicSpec.hs
module LogicSpec (spec) where import Test.Hspec import Language.Mulang import Language.Mulang.Parsers.Prolog spec :: Spec spec = do describe "inspector" $ do describe "declaresFact" $ do it "is True when fact is declared" $ do declaresFact (named "foo") (pl "foo(a).") `shouldBe` True it "is False when fact is not declared" $ do declaresFact (named "foo") (pl "foo(a) :- bar(X).") `shouldBe` False declaresFact (named "baz") (pl "foo(a).") `shouldBe` False describe "declaresRule" $ do it "is True when rule is declared" $ do declaresRule (named "foo") (pl "foo(X) :- bar(X).") `shouldBe` True it "is False when rule is not declared" $ do declaresRule (named "baz") (pl "foo(X) :- bar(X).") `shouldBe` False describe "uses" $ do it "is True when predicate is used, unscoped" $ do uses (named "bar") (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when predicate is used" $ do (scoped "foo" (uses (named "bar"))) (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when predicate is used in not, unscoped" $ do uses (named "bar") (pl "foo(X) :- not(bar(X)).") `shouldBe` True it "is True when predicate is used in forall, unscoped" $ do uses (named "bar") (pl "foo(X) :- forall(bar(X), baz(X)).") `shouldBe` True uses (named "baz") (pl "foo(X) :- forall(bar(X), baz(X)).") `shouldBe` True it "is False when predicate is not used" $ do (scoped "foo" (uses (named "bar")) ) (pl "foo(X) :- baz(X).") `shouldBe` False describe "usesForall" $ do it "is True when used, unscuped" $ do usesForall (pl "foo(X) :- forall(f(x), y(X)).") `shouldBe` True it "is True when used" $ do (scoped "foo" usesForall) (pl "foo(X) :- forall(bar(X), g(X)).") `shouldBe` True it "is False when not used" $ do usesForall (pl "foo(X) :- bar(X), baz(X).") `shouldBe` False describe "usesNot" $ do it "is True when used, unscoped" $ do usesNot (pl "foo(X) :- not(f(x)).") `shouldBe` True it "is True when used" $ do (scoped "foo" usesNot ) (pl "foo(X) :- not(g(X)).") `shouldBe` True it "is False when not used" $ do usesNot (pl "foo(X) :- bar(X), baz(X).") `shouldBe` False describe "usesAnonymousVariable" $ do it "is True when _ is used in rule" $ do usesAnonymousVariable (pl "foo(_) :- bar(X).") `shouldBe` True it "is True when _ is used in fact" $ do usesAnonymousVariable (pl "foo(_).") `shouldBe` True it "is False when _ is not used" $ do usesAnonymousVariable (pl "foo(a).") `shouldBe` False describe "declaresPredicate" $ do it "is True when rule is declared" $ do declaresPredicate (named "foo") (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when fact is declared" $ do declaresPredicate (named "foo") (pl "foo(tom).") `shouldBe` True it "is False when predicate is not declared" $ do declaresPredicate (named "foo") (pl "bar(tom).") `shouldBe` False describe "declaresComputationWithArity" $ do it "is True when fact is declared with given arity" $ do declaresComputationWithArity 1 (named "foo") (pl "foo(tom).") `shouldBe` True it "is True when rule is declared with given arity" $ do declaresComputationWithArity 1 (named "foo") (pl "foo(tom) :- bar(5), baz(6).") `shouldBe` True it "is False when fact is declared with another arity" $ do declaresComputationWithArity 2 (named "foo") (pl "foo(tom).") `shouldBe` False describe "usesUnificationOperator" $ do it "is True when equal" $ do usesUnificationOperator (pl "baz(X):- X = 4.") `shouldBe` True it "is False when no equal" $ do usesUnificationOperator (pl "baz(X):- baz(X).") `shouldBe` False describe "usesCut" $ do it "is True when used" $ do usesCut (pl "baz(X):- !.") `shouldBe` True it "is False when not used" $ do usesCut (pl "baz(X):- baz(X).") `shouldBe` False describe "usesFail" $ do it "is True when used" $ do usesFail (pl "baz(X):- fail.") `shouldBe` True it "is False when not used" $ do usesFail (pl "baz(X):- baz(X).") `shouldBe` False describe "hasRedundantReduction" $ do it "is False when there is no reduction operator" $ do hasRedundantReduction (pl "baz(X):- X > 5.") `shouldBe` False it "is False when there is a reduction of applications" $ do hasRedundantReduction (pl "baz(X):- X is 5 + Y.") `shouldBe` False it "is False when there is a reduction of named function applications" $ do hasRedundantReduction (pl "baz(X):- X is abs(Y).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is mod(Y, 2).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is div(Y, 2).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is rem(Y, 2).") `shouldBe` False it "is True when there is a redundant reduction of parameters" $ do hasRedundantReduction (pl "baz(X, Y):- X is Y.") `shouldBe` True it "is True when there is a redundant reduction of literals" $ do hasRedundantReduction (pl "baz(X, Y):- X is 5.") `shouldBe` True it "is True when there is a redundant reduction of functors" $ do hasRedundantReduction (pl "baz(X, Y):- moo(X, Z), Z is aFunctor(5).") `shouldBe` True
null
https://raw.githubusercontent.com/mumuki/mulang/92684f687566b2adafb331eae5b5916e2d90709e/spec/LogicSpec.hs
haskell
module LogicSpec (spec) where import Test.Hspec import Language.Mulang import Language.Mulang.Parsers.Prolog spec :: Spec spec = do describe "inspector" $ do describe "declaresFact" $ do it "is True when fact is declared" $ do declaresFact (named "foo") (pl "foo(a).") `shouldBe` True it "is False when fact is not declared" $ do declaresFact (named "foo") (pl "foo(a) :- bar(X).") `shouldBe` False declaresFact (named "baz") (pl "foo(a).") `shouldBe` False describe "declaresRule" $ do it "is True when rule is declared" $ do declaresRule (named "foo") (pl "foo(X) :- bar(X).") `shouldBe` True it "is False when rule is not declared" $ do declaresRule (named "baz") (pl "foo(X) :- bar(X).") `shouldBe` False describe "uses" $ do it "is True when predicate is used, unscoped" $ do uses (named "bar") (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when predicate is used" $ do (scoped "foo" (uses (named "bar"))) (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when predicate is used in not, unscoped" $ do uses (named "bar") (pl "foo(X) :- not(bar(X)).") `shouldBe` True it "is True when predicate is used in forall, unscoped" $ do uses (named "bar") (pl "foo(X) :- forall(bar(X), baz(X)).") `shouldBe` True uses (named "baz") (pl "foo(X) :- forall(bar(X), baz(X)).") `shouldBe` True it "is False when predicate is not used" $ do (scoped "foo" (uses (named "bar")) ) (pl "foo(X) :- baz(X).") `shouldBe` False describe "usesForall" $ do it "is True when used, unscuped" $ do usesForall (pl "foo(X) :- forall(f(x), y(X)).") `shouldBe` True it "is True when used" $ do (scoped "foo" usesForall) (pl "foo(X) :- forall(bar(X), g(X)).") `shouldBe` True it "is False when not used" $ do usesForall (pl "foo(X) :- bar(X), baz(X).") `shouldBe` False describe "usesNot" $ do it "is True when used, unscoped" $ do usesNot (pl "foo(X) :- not(f(x)).") `shouldBe` True it "is True when used" $ do (scoped "foo" usesNot ) (pl "foo(X) :- not(g(X)).") `shouldBe` True it "is False when not used" $ do usesNot (pl "foo(X) :- bar(X), baz(X).") `shouldBe` False describe "usesAnonymousVariable" $ do it "is True when _ is used in rule" $ do usesAnonymousVariable (pl "foo(_) :- bar(X).") `shouldBe` True it "is True when _ is used in fact" $ do usesAnonymousVariable (pl "foo(_).") `shouldBe` True it "is False when _ is not used" $ do usesAnonymousVariable (pl "foo(a).") `shouldBe` False describe "declaresPredicate" $ do it "is True when rule is declared" $ do declaresPredicate (named "foo") (pl "foo(X) :- bar(X).") `shouldBe` True it "is True when fact is declared" $ do declaresPredicate (named "foo") (pl "foo(tom).") `shouldBe` True it "is False when predicate is not declared" $ do declaresPredicate (named "foo") (pl "bar(tom).") `shouldBe` False describe "declaresComputationWithArity" $ do it "is True when fact is declared with given arity" $ do declaresComputationWithArity 1 (named "foo") (pl "foo(tom).") `shouldBe` True it "is True when rule is declared with given arity" $ do declaresComputationWithArity 1 (named "foo") (pl "foo(tom) :- bar(5), baz(6).") `shouldBe` True it "is False when fact is declared with another arity" $ do declaresComputationWithArity 2 (named "foo") (pl "foo(tom).") `shouldBe` False describe "usesUnificationOperator" $ do it "is True when equal" $ do usesUnificationOperator (pl "baz(X):- X = 4.") `shouldBe` True it "is False when no equal" $ do usesUnificationOperator (pl "baz(X):- baz(X).") `shouldBe` False describe "usesCut" $ do it "is True when used" $ do usesCut (pl "baz(X):- !.") `shouldBe` True it "is False when not used" $ do usesCut (pl "baz(X):- baz(X).") `shouldBe` False describe "usesFail" $ do it "is True when used" $ do usesFail (pl "baz(X):- fail.") `shouldBe` True it "is False when not used" $ do usesFail (pl "baz(X):- baz(X).") `shouldBe` False describe "hasRedundantReduction" $ do it "is False when there is no reduction operator" $ do hasRedundantReduction (pl "baz(X):- X > 5.") `shouldBe` False it "is False when there is a reduction of applications" $ do hasRedundantReduction (pl "baz(X):- X is 5 + Y.") `shouldBe` False it "is False when there is a reduction of named function applications" $ do hasRedundantReduction (pl "baz(X):- X is abs(Y).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is mod(Y, 2).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is div(Y, 2).") `shouldBe` False hasRedundantReduction (pl "baz(X):- X is rem(Y, 2).") `shouldBe` False it "is True when there is a redundant reduction of parameters" $ do hasRedundantReduction (pl "baz(X, Y):- X is Y.") `shouldBe` True it "is True when there is a redundant reduction of literals" $ do hasRedundantReduction (pl "baz(X, Y):- X is 5.") `shouldBe` True it "is True when there is a redundant reduction of functors" $ do hasRedundantReduction (pl "baz(X, Y):- moo(X, Z), Z is aFunctor(5).") `shouldBe` True
d8740c7a581df7f8474a93b5e54ac14f89b4627e90d75f3cc6270b46a2d6f2b5
abtv/tech-radar
database.clj
(ns tech-radar.utils.database (:require [clj-time.coerce :as tc])) (defn to-underscores [s] (.replace s \- \_)) (defn to-dashes [s] (.replace s \_ \-)) (defn map->db-fn [{:keys [keyword-columns date-columns] :or {keyword-columns #{} date-columns #{}}}] (fn [map*] (if (empty? map*) map* (->> (map (fn [[k v]] (cond (keyword-columns k) [k (when v (name v))] (date-columns k) [k (tc/to-timestamp v)] true [k v])) map*) (into {})))))
null
https://raw.githubusercontent.com/abtv/tech-radar/167c1c66ff2cf7140fe1de247d67a7134b0b1748/src/clj/tech_radar/utils/database.clj
clojure
(ns tech-radar.utils.database (:require [clj-time.coerce :as tc])) (defn to-underscores [s] (.replace s \- \_)) (defn to-dashes [s] (.replace s \_ \-)) (defn map->db-fn [{:keys [keyword-columns date-columns] :or {keyword-columns #{} date-columns #{}}}] (fn [map*] (if (empty? map*) map* (->> (map (fn [[k v]] (cond (keyword-columns k) [k (when v (name v))] (date-columns k) [k (tc/to-timestamp v)] true [k v])) map*) (into {})))))
8c753955cdbe49ae337d69f007fc357006de25c7808cb880e577ac4b7f9ed807
purescript/purescript
Types.hs
| Data types and functions for representing a simplified form of PureScript -- code, intended for use in e.g. HTML documentation. module Language.PureScript.Docs.RenderedCode.Types ( RenderedCodeElement(..) , ContainingModule(..) , asContainingModule , maybeToContainingModule , fromQualified , Namespace(..) , Link(..) , FixityAlias , RenderedCode , outputWith , sp , syntax , keyword , keywordForall , keywordData , keywordType , keywordClass , keywordWhere , keywordFixity , keywordAs , ident , dataCtor , typeCtor , typeOp , typeVar , roleAnn , alias , aliasName ) where import Prelude import GHC.Generics (Generic) import Control.DeepSeq (NFData) import Control.Monad.Error.Class (MonadError(..)) import Data.Aeson.BetterErrors (Parse, nth, withText, withValue, toAesonParser, perhaps, asText) import qualified Data.Aeson as A import Data.Text (Text) import qualified Data.Text as T import qualified Data.ByteString.Lazy as BS import qualified Data.Text.Encoding as TE import Language.PureScript.Names import Language.PureScript.AST (Associativity(..)) | Given a list of actions , attempt them all , returning the first success . If all the actions fail , ' tryAll ' returns the first argument . tryAll :: MonadError e m => m a -> [m a] -> m a tryAll = foldr $ \x y -> catchError x (const y) firstEq :: Text -> Parse Text a -> Parse Text a firstEq str p = nth 0 (withText (eq str)) *> p where eq s s' = if s == s' then Right () else Left "" -- | -- Try the given parsers in sequence. If all fail, fail with the given message, -- and include the JSON in the error. -- tryParse :: Text -> [Parse Text a] -> Parse Text a tryParse msg = tryAll (withValue (Left . (fullMsg <>) . showJSON)) where fullMsg = "Invalid " <> msg <> ": " showJSON :: A.Value -> Text showJSON = TE.decodeUtf8 . BS.toStrict . A.encode -- | This type is isomorphic to ' Maybe ' ' ModuleName ' . It makes code a bit -- easier to read, as the meaning is more explicit. -- data ContainingModule = ThisModule | OtherModule ModuleName deriving (Show, Eq, Ord) instance A.ToJSON ContainingModule where toJSON = A.toJSON . go where go = \case ThisModule -> ["ThisModule"] OtherModule mn -> ["OtherModule", runModuleName mn] instance A.FromJSON ContainingModule where parseJSON = toAesonParser id asContainingModule asContainingModule :: Parse Text ContainingModule asContainingModule = tryParse "containing module" $ current ++ backwardsCompat where current = [ firstEq "ThisModule" (pure ThisModule) , firstEq "OtherModule" (OtherModule <$> nth 1 asModuleName) ] For JSON produced by compilers up to 0.10.5 . backwardsCompat = [ maybeToContainingModule <$> perhaps asModuleName ] asModuleName = moduleNameFromString <$> asText -- | Convert a ' Maybe ' ' ModuleName ' to a ' ContainingModule ' , using the obvious -- isomorphism. -- maybeToContainingModule :: Maybe ModuleName -> ContainingModule maybeToContainingModule Nothing = ThisModule maybeToContainingModule (Just mn) = OtherModule mn fromQualified :: Qualified a -> (ContainingModule, a) fromQualified (Qualified (ByModuleName mn) x) = (OtherModule mn, x) fromQualified (Qualified _ x) = (ThisModule, x) data Link = NoLink | Link ContainingModule deriving (Show, Eq, Ord) instance A.ToJSON Link where toJSON = \case NoLink -> A.toJSON ["NoLink" :: Text] Link mn -> A.toJSON ["Link", A.toJSON mn] asLink :: Parse Text Link asLink = tryParse "link" [ firstEq "NoLink" (pure NoLink) , firstEq "Link" (Link <$> nth 1 asContainingModule) ] instance A.FromJSON Link where parseJSON = toAesonParser id asLink data Namespace = ValueLevel | TypeLevel deriving (Show, Eq, Ord, Generic) instance NFData Namespace instance A.ToJSON Namespace where toJSON = A.toJSON . show asNamespace :: Parse Text Namespace asNamespace = tryParse "namespace" [ withText $ \case "ValueLevel" -> Right ValueLevel "TypeLevel" -> Right TypeLevel _ -> Left "" ] instance A.FromJSON Namespace where parseJSON = toAesonParser id asNamespace -- | -- A single element in a rendered code fragment. The intention is to support -- multiple output formats. For example, plain text, or highlighted HTML. -- data RenderedCodeElement = Syntax Text | Keyword Text | Space -- | Any symbol which you might or might not want to link to, in any -- namespace (value, type, or kind). Note that this is not related to the -- kind called Symbol for type-level strings. | Symbol Namespace Text Link | Role Text deriving (Show, Eq, Ord) instance A.ToJSON RenderedCodeElement where toJSON (Syntax str) = A.toJSON ["syntax", str] toJSON (Keyword str) = A.toJSON ["keyword", str] toJSON Space = A.toJSON ["space" :: Text] toJSON (Symbol ns str link) = A.toJSON ["symbol", A.toJSON ns, A.toJSON str, A.toJSON link] toJSON (Role role) = A.toJSON ["role", role] -- | A type representing a highly simplified version of PureScript code , intended -- for use in output formats like plain text or HTML. -- newtype RenderedCode = RC { unRC :: [RenderedCodeElement] } deriving (Show, Eq, Ord, Semigroup, Monoid) instance A.ToJSON RenderedCode where toJSON (RC elems) = A.toJSON elems -- | This function allows conversion of a ' RenderedCode ' value into a value of some other type ( for example , plain text , or HTML ) . The first argument -- is a function specifying how each individual 'RenderedCodeElement' should be -- rendered. -- outputWith :: Monoid a => (RenderedCodeElement -> a) -> RenderedCode -> a outputWith f = foldMap f . unRC -- | A ' RenderedCode ' fragment representing a space . -- sp :: RenderedCode sp = RC [Space] possible TODO : instead of this function , export RenderedCode values for -- each syntax element, eg syntaxArr (== syntax "->"), syntaxLBrace, syntaxRBrace , etc . syntax :: Text -> RenderedCode syntax x = RC [Syntax x] keyword :: Text -> RenderedCode keyword kw = RC [Keyword kw] keywordForall :: RenderedCode keywordForall = keyword "forall" keywordData :: RenderedCode keywordData = keyword "data" keywordType :: RenderedCode keywordType = keyword "type" keywordClass :: RenderedCode keywordClass = keyword "class" keywordWhere :: RenderedCode keywordWhere = keyword "where" keywordFixity :: Associativity -> RenderedCode keywordFixity Infixl = keyword "infixl" keywordFixity Infixr = keyword "infixr" keywordFixity Infix = keyword "infix" keywordAs :: RenderedCode keywordAs = keyword "as" ident :: Qualified Ident -> RenderedCode ident (fromQualified -> (mn, name)) = RC [Symbol ValueLevel (runIdent name) (Link mn)] dataCtor :: Qualified (ProperName 'ConstructorName) -> RenderedCode dataCtor (fromQualified -> (mn, name)) = RC [Symbol ValueLevel (runProperName name) (Link mn)] typeCtor :: Qualified (ProperName 'TypeName) -> RenderedCode typeCtor (fromQualified -> (mn, name)) = RC [Symbol TypeLevel (runProperName name) (Link mn)] typeOp :: Qualified (OpName 'TypeOpName) -> RenderedCode typeOp (fromQualified -> (mn, name)) = RC [Symbol TypeLevel (runOpName name) (Link mn)] typeVar :: Text -> RenderedCode typeVar x = RC [Symbol TypeLevel x NoLink] roleAnn :: Maybe Text -> RenderedCode roleAnn = RC . maybe [] renderRole where renderRole = \case "nominal" -> [Role "nominal"] "phantom" -> [Role "phantom"] _ -> [] type FixityAlias = Qualified (Either (ProperName 'TypeName) (Either Ident (ProperName 'ConstructorName))) alias :: FixityAlias -> RenderedCode alias for = prefix <> RC [Symbol ns name (Link mn)] where (ns, name, mn) = unpackFixityAlias for prefix = case ns of TypeLevel -> keywordType <> sp _ -> mempty aliasName :: FixityAlias -> Text -> RenderedCode aliasName for name' = let (ns, _, _) = unpackFixityAlias for unParen = T.tail . T.init name = unParen name' in case ns of ValueLevel -> ident (Qualified ByNullSourcePos (Ident name)) TypeLevel -> typeCtor (Qualified ByNullSourcePos (ProperName name)) -- | Converts a FixityAlias into a different representation which is more -- useful to other functions in this module. unpackFixityAlias :: FixityAlias -> (Namespace, Text, ContainingModule) unpackFixityAlias (fromQualified -> (mn, x)) = case x of -- We add some seemingly superfluous type signatures here just to be extra -- sure we are not mixing up our namespaces. Left (n :: ProperName 'TypeName) -> (TypeLevel, runProperName n, mn) Right (Left n) -> (ValueLevel, runIdent n, mn) Right (Right (n :: ProperName 'ConstructorName)) -> (ValueLevel, runProperName n, mn)
null
https://raw.githubusercontent.com/purescript/purescript/02bd6ae60bcd18cbfa892f268ef6359d84ed7c9b/src/Language/PureScript/Docs/RenderedCode/Types.hs
haskell
code, intended for use in e.g. HTML documentation. | Try the given parsers in sequence. If all fail, fail with the given message, and include the JSON in the error. | easier to read, as the meaning is more explicit. | isomorphism. | A single element in a rendered code fragment. The intention is to support multiple output formats. For example, plain text, or highlighted HTML. | Any symbol which you might or might not want to link to, in any namespace (value, type, or kind). Note that this is not related to the kind called Symbol for type-level strings. | for use in output formats like plain text or HTML. | is a function specifying how each individual 'RenderedCodeElement' should be rendered. | each syntax element, eg syntaxArr (== syntax "->"), syntaxLBrace, | Converts a FixityAlias into a different representation which is more useful to other functions in this module. We add some seemingly superfluous type signatures here just to be extra sure we are not mixing up our namespaces.
| Data types and functions for representing a simplified form of PureScript module Language.PureScript.Docs.RenderedCode.Types ( RenderedCodeElement(..) , ContainingModule(..) , asContainingModule , maybeToContainingModule , fromQualified , Namespace(..) , Link(..) , FixityAlias , RenderedCode , outputWith , sp , syntax , keyword , keywordForall , keywordData , keywordType , keywordClass , keywordWhere , keywordFixity , keywordAs , ident , dataCtor , typeCtor , typeOp , typeVar , roleAnn , alias , aliasName ) where import Prelude import GHC.Generics (Generic) import Control.DeepSeq (NFData) import Control.Monad.Error.Class (MonadError(..)) import Data.Aeson.BetterErrors (Parse, nth, withText, withValue, toAesonParser, perhaps, asText) import qualified Data.Aeson as A import Data.Text (Text) import qualified Data.Text as T import qualified Data.ByteString.Lazy as BS import qualified Data.Text.Encoding as TE import Language.PureScript.Names import Language.PureScript.AST (Associativity(..)) | Given a list of actions , attempt them all , returning the first success . If all the actions fail , ' tryAll ' returns the first argument . tryAll :: MonadError e m => m a -> [m a] -> m a tryAll = foldr $ \x y -> catchError x (const y) firstEq :: Text -> Parse Text a -> Parse Text a firstEq str p = nth 0 (withText (eq str)) *> p where eq s s' = if s == s' then Right () else Left "" tryParse :: Text -> [Parse Text a] -> Parse Text a tryParse msg = tryAll (withValue (Left . (fullMsg <>) . showJSON)) where fullMsg = "Invalid " <> msg <> ": " showJSON :: A.Value -> Text showJSON = TE.decodeUtf8 . BS.toStrict . A.encode This type is isomorphic to ' Maybe ' ' ModuleName ' . It makes code a bit data ContainingModule = ThisModule | OtherModule ModuleName deriving (Show, Eq, Ord) instance A.ToJSON ContainingModule where toJSON = A.toJSON . go where go = \case ThisModule -> ["ThisModule"] OtherModule mn -> ["OtherModule", runModuleName mn] instance A.FromJSON ContainingModule where parseJSON = toAesonParser id asContainingModule asContainingModule :: Parse Text ContainingModule asContainingModule = tryParse "containing module" $ current ++ backwardsCompat where current = [ firstEq "ThisModule" (pure ThisModule) , firstEq "OtherModule" (OtherModule <$> nth 1 asModuleName) ] For JSON produced by compilers up to 0.10.5 . backwardsCompat = [ maybeToContainingModule <$> perhaps asModuleName ] asModuleName = moduleNameFromString <$> asText Convert a ' Maybe ' ' ModuleName ' to a ' ContainingModule ' , using the obvious maybeToContainingModule :: Maybe ModuleName -> ContainingModule maybeToContainingModule Nothing = ThisModule maybeToContainingModule (Just mn) = OtherModule mn fromQualified :: Qualified a -> (ContainingModule, a) fromQualified (Qualified (ByModuleName mn) x) = (OtherModule mn, x) fromQualified (Qualified _ x) = (ThisModule, x) data Link = NoLink | Link ContainingModule deriving (Show, Eq, Ord) instance A.ToJSON Link where toJSON = \case NoLink -> A.toJSON ["NoLink" :: Text] Link mn -> A.toJSON ["Link", A.toJSON mn] asLink :: Parse Text Link asLink = tryParse "link" [ firstEq "NoLink" (pure NoLink) , firstEq "Link" (Link <$> nth 1 asContainingModule) ] instance A.FromJSON Link where parseJSON = toAesonParser id asLink data Namespace = ValueLevel | TypeLevel deriving (Show, Eq, Ord, Generic) instance NFData Namespace instance A.ToJSON Namespace where toJSON = A.toJSON . show asNamespace :: Parse Text Namespace asNamespace = tryParse "namespace" [ withText $ \case "ValueLevel" -> Right ValueLevel "TypeLevel" -> Right TypeLevel _ -> Left "" ] instance A.FromJSON Namespace where parseJSON = toAesonParser id asNamespace data RenderedCodeElement = Syntax Text | Keyword Text | Space | Symbol Namespace Text Link | Role Text deriving (Show, Eq, Ord) instance A.ToJSON RenderedCodeElement where toJSON (Syntax str) = A.toJSON ["syntax", str] toJSON (Keyword str) = A.toJSON ["keyword", str] toJSON Space = A.toJSON ["space" :: Text] toJSON (Symbol ns str link) = A.toJSON ["symbol", A.toJSON ns, A.toJSON str, A.toJSON link] toJSON (Role role) = A.toJSON ["role", role] A type representing a highly simplified version of PureScript code , intended newtype RenderedCode = RC { unRC :: [RenderedCodeElement] } deriving (Show, Eq, Ord, Semigroup, Monoid) instance A.ToJSON RenderedCode where toJSON (RC elems) = A.toJSON elems This function allows conversion of a ' RenderedCode ' value into a value of some other type ( for example , plain text , or HTML ) . The first argument outputWith :: Monoid a => (RenderedCodeElement -> a) -> RenderedCode -> a outputWith f = foldMap f . unRC A ' RenderedCode ' fragment representing a space . sp :: RenderedCode sp = RC [Space] possible TODO : instead of this function , export RenderedCode values for syntaxRBrace , etc . syntax :: Text -> RenderedCode syntax x = RC [Syntax x] keyword :: Text -> RenderedCode keyword kw = RC [Keyword kw] keywordForall :: RenderedCode keywordForall = keyword "forall" keywordData :: RenderedCode keywordData = keyword "data" keywordType :: RenderedCode keywordType = keyword "type" keywordClass :: RenderedCode keywordClass = keyword "class" keywordWhere :: RenderedCode keywordWhere = keyword "where" keywordFixity :: Associativity -> RenderedCode keywordFixity Infixl = keyword "infixl" keywordFixity Infixr = keyword "infixr" keywordFixity Infix = keyword "infix" keywordAs :: RenderedCode keywordAs = keyword "as" ident :: Qualified Ident -> RenderedCode ident (fromQualified -> (mn, name)) = RC [Symbol ValueLevel (runIdent name) (Link mn)] dataCtor :: Qualified (ProperName 'ConstructorName) -> RenderedCode dataCtor (fromQualified -> (mn, name)) = RC [Symbol ValueLevel (runProperName name) (Link mn)] typeCtor :: Qualified (ProperName 'TypeName) -> RenderedCode typeCtor (fromQualified -> (mn, name)) = RC [Symbol TypeLevel (runProperName name) (Link mn)] typeOp :: Qualified (OpName 'TypeOpName) -> RenderedCode typeOp (fromQualified -> (mn, name)) = RC [Symbol TypeLevel (runOpName name) (Link mn)] typeVar :: Text -> RenderedCode typeVar x = RC [Symbol TypeLevel x NoLink] roleAnn :: Maybe Text -> RenderedCode roleAnn = RC . maybe [] renderRole where renderRole = \case "nominal" -> [Role "nominal"] "phantom" -> [Role "phantom"] _ -> [] type FixityAlias = Qualified (Either (ProperName 'TypeName) (Either Ident (ProperName 'ConstructorName))) alias :: FixityAlias -> RenderedCode alias for = prefix <> RC [Symbol ns name (Link mn)] where (ns, name, mn) = unpackFixityAlias for prefix = case ns of TypeLevel -> keywordType <> sp _ -> mempty aliasName :: FixityAlias -> Text -> RenderedCode aliasName for name' = let (ns, _, _) = unpackFixityAlias for unParen = T.tail . T.init name = unParen name' in case ns of ValueLevel -> ident (Qualified ByNullSourcePos (Ident name)) TypeLevel -> typeCtor (Qualified ByNullSourcePos (ProperName name)) unpackFixityAlias :: FixityAlias -> (Namespace, Text, ContainingModule) unpackFixityAlias (fromQualified -> (mn, x)) = case x of Left (n :: ProperName 'TypeName) -> (TypeLevel, runProperName n, mn) Right (Left n) -> (ValueLevel, runIdent n, mn) Right (Right (n :: ProperName 'ConstructorName)) -> (ValueLevel, runProperName n, mn)
df99dc6d3540ce5cdb1bc0fe297b65e324959f1b3fc1f47776c9f7223bcf9430
darkleaf/publicator
user_test.clj
(ns publicator.domain.aggregates.user-test (:require [publicator.domain.aggregates.user :as sut] [publicator.domain.test.fakes :as fakes] [publicator.utils.test.instrument :as instrument] [publicator.domain.test.factories :as factories] [publicator.domain.abstractions.aggregate :as aggregate] [clojure.spec.alpha :as s] [clojure.test :as t])) (t/use-fixtures :each fakes/fixture) (t/use-fixtures :once instrument/fixture) (t/deftest build (let [params {:login "john_doe" :full-name "John Doe" :password "password"} user (sut/build params)] (t/is (sut/user? user)))) (t/deftest authenticated? (let [password (factories/gen ::sut/password) user (factories/build-user {:password password})] (t/is (sut/authenticated? user password)))) (t/deftest aggregate (t/testing "id" (let [user (factories/build-user)] (t/is (= (:id user) (aggregate/id user))))) (t/testing "spec" (let [user (factories/build-user) spec (aggregate/spec user)] (t/is (s/valid? spec user)))))
null
https://raw.githubusercontent.com/darkleaf/publicator/e07eee93d8f3d9c07a15d574619d5ea59c00f87d/core/test/publicator/domain/aggregates/user_test.clj
clojure
(ns publicator.domain.aggregates.user-test (:require [publicator.domain.aggregates.user :as sut] [publicator.domain.test.fakes :as fakes] [publicator.utils.test.instrument :as instrument] [publicator.domain.test.factories :as factories] [publicator.domain.abstractions.aggregate :as aggregate] [clojure.spec.alpha :as s] [clojure.test :as t])) (t/use-fixtures :each fakes/fixture) (t/use-fixtures :once instrument/fixture) (t/deftest build (let [params {:login "john_doe" :full-name "John Doe" :password "password"} user (sut/build params)] (t/is (sut/user? user)))) (t/deftest authenticated? (let [password (factories/gen ::sut/password) user (factories/build-user {:password password})] (t/is (sut/authenticated? user password)))) (t/deftest aggregate (t/testing "id" (let [user (factories/build-user)] (t/is (= (:id user) (aggregate/id user))))) (t/testing "spec" (let [user (factories/build-user) spec (aggregate/spec user)] (t/is (s/valid? spec user)))))
a5b0d05a53b7aab5de9409c2cd5bcc81c47b570a5144d7a81639ae7ade497264
charJe/funds
hash.lisp
(in-package :funds) (defstruct dict hash test tree) (defun make-hash (&key (hash #'sxhash) (test #'eql)) "An empty hash that hashes occording to the given hash function, which defaults to #'sxhash and and tests according to the given test function, which defaults to #'eql." (make-dict :hash hash :test test :tree (make-avl-tree))) (defun hash-set (hash key &optional (value t)) "A hash similar to the given hash except that key maps to value in the returned hash." (let* ((h (funcall (dict-hash hash) key)) (old-alist (tree-find (dict-tree hash) h)) (new-alist (acons key value (remove (assoc key old-alist :test (dict-test hash)) old-alist)))) (make-dict :hash (dict-hash hash) :test (dict-test hash) :tree (tree-insert (dict-tree hash) h new-alist)))) (defun hash-remove (hash key) "A hash similar to the given hash, except that key does not map to any value in the returned hash." (let* ((h (funcall (dict-hash hash) key)) (old-alist (tree-find (dict-tree hash) h)) (new-alist (remove (assoc key old-alist :test (dict-test hash)) old-alist))) (make-dict :hash (dict-hash hash) :test (dict-test hash) :tree (if (null new-alist) (tree-remove (dict-tree hash) h) (tree-insert (dict-tree hash) h new-alist))))) (defun hash-ref (hash key &optional default) "The value associated with the given key in the given hash. A second value is returned to indicate whether the key is associated with any value or is not found." (let ((pair (assoc key (tree-find (dict-tree hash) (funcall (dict-hash hash) key)) :test (dict-test hash)))) (if (null pair) (values default nil) (values (cdr pair) t)))) (defun hash-as-alist (hash) "An alist containing the same key-value pairs as the given hash." (labels ((f (tree) (if (tree-empty-p tree) nil (append (f (bt-left tree)) (bt-value tree) (f (bt-right tree)))))) (f (dict-tree hash)))) (defun hash-from-alist (alist &key (test #'eql) (hash #'sxhash)) (reduce (lambda (hash pair) (hash-set hash (car pair) (cdr pair))) alist :initial-value (make-hash :test test :hash hash))) (defun map-hash (function hash) "A new hash where function has been applied to each key-value and the result of the each function call is the new value." (hash-from-alist (map 'list (lambda (cons) (cons (car cons) (funcall function (car cons) (cdr cons)))) (hash-as-alist hash)))) (defun hash-keys (hash) (mapcar #'car (hash-as-alist hash))) (defun hash-values (hash) (mapcar #'cdr (hash-as-alist hash))) (defun hash-size (hash) (tree-weight (dict-tree hash)))
null
https://raw.githubusercontent.com/charJe/funds/39d425818876b898c20780a678803df506df8424/src/hash.lisp
lisp
(in-package :funds) (defstruct dict hash test tree) (defun make-hash (&key (hash #'sxhash) (test #'eql)) "An empty hash that hashes occording to the given hash function, which defaults to #'sxhash and and tests according to the given test function, which defaults to #'eql." (make-dict :hash hash :test test :tree (make-avl-tree))) (defun hash-set (hash key &optional (value t)) "A hash similar to the given hash except that key maps to value in the returned hash." (let* ((h (funcall (dict-hash hash) key)) (old-alist (tree-find (dict-tree hash) h)) (new-alist (acons key value (remove (assoc key old-alist :test (dict-test hash)) old-alist)))) (make-dict :hash (dict-hash hash) :test (dict-test hash) :tree (tree-insert (dict-tree hash) h new-alist)))) (defun hash-remove (hash key) "A hash similar to the given hash, except that key does not map to any value in the returned hash." (let* ((h (funcall (dict-hash hash) key)) (old-alist (tree-find (dict-tree hash) h)) (new-alist (remove (assoc key old-alist :test (dict-test hash)) old-alist))) (make-dict :hash (dict-hash hash) :test (dict-test hash) :tree (if (null new-alist) (tree-remove (dict-tree hash) h) (tree-insert (dict-tree hash) h new-alist))))) (defun hash-ref (hash key &optional default) "The value associated with the given key in the given hash. A second value is returned to indicate whether the key is associated with any value or is not found." (let ((pair (assoc key (tree-find (dict-tree hash) (funcall (dict-hash hash) key)) :test (dict-test hash)))) (if (null pair) (values default nil) (values (cdr pair) t)))) (defun hash-as-alist (hash) "An alist containing the same key-value pairs as the given hash." (labels ((f (tree) (if (tree-empty-p tree) nil (append (f (bt-left tree)) (bt-value tree) (f (bt-right tree)))))) (f (dict-tree hash)))) (defun hash-from-alist (alist &key (test #'eql) (hash #'sxhash)) (reduce (lambda (hash pair) (hash-set hash (car pair) (cdr pair))) alist :initial-value (make-hash :test test :hash hash))) (defun map-hash (function hash) "A new hash where function has been applied to each key-value and the result of the each function call is the new value." (hash-from-alist (map 'list (lambda (cons) (cons (car cons) (funcall function (car cons) (cdr cons)))) (hash-as-alist hash)))) (defun hash-keys (hash) (mapcar #'car (hash-as-alist hash))) (defun hash-values (hash) (mapcar #'cdr (hash-as-alist hash))) (defun hash-size (hash) (tree-weight (dict-tree hash)))
8e22aca1cc8d090dd4bb27d5b0697a6199d1289d83009a3315ae5714b51f02d1
static-analysis-engineering/codehawk
jCHRaw2IF.ml
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Arnaud Venet ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC 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. ============================================================================= *) chlib open CHPretty (* jchlib *) open JCHBasicTypes open JCHBasicTypesAPI open JCHBytecode open JCHClass open JCHDictionary open JCHInstruction open JCHMethod open JCHParseUTF8Signature open JCHRawClass open JCHUnparse let debug = ref 1 module MethodCollections = CHCollections.Make ( struct type t = method_signature_int let compare m1 m2 = m1#compare m2 let toPretty m = m#toPretty end) module FieldCollections = CHCollections.Make ( struct type t = field_signature_int let compare f1 f2 = f1#compare f2 let toPretty f = f#toPretty end) [ map2 ] works even if lists are not the same size by taking elements for the other list as default values other list as default values *) let rec map2 f l1 l2 = match l1,l2 with | [],[] -> [] | [],l | l, [] -> l | e1::r1, e2::r2 -> (f e1 e2)::(map2 f r1 r2) let rec flags2access = function | AccPublic::l -> if List.exists (fun a -> a = AccPrivate || a= AccProtected) l then raise (JCH_class_structure_error (STR "Access flags Public and Private or Protected cannot be set at the same time")) else (Public,l) | AccPrivate::l -> if List.exists (fun a -> a = AccPublic || a= AccProtected) l then raise (JCH_class_structure_error (STR "Access flags Private and Public or Protected cannot be set at the same time")) else (Private,l) | AccProtected::l -> if List.exists (fun a -> a = AccPrivate || a= AccPublic) l then raise (JCH_class_structure_error (STR "Access flags Protected and Private or Public cannot be set at the same time")) else (Protected,l) | f::l -> let (p,fl) = flags2access l in (p,f::fl) | [] -> (Default,[]) let rec get_flag flag = function | [] -> (false,[]) | f::fl when f=flag -> (true,List.filter ((<>)f) fl) | f::fl -> let (b,fl) = get_flag flag fl in (b,f::fl) type lvt = (int * int * string * value_type_t * int) list let combine_LocalVariableTable (lvts:lvt list) : lvt = let lvt = List.concat lvts in if not (JCHBasicTypes.is_permissive ()) then begin let for_all_couple (f:'a -> 'a -> bool) (l:'a list) : bool = List.for_all (fun e1 -> List.for_all (f e1) l) l and overlap (e1_start,e1_end,_,_,_) (e2_start,e2_end,_,_,_) = (e2_start < e1_end && e1_start < e2_end) and similar (_,_,e1_name,_,e1_index) (_,_,e2_name,_,e2_index) = e1_name = e2_name || e1_index = e2_index in if not (for_all_couple (fun e1 e2 -> e1==e1 || not (overlap e1 e2 && similar e1 e2)) lvt) then raise (JCH_class_structure_error (LBLOCK [ STR "A CodeAttribute contains more than one " ; STR "LocalVariableTable and they are not compatible " ; STR "with each other"])) end; lvt type lvtt = (int * int * string * field_type_signature_int * int) list let combine_LocalVariableTypeTable (lvtts:lvtt list) : lvtt = let lvtt = List.concat lvtts in if not (is_permissive ()) then begin let for_all_couple (f:'a -> 'a -> bool) (l:'a list) : bool = List.for_all (fun e1 -> List.for_all (f e1) l) l and overlap (e1_start,e1_end,_,_,_) (e2_start,e2_end,_,_,_) = (e2_start < e1_end && e1_start < e2_end) and similar (_,_,e1_name,_,e1_index) (_,_,e2_name,_,e2_index) = e1_name = e2_name || e1_index = e2_index in if not (for_all_couple (fun e1 e2 -> e1==e1 || not (overlap e1 e2 && similar e1 e2)) lvtt) then raise (JCH_class_structure_error (LBLOCK [ STR "A CodeAttribute contains more than one " ; STR "LocalVariableTypeTable and they are not compatible " ; STR "with each other"])) end; lvtt convert a list of attributes to a list of couple of string , as for AttributeUnknown . let low2high_other_attributes consts : attribute_t list -> (string*string) list = List.map (function | AttributeUnknown (name, contents) -> name, contents | a -> let (name,contents) = unparse_attribute_to_strings consts a in if !debug >0 then prerr_endline ("Warning: unexpected attribute found: "^name); name,contents) (* convert a list of attributes to an [attributes] structure. *) let low2high_attributes consts (al:attribute_t list): attributes_int = make_attributes ~is_synthetic:(List.exists ((=)AttributeSynthetic) al) ~is_deprecated:(List.exists ((=)AttributeDeprecated) al) ~other:( low2high_other_attributes consts (List.filter (function AttributeDeprecated | AttributeSynthetic -> false | _ -> true) al)) let expanse_stackmap_table stackmap_table = let (_,stackmap) = List.fold_left (fun ((pc,l,_),stackmap) frame -> match frame with | SameFrame k -> let offset = pc + k + 1 in let s = (offset,l,[]) in (s,s::stackmap) | SameLocals (k,vtype) -> let offset = pc + k - 64 + 1 in let s = (offset,l,[vtype]) in (s,s::stackmap) | SameLocalsExtended (_,offset_delta,vtype) -> let offset = pc + offset_delta + 1 in let s = (offset,l,[vtype]) in (s,s::stackmap) | ChopFrame (k,offset_delta) -> let offset = pc + offset_delta + 1 in let nb_chop = 251 - k in let l_chop = List.rev (ExtList.List.drop nb_chop (List.rev l)) in let s = (offset,l_chop,[]) in (s,s::stackmap) | SameFrameExtended (_,offset_delta) -> let offset = pc + offset_delta + 1 in let s = (offset,l,[]) in (s,s::stackmap) | AppendFrame (_,offset_delta,vtype_list) -> let offset = pc + offset_delta + 1 in let s = (offset,l@vtype_list,[]) in (s,s::stackmap) | FullFrame (_,offset_delta,lv,sv) -> let offset = pc + offset_delta + 1 in let s = (offset,lv,sv) in (s,s::stackmap) ) ((-1,[],[]),[]) stackmap_table in List.rev stackmap let low2high_code consts = function c -> make_bytecode ~max_stack:c.c_max_stack ~max_locals:c.c_max_locals ~code:(make_opcodes (opcodes2code (DynArray.to_array consts) c.c_code)) ~exception_table:c.c_exc_tbl ?line_number_table: (begin let rec find_lineNumberTable = function | AttributeLineNumberTable l::l' -> if find_lineNumberTable l ' < > None then raise ( JCH_class_structure_error " Only one AttributeLineNumberTable can be attached to a method . " ) ; then raise (JCH_class_structure_error "Only one AttributeLineNumberTable can be attached to a method."); *) Some l | _::l -> find_lineNumberTable l | [] -> None in find_lineNumberTable c.JCHRawClass.c_attributes end) ?local_variable_table: (begin let lvt = combine_LocalVariableTable (List.fold_left (fun lvts -> (function | AttributeLocalVariableTable lvt -> lvt :: lvts | _ -> lvts)) [] c.JCHRawClass.c_attributes) in match lvt with | [] -> None | _ -> Some lvt end) ?local_variable_type_table: (begin let lvtt = combine_LocalVariableTypeTable (List.fold_left (fun lvtts -> (function | AttributeLocalVariableTypeTable lvtt -> lvtt :: lvtts | _ -> lvtts)) [] c.JCHRawClass.c_attributes) in match lvtt with | [] -> None | _ -> Some lvtt end) ?stack_map_midp: (begin let rec find_StackMap = function | AttributeStackMap l :: l' -> if find_StackMap l' <> None then raise (JCH_class_structure_error (STR "Only one StackMap attribute can be attached to a method.")); Some l | _::l -> find_StackMap l | [] -> None in match find_StackMap c.c_attributes with | None -> None | Some l -> Some (List.map (fun s -> make_stackmap s) l) end) ?stack_map_java6: (begin let rec find_StackMapTable = function | AttributeStackMapTable l :: l' -> if find_StackMapTable l' <> None then raise (JCH_class_structure_error (STR "Only one StackMapTable attribute can be attached to a method.")); Some (expanse_stackmap_table l) | _::l -> find_StackMapTable l | [] -> None in match find_StackMapTable c.c_attributes with | None -> None | Some l -> Some (List.map (fun s -> make_stackmap s) l) end) ~attributes:(low2high_other_attributes consts (List.filter (function | AttributeStackMap _ | AttributeStackMapTable _ | AttributeLocalVariableTable _ | AttributeLocalVariableTypeTable _ | AttributeLineNumberTable _ -> false | _ -> true) c.c_attributes)) () let low2high_cfield cn consts fs = function f -> let flags = f.f_flags in let (is_static,flags) = get_flag AccStatic flags in let (access,flags) = flags2access flags in let (is_final,flags) = get_flag AccFinal flags in let (is_volatile,flags) = get_flag AccVolatile flags in let (is_transient,flags) = get_flag AccTransient flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> prerr_endline "unexcepted flag in JLow2High.low2high_cfield"; assert false) flags in let kind = if is_final then if not (JCHBasicTypes.is_permissive ()) && is_volatile then raise (JCH_class_structure_error (STR "A field cannot be final and volatile.")) else Final else if is_volatile then Volatile else NotFinal in let (cst,other_att) = List.partition (function AttributeConstant _ -> true | _ -> false) f.f_attributes in let (cst,other_att) = match cst with | [] -> None,other_att | AttributeConstant c::oc when not is_static -> (* it seems quite common *) if !debug > 1 then prerr_endline ("Warning: Non-static field " ^ cn#name ^ "." ^ fs#name ^ " has been found with a constant value associated."); None, (AttributeConstant c::(oc@other_att)) | AttributeConstant c::[] -> Some c, other_att | AttributeConstant c::oc -> if !debug > 0 then prerr_endline ("Warning: Field " ^ cn#name ^ "." ^ fs#name ^ " contains more than one constant value associated."); Some c, (oc@other_att) | _ -> assert false in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) other_att in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || is_permissive () then try Some (parse_field_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (LBLOCK [ STR "A field contains more than one Signature attribute " ; STR "asscociated with it."])) | _ -> assert false in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in (make_class_field ~signature:fs ~class_signature:(make_cfs cn fs) ~generic_signature ~access ~is_static ~is_final ~kind ~value:cst ~is_transient ~is_synthetic ~is_enum ~other_flags:flags ~annotations ~attributes:(low2high_attributes consts other_att) :> field_int) let low2high_ifield cn consts fs = function f -> let flags = f.f_flags in let (is_public,flags) = get_flag AccPublic flags in let (is_static,flags) = get_flag AccStatic flags in let (is_final,flags) = get_flag AccFinal flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in if not(is_public && is_static && is_final) then raise (JCH_class_structure_error (STR "A field of an interface must be : Public, Static and Final")); let flags = List.map (function | AccRFU i -> i | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "A field of an interface may only have it " ; STR "AccSynthetic flag set in addition of AccPublic, " ; STR "AccStatic and AccFinal" ]))) flags in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) f.f_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_field_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A field contains more than one Signature attribute asscociated with it")) | _ -> assert false in let (csts,other_att) = List.partition (function AttributeConstant _ -> true | _ -> false) other_att in let cst = match csts with | [] -> None | [AttributeConstant c] -> Some c | _ -> raise (JCH_class_structure_error (STR "An interface field contains more than one Constant Attribute")) in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in (make_interface_field ~signature:fs ~class_signature:(make_cfs cn fs) ~generic_signature:generic_signature ~value:cst ~is_synthetic:is_synthetic ~is_final:is_final ~other_flags:flags ~annotations:annotations ~attributes:(low2high_attributes consts other_att) :> field_int) let low2high_amethod consts cs ms = function m -> let flags = m.m_flags in let (access,flags) = flags2access flags in let (_is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_bridge,flags) = get_flag AccBridge flags in let (is_varargs,flags) = get_flag AccVarArgs flags in let access = match access with | Private -> raise (JCH_class_structure_error (STR "Abstract method cannot be private")) | Default -> Default | Protected -> Protected | Public -> Public in let flags = List.map (function | AccRFU i -> i | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "If a method has its ACC_ABSTRACT flag set it " ; STR "may not have any of its ACC_FINAL, ACC_NATIVE, " ; STR "ACC_PRIVATE, ACC_STATIC, ACC_STRICT, or " ; STR "ACC_SYNCHRONIZED flags set"]))) flags in let (generic_signature, other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) m.m_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || is_permissive () then try Some (parse_method_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "An abstract method cannot have several Signature attributes.")) | _ -> assert false in let (exn,other_att) = List.partition (function | AttributeExceptions _-> true | AttributeCode _ -> begin pr_debug [ STR "Encountered Code Attribute in abstract method" ; ms#toPretty ; STR " in class " ; cs#toPretty ; NL ; NL ] ; false end | _ -> false) other_att in let exn = match exn with | [] -> [] | [AttributeExceptions cl] -> cl | _ -> raise (JCH_class_structure_error (STR "Only one Exception attribute is allowed in a method")) in let (default_annotation,other_att) = List.partition (function | AttributeAnnotationDefault _ -> true | _ -> false) other_att in let default_annotation = match default_annotation with | [] -> None | [AttributeAnnotationDefault ad] -> Some ad | _::_::_ -> raise (JCH_class_structure_error (STR "A method should not have more than one AnnotationDefault attribute")) | [_] -> assert false in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in let (parameter_annotations,other_att) = List.partition (function | AttributeRuntimeVisibleParameterAnnotations _ | AttributeRuntimeInvisibleParameterAnnotations _ -> true | _ -> false) other_att in let parameter_annotations = if parameter_annotations = [] then [] else let res = List.fold_left (fun (res:'a list) -> function | AttributeRuntimeVisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,true))) pa in map2 (@) pa res | AttributeRuntimeInvisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,false))) pa in map2 (@) pa res | _ -> assert false) [] parameter_annotations in if List.length res <= List.length ms#descriptor#arguments then res else raise (JCH_class_structure_error (LBLOCK [ STR "The length of an Runtime(In)VisibleParameterAnnotations " ; STR "is longer than the number of arguments of the same method"])) in make_abstract_method ~signature:ms ~class_method_signature:(make_cms cs ms) ~access:access ?generic_signature:generic_signature ~is_synthetic:is_synthetic ~is_bridge:is_bridge ~has_varargs:is_varargs ~other_flags:flags ~exceptions:exn ~attributes:(low2high_attributes consts other_att) ~annotations:(make_method_annotations ~global:annotations ~parameters:parameter_annotations) ?annotation_default:default_annotation () let low2high_cmethod consts cs ms = function m -> if m.m_name = "<init>" && List.exists (fun a -> a=AccStatic || a=AccFinal || a=AccSynchronized || a=AccNative || a=AccAbstract) m.m_flags then raise (JCH_class_structure_error (LBLOCK [ STR "A specific instance initialization method may have at most " ; STR "one of its ACC_PRIVATE, ACC_PROTECTED, and ACC_PUBLIC flags set " ; STR "and may also have its ACC_STRICT flag set" ])); let flags = m.m_flags in let (access,flags) = flags2access flags in let (is_static,flags) = get_flag AccStatic flags in let (is_final,flags) = get_flag AccFinal flags in let (is_synchronized,flags) = get_flag AccSynchronized flags in let (is_strict,flags) = get_flag AccStrict flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_bridge,flags) = get_flag AccBridge flags in let (is_varargs,flags) = get_flag AccVarArgs flags in let (is_native,flags) = get_flag AccNative flags in let flags = List.map (function | AccRFU i -> i | AccAbstract -> raise (JCH_class_structure_error (STR "Non abstract class cannot have abstract methods")) | _ -> raise (Failure "Bug in JLow2High.low2high_cmethod : unexpected flag found.")) flags in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) m.m_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_method_type_signature s) with JCH_class_structure_error _ as e -> if JCHBasicTypes.is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A method cannot have several Signature attributes")) | _ -> assert false and (exn,other_att) = List.partition (function AttributeExceptions _ -> true | _ -> false) other_att in let exn = match exn with | [] -> [] | [AttributeExceptions cl] -> cl | _ -> raise (JCH_class_structure_error (STR "Only one Exception attribute is allowed in a method")) and (code,other_att) = List.partition (function AttributeCode _ -> true | _ -> false) other_att in let code = match code with | [AttributeCode c] when not is_native -> Bytecode (low2high_code consts c) | [] when is_native -> Native | [] -> raise (JCH_class_structure_error (STR "A method not declared as Native, nor Abstract has been found without code")) | [_] -> raise (JCH_class_structure_error (STR "A method declared as Native has been found with a code attribute")) | _::_::_ -> raise (JCH_class_structure_error (STR "Only one Code attribute is allowed in a method")) in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in let (parameter_annotations,other_att) = List.partition (function | AttributeRuntimeVisibleParameterAnnotations _ | AttributeRuntimeInvisibleParameterAnnotations _ -> true | _ -> false) other_att in let parameter_annotations = if parameter_annotations = [] then [] else let res = List.fold_left (fun (res:'a list) -> function | AttributeRuntimeVisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,true))) pa in map2 (@) pa res | AttributeRuntimeInvisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,false))) pa in map2 (@) pa res | _ -> assert false) [] parameter_annotations in if List.length res <= List.length ms#descriptor#arguments then res else raise (JCH_class_structure_error (LBLOCK [ STR "The length of an Runtime(In)VisibleParameterAnnotations " ; STR "is longer than the number of arguments of the same method"])) in let class_method_signature = make_cms cs ms in make_concrete_method ~signature:ms ~class_method_signature ~is_static ~is_final ~is_synchronized ~is_strict ~access ?generic_signature:generic_signature ~is_bridge ~has_varargs:is_varargs ~is_synthetic ~other_flags:flags ~exceptions:exn ~attributes:(low2high_attributes consts other_att) ~annotations:(make_method_annotations ~global:annotations ~parameters:parameter_annotations) ~implementation:code () let low2high_interface_method consts cs ms = function m -> if List.exists (fun a -> match a with AttributeCode _ -> true | _ -> false) m.m_attributes then low2high_cmethod consts cs ms m else low2high_amethod consts cs ms m let low2high_acmethod consts cs ms = function m -> if List.exists ((=)AccAbstract) m.m_flags then low2high_amethod consts cs ms m else low2high_cmethod consts cs ms m let low2high_methods ?(interfacemethod=false) cn consts = function ac -> let cs = ac.rc_name in let methods = List.map (fun meth -> let isstatic = List.exists (fun f -> match f with AccStatic -> true | _ -> false) meth.m_flags in let ms = make_ms isstatic meth.m_name meth.m_descriptor in try if interfacemethod then low2high_interface_method consts cs ms meth else low2high_acmethod consts cs ms meth with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in method " ; STR (JCHDumpBasicTypes.signature meth.m_name (SMethod meth.m_descriptor)) ; STR ": " ; msg ]))) ac.rc_methods in let _ = if !debug > 0 then let mset = new MethodCollections.set_t in let _ = List.iter (fun m -> if mset#has m#get_signature then prerr_endline ("Warning: in " ^ cn#name ^ " two methods with the same signature (" ^ m#get_signature#to_string ^ ")") else mset#add m#get_signature) methods in () in methods let low2high_innerclass = function (inner_class_info,outer_class_info,inner_name,flags) -> let (access,flags) = flags2access flags in let (is_final,flags) = get_flag AccFinal flags in let (is_static,flags) = get_flag AccStatic flags in let (is_interface,flags) = get_flag AccInterface flags in let (is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_annotation,flags) = get_flag AccAnnotation flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> raise (Failure "unexpected flag")) flags in make_inner_class ?name:inner_class_info ?outer_class_name:outer_class_info ?source_name:inner_name ~access ~is_static ~is_final ~is_synthetic ~is_annotation ~is_enum ~other_flags:flags ~kind:(if is_interface then Interface else if is_abstract then Abstract else ConcreteClass) () let low2high_class cl = let java_lang_object = make_cn "java.lang.Object" in if cl.rc_super = None && (not (cl.rc_name#equal java_lang_object)) then raise (JCH_class_structure_error (STR "Only java.lang.Object is allowed not to have a super-class")); let cs = cl.rc_name in let flags = cl.rc_flags in let (access,flags) = flags2access flags in let (accsuper,flags) = get_flag AccSuper flags in let (is_final,flags) = get_flag AccFinal flags in let (is_interface,flags) = get_flag AccInterface flags in let (is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_annotation,flags) = get_flag AccAnnotation flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> raise (Failure "unexpected flag found")) flags in let _ = if not (JCHBasicTypes.is_permissive ()) && not (accsuper || is_interface) && not (accsuper && is_interface) then raise (JCH_class_structure_error (STR "ACC_SUPER must be set for all classes (that are not interfaces)")) in let _ = if not (JCHBasicTypes.is_permissive ()) && (is_final && is_abstract) then raise (JCH_class_structure_error (STR "An abstract class cannot be final")) in let consts = DynArray.of_array cl.rc_consts in let my_name = cl.rc_name in let my_version = cl.rc_version in let my_source_origin = cl.rc_origin in let my_md5_digest = cl.rc_md5 in let my_access = match access with | Public -> Public | Default -> Default | _ -> raise (JCH_class_structure_error (STR "Invalid visibility for a class")) and my_interfaces = cl.rc_interfaces and my_sourcefile = let rec find_SourceFile = function | AttributeSourceFile s::_ -> Some s | _::l -> find_SourceFile l | [] -> None in find_SourceFile cl.rc_attributes and my_deprecated = List.exists ((=)AttributeDeprecated) cl.rc_attributes and my_generic_signature = match List.find_all (function AttributeSignature _ -> true | _ -> false) cl.rc_attributes with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_class_signature s) with JCH_class_structure_error _ as e -> if JCHBasicTypes.is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A class or interface cannot have several Signature attributes")) | _ -> assert false and my_bootstrap_methods = match List.find_all (function AttributeBootstrapMethods _ -> true | _ -> false) cl.rc_attributes with | [] -> [] | [ AttributeBootstrapMethods l ] -> l | _ -> raise (JCH_class_structure_error (STR "A class or interface can only have one BootstrapMethod table")) and my_source_debug_extension = let sde_attributes = List.find_all (function AttributeSourceDebugExtension _ -> true | _ -> false) cl.rc_attributes in match sde_attributes with | [] -> None | (AttributeSourceDebugExtension s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then Some s else raise (JCH_class_structure_error (STR "A class cannot contain several SourceDebugExtension attribute")) | _ -> assert false and my_inner_classes = let rec find_InnerClasses = function | AttributeInnerClasses icl::_ -> List.rev_map low2high_innerclass icl | _::l -> find_InnerClasses l | [] -> [] in find_InnerClasses cl.rc_attributes and my_annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> annots) cl.rc_attributes [] and my_other_attributes = low2high_other_attributes consts (List.filter (function | AttributeSignature _ | AttributeSourceFile _ | AttributeSourceDebugExtension _ | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ | AttributeDeprecated | AttributeInnerClasses _ | AttributeBootstrapMethods _ -> false | AttributeEnclosingMethod _ -> is_interface | _ -> true) cl.rc_attributes); in if is_interface then begin if not (is_permissive ()) then begin (if not is_abstract then raise (JCH_class_structure_error (LBLOCK [ STR "A class file with its AccInterface flag set must " ; STR "also have its AccAbstract flag set"]))); (let obj = make_cn "java.lang.Object" in if not (cl.rc_super = Some obj) then raise (JCH_class_structure_error (STR "The super-class of interfaces must be java.lang.Object"))); if is_enum then raise (JCH_class_structure_error (LBLOCK [ STR "A class file with its AccInterface flag set must " ; STR "not have its their AccEnum flag set"])) end; let (init,methods) = match List.partition (fun m -> let clinit_name = clinit_signature#name in let clinit_desc = clinit_signature#descriptor in m.m_name = clinit_name && m.m_descriptor#arguments = clinit_desc#arguments) cl.rc_methods with | ([ m ],others) -> let ms = make_ms true m.m_name m.m_descriptor in (Some (low2high_cmethod consts cs ms m), others) | ([],others) -> (None, others) | m::_::_,others -> if not (JCHBasicTypes.is_permissive ()) then raise (JCH_class_structure_error (STR "has more than one class initializer <clinit>")) else (Some (low2high_cmethod consts cs clinit_signature m), others) in let fields = List.map (fun f -> let fs = make_fs f.f_name f.f_descriptor in try low2high_ifield my_name consts fs f with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "field " ; STR ((JCHDumpBasicTypes.signature f.f_name (SValue f.f_descriptor))) ; STR ": " ; msg ]))) cl.rc_fields in let _ = if !debug > 0 then let fset = new FieldCollections.set_t in List.iter (fun f -> if fset#has f#get_signature then prerr_endline ("Warning: in " ^ my_name#name ^ " two fields have the same signature (" ^ f#get_signature#to_string ^ ")") else fset#add f#get_signature) fields in let methods = List.map (fun meth -> let isstatic = List.exists (fun f -> match f with AccStatic -> true | _ -> false) meth.m_flags in let ms = make_ms isstatic meth.m_name meth.m_descriptor in try low2high_interface_method consts cs ms meth with JCH_class_structure_error msg -> let sign = JCHDumpBasicTypes.signature meth.m_name (SMethod meth.m_descriptor) in raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ; STR ": method " ; STR sign ; STR ": " ; msg ]))) methods in let _ = if !debug > 0 then let mset = new MethodCollections.set_t in List.iter (fun m -> if mset#has m#get_signature then prerr_endline ("Warning: in " ^ my_name#name ^ " two methods have the same signature (" ^ m#get_signature#to_string ^ ")") else mset#add m#get_signature) methods in (make_java_interface ~name:my_name ~version:my_version ~access:my_access ~generic_signature:my_generic_signature ~interfaces:my_interfaces ~consts:(DynArray.to_array consts) ?source_file:my_sourcefile ~source_origin:my_source_origin ~md5_digest:my_md5_digest ~is_deprecated:my_deprecated ?source_debug_extension:my_source_debug_extension ~inner_classes:my_inner_classes ~other_attributes:my_other_attributes ?initializer_method:init ~is_annotation:is_annotation ~annotations:my_annotations ~bootstrapmethods:my_bootstrap_methods ~other_flags:flags ~fields ~methods () :> java_class_or_interface_int) end else begin if is_annotation then raise (JCH_class_structure_error (LBLOCK [ STR "Class file with their AccAnnotation flag set must also " ; STR "have their AccInterface flag set"])); let my_enclosing_method = let enclosing_method_atts = List.find_all (function AttributeEnclosingMethod _ -> true | _ -> false) cl.rc_attributes in match enclosing_method_atts with | [] -> None | [AttributeEnclosingMethod (cs,mso)] -> let ms = match mso with | None -> None (* make_ms requires an argument is_static, which is not known at this point for an enclosing method; we give it a default argument false; currently the enclosing method is not used; when it is used this is_static argument needs to be fixed *) | Some (mn,SMethod mdesc) -> Some (make_ms false mn mdesc) | Some (_,SValue _) -> raise (JCH_class_structure_error (LBLOCK [ STR "A EnclosingMethod attribute cannot specify " ; STR "a field as enclosing method"])) in Some (cs, ms) | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "A EnclosingMethod attribute can only be " ; STR "specified at most once per class"])) and my_methods = try low2high_methods my_name consts cl with | JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ;STR ": " ; msg ])) and my_fields = List.map (fun f -> let fs = make_fs f.f_name f.f_descriptor in try low2high_cfield my_name consts fs f with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ; STR ": in field " ; STR (JCHDumpBasicTypes.signature f.f_name (SValue f.f_descriptor)) ; STR ": " ; msg ]))) cl.rc_fields in (make_java_class ~name:my_name ~version:my_version ~super_class:cl.rc_super ~generic_signature:my_generic_signature ~is_final:is_final ~is_abstract:is_abstract ~access:my_access ~is_synthetic:is_synthetic ~is_enum:is_enum ~other_flags:flags ~interfaces:my_interfaces ~consts:(DynArray.to_array consts) ?source_file:my_sourcefile ~source_origin:my_source_origin ~md5_digest:my_md5_digest ~is_deprecated:my_deprecated ?source_debug_extension:my_source_debug_extension ?enclosing_method:my_enclosing_method ~annotations:my_annotations ~bootstrapmethods:my_bootstrap_methods ~inner_classes:my_inner_classes ~other_attributes:my_other_attributes ~fields:my_fields ~methods:my_methods () :> java_class_or_interface_int) end let low2high_class cl = try low2high_class cl with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [STR "In " ; STR cl.rc_name#name ; STR ": " ; msg]))
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchlib/jCHRaw2IF.ml
ocaml
jchlib convert a list of attributes to an [attributes] structure. it seems quite common make_ms requires an argument is_static, which is not known at this point for an enclosing method; we give it a default argument false; currently the enclosing method is not used; when it is used this is_static argument needs to be fixed
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Arnaud Venet ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC 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. ============================================================================= *) chlib open CHPretty open JCHBasicTypes open JCHBasicTypesAPI open JCHBytecode open JCHClass open JCHDictionary open JCHInstruction open JCHMethod open JCHParseUTF8Signature open JCHRawClass open JCHUnparse let debug = ref 1 module MethodCollections = CHCollections.Make ( struct type t = method_signature_int let compare m1 m2 = m1#compare m2 let toPretty m = m#toPretty end) module FieldCollections = CHCollections.Make ( struct type t = field_signature_int let compare f1 f2 = f1#compare f2 let toPretty f = f#toPretty end) [ map2 ] works even if lists are not the same size by taking elements for the other list as default values other list as default values *) let rec map2 f l1 l2 = match l1,l2 with | [],[] -> [] | [],l | l, [] -> l | e1::r1, e2::r2 -> (f e1 e2)::(map2 f r1 r2) let rec flags2access = function | AccPublic::l -> if List.exists (fun a -> a = AccPrivate || a= AccProtected) l then raise (JCH_class_structure_error (STR "Access flags Public and Private or Protected cannot be set at the same time")) else (Public,l) | AccPrivate::l -> if List.exists (fun a -> a = AccPublic || a= AccProtected) l then raise (JCH_class_structure_error (STR "Access flags Private and Public or Protected cannot be set at the same time")) else (Private,l) | AccProtected::l -> if List.exists (fun a -> a = AccPrivate || a= AccPublic) l then raise (JCH_class_structure_error (STR "Access flags Protected and Private or Public cannot be set at the same time")) else (Protected,l) | f::l -> let (p,fl) = flags2access l in (p,f::fl) | [] -> (Default,[]) let rec get_flag flag = function | [] -> (false,[]) | f::fl when f=flag -> (true,List.filter ((<>)f) fl) | f::fl -> let (b,fl) = get_flag flag fl in (b,f::fl) type lvt = (int * int * string * value_type_t * int) list let combine_LocalVariableTable (lvts:lvt list) : lvt = let lvt = List.concat lvts in if not (JCHBasicTypes.is_permissive ()) then begin let for_all_couple (f:'a -> 'a -> bool) (l:'a list) : bool = List.for_all (fun e1 -> List.for_all (f e1) l) l and overlap (e1_start,e1_end,_,_,_) (e2_start,e2_end,_,_,_) = (e2_start < e1_end && e1_start < e2_end) and similar (_,_,e1_name,_,e1_index) (_,_,e2_name,_,e2_index) = e1_name = e2_name || e1_index = e2_index in if not (for_all_couple (fun e1 e2 -> e1==e1 || not (overlap e1 e2 && similar e1 e2)) lvt) then raise (JCH_class_structure_error (LBLOCK [ STR "A CodeAttribute contains more than one " ; STR "LocalVariableTable and they are not compatible " ; STR "with each other"])) end; lvt type lvtt = (int * int * string * field_type_signature_int * int) list let combine_LocalVariableTypeTable (lvtts:lvtt list) : lvtt = let lvtt = List.concat lvtts in if not (is_permissive ()) then begin let for_all_couple (f:'a -> 'a -> bool) (l:'a list) : bool = List.for_all (fun e1 -> List.for_all (f e1) l) l and overlap (e1_start,e1_end,_,_,_) (e2_start,e2_end,_,_,_) = (e2_start < e1_end && e1_start < e2_end) and similar (_,_,e1_name,_,e1_index) (_,_,e2_name,_,e2_index) = e1_name = e2_name || e1_index = e2_index in if not (for_all_couple (fun e1 e2 -> e1==e1 || not (overlap e1 e2 && similar e1 e2)) lvtt) then raise (JCH_class_structure_error (LBLOCK [ STR "A CodeAttribute contains more than one " ; STR "LocalVariableTypeTable and they are not compatible " ; STR "with each other"])) end; lvtt convert a list of attributes to a list of couple of string , as for AttributeUnknown . let low2high_other_attributes consts : attribute_t list -> (string*string) list = List.map (function | AttributeUnknown (name, contents) -> name, contents | a -> let (name,contents) = unparse_attribute_to_strings consts a in if !debug >0 then prerr_endline ("Warning: unexpected attribute found: "^name); name,contents) let low2high_attributes consts (al:attribute_t list): attributes_int = make_attributes ~is_synthetic:(List.exists ((=)AttributeSynthetic) al) ~is_deprecated:(List.exists ((=)AttributeDeprecated) al) ~other:( low2high_other_attributes consts (List.filter (function AttributeDeprecated | AttributeSynthetic -> false | _ -> true) al)) let expanse_stackmap_table stackmap_table = let (_,stackmap) = List.fold_left (fun ((pc,l,_),stackmap) frame -> match frame with | SameFrame k -> let offset = pc + k + 1 in let s = (offset,l,[]) in (s,s::stackmap) | SameLocals (k,vtype) -> let offset = pc + k - 64 + 1 in let s = (offset,l,[vtype]) in (s,s::stackmap) | SameLocalsExtended (_,offset_delta,vtype) -> let offset = pc + offset_delta + 1 in let s = (offset,l,[vtype]) in (s,s::stackmap) | ChopFrame (k,offset_delta) -> let offset = pc + offset_delta + 1 in let nb_chop = 251 - k in let l_chop = List.rev (ExtList.List.drop nb_chop (List.rev l)) in let s = (offset,l_chop,[]) in (s,s::stackmap) | SameFrameExtended (_,offset_delta) -> let offset = pc + offset_delta + 1 in let s = (offset,l,[]) in (s,s::stackmap) | AppendFrame (_,offset_delta,vtype_list) -> let offset = pc + offset_delta + 1 in let s = (offset,l@vtype_list,[]) in (s,s::stackmap) | FullFrame (_,offset_delta,lv,sv) -> let offset = pc + offset_delta + 1 in let s = (offset,lv,sv) in (s,s::stackmap) ) ((-1,[],[]),[]) stackmap_table in List.rev stackmap let low2high_code consts = function c -> make_bytecode ~max_stack:c.c_max_stack ~max_locals:c.c_max_locals ~code:(make_opcodes (opcodes2code (DynArray.to_array consts) c.c_code)) ~exception_table:c.c_exc_tbl ?line_number_table: (begin let rec find_lineNumberTable = function | AttributeLineNumberTable l::l' -> if find_lineNumberTable l ' < > None then raise ( JCH_class_structure_error " Only one AttributeLineNumberTable can be attached to a method . " ) ; then raise (JCH_class_structure_error "Only one AttributeLineNumberTable can be attached to a method."); *) Some l | _::l -> find_lineNumberTable l | [] -> None in find_lineNumberTable c.JCHRawClass.c_attributes end) ?local_variable_table: (begin let lvt = combine_LocalVariableTable (List.fold_left (fun lvts -> (function | AttributeLocalVariableTable lvt -> lvt :: lvts | _ -> lvts)) [] c.JCHRawClass.c_attributes) in match lvt with | [] -> None | _ -> Some lvt end) ?local_variable_type_table: (begin let lvtt = combine_LocalVariableTypeTable (List.fold_left (fun lvtts -> (function | AttributeLocalVariableTypeTable lvtt -> lvtt :: lvtts | _ -> lvtts)) [] c.JCHRawClass.c_attributes) in match lvtt with | [] -> None | _ -> Some lvtt end) ?stack_map_midp: (begin let rec find_StackMap = function | AttributeStackMap l :: l' -> if find_StackMap l' <> None then raise (JCH_class_structure_error (STR "Only one StackMap attribute can be attached to a method.")); Some l | _::l -> find_StackMap l | [] -> None in match find_StackMap c.c_attributes with | None -> None | Some l -> Some (List.map (fun s -> make_stackmap s) l) end) ?stack_map_java6: (begin let rec find_StackMapTable = function | AttributeStackMapTable l :: l' -> if find_StackMapTable l' <> None then raise (JCH_class_structure_error (STR "Only one StackMapTable attribute can be attached to a method.")); Some (expanse_stackmap_table l) | _::l -> find_StackMapTable l | [] -> None in match find_StackMapTable c.c_attributes with | None -> None | Some l -> Some (List.map (fun s -> make_stackmap s) l) end) ~attributes:(low2high_other_attributes consts (List.filter (function | AttributeStackMap _ | AttributeStackMapTable _ | AttributeLocalVariableTable _ | AttributeLocalVariableTypeTable _ | AttributeLineNumberTable _ -> false | _ -> true) c.c_attributes)) () let low2high_cfield cn consts fs = function f -> let flags = f.f_flags in let (is_static,flags) = get_flag AccStatic flags in let (access,flags) = flags2access flags in let (is_final,flags) = get_flag AccFinal flags in let (is_volatile,flags) = get_flag AccVolatile flags in let (is_transient,flags) = get_flag AccTransient flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> prerr_endline "unexcepted flag in JLow2High.low2high_cfield"; assert false) flags in let kind = if is_final then if not (JCHBasicTypes.is_permissive ()) && is_volatile then raise (JCH_class_structure_error (STR "A field cannot be final and volatile.")) else Final else if is_volatile then Volatile else NotFinal in let (cst,other_att) = List.partition (function AttributeConstant _ -> true | _ -> false) f.f_attributes in let (cst,other_att) = match cst with | [] -> None,other_att if !debug > 1 then prerr_endline ("Warning: Non-static field " ^ cn#name ^ "." ^ fs#name ^ " has been found with a constant value associated."); None, (AttributeConstant c::(oc@other_att)) | AttributeConstant c::[] -> Some c, other_att | AttributeConstant c::oc -> if !debug > 0 then prerr_endline ("Warning: Field " ^ cn#name ^ "." ^ fs#name ^ " contains more than one constant value associated."); Some c, (oc@other_att) | _ -> assert false in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) other_att in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || is_permissive () then try Some (parse_field_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (LBLOCK [ STR "A field contains more than one Signature attribute " ; STR "asscociated with it."])) | _ -> assert false in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in (make_class_field ~signature:fs ~class_signature:(make_cfs cn fs) ~generic_signature ~access ~is_static ~is_final ~kind ~value:cst ~is_transient ~is_synthetic ~is_enum ~other_flags:flags ~annotations ~attributes:(low2high_attributes consts other_att) :> field_int) let low2high_ifield cn consts fs = function f -> let flags = f.f_flags in let (is_public,flags) = get_flag AccPublic flags in let (is_static,flags) = get_flag AccStatic flags in let (is_final,flags) = get_flag AccFinal flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in if not(is_public && is_static && is_final) then raise (JCH_class_structure_error (STR "A field of an interface must be : Public, Static and Final")); let flags = List.map (function | AccRFU i -> i | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "A field of an interface may only have it " ; STR "AccSynthetic flag set in addition of AccPublic, " ; STR "AccStatic and AccFinal" ]))) flags in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) f.f_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_field_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A field contains more than one Signature attribute asscociated with it")) | _ -> assert false in let (csts,other_att) = List.partition (function AttributeConstant _ -> true | _ -> false) other_att in let cst = match csts with | [] -> None | [AttributeConstant c] -> Some c | _ -> raise (JCH_class_structure_error (STR "An interface field contains more than one Constant Attribute")) in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in (make_interface_field ~signature:fs ~class_signature:(make_cfs cn fs) ~generic_signature:generic_signature ~value:cst ~is_synthetic:is_synthetic ~is_final:is_final ~other_flags:flags ~annotations:annotations ~attributes:(low2high_attributes consts other_att) :> field_int) let low2high_amethod consts cs ms = function m -> let flags = m.m_flags in let (access,flags) = flags2access flags in let (_is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_bridge,flags) = get_flag AccBridge flags in let (is_varargs,flags) = get_flag AccVarArgs flags in let access = match access with | Private -> raise (JCH_class_structure_error (STR "Abstract method cannot be private")) | Default -> Default | Protected -> Protected | Public -> Public in let flags = List.map (function | AccRFU i -> i | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "If a method has its ACC_ABSTRACT flag set it " ; STR "may not have any of its ACC_FINAL, ACC_NATIVE, " ; STR "ACC_PRIVATE, ACC_STATIC, ACC_STRICT, or " ; STR "ACC_SYNCHRONIZED flags set"]))) flags in let (generic_signature, other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) m.m_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || is_permissive () then try Some (parse_method_type_signature s) with JCH_class_structure_error _ as e -> if is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "An abstract method cannot have several Signature attributes.")) | _ -> assert false in let (exn,other_att) = List.partition (function | AttributeExceptions _-> true | AttributeCode _ -> begin pr_debug [ STR "Encountered Code Attribute in abstract method" ; ms#toPretty ; STR " in class " ; cs#toPretty ; NL ; NL ] ; false end | _ -> false) other_att in let exn = match exn with | [] -> [] | [AttributeExceptions cl] -> cl | _ -> raise (JCH_class_structure_error (STR "Only one Exception attribute is allowed in a method")) in let (default_annotation,other_att) = List.partition (function | AttributeAnnotationDefault _ -> true | _ -> false) other_att in let default_annotation = match default_annotation with | [] -> None | [AttributeAnnotationDefault ad] -> Some ad | _::_::_ -> raise (JCH_class_structure_error (STR "A method should not have more than one AnnotationDefault attribute")) | [_] -> assert false in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in let (parameter_annotations,other_att) = List.partition (function | AttributeRuntimeVisibleParameterAnnotations _ | AttributeRuntimeInvisibleParameterAnnotations _ -> true | _ -> false) other_att in let parameter_annotations = if parameter_annotations = [] then [] else let res = List.fold_left (fun (res:'a list) -> function | AttributeRuntimeVisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,true))) pa in map2 (@) pa res | AttributeRuntimeInvisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,false))) pa in map2 (@) pa res | _ -> assert false) [] parameter_annotations in if List.length res <= List.length ms#descriptor#arguments then res else raise (JCH_class_structure_error (LBLOCK [ STR "The length of an Runtime(In)VisibleParameterAnnotations " ; STR "is longer than the number of arguments of the same method"])) in make_abstract_method ~signature:ms ~class_method_signature:(make_cms cs ms) ~access:access ?generic_signature:generic_signature ~is_synthetic:is_synthetic ~is_bridge:is_bridge ~has_varargs:is_varargs ~other_flags:flags ~exceptions:exn ~attributes:(low2high_attributes consts other_att) ~annotations:(make_method_annotations ~global:annotations ~parameters:parameter_annotations) ?annotation_default:default_annotation () let low2high_cmethod consts cs ms = function m -> if m.m_name = "<init>" && List.exists (fun a -> a=AccStatic || a=AccFinal || a=AccSynchronized || a=AccNative || a=AccAbstract) m.m_flags then raise (JCH_class_structure_error (LBLOCK [ STR "A specific instance initialization method may have at most " ; STR "one of its ACC_PRIVATE, ACC_PROTECTED, and ACC_PUBLIC flags set " ; STR "and may also have its ACC_STRICT flag set" ])); let flags = m.m_flags in let (access,flags) = flags2access flags in let (is_static,flags) = get_flag AccStatic flags in let (is_final,flags) = get_flag AccFinal flags in let (is_synchronized,flags) = get_flag AccSynchronized flags in let (is_strict,flags) = get_flag AccStrict flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_bridge,flags) = get_flag AccBridge flags in let (is_varargs,flags) = get_flag AccVarArgs flags in let (is_native,flags) = get_flag AccNative flags in let flags = List.map (function | AccRFU i -> i | AccAbstract -> raise (JCH_class_structure_error (STR "Non abstract class cannot have abstract methods")) | _ -> raise (Failure "Bug in JLow2High.low2high_cmethod : unexpected flag found.")) flags in let (generic_signature,other_att) = List.partition (function AttributeSignature _ -> true | _ -> false) m.m_attributes in let generic_signature = match generic_signature with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_method_type_signature s) with JCH_class_structure_error _ as e -> if JCHBasicTypes.is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A method cannot have several Signature attributes")) | _ -> assert false and (exn,other_att) = List.partition (function AttributeExceptions _ -> true | _ -> false) other_att in let exn = match exn with | [] -> [] | [AttributeExceptions cl] -> cl | _ -> raise (JCH_class_structure_error (STR "Only one Exception attribute is allowed in a method")) and (code,other_att) = List.partition (function AttributeCode _ -> true | _ -> false) other_att in let code = match code with | [AttributeCode c] when not is_native -> Bytecode (low2high_code consts c) | [] when is_native -> Native | [] -> raise (JCH_class_structure_error (STR "A method not declared as Native, nor Abstract has been found without code")) | [_] -> raise (JCH_class_structure_error (STR "A method declared as Native has been found with a code attribute")) | _::_::_ -> raise (JCH_class_structure_error (STR "Only one Code attribute is allowed in a method")) in let (annotations,other_att) = List.partition (function | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ -> true | _ -> false) other_att in let annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> assert false) annotations [] in let (parameter_annotations,other_att) = List.partition (function | AttributeRuntimeVisibleParameterAnnotations _ | AttributeRuntimeInvisibleParameterAnnotations _ -> true | _ -> false) other_att in let parameter_annotations = if parameter_annotations = [] then [] else let res = List.fold_left (fun (res:'a list) -> function | AttributeRuntimeVisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,true))) pa in map2 (@) pa res | AttributeRuntimeInvisibleParameterAnnotations pa -> let pa = List.map (List.map (fun a -> (a,false))) pa in map2 (@) pa res | _ -> assert false) [] parameter_annotations in if List.length res <= List.length ms#descriptor#arguments then res else raise (JCH_class_structure_error (LBLOCK [ STR "The length of an Runtime(In)VisibleParameterAnnotations " ; STR "is longer than the number of arguments of the same method"])) in let class_method_signature = make_cms cs ms in make_concrete_method ~signature:ms ~class_method_signature ~is_static ~is_final ~is_synchronized ~is_strict ~access ?generic_signature:generic_signature ~is_bridge ~has_varargs:is_varargs ~is_synthetic ~other_flags:flags ~exceptions:exn ~attributes:(low2high_attributes consts other_att) ~annotations:(make_method_annotations ~global:annotations ~parameters:parameter_annotations) ~implementation:code () let low2high_interface_method consts cs ms = function m -> if List.exists (fun a -> match a with AttributeCode _ -> true | _ -> false) m.m_attributes then low2high_cmethod consts cs ms m else low2high_amethod consts cs ms m let low2high_acmethod consts cs ms = function m -> if List.exists ((=)AccAbstract) m.m_flags then low2high_amethod consts cs ms m else low2high_cmethod consts cs ms m let low2high_methods ?(interfacemethod=false) cn consts = function ac -> let cs = ac.rc_name in let methods = List.map (fun meth -> let isstatic = List.exists (fun f -> match f with AccStatic -> true | _ -> false) meth.m_flags in let ms = make_ms isstatic meth.m_name meth.m_descriptor in try if interfacemethod then low2high_interface_method consts cs ms meth else low2high_acmethod consts cs ms meth with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in method " ; STR (JCHDumpBasicTypes.signature meth.m_name (SMethod meth.m_descriptor)) ; STR ": " ; msg ]))) ac.rc_methods in let _ = if !debug > 0 then let mset = new MethodCollections.set_t in let _ = List.iter (fun m -> if mset#has m#get_signature then prerr_endline ("Warning: in " ^ cn#name ^ " two methods with the same signature (" ^ m#get_signature#to_string ^ ")") else mset#add m#get_signature) methods in () in methods let low2high_innerclass = function (inner_class_info,outer_class_info,inner_name,flags) -> let (access,flags) = flags2access flags in let (is_final,flags) = get_flag AccFinal flags in let (is_static,flags) = get_flag AccStatic flags in let (is_interface,flags) = get_flag AccInterface flags in let (is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_annotation,flags) = get_flag AccAnnotation flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> raise (Failure "unexpected flag")) flags in make_inner_class ?name:inner_class_info ?outer_class_name:outer_class_info ?source_name:inner_name ~access ~is_static ~is_final ~is_synthetic ~is_annotation ~is_enum ~other_flags:flags ~kind:(if is_interface then Interface else if is_abstract then Abstract else ConcreteClass) () let low2high_class cl = let java_lang_object = make_cn "java.lang.Object" in if cl.rc_super = None && (not (cl.rc_name#equal java_lang_object)) then raise (JCH_class_structure_error (STR "Only java.lang.Object is allowed not to have a super-class")); let cs = cl.rc_name in let flags = cl.rc_flags in let (access,flags) = flags2access flags in let (accsuper,flags) = get_flag AccSuper flags in let (is_final,flags) = get_flag AccFinal flags in let (is_interface,flags) = get_flag AccInterface flags in let (is_abstract,flags) = get_flag AccAbstract flags in let (is_synthetic,flags) = get_flag AccSynthetic flags in let (is_annotation,flags) = get_flag AccAnnotation flags in let (is_enum,flags) = get_flag AccEnum flags in let flags = List.map (function | AccRFU i -> i | _ -> raise (Failure "unexpected flag found")) flags in let _ = if not (JCHBasicTypes.is_permissive ()) && not (accsuper || is_interface) && not (accsuper && is_interface) then raise (JCH_class_structure_error (STR "ACC_SUPER must be set for all classes (that are not interfaces)")) in let _ = if not (JCHBasicTypes.is_permissive ()) && (is_final && is_abstract) then raise (JCH_class_structure_error (STR "An abstract class cannot be final")) in let consts = DynArray.of_array cl.rc_consts in let my_name = cl.rc_name in let my_version = cl.rc_version in let my_source_origin = cl.rc_origin in let my_md5_digest = cl.rc_md5 in let my_access = match access with | Public -> Public | Default -> Default | _ -> raise (JCH_class_structure_error (STR "Invalid visibility for a class")) and my_interfaces = cl.rc_interfaces and my_sourcefile = let rec find_SourceFile = function | AttributeSourceFile s::_ -> Some s | _::l -> find_SourceFile l | [] -> None in find_SourceFile cl.rc_attributes and my_deprecated = List.exists ((=)AttributeDeprecated) cl.rc_attributes and my_generic_signature = match List.find_all (function AttributeSignature _ -> true | _ -> false) cl.rc_attributes with | [] -> None | (AttributeSignature s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then try Some (parse_class_signature s) with JCH_class_structure_error _ as e -> if JCHBasicTypes.is_permissive () then None else raise e else raise (JCH_class_structure_error (STR "A class or interface cannot have several Signature attributes")) | _ -> assert false and my_bootstrap_methods = match List.find_all (function AttributeBootstrapMethods _ -> true | _ -> false) cl.rc_attributes with | [] -> [] | [ AttributeBootstrapMethods l ] -> l | _ -> raise (JCH_class_structure_error (STR "A class or interface can only have one BootstrapMethod table")) and my_source_debug_extension = let sde_attributes = List.find_all (function AttributeSourceDebugExtension _ -> true | _ -> false) cl.rc_attributes in match sde_attributes with | [] -> None | (AttributeSourceDebugExtension s)::rest -> if rest = [] || JCHBasicTypes.is_permissive () then Some s else raise (JCH_class_structure_error (STR "A class cannot contain several SourceDebugExtension attribute")) | _ -> assert false and my_inner_classes = let rec find_InnerClasses = function | AttributeInnerClasses icl::_ -> List.rev_map low2high_innerclass icl | _::l -> find_InnerClasses l | [] -> [] in find_InnerClasses cl.rc_attributes and my_annotations = List.fold_right (fun annot annots -> match annot with | AttributeRuntimeVisibleAnnotations al -> List.fold_right (fun a annots -> (a,true)::annots) al annots | AttributeRuntimeInvisibleAnnotations al -> List.fold_right (fun a annots -> (a,false)::annots) al annots | _ -> annots) cl.rc_attributes [] and my_other_attributes = low2high_other_attributes consts (List.filter (function | AttributeSignature _ | AttributeSourceFile _ | AttributeSourceDebugExtension _ | AttributeRuntimeVisibleAnnotations _ | AttributeRuntimeInvisibleAnnotations _ | AttributeDeprecated | AttributeInnerClasses _ | AttributeBootstrapMethods _ -> false | AttributeEnclosingMethod _ -> is_interface | _ -> true) cl.rc_attributes); in if is_interface then begin if not (is_permissive ()) then begin (if not is_abstract then raise (JCH_class_structure_error (LBLOCK [ STR "A class file with its AccInterface flag set must " ; STR "also have its AccAbstract flag set"]))); (let obj = make_cn "java.lang.Object" in if not (cl.rc_super = Some obj) then raise (JCH_class_structure_error (STR "The super-class of interfaces must be java.lang.Object"))); if is_enum then raise (JCH_class_structure_error (LBLOCK [ STR "A class file with its AccInterface flag set must " ; STR "not have its their AccEnum flag set"])) end; let (init,methods) = match List.partition (fun m -> let clinit_name = clinit_signature#name in let clinit_desc = clinit_signature#descriptor in m.m_name = clinit_name && m.m_descriptor#arguments = clinit_desc#arguments) cl.rc_methods with | ([ m ],others) -> let ms = make_ms true m.m_name m.m_descriptor in (Some (low2high_cmethod consts cs ms m), others) | ([],others) -> (None, others) | m::_::_,others -> if not (JCHBasicTypes.is_permissive ()) then raise (JCH_class_structure_error (STR "has more than one class initializer <clinit>")) else (Some (low2high_cmethod consts cs clinit_signature m), others) in let fields = List.map (fun f -> let fs = make_fs f.f_name f.f_descriptor in try low2high_ifield my_name consts fs f with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "field " ; STR ((JCHDumpBasicTypes.signature f.f_name (SValue f.f_descriptor))) ; STR ": " ; msg ]))) cl.rc_fields in let _ = if !debug > 0 then let fset = new FieldCollections.set_t in List.iter (fun f -> if fset#has f#get_signature then prerr_endline ("Warning: in " ^ my_name#name ^ " two fields have the same signature (" ^ f#get_signature#to_string ^ ")") else fset#add f#get_signature) fields in let methods = List.map (fun meth -> let isstatic = List.exists (fun f -> match f with AccStatic -> true | _ -> false) meth.m_flags in let ms = make_ms isstatic meth.m_name meth.m_descriptor in try low2high_interface_method consts cs ms meth with JCH_class_structure_error msg -> let sign = JCHDumpBasicTypes.signature meth.m_name (SMethod meth.m_descriptor) in raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ; STR ": method " ; STR sign ; STR ": " ; msg ]))) methods in let _ = if !debug > 0 then let mset = new MethodCollections.set_t in List.iter (fun m -> if mset#has m#get_signature then prerr_endline ("Warning: in " ^ my_name#name ^ " two methods have the same signature (" ^ m#get_signature#to_string ^ ")") else mset#add m#get_signature) methods in (make_java_interface ~name:my_name ~version:my_version ~access:my_access ~generic_signature:my_generic_signature ~interfaces:my_interfaces ~consts:(DynArray.to_array consts) ?source_file:my_sourcefile ~source_origin:my_source_origin ~md5_digest:my_md5_digest ~is_deprecated:my_deprecated ?source_debug_extension:my_source_debug_extension ~inner_classes:my_inner_classes ~other_attributes:my_other_attributes ?initializer_method:init ~is_annotation:is_annotation ~annotations:my_annotations ~bootstrapmethods:my_bootstrap_methods ~other_flags:flags ~fields ~methods () :> java_class_or_interface_int) end else begin if is_annotation then raise (JCH_class_structure_error (LBLOCK [ STR "Class file with their AccAnnotation flag set must also " ; STR "have their AccInterface flag set"])); let my_enclosing_method = let enclosing_method_atts = List.find_all (function AttributeEnclosingMethod _ -> true | _ -> false) cl.rc_attributes in match enclosing_method_atts with | [] -> None | [AttributeEnclosingMethod (cs,mso)] -> let ms = match mso with | None -> None | Some (mn,SMethod mdesc) -> Some (make_ms false mn mdesc) | Some (_,SValue _) -> raise (JCH_class_structure_error (LBLOCK [ STR "A EnclosingMethod attribute cannot specify " ; STR "a field as enclosing method"])) in Some (cs, ms) | _ -> raise (JCH_class_structure_error (LBLOCK [ STR "A EnclosingMethod attribute can only be " ; STR "specified at most once per class"])) and my_methods = try low2high_methods my_name consts cl with | JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ;STR ": " ; msg ])) and my_fields = List.map (fun f -> let fs = make_fs f.f_name f.f_descriptor in try low2high_cfield my_name consts fs f with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [ STR "in class " ; STR my_name#name ; STR ": in field " ; STR (JCHDumpBasicTypes.signature f.f_name (SValue f.f_descriptor)) ; STR ": " ; msg ]))) cl.rc_fields in (make_java_class ~name:my_name ~version:my_version ~super_class:cl.rc_super ~generic_signature:my_generic_signature ~is_final:is_final ~is_abstract:is_abstract ~access:my_access ~is_synthetic:is_synthetic ~is_enum:is_enum ~other_flags:flags ~interfaces:my_interfaces ~consts:(DynArray.to_array consts) ?source_file:my_sourcefile ~source_origin:my_source_origin ~md5_digest:my_md5_digest ~is_deprecated:my_deprecated ?source_debug_extension:my_source_debug_extension ?enclosing_method:my_enclosing_method ~annotations:my_annotations ~bootstrapmethods:my_bootstrap_methods ~inner_classes:my_inner_classes ~other_attributes:my_other_attributes ~fields:my_fields ~methods:my_methods () :> java_class_or_interface_int) end let low2high_class cl = try low2high_class cl with JCH_class_structure_error msg -> raise (JCH_class_structure_error (LBLOCK [STR "In " ; STR cl.rc_name#name ; STR ": " ; msg]))
ac8decac4739c94ee1d572e7495f41c383e880eca0d3ab5870ebe68dd661be34
Ptival/language-ocaml
Test.hs
# LANGUAGE QuasiQuotes # module Language.OCaml.Parser.ValIdent.Test ( testStrings, ) where import Data.String.Interpolate import qualified Language.OCaml.Parser.Operator.Test as Operator testStrings :: [String] testStrings = [] ++ ["foo"] ++ [[i|(#{op})|] | op <- Operator.testStrings]
null
https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/test/Language/OCaml/Parser/ValIdent/Test.hs
haskell
# LANGUAGE QuasiQuotes # module Language.OCaml.Parser.ValIdent.Test ( testStrings, ) where import Data.String.Interpolate import qualified Language.OCaml.Parser.Operator.Test as Operator testStrings :: [String] testStrings = [] ++ ["foo"] ++ [[i|(#{op})|] | op <- Operator.testStrings]
b003945790d3767f83b0a36cfe80cd817d5cde2c0b62157d238e70062d968668
0xYUANTI/huckleberry
huck_server.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% @doc A Raft replica. %%% This code is based on the TLA+ specification of the algorithm. C.f . priv / proof.pdf %%% @end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%_* Module declaration =============================================== -module(huck_server). -behaviour(gen_server). %%%_* Exports ========================================================== %% Process API -export([ start_link/1 , stop/0 ]). %% Client API -export([ read/1 , write/1 ]). %% gen_server callbacks -export([ code_change/3 , handle_call/3 , handle_cast/2 , handle_info/2 , init/1 , terminate/2 ]). %%%_* Includes ========================================================= -include("huck.hrl"). %%%_* Macros =========================================================== -define(SERVER, ?MODULE). %%%_* Code ============================================================= %%%_ * Process API ----------------------------------------------------- start_link(Args) -> gen_server:start_link({local, ?SERVER}, ?MODULE, Args, []). stop() -> gen_server:call(?SERVER, stop, infinity). %%%_ * Client API ------------------------------------------------------ -spec read(cmd()) -> ret(). read(Cmd) -> gen_server:call(?SERVER, {read, Cmd}, infinity). -spec write(cmd()) -> ret(). write(Cmd) -> gen_server:call(?SERVER, {write, Cmd}, infinity). %%%_ * gen_server callbacks -------------------------------------------- init(Args) -> {ok, do_init(Args)}. terminate(_Rsn, #s{}) -> ok. code_change(_OldVsn, S, _Extra) -> {ok, S}. handle_call({read, Cmd}, _From, S0) -> {Reply, S} = do_read(Cmd, S0), {reply, Reply, S}; handle_call({write, Cmd}, _From, S0) -> {Reply, S} = do_write(Cmd, S0), {reply, Reply, S}; handle_call(stop, _From, S) -> {stop, normal, ok, S}. handle_cast(_Req, S) -> {stop, bad_cast, S}. handle_info(timeout, S) -> {noreply, do_timeout(S)}; handle_info(#msg{} = Msg, S) -> {noreply, do_msg(Msg, S)}; handle_info(Info, S) -> ?warning("~p", [Info]), {noreply, S}. %%%_ * Internals ------------------------------------------------------- %%%_ * do_init/1 ------------------------------------------------------ -spec do_init(args()) -> #s{} | no_return(). @doc Init and Restart ( ) . do_init(Args) -> {ok, Replicas} = s2_env:get_arg(Args, ?APP, replicas), {ok, Callback} = s2_env:get_arg(Args, ?APP, callback), #s{ replicas = [node()|Replicas] , timer = huck_timer:start(election) , current_term = huck_local_storage:get(current_term, 1) , state = follower , voted_for = huck_local_storage:get(voted_for, '') , votes_responded = [] , votes_granted = [] , next_index = [{Replica, 1} || Replica <- Replicas] , last_agree_index = [{Replica, 0} || Replica <- Replicas] , log = huck_log:new(Callback) , commit_index = 0 }. %%%_ * do_read/2, do_write/2 ------------------------------------------ -spec do_read(cmd(), #s{}) -> {ret(), #s{}}. %% @doc do_read(Cmd, S) -> ok. -spec do_write(cmd(), #s{}) -> {ret(), #s{}}. %% @doc do_write(Cmd, S) -> ok. client_request(V, #s{log=Log} = S) -> ?hence(S#s.state =:= leader), Entry = #entry{term=S#s.current_term, value=V}, NewIndex = huck_log:length(Log) + 1, huck_log:append(Log, Entry). %%%_ * append_entries/2 ---------------------------------------------- append_entries(#s{log=Log} = S) -> ?hence(S#s.state =:= leader), [begin {ok, NextIndex} = s2_lists:assoc(S#s.next_index, Node), PrevLogIndex = NextIndex - 1, PrevLogTerm = if PrevLogIndex > 0 -> (huck_log:nth(Log, PrevLogIndex))#entry.term; true -> 0 end, LastEntry = min(huck_log:length(Log), NextIndex + 1), Entries = huck_log:nthtail(Log, NextIndex), send(Node, #msg{ term = S#s.current_term , payload = #append_req{ prev_log_index = PrevLogIndex , prev_log_term = PrevLogTerm , entries = Entries , commit_index = min(S#s.commit_index, LastEntry) } }) end || Node <- Replicas], S. %%%_ * do_timeout/1 --------------------------------------------------- -spec do_timeout(#s{}) -> #s{}. do_timeout(S) -> request_vote(timeout(S)). timeout(#s{state=State, current_term=CurrentTerm} = S) -> ?hence(State =:= follower orelse State =:= candidate), huck_local_storage:put(voted_for, node()), S#s{ state = candidate , current_term = CurrentTerm + 1 , voted_for = node() , votes_responded = [node()] , votes_granted = [node()] }. request_vote(#s{log=Log} = S) -> ?hence(S#s.state =:= candidate), [send(Node, #msg{ term = S#s.current_term , payload = #vote_req{ last_log_term = last_term(Log) , last_log_index = huck_log:length(Log) } }) || Node <- S#s.replicas, not lists:member(Node, S#s.votes_responded)], S. %%%_ * do_msg/2 ------------------------------------------------------- -spec do_msg(#msg{}, #s{}) -> #s{}. @doc Receive , DropStaleResponse ( ) . do_msg(#msg{payload=Payload} = Msg, #s{} = S0) -> S = update_term(Msg, S0), drop_stale(Msg, S) orelse case Payload of #vote_req{} -> handle_vote_req(Msg, S); #vote_resp{} -> handle_vote_resp(Msg, S); #append_req{} -> handle_append_req(Msg, S); #append_resp{} -> handle_append_resp(Msg, S) end. update_term(#msg{term=Term}, #s{current_term=CurrentTerm} = S) -> case Term > CurrentTerm of true -> huck_local_storage:put(current_term, Term), huck_local_storage:put(vote_for, ''), S#s{current_term=Term, state=follower, voted_for=''}; false -> S end. drop_stale(#msg{term=Term, payload=Payload}, #s{current_term=CurrentTerm}) -> (is_record(Payload, vote_resp) orelse is_record(Payload, append_resp)) andalso Term < CurrentTerm. %%%_ * handle_vote_resp/2 -------------------------------------------- become_leader(#s{replicas=Replicas} = S) -> ?hence(S#s.state =:= candidate), ?hence(is_quorum(S#s.votes_granted, Replicas)), S#s{ state = leader , next_index = [{R, huck_log:length(S#s.log) + 1} || R <- Replicas] , last_agree_index = [{R, 0} || R <- Replicas] }. %% HandleRequestVoteRequest() handle_vote_req(#msg{source=Source, term=Term} = Msg, #s{current_term=CurrentTerm} = S) -> ?hence(Term =< CurrentTerm), Grant = Term =:= CurrentTerm andalso log_is_current(Msg#msg.payload, S#s.log) andalso lists:member(S#s.voted_for, ['', Source]), send(Source, #msg{ term = CurrentTerm , payload = #vote_resp{vote_granted=Grant} }), if Grant -> S#s{voted_for=Source}; true -> S end. log_is_current(#vote_req{ last_log_term = LastLogTerm , last_log_index = LastLogIndex }, Log) -> (LastLogTerm > last_term(Log)) orelse (LastLogTerm =:= last_term(Log) andalso LastLogIndex >= huck_log:length(Log)). %% HandleRequestVoteResponse() handle_vote_resp(#msg{source=Source} = Msg, #s{votes_granted=VotesGranted} = S) -> ?hence(Msg#msg.term =:= S#s.current_term), S#s{ votes_responded = [Source|S#s.votes_responded] , votes_granted = if (Msg#msg.payload)#vote_resp.vote_granted -> [Source|VotesGranted]; true -> VotesGranted end }. %% HandleAppendEntriesRequest() handle_append_req(#msg{source=Source, term=Term} = Msg, #s{current_term=CurrentTerm} = S) -> ?hence(Term =< CurrentTerm), case accept(Msg, S) of false -> send(Source, #msg{term=CurrentTerm, payload=#append_resp{last_agree_index=0}}); true -> Index = (Msg#msg.payload)#append_req.prev_log_index + 1, Length = huck_log:length(Log), LogTerm = (huck_log:nth(Log, Index))#entry.term, Entries = (Msg#msg.payload)#append_req.entries, case {Entries, Length >= Index, (catch LogTerm =:= (hd(Entries))#entry.term)} of {A, B, C} when A =:= [] ; B =:= true andalso C =:= true -> send(Source, #msg{term=CurrentTerm, payload=#append_resp{last_agree_index=PrevLogIndex+length(Entries)}}), S#s{commit_index=(Msg#msg.payload)#append_req.commit_index}; {_, true, false} -> huck_log:truncate(Log, Length-1), S; {_, _, _} when Length =:= Index -> huck_log:append(Log, Entries), S end end. accept(#msg{ term = Term , payload = #append_req{ prev_log_index = PrevLogIndex , prev_log_term = PrevLogTerm } }, #s{ current_term = CurrentTerm , log = Log }) -> Term =:= CurrentTerm andalso (PrevLogIndex =:= 0 orelse (PrevLogIndex > 0 andalso PrevLogIndex =< huck_log:length(Log) andalso PrevLogTerm =:= (huck_log:nth(Log, PrevLogIndex))#entry.term)). handle_append_resp(#msg{from=From, term=Term, payload=Payload}, #s{current_term=CurrentTerm}) -> #append_resp{last_agree_index=LastAgreeIndex} = Payload, ?hence(Term =:= CurrentTerm), case LastAgreeIndex of N when N > 0 -> S#s{ next_index = update(NextIndex, From, LastAgreeIndex + 1) , last_agree_index = update(LastAgreeIndex, From, LastAgreeIndex) , commit_index = case agree_indices(S) of [_|_] = Is when (huck_log:nth(max(Is)))#entry.term = CurrenTerm -> max(Is); _ -> S#s.commit_index end }; 0 -> S#s{next_index=update(NextIndex, From, max(assoc(NextIndex, From) - 1, 1))} end. agree_indices(S) -> [I || I <- lists:seq(1, huck_log:length(Log)), is_quorum(agree(I))]. agree(I, S) -> [R || R <- S#s.replicas, s2_lists:asspc(S#s.last_agree_index, R) >= I]. %%%_ * Helpers -------------------------------------------------------- is_quorum(X, Replicas) -> length(X) * 2 > length(Replicas). last_term(Log) -> case huck_log:length(Log) of 0 -> 0; _ -> (huck_log:last(Log))#entry.term end. send(Node, Msg) -> {?SERVER, Node} ! Msg. %%%_* Tests ============================================================ -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. %%%_* Emacs ============================================================ %%% Local Variables: %%% allout-layout: t erlang - indent - level : 2 %%% End:
null
https://raw.githubusercontent.com/0xYUANTI/huckleberry/1df7d611b509a725140b048f444e820c044fb807/src/huck_server.erl
erlang
@doc A Raft replica. This code is based on the TLA+ specification of the algorithm. @end _* Module declaration =============================================== _* Exports ========================================================== Process API Client API gen_server callbacks _* Includes ========================================================= _* Macros =========================================================== _* Code ============================================================= _ * Process API ----------------------------------------------------- _ * Client API ------------------------------------------------------ _ * gen_server callbacks -------------------------------------------- _ * Internals ------------------------------------------------------- _ * do_init/1 ------------------------------------------------------ _ * do_read/2, do_write/2 ------------------------------------------ @doc @doc _ * append_entries/2 ---------------------------------------------- _ * do_timeout/1 --------------------------------------------------- _ * do_msg/2 ------------------------------------------------------- _ * handle_vote_resp/2 -------------------------------------------- HandleRequestVoteRequest() HandleRequestVoteResponse() HandleAppendEntriesRequest() _ * Helpers -------------------------------------------------------- _* Tests ============================================================ _* Emacs ============================================================ Local Variables: allout-layout: t End:
C.f . priv / proof.pdf -module(huck_server). -behaviour(gen_server). -export([ start_link/1 , stop/0 ]). -export([ read/1 , write/1 ]). -export([ code_change/3 , handle_call/3 , handle_cast/2 , handle_info/2 , init/1 , terminate/2 ]). -include("huck.hrl"). -define(SERVER, ?MODULE). start_link(Args) -> gen_server:start_link({local, ?SERVER}, ?MODULE, Args, []). stop() -> gen_server:call(?SERVER, stop, infinity). -spec read(cmd()) -> ret(). read(Cmd) -> gen_server:call(?SERVER, {read, Cmd}, infinity). -spec write(cmd()) -> ret(). write(Cmd) -> gen_server:call(?SERVER, {write, Cmd}, infinity). init(Args) -> {ok, do_init(Args)}. terminate(_Rsn, #s{}) -> ok. code_change(_OldVsn, S, _Extra) -> {ok, S}. handle_call({read, Cmd}, _From, S0) -> {Reply, S} = do_read(Cmd, S0), {reply, Reply, S}; handle_call({write, Cmd}, _From, S0) -> {Reply, S} = do_write(Cmd, S0), {reply, Reply, S}; handle_call(stop, _From, S) -> {stop, normal, ok, S}. handle_cast(_Req, S) -> {stop, bad_cast, S}. handle_info(timeout, S) -> {noreply, do_timeout(S)}; handle_info(#msg{} = Msg, S) -> {noreply, do_msg(Msg, S)}; handle_info(Info, S) -> ?warning("~p", [Info]), {noreply, S}. -spec do_init(args()) -> #s{} | no_return(). @doc Init and Restart ( ) . do_init(Args) -> {ok, Replicas} = s2_env:get_arg(Args, ?APP, replicas), {ok, Callback} = s2_env:get_arg(Args, ?APP, callback), #s{ replicas = [node()|Replicas] , timer = huck_timer:start(election) , current_term = huck_local_storage:get(current_term, 1) , state = follower , voted_for = huck_local_storage:get(voted_for, '') , votes_responded = [] , votes_granted = [] , next_index = [{Replica, 1} || Replica <- Replicas] , last_agree_index = [{Replica, 0} || Replica <- Replicas] , log = huck_log:new(Callback) , commit_index = 0 }. -spec do_read(cmd(), #s{}) -> {ret(), #s{}}. do_read(Cmd, S) -> ok. -spec do_write(cmd(), #s{}) -> {ret(), #s{}}. do_write(Cmd, S) -> ok. client_request(V, #s{log=Log} = S) -> ?hence(S#s.state =:= leader), Entry = #entry{term=S#s.current_term, value=V}, NewIndex = huck_log:length(Log) + 1, huck_log:append(Log, Entry). append_entries(#s{log=Log} = S) -> ?hence(S#s.state =:= leader), [begin {ok, NextIndex} = s2_lists:assoc(S#s.next_index, Node), PrevLogIndex = NextIndex - 1, PrevLogTerm = if PrevLogIndex > 0 -> (huck_log:nth(Log, PrevLogIndex))#entry.term; true -> 0 end, LastEntry = min(huck_log:length(Log), NextIndex + 1), Entries = huck_log:nthtail(Log, NextIndex), send(Node, #msg{ term = S#s.current_term , payload = #append_req{ prev_log_index = PrevLogIndex , prev_log_term = PrevLogTerm , entries = Entries , commit_index = min(S#s.commit_index, LastEntry) } }) end || Node <- Replicas], S. -spec do_timeout(#s{}) -> #s{}. do_timeout(S) -> request_vote(timeout(S)). timeout(#s{state=State, current_term=CurrentTerm} = S) -> ?hence(State =:= follower orelse State =:= candidate), huck_local_storage:put(voted_for, node()), S#s{ state = candidate , current_term = CurrentTerm + 1 , voted_for = node() , votes_responded = [node()] , votes_granted = [node()] }. request_vote(#s{log=Log} = S) -> ?hence(S#s.state =:= candidate), [send(Node, #msg{ term = S#s.current_term , payload = #vote_req{ last_log_term = last_term(Log) , last_log_index = huck_log:length(Log) } }) || Node <- S#s.replicas, not lists:member(Node, S#s.votes_responded)], S. -spec do_msg(#msg{}, #s{}) -> #s{}. @doc Receive , DropStaleResponse ( ) . do_msg(#msg{payload=Payload} = Msg, #s{} = S0) -> S = update_term(Msg, S0), drop_stale(Msg, S) orelse case Payload of #vote_req{} -> handle_vote_req(Msg, S); #vote_resp{} -> handle_vote_resp(Msg, S); #append_req{} -> handle_append_req(Msg, S); #append_resp{} -> handle_append_resp(Msg, S) end. update_term(#msg{term=Term}, #s{current_term=CurrentTerm} = S) -> case Term > CurrentTerm of true -> huck_local_storage:put(current_term, Term), huck_local_storage:put(vote_for, ''), S#s{current_term=Term, state=follower, voted_for=''}; false -> S end. drop_stale(#msg{term=Term, payload=Payload}, #s{current_term=CurrentTerm}) -> (is_record(Payload, vote_resp) orelse is_record(Payload, append_resp)) andalso Term < CurrentTerm. become_leader(#s{replicas=Replicas} = S) -> ?hence(S#s.state =:= candidate), ?hence(is_quorum(S#s.votes_granted, Replicas)), S#s{ state = leader , next_index = [{R, huck_log:length(S#s.log) + 1} || R <- Replicas] , last_agree_index = [{R, 0} || R <- Replicas] }. handle_vote_req(#msg{source=Source, term=Term} = Msg, #s{current_term=CurrentTerm} = S) -> ?hence(Term =< CurrentTerm), Grant = Term =:= CurrentTerm andalso log_is_current(Msg#msg.payload, S#s.log) andalso lists:member(S#s.voted_for, ['', Source]), send(Source, #msg{ term = CurrentTerm , payload = #vote_resp{vote_granted=Grant} }), if Grant -> S#s{voted_for=Source}; true -> S end. log_is_current(#vote_req{ last_log_term = LastLogTerm , last_log_index = LastLogIndex }, Log) -> (LastLogTerm > last_term(Log)) orelse (LastLogTerm =:= last_term(Log) andalso LastLogIndex >= huck_log:length(Log)). handle_vote_resp(#msg{source=Source} = Msg, #s{votes_granted=VotesGranted} = S) -> ?hence(Msg#msg.term =:= S#s.current_term), S#s{ votes_responded = [Source|S#s.votes_responded] , votes_granted = if (Msg#msg.payload)#vote_resp.vote_granted -> [Source|VotesGranted]; true -> VotesGranted end }. handle_append_req(#msg{source=Source, term=Term} = Msg, #s{current_term=CurrentTerm} = S) -> ?hence(Term =< CurrentTerm), case accept(Msg, S) of false -> send(Source, #msg{term=CurrentTerm, payload=#append_resp{last_agree_index=0}}); true -> Index = (Msg#msg.payload)#append_req.prev_log_index + 1, Length = huck_log:length(Log), LogTerm = (huck_log:nth(Log, Index))#entry.term, Entries = (Msg#msg.payload)#append_req.entries, case {Entries, Length >= Index, (catch LogTerm =:= (hd(Entries))#entry.term)} of {A, B, C} when A =:= [] ; B =:= true andalso C =:= true -> send(Source, #msg{term=CurrentTerm, payload=#append_resp{last_agree_index=PrevLogIndex+length(Entries)}}), S#s{commit_index=(Msg#msg.payload)#append_req.commit_index}; {_, true, false} -> huck_log:truncate(Log, Length-1), S; {_, _, _} when Length =:= Index -> huck_log:append(Log, Entries), S end end. accept(#msg{ term = Term , payload = #append_req{ prev_log_index = PrevLogIndex , prev_log_term = PrevLogTerm } }, #s{ current_term = CurrentTerm , log = Log }) -> Term =:= CurrentTerm andalso (PrevLogIndex =:= 0 orelse (PrevLogIndex > 0 andalso PrevLogIndex =< huck_log:length(Log) andalso PrevLogTerm =:= (huck_log:nth(Log, PrevLogIndex))#entry.term)). handle_append_resp(#msg{from=From, term=Term, payload=Payload}, #s{current_term=CurrentTerm}) -> #append_resp{last_agree_index=LastAgreeIndex} = Payload, ?hence(Term =:= CurrentTerm), case LastAgreeIndex of N when N > 0 -> S#s{ next_index = update(NextIndex, From, LastAgreeIndex + 1) , last_agree_index = update(LastAgreeIndex, From, LastAgreeIndex) , commit_index = case agree_indices(S) of [_|_] = Is when (huck_log:nth(max(Is)))#entry.term = CurrenTerm -> max(Is); _ -> S#s.commit_index end }; 0 -> S#s{next_index=update(NextIndex, From, max(assoc(NextIndex, From) - 1, 1))} end. agree_indices(S) -> [I || I <- lists:seq(1, huck_log:length(Log)), is_quorum(agree(I))]. agree(I, S) -> [R || R <- S#s.replicas, s2_lists:asspc(S#s.last_agree_index, R) >= I]. is_quorum(X, Replicas) -> length(X) * 2 > length(Replicas). last_term(Log) -> case huck_log:length(Log) of 0 -> 0; _ -> (huck_log:last(Log))#entry.term end. send(Node, Msg) -> {?SERVER, Node} ! Msg. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. erlang - indent - level : 2
ab6f781913f305588a7d3035fb5264b7930d44bf895c85cd80b583cd80bca499
fpottier/pprint
PPrint.ml
(******************************************************************************) (* *) PPrint (* *) , (* *) Copyright 2007 - 2022 Inria . All rights reserved . This file is distributed under the terms of the GNU Library General Public (* License, with an exception, as described in the file LICENSE. *) (* *) (******************************************************************************) include PPrintEngine (* -------------------------------------------------------------------------- *) (* Predefined single-character documents. *) let lparen = char '(' let rparen = char ')' let langle = char '<' let rangle = char '>' let lbrace = char '{' let rbrace = char '}' let lbracket = char '[' let rbracket = char ']' let squote = char '\'' let dquote = char '"' let bquote = char '`' let semi = char ';' let colon = char ':' let comma = char ',' let dot = char '.' let sharp = char '#' let slash = char '/' let backslash = char '\\' let equals = char '=' let qmark = char '?' let tilde = char '~' let at = char '@' let percent = char '%' let dollar = char '$' let caret = char '^' let ampersand = char '&' let star = char '*' let plus = char '+' let minus = char '-' let underscore = char '_' let bang = char '!' let bar = char '|' (* -------------------------------------------------------------------------- *) (* Repetition. *) let twice doc = doc ^^ doc let repeat n doc = let rec loop n doc accu = if n = 0 then accu else loop (n - 1) doc (doc ^^ accu) in loop n doc empty (* -------------------------------------------------------------------------- *) Delimiters . let precede l x = l ^^ x let terminate r x = x ^^ r let enclose l r x = l ^^ x ^^ r let squotes = enclose squote squote let dquotes = enclose dquote dquote let bquotes = enclose bquote bquote let braces = enclose lbrace rbrace let parens = enclose lparen rparen let angles = enclose langle rangle let brackets = enclose lbracket rbracket (* -------------------------------------------------------------------------- *) (* Some functions on lists. *) (* A variant of [fold_left] that keeps track of the element index. *) let foldli (f : int -> 'b -> 'a -> 'b) (accu : 'b) (xs : 'a list) : 'b = let r = ref 0 in List.fold_left (fun accu x -> let i = !r in r := i + 1; f i accu x ) accu xs (* -------------------------------------------------------------------------- *) (* Working with lists of documents. *) let concat docs = (* We take advantage of the fact that [^^] operates in constant time, regardless of the size of its arguments. The document that is constructed is essentially a reversed list (i.e., a tree that is biased towards the left). This is not a problem; when pretty-printing this document, the engine will descend along the left branch, pushing the nodes onto its stack as it goes down, effectively reversing the list again. *) List.fold_left (^^) empty docs let separate sep docs = foldli (fun i accu doc -> if i = 0 then doc else accu ^^ sep ^^ doc ) empty docs let concat_map f xs = List.fold_left (fun accu x -> accu ^^ f x ) empty xs let separate_map sep f xs = foldli (fun i accu x -> if i = 0 then f x else accu ^^ sep ^^ f x ) empty xs let separate2 sep last_sep docs = let n = List.length docs in foldli (fun i accu doc -> if i = 0 then doc else accu ^^ (if i < n - 1 then sep else last_sep) ^^ doc ) empty docs let optional f = function | None -> empty | Some x -> f x (* -------------------------------------------------------------------------- *) (* Text. *) (* This variant of [String.index_from] returns an option. *) let index_from s i c = try Some (String.index_from s i c) with Not_found -> None (* [lines s] chops the string [s] into a list of lines, which are turned into documents. *) let lines s = let rec chop accu i = match index_from s i '\n' with | Some j -> let accu = substring s i (j - i) :: accu in chop accu (j + 1) | None -> substring s i (String.length s - i) :: accu in List.rev (chop [] 0) let arbitrary_string s = separate (break 1) (lines s) [ split ok s ] splits the string [ s ] at every occurrence of a character that satisfies the predicate [ ok ] . The substrings thus obtained are turned into documents , and a list of documents is returned . No information is lost : the concatenation of the documents yields the original string . This code is not UTF-8 aware . that satisfies the predicate [ok]. The substrings thus obtained are turned into documents, and a list of documents is returned. No information is lost: the concatenation of the documents yields the original string. This code is not UTF-8 aware. *) let split ok s = let n = String.length s in let rec index_from i = if i = n then None else if ok s.[i] then Some i else index_from (i + 1) in let rec chop accu i = match index_from i with | Some j -> let accu = substring s i (j - i) :: accu in let accu = char s.[j] :: accu in chop accu (j + 1) | None -> substring s i (String.length s - i) :: accu in List.rev (chop [] 0) (* [words s] chops the string [s] into a list of words, which are turned into documents. *) let words s = let n = String.length s in A two - state finite automaton . In this state , we have skipped at least one blank character . let rec skipping accu i = if i = n then (* There was whitespace at the end. Drop it. *) accu else match s.[i] with | ' ' | '\t' | '\n' | '\r' -> (* Skip more whitespace. *) skipping accu (i + 1) | _ -> (* Begin a new word. *) word accu i (i + 1) In this state , we have skipped at least one non - blank character . and word accu i j = if j = n then (* Final word. *) substring s i (j - i) :: accu else match s.[j] with | ' ' | '\t' | '\n' | '\r' -> (* A new word has been identified. *) let accu = substring s i (j - i) :: accu in skipping accu (j + 1) | _ -> (* Continue inside the current word. *) word accu i (j + 1) in List.rev (skipping [] 0) let flow_map sep f docs = foldli (fun i accu doc -> if i = 0 then f doc else accu ^^ (* This idiom allows beginning a new line if [doc] does not fit on the current line. *) group (sep ^^ f doc) ) empty docs let flow sep docs = flow_map sep (fun x -> x) docs let url s = flow (break 0) (split (function '/' | '.' -> true | _ -> false) s) (* -------------------------------------------------------------------------- *) (* Alignment and indentation. *) let hang i d = align (nest i d) let ( !^ ) = string let ( ^/^ ) x y = x ^^ break 1 ^^ y let prefix n b x y = group (x ^^ nest n (break b ^^ y)) let (^//^) = prefix 2 1 let jump n b y = group (nest n (break b ^^ y)) let infix n b op x y = prefix n b (x ^^ blank b ^^ op) y let surround n b opening contents closing = group (opening ^^ nest n ( break b ^^ contents) ^^ break b ^^ closing ) let soft_surround n b opening contents closing = group (opening ^^ nest n (group (break b) ^^ contents) ^^ group (break b ^^ closing)) let surround_separate n b void opening sep closing docs = match docs with | [] -> void | _ :: _ -> surround n b opening (separate sep docs) closing let surround_separate_map n b void opening sep closing f xs = match xs with | [] -> void | _ :: _ -> surround n b opening (separate_map sep f xs) closing (* -------------------------------------------------------------------------- *) (* Printing OCaml values. *) module OCaml = struct open Printf type constructor = string type type_name = string type record_field = string type tag = int (* -------------------------------------------------------------------------- *) (* This internal [sprintf]-like function produces a document. We use [string], as opposed to [arbitrary_string], because the strings that we produce will never contain a newline character. *) let dsprintf format = ksprintf string format (* -------------------------------------------------------------------------- *) prefers using this code as opposed to just [ sprintf " % g " ] or [ sprintf " % f " ] . The latter print [ inf ] and [ -inf ] , whereas OCaml understands [ infinity ] and [ neg_infinity ] . [ sprintf " % g " ] does not add a trailing dot when the number happens to be an integral number . [ sprintf " % F " ] seems to lose precision and ignores the precision modifier . [sprintf "%f"]. The latter print [inf] and [-inf], whereas OCaml understands [infinity] and [neg_infinity]. [sprintf "%g"] does not add a trailing dot when the number happens to be an integral number. [sprintf "%F"] seems to lose precision and ignores the precision modifier. *) let valid_float_lexeme (s : string) : string = let l = String.length s in let rec loop i = if i >= l then (* If we reach the end of the string and have found only characters in the set '0' .. '9' and '-', then this string will be considered as an integer literal by OCaml. Adding a trailing dot makes it a float literal. *) s ^ "." else match s.[i] with | '0' .. '9' | '-' -> loop (i + 1) | _ -> s in loop 0 (* This function constructs a string representation of a floating point number. This representation is supposed to be accepted by OCaml as a valid floating point literal. *) let float_representation (f : float) : string = match classify_float f with | FP_nan -> "nan" | FP_infinite -> if f < 0.0 then "neg_infinity" else "infinity" | _ -> (* Try increasing precisions and validate. *) let s = sprintf "%.12g" f in if f = float_of_string s then valid_float_lexeme s else let s = sprintf "%.15g" f in if f = float_of_string s then valid_float_lexeme s else sprintf "%.18g" f (* -------------------------------------------------------------------------- *) (* A few constants and combinators, used below. *) let some = string "Some" let none = string "None" let lbracketbar = string "[|" let rbracketbar = string "|]" let seq1 opening separator closing = surround_separate 2 0 (opening ^^ closing) opening (separator ^^ break 1) closing let seq2 opening separator closing = surround_separate_map 2 1 (opening ^^ closing) opening (separator ^^ break 1) closing (* -------------------------------------------------------------------------- *) (* The following functions are printers for many types of OCaml values. *) (* There is no protection against cyclic values. *) let tuple = seq1 lparen comma rparen let variant _ cons _ args = match args with | [] -> !^cons | _ :: _ -> !^cons ^^ tuple args let record _ fields = seq2 lbrace semi rbrace (fun (k, v) -> infix 2 1 equals !^k v) fields let option f = function | None -> none | Some x -> some ^^ tuple [f x] let list f xs = seq2 lbracket semi rbracket f xs let flowing_list f xs = group (lbracket ^^ space ^^ nest 2 ( flow_map (semi ^^ break 1) f xs ) ^^ space ^^ rbracket) let array f xs = seq2 lbracketbar semi rbracketbar f (Array.to_list xs) let flowing_array f xs = group (lbracketbar ^^ space ^^ nest 2 ( flow_map (semi ^^ break 1) f (Array.to_list xs) ) ^^ space ^^ rbracketbar) let ref f x = record "ref" ["contents", f !x] let float f = string (float_representation f) let int = dsprintf "%d" let int32 = dsprintf "%ld" let int64 = dsprintf "%Ld" let nativeint = dsprintf "%nd" let char = dsprintf "%C" let bool = dsprintf "%B" let unit = dsprintf "()" let string = dsprintf "%S" let unknown tyname _ = dsprintf "<abstr:%s>" tyname type representation = document end (* OCaml *)
null
https://raw.githubusercontent.com/fpottier/pprint/de9cc6364d33f63c7c279b12e99c8c5935f7ba08/src/PPrint.ml
ocaml
**************************************************************************** License, with an exception, as described in the file LICENSE. **************************************************************************** -------------------------------------------------------------------------- Predefined single-character documents. -------------------------------------------------------------------------- Repetition. -------------------------------------------------------------------------- -------------------------------------------------------------------------- Some functions on lists. A variant of [fold_left] that keeps track of the element index. -------------------------------------------------------------------------- Working with lists of documents. We take advantage of the fact that [^^] operates in constant time, regardless of the size of its arguments. The document that is constructed is essentially a reversed list (i.e., a tree that is biased towards the left). This is not a problem; when pretty-printing this document, the engine will descend along the left branch, pushing the nodes onto its stack as it goes down, effectively reversing the list again. -------------------------------------------------------------------------- Text. This variant of [String.index_from] returns an option. [lines s] chops the string [s] into a list of lines, which are turned into documents. [words s] chops the string [s] into a list of words, which are turned into documents. There was whitespace at the end. Drop it. Skip more whitespace. Begin a new word. Final word. A new word has been identified. Continue inside the current word. This idiom allows beginning a new line if [doc] does not fit on the current line. -------------------------------------------------------------------------- Alignment and indentation. -------------------------------------------------------------------------- Printing OCaml values. -------------------------------------------------------------------------- This internal [sprintf]-like function produces a document. We use [string], as opposed to [arbitrary_string], because the strings that we produce will never contain a newline character. -------------------------------------------------------------------------- If we reach the end of the string and have found only characters in the set '0' .. '9' and '-', then this string will be considered as an integer literal by OCaml. Adding a trailing dot makes it a float literal. This function constructs a string representation of a floating point number. This representation is supposed to be accepted by OCaml as a valid floating point literal. Try increasing precisions and validate. -------------------------------------------------------------------------- A few constants and combinators, used below. -------------------------------------------------------------------------- The following functions are printers for many types of OCaml values. There is no protection against cyclic values. OCaml
PPrint , Copyright 2007 - 2022 Inria . All rights reserved . This file is distributed under the terms of the GNU Library General Public include PPrintEngine let lparen = char '(' let rparen = char ')' let langle = char '<' let rangle = char '>' let lbrace = char '{' let rbrace = char '}' let lbracket = char '[' let rbracket = char ']' let squote = char '\'' let dquote = char '"' let bquote = char '`' let semi = char ';' let colon = char ':' let comma = char ',' let dot = char '.' let sharp = char '#' let slash = char '/' let backslash = char '\\' let equals = char '=' let qmark = char '?' let tilde = char '~' let at = char '@' let percent = char '%' let dollar = char '$' let caret = char '^' let ampersand = char '&' let star = char '*' let plus = char '+' let minus = char '-' let underscore = char '_' let bang = char '!' let bar = char '|' let twice doc = doc ^^ doc let repeat n doc = let rec loop n doc accu = if n = 0 then accu else loop (n - 1) doc (doc ^^ accu) in loop n doc empty Delimiters . let precede l x = l ^^ x let terminate r x = x ^^ r let enclose l r x = l ^^ x ^^ r let squotes = enclose squote squote let dquotes = enclose dquote dquote let bquotes = enclose bquote bquote let braces = enclose lbrace rbrace let parens = enclose lparen rparen let angles = enclose langle rangle let brackets = enclose lbracket rbracket let foldli (f : int -> 'b -> 'a -> 'b) (accu : 'b) (xs : 'a list) : 'b = let r = ref 0 in List.fold_left (fun accu x -> let i = !r in r := i + 1; f i accu x ) accu xs let concat docs = List.fold_left (^^) empty docs let separate sep docs = foldli (fun i accu doc -> if i = 0 then doc else accu ^^ sep ^^ doc ) empty docs let concat_map f xs = List.fold_left (fun accu x -> accu ^^ f x ) empty xs let separate_map sep f xs = foldli (fun i accu x -> if i = 0 then f x else accu ^^ sep ^^ f x ) empty xs let separate2 sep last_sep docs = let n = List.length docs in foldli (fun i accu doc -> if i = 0 then doc else accu ^^ (if i < n - 1 then sep else last_sep) ^^ doc ) empty docs let optional f = function | None -> empty | Some x -> f x let index_from s i c = try Some (String.index_from s i c) with Not_found -> None let lines s = let rec chop accu i = match index_from s i '\n' with | Some j -> let accu = substring s i (j - i) :: accu in chop accu (j + 1) | None -> substring s i (String.length s - i) :: accu in List.rev (chop [] 0) let arbitrary_string s = separate (break 1) (lines s) [ split ok s ] splits the string [ s ] at every occurrence of a character that satisfies the predicate [ ok ] . The substrings thus obtained are turned into documents , and a list of documents is returned . No information is lost : the concatenation of the documents yields the original string . This code is not UTF-8 aware . that satisfies the predicate [ok]. The substrings thus obtained are turned into documents, and a list of documents is returned. No information is lost: the concatenation of the documents yields the original string. This code is not UTF-8 aware. *) let split ok s = let n = String.length s in let rec index_from i = if i = n then None else if ok s.[i] then Some i else index_from (i + 1) in let rec chop accu i = match index_from i with | Some j -> let accu = substring s i (j - i) :: accu in let accu = char s.[j] :: accu in chop accu (j + 1) | None -> substring s i (String.length s - i) :: accu in List.rev (chop [] 0) let words s = let n = String.length s in A two - state finite automaton . In this state , we have skipped at least one blank character . let rec skipping accu i = if i = n then accu else match s.[i] with | ' ' | '\t' | '\n' | '\r' -> skipping accu (i + 1) | _ -> word accu i (i + 1) In this state , we have skipped at least one non - blank character . and word accu i j = if j = n then substring s i (j - i) :: accu else match s.[j] with | ' ' | '\t' | '\n' | '\r' -> let accu = substring s i (j - i) :: accu in skipping accu (j + 1) | _ -> word accu i (j + 1) in List.rev (skipping [] 0) let flow_map sep f docs = foldli (fun i accu doc -> if i = 0 then f doc else accu ^^ group (sep ^^ f doc) ) empty docs let flow sep docs = flow_map sep (fun x -> x) docs let url s = flow (break 0) (split (function '/' | '.' -> true | _ -> false) s) let hang i d = align (nest i d) let ( !^ ) = string let ( ^/^ ) x y = x ^^ break 1 ^^ y let prefix n b x y = group (x ^^ nest n (break b ^^ y)) let (^//^) = prefix 2 1 let jump n b y = group (nest n (break b ^^ y)) let infix n b op x y = prefix n b (x ^^ blank b ^^ op) y let surround n b opening contents closing = group (opening ^^ nest n ( break b ^^ contents) ^^ break b ^^ closing ) let soft_surround n b opening contents closing = group (opening ^^ nest n (group (break b) ^^ contents) ^^ group (break b ^^ closing)) let surround_separate n b void opening sep closing docs = match docs with | [] -> void | _ :: _ -> surround n b opening (separate sep docs) closing let surround_separate_map n b void opening sep closing f xs = match xs with | [] -> void | _ :: _ -> surround n b opening (separate_map sep f xs) closing module OCaml = struct open Printf type constructor = string type type_name = string type record_field = string type tag = int let dsprintf format = ksprintf string format prefers using this code as opposed to just [ sprintf " % g " ] or [ sprintf " % f " ] . The latter print [ inf ] and [ -inf ] , whereas OCaml understands [ infinity ] and [ neg_infinity ] . [ sprintf " % g " ] does not add a trailing dot when the number happens to be an integral number . [ sprintf " % F " ] seems to lose precision and ignores the precision modifier . [sprintf "%f"]. The latter print [inf] and [-inf], whereas OCaml understands [infinity] and [neg_infinity]. [sprintf "%g"] does not add a trailing dot when the number happens to be an integral number. [sprintf "%F"] seems to lose precision and ignores the precision modifier. *) let valid_float_lexeme (s : string) : string = let l = String.length s in let rec loop i = if i >= l then s ^ "." else match s.[i] with | '0' .. '9' | '-' -> loop (i + 1) | _ -> s in loop 0 let float_representation (f : float) : string = match classify_float f with | FP_nan -> "nan" | FP_infinite -> if f < 0.0 then "neg_infinity" else "infinity" | _ -> let s = sprintf "%.12g" f in if f = float_of_string s then valid_float_lexeme s else let s = sprintf "%.15g" f in if f = float_of_string s then valid_float_lexeme s else sprintf "%.18g" f let some = string "Some" let none = string "None" let lbracketbar = string "[|" let rbracketbar = string "|]" let seq1 opening separator closing = surround_separate 2 0 (opening ^^ closing) opening (separator ^^ break 1) closing let seq2 opening separator closing = surround_separate_map 2 1 (opening ^^ closing) opening (separator ^^ break 1) closing let tuple = seq1 lparen comma rparen let variant _ cons _ args = match args with | [] -> !^cons | _ :: _ -> !^cons ^^ tuple args let record _ fields = seq2 lbrace semi rbrace (fun (k, v) -> infix 2 1 equals !^k v) fields let option f = function | None -> none | Some x -> some ^^ tuple [f x] let list f xs = seq2 lbracket semi rbracket f xs let flowing_list f xs = group (lbracket ^^ space ^^ nest 2 ( flow_map (semi ^^ break 1) f xs ) ^^ space ^^ rbracket) let array f xs = seq2 lbracketbar semi rbracketbar f (Array.to_list xs) let flowing_array f xs = group (lbracketbar ^^ space ^^ nest 2 ( flow_map (semi ^^ break 1) f (Array.to_list xs) ) ^^ space ^^ rbracketbar) let ref f x = record "ref" ["contents", f !x] let float f = string (float_representation f) let int = dsprintf "%d" let int32 = dsprintf "%ld" let int64 = dsprintf "%Ld" let nativeint = dsprintf "%nd" let char = dsprintf "%C" let bool = dsprintf "%B" let unit = dsprintf "()" let string = dsprintf "%S" let unknown tyname _ = dsprintf "<abstr:%s>" tyname type representation = document
e9dd5284f742c5d542a36c445ac8c41c594d02e7ad58de666c3398bccd86d2ce
nikita-volkov/rebase
Safe.hs
module Rebase.Foreign.Safe ( module Foreign.Safe ) where import Foreign.Safe
null
https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Foreign/Safe.hs
haskell
module Rebase.Foreign.Safe ( module Foreign.Safe ) where import Foreign.Safe
4972f91a56a386be66a1e0de3195c6baac856e2df4d0f0c2b43f177a25789b50
webnf/webnf
ring_dev.clj
(ns webnf.ring-dev (:require [ring.util.response :refer [content-type response]] [clojure.pprint :refer [pprint *print-right-margin*]] [webnf.base :refer [pprint-str]] [clojure.tools.logging :as log])) (defn echo-handler "A simple echo handler for ring requests. PPrints the request to HTML." [req] (content-type (response (str "<!DOCTYPE html><html><body><pre>\nYour request was:\n\n" (.. (binding [*print-right-margin* 120] (pprint-str (update-in req [:body] slurp))) (replace "&" "&amp;") (replace "<" "&lt;") (replace ">" "&gt;") (replace "\"" "&quot;")) "</pre></body></html>")) "text/html")) (defn wrap-logging ([handler] (wrap-logging handler :trace)) ([handler level] (fn [{:keys [request-method uri query-string] :as req}] (try (let [resp (handler req)] (log/log "http.request" level nil (str (.toUpperCase (name request-method)) " " uri " " query-string \newline (pprint-str {:request req :response resp}))) resp) (catch Exception e (log/error e (str (.toUpperCase (name request-method)) " " uri " " query-string " : Exception during handling of request\n" (pprint-str req))) (throw e))))))
null
https://raw.githubusercontent.com/webnf/webnf/6a2ccaa755e6e40528eb13a5c36bae16ba4947e7/handler/src/clj/webnf/ring_dev.clj
clojure
"))
(ns webnf.ring-dev (:require [ring.util.response :refer [content-type response]] [clojure.pprint :refer [pprint *print-right-margin*]] [webnf.base :refer [pprint-str]] [clojure.tools.logging :as log])) (defn echo-handler "A simple echo handler for ring requests. PPrints the request to HTML." [req] (content-type (response (str "<!DOCTYPE html><html><body><pre>\nYour request was:\n\n" (.. (binding [*print-right-margin* 120] (pprint-str (update-in req [:body] slurp))) (replace "&" "&amp;") (replace "<" "&lt;") (replace ">" "&gt;") "</pre></body></html>")) "text/html")) (defn wrap-logging ([handler] (wrap-logging handler :trace)) ([handler level] (fn [{:keys [request-method uri query-string] :as req}] (try (let [resp (handler req)] (log/log "http.request" level nil (str (.toUpperCase (name request-method)) " " uri " " query-string \newline (pprint-str {:request req :response resp}))) resp) (catch Exception e (log/error e (str (.toUpperCase (name request-method)) " " uri " " query-string " : Exception during handling of request\n" (pprint-str req))) (throw e))))))
67b00f1e2ed6ad9e892979143933c3db7ece800ffbdd96463e33f0408e869877
jbclements/RSound
reverb.rkt
#lang typed/racket (require racket/flonum) (require/typed "network.rkt" [#:struct network/s ([ins : Index] [outs : Index] [maker : (-> (Float -> Float))])]) (require/typed "common.rkt" [default-sample-rate (Parameterof Real)]) ;; this file provides the "reverb" network (provide reverb) constants here from 1979 : uses a base delay of 100ms in seconds (define base-delay-frames (* base-delay (exact->inexact (default-sample-rate)))) (define d1 (inexact->exact (round base-delay-frames))) (define d2 (inexact->exact (round (* 1.1 d1)))) (define d3 (inexact->exact (round (* 1.2 d1)))) (define d4 (inexact->exact (round (* 1.3 d1)))) (define d5 (inexact->exact (round (* 1.4 d1)))) (define d6 (inexact->exact (round (* 1.5 d1)))) (define g11 0.46) (define g12 0.48) (define g13 0.50) (define g14 0.52) (define g15 0.53) (define g16 0.55) ( closer to 1.0 gives more ring ) (define g21 (* (- 1.0 g11) g-konst)) (define g22 (* (- 1.0 g12) g-konst)) (define g23 (* (- 1.0 g13) g-konst)) (define g24 (* (- 1.0 g14) g-konst)) (define g25 (* (- 1.0 g15) g-konst)) (define g26 (* (- 1.0 g16) g-konst)) ;; this function produces a function from floats to floats. (: starter (-> (Float -> Float))) (define starter (lambda () (define v1 (make-flvector (inexact->exact (round d1)) 0.0)) (define v2 (make-flvector (inexact->exact (round d2)) 0.0)) (define v3 (make-flvector (inexact->exact (round d3)) 0.0)) (define v4 (make-flvector (inexact->exact (round d4)) 0.0)) (define v5 (make-flvector (inexact->exact (round d5)) 0.0)) (define v6 (make-flvector (inexact->exact (round d6)) 0.0)) ;; the lpf midpoints (define mvec (make-flvector 6 0.0)) (define m1 0.0) ;(define m2 0.0) ;(define m3 0.0) ;(define m4 0.0) ;(define m5 0.0) ;(define m6 0.0) ;; the tap counters (define c1 0) (define c2 0) (define c3 0) (define c4 0) (define c5 0) (define c6 0) ;; the main feedback buffers (lambda (in) the first comb filter (define delayed1 (flvector-ref v1 c1)) (define midnode1 (fl+ delayed1 (fl* g11 m1))) (define out1 (fl+ (fl* g21 midnode1) in)) (flvector-set! v1 c1 out1) (define next-c1 (add1 c1)) (set! c1 (cond [(<= d1 next-c1) 0] [else next-c1])) (set! m1 midnode1) the second comb filter (define delayed2 (flvector-ref v2 c2)) (define midnode2 (fl+ delayed2 (fl* g12 (flvector-ref mvec 1)))) (define out2 (fl+ (fl* g22 midnode2) in)) (flvector-set! v2 c2 out2) (define next-c2 (add1 c2)) (set! c2 (cond [(<= d2 next-c2) 0] [else next-c2])) (flvector-set! mvec 1 midnode2) the third comb filter ( and so on ) (define delayed3 (flvector-ref v3 c3)) (define midnode3 (fl+ delayed3 (fl* g13 (flvector-ref mvec 2)))) (define out3 (fl+ (fl* g23 midnode3) in)) (flvector-set! v3 c3 out3) (define next-c3 (add1 c3)) (set! c3 (cond [(<= d3 next-c3) 0] [else next-c3])) (flvector-set! mvec 2 midnode3) (define delayed4 (flvector-ref v4 c4)) (define midnode4 (fl+ delayed4 (fl* g14 (flvector-ref mvec 3)))) (define out4 (fl+ (fl* g24 midnode4) in)) (flvector-set! v4 c4 out4) (define next-c4 (add1 c4)) (set! c4 (cond [(<= d4 next-c4) 0] [else next-c4])) (flvector-set! mvec 3 midnode4) (define delayed5 (flvector-ref v5 c5)) (define midnode5 (fl+ delayed5 (fl* g15 (flvector-ref mvec 4)))) (define out5 (fl+ (fl* g25 midnode5) in)) (flvector-set! v5 c5 out5) (define next-c5 (add1 c5)) (set! c5 (cond [(<= d5 next-c5) 0] [else next-c5])) (flvector-set! mvec 4 midnode5) (define delayed6 (flvector-ref v6 c6)) (define midnode6 (fl+ delayed6 (fl* g16 (flvector-ref mvec 5)))) (define out6 (fl+ (fl* g26 midnode6) in)) (flvector-set! v6 c6 out6) (define next-c6 (add1 c6)) (set! c6 (cond [(<= d6 next-c6) 0] [else next-c6])) (flvector-set! mvec 5 midnode6) (/ (+ out1 out2 out3 out4 out5 out6) 6.0)))) (: reverb network/s) (define reverb (network/s 1 1 starter))
null
https://raw.githubusercontent.com/jbclements/RSound/c699db1ffae4cf0185c46bdc059d7879d40614ce/rsound/reverb.rkt
racket
this file provides the "reverb" network this function produces a function from floats to floats. the lpf midpoints (define m2 0.0) (define m3 0.0) (define m4 0.0) (define m5 0.0) (define m6 0.0) the tap counters the main feedback buffers
#lang typed/racket (require racket/flonum) (require/typed "network.rkt" [#:struct network/s ([ins : Index] [outs : Index] [maker : (-> (Float -> Float))])]) (require/typed "common.rkt" [default-sample-rate (Parameterof Real)]) (provide reverb) constants here from 1979 : uses a base delay of 100ms in seconds (define base-delay-frames (* base-delay (exact->inexact (default-sample-rate)))) (define d1 (inexact->exact (round base-delay-frames))) (define d2 (inexact->exact (round (* 1.1 d1)))) (define d3 (inexact->exact (round (* 1.2 d1)))) (define d4 (inexact->exact (round (* 1.3 d1)))) (define d5 (inexact->exact (round (* 1.4 d1)))) (define d6 (inexact->exact (round (* 1.5 d1)))) (define g11 0.46) (define g12 0.48) (define g13 0.50) (define g14 0.52) (define g15 0.53) (define g16 0.55) ( closer to 1.0 gives more ring ) (define g21 (* (- 1.0 g11) g-konst)) (define g22 (* (- 1.0 g12) g-konst)) (define g23 (* (- 1.0 g13) g-konst)) (define g24 (* (- 1.0 g14) g-konst)) (define g25 (* (- 1.0 g15) g-konst)) (define g26 (* (- 1.0 g16) g-konst)) (: starter (-> (Float -> Float))) (define starter (lambda () (define v1 (make-flvector (inexact->exact (round d1)) 0.0)) (define v2 (make-flvector (inexact->exact (round d2)) 0.0)) (define v3 (make-flvector (inexact->exact (round d3)) 0.0)) (define v4 (make-flvector (inexact->exact (round d4)) 0.0)) (define v5 (make-flvector (inexact->exact (round d5)) 0.0)) (define v6 (make-flvector (inexact->exact (round d6)) 0.0)) (define mvec (make-flvector 6 0.0)) (define m1 0.0) (define c1 0) (define c2 0) (define c3 0) (define c4 0) (define c5 0) (define c6 0) (lambda (in) the first comb filter (define delayed1 (flvector-ref v1 c1)) (define midnode1 (fl+ delayed1 (fl* g11 m1))) (define out1 (fl+ (fl* g21 midnode1) in)) (flvector-set! v1 c1 out1) (define next-c1 (add1 c1)) (set! c1 (cond [(<= d1 next-c1) 0] [else next-c1])) (set! m1 midnode1) the second comb filter (define delayed2 (flvector-ref v2 c2)) (define midnode2 (fl+ delayed2 (fl* g12 (flvector-ref mvec 1)))) (define out2 (fl+ (fl* g22 midnode2) in)) (flvector-set! v2 c2 out2) (define next-c2 (add1 c2)) (set! c2 (cond [(<= d2 next-c2) 0] [else next-c2])) (flvector-set! mvec 1 midnode2) the third comb filter ( and so on ) (define delayed3 (flvector-ref v3 c3)) (define midnode3 (fl+ delayed3 (fl* g13 (flvector-ref mvec 2)))) (define out3 (fl+ (fl* g23 midnode3) in)) (flvector-set! v3 c3 out3) (define next-c3 (add1 c3)) (set! c3 (cond [(<= d3 next-c3) 0] [else next-c3])) (flvector-set! mvec 2 midnode3) (define delayed4 (flvector-ref v4 c4)) (define midnode4 (fl+ delayed4 (fl* g14 (flvector-ref mvec 3)))) (define out4 (fl+ (fl* g24 midnode4) in)) (flvector-set! v4 c4 out4) (define next-c4 (add1 c4)) (set! c4 (cond [(<= d4 next-c4) 0] [else next-c4])) (flvector-set! mvec 3 midnode4) (define delayed5 (flvector-ref v5 c5)) (define midnode5 (fl+ delayed5 (fl* g15 (flvector-ref mvec 4)))) (define out5 (fl+ (fl* g25 midnode5) in)) (flvector-set! v5 c5 out5) (define next-c5 (add1 c5)) (set! c5 (cond [(<= d5 next-c5) 0] [else next-c5])) (flvector-set! mvec 4 midnode5) (define delayed6 (flvector-ref v6 c6)) (define midnode6 (fl+ delayed6 (fl* g16 (flvector-ref mvec 5)))) (define out6 (fl+ (fl* g26 midnode6) in)) (flvector-set! v6 c6 out6) (define next-c6 (add1 c6)) (set! c6 (cond [(<= d6 next-c6) 0] [else next-c6])) (flvector-set! mvec 5 midnode6) (/ (+ out1 out2 out3 out4 out5 out6) 6.0)))) (: reverb network/s) (define reverb (network/s 1 1 starter))
b524b8e6981c46a9ddb95413b5fb07b6bb7480c1e6160a409930a6ceebd4116f
mzp/coq-ruby
output.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) i $ I d : output.mli 12187 2009 - 06 - 13 19:36:59Z msozeau $ i open Cdglobals open Index val initialize : unit -> unit val add_printing_token : string -> string option * string option -> unit val remove_printing_token : string -> unit val set_module : coq_module -> unit val header : unit -> unit val trailer : unit -> unit val push_in_preamble : string -> unit val start_module : unit -> unit val start_doc : unit -> unit val end_doc : unit -> unit val start_comment : unit -> unit val end_comment : unit -> unit val start_coq : unit -> unit val end_coq : unit -> unit val start_code : unit -> unit val end_code : unit -> unit val start_inline_coq : unit -> unit val end_inline_coq : unit -> unit val indentation : int -> unit val line_break : unit -> unit val paragraph : unit -> unit val empty_line_of_code : unit -> unit val section : int -> (unit -> unit) -> unit val item : int -> unit val rule : unit -> unit val char : char -> unit val ident : string -> loc -> unit val symbol : string -> unit val latex_char : char -> unit val latex_string : string -> unit val html_char : char -> unit val html_string : string -> unit val verbatim_char : char -> unit val hard_verbatim_char : char -> unit val start_latex_math : unit -> unit val stop_latex_math : unit -> unit val start_verbatim : unit -> unit val stop_verbatim : unit -> unit val make_multi_index : unit -> unit val make_index : unit -> unit val make_toc : unit -> unit
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/tools/coqdoc/output.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i $ I d : output.mli 12187 2009 - 06 - 13 19:36:59Z msozeau $ i open Cdglobals open Index val initialize : unit -> unit val add_printing_token : string -> string option * string option -> unit val remove_printing_token : string -> unit val set_module : coq_module -> unit val header : unit -> unit val trailer : unit -> unit val push_in_preamble : string -> unit val start_module : unit -> unit val start_doc : unit -> unit val end_doc : unit -> unit val start_comment : unit -> unit val end_comment : unit -> unit val start_coq : unit -> unit val end_coq : unit -> unit val start_code : unit -> unit val end_code : unit -> unit val start_inline_coq : unit -> unit val end_inline_coq : unit -> unit val indentation : int -> unit val line_break : unit -> unit val paragraph : unit -> unit val empty_line_of_code : unit -> unit val section : int -> (unit -> unit) -> unit val item : int -> unit val rule : unit -> unit val char : char -> unit val ident : string -> loc -> unit val symbol : string -> unit val latex_char : char -> unit val latex_string : string -> unit val html_char : char -> unit val html_string : string -> unit val verbatim_char : char -> unit val hard_verbatim_char : char -> unit val start_latex_math : unit -> unit val stop_latex_math : unit -> unit val start_verbatim : unit -> unit val stop_verbatim : unit -> unit val make_multi_index : unit -> unit val make_index : unit -> unit val make_toc : unit -> unit
8b873c7af146a03f8d721e339ce2e30e3873ea247206917284d357b895c21a5c
jonsterling/dreamtt
Effect.ml
open Basis open Syntax module E = struct type local = {thy : Logic.thy; env : env} let update_thy upd {thy; env} = {thy = Logic.update upd thy; env} let append_tm tm {thy; env} = {thy; env = Env.append env @@ `Tm tm} let set_env env {thy; _} = {thy; env} end module L = struct module M = Reader.MakeT (E) (Error.M) include M open Monad.Notation (M) let global m = m let local e m = locally (E.set_env e) m let catch (m : 'a m) (k : ('a, exn) Result.t -> 'b m) : 'b m = reader @@ fun env -> Error.M.run (run env m) @@ fun res -> run env @@ k res let throw e = lift @@ Error.M.throw e let theory = let+ x = read in x.thy let env = let+ x = read in x.env let scope_thy upd m = locally (E.update_thy upd) m let bind_tm gtp kont = let* e = env in let lvl = Env.fresh e in let glued = stable_glued gtp @@ GVar lvl in let var = Glued glued in locally (E.append_tm var) @@ kont var let append_tm gtm m = locally (E.append_tm gtm) m end module G = L type 'a gm = 'a G.m type 'a lm = 'a L.m
null
https://raw.githubusercontent.com/jonsterling/dreamtt/aa30a57ca869e91a295e586773a892c6601b5ddb/core/Effect.ml
ocaml
open Basis open Syntax module E = struct type local = {thy : Logic.thy; env : env} let update_thy upd {thy; env} = {thy = Logic.update upd thy; env} let append_tm tm {thy; env} = {thy; env = Env.append env @@ `Tm tm} let set_env env {thy; _} = {thy; env} end module L = struct module M = Reader.MakeT (E) (Error.M) include M open Monad.Notation (M) let global m = m let local e m = locally (E.set_env e) m let catch (m : 'a m) (k : ('a, exn) Result.t -> 'b m) : 'b m = reader @@ fun env -> Error.M.run (run env m) @@ fun res -> run env @@ k res let throw e = lift @@ Error.M.throw e let theory = let+ x = read in x.thy let env = let+ x = read in x.env let scope_thy upd m = locally (E.update_thy upd) m let bind_tm gtp kont = let* e = env in let lvl = Env.fresh e in let glued = stable_glued gtp @@ GVar lvl in let var = Glued glued in locally (E.append_tm var) @@ kont var let append_tm gtm m = locally (E.append_tm gtm) m end module G = L type 'a gm = 'a G.m type 'a lm = 'a L.m
b287ef6d988427695f53806a099749ae11f1178286d2b6df45f99eeb7f8a4e80
GaloisInc/what4
PolyRoot.hs
| Module : What4.Protocol . PolyRoot Description : Representation for algebraic reals Copyright : ( c ) Galois Inc , 2016 - 2020 License : : Defines a numeric data - type where each number is represented as the root of a polynomial over a single variable . This currently only defines operations for parsing the roots from the format generated by Yices , and evaluating a polynomial over rational coefficients to the rational derived from the closest double . Module : What4.Protocol.PolyRoot Description : Representation for algebraic reals Copyright : (c) Galois Inc, 2016-2020 License : BSD3 Maintainer : Defines a numeric data-type where each number is represented as the root of a polynomial over a single variable. This currently only defines operations for parsing the roots from the format generated by Yices, and evaluating a polynomial over rational coefficients to the rational derived from the closest double. -} {-# LANGUAGE DeriveTraversable #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module What4.Protocol.PolyRoot ( Root , approximate , fromYicesText , parseYicesRoot ) where import Control.Applicative import Control.Lens import qualified Data.Attoparsec.Text as Atto import qualified Data.Map as Map import Data.Ratio import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Vector as V import Prettyprinter as PP atto_angle :: Atto.Parser a -> Atto.Parser a atto_angle p = Atto.char '<' *> p <* Atto.char '>' atto_paren :: Atto.Parser a -> Atto.Parser a atto_paren p = Atto.char '(' *> p <* Atto.char ')' | A polynomial with one variable . newtype SingPoly coef = SingPoly (V.Vector coef) deriving (Functor, Foldable, Traversable, Show) instance (Ord coef, Num coef, Pretty coef) => Pretty (SingPoly coef) where pretty (SingPoly v) = case V.findIndex (/= 0) v of Nothing -> pretty "0" Just j -> go (V.length v - 1) where ppc c | c < 0 = parens (pretty c) | otherwise = pretty c ppi 1 = pretty "*x" ppi i = pretty "*x^" <> pretty i go 0 = ppc (v V.! 0) go i | seq i False = error "pretty SingPoly" | i == j = ppc (v V.! i) <> ppi i | v V.! i == 0 = go (i-1) | otherwise = ppc (v V.! i) <> ppi i <+> pretty "+" <+> go (i-1) fromList :: [c] -> SingPoly c fromList = SingPoly . V.fromList -- | Create a polyomial from a map from powers to coefficient. fromMap :: (Eq c, Num c) => Map.Map Int c -> SingPoly c fromMap m0 = SingPoly (V.generate (n+1) f) where m = Map.filter (/= 0) m0 (n,_) = Map.findMax m f i = Map.findWithDefault 0 i m -- | Parse a positive monomial pos_mono :: Integral c => Atto.Parser (c, Int) pos_mono = (,) <$> Atto.decimal <*> times_x where times_x :: Atto.Parser Int times_x = (Atto.char '*' *> Atto.char 'x' *> expon) <|> pure 0 Parse explicit exponent or return 1 expon :: Atto.Parser Int expon = (Atto.char '^' *> Atto.decimal) <|> pure 1 -- | Parses a monomial and returns the coefficient and power mono :: Integral c => Atto.Parser (c, Int) mono = atto_paren (Atto.char '-' *> (over _1 negate <$> pos_mono)) <|> pos_mono parseYicesPoly :: Integral c => Atto.Parser (SingPoly c) parseYicesPoly = do (c,p) <- mono go (Map.singleton p c) where go m = next m <|> pure (fromMap m) next m = seq m $ do _ <- Atto.char ' ' *> Atto.char '+' *> Atto.char ' ' (c,p) <- mono go (Map.insertWith (+) p c m) -- | Evaluate polynomial at a specific value. -- -- Note that due to rounding, the result may not be exact when using -- finite precision arithmetic. eval :: forall c . Num c => SingPoly c -> c -> c eval (SingPoly v) c = f 0 1 0 where -- f takes an index, the current power, and the current sum. f :: Int -> c -> c -> c f i p s | seq p $ seq s $ False = error "internal error: Poly.eval" | i < V.length v = f (i+1) (p * c) (s + p * (v V.! i)) | otherwise = s data Root c = Root { rootPoly :: !(SingPoly c) , rootLbound :: !c , rootUbound :: !c } deriving (Show) -- | Construct a root from a rational constant rootFromRational :: Num c => c -> Root c rootFromRational r = Root { rootPoly = fromList [ negate r, 1 ] , rootLbound = r , rootUbound = r } instance (Ord c, Num c, Pretty c) => Pretty (Root c) where pretty (Root p l u) = langle <> pretty p <> comma <+> bounds <> rangle where bounds = parens (pretty l <> comma <+> pretty u) -- | This either returns the root exactly, or it computes the closest double -- precision approximation of the root. -- -- Underneath the hood, this uses rational arithmetic to guarantee precision, -- so this operation is relatively slow. However, it is guaranteed to provide -- an exact answer. -- -- If performance is a concern, there are faster algorithms for computing this. approximate :: Root Rational -> Rational approximate r | l0 == u0 = l0 | init_lval == 0 = l0 | init_uval == 0 = u0 | init_lval < 0 && init_uval > 0 = bisect (fromRational l0) (fromRational u0) | init_lval > 0 && init_uval < 0 = bisect (fromRational u0) (fromRational l0) | otherwise = error "Closest root given bad root." where p_rat = rootPoly r l0 = rootLbound r u0 = rootUbound r init_lval = eval p_rat l0 init_uval = eval p_rat u0 -- bisect takes a value that evaluates to a negative value under the 'p', and a value that evalautes to a positive value , and runs until it -- converges. bisect :: Double -> Double -> Rational bisect l u -- Stop if mid point is at bound. | m == l || m == u = toRational $ -- Pick whichever bound is cl oser to root. if l_val <= u_val then l else u | m_val == 0 = toRational m -- Stop if mid point is exact root. | m_val < 0 = bisect m u -- Use mid point as new lower bound | otherwise = bisect l m -- Use mid point as new upper bound. where m = (l + u) / 2 m_val = eval p_rat (toRational m) l_val = abs (eval p_rat (toRational l)) u_val = abs (eval p_rat (toRational u)) atto_pair :: (a -> b -> r) -> Atto.Parser a -> Atto.Parser b -> Atto.Parser r atto_pair f x y = f <$> x <*> (Atto.char ',' *> Atto.char ' ' *> y) atto_sdecimal :: Integral c => Atto.Parser c atto_sdecimal = Atto.char '-' *> (negate <$> Atto.decimal) <|> Atto.decimal atto_rational :: Integral c => Atto.Parser (Ratio c) atto_rational = (%) <$> atto_sdecimal <*> denom where denom = (Atto.char '/' *> Atto.decimal) <|> pure 1 parseYicesRoot :: Atto.Parser (Root Rational) parseYicesRoot = atto_angle (atto_pair mkRoot (fmap fromInteger <$> parseYicesPoly) parseBounds) <|> (rootFromRational <$> atto_rational) where mkRoot :: SingPoly c -> (c, c) -> Root c mkRoot = uncurry . Root parseBounds :: Atto.Parser (Rational, Rational) parseBounds = atto_paren (atto_pair (,) atto_rational atto_rational) -- | Convert text to a root fromYicesText :: Text -> Maybe (Root Rational) fromYicesText t = resolve (Atto.parse parseYicesRoot t) where resolve (Atto.Fail _rem _ _msg) = Nothing resolve (Atto.Partial f) = resolve (f Text.empty) resolve (Atto.Done i r) | Text.null i = Just $! r | otherwise = Nothing
null
https://raw.githubusercontent.com/GaloisInc/what4/91200aa39565c156226cec6a9409a692e4022501/what4/src/What4/Protocol/PolyRoot.hs
haskell
# LANGUAGE DeriveTraversable # | Create a polyomial from a map from powers to coefficient. | Parse a positive monomial | Parses a monomial and returns the coefficient and power | Evaluate polynomial at a specific value. Note that due to rounding, the result may not be exact when using finite precision arithmetic. f takes an index, the current power, and the current sum. | Construct a root from a rational constant | This either returns the root exactly, or it computes the closest double precision approximation of the root. Underneath the hood, this uses rational arithmetic to guarantee precision, so this operation is relatively slow. However, it is guaranteed to provide an exact answer. If performance is a concern, there are faster algorithms for computing this. bisect takes a value that evaluates to a negative value under the 'p', converges. Stop if mid point is at bound. Pick whichever bound is cl oser to root. Stop if mid point is exact root. Use mid point as new lower bound Use mid point as new upper bound. | Convert text to a root
| Module : What4.Protocol . PolyRoot Description : Representation for algebraic reals Copyright : ( c ) Galois Inc , 2016 - 2020 License : : Defines a numeric data - type where each number is represented as the root of a polynomial over a single variable . This currently only defines operations for parsing the roots from the format generated by Yices , and evaluating a polynomial over rational coefficients to the rational derived from the closest double . Module : What4.Protocol.PolyRoot Description : Representation for algebraic reals Copyright : (c) Galois Inc, 2016-2020 License : BSD3 Maintainer : Defines a numeric data-type where each number is represented as the root of a polynomial over a single variable. This currently only defines operations for parsing the roots from the format generated by Yices, and evaluating a polynomial over rational coefficients to the rational derived from the closest double. -} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # module What4.Protocol.PolyRoot ( Root , approximate , fromYicesText , parseYicesRoot ) where import Control.Applicative import Control.Lens import qualified Data.Attoparsec.Text as Atto import qualified Data.Map as Map import Data.Ratio import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Vector as V import Prettyprinter as PP atto_angle :: Atto.Parser a -> Atto.Parser a atto_angle p = Atto.char '<' *> p <* Atto.char '>' atto_paren :: Atto.Parser a -> Atto.Parser a atto_paren p = Atto.char '(' *> p <* Atto.char ')' | A polynomial with one variable . newtype SingPoly coef = SingPoly (V.Vector coef) deriving (Functor, Foldable, Traversable, Show) instance (Ord coef, Num coef, Pretty coef) => Pretty (SingPoly coef) where pretty (SingPoly v) = case V.findIndex (/= 0) v of Nothing -> pretty "0" Just j -> go (V.length v - 1) where ppc c | c < 0 = parens (pretty c) | otherwise = pretty c ppi 1 = pretty "*x" ppi i = pretty "*x^" <> pretty i go 0 = ppc (v V.! 0) go i | seq i False = error "pretty SingPoly" | i == j = ppc (v V.! i) <> ppi i | v V.! i == 0 = go (i-1) | otherwise = ppc (v V.! i) <> ppi i <+> pretty "+" <+> go (i-1) fromList :: [c] -> SingPoly c fromList = SingPoly . V.fromList fromMap :: (Eq c, Num c) => Map.Map Int c -> SingPoly c fromMap m0 = SingPoly (V.generate (n+1) f) where m = Map.filter (/= 0) m0 (n,_) = Map.findMax m f i = Map.findWithDefault 0 i m pos_mono :: Integral c => Atto.Parser (c, Int) pos_mono = (,) <$> Atto.decimal <*> times_x where times_x :: Atto.Parser Int times_x = (Atto.char '*' *> Atto.char 'x' *> expon) <|> pure 0 Parse explicit exponent or return 1 expon :: Atto.Parser Int expon = (Atto.char '^' *> Atto.decimal) <|> pure 1 mono :: Integral c => Atto.Parser (c, Int) mono = atto_paren (Atto.char '-' *> (over _1 negate <$> pos_mono)) <|> pos_mono parseYicesPoly :: Integral c => Atto.Parser (SingPoly c) parseYicesPoly = do (c,p) <- mono go (Map.singleton p c) where go m = next m <|> pure (fromMap m) next m = seq m $ do _ <- Atto.char ' ' *> Atto.char '+' *> Atto.char ' ' (c,p) <- mono go (Map.insertWith (+) p c m) eval :: forall c . Num c => SingPoly c -> c -> c eval (SingPoly v) c = f 0 1 0 f :: Int -> c -> c -> c f i p s | seq p $ seq s $ False = error "internal error: Poly.eval" | i < V.length v = f (i+1) (p * c) (s + p * (v V.! i)) | otherwise = s data Root c = Root { rootPoly :: !(SingPoly c) , rootLbound :: !c , rootUbound :: !c } deriving (Show) rootFromRational :: Num c => c -> Root c rootFromRational r = Root { rootPoly = fromList [ negate r, 1 ] , rootLbound = r , rootUbound = r } instance (Ord c, Num c, Pretty c) => Pretty (Root c) where pretty (Root p l u) = langle <> pretty p <> comma <+> bounds <> rangle where bounds = parens (pretty l <> comma <+> pretty u) approximate :: Root Rational -> Rational approximate r | l0 == u0 = l0 | init_lval == 0 = l0 | init_uval == 0 = u0 | init_lval < 0 && init_uval > 0 = bisect (fromRational l0) (fromRational u0) | init_lval > 0 && init_uval < 0 = bisect (fromRational u0) (fromRational l0) | otherwise = error "Closest root given bad root." where p_rat = rootPoly r l0 = rootLbound r u0 = rootUbound r init_lval = eval p_rat l0 init_uval = eval p_rat u0 and a value that evalautes to a positive value , and runs until it bisect :: Double -> Double -> Rational | m == l || m == u = toRational $ if l_val <= u_val then l else u where m = (l + u) / 2 m_val = eval p_rat (toRational m) l_val = abs (eval p_rat (toRational l)) u_val = abs (eval p_rat (toRational u)) atto_pair :: (a -> b -> r) -> Atto.Parser a -> Atto.Parser b -> Atto.Parser r atto_pair f x y = f <$> x <*> (Atto.char ',' *> Atto.char ' ' *> y) atto_sdecimal :: Integral c => Atto.Parser c atto_sdecimal = Atto.char '-' *> (negate <$> Atto.decimal) <|> Atto.decimal atto_rational :: Integral c => Atto.Parser (Ratio c) atto_rational = (%) <$> atto_sdecimal <*> denom where denom = (Atto.char '/' *> Atto.decimal) <|> pure 1 parseYicesRoot :: Atto.Parser (Root Rational) parseYicesRoot = atto_angle (atto_pair mkRoot (fmap fromInteger <$> parseYicesPoly) parseBounds) <|> (rootFromRational <$> atto_rational) where mkRoot :: SingPoly c -> (c, c) -> Root c mkRoot = uncurry . Root parseBounds :: Atto.Parser (Rational, Rational) parseBounds = atto_paren (atto_pair (,) atto_rational atto_rational) fromYicesText :: Text -> Maybe (Root Rational) fromYicesText t = resolve (Atto.parse parseYicesRoot t) where resolve (Atto.Fail _rem _ _msg) = Nothing resolve (Atto.Partial f) = resolve (f Text.empty) resolve (Atto.Done i r) | Text.null i = Just $! r | otherwise = Nothing
d02dfe99da6249e14d8d742d56dfda79354186214c73f1981381dacadf5d3382
ankushdas/Nomos
RastConfig.ml
(* Configuration for running rast files *) module R = Arith module A = Ast module PP = Pprint module F = RastFlags module C = Core module E = Exec module EL = Elab module I = Infer module TC = Typecheck (************************) (* Command Line Options *) (************************) type option = Work of string | Syntax of string | Verbose of int | Invalid of string;; let process_option ext op = match op with Work(s) -> begin match F.parseCost s with None -> C.eprintf "%% cost model %s not recognized\n" s; exit 1 | Some cm -> F.work := cm end | Syntax(s) -> begin match F.parseSyntax s with None -> C.eprintf "%% syntax %s not recognized\n" s; exit 1 | Some syn -> F.syntax := syn end | Verbose(level) -> F.verbosity := level | Invalid(s) -> ErrorMsg.error ErrorMsg.Pragma ext ("unrecognized option: " ^ s ^ "\n");; (*********************************) (* Loading and Elaborating Files *) (*********************************) let reset () = Parsestate.reset () ; ErrorMsg.reset ();; let start_match s1 s2 = let n2 = String.length s2 in let s = String.sub s1 0 n2 in (s = s2);; let get_option arg = let s = String.length arg in if start_match arg "-syntax=" then let n = String.length "-syntax=" in Syntax(String.sub arg n (s - n)) else if start_match arg "-work=" then let n = String.length "-work=" in Work(String.sub arg n (s - n)) else if start_match arg "-verbosity=" then let n = String.length "-verbosity=" in Verbose(int_of_string (String.sub arg n (s - n))) else Invalid(arg);; let apply_options ext line = let args = String.split_on_char ' ' line in let options = List.map get_option (List.tl args) in List.iter (process_option ext) options;; let rec apply_pragmas dcls = match dcls with {A.declaration = A.Pragma("#options",line); A.decl_extent = ext}::dcls' -> if !F.verbosity >= 1 then print_string ("#options" ^ line ^ "\n") else () ; apply_options ext line ; apply_pragmas dcls' | {A.declaration = A.Pragma("#test",_line); A.decl_extent = _ext}::dcls' -> (* ignore #test pragma *) apply_pragmas dcls' | {A.declaration = A.Pragma(pragma,_line); A.decl_extent = ext}::_dcls' -> ErrorMsg.error_msg ErrorMsg.Pragma ext ("unrecognized pragma: " ^ pragma) ; raise ErrorMsg.Error | dcls' -> dcls';; let load file = let () = reset () in (* internal lexer and parser state *) (* let () = I.reset () in (* resets the LP solver *) *) may raise ErrorMsg . Error may raise ErrorMsg . Error (* pragmas apply only to type-checker and execution *) (* may only be at beginning of file; apply now *) let decls' = EL.commit_channels decls decls in remove pragmas ; may raise ErrorMsg . Error (* allow for mutually recursive definitions in the same file *) let env = match EL.elab_decls decls'' decls'' with Some env' -> env' | None -> raise ErrorMsg.Error (* error during elaboration *) in let env = EL.remove_stars env in let env = EL.removeU env in let () = if !F.verbosity >= 2 then print_string ("========================================================\n") in let () = if !F.verbosity >= 2 then print_string (List.fold_left (fun str dcl -> str ^ (PP.pp_decl env dcl.A.declaration) ^ "\n") "" env) in let () = EL.gen_constraints env env in let (psols,msols) = I.solve_and_print () in let env = EL.substitute env psols msols in let () = if !F.verbosity >= 1 then print_string ("========================================================\n") in let () = if !F.verbosity >= 1 then print_string (List.fold_left (fun str dcl -> str ^ (PP.pp_decl env dcl.A.declaration) ^ "\n") "" env) in env;; (**********************) (* Executing Programs *) (**********************) let rec run env dcls = match dcls with {A.declaration = A.Exec(f) ; A.decl_extent = _ext}::dcls' -> let () = if !F.verbosity >= 1 then print_string (PP.pp_decl env (A.Exec(f)) ^ "\n") else () in let _config = E.exec env f in may raise Exec . RuntimeError run env dcls' | _dcl::dcls' -> run env dcls' | [] -> ();; let cmd_ext = None;; let rast_file = C.Command.Arg_type.create (fun filename -> match C.Sys.is_file filename with `No | `Unknown -> begin C.eprintf "'%s' is not a regular file.\n%!" filename; exit 1 end | `Yes -> if Filename.check_suffix filename ".rast" then filename else begin C.eprintf "'%s' does not have rast extension.\n%!" filename; exit 1 end);; let rast_command = C.Command.basic ~summary:"Typechecking Rast files" ~readme:(fun () -> "More detailed information") C.Command.Let_syntax.( let%map_open verbosity_flag = flag "-v" (optional int) ~doc:"verbosity 0: quiet, 1: default, 2: verbose, 3: debugging mode" and work_flag = flag "-w" (optional string) ~doc:"work-cost-model: none, recv, send, recvsend, free" and syntax_flag = flag "-s" (optional string) ~doc:"syntax: implicit, explicit" and file = anon("filename" %: rast_file) in fun () -> let vlevel = begin match verbosity_flag with None -> Verbose(1) | Some n -> Verbose(n) end in let work_cm = begin match work_flag with None -> Work("none") | Some s -> Work(s) end in let syntax = begin match syntax_flag with None -> Syntax("explicit") | Some s -> Syntax(s) end in let () = F.reset () in let () = List.iter (process_option cmd_ext) [vlevel; work_cm; syntax] in let env = try load file with ErrorMsg.Error -> C.eprintf "%% compilation failed!\n"; exit 1 in let () = print_string ("% compilation successful!\n") in try let () = run env env in print_string ("% runtime successful!\n") with E.RuntimeError -> C.eprintf "%% runtime failed!\n"; exit 1);;
null
https://raw.githubusercontent.com/ankushdas/Nomos/db678f3981e75a1b3310bb55f66009bb23430cb1/rast/RastConfig.ml
ocaml
Configuration for running rast files ********************** Command Line Options ********************** ******************************* Loading and Elaborating Files ******************************* ignore #test pragma internal lexer and parser state let () = I.reset () in (* resets the LP solver pragmas apply only to type-checker and execution may only be at beginning of file; apply now allow for mutually recursive definitions in the same file error during elaboration ******************** Executing Programs ********************
module R = Arith module A = Ast module PP = Pprint module F = RastFlags module C = Core module E = Exec module EL = Elab module I = Infer module TC = Typecheck type option = Work of string | Syntax of string | Verbose of int | Invalid of string;; let process_option ext op = match op with Work(s) -> begin match F.parseCost s with None -> C.eprintf "%% cost model %s not recognized\n" s; exit 1 | Some cm -> F.work := cm end | Syntax(s) -> begin match F.parseSyntax s with None -> C.eprintf "%% syntax %s not recognized\n" s; exit 1 | Some syn -> F.syntax := syn end | Verbose(level) -> F.verbosity := level | Invalid(s) -> ErrorMsg.error ErrorMsg.Pragma ext ("unrecognized option: " ^ s ^ "\n");; let reset () = Parsestate.reset () ; ErrorMsg.reset ();; let start_match s1 s2 = let n2 = String.length s2 in let s = String.sub s1 0 n2 in (s = s2);; let get_option arg = let s = String.length arg in if start_match arg "-syntax=" then let n = String.length "-syntax=" in Syntax(String.sub arg n (s - n)) else if start_match arg "-work=" then let n = String.length "-work=" in Work(String.sub arg n (s - n)) else if start_match arg "-verbosity=" then let n = String.length "-verbosity=" in Verbose(int_of_string (String.sub arg n (s - n))) else Invalid(arg);; let apply_options ext line = let args = String.split_on_char ' ' line in let options = List.map get_option (List.tl args) in List.iter (process_option ext) options;; let rec apply_pragmas dcls = match dcls with {A.declaration = A.Pragma("#options",line); A.decl_extent = ext}::dcls' -> if !F.verbosity >= 1 then print_string ("#options" ^ line ^ "\n") else () ; apply_options ext line ; apply_pragmas dcls' | {A.declaration = A.Pragma("#test",_line); A.decl_extent = _ext}::dcls' -> apply_pragmas dcls' | {A.declaration = A.Pragma(pragma,_line); A.decl_extent = ext}::_dcls' -> ErrorMsg.error_msg ErrorMsg.Pragma ext ("unrecognized pragma: " ^ pragma) ; raise ErrorMsg.Error | dcls' -> dcls';; let load file = *) may raise ErrorMsg . Error may raise ErrorMsg . Error let decls' = EL.commit_channels decls decls in remove pragmas ; may raise ErrorMsg . Error let env = match EL.elab_decls decls'' decls'' with Some env' -> env' in let env = EL.remove_stars env in let env = EL.removeU env in let () = if !F.verbosity >= 2 then print_string ("========================================================\n") in let () = if !F.verbosity >= 2 then print_string (List.fold_left (fun str dcl -> str ^ (PP.pp_decl env dcl.A.declaration) ^ "\n") "" env) in let () = EL.gen_constraints env env in let (psols,msols) = I.solve_and_print () in let env = EL.substitute env psols msols in let () = if !F.verbosity >= 1 then print_string ("========================================================\n") in let () = if !F.verbosity >= 1 then print_string (List.fold_left (fun str dcl -> str ^ (PP.pp_decl env dcl.A.declaration) ^ "\n") "" env) in env;; let rec run env dcls = match dcls with {A.declaration = A.Exec(f) ; A.decl_extent = _ext}::dcls' -> let () = if !F.verbosity >= 1 then print_string (PP.pp_decl env (A.Exec(f)) ^ "\n") else () in let _config = E.exec env f in may raise Exec . RuntimeError run env dcls' | _dcl::dcls' -> run env dcls' | [] -> ();; let cmd_ext = None;; let rast_file = C.Command.Arg_type.create (fun filename -> match C.Sys.is_file filename with `No | `Unknown -> begin C.eprintf "'%s' is not a regular file.\n%!" filename; exit 1 end | `Yes -> if Filename.check_suffix filename ".rast" then filename else begin C.eprintf "'%s' does not have rast extension.\n%!" filename; exit 1 end);; let rast_command = C.Command.basic ~summary:"Typechecking Rast files" ~readme:(fun () -> "More detailed information") C.Command.Let_syntax.( let%map_open verbosity_flag = flag "-v" (optional int) ~doc:"verbosity 0: quiet, 1: default, 2: verbose, 3: debugging mode" and work_flag = flag "-w" (optional string) ~doc:"work-cost-model: none, recv, send, recvsend, free" and syntax_flag = flag "-s" (optional string) ~doc:"syntax: implicit, explicit" and file = anon("filename" %: rast_file) in fun () -> let vlevel = begin match verbosity_flag with None -> Verbose(1) | Some n -> Verbose(n) end in let work_cm = begin match work_flag with None -> Work("none") | Some s -> Work(s) end in let syntax = begin match syntax_flag with None -> Syntax("explicit") | Some s -> Syntax(s) end in let () = F.reset () in let () = List.iter (process_option cmd_ext) [vlevel; work_cm; syntax] in let env = try load file with ErrorMsg.Error -> C.eprintf "%% compilation failed!\n"; exit 1 in let () = print_string ("% compilation successful!\n") in try let () = run env env in print_string ("% runtime successful!\n") with E.RuntimeError -> C.eprintf "%% runtime failed!\n"; exit 1);;
9c7e76a26199ae0733b1bfdea0e4000bd5ce50b204ca25f0ca3cf5fe7a8d912d
marick/fp-oo
Y.clj
Exercise 1 (def recurser-core (fn [stop-when ending-value combiner reducer] (letfn [(recursive-function [something] (if (stop-when something) (ending-value something) (combiner something (recursive-function (reducer something)))))] recursive-function))) Exercise 2 (def recurser-core (fn [stop-when ending-value combiner reducer] (Y (fn [recursive-function] (fn [something] (if (stop-when something) (ending-value something) (combiner something (recursive-function (reducer something))))))))) Exercise 3 (def recurser (fn [& args] (let [control-map (apply hash-map args) ending-value (:ending-value control-map) ending-value (if (fn? ending-value) ending-value (constantly ending-value))] (recurser-core (:stop-when control-map) ending-value (:combiner control-map) (:reducer control-map)))))
null
https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/solutions/Y.clj
clojure
Exercise 1 (def recurser-core (fn [stop-when ending-value combiner reducer] (letfn [(recursive-function [something] (if (stop-when something) (ending-value something) (combiner something (recursive-function (reducer something)))))] recursive-function))) Exercise 2 (def recurser-core (fn [stop-when ending-value combiner reducer] (Y (fn [recursive-function] (fn [something] (if (stop-when something) (ending-value something) (combiner something (recursive-function (reducer something))))))))) Exercise 3 (def recurser (fn [& args] (let [control-map (apply hash-map args) ending-value (:ending-value control-map) ending-value (if (fn? ending-value) ending-value (constantly ending-value))] (recurser-core (:stop-when control-map) ending-value (:combiner control-map) (:reducer control-map)))))
564d7edeb4f96739e45b0d167581b55aa2dc16f661bd4f122f35e45454a53167
gerlion/secure-e-voting-with-coq
ElectionGuard_j.mli
Auto - generated from " ElectionGuard.atd " [@@@ocaml.warning "-27-32-35-39"] type pkproof = ElectionGuard_t.pkproof = { commitment: string; challenge: string; response: string } type trustee_public_key = ElectionGuard_t.trustee_public_key = { public_key: string; proof: pkproof } type commitment = ElectionGuard_t.commitment = { public_key: string; ciphertext: string } type proof = ElectionGuard_t.proof = { commitment: commitment; challenge: string; response: string } type decproof = ElectionGuard_t.decproof = { recovery: string option; proof: proof; share: string } type ciphertext = ElectionGuard_t.ciphertext = { public_key: string; ciphertext: string } type spoil = ElectionGuard_t.spoil = { cleartext: string; decrypted_message: string; encrypted_message: ciphertext; shares: decproof list } type parameters = ElectionGuard_t.parameters = { date: string; location: string; num_trustees: string; threshold: string; prime: string; generator: string } type message = ElectionGuard_t.message = { message: ciphertext; zero_proof: proof; one_proof: proof } type decrypt = ElectionGuard_t.decrypt = { cleartext: string; decrypted_tally: string; encrypted_tally: ciphertext; shares: decproof list } type contest = ElectionGuard_t.contest = { selections: message list; max_selections: string; num_selections_proof: proof } type ballot_info = ElectionGuard_t.ballot_info = { date: string; device_info: string; time: string; tracker: string } type ballotspoiled = ElectionGuard_t.ballotspoiled = { ballot_info: ballot_info; contests: spoil list list } type ballot = ElectionGuard_t.ballot = { ballot_info: ballot_info; contests: contest list } type election = ElectionGuard_t.election = { parameters: parameters; base_hash: string; trustee_public_keys: trustee_public_key list list; joint_public_key: string; extended_base_hash: string; cast_ballots: ballot list; contest_tallies: decrypt list list; spoiled_ballots: ballotspoiled list } val write_pkproof : Bi_outbuf.t -> pkproof -> unit * Output a JSON value of type { ! } . val string_of_pkproof : ?len:int -> pkproof -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_pkproof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> pkproof * Input JSON data of type { ! } . val pkproof_of_string : string -> pkproof * JSON data of type { ! } . val write_trustee_public_key : Bi_outbuf.t -> trustee_public_key -> unit (** Output a JSON value of type {!trustee_public_key}. *) val string_of_trustee_public_key : ?len:int -> trustee_public_key -> string * Serialize a value of type { ! trustee_public_key } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_trustee_public_key : Yojson.Safe.lexer_state -> Lexing.lexbuf -> trustee_public_key (** Input JSON data of type {!trustee_public_key}. *) val trustee_public_key_of_string : string -> trustee_public_key * JSON data of type { ! trustee_public_key } . val write_commitment : Bi_outbuf.t -> commitment -> unit (** Output a JSON value of type {!commitment}. *) val string_of_commitment : ?len:int -> commitment -> string * Serialize a value of type { ! commitment } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_commitment : Yojson.Safe.lexer_state -> Lexing.lexbuf -> commitment (** Input JSON data of type {!commitment}. *) val commitment_of_string : string -> commitment * JSON data of type { ! commitment } . val write_proof : Bi_outbuf.t -> proof -> unit (** Output a JSON value of type {!proof}. *) val string_of_proof : ?len:int -> proof -> string * Serialize a value of type { ! proof } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_proof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> proof (** Input JSON data of type {!proof}. *) val proof_of_string : string -> proof * JSON data of type { ! proof } . val write_decproof : Bi_outbuf.t -> decproof -> unit * Output a JSON value of type { ! } . val string_of_decproof : ?len:int -> decproof -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_decproof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> decproof * Input JSON data of type { ! } . val decproof_of_string : string -> decproof * JSON data of type { ! } . val write_ciphertext : Bi_outbuf.t -> ciphertext -> unit (** Output a JSON value of type {!ciphertext}. *) val string_of_ciphertext : ?len:int -> ciphertext -> string * Serialize a value of type { ! ciphertext } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ciphertext : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ciphertext (** Input JSON data of type {!ciphertext}. *) val ciphertext_of_string : string -> ciphertext * JSON data of type { ! ciphertext } . val write_spoil : Bi_outbuf.t -> spoil -> unit (** Output a JSON value of type {!spoil}. *) val string_of_spoil : ?len:int -> spoil -> string * Serialize a value of type { ! spoil } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_spoil : Yojson.Safe.lexer_state -> Lexing.lexbuf -> spoil (** Input JSON data of type {!spoil}. *) val spoil_of_string : string -> spoil * JSON data of type { ! spoil } . val write_parameters : Bi_outbuf.t -> parameters -> unit (** Output a JSON value of type {!parameters}. *) val string_of_parameters : ?len:int -> parameters -> string * Serialize a value of type { ! parameters } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_parameters : Yojson.Safe.lexer_state -> Lexing.lexbuf -> parameters (** Input JSON data of type {!parameters}. *) val parameters_of_string : string -> parameters * JSON data of type { ! parameters } . val write_message : Bi_outbuf.t -> message -> unit (** Output a JSON value of type {!message}. *) val string_of_message : ?len:int -> message -> string * Serialize a value of type { ! message } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_message : Yojson.Safe.lexer_state -> Lexing.lexbuf -> message (** Input JSON data of type {!message}. *) val message_of_string : string -> message * JSON data of type { ! message } . val write_decrypt : Bi_outbuf.t -> decrypt -> unit (** Output a JSON value of type {!decrypt}. *) val string_of_decrypt : ?len:int -> decrypt -> string * Serialize a value of type { ! decrypt } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_decrypt : Yojson.Safe.lexer_state -> Lexing.lexbuf -> decrypt (** Input JSON data of type {!decrypt}. *) val decrypt_of_string : string -> decrypt * JSON data of type { ! decrypt } . val write_contest : Bi_outbuf.t -> contest -> unit (** Output a JSON value of type {!contest}. *) val string_of_contest : ?len:int -> contest -> string * Serialize a value of type { ! contest } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_contest : Yojson.Safe.lexer_state -> Lexing.lexbuf -> contest (** Input JSON data of type {!contest}. *) val contest_of_string : string -> contest * JSON data of type { ! contest } . val write_ballot_info : Bi_outbuf.t -> ballot_info -> unit (** Output a JSON value of type {!ballot_info}. *) val string_of_ballot_info : ?len:int -> ballot_info -> string * Serialize a value of type { ! ballot_info } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballot_info : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballot_info (** Input JSON data of type {!ballot_info}. *) val ballot_info_of_string : string -> ballot_info * JSON data of type { ! ballot_info } . val write_ballotspoiled : Bi_outbuf.t -> ballotspoiled -> unit * Output a JSON value of type { ! } . val string_of_ballotspoiled : ?len:int -> ballotspoiled -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballotspoiled : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballotspoiled * Input JSON data of type { ! } . val ballotspoiled_of_string : string -> ballotspoiled * JSON data of type { ! } . val write_ballot : Bi_outbuf.t -> ballot -> unit (** Output a JSON value of type {!ballot}. *) val string_of_ballot : ?len:int -> ballot -> string * Serialize a value of type { ! ballot } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballot : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballot (** Input JSON data of type {!ballot}. *) val ballot_of_string : string -> ballot * JSON data of type { ! ballot } . val write_election : Bi_outbuf.t -> election -> unit (** Output a JSON value of type {!election}. *) val string_of_election : ?len:int -> election -> string * Serialize a value of type { ! election } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_election : Yojson.Safe.lexer_state -> Lexing.lexbuf -> election (** Input JSON data of type {!election}. *) val election_of_string : string -> election * JSON data of type { ! election } .
null
https://raw.githubusercontent.com/gerlion/secure-e-voting-with-coq/c85f58f5759b960cc9d90a96fe7970e038523a9a/ElectionGuard/OCaml/ElectionGuard_j.mli
ocaml
* Output a JSON value of type {!trustee_public_key}. * Input JSON data of type {!trustee_public_key}. * Output a JSON value of type {!commitment}. * Input JSON data of type {!commitment}. * Output a JSON value of type {!proof}. * Input JSON data of type {!proof}. * Output a JSON value of type {!ciphertext}. * Input JSON data of type {!ciphertext}. * Output a JSON value of type {!spoil}. * Input JSON data of type {!spoil}. * Output a JSON value of type {!parameters}. * Input JSON data of type {!parameters}. * Output a JSON value of type {!message}. * Input JSON data of type {!message}. * Output a JSON value of type {!decrypt}. * Input JSON data of type {!decrypt}. * Output a JSON value of type {!contest}. * Input JSON data of type {!contest}. * Output a JSON value of type {!ballot_info}. * Input JSON data of type {!ballot_info}. * Output a JSON value of type {!ballot}. * Input JSON data of type {!ballot}. * Output a JSON value of type {!election}. * Input JSON data of type {!election}.
Auto - generated from " ElectionGuard.atd " [@@@ocaml.warning "-27-32-35-39"] type pkproof = ElectionGuard_t.pkproof = { commitment: string; challenge: string; response: string } type trustee_public_key = ElectionGuard_t.trustee_public_key = { public_key: string; proof: pkproof } type commitment = ElectionGuard_t.commitment = { public_key: string; ciphertext: string } type proof = ElectionGuard_t.proof = { commitment: commitment; challenge: string; response: string } type decproof = ElectionGuard_t.decproof = { recovery: string option; proof: proof; share: string } type ciphertext = ElectionGuard_t.ciphertext = { public_key: string; ciphertext: string } type spoil = ElectionGuard_t.spoil = { cleartext: string; decrypted_message: string; encrypted_message: ciphertext; shares: decproof list } type parameters = ElectionGuard_t.parameters = { date: string; location: string; num_trustees: string; threshold: string; prime: string; generator: string } type message = ElectionGuard_t.message = { message: ciphertext; zero_proof: proof; one_proof: proof } type decrypt = ElectionGuard_t.decrypt = { cleartext: string; decrypted_tally: string; encrypted_tally: ciphertext; shares: decproof list } type contest = ElectionGuard_t.contest = { selections: message list; max_selections: string; num_selections_proof: proof } type ballot_info = ElectionGuard_t.ballot_info = { date: string; device_info: string; time: string; tracker: string } type ballotspoiled = ElectionGuard_t.ballotspoiled = { ballot_info: ballot_info; contests: spoil list list } type ballot = ElectionGuard_t.ballot = { ballot_info: ballot_info; contests: contest list } type election = ElectionGuard_t.election = { parameters: parameters; base_hash: string; trustee_public_keys: trustee_public_key list list; joint_public_key: string; extended_base_hash: string; cast_ballots: ballot list; contest_tallies: decrypt list list; spoiled_ballots: ballotspoiled list } val write_pkproof : Bi_outbuf.t -> pkproof -> unit * Output a JSON value of type { ! } . val string_of_pkproof : ?len:int -> pkproof -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_pkproof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> pkproof * Input JSON data of type { ! } . val pkproof_of_string : string -> pkproof * JSON data of type { ! } . val write_trustee_public_key : Bi_outbuf.t -> trustee_public_key -> unit val string_of_trustee_public_key : ?len:int -> trustee_public_key -> string * Serialize a value of type { ! trustee_public_key } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_trustee_public_key : Yojson.Safe.lexer_state -> Lexing.lexbuf -> trustee_public_key val trustee_public_key_of_string : string -> trustee_public_key * JSON data of type { ! trustee_public_key } . val write_commitment : Bi_outbuf.t -> commitment -> unit val string_of_commitment : ?len:int -> commitment -> string * Serialize a value of type { ! commitment } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_commitment : Yojson.Safe.lexer_state -> Lexing.lexbuf -> commitment val commitment_of_string : string -> commitment * JSON data of type { ! commitment } . val write_proof : Bi_outbuf.t -> proof -> unit val string_of_proof : ?len:int -> proof -> string * Serialize a value of type { ! proof } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_proof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> proof val proof_of_string : string -> proof * JSON data of type { ! proof } . val write_decproof : Bi_outbuf.t -> decproof -> unit * Output a JSON value of type { ! } . val string_of_decproof : ?len:int -> decproof -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_decproof : Yojson.Safe.lexer_state -> Lexing.lexbuf -> decproof * Input JSON data of type { ! } . val decproof_of_string : string -> decproof * JSON data of type { ! } . val write_ciphertext : Bi_outbuf.t -> ciphertext -> unit val string_of_ciphertext : ?len:int -> ciphertext -> string * Serialize a value of type { ! ciphertext } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ciphertext : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ciphertext val ciphertext_of_string : string -> ciphertext * JSON data of type { ! ciphertext } . val write_spoil : Bi_outbuf.t -> spoil -> unit val string_of_spoil : ?len:int -> spoil -> string * Serialize a value of type { ! spoil } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_spoil : Yojson.Safe.lexer_state -> Lexing.lexbuf -> spoil val spoil_of_string : string -> spoil * JSON data of type { ! spoil } . val write_parameters : Bi_outbuf.t -> parameters -> unit val string_of_parameters : ?len:int -> parameters -> string * Serialize a value of type { ! parameters } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_parameters : Yojson.Safe.lexer_state -> Lexing.lexbuf -> parameters val parameters_of_string : string -> parameters * JSON data of type { ! parameters } . val write_message : Bi_outbuf.t -> message -> unit val string_of_message : ?len:int -> message -> string * Serialize a value of type { ! message } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_message : Yojson.Safe.lexer_state -> Lexing.lexbuf -> message val message_of_string : string -> message * JSON data of type { ! message } . val write_decrypt : Bi_outbuf.t -> decrypt -> unit val string_of_decrypt : ?len:int -> decrypt -> string * Serialize a value of type { ! decrypt } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_decrypt : Yojson.Safe.lexer_state -> Lexing.lexbuf -> decrypt val decrypt_of_string : string -> decrypt * JSON data of type { ! decrypt } . val write_contest : Bi_outbuf.t -> contest -> unit val string_of_contest : ?len:int -> contest -> string * Serialize a value of type { ! contest } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_contest : Yojson.Safe.lexer_state -> Lexing.lexbuf -> contest val contest_of_string : string -> contest * JSON data of type { ! contest } . val write_ballot_info : Bi_outbuf.t -> ballot_info -> unit val string_of_ballot_info : ?len:int -> ballot_info -> string * Serialize a value of type { ! ballot_info } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballot_info : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballot_info val ballot_info_of_string : string -> ballot_info * JSON data of type { ! ballot_info } . val write_ballotspoiled : Bi_outbuf.t -> ballotspoiled -> unit * Output a JSON value of type { ! } . val string_of_ballotspoiled : ?len:int -> ballotspoiled -> string * Serialize a value of type { ! } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballotspoiled : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballotspoiled * Input JSON data of type { ! } . val ballotspoiled_of_string : string -> ballotspoiled * JSON data of type { ! } . val write_ballot : Bi_outbuf.t -> ballot -> unit val string_of_ballot : ?len:int -> ballot -> string * Serialize a value of type { ! ballot } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_ballot : Yojson.Safe.lexer_state -> Lexing.lexbuf -> ballot val ballot_of_string : string -> ballot * JSON data of type { ! ballot } . val write_election : Bi_outbuf.t -> election -> unit val string_of_election : ?len:int -> election -> string * Serialize a value of type { ! election } into a JSON string . @param len specifies the initial length of the buffer used internally . Default : 1024 . into a JSON string. @param len specifies the initial length of the buffer used internally. Default: 1024. *) val read_election : Yojson.Safe.lexer_state -> Lexing.lexbuf -> election val election_of_string : string -> election * JSON data of type { ! election } .
67de1cf0a561d5d753f67b699a0273e441543c0ebf1c290849a75eaa31f893c1
elaforge/karya
LTScore.hs
Copyright 2018 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt -- | Functions to deal with text score, as stored in 'UiConfig.config_tscore'. module Cmd.Repl.LTScore where import qualified App.ReplProtocol as ReplProtocol import qualified Cmd.Cmd as Cmd import qualified Cmd.Create as Create import qualified Cmd.Repl.LState as LState import qualified Derive.TScore.TScore as TScore import qualified Ui.Ui as Ui import qualified Ui.UiConfig as UiConfig import Global -- | Edit both ky and tscore together. both :: Ui.M m => m ReplProtocol.Result both = do tscore <- edit ky <- LState.ky case (ky, tscore) of (ReplProtocol.Edit ky, ReplProtocol.Edit tscore) -> return $ ReplProtocol.Edit (tscore <> ky) _ -> Ui.throw "expected ReplProtocol.Edit" edit :: Ui.M m => m ReplProtocol.Result edit = do tscore <- get return $ ReplProtocol.Edit $ (:| []) $ ReplProtocol.Editor { _file = ReplProtocol.Text ReplProtocol.TScore tscore , _line_number = 0 , _on_save = on_set , _on_send = on_set } where on_set = Just "LTScore.set %s" get :: Ui.M m => m Text get = Ui.config#UiConfig.tscore <#> Ui.get set :: Cmd.M m => Text -> m () set tscore = do Ui.modify_config $ UiConfig.tscore #= tscore integrate integrate :: Cmd.M m => m () integrate = do new_blocks <- TScore.cmd_integrate =<< get mapM_ Create.view new_blocks
null
https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Cmd/Repl/LTScore.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Functions to deal with text score, as stored in 'UiConfig.config_tscore'. | Edit both ky and tscore together.
Copyright 2018 module Cmd.Repl.LTScore where import qualified App.ReplProtocol as ReplProtocol import qualified Cmd.Cmd as Cmd import qualified Cmd.Create as Create import qualified Cmd.Repl.LState as LState import qualified Derive.TScore.TScore as TScore import qualified Ui.Ui as Ui import qualified Ui.UiConfig as UiConfig import Global both :: Ui.M m => m ReplProtocol.Result both = do tscore <- edit ky <- LState.ky case (ky, tscore) of (ReplProtocol.Edit ky, ReplProtocol.Edit tscore) -> return $ ReplProtocol.Edit (tscore <> ky) _ -> Ui.throw "expected ReplProtocol.Edit" edit :: Ui.M m => m ReplProtocol.Result edit = do tscore <- get return $ ReplProtocol.Edit $ (:| []) $ ReplProtocol.Editor { _file = ReplProtocol.Text ReplProtocol.TScore tscore , _line_number = 0 , _on_save = on_set , _on_send = on_set } where on_set = Just "LTScore.set %s" get :: Ui.M m => m Text get = Ui.config#UiConfig.tscore <#> Ui.get set :: Cmd.M m => Text -> m () set tscore = do Ui.modify_config $ UiConfig.tscore #= tscore integrate integrate :: Cmd.M m => m () integrate = do new_blocks <- TScore.cmd_integrate =<< get mapM_ Create.view new_blocks
bed7b301f423e04d7911f4546761cb7982944ba1671c06e78199b0636359abdc
kappelmann/engaging-large-scale-functional-programming
Exercise03.hs
module Exercise03 where isPrime :: Integer -> Bool isPrime n | n < 2 = False isPrime n = go 2 where go x | x * x > n = True | n `mod` x == 0 = False | otherwise = x `seq` go (x + 1) primeMayor :: Integer -> Integer primeMayor 2 = 1 primeMayor n | even n = 2 | isPrime n = 1 | isPrime $ n - 2 = 2 | otherwise = 3
null
https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/03/uploads/maol/Exercise03.hs
haskell
module Exercise03 where isPrime :: Integer -> Bool isPrime n | n < 2 = False isPrime n = go 2 where go x | x * x > n = True | n `mod` x == 0 = False | otherwise = x `seq` go (x + 1) primeMayor :: Integer -> Integer primeMayor 2 = 1 primeMayor n | even n = 2 | isPrime n = 1 | isPrime $ n - 2 = 2 | otherwise = 3
72142c7f6fb4f15ebe9e6c22bd4390c5956b0e245687e88e371aad7376dd59a1
wireapp/wire-server
Run.hs
# LANGUAGE RecordWildCards # -- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- 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. -- -- 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 </>. module Spar.DataMigration.Run where import qualified Cassandra as C import qualified Cassandra.Settings as C import Control.Lens import Control.Monad.Catch (finally) import qualified Data.Text as Text import Data.Time (UTCTime, getCurrentTime) import Imports import qualified Options.Applicative as Opts import Spar.DataMigration.Options (settingsParser) import Spar.DataMigration.Types import qualified Spar.DataMigration.V2_UserV2 as V2 import qualified System.Logger as Log main :: IO () main = do settings <- Opts.execParser (Opts.info (Opts.helper <*> settingsParser) desc) migrate settings V1.migration has been deleted in -server/pull/2768 -- (because the deprecated source table has been removed). V2.migration ] where desc = Opts.header "Spar Cassandra Data Migrations" <> Opts.fullDesc migrate :: MigratorSettings -> [Migration] -> IO () migrate settings ms = do env <- mkEnv settings runMigrations env ms `finally` cleanup env mkEnv :: MigratorSettings -> IO Env mkEnv settings = do lgr <- initLogger settings spar <- initCassandra (settings ^. setCasSpar) lgr brig <- initCassandra (settings ^. setCasBrig) lgr pure $ Env spar brig lgr (settings ^. setPageSize) (settings ^. setDebug) (settings ^. setDryRun) where initLogger s = Log.new . Log.setOutput Log.StdOut . Log.setFormat Nothing . Log.setBufSize 0 . Log.setLogLevel (if s ^. setDebug == Debug then Log.Debug else Log.Info) $ Log.defSettings initCassandra cas l = C.init . C.setLogger (C.mkLogger l) . C.setContacts (cas ^. cHosts) [] . C.setPortNumber (fromIntegral $ cas ^. cPort) . C.setKeyspace (cas ^. cKeyspace) . C.setProtocolVersion C.V4 $ C.defSettings cleanup :: (MonadIO m) => Env -> m () cleanup env = do C.shutdown (sparCassandra env) C.shutdown (brigCassandra env) Log.close (logger env) runMigrations :: Env -> [Migration] -> IO () runMigrations env migrations = do vmax <- latestMigrationVersion env let pendingMigrations = filter (\m -> version m > vmax) migrations if null pendingMigrations then info env "No new migrations." else info env "New migrations found." mapM_ (runMigration env) pendingMigrations runMigration :: Env -> Migration -> IO () runMigration env@Env {..} (Migration ver txt mig) = do info env $ "Running: [" <> show (migrationVersion ver) <> "] " <> Text.unpack txt mig env unless (dryRun == DryRun) $ persistVersion env ver txt =<< liftIO getCurrentTime latestMigrationVersion :: Env -> IO MigrationVersion latestMigrationVersion Env {..} = MigrationVersion . maybe 0 fromIntegral <$> C.runClient sparCassandra (C.query1 cql (C.params C.LocalQuorum ())) where cql :: C.QueryString C.R () (Identity Int32) cql = "select version from data_migration where id=1 order by version desc limit 1" persistVersion :: Env -> MigrationVersion -> Text -> UTCTime -> IO () persistVersion Env {..} (MigrationVersion v) desc time = C.runClient sparCassandra $ C.write cql (C.params C.LocalQuorum (fromIntegral v, desc, time)) where cql :: C.QueryString C.W (Int32, Text, UTCTime) () cql = "insert into data_migration (id, version, descr, date) values (1,?,?,?)" info :: Env -> String -> IO () info Env {..} msg = Log.info logger $ Log.msg $ msg
null
https://raw.githubusercontent.com/wireapp/wire-server/f72b09756102a5c66169cca0343aa7b7e6e54491/services/spar/migrate-data/src/Spar/DataMigration/Run.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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 Affero General Public License for more details. with this program. If not, see </>. (because the deprecated source table has been removed).
# LANGUAGE RecordWildCards # Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module Spar.DataMigration.Run where import qualified Cassandra as C import qualified Cassandra.Settings as C import Control.Lens import Control.Monad.Catch (finally) import qualified Data.Text as Text import Data.Time (UTCTime, getCurrentTime) import Imports import qualified Options.Applicative as Opts import Spar.DataMigration.Options (settingsParser) import Spar.DataMigration.Types import qualified Spar.DataMigration.V2_UserV2 as V2 import qualified System.Logger as Log main :: IO () main = do settings <- Opts.execParser (Opts.info (Opts.helper <*> settingsParser) desc) migrate settings V1.migration has been deleted in -server/pull/2768 V2.migration ] where desc = Opts.header "Spar Cassandra Data Migrations" <> Opts.fullDesc migrate :: MigratorSettings -> [Migration] -> IO () migrate settings ms = do env <- mkEnv settings runMigrations env ms `finally` cleanup env mkEnv :: MigratorSettings -> IO Env mkEnv settings = do lgr <- initLogger settings spar <- initCassandra (settings ^. setCasSpar) lgr brig <- initCassandra (settings ^. setCasBrig) lgr pure $ Env spar brig lgr (settings ^. setPageSize) (settings ^. setDebug) (settings ^. setDryRun) where initLogger s = Log.new . Log.setOutput Log.StdOut . Log.setFormat Nothing . Log.setBufSize 0 . Log.setLogLevel (if s ^. setDebug == Debug then Log.Debug else Log.Info) $ Log.defSettings initCassandra cas l = C.init . C.setLogger (C.mkLogger l) . C.setContacts (cas ^. cHosts) [] . C.setPortNumber (fromIntegral $ cas ^. cPort) . C.setKeyspace (cas ^. cKeyspace) . C.setProtocolVersion C.V4 $ C.defSettings cleanup :: (MonadIO m) => Env -> m () cleanup env = do C.shutdown (sparCassandra env) C.shutdown (brigCassandra env) Log.close (logger env) runMigrations :: Env -> [Migration] -> IO () runMigrations env migrations = do vmax <- latestMigrationVersion env let pendingMigrations = filter (\m -> version m > vmax) migrations if null pendingMigrations then info env "No new migrations." else info env "New migrations found." mapM_ (runMigration env) pendingMigrations runMigration :: Env -> Migration -> IO () runMigration env@Env {..} (Migration ver txt mig) = do info env $ "Running: [" <> show (migrationVersion ver) <> "] " <> Text.unpack txt mig env unless (dryRun == DryRun) $ persistVersion env ver txt =<< liftIO getCurrentTime latestMigrationVersion :: Env -> IO MigrationVersion latestMigrationVersion Env {..} = MigrationVersion . maybe 0 fromIntegral <$> C.runClient sparCassandra (C.query1 cql (C.params C.LocalQuorum ())) where cql :: C.QueryString C.R () (Identity Int32) cql = "select version from data_migration where id=1 order by version desc limit 1" persistVersion :: Env -> MigrationVersion -> Text -> UTCTime -> IO () persistVersion Env {..} (MigrationVersion v) desc time = C.runClient sparCassandra $ C.write cql (C.params C.LocalQuorum (fromIntegral v, desc, time)) where cql :: C.QueryString C.W (Int32, Text, UTCTime) () cql = "insert into data_migration (id, version, descr, date) values (1,?,?,?)" info :: Env -> String -> IO () info Env {..} msg = Log.info logger $ Log.msg $ msg
44ce288392a8d2a00451326acc114912344d93a5cf6c69f8c7140a42936c6fc1
camlp4/camlp4
ex_str_test.ml
(****************************************************************************) (* *) (* OCaml *) (* *) (* INRIA Rocquencourt *) (* *) Copyright 2007 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 LICENSE at the top of the Camlp4 *) (* source tree. *) (* *) (****************************************************************************) function <<foo>> -> <<bar>>
null
https://raw.githubusercontent.com/camlp4/camlp4/9b3314ea63288decb857239bd94f0c3342136844/camlp4/examples/ex_str_test.ml
ocaml
************************************************************************** OCaml INRIA Rocquencourt exception on linking described in LICENSE at the top of the Camlp4 source tree. **************************************************************************
Copyright 2007 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 function <<foo>> -> <<bar>>
466bec1be20e2cbac0cb5934300a29cb69ce3151dd701a4a4eea1f3f15c6b07d
miniway/kafka-clj
serializable_test.clj
(ns kafka.serializable-test (:use :reload-all (kafka types serializable) clojure.test)) ;(deftest test-pack-unpack ; (is (= "test" (String. (.bytes (pack "test")) "UTF8"))) ( is (= 123 ( Long . ( unpack ( pack 123 ) ) ) ) ) ; (is (= true (unpack (pack true)))) ( is (= [ 1 2 3 ] ( unpack ( pack [ 1 2 3 ] ) ) ) ) ( is (= { : a 1 } ( unpack ( pack { : a 1 } ) ) ) ) ; (is (= '(+ 1 2 3) (unpack (pack '(+ 1 2 3))))) ; (let [now (java.util.Date.)] ; (is (= now (unpack (pack now))))) ;)
null
https://raw.githubusercontent.com/miniway/kafka-clj/6cbeb631e87a98ba1b737823ff0493e1ccca6847/test/kafka/serializable_test.clj
clojure
(deftest test-pack-unpack (is (= "test" (String. (.bytes (pack "test")) "UTF8"))) (is (= true (unpack (pack true)))) (is (= '(+ 1 2 3) (unpack (pack '(+ 1 2 3))))) (let [now (java.util.Date.)] (is (= now (unpack (pack now))))) )
(ns kafka.serializable-test (:use :reload-all (kafka types serializable) clojure.test)) ( is (= 123 ( Long . ( unpack ( pack 123 ) ) ) ) ) ( is (= [ 1 2 3 ] ( unpack ( pack [ 1 2 3 ] ) ) ) ) ( is (= { : a 1 } ( unpack ( pack { : a 1 } ) ) ) )
dc909fc6011d6b99165f35668f1d96b10663856308e05194cbf3e410ee7c272e
lambda-pi-plus/lambda-pi-plus
Internals.hs
{-# LANGUAGE QuasiQuotes #-} # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # module Language.LambdaPiPlus.Internals where import Common import qualified ConstraintBased as CB import Main import qualified PatternUnify.Tm as Tm import Text.Parsec import Text.Parsec.Pos (SourcePos) import Control.Monad.Writer import qualified Unbound.Generics.LocallyNameless as LN import Language.Haskell.TH.Lift import Control.Monad (foldM) type CompileM = Either [(Maybe SourcePos, String)] type CompileContext = Common.State Tm.VAL Tm.VAL type ParseResult = [Stmt ITerm_ CTerm_] emptyContext = (True, [], lpve, lpte) int = lp CB.checker parse :: String -> CompileM ParseResult parse source = parseSimple "editor-window" (many (isparse int)) source compile :: [Stmt ITerm_ CTerm_] -> CompileContext -> CompileM (CompileContext, String) compile stmts context = foldM (doStmt $ lp CB.checker) (context, "") stmts doStmt :: LpInterp -> (CompileContext, String) -> Stmt ITerm_ CTerm_ -> CompileM (CompileContext, String) doStmt int (state@(inter, out, ve, te), output) stmt = do case stmt of Assume assm -> foldM (doAssume) (state, output) assm Let x e -> checkEval x e Eval e -> checkEval it e PutStrLn x -> return (state, output ++ x ++"\n") Out f -> return ((inter, f, ve, te), output) where -- checkEval :: String -> i -> IO (State v inf) checkEval i t = doCheck int (state, output) i t (\ (y, v) -> ((inter, "", (Global i, v) : ve, (Global i, ihastype int y) : te))) modOutput ident y v subs output = output ++ makeOutText int ident y v subs ++ "\n" ++ solvedMetasString int subs ++ "\n\n" doAssume :: (CompileContext, String) -> (String, CTerm_) -> CompileM (CompileContext, String) doAssume (state@(inter, out, ve, te), output) (x, t) = doCheck (lp CB.checker) (state, output) x (builtin $ Ann_ t (builtin $ Inf_ $ builtin $ Star_)) (\ (y, v) -> ((inter, out, ve, (Global x, v) : te))) doCheck :: LpInterp -> (CompileContext, String) -> String -> ITerm_ -> ((Tm.Type, Tm.VAL) -> CompileContext) -> CompileM (CompileContext, String) doCheck int (state@(inter, out, ve, te), output) ident t k = do and evaluate (y, newVal, subs) <- iitype int ve te t let v = ieval int ve t return (k (y, newVal), modOutput ident y v subs output) $(deriveLiftMany [''Common.Name, ''Common.ITerm_', ''Common.CTerm_', ''Common.Located, ''Common.Region, ''SourcePos, ''LN.Name, ''LN.Bind, ''Tm.Elim, ''Tm.Head, ''Tm.Twin, ''Tm.Can, ''Tm.VAL])
null
https://raw.githubusercontent.com/lambda-pi-plus/lambda-pi-plus/78eba7ebb7b2ed94f7cb06f0d1aca4d07eb3626f/src/Language/LambdaPiPlus/Internals.hs
haskell
# LANGUAGE QuasiQuotes # checkEval :: String -> i -> IO (State v inf)
# LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # module Language.LambdaPiPlus.Internals where import Common import qualified ConstraintBased as CB import Main import qualified PatternUnify.Tm as Tm import Text.Parsec import Text.Parsec.Pos (SourcePos) import Control.Monad.Writer import qualified Unbound.Generics.LocallyNameless as LN import Language.Haskell.TH.Lift import Control.Monad (foldM) type CompileM = Either [(Maybe SourcePos, String)] type CompileContext = Common.State Tm.VAL Tm.VAL type ParseResult = [Stmt ITerm_ CTerm_] emptyContext = (True, [], lpve, lpte) int = lp CB.checker parse :: String -> CompileM ParseResult parse source = parseSimple "editor-window" (many (isparse int)) source compile :: [Stmt ITerm_ CTerm_] -> CompileContext -> CompileM (CompileContext, String) compile stmts context = foldM (doStmt $ lp CB.checker) (context, "") stmts doStmt :: LpInterp -> (CompileContext, String) -> Stmt ITerm_ CTerm_ -> CompileM (CompileContext, String) doStmt int (state@(inter, out, ve, te), output) stmt = do case stmt of Assume assm -> foldM (doAssume) (state, output) assm Let x e -> checkEval x e Eval e -> checkEval it e PutStrLn x -> return (state, output ++ x ++"\n") Out f -> return ((inter, f, ve, te), output) where checkEval i t = doCheck int (state, output) i t (\ (y, v) -> ((inter, "", (Global i, v) : ve, (Global i, ihastype int y) : te))) modOutput ident y v subs output = output ++ makeOutText int ident y v subs ++ "\n" ++ solvedMetasString int subs ++ "\n\n" doAssume :: (CompileContext, String) -> (String, CTerm_) -> CompileM (CompileContext, String) doAssume (state@(inter, out, ve, te), output) (x, t) = doCheck (lp CB.checker) (state, output) x (builtin $ Ann_ t (builtin $ Inf_ $ builtin $ Star_)) (\ (y, v) -> ((inter, out, ve, (Global x, v) : te))) doCheck :: LpInterp -> (CompileContext, String) -> String -> ITerm_ -> ((Tm.Type, Tm.VAL) -> CompileContext) -> CompileM (CompileContext, String) doCheck int (state@(inter, out, ve, te), output) ident t k = do and evaluate (y, newVal, subs) <- iitype int ve te t let v = ieval int ve t return (k (y, newVal), modOutput ident y v subs output) $(deriveLiftMany [''Common.Name, ''Common.ITerm_', ''Common.CTerm_', ''Common.Located, ''Common.Region, ''SourcePos, ''LN.Name, ''LN.Bind, ''Tm.Elim, ''Tm.Head, ''Tm.Twin, ''Tm.Can, ''Tm.VAL])
018ece6344c80f203b531860c7ad40564826cab22f9609fde447dab42ec0a9e2
mransan/ocaml-protoc
pb_codegen_default.mli
(** Code generator for the [default] function *) include Pb_codegen_sig.S val gen_record_mutable : gen_file_suffix:string -> module_prefix:string -> Pb_codegen_ocaml_type.record -> Pb_codegen_formatting.scope -> unit
null
https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/compilerlib/pb_codegen_default.mli
ocaml
* Code generator for the [default] function
include Pb_codegen_sig.S val gen_record_mutable : gen_file_suffix:string -> module_prefix:string -> Pb_codegen_ocaml_type.record -> Pb_codegen_formatting.scope -> unit
16a23c76a1a9cca019d0ea22a6e449b2bc7f339e7b1c5b788e062cbd681cfbb7
rmloveland/scheme48-0.53
values.scm
Copyright ( c ) 1994 by . See file COPYING . (define (sender) (values 1 2 3 4)) (define (receiver a b c d) (+ a (- b (* c d)))) (define (test) (call-with-values sender receiver))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/ps-compiler/prescheme/test/values.scm
scheme
Copyright ( c ) 1994 by . See file COPYING . (define (sender) (values 1 2 3 4)) (define (receiver a b c d) (+ a (- b (* c d)))) (define (test) (call-with-values sender receiver))
26313653eaa1d6d958ea3b3574182124945c689a98def46e880a2bc13e0de0e8
chenyukang/eopl
tests.scm
(module tests mzscheme (provide test-list) ;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;; (define test-list '( ;; simple arithmetic (positive-const "11" 11) (negative-const "-33" -33) (simple-arith-1 "-(44,33)" 11) ;; nested arithmetic (nested-arith-left "-(-(44,33),22)" -11) (nested-arith-right "-(55, -(22,11))" 44) ;; simple variables (test-var-1 "x" 10) (test-var-2 "-(x,1)" 9) (test-var-3 "-(1,x)" -9) ;; simple unbound variables (test-unbound-var-1 "foo" error) (test-unbound-var-2 "-(x,foo)" error) ;; simple conditionals (if-true "if zero?(0) then 3 else 4" 3) (if-false "if zero?(1) then 3 else 4" 4) ;; test dynamic typechecking (no-bool-to-diff-1 "-(zero?(0),1)" error) (no-bool-to-diff-2 "-(1,zero?(0))" error) (no-int-to-if "if 1 then 2 else 3" error) ;; make sure that the test and both arms get evaluated ;; properly. (if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3) (if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4) ;; and make sure the other arm doesn't get evaluated. (if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3) (if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4) ;; simple let (simple-let-1 "let x = 3 in x" 3) make sure the body and rhs get evaluated (eval-let-body "let x = 3 in -(x,1)" 2) (eval-let-rhs "let x = -(4,1) in -(x,1)" 2) ;; check nested let and shadowing (simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1) (check-shadowing-in-body "let x = 3 in let x = 4 in x" 4) (check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2) ;; simple applications (apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29) (apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29) (let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29) (nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1) (nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)" -1) (y-combinator-1 " let fix = proc (f) let d = proc (x) proc (z) ((f (x x)) z) in proc (n) ((f (d d)) n) in let t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4) in let times4 = (fix t4m) in (times4 3)" 12) ;; simple letrecs (simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32) (simple-letrec-2 "letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)" 8) (simple-letrec-3 "let m = -5 in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)" 20) ; (fact-of-6 "letrec fact(x ) = if ) then 1 else * ( x , ( fact ) ) ) in ( fact 6 ) " 720 ) (HO-nested-letrecs "letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1)) in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1)) in (odd 13)" 1) (begin-test-1 "begin 1; 2; 3 end" 3) (assignment-test-1 "let x = 17 in begin set x = 27; x end" 27) (gensym-test "let g = let count = 0 in proc(d) let d = set count = -(count,-1) in count in -((g 11), (g 22))" -1) (even-odd-via-set " let x = 0 in letrec even(d) = if zero?(x) then 1 else let d = set x = -(x,1) in (odd d) odd(d) = if zero?(x) then 0 else let d = set x = -(x,1) in (even d) in let d = set x = 13 in (odd -99)" 1) (simple-mutpair-left-1 "let p = newpair(22,33) in left(p)" 22) (simple-mutpair-right-1 "let p = newpair(22,33) in right(p)" 33) (simple-mutpair-setleft-1 " left(p ) end " 77 ) (simple-mutpair-setleft-2 " right(p ) end " 33 ) (simple-mutpair-setright-1 " right(p ) end " 77 ) (simple-mutpair-setright-2 " left(p ) end " 22 ) (gensym-using-mutable-pair-left "let g = let count = newpair(0,0) in proc (dummy) begin setleft count = -(left(count), -1); left(count) end in -((g 22), (g 22))" -1) (gensym-using-mutable-pair-right "let g = let count = newpair(0,0) in proc (dummy) begin setright count = -(right(count), -1); right(count) end in -((g 22), (g 22))" -1) ;; new for call-by-reference (cbr-swap-1 "let swap = proc (x) proc (y) let temp = x in begin set x = y; set y = temp end in let a = 33 in let b = 44 in begin ((swap a) b); -(a,b) end" 11) (cbr-global-aliasing-1 "let p = proc (z) set z = 44 in let x = 33 in begin (p x); x end" 44) (cbr-direct-aliasing-1 "let p = proc (x) proc (y) begin set x = 44; y end in let b = 33 in ((p b) b)" 44) (cbr-indirect-aliasing-1 ;; in this language, you can't return a reference. "let p = proc (x) proc (y) begin set x = 44; y end in let q = proc(z) z in let b = 33 in ((p b) (q b))" 33) (cbr-indirect-aliasing-2 ;; in this language, you can't return a reference. "let p = proc (x) proc (y) begin set x = 44; y end in let q = proc(z) z in let b = 33 in ((p (q b)) b)" 33) (cbr-sideeffect-a-passed-structure-1 "let f = proc (x) setleft x = -(left(x),-1) in let p = newpair (44,newpair(55,66)) in begin (f right(p)); left(right(p)) end" 56) (cbr-example-for-book " let f = proc (x) set x = 44 in let g = proc (y) (f y) in let z = 55 in begin (g z); z end" 44) )) )
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter4/call-by-reference/tests.scm
scheme
tests ;;;;;;;;;;;;;;;; simple arithmetic nested arithmetic simple variables simple unbound variables simple conditionals test dynamic typechecking make sure that the test and both arms get evaluated properly. and make sure the other arm doesn't get evaluated. simple let check nested let and shadowing simple applications simple letrecs (fact-of-6 "letrec x end" new for call-by-reference x end" in this language, you can't return a reference. in this language, you can't return a reference.
(module tests mzscheme (provide test-list) (define test-list '( (positive-const "11" 11) (negative-const "-33" -33) (simple-arith-1 "-(44,33)" 11) (nested-arith-left "-(-(44,33),22)" -11) (nested-arith-right "-(55, -(22,11))" 44) (test-var-1 "x" 10) (test-var-2 "-(x,1)" 9) (test-var-3 "-(1,x)" -9) (test-unbound-var-1 "foo" error) (test-unbound-var-2 "-(x,foo)" error) (if-true "if zero?(0) then 3 else 4" 3) (if-false "if zero?(1) then 3 else 4" 4) (no-bool-to-diff-1 "-(zero?(0),1)" error) (no-bool-to-diff-2 "-(1,zero?(0))" error) (no-int-to-if "if 1 then 2 else 3" error) (if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3) (if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4) (if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3) (if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4) (simple-let-1 "let x = 3 in x" 3) make sure the body and rhs get evaluated (eval-let-body "let x = 3 in -(x,1)" 2) (eval-let-rhs "let x = -(4,1) in -(x,1)" 2) (simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1) (check-shadowing-in-body "let x = 3 in let x = 4 in x" 4) (check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2) (apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29) (apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29) (let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29) (nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1) (nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)" -1) (y-combinator-1 " let fix = proc (f) let d = proc (x) proc (z) ((f (x x)) z) in proc (n) ((f (d d)) n) in let t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4) in let times4 = (fix t4m) in (times4 3)" 12) (simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32) (simple-letrec-2 "letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)" 8) (simple-letrec-3 "let m = -5 in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)" 20) fact(x ) = if ) then 1 else * ( x , ( fact ) ) ) in ( fact 6 ) " 720 ) (HO-nested-letrecs "letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1)) in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1)) in (odd 13)" 1) (begin-test-1 "begin 1; 2; 3 end" 3) (assignment-test-1 "let x = 17 27) (gensym-test "let g = let count = 0 in proc(d) let d = set count = -(count,-1) in count in -((g 11), (g 22))" -1) (even-odd-via-set " let x = 0 in letrec even(d) = if zero?(x) then 1 else let d = set x = -(x,1) in (odd d) odd(d) = if zero?(x) then 0 else let d = set x = -(x,1) in (even d) in let d = set x = 13 in (odd -99)" 1) (simple-mutpair-left-1 "let p = newpair(22,33) in left(p)" 22) (simple-mutpair-right-1 "let p = newpair(22,33) in right(p)" 33) (simple-mutpair-setleft-1 " left(p ) end " 77 ) (simple-mutpair-setleft-2 " right(p ) end " 33 ) (simple-mutpair-setright-1 " right(p ) end " 77 ) (simple-mutpair-setright-2 " left(p ) end " 22 ) (gensym-using-mutable-pair-left "let g = let count = newpair(0,0) in proc (dummy) begin left(count) end in -((g 22), (g 22))" -1) (gensym-using-mutable-pair-right "let g = let count = newpair(0,0) in proc (dummy) begin right(count) end in -((g 22), (g 22))" -1) (cbr-swap-1 "let swap = proc (x) proc (y) let temp = x in begin set y = temp end in let a = 33 in let b = 44 in begin -(a,b) end" 11) (cbr-global-aliasing-1 "let p = proc (z) set z = 44 in let x = 33 44) (cbr-direct-aliasing-1 "let p = proc (x) proc (y) begin y end in let b = 33 in ((p b) b)" 44) (cbr-indirect-aliasing-1 "let p = proc (x) proc (y) begin y end in let q = proc(z) z in let b = 33 in ((p b) (q b))" 33) (cbr-indirect-aliasing-2 "let p = proc (x) proc (y) begin y end in let q = proc(z) z in let b = 33 in ((p (q b)) b)" 33) (cbr-sideeffect-a-passed-structure-1 "let f = proc (x) setleft x = -(left(x),-1) in let p = newpair (44,newpair(55,66)) in begin left(right(p)) end" 56) (cbr-example-for-book " let f = proc (x) set x = 44 in let g = proc (y) (f y) in let z = 55 in begin z end" 44) )) )
395fbab036d2182b32096e791324d55a806d2e331345335ecff6e3c10db5081f
arttuka/reagent-material-ui
arrow_outward_outlined.cljs
(ns reagent-mui.icons.arrow-outward-outlined "Imports @mui/icons-material/ArrowOutwardOutlined as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def arrow-outward-outlined (create-svg-icon (e "path" #js {"d" "M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"}) "ArrowOutwardOutlined"))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/arrow_outward_outlined.cljs
clojure
(ns reagent-mui.icons.arrow-outward-outlined "Imports @mui/icons-material/ArrowOutwardOutlined as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def arrow-outward-outlined (create-svg-icon (e "path" #js {"d" "M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"}) "ArrowOutwardOutlined"))
98228448b075b14cd2fb3822319847264bb35538f6dbd167654633f31f83bf96
yallop/ocaml-ctypes
test_coercions.ml
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes (* Check coercions between pointers. *) let test_pointer_coercions _ = let module M = struct type boxed_type = T : 'a typ -> boxed_type let types = [ T void; T int8_t; T uint16_t; T int; T float; T short; T complex64; T (ptr double); T string; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4); ] Check that we can construct a coercion between any two pointer types let () = ListLabels.iter types ~f:(fun (T t1) -> ListLabels.iter types ~f:(fun (T t2) -> let _ = coerce (ptr t1) (ptr t2) in ())) (* Check that pointer coercions are value-preserving. *) let v = 10 let p = allocate int v let p' = coerce (ptr float) (ptr int) (coerce (ptr int) (ptr float) p) let () = assert_equal p p' end in () Check that coercions between a pointer to a struct and a pointer to its first member succeed . Check that coercions between a pointer to a struct and a pointer to its first member succeed. *) let test_struct_first_member_coercions _ = let module M = struct let s = structure "s" let f = field s "f" double let i = field s "i" int let () = seal s let () = begin let v = make s in let p = coerce (ptr s) (ptr double) (addr v) in setf v f 5.5; assert_equal !@p 5.5; p <-@ 6.6; assert_equal (getf v f) 6.6 end end in () (* Check that coercions between a pointer to a union and a pointer to a member succeed. *) let test_union_coercions _ = let module M = struct let u = union "u" let f = field u "f" double let i = field u "i" int let () = seal u let () = begin let v = make u in let pf = coerce (ptr u) (ptr double) (addr v) in let pi = coerce (ptr u) (ptr int) (addr v) in setf v f 5.5; assert_equal !@pf 5.5; pi <-@ 12; assert_equal (getf v i) 12; setf v i 14; assert_equal !@pi 14; pf <-@ 6.6; assert_equal (getf v f) 6.6; end end in () (* Check coercions between views. *) let test_view_coercions _ = let module M = struct type 'a variant = V of 'a let unV (V v) = v and inV v = V v let variant_view v = view v ~read:inV ~write:unV type 'a record = { r : 'a } let record_view v = view v ~read:(fun r -> {r}) ~write:(fun {r} -> r) let pintvv = variant_view (variant_view (ptr int)) let pintr = record_view (ptr int) let () = begin let pi = allocate int 100 in let v = allocate pintvv (V (V pi)) in assert_equal !@((coerce pintvv pintr !@v).r) 100 end end in () module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module M = Functions.Stubs(S) open M (* Check coercions between functions. *) let test_function_coercions _ = let isize_t = view size_t ~read:Unsigned.Size_t.to_int ~write:Unsigned.Size_t.of_int in let memchr' = coerce_fn (ptr void @-> int @-> size_t @-> returning (ptr void)) (string @-> int8_t @-> isize_t @-> returning string_opt) memchr in begin assert_equal (memchr' "foobar" (Char.code 'b') 4) (Some "bar") ; assert_equal (memchr' "foobar" (Char.code 'b') 2) None ; end end (* Check that identity coercions are cost-free. *) let test_identity_coercions _ = let f = fun x y -> x in let fn = int @-> float @-> returning int in let f' = coerce_fn fn fn f in assert_bool "identity coercions are free" (f' == f) let test_unsigned_coercions _ = assert_equal (Unsigned.UInt8.of_int 256) (Unsigned.UInt8.of_int 0); assert_equal (Unsigned.UInt16.of_int (1 lsl 16)) (Unsigned.UInt16.of_int 0) (* Check that coercions between unsupported types raise an exception *) let test_unsupported_coercions _ = let module M = struct type boxed_type = T : 'a typ -> boxed_type let types = [ T int8_t, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T uint16_t, [T int8_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T int, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T float, [T int8_t; T uint16_t; T int; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T ldouble, [T int8_t; T uint16_t; T int; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T short, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T complex64, [T int8_t; T uint16_t; T int; T float; T short; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T complexld, [T int8_t; T uint16_t; T int; T short; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (bigarray array1 10 Bigarray_compat.int32), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (array 5 int32_t), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (structure "s"), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (union "u"), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (abstract ~name:"a" ~size:12 ~alignment:4), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T ocaml_string, [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; ] (* None of the types in the list are currently intercoercible. *) let () = ListLabels.iter types ~f:(fun (T t1, ts) -> ListLabels.iter ts ~f:(fun (T t2) -> try let _ : _ -> _ = coerce t1 t2 in assert_failure "coercion unexpectedly succeeded" with Uncoercible _ -> ())) end in () module Foreign_tests = Common_tests(Tests_common.Foreign_binder) module Stub_tests = Common_tests(Generated_bindings) let suite = "Coercsion tests" >::: ["test pointer coercions" >:: test_pointer_coercions; "test struct first member coercions" >:: test_struct_first_member_coercions; "test union coercions" >:: test_union_coercions; "test view coercions" >:: test_view_coercions; "test function coercions (foreign)" >:: Foreign_tests.test_function_coercions; "test function coercions (stubs)" >:: Stub_tests.test_function_coercions; "test identity coercions" >:: test_identity_coercions; "test unsupported coercions" >:: test_unsupported_coercions; "test unsigned integer coersions" >:: test_unsigned_coercions ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-coercions/test_coercions.ml
ocaml
Check coercions between pointers. Check that pointer coercions are value-preserving. Check that coercions between a pointer to a union and a pointer to a member succeed. Check coercions between views. Check coercions between functions. Check that identity coercions are cost-free. Check that coercions between unsupported types raise an exception None of the types in the list are currently intercoercible.
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes let test_pointer_coercions _ = let module M = struct type boxed_type = T : 'a typ -> boxed_type let types = [ T void; T int8_t; T uint16_t; T int; T float; T short; T complex64; T (ptr double); T string; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4); ] Check that we can construct a coercion between any two pointer types let () = ListLabels.iter types ~f:(fun (T t1) -> ListLabels.iter types ~f:(fun (T t2) -> let _ = coerce (ptr t1) (ptr t2) in ())) let v = 10 let p = allocate int v let p' = coerce (ptr float) (ptr int) (coerce (ptr int) (ptr float) p) let () = assert_equal p p' end in () Check that coercions between a pointer to a struct and a pointer to its first member succeed . Check that coercions between a pointer to a struct and a pointer to its first member succeed. *) let test_struct_first_member_coercions _ = let module M = struct let s = structure "s" let f = field s "f" double let i = field s "i" int let () = seal s let () = begin let v = make s in let p = coerce (ptr s) (ptr double) (addr v) in setf v f 5.5; assert_equal !@p 5.5; p <-@ 6.6; assert_equal (getf v f) 6.6 end end in () let test_union_coercions _ = let module M = struct let u = union "u" let f = field u "f" double let i = field u "i" int let () = seal u let () = begin let v = make u in let pf = coerce (ptr u) (ptr double) (addr v) in let pi = coerce (ptr u) (ptr int) (addr v) in setf v f 5.5; assert_equal !@pf 5.5; pi <-@ 12; assert_equal (getf v i) 12; setf v i 14; assert_equal !@pi 14; pf <-@ 6.6; assert_equal (getf v f) 6.6; end end in () let test_view_coercions _ = let module M = struct type 'a variant = V of 'a let unV (V v) = v and inV v = V v let variant_view v = view v ~read:inV ~write:unV type 'a record = { r : 'a } let record_view v = view v ~read:(fun r -> {r}) ~write:(fun {r} -> r) let pintvv = variant_view (variant_view (ptr int)) let pintr = record_view (ptr int) let () = begin let pi = allocate int 100 in let v = allocate pintvv (V (V pi)) in assert_equal !@((coerce pintvv pintr !@v).r) 100 end end in () module Common_tests(S : Cstubs.FOREIGN with type 'a result = 'a and type 'a return = 'a) = struct module M = Functions.Stubs(S) open M let test_function_coercions _ = let isize_t = view size_t ~read:Unsigned.Size_t.to_int ~write:Unsigned.Size_t.of_int in let memchr' = coerce_fn (ptr void @-> int @-> size_t @-> returning (ptr void)) (string @-> int8_t @-> isize_t @-> returning string_opt) memchr in begin assert_equal (memchr' "foobar" (Char.code 'b') 4) (Some "bar") ; assert_equal (memchr' "foobar" (Char.code 'b') 2) None ; end end let test_identity_coercions _ = let f = fun x y -> x in let fn = int @-> float @-> returning int in let f' = coerce_fn fn fn f in assert_bool "identity coercions are free" (f' == f) let test_unsigned_coercions _ = assert_equal (Unsigned.UInt8.of_int 256) (Unsigned.UInt8.of_int 0); assert_equal (Unsigned.UInt16.of_int (1 lsl 16)) (Unsigned.UInt16.of_int 0) let test_unsupported_coercions _ = let module M = struct type boxed_type = T : 'a typ -> boxed_type let types = [ T int8_t, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T uint16_t, [T int8_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T int, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T float, [T int8_t; T uint16_t; T int; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T ldouble, [T int8_t; T uint16_t; T int; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T short, [T uint16_t; T float; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T complex64, [T int8_t; T uint16_t; T int; T float; T short; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T complexld, [T int8_t; T uint16_t; T int; T short; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (bigarray array1 10 Bigarray_compat.int32), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (array 5 int32_t), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (structure "s"), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (union "u"), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T (abstract ~name:"a" ~size:12 ~alignment:4), [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; T ocaml_string, [T int8_t; T uint16_t; T int; T float; T short; T complex64; T (bigarray array1 10 Bigarray_compat.int32); T (array 5 int32_t); T (structure "s"); T (union "u"); T (abstract ~name:"a" ~size:12 ~alignment:4)]; ] let () = ListLabels.iter types ~f:(fun (T t1, ts) -> ListLabels.iter ts ~f:(fun (T t2) -> try let _ : _ -> _ = coerce t1 t2 in assert_failure "coercion unexpectedly succeeded" with Uncoercible _ -> ())) end in () module Foreign_tests = Common_tests(Tests_common.Foreign_binder) module Stub_tests = Common_tests(Generated_bindings) let suite = "Coercsion tests" >::: ["test pointer coercions" >:: test_pointer_coercions; "test struct first member coercions" >:: test_struct_first_member_coercions; "test union coercions" >:: test_union_coercions; "test view coercions" >:: test_view_coercions; "test function coercions (foreign)" >:: Foreign_tests.test_function_coercions; "test function coercions (stubs)" >:: Stub_tests.test_function_coercions; "test identity coercions" >:: test_identity_coercions; "test unsupported coercions" >:: test_unsupported_coercions; "test unsigned integer coersions" >:: test_unsigned_coercions ] let _ = run_test_tt_main suite
cd1c66c20dc7d81fa48f56e9a67754f33ed40028cda6d8b252abfbe39e73b3e2
ocaml-ppx/cinaps
non_staged_error.ml
let error_message = "the direct mode of cinaps is no longer supported. Please use the \"cinaps\" stanza in \ your dune file instead." ;;
null
https://raw.githubusercontent.com/ocaml-ppx/cinaps/2791bce694bfea6ab077f13fc2987fb56fa5006f/src/non_staged_error.ml
ocaml
let error_message = "the direct mode of cinaps is no longer supported. Please use the \"cinaps\" stanza in \ your dune file instead." ;;
7ee8aaec95be8557813e53bcf5aee0e8d6eb853e007728ac0f05661338850a72
lisp-mirror/clpm
vcs.lisp
Sources for projects taken from source control . A VCS source requires a ;;;; repo to be checked out before much can be done with it. ;;;; This software is part of CLPM . See README.org for more information . See ;;;; LICENSE for license information. ;; * define package (uiop:define-package #:clpm/sources/vcs (:use #:cl #:alexandria #:anaphora #:clpm/archives #:clpm/groveler #:clpm/install/defs #:clpm/log #:clpm/repos #:clpm/requirement #:clpm/session #:clpm/sources/defs #:clpm/utils) (:export #:*vcs-project-override-fun* #:ensure-vcs-release-installed! #:make-vcs-release #:vcs-local-release #:vcs-project/cache-directory #:vcs-project/path #:vcs-release #:vcs-release-commit #:vcs-remote-release #:vcs-source #:vcs-source-clear-visible-releases #:vcs-source-project #:vcs-system)) (in-package #:clpm/sources/vcs) (setup-logger) ;; * sources (defclass vcs-source (clpm-source) ((name :initarg :name :reader source-name) (repo :initarg :repo :reader vcs-source-repo) (project :accessor vcs-source-project :documentation "The single project for the source.") (systems-by-name :initform (make-hash-table :test 'equalp) :accessor vcs-source-systems-by-name :documentation "A hash table mapping system names to system objects.")) (:documentation "A source for any bare VCS projects. Projects must be registered with the source using VCS-SOURCE-REGISTER_PROJECT!.")) (defmethod make-source ((type (eql 'vcs-source)) &key repo project-name) (let* ((repo-object (make-repo-from-description repo)) (name (repo-to-form repo-object))) (with-clpm-session (:key `(make-source ,type ,name)) (make-instance type :name name :project-name project-name :repo repo-object)))) (defmethod initialize-instance :after ((source vcs-source) &key project-name) (setf (vcs-source-project source) (make-instance 'vcs-project :source source :name project-name))) (defun vcs-source-clear-visible-releases (vcs-source) (setf (vcs-project-visible-releases (vcs-source-project vcs-source)) nil)) (defmethod source-ensure-system ((source vcs-source) system-name) (ensure-gethash system-name (vcs-source-systems-by-name source) (make-instance 'vcs-system :source source :name system-name))) (defmethod source-can-lazy-sync-p ((source vcs-source)) t) (defmethod source-project ((source vcs-source) project-name &optional (error t)) (if (equal project-name (project-name (vcs-source-project source))) (vcs-source-project source) (when error (error 'source-missing-project :source source :project-name project-name)))) (defmethod source-system ((source vcs-source) system-name &optional (error t)) (or (gethash system-name (vcs-source-systems-by-name source)) (some (lambda (release) (when-let ((system-release (release-system-release release system-name nil))) (system-release-system system-release))) (project-releases (vcs-source-project source))) (when error (error 'source-missing-system :source source :system-name system-name)))) (defmethod source-to-form ((source vcs-source)) (let ((project (vcs-source-project source))) `(:implicit-vcs :type :vcs :projects ((,(project-name project) . ,(repo-to-form (project-repo project))))))) (defmethod sync-source ((source vcs-source)) nil) ;; * projects ;; ** Overrides (defvar *vcs-project-override-fun* (constantly nil) "A function that, given a project name returns either NIL or a directory pathname. If a directory pathname is returned, then that is assumed to be a local override when requesting a VCS release.") (defun make-vcs-release (source project ref &key (local-release-class 'vcs-local-release) (remote-release-class 'vcs-remote-release)) (let ((override-pathname (funcall *vcs-project-override-fun* (project-name project)))) (if override-pathname (make-instance local-release-class :source source :project project :ref ref :repo (make-instance 'local-git-override-repo :pathname override-pathname)) (make-instance remote-release-class :source source :project project :ref ref)))) ;; ** Projects (defclass vcs-project (clpm-project) ((source :initarg :source :reader project-source) (name :initarg :name :reader project-name) (visible-releases :initform nil :accessor vcs-project-visible-releases) (releases-by-spec :initform (make-hash-table :test 'equal) :accessor vcs-project-releases-by-spec))) (defmethod project-repo ((project vcs-project)) (vcs-source-repo (project-source project))) (defmethod project-releases ((project vcs-project)) (vcs-project-visible-releases project)) (defmethod project-release ((project vcs-project) (version string) &optional (error t)) "A release named by a string is assumed to refer to a commit." (project-release project `(:commit ,version) error)) (defmethod project-release ((project vcs-project) (version list) &optional error) (declare (ignore error)) (apply #'project-vcs-release project version)) (defmethod project-vcs-release ((project vcs-project) &key commit branch tag ref) (let* ((ref (cond (commit `(:commit ,commit)) (branch `(:branch ,branch)) (tag `(:tag ,tag)) (ref `(:ref ,ref)))) (release (ensure-gethash ref (vcs-project-releases-by-spec project) (make-vcs-release (project-source project) project ref)))) (pushnew release (vcs-project-visible-releases project)) (unless commit (setf release (ensure-gethash `(:commit ,(vcs-release-commit release)) (vcs-project-releases-by-spec project) release))) release)) ;; * releases (defclass vcs-release () ((source :initarg :source :reader release-source) (project :initarg :project :reader release-project) (commit :initarg :commit :accessor vcs-release-commit) (installed-p :initform nil :accessor vcs-release-installed-p) (system-files-by-namestring :accessor vcs-release-system-files-by-namestring) (system-files-by-primary-name :accessor vcs-release-system-files-by-primary-name) (system-releases-by-name :initform (make-hash-table :test 'equal) :accessor vcs-release-system-releases-by-name))) (defclass vcs-remote-release (vcs-release) () (:documentation "Represents a release fetched from a remote repository.")) (defclass vcs-local-release (vcs-release) ((installed-p :initform t) (repo :initarg :repo :reader vcs-release-repo)) (:documentation "Represents a release that uses a user managed local repository.")) (defmethod initialize-instance :after ((release vcs-remote-release) &rest initargs &key ref) (declare (ignore initargs)) (vcs-release-resolve! release ref)) (defmethod initialize-instance :after ((release vcs-local-release) &rest initargs &key ref) (declare (ignore initargs)) (destructuring-bind (ref-type ref-name) ref (ecase ref-type (:branch ;; Error unless the target branch name matches the actual branch name. (let ((current-branch-name (repo-current-branch (vcs-release-repo release)))) (unless (equal ref-name current-branch-name) (log:error "In order to use local overrides, branch names must match. Expected: ~a, actual: ~a" ref-name current-branch-name) (error "In order to use local overrides, branch names must match. Expected: ~a, actual: ~a" ref-name current-branch-name)))) (:commit ;; Warn if the desired commit is not present in the repo. (unless (ref-present-p (vcs-release-repo release) ref) (log:warn "Commit ~A is not present in the local override. Your local repo may not be up to date!" ref-name) (warn "Commit ~A is not present in the local override. Your local repo may not be up to date!" ref-name))))) (setf (vcs-release-commit release) (repo-current-commit (vcs-release-repo release)))) (defmethod vcs-release-repo ((release vcs-remote-release)) (project-repo (release-project release))) (defun populate-release-system-files! (release) (ensure-release-installed! release) (let ((ht-by-namestring (make-hash-table :test 'equal)) (ht-by-primary-name (make-hash-table :test 'equalp))) (asdf::collect-sub*directories-asd-files (release-lib-pathname release) :collect (lambda (x) (let* ((namestring (enough-namestring x (release-lib-pathname release))) (system-file (make-instance 'vcs-system-file :relative-pathname namestring :release release :source (release-source release))) (primary-system-name (pathname-name x))) (setf (gethash namestring ht-by-namestring) system-file) (setf (gethash primary-system-name ht-by-primary-name) system-file)))) (setf (vcs-release-system-files-by-namestring release) ht-by-namestring) (setf (vcs-release-system-files-by-primary-name release) ht-by-primary-name))) (defmethod slot-unbound (class (release vcs-release) (slot-name (eql 'system-files-by-namestring))) (populate-release-system-files! release) (vcs-release-system-files-by-namestring release)) (defmethod slot-unbound (class (release vcs-release) (slot-name (eql 'system-files-by-primary-name))) (populate-release-system-files! release) (vcs-release-system-files-by-primary-name release)) (defmethod release-system-files ((release vcs-release)) (hash-table-values (vcs-release-system-files-by-namestring release))) (defmethod release-system-file ((release vcs-release) system-file-namestring) "Requires the release to be installed. Return a system file object if not already created." (gethash system-file-namestring (vcs-release-system-files-by-namestring release))) (defmethod release-lib-pathname ((release vcs-remote-release)) (let ((repo (vcs-release-repo release)) (commit-string (vcs-release-commit release))) (uiop:resolve-absolute-location `(,(repo-lib-base-pathname repo) ,(subseq commit-string 0 2) ,(subseq commit-string 2 4) ,commit-string) :ensure-directory t))) (defmethod release-lib-pathname ((release vcs-local-release)) (git-repo-local-dir (vcs-release-repo release))) (defmethod release-system-releases ((release vcs-release)) "Get all the system files and append together their systems." (let* ((system-files (release-system-files release))) (apply #'append (mapcar #'system-file-system-releases system-files)))) (defmethod release-system-release ((release vcs-release) system-name &optional (error t)) (unless (gethash system-name (vcs-release-system-releases-by-name release)) (let* ((system-file (gethash (asdf:primary-system-name system-name) (vcs-release-system-files-by-primary-name release)))) (when system-file (let* ((source (release-source release)) (system (source-ensure-system source system-name)) (system-release (make-instance 'vcs-system-release :release release :source (release-source release) :system system :system-file system-file))) (system-register-release! system release) (setf (gethash system-name (vcs-system-file-system-releases-by-name system-file)) system-release) (setf (gethash system-name (vcs-release-system-releases-by-name release)) system-release))))) (or (gethash system-name (vcs-release-system-releases-by-name release)) (when error (error 'release-missing-system-release :source (release-source release) :release release :system-name system-name)))) (defmethod release-version ((release vcs-release)) (list :commit (vcs-release-commit release))) ;; * system files (defclass vcs-system-file (clpm-system-file) ((source :initarg :source :accessor system-file-source) (release :initarg :release :accessor system-file-release) (relative-pathname :initarg :relative-pathname :accessor system-file-asd-enough-namestring) (system-releases-by-name :initform (make-hash-table :test 'equalp) :accessor vcs-system-file-system-releases-by-name) (groveled-p :initform nil :accessor vcs-system-file/groveled-p))) (defmethod system-file-absolute-asd-pathname ((system-file vcs-system-file)) "Merge the enough pathname with the release's lib pathname." (merge-pathnames (system-file-asd-enough-namestring system-file) (release-lib-pathname (system-file-release system-file)))) (defmethod system-file-system-releases ((system-file vcs-system-file)) "Grovel over the system file if necessary to determine every system it contains." (unless (vcs-system-file/groveled-p system-file) ;; Sigh. We need to grovel the file to make sure we know ~everything it ;; defines. (active-groveler-ensure-asd-loaded (system-file-absolute-asd-pathname system-file)) (let ((system-names (active-groveler-systems-in-file (system-file-absolute-asd-pathname system-file)))) (dolist (system-name system-names) ;; Get the system release from the release (which will register it in ;; the system-releases-by-name slot of this object). (let* ((release (system-file-release system-file)) (system-release (release-system-release release system-name))) system-release)) (setf (vcs-system-file/groveled-p system-file) t))) (hash-table-values (vcs-system-file-system-releases-by-name system-file))) ;; * systems (defclass vcs-system (clpm-system) ((source :initarg :source :reader system-source) (name :initarg :name :reader system-name) (releases :initform nil :accessor vcs-system-releases))) (defmethod system-system-releases ((system vcs-system)) (mapcar #'(lambda (x) (release-system-release x (system-name system))) (vcs-system-releases system))) (defmethod system-register-release! ((system vcs-system) release) (pushnew release (vcs-system-releases system))) (defmethod system-releases ((system vcs-system)) (copy-list (vcs-system-releases system))) ;; * system-releases (defclass vcs-system-release (clpm-system-release) ((source :initarg :source :reader system-release-source) (release :initarg :release :reader system-release-release) (system :initarg :system :reader system-release-system) (system-version :accessor system-release-system-version) (reqs :accessor system-release-requirements) (system-file :initarg :system-file :accessor system-release-system-file))) (defun parse-system-release-info-from-groveler! (system-release info) "Take the info provided by the groveler and modify system-release in place to include it." (log:debug "Parsing from groveler: ~S" info) (destructuring-bind (&key version depends-on defsystem-depends-on loaded-systems &allow-other-keys) info (setf (system-release-system-version system-release) version) (setf (system-release-requirements system-release) (mapcar #'convert-asd-system-spec-to-req (append depends-on defsystem-depends-on loaded-systems))))) (defun grovel-system-release! (system-release) (active-groveler-ensure-asd-loaded (system-release-absolute-asd-pathname system-release)) (let ((info (active-groveler-system-deps (system-name (system-release-system system-release))))) (parse-system-release-info-from-groveler! system-release info))) (defmethod system-release-absolute-asd-pathname ((system-release vcs-system-release)) (system-file-absolute-asd-pathname (system-release-system-file system-release))) (defmethod system-release-satisfies-version-spec-p ((system-release vcs-system-release) version-spec) t) (defmethod slot-unbound (class (system-release vcs-system-release) (slot-name (eql 'clpm/sources/defs:system-version))) (grovel-system-release! system-release) (system-release-system-version system-release)) (defmethod slot-unbound (class (system-release vcs-system-release) (slot-name (eql 'reqs))) (grovel-system-release! system-release) (system-release-requirements system-release)) ;; * Installing (defun vcs-release-resolve! (release ref) (let ((repo (vcs-release-repo release))) ;; We delay making sure commits are present locally until we want to ;; install. This ensures that if a commit is deleted from a repository we ;; don't get into a situation where we can't even parse the context. (if (eql (first ref) :commit) (setf (vcs-release-commit release) (second ref)) (progn (ensure-ref-present-locally! repo ref) (let ((commit-id (resolve-ref-to-commit repo ref))) (setf (vcs-release-commit release) commit-id)))))) (defmethod ensure-release-installed! ((release vcs-release)) (unless (vcs-release-installed-p release) (let ((project (release-project release)) (repo (vcs-release-repo release))) (ensure-ref-present-locally! repo `(:commit ,(vcs-release-commit release))) (let ((install-root (release-lib-pathname release))) (unless (uiop:probe-file* install-root) (log:info "installing ~A, commit ~A to ~A" (project-name project) (vcs-release-commit release) install-root) (multiple-value-bind (stream archive-type) (repo-archive-stream repo `(:commit ,(vcs-release-commit release))) (with-open-stream (stream stream) (unarchive archive-type stream install-root)))))) (setf (vcs-release-installed-p release) t))) (defmethod install-release ((release vcs-release)) (ensure-release-installed! release))
null
https://raw.githubusercontent.com/lisp-mirror/clpm/174b7db5e548518aff668cdd1f4d1a7b863becfb/clpm/sources/vcs.lisp
lisp
repo to be checked out before much can be done with it. LICENSE for license information. * define package * sources * projects ** Overrides ** Projects * releases Error unless the target branch name matches the actual branch name. Warn if the desired commit is not present in the repo. * system files Sigh. We need to grovel the file to make sure we know ~everything it defines. Get the system release from the release (which will register it in the system-releases-by-name slot of this object). * systems * system-releases * Installing We delay making sure commits are present locally until we want to install. This ensures that if a commit is deleted from a repository we don't get into a situation where we can't even parse the context.
Sources for projects taken from source control . A VCS source requires a This software is part of CLPM . See README.org for more information . See (uiop:define-package #:clpm/sources/vcs (:use #:cl #:alexandria #:anaphora #:clpm/archives #:clpm/groveler #:clpm/install/defs #:clpm/log #:clpm/repos #:clpm/requirement #:clpm/session #:clpm/sources/defs #:clpm/utils) (:export #:*vcs-project-override-fun* #:ensure-vcs-release-installed! #:make-vcs-release #:vcs-local-release #:vcs-project/cache-directory #:vcs-project/path #:vcs-release #:vcs-release-commit #:vcs-remote-release #:vcs-source #:vcs-source-clear-visible-releases #:vcs-source-project #:vcs-system)) (in-package #:clpm/sources/vcs) (setup-logger) (defclass vcs-source (clpm-source) ((name :initarg :name :reader source-name) (repo :initarg :repo :reader vcs-source-repo) (project :accessor vcs-source-project :documentation "The single project for the source.") (systems-by-name :initform (make-hash-table :test 'equalp) :accessor vcs-source-systems-by-name :documentation "A hash table mapping system names to system objects.")) (:documentation "A source for any bare VCS projects. Projects must be registered with the source using VCS-SOURCE-REGISTER_PROJECT!.")) (defmethod make-source ((type (eql 'vcs-source)) &key repo project-name) (let* ((repo-object (make-repo-from-description repo)) (name (repo-to-form repo-object))) (with-clpm-session (:key `(make-source ,type ,name)) (make-instance type :name name :project-name project-name :repo repo-object)))) (defmethod initialize-instance :after ((source vcs-source) &key project-name) (setf (vcs-source-project source) (make-instance 'vcs-project :source source :name project-name))) (defun vcs-source-clear-visible-releases (vcs-source) (setf (vcs-project-visible-releases (vcs-source-project vcs-source)) nil)) (defmethod source-ensure-system ((source vcs-source) system-name) (ensure-gethash system-name (vcs-source-systems-by-name source) (make-instance 'vcs-system :source source :name system-name))) (defmethod source-can-lazy-sync-p ((source vcs-source)) t) (defmethod source-project ((source vcs-source) project-name &optional (error t)) (if (equal project-name (project-name (vcs-source-project source))) (vcs-source-project source) (when error (error 'source-missing-project :source source :project-name project-name)))) (defmethod source-system ((source vcs-source) system-name &optional (error t)) (or (gethash system-name (vcs-source-systems-by-name source)) (some (lambda (release) (when-let ((system-release (release-system-release release system-name nil))) (system-release-system system-release))) (project-releases (vcs-source-project source))) (when error (error 'source-missing-system :source source :system-name system-name)))) (defmethod source-to-form ((source vcs-source)) (let ((project (vcs-source-project source))) `(:implicit-vcs :type :vcs :projects ((,(project-name project) . ,(repo-to-form (project-repo project))))))) (defmethod sync-source ((source vcs-source)) nil) (defvar *vcs-project-override-fun* (constantly nil) "A function that, given a project name returns either NIL or a directory pathname. If a directory pathname is returned, then that is assumed to be a local override when requesting a VCS release.") (defun make-vcs-release (source project ref &key (local-release-class 'vcs-local-release) (remote-release-class 'vcs-remote-release)) (let ((override-pathname (funcall *vcs-project-override-fun* (project-name project)))) (if override-pathname (make-instance local-release-class :source source :project project :ref ref :repo (make-instance 'local-git-override-repo :pathname override-pathname)) (make-instance remote-release-class :source source :project project :ref ref)))) (defclass vcs-project (clpm-project) ((source :initarg :source :reader project-source) (name :initarg :name :reader project-name) (visible-releases :initform nil :accessor vcs-project-visible-releases) (releases-by-spec :initform (make-hash-table :test 'equal) :accessor vcs-project-releases-by-spec))) (defmethod project-repo ((project vcs-project)) (vcs-source-repo (project-source project))) (defmethod project-releases ((project vcs-project)) (vcs-project-visible-releases project)) (defmethod project-release ((project vcs-project) (version string) &optional (error t)) "A release named by a string is assumed to refer to a commit." (project-release project `(:commit ,version) error)) (defmethod project-release ((project vcs-project) (version list) &optional error) (declare (ignore error)) (apply #'project-vcs-release project version)) (defmethod project-vcs-release ((project vcs-project) &key commit branch tag ref) (let* ((ref (cond (commit `(:commit ,commit)) (branch `(:branch ,branch)) (tag `(:tag ,tag)) (ref `(:ref ,ref)))) (release (ensure-gethash ref (vcs-project-releases-by-spec project) (make-vcs-release (project-source project) project ref)))) (pushnew release (vcs-project-visible-releases project)) (unless commit (setf release (ensure-gethash `(:commit ,(vcs-release-commit release)) (vcs-project-releases-by-spec project) release))) release)) (defclass vcs-release () ((source :initarg :source :reader release-source) (project :initarg :project :reader release-project) (commit :initarg :commit :accessor vcs-release-commit) (installed-p :initform nil :accessor vcs-release-installed-p) (system-files-by-namestring :accessor vcs-release-system-files-by-namestring) (system-files-by-primary-name :accessor vcs-release-system-files-by-primary-name) (system-releases-by-name :initform (make-hash-table :test 'equal) :accessor vcs-release-system-releases-by-name))) (defclass vcs-remote-release (vcs-release) () (:documentation "Represents a release fetched from a remote repository.")) (defclass vcs-local-release (vcs-release) ((installed-p :initform t) (repo :initarg :repo :reader vcs-release-repo)) (:documentation "Represents a release that uses a user managed local repository.")) (defmethod initialize-instance :after ((release vcs-remote-release) &rest initargs &key ref) (declare (ignore initargs)) (vcs-release-resolve! release ref)) (defmethod initialize-instance :after ((release vcs-local-release) &rest initargs &key ref) (declare (ignore initargs)) (destructuring-bind (ref-type ref-name) ref (ecase ref-type (:branch (let ((current-branch-name (repo-current-branch (vcs-release-repo release)))) (unless (equal ref-name current-branch-name) (log:error "In order to use local overrides, branch names must match. Expected: ~a, actual: ~a" ref-name current-branch-name) (error "In order to use local overrides, branch names must match. Expected: ~a, actual: ~a" ref-name current-branch-name)))) (:commit (unless (ref-present-p (vcs-release-repo release) ref) (log:warn "Commit ~A is not present in the local override. Your local repo may not be up to date!" ref-name) (warn "Commit ~A is not present in the local override. Your local repo may not be up to date!" ref-name))))) (setf (vcs-release-commit release) (repo-current-commit (vcs-release-repo release)))) (defmethod vcs-release-repo ((release vcs-remote-release)) (project-repo (release-project release))) (defun populate-release-system-files! (release) (ensure-release-installed! release) (let ((ht-by-namestring (make-hash-table :test 'equal)) (ht-by-primary-name (make-hash-table :test 'equalp))) (asdf::collect-sub*directories-asd-files (release-lib-pathname release) :collect (lambda (x) (let* ((namestring (enough-namestring x (release-lib-pathname release))) (system-file (make-instance 'vcs-system-file :relative-pathname namestring :release release :source (release-source release))) (primary-system-name (pathname-name x))) (setf (gethash namestring ht-by-namestring) system-file) (setf (gethash primary-system-name ht-by-primary-name) system-file)))) (setf (vcs-release-system-files-by-namestring release) ht-by-namestring) (setf (vcs-release-system-files-by-primary-name release) ht-by-primary-name))) (defmethod slot-unbound (class (release vcs-release) (slot-name (eql 'system-files-by-namestring))) (populate-release-system-files! release) (vcs-release-system-files-by-namestring release)) (defmethod slot-unbound (class (release vcs-release) (slot-name (eql 'system-files-by-primary-name))) (populate-release-system-files! release) (vcs-release-system-files-by-primary-name release)) (defmethod release-system-files ((release vcs-release)) (hash-table-values (vcs-release-system-files-by-namestring release))) (defmethod release-system-file ((release vcs-release) system-file-namestring) "Requires the release to be installed. Return a system file object if not already created." (gethash system-file-namestring (vcs-release-system-files-by-namestring release))) (defmethod release-lib-pathname ((release vcs-remote-release)) (let ((repo (vcs-release-repo release)) (commit-string (vcs-release-commit release))) (uiop:resolve-absolute-location `(,(repo-lib-base-pathname repo) ,(subseq commit-string 0 2) ,(subseq commit-string 2 4) ,commit-string) :ensure-directory t))) (defmethod release-lib-pathname ((release vcs-local-release)) (git-repo-local-dir (vcs-release-repo release))) (defmethod release-system-releases ((release vcs-release)) "Get all the system files and append together their systems." (let* ((system-files (release-system-files release))) (apply #'append (mapcar #'system-file-system-releases system-files)))) (defmethod release-system-release ((release vcs-release) system-name &optional (error t)) (unless (gethash system-name (vcs-release-system-releases-by-name release)) (let* ((system-file (gethash (asdf:primary-system-name system-name) (vcs-release-system-files-by-primary-name release)))) (when system-file (let* ((source (release-source release)) (system (source-ensure-system source system-name)) (system-release (make-instance 'vcs-system-release :release release :source (release-source release) :system system :system-file system-file))) (system-register-release! system release) (setf (gethash system-name (vcs-system-file-system-releases-by-name system-file)) system-release) (setf (gethash system-name (vcs-release-system-releases-by-name release)) system-release))))) (or (gethash system-name (vcs-release-system-releases-by-name release)) (when error (error 'release-missing-system-release :source (release-source release) :release release :system-name system-name)))) (defmethod release-version ((release vcs-release)) (list :commit (vcs-release-commit release))) (defclass vcs-system-file (clpm-system-file) ((source :initarg :source :accessor system-file-source) (release :initarg :release :accessor system-file-release) (relative-pathname :initarg :relative-pathname :accessor system-file-asd-enough-namestring) (system-releases-by-name :initform (make-hash-table :test 'equalp) :accessor vcs-system-file-system-releases-by-name) (groveled-p :initform nil :accessor vcs-system-file/groveled-p))) (defmethod system-file-absolute-asd-pathname ((system-file vcs-system-file)) "Merge the enough pathname with the release's lib pathname." (merge-pathnames (system-file-asd-enough-namestring system-file) (release-lib-pathname (system-file-release system-file)))) (defmethod system-file-system-releases ((system-file vcs-system-file)) "Grovel over the system file if necessary to determine every system it contains." (unless (vcs-system-file/groveled-p system-file) (active-groveler-ensure-asd-loaded (system-file-absolute-asd-pathname system-file)) (let ((system-names (active-groveler-systems-in-file (system-file-absolute-asd-pathname system-file)))) (dolist (system-name system-names) (let* ((release (system-file-release system-file)) (system-release (release-system-release release system-name))) system-release)) (setf (vcs-system-file/groveled-p system-file) t))) (hash-table-values (vcs-system-file-system-releases-by-name system-file))) (defclass vcs-system (clpm-system) ((source :initarg :source :reader system-source) (name :initarg :name :reader system-name) (releases :initform nil :accessor vcs-system-releases))) (defmethod system-system-releases ((system vcs-system)) (mapcar #'(lambda (x) (release-system-release x (system-name system))) (vcs-system-releases system))) (defmethod system-register-release! ((system vcs-system) release) (pushnew release (vcs-system-releases system))) (defmethod system-releases ((system vcs-system)) (copy-list (vcs-system-releases system))) (defclass vcs-system-release (clpm-system-release) ((source :initarg :source :reader system-release-source) (release :initarg :release :reader system-release-release) (system :initarg :system :reader system-release-system) (system-version :accessor system-release-system-version) (reqs :accessor system-release-requirements) (system-file :initarg :system-file :accessor system-release-system-file))) (defun parse-system-release-info-from-groveler! (system-release info) "Take the info provided by the groveler and modify system-release in place to include it." (log:debug "Parsing from groveler: ~S" info) (destructuring-bind (&key version depends-on defsystem-depends-on loaded-systems &allow-other-keys) info (setf (system-release-system-version system-release) version) (setf (system-release-requirements system-release) (mapcar #'convert-asd-system-spec-to-req (append depends-on defsystem-depends-on loaded-systems))))) (defun grovel-system-release! (system-release) (active-groveler-ensure-asd-loaded (system-release-absolute-asd-pathname system-release)) (let ((info (active-groveler-system-deps (system-name (system-release-system system-release))))) (parse-system-release-info-from-groveler! system-release info))) (defmethod system-release-absolute-asd-pathname ((system-release vcs-system-release)) (system-file-absolute-asd-pathname (system-release-system-file system-release))) (defmethod system-release-satisfies-version-spec-p ((system-release vcs-system-release) version-spec) t) (defmethod slot-unbound (class (system-release vcs-system-release) (slot-name (eql 'clpm/sources/defs:system-version))) (grovel-system-release! system-release) (system-release-system-version system-release)) (defmethod slot-unbound (class (system-release vcs-system-release) (slot-name (eql 'reqs))) (grovel-system-release! system-release) (system-release-requirements system-release)) (defun vcs-release-resolve! (release ref) (let ((repo (vcs-release-repo release))) (if (eql (first ref) :commit) (setf (vcs-release-commit release) (second ref)) (progn (ensure-ref-present-locally! repo ref) (let ((commit-id (resolve-ref-to-commit repo ref))) (setf (vcs-release-commit release) commit-id)))))) (defmethod ensure-release-installed! ((release vcs-release)) (unless (vcs-release-installed-p release) (let ((project (release-project release)) (repo (vcs-release-repo release))) (ensure-ref-present-locally! repo `(:commit ,(vcs-release-commit release))) (let ((install-root (release-lib-pathname release))) (unless (uiop:probe-file* install-root) (log:info "installing ~A, commit ~A to ~A" (project-name project) (vcs-release-commit release) install-root) (multiple-value-bind (stream archive-type) (repo-archive-stream repo `(:commit ,(vcs-release-commit release))) (with-open-stream (stream stream) (unarchive archive-type stream install-root)))))) (setf (vcs-release-installed-p release) t))) (defmethod install-release ((release vcs-release)) (ensure-release-installed! release))
6c17577d3a1ad8cf1fbdd5294d8e65c7f77b8c06e31a9ff70e439b8bc6e01685
letmaik/monadiccp
If.hs
# LANGUAGE FlexibleContexts # module Control.Search.Combinator.If (if') where import Control.Search.Language import Control.Search.GeneratorInfo import Control.Search.MemoReader import Control.Search.Generator import Control.Search.Stat import Control.Monatron.Monatron hiding (Abort, L, state, cont) import Control.Monatron.Zipper hiding (i,r) ( , " cont " ) : xfs1 uid lsuper rsuper = [(field,init) | (field,ty,init) <- evalState_ rsuper ] ( , " cont " ) : xfs2 uid lsuper rsuper = [(field,init) | (field,ty,init) <- evalState_ rsuper ] xs3 uid lsuper rsuper = Struct ("LeftTreeState" ++ show uid) $ (Pointer $ SType $ xs1 uid lsuper rsuper, "evalState") : [(ty, field) | (field,ty,_) <- treeState_ lsuper] xfs3 uid lsuper rsuper = [(field,init) | (field,ty,init) <- treeState_ lsuper] xs4 uid lsuper rsuper = Struct ("RightTreeState" ++ show uid) $ (Pointer $ SType $ xs2 uid lsuper rsuper, "evalState") : [(ty, field) | (field,ty,_) <- treeState_ rsuper] xfs4 uid lsuper rsuper = [(field,init) | (field,ty,init) <- treeState_ rsuper] in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else" xpath uid lsuper rsuper i FirstS = withPath i in1 (SType $ xs1 uid lsuper rsuper) (SType $ xs3 uid lsuper rsuper) xpath uid lsuper rsuper i SecondS = withPath i in2 (SType $ xs2 uid lsuper rsuper) (SType $ xs4 uid lsuper rsuper) ifLoop :: (Evalable m, ReaderM SeqPos m) => Stat -> Int -> Eval m -> Eval m -> Eval m ifLoop cond uid lsuper rsuper = commentEval $ Eval { structs = structs lsuper @++@ structs rsuper @++@ mystructs , toString = "if" ++ show uid ++ "(" ++ show cond ++ "," ++ toString lsuper ++ "," ++ toString rsuper ++ ")" , treeState_ = [("if_true", Bool,const $ return Skip), ("if_union",Union [(SType s3,"if_true"),(SType s4,"if_false")],const $ return Skip) ] , initH = \i -> (readStat cond >>= \r -> return (assign (r i) (tstate i @-> "if_true"))) @>>>@ initstate i , evalState_ = [] , pushLeftH = push pushLeft , pushRightH = push pushRight , nextSameH = \i -> let j = i `withBase` "popped_estate" in do nS1 <- local (const FirstS) $ inSeq nextSame i nS2 <- local (const SecondS) $ inSeq nextSame i nD1 <- local (const FirstS) $ inSeq nextDiff i nD2 <- local (const SecondS) $ inSeq nextDiff i return $ IfThenElse (is_fst i) (IfThenElse (is_fst j) nS1 nD1) (IfThenElse (is_fst j) nD2 nS2) , nextDiffH = \i -> inSeq nextDiff i , bodyH = \i -> let f y z p = let j = mpath i p in do cond < - continue z ( estate j ) deref < - dec_ref i stmt < - bodyE z ( j ` onAbort ` deref ) return $ IfThenElse ( cont j ) ( IfThenElse cond stmt ( ( cont j < = = false ) > > > deref > > > abort j ) ) ( deref > > > abort j ) deref <- dec_ref i stmt <- bodyE z (j `onAbort` deref) return $ IfThenElse (cont j) (IfThenElse cond stmt ( (cont j <== false) >>> deref >>> abort j)) (deref >>> abort j) -} in dec_ref i >>= \deref -> bodyE z (j `onAbort` deref) in IfThenElse (is_fst i) @$ local (const FirstS) (f in1 lsuper FirstS) @. local (const SecondS) (f in2 rsuper SecondS) , addH = inSeq $ addE , failH = \i -> inSeq failE i @>>>@ dec_ref i , returnH = \i -> let j1 deref = mpath i FirstS `onCommit` deref j2 deref = mpath i SecondS `onCommit` deref in IfThenElse (is_fst i) @$ (dec_refx (j1 Skip) >>= returnE lsuper . j1) @. (dec_refx (j2 Skip) >>= returnE rsuper . j2) -- , continue = \_ -> return true , tryH = \i -> IfThenElse (is_fst i) @$ tryE lsuper (mpath i FirstS) @. tryE rsuper (mpath i SecondS) , startTryH = \i -> IfThenElse (is_fst i) @$ startTryE lsuper (mpath i FirstS) @. startTryE rsuper (mpath i SecondS) , tryLH = \i -> IfThenElse (is_fst i) @$ tryE_ lsuper (mpath i FirstS) @. tryE_ rsuper (mpath i SecondS) , boolArraysE = boolArraysE lsuper ++ boolArraysE rsuper , intArraysE = intArraysE lsuper ++ intArraysE rsuper , intVarsE = intVarsE lsuper ++ intVarsE rsuper , deleteH = deleteMe , canBranch = canBranch lsuper >>= \l -> canBranch rsuper >>= \r -> return (l || r) , complete = \i -> do sid1 <- complete lsuper (mpath i FirstS) sid2 <- complete rsuper (mpath i SecondS) return $ Cond (tstate i @-> "is_fst") sid1 sid2 } where mystructs = ([s1,s2],[s3,s4]) s1 = xs1 uid lsuper rsuper s2 = xs2 uid lsuper rsuper s3 = xs3 uid lsuper rsuper s4 = xs4 uid lsuper rsuper fs1 = xfs1 uid lsuper rsuper fs2 = xfs2 uid lsuper rsuper fs3 = xfs3 uid lsuper rsuper fs4 = xfs4 uid lsuper rsuper mpath = xpath uid lsuper rsuper withSeq f = seqSwitch (f lsuper in1) (f rsuper in2) withSeq_ f = seqSwitch (f lsuper in1 FirstS) (f rsuper in2 SecondS) inSeq f = \i -> withSeq_ $ \super ins pos -> f super (mpath i pos) dec_ref = \i -> seqSwitch (dec_refx $ mpath i FirstS) (dec_refx $ mpath i SecondS) dec_refx = \j -> return $ dec (ref_count j) >>> ifthen (ref_count j @== 0) (comment "ifLoop-dec_refx" >>> Delete (estate j)) push dir = \i -> seqSwitch (push1 dir i) (push2 dir i) push1 dir = \i -> let j = mpath i FirstS in dir lsuper (j `onCommit` ( mkCopy i "if_true" >>> mkCopy j "evalState" >>> inc (ref_count j) )) push2 dir = \i -> let j = mpath i SecondS in dir rsuper (j `onCommit` ( mkCopy i "if_true" >>> mkCopy j "evalState" >>> inc (ref_count j) )) initstate = \i -> let f d = let j = mpath i (if d then FirstS else SecondS) in return ( (estate j <== New (if d then s1 else s2)) >>> (ref_count j <== 1) ) @>>>@ inite (if d then fs1 else fs2) j @>>>@ inits (if d then lsuper else rsuper) j in do thenP <- f True elseP <- f False return $ IfThenElse (tstate i @-> "if_true") thenP elseP in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else" is_fst = \i -> tstate i @-> "if_true" deleteMe = \i -> seqSwitch (deleteE lsuper (mpath i FirstS)) (deleteE rsuper (mpath i SecondS)) @>>>@ dec_ref i if' :: Stat -> Search -> Search -> Search if' cond s1 s2 = case s1 of Search { mkeval = evals1, runsearch = runs1 } -> case s2 of Search { mkeval = evals2, runsearch = runs2 } -> Search { mkeval = \super -> do { s2' <- evals2 $ mapE (L . L . L . mmap (mmap runL . runL) . runL) super ; s1' <- evals1 $ mapE (L . L . mmap (mmap runL . runL) . runL) super ; uid <- get ; put (uid + 1) ; return $ mapE (L . mmap L . runL) $ ifLoop cond uid (mapE (L . mmap (mmap L) . runL . runL) s1') (mapE (L . mmap (mmap L) . runL . runL . runL) s2') } , runsearch = runs2 . runs1 . runL . rReaderT FirstS . runL } where in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else"
null
https://raw.githubusercontent.com/letmaik/monadiccp/fe4498e46a7b9d9e387fd5e4ed5d0749a89d0188/src/Control/Search/Combinator/If.hs
haskell
, continue = \_ -> return true
# LANGUAGE FlexibleContexts # module Control.Search.Combinator.If (if') where import Control.Search.Language import Control.Search.GeneratorInfo import Control.Search.MemoReader import Control.Search.Generator import Control.Search.Stat import Control.Monatron.Monatron hiding (Abort, L, state, cont) import Control.Monatron.Zipper hiding (i,r) ( , " cont " ) : xfs1 uid lsuper rsuper = [(field,init) | (field,ty,init) <- evalState_ rsuper ] ( , " cont " ) : xfs2 uid lsuper rsuper = [(field,init) | (field,ty,init) <- evalState_ rsuper ] xs3 uid lsuper rsuper = Struct ("LeftTreeState" ++ show uid) $ (Pointer $ SType $ xs1 uid lsuper rsuper, "evalState") : [(ty, field) | (field,ty,_) <- treeState_ lsuper] xfs3 uid lsuper rsuper = [(field,init) | (field,ty,init) <- treeState_ lsuper] xs4 uid lsuper rsuper = Struct ("RightTreeState" ++ show uid) $ (Pointer $ SType $ xs2 uid lsuper rsuper, "evalState") : [(ty, field) | (field,ty,_) <- treeState_ rsuper] xfs4 uid lsuper rsuper = [(field,init) | (field,ty,init) <- treeState_ rsuper] in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else" xpath uid lsuper rsuper i FirstS = withPath i in1 (SType $ xs1 uid lsuper rsuper) (SType $ xs3 uid lsuper rsuper) xpath uid lsuper rsuper i SecondS = withPath i in2 (SType $ xs2 uid lsuper rsuper) (SType $ xs4 uid lsuper rsuper) ifLoop :: (Evalable m, ReaderM SeqPos m) => Stat -> Int -> Eval m -> Eval m -> Eval m ifLoop cond uid lsuper rsuper = commentEval $ Eval { structs = structs lsuper @++@ structs rsuper @++@ mystructs , toString = "if" ++ show uid ++ "(" ++ show cond ++ "," ++ toString lsuper ++ "," ++ toString rsuper ++ ")" , treeState_ = [("if_true", Bool,const $ return Skip), ("if_union",Union [(SType s3,"if_true"),(SType s4,"if_false")],const $ return Skip) ] , initH = \i -> (readStat cond >>= \r -> return (assign (r i) (tstate i @-> "if_true"))) @>>>@ initstate i , evalState_ = [] , pushLeftH = push pushLeft , pushRightH = push pushRight , nextSameH = \i -> let j = i `withBase` "popped_estate" in do nS1 <- local (const FirstS) $ inSeq nextSame i nS2 <- local (const SecondS) $ inSeq nextSame i nD1 <- local (const FirstS) $ inSeq nextDiff i nD2 <- local (const SecondS) $ inSeq nextDiff i return $ IfThenElse (is_fst i) (IfThenElse (is_fst j) nS1 nD1) (IfThenElse (is_fst j) nD2 nS2) , nextDiffH = \i -> inSeq nextDiff i , bodyH = \i -> let f y z p = let j = mpath i p in do cond < - continue z ( estate j ) deref < - dec_ref i stmt < - bodyE z ( j ` onAbort ` deref ) return $ IfThenElse ( cont j ) ( IfThenElse cond stmt ( ( cont j < = = false ) > > > deref > > > abort j ) ) ( deref > > > abort j ) deref <- dec_ref i stmt <- bodyE z (j `onAbort` deref) return $ IfThenElse (cont j) (IfThenElse cond stmt ( (cont j <== false) >>> deref >>> abort j)) (deref >>> abort j) -} in dec_ref i >>= \deref -> bodyE z (j `onAbort` deref) in IfThenElse (is_fst i) @$ local (const FirstS) (f in1 lsuper FirstS) @. local (const SecondS) (f in2 rsuper SecondS) , addH = inSeq $ addE , failH = \i -> inSeq failE i @>>>@ dec_ref i , returnH = \i -> let j1 deref = mpath i FirstS `onCommit` deref j2 deref = mpath i SecondS `onCommit` deref in IfThenElse (is_fst i) @$ (dec_refx (j1 Skip) >>= returnE lsuper . j1) @. (dec_refx (j2 Skip) >>= returnE rsuper . j2) , tryH = \i -> IfThenElse (is_fst i) @$ tryE lsuper (mpath i FirstS) @. tryE rsuper (mpath i SecondS) , startTryH = \i -> IfThenElse (is_fst i) @$ startTryE lsuper (mpath i FirstS) @. startTryE rsuper (mpath i SecondS) , tryLH = \i -> IfThenElse (is_fst i) @$ tryE_ lsuper (mpath i FirstS) @. tryE_ rsuper (mpath i SecondS) , boolArraysE = boolArraysE lsuper ++ boolArraysE rsuper , intArraysE = intArraysE lsuper ++ intArraysE rsuper , intVarsE = intVarsE lsuper ++ intVarsE rsuper , deleteH = deleteMe , canBranch = canBranch lsuper >>= \l -> canBranch rsuper >>= \r -> return (l || r) , complete = \i -> do sid1 <- complete lsuper (mpath i FirstS) sid2 <- complete rsuper (mpath i SecondS) return $ Cond (tstate i @-> "is_fst") sid1 sid2 } where mystructs = ([s1,s2],[s3,s4]) s1 = xs1 uid lsuper rsuper s2 = xs2 uid lsuper rsuper s3 = xs3 uid lsuper rsuper s4 = xs4 uid lsuper rsuper fs1 = xfs1 uid lsuper rsuper fs2 = xfs2 uid lsuper rsuper fs3 = xfs3 uid lsuper rsuper fs4 = xfs4 uid lsuper rsuper mpath = xpath uid lsuper rsuper withSeq f = seqSwitch (f lsuper in1) (f rsuper in2) withSeq_ f = seqSwitch (f lsuper in1 FirstS) (f rsuper in2 SecondS) inSeq f = \i -> withSeq_ $ \super ins pos -> f super (mpath i pos) dec_ref = \i -> seqSwitch (dec_refx $ mpath i FirstS) (dec_refx $ mpath i SecondS) dec_refx = \j -> return $ dec (ref_count j) >>> ifthen (ref_count j @== 0) (comment "ifLoop-dec_refx" >>> Delete (estate j)) push dir = \i -> seqSwitch (push1 dir i) (push2 dir i) push1 dir = \i -> let j = mpath i FirstS in dir lsuper (j `onCommit` ( mkCopy i "if_true" >>> mkCopy j "evalState" >>> inc (ref_count j) )) push2 dir = \i -> let j = mpath i SecondS in dir rsuper (j `onCommit` ( mkCopy i "if_true" >>> mkCopy j "evalState" >>> inc (ref_count j) )) initstate = \i -> let f d = let j = mpath i (if d then FirstS else SecondS) in return ( (estate j <== New (if d then s1 else s2)) >>> (ref_count j <== 1) ) @>>>@ inite (if d then fs1 else fs2) j @>>>@ inits (if d then lsuper else rsuper) j in do thenP <- f True elseP <- f False return $ IfThenElse (tstate i @-> "if_true") thenP elseP in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else" is_fst = \i -> tstate i @-> "if_true" deleteMe = \i -> seqSwitch (deleteE lsuper (mpath i FirstS)) (deleteE rsuper (mpath i SecondS)) @>>>@ dec_ref i if' :: Stat -> Search -> Search -> Search if' cond s1 s2 = case s1 of Search { mkeval = evals1, runsearch = runs1 } -> case s2 of Search { mkeval = evals2, runsearch = runs2 } -> Search { mkeval = \super -> do { s2' <- evals2 $ mapE (L . L . L . mmap (mmap runL . runL) . runL) super ; s1' <- evals1 $ mapE (L . L . mmap (mmap runL . runL) . runL) super ; uid <- get ; put (uid + 1) ; return $ mapE (L . mmap L . runL) $ ifLoop cond uid (mapE (L . mmap (mmap L) . runL . runL) s1') (mapE (L . mmap (mmap L) . runL . runL . runL) s2') } , runsearch = runs2 . runs1 . runL . rReaderT FirstS . runL } where in1 = \state -> state @-> "if_union" @-> "if_then" in2 = \state -> state @-> "if_union" @-> "if_else"
d1f0e272744e05b98193ab452a2ec6e55fa5feaa07b3963d14c4fe57fb58edb3
bitnomial/bitcoind-rpc
Misc.hs
{-# LANGUAGE OverloadedStrings #-} module Bitcoin.Core.Test.Misc ( miscRPC, ) where import Control.Monad (replicateM) import Data.Text (Text) import Data.Word (Word64) import Haskoin.Address (Address (..), addrToText, pubKeyAddr) import Haskoin.Block (Block (..), BlockHash) import Haskoin.Constants (btcTest) import Haskoin.Crypto (SecKey) import Haskoin.Keys ( PubKeyI, derivePubKeyI, secKey, wrapSecKey, ) import Haskoin.Transaction (OutPoint (..), Tx (..), TxHash, txHash) import Network.HTTP.Client (Manager) import Test.Tasty (TestTree, testGroup) import Bitcoin.Core.RPC import Bitcoin.Core.Regtest (NodeHandle) import qualified Bitcoin.Core.Regtest as R import Bitcoin.Core.Test.Utils (bitcoindTest, testRpc) miscRPC :: Manager -> NodeHandle -> TestTree miscRPC mgr h = testGroup "other-rpcs" $ bitcoindTest mgr h <$> [ testRpc "generatetoaddress" testGenerate , testRpc "getbestblockhash" getBestBlockHash , testRpc "getblockhash" $ getBlockHash 1 , testRpc "getblockfilter" testBlockFilter , testRpc "getblockheader" testBlockHeader , testRpc "getblock" testBlock , testRpc "getblockcount" getBlockCount , testRpc "getdifficulty" getDifficulty , testRpc "getchaintips" getChainTips , testRpc "getblockstats" testBlockStats , testRpc "getchaintxstats" $ getChainTxStats Nothing Nothing , testRpc "getmempoolinfo" getMempoolInfo , testRpc "getrawmempool" getRawMempool , testRpc "getrawtransaction" testGetTransaction , testRpc "sendrawtransaction" testSendTransaction , testRpc "createOutput" testCreateOutput , testRpc "getmempoolancestors" testMempoolAncestors , testRpc "getmempooldescendants" testMempoolDescendants , testRpc "getpeerinfo" getPeerInfo , testRpc "getconnectioncount" getConnectionCount , testRpc "getnodeaddresses" $ getNodeAddresses (Just 10) , testRpc "getaddednodeinfo" $ getAddedNodeInfo Nothing , testRpc "getdescriptorinfo" $ getDescriptorInfo "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)" , testRpc "listbanned" listBanned , testRpc "getnettotals" getNetTotals , testRpc "uptime" uptime , testRpc "addnode" $ addNode "127.0.0.1:8448" Add , testRpc "clearbanned" clearBanned , testRpc "estimatesmartfee" $ estimateSmartFee 6 Nothing ] testGenerate :: BitcoindClient [BlockHash] testGenerate = generateToAddress 120 addrText Nothing key :: SecKey Just key = secKey "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" pk :: PubKeyI pk = derivePubKeyI $ wrapSecKey True key addr :: Address addr = pubKeyAddr pk addrText :: Text Just addrText = addrToText btcTest addr testBlock :: BitcoindClient Block testBlock = getBestBlockHash >>= getBlock testBlockFilter :: BitcoindClient CompactFilter testBlockFilter = getBestBlockHash >>= getBlockFilter testBlockHeader :: BitcoindClient BlockHeader testBlockHeader = getBestBlockHash >>= getBlockHeader testBlockStats :: BitcoindClient BlockStats testBlockStats = getBestBlockHash >>= getBlockStats testGetTransaction :: BitcoindClient Tx testGetTransaction = getBestBlockHash >>= getBlock >>= (`getRawTransaction` Nothing) . txHash . head . blockTxns testSendTransaction :: BitcoindClient TxHash testSendTransaction = do outp <- head <$> replicateM 101 R.generate let Right (tx, _) = R.spendPackageOutputs [outp] (R.addrs !! 3) R.oneBitcoin sendTransaction tx Nothing testMempoolAncestors :: BitcoindClient [TxHash] testMempoolAncestors = testSendTransaction >>= getMempoolAncestors testMempoolDescendants :: BitcoindClient [TxHash] testMempoolDescendants = testSendTransaction >>= getMempoolAncestors testCreateOutput :: BitcoindClient (OutPoint, Word64) testCreateOutput = R.createOutput (R.addrs !! 4) (2 * R.oneBitcoin)
null
https://raw.githubusercontent.com/bitnomial/bitcoind-rpc/02ee92a6365955a427d18ae9be8e7771b0b86a9e/bitcoind-regtest/test/Bitcoin/Core/Test/Misc.hs
haskell
# LANGUAGE OverloadedStrings #
module Bitcoin.Core.Test.Misc ( miscRPC, ) where import Control.Monad (replicateM) import Data.Text (Text) import Data.Word (Word64) import Haskoin.Address (Address (..), addrToText, pubKeyAddr) import Haskoin.Block (Block (..), BlockHash) import Haskoin.Constants (btcTest) import Haskoin.Crypto (SecKey) import Haskoin.Keys ( PubKeyI, derivePubKeyI, secKey, wrapSecKey, ) import Haskoin.Transaction (OutPoint (..), Tx (..), TxHash, txHash) import Network.HTTP.Client (Manager) import Test.Tasty (TestTree, testGroup) import Bitcoin.Core.RPC import Bitcoin.Core.Regtest (NodeHandle) import qualified Bitcoin.Core.Regtest as R import Bitcoin.Core.Test.Utils (bitcoindTest, testRpc) miscRPC :: Manager -> NodeHandle -> TestTree miscRPC mgr h = testGroup "other-rpcs" $ bitcoindTest mgr h <$> [ testRpc "generatetoaddress" testGenerate , testRpc "getbestblockhash" getBestBlockHash , testRpc "getblockhash" $ getBlockHash 1 , testRpc "getblockfilter" testBlockFilter , testRpc "getblockheader" testBlockHeader , testRpc "getblock" testBlock , testRpc "getblockcount" getBlockCount , testRpc "getdifficulty" getDifficulty , testRpc "getchaintips" getChainTips , testRpc "getblockstats" testBlockStats , testRpc "getchaintxstats" $ getChainTxStats Nothing Nothing , testRpc "getmempoolinfo" getMempoolInfo , testRpc "getrawmempool" getRawMempool , testRpc "getrawtransaction" testGetTransaction , testRpc "sendrawtransaction" testSendTransaction , testRpc "createOutput" testCreateOutput , testRpc "getmempoolancestors" testMempoolAncestors , testRpc "getmempooldescendants" testMempoolDescendants , testRpc "getpeerinfo" getPeerInfo , testRpc "getconnectioncount" getConnectionCount , testRpc "getnodeaddresses" $ getNodeAddresses (Just 10) , testRpc "getaddednodeinfo" $ getAddedNodeInfo Nothing , testRpc "getdescriptorinfo" $ getDescriptorInfo "wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)" , testRpc "listbanned" listBanned , testRpc "getnettotals" getNetTotals , testRpc "uptime" uptime , testRpc "addnode" $ addNode "127.0.0.1:8448" Add , testRpc "clearbanned" clearBanned , testRpc "estimatesmartfee" $ estimateSmartFee 6 Nothing ] testGenerate :: BitcoindClient [BlockHash] testGenerate = generateToAddress 120 addrText Nothing key :: SecKey Just key = secKey "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" pk :: PubKeyI pk = derivePubKeyI $ wrapSecKey True key addr :: Address addr = pubKeyAddr pk addrText :: Text Just addrText = addrToText btcTest addr testBlock :: BitcoindClient Block testBlock = getBestBlockHash >>= getBlock testBlockFilter :: BitcoindClient CompactFilter testBlockFilter = getBestBlockHash >>= getBlockFilter testBlockHeader :: BitcoindClient BlockHeader testBlockHeader = getBestBlockHash >>= getBlockHeader testBlockStats :: BitcoindClient BlockStats testBlockStats = getBestBlockHash >>= getBlockStats testGetTransaction :: BitcoindClient Tx testGetTransaction = getBestBlockHash >>= getBlock >>= (`getRawTransaction` Nothing) . txHash . head . blockTxns testSendTransaction :: BitcoindClient TxHash testSendTransaction = do outp <- head <$> replicateM 101 R.generate let Right (tx, _) = R.spendPackageOutputs [outp] (R.addrs !! 3) R.oneBitcoin sendTransaction tx Nothing testMempoolAncestors :: BitcoindClient [TxHash] testMempoolAncestors = testSendTransaction >>= getMempoolAncestors testMempoolDescendants :: BitcoindClient [TxHash] testMempoolDescendants = testSendTransaction >>= getMempoolAncestors testCreateOutput :: BitcoindClient (OutPoint, Word64) testCreateOutput = R.createOutput (R.addrs !! 4) (2 * R.oneBitcoin)
3ea24621736017e643e3edd9a19af009dc66b9eba7b54119da6ec499bb72f196
ocamllabs/ocaml-modular-implicits
test_nats.ml
(***********************************************************************) (* *) (* 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 . (* *) (***********************************************************************) open Test;; open Nat;; Can compare nats less than 2**32 let equal_nat n1 n2 = eq_nat n1 0 (num_digits_nat n1 0 1) n2 0 (num_digits_nat n2 0 1);; testing_function "num_digits_nat";; test (-1) eq (false,not true);; test 0 eq (true,not false);; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 1 1; num_digits_nat r 0 1,1);; testing_function "length_nat";; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 0 1; length_nat r,2);; testing_function "equal_nat";; let zero_nat = make_nat 1 in test 1 equal_nat (zero_nat,zero_nat);; test 2 equal_nat (nat_of_int 1,nat_of_int 1);; test 3 equal_nat (nat_of_string "2",nat_of_string "2");; test 4 eq (equal_nat (nat_of_string "2")(nat_of_string "3"),false);; testing_function "incr_nat";; let zero = nat_of_int 0 in let res = incr_nat zero 0 1 1 in test 1 equal_nat (zero, nat_of_int 1) && test 2 eq (res,0);; let n = nat_of_int 1 in let res = incr_nat n 0 1 1 in test 3 equal_nat (n, nat_of_int 2) && test 4 eq (res,0);; testing_function "decr_nat";; let n = nat_of_int 1 in let res = decr_nat n 0 1 0 in test 1 equal_nat (n, nat_of_int 0) && test 2 eq (res,1);; let n = nat_of_int 2 in let res = decr_nat n 0 1 0 in test 3 equal_nat (n, nat_of_int 1) && test 4 eq (res,1);; testing_function "is_zero_nat";; let n = nat_of_int 1 in test 1 eq (is_zero_nat n 0 1,false) && test 2 eq (is_zero_nat (make_nat 1) 0 1, true) && test 3 eq (is_zero_nat (make_nat 2) 0 2, true) && (let r = make_nat 2 in set_digit_nat r 1 1; test 4 eq (is_zero_nat r 0 1, true)) ;; testing_function "string_of_nat";; let n = make_nat 4;; test 1 eq_string (string_of_nat n, "0");; complement_nat n 0 (if sixtyfour then 2 else 4);; test 2 eq_string (string_of_nat n, "340282366920938463463374607431768211455");; testing_function "string_of_nat && nat_of_string";; for i = 1 to 20 do let s = String.make i '0' in String.set s 0 '1'; ignore (test i eq_string (string_of_nat (nat_of_string s), s)) done;; let set_mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3 = ignore (mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3) ;; let s = "33333333333333333333333333333333333333333333333333333333333333333333\ 33333333333333333333333333333333333333333333333333333333333333333333" in test 21 equal_nat ( nat_of_string s, (let nat = make_nat 15 in set_digit_nat nat 0 3; set_mult_digit_nat nat 0 15 (nat_of_string (String.sub s 0 135)) 0 14 (nat_of_int 10) 0; nat)) ;; test 22 eq_string (string_of_nat(nat_of_string "1073741824"), "1073741824");; testing_function "gcd_nat";; for i = 1 to 20 do let n1 = Random.int 1000000000 and n2 = Random.int 100000 in let nat1 = nat_of_int n1 and nat2 = nat_of_int n2 in ignore (gcd_nat nat1 0 1 nat2 0 1); ignore (test i eq (int_of_nat nat1, gcd_int n1 n2)) done ;; testing_function "sqrt_nat";; test 1 equal_nat (sqrt_nat (nat_of_int 1) 0 1, nat_of_int 1);; test 2 equal_nat (let n = nat_of_string "8589934592" in sqrt_nat n 0 (length_nat n), nat_of_string "92681");; test 3 equal_nat (let n = nat_of_string "4294967295" in sqrt_nat n 0 (length_nat n), nat_of_string "65535");; test 4 equal_nat (let n = nat_of_string "18446744065119617025" in sqrt_nat n 0 (length_nat n), nat_of_string "4294967295");; test 5 equal_nat (sqrt_nat (nat_of_int 15) 0 1, nat_of_int 3);;
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/lib-num/test_nats.ml
ocaml
********************************************************************* 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 . open Test;; open Nat;; Can compare nats less than 2**32 let equal_nat n1 n2 = eq_nat n1 0 (num_digits_nat n1 0 1) n2 0 (num_digits_nat n2 0 1);; testing_function "num_digits_nat";; test (-1) eq (false,not true);; test 0 eq (true,not false);; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 1 1; num_digits_nat r 0 1,1);; testing_function "length_nat";; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 0 1; length_nat r,2);; testing_function "equal_nat";; let zero_nat = make_nat 1 in test 1 equal_nat (zero_nat,zero_nat);; test 2 equal_nat (nat_of_int 1,nat_of_int 1);; test 3 equal_nat (nat_of_string "2",nat_of_string "2");; test 4 eq (equal_nat (nat_of_string "2")(nat_of_string "3"),false);; testing_function "incr_nat";; let zero = nat_of_int 0 in let res = incr_nat zero 0 1 1 in test 1 equal_nat (zero, nat_of_int 1) && test 2 eq (res,0);; let n = nat_of_int 1 in let res = incr_nat n 0 1 1 in test 3 equal_nat (n, nat_of_int 2) && test 4 eq (res,0);; testing_function "decr_nat";; let n = nat_of_int 1 in let res = decr_nat n 0 1 0 in test 1 equal_nat (n, nat_of_int 0) && test 2 eq (res,1);; let n = nat_of_int 2 in let res = decr_nat n 0 1 0 in test 3 equal_nat (n, nat_of_int 1) && test 4 eq (res,1);; testing_function "is_zero_nat";; let n = nat_of_int 1 in test 1 eq (is_zero_nat n 0 1,false) && test 2 eq (is_zero_nat (make_nat 1) 0 1, true) && test 3 eq (is_zero_nat (make_nat 2) 0 2, true) && (let r = make_nat 2 in set_digit_nat r 1 1; test 4 eq (is_zero_nat r 0 1, true)) ;; testing_function "string_of_nat";; let n = make_nat 4;; test 1 eq_string (string_of_nat n, "0");; complement_nat n 0 (if sixtyfour then 2 else 4);; test 2 eq_string (string_of_nat n, "340282366920938463463374607431768211455");; testing_function "string_of_nat && nat_of_string";; for i = 1 to 20 do let s = String.make i '0' in String.set s 0 '1'; ignore (test i eq_string (string_of_nat (nat_of_string s), s)) done;; let set_mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3 = ignore (mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3) ;; let s = "33333333333333333333333333333333333333333333333333333333333333333333\ 33333333333333333333333333333333333333333333333333333333333333333333" in test 21 equal_nat ( nat_of_string s, (let nat = make_nat 15 in set_digit_nat nat 0 3; set_mult_digit_nat nat 0 15 (nat_of_string (String.sub s 0 135)) 0 14 (nat_of_int 10) 0; nat)) ;; test 22 eq_string (string_of_nat(nat_of_string "1073741824"), "1073741824");; testing_function "gcd_nat";; for i = 1 to 20 do let n1 = Random.int 1000000000 and n2 = Random.int 100000 in let nat1 = nat_of_int n1 and nat2 = nat_of_int n2 in ignore (gcd_nat nat1 0 1 nat2 0 1); ignore (test i eq (int_of_nat nat1, gcd_int n1 n2)) done ;; testing_function "sqrt_nat";; test 1 equal_nat (sqrt_nat (nat_of_int 1) 0 1, nat_of_int 1);; test 2 equal_nat (let n = nat_of_string "8589934592" in sqrt_nat n 0 (length_nat n), nat_of_string "92681");; test 3 equal_nat (let n = nat_of_string "4294967295" in sqrt_nat n 0 (length_nat n), nat_of_string "65535");; test 4 equal_nat (let n = nat_of_string "18446744065119617025" in sqrt_nat n 0 (length_nat n), nat_of_string "4294967295");; test 5 equal_nat (sqrt_nat (nat_of_int 15) 0 1, nat_of_int 3);;
2c10037d0b268818b5a6ee3909d3feb2151b8048c3c5a411ee0cada43b87d379
avsm/ocaml-docker-scripts
dockerfile-opam.ml
#!/usr/bin/env ocamlscript Ocaml.packs := ["dockerfile.opam"; "dockerfile.opam-cmdliner"] -- Generate OPAM base images with particular revisions of OCaml and OPAM . ISC License is at the end of the file . ISC License is at the end of the file. *) (* Generate Markdown list of tags for the README master *) let master_markdown_index = let open Dockerfile_distro in let open Printf in let system = "&#127362;" in let default = "&#127347;" in let gen_sws distro ocaml_version = match builtin_ocaml_of_distro distro with | None -> sprintf "%s %s" ocaml_version default | Some v when v = ocaml_version -> sprintf "%s %s%s" ocaml_version system default | Some v -> sprintf "%s %s, %s %s" v system ocaml_version default in [sprintf "This repository contains a set of [Docker]() container definitions for various combination of [OCaml]() and the [OPAM]() package manager. The containers all come preinstalled with a working compiler and an OPAM environment. Using it as simple as:\n\n```\ndocker pull ocaml/opam\ndocker run -ti ocaml/opam bash\n```\n\n...to get a working development environment. You can grab a specific distribution and test out external dependencies as well:\n```\ndocker run ocaml/opam:ubuntu-14.04_ocaml-4.02.3 opam depext -i cohttp lwt ssl\n```\n"; sprintf "Distributions\n==========\n"; sprintf "The default `latest` tag points to the following distribution:\n"; sprintf "Distribution | Available Switches | Command"; sprintf "------------ | ------------------ | -------"; sprintf "%s | %s | `docker pull ocaml/opam`\n" (human_readable_short_string_of_distro master_distro) (gen_sws master_distro latest_ocaml_version); sprintf "The latest stable distributions are summarised below. The default OCaml version available in the container is marked with a %s symbol, and a system installation of OCaml (as opposed to a locally compiled switch) is marked with a %s symbol.\n" default system; sprintf "Distribution | Available Switches | Command"; sprintf "------------ | ------------------ | -------" ] @ List.map (fun (distro, dfile) -> let name = human_readable_short_string_of_distro distro in let tag = latest_tag_of_distro distro in let sws = gen_sws distro latest_ocaml_version in sprintf "%s | %s | `docker pull ocaml/opam:%s`" name sws tag; ) latest_dockerfile_matrix @ [sprintf "\nThere are also individual containers available for each combination of an OS distribution and an OCaml revision. These should be useful for testing and continuous integration, since they will remain pinned to these versions for as long as the upstream distribution is supported. Note that older releases may have security issues if upstream stops maintaining them.\n"; "Distro | Compiler | Command"; "------ | -------- | -------"; ] @ List.map (fun (distro, ocaml_version, dfile) -> let tag = opam_tag_of_distro distro ocaml_version in let name = human_readable_string_of_distro distro in let sws = match builtin_ocaml_of_distro distro with | None -> sprintf "%s %s" ocaml_version default | Some v when v = ocaml_version -> sprintf "%s %s%s" ocaml_version system default | Some v -> sprintf "%s %s" ocaml_version default in sprintf "%s | %s | `docker pull ocaml/opam:%s`" name sws tag ) dockerfile_matrix @ ["\n\nUsing the Containers\n================\n"; "Each container comes with an initialised OPAM repository pointing to the central repository. There are [ONBUILD](/#onbuild) triggers to update the OS distribution and OPAM database when a new container is built. The default user in the container is called `opam`, and `sudo` is configured to allow password-less access to `root`.\n"; "To build an environment for the [Jane Street Core](/) library on the latest stable OCaml, a simple Dockerfile looks like this:\n"; "```\nFROM ocaml/opam\nopam depext -i core\n```"; "You can build and use this image locally for development by saving the Dockerfile and:\n"; "```\ndocker build -t ocaml-core .\ndocker run -ti ocaml-core bash\n```\n"; "You can also use the Docker [volume sharing](/#volume) to map in source code from your host into the container to persist the results of your build. You can also construct more specific Dockerfiles that use the full range of OPAM commands for a custom development environment. For example, to build the [MirageOS]() bleeding edge OCaml environment, this Dockerfile will add in a custom remote:\n"; "```\nFROM ocaml/opam:ubuntu-15.10_ocaml-4.02.3\nopam remote add dev git-dev\nopam depext -i mirage\n```\n"; "\n\nContributing\n==========\n\nTo discuss these containers, please e-mail Anil Madhavapeddy <> or the OPAM development list at <>. Contributions of Dockerfiles for additional OS distributions are most welcome! The files here are all autogenerated from the [ocaml-docker-scripts](-docker-scripts) repository, so please do not submit any PRs directly to this location. The containers are built and hosted on the Docker Hub [ocaml organisation]()."] |> String.concat "\n" Generate a git branch per Dockerfile combination let generate output_dir = let open Dockerfile_distro in [("master", to_dockerfile ~ocaml_version:latest_ocaml_version ~distro:master_distro)] |> generate_dockerfiles_in_git_branches ~readme:master_markdown_index ~crunch:true output_dir; List.map (fun (distro,ocamlv,dfile) -> (opam_tag_of_distro distro ocamlv), dfile) dockerfile_matrix |> generate_dockerfiles_in_git_branches ~crunch:true output_dir; List.map (fun (distro,dfile) -> (latest_tag_of_distro distro), dfile) latest_dockerfile_matrix |> generate_dockerfiles_in_git_branches ~crunch:true output_dir let _ = Dockerfile_opam_cmdliner.cmd ~name:"dockerfile-opam" ~version:"1.1.0" ~summary:"the OPAM source package manager" ~manual:"installs the OPAM source-based package manager and a combination of local compiler switches for various Linux distributions. It depends on the base OCaml containers that are generated via the $(b,opam-dockerfile-ocaml) command." ~default_dir:"opam-dockerfiles" ~generate |> Dockerfile_opam_cmdliner.run * Copyright ( c ) 2015 - 2016 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2015-2016 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *)
null
https://raw.githubusercontent.com/avsm/ocaml-docker-scripts/86fd07285c33fdbe70d3201f7681cb187a115fca/dockerfile-opam.ml
ocaml
Generate Markdown list of tags for the README master
#!/usr/bin/env ocamlscript Ocaml.packs := ["dockerfile.opam"; "dockerfile.opam-cmdliner"] -- Generate OPAM base images with particular revisions of OCaml and OPAM . ISC License is at the end of the file . ISC License is at the end of the file. *) let master_markdown_index = let open Dockerfile_distro in let open Printf in let system = "&#127362;" in let default = "&#127347;" in let gen_sws distro ocaml_version = match builtin_ocaml_of_distro distro with | None -> sprintf "%s %s" ocaml_version default | Some v when v = ocaml_version -> sprintf "%s %s%s" ocaml_version system default | Some v -> sprintf "%s %s, %s %s" v system ocaml_version default in [sprintf "This repository contains a set of [Docker]() container definitions for various combination of [OCaml]() and the [OPAM]() package manager. The containers all come preinstalled with a working compiler and an OPAM environment. Using it as simple as:\n\n```\ndocker pull ocaml/opam\ndocker run -ti ocaml/opam bash\n```\n\n...to get a working development environment. You can grab a specific distribution and test out external dependencies as well:\n```\ndocker run ocaml/opam:ubuntu-14.04_ocaml-4.02.3 opam depext -i cohttp lwt ssl\n```\n"; sprintf "Distributions\n==========\n"; sprintf "The default `latest` tag points to the following distribution:\n"; sprintf "Distribution | Available Switches | Command"; sprintf "------------ | ------------------ | -------"; sprintf "%s | %s | `docker pull ocaml/opam`\n" (human_readable_short_string_of_distro master_distro) (gen_sws master_distro latest_ocaml_version); sprintf "The latest stable distributions are summarised below. The default OCaml version available in the container is marked with a %s symbol, and a system installation of OCaml (as opposed to a locally compiled switch) is marked with a %s symbol.\n" default system; sprintf "Distribution | Available Switches | Command"; sprintf "------------ | ------------------ | -------" ] @ List.map (fun (distro, dfile) -> let name = human_readable_short_string_of_distro distro in let tag = latest_tag_of_distro distro in let sws = gen_sws distro latest_ocaml_version in sprintf "%s | %s | `docker pull ocaml/opam:%s`" name sws tag; ) latest_dockerfile_matrix @ [sprintf "\nThere are also individual containers available for each combination of an OS distribution and an OCaml revision. These should be useful for testing and continuous integration, since they will remain pinned to these versions for as long as the upstream distribution is supported. Note that older releases may have security issues if upstream stops maintaining them.\n"; "Distro | Compiler | Command"; "------ | -------- | -------"; ] @ List.map (fun (distro, ocaml_version, dfile) -> let tag = opam_tag_of_distro distro ocaml_version in let name = human_readable_string_of_distro distro in let sws = match builtin_ocaml_of_distro distro with | None -> sprintf "%s %s" ocaml_version default | Some v when v = ocaml_version -> sprintf "%s %s%s" ocaml_version system default | Some v -> sprintf "%s %s" ocaml_version default in sprintf "%s | %s | `docker pull ocaml/opam:%s`" name sws tag ) dockerfile_matrix @ ["\n\nUsing the Containers\n================\n"; "Each container comes with an initialised OPAM repository pointing to the central repository. There are [ONBUILD](/#onbuild) triggers to update the OS distribution and OPAM database when a new container is built. The default user in the container is called `opam`, and `sudo` is configured to allow password-less access to `root`.\n"; "To build an environment for the [Jane Street Core](/) library on the latest stable OCaml, a simple Dockerfile looks like this:\n"; "```\nFROM ocaml/opam\nopam depext -i core\n```"; "You can build and use this image locally for development by saving the Dockerfile and:\n"; "```\ndocker build -t ocaml-core .\ndocker run -ti ocaml-core bash\n```\n"; "You can also use the Docker [volume sharing](/#volume) to map in source code from your host into the container to persist the results of your build. You can also construct more specific Dockerfiles that use the full range of OPAM commands for a custom development environment. For example, to build the [MirageOS]() bleeding edge OCaml environment, this Dockerfile will add in a custom remote:\n"; "```\nFROM ocaml/opam:ubuntu-15.10_ocaml-4.02.3\nopam remote add dev git-dev\nopam depext -i mirage\n```\n"; "\n\nContributing\n==========\n\nTo discuss these containers, please e-mail Anil Madhavapeddy <> or the OPAM development list at <>. Contributions of Dockerfiles for additional OS distributions are most welcome! The files here are all autogenerated from the [ocaml-docker-scripts](-docker-scripts) repository, so please do not submit any PRs directly to this location. The containers are built and hosted on the Docker Hub [ocaml organisation]()."] |> String.concat "\n" Generate a git branch per Dockerfile combination let generate output_dir = let open Dockerfile_distro in [("master", to_dockerfile ~ocaml_version:latest_ocaml_version ~distro:master_distro)] |> generate_dockerfiles_in_git_branches ~readme:master_markdown_index ~crunch:true output_dir; List.map (fun (distro,ocamlv,dfile) -> (opam_tag_of_distro distro ocamlv), dfile) dockerfile_matrix |> generate_dockerfiles_in_git_branches ~crunch:true output_dir; List.map (fun (distro,dfile) -> (latest_tag_of_distro distro), dfile) latest_dockerfile_matrix |> generate_dockerfiles_in_git_branches ~crunch:true output_dir let _ = Dockerfile_opam_cmdliner.cmd ~name:"dockerfile-opam" ~version:"1.1.0" ~summary:"the OPAM source package manager" ~manual:"installs the OPAM source-based package manager and a combination of local compiler switches for various Linux distributions. It depends on the base OCaml containers that are generated via the $(b,opam-dockerfile-ocaml) command." ~default_dir:"opam-dockerfiles" ~generate |> Dockerfile_opam_cmdliner.run * Copyright ( c ) 2015 - 2016 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2015-2016 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *)
40f83fa909891ff7b922dea125f1156ac7a30569818220d867a836086b2d0426
jackfirth/lens
id-append.rkt
#lang racket/base (provide id-append) (require racket/list racket/syntax syntax/srcloc) ;; orig : Syntax -> Syntax (define (orig stx) (syntax-property stx 'original-for-check-syntax #t)) Sub - Range - Binder - Prop = ( ( Vector I d Nat Nat Real Real I d Nat Nat Real Real ) ) Binder - Proc = I d - > Sub - Range - Binder - Prop ;; make-binder-proc : Id Nat -> Binder-Proc (define ((make-binder-proc base n) id) (vector (syntax-local-introduce id) n (syntax-span base) 0.5 0.5 (syntax-local-introduce base) 0 (syntax-span base) 0.5 0.5)) get - sub - range - binders : I d ( Listof Binder - Proc ) - > Sub - Range - Binder - Prop (define (get-sub-range-binders id binder-procs) (for/list ([binder-proc (in-list binder-procs)]) (binder-proc id))) ;; empty-id : Syntax -> Id (define (empty-id ctxt) (datum->syntax ctxt '||)) (define appended-id-prop (gensym 'appended-id)) ;; id-append : #:context Syntax Identifier ... -> (values Identifier Sub-Range-Binder-Prop) ;; a wrapper around id-append* that keeps track of identifiers that ;; are themselves appended from other identifiers (define (id-append #:context ctxt . ids) (define ids* (append* (for/list ([id (in-list ids)]) appended : ( U # false ( I d ) ) (define appended (syntax-property id appended-id-prop)) (cond [appended appended] [else (list id)])))) (define-values [id sub-range-binders] (apply id-append* #:context ctxt ids*)) (values (syntax-property id appended-id-prop ids*) sub-range-binders)) ;; id-append* : #:context Syntax Identifier ... -> (values Identifier Sub-Range-Binder-Prop) (define (id-append* #:context ctxt . ids) binder - procs : ( Listof Binder - Proc ) (define-values [id n binder-procs] (for/fold ([id1 (empty-id ctxt)] [n 0] [binder-procs '()]) ([id2 (in-list ids)]) (values (format-id ctxt "~a~a" id1 id2) (+ n (syntax-span id2)) (cons (make-binder-proc id2 n) binder-procs)))) (define id* (orig id)) (values id* (get-sub-range-binders id* binder-procs)))
null
https://raw.githubusercontent.com/jackfirth/lens/733db7744921409b69ddc78ae5b23ffaa6b91e37/lens-common/lens/private/util/id-append.rkt
racket
orig : Syntax -> Syntax make-binder-proc : Id Nat -> Binder-Proc empty-id : Syntax -> Id id-append : #:context Syntax Identifier ... -> (values Identifier Sub-Range-Binder-Prop) a wrapper around id-append* that keeps track of identifiers that are themselves appended from other identifiers id-append* : #:context Syntax Identifier ... -> (values Identifier Sub-Range-Binder-Prop)
#lang racket/base (provide id-append) (require racket/list racket/syntax syntax/srcloc) (define (orig stx) (syntax-property stx 'original-for-check-syntax #t)) Sub - Range - Binder - Prop = ( ( Vector I d Nat Nat Real Real I d Nat Nat Real Real ) ) Binder - Proc = I d - > Sub - Range - Binder - Prop (define ((make-binder-proc base n) id) (vector (syntax-local-introduce id) n (syntax-span base) 0.5 0.5 (syntax-local-introduce base) 0 (syntax-span base) 0.5 0.5)) get - sub - range - binders : I d ( Listof Binder - Proc ) - > Sub - Range - Binder - Prop (define (get-sub-range-binders id binder-procs) (for/list ([binder-proc (in-list binder-procs)]) (binder-proc id))) (define (empty-id ctxt) (datum->syntax ctxt '||)) (define appended-id-prop (gensym 'appended-id)) (define (id-append #:context ctxt . ids) (define ids* (append* (for/list ([id (in-list ids)]) appended : ( U # false ( I d ) ) (define appended (syntax-property id appended-id-prop)) (cond [appended appended] [else (list id)])))) (define-values [id sub-range-binders] (apply id-append* #:context ctxt ids*)) (values (syntax-property id appended-id-prop ids*) sub-range-binders)) (define (id-append* #:context ctxt . ids) binder - procs : ( Listof Binder - Proc ) (define-values [id n binder-procs] (for/fold ([id1 (empty-id ctxt)] [n 0] [binder-procs '()]) ([id2 (in-list ids)]) (values (format-id ctxt "~a~a" id1 id2) (+ n (syntax-span id2)) (cons (make-binder-proc id2 n) binder-procs)))) (define id* (orig id)) (values id* (get-sub-range-binders id* binder-procs)))
f8f15321e8f8a958d2e8fa4114cd5866cc8d4467de21ced399f95b32b7a65106
tweag/ormolu
multiline2.hs
module Foo ( foo, bar, baz) where
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/module-header/multiline2.hs
haskell
module Foo ( foo, bar, baz) where
28fdfc97ed5d58a12f941549faf17e5b5826d0be90da0253ea619716e0717cee
NorfairKing/the-notes
Difference.hs
module Sets.Algebra.Difference where import Notes import Logic.PropositionalLogic.Macro import Sets.Algebra.Difference.Terms setDifference :: Note setDifference = subsection "Difference" $ do differenceDefinition intersectionAndDifferenceDisjunct symmetricSetDifferencesDisjunct symmetricDifferenceDefinition symmetricDifferenceEquivalentDefinition symmetricDifferenceITOUnionAndIntersection intersectionOverDifference differenceDefinition :: Note differenceDefinition = de $ do let (a, b, x) = ("A", "B", "x") s ["The set ", difference', " between sets ", m a, and, m b, " is the set of all elements of ", m a, " that are not in ", m b] ma $ a \\ b === setcmpr x ((x ∈ a) ∧ (x `nin` b)) setsDec :: Note setsDec = do let (a, b) = ("A", "B") s ["Let ", m a, and, m b, " be sets"] setssDec :: Note setssDec = do let (a, b, c) = ("A", "B", "C") s ["Let ", m a, ", ", m b, and, m c, " be sets"] intersectionAndDifferenceDisjunct :: Note intersectionAndDifferenceDisjunct = thm $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ ((pars $ a ∩ b) ∩ (pars $ a \\ b)) =§= emptyset proof $ do align_ $ [ (pars $ a ∩ b) ∩ (pars $ a \\ b) & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b)) ∩ setcmpr x ((x ∈ a) ∧ (x `nin` b)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y ∈ b)) ∧ x ∈ (setcmpr y (y ∈ a) ∧ (y `nin` b))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x ∈ b)) ∧ (pars $ (x ∈ a) ∧ (x `nin` b))) , "" & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b) ∧ (x `nin` b)) , "" & "" =§= setcmpr x ((x ∈ a) ∧ false) , "" & "" =§= setcmpr x false , "" & "" =§= emptyset ] symmetricSetDifferencesDisjunct :: Note symmetricSetDifferencesDisjunct = thm $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ ((pars $ a \\ b) ∩ (pars $ b \\ a)) =§= emptyset proof $ do align_ $ [ (pars $ a \\ b) ∩ (pars $ b \\ a) & "" =§= setcmpr x ((x ∈ a) ∧ (x `nin` b)) ∩ setcmpr x ((x ∈ b) ∧ (x `nin` a)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y `nin` b)) ∧ x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` a))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∧ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (a `nin` a)) ∧ (pars $ (x ∈ b) ∧ (x `nin` b))) , "" & "" =§= setcmpr x (false ∧ false) , "" & "" =§= setcmpr x false , "" & "" =§= emptyset ] symmetricDifferenceDefinition :: Note symmetricDifferenceDefinition = de $ do let (a, b, x) = ("A", "B", "x") s [the, defineTerm "symmetric difference", " of two sets ", m a, and, m b, " is the set of all element that are in either ", m a, or, m b, " but not both"] ma $ a △ b === setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x `nin` a) ∧ (x ∈ b))) symmetricDifferenceEquivalentDefinition :: Note symmetricDifferenceEquivalentDefinition = de $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ a △ b =§= (pars $ a \\ b) ∪ (pars $ b \\ a) proof $ do align_ $ [ (pars $ a \\ b) ∪ (pars $ b \\ a) & "" =§= setcmpr x ((x ∈ a) ∧ (x `nin` b)) ∪ setcmpr x ((x ∈ b) ∧ (x `nin` a)) , "" & "" =§= setcmpr x ((x ∈ setcmpr y ((y ∈ a) ∧ (y `nin` b))) ∨ (x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` a)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= a △ b ] symmetricDifferenceITOUnionAndIntersection :: Note symmetricDifferenceITOUnionAndIntersection = thm $ do lab symmetricDifferenceInTermsOfUnionAndIntersectionTheoremLabel setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ a △ b =§= (pars $ a ∪ b) \\ (pars $ a ∩ b) proof $ do align_ $ [ (pars $ a ∪ b) \\ (pars $ a ∩ b) & "" =§= setcmpr x ((x ∈ a) ∨ (x ∈ b)) \\ setcmpr x ((x ∈ a) ∧ (x ∈ b)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∨ (y ∈ b)) ∧ x `nin` setcmpr y ((y ∈ a) ∧ (y ∈ b))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∨ (x ∈ b)) ∧ (not . pars $ ((x ∈ a) ∧ (x ∈ b)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∨ (x ∈ b)) ∧ (pars $ ((x `nin` a) ∨ (x `nin` b)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= a △ b ] intersectionOverDifference :: Note intersectionOverDifference = thm $ do lab intersectionOverDifferenceTheoremLabel setssDec let (a, b, c, x, y) = ("A", "B", "C", "x", "y") ma $ a ∩ (pars $ b \\ c) =§= (pars $ a ∩ b) \\ c proof $ do align_ $ [ a ∩ (pars $ b \\ c) & "" =§= setcmpr x ((x ∈ a) ∧ x ∈ (b \\ c)) , "" & "" =§= setcmpr x ((x ∈ a) ∧ x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` c))) , "" & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b) ∧ (x `nin` c)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y ∈ b)) ∧ (x `nin` c)) , "" & "" =§= setcmpr x (x ∈ (pars $ a ∩ b) ∧ (x `nin` c)) , "" & "" =§= (pars $ a ∩ b) \\ c ]
null
https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Sets/Algebra/Difference.hs
haskell
module Sets.Algebra.Difference where import Notes import Logic.PropositionalLogic.Macro import Sets.Algebra.Difference.Terms setDifference :: Note setDifference = subsection "Difference" $ do differenceDefinition intersectionAndDifferenceDisjunct symmetricSetDifferencesDisjunct symmetricDifferenceDefinition symmetricDifferenceEquivalentDefinition symmetricDifferenceITOUnionAndIntersection intersectionOverDifference differenceDefinition :: Note differenceDefinition = de $ do let (a, b, x) = ("A", "B", "x") s ["The set ", difference', " between sets ", m a, and, m b, " is the set of all elements of ", m a, " that are not in ", m b] ma $ a \\ b === setcmpr x ((x ∈ a) ∧ (x `nin` b)) setsDec :: Note setsDec = do let (a, b) = ("A", "B") s ["Let ", m a, and, m b, " be sets"] setssDec :: Note setssDec = do let (a, b, c) = ("A", "B", "C") s ["Let ", m a, ", ", m b, and, m c, " be sets"] intersectionAndDifferenceDisjunct :: Note intersectionAndDifferenceDisjunct = thm $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ ((pars $ a ∩ b) ∩ (pars $ a \\ b)) =§= emptyset proof $ do align_ $ [ (pars $ a ∩ b) ∩ (pars $ a \\ b) & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b)) ∩ setcmpr x ((x ∈ a) ∧ (x `nin` b)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y ∈ b)) ∧ x ∈ (setcmpr y (y ∈ a) ∧ (y `nin` b))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x ∈ b)) ∧ (pars $ (x ∈ a) ∧ (x `nin` b))) , "" & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b) ∧ (x `nin` b)) , "" & "" =§= setcmpr x ((x ∈ a) ∧ false) , "" & "" =§= setcmpr x false , "" & "" =§= emptyset ] symmetricSetDifferencesDisjunct :: Note symmetricSetDifferencesDisjunct = thm $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ ((pars $ a \\ b) ∩ (pars $ b \\ a)) =§= emptyset proof $ do align_ $ [ (pars $ a \\ b) ∩ (pars $ b \\ a) & "" =§= setcmpr x ((x ∈ a) ∧ (x `nin` b)) ∩ setcmpr x ((x ∈ b) ∧ (x `nin` a)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y `nin` b)) ∧ x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` a))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∧ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (a `nin` a)) ∧ (pars $ (x ∈ b) ∧ (x `nin` b))) , "" & "" =§= setcmpr x (false ∧ false) , "" & "" =§= setcmpr x false , "" & "" =§= emptyset ] symmetricDifferenceDefinition :: Note symmetricDifferenceDefinition = de $ do let (a, b, x) = ("A", "B", "x") s [the, defineTerm "symmetric difference", " of two sets ", m a, and, m b, " is the set of all element that are in either ", m a, or, m b, " but not both"] ma $ a △ b === setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x `nin` a) ∧ (x ∈ b))) symmetricDifferenceEquivalentDefinition :: Note symmetricDifferenceEquivalentDefinition = de $ do setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ a △ b =§= (pars $ a \\ b) ∪ (pars $ b \\ a) proof $ do align_ $ [ (pars $ a \\ b) ∪ (pars $ b \\ a) & "" =§= setcmpr x ((x ∈ a) ∧ (x `nin` b)) ∪ setcmpr x ((x ∈ b) ∧ (x `nin` a)) , "" & "" =§= setcmpr x ((x ∈ setcmpr y ((y ∈ a) ∧ (y `nin` b))) ∨ (x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` a)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= a △ b ] symmetricDifferenceITOUnionAndIntersection :: Note symmetricDifferenceITOUnionAndIntersection = thm $ do lab symmetricDifferenceInTermsOfUnionAndIntersectionTheoremLabel setsDec let (a, b, x, y) = ("A", "B", "x", "y") ma $ a △ b =§= (pars $ a ∪ b) \\ (pars $ a ∩ b) proof $ do align_ $ [ (pars $ a ∪ b) \\ (pars $ a ∩ b) & "" =§= setcmpr x ((x ∈ a) ∨ (x ∈ b)) \\ setcmpr x ((x ∈ a) ∧ (x ∈ b)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∨ (y ∈ b)) ∧ x `nin` setcmpr y ((y ∈ a) ∧ (y ∈ b))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∨ (x ∈ b)) ∧ (not . pars $ ((x ∈ a) ∧ (x ∈ b)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∨ (x ∈ b)) ∧ (pars $ ((x `nin` a) ∨ (x `nin` b)))) , "" & "" =§= setcmpr x ((pars $ (x ∈ a) ∧ (x `nin` b)) ∨ (pars $ (x ∈ b) ∧ (x `nin` a))) , "" & "" =§= a △ b ] intersectionOverDifference :: Note intersectionOverDifference = thm $ do lab intersectionOverDifferenceTheoremLabel setssDec let (a, b, c, x, y) = ("A", "B", "C", "x", "y") ma $ a ∩ (pars $ b \\ c) =§= (pars $ a ∩ b) \\ c proof $ do align_ $ [ a ∩ (pars $ b \\ c) & "" =§= setcmpr x ((x ∈ a) ∧ x ∈ (b \\ c)) , "" & "" =§= setcmpr x ((x ∈ a) ∧ x ∈ setcmpr y ((y ∈ b) ∧ (y `nin` c))) , "" & "" =§= setcmpr x ((x ∈ a) ∧ (x ∈ b) ∧ (x `nin` c)) , "" & "" =§= setcmpr x (x ∈ setcmpr y ((y ∈ a) ∧ (y ∈ b)) ∧ (x `nin` c)) , "" & "" =§= setcmpr x (x ∈ (pars $ a ∩ b) ∧ (x `nin` c)) , "" & "" =§= (pars $ a ∩ b) \\ c ]
2a60d6b5038bff6d2ee3d467bb7b7d886ccd350dc8eab7a6e7ef535a3af15259
lread/test-doc-blocks
example.cljc
(ns example "Cljdoc supports CommonMark in docstrings. Test doc block will scan docstrings for CommonMark Clojure code blocks and generate tests for them. Test doc blocks currently ONLY looks at doc strings, so if your code block needs specific requires, you'll have to include them in, at least, your first block. In this namespace doc string we'll include 2 blocks: ```Clojure (+ 1 2 3) = > 6 ``` Escape chars hinder readability a bit in plain text, but should look good under cljdoc. ```Clojure (require '[clojure.string :as string]) (string/replace \"what,what\" \"what\" \"who\") ;; => \"who,who\" ```") (defn fn1 "No code blocks so will be skipped" []) (defn fn2 "This code block will be found: ```Clojure user=> (* 8 8) 64 ```" []) (defn fn3 "All the test-doc-block inline options are available, let's try one: <!-- :test-doc-blocks/skip --> ```Clojure (brace yourself ``` If the block were not skipped it would not parse and cause a failure." []) (defn fn4 "Let's try and use that `string` alias that we required in the namespace docstring. Escaped embedded quotes are not pretty in plain text, they are handled. ```Clojure (string/upper-case \"all \\\"good\\\"?\") => \"ALL \\\"GOOD\\\"?\" ```" [_x _y _z]) (comment (println "\"hey\\\" dude\"") )
null
https://raw.githubusercontent.com/lread/test-doc-blocks/f81643a5114d0ef9fda94e5da5591c58cae00692/doc/example.cljc
clojure
=> \"who,who\"
(ns example "Cljdoc supports CommonMark in docstrings. Test doc block will scan docstrings for CommonMark Clojure code blocks and generate tests for them. Test doc blocks currently ONLY looks at doc strings, so if your code block needs specific requires, you'll have to include them in, at least, your first block. In this namespace doc string we'll include 2 blocks: ```Clojure (+ 1 2 3) = > 6 ``` Escape chars hinder readability a bit in plain text, but should look good under cljdoc. ```Clojure (require '[clojure.string :as string]) (string/replace \"what,what\" \"what\" \"who\") ```") (defn fn1 "No code blocks so will be skipped" []) (defn fn2 "This code block will be found: ```Clojure user=> (* 8 8) 64 ```" []) (defn fn3 "All the test-doc-block inline options are available, let's try one: <!-- :test-doc-blocks/skip --> ```Clojure (brace yourself ``` If the block were not skipped it would not parse and cause a failure." []) (defn fn4 "Let's try and use that `string` alias that we required in the namespace docstring. Escaped embedded quotes are not pretty in plain text, they are handled. ```Clojure (string/upper-case \"all \\\"good\\\"?\") => \"ALL \\\"GOOD\\\"?\" ```" [_x _y _z]) (comment (println "\"hey\\\" dude\"") )
20718a84d932742cb6479e6d5749d2ba57c5699857d260f71607f51e0d7c2ce1
nushio3/learn-haskell
Main.hs
module Main where import qualified Data.Map as M -- guzaiがnabeに入っていたらその具材の個数を1減らす、 guzaiの個数がゼロになったらその項目をMapから消す 、 -- ように、関数eatを追記してください。 eat :: String -> M.Map String Int -> M.Map String Int eat guzai nabe = nabe party :: M.Map String Int -> IO () party nabe = do putStrLn $ "Nabe: " ++ show nabe order <- getLine let newNabe = eat order nabe if False -- ここで、鍋が空(null)かどうかを判定してください。 then putStrLn "The party is over!" else party newNabe readRecipe :: IO (M.Map String Int) readRecipe = do content <- readFile "recipe.txt" content の内容を解釈して、おいしそうな鍋の中身を作ってください ! return $ M.fromList [("Kuuki",1)] main :: IO () main = do initialNabe <- readRecipe party initialNabe
null
https://raw.githubusercontent.com/nushio3/learn-haskell/eda0fd0b33e9c4b7552afd24c6a25a105cca5f94/exercise-7-nabe/src/Main.hs
haskell
guzaiがnabeに入っていたらその具材の個数を1減らす、 ように、関数eatを追記してください。 ここで、鍋が空(null)かどうかを判定してください。
module Main where import qualified Data.Map as M guzaiの個数がゼロになったらその項目をMapから消す 、 eat :: String -> M.Map String Int -> M.Map String Int eat guzai nabe = nabe party :: M.Map String Int -> IO () party nabe = do putStrLn $ "Nabe: " ++ show nabe order <- getLine let newNabe = eat order nabe then putStrLn "The party is over!" else party newNabe readRecipe :: IO (M.Map String Int) readRecipe = do content <- readFile "recipe.txt" content の内容を解釈して、おいしそうな鍋の中身を作ってください ! return $ M.fromList [("Kuuki",1)] main :: IO () main = do initialNabe <- readRecipe party initialNabe
4fe8a61018cfab942b93707d0c899005de73dea232617a03a9cd262a56208696
mbutterick/typesetting
core.rkt
#lang racket/base (require txexpr/base racket/string racket/list) (provide hyphenate unhyphenate word->hyphenation-points exception-word->word+pattern string->hashpair) (module+ test (require rackunit)) ;; module default values (define default-min-length 5) (define default-min-left-length 2) (define default-min-right-length 2) (define default-joiner #\u00AD) (define default-min-hyphen-count 1) (define (exception-word->word+pattern ew) ;; an exception word indicates its breakpoints with added hyphens (define word (string-replace ew "-" "")) pattern has same number of points as word letters . 1 marks hyphenation point ; 0 no hyphenation (define points (cdr (map (λ (x) (if (equal? x "-") 1 0)) (regexp-split #px"\\p{L}" ew)))) ;; use list here so we can `apply` in `add-exception-word` (list word points)) (module+ test (check-equal? (exception-word->word+pattern "snôw-man") '("snôwman" (0 0 0 1 0 0 0))) (check-equal? (exception-word->word+pattern "snôwman") '("snôwman" (0 0 0 0 0 0 0))) (check-equal? (exception-word->word+pattern "sn-ôw-ma-n") '("snôwman" (0 1 0 1 0 1 0)))) (define (add-exception-word word-cache word) ;; `hash-set!` not `hash-ref!`, because we want an exception to override an existing value (apply hash-set! word-cache (exception-word->word+pattern word))) (define (remove-exception-word word-cache word) (hash-remove! word-cache (string-replace word "-" ""))) (define (string->natural i) (let* ([result (string->number i)] [result (and result (inexact->exact result))] [result (and (exact-nonnegative-integer? result) result)]) result)) (module+ test (check-equal? (string->natural "Foo") #f) (check-equal? (string->natural "1.0") 1) (check-equal? (string->natural "-3") #f)) (define (string->hashpair pat) (define-values (strs nums) (for/lists (strs nums) ;; using unicode-aware regexps to allow unicode hyphenation patterns ;; a pattern is a list of subpatterns, each of which is a character possibly followed by a number. also , the first position may just have a number . ([subpat (in-list (regexp-match* #px"^\\d?|(\\p{L}|\\p{P})\\d?" pat))]) (define str (cond [(regexp-match #px"(\\p{L}|\\p{P})?" subpat) => car] [else ""])) (define num (cond [(regexp-match #px"\\d" subpat) => (compose1 string->natural car)] [else 0])) (values str num))) (list (string-append* strs) nums)) (module+ test (check-equal? (string->hashpair "2'2") '("'" (2 2))) (check-equal? (string->hashpair ".â4") '(".â" (0 0 4))) (check-equal? (string->hashpair ".ý4") '(".ý" (0 0 4))) (check-equal? (string->hashpair "'ý4") '("'ý" (0 0 4))) (check-equal? (string->hashpair "’ý4") '("’ý" (0 0 4))) (check-equal? (string->hashpair "4ý-") '("ý-" (4 0 0))) (check-equal? (string->hashpair ".ach4") '(".ach" (0 0 0 0 4)))) (define (calculate-max-pattern patterns) ;; each pattern is a list of numbers ;; all the patterns have the same length run against parallel elements (apply map (λ xs (apply max xs)) patterns)) (module+ test (require rackunit) (check-equal? (calculate-max-pattern '((1 0 0))) '(1 0 0)) (check-equal? (calculate-max-pattern '((1 0 0) (0 1 0))) '(1 1 0)) (check-equal? (calculate-max-pattern '((1 0 0) (0 1 0) (0 0 1))) '(1 1 1)) (check-equal? (calculate-max-pattern '((1 2 3) (2 3 1) (3 1 2))) '(3 3 3))) (define (make-points word word-cache pattern-cache) (hash-ref! word-cache word (λ () ;; dots are used to denote the beginning and end of the word when matching patterns (define boundary-marker ".") (define word-with-boundaries (format "~a~a~a" boundary-marker (string-downcase word) boundary-marker)) (define word-length (string-length word-with-boundaries)) (define default-zero-pattern (make-list (add1 word-length) 0)) ;; walk through all the substrings and see if there's a matching pattern. (define matching-patterns (for*/list ([start (in-range word-length)] [end (in-range start word-length)] [substr (in-value (substring word-with-boundaries start (add1 end)))] [partial-pattern (in-value (hash-ref pattern-cache (string->symbol substr) #f))] #:when partial-pattern) ;; pad out partial-pattern to full length ;; (so we can compare patterns to find max value for each slot) (define left-zeroes (make-list start 0)) (define right-zeroes (make-list (- (add1 word-length) (length partial-pattern) start) 0)) (append left-zeroes partial-pattern right-zeroes))) (define max-pattern (calculate-max-pattern (cons default-zero-pattern matching-patterns))) ;; for point list generated from a pattern, drop first two elements because they represent hyphenation weight before the starting " . " and between " . " and the first letter . ;; drop last element because it represents hyphen after last "." after you drop these two , then each number corresponds to ;; whether a hyphen goes after that letter. (drop-right (drop max-pattern 2) 1)))) ;; Find hyphenation points in a word. This is not quite synonymous with syllables. (define (word->hyphenation-points word word-cache pattern-cache [min-length #f] [min-left-length #f] [min-right-length #f]) (cond [(< (string-length word) (or min-length default-min-length)) (list word)] [else ;; points is a list corresponding to the letters of the word. to create a no - hyphenation zone of length n , zero out the first n-1 points ;; and the last n points (because the last value in points is always superfluous) (define word-points (let* ([points (make-points word word-cache pattern-cache)] [left-zeroes (min (or min-left-length default-min-left-length) (length points))] [right-zeroes (min (or min-right-length default-min-right-length) (length points))]) (for/list ([(point idx) (in-indexed points)]) (if (<= left-zeroes (add1 idx) (- (length points) right-zeroes)) point 0)))) ;; odd-valued points in the pattern denote hyphenation points (define odd-point-indexes (for/list ([(wp idx) (in-indexed word-points)] #:when (odd? wp)) idx)) the hyphenation goes after the indexed letter , so add1 to the raw points for slicing (define breakpoints (append (list 0) (map add1 odd-point-indexes) (list (string-length word)))) (for/list ([start (in-list breakpoints)] [end (in-list (cdr breakpoints))]) ; shorter list controls exit of loop (substring word start end))])) ;; joiner contract allows char or string; this coerces to string. (define (joiner->string joiner) (format "~a" joiner)) (define (apply-proc proc x [omit-string (λ (x) #f)] [omit-txexpr (λ (x) #f)] [joiner default-joiner]) (let loop ([x x]) (cond [(and (string? x) (not (omit-string x))) handle intercapped words as capitalized pieces (define letter-before-uc #px"(?<=\\p{Ll})(?=\\p{Lu}\\p{Ll})") ; match xXx but not xXX or XXX (string-join (for/list ([x (in-list (string-split x letter-before-uc))]) (proc x)) (joiner->string joiner))] [(and (txexpr? x) (not (omit-txexpr x))) (make-txexpr (get-tag x) (get-attrs x) (map loop (get-elements x)))] [else x]))) (define (hyphenate word-cache pattern-cache x [joiner default-joiner] #:exceptions [extra-exceptions empty] #:min-length [min-length default-min-length] #:min-left-length [min-left-length default-min-left-length] #:min-right-length [min-right-length default-min-right-length] #:min-hyphens [min-hyphens-added default-min-hyphen-count] #:omit-word [omit-word? (λ (x) #f)] #:omit-string [omit-string? (λ (x) #f)] #:omit-txexpr [omit-txexpr? (λ (x) #f)]) ;; todo?: connect this regexp pattern to the one used in word? predicate (for-each (λ (ee) (add-exception-word word-cache ee)) extra-exceptions) (define word-pattern #px"\\p{L}+") ;; more restrictive than exception-word (define (replacer word . words) (cond [(omit-word? word) word] [else (define hyphenation-points (word->hyphenation-points word word-cache pattern-cache min-length min-left-length min-right-length)) (cond [(>= (sub1 (length hyphenation-points)) min-hyphens-added) (string-join hyphenation-points (joiner->string joiner))] [else word])])) (define (insert-hyphens text) (regexp-replace* word-pattern text replacer)) (begin0 (apply-proc insert-hyphens x omit-string? omit-txexpr? joiner) deleting from the main cache is cheaper than having to do two cache lookups for every word ;; (missing words will just be regenerated later) (for-each (λ (ee) (remove-exception-word word-cache ee)) extra-exceptions))) (define (unhyphenate x [joiner default-joiner] #:omit-word [omit-word? (λ (x) #f)] #:omit-string [omit-string? (λ (x) #f)] #:omit-txexpr [omit-txexpr? (λ (x) #f)]) (define word-pattern (pregexp (format "[\\w~a]+" joiner))) (define (replacer word . words) (if (not (omit-word? word)) (string-replace word (joiner->string joiner) "") word)) (define (remove-hyphens text) (regexp-replace* word-pattern text replacer)) (apply-proc remove-hyphens x omit-string? omit-txexpr?))
null
https://raw.githubusercontent.com/mbutterick/typesetting/8eedb97bb64cb2ff0cd9646eb1b0e46b67f1af44/hyphenate/hyphenate/private/core.rkt
racket
module default values an exception word indicates its breakpoints with added hyphens 0 no hyphenation use list here so we can `apply` in `add-exception-word` `hash-set!` not `hash-ref!`, because we want an exception to override an existing value using unicode-aware regexps to allow unicode hyphenation patterns a pattern is a list of subpatterns, each of which is a character possibly followed by a number. each pattern is a list of numbers all the patterns have the same length dots are used to denote the beginning and end of the word when matching patterns walk through all the substrings and see if there's a matching pattern. pad out partial-pattern to full length (so we can compare patterns to find max value for each slot) for point list generated from a pattern, drop last element because it represents hyphen after last "." whether a hyphen goes after that letter. Find hyphenation points in a word. This is not quite synonymous with syllables. points is a list corresponding to the letters of the word. and the last n points (because the last value in points is always superfluous) odd-valued points in the pattern denote hyphenation points shorter list controls exit of loop joiner contract allows char or string; this coerces to string. match xXx but not xXX or XXX todo?: connect this regexp pattern to the one used in word? predicate more restrictive than exception-word (missing words will just be regenerated later)
#lang racket/base (require txexpr/base racket/string racket/list) (provide hyphenate unhyphenate word->hyphenation-points exception-word->word+pattern string->hashpair) (module+ test (require rackunit)) (define default-min-length 5) (define default-min-left-length 2) (define default-min-right-length 2) (define default-joiner #\u00AD) (define default-min-hyphen-count 1) (define (exception-word->word+pattern ew) (define word (string-replace ew "-" "")) (define points (cdr (map (λ (x) (if (equal? x "-") 1 0)) (regexp-split #px"\\p{L}" ew)))) (list word points)) (module+ test (check-equal? (exception-word->word+pattern "snôw-man") '("snôwman" (0 0 0 1 0 0 0))) (check-equal? (exception-word->word+pattern "snôwman") '("snôwman" (0 0 0 0 0 0 0))) (check-equal? (exception-word->word+pattern "sn-ôw-ma-n") '("snôwman" (0 1 0 1 0 1 0)))) (define (add-exception-word word-cache word) (apply hash-set! word-cache (exception-word->word+pattern word))) (define (remove-exception-word word-cache word) (hash-remove! word-cache (string-replace word "-" ""))) (define (string->natural i) (let* ([result (string->number i)] [result (and result (inexact->exact result))] [result (and (exact-nonnegative-integer? result) result)]) result)) (module+ test (check-equal? (string->natural "Foo") #f) (check-equal? (string->natural "1.0") 1) (check-equal? (string->natural "-3") #f)) (define (string->hashpair pat) (define-values (strs nums) (for/lists (strs nums) also , the first position may just have a number . ([subpat (in-list (regexp-match* #px"^\\d?|(\\p{L}|\\p{P})\\d?" pat))]) (define str (cond [(regexp-match #px"(\\p{L}|\\p{P})?" subpat) => car] [else ""])) (define num (cond [(regexp-match #px"\\d" subpat) => (compose1 string->natural car)] [else 0])) (values str num))) (list (string-append* strs) nums)) (module+ test (check-equal? (string->hashpair "2'2") '("'" (2 2))) (check-equal? (string->hashpair ".â4") '(".â" (0 0 4))) (check-equal? (string->hashpair ".ý4") '(".ý" (0 0 4))) (check-equal? (string->hashpair "'ý4") '("'ý" (0 0 4))) (check-equal? (string->hashpair "’ý4") '("’ý" (0 0 4))) (check-equal? (string->hashpair "4ý-") '("ý-" (4 0 0))) (check-equal? (string->hashpair ".ach4") '(".ach" (0 0 0 0 4)))) (define (calculate-max-pattern patterns) run against parallel elements (apply map (λ xs (apply max xs)) patterns)) (module+ test (require rackunit) (check-equal? (calculate-max-pattern '((1 0 0))) '(1 0 0)) (check-equal? (calculate-max-pattern '((1 0 0) (0 1 0))) '(1 1 0)) (check-equal? (calculate-max-pattern '((1 0 0) (0 1 0) (0 0 1))) '(1 1 1)) (check-equal? (calculate-max-pattern '((1 2 3) (2 3 1) (3 1 2))) '(3 3 3))) (define (make-points word word-cache pattern-cache) (hash-ref! word-cache word (λ () (define boundary-marker ".") (define word-with-boundaries (format "~a~a~a" boundary-marker (string-downcase word) boundary-marker)) (define word-length (string-length word-with-boundaries)) (define default-zero-pattern (make-list (add1 word-length) 0)) (define matching-patterns (for*/list ([start (in-range word-length)] [end (in-range start word-length)] [substr (in-value (substring word-with-boundaries start (add1 end)))] [partial-pattern (in-value (hash-ref pattern-cache (string->symbol substr) #f))] #:when partial-pattern) (define left-zeroes (make-list start 0)) (define right-zeroes (make-list (- (add1 word-length) (length partial-pattern) start) 0)) (append left-zeroes partial-pattern right-zeroes))) (define max-pattern (calculate-max-pattern (cons default-zero-pattern matching-patterns))) drop first two elements because they represent hyphenation weight before the starting " . " and between " . " and the first letter . after you drop these two , then each number corresponds to (drop-right (drop max-pattern 2) 1)))) (define (word->hyphenation-points word word-cache pattern-cache [min-length #f] [min-left-length #f] [min-right-length #f]) (cond [(< (string-length word) (or min-length default-min-length)) (list word)] [else to create a no - hyphenation zone of length n , zero out the first n-1 points (define word-points (let* ([points (make-points word word-cache pattern-cache)] [left-zeroes (min (or min-left-length default-min-left-length) (length points))] [right-zeroes (min (or min-right-length default-min-right-length) (length points))]) (for/list ([(point idx) (in-indexed points)]) (if (<= left-zeroes (add1 idx) (- (length points) right-zeroes)) point 0)))) (define odd-point-indexes (for/list ([(wp idx) (in-indexed word-points)] #:when (odd? wp)) idx)) the hyphenation goes after the indexed letter , so add1 to the raw points for slicing (define breakpoints (append (list 0) (map add1 odd-point-indexes) (list (string-length word)))) (for/list ([start (in-list breakpoints)] (substring word start end))])) (define (joiner->string joiner) (format "~a" joiner)) (define (apply-proc proc x [omit-string (λ (x) #f)] [omit-txexpr (λ (x) #f)] [joiner default-joiner]) (let loop ([x x]) (cond [(and (string? x) (not (omit-string x))) handle intercapped words as capitalized pieces (string-join (for/list ([x (in-list (string-split x letter-before-uc))]) (proc x)) (joiner->string joiner))] [(and (txexpr? x) (not (omit-txexpr x))) (make-txexpr (get-tag x) (get-attrs x) (map loop (get-elements x)))] [else x]))) (define (hyphenate word-cache pattern-cache x [joiner default-joiner] #:exceptions [extra-exceptions empty] #:min-length [min-length default-min-length] #:min-left-length [min-left-length default-min-left-length] #:min-right-length [min-right-length default-min-right-length] #:min-hyphens [min-hyphens-added default-min-hyphen-count] #:omit-word [omit-word? (λ (x) #f)] #:omit-string [omit-string? (λ (x) #f)] #:omit-txexpr [omit-txexpr? (λ (x) #f)]) (for-each (λ (ee) (add-exception-word word-cache ee)) extra-exceptions) (define (replacer word . words) (cond [(omit-word? word) word] [else (define hyphenation-points (word->hyphenation-points word word-cache pattern-cache min-length min-left-length min-right-length)) (cond [(>= (sub1 (length hyphenation-points)) min-hyphens-added) (string-join hyphenation-points (joiner->string joiner))] [else word])])) (define (insert-hyphens text) (regexp-replace* word-pattern text replacer)) (begin0 (apply-proc insert-hyphens x omit-string? omit-txexpr? joiner) deleting from the main cache is cheaper than having to do two cache lookups for every word (for-each (λ (ee) (remove-exception-word word-cache ee)) extra-exceptions))) (define (unhyphenate x [joiner default-joiner] #:omit-word [omit-word? (λ (x) #f)] #:omit-string [omit-string? (λ (x) #f)] #:omit-txexpr [omit-txexpr? (λ (x) #f)]) (define word-pattern (pregexp (format "[\\w~a]+" joiner))) (define (replacer word . words) (if (not (omit-word? word)) (string-replace word (joiner->string joiner) "") word)) (define (remove-hyphens text) (regexp-replace* word-pattern text replacer)) (apply-proc remove-hyphens x omit-string? omit-txexpr?))
97943a9e5d84af7396785e482b991cebd7095abc0d091bd6a3b1e75e045bea42
frenetic-lang/ocaml-topology
myocamlbuild.ml
OASIS_START DO NOT EDIT ( digest : 2b5a8e0179c60ac087ac61f4ea3a67d4 ) module OASISGettext = struct # 22 " src / oasis / OASISGettext.ml " let ns_ str = str let s_ str = str let f_ (str: ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISExpr = struct # 22 " src / oasis / OASISExpr.ml " open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "<empty>" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "<no printer>") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end # 132 "myocamlbuild.ml" module BaseEnvLight = struct # 22 " src / base / BaseEnvLight.ml " module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let rec var_expand str env = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) env with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff let var_get name env = var_expand (MapString.find name env) env let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 237 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct # 22 " src / plugins / ocamlbuild / MyOCamlbuildFindlib.ml " * extension , copied from * * by and others * * Updated on 2009/02/28 * * Modified by * * by N. Pouillard and others * * Updated on 2009/02/28 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin type conf = { no_automatic_syntax: bool; } (* these functions are not really officially exported *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let exec_from_conf exec = let exec = let env_filename = Pathname.basename BaseEnvLight.default_filename in let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in try BaseEnvLight.var_get exec env with Not_found -> Printf.eprintf "W: Cannot get variable %s\n" exec; exec in let fix_win32 str = if Sys.os_type = "Win32" then begin let buff = Buffer.create (String.length str) in Adapt for windowsi , ocamlbuild + win32 has a hard time to handle ' \\ ' . *) String.iter (fun c -> Buffer.add_char buff (if c = '\\' then '/' else c)) str; Buffer.contents buff end else begin str end in fix_win32 exec let split s ch = let buf = Buffer.create 13 in let x = ref [] in let flush () = x := (Buffer.contents buf) :: !x; Buffer.clear buf in String.iter (fun c -> if c = ch then flush () else Buffer.add_char buf c) s; flush (); List.rev !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* ocamlfind command *) let ocamlfind x = S[Sh (exec_from_conf "ocamlfind"); x] (* This lists all supported packages. *) let find_packages () = List.map before_space (split_nl & run_and_read (exec_from_conf "ocamlfind" ^ " list")) (* Mock to list available syntaxes. *) let find_syntaxes () = ["camlp4o"; "camlp4r"] let well_known_syntax = [ "camlp4.quotations.o"; "camlp4.quotations.r"; "camlp4.exceptiontracer"; "camlp4.extend"; "camlp4.foldgenerator"; "camlp4.listcomprehension"; "camlp4.locationstripper"; "camlp4.macro"; "camlp4.mapgenerator"; "camlp4.metagenerator"; "camlp4.profiler"; "camlp4.tracer" ] let dispatch conf = function | After_options -> (* By using Before_options one let command line options have an higher * priority on the contrary using After_options will guarantee to have * the higher priority override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop"; Options.ocamlmklib := ocamlfind & A"ocamlmklib" | After_rules -> When one link an OCaml library / binary / package , one should use * -linkpkg * -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; if not (conf.no_automatic_syntax) then begin For each ocamlfind package one inject the -package option when * compiling , computing dependencies , generating documentation and * linking . * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> let base_args = [A"-package"; A pkg] in TODO : consider how to really choose camlp4o or camlp4r . let syn_args = [A"-syntax"; A "camlp4o"] in let (args, pargs) = (* Heuristic to identify syntax extensions: whether they end in ".syntax"; some might not. *) if Filename.check_suffix pkg "syntax" || List.mem pkg well_known_syntax then (syn_args @ base_args, syn_args) else (base_args, []) in flag ["ocaml"; "compile"; "pkg_"^pkg] & S args; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S args; flag ["ocaml"; "doc"; "pkg_"^pkg] & S args; flag ["ocaml"; "link"; "pkg_"^pkg] & S base_args; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S args; TODO : Check if this is allowed for OCaml < 3.12.1 flag ["ocaml"; "compile"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "ocamldep"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "doc"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "infer_interface"; "package("^pkg^")"] & S pargs; end (find_packages ()); end; Like -package but for extensions syntax . -syntax is useless * when linking . * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); The default " thread " tag is not compatible with ocamlfind . * Indeed , the default rules add the " threads.cma " or " threads.cmxa " * options when using this tag . When using the " -linkpkg " option with * ocamlfind , this module will then be added twice on the command line . * * To solve this , one approach is to add the " -thread " option when using * the " threads " package using the previous plugin . * Indeed, the default rules add the "threads.cma" or "threads.cmxa" * options when using this tag. When using the "-linkpkg" option with * ocamlfind, this module will then be added twice on the command line. * * To solve this, one approach is to add the "-thread" option when using * the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "compile"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "package(threads)"; "link"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "infer_interface"] (S[A "-thread"]); | _ -> () end module MyOCamlbuildBase = struct # 22 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml " * Base functions for writing myocamlbuild.ml @author @author Sylvain Le Gall *) open Ocamlbuild_plugin module OC = Ocamlbuild_pack.Ocaml_compiler type dir = string type file = string type name = string type tag = string # 62 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml " type t = { lib_ocaml: (name * dir list * string list) list; lib_c: (name * dir * file list) list; flags: (tag list * (spec OASISExpr.choices)) list; (* Replace the 'dir: include' from _tags by a precise interdepends in * directory. *) includes: (dir * dir list) list; } let env_filename = Pathname.basename BaseEnvLight.default_filename let dispatch_combine lst = fun e -> List.iter (fun dispatch -> dispatch e) lst let tag_libstubs nm = "use_lib"^nm^"_stubs" let nm_libstubs nm = nm^"_stubs" let dispatch t e = let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in match e with | Before_options -> let no_trailing_dot s = if String.length s >= 1 && s.[0] = '.' then String.sub s 1 ((String.length s) - 1) else s in List.iter (fun (opt, var) -> try opt := no_trailing_dot (BaseEnvLight.var_get var env) with Not_found -> Printf.eprintf "W: Cannot get variable %s\n" var) [ Options.ext_obj, "ext_obj"; Options.ext_lib, "ext_lib"; Options.ext_dll, "ext_dll"; ] | After_rules -> (* Declare OCaml libraries *) List.iter (function | nm, [], intf_modules -> ocaml_lib nm; let cmis = List.map (fun m -> (String.uncapitalize m) ^ ".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^nm^".cma"] cmis | nm, dir :: tl, intf_modules -> ocaml_lib ~dir:dir (dir^"/"^nm); List.iter (fun dir -> List.iter (fun str -> flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir])) ["compile"; "infer_interface"; "doc"]) tl; let cmis = List.map (fun m -> dir^"/"^(String.uncapitalize m)^".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^dir^"/"^nm^".cma"] cmis) t.lib_ocaml; (* Declare directories dependencies, replace "include" in _tags. *) List.iter (fun (dir, include_dirs) -> Pathname.define_context dir include_dirs) t.includes; (* Declare C libraries *) List.iter (fun (lib, dir, headers) -> (* Handle C part of library *) flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib] (S[A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("dll"^(nm_libstubs lib))]); When ocaml link something that use the C library , then one need that file to be up to date . This holds both for programs and for libraries . need that file to be up to date. This holds both for programs and for libraries. *) dep ["link"; "ocaml"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; (* TODO: be more specific about what depends on headers *) (* Depends on .h files *) dep ["compile"; "c"] headers; (* Setup search path for lib *) flag ["link"; "ocaml"; "use_"^lib] (S[A"-I"; P(dir)]); ) t.lib_c; (* Add flags *) List.iter (fun (tags, cond_specs) -> let spec = BaseEnvLight.var_choose cond_specs env in let rec eval_specs = function | S lst -> S (List.map eval_specs lst) | A str -> A (BaseEnvLight.var_expand str env) | spec -> spec in flag tags & (eval_specs spec)) t.flags | _ -> () let dispatch_default conf t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch conf; ] end # 606 "myocamlbuild.ml" open Ocamlbuild_plugin;; let package_default = { MyOCamlbuildBase.lib_ocaml = [("topology", ["lib"], [])]; lib_c = []; flags = []; includes = [("test", ["lib"]); ("exe", ["lib"])] } ;; let conf = {MyOCamlbuildFindlib.no_automatic_syntax = false} let dispatch_default = MyOCamlbuildBase.dispatch_default conf package_default;; # 622 "myocamlbuild.ml" OASIS_STOP Ocamlbuild_plugin.dispatch dispatch_default;;
null
https://raw.githubusercontent.com/frenetic-lang/ocaml-topology/a13ed36faaf216962fabd24d3402f91f5fec781d/myocamlbuild.ml
ocaml
these functions are not really officially exported ocamlfind command This lists all supported packages. Mock to list available syntaxes. By using Before_options one let command line options have an higher * priority on the contrary using After_options will guarantee to have * the higher priority override default commands by ocamlfind ones Heuristic to identify syntax extensions: whether they end in ".syntax"; some might not. Replace the 'dir: include' from _tags by a precise interdepends in * directory. Declare OCaml libraries Declare directories dependencies, replace "include" in _tags. Declare C libraries Handle C part of library TODO: be more specific about what depends on headers Depends on .h files Setup search path for lib Add flags
OASIS_START DO NOT EDIT ( digest : 2b5a8e0179c60ac087ac61f4ea3a67d4 ) module OASISGettext = struct # 22 " src / oasis / OASISGettext.ml " let ns_ str = str let s_ str = str let f_ (str: ('a, 'b, 'c, 'd) format4) = str let fn_ fmt1 fmt2 n = if n = 1 then fmt1^^"" else fmt2^^"" let init = [] end module OASISExpr = struct # 22 " src / oasis / OASISExpr.ml " open OASISGettext type test = string type flag = string type t = | EBool of bool | ENot of t | EAnd of t * t | EOr of t * t | EFlag of flag | ETest of test * string type 'a choices = (t * 'a) list let eval var_get t = let rec eval' = function | EBool b -> b | ENot e -> not (eval' e) | EAnd (e1, e2) -> (eval' e1) && (eval' e2) | EOr (e1, e2) -> (eval' e1) || (eval' e2) | EFlag nm -> let v = var_get nm in assert(v = "true" || v = "false"); (v = "true") | ETest (nm, vl) -> let v = var_get nm in (v = vl) in eval' t let choose ?printer ?name var_get lst = let rec choose_aux = function | (cond, vl) :: tl -> if eval var_get cond then vl else choose_aux tl | [] -> let str_lst = if lst = [] then s_ "<empty>" else String.concat (s_ ", ") (List.map (fun (cond, vl) -> match printer with | Some p -> p vl | None -> s_ "<no printer>") lst) in match name with | Some nm -> failwith (Printf.sprintf (f_ "No result for the choice list '%s': %s") nm str_lst) | None -> failwith (Printf.sprintf (f_ "No result for a choice list: %s") str_lst) in choose_aux (List.rev lst) end # 132 "myocamlbuild.ml" module BaseEnvLight = struct # 22 " src / base / BaseEnvLight.ml " module MapString = Map.Make(String) type t = string MapString.t let default_filename = Filename.concat (Sys.getcwd ()) "setup.data" let load ?(allow_empty=false) ?(filename=default_filename) () = if Sys.file_exists filename then begin let chn = open_in_bin filename in let st = Stream.of_channel chn in let line = ref 1 in let st_line = Stream.from (fun _ -> try match Stream.next st with | '\n' -> incr line; Some '\n' | c -> Some c with Stream.Failure -> None) in let lexer = Genlex.make_lexer ["="] st_line in let rec read_file mp = match Stream.npeek 3 lexer with | [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] -> Stream.junk lexer; Stream.junk lexer; Stream.junk lexer; read_file (MapString.add nm value mp) | [] -> mp | _ -> failwith (Printf.sprintf "Malformed data file '%s' line %d" filename !line) in let mp = read_file MapString.empty in close_in chn; mp end else if allow_empty then begin MapString.empty end else begin failwith (Printf.sprintf "Unable to load environment, the file '%s' doesn't exist." filename) end let rec var_expand str env = let buff = Buffer.create ((String.length str) * 2) in Buffer.add_substitute buff (fun var -> try var_expand (MapString.find var env) env with Not_found -> failwith (Printf.sprintf "No variable %s defined when trying to expand %S." var str)) str; Buffer.contents buff let var_get name env = var_expand (MapString.find name env) env let var_choose lst env = OASISExpr.choose (fun nm -> var_get nm env) lst end # 237 "myocamlbuild.ml" module MyOCamlbuildFindlib = struct # 22 " src / plugins / ocamlbuild / MyOCamlbuildFindlib.ml " * extension , copied from * * by and others * * Updated on 2009/02/28 * * Modified by * * by N. Pouillard and others * * Updated on 2009/02/28 * * Modified by Sylvain Le Gall *) open Ocamlbuild_plugin type conf = { no_automatic_syntax: bool; } let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let exec_from_conf exec = let exec = let env_filename = Pathname.basename BaseEnvLight.default_filename in let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in try BaseEnvLight.var_get exec env with Not_found -> Printf.eprintf "W: Cannot get variable %s\n" exec; exec in let fix_win32 str = if Sys.os_type = "Win32" then begin let buff = Buffer.create (String.length str) in Adapt for windowsi , ocamlbuild + win32 has a hard time to handle ' \\ ' . *) String.iter (fun c -> Buffer.add_char buff (if c = '\\' then '/' else c)) str; Buffer.contents buff end else begin str end in fix_win32 exec let split s ch = let buf = Buffer.create 13 in let x = ref [] in let flush () = x := (Buffer.contents buf) :: !x; Buffer.clear buf in String.iter (fun c -> if c = ch then flush () else Buffer.add_char buf c) s; flush (); List.rev !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s let ocamlfind x = S[Sh (exec_from_conf "ocamlfind"); x] let find_packages () = List.map before_space (split_nl & run_and_read (exec_from_conf "ocamlfind" ^ " list")) let find_syntaxes () = ["camlp4o"; "camlp4r"] let well_known_syntax = [ "camlp4.quotations.o"; "camlp4.quotations.r"; "camlp4.exceptiontracer"; "camlp4.extend"; "camlp4.foldgenerator"; "camlp4.listcomprehension"; "camlp4.locationstripper"; "camlp4.macro"; "camlp4.mapgenerator"; "camlp4.metagenerator"; "camlp4.profiler"; "camlp4.tracer" ] let dispatch conf = function | After_options -> Options.ocamlc := ocamlfind & A"ocamlc"; Options.ocamlopt := ocamlfind & A"ocamlopt"; Options.ocamldep := ocamlfind & A"ocamldep"; Options.ocamldoc := ocamlfind & A"ocamldoc"; Options.ocamlmktop := ocamlfind & A"ocamlmktop"; Options.ocamlmklib := ocamlfind & A"ocamlmklib" | After_rules -> When one link an OCaml library / binary / package , one should use * -linkpkg * -linkpkg *) flag ["ocaml"; "link"; "program"] & A"-linkpkg"; if not (conf.no_automatic_syntax) then begin For each ocamlfind package one inject the -package option when * compiling , computing dependencies , generating documentation and * linking . * compiling, computing dependencies, generating documentation and * linking. *) List.iter begin fun pkg -> let base_args = [A"-package"; A pkg] in TODO : consider how to really choose camlp4o or camlp4r . let syn_args = [A"-syntax"; A "camlp4o"] in let (args, pargs) = if Filename.check_suffix pkg "syntax" || List.mem pkg well_known_syntax then (syn_args @ base_args, syn_args) else (base_args, []) in flag ["ocaml"; "compile"; "pkg_"^pkg] & S args; flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S args; flag ["ocaml"; "doc"; "pkg_"^pkg] & S args; flag ["ocaml"; "link"; "pkg_"^pkg] & S base_args; flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S args; TODO : Check if this is allowed for OCaml < 3.12.1 flag ["ocaml"; "compile"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "ocamldep"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "doc"; "package("^pkg^")"] & S pargs; flag ["ocaml"; "infer_interface"; "package("^pkg^")"] & S pargs; end (find_packages ()); end; Like -package but for extensions syntax . -syntax is useless * when linking . * when linking. *) List.iter begin fun syntax -> flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; flag ["ocaml"; "infer_interface"; "syntax_"^syntax] & S[A"-syntax"; A syntax]; end (find_syntaxes ()); The default " thread " tag is not compatible with ocamlfind . * Indeed , the default rules add the " threads.cma " or " threads.cmxa " * options when using this tag . When using the " -linkpkg " option with * ocamlfind , this module will then be added twice on the command line . * * To solve this , one approach is to add the " -thread " option when using * the " threads " package using the previous plugin . * Indeed, the default rules add the "threads.cma" or "threads.cmxa" * options when using this tag. When using the "-linkpkg" option with * ocamlfind, this module will then be added twice on the command line. * * To solve this, one approach is to add the "-thread" option when using * the "threads" package using the previous plugin. *) flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]); flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "compile"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "doc"] (S[A "-I"; A "+threads"]); flag ["ocaml"; "package(threads)"; "link"] (S[A "-thread"]); flag ["ocaml"; "package(threads)"; "infer_interface"] (S[A "-thread"]); | _ -> () end module MyOCamlbuildBase = struct # 22 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml " * Base functions for writing myocamlbuild.ml @author @author Sylvain Le Gall *) open Ocamlbuild_plugin module OC = Ocamlbuild_pack.Ocaml_compiler type dir = string type file = string type name = string type tag = string # 62 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml " type t = { lib_ocaml: (name * dir list * string list) list; lib_c: (name * dir * file list) list; flags: (tag list * (spec OASISExpr.choices)) list; includes: (dir * dir list) list; } let env_filename = Pathname.basename BaseEnvLight.default_filename let dispatch_combine lst = fun e -> List.iter (fun dispatch -> dispatch e) lst let tag_libstubs nm = "use_lib"^nm^"_stubs" let nm_libstubs nm = nm^"_stubs" let dispatch t e = let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in match e with | Before_options -> let no_trailing_dot s = if String.length s >= 1 && s.[0] = '.' then String.sub s 1 ((String.length s) - 1) else s in List.iter (fun (opt, var) -> try opt := no_trailing_dot (BaseEnvLight.var_get var env) with Not_found -> Printf.eprintf "W: Cannot get variable %s\n" var) [ Options.ext_obj, "ext_obj"; Options.ext_lib, "ext_lib"; Options.ext_dll, "ext_dll"; ] | After_rules -> List.iter (function | nm, [], intf_modules -> ocaml_lib nm; let cmis = List.map (fun m -> (String.uncapitalize m) ^ ".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^nm^".cma"] cmis | nm, dir :: tl, intf_modules -> ocaml_lib ~dir:dir (dir^"/"^nm); List.iter (fun dir -> List.iter (fun str -> flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir])) ["compile"; "infer_interface"; "doc"]) tl; let cmis = List.map (fun m -> dir^"/"^(String.uncapitalize m)^".cmi") intf_modules in dep ["ocaml"; "link"; "library"; "file:"^dir^"/"^nm^".cma"] cmis) t.lib_ocaml; List.iter (fun (dir, include_dirs) -> Pathname.define_context dir include_dirs) t.includes; List.iter (fun (lib, dir, headers) -> flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib] (S[A"-cclib"; A("-l"^(nm_libstubs lib))]); flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib] (S[A"-dllib"; A("dll"^(nm_libstubs lib))]); When ocaml link something that use the C library , then one need that file to be up to date . This holds both for programs and for libraries . need that file to be up to date. This holds both for programs and for libraries. *) dep ["link"; "ocaml"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "ocaml"; tag_libstubs lib] [dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)]; dep ["compile"; "c"] headers; flag ["link"; "ocaml"; "use_"^lib] (S[A"-I"; P(dir)]); ) t.lib_c; List.iter (fun (tags, cond_specs) -> let spec = BaseEnvLight.var_choose cond_specs env in let rec eval_specs = function | S lst -> S (List.map eval_specs lst) | A str -> A (BaseEnvLight.var_expand str env) | spec -> spec in flag tags & (eval_specs spec)) t.flags | _ -> () let dispatch_default conf t = dispatch_combine [ dispatch t; MyOCamlbuildFindlib.dispatch conf; ] end # 606 "myocamlbuild.ml" open Ocamlbuild_plugin;; let package_default = { MyOCamlbuildBase.lib_ocaml = [("topology", ["lib"], [])]; lib_c = []; flags = []; includes = [("test", ["lib"]); ("exe", ["lib"])] } ;; let conf = {MyOCamlbuildFindlib.no_automatic_syntax = false} let dispatch_default = MyOCamlbuildBase.dispatch_default conf package_default;; # 622 "myocamlbuild.ml" OASIS_STOP Ocamlbuild_plugin.dispatch dispatch_default;;
505845b3dfd45b246ae5edfda0a5dcff826003090e7cdc4bb498fca573462e79
entangled/entangled
TextUtil.hs
-- ~\~ language=Haskell filename=src/TextUtil.hs -- ~\~ begin <<lit/a6-text-utils.md|src/TextUtil.hs>>[init] # LANGUAGE NoImplicitPrelude # module TextUtil where import RIO import qualified RIO.Text as T import Data.Char (isSpace) -- ~\~ begin <<lit/a6-text-utils.md|indent>>[init] indent :: Text -> Text -> Text indent pre text = unlines' $ map indentLine $ lines' text where indentLine line | line == "" = line | otherwise = pre <> line -- ~\~ end -- ~\~ begin <<lit/a6-text-utils.md|unindent>>[init] unindent :: Text -> Text -> Maybe Text unindent prefix s = unlines' <$> mapM unindentLine (lines' s) where unindentLine t | T.all isSpace t = Just "" | otherwise = T.stripPrefix prefix t -- ~\~ end -- ~\~ begin <<lit/a6-text-utils.md|unlines>>[init] lines' :: Text -> [Text] lines' text | text == "" = [""] | "\n" `T.isSuffixOf` text = T.lines text <> [""] | otherwise = T.lines text unlines' :: [Text] -> Text unlines' = T.intercalate "\n" -- ~\~ end -- ~\~ begin <<lit/a6-text-utils.md|maybe-unlines>>[init] mLines :: Maybe Text -> [Text] mLines Nothing = [] mLines (Just text) = lines' text mUnlines :: [Text] -> Maybe Text mUnlines [] = Nothing mUnlines ts = Just $ unlines' ts -- ~\~ end -- ~\~ end
null
https://raw.githubusercontent.com/entangled/entangled/bd3e996959f3beddba6c0727e9a11d1190e8cb7b/src/TextUtil.hs
haskell
~\~ language=Haskell filename=src/TextUtil.hs ~\~ begin <<lit/a6-text-utils.md|src/TextUtil.hs>>[init] ~\~ begin <<lit/a6-text-utils.md|indent>>[init] ~\~ end ~\~ begin <<lit/a6-text-utils.md|unindent>>[init] ~\~ end ~\~ begin <<lit/a6-text-utils.md|unlines>>[init] ~\~ end ~\~ begin <<lit/a6-text-utils.md|maybe-unlines>>[init] ~\~ end ~\~ end
# LANGUAGE NoImplicitPrelude # module TextUtil where import RIO import qualified RIO.Text as T import Data.Char (isSpace) indent :: Text -> Text -> Text indent pre text = unlines' $ map indentLine $ lines' text where indentLine line | line == "" = line | otherwise = pre <> line unindent :: Text -> Text -> Maybe Text unindent prefix s = unlines' <$> mapM unindentLine (lines' s) where unindentLine t | T.all isSpace t = Just "" | otherwise = T.stripPrefix prefix t lines' :: Text -> [Text] lines' text | text == "" = [""] | "\n" `T.isSuffixOf` text = T.lines text <> [""] | otherwise = T.lines text unlines' :: [Text] -> Text unlines' = T.intercalate "\n" mLines :: Maybe Text -> [Text] mLines Nothing = [] mLines (Just text) = lines' text mUnlines :: [Text] -> Maybe Text mUnlines [] = Nothing mUnlines ts = Just $ unlines' ts
7b895057db55a6d841dcca4908dec39755e015cef945752b74b09287e6a19d9d
Jannis/om-next-kanban-demo
sortable_list.cljs
(ns cards.sortable-list (:require [clojure.string :as str] [devcards.core :as dc :refer-macros [defcard]] [om.dom :as dom] [kanban.components.card :as kanban-card] [kanban.components.sortable-list :refer [sortable-list]])) (defcard "# Sortable List This is a generic list component that takes a sequence of items and allows these to be reordered via drag and drop. Custom functions to identify items and to render them in the list are supported. ## Invocation The overall sortable list invocation looks like this: ``` (sortable-list {:items ... :direction ... :key-fn (fn [item] ...) :element-fn (fn [item] ...) :change-fn (fn [items] ...)}) ``` Parameters: * `:items` is an ordered sequence of items of any type * `:direction` specifies the direction of the list and has to be either `:vertical` or `:horizontal`, with `:horizontal` being the default direction * `:key-fn` is function that must return a unique key for each item * `:element-fn` is a function that must return a React element for each item * `:change-fn` is a function that is called whenever the order of items in the list changes; it receives an ordered sequence of items in the same form that they were passed in to `:items`, so if `:items [1 2]` was passed in, `:change-fn` may be called with `[2 1]`. ### Example invocation ``` (def data (atom {:people [{:id 1 :name \"John\"} {:id 2 :name \"Tina\"}]})) ... (sortable-list {:items (:people @data) :key-fn :id :element-fn (fn [person] (dom/span (:name person))) :change-fn (fn [people] (swap! data assoc :people people))}) ``` Of course, rather than operating against a plain atom and having to watch it for changes yourself, you would normally use `sortable-list` with Om Next and have `:change-fn` mutate the app state.") (defcard "## Examples") (defcard "### Sortable list with words" (fn [state _] (sortable-list {:items (:items @state) :key-fn identity :element-fn (fn [word] (dom/span #js {:style #js {:border "thin solid black" :padding "1rem" :display "inline-block"}} word)) :change-fn #(swap! state assoc :items %)})) {:items (str/split "This is a list of short words" " ")} {:inspect-data true}) (defcard "### Sortable list with numbers and a different element function" (fn [state _] (sortable-list {:items (:items @state) :key-fn identity :element-fn (fn [number] (dom/span #js {:style #js {:background "#eee" :padding "0.5rem" :display "inline-block"}} number)) :change-fn #(swap! state assoc :items %)})) {:items [10000 20000 30000 40000 50000 60000]} {:inspect-data true}) (defcard "### Vertical sortable list with cards" (fn [state _] (dom/div #js {:className "sortable-list-vertical"} (sortable-list {:items (:items @state) :direction :vertical :key-fn :id :element-fn (fn [card] (kanban-card/card card)) :change-fn #(swap! state assoc :items %)}))) {:items [{:id 1 :text "This is the first card"} {:id 2 :text "This is the second card, this time with an assignee" :assignees [{:id 10 :username "ada" :name "Ada Lovelace"}]} {:id 3 :text "This is the third card"} {:id 4 :text "This is the fourth card"} {:id 5 :text "This is the fifth card"} {:id 6 :text "This is the sixth card"} {:id 7 :text "This is the seventh card"} {:id 8 :text "This is the eighth card"}]} {:inspect-data true})
null
https://raw.githubusercontent.com/Jannis/om-next-kanban-demo/84719bfb161d82f1d4405e263f258730277c7783/src/cards/sortable_list.cljs
clojure
it receives an ordered sequence of items in the
(ns cards.sortable-list (:require [clojure.string :as str] [devcards.core :as dc :refer-macros [defcard]] [om.dom :as dom] [kanban.components.card :as kanban-card] [kanban.components.sortable-list :refer [sortable-list]])) (defcard "# Sortable List This is a generic list component that takes a sequence of items and allows these to be reordered via drag and drop. Custom functions to identify items and to render them in the list are supported. ## Invocation The overall sortable list invocation looks like this: ``` (sortable-list {:items ... :direction ... :key-fn (fn [item] ...) :element-fn (fn [item] ...) :change-fn (fn [items] ...)}) ``` Parameters: * `:items` is an ordered sequence of items of any type * `:direction` specifies the direction of the list and has to be either `:vertical` or `:horizontal`, with `:horizontal` being the default direction * `:key-fn` is function that must return a unique key for each item * `:element-fn` is a function that must return a React element for each item * `:change-fn` is a function that is called whenever the order of items same form that they were passed in to `:items`, so if `:items [1 2]` was passed in, `:change-fn` may be called with `[2 1]`. ### Example invocation ``` (def data (atom {:people [{:id 1 :name \"John\"} {:id 2 :name \"Tina\"}]})) ... (sortable-list {:items (:people @data) :key-fn :id :element-fn (fn [person] (dom/span (:name person))) :change-fn (fn [people] (swap! data assoc :people people))}) ``` Of course, rather than operating against a plain atom and having to watch it for changes yourself, you would normally use `sortable-list` with Om Next and have `:change-fn` mutate the app state.") (defcard "## Examples") (defcard "### Sortable list with words" (fn [state _] (sortable-list {:items (:items @state) :key-fn identity :element-fn (fn [word] (dom/span #js {:style #js {:border "thin solid black" :padding "1rem" :display "inline-block"}} word)) :change-fn #(swap! state assoc :items %)})) {:items (str/split "This is a list of short words" " ")} {:inspect-data true}) (defcard "### Sortable list with numbers and a different element function" (fn [state _] (sortable-list {:items (:items @state) :key-fn identity :element-fn (fn [number] (dom/span #js {:style #js {:background "#eee" :padding "0.5rem" :display "inline-block"}} number)) :change-fn #(swap! state assoc :items %)})) {:items [10000 20000 30000 40000 50000 60000]} {:inspect-data true}) (defcard "### Vertical sortable list with cards" (fn [state _] (dom/div #js {:className "sortable-list-vertical"} (sortable-list {:items (:items @state) :direction :vertical :key-fn :id :element-fn (fn [card] (kanban-card/card card)) :change-fn #(swap! state assoc :items %)}))) {:items [{:id 1 :text "This is the first card"} {:id 2 :text "This is the second card, this time with an assignee" :assignees [{:id 10 :username "ada" :name "Ada Lovelace"}]} {:id 3 :text "This is the third card"} {:id 4 :text "This is the fourth card"} {:id 5 :text "This is the fifth card"} {:id 6 :text "This is the sixth card"} {:id 7 :text "This is the seventh card"} {:id 8 :text "This is the eighth card"}]} {:inspect-data true})
45d90259b7c5677f7c1ff08d11053d6df34c8ccc4854f64e848e6aadb98a88e3
aeternity/aesophia
aeso_abi_tests.erl
-module(aeso_abi_tests). -include_lib("eunit/include/eunit.hrl"). -compile([export_all, nowarn_export_all]). -define(SANDBOX(Code), sandbox(fun() -> Code end)). -define(DUMMY_HASH_WORD, 16#123). -define(DUMMY_HASH_LIT, "#0000000000000000000000000000000000000000000000000000000000000123"). sandbox(Code) -> Parent = self(), Tag = make_ref(), {Pid, Ref} = spawn_monitor(fun() -> Parent ! {Tag, Code()} end), receive {Tag, Res} -> erlang:demonitor(Ref, [flush]), {ok, Res}; {'DOWN', Ref, process, Pid, Reason} -> {error, Reason} after 100 -> exit(Pid, kill), {error, loop} end. from_words(Ws) -> << <<(from_word(W))/binary>> || W <- Ws >>. from_word(W) when is_integer(W) -> <<W:256>>; from_word(S) when is_list(S) -> Len = length(S), Bin = <<(list_to_binary(S))/binary, 0:(32 - Len)/unit:8>>, <<Len:256, Bin/binary>>. encode_decode_test() -> Tests = [42, 1, 0 -1, <<"Hello">>, {tuple, {}}, {tuple, {42}}, {tuple, {21, 37}}, [], [42], [21, 37], {variant, [0, 1], 0, {}}, {variant, [0, 1], 1, {42}}, {variant, [2], 0, {21, 37}}, {typerep, string}, {typerep, integer}, {typerep, {list, integer}}, {typerep, {tuple, [integer]}} ], [?assertEqual(Test, encode_decode(Test)) || Test <- Tests], ok. encode_decode_sophia_test() -> Check = fun(Type, Str) -> case {encode_decode_sophia_string(Type, Str), Str} of {X, X} -> ok; Other -> Other end end, ok = Check("int", "42"), ok = Check("int", "- 42"), ok = Check("bool", "true"), ok = Check("bool", "false"), ok = Check("string", "\"Hello\""), ok = Check("string * list(int) * option(bool)", "(\"Hello\", [1, 2, 3], Some(true))"), ok = Check("variant", "Blue({[\"x\"] = 1})"), ok = Check("r", "{x = (\"foo\", 0), y = Red}"), ok. to_sophia_value_mcl_bls12_381_test() -> Code = "include \"BLS12_381.aes\"\n" "contract C =\n" " entrypoint test_bls12_381_fp(x : int) = BLS12_381.int_to_fp(x)\n" " entrypoint test_bls12_381_fr(x : int) = BLS12_381.int_to_fr(x)\n" " entrypoint test_bls12_381_g1(x : int) = BLS12_381.mk_g1(x, x, x)\n", Opts = [{backend, fate}], CallValue32 = aeb_fate_encoding:serialize({bytes, <<20:256>>}), CallValue48 = aeb_fate_encoding:serialize({bytes, <<55:384>>}), CallValueTp = aeb_fate_encoding:serialize({tuple, {{bytes, <<15:256>>}, {bytes, <<160:256>>}, {bytes, <<1234:256>>}}}), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fp", ok, CallValue32, Opts), {error, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fp", ok, CallValue48, Opts), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fr", ok, CallValue48, Opts), {error, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fr", ok, CallValue32, Opts), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_g1", ok, CallValueTp, Opts), ok. to_sophia_value_neg_test() -> Code = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], {error, [Err1]} = aeso_compiler:to_sophia_value(Code, "f", ok, encode(12)), ?assertEqual("Data error:\nCannot translate FATE value 12\n of Sophia type string\n", aeso_errors:pp(Err1)), {error, [Err2]} = aeso_compiler:to_sophia_value(Code, "f", revert, encode(12)), ?assertEqual("Data error:\nCould not deserialize the revert message\n", aeso_errors:pp(Err2)), ok. encode_calldata_neg_test() -> Code = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], ExpErr1 = "Type error at line 5, col 34:\nCannot unify `int` and `bool`\n" "when checking the application of\n" " `f : (int) => string`\n" "to arguments\n" " `true : bool`\n", {error, [Err1]} = aeso_compiler:create_calldata(Code, "f", ["true"]), ?assertEqual(ExpErr1, aeso_errors:pp(Err1)), ok. decode_calldata_neg_test() -> Code1 = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], Code2 = [ "contract Foo =\n" " entrypoint f(x : string) : int = 42\n" ], {ok, CallDataFATE} = aeso_compiler:create_calldata(Code1, "f", ["42"]), {error, [Err1]} = aeso_compiler:decode_calldata(Code2, "f", <<1,2,3>>), ?assertEqual("Data error:\nFailed to decode calldata binary\n", aeso_errors:pp(Err1)), {error, [Err2]} = aeso_compiler:decode_calldata(Code2, "f", CallDataFATE), ?assertEqual("Data error:\nCannot translate FATE value \"*\"\n to Sophia type (string)\n", aeso_errors:pp(Err2)), {error, [Err3]} = aeso_compiler:decode_calldata(Code2, "x", CallDataFATE), ?assertEqual("Data error at line 1, col 1:\nFunction 'x' is missing in contract\n", aeso_errors:pp(Err3)), ok. encode_decode_sophia_string(SophiaType, String) -> io:format("String ~p~n", [String]), Code = [ "contract MakeCall =\n" , " type arg_type = ", SophiaType, "\n" , " type an_alias('a) = string * 'a\n" , " record r = {x : an_alias(int), y : variant}\n" , " datatype variant = Red | Blue(map(string, int))\n" , " entrypoint foo : arg_type => arg_type\n" ], case aeso_compiler:check_call(lists:flatten(Code), "foo", [String], [no_code]) of {ok, _, [Arg]} -> Data = encode(Arg), case aeso_compiler:to_sophia_value(Code, "foo", ok, Data, [no_code]) of {ok, Sophia} -> lists:flatten(io_lib:format("~s", [prettypr:format(aeso_pretty:expr(Sophia))])); {error, Err} -> io:format("~s\n", [Err]), {error, Err} end; {error, Err} -> io:format("~s\n", [Err]), {error, Err} end. calldata_test() -> [42, <<"foobar">>] = encode_decode_calldata("foo", ["int", "string"], ["42", "\"foobar\""]), [{variant, [0,1], 1, {#{ <<"a">> := 4 }}}, {tuple, {{tuple, {<<"b">>, 5}}, {variant, [0,1], 0, {}}}}] = encode_decode_calldata("foo", ["variant", "r"], ["Blue({[\"a\"] = 4})", "{x = (\"b\", 5), y = Red}"]), [{bytes, <<291:256>>}, {address, <<1110:256>>}] = encode_decode_calldata("foo", ["bytes(32)", "address"], [?DUMMY_HASH_LIT, "ak_1111111111111111111111111111113AFEFpt5"]), [{bytes, <<291:256>>}, {bytes, <<291:256>>}] = encode_decode_calldata("foo", ["bytes(32)", "hash"], [?DUMMY_HASH_LIT, ?DUMMY_HASH_LIT]), [119, {bytes, <<0:64/unit:8>>}] = encode_decode_calldata("foo", ["int", "signature"], ["119", [$# | lists:duplicate(128, $0)]]), [{contract, <<1110:256>>}] = encode_decode_calldata("foo", ["Remote"], ["ct_1111111111111111111111111111113AFEFpt5"]), ok. calldata_init_test() -> encode_decode_calldata("init", ["int"], ["42"]), Code = parameterized_contract("foo", ["int"]), encode_decode_calldata_(Code, "init", []), ok. calldata_indent_test() -> Test = fun(Extra) -> Code = parameterized_contract(Extra, "foo", ["int"]), encode_decode_calldata_(Code, "foo", ["42"]) end, Test(" stateful entrypoint bla() = ()"), Test(" type x = int"), Test(" stateful entrypoint bla(x : int) =\n" " x + 1"), Test(" stateful entrypoint bla(x : int) : int =\n" " x + 1"), ok. parameterized_contract(FunName, Types) -> parameterized_contract([], FunName, Types). parameterized_contract(ExtraCode, FunName, Types) -> lists:flatten( ["contract Remote =\n" " entrypoint bla : () => unit\n\n" "main contract Dummy =\n", ExtraCode, "\n", " type an_alias('a) = string * 'a\n" " record r = {x : an_alias(int), y : variant}\n" " datatype variant = Red | Blue(map(string, int))\n" " entrypoint ", FunName, " : (", string:join(Types, ", "), ") => int\n" ]). oracle_test() -> Contract = "contract OracleTest =\n" " entrypoint question(o, q : oracle_query(list(string), option(int))) =\n" " Oracle.get_question(o, q)\n", ?assertEqual({ok, "question", [{oracle, <<291:256>>}, {oracle_query, <<1110:256>>}]}, aeso_compiler:check_call(Contract, "question", ["ok_111111111111111111111111111111ZrdqRz9", "oq_1111111111111111111111111111113AFEFpt5"], [no_code])), ok. permissive_literals_fail_test() -> Contract = "contract OracleTest =\n" " stateful entrypoint haxx(o : oracle(list(string), option(int))) =\n" " Chain.spend(o, 1000000)\n", {error, [Err]} = aeso_compiler:check_call(Contract, "haxx", ["#123"], []), ?assertMatch("Type error at line 3, col 5:\nCannot unify" ++ _, aeso_errors:pp(Err)), ?assertEqual(type_error, aeso_errors:type(Err)), ok. encode_decode_calldata(FunName, Types, Args) -> Code = parameterized_contract(FunName, Types), encode_decode_calldata_(Code, FunName, Args). encode_decode_calldata_(Code, FunName, Args) -> {ok, Calldata} = aeso_compiler:create_calldata(Code, FunName, Args, []), {ok, _, _} = aeso_compiler:check_call(Code, FunName, Args, [no_code]), case FunName of "init" -> []; _ -> {ok, FateArgs} = aeb_fate_abi:decode_calldata(FunName, Calldata), FateArgs end. encode_decode(D) -> ?assertEqual(D, decode(encode(D))), D. encode(D) -> aeb_fate_encoding:serialize(D). decode(B) -> aeb_fate_encoding:deserialize(B).
null
https://raw.githubusercontent.com/aeternity/aesophia/a894876f56a818f6237259a7c48cbe6f4a4c01f8/test/aeso_abi_tests.erl
erlang
-module(aeso_abi_tests). -include_lib("eunit/include/eunit.hrl"). -compile([export_all, nowarn_export_all]). -define(SANDBOX(Code), sandbox(fun() -> Code end)). -define(DUMMY_HASH_WORD, 16#123). -define(DUMMY_HASH_LIT, "#0000000000000000000000000000000000000000000000000000000000000123"). sandbox(Code) -> Parent = self(), Tag = make_ref(), {Pid, Ref} = spawn_monitor(fun() -> Parent ! {Tag, Code()} end), receive {Tag, Res} -> erlang:demonitor(Ref, [flush]), {ok, Res}; {'DOWN', Ref, process, Pid, Reason} -> {error, Reason} after 100 -> exit(Pid, kill), {error, loop} end. from_words(Ws) -> << <<(from_word(W))/binary>> || W <- Ws >>. from_word(W) when is_integer(W) -> <<W:256>>; from_word(S) when is_list(S) -> Len = length(S), Bin = <<(list_to_binary(S))/binary, 0:(32 - Len)/unit:8>>, <<Len:256, Bin/binary>>. encode_decode_test() -> Tests = [42, 1, 0 -1, <<"Hello">>, {tuple, {}}, {tuple, {42}}, {tuple, {21, 37}}, [], [42], [21, 37], {variant, [0, 1], 0, {}}, {variant, [0, 1], 1, {42}}, {variant, [2], 0, {21, 37}}, {typerep, string}, {typerep, integer}, {typerep, {list, integer}}, {typerep, {tuple, [integer]}} ], [?assertEqual(Test, encode_decode(Test)) || Test <- Tests], ok. encode_decode_sophia_test() -> Check = fun(Type, Str) -> case {encode_decode_sophia_string(Type, Str), Str} of {X, X} -> ok; Other -> Other end end, ok = Check("int", "42"), ok = Check("int", "- 42"), ok = Check("bool", "true"), ok = Check("bool", "false"), ok = Check("string", "\"Hello\""), ok = Check("string * list(int) * option(bool)", "(\"Hello\", [1, 2, 3], Some(true))"), ok = Check("variant", "Blue({[\"x\"] = 1})"), ok = Check("r", "{x = (\"foo\", 0), y = Red}"), ok. to_sophia_value_mcl_bls12_381_test() -> Code = "include \"BLS12_381.aes\"\n" "contract C =\n" " entrypoint test_bls12_381_fp(x : int) = BLS12_381.int_to_fp(x)\n" " entrypoint test_bls12_381_fr(x : int) = BLS12_381.int_to_fr(x)\n" " entrypoint test_bls12_381_g1(x : int) = BLS12_381.mk_g1(x, x, x)\n", Opts = [{backend, fate}], CallValue32 = aeb_fate_encoding:serialize({bytes, <<20:256>>}), CallValue48 = aeb_fate_encoding:serialize({bytes, <<55:384>>}), CallValueTp = aeb_fate_encoding:serialize({tuple, {{bytes, <<15:256>>}, {bytes, <<160:256>>}, {bytes, <<1234:256>>}}}), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fp", ok, CallValue32, Opts), {error, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fp", ok, CallValue48, Opts), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fr", ok, CallValue48, Opts), {error, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_fr", ok, CallValue32, Opts), {ok, _} = aeso_compiler:to_sophia_value(Code, "test_bls12_381_g1", ok, CallValueTp, Opts), ok. to_sophia_value_neg_test() -> Code = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], {error, [Err1]} = aeso_compiler:to_sophia_value(Code, "f", ok, encode(12)), ?assertEqual("Data error:\nCannot translate FATE value 12\n of Sophia type string\n", aeso_errors:pp(Err1)), {error, [Err2]} = aeso_compiler:to_sophia_value(Code, "f", revert, encode(12)), ?assertEqual("Data error:\nCould not deserialize the revert message\n", aeso_errors:pp(Err2)), ok. encode_calldata_neg_test() -> Code = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], ExpErr1 = "Type error at line 5, col 34:\nCannot unify `int` and `bool`\n" "when checking the application of\n" " `f : (int) => string`\n" "to arguments\n" " `true : bool`\n", {error, [Err1]} = aeso_compiler:create_calldata(Code, "f", ["true"]), ?assertEqual(ExpErr1, aeso_errors:pp(Err1)), ok. decode_calldata_neg_test() -> Code1 = [ "contract Foo =\n" " entrypoint f(x : int) : string = \"hello\"\n" ], Code2 = [ "contract Foo =\n" " entrypoint f(x : string) : int = 42\n" ], {ok, CallDataFATE} = aeso_compiler:create_calldata(Code1, "f", ["42"]), {error, [Err1]} = aeso_compiler:decode_calldata(Code2, "f", <<1,2,3>>), ?assertEqual("Data error:\nFailed to decode calldata binary\n", aeso_errors:pp(Err1)), {error, [Err2]} = aeso_compiler:decode_calldata(Code2, "f", CallDataFATE), ?assertEqual("Data error:\nCannot translate FATE value \"*\"\n to Sophia type (string)\n", aeso_errors:pp(Err2)), {error, [Err3]} = aeso_compiler:decode_calldata(Code2, "x", CallDataFATE), ?assertEqual("Data error at line 1, col 1:\nFunction 'x' is missing in contract\n", aeso_errors:pp(Err3)), ok. encode_decode_sophia_string(SophiaType, String) -> io:format("String ~p~n", [String]), Code = [ "contract MakeCall =\n" , " type arg_type = ", SophiaType, "\n" , " type an_alias('a) = string * 'a\n" , " record r = {x : an_alias(int), y : variant}\n" , " datatype variant = Red | Blue(map(string, int))\n" , " entrypoint foo : arg_type => arg_type\n" ], case aeso_compiler:check_call(lists:flatten(Code), "foo", [String], [no_code]) of {ok, _, [Arg]} -> Data = encode(Arg), case aeso_compiler:to_sophia_value(Code, "foo", ok, Data, [no_code]) of {ok, Sophia} -> lists:flatten(io_lib:format("~s", [prettypr:format(aeso_pretty:expr(Sophia))])); {error, Err} -> io:format("~s\n", [Err]), {error, Err} end; {error, Err} -> io:format("~s\n", [Err]), {error, Err} end. calldata_test() -> [42, <<"foobar">>] = encode_decode_calldata("foo", ["int", "string"], ["42", "\"foobar\""]), [{variant, [0,1], 1, {#{ <<"a">> := 4 }}}, {tuple, {{tuple, {<<"b">>, 5}}, {variant, [0,1], 0, {}}}}] = encode_decode_calldata("foo", ["variant", "r"], ["Blue({[\"a\"] = 4})", "{x = (\"b\", 5), y = Red}"]), [{bytes, <<291:256>>}, {address, <<1110:256>>}] = encode_decode_calldata("foo", ["bytes(32)", "address"], [?DUMMY_HASH_LIT, "ak_1111111111111111111111111111113AFEFpt5"]), [{bytes, <<291:256>>}, {bytes, <<291:256>>}] = encode_decode_calldata("foo", ["bytes(32)", "hash"], [?DUMMY_HASH_LIT, ?DUMMY_HASH_LIT]), [119, {bytes, <<0:64/unit:8>>}] = encode_decode_calldata("foo", ["int", "signature"], ["119", [$# | lists:duplicate(128, $0)]]), [{contract, <<1110:256>>}] = encode_decode_calldata("foo", ["Remote"], ["ct_1111111111111111111111111111113AFEFpt5"]), ok. calldata_init_test() -> encode_decode_calldata("init", ["int"], ["42"]), Code = parameterized_contract("foo", ["int"]), encode_decode_calldata_(Code, "init", []), ok. calldata_indent_test() -> Test = fun(Extra) -> Code = parameterized_contract(Extra, "foo", ["int"]), encode_decode_calldata_(Code, "foo", ["42"]) end, Test(" stateful entrypoint bla() = ()"), Test(" type x = int"), Test(" stateful entrypoint bla(x : int) =\n" " x + 1"), Test(" stateful entrypoint bla(x : int) : int =\n" " x + 1"), ok. parameterized_contract(FunName, Types) -> parameterized_contract([], FunName, Types). parameterized_contract(ExtraCode, FunName, Types) -> lists:flatten( ["contract Remote =\n" " entrypoint bla : () => unit\n\n" "main contract Dummy =\n", ExtraCode, "\n", " type an_alias('a) = string * 'a\n" " record r = {x : an_alias(int), y : variant}\n" " datatype variant = Red | Blue(map(string, int))\n" " entrypoint ", FunName, " : (", string:join(Types, ", "), ") => int\n" ]). oracle_test() -> Contract = "contract OracleTest =\n" " entrypoint question(o, q : oracle_query(list(string), option(int))) =\n" " Oracle.get_question(o, q)\n", ?assertEqual({ok, "question", [{oracle, <<291:256>>}, {oracle_query, <<1110:256>>}]}, aeso_compiler:check_call(Contract, "question", ["ok_111111111111111111111111111111ZrdqRz9", "oq_1111111111111111111111111111113AFEFpt5"], [no_code])), ok. permissive_literals_fail_test() -> Contract = "contract OracleTest =\n" " stateful entrypoint haxx(o : oracle(list(string), option(int))) =\n" " Chain.spend(o, 1000000)\n", {error, [Err]} = aeso_compiler:check_call(Contract, "haxx", ["#123"], []), ?assertMatch("Type error at line 3, col 5:\nCannot unify" ++ _, aeso_errors:pp(Err)), ?assertEqual(type_error, aeso_errors:type(Err)), ok. encode_decode_calldata(FunName, Types, Args) -> Code = parameterized_contract(FunName, Types), encode_decode_calldata_(Code, FunName, Args). encode_decode_calldata_(Code, FunName, Args) -> {ok, Calldata} = aeso_compiler:create_calldata(Code, FunName, Args, []), {ok, _, _} = aeso_compiler:check_call(Code, FunName, Args, [no_code]), case FunName of "init" -> []; _ -> {ok, FateArgs} = aeb_fate_abi:decode_calldata(FunName, Calldata), FateArgs end. encode_decode(D) -> ?assertEqual(D, decode(encode(D))), D. encode(D) -> aeb_fate_encoding:serialize(D). decode(B) -> aeb_fate_encoding:deserialize(B).
47ca85a522d77473728f619157d9474a6dede6a3a7767c729c8bd29e9b5a8490
VisionsGlobalEmpowerment/webchange
icon_page_image_only.cljs
(ns webchange.ui.components.icon.layout.icon-page-image-only) (def data [:svg {:xmlns "" :width "104" :height "142" :viewBox "0 0 104 142" :fill "none" :stroke "#DCE3F5" :stroke-width "2" :class-name "stroke-colored"} [:g [:rect {:x "1" :y "1" :width "102" :height "140" :rx "5"}] [:path {:d "M103 138.721L71.8531 105.458L53.3885 125.391L69.8781 142L20.2587 92L0.999998 112.568"}] [:path {:d "M90.9396 23C90.9396 29.062 85.9523 34 79.7706 34C73.5889 34 68.6016 29.062 68.6016 23C68.6016 16.938 73.5889 12 79.7706 12C85.9523 12 90.9396 16.938 90.9396 23Z"}]]])
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/0df52dd08d54f14d4ec5d2717f48031849a7ee16/src/cljs/webchange/ui/components/icon/layout/icon_page_image_only.cljs
clojure
(ns webchange.ui.components.icon.layout.icon-page-image-only) (def data [:svg {:xmlns "" :width "104" :height "142" :viewBox "0 0 104 142" :fill "none" :stroke "#DCE3F5" :stroke-width "2" :class-name "stroke-colored"} [:g [:rect {:x "1" :y "1" :width "102" :height "140" :rx "5"}] [:path {:d "M103 138.721L71.8531 105.458L53.3885 125.391L69.8781 142L20.2587 92L0.999998 112.568"}] [:path {:d "M90.9396 23C90.9396 29.062 85.9523 34 79.7706 34C73.5889 34 68.6016 29.062 68.6016 23C68.6016 16.938 73.5889 12 79.7706 12C85.9523 12 90.9396 16.938 90.9396 23Z"}]]])
7961f88ec8adbd9041f53aeb6dd5e327002f6a2dc39e97c9174facf5fa5be03d
lisper99/cltcl
system.lisp
Copyright ( c ) 2008 - 2014 ;; ;; 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. ;; ---------------------------------------------------------------------------- ;; System definition for the clTcl package ;; 2008 - 2014 ;; ---------------------------------------------------------------------------- (in-package :cl-user) (defsystem cltcl () :members ("package" "cltcl" "communication" "protocol") :rules ((:in-order-to :compile :all (:requires (:load :previous))) (:in-order-to :load :all (:requires (:load :previous)))))
null
https://raw.githubusercontent.com/lisper99/cltcl/6edcec24689f04a10d6df4d402548c254b76eac5/system.lisp
lisp
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 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. ---------------------------------------------------------------------------- System definition for the clTcl package ----------------------------------------------------------------------------
Copyright ( c ) 2008 - 2014 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 , BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN 2008 - 2014 (in-package :cl-user) (defsystem cltcl () :members ("package" "cltcl" "communication" "protocol") :rules ((:in-order-to :compile :all (:requires (:load :previous))) (:in-order-to :load :all (:requires (:load :previous)))))