_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
d4a2ff4f1413b2dfa0ca2e5318a3c8c567f5af35e75dc732d82316017badef13
alavrik/piqi
expand.ml
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 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 . Copyright 2009, 2010, 2011, 2012, 2013, 2014 Anton Lavrik 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 C = Piqi_common open C (* command-line arguments *) let flag_includes_only = ref false let flag_extensions = ref true let flag_functions = ref false let flag_all = ref false let flag_add_module_name = ref false let usage = "Usage: piqi expand [options] <.piqi file> [output file]\nOptions:" let speclist = Main.common_speclist @ [ Main.arg_o; "--includes-only", Arg.Set flag_includes_only, "expand only includes"; "--extensions", Arg.Set flag_extensions, "expand extensions in additon to includes (this is the default option)"; "--functions", Arg.Set flag_functions, "expand functions in additon to includes"; "--all", Arg.Set flag_all, "same as specifying --extensions --functions"; "--add-module-name", Arg.Set flag_add_module_name, "add module name if it wasn't originally present"; Main.arg__strict; Main.arg__include_extension; ] let expand_file () = let ich = Main.open_input !Main.ifile in let piqi = Piqi.load_piqi !Main.ifile ich in if !flag_functions then flag_extensions := false; if !flag_includes_only then (flag_extensions := false; flag_functions := false); if !flag_all then (flag_extensions := true; flag_functions := true); let res_piqi = Piqi.expand_piqi piqi ~extensions:!flag_extensions ~functions:!flag_functions in if !flag_add_module_name && res_piqi.P.modname = None then res_piqi.P.modname <- piqi.P.modname; let och = Main.open_output !Main.ofile in Piqi_pp.prettyprint_piqi och res_piqi let run () = Main.parse_args () ~speclist ~usage ~min_arg_count:1 ~max_arg_count:2; expand_file () let _ = Main.register_command run "expand" "expand %.piqi includes and extensions"
null
https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/src/expand.ml
ocaml
command-line arguments
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 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 . Copyright 2009, 2010, 2011, 2012, 2013, 2014 Anton Lavrik 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 C = Piqi_common open C let flag_includes_only = ref false let flag_extensions = ref true let flag_functions = ref false let flag_all = ref false let flag_add_module_name = ref false let usage = "Usage: piqi expand [options] <.piqi file> [output file]\nOptions:" let speclist = Main.common_speclist @ [ Main.arg_o; "--includes-only", Arg.Set flag_includes_only, "expand only includes"; "--extensions", Arg.Set flag_extensions, "expand extensions in additon to includes (this is the default option)"; "--functions", Arg.Set flag_functions, "expand functions in additon to includes"; "--all", Arg.Set flag_all, "same as specifying --extensions --functions"; "--add-module-name", Arg.Set flag_add_module_name, "add module name if it wasn't originally present"; Main.arg__strict; Main.arg__include_extension; ] let expand_file () = let ich = Main.open_input !Main.ifile in let piqi = Piqi.load_piqi !Main.ifile ich in if !flag_functions then flag_extensions := false; if !flag_includes_only then (flag_extensions := false; flag_functions := false); if !flag_all then (flag_extensions := true; flag_functions := true); let res_piqi = Piqi.expand_piqi piqi ~extensions:!flag_extensions ~functions:!flag_functions in if !flag_add_module_name && res_piqi.P.modname = None then res_piqi.P.modname <- piqi.P.modname; let och = Main.open_output !Main.ofile in Piqi_pp.prettyprint_piqi och res_piqi let run () = Main.parse_args () ~speclist ~usage ~min_arg_count:1 ~max_arg_count:2; expand_file () let _ = Main.register_command run "expand" "expand %.piqi includes and extensions"
ece4b01c03a60bf01975fdf54fb6a1513e3f8e446543adc3de38ddf4a2ea7203
google/haskell-trainings
Codelab.hs
Copyright 2021 Google LLC -- 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. # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - type - defaults # module Codelab where import Internal (codelab) import Prelude hiding (null, head, tail, length, and, or, (++)) CODELAB 03 : Lists and recursion -- The default list is ubiquitous in the Prelude ; the default String type is but a type alias to [ ] after all . Though they have limitations , -- they're always useful. -- -- As a reminder, a list is either: -- * [] the empty list -- * (x:xs) a cell containing the value x, followed by the list xs -- There is no looping construct in Haskell . To go through a list , we use -- recursion instead. Here are a some common functions for you to reimplement! -- null tells you whether a list is empty or not null :: [a] -> Bool null fixme = codelab head returns the first element of the list . -- -- On an empty list, head panics: functions that can panic are "partial" head :: [a] -> a head [] = error "head: empty list" head fixme = codelab tail returns everything but the first element . -- If the list is empty it panics tail :: [a] -> [a] tail = codelab -- Do you remember it from the slides? length :: [a] -> Int length l = codelab -- "and" returns True if all the boolean values in the list are True. -- What do you think it returns for an empty list? and :: [Bool] -> Bool and l = codelab " or " returns True if at least one value in the list is True . -- What do you think it returns for an empty list? or :: [Bool] -> Bool or l = codelab " ( + + ) " is the concatenation operator . To concatenate two linked lists you have to chain the second one at the end of the first one . (++) :: [a] -> [a] -> [a] l1 ++ l2 = codelab
null
https://raw.githubusercontent.com/google/haskell-trainings/214013fc324fd6c8f63b874a58ead0c1d3e6788c/haskell_101/codelab/03_lists/src/Codelab.hs
haskell
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. they're always useful. As a reminder, a list is either: * [] the empty list * (x:xs) a cell containing the value x, followed by the list xs recursion instead. Here are a some common functions for you to reimplement! null tells you whether a list is empty or not On an empty list, head panics: functions that can panic are "partial" If the list is empty it panics Do you remember it from the slides? "and" returns True if all the boolean values in the list are True. What do you think it returns for an empty list? What do you think it returns for an empty list?
Copyright 2021 Google LLC Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - type - defaults # module Codelab where import Internal (codelab) import Prelude hiding (null, head, tail, length, and, or, (++)) CODELAB 03 : Lists and recursion The default list is ubiquitous in the Prelude ; the default String type is but a type alias to [ ] after all . Though they have limitations , There is no looping construct in Haskell . To go through a list , we use null :: [a] -> Bool null fixme = codelab head returns the first element of the list . head :: [a] -> a head [] = error "head: empty list" head fixme = codelab tail returns everything but the first element . tail :: [a] -> [a] tail = codelab length :: [a] -> Int length l = codelab and :: [Bool] -> Bool and l = codelab " or " returns True if at least one value in the list is True . or :: [Bool] -> Bool or l = codelab " ( + + ) " is the concatenation operator . To concatenate two linked lists you have to chain the second one at the end of the first one . (++) :: [a] -> [a] -> [a] l1 ++ l2 = codelab
aa1cd8f37af584061daef4a21dea7c1bf8a9c4773fdcc49398e19a3b1c9ccf8e
spechub/Hets
AS.der.hs
{-# LANGUAGE DeriveDataTypeable #-} | Module : ./NeSyPatterns / AS.der.hs Description : Abstract syntax for neural - symbolic patterns Copyright : ( c ) , Uni Magdeburg 2022 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of abstract syntax for neural - symbolic patterns Module : ./NeSyPatterns/AS.der.hs Description : Abstract syntax for neural-symbolic patterns Copyright : (c) Till Mossakowski, Uni Magdeburg 2022 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of abstract syntax for neural-symbolic patterns -} Ref . , , , . Modular design patterns for hybrid learning and reasoning systems . Appl Intell 51 , 6528 - 6546 ( 2021 ) . -021-02394-3 Ref. van Bekkum, M., de Boer, M., van Harmelen, F. et al. Modular design patterns for hybrid learning and reasoning systems. Appl Intell 51, 6528-6546 (2021). -021-02394-3 -} module NeSyPatterns.AS where import Common.IRI import Common.Id as Id import Common.AS_Annotation as AS_Anno import Data.Data -- DrIFT command ! global : GetRange ! | nodes are of form : i d : ontology_term -- | id is optional data Node = Node { ontologyTerm :: IRI, nesyId :: (Maybe IRI), nodeRange :: Id.Range } deriving (Show, Typeable, Data, Eq, Ord) newtype BASIC_SPEC = Basic_spec { items :: [AS_Anno.Annoted BASIC_ITEM] } deriving (Show, Typeable, Data) data BASIC_ITEM = Path { path :: [Node] -- written node -> ... -> node; } deriving (Show, Typeable, Data) newtype SYMB = Symb_id Node deriving (Show, Eq, Ord, Typeable, Data) data SYMB_ITEMS = Symb_items [SYMB] Id.Range deriving (Show, Eq, Ord, Typeable, Data) data SYMB_MAP_ITEMS = Symb_map_items [SYMB_OR_MAP] Id.Range deriving (Show, Eq, Ord, Typeable, Data) data SYMB_OR_MAP = Symb SYMB | Symb_map SYMB SYMB Id.Range -- pos: "|->" deriving (Show, Eq, Ord, Typeable, Data)
null
https://raw.githubusercontent.com/spechub/Hets/64b378dbf84168942ede394481f2f88e46ee1a29/NeSyPatterns/AS.der.hs
haskell
# LANGUAGE DeriveDataTypeable # DrIFT command | id is optional written node -> ... -> node; pos: "|->"
| Module : ./NeSyPatterns / AS.der.hs Description : Abstract syntax for neural - symbolic patterns Copyright : ( c ) , Uni Magdeburg 2022 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of abstract syntax for neural - symbolic patterns Module : ./NeSyPatterns/AS.der.hs Description : Abstract syntax for neural-symbolic patterns Copyright : (c) Till Mossakowski, Uni Magdeburg 2022 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of abstract syntax for neural-symbolic patterns -} Ref . , , , . Modular design patterns for hybrid learning and reasoning systems . Appl Intell 51 , 6528 - 6546 ( 2021 ) . -021-02394-3 Ref. van Bekkum, M., de Boer, M., van Harmelen, F. et al. Modular design patterns for hybrid learning and reasoning systems. Appl Intell 51, 6528-6546 (2021). -021-02394-3 -} module NeSyPatterns.AS where import Common.IRI import Common.Id as Id import Common.AS_Annotation as AS_Anno import Data.Data ! global : GetRange ! | nodes are of form : i d : ontology_term data Node = Node { ontologyTerm :: IRI, nesyId :: (Maybe IRI), nodeRange :: Id.Range } deriving (Show, Typeable, Data, Eq, Ord) newtype BASIC_SPEC = Basic_spec { items :: [AS_Anno.Annoted BASIC_ITEM] } deriving (Show, Typeable, Data) data BASIC_ITEM = Path { } deriving (Show, Typeable, Data) newtype SYMB = Symb_id Node deriving (Show, Eq, Ord, Typeable, Data) data SYMB_ITEMS = Symb_items [SYMB] Id.Range deriving (Show, Eq, Ord, Typeable, Data) data SYMB_MAP_ITEMS = Symb_map_items [SYMB_OR_MAP] Id.Range deriving (Show, Eq, Ord, Typeable, Data) data SYMB_OR_MAP = Symb SYMB | Symb_map SYMB SYMB Id.Range deriving (Show, Eq, Ord, Typeable, Data)
320ac3972b20ae1508009272acddeb90f8a1f82e67c7f6a5bb60b67148dbbef4
aryx/xix
lazy.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Para , INRIA Rocquencourt (* *) Copyright 1997 Institut National de Recherche en Informatique et en Automatique . Distributed only by permission . (* *) (***********************************************************************) $ I d : lazy.ml , v 1.2 1997/10/22 13:26:04 doligez Exp $ (* Module [Lazy]: deferred computations *) type 'a status = | Delayed of (unit -> 'a) | Value of 'a | Exception of exn ;; type 'a t = 'a status ref;; let force l = match !l with | Value v -> v | Exception e -> raise e | Delayed f -> try let v = f () in l := Value v; v with e -> l := Exception e; raise e ;;
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_core/unused/lazy.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* Module [Lazy]: deferred computations
, projet Para , INRIA Rocquencourt Copyright 1997 Institut National de Recherche en Informatique et en Automatique . Distributed only by permission . $ I d : lazy.ml , v 1.2 1997/10/22 13:26:04 doligez Exp $ type 'a status = | Delayed of (unit -> 'a) | Value of 'a | Exception of exn ;; type 'a t = 'a status ref;; let force l = match !l with | Value v -> v | Exception e -> raise e | Delayed f -> try let v = f () in l := Value v; v with e -> l := Exception e; raise e ;;
c34adba1538bdc5078817b6ff5214c723a824ee5dd5cd22ef0b8ea0f71a703a6
rleonid/oml
epsitst.ml
let dx = 2.22044e-16 let () = Printf.printf "add eps to 1.0 %b\n" (1.0 +. epsilon_float = 1.0); Printf.printf "sub eps from 1.0 %b\n" (1.0 -. epsilon_float = 1.0); Printf.printf "add dx to 1.0 %b\n" (1.0 +. dx = 1.0); Printf.printf "sub dx from 1.0 %b\n" (1.0 -. dx = 1.0); Printf.printf "dx is less %b\n" (dx < epsilon_float)
null
https://raw.githubusercontent.com/rleonid/oml/a857d67708827ed00df3f175a942044601ca50cf/scripts/epsitst.ml
ocaml
let dx = 2.22044e-16 let () = Printf.printf "add eps to 1.0 %b\n" (1.0 +. epsilon_float = 1.0); Printf.printf "sub eps from 1.0 %b\n" (1.0 -. epsilon_float = 1.0); Printf.printf "add dx to 1.0 %b\n" (1.0 +. dx = 1.0); Printf.printf "sub dx from 1.0 %b\n" (1.0 -. dx = 1.0); Printf.printf "dx is less %b\n" (dx < epsilon_float)
a044fe98946b379e8f0cad73cd23713058740bbf0de0ac9a54e1572492352756
nikita-volkov/rerebase
Array.hs
module Data.Text.Array ( module Rebase.Data.Text.Array ) where import Rebase.Data.Text.Array
null
https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/Text/Array.hs
haskell
module Data.Text.Array ( module Rebase.Data.Text.Array ) where import Rebase.Data.Text.Array
139fb83616646fed9f07ddf19581a9808d22bbdc1210e0eecb065cf197d56096
EFanZh/EOPL-Exercises
exercise-2.28-test.rkt
#lang racket/base (require rackunit) (require "../solutions/exercise-2.28.rkt") (check-equal? (unparse-lc-exp (var-exp 'a)) "a") (check-equal? (unparse-lc-exp (lambda-exp 'a (var-exp 'b))) "(lambda (a) b)") (check-equal? (unparse-lc-exp (app-exp (var-exp 'a) (var-exp 'b))) "(a b)") (check-equal? (unparse-lc-exp (lambda-exp 'a (app-exp (var-exp 'b) (var-exp 'c)))) "(lambda (a) (b c))") (check-equal? (unparse-lc-exp (app-exp (app-exp (var-exp 'a) (var-exp 'b)) (app-exp (var-exp 'c) (var-exp 'd)))) "((a b) (c d))")
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/tests/exercise-2.28-test.rkt
racket
#lang racket/base (require rackunit) (require "../solutions/exercise-2.28.rkt") (check-equal? (unparse-lc-exp (var-exp 'a)) "a") (check-equal? (unparse-lc-exp (lambda-exp 'a (var-exp 'b))) "(lambda (a) b)") (check-equal? (unparse-lc-exp (app-exp (var-exp 'a) (var-exp 'b))) "(a b)") (check-equal? (unparse-lc-exp (lambda-exp 'a (app-exp (var-exp 'b) (var-exp 'c)))) "(lambda (a) (b c))") (check-equal? (unparse-lc-exp (app-exp (app-exp (var-exp 'a) (var-exp 'b)) (app-exp (var-exp 'c) (var-exp 'd)))) "((a b) (c d))")
03761ff3dc60a3b93529dea6b50fd0a3f9a3aa31e489b48708a8385c9147b269
namin/biohacker
abduction-ex.lisp
(in-ltre (create-ltre "Abduction Test")) (rule ((:INTERN (son ?son of ?father) :var ?def)) (rassert! (:IMPLIES ?def (father ?father of ?son)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?son ?father)) :FAMILY) (rassert! (:IMPLIES ?def (related ?father ?son))) :FAMILY) (rule ((:INTERN (father ?father of ?son) :var ?def)) (rassert! (:IMPLIES ?def (son ?son of ?father)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?son ?father)) :FAMILY) (rassert! (:IMPLIES ?def (related ?father ?son))) :FAMILY) (rule ((:INTERN (brothers ?a ?b) :var ?def)) (rassert! (:IMPLIES ?def (brothers ?b ?a)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?a ?b)) :FAMILY) (rassert! (:IMPLIES ?def (related ?b ?a)) :FAMILY)) (rule ((:INTERN (uncle ?uncle of ?nephew) :var ?def)) (rassert! (:IMPLIES ?def (nephew ?nephew of ?uncle)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?nephew ?uncle)) :FAMILY) (rassert! (:IMPLIES ?def (related ?uncle ?nephew))) :FAMILY) (rule ((:INTERN (nephew ?nephew of ?uncle) :var ?def)) (rassert! (:IMPLIES ?def (uncle ?uncle of ?nephew)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?nephew ?uncle)) :FAMILY) (rassert! (:IMPLIES ?def (related ?uncle ?nephew))) :FAMILY) (rule ((:INTERN (brothers ?a ?b) :var ?brothers-def) (:INTERN (son ?c of ?a) :var ?son-def)) (rassert! (:IMPLIES (:AND ?brothers-def ?son-def) (uncle ?b of ?c)) :FAMILY)) (rule ((:INTERN (related ?a ?b) :var ?def)) (rassert! (:IMPLIES ?def (:OR (brothers ?a ?b) (father ?a of ?b) (son ?a of ?b) (uncle ?a of ?b) (nephew ?a of ?b))) :RELATED-SIMPLE-MINDED-GUESS)) (setq patterns '((son ?son of ?father) (father ?father of ?son) (brothers ?a ?b) (uncle ?a of ?b) (nephew ?a of ?b))) (needs '(father mohamed of aadel) :TRUE patterns) ( ( ( FATHER MOHAMED OF AADEL ) ) ( ( SON AADEL OF ) ) ) (sort-fact-sets (needs '(related mohamed aadel) :TRUE patterns)) ;(((BROTHERS AADEL MOHAMED)) ; ((BROTHERS MOHAMED AADEL)) ( ( FATHER AADEL OF ) ) ; ((FATHER MOHAMED OF AADEL)) ( ( NEPHEW AADEL OF ) ) ( ( NEPHEW MOHAMED OF AADEL ) ) ( ( SON AADEL OF ) ) ; ((SON MOHAMED OF AADEL)) ( ( AADEL OF ) ) ( ( OF AADEL ) ) ) (setq pattern-cost-list '(((son ?son of ?father) . 20) ((father ?father of ?son) . 10) ((brothers ?a ?b) . 30) ((uncle ?a of ?b) . 40) ((nephew ?a of ?b) . 50))) (labduce '(related mohamed aadel) :TRUE pattern-cost-list) ( ( ( FATHER MOHAMED OF AADEL ) ) . 10 )
null
https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/BPS/ltms/abduction-ex.lisp
lisp
(((BROTHERS AADEL MOHAMED)) ((BROTHERS MOHAMED AADEL)) ((FATHER MOHAMED OF AADEL)) ((SON MOHAMED OF AADEL))
(in-ltre (create-ltre "Abduction Test")) (rule ((:INTERN (son ?son of ?father) :var ?def)) (rassert! (:IMPLIES ?def (father ?father of ?son)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?son ?father)) :FAMILY) (rassert! (:IMPLIES ?def (related ?father ?son))) :FAMILY) (rule ((:INTERN (father ?father of ?son) :var ?def)) (rassert! (:IMPLIES ?def (son ?son of ?father)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?son ?father)) :FAMILY) (rassert! (:IMPLIES ?def (related ?father ?son))) :FAMILY) (rule ((:INTERN (brothers ?a ?b) :var ?def)) (rassert! (:IMPLIES ?def (brothers ?b ?a)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?a ?b)) :FAMILY) (rassert! (:IMPLIES ?def (related ?b ?a)) :FAMILY)) (rule ((:INTERN (uncle ?uncle of ?nephew) :var ?def)) (rassert! (:IMPLIES ?def (nephew ?nephew of ?uncle)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?nephew ?uncle)) :FAMILY) (rassert! (:IMPLIES ?def (related ?uncle ?nephew))) :FAMILY) (rule ((:INTERN (nephew ?nephew of ?uncle) :var ?def)) (rassert! (:IMPLIES ?def (uncle ?uncle of ?nephew)) :EQUIVALENCE) (rassert! (:IMPLIES ?def (related ?nephew ?uncle)) :FAMILY) (rassert! (:IMPLIES ?def (related ?uncle ?nephew))) :FAMILY) (rule ((:INTERN (brothers ?a ?b) :var ?brothers-def) (:INTERN (son ?c of ?a) :var ?son-def)) (rassert! (:IMPLIES (:AND ?brothers-def ?son-def) (uncle ?b of ?c)) :FAMILY)) (rule ((:INTERN (related ?a ?b) :var ?def)) (rassert! (:IMPLIES ?def (:OR (brothers ?a ?b) (father ?a of ?b) (son ?a of ?b) (uncle ?a of ?b) (nephew ?a of ?b))) :RELATED-SIMPLE-MINDED-GUESS)) (setq patterns '((son ?son of ?father) (father ?father of ?son) (brothers ?a ?b) (uncle ?a of ?b) (nephew ?a of ?b))) (needs '(father mohamed of aadel) :TRUE patterns) ( ( ( FATHER MOHAMED OF AADEL ) ) ( ( SON AADEL OF ) ) ) (sort-fact-sets (needs '(related mohamed aadel) :TRUE patterns)) ( ( FATHER AADEL OF ) ) ( ( NEPHEW AADEL OF ) ) ( ( NEPHEW MOHAMED OF AADEL ) ) ( ( SON AADEL OF ) ) ( ( AADEL OF ) ) ( ( OF AADEL ) ) ) (setq pattern-cost-list '(((son ?son of ?father) . 20) ((father ?father of ?son) . 10) ((brothers ?a ?b) . 30) ((uncle ?a of ?b) . 40) ((nephew ?a of ?b) . 50))) (labduce '(related mohamed aadel) :TRUE pattern-cost-list) ( ( ( FATHER MOHAMED OF AADEL ) ) . 10 )
550b66eeb155f2a8f7fdf22cad5a10b22efd7f01b5d128f90bcb8295249435b1
lucasdicioccio/prodapi
BackgroundNetwork.hs
module BackgroundNetwork where import Prod.Background (background, BackgroundVal, readBackgroundVal) import Prod.Tracer (Tracer(..), tracePrint, pulls, silent) import Control.Concurrent.Chan (Chan, newChan, writeChan, readChan) import Control.Concurrent (threadDelay) import Control.Monad (forever) -- | Showcases how one could use channels to perform scheduling -- between different background values (some are polled, some are pushed, one is combining) complicatedNetworkOfBackgroundUpdates :: Tracer IO Int -> IO (BackgroundVal Int) complicatedNetworkOfBackgroundUpdates traceInt = do a first background task continuously write to a channel c <- newChan _ <- background silent nostate 0 (act0 c) a second background task actually ( which happens to do nothing ) has a value b1 <- background silent nostate 500 act1 -- the composed background tasks actually is composed of a combination of - the updates sent on the channel by the first background job - and the second background job ( read on demand ) background silent 0 0 (act2 (readBackgroundVal b1) c) where nostate = () stateless :: IO a -> (() -> IO (a, ())) stateless io = const $ (,) <$> io <*> pure () act0 :: Chan Int -> () -> IO (Int, ()) act0 c = stateless (threadDelay 10000000 >> writeChan c 1 >> pure 1) act1 :: () -> IO (Int, ()) act1 = stateless (forever $ threadDelay 10000000) act2 :: IO Int -> Chan Int -> Int -> IO (Int, Int) act2 io c n = do m <- readChan c let ret = n + m runTracer (pulls (\k -> (+k) <$> io) traceInt) ret pure $ (ret, ret)
null
https://raw.githubusercontent.com/lucasdicioccio/prodapi/4c43e1d617832f8ae88cb15afada1d5ab5e46ea4/example/src/BackgroundNetwork.hs
haskell
| Showcases how one could use channels to perform scheduling between different background values (some are polled, some are pushed, one is combining) the composed background tasks actually is composed of a combination of
module BackgroundNetwork where import Prod.Background (background, BackgroundVal, readBackgroundVal) import Prod.Tracer (Tracer(..), tracePrint, pulls, silent) import Control.Concurrent.Chan (Chan, newChan, writeChan, readChan) import Control.Concurrent (threadDelay) import Control.Monad (forever) complicatedNetworkOfBackgroundUpdates :: Tracer IO Int -> IO (BackgroundVal Int) complicatedNetworkOfBackgroundUpdates traceInt = do a first background task continuously write to a channel c <- newChan _ <- background silent nostate 0 (act0 c) a second background task actually ( which happens to do nothing ) has a value b1 <- background silent nostate 500 act1 - the updates sent on the channel by the first background job - and the second background job ( read on demand ) background silent 0 0 (act2 (readBackgroundVal b1) c) where nostate = () stateless :: IO a -> (() -> IO (a, ())) stateless io = const $ (,) <$> io <*> pure () act0 :: Chan Int -> () -> IO (Int, ()) act0 c = stateless (threadDelay 10000000 >> writeChan c 1 >> pure 1) act1 :: () -> IO (Int, ()) act1 = stateless (forever $ threadDelay 10000000) act2 :: IO Int -> Chan Int -> Int -> IO (Int, Int) act2 io c n = do m <- readChan c let ret = n + m runTracer (pulls (\k -> (+k) <$> io) traceInt) ret pure $ (ret, ret)
4df9f2b4169112dccaa39602055c3bbf3e00329b2a6491dab44cab347f404d6d
OCamlPro/ocaml-benchs
date.mli
(***************************************************************************) Copyright ( C ) 2000 - 2013 LexiFi SAS . All rights reserved . (* *) (* This program is free software: you can redistribute it and/or modify *) it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , (* or (at your option) any later version. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License (* along with this program. If not, see </>. *) (***************************************************************************) type date val max_date: date val min_date: date val of_string: string -> date val days_between: date -> date -> float val act_365: date -> date -> float val add_months: date -> int -> date val add_years: date -> int -> date
null
https://raw.githubusercontent.com/OCamlPro/ocaml-benchs/98047e112574e6bf55137dd8058f227a9f40281b/lexifi-g2pp/date.mli
ocaml
************************************************************************* This program is free software: you can redistribute it and/or modify or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. *************************************************************************
Copyright ( C ) 2000 - 2013 LexiFi SAS . All rights reserved . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , You should have received a copy of the GNU General Public License type date val max_date: date val min_date: date val of_string: string -> date val days_between: date -> date -> float val act_365: date -> date -> float val add_months: date -> int -> date val add_years: date -> int -> date
62235b742331092a3c6c9ff901b79fadeb3ad58afc04cff4543a0ab8d1100389
idris-lang/Idris-dev
LangOpts.hs
| Module : IRTS.LangOpts Description : Transformations to apply to ' IR . License : : The Idris Community . Module : IRTS.LangOpts Description : Transformations to apply to Idris' IR. License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveFunctor, PatternGuards #-} module IRTS.LangOpts(inlineAll) where import Idris.Core.CaseTree import Idris.Core.TT import IRTS.Lang import Control.Monad.State hiding (lift) inlineAll :: [(Name, LDecl)] -> [(Name, LDecl)] inlineAll lds = let defs = addAlist lds emptyContext in map (\ (n, def) -> (n, doInline defs def)) lds nextN :: State Int Name nextN = do i <- get put (i + 1) return $ sMN i "in" -- | Inline inside a declaration. -- -- Variables are still Name at this stage. Need to preserve -- uniqueness of variable names in the resulting definition, so invent -- a new name for every variable we encounter doInline :: LDefs -> LDecl -> LDecl doInline = doInline' 1 doInline' :: Int -> LDefs -> LDecl -> LDecl doInline' 0 defs d = d doInline' i defs d@(LConstructor _ _ _) = d doInline' i defs (LFun opts topn args exp) = let inl = evalState (eval [] initEnv [topn] defs exp) (length args) -- do some case floating, which might arise as a result -- then, eta contract res = eta $ caseFloats 10 inl in case res of LLam args' body -> doInline' (i - 1) defs $ LFun opts topn (map snd initNames ++ args') body _ -> doInline' (i - 1) defs $ LFun opts topn (map snd initNames) res where caseFloats 0 tm = tm caseFloats n tm = let res = caseFloat tm in if res == tm then res else caseFloats (n-1) res initNames = zipWith (\n i -> (n, newn n i)) args [0..] initEnv = map (\(n, n') -> (n, LV n')) initNames newn (UN n) i = MN i n newn _ i = sMN i "arg" unload :: [LExp] -> LExp -> LExp unload [] e = e unload stk (LApp tc e args) = LApp tc e (args ++ stk) unload stk e = LApp False e stk takeStk :: [(Name, LExp)] -> [Name] -> [LExp] -> ([(Name, LExp)], [Name], [LExp]) takeStk env (a : args) (v : stk) = takeStk ((a, v) : env) args stk takeStk env args stk = (env, args, stk) eval :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp -> State Int LExp eval stk env rec defs (LLazyApp n es) = unload stk <$> LLazyApp n <$> (mapM (eval [] env rec defs) es) eval stk env rec defs (LForce e) = do e' <- eval [] env rec defs e case e' of LLazyExp forced -> eval stk env rec defs forced LLazyApp n es -> eval stk env rec defs (LApp False (LV n) es) _ -> return (unload stk (LForce e')) eval stk env rec defs (LLazyExp e) = unload stk <$> LLazyExp <$> eval [] env rec defs e Special case for io_bind , because it needs to keep executing the first -- action, and is worth inlining to avoid the thunk eval [] env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)]) | n == sUN "io_bind" = do w <- nextN let env' = (w, LV w) : env act' <- eval [] env' rec defs (LApp False act [LV w]) argn <- nextN k' <- eval [] ((arg, LV argn) : env') rec defs (LApp False k [LV w]) return $ LLam [w] (LLet argn act' k') eval (world : stk) env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)]) | n == sUN "io_bind" = do act' <- eval [] env rec defs (LApp False act [world]) argn <- nextN k' <- eval stk ((arg, LV argn) : env) rec defs (LApp False k [world]) Needs to be a LLet to make sure the action gets evaluated return $ LLet argn act' k' eval stk env rec defs (LApp t f es) = do es' <- mapM (eval [] env rec defs) es eval (es' ++ stk) env rec defs f eval stk env rec defs (LLet n val sc) = do n' <- nextN LLet n' <$> eval [] env rec defs val <*> eval stk ((n, LV n') : env) rec defs sc eval stk env rec defs (LProj exp i) = unload stk <$> (LProj <$> eval [] env rec defs exp <*> return i) eval stk env rec defs (LCon loc i n es) = unload stk <$> (LCon loc i n <$> mapM (eval [] env rec defs) es) eval stk env rec defs (LCase ty e []) = pure LNothing eval stk env rec defs (LCase ty e alts) = do e' <- eval [] env rec defs e case evalAlts e' alts of Just (env', tm) -> eval stk env' rec defs tm Nothing -> do alts' <- mapM (evalAlt stk env rec defs) alts -- If they're all lambdas, bind the lambda at the top let prefix = getLams (map getRHS alts') case prefix of [] -> return $ LCase ty e' (replaceInAlts e' alts') args -> do alts_red <- mapM (dropArgs args) alts' return $ LLam args (LCase ty e' (replaceInAlts e' alts_red)) where evalAlts e' [] = Nothing evalAlts (LCon _ t n args) (LConCase i n' es rhs : as) | n == n' = Just (zip es args ++ env, rhs) evalAlts (LConst c) (LConstCase c' rhs : as) | c == c' = Just (env, rhs) evalAlts (LCon _ _ _ _) (LDefaultCase rhs : as) = Just (env, rhs) evalAlts (LConst _) (LDefaultCase rhs : as) = Just (env, rhs) evalAlts tm (_ : as) = evalAlts tm as eval stk env rec defs (LOp f es) = unload stk <$> LOp f <$> mapM (eval [] env rec defs) es eval stk env rec defs (LForeign t s args) = unload stk <$> LForeign t s <$> mapM (\(t, e) -> do e' <- eval [] env rec defs e return (t, e')) args -- save the interesting cases for the end: -- lambdas, and names to reduce eval stk env rec defs (LLam args sc) | (env', args', stk') <- takeStk env args stk = case args' of [] -> eval stk' env' rec defs sc as -> do ns' <- mapM (\n -> do n' <- nextN return (n, n')) args' LLam (map snd ns') <$> eval stk' (map (\ (n, n') -> (n, LV n')) ns' ++ env') rec defs sc eval stk env rec defs var@(LV n) = case lookup n env of Just t | t /= LV n && n `notElem` rec -> eval stk env (n : rec) defs t | otherwise -> return (unload stk t) Nothing | n `notElem` rec, Just (LFun opts _ args body) <- lookupCtxtExact n defs, Inline `elem` opts -> apply stk env (n : rec) defs var args body | Just (LConstructor n t a) <- lookupCtxtExact n defs -> return (LCon Nothing t n stk) | otherwise -> return (unload stk var) eval stk env rec defs t = return (unload stk t) evalAlt stk env rec defs (LConCase i n es rhs) = do ns' <- mapM (\n -> do n' <- nextN return (n, n')) es LConCase i n (map snd ns') <$> eval stk (map (\ (n, n') -> (n, LV n')) ns' ++ env) rec defs rhs evalAlt stk env rec defs (LConstCase c e) = LConstCase c <$> eval stk env rec defs e evalAlt stk env rec defs (LDefaultCase e) = LDefaultCase <$> eval stk env rec defs e apply :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp -> [Name] -> LExp -> State Int LExp apply stk env rec defs var args body = eval stk env rec defs (LLam args body) dropArgs :: [Name] -> LAlt -> State Int LAlt dropArgs as (LConCase i n es t) = do rhs' <- dropArgsTm as t return (LConCase i n es rhs') dropArgs as (LConstCase c t) = do rhs' <- dropArgsTm as t return (LConstCase c rhs') dropArgs as (LDefaultCase t) = do rhs' <- dropArgsTm as t return (LDefaultCase rhs') dropArgsTm as (LLam args rhs) = do let old = take (length as) args eval [] (zipWith (\ o n -> (o, LV n)) old as) [] emptyContext rhs dropArgsTm as (LLet n val rhs) = do rhs' <- dropArgsTm as rhs pure (LLet n val rhs') dropArgsTm as tm = return tm caseFloat :: LExp -> LExp caseFloat (LApp tc e es) = LApp tc (caseFloat e) (map caseFloat es) caseFloat (LLazyExp e) = LLazyExp (caseFloat e) caseFloat (LForce e) = LForce (caseFloat e) caseFloat (LCon up i n es) = LCon up i n (map caseFloat es) caseFloat (LOp f es) = LOp f (map caseFloat es) caseFloat (LLam ns sc) = LLam ns (caseFloat sc) caseFloat (LLet v val sc) = LLet v (caseFloat val) (caseFloat sc) caseFloat (LCase _ (LCase ct exp alts) alts') | all conRHS alts || length alts == 1 = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map (updateWith alts') alts)) where conRHS (LConCase _ _ _ (LCon _ _ _ _)) = True conRHS (LConstCase _ (LCon _ _ _ _)) = True conRHS (LDefaultCase (LCon _ _ _ _)) = True conRHS _ = False updateWith alts (LConCase i n es rhs) = LConCase i n es (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) updateWith alts (LConstCase c rhs) = LConstCase c (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) updateWith alts (LDefaultCase rhs) = LDefaultCase (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) caseFloat (LCase ct exp alts') = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map cfAlt alts')) where cfAlt (LConCase i n es rhs) = LConCase i n es (caseFloat rhs) cfAlt (LConstCase c rhs) = LConstCase c (caseFloat rhs) cfAlt (LDefaultCase rhs) = LDefaultCase (caseFloat rhs) caseFloat exp = exp -- Case of constructor conOpt :: LExp -> LExp conOpt (LCase ct (LCon _ t n args) alts) = pickAlt n args alts where pickAlt n args (LConCase i n' es rhs : as) | n == n' = substAll (zip es args) rhs pickAlt _ _ (LDefaultCase rhs : as) = rhs pickAlt n args (_ : as) = pickAlt n args as pickAlt n args [] = error "Can't happen pickAlt - impossible case found" substAll [] rhs = rhs substAll ((n, tm) : ss) rhs = lsubst n tm (substAll ss rhs) conOpt tm = tm replaceInCase :: LExp -> LExp replaceInCase (LCase ty e alts) = LCase ty e (replaceInAlts e alts) replaceInCase exp = exp replaceInAlts :: LExp -> [LAlt] -> [LAlt] replaceInAlts exp alts = dropDups $ concatMap (replaceInAlt exp) alts -- Drop overlapping case (arising from case merging of overlapping -- patterns) dropDups (alt@(LConCase _ i n ns) : alts) = alt : dropDups (filter (notTag i) alts) where notTag i (LConCase _ j n ns) = i /= j notTag _ _ = True dropDups (c : alts) = c : dropDups alts dropDups [] = [] replaceInAlt :: LExp -> LAlt -> [LAlt] -- In an alternative, if the case appears on the right hand side, replace -- it with the given expression, to preserve sharing replaceInAlt exp@(LV _) (LConCase i con args rhs) = [LConCase i con args $ replaceExp (LCon Nothing i con (map LV args)) exp rhs] -- if a default case inspects the same variable as the case it's in, -- remove the inspection and replace with the alternatives -- (i.e. merge the inner case block) replaceInAlt exp@(LV var) (LDefaultCase (LCase ty (LV var') alts)) | var == var' = alts replaceInAlt exp a = [a] replaceExp :: LExp -> LExp -> LExp -> LExp replaceExp (LCon _ t n args) new (LCon _ t' n' args') | n == n' && args == args' = new replaceExp (LCon _ t n args) new (LApp _ (LV n') args') | n == n' && args == args' = new replaceExp old new tm = tm -- dropArgs as (LConstCase c rhs) = LConstCase c (dropRHS as rhs) dropArgs as ( LDefaultCase rhs ) = LDefaultCase ( dropRHS as rhs ) getRHS (LConCase i n es rhs) = rhs getRHS (LConstCase _ rhs) = rhs getRHS (LDefaultCase rhs) = rhs getLams [] = [] getLams (LLam args tm : cs) = getLamPrefix args cs getLams (LLet n val exp : cs) = getLams (exp : cs) getLams _ = [] getLamPrefix as [] = as getLamPrefix as (LLam args tm : cs) | length args < length as = getLamPrefix args cs | otherwise = getLamPrefix as cs getLamPrefix as (LLet n val exp : cs) = getLamPrefix as (exp : cs) getLamPrefix as (_ : cs) = [] eta contract ( ' \x - > f x ' can just be compiled as ' f ' when f is local ) eta :: LExp -> LExp eta (LApp tc a es) = LApp tc (eta a) (map eta es) eta (LLazyApp n es) = LLazyApp n (map eta es) eta (LLazyExp e) = LLazyExp (eta e) eta (LForce e) = LForce (eta e) eta (LLet n val sc) = LLet n (eta val) (eta sc) eta (LLam args (LApp tc f args')) | args' == map LV args = eta f eta (LLam args e) = LLam args (eta e) eta (LProj e i) = LProj (eta e) i eta (LCon a t n es) = LCon a t n (map eta es) eta (LCase ct e alts) = LCase ct (eta e) (map (fmap eta) alts) eta (LOp f es) = LOp f (map eta es) eta tm = tm
null
https://raw.githubusercontent.com/idris-lang/Idris-dev/a13caeb4e50d0c096d34506f2ebf6b9d140a07aa/src/IRTS/LangOpts.hs
haskell
# LANGUAGE DeriveFunctor, PatternGuards # | Inline inside a declaration. Variables are still Name at this stage. Need to preserve uniqueness of variable names in the resulting definition, so invent a new name for every variable we encounter do some case floating, which might arise as a result then, eta contract action, and is worth inlining to avoid the thunk If they're all lambdas, bind the lambda at the top save the interesting cases for the end: lambdas, and names to reduce Case of constructor Drop overlapping case (arising from case merging of overlapping patterns) In an alternative, if the case appears on the right hand side, replace it with the given expression, to preserve sharing if a default case inspects the same variable as the case it's in, remove the inspection and replace with the alternatives (i.e. merge the inner case block) dropArgs as (LConstCase c rhs) = LConstCase c (dropRHS as rhs)
| Module : IRTS.LangOpts Description : Transformations to apply to ' IR . License : : The Idris Community . Module : IRTS.LangOpts Description : Transformations to apply to Idris' IR. License : BSD3 Maintainer : The Idris Community. -} module IRTS.LangOpts(inlineAll) where import Idris.Core.CaseTree import Idris.Core.TT import IRTS.Lang import Control.Monad.State hiding (lift) inlineAll :: [(Name, LDecl)] -> [(Name, LDecl)] inlineAll lds = let defs = addAlist lds emptyContext in map (\ (n, def) -> (n, doInline defs def)) lds nextN :: State Int Name nextN = do i <- get put (i + 1) return $ sMN i "in" doInline :: LDefs -> LDecl -> LDecl doInline = doInline' 1 doInline' :: Int -> LDefs -> LDecl -> LDecl doInline' 0 defs d = d doInline' i defs d@(LConstructor _ _ _) = d doInline' i defs (LFun opts topn args exp) = let inl = evalState (eval [] initEnv [topn] defs exp) (length args) res = eta $ caseFloats 10 inl in case res of LLam args' body -> doInline' (i - 1) defs $ LFun opts topn (map snd initNames ++ args') body _ -> doInline' (i - 1) defs $ LFun opts topn (map snd initNames) res where caseFloats 0 tm = tm caseFloats n tm = let res = caseFloat tm in if res == tm then res else caseFloats (n-1) res initNames = zipWith (\n i -> (n, newn n i)) args [0..] initEnv = map (\(n, n') -> (n, LV n')) initNames newn (UN n) i = MN i n newn _ i = sMN i "arg" unload :: [LExp] -> LExp -> LExp unload [] e = e unload stk (LApp tc e args) = LApp tc e (args ++ stk) unload stk e = LApp False e stk takeStk :: [(Name, LExp)] -> [Name] -> [LExp] -> ([(Name, LExp)], [Name], [LExp]) takeStk env (a : args) (v : stk) = takeStk ((a, v) : env) args stk takeStk env args stk = (env, args, stk) eval :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp -> State Int LExp eval stk env rec defs (LLazyApp n es) = unload stk <$> LLazyApp n <$> (mapM (eval [] env rec defs) es) eval stk env rec defs (LForce e) = do e' <- eval [] env rec defs e case e' of LLazyExp forced -> eval stk env rec defs forced LLazyApp n es -> eval stk env rec defs (LApp False (LV n) es) _ -> return (unload stk (LForce e')) eval stk env rec defs (LLazyExp e) = unload stk <$> LLazyExp <$> eval [] env rec defs e Special case for io_bind , because it needs to keep executing the first eval [] env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)]) | n == sUN "io_bind" = do w <- nextN let env' = (w, LV w) : env act' <- eval [] env' rec defs (LApp False act [LV w]) argn <- nextN k' <- eval [] ((arg, LV argn) : env') rec defs (LApp False k [LV w]) return $ LLam [w] (LLet argn act' k') eval (world : stk) env rec defs (LApp t (LV n) [_, _, _, act, (LLam [arg] k)]) | n == sUN "io_bind" = do act' <- eval [] env rec defs (LApp False act [world]) argn <- nextN k' <- eval stk ((arg, LV argn) : env) rec defs (LApp False k [world]) Needs to be a LLet to make sure the action gets evaluated return $ LLet argn act' k' eval stk env rec defs (LApp t f es) = do es' <- mapM (eval [] env rec defs) es eval (es' ++ stk) env rec defs f eval stk env rec defs (LLet n val sc) = do n' <- nextN LLet n' <$> eval [] env rec defs val <*> eval stk ((n, LV n') : env) rec defs sc eval stk env rec defs (LProj exp i) = unload stk <$> (LProj <$> eval [] env rec defs exp <*> return i) eval stk env rec defs (LCon loc i n es) = unload stk <$> (LCon loc i n <$> mapM (eval [] env rec defs) es) eval stk env rec defs (LCase ty e []) = pure LNothing eval stk env rec defs (LCase ty e alts) = do e' <- eval [] env rec defs e case evalAlts e' alts of Just (env', tm) -> eval stk env' rec defs tm Nothing -> do alts' <- mapM (evalAlt stk env rec defs) alts let prefix = getLams (map getRHS alts') case prefix of [] -> return $ LCase ty e' (replaceInAlts e' alts') args -> do alts_red <- mapM (dropArgs args) alts' return $ LLam args (LCase ty e' (replaceInAlts e' alts_red)) where evalAlts e' [] = Nothing evalAlts (LCon _ t n args) (LConCase i n' es rhs : as) | n == n' = Just (zip es args ++ env, rhs) evalAlts (LConst c) (LConstCase c' rhs : as) | c == c' = Just (env, rhs) evalAlts (LCon _ _ _ _) (LDefaultCase rhs : as) = Just (env, rhs) evalAlts (LConst _) (LDefaultCase rhs : as) = Just (env, rhs) evalAlts tm (_ : as) = evalAlts tm as eval stk env rec defs (LOp f es) = unload stk <$> LOp f <$> mapM (eval [] env rec defs) es eval stk env rec defs (LForeign t s args) = unload stk <$> LForeign t s <$> mapM (\(t, e) -> do e' <- eval [] env rec defs e return (t, e')) args eval stk env rec defs (LLam args sc) | (env', args', stk') <- takeStk env args stk = case args' of [] -> eval stk' env' rec defs sc as -> do ns' <- mapM (\n -> do n' <- nextN return (n, n')) args' LLam (map snd ns') <$> eval stk' (map (\ (n, n') -> (n, LV n')) ns' ++ env') rec defs sc eval stk env rec defs var@(LV n) = case lookup n env of Just t | t /= LV n && n `notElem` rec -> eval stk env (n : rec) defs t | otherwise -> return (unload stk t) Nothing | n `notElem` rec, Just (LFun opts _ args body) <- lookupCtxtExact n defs, Inline `elem` opts -> apply stk env (n : rec) defs var args body | Just (LConstructor n t a) <- lookupCtxtExact n defs -> return (LCon Nothing t n stk) | otherwise -> return (unload stk var) eval stk env rec defs t = return (unload stk t) evalAlt stk env rec defs (LConCase i n es rhs) = do ns' <- mapM (\n -> do n' <- nextN return (n, n')) es LConCase i n (map snd ns') <$> eval stk (map (\ (n, n') -> (n, LV n')) ns' ++ env) rec defs rhs evalAlt stk env rec defs (LConstCase c e) = LConstCase c <$> eval stk env rec defs e evalAlt stk env rec defs (LDefaultCase e) = LDefaultCase <$> eval stk env rec defs e apply :: [LExp] -> [(Name, LExp)] -> [Name] -> LDefs -> LExp -> [Name] -> LExp -> State Int LExp apply stk env rec defs var args body = eval stk env rec defs (LLam args body) dropArgs :: [Name] -> LAlt -> State Int LAlt dropArgs as (LConCase i n es t) = do rhs' <- dropArgsTm as t return (LConCase i n es rhs') dropArgs as (LConstCase c t) = do rhs' <- dropArgsTm as t return (LConstCase c rhs') dropArgs as (LDefaultCase t) = do rhs' <- dropArgsTm as t return (LDefaultCase rhs') dropArgsTm as (LLam args rhs) = do let old = take (length as) args eval [] (zipWith (\ o n -> (o, LV n)) old as) [] emptyContext rhs dropArgsTm as (LLet n val rhs) = do rhs' <- dropArgsTm as rhs pure (LLet n val rhs') dropArgsTm as tm = return tm caseFloat :: LExp -> LExp caseFloat (LApp tc e es) = LApp tc (caseFloat e) (map caseFloat es) caseFloat (LLazyExp e) = LLazyExp (caseFloat e) caseFloat (LForce e) = LForce (caseFloat e) caseFloat (LCon up i n es) = LCon up i n (map caseFloat es) caseFloat (LOp f es) = LOp f (map caseFloat es) caseFloat (LLam ns sc) = LLam ns (caseFloat sc) caseFloat (LLet v val sc) = LLet v (caseFloat val) (caseFloat sc) caseFloat (LCase _ (LCase ct exp alts) alts') | all conRHS alts || length alts == 1 = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map (updateWith alts') alts)) where conRHS (LConCase _ _ _ (LCon _ _ _ _)) = True conRHS (LConstCase _ (LCon _ _ _ _)) = True conRHS (LDefaultCase (LCon _ _ _ _)) = True conRHS _ = False updateWith alts (LConCase i n es rhs) = LConCase i n es (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) updateWith alts (LConstCase c rhs) = LConstCase c (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) updateWith alts (LDefaultCase rhs) = LDefaultCase (caseFloat (conOpt (LCase Shared (caseFloat rhs) alts))) caseFloat (LCase ct exp alts') = conOpt $ replaceInCase (LCase ct (caseFloat exp) (map cfAlt alts')) where cfAlt (LConCase i n es rhs) = LConCase i n es (caseFloat rhs) cfAlt (LConstCase c rhs) = LConstCase c (caseFloat rhs) cfAlt (LDefaultCase rhs) = LDefaultCase (caseFloat rhs) caseFloat exp = exp conOpt :: LExp -> LExp conOpt (LCase ct (LCon _ t n args) alts) = pickAlt n args alts where pickAlt n args (LConCase i n' es rhs : as) | n == n' = substAll (zip es args) rhs pickAlt _ _ (LDefaultCase rhs : as) = rhs pickAlt n args (_ : as) = pickAlt n args as pickAlt n args [] = error "Can't happen pickAlt - impossible case found" substAll [] rhs = rhs substAll ((n, tm) : ss) rhs = lsubst n tm (substAll ss rhs) conOpt tm = tm replaceInCase :: LExp -> LExp replaceInCase (LCase ty e alts) = LCase ty e (replaceInAlts e alts) replaceInCase exp = exp replaceInAlts :: LExp -> [LAlt] -> [LAlt] replaceInAlts exp alts = dropDups $ concatMap (replaceInAlt exp) alts dropDups (alt@(LConCase _ i n ns) : alts) = alt : dropDups (filter (notTag i) alts) where notTag i (LConCase _ j n ns) = i /= j notTag _ _ = True dropDups (c : alts) = c : dropDups alts dropDups [] = [] replaceInAlt :: LExp -> LAlt -> [LAlt] replaceInAlt exp@(LV _) (LConCase i con args rhs) = [LConCase i con args $ replaceExp (LCon Nothing i con (map LV args)) exp rhs] replaceInAlt exp@(LV var) (LDefaultCase (LCase ty (LV var') alts)) | var == var' = alts replaceInAlt exp a = [a] replaceExp :: LExp -> LExp -> LExp -> LExp replaceExp (LCon _ t n args) new (LCon _ t' n' args') | n == n' && args == args' = new replaceExp (LCon _ t n args) new (LApp _ (LV n') args') | n == n' && args == args' = new replaceExp old new tm = tm dropArgs as ( LDefaultCase rhs ) = LDefaultCase ( dropRHS as rhs ) getRHS (LConCase i n es rhs) = rhs getRHS (LConstCase _ rhs) = rhs getRHS (LDefaultCase rhs) = rhs getLams [] = [] getLams (LLam args tm : cs) = getLamPrefix args cs getLams (LLet n val exp : cs) = getLams (exp : cs) getLams _ = [] getLamPrefix as [] = as getLamPrefix as (LLam args tm : cs) | length args < length as = getLamPrefix args cs | otherwise = getLamPrefix as cs getLamPrefix as (LLet n val exp : cs) = getLamPrefix as (exp : cs) getLamPrefix as (_ : cs) = [] eta contract ( ' \x - > f x ' can just be compiled as ' f ' when f is local ) eta :: LExp -> LExp eta (LApp tc a es) = LApp tc (eta a) (map eta es) eta (LLazyApp n es) = LLazyApp n (map eta es) eta (LLazyExp e) = LLazyExp (eta e) eta (LForce e) = LForce (eta e) eta (LLet n val sc) = LLet n (eta val) (eta sc) eta (LLam args (LApp tc f args')) | args' == map LV args = eta f eta (LLam args e) = LLam args (eta e) eta (LProj e i) = LProj (eta e) i eta (LCon a t n es) = LCon a t n (map eta es) eta (LCase ct e alts) = LCase ct (eta e) (map (fmap eta) alts) eta (LOp f es) = LOp f (map eta es) eta tm = tm
39b01c7115322045d7b15aee1b55318880f19ffec57c1e971655a1f118e6e256
picty/parsifal
test_tls_client.ml
open Lwt open Parsifal open PTypes open TlsEnums open Tls open TlsEngineNG let test_client host port prefs = let ctx = { (empty_context prefs) with direction = Some ClientToServer } in resolve host port >>= (fun resolved_host -> init_client_connection resolved_host) >>= fun c_sock -> let ch () = mk_client_hello ctx in output_record ctx c_sock ch; run_automata client_automata ClientHelloSent "" ctx c_sock >>= fun _ -> let print_certs = function | Parsed (_, cert) -> print_endline (String.concat ", " (List.map X509Basics.string_of_atv (List.flatten cert.X509.tbsCertificate.X509.subject))) | _ -> () in List.iter print_certs ctx.future.f_certificates; Lwt_unix.close c_sock.socket let _ = if Array.length Sys.argv <> 3 then begin prerr_endline "Usage: test_tls_client [host] [port]"; exit 1 end; try TlsDatabase.enrich_suite_hash (); let host = Sys.argv.(1) and port = int_of_string Sys.argv.(2) in let prefs = { (default_prefs DummyRNG) with acceptable_ciphersuites = [TLS_RSA_WITH_RC4_128_MD5; TLS_RSA_WITH_AES_128_CBC_SHA] } in Unix.handle_unix_error Lwt_main.run (test_client host port prefs) with | ParsingException (e, h) -> prerr_endline (string_of_exception e h); exit 1 | e -> prerr_endline (Printexc.to_string e)
null
https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/ssl/test/test_tls_client.ml
ocaml
open Lwt open Parsifal open PTypes open TlsEnums open Tls open TlsEngineNG let test_client host port prefs = let ctx = { (empty_context prefs) with direction = Some ClientToServer } in resolve host port >>= (fun resolved_host -> init_client_connection resolved_host) >>= fun c_sock -> let ch () = mk_client_hello ctx in output_record ctx c_sock ch; run_automata client_automata ClientHelloSent "" ctx c_sock >>= fun _ -> let print_certs = function | Parsed (_, cert) -> print_endline (String.concat ", " (List.map X509Basics.string_of_atv (List.flatten cert.X509.tbsCertificate.X509.subject))) | _ -> () in List.iter print_certs ctx.future.f_certificates; Lwt_unix.close c_sock.socket let _ = if Array.length Sys.argv <> 3 then begin prerr_endline "Usage: test_tls_client [host] [port]"; exit 1 end; try TlsDatabase.enrich_suite_hash (); let host = Sys.argv.(1) and port = int_of_string Sys.argv.(2) in let prefs = { (default_prefs DummyRNG) with acceptable_ciphersuites = [TLS_RSA_WITH_RC4_128_MD5; TLS_RSA_WITH_AES_128_CBC_SHA] } in Unix.handle_unix_error Lwt_main.run (test_client host port prefs) with | ParsingException (e, h) -> prerr_endline (string_of_exception e h); exit 1 | e -> prerr_endline (Printexc.to_string e)
7f055d6a99a9c3af5f424274d5302bd843258f501b81a0b7f0747b2050e34801
AccelerationNet/cl-csv
read-until.lisp
(in-package :cl-csv) (defun read-into-buffer-until (buffer stream &key (nl #\newline) nl-match &aux (c #\null) (nl-idx (or nl-match -1)) (nl-len (etypecase nl (string (length nl)) (character 1))) (nl-len-1 (- nl-len 1)) (buffer-len (length buffer))) "This reads into a buffer until either the buffer is full or the we have read the newline character(s). If we read the newline characters they will be the last character(s) in the buffer " (declare (optimize (speed 3) (safety 0) (debug 0)) (type character c) (type (or simple-string character) nl) (type fixnum nl-len nl-len-1 nl-idx buffer-len) (type (simple-array character) buffer)) (dotimes (i buffer-len) (setf c (read-char stream nil *eof-char*)) ;; look for newlines (let ((new-idx (+ 1 nl-idx))) (declare (type fixnum new-idx)) (if (char= (etypecase nl (string (schar nl new-idx)) (character nl)) c) (setf nl-idx new-idx) (setf nl-idx -1))) (when (char= *eof-char* c) (if (zerop i) (error 'end-of-file :stream stream) ;; read some, then got an end of file (return-from read-into-buffer-until i))) (setf (schar buffer i) c) got the nl (when (= nl-len-1 nl-idx) (return-from read-into-buffer-until (+ 1 i)))) ;; got a full buffer (return-from read-into-buffer-until buffer-len))
null
https://raw.githubusercontent.com/AccelerationNet/cl-csv/68ecb5d816545677513d7f6308d9e5e8d2265651/read-until.lisp
lisp
look for newlines read some, then got an end of file got a full buffer
(in-package :cl-csv) (defun read-into-buffer-until (buffer stream &key (nl #\newline) nl-match &aux (c #\null) (nl-idx (or nl-match -1)) (nl-len (etypecase nl (string (length nl)) (character 1))) (nl-len-1 (- nl-len 1)) (buffer-len (length buffer))) "This reads into a buffer until either the buffer is full or the we have read the newline character(s). If we read the newline characters they will be the last character(s) in the buffer " (declare (optimize (speed 3) (safety 0) (debug 0)) (type character c) (type (or simple-string character) nl) (type fixnum nl-len nl-len-1 nl-idx buffer-len) (type (simple-array character) buffer)) (dotimes (i buffer-len) (setf c (read-char stream nil *eof-char*)) (let ((new-idx (+ 1 nl-idx))) (declare (type fixnum new-idx)) (if (char= (etypecase nl (string (schar nl new-idx)) (character nl)) c) (setf nl-idx new-idx) (setf nl-idx -1))) (when (char= *eof-char* c) (if (zerop i) (error 'end-of-file :stream stream) (return-from read-into-buffer-until i))) (setf (schar buffer i) c) got the nl (when (= nl-len-1 nl-idx) (return-from read-into-buffer-until (+ 1 i)))) (return-from read-into-buffer-until buffer-len))
3890d1245b744c7fd1a0554539a66408b6577cfd56959d6dac51080c5da898c6
ChrisPenner/Candor
Main.hs
{-# language OverloadedStrings #-} # language GeneralizedNewtypeDeriving # module Main where import RIO import System.IO import Parse import Eval import AST import CLI import REPL import Options.Applicative (execParser) import qualified Data.Text as Text newtype ParseError = ParseError String instance Show ParseError where show (ParseError err) = "Parse Error: " ++ err newtype EvalError = EvalError String instance Show EvalError where show (EvalError err) = "Eval Error: " ++ err newtype ArgError = ArgError String instance Show ArgError where show (ArgError err) = err instance Exception ParseError instance Exception EvalError instance Exception ArgError main :: IO () main = do Options runRepl srcFile <- execParser opts if runRepl then repl else compiler srcFile compiler :: FilePath -> IO () compiler srcFile = flip catchAny print $ do fileContents <- readFileUtf8 srcFile ast <- either (throwIO . ParseError) return (parse $ Text.unpack fileContents) result <- either (throwIO . EvalError) return (eval ast) putStrLn . pretty $ result
null
https://raw.githubusercontent.com/ChrisPenner/Candor/a2e5052c2f264d51b539c8979d1758c08a9bc2e1/app/Main.hs
haskell
# language OverloadedStrings #
# language GeneralizedNewtypeDeriving # module Main where import RIO import System.IO import Parse import Eval import AST import CLI import REPL import Options.Applicative (execParser) import qualified Data.Text as Text newtype ParseError = ParseError String instance Show ParseError where show (ParseError err) = "Parse Error: " ++ err newtype EvalError = EvalError String instance Show EvalError where show (EvalError err) = "Eval Error: " ++ err newtype ArgError = ArgError String instance Show ArgError where show (ArgError err) = err instance Exception ParseError instance Exception EvalError instance Exception ArgError main :: IO () main = do Options runRepl srcFile <- execParser opts if runRepl then repl else compiler srcFile compiler :: FilePath -> IO () compiler srcFile = flip catchAny print $ do fileContents <- readFileUtf8 srcFile ast <- either (throwIO . ParseError) return (parse $ Text.unpack fileContents) result <- either (throwIO . EvalError) return (eval ast) putStrLn . pretty $ result
b88664f08af6ca54a5ed2dbd6f2f3120debc3f219fdaee5ddf484fde8afe35b7
alanforr/complex
project.clj
(defproject complex "0.1.12" :description "A Clojure library for doing fast complex number calculations that wraps the Java commons-math3 Complex library." :url "" :uberjar {:aot :all} :profiles {:dev {:dependencies [[criterium "0.4.3"]]}} :deploy-repositories [["releases" {:sign-releases false :url ""}] ["snapshots" {:sign-releases false :url ""}]] :scm {:name "git" :url ""} :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.apache.commons/commons-math3 "3.5"]] :main complex.core)
null
https://raw.githubusercontent.com/alanforr/complex/3cdd2d5c9c95454cc549b217acc368cc76f2416b/project.clj
clojure
(defproject complex "0.1.12" :description "A Clojure library for doing fast complex number calculations that wraps the Java commons-math3 Complex library." :url "" :uberjar {:aot :all} :profiles {:dev {:dependencies [[criterium "0.4.3"]]}} :deploy-repositories [["releases" {:sign-releases false :url ""}] ["snapshots" {:sign-releases false :url ""}]] :scm {:name "git" :url ""} :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.apache.commons/commons-math3 "3.5"]] :main complex.core)
4a3340a836883e642a4020df8372bab83cac3f4e4fcf8495e1fb59ef4b7137cf
haskell-servant/servant
BaseUrl.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveLift #-} {-# LANGUAGE ViewPatterns #-} module Servant.Client.Core.BaseUrl ( BaseUrl (..), Scheme (..), showBaseUrl, parseBaseUrl, InvalidBaseUrlException (..), ) where import Control.DeepSeq (NFData (..)) import Control.Monad.Catch (Exception, MonadThrow, throwM) import Data.Aeson (FromJSON (..), FromJSONKey (..), ToJSON (..), ToJSONKey (..)) import Data.Aeson.Types (FromJSONKeyFunction (..), contramapToJSONKeyFunction, withText) import Data.Data (Data) import Data.List import qualified Data.Text as T import GHC.Generics import Language.Haskell.TH.Syntax (Lift) import Network.URI hiding (path) import Safe import Text.Read -- | URI scheme to use data Scheme = Http -- ^ http:// | Https -- ^ https:// deriving (Show, Eq, Ord, Generic, Lift, Data) -- | Simple data type to represent the target of HTTP requests -- for servant's automatically-generated clients. data BaseUrl = BaseUrl { baseUrlScheme :: Scheme -- ^ URI scheme to use , baseUrlHost :: String -- ^ host (eg "haskell.org") ^ port ( eg 80 ) ^ path ( eg " /a / b / c " ) } deriving (Show, Ord, Generic, Lift, Data) TODO : is more precise than Eq -- TODO: Add Hashable instance? -- instance NFData BaseUrl where rnf (BaseUrl a b c d) = a `seq` rnf b `seq` rnf c `seq` rnf d instance Eq BaseUrl where BaseUrl a b c path == BaseUrl a' b' c' path' = a == a' && b == b' && c == c' && s path == s path' where s ('/':x) = x s x = x -- | >>> traverse_ (LBS8.putStrLn . encode) $ parseBaseUrl "api.example.com" -- "" instance ToJSON BaseUrl where toJSON = toJSON . showBaseUrl toEncoding = toEncoding . showBaseUrl | > > > parseBaseUrl " api.example.com " > > = decode . encode : : Maybe Just ( BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } ) instance FromJSON BaseUrl where parseJSON = withText "BaseUrl" $ \t -> case parseBaseUrl (T.unpack t) of Just u -> return u Nothing -> fail $ "Invalid base url: " ++ T.unpack t -- | >>> :{ -- traverse_ (LBS8.putStrLn . encode) $ do -- u1 <- parseBaseUrl "api.example.com" -- u2 <- parseBaseUrl "example.com" return $ Map.fromList [ ( u1 , ' x ' ) , ( u2 , ' y ' ) ] -- :} -- {"":"x","":"y"} instance ToJSONKey BaseUrl where toJSONKey = contramapToJSONKeyFunction showBaseUrl toJSONKey instance FromJSONKey BaseUrl where fromJSONKey = FromJSONKeyTextParser $ \t -> case parseBaseUrl (T.unpack t) of Just u -> return u Nothing -> fail $ "Invalid base url: " ++ T.unpack t -- | >>> showBaseUrl <$> parseBaseUrl "api.example.com" -- "" showBaseUrl :: BaseUrl -> String showBaseUrl (BaseUrl urlscheme host port path) = schemeString ++ "//" ++ host ++ (portString </> path) where a </> b = if "/" `isPrefixOf` b || null b then a ++ b else a ++ '/':b schemeString = case urlscheme of Http -> "http:" Https -> "https:" portString = case (urlscheme, port) of (Http, 80) -> "" (Https, 443) -> "" _ -> ":" ++ show port newtype InvalidBaseUrlException = InvalidBaseUrlException String deriving (Show) instance Exception InvalidBaseUrlException -- | -- -- >>> parseBaseUrl "api.example.com" BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } -- -- /Note:/ trailing slash is removed -- -- >>> parseBaseUrl "api.example.com/" BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } -- -- >>> parseBaseUrl "api.example.com/dir/" BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " /dir " } -- parseBaseUrl :: MonadThrow m => String -> m BaseUrl parseBaseUrl s = case parseURI (removeTrailingSlash s) of -- This is a rather hacky implementation and should be replaced with something implemented in attoparsec ( which is already a dependency anyhow ( via aeson ) ) . Just (URI "http:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) path "" "") -> return (BaseUrl Http host port path) Just (URI "http:" (Just (URIAuth "" host "")) path "" "") -> return (BaseUrl Http host 80 path) Just (URI "https:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) path "" "") -> return (BaseUrl Https host port path) Just (URI "https:" (Just (URIAuth "" host "")) path "" "") -> return (BaseUrl Https host 443 path) _ -> if "://" `isInfixOf` s then throwM (InvalidBaseUrlException $ "Invalid base URL: " ++ s) else parseBaseUrl ("http://" ++ s) where removeTrailingSlash str = case lastMay str of Just '/' -> init str _ -> str -- $setup -- -- >>> import Data.Aeson -- >>> import Data.Foldable (traverse_) > > > import qualified Data . ByteString . Lazy . Char8 as LBS8 -- >>> import qualified Data.Map.Strict as Map
null
https://raw.githubusercontent.com/haskell-servant/servant/d06b65c4e6116f992debbac2eeeb83eafb960321/servant-client-core/src/Servant/Client/Core/BaseUrl.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveLift # # LANGUAGE ViewPatterns # | URI scheme to use ^ http:// ^ https:// | Simple data type to represent the target of HTTP requests for servant's automatically-generated clients. ^ URI scheme to use ^ host (eg "haskell.org") TODO: Add Hashable instance? | >>> traverse_ (LBS8.putStrLn . encode) $ parseBaseUrl "api.example.com" "" | >>> :{ traverse_ (LBS8.putStrLn . encode) $ do u1 <- parseBaseUrl "api.example.com" u2 <- parseBaseUrl "example.com" :} {"":"x","":"y"} | >>> showBaseUrl <$> parseBaseUrl "api.example.com" "" | >>> parseBaseUrl "api.example.com" /Note:/ trailing slash is removed >>> parseBaseUrl "api.example.com/" >>> parseBaseUrl "api.example.com/dir/" This is a rather hacky implementation and should be replaced with something $setup >>> import Data.Aeson >>> import Data.Foldable (traverse_) >>> import qualified Data.Map.Strict as Map
# LANGUAGE DeriveGeneric # module Servant.Client.Core.BaseUrl ( BaseUrl (..), Scheme (..), showBaseUrl, parseBaseUrl, InvalidBaseUrlException (..), ) where import Control.DeepSeq (NFData (..)) import Control.Monad.Catch (Exception, MonadThrow, throwM) import Data.Aeson (FromJSON (..), FromJSONKey (..), ToJSON (..), ToJSONKey (..)) import Data.Aeson.Types (FromJSONKeyFunction (..), contramapToJSONKeyFunction, withText) import Data.Data (Data) import Data.List import qualified Data.Text as T import GHC.Generics import Language.Haskell.TH.Syntax (Lift) import Network.URI hiding (path) import Safe import Text.Read data Scheme = deriving (Show, Eq, Ord, Generic, Lift, Data) data BaseUrl = BaseUrl ^ port ( eg 80 ) ^ path ( eg " /a / b / c " ) } deriving (Show, Ord, Generic, Lift, Data) TODO : is more precise than Eq instance NFData BaseUrl where rnf (BaseUrl a b c d) = a `seq` rnf b `seq` rnf c `seq` rnf d instance Eq BaseUrl where BaseUrl a b c path == BaseUrl a' b' c' path' = a == a' && b == b' && c == c' && s path == s path' where s ('/':x) = x s x = x instance ToJSON BaseUrl where toJSON = toJSON . showBaseUrl toEncoding = toEncoding . showBaseUrl | > > > parseBaseUrl " api.example.com " > > = decode . encode : : Maybe Just ( BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } ) instance FromJSON BaseUrl where parseJSON = withText "BaseUrl" $ \t -> case parseBaseUrl (T.unpack t) of Just u -> return u Nothing -> fail $ "Invalid base url: " ++ T.unpack t return $ Map.fromList [ ( u1 , ' x ' ) , ( u2 , ' y ' ) ] instance ToJSONKey BaseUrl where toJSONKey = contramapToJSONKeyFunction showBaseUrl toJSONKey instance FromJSONKey BaseUrl where fromJSONKey = FromJSONKeyTextParser $ \t -> case parseBaseUrl (T.unpack t) of Just u -> return u Nothing -> fail $ "Invalid base url: " ++ T.unpack t showBaseUrl :: BaseUrl -> String showBaseUrl (BaseUrl urlscheme host port path) = schemeString ++ "//" ++ host ++ (portString </> path) where a </> b = if "/" `isPrefixOf` b || null b then a ++ b else a ++ '/':b schemeString = case urlscheme of Http -> "http:" Https -> "https:" portString = case (urlscheme, port) of (Http, 80) -> "" (Https, 443) -> "" _ -> ":" ++ show port newtype InvalidBaseUrlException = InvalidBaseUrlException String deriving (Show) instance Exception InvalidBaseUrlException BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " " } BaseUrl { baseUrlScheme = Http , baseUrlHost = " api.example.com " , baseUrlPort = 80 , baseUrlPath = " /dir " } parseBaseUrl :: MonadThrow m => String -> m BaseUrl parseBaseUrl s = case parseURI (removeTrailingSlash s) of implemented in attoparsec ( which is already a dependency anyhow ( via aeson ) ) . Just (URI "http:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) path "" "") -> return (BaseUrl Http host port path) Just (URI "http:" (Just (URIAuth "" host "")) path "" "") -> return (BaseUrl Http host 80 path) Just (URI "https:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) path "" "") -> return (BaseUrl Https host port path) Just (URI "https:" (Just (URIAuth "" host "")) path "" "") -> return (BaseUrl Https host 443 path) _ -> if "://" `isInfixOf` s then throwM (InvalidBaseUrlException $ "Invalid base URL: " ++ s) else parseBaseUrl ("http://" ++ s) where removeTrailingSlash str = case lastMay str of Just '/' -> init str _ -> str > > > import qualified Data . ByteString . Lazy . Char8 as LBS8
fa74cc3ef9c26e118fa8c48da90cfcec0639a7a4078e105105488be38e7dfccc
Clozure/ccl
objc-runtime.lisp
-*-Mode : LISP ; Package : CCL -*- ;;; Copyright 2002 - 2009 Clozure Associates ;;; 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. (in-package "CCL") Utilities for interacting with the Apple / GNU Objective - C runtime ;;; systems. (eval-when (:compile-toplevel :load-toplevel :execute) #+darwin-target (pushnew :apple-objc *features*) #+(and darwin-target 64-bit-target) (pushnew :apple-objc-2.0 *features*) #+win32-target (pushnew :cocotron-objc *features*) #-(or darwin-target win32-target) (pushnew :gnu-objc *features*)) (eval-when (:compile-toplevel :load-toplevel :execute) (set-dispatch-macro-character #\# #\@ (nfunction |objc-#@-reader| (lambda (stream subchar numarg) (declare (ignore subchar numarg)) (let* ((string (read stream))) (unless *read-suppress* (check-type string string) `(@ ,string))))))) (eval-when (:compile-toplevel :execute) #+(or apple-objc cocotron-objc) (use-interface-dir :cocoa) #+gnu-objc (use-interface-dir :gnustep)) (eval-when (:compile-toplevel :load-toplevel :execute) (require "OBJC-PACKAGE") (require "NAME-TRANSLATION") (require "OBJC-CLOS")) (defconstant +cgfloat-zero+ #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 0.0d0 #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 0.0f0) (deftype cgfloat () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 'double-float #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 'single-float) (deftype cg-float () 'cgfloat) (deftype nsuinteger () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(unsigned-byte 64) #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(unsigned-byte 32)) (deftype nsinteger () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(signed-byte 64) #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(signed-byte 32)) (defloadvar *NSApp* nil ) Apple ObjC 2.0 provides ( # _ objc_getProtocol name ) . In other runtimes , there does n't seem to be any way to find a Protocol ;;; object given its name. We need to be able to ask at runtime ;;; whether a given object conforms to a protocol in order to ;;; know when a protocol method is ambiguous, at least when the ;;; message contains ambiguous methods and some methods are protocol ;;; methods (defvar *objc-protocols* (make-hash-table :test #'equal)) (defstruct objc-protocol name address) (defun clear-objc-protocols () (maphash #'(lambda (name proto) (declare (ignore name)) (setf (objc-protocol-address proto) nil)) *objc-protocols*)) (defun lookup-objc-protocol (name) (values (gethash name *objc-protocols*))) ;;; I'm not sure we still need to avoid #_objc_getProtocol. (defun %get-objc-protocol (name) (let ((p (lookup-objc-protocol name))) (if p (objc-protocol-address p) (error "No Objective-C protocol named ~s" name)))) (defun %add-objc-protocol (class protocol) (when (= (#_class_addProtocol class protocol) #$YES) protocol)) (defun ensure-objc-classptr-resolved (classptr) #-gnu-objc (declare (ignore classptr)) #+gnu-objc (unless (logtest #$_CLS_RESOLV (pref classptr :objc_class.info)) (external-call "__objc_resolve_class_links" :void))) (defstruct private-objc-class-info name declared-ancestor) (defun compute-objc-direct-slots-from-info (info class) (let* ((ns-package (find-package "NS"))) (mapcar #'(lambda (field) (let* ((name (compute-lisp-name (unescape-foreign-name (foreign-record-field-name field)) ns-package)) (type (foreign-record-field-type field)) (offset (progn (ensure-foreign-type-bits type) (foreign-record-field-offset field)))) (make-instance 'foreign-direct-slot-definition :initfunction #'false :initform nil :name name :foreign-type type :class class :bit-offset offset :allocation :instance))) (db-objc-class-info-ivars info)))) (defun %ptr< (x y) (< (the (unsigned-byte #+64-bit-target 64 #+32-bit-target 32) (%ptr-to-int x)) (the (unsigned-byte #+64-bit-target 64 #+32-bit-target 32) (%ptr-to-int Y)))) (let* ((objc-class-map (make-hash-table :test #'eql :size 1024)) (objc-metaclass-map (make-hash-table :test #'eql :size 1024)) ;;; These are NOT lisp classes; we mostly want to keep track ;;; of them so that we can pretend that instances of them ;;; are instances of some known (declared) superclass. (private-objc-classes (make-hash-table :test #'eql :size 2048)) (objc-class-lock (make-lock)) (next-objc-class-id 0) (next-objc-metaclass-id 0) (class-table-size 1024) (c (make-array class-table-size)) (m (make-array class-table-size)) (cw (make-array class-table-size :initial-element nil)) (mw (make-array class-table-size :initial-element nil)) (csv (make-array class-table-size)) (msv (make-array class-table-size)) (class-id->metaclass-id (make-array class-table-size :initial-element nil)) (class-foreign-names (make-array class-table-size)) (metaclass-foreign-names (make-array class-table-size)) (class-id->ordinal (make-array class-table-size :initial-element nil)) (metaclass-id->ordinal (make-array class-table-size :initial-element nil)) ) (flet ((grow-vectors () (let* ((old-size class-table-size) (new-size (* 2 old-size))) (declare (fixnum old-size new-size)) (macrolet ((extend (v) `(setq ,v (%extend-vector old-size ,v new-size)))) (extend c) (extend m) (extend cw) (extend mw) (fill cw nil :start old-size :end new-size) (fill mw nil :start old-size :end new-size) (extend csv) (extend msv) (extend class-id->metaclass-id) (fill class-id->metaclass-id nil :start old-size :end new-size) (extend class-foreign-names) (extend metaclass-foreign-names) (extend class-id->ordinal) (extend metaclass-id->ordinal) (fill class-id->ordinal nil :start old-size :end new-size) (fill metaclass-id->ordinal nil :start old-size :end new-size)) (setq class-table-size new-size)))) (flet ((assign-next-class-id () (let* ((id next-objc-class-id)) (if (= (incf next-objc-class-id) class-table-size) (grow-vectors)) id)) (assign-next-metaclass-id () (let* ((id next-objc-metaclass-id)) (if (= (incf next-objc-metaclass-id) class-table-size) (grow-vectors)) id))) (defun id->objc-class (i) (svref c i)) (defun (setf id->objc-class) (new i) (setf (svref c i) new)) (defun id->objc-metaclass (i) (svref m i)) (defun (setf id->objc-metaclass) (new i) (setf (svref m i) new)) (defun id->objc-class-wrapper (i) (svref cw i)) (defun (setf id->objc-class-wrapper) (new i) (setf (svref cw i) new)) (defun id->objc-metaclass-wrapper (i) (svref mw i)) (defun (setf id->objc-metaclass-wrapper) (new i) (setf (svref mw i) new)) (defun id->objc-class-slots-vector (i) (svref csv i)) (defun (setf id->objc-class-slots-vector) (new i) (setf (svref csv i) new)) (defun id->objc-metaclass-slots-vector (i) (svref msv i)) (defun (setf id->objc-metaclass-slots-vector) (new i) (setf (svref msv i) new)) (defun objc-class-id-foreign-name (i) (svref class-foreign-names i)) (defun (setf objc-class-id-foreign-name) (new i) (setf (svref class-foreign-names i) new)) (defun objc-metaclass-id-foreign-name (i) (svref metaclass-foreign-names i)) (defun (setf objc-metaclass-id-foreign-name) (new i) (setf (svref metaclass-foreign-names i) new)) (defun %clear-objc-class-maps () (with-lock-grabbed (objc-class-lock) (clrhash objc-class-map) (clrhash objc-metaclass-map) (clrhash private-objc-classes))) (flet ((install-objc-metaclass (meta) (or (gethash meta objc-metaclass-map) (let* ((id (assign-next-metaclass-id)) (meta (%inc-ptr meta 0))) (setf (gethash meta objc-metaclass-map) id) (setf (svref m id) meta (svref msv id) (make-objc-metaclass-slots-vector meta) (svref metaclass-id->ordinal id) (%next-class-ordinal)) id)))) (defun register-objc-class (class) "ensure that the class is mapped to a small integer and associate a slots-vector with it." (with-lock-grabbed (objc-class-lock) (ensure-objc-classptr-resolved class) (or (gethash class objc-class-map) (let* ((id (assign-next-class-id)) (class (%inc-ptr class 0)) (meta (#_object_getClass class))) (setf (gethash class objc-class-map) id) (setf (svref c id) class (svref csv id) (make-objc-class-slots-vector class) (svref class-id->metaclass-id id) (install-objc-metaclass meta) (svref class-id->ordinal id) (%next-class-ordinal)) id))))) (defun objc-class-id (class) (gethash class objc-class-map)) (defun objc-metaclass-id (meta) (gethash meta objc-metaclass-map)) (defun objc-class-id->objc-metaclass-id (class-id) (svref class-id->metaclass-id class-id)) (defun objc-class-id->objc-metaclass (class-id) (svref m (svref class-id->metaclass-id class-id))) (defun objc-class-id->ordinal (i) (svref class-id->ordinal i)) (defun (setf objc-class-id->ordinal) (new i) (setf (svref class-id->ordinal i) new)) (defun objc-metaclass-id->ordinal (m) (svref metaclass-id->ordinal m)) (defun (setf objc-metaclass-id->ordinal) (new m) (setf (svref class-id->ordinal m) new)) (defun objc-class-map () objc-class-map) (defun %objc-class-count () next-objc-class-id) (defun objc-metaclass-map () objc-metaclass-map) (defun %objc-metaclass-count () next-objc-metaclass-id) (defun %register-private-objc-class (c name) (setf (gethash c private-objc-classes) (make-private-objc-class-info :name name))) (defun %get-private-objc-class (c) (gethash c private-objc-classes)) (defun private-objc-classes () private-objc-classes)))) (pushnew #'%clear-objc-class-maps *save-exit-functions* :test #'eq :key #'function-name) (defun do-all-objc-classes (f) (maphash #'(lambda (ptr id) (declare (ignore ptr)) (funcall f (id->objc-class id))) (objc-class-map))) (defun canonicalize-registered-class (c) (let* ((id (objc-class-id c))) (if id (id->objc-class id) (error "Class ~S isn't recognized." c)))) (defun canonicalize-registered-metaclass (m) (let* ((id (objc-metaclass-id m))) (if id (id->objc-metaclass id) (error "Class ~S isn't recognized." m)))) (defun canonicalize-registered-class-or-metaclass (x) (if (%objc-metaclass-p x) (canonicalize-registered-metaclass x) (canonicalize-registered-class x))) Open shared libs . #+(or darwin-target cocotron-objc) (progn (defloadvar *cocoa-event-process* *initial-process*) (defun current-ns-thread () (with-cstrs ((class-name "NSThread") (message-selector-name "currentThread")) (let* ((nsthread-class (#_objc_lookUpClass class-name)) (message-selector (#_sel_getUid message-selector-name))) (#_objc_msgSend nsthread-class message-selector) nil))) (defun create-void-nsthread () Create an NSThread which does nothing but exit . This 'll help to convince the AppKit that we 're ;; multitheaded. (A lot of other things, including ;; the ObjC runtime, seem to have already noticed.) (with-cstrs ((thread-class-name "NSThread") (pool-class-name "NSAutoreleasePool") (thread-message-selector-name "detachNewThreadSelector:toTarget:withObject:") (exit-selector-name "class") (alloc-selector-name "alloc") (init-selector-name "init") (release-selector-name "release")) (let* ((nsthread-class (#_objc_lookUpClass thread-class-name)) (pool-class (#_objc_lookUpClass pool-class-name)) (thread-message-selector (#_sel_getUid thread-message-selector-name)) (exit-selector (#_sel_getUid exit-selector-name)) (alloc-selector (#_sel_getUid alloc-selector-name)) (init-selector (#_sel_getUid init-selector-name)) (release-selector (#_sel_getUid release-selector-name)) (pool (#_objc_msgSend (#_objc_msgSend pool-class alloc-selector) init-selector))) (unwind-protect (#_objc_msgSend nsthread-class thread-message-selector :address exit-selector :address nsthread-class :address (%null-ptr)) (#_objc_msgSend pool release-selector)) nil))) (defun load-cocoa-framework () (call-in-initial-process #'(lambda () We need to load and " initialize " the CoreFoundation library ;; in the thread that's going to process events. Looking up a ;; symbol in the library should cause it to be initialized #+apple-objc (open-shared-library "/System/Library/Frameworks/Cocoa.framework/Cocoa") #+cocotron-objc (progn (open-shared-library "Foundation.1.0.dll") (open-shared-library "AppKit.1.0.dll") (open-shared-library "CoreData.1.0.dll") ;; If the BOOL variable NSDebugEnabled can be found, ensure that it 's set to # $ NO . ( When set to non - zero values , it can cause attempts to raise NSExceptions to do nothing . ;; It's not clear how it gets set to a non-zero value.) (let* ((addr (foreign-symbol-address "NSDebugEnabled"))) (when addr (setf (%get-unsigned-byte addr) #$NO))) ;; We may need to call #_NSInitializeProcess under Cocotron . If so , we 'd need to do ;; so on standalone startup, too, and would ;; have to have heap-allocated the string vector ;; and its strings. #+notyet (with-string-vector (argv (list (kernel-path))) (#_NSInitializeProcess 1 argv))) ;(#_GetCurrentEventQueue) (current-ns-thread) (create-void-nsthread)))) (pushnew #'load-cocoa-framework *lisp-system-pointer-functions* :key #'function-name) #+darwin-target Nuke any command - line arguments , to keep the Cocoa runtime from ;;; trying to process them. (let* ((argv (foreign-symbol-address "NXArgv")) (argc (foreign-symbol-address "NXArgc"))) (when argc (setf (pref argc :int) 1)) (when argv (setf (paref (%get-ptr argv) (:* :char) 1) +null-ptr+))) #-cocotron (load-cocoa-framework) #+cocotron (let* ((path (getenv "PATH"))) (unwind-protect (progn (setenv "PATH" (format nil "~a;~a" (native-translated-namestring (truename "ccl:cocotron;")) path)) (load-cocoa-framework)) (setenv "PATH" path))) (defun find-cfstring-sections () (warn "~s is obsolete" 'find-cfstring-sections)) ) #+gnu-objc (progn (defparameter *gnustep-system-root* "/usr/GNUstep/" "The root of all evil.") (defparameter *gnustep-libraries-pathname* (merge-pathnames "System/Library/Libraries/" *gnustep-system-root*)) (defloadvar *pending-loaded-classes* ()) (defcallback register-class-callback (:address class :address category :void) (let* ((id (map-objc-class class))) (unless (%null-ptr-p category) (let* ((cell (or (assoc id *pending-loaded-classes*) (let* ((c (list id))) (push c *pending-loaded-classes*) c)))) (push (%inc-ptr category 0) (cdr cell)))))) ;;; Shouldn't really be GNU-objc-specific. (defun get-c-format-string (c-format-ptr c-arg-ptr) (do* ((n 128)) () (declare (fixnum n)) (%stack-block ((buf n)) (let* ((m (#_vsnprintf buf n c-format-ptr c-arg-ptr))) (declare (fixnum m)) (cond ((< m 0) (return nil)) ((< m n) (return (%get-cstring buf))) (t (setq n m))))))) (defun init-gnustep-framework () (or (getenv "GNUSTEP_SYSTEM_ROOT") (setenv "GNUSTEP_SYSTEM_ROOT" *gnustep-system-root*)) (open-shared-library "libobjc.so.1") (setf (%get-ptr (foreign-symbol-address "_objc_load_callback")) register-class-callback) (open-shared-library (namestring (merge-pathnames "libgnustep-base.so" *gnustep-libraries-pathname*))) (open-shared-library (namestring (merge-pathnames "libgnustep-gui.so" *gnustep-libraries-pathname*)))) (def-ccl-pointers gnustep-framework () (init-gnustep-framework)) ) (defun get-appkit-version () #+apple-objc #&NSAppKitVersionNumber #+cocotron-objc 1.0 ; fix this #+gnu-objc (get-foundation-version)) (defun get-foundation-version () #+apple-objc #&NSFoundationVersionNumber #+cocotron-objc 1.0 ; fix this #+gnu-objc (%get-cstring (foreign-symbol-address "gnustep_base_version"))) (defparameter *appkit-library-version-number* (get-appkit-version)) (defparameter *foundation-library-version-number* (get-foundation-version)) (defparameter *extension-framework-paths* ()) An instance of NSConstantString ( which is a subclass of NSString ) ;;; consists of a pointer to the NSConstantString class (which the ;;; global "_NSConstantStringClassReference" conveniently refers to), a pointer to an array of 8 - bit characters ( does n't have to be # \Nul ;;; terminated, but doesn't hurt) and the length of that string (not ;;; counting any #\Nul.) ;;; The global reference to the "NSConstantString" class allows us to make instances of NSConstantString , the @"foo " construct in ObjC. Sure it 's ugly , but it seems to be exactly what the ObjC ;;; compiler does. (defloadvar *NSConstantString-class* (with-cstrs ((name "NSConstantString")) #+(or apple-objc cocotron-objc) (#_objc_lookUpClass name) #+gnu-objc (#_objc_lookup_class name))) ;;; Catch frames are allocated on a stack, so it's OK to pass their ;;; addresses around to foreign code. (defcallback throw-to-catch-frame (:signed-fullword value :address frame :void) (throw (%get-object frame target::catch-frame.catch-tag) value)) #+(and x8632-target (or apple-objc cocotron-objc)) (defloadvar *setjmp-catch-rip-code* (let* ((code-bytes '(#x83 #xec #x10 ; subl $16,%esp #x89 #x04 #x24 ; movl %eax,(%esp) #x89 #x7c #x24 #x04 ; movl %edi,4(%esp) #xff #xd3)) ; call *%ebx (nbytes (length code-bytes)) (p (malloc nbytes))) (dotimes (i nbytes p) (setf (%get-unsigned-byte p i) (pop code-bytes))))) #+apple-objc (progn NSException - handling stuff . First , we have to jump through some hoops so that # _ longjmp can ;;; jump through some hoops (a jmp_buf) and wind up throwing to a ;;; lisp catch tag. ;;; These constants (offsets in the jmp_buf structure) come from the _ setjmp.h header file in the LibC source . #+ppc32-target (progn (defconstant JMP-lr #x54 "link register (return address) offset in jmp_buf") #|(defconstant JMP-ctr #x5c "count register jmp_buf offset")|# (defconstant JMP-sp 0 "stack pointer offset in jmp_buf") (defconstant JMP-r14 12 "offset of r14 (which we clobber) in jmp_buf") (defconstant JMP-r15 16 "offset of r14 (which we also clobber) in jmp_buf")) #+ppc64-target (progn (defconstant JMP-lr #xa8 "link register (return address) offset in jmp_buf") #|(defconstant JMP-ctr #x5c "count register jmp_buf offset")|# (defconstant JMP-sp 0 "stack pointer offset in jmp_buf") (defconstant JMP-r13 #x10 "offset of r13 (which we preserve) in jmp_buf") (defconstant JMP-r14 #x18 "offset of r14 (which we clobber) in jmp_buf") (defconstant JMP-r15 #x20 "offset of r15 (which we also clobber) in jmp_buf")) These constants also come from Libc sources . Hey , who needs ;;; header files ? #+x8664-target (progn (defconstant JB-RBX 0) (defconstant JB-RBP 8) (defconstant JB-RSP 16) (defconstant JB-R12 24) (defconstant JB-R13 32) (defconstant JB-R14 40) (defconstant JB-R15 48) (defconstant JB-RIP 56) (defconstant JB-RFLAGS 64) (defconstant JB-MXCSR 72) (defconstant JB-FPCONTROL 76) (defconstant JB-MASK 80) ) ;;; I think that we know where these constants come from. #+x8632-target (progn (defconstant JB-FPCW 0) (defconstant JB-MASK 4) (defconstant JB-MXCSR 8) (defconstant JB-EBX 12) (defconstant JB-ECX 16) (defconstant JB-EDX 20) (defconstant JB-EDI 24) (defconstant JB-ESI 28) (defconstant JB-EBP 32) (defconstant JB-ESP 36) (defconstant JB-SS 40) (defconstant JB-EFLAGS 44) (defconstant JB-EIP 48) (defconstant JB-CS 52) (defconstant JB-DS 56) (defconstant JB-ES 60) (defconstant JB-FS 64) (defconstant JB-GS 68) ) A malloc'ed pointer to three words of machine code . The first ;;; instruction copies the address of the trampoline callback from r14 to the count register . The second instruction ( rather obviously ) copies r15 to r4 . A C function passes its second argument in r4 , ;;; but since r4 isn't saved in a jmp_buf, we have to do this copy. The second instruction just jumps to the address in the count register , which is where we really wanted to go in the first ;;; place. #+ppc-target (macrolet ((ppc-lap-word (instruction-form) (uvref (uvref (compile nil `(lambda (&lap 0) (ppc-lap-function () ((?? 0)) ,instruction-form))) 0) #+ppc64-target 1 #+ppc32-target 0))) (defloadvar *setjmp-catch-lr-code* (let* ((p (malloc 12))) (setf (%get-unsigned-long p 0) (ppc-lap-word (mtctr 14)) (%get-unsigned-long p 4) (ppc-lap-word (mr 4 15)) (%get-unsigned-long p 8) (ppc-lap-word (bctr))) Force this code out of the data cache and into memory , so that it 'll get loaded into the icache . (ff-call (%kernel-import #.target::kernel-import-makedataexecutable) :address p :unsigned-fullword 12 :void) p))) ;;; This isn't used; it isn't right, either. #+x8664-target (defloadvar *setjmp-catch-rip-code* movq % r12 , % rsi #xff #xd3)) ; call *%rbx (nbytes (length code-bytes)) (p (malloc nbytes))) (dotimes (i nbytes p) (setf (%get-unsigned-byte p i) (pop code-bytes))))) Initialize a jmp_buf so that when it 's # _ longjmp - ed to , it 'll ;;; wind up calling THROW-TO-CATCH-FRAME with the specified catch frame as its second argument . The C frame used here is just ;;; an empty C stack frame from which the callback will be called. #+ppc-target (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (%set-object jmp-buf JMP-sp c-frame) (%set-object jmp-buf JMP-r15 catch-frame) #+ppc64-target (%set-object jmp-buf JMP-r13 (%get-os-context)) (setf (%get-ptr jmp-buf JMP-lr) *setjmp-catch-lr-code* (%get-ptr jmp-buf JMP-r14) throw-to-catch-frame) t) #+x8664-target (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (setf (%get-ptr jmp-buf JB-rbx) throw-to-catch-frame (%get-ptr jmp-buf JB-rip) *setjmp-catch-rip-code*) (setf (%get-unsigned-long jmp-buf JB-mxcsr) #x1f80 (%get-unsigned-long jmp-buf JB-fpcontrol) #x37f) (%set-object jmp-buf JB-RSP c-frame) (%set-object jmp-buf JB-RBP c-frame) (%set-object jmp-buf JB-r12 catch-frame) t) #+x8632-target Ugh . Apple stores segment register values in jmp_bufs . You know , ;;; since they're so volatile and everything. (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (setf (%get-unsigned-word jmp-buf JB-FS) (%get-fs-register) (%get-unsigned-word jmp-buf JB-GS) (%get-gs-register) (%get-unsigned-word jmp-buf JB-CS) #x17 (%get-unsigned-word jmp-buf JB-DS) #x1f (%get-unsigned-word jmp-buf JB-ES) #x1f (%get-unsigned-word jmp-buf JB-SS) #x1f) (%set-object jmp-buf JB-ESP c-frame) (%set-object jmp-buf JB-EBP c-frame) (setf (%get-unsigned-long jmp-buf JB-MXCSR) #x1f80 (%get-unsigned-long jmp-buf JB-FPCW) #x37f (%get-unsigned-long jmp-buf JB-MASK) 0) (setf (%get-ptr jmp-buf JB-EBX) throw-to-catch-frame (%get-ptr jmp-buf JB-EIP) *setjmp-catch-rip-code*) (%set-object jmp-buf JB-EDI catch-frame) t) ) #+win32-target (progn (eval-when (:compile-toplevel :execute) (progn (defconstant jb-ebp 0) (defconstant jb-ebx 4) (defconstant jb-edi 8) (defconstant jb-esi 12) (defconstant jb-esp 16) (defconstant jb-eip 20) (defconstant jb-seh 24) (defconstant jb-seh-info 28))) (defx8632lapfunction set-jb-seh ((jb arg_z)) (macptr-ptr arg_z temp0) ;fixnum-aligned (movl (@ (% fs) 0) (% imm0)) (movl (% imm0) (@ jb-seh (% temp0))) (cmpl ($ -1) (% imm0)) (je @store) (movl (@ 12 (% imm0)) (% imm0)) @store (movl (% imm0) (@ jb-seh-info (% temp0))) (single-value-return)) (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (%set-object jmp-buf JB-ESP (1+ c-frame)) (%set-object jmp-buf JB-EBP (1+ c-frame)) (setf (%get-ptr jmp-buf JB-EBX) throw-to-catch-frame (%get-ptr jmp-buf JB-EIP) *setjmp-catch-rip-code*) (%set-object jmp-buf JB-EDI catch-frame) (set-jb-seh jmp-buf) t) ) ;;; When starting up an image that's had ObjC classes in it, all of ;;; those canonical classes (and metaclasses) will have had their type changed ( by SAVE - APPLICATION ) to , CCL::DEAD - MACPTR and the addresses ;;; of those classes may be bogus. The hash tables (objc-class/metaclass-map) ;;; should be empty. ;;; For each class that -had- had an assigned ID, determine its ObjC ;;; class name, and ask ObjC where (if anywhere) the class is now. ;;; If we get a non-null answer, revive the class pointer and set its ;;; address appropriately, then add an entry to the hash-table; this means that classes that existed on both sides of SAVE - APPLICATION ;;; will retain the same ID. (defun revive-objc-classes () We need to do some things so that we can use ( @class ... ) ;; and (@selector ...) early. (invalidate-objc-class-descriptors) (clear-objc-selectors) (clear-objc-protocols) (reset-objc-class-count) ;; Ensure that any addon frameworks are loaded. (dolist (path *extension-framework-paths*) (%reload-objc-framework path)) Make a first pass over the class and metaclass tables ; ;; resolving those foreign classes that existed in the old ;; image and still exist in the new. (let* ((class-map (objc-class-map)) (metaclass-map (objc-metaclass-map)) (nclasses (%objc-class-count))) (dotimes (i nclasses) (let* ((c (id->objc-class i)) (meta-id (objc-class-id->objc-metaclass-id i)) (m (id->objc-metaclass meta-id))) (unless (typep c 'macptr) (%revive-macptr c) (%setf-macptr c (%null-ptr))) (unless (typep m 'macptr) (%revive-macptr m) (%setf-macptr m (%null-ptr))) (unless (gethash c class-map) (%set-pointer-to-objc-class-address (objc-class-id-foreign-name i) c) ;; If the class is valid and the metaclass is still ;; unmapped, set the metaclass pointer's address and map it. (unless (%null-ptr-p c) (setf (gethash c class-map) i) (unless (gethash m metaclass-map) (%setf-macptr m (#_object_getClass c)) (setf (gethash m metaclass-map) meta-id)) (note-class-protocols c))))) Second pass : install class objects for user - defined classes , assuming the superclasses are already " revived " . If the superclass is itself user - defined , it 'll appear first in the ;; class table; that's an artifact of the current implementation. (dotimes (i nclasses) (let* ((c (id->objc-class i))) (when (and (%null-ptr-p c) (not (slot-value c 'foreign))) (let* ((super (dolist (s (class-direct-superclasses c) (error "No ObjC superclass of ~s" c)) (when (objc-class-p s) (return s)))) (meta-id (objc-class-id->objc-metaclass-id i)) (m (id->objc-metaclass meta-id))) (let* ((class (make-objc-class-pair super (make-cstring (objc-class-id-foreign-name i)))) (meta (#_object_getClass class))) (unless (gethash m metaclass-map) (%revive-macptr m) (%setf-macptr m meta) (setf (gethash m metaclass-map) meta-id)) (%setf-macptr c class)) #+(or apple-objc-2.0 cocotron-objc) (%revive-foreign-slots c) #+(or apple-objc-2.0 cocotron-objc) (%add-objc-class c) #-(or apple-objc-2.0 cocotron-objc) (multiple-value-bind (ivars instance-size) (%make-objc-ivars c) (%add-objc-class c ivars instance-size)) (setf (gethash c class-map) i))))) ;; Finally, iterate over all classes in the runtime world. ;; Register any class that's not found in the class map ;; as a "private" ObjC class. ;; Iterate over all classes in the runtime. Those that ;; aren't already registered will get identified as ;; "private" (undeclared) ObjC classes. ;; Note that this means that if an application bundle was saved on ( for instance ) and Tiger interfaces were used , and then the application is run on Tiger , any ;; Tiger-specific classes will not be magically integrated into CLOS in the running application . ;; A development envronment might want to provide such a mechanism ; it would need access to Panther class ;; declarations, and - in the general case - a standalone ;; application doesn't necessarily have access to the ;; interface database. (map-objc-classes nil) )) (pushnew #'revive-objc-classes *lisp-system-pointer-functions* :test #'eq :key #'function-name) (defun %objc-class-instance-size (c) #+(or apple-objc-2.0 cocotron-objc) (#_class_getInstanceSize c) #-(or apple-objc-2.0 cocotron-objc) (pref c :objc_class.instance_size)) (defun find-named-objc-superclass (class string) (unless (or (null string) (%null-ptr-p class)) (with-macptrs ((name #+(or apple-objc-2.0 cocotron-objc) (#_class_getName class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.name))) (or (dotimes (i (length string) class) (let* ((b (%get-unsigned-byte name i))) (unless (eq b (char-code (schar string i))) (return)))) (find-named-objc-superclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class) string))))) (defun install-foreign-objc-class (class &optional (use-db t)) (let* ((id (objc-class-id class))) (unless id (let* ((name (%get-cstring #+(or apple-objc-2.0 cocotron-objc) (#_class_getName class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.name))) (decl (get-objc-class-decl name use-db))) (if (null decl) (or (%get-private-objc-class class) (%register-private-objc-class class name)) (progn (setq id (register-objc-class class) class (id->objc-class id)) ;; If not mapped, map the superclass (if there is one.) (let* ((super (find-named-objc-superclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class) (db-objc-class-info-superclass-name decl)))) (unless (null super) (install-foreign-objc-class super)) (let* ((class-name (objc-to-lisp-classname name "NS")) (meta-id (objc-class-id->objc-metaclass-id id)) (meta (id->objc-metaclass meta-id))) may already be initialized . It 'll have a ;; class wrapper if so. (unless (id->objc-metaclass-wrapper meta-id) (let* ((meta-foreign-name (%get-cstring #+(or apple-objc-2.0 cocotron-objc) (#_class_getName meta) #-(or apple-objc-2.0 cocotron-objc) (pref meta :objc_class.name))) (meta-name (intern (concatenate 'string "+" (string (objc-to-lisp-classname meta-foreign-name "NS"))) "NS")) (meta-super (if super (#_object_getClass super)))) ;; It's important (here and when initializing the ;; class below) to use the "canonical" ;; (registered) version of the class, since some things in CLOS assume EQness . We probably ;; don't want to violate that assumption; it'll be ;; easier to revive a saved image if we don't have a lot of EQL - but - not - EQ class pointers to deal ;; with. (initialize-instance meta :name meta-name :direct-superclasses (list (if (or (null meta-super) (not (%objc-metaclass-p meta-super))) (find-class 'objc:objc-class) (canonicalize-registered-metaclass meta-super))) :peer class :foreign t) (setf (objc-metaclass-id-foreign-name meta-id) meta-foreign-name) (setf (find-class meta-name) meta) (%defglobal meta-name meta))) (setf (slot-value class 'direct-slots) (compute-objc-direct-slots-from-info decl class)) (initialize-instance class :name class-name :direct-superclasses (list (if (null super) (find-class 'objc:objc-object) (canonicalize-registered-class super))) :peer meta :foreign t) (setf (objc-class-id-foreign-name id) name) (setf (find-class class-name) class) (%defglobal class-name class) class)))))))) Execute the body with the variable NSSTR bound to a ;;; stack-allocated NSConstantString instance (made from ;;; *NSConstantString-class*, CSTRING and LEN). (defmacro with-nsstr ((nsstr cstring len) &body body) #+apple-objc `(rlet ((,nsstr :<NSC>onstant<S>tring :isa *NSConstantString-class* :bytes ,cstring :num<B>ytes ,len)) ,@body) #+cocotron-objc `(rlet ((,nsstr :<NSC>onstant<S>tring :isa *NSConstantString-class* :_bytes ,cstring :_length ,len)) ,@body) #+gnu-objc `(rlet ((,nsstr :<NXC>onstant<S>tring :isa *NSConstantString-class* :c_string ,cstring :len ,len)) ,@body)) ;;; Make a persistent (heap-allocated) NSConstantString. (defun %make-constant-nsstring (string) "Make a persistent (heap-allocated) NSConstantString from the argument lisp string." #+apple-objc (make-record :<NSC>onstant<S>tring :isa *NSConstantString-Class* :bytes (make-cstring string) :num<B>ytes (length string)) #+cocotron-objc (make-record :<NSC>onstant<S>tring :isa *NSConstantString-Class* :_bytes (make-cstring string) :_length (length string)) #+gnu-objc (make-record :<NXC>onstant<S>tring :isa *NSConstantString-Class* :c_string (make-cstring string) :len (length string)) ) ;;; Class declarations (defparameter *objc-class-declarations* (make-hash-table :test #'equal)) (defun register-objc-class-decls () (do-interface-dirs (d) (dolist (class-name (cdb-enumerate-keys (db-objc-classes d))) (get-objc-class-decl class-name t)))) (defun get-objc-class-decl (class-name &optional (use-db nil)) (or (gethash class-name *objc-class-declarations*) (and use-db (let* ((decl (%find-objc-class-info class-name))) (when decl (setf (gethash class-name *objc-class-declarations*) decl)))))) (defun %ensure-class-declaration (name super-name) (unless (get-objc-class-decl name) (setf (gethash name *objc-class-declarations*) (make-db-objc-class-info :class-name (string name) :superclass-name (string super-name)))) name) ;;; It's hard (and questionable) to allow ivars here. (defmacro declare-objc-class (name super-name) `(%ensure-class-declaration ',name ',super-name)) Intern NSConstantString instances . (defvar *objc-constant-strings* (make-hash-table :test #'equal)) (defstruct objc-constant-string string nsstringptr) (defun ns-constant-string (string) (or (gethash string *objc-constant-strings*) (setf (gethash string *objc-constant-strings*) (make-objc-constant-string :string string :nsstringptr (%make-constant-nsstring string))))) (def-ccl-pointers objc-strings () (maphash #'(lambda (string cached) (setf (objc-constant-string-nsstringptr cached) (%make-constant-nsstring string))) *objc-constant-strings*)) (defmethod make-load-form ((s objc-constant-string) &optional env) (declare (ignore env)) `(ns-constant-string ,(objc-constant-string-string s))) (defmacro @ (string) `(objc-constant-string-nsstringptr ,(ns-constant-string string))) #+gnu-objc (progn (defcallback lisp-objc-error-handler (:id receiver :int errcode (:* :char) format :address argptr :<BOOL>) (let* ((message (get-c-format-string format argptr))) (error "ObjC runtime error ~d, receiver ~s :~& ~a" errcode receiver message)) #$YES) (def-ccl-pointers install-lisp-objc-error-handler () (#_objc_set_error_handler lisp-objc-error-handler))) ;;; Registering named objc classes. (defun objc-class-name-string (name) (etypecase name (symbol (lisp-to-objc-classname name)) (string name))) ;;; We'd presumably cache this result somewhere, so we'd only do the ;;; lookup once per session (in general.) (defun lookup-objc-class (name &optional error-p) (with-cstrs ((cstr (objc-class-name-string name))) (let* ((p (#+(or apple-objc cocotron-objc) #_objc_lookUpClass #+gnu-objc #_objc_lookup_class cstr))) (if (%null-ptr-p p) (if error-p (error "ObjC class ~a not found" name)) p)))) (defun %set-pointer-to-objc-class-address (class-name-string ptr) (with-cstrs ((cstr class-name-string)) (%setf-macptr ptr (#+(or apple-objc cocotron-objc) #_objc_lookUpClass #+gnu-objc #_objc_lookup_class cstr))) nil) (defvar *objc-class-descriptors* (make-hash-table :test #'equal)) (defstruct objc-class-descriptor name classptr) (defun invalidate-objc-class-descriptors () (maphash #'(lambda (name descriptor) (declare (ignore name)) (setf (objc-class-descriptor-classptr descriptor) nil)) *objc-class-descriptors*)) (defun %objc-class-classptr (class-descriptor &optional (error-p t)) (or (objc-class-descriptor-classptr class-descriptor) (setf (objc-class-descriptor-classptr class-descriptor) (lookup-objc-class (objc-class-descriptor-name class-descriptor) error-p)))) (defun load-objc-class-descriptor (name) (let* ((descriptor (or (gethash name *objc-class-descriptors*) (setf (gethash name *objc-class-descriptors*) (make-objc-class-descriptor :name name))))) (%objc-class-classptr descriptor nil) descriptor)) (defmacro objc-class-descriptor (name) `(load-objc-class-descriptor ,name)) (defmethod make-load-form ((o objc-class-descriptor) &optional env) (declare (ignore env)) `(load-objc-class-descriptor ,(objc-class-descriptor-name o))) (defmacro @class (name) (let* ((name (objc-class-name-string name))) `(the (@metaclass ,name) (%objc-class-classptr ,(objc-class-descriptor name))))) ;;; This isn't quite the inverse operation of LOOKUP-OBJC-CLASS: it ;;; returns a simple C string. and can be applied to a class or any ;;; instance (returning the class name.) (defun objc-class-name (object) #+(or apple-objc cocotron-objc) (with-macptrs (p) (%setf-macptr p (#_object_getClassName object)) (unless (%null-ptr-p p) (%get-cstring p))) #+gnu-objc (unless (%null-ptr-p object) (with-macptrs ((parent (pref object :objc_object.class_pointer))) (unless (%null-ptr-p parent) (if (logtest (pref parent :objc_class.info) #$_CLS_CLASS) (%get-cstring (pref parent :objc_class.name)) (%get-cstring (pref object :objc_class.name))))))) Likewise , we want to cache the selectors ( " SEL"s ) which identify ;;; method names. They can vary from session to session, but within ;;; a session, all methods with a given name (e.g, "init") will be represented by the same SEL . (defun get-selector-for (method-name &optional error) (with-cstrs ((cmethod-name method-name)) (let* ((p (#+(or apple-objc cocotron-objc) #_sel_getUid #+gnu-objc #_sel_get_uid cmethod-name))) (if (%null-ptr-p p) (if error (error "Can't find ObjC selector for ~a" method-name)) p)))) (defvar *objc-selectors* (make-hash-table :test #'equal)) (defstruct objc-selector name %sel) (defun %get-SELECTOR (selector &optional (error-p t)) (or (objc-selector-%sel selector) (setf (objc-selector-%sel selector) (get-selector-for (objc-selector-name selector) error-p)))) (defun clear-objc-selectors () (maphash #'(lambda (name sel) (declare (ignore name)) (setf (objc-selector-%sel sel) nil)) *objc-selectors*)) Find or create a SELECTOR ; do n't bother resolving it . (defun ensure-objc-selector (name) (setq name (string name)) (or (gethash name *objc-selectors*) (setf (gethash name *objc-selectors*) (make-objc-selector :name name)))) (defun load-objc-selector (name) (let* ((selector (ensure-objc-selector name))) (%get-SELECTOR selector nil) selector)) (defmacro @SELECTOR (name) `(%get-selector ,(load-objc-selector name))) (defmethod make-load-form ((s objc-selector) &optional env) (declare (ignore env)) `(load-objc-selector ,(objc-selector-name s))) Convert a Lisp object X to a desired foreign type FTYPE ;;; The following conversions are currently done: - T / NIL = > # $ YES/#$NO ;;; - NIL => (%null-ptr) ;;; - Lisp numbers => SINGLE-FLOAT when possible (defun coerce-to-bool (x) (let ((x-temp (gensym))) `(let ((,x-temp ,x)) (if (or (eq ,x-temp 0) (null ,x-temp)) #.#$NO #.#$YES)))) (declaim (inline %coerce-to-bool)) (defun %coerce-to-bool (x) (if (and x (not (eql x 0))) #$YES #$NO)) (defun coerce-to-address (x) (let ((x-temp (gensym))) `(let ((,x-temp ,x)) (cond ((null ,x-temp) +null-ptr+) (t ,x-temp))))) ;;; This is generally a bad idea; it forces us to ;;; box intermediate pointer arguments in order ;;; to typecase on them, and it's not clear to ;;; me that it offers much in the way of additional ;;; expressiveness. (declaim (inline %coerce-to-address)) (defun %coerce-to-address (x) (etypecase x (macptr x) (null (%null-ptr)))) (defun coerce-to-foreign-type (x ftype) (cond ((and (constantp x) (constantp ftype)) (case ftype (:id (if (null x) `(%null-ptr) (coerce-to-address x))) (:<BOOL> (coerce-to-bool (eval x))) (t x))) ((constantp ftype) (case ftype (:id `(%coerce-to-address ,x)) (:<BOOL> `(%coerce-to-bool ,x)) (t x))) (t `(case ,(if (atom ftype) ftype) (:id (%coerce-to-address ,x)) (:<BOOL> (%coerce-to-bool ,x)) (t ,x))))) (defun objc-arg-coerce (typespec arg) (case typespec (:<BOOL> `(%coerce-to-bool ,arg)) (:id `(%coerce-to-address ,arg)) (t arg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Boolean Return Hackery ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Convert a foreign object X to T or NIL (defun coerce-from-bool (x) (cond ((eq x #$NO) nil) ((eq x #$YES) t) (t (error "Cannot coerce ~S to T or NIL" x)))) (defun objc-result-coerce (type result) (cond ((eq type :<BOOL>) `(coerce-from-bool ,result)) (t result))) Add a faster way to get the message from a SEL by taking advantage of the ;;; fact that a selector is really just a canonicalized, interned C string ;;; containing the message. (This is an admitted modularity violation; ;;; there's a more portable but slower way to do this if we ever need to.) (defun lisp-string-from-sel (sel) (%get-cstring #+apple-objc sel #+cocotron-objc (#_sel_getName sel) #+gnu-objc (#_sel_get_name sel))) # _ objc_msgSend takes two required arguments ( the receiving object and the method selector ) and 0 or more additional arguments ; ;;; there'd have to be some macrology to handle common cases, since we ;;; want the compiler to see all of the args in a foreign call. I do n't remmber what the second half of the above comment might ;;; have been talking about. (defmacro objc-message-send (receiver selector-name &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) `(:address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) (defmacro objc-message-send-with-selector (receiver selector &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) `(:address ,receiver :<SEL> (%get-selector ,selector) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (%get-selector ,selector)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) ;;; A method that returns a structure does so by platform-dependent means . One of those means ( which is fairly common ) is to pass a pointer to an instance of a structure type as a first argument to the method implementation function ( thereby making SELF the second ;;; argument, etc.), but whether or not it's actually done that way ;;; depends on the platform and on the structure type. The special variable * holds a structure ( of type ;;; CCL::FOREIGN-TYPE-DATA) which describes some static attributes of ;;; the foreign type system on the target platform and contains some functions which can determine dynamic ABI attributes . One such ;;; function can be used to determine whether or not the "invisible first arg " convention is used to return structures of a given ;;; foreign type; another function in *TARGET-FTD* can be used to ;;; construct a foreign function call form that handles ;;; structure-return and structure-types-as-arguments details. In the Apple ObjC runtime , # _ objc_msgSend_stret must be used if the invisible - first - argument convention is used to return a structure and must NOT be used otherwise . ( The ppc64 and all ;;; supported x86-64 ABIs often use more complicated structure return conventions than ppc32 or ppc Linux . ) We should use ;;; OBJC-MESSAGE-SEND-STRET to send any message that returns a ;;; structure or union, regardless of how that structure return is ;;; actually implemented. (defmacro objc-message-send-stret (structptr receiver selector-name &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSend_stret" "objc_msgSend"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) , (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(,structptr :address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) (defmacro objc-message-send-stret-with-selector (structptr receiver selector &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSend_stret" "objc_msgSend"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,receiver :<SEL> (%get-selector ,selector) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (%get-selector ,selector)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) , (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(,structptr :address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) # _ objc_msgSendSuper is similar to # _ objc_msgSend ; its first argument ;;; is a pointer to a structure of type objc_super {self, the defining ;;; class's superclass}. It only makes sense to use this inside an ;;; objc method. (defmacro objc-message-send-super (super selector-name &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSendSuper")))) `(:address ,super :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs))))) (defmacro objc-message-send-super-with-selector (super selector &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSendSuper")))) `(:address ,super :<SEL> ,selector ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel ,selector) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs))))) ;;; Send to superclass method, returning a structure. See above. (defmacro objc-message-send-super-stret (structptr super selector-name &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSendSuper_stret" "objc_msgSendSuper"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,super :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) ,structptr :id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs)))) (defmacro objc-message-send-super-stret-with-selector (structptr super selector &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSendSuper_stret" "objc_msgSendSuper"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,super :<SEL> ,selector ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel ,selector) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) ,structptr :id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs)))) (defun message-send-form-for-call (receiver selector args super-p struct-return-var) (if struct-return-var (if super-p `(objc-message-send-super-stret-with-selector ,struct-return-var ,receiver ,selector ,@args) `(objc-message-send-stret-with-selector ,struct-return-var ,receiver ,selector ,@args)) (if super-p `(objc-message-send-super-with-selector ,receiver ,selector ,@args) `(objc-message-send-with-selector ,receiver ,selector ,@args)))) #+(and apple-objc x8664-target) (defun %process-varargs-list (gpr-pointer fpr-pointer stack-pointer ngprs nfprs nstackargs arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 64) (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* (:signed 64)) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* (:signed 64)) nstackargs) arg-temp) (incf nstackargs)))) ((unsigned-byte 64) (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* (:unsigned 64)) nstackargs) arg-temp) (incf nstackargs)))) (macptr (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* :address) nstackargs) arg-temp) (incf nstackargs)))) (single-float (if (< nfprs 8) (progn (setf (%get-single-float fpr-pointer (* nfprs 16)) arg-temp) (incf nfprs)) (progn (setf (paref stack-pointer (:* :float) (* 2 nstackargs)) arg-temp) (incf nstackargs)))) (double-float (if (< nfprs 8) (progn (setf (%get-double-float fpr-pointer (* nfprs 16)) arg-temp) (incf nfprs)) (progn (setf (paref stack-pointer (:* :double) nstackargs) arg-temp) (incf nstackargs))))))) #+x8632-target (defun %process-varargs-list (ptr index arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 32) (setf (paref ptr (:* (:signed 32)) index) arg-temp) (incf index)) ((unsigned-byte 32) (setf (paref ptr (:* (:unsigned 32)) index) arg-temp) (incf index)) (macptr (setf (paref ptr (:* :address) index) arg-temp) (incf index)) (single-float (setf (%get-single-float ptr (* 4 index)) arg-temp) (incf index)) (double-float (setf (%get-double-float ptr (* 4 index)) arg-temp) (incf index 2)) ((or (signed-byte 64) (unsigned-byte 64)) (setf (paref ptr (:* :unsigned) index) (ldb (byte 32 0) arg-temp)) (incf index) (setf (paref ptr (:* :unsigned) index) (ldb (byte 32 32) arg-temp)) (incf index))))) #+(and apple-objc ppc32-target) (defun %process-varargs-list (gpr-pointer fpr-pointer ngprs nfprs arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 32) (setf (paref gpr-pointer (:* (:signed 32)) ngprs) arg-temp) (incf ngprs)) ((unsigned-byte 32) (setf (paref gpr-pointer (:* (:unsigned 32)) ngprs) arg-temp) (incf ngprs)) (macptr (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (single-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) (float arg-temp 0.0d0)) (incf nfprs)) (setf (paref gpr-pointer (:* :single-float) ngprs) arg-temp) (incf ngprs)) (double-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) arg-temp) (incf nfprs)) (multiple-value-bind (high low) (double-float-bits arg-temp) (setf (paref gpr-pointer (:* :unsigned) ngprs) high) (incf ngprs) (setf (paref gpr-pointer (:* :unsigned) ngprs) low) (incf nfprs))) ((or (signed-byte 64) (unsigned-byte 64)) (setf (paref gpr-pointer (:* :unsigned) ngprs) (ldb (byte 32 32) arg-temp)) (incf ngprs) (setf (paref gpr-pointer (:* :unsigned) ngprs) (ldb (byte 32 0) arg-temp)) (incf ngprs))))) #+(and apple-objc ppc64-target) (defun %process-varargs-list (gpr-pointer fpr-pointer ngprs nfprs arglist) (dolist (arg-temp arglist (min nfprs 13)) (typecase arg-temp ((signed-byte 64) (setf (paref gpr-pointer (:* (:signed 64)) ngprs) arg-temp) (incf ngprs)) ((unsigned-byte 64) (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) arg-temp) (incf ngprs)) (macptr (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (single-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) (float arg-temp 0.0d0)) (incf nfprs)) (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) (single-float-bits arg-temp)) (incf ngprs)) (double-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) arg-temp) (incf nfprs)) (setf (paref gpr-pointer (:* :double-float) ngprs) arg-temp) (incf ngprs))))) #+apple-objc (eval-when (:compile-toplevel :execute) #+(and ppc-target (not apple-objc-2.0)) (def-foreign-type :<MARG> (:struct nil (:fp<P>arams (:array :double 13)) (:linkage (:array :uintptr_t 6)) (:reg<P>arams (:array :uintptr_t 8)) (:stack<P>arams (:array :uintptr_t) 0))) ) #+(and apple-objc-2.0 x8664-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (foreign-type-to-representation-type (car sig))) (op (case return-type-spec (:address '%get-ptr) (:unsigned-byte '%get-unsigned-byte) (:signed-byte '%get-signed-byte) (:unsigned-halfword '%get-unsigned-word) (:signed-halfword '%get-signed-word) (:unsigned-fullword '%get-unsigned-long) (:signed-fullword '%get-signed-long) (:unsigned-doubleword '%get-natural) (:signed-doubleword '%get-signed-natural) (:single-float '%get-single-float) (:double-float '%get-double-float))) (result-offset (case op ((:single-float :double-float) 0) (t -8))) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (regparams (gensym)) (stackparams (gensym)) (fpparams (gensym)) (cframe (gensym)) (selptr (gensym)) (gpr-total (gensym)) (fpr-total (gensym)) (stack-total (gensym)) (n-static-gprs 2) ;receiver, selptr (n-static-fprs 0) (n-static-stack-args 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,regparams (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,regparams (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base (if (< n-static-gprs 6) regparams stackparams)) (fpr-base (if (< n-static-fprs 8) fpparams stackparams)) (gpr-offset (if (< n-static-gprs 6) n-static-gprs n-static-stack-args)) (fpr-offset (if (< n-static-fprs 8) (* 8 n-static-fprs) (* 8 n-static-stack-args)))) (etypecase static-arg-type (foreign-integer-type (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) ,(foreign-integer-type-bits static-arg-type))) ,gpr-offset) ,arg)) (if (< n-static-gprs 6) (incf n-static-gprs) (incf n-static-stack-args))) (foreign-single-float-type (static-arg-forms `(setf (%get-single-float ,fpr-base ,fpr-offset) ,arg)) (if (< n-static-fprs 8) (incf n-static-fprs) (incf n-static-stack-args))) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,fpr-base ,fpr-offset) ,arg)) (if (< n-static-fprs 8) (incf n-static-fprs) (incf n-static-stack-args))) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,gpr-offset) ,arg)) (if (< n-static-gprs 6) (incf n-static-gprs) (incf n-static-stack-args)))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total ,n-static-gprs) (,fpr-total ,n-static-fprs) (,stack-total ,n-static-stack-args)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (typep ,arg-temp 'single-float)) (if (< ,fpr-total 8) (incf ,fpr-total) (incf ,stack-total)) (if (< ,gpr-total 6) (incf ,gpr-total) (incf ,stack-total)))) (%stack-block ((,fpparams (* 8 8))) (with-macptrs (,regparams ,stackparams) (with-variable-c-frame (+ 8 ,stack-total) ,cframe (%setf-macptr-to-object ,regparams (+ ,cframe 2)) (%setf-macptr-to-object ,stackparams (+ ,cframe 8)) (progn ,@(static-arg-forms)) (%process-varargs-list ,regparams ,fpparams ,stackparams ,n-static-gprs ,n-static-fprs ,n-static-stack-args ,rest-arg) (%do-ff-call ,fpr-total ,cframe ,fpparams (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) ,@(if op `((,op ,regparams ,result-offset)) `(()))))))))))) #+(and apple-objc ppc32-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (marg-ptr (gensym)) (regparams (gensym)) (selptr (gensym)) (gpr-total (gensym)) (n-static-gprs 2) ;receiver, selptr (n-static-fprs 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,regparams (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,regparams (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base regparams) (fpr-base marg-ptr) (gpr-offset (* n-static-gprs 4))) (etypecase static-arg-type (foreign-integer-type (let* ((bits (foreign-type-bits static-arg-type)) (signed (foreign-integer-type-signed static-arg-type))) (if (> bits 32) (progn (static-arg-forms `(setf (,(if signed '%%get-signed-longlong '%%get-unsigned-long-long) ,gpr-base ,gpr-offset) ,arg)) (incf n-static-gprs 2)) (progn (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 32)) ,gpr-offset) ,arg)) (incf n-static-gprs))))) (foreign-single-float-type (static-arg-forms `(setf (paref ,gpr-base (:* :single-float) ,n-static-gprs) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (float (paref ,gpr-base (:* :single-float) ,n-static-gprs) 0.0d0))) (incf n-static-fprs)) (incf n-static-gprs)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,gpr-base ,gpr-offset) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (%get-double-float ,gpr-base ,gpr-offset))) (incf n-static-fprs)) (incf n-static-gprs 2)) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,n-static-gprs) ,arg)) (incf n-static-gprs))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total ,n-static-gprs)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (and (typep ,arg-temp 'integer) (if (< ,arg-temp 0) (>= (integer-length ,arg-temp) 32) (> (integer-length ,arg-temp) 32)))) (incf ,gpr-total 2) (incf ,gpr-total 1))) (if (> ,gpr-total 8) (setq ,gpr-total (- ,gpr-total 8)) (setq ,gpr-total 0)) (%stack-block ((,marg-ptr (+ ,(%foreign-type-or-record-size :<MARG> :bytes) (* 4 ,gpr-total)))) (with-macptrs ((,regparams (pref ,marg-ptr :<MARG>.reg<P>arams))) (progn ,@(static-arg-forms)) (%process-varargs-list ,regparams ,marg-ptr ,n-static-gprs ,n-static-fprs ,rest-arg) (external-call "objc_msgSendv" :address ,receiver :address ,selptr :size_t (+ 32 (* 4 ,gpr-total)) :address ,marg-ptr ,return-type-spec))))))))) #+(and (or apple-objc cocotron-objc) x8632-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (marg-ptr (gensym)) (static-arg-words 2) ;receiver, selptr (marg-words (gensym)) (marg-size (gensym)) (selptr (gensym))) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,marg-ptr (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,marg-ptr (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec))) (etypecase static-arg-type (foreign-integer-type (let* ((bits (foreign-type-bits static-arg-type)) (signed (foreign-integer-type-signed static-arg-type))) (if (> bits 32) (progn (static-arg-forms `(setf (,(if signed '%%get-signed-longlong '%%get-unsigned-long-long) ,marg-ptr (* 4 ,static-arg-words)) ,arg)) (incf static-arg-words 2)) (progn (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,marg-ptr (:* (,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 32)) ,static-arg-words) ,arg)) (incf static-arg-words))))) (foreign-single-float-type (static-arg-forms `(setf (paref ,marg-ptr (:* :single-float) ,static-arg-words) ,arg)) (incf static-arg-words)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,marg-ptr (* 4 ,static-arg-words)) ,arg)) (incf static-arg-words 2)) (foreign-pointer-type (static-arg-forms `(setf (paref ,marg-ptr (:* address) ,static-arg-words) ,arg)) (incf static-arg-words))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,marg-words ,static-arg-words) (,marg-size nil)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (and (typep ,arg-temp 'integer) (if (< ,arg-temp 0) (>= (integer-length ,arg-temp) 32) (> (integer-length ,arg-temp) 32)))) (incf ,marg-words 2) (incf ,marg-words 1))) (setq ,marg-size (ash ,marg-words 2)) (%stack-block ((,marg-ptr ,marg-size)) (progn ,@(static-arg-forms)) (%process-varargs-list ,marg-ptr ,static-arg-words ,rest-arg) (external-call "objc_msgSendv" :id ,receiver :<SEL> ,selptr :size_t ,marg-size :address ,marg-ptr ,return-type-spec)))))))) #+(and apple-objc-2.0 ppc64-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (fp-arg-ptr (gensym)) (c-frame (gensym)) (gen-arg-ptr (gensym)) (selptr (gensym)) (gpr-total (gensym)) (n-static-gprs 2) ;receiver, selptr (n-static-fprs 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,gen-arg-ptr (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,gen-arg-ptr (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base gen-arg-ptr) (fpr-base fp-arg-ptr) (gpr-offset (* n-static-gprs 8))) (etypecase static-arg-type (foreign-integer-type (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 64)) ,gpr-offset) ,arg)) (incf n-static-gprs)) (foreign-single-float-type (static-arg-forms `(setf (%get-single-float ,gpr-base ,(+ 4 gpr-offset)) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (float (%get-single-float ,gpr-base ,(+ 4 (* 8 n-static-gprs))) 0.0d0))) (incf n-static-fprs)) (incf n-static-gprs)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,gpr-base ,gpr-offset) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (%get-double-float ,gpr-base ,gpr-offset))) (incf n-static-fprs)) (incf n-static-gprs 1)) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,n-static-gprs) ,arg)) (incf n-static-gprs))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total (+ ,n-static-gprs (length ,rest-arg)))) (%stack-block ((,fp-arg-ptr (* 8 13))) (with-variable-c-frame ,gpr-total ,c-frame (with-macptrs ((,gen-arg-ptr)) (%setf-macptr-to-object ,gen-arg-ptr (+ ,c-frame (ash ppc64::c-frame.param0 (- ppc64::word-shift)))) (progn ,@(static-arg-forms)) (%load-fp-arg-regs (%process-varargs-list ,gen-arg-ptr ,fp-arg-ptr ,n-static-gprs ,n-static-fprs ,rest-arg) ,fp-arg-ptr) (%do-ff-call nil (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) ;; Using VALUES here is a hack: the multiple-value ;; returning machinery clobbers imm0. (values (%%ff-result ,(foreign-type-to-representation-type return-type-spec)))))))))))) (defun %compile-send-function-for-signature (sig &optional super-p) (let* ((return-type-spec (car sig)) (arg-type-specs (cdr sig))) (if (eq (car (last arg-type-specs)) :void) (%compile-varargs-send-function-for-signature sig) (let* ((args (objc-gen-message-arglist (length arg-type-specs))) (struct-return-var nil) (receiver (gensym)) (selector (gensym))) (collect ((call) (lets)) (let* ((result-type (parse-foreign-type return-type-spec))) (when (typep result-type 'foreign-record-type) (setq struct-return-var (gensym)) (lets `(,struct-return-var (make-gcable-record ,return-type-spec)))) (do ((args args (cdr args)) (spec (pop arg-type-specs) (pop arg-type-specs))) ((null args) (call return-type-spec)) (let* ((arg (car args))) (call spec) (case spec (:<BOOL> (call `(%coerce-to-bool ,arg))) (:id (call `(%coerce-to-address ,arg))) (:<CGF>loat (call `(float ,arg +cgfloat-zero+))) (t (call arg))))) (let* ((call (call)) (lets (lets)) (body (message-send-form-for-call receiver selector call super-p struct-return-var))) (if struct-return-var (setq body `(progn ,body ,struct-return-var))) (if lets (setq body `(let* ,lets ,body))) (compile nil `(lambda (,receiver ,selector ,@args) ,body))))))))) (defun compile-send-function-for-signature (sig) (%compile-send-function-for-signature sig nil)) The first 8 words of non - fp arguments get passed in R3 - R10 #+ppc-target (defvar *objc-gpr-offsets* #+32-bit-target #(4 8 12 16 20 24 28 32) #+64-bit-target #(8 16 24 32 40 48 56 64) ) The first 13 fp arguments get passed in F1 - F13 ( and also " consume " a GPR or two . ) It 's certainly possible for an FP arg and a non- FP arg to share the same " offset " , and parameter offsets are n't ;;; strictly increasing. #+ppc-target (defvar *objc-fpr-offsets* #+32-bit-target #(36 44 52 60 68 76 84 92 100 108 116 124 132) #+64-bit-target #(68 76 84 92 100 108 116 124 132 140 148 156 164)) ;;; Just to make things even more confusing: once we've filled in the first 8 words of the parameter area , args that are n't passed in FP - regs get assigned offsets starting at 32 . That almost makes ;;; sense (even though it conflicts with the last offset in ;;; *objc-gpr-offsets* (assigned to R10), but we then have to add ;;; this constant to the memory offset. (defconstant objc-forwarding-stack-offset 8) (defvar *objc-id-type* (parse-foreign-type :id)) (defvar *objc-sel-type* (parse-foreign-type :<SEL>)) (defvar *objc-char-type* (parse-foreign-type :char)) (defun encode-objc-type (type &optional for-ivar recursive) (if (or (eq type *objc-id-type*) (foreign-type-= type *objc-id-type*)) "@" (if (or (eq type *objc-sel-type*) (foreign-type-= type *objc-sel-type*)) ":" (if (eq (foreign-type-class type) 'root) "v" (typecase type (foreign-pointer-type (let* ((target (foreign-pointer-type-to type))) (if (or (eq target *objc-char-type*) (foreign-type-= target *objc-char-type*)) "*" (format nil "^~a" (encode-objc-type target nil t))))) (foreign-double-float-type "d") (foreign-single-float-type "f") (foreign-integer-type (let* ((signed (foreign-integer-type-signed type)) (bits (foreign-integer-type-bits type))) (if (eq (foreign-integer-type-alignment type) 1) (format nil "b~d" bits) (cond ((= bits 8) (if signed "c" "C")) ((= bits 16) (if signed "s" "S")) ((= bits 32) ;; Should be some way of noting "longness". (if signed "i" "I")) ((= bits 64) (if signed "q" "Q")))))) (foreign-record-type (ensure-foreign-type-bits type) (let* ((name (unescape-foreign-name (or (foreign-record-type-name type) "?"))) (kind (foreign-record-type-kind type)) (fields (foreign-record-type-fields type))) (with-output-to-string (s) (format s "~c~a=" (if (eq kind :struct) #\{ #\() name) (dolist (f fields (format s "~a" (if (eq kind :struct) #\} #\)))) (when for-ivar (format s "\"~a\"" (unescape-foreign-name (or (foreign-record-field-name f) "")))) (unless recursive (format s "~a" (encode-objc-type (foreign-record-field-type f) nil nil))))))) (foreign-array-type (ensure-foreign-type-bits type) (let* ((dims (foreign-array-type-dimensions type)) (element-type (foreign-array-type-element-type type))) (if dims (format nil "[~d~a]" (car dims) (encode-objc-type element-type nil t)) (if (or (eq element-type *objc-char-type*) (foreign-type-= element-type *objc-char-type*)) "*" (format nil "^~a" (encode-objc-type element-type nil t)))))) (t (break "type = ~s" type))))))) #+ppc-target (defun encode-objc-method-arglist (arglist result-spec) (let* ((gprs-used 0) (fprs-used 0) (arg-info (flet ((current-memory-arg-offset () (+ 32 (* 4 (- gprs-used 8)) objc-forwarding-stack-offset))) (flet ((current-gpr-arg-offset () (if (< gprs-used 8) (svref *objc-gpr-offsets* gprs-used) (current-memory-arg-offset))) (current-fpr-arg-offset () (if (< fprs-used 13) (svref *objc-fpr-offsets* fprs-used) (current-memory-arg-offset)))) (let* ((result nil)) (dolist (argspec arglist (nreverse result)) (let* ((arg (parse-foreign-type argspec)) (offset 0) (size 0)) (typecase arg (foreign-double-float-type (setq size 8 offset (current-fpr-arg-offset)) (incf fprs-used) (incf gprs-used 2)) (foreign-single-float-type (setq size target::node-size offset (current-fpr-arg-offset)) (incf fprs-used) (incf gprs-used 1)) (foreign-pointer-type (setq size target::node-size offset (current-gpr-arg-offset)) (incf gprs-used)) (foreign-integer-type (let* ((bits (foreign-type-bits arg))) (setq size (ceiling bits 8) offset (current-gpr-arg-offset)) (incf gprs-used (ceiling bits target::nbits-in-word)))) ((or foreign-record-type foreign-array-type) (let* ((bits (ensure-foreign-type-bits arg))) (setq size (ceiling bits 8) offset (current-gpr-arg-offset)) (incf gprs-used (ceiling bits target::nbits-in-word)))) (t (break "argspec = ~s, arg = ~s" argspec arg))) (push (list (encode-objc-type arg) offset size) result)))))))) (declare (fixnum gprs-used fprs-used)) (let* ((max-parm-end (- (apply #'max (mapcar #'(lambda (i) (+ (cadr i) (caddr i))) arg-info)) objc-forwarding-stack-offset))) (with-standard-io-syntax (format nil "~a~d~:{~a~d~}" (encode-objc-type (parse-foreign-type result-spec)) max-parm-end arg-info))))) #+x86-target (defun encode-objc-method-arglist (arglist result-spec) (let* ((offset 0) (arg-info (let* ((result nil)) (dolist (argspec arglist (nreverse result)) (let* ((arg (parse-foreign-type argspec)) (delta target::node-size)) (typecase arg (foreign-double-float-type) (foreign-single-float-type) ((or foreign-pointer-type foreign-array-type)) (foreign-integer-type) (foreign-record-type (let* ((bits (ensure-foreign-type-bits arg))) (setq delta (ceiling bits target::node-size)))) (t (break "argspec = ~s, arg = ~s" argspec arg))) (push (list (encode-objc-type arg) offset) result) (setq offset (* target::node-size (ceiling (+ offset delta) target::node-size)))))))) (let* ((max-parm-end offset)) (with-standard-io-syntax (format nil "~a~d~:{~a~d~}" (encode-objc-type (parse-foreign-type result-spec)) max-parm-end arg-info))))) In Apple Objc , a class 's methods are stored in a ( -1)-terminated ;;; vector of method lists. In GNU ObjC, method lists are linked ;;; together. (defun %make-method-vector () #+apple-objc (let* ((method-vector (malloc 16))) (setf (%get-signed-long method-vector 0) 0 (%get-signed-long method-vector 4) 0 (%get-signed-long method-vector 8) 0 (%get-signed-long method-vector 12) -1) method-vector)) ;;; Make a meta-class object (with no instance variables or class ;;; methods.) #-(or apple-objc-2.0 cocotron-objc) (defun %make-basic-meta-class (nameptr superptr rootptr) #+apple-objc (let* ((method-vector (%make-method-vector))) (make-record :objc_class :isa (pref rootptr :objc_class.isa) :super_class (pref superptr :objc_class.isa) :name nameptr :version 0 :info #$CLS_META :instance_size 0 :ivars (%null-ptr) :method<L>ists method-vector :cache (%null-ptr) :protocols (%null-ptr))) #+gnu-objc (make-record :objc_class :class_pointer (pref rootptr :objc_class.class_pointer) :super_class (pref superptr :objc_class.class_pointer) :name nameptr :version 0 :info #$_CLS_META :instance_size 0 :ivars (%null-ptr) :methods (%null-ptr) :dtable (%null-ptr) :subclass_list (%null-ptr) :sibling_class (%null-ptr) :protocols (%null-ptr) :gc_object_type (%null-ptr))) #-(or apple-objc-2.0 cocotron-objc) (defun %make-class-object (metaptr superptr nameptr ivars instance-size) #+apple-objc (let* ((method-vector (%make-method-vector))) (make-record :objc_class :isa metaptr :super_class superptr :name nameptr :version 0 :info #$CLS_CLASS :instance_size instance-size :ivars ivars :method<L>ists method-vector :cache (%null-ptr) :protocols (%null-ptr))) #+gnu-objc (make-record :objc_class :class_pointer metaptr :super_class superptr :name nameptr :version 0 :info #$_CLS_CLASS :instance_size instance-size :ivars ivars :methods (%null-ptr) :dtable (%null-ptr) :protocols (%null-ptr))) (defun make-objc-class-pair (superptr nameptr) #+(or apple-objc-2.0 cocotron-objc) (#_objc_allocateClassPair superptr nameptr 0) #-(or apple-objc-2.0 cocotron-objc) (%make-class-object (%make-basic-meta-class nameptr superptr (@class "NSObject")) superptr nameptr (%null-ptr) 0)) (defun superclass-instance-size (class) (with-macptrs ((super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class))) (if (%null-ptr-p super) 0 (%objc-class-instance-size super)))) #+gnu-objc (progn (defloadvar *gnu-objc-runtime-mutex* (%get-ptr (foreign-symbol-address "__objc_runtime_mutex"))) (defmacro with-gnu-objc-mutex-locked ((mutex) &body body) (let* ((mname (gensym))) `(let ((,mname ,mutex)) (unwind-protect (progn (external-call "objc_mutex_lock" :address ,mname :void) ,@body) (external-call "objc_mutex_lock" :address ,mname :void))))) ) (defun %objc-metaclass-p (class) #+(or apple-objc-2.0 cocotron-objc) (not (eql #$NO (#_class_isMetaClass class))) #-(or apple-objc-2.0 cocotron-objc) (logtest (pref class :objc_class.info) #+apple-objc #$CLS_META #+gnu-objc #$_CLS_META)) ;; No way to tell in Objc-2.0. Does anything care ? #-(or apple-objc-2.0 cocotron-objc) (defun %objc-class-posing-p (class) (logtest (pref class :objc_class.info) #+apple-objc #$CLS_POSING #+gnu-objc #$_CLS_POSING)) ;;; Create (malloc) class and metaclass objects with the specified name ( string ) and superclass name . Initialize the metaclass ;;; instance, but don't install the class in the ObjC runtime system ;;; (yet): we don't know anything about its ivars and don't know ;;; how big instances will be yet. ;;; If an ObjC class with this name already exists, we're very ;;; confused; check for that case and error out if it occurs. (defun %allocate-objc-class (name superptr) (let* ((class-name (compute-objc-classname name))) (if (lookup-objc-class class-name nil) (error "An Objective C class with name ~s already exists." class-name)) (let* ((nameptr (make-cstring class-name)) (id (register-objc-class (make-objc-class-pair superptr nameptr) )) (meta-id (objc-class-id->objc-metaclass-id id)) (meta (id->objc-metaclass meta-id)) (class (id->objc-class id)) (meta-name (intern (format nil "+~a" name) (symbol-package name))) (meta-super (canonicalize-registered-metaclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass meta) #-(or apple-objc-2.0 cocotron-objc) (pref meta :objc_class.super_class)))) (initialize-instance meta :name meta-name :direct-superclasses (list meta-super)) (setf (objc-class-id-foreign-name id) class-name (objc-metaclass-id-foreign-name meta-id) class-name (find-class meta-name) meta) (%defglobal name class) (%defglobal meta-name meta) class))) Set up the class 's ivar_list and instance_size fields , then ;;; add the class to the ObjC runtime. #-(or apple-objc-2.0 cocotron-objc) (defun %add-objc-class (class ivars instance-size) (setf (pref class :objc_class.ivars) ivars (pref class :objc_class.instance_size) instance-size) #+apple-objc (#_objc_addClass class) #+gnu-objc ;; Why would anyone want to create a class without creating a Module ? ;; Rather than ask that vexing question, let's create a Module with one class in it and use # _ _ _ objc_exec_class to add the Module . ;; (I mean "... to add the class", of course. It appears that we have to heap allocate the module , , and ;; module name: the GNU ObjC runtime wants to add the module to a list ;; that it subsequently ignores. (let* ((name (make-cstring "Phony Module")) (symtab (malloc (+ (record-length :objc_symtab) (record-length (:* :void))))) (m (make-record :objc_module :version 8 #|OBJC_VERSION|# :size (record-length :<M>odule) :name name :symtab symtab))) (setf (%get-ptr symtab (record-length :objc_symtab)) (%null-ptr)) (setf (pref symtab :objc_symtab.sel_ref_cnt) 0 (pref symtab :objc_symtab.refs) (%null-ptr) (pref symtab :objc_symtab.cls_def_cnt) 1 (pref symtab :objc_symtab.cat_def_cnt) 0 (%get-ptr (pref symtab :objc_symtab.defs)) class (pref class :objc_class.info) (logior #$_CLS_RESOLV (pref class :objc_class.info))) (#___objc_exec_class m))) #+(or apple-objc-2.0 cocotron-objc) (defun %add-objc-class (class) (#_objc_registerClassPair class)) (let* ((objc-gen-message-args (make-array 10 :fill-pointer 0 :adjustable t))) (defun %objc-gen-message-arg (n) (let* ((len (length objc-gen-message-args))) (do* ((i len (1+ i))) ((> i n) (aref objc-gen-message-args n)) (vector-push-extend (intern (format nil "ARG~d" i)) objc-gen-message-args))))) (defun objc-gen-message-arglist (n) (collect ((args)) (dotimes (i n (args)) (args (%objc-gen-message-arg i))))) ;;; Call get-objc-message-info for all known init messages. (A ;;; message is an "init message" if it starts with the string "init", and has at least one declared method that returns : ID and is not a ;;; protocol method. (defun register-objc-init-messages () (do-interface-dirs (d) (dolist (init (cdb-enumerate-keys (db-objc-methods d) #'(lambda (string) (string= string "init" :end1 (min (length string) 4))))) (process-init-message (get-objc-message-info init))))) (defvar *objc-init-messages-for-init-keywords* (make-hash-table :test #'equal) "Maps from lists of init keywords to dispatch-functions for init messages") (defun send-objc-init-message (instance init-keywords args) (let* ((info (gethash init-keywords *objc-init-messages-for-init-keywords*))) (unless info (let* ((name (lisp-to-objc-init init-keywords)) (name-info (get-objc-message-info name nil))) (unless name-info (error "Unknown ObjC init message: ~s" name)) (setf (gethash init-keywords *objc-init-messages-for-init-keywords*) (setq info name-info)))) (apply (objc-message-info-lisp-name info) instance args))) (defun objc-set->setf (method) (let* ((info (get-objc-message-info method)) (name (objc-message-info-lisp-name info)) (str (symbol-name name)) (value-placeholder-index (position #\: str))) (when (and (> (length str) 4) value-placeholder-index) (let* ((truncated-name (nstring-downcase (subseq (remove #\: str :test #'char= :count 1) 3) :end 1)) (reader-name (if (> (length truncated-name) (decf value-placeholder-index 3)) (nstring-upcase truncated-name :start value-placeholder-index :end (1+ value-placeholder-index)) truncated-name)) (reader (intern reader-name :nextstep-functions))) (eval `(defun (setf ,reader) (value object &rest args) (apply #',name object value args) value)))))) (defun register-objc-set-messages () (do-interface-dirs (d) (dolist (init (cdb-enumerate-keys (db-objc-methods d) #'(lambda (string) (string= string "set" :end1 (min (length string) 3))))) (objc-set->setf init)))) ;;; Return the "canonical" version of P iff it's a known ObjC class (defun objc-class-p (p) (if (typep p 'macptr) (let* ((id (objc-class-id p))) (if id (id->objc-class id))))) ;;; Return the canonical version of P iff it's a known ObjC metaclass (defun objc-metaclass-p (p) (if (typep p 'macptr) (let* ((id (objc-metaclass-id p))) (if id (id->objc-metaclass id))))) ;;; If P is an ObjC instance, return a pointer to its class. ;;; This assumes that all instances are allocated via something that's ;;; ultimately malloc-based. (defun objc-instance-p (p) (when (typep p 'macptr) (let* ((idx (%objc-instance-class-index p))) (if idx (id->objc-class idx))))) (defun objc-private-class-id (classptr) (let* ((info (%get-private-objc-class classptr))) (when info (or (private-objc-class-info-declared-ancestor info) (with-macptrs ((super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass classptr) #-(or apple-objc-2.0 cocotron-objc) (pref classptr :objc_class.super_class))) (loop (when (%null-ptr-p super) (return)) (let* ((id (objc-class-id super))) (if id (return (setf (private-objc-class-info-declared-ancestor info) id)) (%setf-macptr super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass super) #-(or apple-objc-2.0 cocotron-objc) (pref super :objc_class.super_class)))))))))) (defun objc-class-or-private-class-id (classptr) (or (objc-class-id classptr) (objc-private-class-id classptr))) The World 's Most Advanced Operating System keeps getting better ! #+(or apple-objc-2.0 apple-objc) (defun objc-hidden-class-id (classptr) ;; This should only be called on something for which OBJC-CLASS-ID and OBJC-PRIVATE-CLASS-ID ;; both return false. If CLASSPTR looks enough like an ObjC class , register it as a private class and return ;; the private class ID. ;; This wouldn't be necessary if the ObjC class hierarchy wasn't broken. (unless (%null-ptr-p classptr) (with-macptrs (meta metameta) (safe-get-ptr classptr meta) (unless (%null-ptr-p meta) (safe-get-ptr meta metameta) (when (and (eql metameta (find-class 'ns::+ns-object nil)) (%objc-metaclass-p meta)) (let* ((classptr (%inc-ptr classptr 0))) (install-foreign-objc-class classptr nil) (objc-private-class-id classptr))))))) Apple invented tags in 10.7 , in which the CF version number was 635.0d0 (defloadvar *objc-runtime-uses-tags* (>= #&kCFCoreFoundationVersionNumber 635.0d0)) (defun tagged-objc-instance-p (p) (when *objc-runtime-uses-tags* (let* ((tag (logand (the natural (%ptr-to-int p)) #xf))) (declare (fixnum tag)) (if (logbitp 0 tag) tag)))) (defun %objc-instance-class-index (p) (unless (%null-ptr-p p) (let* ((tag (tagged-objc-instance-p p))) (if tag (objc-tagged-instance-class-index p tag) (if (with-macptrs (q) (safe-get-ptr p q) (not (%null-ptr-p q))) (with-macptrs ((parent (#_object_getClass p))) (or (objc-class-id parent) (objc-private-class-id parent) #+(or apple-objc-2.0 apple-objc) (objc-hidden-class-id parent)))))))) ;;; If an instance, return (values :INSTANCE <class>) ;;; If a class, return (values :CLASS <class>). ;;; If a metaclass, return (values :METACLASS <metaclass>). ;;; Else return (values NIL NIL). (defun objc-object-p (p) (let* ((instance-p (objc-instance-p p))) (if instance-p (values :instance instance-p) (let* ((class-p (objc-class-p p))) (if class-p (values :class class-p) (let* ((metaclass-p (objc-metaclass-p p))) (if metaclass-p (values :metaclass metaclass-p) (values nil nil)))))))) ;;; If the class contains an mlist that contains a method that matches ( is EQL to ) the selector , remove the mlist and set its IMP ; return the containing mlist . ;;; If the class doesn't contain any matching mlist, create an mlist with one method slot , initialize the method , and ;;; return the new mlist. Doing it this way ensures ;;; that the objc runtime will invalidate any cached references to the old IMP , at least as far as objc method dispatch is ;;; concerned. #-(or apple-objc-2.0 cocotron-objc) (defun %mlist-containing (classptr selector typestring imp) #-apple-objc (declare (ignore classptr selector typestring imp)) #+apple-objc (%stack-block ((iter 4)) (setf (%get-ptr iter) (%null-ptr)) (loop (let* ((mlist (#_class_nextMethodList classptr iter))) (when (%null-ptr-p mlist) (let* ((mlist (make-record :objc_method_list :method_count 1)) (method (pref mlist :objc_method_list.method_list))) (setf (pref method :objc_method.method_name) selector (pref method :objc_method.method_types) (make-cstring typestring) (pref method :objc_method.method_imp) imp) (return mlist))) (do* ((n (pref mlist :objc_method_list.method_count)) (i 0 (1+ i)) (method (pref mlist :objc_method_list.method_list) (%incf-ptr method (record-length :objc_method)))) ((= i n)) (declare (fixnum i n)) (when (eql selector (pref method :objc_method.method_name)) (#_class_removeMethods classptr mlist) (setf (pref method :objc_method.method_imp) imp) (return-from %mlist-containing mlist))))))) (defun %add-objc-method (classptr selector typestring imp) #+(or apple-objc-2.0 cocotron-objc) (with-cstrs ((typestring typestring)) (or (not (eql #$NO (#_class_addMethod classptr selector imp typestring))) (let* ((m (if (objc-metaclass-p classptr) (#_class_getClassMethod classptr selector) (#_class_getInstanceMethod classptr selector)))) (if (not (%null-ptr-p m)) (#_method_setImplementation m imp) (error "Can't add ~s method to class ~s" selector typestring))))) #-(or apple-objc-2.0 cocotron-objc) (progn #+apple-objc (#_class_addMethods classptr (%mlist-containing classptr selector typestring imp)) #+gnu-objc ;;; We have to do this ourselves, and have to do it with the runtime ;;; mutex held. (with-gnu-objc-mutex-locked (*gnu-objc-runtime-mutex*) (let* ((ctypestring (make-cstring typestring)) (new-mlist nil)) (with-macptrs ((method (external-call "search_for_method_in_list" :address (pref classptr :objc_class.methods) :address selector :address))) (when (%null-ptr-p method) (setq new-mlist (make-record :objc_method_list :method_count 1)) (%setf-macptr method (pref new-mlist :objc_method_list.method_list))) (setf (pref method :objc_method.method_name) selector (pref method :objc_method.method_types) ctypestring (pref method :objc_method.method_imp) imp) (if new-mlist (external-call "GSObjCAddMethods" :address classptr :address new-mlist :void) (external-call "__objc_update_dispatch_table_for_class" :address classptr :void))))))) (defvar *lisp-objc-methods* (make-hash-table :test #'eq)) (defstruct lisp-objc-method class-descriptor sel typestring class-p ;t for class methods imp ; callback ptr ) (defun %add-lisp-objc-method (m) (let* ((class (%objc-class-classptr (lisp-objc-method-class-descriptor m))) (sel (%get-selector (lisp-objc-method-sel m))) (typestring (lisp-objc-method-typestring m)) (imp (lisp-objc-method-imp m))) (%add-objc-method (if (lisp-objc-method-class-p m) (#_object_getClass class) ;class methods go on the metaclass class) sel typestring imp))) (def-ccl-pointers add-objc-methods () (maphash #'(lambda (impname m) (declare (ignore impname)) (%add-lisp-objc-method m)) *lisp-objc-methods*)) (defun %define-lisp-objc-method (impname classname selname typestring imp &optional class-p) (%add-lisp-objc-method (setf (gethash impname *lisp-objc-methods*) (make-lisp-objc-method :class-descriptor (load-objc-class-descriptor classname) :sel (load-objc-selector selname) :typestring typestring :imp imp :class-p class-p))) (if (string= selname "set" :end1 (min (length selname) 3)) (objc-set->setf selname)) impname) ;;; If any of the argspecs denote a value of type :<BOOL>, push an ;;; appropriate SETQ on the front of the body. (Order doesn't matter.) (defun coerce-foreign-boolean-args (argspecs body) (do* ((argspecs argspecs (cddr argspecs)) (type (car argspecs) (car argspecs)) (var (cadr argspecs) (cadr argspecs))) ((null argspecs) body) (when (eq type :<BOOL>) (push `(setq ,var (not (eql ,var 0))) body)))) (defun lisp-boolean->foreign-boolean (form) (let* ((val (gensym))) `((let* ((,val (progn ,@form))) (if (and ,val (not (eql 0 ,val))) 1 0))))) ;;; Return, as multiple values: ;;; the selector name, as a string ;;; the ObjC class name, as a string ;;; the foreign result type ;;; the foreign argument type/argument list ;;; the body ;;; a string which encodes the foreign result and argument types (defun parse-objc-method (selector-arg class-arg body) (let* ((class-name (objc-class-name-string class-arg)) (selector-form selector-arg) (selector nil) (argspecs nil) (resulttype nil) (struct-return nil)) (flet ((bad-selector (why) (error "Can't parse method selector ~s : ~a" selector-arg why))) (typecase selector-form (string (let* ((specs (pop body))) (setq selector selector-form) (if (evenp (length specs)) (setq argspecs specs resulttype :id) (setq resulttype (car (last specs)) argspecs (butlast specs))))) (cons ;sic (setq resulttype (pop selector-form)) (unless (consp selector-form) (bad-selector "selector-form not a cons")) (ccl::collect ((components) (specs)) ;; At this point, selector-form should be either a list of ;; a single symbol (a lispified version of the selector name ;; of a selector that takes no arguments) or a list of keyword/ ;; variable pairs. Each keyword is a lispified component of ;; the selector name; each "variable" is either a symbol ;; or a list of the form (<foreign-type> <symbol>), where ;; an atomic variable is shorthand for (:id <symbol>). (if (and (null (cdr selector-form)) (car selector-form) (typep (car selector-form) 'symbol) (not (typep (car selector-form) 'keyword))) (components (car selector-form)) (progn (unless (evenp (length selector-form)) (bad-selector "Odd length")) (do* ((s selector-form (cddr s)) (comp (car s) (car s)) (var (cadr s) (cadr s))) ((null s)) (unless (typep comp 'keyword) (bad-selector "not a keyword")) (components comp) (cond ((atom var) (unless (and var (symbolp var)) (bad-selector "not a non-null symbol")) (specs :id) (specs var)) ((and (consp (cdr var)) (null (cddr var)) (cadr var) (symbolp (cadr var))) (specs (car var)) (specs (cadr var))) (t (bad-selector "bad variable/type clause")))))) (setq argspecs (specs) selector (lisp-to-objc-message (components))))) (t (bad-selector "general failure"))) ;; If the result type is of the form (:STRUCT <typespec> <name>), make < name > be the first argument . (when (and (consp resulttype) (eq (car resulttype) :struct)) (destructuring-bind (typespec name) (cdr resulttype) (let* ((rtype (%foreign-type-or-record typespec))) (if (and (typep name 'symbol) (typep rtype 'foreign-record-type)) (setq struct-return name resulttype (unparse-foreign-type rtype)) (bad-selector "Bad struct return type"))))) (values selector class-name resulttype argspecs body (do* ((argtypes ()) (argspecs argspecs (cddr argspecs))) ((null argspecs) (encode-objc-method-arglist `(:id :<sel> ,@(nreverse argtypes)) resulttype)) (push (car argspecs) argtypes)) struct-return)))) (defun objc-method-definition-form (class-p selector-arg class-arg body env) (multiple-value-bind (selector-name class-name resulttype argspecs body typestring struct-return) (parse-objc-method selector-arg class-arg body) (%declare-objc-method selector-name class-name class-p (concise-foreign-type resulttype) (collect ((argtypes)) (do* ((argspecs argspecs (cddr argspecs))) ((null argspecs) (mapcar #'concise-foreign-type (argtypes))) (argtypes (car argspecs))))) (let* ((self (intern "SELF"))) (multiple-value-bind (body decls) (parse-body body env) (unless class-p (push `(%set-objc-instance-type ,self) body)) (setq body (coerce-foreign-boolean-args argspecs body)) (if (eq resulttype :<BOOL>) (setq body (lisp-boolean->foreign-boolean body))) (let* ((impname (intern (format nil "~c[~a ~a]" (if class-p #\+ #\-) class-name selector-name))) (_cmd (intern "_CMD")) (super (gensym "SUPER")) (params `(:id ,self :<sel> ,_cmd))) (when struct-return (push struct-return params)) (setq params (nconc params argspecs)) `(progn (defcallback ,impname (:without-interrupts nil #+(and openmcl-native-threads (or apple-objc cocotron-objc)) :propagate-throw #+(and openmcl-native-threads (or apple-objc cocotron-objc)) objc-propagate-throw ,@params ,resulttype) (declare (ignorable ,_cmd)) ,@decls (rlet ((,super :objc_super #+(or apple-objc cocotron-objc) :receiver #+gnu-objc :self ,self #+(or apple-objc-2.0 cocotron-objc) :super_class #-(or apple-objc-2.0 cocotron-objc) :class ,@(if class-p #+(or apple-objc-2.0 cocotron-objc) `((external-call "class_getSuperclass" :address (external-call "object_getClass" :address (@class ,class-name) :address))) #-(or apple-objc-2.0 cocotron-objc) `((pref (pref (@class ,class-name) #+apple-objc :objc_class.isa #+gnu-objc :objc_class.class_pointer) :objc_class.super_class)) #+(or apple-objc-2.0 cocotron-objc) `((external-call "class_getSuperclass" :address (@class ,class-name) :address)) #-(or apple-objc-2.0 cocotron-objc) `((pref (@class ,class-name) :objc_class.super_class))))) (macrolet ((send-super (msg &rest args &environment env) (make-optimized-send nil msg args env nil ',super ,class-name)) (send-super/stret (s msg &rest args &environment env) (make-optimized-send nil msg args env s ',super ,class-name))) ,@body))) (%define-lisp-objc-method ',impname ,class-name ,selector-name ,typestring ,impname ,class-p))))))) (defmacro define-objc-method (&whole w (selector-arg class-arg) &body body &environment env) (warn-about-deprecated-objc-bridge-construct w "OBJC:DEFMETHOD") (objc-method-definition-form nil selector-arg class-arg body env)) (defmacro define-objc-class-method (&whole w (selector-arg class-arg) &body body &environment env) (warn-about-deprecated-objc-bridge-construct w "OBJC:DEFMETHOD") (objc-method-definition-form t selector-arg class-arg body env)) (declaim (inline %objc-struct-return)) (defun %objc-struct-return (return-temp size value) (unless (eq return-temp value) (#_memmove return-temp value size))) (defvar *objc-error-return-condition* 'condition "Type of conditions to be caught by objc:defmethod and resignalled as objc exceptions, allowing handlers for them to safely take a non-local exit despite possible intervening ObjC frames. The resignalling unwinds the stack before the handler is invoked, which can be a problem for some handlers.") (defmacro objc:defmethod (name (self-arg &rest other-args) &body body &environment env) (collect ((arglist) (arg-names) (arg-types) (bool-args) (type-assertions)) (let* ((result-type nil) (struct-return-var nil) (struct-return-size nil) (selector nil) (class-p nil) (objc-class-name nil)) (if (atom name) (setq selector (string name) result-type :id) (setq selector (string (car name)) result-type (concise-foreign-type (or (cadr name) :id)))) (destructuring-bind (self-name lisp-class-name) self-arg (arg-names self-name) (arg-types :id) ;; Hack-o-rama (let* ((lisp-class-name (string lisp-class-name))) (if (eq (schar lisp-class-name 0) #\+) (setq class-p t lisp-class-name (subseq lisp-class-name 1))) (setq objc-class-name (lisp-to-objc-classname lisp-class-name))) (let* ((rtype (parse-foreign-type result-type))) (when (typep rtype 'foreign-record-type) (setq struct-return-var (gensym)) (setq struct-return-size (ceiling (foreign-type-bits rtype) 8)) (arglist struct-return-var))) (arg-types :<SEL>) (arg-names nil) ;newfangled (dolist (arg other-args) (if (atom arg) (progn (arg-types :id) (arg-names arg)) (destructuring-bind (arg-name arg-type) arg (let* ((concise-type (concise-foreign-type arg-type))) (unless (eq concise-type :id) (let* ((ftype (parse-foreign-type concise-type))) (if (typep ftype 'foreign-pointer-type) (setq ftype (foreign-pointer-type-to ftype))) (if (and (typep ftype 'foreign-record-type) (foreign-record-type-name ftype)) (type-assertions `(%set-macptr-type ,arg-name (foreign-type-ordinal (load-time-value (%foreign-type-or-record ,(foreign-record-type-name ftype))))))))) (arg-types concise-type) (arg-names arg-name))))) (let* ((arg-names (arg-names)) (arg-types (arg-types))) (do* ((names arg-names) (types arg-types)) ((null types) (arglist result-type)) (let* ((name (pop names)) (type (pop types))) (arglist type) (arglist name) (if (eq type :<BOOL>) (bool-args `(setq ,name (not (eql ,name 0))))))) (let* ((impname (intern (format nil "~c[~a ~a]" (if class-p #\+ #\-) objc-class-name selector))) (typestring (encode-objc-method-arglist arg-types result-type)) (signature (cons result-type (cddr arg-types)))) (multiple-value-bind (body decls) (parse-body body env) (setq body `((progn ,@(bool-args) ,@(type-assertions) ,@body))) (if (eq result-type :<BOOL>) (setq body `((%coerce-to-bool ,@body)))) (when struct-return-var (setq body `((%objc-struct-return ,struct-return-var ,struct-return-size ,@body))) (setq body `((flet ((struct-return-var-function () ,struct-return-var)) (declaim (inline struct-return-var-function)) ,@body))) (setq body `((macrolet ((objc:returning-foreign-struct ((var) &body body) `(let* ((,var (struct-return-var-function))) ,@body))) ,@body)))) (setq body `((flet ((call-next-method (&rest args) (declare (dynamic-extent args)) (apply (function ,(if class-p '%call-next-objc-class-method '%call-next-objc-method)) ,self-name (@class ,objc-class-name) (@selector ,selector) ',signature args))) (declare (inline call-next-method)) ,@body))) `(progn (%declare-objc-method ',selector ',objc-class-name ,class-p ',result-type ',(cddr arg-types)) (defcallback ,impname ( :propagate-throw objc-propagate-throw ,@(arglist)) (declare (ignorable ,self-name) (unsettable ,self-name) ,@(unless class-p `((type ,lisp-class-name ,self-name)))) ,@decls ,@body) (%define-lisp-objc-method ',impname ,objc-class-name ,selector ,typestring ,impname ,class-p))))))))) (defun class-get-instance-method (class sel) #+(or apple-objc cocotron-objc) (#_class_getInstanceMethod class sel) #+gnu-objc (#_class_get_instance_method class sel)) (defun class-get-class-method (class sel) #+(or apple-objc cocotron-objc) (#_class_getClassMethod class sel) #+gnu-objc (#_class_get_class_method class sel)) (defun method-get-number-of-arguments (m) #+(or apple-objc cocotron-objc) (#_method_getNumberOfArguments m) #+gnu-objc (#_method_get_number_of_arguments m)) (defloadvar *nsstring-newline* #@" ") ;;; Execute BODY with an autorelease pool (defmacro with-autorelease-pool (&body body) (let ((pool-temp (gensym))) `(let ((,pool-temp (create-autorelease-pool))) (unwind-protect (progn ,@body) (release-autorelease-pool ,pool-temp))))) #+apple-objc-2.0 New ! ! ! Improved ! ! ! At best , half - right ! ! ! (defmacro with-ns-exceptions-as-errors (&body body) `(progn ,@body)) The NSHandler2 type was visible in Tiger headers , but it 's not in the Leopard headers . #+(and apple-objc (not apple-objc-2.0)) (def-foreign-type #>NSHandler2_private (:struct #>NSHandler2_private (:_state :jmp_buf) (:_exception :address) (:_others :address) (:_thread :address) (:_reserved1 :address))) #-apple-objc-2.0 (defmacro with-ns-exceptions-as-errors (&body body) #+apple-objc (let* ((nshandler (gensym)) (cframe (gensym))) `(rletZ ((,nshandler #>NSHandler2_private)) (unwind-protect (progn (external-call "__NSAddHandler2" :address ,nshandler :void) (catch ,nshandler (with-c-frame ,cframe (%associate-jmp-buf-with-catch-frame ,nshandler (%fixnum-ref (%current-tcr) target::tcr.catch-top) ,cframe) (progn ,@body)))) (check-ns-exception ,nshandler)))) #+cocotron-objc (let* ((xframe (gensym)) (cframe (gensym))) `(rletZ ((,xframe #>NSExceptionFrame)) (unwind-protect (progn (external-call "__NSPushExceptionFrame" :address ,xframe :void) (catch ,xframe (with-c-frame ,cframe (%associate-jmp-buf-with-catch-frame ,xframe (%fixnum-ref (%current-tcr) (- target::tcr.catch-top target::tcr-bias)) ,cframe) (progn ,@body)))) (check-ns-exception ,xframe)))) #+gnu-objc `(progn ,@body) ) (defvar *condition-id-map* (make-id-map) "Map lisp conditions to small integers") #+(and apple-objc (not apple-objc-2.0)) (defun check-ns-exception (nshandler) (with-macptrs ((exception (external-call "__NSExceptionObjectFromHandler2" :address nshandler :address))) (if (%null-ptr-p exception) (external-call "__NSRemoveHandler2" :address nshandler :void) (if (typep exception 'encapsulated-lisp-throw) (apply #'%throw (with-slots (id) exception (id-map-object *condition-id-map* id))) (error (ns-exception->lisp-condition (%inc-ptr exception 0))))))) #+cocotron-objc (defun check-ns-exception (xframe) (with-macptrs ((exception (pref xframe #>NSExceptionFrame.exception))) (if (%null-ptr-p exception) (external-call "__NSPopExceptionFrame" :address xframe :void) (if (typep exception 'encapsulated-lisp-throw) (apply #'%throw (with-slots (id) exception (id-map-object *condition-id-map* id))) (error (ns-exception->lisp-condition (%inc-ptr exception 0)))))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/objc-bridge/objc-runtime.lisp
lisp
Package : CCL -*- 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. systems. object given its name. We need to be able to ask at runtime whether a given object conforms to a protocol in order to know when a protocol method is ambiguous, at least when the message contains ambiguous methods and some methods are protocol methods I'm not sure we still need to avoid #_objc_getProtocol. These are NOT lisp classes; we mostly want to keep track of them so that we can pretend that instances of them are instances of some known (declared) superclass. multitheaded. (A lot of other things, including the ObjC runtime, seem to have already noticed.) in the thread that's going to process events. Looking up a symbol in the library should cause it to be initialized If the BOOL variable NSDebugEnabled can be found, ensure It's not clear how it gets set to a non-zero value.) We may need to call #_NSInitializeProcess so on standalone startup, too, and would have to have heap-allocated the string vector and its strings. (#_GetCurrentEventQueue) trying to process them. Shouldn't really be GNU-objc-specific. fix this fix this consists of a pointer to the NSConstantString class (which the global "_NSConstantStringClassReference" conveniently refers to), a terminated, but doesn't hurt) and the length of that string (not counting any #\Nul.) The global reference to the "NSConstantString" class allows us to compiler does. Catch frames are allocated on a stack, so it's OK to pass their addresses around to foreign code. subl $16,%esp movl %eax,(%esp) movl %edi,4(%esp) call *%ebx jump through some hoops (a jmp_buf) and wind up throwing to a lisp catch tag. These constants (offsets in the jmp_buf structure) come from (defconstant JMP-ctr #x5c "count register jmp_buf offset") (defconstant JMP-ctr #x5c "count register jmp_buf offset") header files ? I think that we know where these constants come from. instruction copies the address of the trampoline callback from r14 but since r4 isn't saved in a jmp_buf, we have to do this copy. place. This isn't used; it isn't right, either. call *%rbx wind up calling THROW-TO-CATCH-FRAME with the specified catch an empty C stack frame from which the callback will be called. since they're so volatile and everything. fixnum-aligned When starting up an image that's had ObjC classes in it, all of those canonical classes (and metaclasses) will have had their type of those classes may be bogus. The hash tables (objc-class/metaclass-map) should be empty. For each class that -had- had an assigned ID, determine its ObjC class name, and ask ObjC where (if anywhere) the class is now. If we get a non-null answer, revive the class pointer and set its address appropriately, then add an entry to the hash-table; this will retain the same ID. and (@selector ...) early. Ensure that any addon frameworks are loaded. resolving those foreign classes that existed in the old image and still exist in the new. If the class is valid and the metaclass is still unmapped, set the metaclass pointer's address and map it. class table; that's an artifact of the current implementation. Finally, iterate over all classes in the runtime world. Register any class that's not found in the class map as a "private" ObjC class. Iterate over all classes in the runtime. Those that aren't already registered will get identified as "private" (undeclared) ObjC classes. Note that this means that if an application bundle Tiger-specific classes will not be magically integrated A development envronment might want to provide such a it would need access to Panther class declarations, and - in the general case - a standalone application doesn't necessarily have access to the interface database. If not mapped, map the superclass (if there is one.) class wrapper if so. It's important (here and when initializing the class below) to use the "canonical" (registered) version of the class, since some don't want to violate that assumption; it'll be easier to revive a saved image if we don't have with. stack-allocated NSConstantString instance (made from *NSConstantString-class*, CSTRING and LEN). Make a persistent (heap-allocated) NSConstantString. Class declarations It's hard (and questionable) to allow ivars here. Registering named objc classes. We'd presumably cache this result somewhere, so we'd only do the lookup once per session (in general.) This isn't quite the inverse operation of LOOKUP-OBJC-CLASS: it returns a simple C string. and can be applied to a class or any instance (returning the class name.) method names. They can vary from session to session, but within a session, all methods with a given name (e.g, "init") will be do n't bother resolving it . The following conversions are currently done: - NIL => (%null-ptr) - Lisp numbers => SINGLE-FLOAT when possible This is generally a bad idea; it forces us to box intermediate pointer arguments in order to typecase on them, and it's not clear to me that it offers much in the way of additional expressiveness. Boolean Return Hackery ;;;; Convert a foreign object X to T or NIL fact that a selector is really just a canonicalized, interned C string containing the message. (This is an admitted modularity violation; there's a more portable but slower way to do this if we ever need to.) there'd have to be some macrology to handle common cases, since we want the compiler to see all of the args in a foreign call. have been talking about. A method that returns a structure does so by platform-dependent argument, etc.), but whether or not it's actually done that way depends on the platform and on the structure type. The special CCL::FOREIGN-TYPE-DATA) which describes some static attributes of the foreign type system on the target platform and contains some function can be used to determine whether or not the "invisible foreign type; another function in *TARGET-FTD* can be used to construct a foreign function call form that handles structure-return and structure-types-as-arguments details. In the supported x86-64 ABIs often use more complicated structure return OBJC-MESSAGE-SEND-STRET to send any message that returns a structure or union, regardless of how that structure return is actually implemented. its first argument is a pointer to a structure of type objc_super {self, the defining class's superclass}. It only makes sense to use this inside an objc method. Send to superclass method, returning a structure. See above. receiver, selptr receiver, selptr receiver, selptr receiver, selptr Using VALUES here is a hack: the multiple-value returning machinery clobbers imm0. strictly increasing. Just to make things even more confusing: once we've filled in the sense (even though it conflicts with the last offset in *objc-gpr-offsets* (assigned to R10), but we then have to add this constant to the memory offset. Should be some way of noting "longness". vector of method lists. In GNU ObjC, method lists are linked together. Make a meta-class object (with no instance variables or class methods.) No way to tell in Objc-2.0. Does anything care ? Create (malloc) class and metaclass objects with the specified instance, but don't install the class in the ObjC runtime system (yet): we don't know anything about its ivars and don't know how big instances will be yet. If an ObjC class with this name already exists, we're very confused; check for that case and error out if it occurs. add the class to the ObjC runtime. Why would anyone want to create a class without creating a Module ? Rather than ask that vexing question, let's create a Module with (I mean "... to add the class", of course. module name: the GNU ObjC runtime wants to add the module to a list that it subsequently ignores. OBJC_VERSION Call get-objc-message-info for all known init messages. (A message is an "init message" if it starts with the string "init", protocol method. Return the "canonical" version of P iff it's a known ObjC class Return the canonical version of P iff it's a known ObjC metaclass If P is an ObjC instance, return a pointer to its class. This assumes that all instances are allocated via something that's ultimately malloc-based. This should only be called on something for which OBJC-CLASS-ID and OBJC-PRIVATE-CLASS-ID both return false. the private class ID. This wouldn't be necessary if the ObjC class hierarchy wasn't broken. If an instance, return (values :INSTANCE <class>) If a class, return (values :CLASS <class>). If a metaclass, return (values :METACLASS <metaclass>). Else return (values NIL NIL). If the class contains an mlist that contains a method that return the containing mlist . If the class doesn't contain any matching mlist, create return the new mlist. Doing it this way ensures that the objc runtime will invalidate any cached references concerned. We have to do this ourselves, and have to do it with the runtime mutex held. t for class methods callback ptr class methods go on the metaclass If any of the argspecs denote a value of type :<BOOL>, push an appropriate SETQ on the front of the body. (Order doesn't matter.) Return, as multiple values: the selector name, as a string the ObjC class name, as a string the foreign result type the foreign argument type/argument list the body a string which encodes the foreign result and argument types sic At this point, selector-form should be either a list of a single symbol (a lispified version of the selector name of a selector that takes no arguments) or a list of keyword/ variable pairs. Each keyword is a lispified component of the selector name; each "variable" is either a symbol or a list of the form (<foreign-type> <symbol>), where an atomic variable is shorthand for (:id <symbol>). If the result type is of the form (:STRUCT <typespec> <name>), Hack-o-rama newfangled Execute BODY with an autorelease pool
Copyright 2002 - 2009 Clozure Associates distributed under the License is distributed on an " AS IS " BASIS , (in-package "CCL") Utilities for interacting with the Apple / GNU Objective - C runtime (eval-when (:compile-toplevel :load-toplevel :execute) #+darwin-target (pushnew :apple-objc *features*) #+(and darwin-target 64-bit-target) (pushnew :apple-objc-2.0 *features*) #+win32-target (pushnew :cocotron-objc *features*) #-(or darwin-target win32-target) (pushnew :gnu-objc *features*)) (eval-when (:compile-toplevel :load-toplevel :execute) (set-dispatch-macro-character #\# #\@ (nfunction |objc-#@-reader| (lambda (stream subchar numarg) (declare (ignore subchar numarg)) (let* ((string (read stream))) (unless *read-suppress* (check-type string string) `(@ ,string))))))) (eval-when (:compile-toplevel :execute) #+(or apple-objc cocotron-objc) (use-interface-dir :cocoa) #+gnu-objc (use-interface-dir :gnustep)) (eval-when (:compile-toplevel :load-toplevel :execute) (require "OBJC-PACKAGE") (require "NAME-TRANSLATION") (require "OBJC-CLOS")) (defconstant +cgfloat-zero+ #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 0.0d0 #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 0.0f0) (deftype cgfloat () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 'double-float #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) 'single-float) (deftype cg-float () 'cgfloat) (deftype nsuinteger () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(unsigned-byte 64) #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(unsigned-byte 32)) (deftype nsinteger () #+(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(signed-byte 64) #-(and (or apple-objc-2.0 cocotron-objc) 64-bit-target) '(signed-byte 32)) (defloadvar *NSApp* nil ) Apple ObjC 2.0 provides ( # _ objc_getProtocol name ) . In other runtimes , there does n't seem to be any way to find a Protocol (defvar *objc-protocols* (make-hash-table :test #'equal)) (defstruct objc-protocol name address) (defun clear-objc-protocols () (maphash #'(lambda (name proto) (declare (ignore name)) (setf (objc-protocol-address proto) nil)) *objc-protocols*)) (defun lookup-objc-protocol (name) (values (gethash name *objc-protocols*))) (defun %get-objc-protocol (name) (let ((p (lookup-objc-protocol name))) (if p (objc-protocol-address p) (error "No Objective-C protocol named ~s" name)))) (defun %add-objc-protocol (class protocol) (when (= (#_class_addProtocol class protocol) #$YES) protocol)) (defun ensure-objc-classptr-resolved (classptr) #-gnu-objc (declare (ignore classptr)) #+gnu-objc (unless (logtest #$_CLS_RESOLV (pref classptr :objc_class.info)) (external-call "__objc_resolve_class_links" :void))) (defstruct private-objc-class-info name declared-ancestor) (defun compute-objc-direct-slots-from-info (info class) (let* ((ns-package (find-package "NS"))) (mapcar #'(lambda (field) (let* ((name (compute-lisp-name (unescape-foreign-name (foreign-record-field-name field)) ns-package)) (type (foreign-record-field-type field)) (offset (progn (ensure-foreign-type-bits type) (foreign-record-field-offset field)))) (make-instance 'foreign-direct-slot-definition :initfunction #'false :initform nil :name name :foreign-type type :class class :bit-offset offset :allocation :instance))) (db-objc-class-info-ivars info)))) (defun %ptr< (x y) (< (the (unsigned-byte #+64-bit-target 64 #+32-bit-target 32) (%ptr-to-int x)) (the (unsigned-byte #+64-bit-target 64 #+32-bit-target 32) (%ptr-to-int Y)))) (let* ((objc-class-map (make-hash-table :test #'eql :size 1024)) (objc-metaclass-map (make-hash-table :test #'eql :size 1024)) (private-objc-classes (make-hash-table :test #'eql :size 2048)) (objc-class-lock (make-lock)) (next-objc-class-id 0) (next-objc-metaclass-id 0) (class-table-size 1024) (c (make-array class-table-size)) (m (make-array class-table-size)) (cw (make-array class-table-size :initial-element nil)) (mw (make-array class-table-size :initial-element nil)) (csv (make-array class-table-size)) (msv (make-array class-table-size)) (class-id->metaclass-id (make-array class-table-size :initial-element nil)) (class-foreign-names (make-array class-table-size)) (metaclass-foreign-names (make-array class-table-size)) (class-id->ordinal (make-array class-table-size :initial-element nil)) (metaclass-id->ordinal (make-array class-table-size :initial-element nil)) ) (flet ((grow-vectors () (let* ((old-size class-table-size) (new-size (* 2 old-size))) (declare (fixnum old-size new-size)) (macrolet ((extend (v) `(setq ,v (%extend-vector old-size ,v new-size)))) (extend c) (extend m) (extend cw) (extend mw) (fill cw nil :start old-size :end new-size) (fill mw nil :start old-size :end new-size) (extend csv) (extend msv) (extend class-id->metaclass-id) (fill class-id->metaclass-id nil :start old-size :end new-size) (extend class-foreign-names) (extend metaclass-foreign-names) (extend class-id->ordinal) (extend metaclass-id->ordinal) (fill class-id->ordinal nil :start old-size :end new-size) (fill metaclass-id->ordinal nil :start old-size :end new-size)) (setq class-table-size new-size)))) (flet ((assign-next-class-id () (let* ((id next-objc-class-id)) (if (= (incf next-objc-class-id) class-table-size) (grow-vectors)) id)) (assign-next-metaclass-id () (let* ((id next-objc-metaclass-id)) (if (= (incf next-objc-metaclass-id) class-table-size) (grow-vectors)) id))) (defun id->objc-class (i) (svref c i)) (defun (setf id->objc-class) (new i) (setf (svref c i) new)) (defun id->objc-metaclass (i) (svref m i)) (defun (setf id->objc-metaclass) (new i) (setf (svref m i) new)) (defun id->objc-class-wrapper (i) (svref cw i)) (defun (setf id->objc-class-wrapper) (new i) (setf (svref cw i) new)) (defun id->objc-metaclass-wrapper (i) (svref mw i)) (defun (setf id->objc-metaclass-wrapper) (new i) (setf (svref mw i) new)) (defun id->objc-class-slots-vector (i) (svref csv i)) (defun (setf id->objc-class-slots-vector) (new i) (setf (svref csv i) new)) (defun id->objc-metaclass-slots-vector (i) (svref msv i)) (defun (setf id->objc-metaclass-slots-vector) (new i) (setf (svref msv i) new)) (defun objc-class-id-foreign-name (i) (svref class-foreign-names i)) (defun (setf objc-class-id-foreign-name) (new i) (setf (svref class-foreign-names i) new)) (defun objc-metaclass-id-foreign-name (i) (svref metaclass-foreign-names i)) (defun (setf objc-metaclass-id-foreign-name) (new i) (setf (svref metaclass-foreign-names i) new)) (defun %clear-objc-class-maps () (with-lock-grabbed (objc-class-lock) (clrhash objc-class-map) (clrhash objc-metaclass-map) (clrhash private-objc-classes))) (flet ((install-objc-metaclass (meta) (or (gethash meta objc-metaclass-map) (let* ((id (assign-next-metaclass-id)) (meta (%inc-ptr meta 0))) (setf (gethash meta objc-metaclass-map) id) (setf (svref m id) meta (svref msv id) (make-objc-metaclass-slots-vector meta) (svref metaclass-id->ordinal id) (%next-class-ordinal)) id)))) (defun register-objc-class (class) "ensure that the class is mapped to a small integer and associate a slots-vector with it." (with-lock-grabbed (objc-class-lock) (ensure-objc-classptr-resolved class) (or (gethash class objc-class-map) (let* ((id (assign-next-class-id)) (class (%inc-ptr class 0)) (meta (#_object_getClass class))) (setf (gethash class objc-class-map) id) (setf (svref c id) class (svref csv id) (make-objc-class-slots-vector class) (svref class-id->metaclass-id id) (install-objc-metaclass meta) (svref class-id->ordinal id) (%next-class-ordinal)) id))))) (defun objc-class-id (class) (gethash class objc-class-map)) (defun objc-metaclass-id (meta) (gethash meta objc-metaclass-map)) (defun objc-class-id->objc-metaclass-id (class-id) (svref class-id->metaclass-id class-id)) (defun objc-class-id->objc-metaclass (class-id) (svref m (svref class-id->metaclass-id class-id))) (defun objc-class-id->ordinal (i) (svref class-id->ordinal i)) (defun (setf objc-class-id->ordinal) (new i) (setf (svref class-id->ordinal i) new)) (defun objc-metaclass-id->ordinal (m) (svref metaclass-id->ordinal m)) (defun (setf objc-metaclass-id->ordinal) (new m) (setf (svref class-id->ordinal m) new)) (defun objc-class-map () objc-class-map) (defun %objc-class-count () next-objc-class-id) (defun objc-metaclass-map () objc-metaclass-map) (defun %objc-metaclass-count () next-objc-metaclass-id) (defun %register-private-objc-class (c name) (setf (gethash c private-objc-classes) (make-private-objc-class-info :name name))) (defun %get-private-objc-class (c) (gethash c private-objc-classes)) (defun private-objc-classes () private-objc-classes)))) (pushnew #'%clear-objc-class-maps *save-exit-functions* :test #'eq :key #'function-name) (defun do-all-objc-classes (f) (maphash #'(lambda (ptr id) (declare (ignore ptr)) (funcall f (id->objc-class id))) (objc-class-map))) (defun canonicalize-registered-class (c) (let* ((id (objc-class-id c))) (if id (id->objc-class id) (error "Class ~S isn't recognized." c)))) (defun canonicalize-registered-metaclass (m) (let* ((id (objc-metaclass-id m))) (if id (id->objc-metaclass id) (error "Class ~S isn't recognized." m)))) (defun canonicalize-registered-class-or-metaclass (x) (if (%objc-metaclass-p x) (canonicalize-registered-metaclass x) (canonicalize-registered-class x))) Open shared libs . #+(or darwin-target cocotron-objc) (progn (defloadvar *cocoa-event-process* *initial-process*) (defun current-ns-thread () (with-cstrs ((class-name "NSThread") (message-selector-name "currentThread")) (let* ((nsthread-class (#_objc_lookUpClass class-name)) (message-selector (#_sel_getUid message-selector-name))) (#_objc_msgSend nsthread-class message-selector) nil))) (defun create-void-nsthread () Create an NSThread which does nothing but exit . This 'll help to convince the AppKit that we 're (with-cstrs ((thread-class-name "NSThread") (pool-class-name "NSAutoreleasePool") (thread-message-selector-name "detachNewThreadSelector:toTarget:withObject:") (exit-selector-name "class") (alloc-selector-name "alloc") (init-selector-name "init") (release-selector-name "release")) (let* ((nsthread-class (#_objc_lookUpClass thread-class-name)) (pool-class (#_objc_lookUpClass pool-class-name)) (thread-message-selector (#_sel_getUid thread-message-selector-name)) (exit-selector (#_sel_getUid exit-selector-name)) (alloc-selector (#_sel_getUid alloc-selector-name)) (init-selector (#_sel_getUid init-selector-name)) (release-selector (#_sel_getUid release-selector-name)) (pool (#_objc_msgSend (#_objc_msgSend pool-class alloc-selector) init-selector))) (unwind-protect (#_objc_msgSend nsthread-class thread-message-selector :address exit-selector :address nsthread-class :address (%null-ptr)) (#_objc_msgSend pool release-selector)) nil))) (defun load-cocoa-framework () (call-in-initial-process #'(lambda () We need to load and " initialize " the CoreFoundation library #+apple-objc (open-shared-library "/System/Library/Frameworks/Cocoa.framework/Cocoa") #+cocotron-objc (progn (open-shared-library "Foundation.1.0.dll") (open-shared-library "AppKit.1.0.dll") (open-shared-library "CoreData.1.0.dll") that it 's set to # $ NO . ( When set to non - zero values , it can cause attempts to raise NSExceptions to do nothing . (let* ((addr (foreign-symbol-address "NSDebugEnabled"))) (when addr (setf (%get-unsigned-byte addr) #$NO))) under Cocotron . If so , we 'd need to do #+notyet (with-string-vector (argv (list (kernel-path))) (#_NSInitializeProcess 1 argv))) (current-ns-thread) (create-void-nsthread)))) (pushnew #'load-cocoa-framework *lisp-system-pointer-functions* :key #'function-name) #+darwin-target Nuke any command - line arguments , to keep the Cocoa runtime from (let* ((argv (foreign-symbol-address "NXArgv")) (argc (foreign-symbol-address "NXArgc"))) (when argc (setf (pref argc :int) 1)) (when argv (setf (paref (%get-ptr argv) (:* :char) 1) +null-ptr+))) #-cocotron (load-cocoa-framework) #+cocotron (let* ((path (getenv "PATH"))) (unwind-protect (progn (setenv "PATH" (format nil "~a;~a" (native-translated-namestring (truename "ccl:cocotron;")) path)) (load-cocoa-framework)) (setenv "PATH" path))) (defun find-cfstring-sections () (warn "~s is obsolete" 'find-cfstring-sections)) ) #+gnu-objc (progn (defparameter *gnustep-system-root* "/usr/GNUstep/" "The root of all evil.") (defparameter *gnustep-libraries-pathname* (merge-pathnames "System/Library/Libraries/" *gnustep-system-root*)) (defloadvar *pending-loaded-classes* ()) (defcallback register-class-callback (:address class :address category :void) (let* ((id (map-objc-class class))) (unless (%null-ptr-p category) (let* ((cell (or (assoc id *pending-loaded-classes*) (let* ((c (list id))) (push c *pending-loaded-classes*) c)))) (push (%inc-ptr category 0) (cdr cell)))))) (defun get-c-format-string (c-format-ptr c-arg-ptr) (do* ((n 128)) () (declare (fixnum n)) (%stack-block ((buf n)) (let* ((m (#_vsnprintf buf n c-format-ptr c-arg-ptr))) (declare (fixnum m)) (cond ((< m 0) (return nil)) ((< m n) (return (%get-cstring buf))) (t (setq n m))))))) (defun init-gnustep-framework () (or (getenv "GNUSTEP_SYSTEM_ROOT") (setenv "GNUSTEP_SYSTEM_ROOT" *gnustep-system-root*)) (open-shared-library "libobjc.so.1") (setf (%get-ptr (foreign-symbol-address "_objc_load_callback")) register-class-callback) (open-shared-library (namestring (merge-pathnames "libgnustep-base.so" *gnustep-libraries-pathname*))) (open-shared-library (namestring (merge-pathnames "libgnustep-gui.so" *gnustep-libraries-pathname*)))) (def-ccl-pointers gnustep-framework () (init-gnustep-framework)) ) (defun get-appkit-version () #+apple-objc #&NSAppKitVersionNumber #+gnu-objc (get-foundation-version)) (defun get-foundation-version () #+apple-objc #&NSFoundationVersionNumber #+gnu-objc (%get-cstring (foreign-symbol-address "gnustep_base_version"))) (defparameter *appkit-library-version-number* (get-appkit-version)) (defparameter *foundation-library-version-number* (get-foundation-version)) (defparameter *extension-framework-paths* ()) An instance of NSConstantString ( which is a subclass of NSString ) pointer to an array of 8 - bit characters ( does n't have to be # \Nul make instances of NSConstantString , the @"foo " construct in ObjC. Sure it 's ugly , but it seems to be exactly what the ObjC (defloadvar *NSConstantString-class* (with-cstrs ((name "NSConstantString")) #+(or apple-objc cocotron-objc) (#_objc_lookUpClass name) #+gnu-objc (#_objc_lookup_class name))) (defcallback throw-to-catch-frame (:signed-fullword value :address frame :void) (throw (%get-object frame target::catch-frame.catch-tag) value)) #+(and x8632-target (or apple-objc cocotron-objc)) (defloadvar *setjmp-catch-rip-code* (nbytes (length code-bytes)) (p (malloc nbytes))) (dotimes (i nbytes p) (setf (%get-unsigned-byte p i) (pop code-bytes))))) #+apple-objc (progn NSException - handling stuff . First , we have to jump through some hoops so that # _ longjmp can the _ setjmp.h header file in the LibC source . #+ppc32-target (progn (defconstant JMP-lr #x54 "link register (return address) offset in jmp_buf") (defconstant JMP-sp 0 "stack pointer offset in jmp_buf") (defconstant JMP-r14 12 "offset of r14 (which we clobber) in jmp_buf") (defconstant JMP-r15 16 "offset of r14 (which we also clobber) in jmp_buf")) #+ppc64-target (progn (defconstant JMP-lr #xa8 "link register (return address) offset in jmp_buf") (defconstant JMP-sp 0 "stack pointer offset in jmp_buf") (defconstant JMP-r13 #x10 "offset of r13 (which we preserve) in jmp_buf") (defconstant JMP-r14 #x18 "offset of r14 (which we clobber) in jmp_buf") (defconstant JMP-r15 #x20 "offset of r15 (which we also clobber) in jmp_buf")) These constants also come from Libc sources . Hey , who needs #+x8664-target (progn (defconstant JB-RBX 0) (defconstant JB-RBP 8) (defconstant JB-RSP 16) (defconstant JB-R12 24) (defconstant JB-R13 32) (defconstant JB-R14 40) (defconstant JB-R15 48) (defconstant JB-RIP 56) (defconstant JB-RFLAGS 64) (defconstant JB-MXCSR 72) (defconstant JB-FPCONTROL 76) (defconstant JB-MASK 80) ) #+x8632-target (progn (defconstant JB-FPCW 0) (defconstant JB-MASK 4) (defconstant JB-MXCSR 8) (defconstant JB-EBX 12) (defconstant JB-ECX 16) (defconstant JB-EDX 20) (defconstant JB-EDI 24) (defconstant JB-ESI 28) (defconstant JB-EBP 32) (defconstant JB-ESP 36) (defconstant JB-SS 40) (defconstant JB-EFLAGS 44) (defconstant JB-EIP 48) (defconstant JB-CS 52) (defconstant JB-DS 56) (defconstant JB-ES 60) (defconstant JB-FS 64) (defconstant JB-GS 68) ) A malloc'ed pointer to three words of machine code . The first to the count register . The second instruction ( rather obviously ) copies r15 to r4 . A C function passes its second argument in r4 , The second instruction just jumps to the address in the count register , which is where we really wanted to go in the first #+ppc-target (macrolet ((ppc-lap-word (instruction-form) (uvref (uvref (compile nil `(lambda (&lap 0) (ppc-lap-function () ((?? 0)) ,instruction-form))) 0) #+ppc64-target 1 #+ppc32-target 0))) (defloadvar *setjmp-catch-lr-code* (let* ((p (malloc 12))) (setf (%get-unsigned-long p 0) (ppc-lap-word (mtctr 14)) (%get-unsigned-long p 4) (ppc-lap-word (mr 4 15)) (%get-unsigned-long p 8) (ppc-lap-word (bctr))) Force this code out of the data cache and into memory , so that it 'll get loaded into the icache . (ff-call (%kernel-import #.target::kernel-import-makedataexecutable) :address p :unsigned-fullword 12 :void) p))) #+x8664-target (defloadvar *setjmp-catch-rip-code* movq % r12 , % rsi (nbytes (length code-bytes)) (p (malloc nbytes))) (dotimes (i nbytes p) (setf (%get-unsigned-byte p i) (pop code-bytes))))) Initialize a jmp_buf so that when it 's # _ longjmp - ed to , it 'll frame as its second argument . The C frame used here is just #+ppc-target (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (%set-object jmp-buf JMP-sp c-frame) (%set-object jmp-buf JMP-r15 catch-frame) #+ppc64-target (%set-object jmp-buf JMP-r13 (%get-os-context)) (setf (%get-ptr jmp-buf JMP-lr) *setjmp-catch-lr-code* (%get-ptr jmp-buf JMP-r14) throw-to-catch-frame) t) #+x8664-target (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (setf (%get-ptr jmp-buf JB-rbx) throw-to-catch-frame (%get-ptr jmp-buf JB-rip) *setjmp-catch-rip-code*) (setf (%get-unsigned-long jmp-buf JB-mxcsr) #x1f80 (%get-unsigned-long jmp-buf JB-fpcontrol) #x37f) (%set-object jmp-buf JB-RSP c-frame) (%set-object jmp-buf JB-RBP c-frame) (%set-object jmp-buf JB-r12 catch-frame) t) #+x8632-target Ugh . Apple stores segment register values in jmp_bufs . You know , (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (setf (%get-unsigned-word jmp-buf JB-FS) (%get-fs-register) (%get-unsigned-word jmp-buf JB-GS) (%get-gs-register) (%get-unsigned-word jmp-buf JB-CS) #x17 (%get-unsigned-word jmp-buf JB-DS) #x1f (%get-unsigned-word jmp-buf JB-ES) #x1f (%get-unsigned-word jmp-buf JB-SS) #x1f) (%set-object jmp-buf JB-ESP c-frame) (%set-object jmp-buf JB-EBP c-frame) (setf (%get-unsigned-long jmp-buf JB-MXCSR) #x1f80 (%get-unsigned-long jmp-buf JB-FPCW) #x37f (%get-unsigned-long jmp-buf JB-MASK) 0) (setf (%get-ptr jmp-buf JB-EBX) throw-to-catch-frame (%get-ptr jmp-buf JB-EIP) *setjmp-catch-rip-code*) (%set-object jmp-buf JB-EDI catch-frame) t) ) #+win32-target (progn (eval-when (:compile-toplevel :execute) (progn (defconstant jb-ebp 0) (defconstant jb-ebx 4) (defconstant jb-edi 8) (defconstant jb-esi 12) (defconstant jb-esp 16) (defconstant jb-eip 20) (defconstant jb-seh 24) (defconstant jb-seh-info 28))) (defx8632lapfunction set-jb-seh ((jb arg_z)) (movl (@ (% fs) 0) (% imm0)) (movl (% imm0) (@ jb-seh (% temp0))) (cmpl ($ -1) (% imm0)) (je @store) (movl (@ 12 (% imm0)) (% imm0)) @store (movl (% imm0) (@ jb-seh-info (% temp0))) (single-value-return)) (defun %associate-jmp-buf-with-catch-frame (jmp-buf catch-frame c-frame) (%set-object jmp-buf JB-ESP (1+ c-frame)) (%set-object jmp-buf JB-EBP (1+ c-frame)) (setf (%get-ptr jmp-buf JB-EBX) throw-to-catch-frame (%get-ptr jmp-buf JB-EIP) *setjmp-catch-rip-code*) (%set-object jmp-buf JB-EDI catch-frame) (set-jb-seh jmp-buf) t) ) changed ( by SAVE - APPLICATION ) to , CCL::DEAD - MACPTR and the addresses means that classes that existed on both sides of SAVE - APPLICATION (defun revive-objc-classes () We need to do some things so that we can use ( @class ... ) (invalidate-objc-class-descriptors) (clear-objc-selectors) (clear-objc-protocols) (reset-objc-class-count) (dolist (path *extension-framework-paths*) (%reload-objc-framework path)) (let* ((class-map (objc-class-map)) (metaclass-map (objc-metaclass-map)) (nclasses (%objc-class-count))) (dotimes (i nclasses) (let* ((c (id->objc-class i)) (meta-id (objc-class-id->objc-metaclass-id i)) (m (id->objc-metaclass meta-id))) (unless (typep c 'macptr) (%revive-macptr c) (%setf-macptr c (%null-ptr))) (unless (typep m 'macptr) (%revive-macptr m) (%setf-macptr m (%null-ptr))) (unless (gethash c class-map) (%set-pointer-to-objc-class-address (objc-class-id-foreign-name i) c) (unless (%null-ptr-p c) (setf (gethash c class-map) i) (unless (gethash m metaclass-map) (%setf-macptr m (#_object_getClass c)) (setf (gethash m metaclass-map) meta-id)) (note-class-protocols c))))) Second pass : install class objects for user - defined classes , assuming the superclasses are already " revived " . If the superclass is itself user - defined , it 'll appear first in the (dotimes (i nclasses) (let* ((c (id->objc-class i))) (when (and (%null-ptr-p c) (not (slot-value c 'foreign))) (let* ((super (dolist (s (class-direct-superclasses c) (error "No ObjC superclass of ~s" c)) (when (objc-class-p s) (return s)))) (meta-id (objc-class-id->objc-metaclass-id i)) (m (id->objc-metaclass meta-id))) (let* ((class (make-objc-class-pair super (make-cstring (objc-class-id-foreign-name i)))) (meta (#_object_getClass class))) (unless (gethash m metaclass-map) (%revive-macptr m) (%setf-macptr m meta) (setf (gethash m metaclass-map) meta-id)) (%setf-macptr c class)) #+(or apple-objc-2.0 cocotron-objc) (%revive-foreign-slots c) #+(or apple-objc-2.0 cocotron-objc) (%add-objc-class c) #-(or apple-objc-2.0 cocotron-objc) (multiple-value-bind (ivars instance-size) (%make-objc-ivars c) (%add-objc-class c ivars instance-size)) (setf (gethash c class-map) i))))) was saved on ( for instance ) and Tiger interfaces were used , and then the application is run on Tiger , any into CLOS in the running application . (map-objc-classes nil) )) (pushnew #'revive-objc-classes *lisp-system-pointer-functions* :test #'eq :key #'function-name) (defun %objc-class-instance-size (c) #+(or apple-objc-2.0 cocotron-objc) (#_class_getInstanceSize c) #-(or apple-objc-2.0 cocotron-objc) (pref c :objc_class.instance_size)) (defun find-named-objc-superclass (class string) (unless (or (null string) (%null-ptr-p class)) (with-macptrs ((name #+(or apple-objc-2.0 cocotron-objc) (#_class_getName class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.name))) (or (dotimes (i (length string) class) (let* ((b (%get-unsigned-byte name i))) (unless (eq b (char-code (schar string i))) (return)))) (find-named-objc-superclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class) string))))) (defun install-foreign-objc-class (class &optional (use-db t)) (let* ((id (objc-class-id class))) (unless id (let* ((name (%get-cstring #+(or apple-objc-2.0 cocotron-objc) (#_class_getName class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.name))) (decl (get-objc-class-decl name use-db))) (if (null decl) (or (%get-private-objc-class class) (%register-private-objc-class class name)) (progn (setq id (register-objc-class class) class (id->objc-class id)) (let* ((super (find-named-objc-superclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class) (db-objc-class-info-superclass-name decl)))) (unless (null super) (install-foreign-objc-class super)) (let* ((class-name (objc-to-lisp-classname name "NS")) (meta-id (objc-class-id->objc-metaclass-id id)) (meta (id->objc-metaclass meta-id))) may already be initialized . It 'll have a (unless (id->objc-metaclass-wrapper meta-id) (let* ((meta-foreign-name (%get-cstring #+(or apple-objc-2.0 cocotron-objc) (#_class_getName meta) #-(or apple-objc-2.0 cocotron-objc) (pref meta :objc_class.name))) (meta-name (intern (concatenate 'string "+" (string (objc-to-lisp-classname meta-foreign-name "NS"))) "NS")) (meta-super (if super (#_object_getClass super)))) things in CLOS assume EQness . We probably a lot of EQL - but - not - EQ class pointers to deal (initialize-instance meta :name meta-name :direct-superclasses (list (if (or (null meta-super) (not (%objc-metaclass-p meta-super))) (find-class 'objc:objc-class) (canonicalize-registered-metaclass meta-super))) :peer class :foreign t) (setf (objc-metaclass-id-foreign-name meta-id) meta-foreign-name) (setf (find-class meta-name) meta) (%defglobal meta-name meta))) (setf (slot-value class 'direct-slots) (compute-objc-direct-slots-from-info decl class)) (initialize-instance class :name class-name :direct-superclasses (list (if (null super) (find-class 'objc:objc-object) (canonicalize-registered-class super))) :peer meta :foreign t) (setf (objc-class-id-foreign-name id) name) (setf (find-class class-name) class) (%defglobal class-name class) class)))))))) Execute the body with the variable NSSTR bound to a (defmacro with-nsstr ((nsstr cstring len) &body body) #+apple-objc `(rlet ((,nsstr :<NSC>onstant<S>tring :isa *NSConstantString-class* :bytes ,cstring :num<B>ytes ,len)) ,@body) #+cocotron-objc `(rlet ((,nsstr :<NSC>onstant<S>tring :isa *NSConstantString-class* :_bytes ,cstring :_length ,len)) ,@body) #+gnu-objc `(rlet ((,nsstr :<NXC>onstant<S>tring :isa *NSConstantString-class* :c_string ,cstring :len ,len)) ,@body)) (defun %make-constant-nsstring (string) "Make a persistent (heap-allocated) NSConstantString from the argument lisp string." #+apple-objc (make-record :<NSC>onstant<S>tring :isa *NSConstantString-Class* :bytes (make-cstring string) :num<B>ytes (length string)) #+cocotron-objc (make-record :<NSC>onstant<S>tring :isa *NSConstantString-Class* :_bytes (make-cstring string) :_length (length string)) #+gnu-objc (make-record :<NXC>onstant<S>tring :isa *NSConstantString-Class* :c_string (make-cstring string) :len (length string)) ) (defparameter *objc-class-declarations* (make-hash-table :test #'equal)) (defun register-objc-class-decls () (do-interface-dirs (d) (dolist (class-name (cdb-enumerate-keys (db-objc-classes d))) (get-objc-class-decl class-name t)))) (defun get-objc-class-decl (class-name &optional (use-db nil)) (or (gethash class-name *objc-class-declarations*) (and use-db (let* ((decl (%find-objc-class-info class-name))) (when decl (setf (gethash class-name *objc-class-declarations*) decl)))))) (defun %ensure-class-declaration (name super-name) (unless (get-objc-class-decl name) (setf (gethash name *objc-class-declarations*) (make-db-objc-class-info :class-name (string name) :superclass-name (string super-name)))) name) (defmacro declare-objc-class (name super-name) `(%ensure-class-declaration ',name ',super-name)) Intern NSConstantString instances . (defvar *objc-constant-strings* (make-hash-table :test #'equal)) (defstruct objc-constant-string string nsstringptr) (defun ns-constant-string (string) (or (gethash string *objc-constant-strings*) (setf (gethash string *objc-constant-strings*) (make-objc-constant-string :string string :nsstringptr (%make-constant-nsstring string))))) (def-ccl-pointers objc-strings () (maphash #'(lambda (string cached) (setf (objc-constant-string-nsstringptr cached) (%make-constant-nsstring string))) *objc-constant-strings*)) (defmethod make-load-form ((s objc-constant-string) &optional env) (declare (ignore env)) `(ns-constant-string ,(objc-constant-string-string s))) (defmacro @ (string) `(objc-constant-string-nsstringptr ,(ns-constant-string string))) #+gnu-objc (progn (defcallback lisp-objc-error-handler (:id receiver :int errcode (:* :char) format :address argptr :<BOOL>) (let* ((message (get-c-format-string format argptr))) (error "ObjC runtime error ~d, receiver ~s :~& ~a" errcode receiver message)) #$YES) (def-ccl-pointers install-lisp-objc-error-handler () (#_objc_set_error_handler lisp-objc-error-handler))) (defun objc-class-name-string (name) (etypecase name (symbol (lisp-to-objc-classname name)) (string name))) (defun lookup-objc-class (name &optional error-p) (with-cstrs ((cstr (objc-class-name-string name))) (let* ((p (#+(or apple-objc cocotron-objc) #_objc_lookUpClass #+gnu-objc #_objc_lookup_class cstr))) (if (%null-ptr-p p) (if error-p (error "ObjC class ~a not found" name)) p)))) (defun %set-pointer-to-objc-class-address (class-name-string ptr) (with-cstrs ((cstr class-name-string)) (%setf-macptr ptr (#+(or apple-objc cocotron-objc) #_objc_lookUpClass #+gnu-objc #_objc_lookup_class cstr))) nil) (defvar *objc-class-descriptors* (make-hash-table :test #'equal)) (defstruct objc-class-descriptor name classptr) (defun invalidate-objc-class-descriptors () (maphash #'(lambda (name descriptor) (declare (ignore name)) (setf (objc-class-descriptor-classptr descriptor) nil)) *objc-class-descriptors*)) (defun %objc-class-classptr (class-descriptor &optional (error-p t)) (or (objc-class-descriptor-classptr class-descriptor) (setf (objc-class-descriptor-classptr class-descriptor) (lookup-objc-class (objc-class-descriptor-name class-descriptor) error-p)))) (defun load-objc-class-descriptor (name) (let* ((descriptor (or (gethash name *objc-class-descriptors*) (setf (gethash name *objc-class-descriptors*) (make-objc-class-descriptor :name name))))) (%objc-class-classptr descriptor nil) descriptor)) (defmacro objc-class-descriptor (name) `(load-objc-class-descriptor ,name)) (defmethod make-load-form ((o objc-class-descriptor) &optional env) (declare (ignore env)) `(load-objc-class-descriptor ,(objc-class-descriptor-name o))) (defmacro @class (name) (let* ((name (objc-class-name-string name))) `(the (@metaclass ,name) (%objc-class-classptr ,(objc-class-descriptor name))))) (defun objc-class-name (object) #+(or apple-objc cocotron-objc) (with-macptrs (p) (%setf-macptr p (#_object_getClassName object)) (unless (%null-ptr-p p) (%get-cstring p))) #+gnu-objc (unless (%null-ptr-p object) (with-macptrs ((parent (pref object :objc_object.class_pointer))) (unless (%null-ptr-p parent) (if (logtest (pref parent :objc_class.info) #$_CLS_CLASS) (%get-cstring (pref parent :objc_class.name)) (%get-cstring (pref object :objc_class.name))))))) Likewise , we want to cache the selectors ( " SEL"s ) which identify represented by the same SEL . (defun get-selector-for (method-name &optional error) (with-cstrs ((cmethod-name method-name)) (let* ((p (#+(or apple-objc cocotron-objc) #_sel_getUid #+gnu-objc #_sel_get_uid cmethod-name))) (if (%null-ptr-p p) (if error (error "Can't find ObjC selector for ~a" method-name)) p)))) (defvar *objc-selectors* (make-hash-table :test #'equal)) (defstruct objc-selector name %sel) (defun %get-SELECTOR (selector &optional (error-p t)) (or (objc-selector-%sel selector) (setf (objc-selector-%sel selector) (get-selector-for (objc-selector-name selector) error-p)))) (defun clear-objc-selectors () (maphash #'(lambda (name sel) (declare (ignore name)) (setf (objc-selector-%sel sel) nil)) *objc-selectors*)) (defun ensure-objc-selector (name) (setq name (string name)) (or (gethash name *objc-selectors*) (setf (gethash name *objc-selectors*) (make-objc-selector :name name)))) (defun load-objc-selector (name) (let* ((selector (ensure-objc-selector name))) (%get-SELECTOR selector nil) selector)) (defmacro @SELECTOR (name) `(%get-selector ,(load-objc-selector name))) (defmethod make-load-form ((s objc-selector) &optional env) (declare (ignore env)) `(load-objc-selector ,(objc-selector-name s))) Convert a Lisp object X to a desired foreign type FTYPE - T / NIL = > # $ YES/#$NO (defun coerce-to-bool (x) (let ((x-temp (gensym))) `(let ((,x-temp ,x)) (if (or (eq ,x-temp 0) (null ,x-temp)) #.#$NO #.#$YES)))) (declaim (inline %coerce-to-bool)) (defun %coerce-to-bool (x) (if (and x (not (eql x 0))) #$YES #$NO)) (defun coerce-to-address (x) (let ((x-temp (gensym))) `(let ((,x-temp ,x)) (cond ((null ,x-temp) +null-ptr+) (t ,x-temp))))) (declaim (inline %coerce-to-address)) (defun %coerce-to-address (x) (etypecase x (macptr x) (null (%null-ptr)))) (defun coerce-to-foreign-type (x ftype) (cond ((and (constantp x) (constantp ftype)) (case ftype (:id (if (null x) `(%null-ptr) (coerce-to-address x))) (:<BOOL> (coerce-to-bool (eval x))) (t x))) ((constantp ftype) (case ftype (:id `(%coerce-to-address ,x)) (:<BOOL> `(%coerce-to-bool ,x)) (t x))) (t `(case ,(if (atom ftype) ftype) (:id (%coerce-to-address ,x)) (:<BOOL> (%coerce-to-bool ,x)) (t ,x))))) (defun objc-arg-coerce (typespec arg) (case typespec (:<BOOL> `(%coerce-to-bool ,arg)) (:id `(%coerce-to-address ,arg)) (t arg))) (defun coerce-from-bool (x) (cond ((eq x #$NO) nil) ((eq x #$YES) t) (t (error "Cannot coerce ~S to T or NIL" x)))) (defun objc-result-coerce (type result) (cond ((eq type :<BOOL>) `(coerce-from-bool ,result)) (t result))) Add a faster way to get the message from a SEL by taking advantage of the (defun lisp-string-from-sel (sel) (%get-cstring #+apple-objc sel #+cocotron-objc (#_sel_getName sel) #+gnu-objc (#_sel_get_name sel))) # _ objc_msgSend takes two required arguments ( the receiving object I do n't remmber what the second half of the above comment might (defmacro objc-message-send (receiver selector-name &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) `(:address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) (defmacro objc-message-send-with-selector (receiver selector &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) `(:address ,receiver :<SEL> (%get-selector ,selector) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (%get-selector ,selector)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) means . One of those means ( which is fairly common ) is to pass a pointer to an instance of a structure type as a first argument to the method implementation function ( thereby making SELF the second variable * holds a structure ( of type functions which can determine dynamic ABI attributes . One such first arg " convention is used to return structures of a given Apple ObjC runtime , # _ objc_msgSend_stret must be used if the invisible - first - argument convention is used to return a structure and must NOT be used otherwise . ( The ppc64 and all conventions than ppc32 or ppc Linux . ) We should use (defmacro objc-message-send-stret (structptr receiver selector-name &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSend_stret" "objc_msgSend"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,receiver :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) , (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(,structptr :address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) (defmacro objc-message-send-stret-with-selector (structptr receiver selector &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSend_stret" "objc_msgSend"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,receiver :<SEL> (%get-selector ,selector) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((r (gensym)) (s (gensym)) (imp (gensym))) `(with-macptrs ((,r ,receiver) (,s (%get-selector ,selector)) (,imp (external-call "objc_msg_lookup" :id ,r :<SEL> ,s :<IMP>))) , (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(,structptr :address ,receiver :<SEL> ,s ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)))) (defmacro objc-message-send-super (super selector-name &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSendSuper")))) `(:address ,super :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs))))) (defmacro objc-message-send-super-with-selector (super selector &rest argspecs) (when (evenp (length argspecs)) (setq argspecs (append argspecs '(:id)))) #+(or apple-objc cocotron-objc) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external "objc_msgSendSuper")))) `(:address ,super :<SEL> ,selector ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel ,selector) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) `(:id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs))))) (defmacro objc-message-send-super-stret (structptr super selector-name &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSendSuper_stret" "objc_msgSendSuper"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,super :<SEL> (@selector ,selector-name) ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel (@selector ,selector-name)) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) ,structptr :id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs)))) (defmacro objc-message-send-super-stret-with-selector (structptr super selector &rest argspecs) #+(or apple-objc cocotron-objc) (let* ((return-typespec (car (last argspecs))) (entry-name (if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function *target-ftd*) return-typespec) "objc_msgSendSuper_stret" "objc_msgSendSuper"))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call (%reference-external-entry-point (load-time-value (external ,entry-name)))) `(,structptr :address ,super :<SEL> ,selector ,@argspecs) :arg-coerce 'objc-arg-coerce :result-coerce 'objc-result-coerce)) #+gnu-objc (let* ((sup (gensym)) (sel (gensym)) (imp (gensym))) `(with-macptrs ((,sup ,super) (,sel ,selector) (,imp (external-call "objc_msg_lookup_super" :<S>uper_t ,sup :<SEL> ,sel :<IMP>))) (funcall (ftd-ff-call-expand-function *target-ftd*) `(%ff-call ,imp) ,structptr :id (pref ,sup :<S>uper.self) :<SEL> ,sel ,@argspecs)))) (defun message-send-form-for-call (receiver selector args super-p struct-return-var) (if struct-return-var (if super-p `(objc-message-send-super-stret-with-selector ,struct-return-var ,receiver ,selector ,@args) `(objc-message-send-stret-with-selector ,struct-return-var ,receiver ,selector ,@args)) (if super-p `(objc-message-send-super-with-selector ,receiver ,selector ,@args) `(objc-message-send-with-selector ,receiver ,selector ,@args)))) #+(and apple-objc x8664-target) (defun %process-varargs-list (gpr-pointer fpr-pointer stack-pointer ngprs nfprs nstackargs arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 64) (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* (:signed 64)) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* (:signed 64)) nstackargs) arg-temp) (incf nstackargs)))) ((unsigned-byte 64) (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* (:unsigned 64)) nstackargs) arg-temp) (incf nstackargs)))) (macptr (if (< ngprs 6) (progn (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (progn (setf (paref stack-pointer (:* :address) nstackargs) arg-temp) (incf nstackargs)))) (single-float (if (< nfprs 8) (progn (setf (%get-single-float fpr-pointer (* nfprs 16)) arg-temp) (incf nfprs)) (progn (setf (paref stack-pointer (:* :float) (* 2 nstackargs)) arg-temp) (incf nstackargs)))) (double-float (if (< nfprs 8) (progn (setf (%get-double-float fpr-pointer (* nfprs 16)) arg-temp) (incf nfprs)) (progn (setf (paref stack-pointer (:* :double) nstackargs) arg-temp) (incf nstackargs))))))) #+x8632-target (defun %process-varargs-list (ptr index arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 32) (setf (paref ptr (:* (:signed 32)) index) arg-temp) (incf index)) ((unsigned-byte 32) (setf (paref ptr (:* (:unsigned 32)) index) arg-temp) (incf index)) (macptr (setf (paref ptr (:* :address) index) arg-temp) (incf index)) (single-float (setf (%get-single-float ptr (* 4 index)) arg-temp) (incf index)) (double-float (setf (%get-double-float ptr (* 4 index)) arg-temp) (incf index 2)) ((or (signed-byte 64) (unsigned-byte 64)) (setf (paref ptr (:* :unsigned) index) (ldb (byte 32 0) arg-temp)) (incf index) (setf (paref ptr (:* :unsigned) index) (ldb (byte 32 32) arg-temp)) (incf index))))) #+(and apple-objc ppc32-target) (defun %process-varargs-list (gpr-pointer fpr-pointer ngprs nfprs arglist) (dolist (arg-temp arglist) (typecase arg-temp ((signed-byte 32) (setf (paref gpr-pointer (:* (:signed 32)) ngprs) arg-temp) (incf ngprs)) ((unsigned-byte 32) (setf (paref gpr-pointer (:* (:unsigned 32)) ngprs) arg-temp) (incf ngprs)) (macptr (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (single-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) (float arg-temp 0.0d0)) (incf nfprs)) (setf (paref gpr-pointer (:* :single-float) ngprs) arg-temp) (incf ngprs)) (double-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) arg-temp) (incf nfprs)) (multiple-value-bind (high low) (double-float-bits arg-temp) (setf (paref gpr-pointer (:* :unsigned) ngprs) high) (incf ngprs) (setf (paref gpr-pointer (:* :unsigned) ngprs) low) (incf nfprs))) ((or (signed-byte 64) (unsigned-byte 64)) (setf (paref gpr-pointer (:* :unsigned) ngprs) (ldb (byte 32 32) arg-temp)) (incf ngprs) (setf (paref gpr-pointer (:* :unsigned) ngprs) (ldb (byte 32 0) arg-temp)) (incf ngprs))))) #+(and apple-objc ppc64-target) (defun %process-varargs-list (gpr-pointer fpr-pointer ngprs nfprs arglist) (dolist (arg-temp arglist (min nfprs 13)) (typecase arg-temp ((signed-byte 64) (setf (paref gpr-pointer (:* (:signed 64)) ngprs) arg-temp) (incf ngprs)) ((unsigned-byte 64) (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) arg-temp) (incf ngprs)) (macptr (setf (paref gpr-pointer (:* :address) ngprs) arg-temp) (incf ngprs)) (single-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) (float arg-temp 0.0d0)) (incf nfprs)) (setf (paref gpr-pointer (:* (:unsigned 64)) ngprs) (single-float-bits arg-temp)) (incf ngprs)) (double-float (when (< nfprs 13) (setf (paref fpr-pointer (:* :double-float) nfprs) arg-temp) (incf nfprs)) (setf (paref gpr-pointer (:* :double-float) ngprs) arg-temp) (incf ngprs))))) #+apple-objc (eval-when (:compile-toplevel :execute) #+(and ppc-target (not apple-objc-2.0)) (def-foreign-type :<MARG> (:struct nil (:fp<P>arams (:array :double 13)) (:linkage (:array :uintptr_t 6)) (:reg<P>arams (:array :uintptr_t 8)) (:stack<P>arams (:array :uintptr_t) 0))) ) #+(and apple-objc-2.0 x8664-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (foreign-type-to-representation-type (car sig))) (op (case return-type-spec (:address '%get-ptr) (:unsigned-byte '%get-unsigned-byte) (:signed-byte '%get-signed-byte) (:unsigned-halfword '%get-unsigned-word) (:signed-halfword '%get-signed-word) (:unsigned-fullword '%get-unsigned-long) (:signed-fullword '%get-signed-long) (:unsigned-doubleword '%get-natural) (:signed-doubleword '%get-signed-natural) (:single-float '%get-single-float) (:double-float '%get-double-float))) (result-offset (case op ((:single-float :double-float) 0) (t -8))) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (regparams (gensym)) (stackparams (gensym)) (fpparams (gensym)) (cframe (gensym)) (selptr (gensym)) (gpr-total (gensym)) (fpr-total (gensym)) (stack-total (gensym)) (n-static-fprs 0) (n-static-stack-args 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,regparams (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,regparams (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base (if (< n-static-gprs 6) regparams stackparams)) (fpr-base (if (< n-static-fprs 8) fpparams stackparams)) (gpr-offset (if (< n-static-gprs 6) n-static-gprs n-static-stack-args)) (fpr-offset (if (< n-static-fprs 8) (* 8 n-static-fprs) (* 8 n-static-stack-args)))) (etypecase static-arg-type (foreign-integer-type (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) ,(foreign-integer-type-bits static-arg-type))) ,gpr-offset) ,arg)) (if (< n-static-gprs 6) (incf n-static-gprs) (incf n-static-stack-args))) (foreign-single-float-type (static-arg-forms `(setf (%get-single-float ,fpr-base ,fpr-offset) ,arg)) (if (< n-static-fprs 8) (incf n-static-fprs) (incf n-static-stack-args))) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,fpr-base ,fpr-offset) ,arg)) (if (< n-static-fprs 8) (incf n-static-fprs) (incf n-static-stack-args))) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,gpr-offset) ,arg)) (if (< n-static-gprs 6) (incf n-static-gprs) (incf n-static-stack-args)))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total ,n-static-gprs) (,fpr-total ,n-static-fprs) (,stack-total ,n-static-stack-args)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (typep ,arg-temp 'single-float)) (if (< ,fpr-total 8) (incf ,fpr-total) (incf ,stack-total)) (if (< ,gpr-total 6) (incf ,gpr-total) (incf ,stack-total)))) (%stack-block ((,fpparams (* 8 8))) (with-macptrs (,regparams ,stackparams) (with-variable-c-frame (+ 8 ,stack-total) ,cframe (%setf-macptr-to-object ,regparams (+ ,cframe 2)) (%setf-macptr-to-object ,stackparams (+ ,cframe 8)) (progn ,@(static-arg-forms)) (%process-varargs-list ,regparams ,fpparams ,stackparams ,n-static-gprs ,n-static-fprs ,n-static-stack-args ,rest-arg) (%do-ff-call ,fpr-total ,cframe ,fpparams (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) ,@(if op `((,op ,regparams ,result-offset)) `(()))))))))))) #+(and apple-objc ppc32-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (marg-ptr (gensym)) (regparams (gensym)) (selptr (gensym)) (gpr-total (gensym)) (n-static-fprs 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,regparams (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,regparams (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base regparams) (fpr-base marg-ptr) (gpr-offset (* n-static-gprs 4))) (etypecase static-arg-type (foreign-integer-type (let* ((bits (foreign-type-bits static-arg-type)) (signed (foreign-integer-type-signed static-arg-type))) (if (> bits 32) (progn (static-arg-forms `(setf (,(if signed '%%get-signed-longlong '%%get-unsigned-long-long) ,gpr-base ,gpr-offset) ,arg)) (incf n-static-gprs 2)) (progn (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 32)) ,gpr-offset) ,arg)) (incf n-static-gprs))))) (foreign-single-float-type (static-arg-forms `(setf (paref ,gpr-base (:* :single-float) ,n-static-gprs) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (float (paref ,gpr-base (:* :single-float) ,n-static-gprs) 0.0d0))) (incf n-static-fprs)) (incf n-static-gprs)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,gpr-base ,gpr-offset) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (%get-double-float ,gpr-base ,gpr-offset))) (incf n-static-fprs)) (incf n-static-gprs 2)) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,n-static-gprs) ,arg)) (incf n-static-gprs))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total ,n-static-gprs)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (and (typep ,arg-temp 'integer) (if (< ,arg-temp 0) (>= (integer-length ,arg-temp) 32) (> (integer-length ,arg-temp) 32)))) (incf ,gpr-total 2) (incf ,gpr-total 1))) (if (> ,gpr-total 8) (setq ,gpr-total (- ,gpr-total 8)) (setq ,gpr-total 0)) (%stack-block ((,marg-ptr (+ ,(%foreign-type-or-record-size :<MARG> :bytes) (* 4 ,gpr-total)))) (with-macptrs ((,regparams (pref ,marg-ptr :<MARG>.reg<P>arams))) (progn ,@(static-arg-forms)) (%process-varargs-list ,regparams ,marg-ptr ,n-static-gprs ,n-static-fprs ,rest-arg) (external-call "objc_msgSendv" :address ,receiver :address ,selptr :size_t (+ 32 (* 4 ,gpr-total)) :address ,marg-ptr ,return-type-spec))))))))) #+(and (or apple-objc cocotron-objc) x8632-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (arg-temp (gensym)) (marg-ptr (gensym)) (marg-words (gensym)) (marg-size (gensym)) (selptr (gensym))) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,marg-ptr (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,marg-ptr (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec))) (etypecase static-arg-type (foreign-integer-type (let* ((bits (foreign-type-bits static-arg-type)) (signed (foreign-integer-type-signed static-arg-type))) (if (> bits 32) (progn (static-arg-forms `(setf (,(if signed '%%get-signed-longlong '%%get-unsigned-long-long) ,marg-ptr (* 4 ,static-arg-words)) ,arg)) (incf static-arg-words 2)) (progn (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,marg-ptr (:* (,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 32)) ,static-arg-words) ,arg)) (incf static-arg-words))))) (foreign-single-float-type (static-arg-forms `(setf (paref ,marg-ptr (:* :single-float) ,static-arg-words) ,arg)) (incf static-arg-words)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,marg-ptr (* 4 ,static-arg-words)) ,arg)) (incf static-arg-words 2)) (foreign-pointer-type (static-arg-forms `(setf (paref ,marg-ptr (:* address) ,static-arg-words) ,arg)) (incf static-arg-words))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,marg-words ,static-arg-words) (,marg-size nil)) (dolist (,arg-temp ,rest-arg) (if (or (typep ,arg-temp 'double-float) (and (typep ,arg-temp 'integer) (if (< ,arg-temp 0) (>= (integer-length ,arg-temp) 32) (> (integer-length ,arg-temp) 32)))) (incf ,marg-words 2) (incf ,marg-words 1))) (setq ,marg-size (ash ,marg-words 2)) (%stack-block ((,marg-ptr ,marg-size)) (progn ,@(static-arg-forms)) (%process-varargs-list ,marg-ptr ,static-arg-words ,rest-arg) (external-call "objc_msgSendv" :id ,receiver :<SEL> ,selptr :size_t ,marg-size :address ,marg-ptr ,return-type-spec)))))))) #+(and apple-objc-2.0 ppc64-target) (defun %compile-varargs-send-function-for-signature (sig) (let* ((return-type-spec (car sig)) (arg-type-specs (butlast (cdr sig))) (args (objc-gen-message-arglist (length arg-type-specs))) (receiver (gensym)) (selector (gensym)) (rest-arg (gensym)) (fp-arg-ptr (gensym)) (c-frame (gensym)) (gen-arg-ptr (gensym)) (selptr (gensym)) (gpr-total (gensym)) (n-static-fprs 0)) (collect ((static-arg-forms)) (static-arg-forms `(setf (paref ,gen-arg-ptr (:* address) 0) ,receiver)) (static-arg-forms `(setf (paref ,gen-arg-ptr (:* address) 1) ,selptr)) (do* ((args args (cdr args)) (arg-type-specs arg-type-specs (cdr arg-type-specs))) ((null args)) (let* ((arg (car args)) (spec (car arg-type-specs)) (static-arg-type (parse-foreign-type spec)) (gpr-base gen-arg-ptr) (fpr-base fp-arg-ptr) (gpr-offset (* n-static-gprs 8))) (etypecase static-arg-type (foreign-integer-type (if (eq spec :<BOOL>) (setq arg `(%coerce-to-bool ,arg))) (static-arg-forms `(setf (paref ,gpr-base (:* ( ,(if (foreign-integer-type-signed static-arg-type) :signed :unsigned) 64)) ,gpr-offset) ,arg)) (incf n-static-gprs)) (foreign-single-float-type (static-arg-forms `(setf (%get-single-float ,gpr-base ,(+ 4 gpr-offset)) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (float (%get-single-float ,gpr-base ,(+ 4 (* 8 n-static-gprs))) 0.0d0))) (incf n-static-fprs)) (incf n-static-gprs)) (foreign-double-float-type (static-arg-forms `(setf (%get-double-float ,gpr-base ,gpr-offset) ,arg)) (when (< n-static-fprs 13) (static-arg-forms `(setf (paref ,fpr-base (:* :double-float) ,n-static-fprs) (%get-double-float ,gpr-base ,gpr-offset))) (incf n-static-fprs)) (incf n-static-gprs 1)) (foreign-pointer-type (static-arg-forms `(setf (paref ,gpr-base (:* address) ,n-static-gprs) ,arg)) (incf n-static-gprs))))) (compile nil `(lambda (,receiver ,selector ,@args &rest ,rest-arg) (declare (dynamic-extent ,rest-arg)) (let* ((,selptr (%get-selector ,selector)) (,gpr-total (+ ,n-static-gprs (length ,rest-arg)))) (%stack-block ((,fp-arg-ptr (* 8 13))) (with-variable-c-frame ,gpr-total ,c-frame (with-macptrs ((,gen-arg-ptr)) (%setf-macptr-to-object ,gen-arg-ptr (+ ,c-frame (ash ppc64::c-frame.param0 (- ppc64::word-shift)))) (progn ,@(static-arg-forms)) (%load-fp-arg-regs (%process-varargs-list ,gen-arg-ptr ,fp-arg-ptr ,n-static-gprs ,n-static-fprs ,rest-arg) ,fp-arg-ptr) (%do-ff-call nil (%reference-external-entry-point (load-time-value (external "objc_msgSend")))) (values (%%ff-result ,(foreign-type-to-representation-type return-type-spec)))))))))))) (defun %compile-send-function-for-signature (sig &optional super-p) (let* ((return-type-spec (car sig)) (arg-type-specs (cdr sig))) (if (eq (car (last arg-type-specs)) :void) (%compile-varargs-send-function-for-signature sig) (let* ((args (objc-gen-message-arglist (length arg-type-specs))) (struct-return-var nil) (receiver (gensym)) (selector (gensym))) (collect ((call) (lets)) (let* ((result-type (parse-foreign-type return-type-spec))) (when (typep result-type 'foreign-record-type) (setq struct-return-var (gensym)) (lets `(,struct-return-var (make-gcable-record ,return-type-spec)))) (do ((args args (cdr args)) (spec (pop arg-type-specs) (pop arg-type-specs))) ((null args) (call return-type-spec)) (let* ((arg (car args))) (call spec) (case spec (:<BOOL> (call `(%coerce-to-bool ,arg))) (:id (call `(%coerce-to-address ,arg))) (:<CGF>loat (call `(float ,arg +cgfloat-zero+))) (t (call arg))))) (let* ((call (call)) (lets (lets)) (body (message-send-form-for-call receiver selector call super-p struct-return-var))) (if struct-return-var (setq body `(progn ,body ,struct-return-var))) (if lets (setq body `(let* ,lets ,body))) (compile nil `(lambda (,receiver ,selector ,@args) ,body))))))))) (defun compile-send-function-for-signature (sig) (%compile-send-function-for-signature sig nil)) The first 8 words of non - fp arguments get passed in R3 - R10 #+ppc-target (defvar *objc-gpr-offsets* #+32-bit-target #(4 8 12 16 20 24 28 32) #+64-bit-target #(8 16 24 32 40 48 56 64) ) The first 13 fp arguments get passed in F1 - F13 ( and also " consume " a GPR or two . ) It 's certainly possible for an FP arg and a non- FP arg to share the same " offset " , and parameter offsets are n't #+ppc-target (defvar *objc-fpr-offsets* #+32-bit-target #(36 44 52 60 68 76 84 92 100 108 116 124 132) #+64-bit-target #(68 76 84 92 100 108 116 124 132 140 148 156 164)) first 8 words of the parameter area , args that are n't passed in FP - regs get assigned offsets starting at 32 . That almost makes (defconstant objc-forwarding-stack-offset 8) (defvar *objc-id-type* (parse-foreign-type :id)) (defvar *objc-sel-type* (parse-foreign-type :<SEL>)) (defvar *objc-char-type* (parse-foreign-type :char)) (defun encode-objc-type (type &optional for-ivar recursive) (if (or (eq type *objc-id-type*) (foreign-type-= type *objc-id-type*)) "@" (if (or (eq type *objc-sel-type*) (foreign-type-= type *objc-sel-type*)) ":" (if (eq (foreign-type-class type) 'root) "v" (typecase type (foreign-pointer-type (let* ((target (foreign-pointer-type-to type))) (if (or (eq target *objc-char-type*) (foreign-type-= target *objc-char-type*)) "*" (format nil "^~a" (encode-objc-type target nil t))))) (foreign-double-float-type "d") (foreign-single-float-type "f") (foreign-integer-type (let* ((signed (foreign-integer-type-signed type)) (bits (foreign-integer-type-bits type))) (if (eq (foreign-integer-type-alignment type) 1) (format nil "b~d" bits) (cond ((= bits 8) (if signed "c" "C")) ((= bits 16) (if signed "s" "S")) ((= bits 32) (if signed "i" "I")) ((= bits 64) (if signed "q" "Q")))))) (foreign-record-type (ensure-foreign-type-bits type) (let* ((name (unescape-foreign-name (or (foreign-record-type-name type) "?"))) (kind (foreign-record-type-kind type)) (fields (foreign-record-type-fields type))) (with-output-to-string (s) (format s "~c~a=" (if (eq kind :struct) #\{ #\() name) (dolist (f fields (format s "~a" (if (eq kind :struct) #\} #\)))) (when for-ivar (format s "\"~a\"" (unescape-foreign-name (or (foreign-record-field-name f) "")))) (unless recursive (format s "~a" (encode-objc-type (foreign-record-field-type f) nil nil))))))) (foreign-array-type (ensure-foreign-type-bits type) (let* ((dims (foreign-array-type-dimensions type)) (element-type (foreign-array-type-element-type type))) (if dims (format nil "[~d~a]" (car dims) (encode-objc-type element-type nil t)) (if (or (eq element-type *objc-char-type*) (foreign-type-= element-type *objc-char-type*)) "*" (format nil "^~a" (encode-objc-type element-type nil t)))))) (t (break "type = ~s" type))))))) #+ppc-target (defun encode-objc-method-arglist (arglist result-spec) (let* ((gprs-used 0) (fprs-used 0) (arg-info (flet ((current-memory-arg-offset () (+ 32 (* 4 (- gprs-used 8)) objc-forwarding-stack-offset))) (flet ((current-gpr-arg-offset () (if (< gprs-used 8) (svref *objc-gpr-offsets* gprs-used) (current-memory-arg-offset))) (current-fpr-arg-offset () (if (< fprs-used 13) (svref *objc-fpr-offsets* fprs-used) (current-memory-arg-offset)))) (let* ((result nil)) (dolist (argspec arglist (nreverse result)) (let* ((arg (parse-foreign-type argspec)) (offset 0) (size 0)) (typecase arg (foreign-double-float-type (setq size 8 offset (current-fpr-arg-offset)) (incf fprs-used) (incf gprs-used 2)) (foreign-single-float-type (setq size target::node-size offset (current-fpr-arg-offset)) (incf fprs-used) (incf gprs-used 1)) (foreign-pointer-type (setq size target::node-size offset (current-gpr-arg-offset)) (incf gprs-used)) (foreign-integer-type (let* ((bits (foreign-type-bits arg))) (setq size (ceiling bits 8) offset (current-gpr-arg-offset)) (incf gprs-used (ceiling bits target::nbits-in-word)))) ((or foreign-record-type foreign-array-type) (let* ((bits (ensure-foreign-type-bits arg))) (setq size (ceiling bits 8) offset (current-gpr-arg-offset)) (incf gprs-used (ceiling bits target::nbits-in-word)))) (t (break "argspec = ~s, arg = ~s" argspec arg))) (push (list (encode-objc-type arg) offset size) result)))))))) (declare (fixnum gprs-used fprs-used)) (let* ((max-parm-end (- (apply #'max (mapcar #'(lambda (i) (+ (cadr i) (caddr i))) arg-info)) objc-forwarding-stack-offset))) (with-standard-io-syntax (format nil "~a~d~:{~a~d~}" (encode-objc-type (parse-foreign-type result-spec)) max-parm-end arg-info))))) #+x86-target (defun encode-objc-method-arglist (arglist result-spec) (let* ((offset 0) (arg-info (let* ((result nil)) (dolist (argspec arglist (nreverse result)) (let* ((arg (parse-foreign-type argspec)) (delta target::node-size)) (typecase arg (foreign-double-float-type) (foreign-single-float-type) ((or foreign-pointer-type foreign-array-type)) (foreign-integer-type) (foreign-record-type (let* ((bits (ensure-foreign-type-bits arg))) (setq delta (ceiling bits target::node-size)))) (t (break "argspec = ~s, arg = ~s" argspec arg))) (push (list (encode-objc-type arg) offset) result) (setq offset (* target::node-size (ceiling (+ offset delta) target::node-size)))))))) (let* ((max-parm-end offset)) (with-standard-io-syntax (format nil "~a~d~:{~a~d~}" (encode-objc-type (parse-foreign-type result-spec)) max-parm-end arg-info))))) In Apple Objc , a class 's methods are stored in a ( -1)-terminated (defun %make-method-vector () #+apple-objc (let* ((method-vector (malloc 16))) (setf (%get-signed-long method-vector 0) 0 (%get-signed-long method-vector 4) 0 (%get-signed-long method-vector 8) 0 (%get-signed-long method-vector 12) -1) method-vector)) #-(or apple-objc-2.0 cocotron-objc) (defun %make-basic-meta-class (nameptr superptr rootptr) #+apple-objc (let* ((method-vector (%make-method-vector))) (make-record :objc_class :isa (pref rootptr :objc_class.isa) :super_class (pref superptr :objc_class.isa) :name nameptr :version 0 :info #$CLS_META :instance_size 0 :ivars (%null-ptr) :method<L>ists method-vector :cache (%null-ptr) :protocols (%null-ptr))) #+gnu-objc (make-record :objc_class :class_pointer (pref rootptr :objc_class.class_pointer) :super_class (pref superptr :objc_class.class_pointer) :name nameptr :version 0 :info #$_CLS_META :instance_size 0 :ivars (%null-ptr) :methods (%null-ptr) :dtable (%null-ptr) :subclass_list (%null-ptr) :sibling_class (%null-ptr) :protocols (%null-ptr) :gc_object_type (%null-ptr))) #-(or apple-objc-2.0 cocotron-objc) (defun %make-class-object (metaptr superptr nameptr ivars instance-size) #+apple-objc (let* ((method-vector (%make-method-vector))) (make-record :objc_class :isa metaptr :super_class superptr :name nameptr :version 0 :info #$CLS_CLASS :instance_size instance-size :ivars ivars :method<L>ists method-vector :cache (%null-ptr) :protocols (%null-ptr))) #+gnu-objc (make-record :objc_class :class_pointer metaptr :super_class superptr :name nameptr :version 0 :info #$_CLS_CLASS :instance_size instance-size :ivars ivars :methods (%null-ptr) :dtable (%null-ptr) :protocols (%null-ptr))) (defun make-objc-class-pair (superptr nameptr) #+(or apple-objc-2.0 cocotron-objc) (#_objc_allocateClassPair superptr nameptr 0) #-(or apple-objc-2.0 cocotron-objc) (%make-class-object (%make-basic-meta-class nameptr superptr (@class "NSObject")) superptr nameptr (%null-ptr) 0)) (defun superclass-instance-size (class) (with-macptrs ((super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass class) #-(or apple-objc-2.0 cocotron-objc) (pref class :objc_class.super_class))) (if (%null-ptr-p super) 0 (%objc-class-instance-size super)))) #+gnu-objc (progn (defloadvar *gnu-objc-runtime-mutex* (%get-ptr (foreign-symbol-address "__objc_runtime_mutex"))) (defmacro with-gnu-objc-mutex-locked ((mutex) &body body) (let* ((mname (gensym))) `(let ((,mname ,mutex)) (unwind-protect (progn (external-call "objc_mutex_lock" :address ,mname :void) ,@body) (external-call "objc_mutex_lock" :address ,mname :void))))) ) (defun %objc-metaclass-p (class) #+(or apple-objc-2.0 cocotron-objc) (not (eql #$NO (#_class_isMetaClass class))) #-(or apple-objc-2.0 cocotron-objc) (logtest (pref class :objc_class.info) #+apple-objc #$CLS_META #+gnu-objc #$_CLS_META)) #-(or apple-objc-2.0 cocotron-objc) (defun %objc-class-posing-p (class) (logtest (pref class :objc_class.info) #+apple-objc #$CLS_POSING #+gnu-objc #$_CLS_POSING)) name ( string ) and superclass name . Initialize the metaclass (defun %allocate-objc-class (name superptr) (let* ((class-name (compute-objc-classname name))) (if (lookup-objc-class class-name nil) (error "An Objective C class with name ~s already exists." class-name)) (let* ((nameptr (make-cstring class-name)) (id (register-objc-class (make-objc-class-pair superptr nameptr) )) (meta-id (objc-class-id->objc-metaclass-id id)) (meta (id->objc-metaclass meta-id)) (class (id->objc-class id)) (meta-name (intern (format nil "+~a" name) (symbol-package name))) (meta-super (canonicalize-registered-metaclass #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass meta) #-(or apple-objc-2.0 cocotron-objc) (pref meta :objc_class.super_class)))) (initialize-instance meta :name meta-name :direct-superclasses (list meta-super)) (setf (objc-class-id-foreign-name id) class-name (objc-metaclass-id-foreign-name meta-id) class-name (find-class meta-name) meta) (%defglobal name class) (%defglobal meta-name meta) class))) Set up the class 's ivar_list and instance_size fields , then #-(or apple-objc-2.0 cocotron-objc) (defun %add-objc-class (class ivars instance-size) (setf (pref class :objc_class.ivars) ivars (pref class :objc_class.instance_size) instance-size) #+apple-objc (#_objc_addClass class) #+gnu-objc one class in it and use # _ _ _ objc_exec_class to add the Module . It appears that we have to heap allocate the module , , and (let* ((name (make-cstring "Phony Module")) (symtab (malloc (+ (record-length :objc_symtab) (record-length (:* :void))))) (m (make-record :objc_module :size (record-length :<M>odule) :name name :symtab symtab))) (setf (%get-ptr symtab (record-length :objc_symtab)) (%null-ptr)) (setf (pref symtab :objc_symtab.sel_ref_cnt) 0 (pref symtab :objc_symtab.refs) (%null-ptr) (pref symtab :objc_symtab.cls_def_cnt) 1 (pref symtab :objc_symtab.cat_def_cnt) 0 (%get-ptr (pref symtab :objc_symtab.defs)) class (pref class :objc_class.info) (logior #$_CLS_RESOLV (pref class :objc_class.info))) (#___objc_exec_class m))) #+(or apple-objc-2.0 cocotron-objc) (defun %add-objc-class (class) (#_objc_registerClassPair class)) (let* ((objc-gen-message-args (make-array 10 :fill-pointer 0 :adjustable t))) (defun %objc-gen-message-arg (n) (let* ((len (length objc-gen-message-args))) (do* ((i len (1+ i))) ((> i n) (aref objc-gen-message-args n)) (vector-push-extend (intern (format nil "ARG~d" i)) objc-gen-message-args))))) (defun objc-gen-message-arglist (n) (collect ((args)) (dotimes (i n (args)) (args (%objc-gen-message-arg i))))) and has at least one declared method that returns : ID and is not a (defun register-objc-init-messages () (do-interface-dirs (d) (dolist (init (cdb-enumerate-keys (db-objc-methods d) #'(lambda (string) (string= string "init" :end1 (min (length string) 4))))) (process-init-message (get-objc-message-info init))))) (defvar *objc-init-messages-for-init-keywords* (make-hash-table :test #'equal) "Maps from lists of init keywords to dispatch-functions for init messages") (defun send-objc-init-message (instance init-keywords args) (let* ((info (gethash init-keywords *objc-init-messages-for-init-keywords*))) (unless info (let* ((name (lisp-to-objc-init init-keywords)) (name-info (get-objc-message-info name nil))) (unless name-info (error "Unknown ObjC init message: ~s" name)) (setf (gethash init-keywords *objc-init-messages-for-init-keywords*) (setq info name-info)))) (apply (objc-message-info-lisp-name info) instance args))) (defun objc-set->setf (method) (let* ((info (get-objc-message-info method)) (name (objc-message-info-lisp-name info)) (str (symbol-name name)) (value-placeholder-index (position #\: str))) (when (and (> (length str) 4) value-placeholder-index) (let* ((truncated-name (nstring-downcase (subseq (remove #\: str :test #'char= :count 1) 3) :end 1)) (reader-name (if (> (length truncated-name) (decf value-placeholder-index 3)) (nstring-upcase truncated-name :start value-placeholder-index :end (1+ value-placeholder-index)) truncated-name)) (reader (intern reader-name :nextstep-functions))) (eval `(defun (setf ,reader) (value object &rest args) (apply #',name object value args) value)))))) (defun register-objc-set-messages () (do-interface-dirs (d) (dolist (init (cdb-enumerate-keys (db-objc-methods d) #'(lambda (string) (string= string "set" :end1 (min (length string) 3))))) (objc-set->setf init)))) (defun objc-class-p (p) (if (typep p 'macptr) (let* ((id (objc-class-id p))) (if id (id->objc-class id))))) (defun objc-metaclass-p (p) (if (typep p 'macptr) (let* ((id (objc-metaclass-id p))) (if id (id->objc-metaclass id))))) (defun objc-instance-p (p) (when (typep p 'macptr) (let* ((idx (%objc-instance-class-index p))) (if idx (id->objc-class idx))))) (defun objc-private-class-id (classptr) (let* ((info (%get-private-objc-class classptr))) (when info (or (private-objc-class-info-declared-ancestor info) (with-macptrs ((super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass classptr) #-(or apple-objc-2.0 cocotron-objc) (pref classptr :objc_class.super_class))) (loop (when (%null-ptr-p super) (return)) (let* ((id (objc-class-id super))) (if id (return (setf (private-objc-class-info-declared-ancestor info) id)) (%setf-macptr super #+(or apple-objc-2.0 cocotron-objc) (#_class_getSuperclass super) #-(or apple-objc-2.0 cocotron-objc) (pref super :objc_class.super_class)))))))))) (defun objc-class-or-private-class-id (classptr) (or (objc-class-id classptr) (objc-private-class-id classptr))) The World 's Most Advanced Operating System keeps getting better ! #+(or apple-objc-2.0 apple-objc) (defun objc-hidden-class-id (classptr) If CLASSPTR looks enough like an ObjC class , register it as a private class and return (unless (%null-ptr-p classptr) (with-macptrs (meta metameta) (safe-get-ptr classptr meta) (unless (%null-ptr-p meta) (safe-get-ptr meta metameta) (when (and (eql metameta (find-class 'ns::+ns-object nil)) (%objc-metaclass-p meta)) (let* ((classptr (%inc-ptr classptr 0))) (install-foreign-objc-class classptr nil) (objc-private-class-id classptr))))))) Apple invented tags in 10.7 , in which the CF version number was 635.0d0 (defloadvar *objc-runtime-uses-tags* (>= #&kCFCoreFoundationVersionNumber 635.0d0)) (defun tagged-objc-instance-p (p) (when *objc-runtime-uses-tags* (let* ((tag (logand (the natural (%ptr-to-int p)) #xf))) (declare (fixnum tag)) (if (logbitp 0 tag) tag)))) (defun %objc-instance-class-index (p) (unless (%null-ptr-p p) (let* ((tag (tagged-objc-instance-p p))) (if tag (objc-tagged-instance-class-index p tag) (if (with-macptrs (q) (safe-get-ptr p q) (not (%null-ptr-p q))) (with-macptrs ((parent (#_object_getClass p))) (or (objc-class-id parent) (objc-private-class-id parent) #+(or apple-objc-2.0 apple-objc) (objc-hidden-class-id parent)))))))) (defun objc-object-p (p) (let* ((instance-p (objc-instance-p p))) (if instance-p (values :instance instance-p) (let* ((class-p (objc-class-p p))) (if class-p (values :class class-p) (let* ((metaclass-p (objc-metaclass-p p))) (if metaclass-p (values :metaclass metaclass-p) (values nil nil)))))))) matches ( is EQL to ) the selector , remove the mlist and an mlist with one method slot , initialize the method , and to the old IMP , at least as far as objc method dispatch is #-(or apple-objc-2.0 cocotron-objc) (defun %mlist-containing (classptr selector typestring imp) #-apple-objc (declare (ignore classptr selector typestring imp)) #+apple-objc (%stack-block ((iter 4)) (setf (%get-ptr iter) (%null-ptr)) (loop (let* ((mlist (#_class_nextMethodList classptr iter))) (when (%null-ptr-p mlist) (let* ((mlist (make-record :objc_method_list :method_count 1)) (method (pref mlist :objc_method_list.method_list))) (setf (pref method :objc_method.method_name) selector (pref method :objc_method.method_types) (make-cstring typestring) (pref method :objc_method.method_imp) imp) (return mlist))) (do* ((n (pref mlist :objc_method_list.method_count)) (i 0 (1+ i)) (method (pref mlist :objc_method_list.method_list) (%incf-ptr method (record-length :objc_method)))) ((= i n)) (declare (fixnum i n)) (when (eql selector (pref method :objc_method.method_name)) (#_class_removeMethods classptr mlist) (setf (pref method :objc_method.method_imp) imp) (return-from %mlist-containing mlist))))))) (defun %add-objc-method (classptr selector typestring imp) #+(or apple-objc-2.0 cocotron-objc) (with-cstrs ((typestring typestring)) (or (not (eql #$NO (#_class_addMethod classptr selector imp typestring))) (let* ((m (if (objc-metaclass-p classptr) (#_class_getClassMethod classptr selector) (#_class_getInstanceMethod classptr selector)))) (if (not (%null-ptr-p m)) (#_method_setImplementation m imp) (error "Can't add ~s method to class ~s" selector typestring))))) #-(or apple-objc-2.0 cocotron-objc) (progn #+apple-objc (#_class_addMethods classptr (%mlist-containing classptr selector typestring imp)) #+gnu-objc (with-gnu-objc-mutex-locked (*gnu-objc-runtime-mutex*) (let* ((ctypestring (make-cstring typestring)) (new-mlist nil)) (with-macptrs ((method (external-call "search_for_method_in_list" :address (pref classptr :objc_class.methods) :address selector :address))) (when (%null-ptr-p method) (setq new-mlist (make-record :objc_method_list :method_count 1)) (%setf-macptr method (pref new-mlist :objc_method_list.method_list))) (setf (pref method :objc_method.method_name) selector (pref method :objc_method.method_types) ctypestring (pref method :objc_method.method_imp) imp) (if new-mlist (external-call "GSObjCAddMethods" :address classptr :address new-mlist :void) (external-call "__objc_update_dispatch_table_for_class" :address classptr :void))))))) (defvar *lisp-objc-methods* (make-hash-table :test #'eq)) (defstruct lisp-objc-method class-descriptor sel typestring ) (defun %add-lisp-objc-method (m) (let* ((class (%objc-class-classptr (lisp-objc-method-class-descriptor m))) (sel (%get-selector (lisp-objc-method-sel m))) (typestring (lisp-objc-method-typestring m)) (imp (lisp-objc-method-imp m))) (%add-objc-method (if (lisp-objc-method-class-p m) class) sel typestring imp))) (def-ccl-pointers add-objc-methods () (maphash #'(lambda (impname m) (declare (ignore impname)) (%add-lisp-objc-method m)) *lisp-objc-methods*)) (defun %define-lisp-objc-method (impname classname selname typestring imp &optional class-p) (%add-lisp-objc-method (setf (gethash impname *lisp-objc-methods*) (make-lisp-objc-method :class-descriptor (load-objc-class-descriptor classname) :sel (load-objc-selector selname) :typestring typestring :imp imp :class-p class-p))) (if (string= selname "set" :end1 (min (length selname) 3)) (objc-set->setf selname)) impname) (defun coerce-foreign-boolean-args (argspecs body) (do* ((argspecs argspecs (cddr argspecs)) (type (car argspecs) (car argspecs)) (var (cadr argspecs) (cadr argspecs))) ((null argspecs) body) (when (eq type :<BOOL>) (push `(setq ,var (not (eql ,var 0))) body)))) (defun lisp-boolean->foreign-boolean (form) (let* ((val (gensym))) `((let* ((,val (progn ,@form))) (if (and ,val (not (eql 0 ,val))) 1 0))))) (defun parse-objc-method (selector-arg class-arg body) (let* ((class-name (objc-class-name-string class-arg)) (selector-form selector-arg) (selector nil) (argspecs nil) (resulttype nil) (struct-return nil)) (flet ((bad-selector (why) (error "Can't parse method selector ~s : ~a" selector-arg why))) (typecase selector-form (string (let* ((specs (pop body))) (setq selector selector-form) (if (evenp (length specs)) (setq argspecs specs resulttype :id) (setq resulttype (car (last specs)) argspecs (butlast specs))))) (setq resulttype (pop selector-form)) (unless (consp selector-form) (bad-selector "selector-form not a cons")) (ccl::collect ((components) (specs)) (if (and (null (cdr selector-form)) (car selector-form) (typep (car selector-form) 'symbol) (not (typep (car selector-form) 'keyword))) (components (car selector-form)) (progn (unless (evenp (length selector-form)) (bad-selector "Odd length")) (do* ((s selector-form (cddr s)) (comp (car s) (car s)) (var (cadr s) (cadr s))) ((null s)) (unless (typep comp 'keyword) (bad-selector "not a keyword")) (components comp) (cond ((atom var) (unless (and var (symbolp var)) (bad-selector "not a non-null symbol")) (specs :id) (specs var)) ((and (consp (cdr var)) (null (cddr var)) (cadr var) (symbolp (cadr var))) (specs (car var)) (specs (cadr var))) (t (bad-selector "bad variable/type clause")))))) (setq argspecs (specs) selector (lisp-to-objc-message (components))))) (t (bad-selector "general failure"))) make < name > be the first argument . (when (and (consp resulttype) (eq (car resulttype) :struct)) (destructuring-bind (typespec name) (cdr resulttype) (let* ((rtype (%foreign-type-or-record typespec))) (if (and (typep name 'symbol) (typep rtype 'foreign-record-type)) (setq struct-return name resulttype (unparse-foreign-type rtype)) (bad-selector "Bad struct return type"))))) (values selector class-name resulttype argspecs body (do* ((argtypes ()) (argspecs argspecs (cddr argspecs))) ((null argspecs) (encode-objc-method-arglist `(:id :<sel> ,@(nreverse argtypes)) resulttype)) (push (car argspecs) argtypes)) struct-return)))) (defun objc-method-definition-form (class-p selector-arg class-arg body env) (multiple-value-bind (selector-name class-name resulttype argspecs body typestring struct-return) (parse-objc-method selector-arg class-arg body) (%declare-objc-method selector-name class-name class-p (concise-foreign-type resulttype) (collect ((argtypes)) (do* ((argspecs argspecs (cddr argspecs))) ((null argspecs) (mapcar #'concise-foreign-type (argtypes))) (argtypes (car argspecs))))) (let* ((self (intern "SELF"))) (multiple-value-bind (body decls) (parse-body body env) (unless class-p (push `(%set-objc-instance-type ,self) body)) (setq body (coerce-foreign-boolean-args argspecs body)) (if (eq resulttype :<BOOL>) (setq body (lisp-boolean->foreign-boolean body))) (let* ((impname (intern (format nil "~c[~a ~a]" (if class-p #\+ #\-) class-name selector-name))) (_cmd (intern "_CMD")) (super (gensym "SUPER")) (params `(:id ,self :<sel> ,_cmd))) (when struct-return (push struct-return params)) (setq params (nconc params argspecs)) `(progn (defcallback ,impname (:without-interrupts nil #+(and openmcl-native-threads (or apple-objc cocotron-objc)) :propagate-throw #+(and openmcl-native-threads (or apple-objc cocotron-objc)) objc-propagate-throw ,@params ,resulttype) (declare (ignorable ,_cmd)) ,@decls (rlet ((,super :objc_super #+(or apple-objc cocotron-objc) :receiver #+gnu-objc :self ,self #+(or apple-objc-2.0 cocotron-objc) :super_class #-(or apple-objc-2.0 cocotron-objc) :class ,@(if class-p #+(or apple-objc-2.0 cocotron-objc) `((external-call "class_getSuperclass" :address (external-call "object_getClass" :address (@class ,class-name) :address))) #-(or apple-objc-2.0 cocotron-objc) `((pref (pref (@class ,class-name) #+apple-objc :objc_class.isa #+gnu-objc :objc_class.class_pointer) :objc_class.super_class)) #+(or apple-objc-2.0 cocotron-objc) `((external-call "class_getSuperclass" :address (@class ,class-name) :address)) #-(or apple-objc-2.0 cocotron-objc) `((pref (@class ,class-name) :objc_class.super_class))))) (macrolet ((send-super (msg &rest args &environment env) (make-optimized-send nil msg args env nil ',super ,class-name)) (send-super/stret (s msg &rest args &environment env) (make-optimized-send nil msg args env s ',super ,class-name))) ,@body))) (%define-lisp-objc-method ',impname ,class-name ,selector-name ,typestring ,impname ,class-p))))))) (defmacro define-objc-method (&whole w (selector-arg class-arg) &body body &environment env) (warn-about-deprecated-objc-bridge-construct w "OBJC:DEFMETHOD") (objc-method-definition-form nil selector-arg class-arg body env)) (defmacro define-objc-class-method (&whole w (selector-arg class-arg) &body body &environment env) (warn-about-deprecated-objc-bridge-construct w "OBJC:DEFMETHOD") (objc-method-definition-form t selector-arg class-arg body env)) (declaim (inline %objc-struct-return)) (defun %objc-struct-return (return-temp size value) (unless (eq return-temp value) (#_memmove return-temp value size))) (defvar *objc-error-return-condition* 'condition "Type of conditions to be caught by objc:defmethod and resignalled as objc exceptions, allowing handlers for them to safely take a non-local exit despite possible intervening ObjC frames. The resignalling unwinds the stack before the handler is invoked, which can be a problem for some handlers.") (defmacro objc:defmethod (name (self-arg &rest other-args) &body body &environment env) (collect ((arglist) (arg-names) (arg-types) (bool-args) (type-assertions)) (let* ((result-type nil) (struct-return-var nil) (struct-return-size nil) (selector nil) (class-p nil) (objc-class-name nil)) (if (atom name) (setq selector (string name) result-type :id) (setq selector (string (car name)) result-type (concise-foreign-type (or (cadr name) :id)))) (destructuring-bind (self-name lisp-class-name) self-arg (arg-names self-name) (arg-types :id) (let* ((lisp-class-name (string lisp-class-name))) (if (eq (schar lisp-class-name 0) #\+) (setq class-p t lisp-class-name (subseq lisp-class-name 1))) (setq objc-class-name (lisp-to-objc-classname lisp-class-name))) (let* ((rtype (parse-foreign-type result-type))) (when (typep rtype 'foreign-record-type) (setq struct-return-var (gensym)) (setq struct-return-size (ceiling (foreign-type-bits rtype) 8)) (arglist struct-return-var))) (arg-types :<SEL>) (dolist (arg other-args) (if (atom arg) (progn (arg-types :id) (arg-names arg)) (destructuring-bind (arg-name arg-type) arg (let* ((concise-type (concise-foreign-type arg-type))) (unless (eq concise-type :id) (let* ((ftype (parse-foreign-type concise-type))) (if (typep ftype 'foreign-pointer-type) (setq ftype (foreign-pointer-type-to ftype))) (if (and (typep ftype 'foreign-record-type) (foreign-record-type-name ftype)) (type-assertions `(%set-macptr-type ,arg-name (foreign-type-ordinal (load-time-value (%foreign-type-or-record ,(foreign-record-type-name ftype))))))))) (arg-types concise-type) (arg-names arg-name))))) (let* ((arg-names (arg-names)) (arg-types (arg-types))) (do* ((names arg-names) (types arg-types)) ((null types) (arglist result-type)) (let* ((name (pop names)) (type (pop types))) (arglist type) (arglist name) (if (eq type :<BOOL>) (bool-args `(setq ,name (not (eql ,name 0))))))) (let* ((impname (intern (format nil "~c[~a ~a]" (if class-p #\+ #\-) objc-class-name selector))) (typestring (encode-objc-method-arglist arg-types result-type)) (signature (cons result-type (cddr arg-types)))) (multiple-value-bind (body decls) (parse-body body env) (setq body `((progn ,@(bool-args) ,@(type-assertions) ,@body))) (if (eq result-type :<BOOL>) (setq body `((%coerce-to-bool ,@body)))) (when struct-return-var (setq body `((%objc-struct-return ,struct-return-var ,struct-return-size ,@body))) (setq body `((flet ((struct-return-var-function () ,struct-return-var)) (declaim (inline struct-return-var-function)) ,@body))) (setq body `((macrolet ((objc:returning-foreign-struct ((var) &body body) `(let* ((,var (struct-return-var-function))) ,@body))) ,@body)))) (setq body `((flet ((call-next-method (&rest args) (declare (dynamic-extent args)) (apply (function ,(if class-p '%call-next-objc-class-method '%call-next-objc-method)) ,self-name (@class ,objc-class-name) (@selector ,selector) ',signature args))) (declare (inline call-next-method)) ,@body))) `(progn (%declare-objc-method ',selector ',objc-class-name ,class-p ',result-type ',(cddr arg-types)) (defcallback ,impname ( :propagate-throw objc-propagate-throw ,@(arglist)) (declare (ignorable ,self-name) (unsettable ,self-name) ,@(unless class-p `((type ,lisp-class-name ,self-name)))) ,@decls ,@body) (%define-lisp-objc-method ',impname ,objc-class-name ,selector ,typestring ,impname ,class-p))))))))) (defun class-get-instance-method (class sel) #+(or apple-objc cocotron-objc) (#_class_getInstanceMethod class sel) #+gnu-objc (#_class_get_instance_method class sel)) (defun class-get-class-method (class sel) #+(or apple-objc cocotron-objc) (#_class_getClassMethod class sel) #+gnu-objc (#_class_get_class_method class sel)) (defun method-get-number-of-arguments (m) #+(or apple-objc cocotron-objc) (#_method_getNumberOfArguments m) #+gnu-objc (#_method_get_number_of_arguments m)) (defloadvar *nsstring-newline* #@" ") (defmacro with-autorelease-pool (&body body) (let ((pool-temp (gensym))) `(let ((,pool-temp (create-autorelease-pool))) (unwind-protect (progn ,@body) (release-autorelease-pool ,pool-temp))))) #+apple-objc-2.0 New ! ! ! Improved ! ! ! At best , half - right ! ! ! (defmacro with-ns-exceptions-as-errors (&body body) `(progn ,@body)) The NSHandler2 type was visible in Tiger headers , but it 's not in the Leopard headers . #+(and apple-objc (not apple-objc-2.0)) (def-foreign-type #>NSHandler2_private (:struct #>NSHandler2_private (:_state :jmp_buf) (:_exception :address) (:_others :address) (:_thread :address) (:_reserved1 :address))) #-apple-objc-2.0 (defmacro with-ns-exceptions-as-errors (&body body) #+apple-objc (let* ((nshandler (gensym)) (cframe (gensym))) `(rletZ ((,nshandler #>NSHandler2_private)) (unwind-protect (progn (external-call "__NSAddHandler2" :address ,nshandler :void) (catch ,nshandler (with-c-frame ,cframe (%associate-jmp-buf-with-catch-frame ,nshandler (%fixnum-ref (%current-tcr) target::tcr.catch-top) ,cframe) (progn ,@body)))) (check-ns-exception ,nshandler)))) #+cocotron-objc (let* ((xframe (gensym)) (cframe (gensym))) `(rletZ ((,xframe #>NSExceptionFrame)) (unwind-protect (progn (external-call "__NSPushExceptionFrame" :address ,xframe :void) (catch ,xframe (with-c-frame ,cframe (%associate-jmp-buf-with-catch-frame ,xframe (%fixnum-ref (%current-tcr) (- target::tcr.catch-top target::tcr-bias)) ,cframe) (progn ,@body)))) (check-ns-exception ,xframe)))) #+gnu-objc `(progn ,@body) ) (defvar *condition-id-map* (make-id-map) "Map lisp conditions to small integers") #+(and apple-objc (not apple-objc-2.0)) (defun check-ns-exception (nshandler) (with-macptrs ((exception (external-call "__NSExceptionObjectFromHandler2" :address nshandler :address))) (if (%null-ptr-p exception) (external-call "__NSRemoveHandler2" :address nshandler :void) (if (typep exception 'encapsulated-lisp-throw) (apply #'%throw (with-slots (id) exception (id-map-object *condition-id-map* id))) (error (ns-exception->lisp-condition (%inc-ptr exception 0))))))) #+cocotron-objc (defun check-ns-exception (xframe) (with-macptrs ((exception (pref xframe #>NSExceptionFrame.exception))) (if (%null-ptr-p exception) (external-call "__NSPopExceptionFrame" :address xframe :void) (if (typep exception 'encapsulated-lisp-throw) (apply #'%throw (with-slots (id) exception (id-map-object *condition-id-map* id))) (error (ns-exception->lisp-condition (%inc-ptr exception 0)))))))
d79622cdd93b70509e0dd961420d0dc8eb27fc7ba722f477ef73277eed1fc351
metanivek/irmin-ipfs
conf.mli
module Key : sig val fresh : bool Irmin.Backend.Conf.key val name : string Irmin.Backend.Conf.key end val v : ?fresh:bool -> string -> Irmin.Backend.Conf.t
null
https://raw.githubusercontent.com/metanivek/irmin-ipfs/4b51bd0ab62e8d82078823c0f2b835afa751ebcd/src/conf.mli
ocaml
module Key : sig val fresh : bool Irmin.Backend.Conf.key val name : string Irmin.Backend.Conf.key end val v : ?fresh:bool -> string -> Irmin.Backend.Conf.t
9709083ed2860c958d0d3e3f9a075135d211e93f1573f7d693d36d240c2a4472
zotonic/zotonic
controller_keyserver_key.erl
@author < > 2018 < > %% @doc Retrieve the public key of the keyserver. Copyright 2018 %% 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(controller_keyserver_key). -author("Maas-Maarten Zeeman <>"). -export([ content_types_provided/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). content_types_provided(Context) -> {[ {<<"application">>, <<"javascript">>, []} ], Context}. process(_Method, _AcceptedCT, _ProvidedCT, Context) -> Context1 = z_context:set_noindex_header(Context), Context2 = set_cache_header(Context1), KeyServerName = z_utils:name_for_site(keyserver, z_context:site(Context)), {ok, [PublicExponent, Modulus]} = keyserver:public_enc_key(KeyServerName), E = base64url:encode(PublicExponent), N = base64url:encode(Modulus), z_context:output(["keyserver_public_encrypt_key = {\"kty\": \"RSA\", \"e\":\"", E, "\", \"n\": \"", N, "\"}"], Context2). set_cache_header(Context) -> z_context:set_resp_header( <<"cache-control">>, <<"public, max-age=600">>, Context).
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_base/src/controllers/controller_keyserver_key.erl
erlang
@doc Retrieve the public key of the keyserver. 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.
@author < > 2018 < > Copyright 2018 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(controller_keyserver_key). -author("Maas-Maarten Zeeman <>"). -export([ content_types_provided/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). content_types_provided(Context) -> {[ {<<"application">>, <<"javascript">>, []} ], Context}. process(_Method, _AcceptedCT, _ProvidedCT, Context) -> Context1 = z_context:set_noindex_header(Context), Context2 = set_cache_header(Context1), KeyServerName = z_utils:name_for_site(keyserver, z_context:site(Context)), {ok, [PublicExponent, Modulus]} = keyserver:public_enc_key(KeyServerName), E = base64url:encode(PublicExponent), N = base64url:encode(Modulus), z_context:output(["keyserver_public_encrypt_key = {\"kty\": \"RSA\", \"e\":\"", E, "\", \"n\": \"", N, "\"}"], Context2). set_cache_header(Context) -> z_context:set_resp_header( <<"cache-control">>, <<"public, max-age=600">>, Context).
942fa8f32eb9d13b69763789f2004fdd61cf0f54ce5bcf41ab15351450e72a6d
mwunsch/overscan
caps.rkt
#lang racket/base (require ffi/unsafe/introspection racket/contract "private/core.rkt" "private/structure.rkt") (provide (contract-out [caps? (-> any/c boolean?)] [string->caps (-> string? (or/c caps? false/c))] [caps->string (-> caps? string?)] [caps-merge! (-> caps? caps? caps?)] [caps-append! (-> caps? caps? void?)] [caps-any? (-> caps? boolean?)] [caps-empty? (-> caps? boolean?)] [caps-fixed? (-> caps? boolean?)] [caps=? (-> caps? caps? boolean?)] [caps-size (-> caps? exact-nonnegative-integer?)] [caps-structure (-> caps? exact-nonnegative-integer? gst-structure?)])) (define (caps? v) (is-gtype? v gst-caps)) (define (string->caps str) (gst-caps 'from_string str)) (define (caps->string caps) (gobject-send caps 'to_string)) (define (caps-merge! cap1 cap2) (gobject-send cap1 'merge cap2)) (define (caps-append! cap1 cap2) (gobject-send cap1 'append cap2)) (define (caps-any? caps) (gobject-send caps 'is_any)) (define (caps-empty? caps) (gobject-send caps 'is_empty)) (define (caps-fixed? caps) (gobject-send caps 'is_fixed)) (define (caps=? caps1 caps2) (gobject-send caps1 'is_equal caps2)) (define (caps-size caps) (gobject-send caps 'get_size)) (define (caps-structure caps index) (gobject-send caps 'get_structure index))
null
https://raw.githubusercontent.com/mwunsch/overscan/f198e6b4c1f64cf5720e66ab5ad27fdc4b9e67e9/gstreamer/caps.rkt
racket
#lang racket/base (require ffi/unsafe/introspection racket/contract "private/core.rkt" "private/structure.rkt") (provide (contract-out [caps? (-> any/c boolean?)] [string->caps (-> string? (or/c caps? false/c))] [caps->string (-> caps? string?)] [caps-merge! (-> caps? caps? caps?)] [caps-append! (-> caps? caps? void?)] [caps-any? (-> caps? boolean?)] [caps-empty? (-> caps? boolean?)] [caps-fixed? (-> caps? boolean?)] [caps=? (-> caps? caps? boolean?)] [caps-size (-> caps? exact-nonnegative-integer?)] [caps-structure (-> caps? exact-nonnegative-integer? gst-structure?)])) (define (caps? v) (is-gtype? v gst-caps)) (define (string->caps str) (gst-caps 'from_string str)) (define (caps->string caps) (gobject-send caps 'to_string)) (define (caps-merge! cap1 cap2) (gobject-send cap1 'merge cap2)) (define (caps-append! cap1 cap2) (gobject-send cap1 'append cap2)) (define (caps-any? caps) (gobject-send caps 'is_any)) (define (caps-empty? caps) (gobject-send caps 'is_empty)) (define (caps-fixed? caps) (gobject-send caps 'is_fixed)) (define (caps=? caps1 caps2) (gobject-send caps1 'is_equal caps2)) (define (caps-size caps) (gobject-send caps 'get_size)) (define (caps-structure caps index) (gobject-send caps 'get_structure index))
7beb2e424f68dea6222f8b38f1f885d7edebe41ca2f15023963c93805fb644cf
findmyway/reinforcement-learning-an-introduction
ten_armed_testbed.clj
gorilla-repl.fileformat = 1 ;; @@ (ns rl.chapter02.ten-armed-testbed (:require [incanter.stats :refer [sample-normal sample-binomial]] [rl.util :refer [argmax rand-weighted]] [clojure.core.matrix.stats :refer [mean]] [clojure.core.matrix :refer [to-nested-vectors mset!]] [clojure.core.matrix.operators :refer [+ - *]] [incanter.core :refer [view sel dataset]] [incanter.charts :refer [line-chart add-categories]]) (:use [plotly-clj.core])) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} ;; <= ;; @@ (online-init) ;; @@ ;; => ;;; {"type":"html","content":"<script src=\"-latest.min.js\" type=\"text/javascript\"></script>","value":"pr'ed value"} ;; <= ;; @@ (defn softmax [xs] (let [est (map #(Math/exp %) xs) est-sum (apply + est) est-norm (map #(/ % est-sum) est)] est-norm)) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/softmax</span>","value":"#'rl.chapter02.ten-armed-testbed/softmax"} ;; <= ;; @@ (defn get-action [{:keys [k epsilon estimations ucb-degree action-counts times method]}] (cond (not (nil? ucb-degree)) (let [est (map #(+ %1 (* ucb-degree (Math/sqrt (/ (Math/log (inc times)) (inc %2))))) estimations action-counts)] (-> est argmax shuffle ffirst)) (= :gradient method) (rand-weighted (zipmap (range k) (softmax estimations))) :else (if (and (pos? epsilon) (= 1 (sample-binomial 1 :prob epsilon))) (rand-nth (range k)) (-> estimations argmax shuffle ffirst)))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/get-action</span>","value":"#'rl.chapter02.ten-armed-testbed/get-action"} ;; <= ;; @@ (defn get-reward! [action {:keys [means avg-reward action-counts times estimations method k step-size base-line] :as bandit}] (let [reward (sample-normal 1 :mean (nth means action)) times (inc times) avg-reward (+ (/ reward times) (* avg-reward (/ (dec times) times))) action-counts (update action-counts action inc) estimations (case method :sample-avg (update estimations action #(+ % (/ (- reward %) (nth action-counts action)))) :constant (update estimations action #(+ % (* (:step-size bandit) (- reward %)))) :gradient (let [a (update (vec (repeat k 0)) action inc) prob (softmax estimations) base (if base-line avg-reward 0)] (+ estimations (* step-size (- reward base) (- a prob)))) estimations)] (assoc! bandit :times times :avg-reward avg-reward :action-counts action-counts :estimations estimations) reward)) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/get-reward!</span>","value":"#'rl.chapter02.ten-armed-testbed/get-reward!"} ;; <= ;; @@ ;; data for figure-2-2-a (defn rewards [steps & bandit-params] (let [wrapper (fn [b] (repeatedly steps #(get-reward! (get-action b) b))) bandits (for [_ (range 200)] (apply gen-bandit bandit-params))] (->> bandits (map wrapper) mean to-nested-vectors))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/rewards</span>","value":"#'rl.chapter02.ten-armed-testbed/rewards"} ;; <= ;; @@ (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (rewards steps :epsilon 0) :name "$\\epsilon=0$") (add-scatter :x idx :y (rewards steps :epsilon 0.01) :name "$\\epsilon=0.01$") (add-scatter :x idx :y (rewards steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :title "$\\text{Average performance of } \\epsilon \\text{ greedy action-value methods on the 10-armed testbed}$" :xaxis {:title "Step"} :yaxis {:title "Average reward"}) (plot "RL-figure-2-2-a" :fileopt "overwrite") embed-url)) ;; @@ ;; => ;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/100.embed\" width=\"800\"></iframe>","value":"pr'ed value"} ;; <= ;; @@ ;; data for figure-2-2-b (defn actions [steps & bandit-params] (let [wrapper (fn [b] (take steps (map #(if (= (:best-action b) %) 1 0) (iterate #(do (get-reward! % b) (get-action b)) (get-action b))))) bandits (for [_ (range 200)] (apply gen-bandit bandit-params))] (->> bandits (map wrapper) mean to-nested-vectors))) ;; @@ ;; => ;;; {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/actions</span>","value":"#'rl.chapter02.ten-armed-testbed/actions"} ;; <= ;; @@ ;; plot fitur-2-2-b (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (actions steps :epsilon 0) :name "$\\epsilon=0$") (add-scatter :x idx :y (actions steps :epsilon 0.01) :name "$\\epsilon=0.01$") (add-scatter :x idx :y (actions steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :xaxis {:title "Step"} :yaxis {:title "Optimal Action"} :title "$\\text{Average performance of } \\epsilon \\text{-greedy action-value methods on the 10-armed testbed}$") (plot "RL-figure-2-2-b" :fileopt "overwrite") embed-url)) ;; @@ ;; => ;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/102.embed\" width=\"800\"></iframe>","value":"pr'ed value"} ;; <= ;; @@ ;; figure-2-3 (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (actions steps :epsilon 0 :initial 5 :method :constant) :name "$\\epsilon=0, initial=5$") (add-scatter :x idx :y (actions steps :epsilon 0.1 :initial 0 :method :constant) :name "$\\epsilon=0.1, initial=0$") (set-layout :xaxis {:title "Step"} :yaxis {:title "Optimal action"}) (plot "RL-figure-2-3" :fileopt "overwrite") embed-url)) ;; @@ ;; => ;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/104.embed\" width=\"800\"></iframe>","value":"pr'ed value"} ;; <= ;; @@ fiture-2 - 4 (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (rewards steps :ucb-degree 2) :name "UCB c=2") (add-scatter :x idx :y (rewards steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :title "$\\text{Average performance of }\\epsilon \\text{-greedy action-value methods on the 10-armed testbed}$") (plot "RL-figure-2-4" :fileopt "overwrite") embed-url)) ;; @@ ;; => { " type":"html","content":"<iframe " src=\"//plot.ly/~findmyway/106.embed\ " width=\"800\"></iframe>","value":"pr'ed value " } ;; <= ;; @@ (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly {:x idx}) (add-scatter :y (actions steps :method :gradient :base-line true :step-size 0.1 :true-reward 4) :name "base-line:true step-size:0.1") (add-scatter :y (actions steps :method :gradient :base-line true :step-size 0.4 :true-reward 4) :name "base-line:true step-size:0.4") (add-scatter :y (actions steps :method :gradient :base-line false :step-size 0.1 :true-reward 4) :name "base-line:false step-size:0.1") (add-scatter :y (actions steps :method :gradient :base-line false :step-size 0.4 :true-reward 4) :name "base-line:false step-size:0.4") (plot "RL-figure-2-5" :fileopt "overwrite") embed-url)) ;; @@ ;; => ;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/108.embed\" width=\"800\"></iframe>","value":"pr'ed value"} ;; <= ;; @@ (let [epsilon-greedy #(/ (apply + (rewards 1000 :method :sample-avg :epsilon %)) 1000) gradient #(/ (apply + (rewards 1000 :method :gradient :base-line true :step-size %)) 1000) ucb #(/ (apply + (rewards 1000 :ucb-degree %)) 1000) greedy-initial #(/ (apply + (rewards 1000 :epsilon 0 :initial %)) 1000) [xs1 xs2 xs3 xs4] (map #(map (fn [r] (Math/pow 2 r)) %) [(range -7 -1) (range -5 2) (range -4 3) (range -2 3)])] (-> (plotly) (add-scatter :x xs1 :y (map epsilon-greedy xs1) :name "$\\epsilon greedy$") (add-scatter :x xs2 :y (map gradient xs2) :name "gradient bandit") (add-scatter :x xs3 :y (map ucb xs3) :name "UCB") (add-scatter :x xs4 :y (map greedy-initial xs4) :name "greedy with optimistic initialization") (set-layout :xaxis {:type "log" :title "$\\epsilon/\\alpha/c/Q_0$"}) (plot "RL-figure-2-6" :fileopt "overwrite") embed-url)) ;; @@ ;; => ;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/110.embed\" width=\"800\"></iframe>","value":"pr'ed value"} ;; <= ;; @@ ;; @@
null
https://raw.githubusercontent.com/findmyway/reinforcement-learning-an-introduction/6911efbe7a6478658b188022ebad542751146ddd/src/rl/chapter02/ten_armed_testbed.clj
clojure
@@ @@ => {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"} <= @@ @@ => {"type":"html","content":"<script src=\"-latest.min.js\" type=\"text/javascript\"></script>","value":"pr'ed value"} <= @@ @@ => {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/softmax</span>","value":"#'rl.chapter02.ten-armed-testbed/softmax"} <= @@ @@ => {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/get-action</span>","value":"#'rl.chapter02.ten-armed-testbed/get-action"} <= @@ @@ => {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/get-reward!</span>","value":"#'rl.chapter02.ten-armed-testbed/get-reward!"} <= @@ data for figure-2-2-a @@ => {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/rewards</span>","value":"#'rl.chapter02.ten-armed-testbed/rewards"} <= @@ @@ => {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/100.embed\" width=\"800\"></iframe>","value":"pr'ed value"} <= @@ data for figure-2-2-b @@ => {"type":"html","content":"<span class='clj-var'>#&#x27;rl.chapter02.ten-armed-testbed/actions</span>","value":"#'rl.chapter02.ten-armed-testbed/actions"} <= @@ plot fitur-2-2-b @@ => {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/102.embed\" width=\"800\"></iframe>","value":"pr'ed value"} <= @@ figure-2-3 @@ => {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/104.embed\" width=\"800\"></iframe>","value":"pr'ed value"} <= @@ @@ => <= @@ @@ => {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/108.embed\" width=\"800\"></iframe>","value":"pr'ed value"} <= @@ @@ => {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/110.embed\" width=\"800\"></iframe>","value":"pr'ed value"} <= @@ @@
gorilla-repl.fileformat = 1 (ns rl.chapter02.ten-armed-testbed (:require [incanter.stats :refer [sample-normal sample-binomial]] [rl.util :refer [argmax rand-weighted]] [clojure.core.matrix.stats :refer [mean]] [clojure.core.matrix :refer [to-nested-vectors mset!]] [clojure.core.matrix.operators :refer [+ - *]] [incanter.core :refer [view sel dataset]] [incanter.charts :refer [line-chart add-categories]]) (:use [plotly-clj.core])) (online-init) (defn softmax [xs] (let [est (map #(Math/exp %) xs) est-sum (apply + est) est-norm (map #(/ % est-sum) est)] est-norm)) (defn get-action [{:keys [k epsilon estimations ucb-degree action-counts times method]}] (cond (not (nil? ucb-degree)) (let [est (map #(+ %1 (* ucb-degree (Math/sqrt (/ (Math/log (inc times)) (inc %2))))) estimations action-counts)] (-> est argmax shuffle ffirst)) (= :gradient method) (rand-weighted (zipmap (range k) (softmax estimations))) :else (if (and (pos? epsilon) (= 1 (sample-binomial 1 :prob epsilon))) (rand-nth (range k)) (-> estimations argmax shuffle ffirst)))) (defn get-reward! [action {:keys [means avg-reward action-counts times estimations method k step-size base-line] :as bandit}] (let [reward (sample-normal 1 :mean (nth means action)) times (inc times) avg-reward (+ (/ reward times) (* avg-reward (/ (dec times) times))) action-counts (update action-counts action inc) estimations (case method :sample-avg (update estimations action #(+ % (/ (- reward %) (nth action-counts action)))) :constant (update estimations action #(+ % (* (:step-size bandit) (- reward %)))) :gradient (let [a (update (vec (repeat k 0)) action inc) prob (softmax estimations) base (if base-line avg-reward 0)] (+ estimations (* step-size (- reward base) (- a prob)))) estimations)] (assoc! bandit :times times :avg-reward avg-reward :action-counts action-counts :estimations estimations) reward)) (defn rewards [steps & bandit-params] (let [wrapper (fn [b] (repeatedly steps #(get-reward! (get-action b) b))) bandits (for [_ (range 200)] (apply gen-bandit bandit-params))] (->> bandits (map wrapper) mean to-nested-vectors))) (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (rewards steps :epsilon 0) :name "$\\epsilon=0$") (add-scatter :x idx :y (rewards steps :epsilon 0.01) :name "$\\epsilon=0.01$") (add-scatter :x idx :y (rewards steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :title "$\\text{Average performance of } \\epsilon \\text{ greedy action-value methods on the 10-armed testbed}$" :xaxis {:title "Step"} :yaxis {:title "Average reward"}) (plot "RL-figure-2-2-a" :fileopt "overwrite") embed-url)) (defn actions [steps & bandit-params] (let [wrapper (fn [b] (take steps (map #(if (= (:best-action b) %) 1 0) (iterate #(do (get-reward! % b) (get-action b)) (get-action b))))) bandits (for [_ (range 200)] (apply gen-bandit bandit-params))] (->> bandits (map wrapper) mean to-nested-vectors))) (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (actions steps :epsilon 0) :name "$\\epsilon=0$") (add-scatter :x idx :y (actions steps :epsilon 0.01) :name "$\\epsilon=0.01$") (add-scatter :x idx :y (actions steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :xaxis {:title "Step"} :yaxis {:title "Optimal Action"} :title "$\\text{Average performance of } \\epsilon \\text{-greedy action-value methods on the 10-armed testbed}$") (plot "RL-figure-2-2-b" :fileopt "overwrite") embed-url)) (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (actions steps :epsilon 0 :initial 5 :method :constant) :name "$\\epsilon=0, initial=5$") (add-scatter :x idx :y (actions steps :epsilon 0.1 :initial 0 :method :constant) :name "$\\epsilon=0.1, initial=0$") (set-layout :xaxis {:title "Step"} :yaxis {:title "Optimal action"}) (plot "RL-figure-2-3" :fileopt "overwrite") embed-url)) fiture-2 - 4 (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly) (add-scatter :x idx :y (rewards steps :ucb-degree 2) :name "UCB c=2") (add-scatter :x idx :y (rewards steps :epsilon 0.1) :name "$\\epsilon=0.1$") (set-layout :title "$\\text{Average performance of }\\epsilon \\text{-greedy action-value methods on the 10-armed testbed}$") (plot "RL-figure-2-4" :fileopt "overwrite") embed-url)) { " type":"html","content":"<iframe " src=\"//plot.ly/~findmyway/106.embed\ " width=\"800\"></iframe>","value":"pr'ed value " } (let [steps 1000 idx (range 1 (inc steps))] (-> (plotly {:x idx}) (add-scatter :y (actions steps :method :gradient :base-line true :step-size 0.1 :true-reward 4) :name "base-line:true step-size:0.1") (add-scatter :y (actions steps :method :gradient :base-line true :step-size 0.4 :true-reward 4) :name "base-line:true step-size:0.4") (add-scatter :y (actions steps :method :gradient :base-line false :step-size 0.1 :true-reward 4) :name "base-line:false step-size:0.1") (add-scatter :y (actions steps :method :gradient :base-line false :step-size 0.4 :true-reward 4) :name "base-line:false step-size:0.4") (plot "RL-figure-2-5" :fileopt "overwrite") embed-url)) (let [epsilon-greedy #(/ (apply + (rewards 1000 :method :sample-avg :epsilon %)) 1000) gradient #(/ (apply + (rewards 1000 :method :gradient :base-line true :step-size %)) 1000) ucb #(/ (apply + (rewards 1000 :ucb-degree %)) 1000) greedy-initial #(/ (apply + (rewards 1000 :epsilon 0 :initial %)) 1000) [xs1 xs2 xs3 xs4] (map #(map (fn [r] (Math/pow 2 r)) %) [(range -7 -1) (range -5 2) (range -4 3) (range -2 3)])] (-> (plotly) (add-scatter :x xs1 :y (map epsilon-greedy xs1) :name "$\\epsilon greedy$") (add-scatter :x xs2 :y (map gradient xs2) :name "gradient bandit") (add-scatter :x xs3 :y (map ucb xs3) :name "UCB") (add-scatter :x xs4 :y (map greedy-initial xs4) :name "greedy with optimistic initialization") (set-layout :xaxis {:type "log" :title "$\\epsilon/\\alpha/c/Q_0$"}) (plot "RL-figure-2-6" :fileopt "overwrite") embed-url))
40fb1a4cab6356749677cc2ef0007022b7dc92426a8953a95007d1c8ab904cfe
racket/typed-racket
env-lang.rkt
#lang racket/base (require "../utils/utils.rkt") (require (for-syntax racket/base syntax/parse) racket/stxparam "../utils/tc-utils.rkt" "../env/init-envs.rkt" "../types/abbrev.rkt" "../types/numeric-tower.rkt" "../types/prop-ops.rkt") (define-syntax (-#%module-begin stx) (define-syntax-class clause #:description "[id type]" (pattern [id:identifier ty])) (syntax-parse stx #:literals (require begin) [(mb (~optional (~seq #:default-T+ T+) #:defaults ([T+ #'#false])) (~optional (~and extra (~or (begin . _) (require . args)))) ~! :clause ...) #'(#%plain-module-begin (begin extra (define org-map (syntax-parameterize ([default-rng-shallow-safe? T+]) ;; shallow: don't check base-env functions unless specified (make-env [id (λ () ty)] ...))) (define (init) (initialize-type-env org-map)) (provide init org-map)))] [(mb . rest) #'(mb (begin) . rest)])) (provide (rename-out [-#%module-begin #%module-begin]) require (for-syntax #%datum) (except-out (all-from-out racket/base) #%module-begin) (combine-out (all-from-out "../types/abbrev.rkt" "../types/numeric-tower.rkt" "../types/prop-ops.rkt")))
null
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-lib/typed-racket/base-env/env-lang.rkt
racket
shallow: don't check base-env functions unless specified
#lang racket/base (require "../utils/utils.rkt") (require (for-syntax racket/base syntax/parse) racket/stxparam "../utils/tc-utils.rkt" "../env/init-envs.rkt" "../types/abbrev.rkt" "../types/numeric-tower.rkt" "../types/prop-ops.rkt") (define-syntax (-#%module-begin stx) (define-syntax-class clause #:description "[id type]" (pattern [id:identifier ty])) (syntax-parse stx #:literals (require begin) [(mb (~optional (~seq #:default-T+ T+) #:defaults ([T+ #'#false])) (~optional (~and extra (~or (begin . _) (require . args)))) ~! :clause ...) #'(#%plain-module-begin (begin extra (define org-map (syntax-parameterize ([default-rng-shallow-safe? T+]) (make-env [id (λ () ty)] ...))) (define (init) (initialize-type-env org-map)) (provide init org-map)))] [(mb . rest) #'(mb (begin) . rest)])) (provide (rename-out [-#%module-begin #%module-begin]) require (for-syntax #%datum) (except-out (all-from-out racket/base) #%module-begin) (combine-out (all-from-out "../types/abbrev.rkt" "../types/numeric-tower.rkt" "../types/prop-ops.rkt")))
6a4003ed9228f43f4e5205d63e8fc911a2d403b93f5672e71edf54a04eb727b9
nomaddo/loop
ast.ml
type direction = | To | Downto [@@deriving show] type expr = | Var of Pident.path | Iconst of int | Rconst of string | Call of Pident.path * expr list | Aref of Pident.path * expr list [@@deriving show] type typ = | Void | Int | Real | Array of typ * expr | Lambda of typ list * typ [@@deriving show] type decl = | Decl of typ * Pident.path * expr option | If of expr * decl list * decl list option | Assign of Pident.path * expr | Astore of Pident.path * expr list * expr | For of Pident.path * expr * direction * expr * expr option * decl list | While of expr * decl list | Call of Pident.path * expr list | Return of expr option [@@deriving show] type top_decl = | Fundef of typ * Pident.path * (string * typ) list * decl list | Global_var of typ * Pident.path * expr option | Prim of typ * Pident.path * string [@@deriving show] type t = top_decl list [@@deriving show]
null
https://raw.githubusercontent.com/nomaddo/loop/cd2204208b67b7e1f386b730c953404482ca36d6/parsing/ast.ml
ocaml
type direction = | To | Downto [@@deriving show] type expr = | Var of Pident.path | Iconst of int | Rconst of string | Call of Pident.path * expr list | Aref of Pident.path * expr list [@@deriving show] type typ = | Void | Int | Real | Array of typ * expr | Lambda of typ list * typ [@@deriving show] type decl = | Decl of typ * Pident.path * expr option | If of expr * decl list * decl list option | Assign of Pident.path * expr | Astore of Pident.path * expr list * expr | For of Pident.path * expr * direction * expr * expr option * decl list | While of expr * decl list | Call of Pident.path * expr list | Return of expr option [@@deriving show] type top_decl = | Fundef of typ * Pident.path * (string * typ) list * decl list | Global_var of typ * Pident.path * expr option | Prim of typ * Pident.path * string [@@deriving show] type t = top_decl list [@@deriving show]
afdc8b02a5552ac65fbea66afc2ca6d0227f4694d6f671c2370cfddcf73ac58d
andrenth/release
release.mli
* Release is a multi - process daemon library for OCaml . Its main goal is to ease the development of servers following the common pattern of one master process and one or many slave processes . The usual tasks involved in setting up such process scheme are handled by Release . These consist of turning the master process into a daemon , executing the slave processes , setting up inter - process communication channels between master and slave , dropping privileges and chroot'ing the slave process , etc . The library also provides helper sub - modules [ Io ] , for simple and safe I / O operations , [ Ipc ] , for type- and thread - safe inter - process communication and [ Socket ] for miscellaneous socket - related utility functions . Release also provides some utility sub - modules : [ Buffer ] , a module for buffer operations , [ Bytes ] , for handling binary representation of integers stored in buffers , [ Config ] , for parsing and validating configuration files , and [ Util ] , with miscellaneous functions . Please refer to each sub - module 's documentation for details on their interfaces . Release is a multi - process framework where each process handles concurrent operations by relying on a library that provides asynchronous computation capabilities . The framework provides a functor ( see [ Release . Make ] ) which allows the construction of a module based on any given asynchronous library that provides the necessary primitives . In Release , asynchronous computations are represented by the [ ' a Lwt.t ] type . to ease the development of servers following the common pattern of one master process and one or many slave processes. The usual tasks involved in setting up such process scheme are handled by Release. These consist of turning the master process into a daemon, executing the slave processes, setting up inter-process communication channels between master and slave, dropping privileges and chroot'ing the slave process, etc. The library also provides helper sub-modules [Io], for simple and safe I/O operations, [Ipc], for type- and thread-safe inter-process communication and [Socket] for miscellaneous socket-related utility functions. Release also provides some utility sub-modules: [Buffer], a module for buffer operations, [Bytes], for handling binary representation of integers stored in buffers, [Config], for parsing and validating configuration files, and [Util], with miscellaneous functions. Please refer to each sub-module's documentation for details on their interfaces. Release is a multi-process framework where each process handles concurrent operations by relying on a library that provides asynchronous computation capabilities. The framework provides a functor (see [Release.Make]) which allows the construction of a module based on any given asynchronous library that provides the necessary primitives. In Release, asynchronous computations are represented by the ['a Lwt.t] type. *) open Stdint type command = string * string array (** This module defines a buffer type [Buffer.t] and a set of operations on such buffers. *) module Buffer : sig type t (** The type of buffers. *) val create : int -> t (** [create n] will create a buffer of [n] bytes. *) val make : int -> char -> t (** [make n c] will create a buffer of [n] bytes, all initialized to character [c]. *) val get : t -> int -> char * [ get buf off ] returns the byte at offset [ off ] in [ buf ] . val set : t -> int -> char -> unit * [ set buf off c ] sets the byte at offset [ off ] in [ buf ] to [ c ] . val size : t -> int * [ size buf ] returns the amount of bytes currently allocated for [ buf ] . [buf]. *) val length : t -> int * [ length buf ] returns the offset of the byte set at the highest position in [ buf ] , plus [ 1 ] . This means that a mostly empty buffer with a single byte set at offset [ off ] is considered to have length [ off+1 ] . position in [buf], plus [1]. This means that a mostly empty buffer with a single byte set at offset [off] is considered to have length [off+1]. *) val index : t -> char -> int option * [ index buf c ] returns [ Some off ] , where [ off ] is the offset of the first occurrence of [ c ] in [ buf ] , or [ None ] in case [ c ] does not occur in [ buf ] . first occurrence of [c] in [buf], or [None] in case [c] does not occur in [buf]. *) val index_from : t -> int -> char -> int option * [ index_from buf i c ] returns [ Some off ] , where [ off ] is the offset of the first occurrence of [ c ] in [ buf ] , starting from offset [ i ] , or [ None ] in case [ c ] does not occur in [ buf ] at or after [ i ] . If [ i ] is not in the [ \[0 , length buf ) ] range , also returns [ None ] . the first occurrence of [c] in [buf], starting from offset [i], or [None] in case [c] does not occur in [buf] at or after [i]. If [i] is not in the [\[0, length buf)] range, also returns [None]. *) val add_char : t -> char -> unit * [ c ] appends character [ c ] at the end of [ buf ] . val add_bytes : t -> bytes -> unit * [ add_bytes buf b ] appends bytes [ b ] at the end of [ buf ] . val add_buffer : t -> t -> unit * [ ] appends buffer [ buf2 ] at the end of [ buf1 ] . val contents : t -> string * [ contents buf ] converts the contents of a [ buf ] to a string . The string will be [ size buf ] bytes long . string will be [size buf] bytes long. *) val to_string : t -> string * [ to_string buf ] converts the first [ length buf ] bytes of [ buf ] to a string . a string. *) val of_string : string -> t (** Converts a string to a buffer. *) val blit : t -> int -> t -> int -> int -> unit * [ buf2 off2 len ] copies [ len ] bytes from [ buf1 ] , starting at offset [ off1 ] , to [ buf2 ] , starting at offset [ off2 ] . starting at offset [off1], to [buf2], starting at offset [off2]. *) val sub : t -> int -> int -> t * [ sub buf off len ] returns a buffer consisting of [ len ] bytes from [ buf ] starting at offset [ off ] . No copying is made . [buf] starting at offset [off]. No copying is made. *) val read : Lwt_unix.file_descr -> t -> int -> int -> int Lwt.t * [ read off n ] reads at most [ n ] bytes from file descriptor [ fd ] into buffer [ buf ] , which is filled starting at offset [ off ] . Returns the number of bytes actually read , and 0 on EOF . into buffer [buf], which is filled starting at offset [off]. Returns the number of bytes actually read, and 0 on EOF. *) val write : Lwt_unix.file_descr -> t -> int -> int -> int Lwt.t * [ write Lwt_unix.file_descr buf off n ] writes at most [ n ] bytes from [ buf ] starting at offset [ off ] into file descriptor [ fd ] . Returns the number of bytes actually written . offset [off] into file descriptor [fd]. Returns the number of bytes actually written. *) end * This module contains the file descriptor type definition and functions for easy and safe network I / O functions . The functions are safe in the sense that reads and writes are automatically retried when [ Unix . ] or [ Unix . EAGAIN ] errors are caught . for easy and safe network I/O functions. The functions are safe in the sense that reads and writes are automatically retried when [Unix.EINTR] or [Unix.EAGAIN] errors are caught. *) module Io : sig val read_once : Lwt_unix.file_descr -> Buffer.t -> int -> int -> int Lwt.t * [ read_once off n ] reads at most [ n ] bytes from file descriptor [ fd ] into buffer [ buf ] , starting at offset [ off ] in the buffer . The actual number of bytes read is returned . descriptor [fd] into buffer [buf], starting at offset [off] in the buffer. The actual number of bytes read is returned. *) val read : ?timeout:float -> Lwt_unix.file_descr -> int -> [`Data of Buffer.t | `EOF | `Timeout] Lwt.t * [ read Lwt_unix.file_descr n ] will try to read [ n ] bytes from file descriptor [ fd ] . Data will be read until [ n ] bytes are read or an end - of - file condition occurs . An optional [ timeout ] argument may be given , in which case [ read ] is interrupted after the specified amount of seconds . Data will be read until [n] bytes are read or an end-of-file condition occurs. An optional [timeout] argument may be given, in which case [read] is interrupted after the specified amount of seconds. *) val write : Lwt_unix.file_descr -> Buffer.t -> unit Lwt.t * [ write Lwt_unix.file_descr s ] writes the full contents of [ s ] to file descriptor [ fd ] . [fd]. *) end * This module contains functions for handling binary representation of integers . Functions in the form [ read_<t>_at ] will return an integer of type [ t ] at the offset given as the first argument from the buffer given as the second argument . Functions in the form [ read_<t > ] are equivalent to [ read_<t>_at 0 ] . The [ write_<t > ] functions will append an integer of type [ t ] given as the first argument to the buffer given as the second argument . The [ write_<t>_byte ] functions do the same , but a single byte is appended . integers. Functions in the form [read_<t>_at] will return an integer of type [t] at the offset given as the first argument from the buffer given as the second argument. Functions in the form [read_<t>] are equivalent to [read_<t>_at 0]. The [write_<t>] functions will append an integer of type [t] given as the first argument to the buffer given as the second argument. The [write_<t>_byte] functions do the same, but a single byte is appended. *) module Bytes : sig val read_byte_at : int -> Buffer.t -> int val read_byte : Buffer.t -> int val write_byte : int -> Buffer.t -> unit module type Integer = sig type t val bytes : int val zero : t val byte_max : t val shift_left : t -> int -> t val shift_right_logical : t -> int -> t val logor : t -> t -> t val logand : t -> t -> t val of_int : int -> t val to_int : t -> int end module type ByteOps = sig type t val read_at : int -> Buffer.t -> t val write_byte : t -> Buffer.t -> unit val write : t -> Buffer.t -> unit end module type IntegerOps = sig module Make (I : Integer) : ByteOps with type t = I.t val read_int16_at : int -> Buffer.t -> int val read_int16 : Buffer.t -> int val write_int16_byte : int -> Buffer.t -> unit val write_int16 : int -> Buffer.t -> unit val read_int_at : int -> Buffer.t -> int val read_int : Buffer.t -> int val write_int_byte : int -> Buffer.t -> unit val write_int : int -> Buffer.t -> unit val read_int32_at : int -> Buffer.t -> int32 val read_int32 : Buffer.t -> int32 val write_int32_byte : int32 -> Buffer.t -> unit val write_int32 : int32 -> Buffer.t -> unit val read_uint32_at : int -> Buffer.t -> Uint32.t val read_uint32 : Buffer.t -> Uint32.t val write_uint32_byte : Uint32.t -> Buffer.t -> unit val write_uint32 : Uint32.t -> Buffer.t -> unit val read_int64_at : int -> Buffer.t -> int64 val read_int64 : Buffer.t -> int64 val write_int64_byte : int64 -> Buffer.t -> unit val write_int64 : int64 -> Buffer.t -> unit val read_uint64_at : int -> Buffer.t -> Uint64.t val read_uint64 : Buffer.t -> Uint64.t val write_uint64_byte : Uint64.t -> Buffer.t -> unit val write_uint64 : Uint64.t -> Buffer.t -> unit val read_uint128_at : int -> Buffer.t -> Uint128.t val read_uint128 : Buffer.t -> Uint128.t val write_uint128_byte : Uint128.t -> Buffer.t -> unit val write_uint128 : Uint128.t -> Buffer.t -> unit end module Big_endian : IntegerOps module Little_endian : IntegerOps end * This module provides an interface to configuration file parsing . Configuration files are assumed to be collections of key - value pairs possibly organized in sections . Sections are started by a section name enclosed in square brackets . Keys and values are separated by an equals sign , and values can be integers , floats , booleans , strings , regular expressions , user - defined keywords or lists of one of those types , as defined by the { ! Value.t } type . Keys must be named starting with a letter and optionally followed by any character except whitespace characters , square brackets , equals signs or hash signs . Integers values are represented by sequences of digits and floats are represented by sequences of digits separated by a dot character . Strings are sequences of characters enclosed by double quotes , and newline characters inside strings are supported . Regular expressions are enclosed by forward slash characters and support the same constructs as the ones documented in 's [ ] module , but the grouping constructs [ ( ] and [ ) ] and the alternative between expressions construct [ | ] do n't need to be escaped by a backslash . Newlines can be inserted in regular expressions for organization purposes and are ignored along with any following whitespace characters . Keywords are any user - defined bare words . For example , one can define the keywords [ debug ] , [ info ] , [ notice ] , [ warning ] , [ error ] and [ fatal ] in order to configure log levels of an application , thus making the configuration cleaner by avoiding strings for these settings . Finally , lists are sequences of the above types enclosed by square brackets and separated by commas . In terms of code , configuration files are specified by the { ! Config.spec } type . This is simply a list of { ! Config.section}s , each containing lists of { ! . Keys are defined by their name , an optional default value and a list of validations . If a key has no default value and is absent from the configuration file , an error will be generated . Validation are functions as defined by the { ! Validation.t } type . Many pre - defined validations are available in the { ! Validation } module . Configuration files are assumed to be collections of key-value pairs possibly organized in sections. Sections are started by a section name enclosed in square brackets. Keys and values are separated by an equals sign, and values can be integers, floats, booleans, strings, regular expressions, user-defined keywords or lists of one of those types, as defined by the {!Value.t} type. Keys must be named starting with a letter and optionally followed by any character except whitespace characters, square brackets, equals signs or hash signs. Integers values are represented by sequences of digits and floats are represented by sequences of digits separated by a dot character. Strings are sequences of characters enclosed by double quotes, and newline characters inside strings are supported. Regular expressions are enclosed by forward slash characters and support the same constructs as the ones documented in OCaml's [Str] module, but the grouping constructs [(] and [)] and the alternative between expressions construct [|] don't need to be escaped by a backslash. Newlines can be inserted in regular expressions for organization purposes and are ignored along with any following whitespace characters. Keywords are any user-defined bare words. For example, one can define the keywords [debug], [info], [notice], [warning], [error] and [fatal] in order to configure log levels of an application, thus making the configuration cleaner by avoiding strings for these settings. Finally, lists are sequences of the above types enclosed by square brackets and separated by commas. In terms of code, configuration files are specified by the {!Config.spec} type. This is simply a list of {!Config.section}s, each containing lists of {!Config.key}s. Keys are defined by their name, an optional default value and a list of validations. If a key has no default value and is absent from the configuration file, an error will be generated. Validation are functions as defined by the {!Validation.t} type. Many pre-defined validations are available in the {!Validation} module. *) module Config : sig module Value : sig type t = [ `Keyword of string | `Bool of bool | `Int of int | `Float of float | `Str of string | `Regexp of Re.re | `List of t list ] (** The type of configuration values. Literal newline (['\n']) characters are allowed inside strings. In regular expressions, newlines are ignored along with any following whitespace characters ([' '], ['\t']). *) * { 6 Conversion from [ Config ] values to OCaml values } val to_keyword : [>`Keyword of string] -> string val to_bool : [>`Bool of bool] -> bool val to_int : [>`Int of int] -> int val to_float : [>`Float of float] -> float val to_string : [>`Str of string] -> string val to_regexp : [>`Regexp of Re.re] -> Re.Pcre.regexp val to_list : string -> (t -> 'a) -> [>`List of t list] -> 'a list val to_keyword_list : [>`List of [>`Keyword of string] list] -> string list val to_bool_list : [>`List of [>`Bool of bool] list] -> bool list val to_int_list : [>`List of [>`Int of int] list] -> int list val to_float_list : [>`List of [>`Float of float] list] -> float list val to_string_list : [>`List of [>`Str of string] list] -> string list * { 6 Helpers for specifying default values of directives } module Default : sig val keyword : string -> [>`Keyword of string] option val bool : bool -> [>`Bool of bool] option val int : int -> [>`Int of int] option val float : float -> [>`Float of float] option val string : string -> [>`Str of string] option val regexp : Re.Pcre.regexp -> [>`Regexp of Re.re] option val keyword_list : string list -> [>`List of [>`Keyword of string] list] option val bool_list : bool list -> [>`List of [>`Bool of bool] list] option val int_list : int list -> [>`List of [>`Int of int] list] option val float_list : float list -> [>`List of [>`Float of float] list] option val string_list : string list -> [>`List of [>`Str of string] list] option end end module Validation : sig type result = [`Valid | `Invalid of string] type t = Value.t -> result val keyword : string -> t (** The value is the given keyword. *) val keywords : string list -> t (** The value is one of the given keywords. *) val bool : t (** The value is a boolean. *) val int : t (** The value is an integer. *) val float : t (** The value is a float. *) val string : t (** The value is a string. *) val regexp : t (** The value is a regular expression. *) val bool_list : t (** The value is a list of boolean values. *) val int_list : t (** The value is a list of integer values. *) val float_list : t (** The value is a list of float values. *) val string_list : t (** The value is a list of string values. *) val int_in_range : int * int -> t (** The value is an integer in the inclusive range defined by the given tuple. *) val int_greater_than : int -> t (** The value is an integer greater than the given argument. *) val int_less_than : int -> t (** The value is an integer less than the given argument. *) val float_in_range : float * float -> t (** The value is a float in the inclusive range defined by the given tuple. *) val float_greater_than : float -> t (** The value is a float greater than the given argument.. *) val float_less_than : float -> t (** The value is a float less than the given argument. *) val string_matching : string -> t * The value is a string matching the regular expression given as a string . The regular expression is created by calling [ Re.Pcre.regexp ] on the first argument . string. The regular expression is created by calling [Re.Pcre.regexp] on the first argument. *) val int_in : int list -> t * The value is equal to one of the integers in the given list . val string_in : string list -> t * The value is equal to one of the strings in the given list . val existing_file : t (** The value is an existing file. *) val nonempty_file : t (** The value is a file whose size is nonzero. *) val file_with_mode : Unix.file_perm -> t (** The value is a file with the given mode. *) val file_with_owner : string -> t (** The value is a file with the given owner. *) val file_with_group : string -> t (** The value is a file with the given group. *) val existing_directory : t (** The value is an existing directory. *) val existing_dirname : t (** The value is a path whose directory name (as in [dirname(3)]) exists. *) val block_device : t (** The value is a block device. *) val character_device : t (** The value is a character device. *) val symbolic_link : t (** The value is a symbolic link. *) val named_pipe : t (** The value is a named pipe. *) val unix_socket : t (** The value is a unix socket. *) val existing_user : t (** The value is an exiting user. *) val unprivileged_user : t (** The value is a non-root user. *) val existing_group : t (** The value is an existing group. *) val list_of : t -> t (** The value is a list whose elements must pass the given validation. *) end type t (** The type of a configuration. *) type key = string * Value.t option * Validation.t list (** The type of a configuration key specification. A key is specified by its name, a possible default value and a list of validations. *) type section = [ `Global of key list | `Section of (string * key list) ] (** The type of a configuration section specification. A section specification contains a list of keys belonging to that section, and can either have a name or be global (in which case its keys will not appear under any section definitions in the configuration file). *) type spec = section list (** The type of configuration file specifications. *) val parse : string -> spec -> [`Configuration of t | `Error of string] Lwt.t * a configuration file . [ parse file spec ] will try to parse [ file ] and , if it is syntatically correct , validate it against the specification given in [ spec ] . [file] and, if it is syntatically correct, validate it against the specification given in [spec]. *) val defaults : spec -> t (** [defaults spec] returns a configuration built from the default values of [spec]. This only makes sense if every key in the specification has a default value. *) val get : t -> string -> string -> Value.t (** [get conf section key] returns the value of the parameter [key] of section [section] in configuration [conf]. *) val get_global : t -> string -> Value.t (** [get_global conf key] returns the value of the global parameter [key]. *) end (** Socket type definition and miscellaneous socket-related utility functions. *) module Socket : sig val accept_loop : ?backlog:int -> ?timeout:float -> Lwt_unix.file_descr -> Lwt_unix.sockaddr -> (Lwt_unix.file_descr -> unit Lwt.t) -> 'a Lwt.t * Returns a thread that creates a socket of the given type , binds it to the given address and blocks listening for connections . When a new connection is established , the callback function is called in a handler thread . The default [ backlog ] value is 10 and the default [ timeout ] is 10 seconds . the given address and blocks listening for connections. When a new connection is established, the callback function is called in a handler thread. The default [backlog] value is 10 and the default [timeout] is 10 seconds. *) end * This module allows one to implement type - safe inter - process communication when using Release . The UNIX socket used by Release to implement IPC is a resource that can be shared by multiple threads . Therefore , if multiple threads in your program have access to the IPC file descriptor , it should be protected by a lock in order to ensure atomicity . A simple protocol is assumed . Each IPC message contains a 4 - byte header followed by a variable length payload . The length of the payload is given by the 4 - byte integer in the header , but must fit an OCaml [ int ] . Therefore , in 32 - bit architectures , an exception might be raises during header parsing . when using Release. The UNIX socket used by Release to implement IPC is a resource that can be shared by multiple threads. Therefore, if multiple threads in your program have access to the IPC file descriptor, it should be protected by a lock in order to ensure atomicity. A simple protocol is assumed. Each IPC message contains a 4-byte header followed by a variable length payload. The length of the payload is given by the 4-byte integer in the header, but must fit an OCaml [int]. Therefore, in 32-bit architectures, an exception might be raises during header parsing. *) module Ipc : sig * The type of IPC connections . type connection * The type of IPC handler functions . type handler = connection -> unit Lwt.t val create_connection : Lwt_unix.file_descr -> connection (** Creates an IPC connection from an active unix socket. *) val control_socket : string -> handler -> unit Lwt.t (** [control_socket path handler] creates UNIX domain socket at the specified path and sets up an accept loop thread that waits for connections on the socket. When a new connection is established, [handler] is called on a separate thread. *) module type Types = sig type request * The type of IPC requests . type response * The type of IPC responses . end module type Ops = sig include Types val string_of_request : request -> string (** A function that converts a request into a string. *) val request_of_string : string -> request (** A function that converts a string into a request. *) val string_of_response : response -> string (** A function that converts a response into a string. *) val response_of_string : string -> response (** A function that converts a string into a response. *) end * This module defines a functor providing default string conversion implementation for IPC types based on 's [ Marshal ] module . implementation for IPC types based on OCaml's [Marshal] module. *) module Marshal : sig module Make (T : Types) : Ops with type request := T.request and type response := T.response end module type S = sig type request * The type of IPC requests . type response * The type of IPC responses . module Server : sig * Module containing functions to be used by an IPC server , that is , the master process . the master process. *) val read_request : ?timeout:float -> connection -> [`Request of request | `EOF | `Timeout] Lwt.t * Reads an IPC request from a file descriptor . val write_response : connection -> response -> unit Lwt.t (** Writes an IPC response to a file descriptor. *) val handle_request : ?timeout:float -> ?eof_warning:bool -> connection -> (request -> response Lwt.t) -> unit Lwt.t * This function reads an IPC { ! request } from a file descriptor and passes it to a callback function that must return an appropriate { ! response } . passes it to a callback function that must return an appropriate {!response}. *) end module Client : sig * Module containing functions to be used by an IPC client , that is , a slave , helper or control process . a slave, helper or control process. *) val read_response : ?timeout:float -> connection -> [`Response of response | `EOF | `Timeout] Lwt.t (** Reads an IPC response from a file descriptor. *) val write_request : connection -> request -> unit Lwt.t * Writes an IPC request to a file descriptor . val make_request : ?timeout:float -> connection -> request -> ([`Response of response | `EOF | `Timeout] -> 'a Lwt.t) -> 'a Lwt.t * This function sends an IPC { ! request } on a file descriptor and waits for a { ! response } , passing it to a callback function responsible for handling it . waits for a {!response}, passing it to a callback function responsible for handling it. *) end end module Make (O : Ops) : S with type request := O.request and type response := O.response * Functor that builds an implementation of the IPC - handling functions given the request and response types and the appropriate string conversion functions . given the request and response types and the appropriate string conversion functions. *) end module Util : sig module Option : sig val either : (unit -> 'a) -> ('b -> 'a) -> 'b option -> 'a val some : 'a option -> 'a val default : 'a -> 'a option -> 'a val may : ('a -> unit) -> 'a option -> unit val maybe : ('a -> 'b option) -> 'a option -> 'b option val may_default : 'a -> ('b -> 'a) -> 'b option -> 'a val map : ('a -> 'b) -> 'a option -> 'b option val choose : 'a option -> 'a option -> 'a option val apply : 'a -> 'b -> ('b -> 'a) option -> 'a end end val daemon : (unit -> unit Lwt.t) -> unit Lwt.t * [ daemon f ] turns the current process into a daemon and subsequently calls [ f ] . The following steps are taken by the function : + The [ umask ] is set to 0 ; + [ fork ] is called and the parent process exits ; + The child process calls [ ] , ignores [ SIGHUP ] and [ ] , calls [ fork ] again and exits ; + The grandchild process changes the working directory to [ / ] , redirects [ stdin ] , [ stdout ] and [ stderr ] to [ /dev / null ] and calls [ f ] . calls [f]. The following steps are taken by the function: + The [umask] is set to 0; + [fork] is called and the parent process exits; + The child process calls [setsid], ignores [SIGHUP] and [SIGPIPE], calls [fork] again and exits; + The grandchild process changes the working directory to [/], redirects [stdin], [stdout] and [stderr] to [/dev/null] and calls [f]. *) val master_slave : slave:(command * Ipc.handler) -> ?background:bool -> ?logger:Lwt_log.logger -> ?privileged:bool -> ?slave_env:[`Inherit | `Keep of string list] -> ?control:(string * Ipc.handler) -> ?main:((unit -> (int * Ipc.connection) list) -> unit Lwt.t) -> lock_file:string -> unit -> unit * Sets up a master process with one slave . [ slave ] is a tuple whose first element contains the { ! command } associated to the slave process and second element is a callback function that is called in the master process to handle IPC requests from the slave ( see { ! ) . [ background ] indicates whether { ! daemon } will be called . Defaults to [ true ] . [ logger ] provides an optional logging facility for the master process . Defaults to a syslog logger . [ privileged ] indicates if the master process is to be run as [ root ] . Defaults to [ true ] . [ slave_env ] controls the environment variables available to the slave process . If [ slave_env ] is [ ` Inherit ] , the slave process will inherit the master 's full environment . Otherwise , if [ slave_env ] is [ ` Keep env ] , the slave process will only have access to the variables in the [ env ] list . Defaults to [ ` Keep [ " " ] ] . [ control ] , if present , is a tuple containing a path to a UNIX domain socket that will be created for communication with external process and a callback function that is called when data is sent on the socket . Release will set up a listener thread to deal with IPC on the control socket and each connection will be handled by a separate thread . [ main ] , if given , is a callback function that works as the main thread of the master process . This function receives as an argument a function that returns the current list of sockets that connect the master process to the slave processes . This is useful for broadcast - style communication from the master to the slaves . [ lock_file ] is the path to the lock file created by the master process . This file contains the PID of the master process . If the file already exists and contains the PID of a running process , the master will refuse to start . [slave] is a tuple whose first element contains the {!command} associated to the slave process and second element is a callback function that is called in the master process to handle IPC requests from the slave (see {!Ipc}). [background] indicates whether {!daemon} will be called. Defaults to [true]. [logger] provides an optional logging facility for the master process. Defaults to a syslog logger. [privileged] indicates if the master process is to be run as [root]. Defaults to [true]. [slave_env] controls the environment variables available to the slave process. If [slave_env] is [`Inherit], the slave process will inherit the master's full environment. Otherwise, if [slave_env] is [`Keep env], the slave process will only have access to the variables in the [env] list. Defaults to [`Keep ["OCAMLRUNPARAM"]]. [control], if present, is a tuple containing a path to a UNIX domain socket that will be created for communication with external process and a callback function that is called when data is sent on the socket. Release will set up a listener thread to deal with IPC on the control socket and each connection will be handled by a separate thread. [main], if given, is a callback function that works as the main thread of the master process. This function receives as an argument a function that returns the current list of sockets that connect the master process to the slave processes. This is useful for broadcast-style communication from the master to the slaves. [lock_file] is the path to the lock file created by the master process. This file contains the PID of the master process. If the file already exists and contains the PID of a running process, the master will refuse to start. *) val master_slaves : ?background:bool -> ?logger:Lwt_log.logger -> ?privileged:bool -> ?slave_env:[`Inherit | `Keep of string list] -> ?control:(string * Ipc.handler) -> ?main:((unit -> (int * Ipc.connection) list) -> unit Lwt.t) -> lock_file:string -> slaves:(command * Ipc.handler * int) list -> unit -> unit * This function generalizes { ! master_slave } , taking the same arguments , except for [ slave ] , which is substituted by [ slaves ] . This argument is a list of 3 - element tuples . The first element of the tuple is the { ! command } associated to the slave executable , the second element is the IPC handler for that slave and the third element is the number of instances to be created ( i.e. the number of times the appropriate command will be run . except for [slave], which is substituted by [slaves]. This argument is a list of 3-element tuples. The first element of the tuple is the {!command} associated to the slave executable, the second element is the IPC handler for that slave and the third element is the number of instances to be created (i.e. the number of times the appropriate command will be run. *) val me : ?logger:Lwt_log.logger -> ?user:string -> main:(Ipc.connection -> unit Lwt.t) -> unit -> unit * This function is supposed to be called in the slave process . [ logger ] provides an optional logging facility for the slave process . Defaults to a syslog logger . [ user ] , if present , indicates the name of the user the slave process will drop privileges to . Dropping privileges involves the following steps : + [ chroot ] to the users 's home directory ; + Change the current working directory to [ / ] ; + Call [ setgroups ] on the user 's GID ; + Call [ setgid ] and [ setuid ] on the user 's GID and UID , respectively ; + Check if privileges were successfully dropped . If [ user ] is not given , the slave process will run as the same user used to run the master process . [ main ] is a function that works as the entry point for the slave process code . The file descriptor given as an argument to [ main ] can be used by the slave for communication with the master . [logger] provides an optional logging facility for the slave process. Defaults to a syslog logger. [user], if present, indicates the name of the user the slave process will drop privileges to. Dropping privileges involves the following steps: + [chroot] to the users's home directory; + Change the current working directory to [/]; + Call [setgroups] on the user's GID; + Call [setgid] and [setuid] on the user's GID and UID, respectively; + Check if privileges were successfully dropped. If [user] is not given, the slave process will run as the same user used to run the master process. [main] is a function that works as the entry point for the slave process code. The file descriptor given as an argument to [main] can be used by the slave for communication with the master. *)
null
https://raw.githubusercontent.com/andrenth/release/c88b472d8b142f7f306299d0f51cfd8add4a1a58/src/release.mli
ocaml
* This module defines a buffer type [Buffer.t] and a set of operations on such buffers. * The type of buffers. * [create n] will create a buffer of [n] bytes. * [make n c] will create a buffer of [n] bytes, all initialized to character [c]. * Converts a string to a buffer. * The type of configuration values. Literal newline (['\n']) characters are allowed inside strings. In regular expressions, newlines are ignored along with any following whitespace characters ([' '], ['\t']). * The value is the given keyword. * The value is one of the given keywords. * The value is a boolean. * The value is an integer. * The value is a float. * The value is a string. * The value is a regular expression. * The value is a list of boolean values. * The value is a list of integer values. * The value is a list of float values. * The value is a list of string values. * The value is an integer in the inclusive range defined by the given tuple. * The value is an integer greater than the given argument. * The value is an integer less than the given argument. * The value is a float in the inclusive range defined by the given tuple. * The value is a float greater than the given argument.. * The value is a float less than the given argument. * The value is an existing file. * The value is a file whose size is nonzero. * The value is a file with the given mode. * The value is a file with the given owner. * The value is a file with the given group. * The value is an existing directory. * The value is a path whose directory name (as in [dirname(3)]) exists. * The value is a block device. * The value is a character device. * The value is a symbolic link. * The value is a named pipe. * The value is a unix socket. * The value is an exiting user. * The value is a non-root user. * The value is an existing group. * The value is a list whose elements must pass the given validation. * The type of a configuration. * The type of a configuration key specification. A key is specified by its name, a possible default value and a list of validations. * The type of a configuration section specification. A section specification contains a list of keys belonging to that section, and can either have a name or be global (in which case its keys will not appear under any section definitions in the configuration file). * The type of configuration file specifications. * [defaults spec] returns a configuration built from the default values of [spec]. This only makes sense if every key in the specification has a default value. * [get conf section key] returns the value of the parameter [key] of section [section] in configuration [conf]. * [get_global conf key] returns the value of the global parameter [key]. * Socket type definition and miscellaneous socket-related utility functions. * Creates an IPC connection from an active unix socket. * [control_socket path handler] creates UNIX domain socket at the specified path and sets up an accept loop thread that waits for connections on the socket. When a new connection is established, [handler] is called on a separate thread. * A function that converts a request into a string. * A function that converts a string into a request. * A function that converts a response into a string. * A function that converts a string into a response. * Writes an IPC response to a file descriptor. * Reads an IPC response from a file descriptor.
* Release is a multi - process daemon library for OCaml . Its main goal is to ease the development of servers following the common pattern of one master process and one or many slave processes . The usual tasks involved in setting up such process scheme are handled by Release . These consist of turning the master process into a daemon , executing the slave processes , setting up inter - process communication channels between master and slave , dropping privileges and chroot'ing the slave process , etc . The library also provides helper sub - modules [ Io ] , for simple and safe I / O operations , [ Ipc ] , for type- and thread - safe inter - process communication and [ Socket ] for miscellaneous socket - related utility functions . Release also provides some utility sub - modules : [ Buffer ] , a module for buffer operations , [ Bytes ] , for handling binary representation of integers stored in buffers , [ Config ] , for parsing and validating configuration files , and [ Util ] , with miscellaneous functions . Please refer to each sub - module 's documentation for details on their interfaces . Release is a multi - process framework where each process handles concurrent operations by relying on a library that provides asynchronous computation capabilities . The framework provides a functor ( see [ Release . Make ] ) which allows the construction of a module based on any given asynchronous library that provides the necessary primitives . In Release , asynchronous computations are represented by the [ ' a Lwt.t ] type . to ease the development of servers following the common pattern of one master process and one or many slave processes. The usual tasks involved in setting up such process scheme are handled by Release. These consist of turning the master process into a daemon, executing the slave processes, setting up inter-process communication channels between master and slave, dropping privileges and chroot'ing the slave process, etc. The library also provides helper sub-modules [Io], for simple and safe I/O operations, [Ipc], for type- and thread-safe inter-process communication and [Socket] for miscellaneous socket-related utility functions. Release also provides some utility sub-modules: [Buffer], a module for buffer operations, [Bytes], for handling binary representation of integers stored in buffers, [Config], for parsing and validating configuration files, and [Util], with miscellaneous functions. Please refer to each sub-module's documentation for details on their interfaces. Release is a multi-process framework where each process handles concurrent operations by relying on a library that provides asynchronous computation capabilities. The framework provides a functor (see [Release.Make]) which allows the construction of a module based on any given asynchronous library that provides the necessary primitives. In Release, asynchronous computations are represented by the ['a Lwt.t] type. *) open Stdint type command = string * string array module Buffer : sig type t val create : int -> t val make : int -> char -> t val get : t -> int -> char * [ get buf off ] returns the byte at offset [ off ] in [ buf ] . val set : t -> int -> char -> unit * [ set buf off c ] sets the byte at offset [ off ] in [ buf ] to [ c ] . val size : t -> int * [ size buf ] returns the amount of bytes currently allocated for [ buf ] . [buf]. *) val length : t -> int * [ length buf ] returns the offset of the byte set at the highest position in [ buf ] , plus [ 1 ] . This means that a mostly empty buffer with a single byte set at offset [ off ] is considered to have length [ off+1 ] . position in [buf], plus [1]. This means that a mostly empty buffer with a single byte set at offset [off] is considered to have length [off+1]. *) val index : t -> char -> int option * [ index buf c ] returns [ Some off ] , where [ off ] is the offset of the first occurrence of [ c ] in [ buf ] , or [ None ] in case [ c ] does not occur in [ buf ] . first occurrence of [c] in [buf], or [None] in case [c] does not occur in [buf]. *) val index_from : t -> int -> char -> int option * [ index_from buf i c ] returns [ Some off ] , where [ off ] is the offset of the first occurrence of [ c ] in [ buf ] , starting from offset [ i ] , or [ None ] in case [ c ] does not occur in [ buf ] at or after [ i ] . If [ i ] is not in the [ \[0 , length buf ) ] range , also returns [ None ] . the first occurrence of [c] in [buf], starting from offset [i], or [None] in case [c] does not occur in [buf] at or after [i]. If [i] is not in the [\[0, length buf)] range, also returns [None]. *) val add_char : t -> char -> unit * [ c ] appends character [ c ] at the end of [ buf ] . val add_bytes : t -> bytes -> unit * [ add_bytes buf b ] appends bytes [ b ] at the end of [ buf ] . val add_buffer : t -> t -> unit * [ ] appends buffer [ buf2 ] at the end of [ buf1 ] . val contents : t -> string * [ contents buf ] converts the contents of a [ buf ] to a string . The string will be [ size buf ] bytes long . string will be [size buf] bytes long. *) val to_string : t -> string * [ to_string buf ] converts the first [ length buf ] bytes of [ buf ] to a string . a string. *) val of_string : string -> t val blit : t -> int -> t -> int -> int -> unit * [ buf2 off2 len ] copies [ len ] bytes from [ buf1 ] , starting at offset [ off1 ] , to [ buf2 ] , starting at offset [ off2 ] . starting at offset [off1], to [buf2], starting at offset [off2]. *) val sub : t -> int -> int -> t * [ sub buf off len ] returns a buffer consisting of [ len ] bytes from [ buf ] starting at offset [ off ] . No copying is made . [buf] starting at offset [off]. No copying is made. *) val read : Lwt_unix.file_descr -> t -> int -> int -> int Lwt.t * [ read off n ] reads at most [ n ] bytes from file descriptor [ fd ] into buffer [ buf ] , which is filled starting at offset [ off ] . Returns the number of bytes actually read , and 0 on EOF . into buffer [buf], which is filled starting at offset [off]. Returns the number of bytes actually read, and 0 on EOF. *) val write : Lwt_unix.file_descr -> t -> int -> int -> int Lwt.t * [ write Lwt_unix.file_descr buf off n ] writes at most [ n ] bytes from [ buf ] starting at offset [ off ] into file descriptor [ fd ] . Returns the number of bytes actually written . offset [off] into file descriptor [fd]. Returns the number of bytes actually written. *) end * This module contains the file descriptor type definition and functions for easy and safe network I / O functions . The functions are safe in the sense that reads and writes are automatically retried when [ Unix . ] or [ Unix . EAGAIN ] errors are caught . for easy and safe network I/O functions. The functions are safe in the sense that reads and writes are automatically retried when [Unix.EINTR] or [Unix.EAGAIN] errors are caught. *) module Io : sig val read_once : Lwt_unix.file_descr -> Buffer.t -> int -> int -> int Lwt.t * [ read_once off n ] reads at most [ n ] bytes from file descriptor [ fd ] into buffer [ buf ] , starting at offset [ off ] in the buffer . The actual number of bytes read is returned . descriptor [fd] into buffer [buf], starting at offset [off] in the buffer. The actual number of bytes read is returned. *) val read : ?timeout:float -> Lwt_unix.file_descr -> int -> [`Data of Buffer.t | `EOF | `Timeout] Lwt.t * [ read Lwt_unix.file_descr n ] will try to read [ n ] bytes from file descriptor [ fd ] . Data will be read until [ n ] bytes are read or an end - of - file condition occurs . An optional [ timeout ] argument may be given , in which case [ read ] is interrupted after the specified amount of seconds . Data will be read until [n] bytes are read or an end-of-file condition occurs. An optional [timeout] argument may be given, in which case [read] is interrupted after the specified amount of seconds. *) val write : Lwt_unix.file_descr -> Buffer.t -> unit Lwt.t * [ write Lwt_unix.file_descr s ] writes the full contents of [ s ] to file descriptor [ fd ] . [fd]. *) end * This module contains functions for handling binary representation of integers . Functions in the form [ read_<t>_at ] will return an integer of type [ t ] at the offset given as the first argument from the buffer given as the second argument . Functions in the form [ read_<t > ] are equivalent to [ read_<t>_at 0 ] . The [ write_<t > ] functions will append an integer of type [ t ] given as the first argument to the buffer given as the second argument . The [ write_<t>_byte ] functions do the same , but a single byte is appended . integers. Functions in the form [read_<t>_at] will return an integer of type [t] at the offset given as the first argument from the buffer given as the second argument. Functions in the form [read_<t>] are equivalent to [read_<t>_at 0]. The [write_<t>] functions will append an integer of type [t] given as the first argument to the buffer given as the second argument. The [write_<t>_byte] functions do the same, but a single byte is appended. *) module Bytes : sig val read_byte_at : int -> Buffer.t -> int val read_byte : Buffer.t -> int val write_byte : int -> Buffer.t -> unit module type Integer = sig type t val bytes : int val zero : t val byte_max : t val shift_left : t -> int -> t val shift_right_logical : t -> int -> t val logor : t -> t -> t val logand : t -> t -> t val of_int : int -> t val to_int : t -> int end module type ByteOps = sig type t val read_at : int -> Buffer.t -> t val write_byte : t -> Buffer.t -> unit val write : t -> Buffer.t -> unit end module type IntegerOps = sig module Make (I : Integer) : ByteOps with type t = I.t val read_int16_at : int -> Buffer.t -> int val read_int16 : Buffer.t -> int val write_int16_byte : int -> Buffer.t -> unit val write_int16 : int -> Buffer.t -> unit val read_int_at : int -> Buffer.t -> int val read_int : Buffer.t -> int val write_int_byte : int -> Buffer.t -> unit val write_int : int -> Buffer.t -> unit val read_int32_at : int -> Buffer.t -> int32 val read_int32 : Buffer.t -> int32 val write_int32_byte : int32 -> Buffer.t -> unit val write_int32 : int32 -> Buffer.t -> unit val read_uint32_at : int -> Buffer.t -> Uint32.t val read_uint32 : Buffer.t -> Uint32.t val write_uint32_byte : Uint32.t -> Buffer.t -> unit val write_uint32 : Uint32.t -> Buffer.t -> unit val read_int64_at : int -> Buffer.t -> int64 val read_int64 : Buffer.t -> int64 val write_int64_byte : int64 -> Buffer.t -> unit val write_int64 : int64 -> Buffer.t -> unit val read_uint64_at : int -> Buffer.t -> Uint64.t val read_uint64 : Buffer.t -> Uint64.t val write_uint64_byte : Uint64.t -> Buffer.t -> unit val write_uint64 : Uint64.t -> Buffer.t -> unit val read_uint128_at : int -> Buffer.t -> Uint128.t val read_uint128 : Buffer.t -> Uint128.t val write_uint128_byte : Uint128.t -> Buffer.t -> unit val write_uint128 : Uint128.t -> Buffer.t -> unit end module Big_endian : IntegerOps module Little_endian : IntegerOps end * This module provides an interface to configuration file parsing . Configuration files are assumed to be collections of key - value pairs possibly organized in sections . Sections are started by a section name enclosed in square brackets . Keys and values are separated by an equals sign , and values can be integers , floats , booleans , strings , regular expressions , user - defined keywords or lists of one of those types , as defined by the { ! Value.t } type . Keys must be named starting with a letter and optionally followed by any character except whitespace characters , square brackets , equals signs or hash signs . Integers values are represented by sequences of digits and floats are represented by sequences of digits separated by a dot character . Strings are sequences of characters enclosed by double quotes , and newline characters inside strings are supported . Regular expressions are enclosed by forward slash characters and support the same constructs as the ones documented in 's [ ] module , but the grouping constructs [ ( ] and [ ) ] and the alternative between expressions construct [ | ] do n't need to be escaped by a backslash . Newlines can be inserted in regular expressions for organization purposes and are ignored along with any following whitespace characters . Keywords are any user - defined bare words . For example , one can define the keywords [ debug ] , [ info ] , [ notice ] , [ warning ] , [ error ] and [ fatal ] in order to configure log levels of an application , thus making the configuration cleaner by avoiding strings for these settings . Finally , lists are sequences of the above types enclosed by square brackets and separated by commas . In terms of code , configuration files are specified by the { ! Config.spec } type . This is simply a list of { ! Config.section}s , each containing lists of { ! . Keys are defined by their name , an optional default value and a list of validations . If a key has no default value and is absent from the configuration file , an error will be generated . Validation are functions as defined by the { ! Validation.t } type . Many pre - defined validations are available in the { ! Validation } module . Configuration files are assumed to be collections of key-value pairs possibly organized in sections. Sections are started by a section name enclosed in square brackets. Keys and values are separated by an equals sign, and values can be integers, floats, booleans, strings, regular expressions, user-defined keywords or lists of one of those types, as defined by the {!Value.t} type. Keys must be named starting with a letter and optionally followed by any character except whitespace characters, square brackets, equals signs or hash signs. Integers values are represented by sequences of digits and floats are represented by sequences of digits separated by a dot character. Strings are sequences of characters enclosed by double quotes, and newline characters inside strings are supported. Regular expressions are enclosed by forward slash characters and support the same constructs as the ones documented in OCaml's [Str] module, but the grouping constructs [(] and [)] and the alternative between expressions construct [|] don't need to be escaped by a backslash. Newlines can be inserted in regular expressions for organization purposes and are ignored along with any following whitespace characters. Keywords are any user-defined bare words. For example, one can define the keywords [debug], [info], [notice], [warning], [error] and [fatal] in order to configure log levels of an application, thus making the configuration cleaner by avoiding strings for these settings. Finally, lists are sequences of the above types enclosed by square brackets and separated by commas. In terms of code, configuration files are specified by the {!Config.spec} type. This is simply a list of {!Config.section}s, each containing lists of {!Config.key}s. Keys are defined by their name, an optional default value and a list of validations. If a key has no default value and is absent from the configuration file, an error will be generated. Validation are functions as defined by the {!Validation.t} type. Many pre-defined validations are available in the {!Validation} module. *) module Config : sig module Value : sig type t = [ `Keyword of string | `Bool of bool | `Int of int | `Float of float | `Str of string | `Regexp of Re.re | `List of t list ] * { 6 Conversion from [ Config ] values to OCaml values } val to_keyword : [>`Keyword of string] -> string val to_bool : [>`Bool of bool] -> bool val to_int : [>`Int of int] -> int val to_float : [>`Float of float] -> float val to_string : [>`Str of string] -> string val to_regexp : [>`Regexp of Re.re] -> Re.Pcre.regexp val to_list : string -> (t -> 'a) -> [>`List of t list] -> 'a list val to_keyword_list : [>`List of [>`Keyword of string] list] -> string list val to_bool_list : [>`List of [>`Bool of bool] list] -> bool list val to_int_list : [>`List of [>`Int of int] list] -> int list val to_float_list : [>`List of [>`Float of float] list] -> float list val to_string_list : [>`List of [>`Str of string] list] -> string list * { 6 Helpers for specifying default values of directives } module Default : sig val keyword : string -> [>`Keyword of string] option val bool : bool -> [>`Bool of bool] option val int : int -> [>`Int of int] option val float : float -> [>`Float of float] option val string : string -> [>`Str of string] option val regexp : Re.Pcre.regexp -> [>`Regexp of Re.re] option val keyword_list : string list -> [>`List of [>`Keyword of string] list] option val bool_list : bool list -> [>`List of [>`Bool of bool] list] option val int_list : int list -> [>`List of [>`Int of int] list] option val float_list : float list -> [>`List of [>`Float of float] list] option val string_list : string list -> [>`List of [>`Str of string] list] option end end module Validation : sig type result = [`Valid | `Invalid of string] type t = Value.t -> result val keyword : string -> t val keywords : string list -> t val bool : t val int : t val float : t val string : t val regexp : t val bool_list : t val int_list : t val float_list : t val string_list : t val int_in_range : int * int -> t val int_greater_than : int -> t val int_less_than : int -> t val float_in_range : float * float -> t val float_greater_than : float -> t val float_less_than : float -> t val string_matching : string -> t * The value is a string matching the regular expression given as a string . The regular expression is created by calling [ Re.Pcre.regexp ] on the first argument . string. The regular expression is created by calling [Re.Pcre.regexp] on the first argument. *) val int_in : int list -> t * The value is equal to one of the integers in the given list . val string_in : string list -> t * The value is equal to one of the strings in the given list . val existing_file : t val nonempty_file : t val file_with_mode : Unix.file_perm -> t val file_with_owner : string -> t val file_with_group : string -> t val existing_directory : t val existing_dirname : t val block_device : t val character_device : t val symbolic_link : t val named_pipe : t val unix_socket : t val existing_user : t val unprivileged_user : t val existing_group : t val list_of : t -> t end type t type key = string * Value.t option * Validation.t list type section = [ `Global of key list | `Section of (string * key list) ] type spec = section list val parse : string -> spec -> [`Configuration of t | `Error of string] Lwt.t * a configuration file . [ parse file spec ] will try to parse [ file ] and , if it is syntatically correct , validate it against the specification given in [ spec ] . [file] and, if it is syntatically correct, validate it against the specification given in [spec]. *) val defaults : spec -> t val get : t -> string -> string -> Value.t val get_global : t -> string -> Value.t end module Socket : sig val accept_loop : ?backlog:int -> ?timeout:float -> Lwt_unix.file_descr -> Lwt_unix.sockaddr -> (Lwt_unix.file_descr -> unit Lwt.t) -> 'a Lwt.t * Returns a thread that creates a socket of the given type , binds it to the given address and blocks listening for connections . When a new connection is established , the callback function is called in a handler thread . The default [ backlog ] value is 10 and the default [ timeout ] is 10 seconds . the given address and blocks listening for connections. When a new connection is established, the callback function is called in a handler thread. The default [backlog] value is 10 and the default [timeout] is 10 seconds. *) end * This module allows one to implement type - safe inter - process communication when using Release . The UNIX socket used by Release to implement IPC is a resource that can be shared by multiple threads . Therefore , if multiple threads in your program have access to the IPC file descriptor , it should be protected by a lock in order to ensure atomicity . A simple protocol is assumed . Each IPC message contains a 4 - byte header followed by a variable length payload . The length of the payload is given by the 4 - byte integer in the header , but must fit an OCaml [ int ] . Therefore , in 32 - bit architectures , an exception might be raises during header parsing . when using Release. The UNIX socket used by Release to implement IPC is a resource that can be shared by multiple threads. Therefore, if multiple threads in your program have access to the IPC file descriptor, it should be protected by a lock in order to ensure atomicity. A simple protocol is assumed. Each IPC message contains a 4-byte header followed by a variable length payload. The length of the payload is given by the 4-byte integer in the header, but must fit an OCaml [int]. Therefore, in 32-bit architectures, an exception might be raises during header parsing. *) module Ipc : sig * The type of IPC connections . type connection * The type of IPC handler functions . type handler = connection -> unit Lwt.t val create_connection : Lwt_unix.file_descr -> connection val control_socket : string -> handler -> unit Lwt.t module type Types = sig type request * The type of IPC requests . type response * The type of IPC responses . end module type Ops = sig include Types val string_of_request : request -> string val request_of_string : string -> request val string_of_response : response -> string val response_of_string : string -> response end * This module defines a functor providing default string conversion implementation for IPC types based on 's [ Marshal ] module . implementation for IPC types based on OCaml's [Marshal] module. *) module Marshal : sig module Make (T : Types) : Ops with type request := T.request and type response := T.response end module type S = sig type request * The type of IPC requests . type response * The type of IPC responses . module Server : sig * Module containing functions to be used by an IPC server , that is , the master process . the master process. *) val read_request : ?timeout:float -> connection -> [`Request of request | `EOF | `Timeout] Lwt.t * Reads an IPC request from a file descriptor . val write_response : connection -> response -> unit Lwt.t val handle_request : ?timeout:float -> ?eof_warning:bool -> connection -> (request -> response Lwt.t) -> unit Lwt.t * This function reads an IPC { ! request } from a file descriptor and passes it to a callback function that must return an appropriate { ! response } . passes it to a callback function that must return an appropriate {!response}. *) end module Client : sig * Module containing functions to be used by an IPC client , that is , a slave , helper or control process . a slave, helper or control process. *) val read_response : ?timeout:float -> connection -> [`Response of response | `EOF | `Timeout] Lwt.t val write_request : connection -> request -> unit Lwt.t * Writes an IPC request to a file descriptor . val make_request : ?timeout:float -> connection -> request -> ([`Response of response | `EOF | `Timeout] -> 'a Lwt.t) -> 'a Lwt.t * This function sends an IPC { ! request } on a file descriptor and waits for a { ! response } , passing it to a callback function responsible for handling it . waits for a {!response}, passing it to a callback function responsible for handling it. *) end end module Make (O : Ops) : S with type request := O.request and type response := O.response * Functor that builds an implementation of the IPC - handling functions given the request and response types and the appropriate string conversion functions . given the request and response types and the appropriate string conversion functions. *) end module Util : sig module Option : sig val either : (unit -> 'a) -> ('b -> 'a) -> 'b option -> 'a val some : 'a option -> 'a val default : 'a -> 'a option -> 'a val may : ('a -> unit) -> 'a option -> unit val maybe : ('a -> 'b option) -> 'a option -> 'b option val may_default : 'a -> ('b -> 'a) -> 'b option -> 'a val map : ('a -> 'b) -> 'a option -> 'b option val choose : 'a option -> 'a option -> 'a option val apply : 'a -> 'b -> ('b -> 'a) option -> 'a end end val daemon : (unit -> unit Lwt.t) -> unit Lwt.t * [ daemon f ] turns the current process into a daemon and subsequently calls [ f ] . The following steps are taken by the function : + The [ umask ] is set to 0 ; + [ fork ] is called and the parent process exits ; + The child process calls [ ] , ignores [ SIGHUP ] and [ ] , calls [ fork ] again and exits ; + The grandchild process changes the working directory to [ / ] , redirects [ stdin ] , [ stdout ] and [ stderr ] to [ /dev / null ] and calls [ f ] . calls [f]. The following steps are taken by the function: + The [umask] is set to 0; + [fork] is called and the parent process exits; + The child process calls [setsid], ignores [SIGHUP] and [SIGPIPE], calls [fork] again and exits; + The grandchild process changes the working directory to [/], redirects [stdin], [stdout] and [stderr] to [/dev/null] and calls [f]. *) val master_slave : slave:(command * Ipc.handler) -> ?background:bool -> ?logger:Lwt_log.logger -> ?privileged:bool -> ?slave_env:[`Inherit | `Keep of string list] -> ?control:(string * Ipc.handler) -> ?main:((unit -> (int * Ipc.connection) list) -> unit Lwt.t) -> lock_file:string -> unit -> unit * Sets up a master process with one slave . [ slave ] is a tuple whose first element contains the { ! command } associated to the slave process and second element is a callback function that is called in the master process to handle IPC requests from the slave ( see { ! ) . [ background ] indicates whether { ! daemon } will be called . Defaults to [ true ] . [ logger ] provides an optional logging facility for the master process . Defaults to a syslog logger . [ privileged ] indicates if the master process is to be run as [ root ] . Defaults to [ true ] . [ slave_env ] controls the environment variables available to the slave process . If [ slave_env ] is [ ` Inherit ] , the slave process will inherit the master 's full environment . Otherwise , if [ slave_env ] is [ ` Keep env ] , the slave process will only have access to the variables in the [ env ] list . Defaults to [ ` Keep [ " " ] ] . [ control ] , if present , is a tuple containing a path to a UNIX domain socket that will be created for communication with external process and a callback function that is called when data is sent on the socket . Release will set up a listener thread to deal with IPC on the control socket and each connection will be handled by a separate thread . [ main ] , if given , is a callback function that works as the main thread of the master process . This function receives as an argument a function that returns the current list of sockets that connect the master process to the slave processes . This is useful for broadcast - style communication from the master to the slaves . [ lock_file ] is the path to the lock file created by the master process . This file contains the PID of the master process . If the file already exists and contains the PID of a running process , the master will refuse to start . [slave] is a tuple whose first element contains the {!command} associated to the slave process and second element is a callback function that is called in the master process to handle IPC requests from the slave (see {!Ipc}). [background] indicates whether {!daemon} will be called. Defaults to [true]. [logger] provides an optional logging facility for the master process. Defaults to a syslog logger. [privileged] indicates if the master process is to be run as [root]. Defaults to [true]. [slave_env] controls the environment variables available to the slave process. If [slave_env] is [`Inherit], the slave process will inherit the master's full environment. Otherwise, if [slave_env] is [`Keep env], the slave process will only have access to the variables in the [env] list. Defaults to [`Keep ["OCAMLRUNPARAM"]]. [control], if present, is a tuple containing a path to a UNIX domain socket that will be created for communication with external process and a callback function that is called when data is sent on the socket. Release will set up a listener thread to deal with IPC on the control socket and each connection will be handled by a separate thread. [main], if given, is a callback function that works as the main thread of the master process. This function receives as an argument a function that returns the current list of sockets that connect the master process to the slave processes. This is useful for broadcast-style communication from the master to the slaves. [lock_file] is the path to the lock file created by the master process. This file contains the PID of the master process. If the file already exists and contains the PID of a running process, the master will refuse to start. *) val master_slaves : ?background:bool -> ?logger:Lwt_log.logger -> ?privileged:bool -> ?slave_env:[`Inherit | `Keep of string list] -> ?control:(string * Ipc.handler) -> ?main:((unit -> (int * Ipc.connection) list) -> unit Lwt.t) -> lock_file:string -> slaves:(command * Ipc.handler * int) list -> unit -> unit * This function generalizes { ! master_slave } , taking the same arguments , except for [ slave ] , which is substituted by [ slaves ] . This argument is a list of 3 - element tuples . The first element of the tuple is the { ! command } associated to the slave executable , the second element is the IPC handler for that slave and the third element is the number of instances to be created ( i.e. the number of times the appropriate command will be run . except for [slave], which is substituted by [slaves]. This argument is a list of 3-element tuples. The first element of the tuple is the {!command} associated to the slave executable, the second element is the IPC handler for that slave and the third element is the number of instances to be created (i.e. the number of times the appropriate command will be run. *) val me : ?logger:Lwt_log.logger -> ?user:string -> main:(Ipc.connection -> unit Lwt.t) -> unit -> unit * This function is supposed to be called in the slave process . [ logger ] provides an optional logging facility for the slave process . Defaults to a syslog logger . [ user ] , if present , indicates the name of the user the slave process will drop privileges to . Dropping privileges involves the following steps : + [ chroot ] to the users 's home directory ; + Change the current working directory to [ / ] ; + Call [ setgroups ] on the user 's GID ; + Call [ setgid ] and [ setuid ] on the user 's GID and UID , respectively ; + Check if privileges were successfully dropped . If [ user ] is not given , the slave process will run as the same user used to run the master process . [ main ] is a function that works as the entry point for the slave process code . The file descriptor given as an argument to [ main ] can be used by the slave for communication with the master . [logger] provides an optional logging facility for the slave process. Defaults to a syslog logger. [user], if present, indicates the name of the user the slave process will drop privileges to. Dropping privileges involves the following steps: + [chroot] to the users's home directory; + Change the current working directory to [/]; + Call [setgroups] on the user's GID; + Call [setgid] and [setuid] on the user's GID and UID, respectively; + Check if privileges were successfully dropped. If [user] is not given, the slave process will run as the same user used to run the master process. [main] is a function that works as the entry point for the slave process code. The file descriptor given as an argument to [main] can be used by the slave for communication with the master. *)
bff1a5ffe256f8e22604aefc6116ba3e194026afee4ce2a2001e98bb3b9ee881
ertugrulcetin/jme-clj
hello_asset.clj
;; Please start your REPL with `+test` profile (ns examples.beginner-tutorials.hello-asset "Clojure version of " (:require [jme-clj.core :refer :all])) (defn init [] (let [root-node (root-node) mat-default (material "Common/MatDefs/Misc/ShowNormals.j3md") teapot (load-model "Models/Teapot/Teapot.obj") teapot (set* teapot :material mat-default) root-node (attach-child root-node teapot) ;; Create a wall with a simple texture from test_data box (box 2.5 2.5 1.0) mat-brick (material "Common/MatDefs/Misc/Unshaded.j3md") texture (load-texture "Textures/Terrain/BrickWall/BrickWall.jpg") mat-brick (set* mat-brick :texture "ColorMap" texture) wall (geo "Box" box) wall (-> wall (set* :material mat-brick) (set* :local-translation 2.0 -2.5 0.0)) root-node (attach-child root-node wall) ;; Display a line of text with a default font gui-node (detach-all-child (gui-node)) gui-font (load-font "Interface/Fonts/Default.fnt") size (-> gui-font (get* :char-set) (get* :rendered-size)) hello-text (bitmap-text gui-font false) hello-text (-> hello-text (set* :size size) (set* :text "Hello World") (set* :local-translation 300 (get* hello-text :line-height) 0))] (attach-child gui-node hello-text) ; Load a model from test_data (OgreXML + material + texture) (-> (load-model "Models/Ninja/Ninja.mesh.xml") (scale 0.05 0.05 0.05) (rotate 0.0 -3.0 0.0) (set* :local-translation 0.0 -5.0 -2.0) (add-to-root)) ;; You must add a light to make the model visible (-> (light :directional) (set* :direction (vec3 -0.1 -0.7 -1.0)) (add-light-to-root)))) (defsimpleapp app :init init) (comment (start app) after calling unbind - app , we need to re - define the app with defsimpleapp (unbind-app #'app) (run app (re-init init)) )
null
https://raw.githubusercontent.com/ertugrulcetin/jme-clj/167ef8f9e6396cc6e3c234290c5698c098fcad28/test/examples/beginner_tutorials/hello_asset.clj
clojure
Please start your REPL with `+test` profile Create a wall with a simple texture from test_data Display a line of text with a default font Load a model from test_data (OgreXML + material + texture) You must add a light to make the model visible
(ns examples.beginner-tutorials.hello-asset "Clojure version of " (:require [jme-clj.core :refer :all])) (defn init [] (let [root-node (root-node) mat-default (material "Common/MatDefs/Misc/ShowNormals.j3md") teapot (load-model "Models/Teapot/Teapot.obj") teapot (set* teapot :material mat-default) root-node (attach-child root-node teapot) box (box 2.5 2.5 1.0) mat-brick (material "Common/MatDefs/Misc/Unshaded.j3md") texture (load-texture "Textures/Terrain/BrickWall/BrickWall.jpg") mat-brick (set* mat-brick :texture "ColorMap" texture) wall (geo "Box" box) wall (-> wall (set* :material mat-brick) (set* :local-translation 2.0 -2.5 0.0)) root-node (attach-child root-node wall) gui-node (detach-all-child (gui-node)) gui-font (load-font "Interface/Fonts/Default.fnt") size (-> gui-font (get* :char-set) (get* :rendered-size)) hello-text (bitmap-text gui-font false) hello-text (-> hello-text (set* :size size) (set* :text "Hello World") (set* :local-translation 300 (get* hello-text :line-height) 0))] (attach-child gui-node hello-text) (-> (load-model "Models/Ninja/Ninja.mesh.xml") (scale 0.05 0.05 0.05) (rotate 0.0 -3.0 0.0) (set* :local-translation 0.0 -5.0 -2.0) (add-to-root)) (-> (light :directional) (set* :direction (vec3 -0.1 -0.7 -1.0)) (add-light-to-root)))) (defsimpleapp app :init init) (comment (start app) after calling unbind - app , we need to re - define the app with defsimpleapp (unbind-app #'app) (run app (re-init init)) )
71d4f3ce04cd5f22ed4de2457204c574b69a1d1fd1bfa0570b3b144ac2d3d3af
dyzsr/ocaml-selectml
pr5026_bad.ml
TEST flags = " -w -a " ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output flags = " -w -a " ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) type untyped;; type -'a typed = private untyped;; type -'typing wrapped = private sexp and +'a t = 'a typed wrapped and sexp = private untyped wrapped;; class type ['a] s3 = object val underlying : 'a t end;; class ['a] s3object r : ['a] s3 = object val underlying = r end;;
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-private-bugs/pr5026_bad.ml
ocaml
TEST flags = " -w -a " ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output flags = " -w -a " ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) type untyped;; type -'a typed = private untyped;; type -'typing wrapped = private sexp and +'a t = 'a typed wrapped and sexp = private untyped wrapped;; class type ['a] s3 = object val underlying : 'a t end;; class ['a] s3object r : ['a] s3 = object val underlying = r end;;
108bbb081b62f21333c181811b0bae852a4b4d1a88f6aff278aef060b5253b86
larcenists/larceny
control.sps
(import (tests r6rs control) (tests scheme test) (scheme write)) (display "Running tests for (rnrs control)\n") (run-control-tests) (report-test-results)
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/R7RS/Lib/tests/r6rs/run/control.sps
scheme
(import (tests r6rs control) (tests scheme test) (scheme write)) (display "Running tests for (rnrs control)\n") (run-control-tests) (report-test-results)
2199691b217322a43d906c09256ebfb71c4ae5a65904d552c8842244e694dab3
gwkkwg/trivial-shell
utilities.lisp
(in-package #:com.metabang.trivial-shell) (defparameter *os-alist* '((:windows :windows :mswindows :win32) (:sun :solaris :sunos) (:osx :macosx :darwin :apple) (:linux :freebsd :netbsd :openbsd :bsd :linux :unix))) (defun host-os () (dolist (mapping *os-alist*) (destructuring-bind (os &rest features) mapping (dolist (f features) (when (find f *features*) (return-from host-os os)))))) #+(or) (defun os-pathname (pathname &key (os (os))) (namestring pathname)) (defun directory-pathname-p (pathname) "Does `pathname` syntactically represent a directory? A directory-pathname is a pathname _without_ a filename. The three ways that the filename components can be missing are for it to be `nil`, `:unspecific` or the empty string. " (flet ((check-one (x) (not (null (member x '(nil :unspecific "") :test 'equal))))) (and (check-one (pathname-name pathname)) (check-one (pathname-type pathname))))) #+(or) ;; from asdf-install (defun tar-argument (arg) "Given a filename argument for tar, massage it into our guess of the correct form based on the feature list." #-(or :win32 :mswindows :scl) (namestring (truename arg)) #+scl (ext:unix-namestring (truename arg)) Here we assume that if we 're in Windows , we 're running , and cygpath is available . We call out to cygpath here rather than ;; using shell backquoting. Relying on the shell can cause a host of ;; problems with argument quoting, so we won't assume that ;; RETURN-OUTPUT-FROM-PROGRAM will use a shell. [dwm] #+(or :win32 :mswindows) (with-input-from-string (s (return-output-from-program (find-program "cygpath.exe") (list (namestring (truename arg))))) (values (read-line s))))
null
https://raw.githubusercontent.com/gwkkwg/trivial-shell/e02ec191b34b52deca5d1c4ee99d4fa13b8772e0/dev/utilities.lisp
lisp
from asdf-install using shell backquoting. Relying on the shell can cause a host of problems with argument quoting, so we won't assume that RETURN-OUTPUT-FROM-PROGRAM will use a shell. [dwm]
(in-package #:com.metabang.trivial-shell) (defparameter *os-alist* '((:windows :windows :mswindows :win32) (:sun :solaris :sunos) (:osx :macosx :darwin :apple) (:linux :freebsd :netbsd :openbsd :bsd :linux :unix))) (defun host-os () (dolist (mapping *os-alist*) (destructuring-bind (os &rest features) mapping (dolist (f features) (when (find f *features*) (return-from host-os os)))))) #+(or) (defun os-pathname (pathname &key (os (os))) (namestring pathname)) (defun directory-pathname-p (pathname) "Does `pathname` syntactically represent a directory? A directory-pathname is a pathname _without_ a filename. The three ways that the filename components can be missing are for it to be `nil`, `:unspecific` or the empty string. " (flet ((check-one (x) (not (null (member x '(nil :unspecific "") :test 'equal))))) (and (check-one (pathname-name pathname)) (check-one (pathname-type pathname))))) #+(or) (defun tar-argument (arg) "Given a filename argument for tar, massage it into our guess of the correct form based on the feature list." #-(or :win32 :mswindows :scl) (namestring (truename arg)) #+scl (ext:unix-namestring (truename arg)) Here we assume that if we 're in Windows , we 're running , and cygpath is available . We call out to cygpath here rather than #+(or :win32 :mswindows) (with-input-from-string (s (return-output-from-program (find-program "cygpath.exe") (list (namestring (truename arg))))) (values (read-line s))))
c9395bcb57ca4258fd542b60ba62635cf83549e8c92d1ae1f5b09386a5dfe913
xtdb/core2
tx_producer.clj
(ns core2.tx-producer (:require [clojure.spec.alpha :as s] [core2.error :as err] core2.log [core2.rewrite :refer [zmatch]] [core2.sql :as sql] [core2.types :as types] [core2.util :as util] [core2.vector.writer :as vw] [juxt.clojars-mirrors.integrant.core :as ig]) (:import (core2.log Log LogRecord) core2.vector.IDenseUnionWriter (java.time Instant ZoneId) java.util.ArrayList org.apache.arrow.memory.BufferAllocator (org.apache.arrow.vector TimeStampMicroTZVector VectorSchemaRoot) (org.apache.arrow.vector.complex DenseUnionVector) (org.apache.arrow.vector.types.pojo ArrowType$Union Schema) org.apache.arrow.vector.types.UnionMode)) #_{:clj-kondo/ignore [:unused-binding]} (definterface ITxProducer (submitTx ^java.util.concurrent.CompletableFuture #_<TransactionInstant> [^java.util.List txOps]) (submitTx ^java.util.concurrent.CompletableFuture #_<TransactionInstant> [^java.util.List txOps, ^java.util.Map opts])) (s/def ::id any?) (s/def ::doc (s/keys :req-un [::id])) (s/def ::app-time-start inst?) (s/def ::app-time-end inst?) #_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]} (s/def ::app-time-as-of-now? boolean) (defmulti tx-op-spec first) (defmethod tx-op-spec :sql [_] (s/cat :op #{:sql} :query string? :params (s/? (s/or :rows (s/coll-of (s/coll-of any? :kind sequential?) :kind sequential?) :bytes #(= :varbinary (types/value->col-type %)))))) (defmethod tx-op-spec :put [_] (s/cat :op #{:put} :doc ::doc :app-time-opts (s/? (s/keys :opt-un [::app-time-start ::app-time-end])))) (defmethod tx-op-spec :delete [_] (s/cat :op #{:delete} :table (s/? string?) :id ::id :app-time-opts (s/? (s/keys :opt-un [::app-time-start ::app-time-end])))) (defmethod tx-op-spec :evict [_] eventually this could have app - time / sys start / end ? (s/cat :op #{:evict} :table (s/? string?) :id ::id)) required for C1 importer (defmethod tx-op-spec :abort [_] (s/cat :op #{:abort})) (defmethod tx-op-spec :call [_] (s/cat :op #{:call} :fn-id ::id :args (s/* any?))) (s/def ::tx-op (s/and vector? (s/multi-spec tx-op-spec (fn [v _] v)))) (s/def ::tx-ops (s/coll-of ::tx-op :kind sequential?)) (defn conform-tx-ops [tx-ops] (let [parsed-tx-ops (s/conform ::tx-ops tx-ops)] (when (s/invalid? parsed-tx-ops) (throw (err/illegal-arg :core2/invalid-tx-ops {::err/message (str "Invalid tx ops: " (s/explain-str ::tx-ops tx-ops)) :tx-ops tx-ops :explain-data (s/explain-data ::tx-ops tx-ops)}))) parsed-tx-ops)) (def ^:private nullable-inst-type [:union #{:null [:timestamp-tz :micro "UTC"]}]) (def ^:private ^org.apache.arrow.vector.types.pojo.Field tx-ops-field (types/->field "tx-ops" (ArrowType$Union. UnionMode/Dense (int-array (range 6))) false (types/col-type->field 'sql [:struct {:query :utf8 :params [:union #{:null :varbinary}]}]) (types/->field "put" types/struct-type false (types/col-type->field 'table :utf8) (types/->field "id" types/dense-union-type false) (types/->field "document" types/dense-union-type false) (types/col-type->field 'application_time_start nullable-inst-type) (types/col-type->field 'application_time_end nullable-inst-type)) (types/->field "delete" types/struct-type false (types/col-type->field 'table :utf8) (types/->field "id" types/dense-union-type false) (types/col-type->field 'application_time_start nullable-inst-type) (types/col-type->field 'application_time_end nullable-inst-type)) (types/->field "evict" types/struct-type false (types/col-type->field '_table [:union #{:null :utf8}]) (types/->field "id" types/dense-union-type false)) (types/->field "call" types/struct-type false (types/->field "fn-id" types/dense-union-type false) (types/->field "args" types/list-type false (types/->field "arg" types/dense-union-type false))) ;; C1 importer (types/col-type->field 'abort :null))) (def ^:private ^org.apache.arrow.vector.types.pojo.Schema tx-schema (Schema. [(types/->field "tx-ops" types/list-type false tx-ops-field) (types/col-type->field "system-time" nullable-inst-type) (types/col-type->field "default-tz" :utf8) (types/col-type->field "application-time-as-of-now?" :bool)])) (defn encode-params [^BufferAllocator allocator, query, param-rows] (let [plan (sql/compile-query query) {:keys [^long param-count]} (meta plan) vecs (ArrayList. param-count)] (try ;; TODO check param count in each row, handle error (dotimes [col-idx param-count] (.add vecs (vw/open-vec allocator (symbol (str "?_" col-idx)) (mapv #(nth % col-idx) param-rows)))) (let [root (doto (VectorSchemaRoot. vecs) (.setRowCount (count param-rows)))] (util/build-arrow-ipc-byte-buffer root :stream (fn [write-batch!] (write-batch!)))) (finally (run! util/try-close vecs))))) (defn- ->sql-writer [^IDenseUnionWriter tx-ops-writer, ^BufferAllocator allocator] (let [sql-writer (.asStruct (.writerForTypeId tx-ops-writer 0)) query-writer (.writerForName sql-writer "query") params-writer (.writerForName sql-writer "params")] (fn write-sql! [{:keys [query params]}] (.startValue sql-writer) (types/write-value! query query-writer) (when params (zmatch params [:rows param-rows] (types/write-value! (encode-params allocator query param-rows) params-writer) [:bytes param-bytes] (types/write-value! param-bytes params-writer))) (.endValue sql-writer)))) (defn- ->put-writer [^IDenseUnionWriter tx-ops-writer] (let [put-writer (.asStruct (.writerForTypeId tx-ops-writer 1)) table-writer (.writerForName put-writer "table") id-writer (.asDenseUnion (.writerForName put-writer "id")) doc-writer (.asDenseUnion (.writerForName put-writer "document")) app-time-start-writer (.writerForName put-writer "application_time_start") app-time-end-writer (.writerForName put-writer "application_time_end")] (fn write-put! [{:keys [doc], {:keys [app-time-start app-time-end]} :app-time-opts}] (.startValue put-writer) (let [{:keys [id]} doc] (doto (.writerForType id-writer (types/value->col-type id)) (.startValue) (->> (types/write-value! id)) (.endValue))) (let [doc (dissoc doc :_table :id)] (doto (.writerForType doc-writer (types/value->col-type doc)) (.startValue) (->> (types/write-value! doc)) (.endValue))) (types/write-value! (name (:_table doc "xt_docs")) table-writer) (types/write-value! app-time-start app-time-start-writer) (types/write-value! app-time-end app-time-end-writer) (.endValue put-writer)))) (defn- ->delete-writer [^IDenseUnionWriter tx-ops-writer] (let [delete-writer (.asStruct (.writerForTypeId tx-ops-writer 2)) table-writer (.writerForName delete-writer "table") id-writer (.asDenseUnion (.writerForName delete-writer "id")) app-time-start-writer (.writerForName delete-writer "application_time_start") app-time-end-writer (.writerForName delete-writer "application_time_end")] (fn write-delete! [{:keys [id table], {:keys [app-time-start app-time-end]} :app-time-opts :or {table "xt_docs"}}] (.startValue delete-writer) (types/write-value! table table-writer) (doto (-> id-writer (.writerForType (types/value->col-type id))) (.startValue) (->> (types/write-value! id)) (.endValue)) (types/write-value! app-time-start app-time-start-writer) (types/write-value! app-time-end app-time-end-writer) (.endValue delete-writer)))) (defn- ->evict-writer [^IDenseUnionWriter tx-ops-writer] (let [evict-writer (.asStruct (.writerForTypeId tx-ops-writer 3)) table-writer (.writerForName evict-writer "_table") id-writer (.asDenseUnion (.writerForName evict-writer "id"))] (fn [{:keys [table id]}] (.startValue evict-writer) (some-> table (types/write-value! table-writer)) (doto (-> id-writer (.writerForType (types/value->col-type id))) (.startValue) (->> (types/write-value! id)) (.endValue)) (.endValue evict-writer)))) (defn- ->call-writer [^IDenseUnionWriter tx-ops-writer] (let [call-writer (.asStruct (.writerForTypeId tx-ops-writer 4)) fn-id-writer (.asDenseUnion (.writerForName call-writer "fn-id")) args-list-writer (.asList (.writerForName call-writer "args"))] (fn write-call! [{:keys [fn-id args]}] (.startValue call-writer) (doto (-> fn-id-writer (.writerForType (types/value->col-type fn-id))) (.startValue) (->> (types/write-value! fn-id)) (.endValue)) (types/write-value! (vec args) args-list-writer) (.endValue call-writer)))) (defn- ->abort-writer [^IDenseUnionWriter tx-ops-writer] (let [abort-writer (.writerForTypeId tx-ops-writer 5)] (fn [_] (.startValue abort-writer) (.endValue abort-writer)))) (defn open-tx-ops-vec ^org.apache.arrow.vector.ValueVector [^BufferAllocator allocator] (.createVector tx-ops-field allocator)) (defn write-tx-ops! [^BufferAllocator allocator, ^IDenseUnionWriter tx-ops-writer, tx-ops] (let [tx-ops (conform-tx-ops tx-ops) op-count (count tx-ops) write-sql! (->sql-writer tx-ops-writer allocator) write-put! (->put-writer tx-ops-writer) write-delete! (->delete-writer tx-ops-writer) write-evict! (->evict-writer tx-ops-writer) write-call! (->call-writer tx-ops-writer) write-abort! (->abort-writer tx-ops-writer)] (dotimes [tx-op-n op-count] (.startValue tx-ops-writer) (let [tx-op (nth tx-ops tx-op-n)] (case (:op tx-op) :sql (write-sql! tx-op) :put (write-put! tx-op) :delete (write-delete! tx-op) :evict (write-evict! tx-op) :call (write-call! tx-op) :abort (write-abort! tx-op))) (.endValue tx-ops-writer)))) (defn serialize-tx-ops ^java.nio.ByteBuffer [^BufferAllocator allocator tx-ops {:keys [^Instant sys-time, default-tz, app-time-as-of-now?]}] (with-open [root (VectorSchemaRoot/create tx-schema allocator)] (let [ops-list-writer (.asList (vw/vec->writer (.getVector root "tx-ops"))) tx-ops-writer (.asDenseUnion (.getDataWriter ops-list-writer)) default-tz-writer (vw/vec->writer (.getVector root "default-tz")) app-time-behaviour-writer (vw/vec->writer (.getVector root "application-time-as-of-now?"))] (when sys-time (doto ^TimeStampMicroTZVector (.getVector root "system-time") (.setSafe 0 (util/instant->micros sys-time)))) (types/write-value! (str default-tz) default-tz-writer) (types/write-value! (boolean app-time-as-of-now?) app-time-behaviour-writer) (.startValue ops-list-writer) (write-tx-ops! allocator tx-ops-writer tx-ops) (.endValue ops-list-writer) (.setRowCount root 1) (.syncSchema root) (util/root->arrow-ipc-byte-buffer root :stream)))) (deftype TxProducer [^BufferAllocator allocator, ^Log log, ^ZoneId default-tz] ITxProducer (submitTx [this tx-ops] (.submitTx this tx-ops {})) (submitTx [_ tx-ops opts] (let [{:keys [sys-time] :as opts} (-> (into {:default-tz default-tz} opts) (util/maybe-update :sys-time util/->instant))] (-> (.appendRecord log (serialize-tx-ops allocator tx-ops opts)) (util/then-apply (fn [^LogRecord result] (cond-> (.tx result) sys-time (assoc :sys-time sys-time)))))))) (defmethod ig/prep-key ::tx-producer [_ opts] (merge {:log (ig/ref :core2/log) :allocator (ig/ref :core2/allocator) :default-tz (ig/ref :core2/default-tz)} opts)) (defmethod ig/init-key ::tx-producer [_ {:keys [log allocator default-tz]}] (TxProducer. allocator log default-tz))
null
https://raw.githubusercontent.com/xtdb/core2/3adeb391ca4dd73a3f79faba8024289376597d23/core/src/main/clojure/core2/tx_producer.clj
clojure
C1 importer TODO check param count in each row, handle error
(ns core2.tx-producer (:require [clojure.spec.alpha :as s] [core2.error :as err] core2.log [core2.rewrite :refer [zmatch]] [core2.sql :as sql] [core2.types :as types] [core2.util :as util] [core2.vector.writer :as vw] [juxt.clojars-mirrors.integrant.core :as ig]) (:import (core2.log Log LogRecord) core2.vector.IDenseUnionWriter (java.time Instant ZoneId) java.util.ArrayList org.apache.arrow.memory.BufferAllocator (org.apache.arrow.vector TimeStampMicroTZVector VectorSchemaRoot) (org.apache.arrow.vector.complex DenseUnionVector) (org.apache.arrow.vector.types.pojo ArrowType$Union Schema) org.apache.arrow.vector.types.UnionMode)) #_{:clj-kondo/ignore [:unused-binding]} (definterface ITxProducer (submitTx ^java.util.concurrent.CompletableFuture #_<TransactionInstant> [^java.util.List txOps]) (submitTx ^java.util.concurrent.CompletableFuture #_<TransactionInstant> [^java.util.List txOps, ^java.util.Map opts])) (s/def ::id any?) (s/def ::doc (s/keys :req-un [::id])) (s/def ::app-time-start inst?) (s/def ::app-time-end inst?) #_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]} (s/def ::app-time-as-of-now? boolean) (defmulti tx-op-spec first) (defmethod tx-op-spec :sql [_] (s/cat :op #{:sql} :query string? :params (s/? (s/or :rows (s/coll-of (s/coll-of any? :kind sequential?) :kind sequential?) :bytes #(= :varbinary (types/value->col-type %)))))) (defmethod tx-op-spec :put [_] (s/cat :op #{:put} :doc ::doc :app-time-opts (s/? (s/keys :opt-un [::app-time-start ::app-time-end])))) (defmethod tx-op-spec :delete [_] (s/cat :op #{:delete} :table (s/? string?) :id ::id :app-time-opts (s/? (s/keys :opt-un [::app-time-start ::app-time-end])))) (defmethod tx-op-spec :evict [_] eventually this could have app - time / sys start / end ? (s/cat :op #{:evict} :table (s/? string?) :id ::id)) required for C1 importer (defmethod tx-op-spec :abort [_] (s/cat :op #{:abort})) (defmethod tx-op-spec :call [_] (s/cat :op #{:call} :fn-id ::id :args (s/* any?))) (s/def ::tx-op (s/and vector? (s/multi-spec tx-op-spec (fn [v _] v)))) (s/def ::tx-ops (s/coll-of ::tx-op :kind sequential?)) (defn conform-tx-ops [tx-ops] (let [parsed-tx-ops (s/conform ::tx-ops tx-ops)] (when (s/invalid? parsed-tx-ops) (throw (err/illegal-arg :core2/invalid-tx-ops {::err/message (str "Invalid tx ops: " (s/explain-str ::tx-ops tx-ops)) :tx-ops tx-ops :explain-data (s/explain-data ::tx-ops tx-ops)}))) parsed-tx-ops)) (def ^:private nullable-inst-type [:union #{:null [:timestamp-tz :micro "UTC"]}]) (def ^:private ^org.apache.arrow.vector.types.pojo.Field tx-ops-field (types/->field "tx-ops" (ArrowType$Union. UnionMode/Dense (int-array (range 6))) false (types/col-type->field 'sql [:struct {:query :utf8 :params [:union #{:null :varbinary}]}]) (types/->field "put" types/struct-type false (types/col-type->field 'table :utf8) (types/->field "id" types/dense-union-type false) (types/->field "document" types/dense-union-type false) (types/col-type->field 'application_time_start nullable-inst-type) (types/col-type->field 'application_time_end nullable-inst-type)) (types/->field "delete" types/struct-type false (types/col-type->field 'table :utf8) (types/->field "id" types/dense-union-type false) (types/col-type->field 'application_time_start nullable-inst-type) (types/col-type->field 'application_time_end nullable-inst-type)) (types/->field "evict" types/struct-type false (types/col-type->field '_table [:union #{:null :utf8}]) (types/->field "id" types/dense-union-type false)) (types/->field "call" types/struct-type false (types/->field "fn-id" types/dense-union-type false) (types/->field "args" types/list-type false (types/->field "arg" types/dense-union-type false))) (types/col-type->field 'abort :null))) (def ^:private ^org.apache.arrow.vector.types.pojo.Schema tx-schema (Schema. [(types/->field "tx-ops" types/list-type false tx-ops-field) (types/col-type->field "system-time" nullable-inst-type) (types/col-type->field "default-tz" :utf8) (types/col-type->field "application-time-as-of-now?" :bool)])) (defn encode-params [^BufferAllocator allocator, query, param-rows] (let [plan (sql/compile-query query) {:keys [^long param-count]} (meta plan) vecs (ArrayList. param-count)] (try (dotimes [col-idx param-count] (.add vecs (vw/open-vec allocator (symbol (str "?_" col-idx)) (mapv #(nth % col-idx) param-rows)))) (let [root (doto (VectorSchemaRoot. vecs) (.setRowCount (count param-rows)))] (util/build-arrow-ipc-byte-buffer root :stream (fn [write-batch!] (write-batch!)))) (finally (run! util/try-close vecs))))) (defn- ->sql-writer [^IDenseUnionWriter tx-ops-writer, ^BufferAllocator allocator] (let [sql-writer (.asStruct (.writerForTypeId tx-ops-writer 0)) query-writer (.writerForName sql-writer "query") params-writer (.writerForName sql-writer "params")] (fn write-sql! [{:keys [query params]}] (.startValue sql-writer) (types/write-value! query query-writer) (when params (zmatch params [:rows param-rows] (types/write-value! (encode-params allocator query param-rows) params-writer) [:bytes param-bytes] (types/write-value! param-bytes params-writer))) (.endValue sql-writer)))) (defn- ->put-writer [^IDenseUnionWriter tx-ops-writer] (let [put-writer (.asStruct (.writerForTypeId tx-ops-writer 1)) table-writer (.writerForName put-writer "table") id-writer (.asDenseUnion (.writerForName put-writer "id")) doc-writer (.asDenseUnion (.writerForName put-writer "document")) app-time-start-writer (.writerForName put-writer "application_time_start") app-time-end-writer (.writerForName put-writer "application_time_end")] (fn write-put! [{:keys [doc], {:keys [app-time-start app-time-end]} :app-time-opts}] (.startValue put-writer) (let [{:keys [id]} doc] (doto (.writerForType id-writer (types/value->col-type id)) (.startValue) (->> (types/write-value! id)) (.endValue))) (let [doc (dissoc doc :_table :id)] (doto (.writerForType doc-writer (types/value->col-type doc)) (.startValue) (->> (types/write-value! doc)) (.endValue))) (types/write-value! (name (:_table doc "xt_docs")) table-writer) (types/write-value! app-time-start app-time-start-writer) (types/write-value! app-time-end app-time-end-writer) (.endValue put-writer)))) (defn- ->delete-writer [^IDenseUnionWriter tx-ops-writer] (let [delete-writer (.asStruct (.writerForTypeId tx-ops-writer 2)) table-writer (.writerForName delete-writer "table") id-writer (.asDenseUnion (.writerForName delete-writer "id")) app-time-start-writer (.writerForName delete-writer "application_time_start") app-time-end-writer (.writerForName delete-writer "application_time_end")] (fn write-delete! [{:keys [id table], {:keys [app-time-start app-time-end]} :app-time-opts :or {table "xt_docs"}}] (.startValue delete-writer) (types/write-value! table table-writer) (doto (-> id-writer (.writerForType (types/value->col-type id))) (.startValue) (->> (types/write-value! id)) (.endValue)) (types/write-value! app-time-start app-time-start-writer) (types/write-value! app-time-end app-time-end-writer) (.endValue delete-writer)))) (defn- ->evict-writer [^IDenseUnionWriter tx-ops-writer] (let [evict-writer (.asStruct (.writerForTypeId tx-ops-writer 3)) table-writer (.writerForName evict-writer "_table") id-writer (.asDenseUnion (.writerForName evict-writer "id"))] (fn [{:keys [table id]}] (.startValue evict-writer) (some-> table (types/write-value! table-writer)) (doto (-> id-writer (.writerForType (types/value->col-type id))) (.startValue) (->> (types/write-value! id)) (.endValue)) (.endValue evict-writer)))) (defn- ->call-writer [^IDenseUnionWriter tx-ops-writer] (let [call-writer (.asStruct (.writerForTypeId tx-ops-writer 4)) fn-id-writer (.asDenseUnion (.writerForName call-writer "fn-id")) args-list-writer (.asList (.writerForName call-writer "args"))] (fn write-call! [{:keys [fn-id args]}] (.startValue call-writer) (doto (-> fn-id-writer (.writerForType (types/value->col-type fn-id))) (.startValue) (->> (types/write-value! fn-id)) (.endValue)) (types/write-value! (vec args) args-list-writer) (.endValue call-writer)))) (defn- ->abort-writer [^IDenseUnionWriter tx-ops-writer] (let [abort-writer (.writerForTypeId tx-ops-writer 5)] (fn [_] (.startValue abort-writer) (.endValue abort-writer)))) (defn open-tx-ops-vec ^org.apache.arrow.vector.ValueVector [^BufferAllocator allocator] (.createVector tx-ops-field allocator)) (defn write-tx-ops! [^BufferAllocator allocator, ^IDenseUnionWriter tx-ops-writer, tx-ops] (let [tx-ops (conform-tx-ops tx-ops) op-count (count tx-ops) write-sql! (->sql-writer tx-ops-writer allocator) write-put! (->put-writer tx-ops-writer) write-delete! (->delete-writer tx-ops-writer) write-evict! (->evict-writer tx-ops-writer) write-call! (->call-writer tx-ops-writer) write-abort! (->abort-writer tx-ops-writer)] (dotimes [tx-op-n op-count] (.startValue tx-ops-writer) (let [tx-op (nth tx-ops tx-op-n)] (case (:op tx-op) :sql (write-sql! tx-op) :put (write-put! tx-op) :delete (write-delete! tx-op) :evict (write-evict! tx-op) :call (write-call! tx-op) :abort (write-abort! tx-op))) (.endValue tx-ops-writer)))) (defn serialize-tx-ops ^java.nio.ByteBuffer [^BufferAllocator allocator tx-ops {:keys [^Instant sys-time, default-tz, app-time-as-of-now?]}] (with-open [root (VectorSchemaRoot/create tx-schema allocator)] (let [ops-list-writer (.asList (vw/vec->writer (.getVector root "tx-ops"))) tx-ops-writer (.asDenseUnion (.getDataWriter ops-list-writer)) default-tz-writer (vw/vec->writer (.getVector root "default-tz")) app-time-behaviour-writer (vw/vec->writer (.getVector root "application-time-as-of-now?"))] (when sys-time (doto ^TimeStampMicroTZVector (.getVector root "system-time") (.setSafe 0 (util/instant->micros sys-time)))) (types/write-value! (str default-tz) default-tz-writer) (types/write-value! (boolean app-time-as-of-now?) app-time-behaviour-writer) (.startValue ops-list-writer) (write-tx-ops! allocator tx-ops-writer tx-ops) (.endValue ops-list-writer) (.setRowCount root 1) (.syncSchema root) (util/root->arrow-ipc-byte-buffer root :stream)))) (deftype TxProducer [^BufferAllocator allocator, ^Log log, ^ZoneId default-tz] ITxProducer (submitTx [this tx-ops] (.submitTx this tx-ops {})) (submitTx [_ tx-ops opts] (let [{:keys [sys-time] :as opts} (-> (into {:default-tz default-tz} opts) (util/maybe-update :sys-time util/->instant))] (-> (.appendRecord log (serialize-tx-ops allocator tx-ops opts)) (util/then-apply (fn [^LogRecord result] (cond-> (.tx result) sys-time (assoc :sys-time sys-time)))))))) (defmethod ig/prep-key ::tx-producer [_ opts] (merge {:log (ig/ref :core2/log) :allocator (ig/ref :core2/allocator) :default-tz (ig/ref :core2/default-tz)} opts)) (defmethod ig/init-key ::tx-producer [_ {:keys [log allocator default-tz]}] (TxProducer. allocator log default-tz))
f7b498ad385cd073b7b59e7bea1a8bf97fb71cd66b8ec88314d7f6f390f5f5f1
arvyy/racket-raylib-2d
colors.rkt
#lang racket/base (provide (all-defined-out)) (require "structs.rkt") (define LIGHTGRAY (make-Color 200 200 200 255 )) (define GRAY (make-Color 130 130 130 255 )) (define DARKGRAY (make-Color 80 80 80 255 )) (define YELLOW (make-Color 253 249 0 255 )) (define GOLD (make-Color 255 203 0 255 )) (define ORANGE (make-Color 255 161 0 255 )) (define PINK (make-Color 255 109 194 255 )) (define RED (make-Color 230 41 55 255 )) (define MAROON (make-Color 190 33 55 255 )) (define GREEN (make-Color 0 228 48 255 )) (define LIME (make-Color 0 158 47 255 )) (define DARKGREEN (make-Color 0 117 44 255 )) (define SKYBLUE (make-Color 102 191 255 255 )) (define BLUE (make-Color 0 121 241 255 )) (define DARKBLUE (make-Color 0 82 172 255 )) (define PURPLE (make-Color 200 122 255 255 )) (define VIOLET (make-Color 135 60 190 255 )) (define DARKPURPLE (make-Color 112 31 126 255 )) (define BEIGE (make-Color 211 176 131 255 )) (define BROWN (make-Color 127 106 79 255 )) (define DARKBROWN (make-Color 76 63 47 255 )) (define WHITE (make-Color 255 255 255 255 )) (define BLACK (make-Color 0 0 0 255 )) (define BLANK (make-Color 0 0 0 0 )) (define MAGENTA (make-Color 255 0 255 255 )) (define RAYWHITE (make-Color 245 245 245 255 ))
null
https://raw.githubusercontent.com/arvyy/racket-raylib-2d/2f0b05f37e6bd81cf4246116c7d32f2744dc53c0/colors.rkt
racket
#lang racket/base (provide (all-defined-out)) (require "structs.rkt") (define LIGHTGRAY (make-Color 200 200 200 255 )) (define GRAY (make-Color 130 130 130 255 )) (define DARKGRAY (make-Color 80 80 80 255 )) (define YELLOW (make-Color 253 249 0 255 )) (define GOLD (make-Color 255 203 0 255 )) (define ORANGE (make-Color 255 161 0 255 )) (define PINK (make-Color 255 109 194 255 )) (define RED (make-Color 230 41 55 255 )) (define MAROON (make-Color 190 33 55 255 )) (define GREEN (make-Color 0 228 48 255 )) (define LIME (make-Color 0 158 47 255 )) (define DARKGREEN (make-Color 0 117 44 255 )) (define SKYBLUE (make-Color 102 191 255 255 )) (define BLUE (make-Color 0 121 241 255 )) (define DARKBLUE (make-Color 0 82 172 255 )) (define PURPLE (make-Color 200 122 255 255 )) (define VIOLET (make-Color 135 60 190 255 )) (define DARKPURPLE (make-Color 112 31 126 255 )) (define BEIGE (make-Color 211 176 131 255 )) (define BROWN (make-Color 127 106 79 255 )) (define DARKBROWN (make-Color 76 63 47 255 )) (define WHITE (make-Color 255 255 255 255 )) (define BLACK (make-Color 0 0 0 255 )) (define BLANK (make-Color 0 0 0 0 )) (define MAGENTA (make-Color 255 0 255 255 )) (define RAYWHITE (make-Color 245 245 245 255 ))
1ed6f2eae26c1f59575ab7e146b74675bc68e4363955912af07091c5a936c010
pirapira/coq2rust
ppstyle.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (** Highlighting of printers. Used for pretty-printing terms that should be displayed on a color-capable terminal. *) * { 5 Style tags } type t (** Style tags *) val make : ?style:Terminal.style -> string list -> t (** Create a new tag with the given name. Each name must be unique. The optional style is taken as the default one. *) val repr : t -> string list (** Gives back the original name of the style tag where each string has been concatenated and separated with a dot. *) val tag : t Pp.Tag.key (** An annotation for styles *) * { 5 Manipulating global styles } val get_style : t -> Terminal.style option (** Get the style associated to a tag. *) val set_style : t -> Terminal.style option -> unit (** Set a style associated to a tag. *) val clear_styles : unit -> unit (** Clear all styles. *) val parse_config : string -> unit (** Add all styles from the given string as parsed by {!Terminal.parse}. Unregistered tags are ignored. *) val dump : unit -> (t * Terminal.style option) list (** Recover the list of known tags together with their current style. *) * { 5 Setting color output } val init_color_output : unit -> unit * Once called , all tags defined here will use their current style when printed . To this end , this function redefines the loggers used when sending messages to the user . The program will in particular use the formatters { ! Pp_control.std_ft } and { ! Pp_control.err_ft } to display those messages , with additional syle information provided by this module . Be careful this is not compatible with the Emacs mode ! printed. To this end, this function redefines the loggers used when sending messages to the user. The program will in particular use the formatters {!Pp_control.std_ft} and {!Pp_control.err_ft} to display those messages, with additional syle information provided by this module. Be careful this is not compatible with the Emacs mode! *) val pp_tag : Pp.tag_handler (** Returns the name of a style tag that is understandable by the formatters that have been inititialized through {!init_color_output}. To be used with {!Pp.pp_with}. *) * { 5 Tags } val error_tag : t (** Tag used by the {!Pp.msg_error} function. *) val warning_tag : t (** Tag used by the {!Pp.msg_warning} function. *) val debug_tag : t (** Tag used by the {!Pp.msg_debug} function. *)
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/printing/ppstyle.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Highlighting of printers. Used for pretty-printing terms that should be displayed on a color-capable terminal. * Style tags * Create a new tag with the given name. Each name must be unique. The optional style is taken as the default one. * Gives back the original name of the style tag where each string has been concatenated and separated with a dot. * An annotation for styles * Get the style associated to a tag. * Set a style associated to a tag. * Clear all styles. * Add all styles from the given string as parsed by {!Terminal.parse}. Unregistered tags are ignored. * Recover the list of known tags together with their current style. * Returns the name of a style tag that is understandable by the formatters that have been inititialized through {!init_color_output}. To be used with {!Pp.pp_with}. * Tag used by the {!Pp.msg_error} function. * Tag used by the {!Pp.msg_warning} function. * Tag used by the {!Pp.msg_debug} function.
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * { 5 Style tags } type t val make : ?style:Terminal.style -> string list -> t val repr : t -> string list val tag : t Pp.Tag.key * { 5 Manipulating global styles } val get_style : t -> Terminal.style option val set_style : t -> Terminal.style option -> unit val clear_styles : unit -> unit val parse_config : string -> unit val dump : unit -> (t * Terminal.style option) list * { 5 Setting color output } val init_color_output : unit -> unit * Once called , all tags defined here will use their current style when printed . To this end , this function redefines the loggers used when sending messages to the user . The program will in particular use the formatters { ! Pp_control.std_ft } and { ! Pp_control.err_ft } to display those messages , with additional syle information provided by this module . Be careful this is not compatible with the Emacs mode ! printed. To this end, this function redefines the loggers used when sending messages to the user. The program will in particular use the formatters {!Pp_control.std_ft} and {!Pp_control.err_ft} to display those messages, with additional syle information provided by this module. Be careful this is not compatible with the Emacs mode! *) val pp_tag : Pp.tag_handler * { 5 Tags } val error_tag : t val warning_tag : t val debug_tag : t
c3dad23d8774f3951398b8fa71a78cfbb285c4e7ff7b3c87f6ede24239fbdda2
haskell-compat/base-compat
Batteries.hs
{-# LANGUAGE PackageImports #-} # OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports # | Reexports " Control . . Compat " -- from a globally unique namespace. module Control.Monad.Compat.Repl.Batteries ( module Control.Monad.Compat ) where import "this" Control.Monad.Compat
null
https://raw.githubusercontent.com/haskell-compat/base-compat/847aa35c4142f529525ffc645cd035ddb23ce8ee/base-compat-batteries/src/Control/Monad/Compat/Repl/Batteries.hs
haskell
# LANGUAGE PackageImports # from a globally unique namespace.
# OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports # | Reexports " Control . . Compat " module Control.Monad.Compat.Repl.Batteries ( module Control.Monad.Compat ) where import "this" Control.Monad.Compat
9492dac9431598b1eb897c3d1b8222d78476b09a266a28d83cca2e5605737845
holdybot/holdybot
dev_middleware.clj
(ns parky.dev-middleware (:require [ring.middleware.reload :refer [wrap-reload]] [selmer.middleware :refer [wrap-error-page]] [prone.middleware :refer [wrap-exceptions]])) (defn wrap-dev [handler] (-> handler wrap-reload wrap-error-page (wrap-exceptions {:app-namespaces ['parky]})))
null
https://raw.githubusercontent.com/holdybot/holdybot/e65007a3113c89b3f457b9d966d6bf305983c975/env/dev/clj/parky/dev_middleware.clj
clojure
(ns parky.dev-middleware (:require [ring.middleware.reload :refer [wrap-reload]] [selmer.middleware :refer [wrap-error-page]] [prone.middleware :refer [wrap-exceptions]])) (defn wrap-dev [handler] (-> handler wrap-reload wrap-error-page (wrap-exceptions {:app-namespaces ['parky]})))
f620d1aa68dcd716d41e14edf986b56e3767a5c34f1fe8c05d47b9d9021e2781
melange-re/melange
ext_list.mli
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val map : 'a list -> ('a -> 'b) -> 'b list val map_combine : 'a list -> 'b list -> ('a -> 'c) -> ('c * 'b) list val combine_array : 'a array -> 'b list -> ('a -> 'c) -> ('c * 'b) list val combine_array_append : 'a array -> 'b list -> ('c * 'b) list -> ('a -> 'c) -> ('c * 'b) list val has_string : string list -> string -> bool val map_split_opt : 'a list -> ('a -> 'b option * 'c option) -> 'b list * 'c list val mapi : 'a list -> (int -> 'a -> 'b) -> 'b list val mapi_append : 'a list -> (int -> 'a -> 'b) -> 'b list -> 'b list val map_snd : ('a * 'b) list -> ('b -> 'c) -> ('a * 'c) list val map_last : 'a list -> (bool -> 'a -> 'b) -> 'b list (** [map_last f xs ] will pass [true] to [f] for the last element, [false] otherwise. For empty list, it returns empty *) val last : 'a list -> 'a (** [last l] return the last element raise if the list is empty *) val append : 'a list -> 'a list -> 'a list val append_one : 'a list -> 'a -> 'a list val map_append : 'b list -> 'a list -> ('b -> 'a) -> 'a list val fold_right : 'a list -> 'b -> ('a -> 'b -> 'b) -> 'b val fold_right2 : 'a list -> 'b list -> 'c -> ('a -> 'b -> 'c -> 'c) -> 'c val fold_right3 : 'a list -> 'b list -> 'c list -> 'd -> ('a -> 'b -> 'c -> 'd -> 'd) -> 'd val map2 : 'a list -> 'b list -> ('a -> 'b -> 'c) -> 'c list val map2i : 'a list -> 'b list -> (int -> 'a -> 'b -> 'c) -> 'c list val fold_left_with_offset : 'a list -> 'acc -> int -> ('a -> 'acc -> int -> 'acc) -> 'acc val filter_map : 'a list -> ('a -> 'b option) -> 'b list (** @unused *) val exclude : 'a list -> ('a -> bool) -> 'a list (** [exclude p l] is the opposite of [filter p l] *) val exclude_with_val : 'a list -> ('a -> bool) -> 'a list option * [ excludes p l ] return a tuple [ excluded , newl ] where [ exluded ] is true indicates that at least one element is removed,[newl ] is the new list where all [ p x ] for [ x ] is false return a tuple [excluded,newl] where [exluded] is true indicates that at least one element is removed,[newl] is the new list where all [p x] for [x] is false *) val same_length : 'a list -> 'b list -> bool val init : int -> (int -> 'a) -> 'a list val split_at : 'a list -> int -> 'a list * 'a list * [ split_at n l ] will split [ l ] into two lists [ a , b ] , [ a ] will be of length [ n ] , otherwise , it will raise will split [l] into two lists [a,b], [a] will be of length [n], otherwise, it will raise *) val split_at_last : 'a list -> 'a list * 'a * [ split_at_last l ] It is equivalent to [ split_at ( l - 1 ) l ] It is equivalent to [split_at (List.length l - 1) l ] *) val filter_mapi : 'a list -> ('a -> int -> 'b option) -> 'b list val filter_map2 : 'a list -> 'b list -> ('a -> 'b -> 'c option) -> 'c list val length_compare : 'a list -> int -> [ `Gt | `Eq | `Lt ] val length_ge : 'a list -> int -> bool * { [ length xs = length ys + n ] } input n should be positive TODO : input checking {[length xs = length ys + n ]} input n should be positive TODO: input checking *) val length_larger_than_n : 'a list -> 'a list -> int -> bool val rev_map_append : 'a list -> 'b list -> ('a -> 'b) -> 'b list (** [rev_map_append f l1 l2] [map f l1] and reverse it to append [l2] This weird semantics is due to it is the most efficient operation we can do *) val flat_map : 'a list -> ('a -> 'b list) -> 'b list val flat_map_append : 'a list -> 'b list -> ('a -> 'b list) -> 'b list val stable_group : 'a list -> ('a -> 'a -> bool) -> 'a list list (** [stable_group eq lst] Example: Input: {[ stable_group (=) [1;2;3;4;3] ]} Output: {[ [[1];[2];[4];[3;3]] ]} TODO: this is O(n^2) behavior which could be improved later *) val drop : 'a list -> int -> 'a list (** [drop n list] raise when [n] is negative raise when list's length is less than [n] *) val find_first : 'a list -> ('a -> bool) -> 'a option val find_first_exn : 'a list -> ('a -> bool) -> 'a val find_first_not : 'a list -> ('a -> bool) -> 'a option * [ find_first_not p lst ] if all elements in [ lst ] pass , return [ None ] otherwise return the first element [ e ] as [ Some e ] which fails the predicate if all elements in [lst] pass, return [None] otherwise return the first element [e] as [Some e] which fails the predicate *) * [ find_opt f l ] returns [ None ] if all return [ None ] , otherwise returns the first one . otherwise returns the first one. *) val find_opt : 'a list -> ('a -> 'b option) -> 'b option val find_def : 'a list -> ('a -> 'b option) -> 'b -> 'b val rev_iter : 'a list -> ('a -> unit) -> unit val iter : 'a list -> ('a -> unit) -> unit val for_all : 'a list -> ('a -> bool) -> bool val for_all_snd : ('a * 'b) list -> ('b -> bool) -> bool val for_all2_no_exn : 'a list -> 'b list -> ('a -> 'b -> bool) -> bool (** [for_all2_no_exn p xs ys] return [true] if all satisfied, [false] otherwise or length not equal *) val split_map : 'a list -> ('a -> 'b * 'c) -> 'b list * 'c list (** [f] is applied follow the list order *) val reduce_from_left : 'a list -> ('a -> 'a -> 'a) -> 'a (** [fn] is applied from left to right *) val sort_via_array : 'a list -> ('a -> 'a -> int) -> 'a list val sort_via_arrayf : 'a list -> ('a -> 'a -> int) -> ('a -> 'b) -> 'b list val assoc_by_string : (string * 'a) list -> string -> 'a option -> 'a * [ assoc_by_string default key lst ] if [ key ] is found in the list return that val , other unbox the [ default ] , otherwise [ assert false ] if [key] is found in the list return that val, other unbox the [default], otherwise [assert false ] *) val assoc_by_int : (int * 'a) list -> int -> 'a option -> 'a val nth_opt : 'a list -> int -> 'a option val iter_snd : ('a * 'b) list -> ('b -> unit) -> unit val iter_fst : ('a * 'b) list -> ('a -> unit) -> unit val exists : 'a list -> ('a -> bool) -> bool val exists_fst : ('a * 'b) list -> ('a -> bool) -> bool val exists_snd : ('a * 'b) list -> ('b -> bool) -> bool val concat_append : 'a list list -> 'a list -> 'a list val fold_left2 : 'a list -> 'b list -> 'c -> ('a -> 'b -> 'c -> 'c) -> 'c val fold_left : 'a list -> 'b -> ('b -> 'a -> 'b) -> 'b val singleton_exn : 'a list -> 'a val mem_string : string list -> string -> bool val group_by : fk:('a -> string) -> fv:('a -> 'b) -> 'a list -> 'b list Hash_string.t val filter : 'a list -> ('a -> bool) -> 'a list val array_list_filter_map : 'a array -> 'b list -> ('a -> 'b -> 'c option) -> 'c list
null
https://raw.githubusercontent.com/melange-re/melange/2293d9a3afff15b1853571a5fb2d15eb296437ed/jscomp/ext/ext_list.mli
ocaml
* [map_last f xs ] will pass [true] to [f] for the last element, [false] otherwise. For empty list, it returns empty * [last l] return the last element raise if the list is empty * @unused * [exclude p l] is the opposite of [filter p l] * [rev_map_append f l1 l2] [map f l1] and reverse it to append [l2] This weird semantics is due to it is the most efficient operation we can do * [stable_group eq lst] Example: Input: {[ stable_group (=) [1;2;3;4;3] ]} Output: {[ [[1];[2];[4];[3;3]] ]} TODO: this is O(n^2) behavior which could be improved later * [drop n list] raise when [n] is negative raise when list's length is less than [n] * [for_all2_no_exn p xs ys] return [true] if all satisfied, [false] otherwise or length not equal * [f] is applied follow the list order * [fn] is applied from left to right
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val map : 'a list -> ('a -> 'b) -> 'b list val map_combine : 'a list -> 'b list -> ('a -> 'c) -> ('c * 'b) list val combine_array : 'a array -> 'b list -> ('a -> 'c) -> ('c * 'b) list val combine_array_append : 'a array -> 'b list -> ('c * 'b) list -> ('a -> 'c) -> ('c * 'b) list val has_string : string list -> string -> bool val map_split_opt : 'a list -> ('a -> 'b option * 'c option) -> 'b list * 'c list val mapi : 'a list -> (int -> 'a -> 'b) -> 'b list val mapi_append : 'a list -> (int -> 'a -> 'b) -> 'b list -> 'b list val map_snd : ('a * 'b) list -> ('b -> 'c) -> ('a * 'c) list val map_last : 'a list -> (bool -> 'a -> 'b) -> 'b list val last : 'a list -> 'a val append : 'a list -> 'a list -> 'a list val append_one : 'a list -> 'a -> 'a list val map_append : 'b list -> 'a list -> ('b -> 'a) -> 'a list val fold_right : 'a list -> 'b -> ('a -> 'b -> 'b) -> 'b val fold_right2 : 'a list -> 'b list -> 'c -> ('a -> 'b -> 'c -> 'c) -> 'c val fold_right3 : 'a list -> 'b list -> 'c list -> 'd -> ('a -> 'b -> 'c -> 'd -> 'd) -> 'd val map2 : 'a list -> 'b list -> ('a -> 'b -> 'c) -> 'c list val map2i : 'a list -> 'b list -> (int -> 'a -> 'b -> 'c) -> 'c list val fold_left_with_offset : 'a list -> 'acc -> int -> ('a -> 'acc -> int -> 'acc) -> 'acc val filter_map : 'a list -> ('a -> 'b option) -> 'b list val exclude : 'a list -> ('a -> bool) -> 'a list val exclude_with_val : 'a list -> ('a -> bool) -> 'a list option * [ excludes p l ] return a tuple [ excluded , newl ] where [ exluded ] is true indicates that at least one element is removed,[newl ] is the new list where all [ p x ] for [ x ] is false return a tuple [excluded,newl] where [exluded] is true indicates that at least one element is removed,[newl] is the new list where all [p x] for [x] is false *) val same_length : 'a list -> 'b list -> bool val init : int -> (int -> 'a) -> 'a list val split_at : 'a list -> int -> 'a list * 'a list * [ split_at n l ] will split [ l ] into two lists [ a , b ] , [ a ] will be of length [ n ] , otherwise , it will raise will split [l] into two lists [a,b], [a] will be of length [n], otherwise, it will raise *) val split_at_last : 'a list -> 'a list * 'a * [ split_at_last l ] It is equivalent to [ split_at ( l - 1 ) l ] It is equivalent to [split_at (List.length l - 1) l ] *) val filter_mapi : 'a list -> ('a -> int -> 'b option) -> 'b list val filter_map2 : 'a list -> 'b list -> ('a -> 'b -> 'c option) -> 'c list val length_compare : 'a list -> int -> [ `Gt | `Eq | `Lt ] val length_ge : 'a list -> int -> bool * { [ length xs = length ys + n ] } input n should be positive TODO : input checking {[length xs = length ys + n ]} input n should be positive TODO: input checking *) val length_larger_than_n : 'a list -> 'a list -> int -> bool val rev_map_append : 'a list -> 'b list -> ('a -> 'b) -> 'b list val flat_map : 'a list -> ('a -> 'b list) -> 'b list val flat_map_append : 'a list -> 'b list -> ('a -> 'b list) -> 'b list val stable_group : 'a list -> ('a -> 'a -> bool) -> 'a list list val drop : 'a list -> int -> 'a list val find_first : 'a list -> ('a -> bool) -> 'a option val find_first_exn : 'a list -> ('a -> bool) -> 'a val find_first_not : 'a list -> ('a -> bool) -> 'a option * [ find_first_not p lst ] if all elements in [ lst ] pass , return [ None ] otherwise return the first element [ e ] as [ Some e ] which fails the predicate if all elements in [lst] pass, return [None] otherwise return the first element [e] as [Some e] which fails the predicate *) * [ find_opt f l ] returns [ None ] if all return [ None ] , otherwise returns the first one . otherwise returns the first one. *) val find_opt : 'a list -> ('a -> 'b option) -> 'b option val find_def : 'a list -> ('a -> 'b option) -> 'b -> 'b val rev_iter : 'a list -> ('a -> unit) -> unit val iter : 'a list -> ('a -> unit) -> unit val for_all : 'a list -> ('a -> bool) -> bool val for_all_snd : ('a * 'b) list -> ('b -> bool) -> bool val for_all2_no_exn : 'a list -> 'b list -> ('a -> 'b -> bool) -> bool val split_map : 'a list -> ('a -> 'b * 'c) -> 'b list * 'c list val reduce_from_left : 'a list -> ('a -> 'a -> 'a) -> 'a val sort_via_array : 'a list -> ('a -> 'a -> int) -> 'a list val sort_via_arrayf : 'a list -> ('a -> 'a -> int) -> ('a -> 'b) -> 'b list val assoc_by_string : (string * 'a) list -> string -> 'a option -> 'a * [ assoc_by_string default key lst ] if [ key ] is found in the list return that val , other unbox the [ default ] , otherwise [ assert false ] if [key] is found in the list return that val, other unbox the [default], otherwise [assert false ] *) val assoc_by_int : (int * 'a) list -> int -> 'a option -> 'a val nth_opt : 'a list -> int -> 'a option val iter_snd : ('a * 'b) list -> ('b -> unit) -> unit val iter_fst : ('a * 'b) list -> ('a -> unit) -> unit val exists : 'a list -> ('a -> bool) -> bool val exists_fst : ('a * 'b) list -> ('a -> bool) -> bool val exists_snd : ('a * 'b) list -> ('b -> bool) -> bool val concat_append : 'a list list -> 'a list -> 'a list val fold_left2 : 'a list -> 'b list -> 'c -> ('a -> 'b -> 'c -> 'c) -> 'c val fold_left : 'a list -> 'b -> ('b -> 'a -> 'b) -> 'b val singleton_exn : 'a list -> 'a val mem_string : string list -> string -> bool val group_by : fk:('a -> string) -> fv:('a -> 'b) -> 'a list -> 'b list Hash_string.t val filter : 'a list -> ('a -> bool) -> 'a list val array_list_filter_map : 'a array -> 'b list -> ('a -> 'b -> 'c option) -> 'c list
6224ee32db101e9dedf9f549fd973576259acde787c72fae1a7e409568929523
vonli/Ext2-for-movitz
special-operators.lisp
;;;;------------------------------------------------------------------ ;;;; Copyright ( C ) 20012000 , 2002 - 2005 , Department of Computer Science , University of Tromso , Norway ;;;; Filename : special-operators.lisp ;;;; Description: Compilation of internal special operators. Author : < > Created at : Fri Nov 24 16:22:59 2000 ;;;; $ I d : special - operators.lisp , v 1.56 2007/02/26 18:25:21 Exp $ ;;;; ;;;;------------------------------------------------------------------ (in-package movitz) (defun ccc-result-to-returns (result-mode) (check-type result-mode keyword) (case result-mode (:ignore :nothing) (:function :multiple-values) (t result-mode))) (defun make-compiled-cond-clause (clause clause-num last-clause-p exit-label funobj env result-mode) "Return three values: The code for a cond clause, a boolean value indicating whether the clause's test was constantly true, The set of modified bindings." (assert (not (atom clause))) (let* ((clause-modifies nil) (test-form (car clause)) (then-forms (cdr clause))) (cond ((null then-forms) (compiler-values-bind (&code test-code &returns test-returns) (compiler-call #'compile-form :modify-accumulate clause-modifies :result-mode (case (operator result-mode) (:boolean-branch-on-false (if last-clause-p result-mode (cons :boolean-branch-on-true exit-label))) (:boolean-branch-on-true result-mode) (:ignore (cons :boolean-branch-on-true exit-label)) (:push (if last-clause-p :push :eax)) (#.+multiple-value-result-modes+ :eax) (t result-mode)) :form test-form :funobj funobj :env env) (assert (not (null test-code)) (clause) "null test-code!") (values (ecase (operator test-returns) ((:boolean-branch-on-true :boolean-branch-on-false) test-code) (:push (assert last-clause-p) test-code) ((:multiple-values :eax :ebx :ecx :edx) ;;; (when (eq result-mode :function) ;;; (warn "test-returns: ~S" test-returns)) (let ((singlify (when (member result-mode +multiple-value-result-modes+) '((:clc))))) (append test-code (cond ((not last-clause-p) (append `((:cmpl :edi ,(single-value-register (operator test-returns)))) singlify (when (eq :push result-mode) `((:pushl ,(single-value-register (operator test-returns))))) `((:jne ',exit-label)))) (t singlify)))))) nil))) ((not (null then-forms)) (let ((skip-label (gensym (format nil "cond-skip-~D-" clause-num)))) (compiler-values-bind (&code test-code) (compiler-call #'compile-form :result-mode (cond ((and last-clause-p (eq (operator result-mode) :boolean-branch-on-false)) (cons :boolean-branch-on-false (cdr result-mode))) (t (cons :boolean-branch-on-false skip-label))) :modify-accumulate clause-modifies :form test-form :funobj funobj :env env) (compiler-values-bind (&code then-code &returns then-returns) (compiler-call #'compile-form :form (cons 'muerte.cl::progn then-forms) :modify-accumulate clause-modifies :funobj funobj :env env :result-mode result-mode) (let ((constantly-true-p (null test-code))) (values (append test-code then-code (unless (or last-clause-p (eq then-returns :non-local-exit)) `((:jmp ',exit-label))) (unless constantly-true-p (list skip-label))) constantly-true-p clause-modifies))))))))) (defun chose-joined-returns-and-result (result-mode) "From a result-mode, determine a joined result-mode (for several branches), and the correspondig returns mode (secondary value)." (let ((joined-result-mode (case (operator result-mode) (:values :multiple-values) ((:ignore :function :multiple-values :eax :ebx :ecx :edx :boolean-branch-on-false :boolean-branch-on-true) result-mode) (t :eax)))) (values joined-result-mode (ecase (operator joined-result-mode) (:ignore :nothing) (:function :multiple-values) ((:multiple-values :eax :push :eax :ebx :ecx :edx :boolean-branch-on-true :boolean-branch-on-false) joined-result-mode))))) (define-special-operator compiled-cond (&form form &funobj funobj &env env &result-mode result-mode) (let ((clauses (cdr form))) (let* ((cond-exit-label (gensym "cond-exit-")) (cond-result-mode (case (operator result-mode) (:values :multiple-values) ((:ignore :function :multiple-values :eax :ebx :ecx :edx :boolean-branch-on-false :boolean-branch-on-true) result-mode) (t :eax))) (cond-returns (ecase (operator cond-result-mode) (:ignore :nothing) (:function :multiple-values) ((:multiple-values :eax :push :eax :ebx :ecx :edx :boolean-branch-on-true :boolean-branch-on-false) cond-result-mode))) (only-control-p (member (operator cond-result-mode) '(:ignore :boolean-branch-on-true :boolean-branch-on-false)))) (loop with last-clause-num = (1- (length clauses)) for clause in clauses for clause-num upfrom 0 as (clause-code constantly-true-p) = (multiple-value-list (make-compiled-cond-clause clause clause-num (and only-control-p (= clause-num last-clause-num)) cond-exit-label funobj env cond-result-mode)) append clause-code into cond-code when constantly-true-p do (return (compiler-values () :returns cond-returns :code (append cond-code (list cond-exit-label)))) finally (return (compiler-values () :returns cond-returns :code (append cond-code ;; no test succeeded => nil (unless only-control-p (compiler-call #'compile-form :form nil :funobj funobj :env env :top-level-p nil :result-mode cond-result-mode)) (list cond-exit-label)))))))) (define-special-operator compiled-case (&all all &form form &result-mode result-mode) (destructuring-bind (keyform &rest clauses) (cdr form) #+ignore (let ((cases (loop for (clause . nil) in clauses append (if (consp clause) clause (unless (member clause '(nil muerte.cl:t muerte.cl:otherwise)) (list clause)))))) (warn "case clauses:~%~S" cases)) (compiler-values-bind (&code key-code &returns key-returns) (compiler-call #'compile-form-unprotected :result-mode :eax :forward all :form keyform) (multiple-value-bind (case-result-mode case-returns) (chose-joined-returns-and-result result-mode) (let ((key-reg (accept-register-mode key-returns))) (flet ((otherwise-clause-p (x) (member (car x) '(muerte.cl:t muerte.cl:otherwise))) (make-first-check (key then-label then-code exit-label) `((:load-constant ,key ,key-reg :op :cmpl) (:je '(:sub-program (,then-label) ,@then-code (:jmp ',exit-label)))))) (cond ((otherwise-clause-p (first clauses)) (compiler-call #'compile-implicit-progn :forward all :form (rest (first clauses)))) (t (compiler-values () :returns case-returns :code (append (make-result-and-returns-glue key-reg key-returns key-code) (loop with exit-label = (gensym "case-exit-") for clause-head on clauses as clause = (first clause-head) as keys = (first clause) as then-forms = (rest clause) as then-label = (gensym "case-then-") as then-code = (compiler-call #'compile-form :result-mode case-result-mode :forward all :form `(muerte.cl:progn ,@then-forms)) if (otherwise-clause-p clause) do (assert (endp (rest clause-head)) () "Case's otherwise clause must be the last clause.") and append then-code else if (atom keys) append (make-first-check keys then-label then-code exit-label) else append (make-first-check (first keys) then-label then-code exit-label) and append (loop for key in (rest keys) append `((:load-constant ,key ,key-reg :op :cmpl) (:je ',then-label))) if (endp (rest clause-head)) append (append (unless (otherwise-clause-p clause) (compiler-call #'compile-form :result-mode case-result-mode :forward all :form nil)) (list exit-label))))))))))))) (define-special-operator compile-time-find-class (&all all &form form) (destructuring-bind (class-name) (cdr form) (compiler-call #'compile-form-unprotected :form (muerte::movitz-find-class class-name) :forward all))) (define-special-operator make-named-function (&form form &env env) (destructuring-bind (name formals declarations docstring body) (cdr form) (declare (ignore docstring)) (handler-bind (#+ignore ((or error warning) (lambda (c) (declare (ignore c)) (format *error-output* "~&;; In function ~S:~&" name)))) (let* ((*compiling-function-name* name) (funobj (make-compiled-funobj name formals declarations body env nil))) (setf (movitz-funobj-symbolic-name funobj) name) (setf (movitz-env-named-function name) funobj)))) (compiler-values ())) (define-special-operator make-primitive-function (&form form &env env) (destructuring-bind (name docstring body) (cdr form) (destructuring-bind (name &key symtab-property) (if (consp name) name (list name)) (handler-bind (((or warning error) (lambda (c) (declare (ignore c)) (format *error-output* "~&;; In primitive function ~S:" name)))) (multiple-value-bind (code-vector symtab) (make-compiled-primitive body env nil docstring) (setf (movitz-symbol-value (movitz-read name)) code-vector) (when symtab-property (setf (movitz-env-get name :symtab) (muerte::translate-program symtab :movitz :muerte))) (compiler-values ())))))) (define-special-operator define-prototyped-function (&form form) (destructuring-bind (function-name proto-name &rest parameters) (cdr form) (let* ((funobj-proto (movitz-env-named-function proto-name)) (funobj (make-instance 'movitz-funobj :name (movitz-read function-name) :code-vector (movitz-funobj-code-vector funobj-proto) :code-vector%1op (movitz-funobj-code-vector%1op funobj-proto) :code-vector%2op (movitz-funobj-code-vector%2op funobj-proto) :code-vector%3op (movitz-funobj-code-vector%3op funobj-proto) :lambda-list (movitz-funobj-lambda-list funobj-proto) :num-constants (movitz-funobj-num-constants funobj-proto) :num-jumpers (movitz-funobj-num-jumpers funobj-proto) :jumpers-map (movitz-funobj-jumpers-map funobj-proto) :symbolic-code (when (slot-boundp funobj-proto 'symbolic-code) (movitz-funobj-symbolic-code funobj-proto)) :const-list (let ((c (copy-list (movitz-funobj-const-list funobj-proto)))) (loop for (lisp-parameter value) in parameters as parameter = (movitz-read lisp-parameter) do (assert (member parameter c) () "~S is not a function prototype parameter for ~S. ~ The valid parameters are~{ ~S~}." parameter proto-name (mapcar #'movitz-print (movitz-funobj-const-list funobj-proto))) (setf (car (member parameter c)) (if (and (consp value) (eq :movitz-find-class (car value))) (muerte::movitz-find-class (cadr value)) (movitz-read value)))) c)))) (setf (movitz-funobj-symbolic-name funobj) function-name) (setf (movitz-env-named-function function-name) funobj) (compiler-values ())))) (define-special-operator define-setf-expander-compile-time (&form form) (destructuring-bind (access-fn lambda-list macro-body) (cdr form) (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-macro-body (translate-program macro-body :muerte.cl :cl))) (multiple-value-bind (cl-body declarations doc-string) (parse-docstring-declarations-and-body cl-macro-body 'cl:declare) (declare (ignore doc-string)) (setf (movitz-env-get access-fn 'muerte::setf-expander nil) (let* ((form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym))) (expander (if (null cl-lambda-list) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal) ,@declarations) (translate-program (block ,access-fn ,@cl-body) :cl :muerte.cl)) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal) ,@declarations) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (values-list (translate-program (multiple-value-list (block ,access-fn ,@cl-body)) :cl :muerte.cl))))))) (movitz-macro-expander-make-function expander :type :setf :name access-fn))))))) (compiler-values ())) (define-special-operator muerte::defmacro-compile-time (&form form) (destructuring-bind (name lambda-list macro-body) (cdr form) (check-type name symbol "a macro name") (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((expander-name (make-symbol (format nil "~A-macro" name))) (cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-macro-body (translate-program macro-body :muerte.cl :cl))) (when (member name (image-called-functions *image*) :key #'first) #+ignore (warn "Macro ~S defined after being called as function (first in ~S)." name (cdr (find name (image-called-functions *image*) :key #'first)))) (multiple-value-bind (cl-body declarations doc-string) (parse-docstring-declarations-and-body cl-macro-body 'cl:declare) (declare (ignore doc-string)) ( warn " defmacro ~S : ~S " name cl - body ) (let ((expander-lambda (let ((form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym)))) (if (null cl-lambda-list) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal)) (declare ,@declarations) (translate-program (block ,name ,@cl-body) :cl :muerte.cl)) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal)) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (declare ,@declarations) (translate-program (block ,name ,@cl-body) :cl :muerte.cl))))))) (setf (movitz-macro-function name) (movitz-macro-expander-make-function expander-lambda :name expander-name :type :defmacro))))))) (compiler-values ())) (define-special-operator muerte::define-compiler-macro-compile-time (&form form) ;; This scheme doesn't quite cut it.. (destructuring-bind (name lambda-list doc-dec-body) (cdr form) (multiple-value-bind (body declarations) (parse-docstring-declarations-and-body doc-dec-body) (let ((operator-name (or (and (setf-name name) (movitz-env-setf-operator-name (setf-name name))) name))) (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-body (translate-program body :muerte.cl :cl)) (declarations (translate-program declarations :muerte.cl :cl)) (form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym))) (expansion-var (gensym))) (when (member operator-name (image-called-functions *image*) :key #'first) (warn "Compiler-macro ~S defined after being called as function (first in ~S)" operator-name (cdr (find operator-name (image-called-functions *image*) :key #'first)))) (let ((expander `(lambda (,form-formal ,env-formal) (declare (ignorable ,env-formal)) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (declare ,@declarations) (let ((,expansion-var (block ,operator-name ,@cl-body))) (if (eq ,form-formal ,expansion-var) ,form-formal ; declined (translate-program ,expansion-var :cl :muerte.cl))))))) (setf (movitz-compiler-macro-function operator-name nil) (movitz-macro-expander-make-function expander :name name :type :compiler-macro)))))))) (compiler-values ())) (define-special-operator muerte::with-inline-assembly-case (&all forward &form form &funobj funobj &env env &result-mode result-mode) (destructuring-bind (global-options &body inline-asm-cases) (cdr form) (destructuring-bind (&key (side-effects t) ((:type global-type))) global-options (let ((modifies ())) (loop for case-spec in inline-asm-cases finally (error "Found no inline-assembly-case matching ~S." result-mode) do (destructuring-bind ((matching-result-modes &optional (returns :same) &key labels (type global-type)) &body inline-asm) (cdr case-spec) (when (eq returns :same) (setf returns (case result-mode (:function :multiple-values) (t result-mode)))) (when (flet ((match (matching-result-mode) (or (eq 'muerte.cl::t matching-result-mode) (eq t matching-result-mode) (eq (operator result-mode) matching-result-mode) (and (eq :register matching-result-mode) (member result-mode '(:eax ebx ecx edx :single-value)))))) (if (symbolp matching-result-modes) (match matching-result-modes) (find-if #'match matching-result-modes))) (case returns (:register (setf returns (case result-mode ((:eax :ebx :ecx :edx) result-mode) (t :eax))))) (unless type (setf type (ecase (operator returns) ((:nothing) nil) ((:eax :ebx :ecx :edx) t) (#.+boolean-modes+ t) ((:boolean-branch-on-false :boolean-branch-on-true) t) ((:multiple-values) '(values &rest t))))) (return (let ((amenv (make-assembly-macro-environment))) ; XXX this is really wasteful.. (setf (assembly-macro-expander :branch-when amenv) #'(lambda (expr) (destructuring-bind (boolean-mode) (cdr expr) (ecase (operator result-mode) ((:boolean-branch-on-true :boolean-branch-on-false) (list (make-branch-on-boolean boolean-mode (operands result-mode) :invert nil))))))) (setf (assembly-macro-expander :compile-form amenv) #'(lambda (expr) (destructuring-bind ((&key ((:result-mode sub-result-mode))) sub-form) (cdr expr) (case sub-result-mode (:register (setf sub-result-mode returns)) (:same (setf sub-result-mode result-mode))) (assert sub-result-mode (sub-result-mode) "Assembly :COMPILE-FORM directive doesn't provide a result-mode: ~S" expr) (compiler-values-bind (&code sub-code &functional-p sub-functional-p &modifies sub-modifies) (compiler-call #'compile-form :defaults forward :form sub-form :result-mode sub-result-mode) ;; if a sub-compile has side-effects, then the entire ;; with-inline-assembly form does too. (unless sub-functional-p (setq side-effects t)) (setf modifies (modifies-union modifies sub-modifies)) sub-code)))) (setf (assembly-macro-expander :offset amenv) #'(lambda (expr) (destructuring-bind (type slot &optional (extra 0)) (cdr expr) (let ((mtype (find-symbol (symbol-name type) :movitz)) (mslot (find-symbol (symbol-name slot) :movitz))) (assert mtype (mtype) "Type not a Movitz symbol: ~A" type) (assert mslot (mslot) "Slot not a Movitz symbol: ~A" slot) (list (+ (slot-offset mtype mslot) (eval extra))))))) (setf (assembly-macro-expander :returns-mode amenv) #'(lambda (expr) (assert (= 1 (length expr))) (list returns))) (setf (assembly-macro-expander :result-register amenv) #'(lambda (expr) (assert (= 1 (length expr))) (assert (member returns '(:eax :ebx :ecx :edx))) (list returns))) (setf (assembly-macro-expander :result-register-low8 amenv) #'(lambda (expr) (assert (= 1 (length expr))) (assert (member returns '(:eax :ebx :ecx :edx))) (list (register32-to-low8 returns)))) (setf (assembly-macro-expander :compile-arglist amenv) #'(lambda (expr) (destructuring-bind (ignore &rest arg-forms) (cdr expr) (declare (ignore ignore)) (setq side-effects t) (make-compiled-argument-forms arg-forms funobj env)))) (setf (assembly-macro-expander :compile-two-forms amenv) #'(lambda (expr) (destructuring-bind ((reg1 reg2) form1 form2) (cdr expr) (multiple-value-bind (code sub-functional-p sub-modifies) (make-compiled-two-forms-into-registers form1 reg1 form2 reg2 funobj env) (unless sub-functional-p (setq side-effects t)) (setq modifies (modifies-union modifies sub-modifies)) code)))) (setf (assembly-macro-expander :call-global-pf amenv) #'(lambda (expr) (destructuring-bind (name) (cdr expr) `((:globally (:call (:edi (:edi-offset ,name)))))))) (setf (assembly-macro-expander :call-local-pf amenv) #'(lambda (expr) (destructuring-bind (name) (cdr expr) `((:locally (:call (:edi (:edi-offset ,name)))))))) (setf (assembly-macro-expander :warn amenv) #'(lambda (expr) (apply #'warn (cdr expr)) nil)) (setf (assembly-macro-expander :lexical-store amenv) (lambda (expr) (destructuring-bind (var reg &key (type t)) (cdr expr) `((:store-lexical ,(movitz-binding var env) ,reg :type ,type))))) (setf (assembly-macro-expander :lexical-binding amenv) (lambda (expr) (destructuring-bind (var) (cdr expr) (let ((binding (movitz-binding var env))) (check-type binding binding) (list binding))))) (let ((code (assembly-macroexpand inline-asm amenv))) #+ignore (assert (not (and (not side-effects) (tree-search code '(:store-lexical)))) () "Inline assembly is declared side-effects-free, but contains :store-lexical.") (when labels (setf code (subst (gensym (format nil "~A-" (first labels))) (first labels) code)) (dolist (label (rest labels)) (setf code (nsubst (gensym (format nil "~A-" label)) label code)))) (compiler-values () :code code :returns returns :type (translate-program type :muerte.cl :cl) :modifies modifies :functional-p (not side-effects)))))))))))) (define-special-operator muerte::declaim-compile-time (&form form &top-level-p top-level-p) (unless top-level-p (warn "DECLAIM not at top-level.")) (let ((declaration-specifiers (cdr form))) (movitz-env-load-declarations declaration-specifiers *movitz-global-environment* :declaim)) (compiler-values ())) (define-special-operator call-internal (&form form) (destructuring-bind (if-name &optional argument) (cdr form) (assert (not argument)) (compiler-values () :code `((:call (:edi ,(slot-offset 'movitz-run-time-context if-name)))) :returns :nothing))) (define-special-operator inlined-not (&all forward &form form &result-mode result-mode) (assert (= 2 (length form))) (let ((x (second form))) (if (eq result-mode :ignore) (compiler-call #'compile-form-unprotected :forward forward :form x) (multiple-value-bind (not-result-mode result-mode-inverted-p) (cond ((or (member (operator result-mode) +boolean-modes+) (member (operator result-mode) '(:boolean-branch-on-false :boolean-branch-on-true))) (values (complement-boolean-result-mode result-mode) t)) ((member (operator result-mode) +multiple-value-result-modes+) (values :eax nil)) ((member (operator result-mode) '(:push)) (values :eax nil)) (t (values result-mode nil))) (compiler-values-bind (&all not-values &returns not-returns &code not-code &type not-type) (compiler-call #'compile-form-unprotected :defaults forward :form x :result-mode not-result-mode) (setf (not-values :producer) (list :not (not-values :producer))) (let ((not-type (type-specifier-primary not-type))) (setf (not-values :type) (cond ((movitz-subtypep not-type 'null) '(eql t)) ((movitz-subtypep not-type '(not null)) 'null) (t 'boolean)))) ;; (warn "res: ~S" result-mode-inverted-p) (cond ((and result-mode-inverted-p (eql not-result-mode not-returns)) ;; Inversion by result-mode ok. (compiler-values (not-values) :returns result-mode)) (result-mode-inverted-p ;; (warn "Not done: ~S/~S/~S." result-mode not-result-mode not-returns) (multiple-value-bind (code) (make-result-and-returns-glue not-result-mode not-returns not-code) (compiler-values (not-values) :returns result-mode :code code))) ((not result-mode-inverted-p) ;; We must invert returns-mode (case (operator not-returns) (#.(append +boolean-modes+ '(:boolean-branch-on-true :boolean-branch-on-false)) (compiler-values (not-values) :returns (complement-boolean-result-mode not-returns))) ;;; ((:eax :function :multiple-values :ebx :edx) ;;; (case result-mode ;;; ((:eax :ebx :ecx :edx :function :multiple-values) ;;; (compiler-values (not-values) ;;; :code (append (not-values :code) ;;; `((:cmpl :edi ,(single-value-register not-returns)) (: : ecx : ecx ) (: cmpl , ( 1 + ( image - nil - word * image * ) ) ;;; ,(single-value-register not-returns)) ;;; (:adcl 0 :ecx))) : returns ' (: boolean - ecx 1 0 ) ) ) ;;; (t (compiler-values (not-values) ;;; :code (append (not-values :code) ;;; `((:cmpl :edi ,(single-value-register not-returns)))) ;;; :returns :boolean-zf=1)))) ((:eax :function :multiple-values :ebx :ecx :edx) (compiler-values (not-values) :code (append (not-values :code) `((:cmpl :edi ,(single-value-register not-returns)))) :returns :boolean-zf=1)) ; TRUE iff result equal to :edi/NIL. (otherwise #+ignore (warn "unable to deal intelligently with inlined-NOT not-returns: ~S for ~S from ~S" not-returns not-result-mode (not-values :producer)) (let ((label (make-symbol "not-label"))) (compiler-values (not-values) :returns :eax :code (append (make-result-and-returns-glue :eax not-returns (not-values :code)) `((:cmpl :edi :eax) (:movl :edi :eax) (:jne ',label) (:globally (:movl (:edi (:edi-offset t-symbol)) :eax)) ,label))))))))))))) (define-special-operator muerte::with-progn-results (&all forward &form form &top-level-p top-level-p &result-mode result-mode) (destructuring-bind (buried-result-modes &body body) (cdr form) (assert (< (length buried-result-modes) (length body)) () "WITH-PROGN-RESULTS must have fewer result-modes than body elements: ~S" form) (loop with returns-mode = :nothing with no-side-effects-p = t with modifies = nil for sub-form on body as sub-form-result-mode = buried-result-modes then (or (cdr sub-form-result-mode) sub-form-result-mode) as current-result-mode = (if (endp (cdr sub-form)) ;; all but the last form have result-mode as declared result-mode (car sub-form-result-mode)) as last-form-p = (endp (cdr sub-form)) ;; do (warn "progn rm: ~S" (car sub-form-result-mode)) appending (compiler-values-bind (&code code &returns sub-returns-mode &functional-p no-sub-side-effects-p &modifies sub-modifies) (compiler-call (if last-form-p #'compile-form-unprotected #'compile-form) :defaults forward :form (car sub-form) :top-level-p top-level-p :result-mode current-result-mode) (unless no-sub-side-effects-p (setf no-side-effects-p nil)) (setq modifies (modifies-union modifies sub-modifies)) (when last-form-p ;; (warn "progn rm: ~S form: ~S" sub-returns-mode (car sub-form)) (setf returns-mode sub-returns-mode)) (if (and no-sub-side-effects-p (eq current-result-mode :ignore)) nil code)) into progn-code finally (return (compiler-values () :code progn-code :returns returns-mode :modifies modifies :functional-p no-side-effects-p))))) (define-special-operator muerte::simple-funcall (&form form) (destructuring-bind (apply-funobj) (cdr form) (compiler-values () :returns :multiple-values :functional-p nil put function funobj in ESI (:xorl :ecx :ecx) ; number of arguments call new ESI 's code - vector (:call (:esi ,(slot-offset 'movitz-funobj 'code-vector))))))) (define-special-operator muerte::compiled-nth-value (&all all &form form &env env &result-mode result-mode) (destructuring-bind (n-form subform) (cdr form) (cond ((movitz-constantp n-form) (let ((n (eval-form n-form env))) (check-type n (integer 0 *)) (compiler-values-bind (&code subform-code &returns subform-returns) (compiler-call #'compile-form-unprotected :forward all :result-mode :multiple-values :form subform) (if (not (eq subform-returns :multiple-values)) ;; single-value result (case n (0 (compiler-values () :code subform-code :returns subform-returns)) (t (compiler-call #'compile-implicit-progn :forward all :form `(,subform nil)))) ;; multiple-value result (case n (0 (compiler-call #'compile-form-unprotected :forward all :result-mode result-mode :form `(muerte.cl:values ,subform))) (1 (compiler-values () :returns :ebx :code (append subform-code (with-labels (nth-value (done no-secondary)) `((:jnc '(:sub-program (,no-secondary) (:movl :edi :ebx) (:jmp ',done))) (:cmpl 2 :ecx) (:jb ',no-secondary) ,done))))) (t (compiler-values () :returns :eax :code (append subform-code (with-labels (nth-value (done no-value)) `((:jnc '(:sub-program (,no-value) (:movl :edi :eax) (:jmp ',done))) (:cmpl ,(1+ n) :ecx) (:jb ',no-value) (:locally (:movl (:edi (:edi-offset values ,(* 4 (- n 2)))) :eax)) ,done)))))))))) (t (error "non-constant nth-values not yet implemented."))))) (define-special-operator muerte::with-cloak (&all all &result-mode result-mode &form form &env env &funobj funobj) "Compile sub-forms such that they execute ``invisibly'', i.e. have no impact on the current result." (destructuring-bind ((&optional (cover-returns :nothing) cover-code (cover-modifies t) (cover-type '(values &rest t))) &body cloaked-forms) (cdr form) (assert (or cover-type (eq cover-returns :nothing))) (let ((modifies cover-modifies)) (cond ((null cloaked-forms) (compiler-values () :code cover-code :modifies modifies :type cover-type :returns cover-returns)) ((or (eq :nothing cover-returns) (eq :ignore result-mode)) (let* ((code (append cover-code (loop for cloaked-form in cloaked-forms appending (compiler-values-bind (&code code &modifies sub-modifies) (compiler-call #'compile-form-unprotected :forward all :form cloaked-form :result-mode :ignore) (setf modifies (modifies-union modifies sub-modifies)) code))))) (compiler-values () :code code :type nil :modifies modifies :returns :nothing))) (t (let* ((cloaked-env (make-instance 'with-things-on-stack-env :uplink env :funobj funobj)) (cloaked-code (loop for cloaked-form in cloaked-forms append (compiler-values-bind (&code code &modifies sub-modifies) (compiler-call #'compile-form-unprotected :env cloaked-env :defaults all :form cloaked-form :result-mode :ignore) (setf modifies (modifies-union modifies sub-modifies)) code)))) (cond ((member cloaked-code '(() ((:cld)) ((:std))) ; simple programs that don't interfere with current-result. :test #'equal) (compiler-values () :returns cover-returns :type cover-type :modifies modifies :code (append cover-code cloaked-code))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values)) (type-specifier-num-values cover-type) (loop for i from 0 below (type-specifier-num-values cover-type) always (type-specifier-singleton (type-specifier-nth-value i cover-type)))) ;; We cover a known set of values, so no need to push anything. (let ((value-forms (loop for i from 0 below (type-specifier-num-values cover-type) collect (cons 'muerte.cl:quote (type-specifier-singleton (type-specifier-nth-value i cover-type)))))) (compiler-values () :returns :multiple-values :type cover-type :code (append cover-code cloaked-code (compiler-call #'compile-form :defaults all :result-mode :multiple-values :form `(muerte.cl:values ,@value-forms)))))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values)) (type-specifier-num-values cover-type)) (when (loop for i from 0 below (type-specifier-num-values cover-type) always (type-specifier-singleton (type-specifier-nth-value i cover-type))) (warn "Covering only constants: ~S" cover-type)) ;; We know the number of values to cover.. (let ((num-values (type-specifier-num-values cover-type))) ( warn " covering ~D values .. " num - values ) (setf (stack-used cloaked-env) num-values) (compiler-values () :returns :multiple-values :type cover-type :code (append cover-code (when (<= 1 num-values) '((:locally (:pushl :eax)))) (when (<= 2 num-values) '((:locally (:pushl :ebx)))) (loop for i from 0 below (- num-values 2) collect `(:locally (:pushl (:edi ,(+ (global-constant-offset 'values) (* 4 i)))))) cloaked-code (when (<= 3 num-values) `((:locally (:movl ,(* +movitz-fixnum-factor+ (- num-values 2)) (:edi (:edi-offset num-values)))))) (loop for i downfrom (- num-values 2 1) to 0 collect `(:locally (:popl (:edi ,(+ (global-constant-offset 'values) (* 4 i)))))) (when (<= 2 num-values) '((:popl :ebx))) (when (<= 1 num-values) '((:popl :eax))) (case num-values (1 '((:clc))) (t (append (make-immediate-move num-values :ecx) '((:stc))))))))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values))) (when (type-specifier-num-values cover-type) (warn "covering ~D values: ~S." (type-specifier-num-values cover-type) cover-type)) we need a full - fledged m - v - prog1 , i.e to save all values of first - form . ;; (lexically) unknown amount of stack is used. (setf (stack-used cloaked-env) t) (compiler-values () :returns :multiple-values :modifies modifies :type cover-type :code (append cover-code (make-compiled-push-current-values) `((:pushl :ecx)) cloaked-code `((:popl :ecx) (:globally (:call (:edi (:edi-offset pop-current-values)))) (:leal (:esp (:ecx 4)) :esp))))) ((and (not (cdr cloaked-code)) (instruction-is (car cloaked-code) :incf-lexvar)) (destructuring-bind (binding delta &key protect-registers) (cdar cloaked-code) (let ((protected-register (case cover-returns ((:eax :ebx :ecx :edx) cover-returns) (t :edx)))) (assert (not (member protected-register protect-registers)) () "Can't protect ~S. Sorry, this opertor must be smartened up." protected-register) (compiler-values () :returns protected-register :type cover-type :code (append cover-code (make-result-and-returns-glue protected-register cover-returns) `((:incf-lexvar ,binding ,delta :protect-registers ,(cons protected-register protect-registers)))))))) just put the ( singular ) result of on the stack .. ;;; (when (not (typep cover-returns 'keyword)) ;;; ;; if it's a (non-modified) lexical-binding, we can do better.. ( warn " Covering non - register ~S " cover - returns ) ) ;;; (when (type-specifier-singleton (type-specifier-primary cover-type)) ( warn " Covering constant ~S " ;;; (type-specifier-singleton cover-type))) (let ((protected-register (case cover-returns ((:ebx :ecx :edx) cover-returns) (t :eax)))) #+ignore (when (>= 2 (length cloaked-code)) (warn "simple-cloaking for ~S: ~{~&~S~}" cover-returns cloaked-code)) (setf (stack-used cloaked-env) 1) (compiler-values () :returns protected-register :modifies modifies :type cover-type :code (append cover-code (make-result-and-returns-glue protected-register cover-returns) `((:pushl ,protected-register)) ;; evaluate each rest-form, discarding results cloaked-code ;; pop the result back `((:popl ,protected-register))))))))))))) (define-special-operator muerte::with-local-env (&all all &form form) (destructuring-bind ((local-env) sub-form) (cdr form) (compiler-call #'compile-form-unprotected :forward all :env local-env :form sub-form))) (define-special-operator muerte::++%2op (&all all &form form &env env &result-mode result-mode) (destructuring-bind (term1 term2) (cdr form) (if (eq :ignore result-mode) (compiler-call #'compile-form-unprotected :forward all :form `(muerte.cl:progn term1 term2)) (let ((returns (ecase (result-mode-type result-mode) ((:function :multiple-values :eax :push) :eax) ((:ebx :ecx :edx) result-mode) ((:lexical-binding) result-mode)))) (compiler-values () :returns returns :type 'number :code `((:add ,(movitz-binding term1 env) ,(movitz-binding term2 env) ,returns))))))) (define-special-operator muerte::include (&form form) (let ((*require-dependency-chain* (and (boundp '*require-dependency-chain*) (symbol-value '*require-dependency-chain*)))) (declare (special *require-dependency-chain*)) (destructuring-bind (module-name &optional path-spec) (cdr form) (declare (ignore path-spec)) (push module-name *require-dependency-chain*) (when (member module-name (cdr *require-dependency-chain*)) (error "Circular Movitz module dependency chain: ~S" (reverse (subseq *require-dependency-chain* 0 (1+ (position module-name *require-dependency-chain* :start 1)))))) (let ((require-path (movitz-module-path form))) (movitz-compile-file-internal require-path)))) (compiler-values ())) ;;; (define-special-operator muerte::no-macro-call (&all all &form form) (destructuring-bind (operator &rest arguments) (cdr form) (compiler-call #'compile-apply-symbol :forward all :form (cons operator arguments)))) (define-special-operator muerte::compiler-macro-call (&all all &form form &env env) (destructuring-bind (operator &rest arguments) (cdr form) (let ((name (if (not (setf-name operator)) operator (movitz-env-setf-operator-name (setf-name operator))))) (assert (movitz-compiler-macro-function name env) () "There is no compiler-macro ~S." name) (compiler-call #'compile-compiler-macro-form :forward all :form (cons name arguments))))) (define-special-operator muerte::do-result-mode-case (&all all &result-mode result-mode &form form) (loop for (cases . then-forms) in (cddr form) do (when (or (eq cases 'muerte.cl::t) (and (eq cases :plural) (member result-mode +multiple-value-result-modes+)) (and (eq cases :booleans) (member (result-mode-type result-mode) '(:boolean-branch-on-false :boolean-branch-on-true))) (if (atom cases) (eq cases (result-mode-type result-mode)) (member (result-mode-type result-mode) cases))) (return (compiler-call #'compile-implicit-progn :form then-forms :forward all))) finally (error "No matching result-mode-case for result-mode ~S." result-mode))) (define-special-operator muerte::inline-values (&all all &result-mode result-mode &form form) (let ((sub-forms (cdr form))) (if (eq :ignore result-mode) (compiler-call #'compile-implicit-progn ; compile only for side-effects. :forward all :form sub-forms) (case (length sub-forms) (0 (compiler-values () :functional-p t :returns :multiple-values :type '(values) :code `((:movl :edi :eax) (:xorl :ecx :ecx) (:stc)))) (1 (compiler-values-bind (&all sub-form &code code &returns returns &type type) (compiler-call #'compile-form-unprotected :result-mode (if (member result-mode +multiple-value-result-modes+) :eax result-mode) :forward all :form (first sub-forms)) (compiler-values (sub-form) :type (type-specifier-primary type) :returns (if (eq :multiple-values returns) :eax returns)))) (2 (multiple-value-bind (code functional-p modifies first-values second-values) (make-compiled-two-forms-into-registers (first sub-forms) :eax (second sub-forms) :ebx (all :funobj) (all :env)) (compiler-values () :code (append code ( make - immediate - move 2 : ecx ) '((:xorl :ecx :ecx) (:movb 2 :cl)) '((:stc))) :returns :multiple-values :type `(values ,(type-specifier-primary (compiler-values-getf first-values :type)) ,(type-specifier-primary (compiler-values-getf second-values :type))) :functional-p functional-p :modifies modifies))) (t (multiple-value-bind (arguments-code stack-displacement arguments-modifies arguments-types arguments-functional-p) (make-compiled-argument-forms sub-forms (all :funobj) (all :env)) (assert (not (minusp (- stack-displacement (- (length sub-forms) 2))))) (multiple-value-bind (stack-restore-code new-returns) (make-compiled-stack-restore (- stack-displacement (- (length sub-forms) 2)) result-mode :multiple-values) (compiler-values () :returns new-returns :type `(values ,@arguments-types) :functional-p arguments-functional-p :modifies arguments-modifies :code (append arguments-code (loop for i from (- (length sub-forms) 3) downto 0 collecting `(:locally (:popl (:edi (:edi-offset values ,(* i 4)))))) (make-immediate-move (* +movitz-fixnum-factor+ (- (length sub-forms) 2)) :ecx) `((:locally (:movl :ecx (:edi (:edi-offset num-values))))) (make-immediate-move (length sub-forms) :ecx) `((:stc)) stack-restore-code))))))))) (define-special-operator muerte::compiler-typecase (&all all &form form) (destructuring-bind (keyform &rest clauses) (cdr form) (compiler-values-bind (&type keyform-type) ;; This compiler-call is only for the &type.. (compiler-call #'compile-form-unprotected :form keyform :result-mode :eax :forward all) ( declare ( ignore keyform - type ) ) ( warn " keyform type : ~S " keyform - type ) ;;; (warn "clause-types: ~S" (mapcar #'car clauses)) #+ignore (let ((clause (find 'muerte.cl::t clauses :key #'car))) (assert clause) (compiler-call #'compile-implicit-progn :form (cdr clause) :forward all)) (loop for (clause-type . clause-forms) in clauses when (movitz-subtypep (type-specifier-primary keyform-type) clause-type) return (compiler-call #'compile-implicit-progn :form clause-forms :forward all) finally (error "No compiler-typecase clause matched compile-time type ~S." keyform-type))))) (define-special-operator muerte::exact-throw (&all all-throw &form form &env env &funobj funobj) "Perform a dynamic control transfer to catch-env-slot context (evaluated), with values from value-form. Error-form, if provided, is evaluated in case the context is zero (i.e. not found)." (destructuring-bind (context value-form &optional error-form) (cdr form) (let* ((local-env (make-local-movitz-environment env funobj :type 'let-env)) (dynamic-slot-binding (movitz-env-add-binding local-env (make-instance 'located-binding :name (gensym "dynamic-slot-")))) (next-continuation-step-binding (movitz-env-add-binding local-env (make-instance 'located-binding :name (gensym "continuation-step-"))))) (compiler-values () :returns :non-local-exit :code (append (compiler-call #'compile-form :forward all-throw :result-mode dynamic-slot-binding :form context) (compiler-call #'compile-form :forward all-throw :result-mode :multiple-values :form `(muerte.cl:multiple-value-prog1 ,value-form (muerte::with-inline-assembly (:returns :nothing) (:load-lexical ,dynamic-slot-binding :eax) ,@(when error-form `((:testl :eax :eax) (:jz '(:sub-program () (:compile-form (:result-mode :ignore) ,error-form))))) (:locally (:call (:edi (:edi-offset dynamic-unwind-next)))) (:store-lexical ,next-continuation-step-binding :eax :type t) ))) now outside of m - v - prog1 's cloak , with final dynamic - slot in .. ;; ..unwind it and transfer control. ;; * 12 dynamic - env uplink * 8 target jumper number * 4 target catch tag * 0 target EBP `((:load-lexical ,dynamic-slot-binding :edx) (:locally (:movl :edx (:edi (:edi-offset raw-scratch0)))) ; final continuation (:load-lexical ,next-continuation-step-binding :edx) ; next continuation-step (:locally (:movl :edx (:edi (:edi-offset dynamic-env)))) ; goto target dynamic-env (:locally (:call (:edi (:edi-offset dynamic-jump-next)))))))))) (: locally (: : esi (: edi (: edi - offset scratch1 ) ) ) ) (: locally (: : edx (: edi (: edi - offset dynamic - env ) ) ) ) ; exit dynamic - env ;;; (:movl :edx :esp) ; enter non-local jump stack mode. (: movl (: esp ) : edx ) ; target stack - frame EBP (: movl (: edx -4 ) : esi ) ; get target funobj into ESI (: (: esp 8) : edx ) ; target jumper number (: jmp (: esi : edx , ( slot - offset ' movitz - funobj ' ) ) ) ) ) ) ) ) ) (define-special-operator muerte::with-basic-restart (&all defaults &form form &env env) (destructuring-bind ((name function interactive test format-control &rest format-arguments) &body body) (cdr form) (check-type name symbol "a restart name") (let* ((entry-size (+ 10 (* 2 (length format-arguments))))) (with-labels (basic-restart-catch (label-set exit-point)) (compiler-values () :returns :multiple-values ;;; Basic-restart entry: 12 : parent 8 : jumper index (= > eip ) 4 : tag = # : basic - restart - tag ;;; 0: ebp/stack-frame ;;; -4: name ;;; -8: function ;;; -12: interactive function ;;; -16: test ;;; -20: format-control ;;; -24: (on-stack) list of format-arguments ;;; -28: cdr ;;; -32: car ... :code (append `((:locally (:pushl (:edi (:edi-offset dynamic-env)))) ; parent (:declare-label-set ,label-set (,exit-point)) (:pushl ',label-set) ; jumper index (:globally (:pushl (:edi (:edi-offset restart-tag)))) ; tag ebp (:load-constant ,name :push)) ; name (compiler-call #'compile-form :defaults defaults :form function :with-stack-used 5 :result-mode :push) (compiler-call #'compile-form :defaults defaults :form interactive :with-stack-used 6 :result-mode :push) (compiler-call #'compile-form :defaults defaults :form test :with-stack-used 7 :result-mode :push) `((:load-constant ,format-control :push) (:pushl :edi)) (loop for format-argument-cons on format-arguments as stack-use upfrom 11 by 2 append (if (cdr format-argument-cons) '((:leal (:esp -15) :eax) (:pushl :eax)) '((:pushl :edi))) append (compiler-call #'compile-form :defaults defaults :form (car format-argument-cons) :result-mode :push :with-stack-used stack-use :env env)) `((:leal (:esp ,(* 4 (+ 6 (* 2 (length format-arguments))))) :eax) (:locally (:movl :eax (:edi (:edi-offset dynamic-env))))) (when format-arguments `((:leal (:eax -31) :ebx) (:movl :ebx (:eax -24)))) (compiler-call #'compile-implicit-progn :forward defaults :env (make-instance 'simple-dynamic-env :uplink env :funobj (defaults :funobj) :num-specials 1) :result-mode :multiple-values :with-stack-used entry-size :form body) `((:leal (:esp ,(+ -12 -4 (* 4 entry-size))) :esp) ,exit-point (:movl (:esp) :ebp) (:movl (:esp 12) :edx) (:locally (:movl :edx (:edi (:edi-offset dynamic-env)))) (:leal (:esp 16) :esp) ))))))) (define-special-operator muerte::eql%b (&form form &env env &result-mode result-mode) (destructuring-bind (x y) (cdr form) (let ((returns (case (result-mode-type result-mode) ((:boolean-branch-on-true :boolean-branch-on-false) result-mode) (t :boolean-zf=1))) (x (movitz-binding x env)) (y (movitz-binding y env))) (compiler-values () :returns returns :code `((:eql ,x ,y ,returns)))))) (define-special-operator muerte::with-dynamic-extent-scope (&all all &form form &env env &funobj funobj) (destructuring-bind ((scope-tag) &body body) (cdr form) (let* ((save-esp-binding (make-instance 'located-binding :name (gensym "dynamic-extent-save-esp-"))) (base-binding (make-instance 'located-binding :name (gensym "dynamic-extent-base-"))) (scope-env (make-local-movitz-environment env funobj :type 'with-dynamic-extent-scope-env :scope-tag scope-tag :save-esp-binding save-esp-binding :base-binding base-binding))) (movitz-env-add-binding scope-env save-esp-binding) (movitz-env-add-binding scope-env base-binding) (compiler-values-bind (&code body-code &all body-values) (compiler-call #'compile-implicit-progn :env scope-env :form body :forward all) (compiler-values (body-values) :code (append `((:init-lexvar ,save-esp-binding :init-with-register :esp :init-with-type fixnum) (:enter-dynamic-scope ,scope-env) (:init-lexvar ,base-binding :init-with-register :esp :init-with-type fixnum)) body-code `((:load-lexical ,save-esp-binding :esp)))))))) (define-special-operator muerte::with-dynamic-extent-allocation (&all all &form form &env env &funobj funobj) (destructuring-bind ((scope-tag) &body body) (cdr form) (let* ((scope-env (loop for e = env then (movitz-environment-uplink e) unless e do (error "Dynamic-extent scope ~S not seen." scope-tag) when (and (typep e 'with-dynamic-extent-scope-env) (eq scope-tag (dynamic-extent-scope-tag e))) return e)) (allocation-env (make-local-movitz-environment env funobj :type 'with-dynamic-extent-allocation-env :scope scope-env))) (compiler-call #'compile-implicit-progn :form body :forward all :env allocation-env)))) (define-special-operator muerte::compiled-cons (&all all &form form &env env &funobj funobj) (destructuring-bind (car cdr) (cdr form) (let ((dynamic-extent-scope (find-dynamic-extent-scope env))) (cond (dynamic-extent-scope (compiler-values () :returns :eax :functional-p t :type 'cons :code (append (make-compiled-two-forms-into-registers car :eax cdr :ebx funobj env) `((:stack-cons ,(make-instance 'movitz-cons) ,dynamic-extent-scope))))) (t (compiler-values () :returns :eax :functional-p t :type 'cons :code (append (make-compiled-two-forms-into-registers car :eax cdr :ebx funobj env) `((:globally (:call (:edi (:edi-offset fast-cons))))))))))))
null
https://raw.githubusercontent.com/vonli/Ext2-for-movitz/81b6f8e165de3e1ea9cc7d2035b9259af83a6d26/special-operators.lisp
lisp
------------------------------------------------------------------ Description: Compilation of internal special operators. ------------------------------------------------------------------ (when (eq result-mode :function) (warn "test-returns: ~S" test-returns)) no test succeeded => nil This scheme doesn't quite cut it.. declined XXX this is really wasteful.. if a sub-compile has side-effects, then the entire with-inline-assembly form does too. (warn "res: ~S" result-mode-inverted-p) Inversion by result-mode ok. (warn "Not done: ~S/~S/~S." result-mode not-result-mode not-returns) We must invert returns-mode ((:eax :function :multiple-values :ebx :edx) (case result-mode ((:eax :ebx :ecx :edx :function :multiple-values) (compiler-values (not-values) :code (append (not-values :code) `((:cmpl :edi ,(single-value-register not-returns)) ,(single-value-register not-returns)) (:adcl 0 :ecx))) (t (compiler-values (not-values) :code (append (not-values :code) `((:cmpl :edi ,(single-value-register not-returns)))) :returns :boolean-zf=1)))) TRUE iff result equal to :edi/NIL. all but the last form have result-mode as declared do (warn "progn rm: ~S" (car sub-form-result-mode)) (warn "progn rm: ~S form: ~S" sub-returns-mode (car sub-form)) number of arguments single-value result multiple-value result simple programs that don't interfere with current-result. We cover a known set of values, so no need to push anything. We know the number of values to cover.. (lexically) unknown amount of stack is used. (when (not (typep cover-returns 'keyword)) ;; if it's a (non-modified) lexical-binding, we can do better.. (when (type-specifier-singleton (type-specifier-primary cover-type)) (type-specifier-singleton cover-type))) evaluate each rest-form, discarding results pop the result back compile only for side-effects. This compiler-call is only for the &type.. (warn "clause-types: ~S" (mapcar #'car clauses)) ..unwind it and transfer control. final continuation next continuation-step goto target dynamic-env exit dynamic - env (:movl :edx :esp) ; enter non-local jump stack mode. target stack - frame EBP get target funobj into ESI target jumper number Basic-restart entry: 0: ebp/stack-frame -4: name -8: function -12: interactive function -16: test -20: format-control -24: (on-stack) list of format-arguments -28: cdr -32: car ... parent jumper index tag name
Copyright ( C ) 20012000 , 2002 - 2005 , Department of Computer Science , University of Tromso , Norway Filename : special-operators.lisp Author : < > Created at : Fri Nov 24 16:22:59 2000 $ I d : special - operators.lisp , v 1.56 2007/02/26 18:25:21 Exp $ (in-package movitz) (defun ccc-result-to-returns (result-mode) (check-type result-mode keyword) (case result-mode (:ignore :nothing) (:function :multiple-values) (t result-mode))) (defun make-compiled-cond-clause (clause clause-num last-clause-p exit-label funobj env result-mode) "Return three values: The code for a cond clause, a boolean value indicating whether the clause's test was constantly true, The set of modified bindings." (assert (not (atom clause))) (let* ((clause-modifies nil) (test-form (car clause)) (then-forms (cdr clause))) (cond ((null then-forms) (compiler-values-bind (&code test-code &returns test-returns) (compiler-call #'compile-form :modify-accumulate clause-modifies :result-mode (case (operator result-mode) (:boolean-branch-on-false (if last-clause-p result-mode (cons :boolean-branch-on-true exit-label))) (:boolean-branch-on-true result-mode) (:ignore (cons :boolean-branch-on-true exit-label)) (:push (if last-clause-p :push :eax)) (#.+multiple-value-result-modes+ :eax) (t result-mode)) :form test-form :funobj funobj :env env) (assert (not (null test-code)) (clause) "null test-code!") (values (ecase (operator test-returns) ((:boolean-branch-on-true :boolean-branch-on-false) test-code) (:push (assert last-clause-p) test-code) ((:multiple-values :eax :ebx :ecx :edx) (let ((singlify (when (member result-mode +multiple-value-result-modes+) '((:clc))))) (append test-code (cond ((not last-clause-p) (append `((:cmpl :edi ,(single-value-register (operator test-returns)))) singlify (when (eq :push result-mode) `((:pushl ,(single-value-register (operator test-returns))))) `((:jne ',exit-label)))) (t singlify)))))) nil))) ((not (null then-forms)) (let ((skip-label (gensym (format nil "cond-skip-~D-" clause-num)))) (compiler-values-bind (&code test-code) (compiler-call #'compile-form :result-mode (cond ((and last-clause-p (eq (operator result-mode) :boolean-branch-on-false)) (cons :boolean-branch-on-false (cdr result-mode))) (t (cons :boolean-branch-on-false skip-label))) :modify-accumulate clause-modifies :form test-form :funobj funobj :env env) (compiler-values-bind (&code then-code &returns then-returns) (compiler-call #'compile-form :form (cons 'muerte.cl::progn then-forms) :modify-accumulate clause-modifies :funobj funobj :env env :result-mode result-mode) (let ((constantly-true-p (null test-code))) (values (append test-code then-code (unless (or last-clause-p (eq then-returns :non-local-exit)) `((:jmp ',exit-label))) (unless constantly-true-p (list skip-label))) constantly-true-p clause-modifies))))))))) (defun chose-joined-returns-and-result (result-mode) "From a result-mode, determine a joined result-mode (for several branches), and the correspondig returns mode (secondary value)." (let ((joined-result-mode (case (operator result-mode) (:values :multiple-values) ((:ignore :function :multiple-values :eax :ebx :ecx :edx :boolean-branch-on-false :boolean-branch-on-true) result-mode) (t :eax)))) (values joined-result-mode (ecase (operator joined-result-mode) (:ignore :nothing) (:function :multiple-values) ((:multiple-values :eax :push :eax :ebx :ecx :edx :boolean-branch-on-true :boolean-branch-on-false) joined-result-mode))))) (define-special-operator compiled-cond (&form form &funobj funobj &env env &result-mode result-mode) (let ((clauses (cdr form))) (let* ((cond-exit-label (gensym "cond-exit-")) (cond-result-mode (case (operator result-mode) (:values :multiple-values) ((:ignore :function :multiple-values :eax :ebx :ecx :edx :boolean-branch-on-false :boolean-branch-on-true) result-mode) (t :eax))) (cond-returns (ecase (operator cond-result-mode) (:ignore :nothing) (:function :multiple-values) ((:multiple-values :eax :push :eax :ebx :ecx :edx :boolean-branch-on-true :boolean-branch-on-false) cond-result-mode))) (only-control-p (member (operator cond-result-mode) '(:ignore :boolean-branch-on-true :boolean-branch-on-false)))) (loop with last-clause-num = (1- (length clauses)) for clause in clauses for clause-num upfrom 0 as (clause-code constantly-true-p) = (multiple-value-list (make-compiled-cond-clause clause clause-num (and only-control-p (= clause-num last-clause-num)) cond-exit-label funobj env cond-result-mode)) append clause-code into cond-code when constantly-true-p do (return (compiler-values () :returns cond-returns :code (append cond-code (list cond-exit-label)))) finally (return (compiler-values () :returns cond-returns :code (append cond-code (unless only-control-p (compiler-call #'compile-form :form nil :funobj funobj :env env :top-level-p nil :result-mode cond-result-mode)) (list cond-exit-label)))))))) (define-special-operator compiled-case (&all all &form form &result-mode result-mode) (destructuring-bind (keyform &rest clauses) (cdr form) #+ignore (let ((cases (loop for (clause . nil) in clauses append (if (consp clause) clause (unless (member clause '(nil muerte.cl:t muerte.cl:otherwise)) (list clause)))))) (warn "case clauses:~%~S" cases)) (compiler-values-bind (&code key-code &returns key-returns) (compiler-call #'compile-form-unprotected :result-mode :eax :forward all :form keyform) (multiple-value-bind (case-result-mode case-returns) (chose-joined-returns-and-result result-mode) (let ((key-reg (accept-register-mode key-returns))) (flet ((otherwise-clause-p (x) (member (car x) '(muerte.cl:t muerte.cl:otherwise))) (make-first-check (key then-label then-code exit-label) `((:load-constant ,key ,key-reg :op :cmpl) (:je '(:sub-program (,then-label) ,@then-code (:jmp ',exit-label)))))) (cond ((otherwise-clause-p (first clauses)) (compiler-call #'compile-implicit-progn :forward all :form (rest (first clauses)))) (t (compiler-values () :returns case-returns :code (append (make-result-and-returns-glue key-reg key-returns key-code) (loop with exit-label = (gensym "case-exit-") for clause-head on clauses as clause = (first clause-head) as keys = (first clause) as then-forms = (rest clause) as then-label = (gensym "case-then-") as then-code = (compiler-call #'compile-form :result-mode case-result-mode :forward all :form `(muerte.cl:progn ,@then-forms)) if (otherwise-clause-p clause) do (assert (endp (rest clause-head)) () "Case's otherwise clause must be the last clause.") and append then-code else if (atom keys) append (make-first-check keys then-label then-code exit-label) else append (make-first-check (first keys) then-label then-code exit-label) and append (loop for key in (rest keys) append `((:load-constant ,key ,key-reg :op :cmpl) (:je ',then-label))) if (endp (rest clause-head)) append (append (unless (otherwise-clause-p clause) (compiler-call #'compile-form :result-mode case-result-mode :forward all :form nil)) (list exit-label))))))))))))) (define-special-operator compile-time-find-class (&all all &form form) (destructuring-bind (class-name) (cdr form) (compiler-call #'compile-form-unprotected :form (muerte::movitz-find-class class-name) :forward all))) (define-special-operator make-named-function (&form form &env env) (destructuring-bind (name formals declarations docstring body) (cdr form) (declare (ignore docstring)) (handler-bind (#+ignore ((or error warning) (lambda (c) (declare (ignore c)) (format *error-output* "~&;; In function ~S:~&" name)))) (let* ((*compiling-function-name* name) (funobj (make-compiled-funobj name formals declarations body env nil))) (setf (movitz-funobj-symbolic-name funobj) name) (setf (movitz-env-named-function name) funobj)))) (compiler-values ())) (define-special-operator make-primitive-function (&form form &env env) (destructuring-bind (name docstring body) (cdr form) (destructuring-bind (name &key symtab-property) (if (consp name) name (list name)) (handler-bind (((or warning error) (lambda (c) (declare (ignore c)) (format *error-output* "~&;; In primitive function ~S:" name)))) (multiple-value-bind (code-vector symtab) (make-compiled-primitive body env nil docstring) (setf (movitz-symbol-value (movitz-read name)) code-vector) (when symtab-property (setf (movitz-env-get name :symtab) (muerte::translate-program symtab :movitz :muerte))) (compiler-values ())))))) (define-special-operator define-prototyped-function (&form form) (destructuring-bind (function-name proto-name &rest parameters) (cdr form) (let* ((funobj-proto (movitz-env-named-function proto-name)) (funobj (make-instance 'movitz-funobj :name (movitz-read function-name) :code-vector (movitz-funobj-code-vector funobj-proto) :code-vector%1op (movitz-funobj-code-vector%1op funobj-proto) :code-vector%2op (movitz-funobj-code-vector%2op funobj-proto) :code-vector%3op (movitz-funobj-code-vector%3op funobj-proto) :lambda-list (movitz-funobj-lambda-list funobj-proto) :num-constants (movitz-funobj-num-constants funobj-proto) :num-jumpers (movitz-funobj-num-jumpers funobj-proto) :jumpers-map (movitz-funobj-jumpers-map funobj-proto) :symbolic-code (when (slot-boundp funobj-proto 'symbolic-code) (movitz-funobj-symbolic-code funobj-proto)) :const-list (let ((c (copy-list (movitz-funobj-const-list funobj-proto)))) (loop for (lisp-parameter value) in parameters as parameter = (movitz-read lisp-parameter) do (assert (member parameter c) () "~S is not a function prototype parameter for ~S. ~ The valid parameters are~{ ~S~}." parameter proto-name (mapcar #'movitz-print (movitz-funobj-const-list funobj-proto))) (setf (car (member parameter c)) (if (and (consp value) (eq :movitz-find-class (car value))) (muerte::movitz-find-class (cadr value)) (movitz-read value)))) c)))) (setf (movitz-funobj-symbolic-name funobj) function-name) (setf (movitz-env-named-function function-name) funobj) (compiler-values ())))) (define-special-operator define-setf-expander-compile-time (&form form) (destructuring-bind (access-fn lambda-list macro-body) (cdr form) (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-macro-body (translate-program macro-body :muerte.cl :cl))) (multiple-value-bind (cl-body declarations doc-string) (parse-docstring-declarations-and-body cl-macro-body 'cl:declare) (declare (ignore doc-string)) (setf (movitz-env-get access-fn 'muerte::setf-expander nil) (let* ((form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym))) (expander (if (null cl-lambda-list) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal) ,@declarations) (translate-program (block ,access-fn ,@cl-body) :cl :muerte.cl)) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal) ,@declarations) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (values-list (translate-program (multiple-value-list (block ,access-fn ,@cl-body)) :cl :muerte.cl))))))) (movitz-macro-expander-make-function expander :type :setf :name access-fn))))))) (compiler-values ())) (define-special-operator muerte::defmacro-compile-time (&form form) (destructuring-bind (name lambda-list macro-body) (cdr form) (check-type name symbol "a macro name") (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((expander-name (make-symbol (format nil "~A-macro" name))) (cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-macro-body (translate-program macro-body :muerte.cl :cl))) (when (member name (image-called-functions *image*) :key #'first) #+ignore (warn "Macro ~S defined after being called as function (first in ~S)." name (cdr (find name (image-called-functions *image*) :key #'first)))) (multiple-value-bind (cl-body declarations doc-string) (parse-docstring-declarations-and-body cl-macro-body 'cl:declare) (declare (ignore doc-string)) ( warn " defmacro ~S : ~S " name cl - body ) (let ((expander-lambda (let ((form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym)))) (if (null cl-lambda-list) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal)) (declare ,@declarations) (translate-program (block ,name ,@cl-body) :cl :muerte.cl)) `(lambda (,form-formal ,env-formal) (declare (ignorable ,form-formal ,env-formal)) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (declare ,@declarations) (translate-program (block ,name ,@cl-body) :cl :muerte.cl))))))) (setf (movitz-macro-function name) (movitz-macro-expander-make-function expander-lambda :name expander-name :type :defmacro))))))) (compiler-values ())) (define-special-operator muerte::define-compiler-macro-compile-time (&form form) (destructuring-bind (name lambda-list doc-dec-body) (cdr form) (multiple-value-bind (body declarations) (parse-docstring-declarations-and-body doc-dec-body) (let ((operator-name (or (and (setf-name name) (movitz-env-setf-operator-name (setf-name name))) name))) (multiple-value-bind (wholevar envvar reqvars optionals restvar keyvars auxvars) (decode-macro-lambda-list lambda-list) (let ((cl-lambda-list (translate-program `(,@reqvars ,@(when optionals '(&optional)) ,@optionals ,@(when restvar `(&rest ,restvar)) ,@(when keyvars '(&key)) ,@keyvars ,@(when auxvars '(&aux)) ,@auxvars) :muerte.cl :cl)) (cl-body (translate-program body :muerte.cl :cl)) (declarations (translate-program declarations :muerte.cl :cl)) (form-formal (or wholevar (gensym))) (env-formal (or envvar (gensym))) (expansion-var (gensym))) (when (member operator-name (image-called-functions *image*) :key #'first) (warn "Compiler-macro ~S defined after being called as function (first in ~S)" operator-name (cdr (find operator-name (image-called-functions *image*) :key #'first)))) (let ((expander `(lambda (,form-formal ,env-formal) (declare (ignorable ,env-formal)) (destructuring-bind ,cl-lambda-list (translate-program (rest ,form-formal) :muerte.cl :cl) (declare ,@declarations) (let ((,expansion-var (block ,operator-name ,@cl-body))) (if (eq ,form-formal ,expansion-var) (translate-program ,expansion-var :cl :muerte.cl))))))) (setf (movitz-compiler-macro-function operator-name nil) (movitz-macro-expander-make-function expander :name name :type :compiler-macro)))))))) (compiler-values ())) (define-special-operator muerte::with-inline-assembly-case (&all forward &form form &funobj funobj &env env &result-mode result-mode) (destructuring-bind (global-options &body inline-asm-cases) (cdr form) (destructuring-bind (&key (side-effects t) ((:type global-type))) global-options (let ((modifies ())) (loop for case-spec in inline-asm-cases finally (error "Found no inline-assembly-case matching ~S." result-mode) do (destructuring-bind ((matching-result-modes &optional (returns :same) &key labels (type global-type)) &body inline-asm) (cdr case-spec) (when (eq returns :same) (setf returns (case result-mode (:function :multiple-values) (t result-mode)))) (when (flet ((match (matching-result-mode) (or (eq 'muerte.cl::t matching-result-mode) (eq t matching-result-mode) (eq (operator result-mode) matching-result-mode) (and (eq :register matching-result-mode) (member result-mode '(:eax ebx ecx edx :single-value)))))) (if (symbolp matching-result-modes) (match matching-result-modes) (find-if #'match matching-result-modes))) (case returns (:register (setf returns (case result-mode ((:eax :ebx :ecx :edx) result-mode) (t :eax))))) (unless type (setf type (ecase (operator returns) ((:nothing) nil) ((:eax :ebx :ecx :edx) t) (#.+boolean-modes+ t) ((:boolean-branch-on-false :boolean-branch-on-true) t) ((:multiple-values) '(values &rest t))))) (return (setf (assembly-macro-expander :branch-when amenv) #'(lambda (expr) (destructuring-bind (boolean-mode) (cdr expr) (ecase (operator result-mode) ((:boolean-branch-on-true :boolean-branch-on-false) (list (make-branch-on-boolean boolean-mode (operands result-mode) :invert nil))))))) (setf (assembly-macro-expander :compile-form amenv) #'(lambda (expr) (destructuring-bind ((&key ((:result-mode sub-result-mode))) sub-form) (cdr expr) (case sub-result-mode (:register (setf sub-result-mode returns)) (:same (setf sub-result-mode result-mode))) (assert sub-result-mode (sub-result-mode) "Assembly :COMPILE-FORM directive doesn't provide a result-mode: ~S" expr) (compiler-values-bind (&code sub-code &functional-p sub-functional-p &modifies sub-modifies) (compiler-call #'compile-form :defaults forward :form sub-form :result-mode sub-result-mode) (unless sub-functional-p (setq side-effects t)) (setf modifies (modifies-union modifies sub-modifies)) sub-code)))) (setf (assembly-macro-expander :offset amenv) #'(lambda (expr) (destructuring-bind (type slot &optional (extra 0)) (cdr expr) (let ((mtype (find-symbol (symbol-name type) :movitz)) (mslot (find-symbol (symbol-name slot) :movitz))) (assert mtype (mtype) "Type not a Movitz symbol: ~A" type) (assert mslot (mslot) "Slot not a Movitz symbol: ~A" slot) (list (+ (slot-offset mtype mslot) (eval extra))))))) (setf (assembly-macro-expander :returns-mode amenv) #'(lambda (expr) (assert (= 1 (length expr))) (list returns))) (setf (assembly-macro-expander :result-register amenv) #'(lambda (expr) (assert (= 1 (length expr))) (assert (member returns '(:eax :ebx :ecx :edx))) (list returns))) (setf (assembly-macro-expander :result-register-low8 amenv) #'(lambda (expr) (assert (= 1 (length expr))) (assert (member returns '(:eax :ebx :ecx :edx))) (list (register32-to-low8 returns)))) (setf (assembly-macro-expander :compile-arglist amenv) #'(lambda (expr) (destructuring-bind (ignore &rest arg-forms) (cdr expr) (declare (ignore ignore)) (setq side-effects t) (make-compiled-argument-forms arg-forms funobj env)))) (setf (assembly-macro-expander :compile-two-forms amenv) #'(lambda (expr) (destructuring-bind ((reg1 reg2) form1 form2) (cdr expr) (multiple-value-bind (code sub-functional-p sub-modifies) (make-compiled-two-forms-into-registers form1 reg1 form2 reg2 funobj env) (unless sub-functional-p (setq side-effects t)) (setq modifies (modifies-union modifies sub-modifies)) code)))) (setf (assembly-macro-expander :call-global-pf amenv) #'(lambda (expr) (destructuring-bind (name) (cdr expr) `((:globally (:call (:edi (:edi-offset ,name)))))))) (setf (assembly-macro-expander :call-local-pf amenv) #'(lambda (expr) (destructuring-bind (name) (cdr expr) `((:locally (:call (:edi (:edi-offset ,name)))))))) (setf (assembly-macro-expander :warn amenv) #'(lambda (expr) (apply #'warn (cdr expr)) nil)) (setf (assembly-macro-expander :lexical-store amenv) (lambda (expr) (destructuring-bind (var reg &key (type t)) (cdr expr) `((:store-lexical ,(movitz-binding var env) ,reg :type ,type))))) (setf (assembly-macro-expander :lexical-binding amenv) (lambda (expr) (destructuring-bind (var) (cdr expr) (let ((binding (movitz-binding var env))) (check-type binding binding) (list binding))))) (let ((code (assembly-macroexpand inline-asm amenv))) #+ignore (assert (not (and (not side-effects) (tree-search code '(:store-lexical)))) () "Inline assembly is declared side-effects-free, but contains :store-lexical.") (when labels (setf code (subst (gensym (format nil "~A-" (first labels))) (first labels) code)) (dolist (label (rest labels)) (setf code (nsubst (gensym (format nil "~A-" label)) label code)))) (compiler-values () :code code :returns returns :type (translate-program type :muerte.cl :cl) :modifies modifies :functional-p (not side-effects)))))))))))) (define-special-operator muerte::declaim-compile-time (&form form &top-level-p top-level-p) (unless top-level-p (warn "DECLAIM not at top-level.")) (let ((declaration-specifiers (cdr form))) (movitz-env-load-declarations declaration-specifiers *movitz-global-environment* :declaim)) (compiler-values ())) (define-special-operator call-internal (&form form) (destructuring-bind (if-name &optional argument) (cdr form) (assert (not argument)) (compiler-values () :code `((:call (:edi ,(slot-offset 'movitz-run-time-context if-name)))) :returns :nothing))) (define-special-operator inlined-not (&all forward &form form &result-mode result-mode) (assert (= 2 (length form))) (let ((x (second form))) (if (eq result-mode :ignore) (compiler-call #'compile-form-unprotected :forward forward :form x) (multiple-value-bind (not-result-mode result-mode-inverted-p) (cond ((or (member (operator result-mode) +boolean-modes+) (member (operator result-mode) '(:boolean-branch-on-false :boolean-branch-on-true))) (values (complement-boolean-result-mode result-mode) t)) ((member (operator result-mode) +multiple-value-result-modes+) (values :eax nil)) ((member (operator result-mode) '(:push)) (values :eax nil)) (t (values result-mode nil))) (compiler-values-bind (&all not-values &returns not-returns &code not-code &type not-type) (compiler-call #'compile-form-unprotected :defaults forward :form x :result-mode not-result-mode) (setf (not-values :producer) (list :not (not-values :producer))) (let ((not-type (type-specifier-primary not-type))) (setf (not-values :type) (cond ((movitz-subtypep not-type 'null) '(eql t)) ((movitz-subtypep not-type '(not null)) 'null) (t 'boolean)))) (cond ((and result-mode-inverted-p (eql not-result-mode not-returns)) (compiler-values (not-values) :returns result-mode)) (result-mode-inverted-p (multiple-value-bind (code) (make-result-and-returns-glue not-result-mode not-returns not-code) (compiler-values (not-values) :returns result-mode :code code))) ((not result-mode-inverted-p) (case (operator not-returns) (#.(append +boolean-modes+ '(:boolean-branch-on-true :boolean-branch-on-false)) (compiler-values (not-values) :returns (complement-boolean-result-mode not-returns))) (: : ecx : ecx ) (: cmpl , ( 1 + ( image - nil - word * image * ) ) : returns ' (: boolean - ecx 1 0 ) ) ) ((:eax :function :multiple-values :ebx :ecx :edx) (compiler-values (not-values) :code (append (not-values :code) `((:cmpl :edi ,(single-value-register not-returns)))) (otherwise #+ignore (warn "unable to deal intelligently with inlined-NOT not-returns: ~S for ~S from ~S" not-returns not-result-mode (not-values :producer)) (let ((label (make-symbol "not-label"))) (compiler-values (not-values) :returns :eax :code (append (make-result-and-returns-glue :eax not-returns (not-values :code)) `((:cmpl :edi :eax) (:movl :edi :eax) (:jne ',label) (:globally (:movl (:edi (:edi-offset t-symbol)) :eax)) ,label))))))))))))) (define-special-operator muerte::with-progn-results (&all forward &form form &top-level-p top-level-p &result-mode result-mode) (destructuring-bind (buried-result-modes &body body) (cdr form) (assert (< (length buried-result-modes) (length body)) () "WITH-PROGN-RESULTS must have fewer result-modes than body elements: ~S" form) (loop with returns-mode = :nothing with no-side-effects-p = t with modifies = nil for sub-form on body as sub-form-result-mode = buried-result-modes then (or (cdr sub-form-result-mode) sub-form-result-mode) as current-result-mode = (if (endp (cdr sub-form)) result-mode (car sub-form-result-mode)) as last-form-p = (endp (cdr sub-form)) appending (compiler-values-bind (&code code &returns sub-returns-mode &functional-p no-sub-side-effects-p &modifies sub-modifies) (compiler-call (if last-form-p #'compile-form-unprotected #'compile-form) :defaults forward :form (car sub-form) :top-level-p top-level-p :result-mode current-result-mode) (unless no-sub-side-effects-p (setf no-side-effects-p nil)) (setq modifies (modifies-union modifies sub-modifies)) (when last-form-p (setf returns-mode sub-returns-mode)) (if (and no-sub-side-effects-p (eq current-result-mode :ignore)) nil code)) into progn-code finally (return (compiler-values () :code progn-code :returns returns-mode :modifies modifies :functional-p no-side-effects-p))))) (define-special-operator muerte::simple-funcall (&form form) (destructuring-bind (apply-funobj) (cdr form) (compiler-values () :returns :multiple-values :functional-p nil put function funobj in ESI call new ESI 's code - vector (:call (:esi ,(slot-offset 'movitz-funobj 'code-vector))))))) (define-special-operator muerte::compiled-nth-value (&all all &form form &env env &result-mode result-mode) (destructuring-bind (n-form subform) (cdr form) (cond ((movitz-constantp n-form) (let ((n (eval-form n-form env))) (check-type n (integer 0 *)) (compiler-values-bind (&code subform-code &returns subform-returns) (compiler-call #'compile-form-unprotected :forward all :result-mode :multiple-values :form subform) (if (not (eq subform-returns :multiple-values)) (case n (0 (compiler-values () :code subform-code :returns subform-returns)) (t (compiler-call #'compile-implicit-progn :forward all :form `(,subform nil)))) (case n (0 (compiler-call #'compile-form-unprotected :forward all :result-mode result-mode :form `(muerte.cl:values ,subform))) (1 (compiler-values () :returns :ebx :code (append subform-code (with-labels (nth-value (done no-secondary)) `((:jnc '(:sub-program (,no-secondary) (:movl :edi :ebx) (:jmp ',done))) (:cmpl 2 :ecx) (:jb ',no-secondary) ,done))))) (t (compiler-values () :returns :eax :code (append subform-code (with-labels (nth-value (done no-value)) `((:jnc '(:sub-program (,no-value) (:movl :edi :eax) (:jmp ',done))) (:cmpl ,(1+ n) :ecx) (:jb ',no-value) (:locally (:movl (:edi (:edi-offset values ,(* 4 (- n 2)))) :eax)) ,done)))))))))) (t (error "non-constant nth-values not yet implemented."))))) (define-special-operator muerte::with-cloak (&all all &result-mode result-mode &form form &env env &funobj funobj) "Compile sub-forms such that they execute ``invisibly'', i.e. have no impact on the current result." (destructuring-bind ((&optional (cover-returns :nothing) cover-code (cover-modifies t) (cover-type '(values &rest t))) &body cloaked-forms) (cdr form) (assert (or cover-type (eq cover-returns :nothing))) (let ((modifies cover-modifies)) (cond ((null cloaked-forms) (compiler-values () :code cover-code :modifies modifies :type cover-type :returns cover-returns)) ((or (eq :nothing cover-returns) (eq :ignore result-mode)) (let* ((code (append cover-code (loop for cloaked-form in cloaked-forms appending (compiler-values-bind (&code code &modifies sub-modifies) (compiler-call #'compile-form-unprotected :forward all :form cloaked-form :result-mode :ignore) (setf modifies (modifies-union modifies sub-modifies)) code))))) (compiler-values () :code code :type nil :modifies modifies :returns :nothing))) (t (let* ((cloaked-env (make-instance 'with-things-on-stack-env :uplink env :funobj funobj)) (cloaked-code (loop for cloaked-form in cloaked-forms append (compiler-values-bind (&code code &modifies sub-modifies) (compiler-call #'compile-form-unprotected :env cloaked-env :defaults all :form cloaked-form :result-mode :ignore) (setf modifies (modifies-union modifies sub-modifies)) code)))) (cond ((member cloaked-code :test #'equal) (compiler-values () :returns cover-returns :type cover-type :modifies modifies :code (append cover-code cloaked-code))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values)) (type-specifier-num-values cover-type) (loop for i from 0 below (type-specifier-num-values cover-type) always (type-specifier-singleton (type-specifier-nth-value i cover-type)))) (let ((value-forms (loop for i from 0 below (type-specifier-num-values cover-type) collect (cons 'muerte.cl:quote (type-specifier-singleton (type-specifier-nth-value i cover-type)))))) (compiler-values () :returns :multiple-values :type cover-type :code (append cover-code cloaked-code (compiler-call #'compile-form :defaults all :result-mode :multiple-values :form `(muerte.cl:values ,@value-forms)))))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values)) (type-specifier-num-values cover-type)) (when (loop for i from 0 below (type-specifier-num-values cover-type) always (type-specifier-singleton (type-specifier-nth-value i cover-type))) (warn "Covering only constants: ~S" cover-type)) (let ((num-values (type-specifier-num-values cover-type))) ( warn " covering ~D values .. " num - values ) (setf (stack-used cloaked-env) num-values) (compiler-values () :returns :multiple-values :type cover-type :code (append cover-code (when (<= 1 num-values) '((:locally (:pushl :eax)))) (when (<= 2 num-values) '((:locally (:pushl :ebx)))) (loop for i from 0 below (- num-values 2) collect `(:locally (:pushl (:edi ,(+ (global-constant-offset 'values) (* 4 i)))))) cloaked-code (when (<= 3 num-values) `((:locally (:movl ,(* +movitz-fixnum-factor+ (- num-values 2)) (:edi (:edi-offset num-values)))))) (loop for i downfrom (- num-values 2 1) to 0 collect `(:locally (:popl (:edi ,(+ (global-constant-offset 'values) (* 4 i)))))) (when (<= 2 num-values) '((:popl :ebx))) (when (<= 1 num-values) '((:popl :eax))) (case num-values (1 '((:clc))) (t (append (make-immediate-move num-values :ecx) '((:stc))))))))) ((and (eq :multiple-values cover-returns) (member result-mode '(:function :multiple-values))) (when (type-specifier-num-values cover-type) (warn "covering ~D values: ~S." (type-specifier-num-values cover-type) cover-type)) we need a full - fledged m - v - prog1 , i.e to save all values of first - form . (setf (stack-used cloaked-env) t) (compiler-values () :returns :multiple-values :modifies modifies :type cover-type :code (append cover-code (make-compiled-push-current-values) `((:pushl :ecx)) cloaked-code `((:popl :ecx) (:globally (:call (:edi (:edi-offset pop-current-values)))) (:leal (:esp (:ecx 4)) :esp))))) ((and (not (cdr cloaked-code)) (instruction-is (car cloaked-code) :incf-lexvar)) (destructuring-bind (binding delta &key protect-registers) (cdar cloaked-code) (let ((protected-register (case cover-returns ((:eax :ebx :ecx :edx) cover-returns) (t :edx)))) (assert (not (member protected-register protect-registers)) () "Can't protect ~S. Sorry, this opertor must be smartened up." protected-register) (compiler-values () :returns protected-register :type cover-type :code (append cover-code (make-result-and-returns-glue protected-register cover-returns) `((:incf-lexvar ,binding ,delta :protect-registers ,(cons protected-register protect-registers)))))))) just put the ( singular ) result of on the stack .. ( warn " Covering non - register ~S " cover - returns ) ) ( warn " Covering constant ~S " (let ((protected-register (case cover-returns ((:ebx :ecx :edx) cover-returns) (t :eax)))) #+ignore (when (>= 2 (length cloaked-code)) (warn "simple-cloaking for ~S: ~{~&~S~}" cover-returns cloaked-code)) (setf (stack-used cloaked-env) 1) (compiler-values () :returns protected-register :modifies modifies :type cover-type :code (append cover-code (make-result-and-returns-glue protected-register cover-returns) `((:pushl ,protected-register)) cloaked-code `((:popl ,protected-register))))))))))))) (define-special-operator muerte::with-local-env (&all all &form form) (destructuring-bind ((local-env) sub-form) (cdr form) (compiler-call #'compile-form-unprotected :forward all :env local-env :form sub-form))) (define-special-operator muerte::++%2op (&all all &form form &env env &result-mode result-mode) (destructuring-bind (term1 term2) (cdr form) (if (eq :ignore result-mode) (compiler-call #'compile-form-unprotected :forward all :form `(muerte.cl:progn term1 term2)) (let ((returns (ecase (result-mode-type result-mode) ((:function :multiple-values :eax :push) :eax) ((:ebx :ecx :edx) result-mode) ((:lexical-binding) result-mode)))) (compiler-values () :returns returns :type 'number :code `((:add ,(movitz-binding term1 env) ,(movitz-binding term2 env) ,returns))))))) (define-special-operator muerte::include (&form form) (let ((*require-dependency-chain* (and (boundp '*require-dependency-chain*) (symbol-value '*require-dependency-chain*)))) (declare (special *require-dependency-chain*)) (destructuring-bind (module-name &optional path-spec) (cdr form) (declare (ignore path-spec)) (push module-name *require-dependency-chain*) (when (member module-name (cdr *require-dependency-chain*)) (error "Circular Movitz module dependency chain: ~S" (reverse (subseq *require-dependency-chain* 0 (1+ (position module-name *require-dependency-chain* :start 1)))))) (let ((require-path (movitz-module-path form))) (movitz-compile-file-internal require-path)))) (compiler-values ())) (define-special-operator muerte::no-macro-call (&all all &form form) (destructuring-bind (operator &rest arguments) (cdr form) (compiler-call #'compile-apply-symbol :forward all :form (cons operator arguments)))) (define-special-operator muerte::compiler-macro-call (&all all &form form &env env) (destructuring-bind (operator &rest arguments) (cdr form) (let ((name (if (not (setf-name operator)) operator (movitz-env-setf-operator-name (setf-name operator))))) (assert (movitz-compiler-macro-function name env) () "There is no compiler-macro ~S." name) (compiler-call #'compile-compiler-macro-form :forward all :form (cons name arguments))))) (define-special-operator muerte::do-result-mode-case (&all all &result-mode result-mode &form form) (loop for (cases . then-forms) in (cddr form) do (when (or (eq cases 'muerte.cl::t) (and (eq cases :plural) (member result-mode +multiple-value-result-modes+)) (and (eq cases :booleans) (member (result-mode-type result-mode) '(:boolean-branch-on-false :boolean-branch-on-true))) (if (atom cases) (eq cases (result-mode-type result-mode)) (member (result-mode-type result-mode) cases))) (return (compiler-call #'compile-implicit-progn :form then-forms :forward all))) finally (error "No matching result-mode-case for result-mode ~S." result-mode))) (define-special-operator muerte::inline-values (&all all &result-mode result-mode &form form) (let ((sub-forms (cdr form))) (if (eq :ignore result-mode) :forward all :form sub-forms) (case (length sub-forms) (0 (compiler-values () :functional-p t :returns :multiple-values :type '(values) :code `((:movl :edi :eax) (:xorl :ecx :ecx) (:stc)))) (1 (compiler-values-bind (&all sub-form &code code &returns returns &type type) (compiler-call #'compile-form-unprotected :result-mode (if (member result-mode +multiple-value-result-modes+) :eax result-mode) :forward all :form (first sub-forms)) (compiler-values (sub-form) :type (type-specifier-primary type) :returns (if (eq :multiple-values returns) :eax returns)))) (2 (multiple-value-bind (code functional-p modifies first-values second-values) (make-compiled-two-forms-into-registers (first sub-forms) :eax (second sub-forms) :ebx (all :funobj) (all :env)) (compiler-values () :code (append code ( make - immediate - move 2 : ecx ) '((:xorl :ecx :ecx) (:movb 2 :cl)) '((:stc))) :returns :multiple-values :type `(values ,(type-specifier-primary (compiler-values-getf first-values :type)) ,(type-specifier-primary (compiler-values-getf second-values :type))) :functional-p functional-p :modifies modifies))) (t (multiple-value-bind (arguments-code stack-displacement arguments-modifies arguments-types arguments-functional-p) (make-compiled-argument-forms sub-forms (all :funobj) (all :env)) (assert (not (minusp (- stack-displacement (- (length sub-forms) 2))))) (multiple-value-bind (stack-restore-code new-returns) (make-compiled-stack-restore (- stack-displacement (- (length sub-forms) 2)) result-mode :multiple-values) (compiler-values () :returns new-returns :type `(values ,@arguments-types) :functional-p arguments-functional-p :modifies arguments-modifies :code (append arguments-code (loop for i from (- (length sub-forms) 3) downto 0 collecting `(:locally (:popl (:edi (:edi-offset values ,(* i 4)))))) (make-immediate-move (* +movitz-fixnum-factor+ (- (length sub-forms) 2)) :ecx) `((:locally (:movl :ecx (:edi (:edi-offset num-values))))) (make-immediate-move (length sub-forms) :ecx) `((:stc)) stack-restore-code))))))))) (define-special-operator muerte::compiler-typecase (&all all &form form) (destructuring-bind (keyform &rest clauses) (cdr form) (compiler-values-bind (&type keyform-type) (compiler-call #'compile-form-unprotected :form keyform :result-mode :eax :forward all) ( declare ( ignore keyform - type ) ) ( warn " keyform type : ~S " keyform - type ) #+ignore (let ((clause (find 'muerte.cl::t clauses :key #'car))) (assert clause) (compiler-call #'compile-implicit-progn :form (cdr clause) :forward all)) (loop for (clause-type . clause-forms) in clauses when (movitz-subtypep (type-specifier-primary keyform-type) clause-type) return (compiler-call #'compile-implicit-progn :form clause-forms :forward all) finally (error "No compiler-typecase clause matched compile-time type ~S." keyform-type))))) (define-special-operator muerte::exact-throw (&all all-throw &form form &env env &funobj funobj) "Perform a dynamic control transfer to catch-env-slot context (evaluated), with values from value-form. Error-form, if provided, is evaluated in case the context is zero (i.e. not found)." (destructuring-bind (context value-form &optional error-form) (cdr form) (let* ((local-env (make-local-movitz-environment env funobj :type 'let-env)) (dynamic-slot-binding (movitz-env-add-binding local-env (make-instance 'located-binding :name (gensym "dynamic-slot-")))) (next-continuation-step-binding (movitz-env-add-binding local-env (make-instance 'located-binding :name (gensym "continuation-step-"))))) (compiler-values () :returns :non-local-exit :code (append (compiler-call #'compile-form :forward all-throw :result-mode dynamic-slot-binding :form context) (compiler-call #'compile-form :forward all-throw :result-mode :multiple-values :form `(muerte.cl:multiple-value-prog1 ,value-form (muerte::with-inline-assembly (:returns :nothing) (:load-lexical ,dynamic-slot-binding :eax) ,@(when error-form `((:testl :eax :eax) (:jz '(:sub-program () (:compile-form (:result-mode :ignore) ,error-form))))) (:locally (:call (:edi (:edi-offset dynamic-unwind-next)))) (:store-lexical ,next-continuation-step-binding :eax :type t) ))) now outside of m - v - prog1 's cloak , with final dynamic - slot in .. * 12 dynamic - env uplink * 8 target jumper number * 4 target catch tag * 0 target EBP `((:load-lexical ,dynamic-slot-binding :edx) (:locally (:call (:edi (:edi-offset dynamic-jump-next)))))))))) (: locally (: : esi (: edi (: edi - offset scratch1 ) ) ) ) (: jmp (: esi : edx , ( slot - offset ' movitz - funobj ' ) ) ) ) ) ) ) ) ) (define-special-operator muerte::with-basic-restart (&all defaults &form form &env env) (destructuring-bind ((name function interactive test format-control &rest format-arguments) &body body) (cdr form) (check-type name symbol "a restart name") (let* ((entry-size (+ 10 (* 2 (length format-arguments))))) (with-labels (basic-restart-catch (label-set exit-point)) (compiler-values () :returns :multiple-values 12 : parent 8 : jumper index (= > eip ) 4 : tag = # : basic - restart - tag (:declare-label-set ,label-set (,exit-point)) ebp (compiler-call #'compile-form :defaults defaults :form function :with-stack-used 5 :result-mode :push) (compiler-call #'compile-form :defaults defaults :form interactive :with-stack-used 6 :result-mode :push) (compiler-call #'compile-form :defaults defaults :form test :with-stack-used 7 :result-mode :push) `((:load-constant ,format-control :push) (:pushl :edi)) (loop for format-argument-cons on format-arguments as stack-use upfrom 11 by 2 append (if (cdr format-argument-cons) '((:leal (:esp -15) :eax) (:pushl :eax)) '((:pushl :edi))) append (compiler-call #'compile-form :defaults defaults :form (car format-argument-cons) :result-mode :push :with-stack-used stack-use :env env)) `((:leal (:esp ,(* 4 (+ 6 (* 2 (length format-arguments))))) :eax) (:locally (:movl :eax (:edi (:edi-offset dynamic-env))))) (when format-arguments `((:leal (:eax -31) :ebx) (:movl :ebx (:eax -24)))) (compiler-call #'compile-implicit-progn :forward defaults :env (make-instance 'simple-dynamic-env :uplink env :funobj (defaults :funobj) :num-specials 1) :result-mode :multiple-values :with-stack-used entry-size :form body) `((:leal (:esp ,(+ -12 -4 (* 4 entry-size))) :esp) ,exit-point (:movl (:esp) :ebp) (:movl (:esp 12) :edx) (:locally (:movl :edx (:edi (:edi-offset dynamic-env)))) (:leal (:esp 16) :esp) ))))))) (define-special-operator muerte::eql%b (&form form &env env &result-mode result-mode) (destructuring-bind (x y) (cdr form) (let ((returns (case (result-mode-type result-mode) ((:boolean-branch-on-true :boolean-branch-on-false) result-mode) (t :boolean-zf=1))) (x (movitz-binding x env)) (y (movitz-binding y env))) (compiler-values () :returns returns :code `((:eql ,x ,y ,returns)))))) (define-special-operator muerte::with-dynamic-extent-scope (&all all &form form &env env &funobj funobj) (destructuring-bind ((scope-tag) &body body) (cdr form) (let* ((save-esp-binding (make-instance 'located-binding :name (gensym "dynamic-extent-save-esp-"))) (base-binding (make-instance 'located-binding :name (gensym "dynamic-extent-base-"))) (scope-env (make-local-movitz-environment env funobj :type 'with-dynamic-extent-scope-env :scope-tag scope-tag :save-esp-binding save-esp-binding :base-binding base-binding))) (movitz-env-add-binding scope-env save-esp-binding) (movitz-env-add-binding scope-env base-binding) (compiler-values-bind (&code body-code &all body-values) (compiler-call #'compile-implicit-progn :env scope-env :form body :forward all) (compiler-values (body-values) :code (append `((:init-lexvar ,save-esp-binding :init-with-register :esp :init-with-type fixnum) (:enter-dynamic-scope ,scope-env) (:init-lexvar ,base-binding :init-with-register :esp :init-with-type fixnum)) body-code `((:load-lexical ,save-esp-binding :esp)))))))) (define-special-operator muerte::with-dynamic-extent-allocation (&all all &form form &env env &funobj funobj) (destructuring-bind ((scope-tag) &body body) (cdr form) (let* ((scope-env (loop for e = env then (movitz-environment-uplink e) unless e do (error "Dynamic-extent scope ~S not seen." scope-tag) when (and (typep e 'with-dynamic-extent-scope-env) (eq scope-tag (dynamic-extent-scope-tag e))) return e)) (allocation-env (make-local-movitz-environment env funobj :type 'with-dynamic-extent-allocation-env :scope scope-env))) (compiler-call #'compile-implicit-progn :form body :forward all :env allocation-env)))) (define-special-operator muerte::compiled-cons (&all all &form form &env env &funobj funobj) (destructuring-bind (car cdr) (cdr form) (let ((dynamic-extent-scope (find-dynamic-extent-scope env))) (cond (dynamic-extent-scope (compiler-values () :returns :eax :functional-p t :type 'cons :code (append (make-compiled-two-forms-into-registers car :eax cdr :ebx funobj env) `((:stack-cons ,(make-instance 'movitz-cons) ,dynamic-extent-scope))))) (t (compiler-values () :returns :eax :functional-p t :type 'cons :code (append (make-compiled-two-forms-into-registers car :eax cdr :ebx funobj env) `((:globally (:call (:edi (:edi-offset fast-cons))))))))))))
5394af00707c509bb061b7c9af9441a86bae0d7207b7c3a4ee721677911aec96
WormBase/wormbase_rest
microarray_results.clj
(ns rest-api.classes.microarray-results (:require [rest-api.classes.microarray-results.widgets.overview :as overview] [rest-api.classes.microarray-results.widgets.experiments :as experiments] [rest-api.classes.graphview.widget :as graphview] [rest-api.routing :as routing])) (routing/defroutes {:entity-ns "microarray-results" :widget {:overview overview/widget :graphview graphview/widget :experiments experiments/widget}})
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/microarray_results.clj
clojure
(ns rest-api.classes.microarray-results (:require [rest-api.classes.microarray-results.widgets.overview :as overview] [rest-api.classes.microarray-results.widgets.experiments :as experiments] [rest-api.classes.graphview.widget :as graphview] [rest-api.routing :as routing])) (routing/defroutes {:entity-ns "microarray-results" :widget {:overview overview/widget :graphview graphview/widget :experiments experiments/widget}})
a2c512ad1422ead5a5bba32931f92f121244e5ac54db131f95f2fef567699a23
avsm/eeww
connection.mli
type t (** The type of a bidirectional data connection between a local endpoint and a remote endpoint *) val create : params:Parameters.t -> Endpoint.t -> t (** [create ~params endpoint] initialises a new connection to a remote endpoint *) val set_queue : queue:Dispatch.Queue.t -> t -> unit (** [set_queue ~queue conn] sets the dispatch queue on which all events are delivered *) val retain : t -> unit (** [retain t] -- connection objects close the underlying network connection when its last reference is release. If you need the connection it must be retained *) val start : t -> unit (** [start conn] starts establishing a connection *) val restart : t -> unit (** [restart conn] restarts a connection that is in the waiting state *) val cancel : t -> unit (** [cancel t] cancels the connection and gracefully disconnects any established network protocols *) val copy_endpoint : t -> Endpoint.t (** [copy_endpoint conn] accesses the endpoint with which the connection was created *) module State : sig type t = | Invalid | Waiting | Preparing | Ready | Failed | Cancelled (** The state indicates whether a connection can be used to send and receive data *) type handler = t -> Error.t -> unit (** A handler is a function which can be set to respond to state changes on a given connection. *) end val set_state_changed_handler : handler:State.handler -> t -> unit (** Set the state changed handler for a given connection. *) module Context : sig type t = Default | Final end type receive_completion = Dispatch.Data.t option -> Context.t -> bool -> Error.t -> unit val receive : min:int -> max:int -> completion:receive_completion -> t -> unit val receive_message : completion:receive_completion -> t -> unit type send_completion = Error.t -> unit val send : ?data:Dispatch.Data.t -> is_complete:bool -> completion:send_completion -> context:Context.t -> t -> unit (** [send ~context ~is_complete ~completion ~data t] sends [data] on the connection [t]. @param data The data being sent on the connection @param context The context associated with content *)
null
https://raw.githubusercontent.com/avsm/eeww/ab64c5391b67fb3f5b1d3de5e0a5a5cb4c80207b/lib/network/lib/connection.mli
ocaml
* The type of a bidirectional data connection between a local endpoint and a remote endpoint * [create ~params endpoint] initialises a new connection to a remote endpoint * [set_queue ~queue conn] sets the dispatch queue on which all events are delivered * [retain t] -- connection objects close the underlying network connection when its last reference is release. If you need the connection it must be retained * [start conn] starts establishing a connection * [restart conn] restarts a connection that is in the waiting state * [cancel t] cancels the connection and gracefully disconnects any established network protocols * [copy_endpoint conn] accesses the endpoint with which the connection was created * The state indicates whether a connection can be used to send and receive data * A handler is a function which can be set to respond to state changes on a given connection. * Set the state changed handler for a given connection. * [send ~context ~is_complete ~completion ~data t] sends [data] on the connection [t]. @param data The data being sent on the connection @param context The context associated with content
type t val create : params:Parameters.t -> Endpoint.t -> t val set_queue : queue:Dispatch.Queue.t -> t -> unit val retain : t -> unit val start : t -> unit val restart : t -> unit val cancel : t -> unit val copy_endpoint : t -> Endpoint.t module State : sig type t = | Invalid | Waiting | Preparing | Ready | Failed | Cancelled type handler = t -> Error.t -> unit end val set_state_changed_handler : handler:State.handler -> t -> unit module Context : sig type t = Default | Final end type receive_completion = Dispatch.Data.t option -> Context.t -> bool -> Error.t -> unit val receive : min:int -> max:int -> completion:receive_completion -> t -> unit val receive_message : completion:receive_completion -> t -> unit type send_completion = Error.t -> unit val send : ?data:Dispatch.Data.t -> is_complete:bool -> completion:send_completion -> context:Context.t -> t -> unit
a8a267c193c994aeb72c7cd038a58d22f1ec760a18edaaaecf0a7341276d88c9
aib/Project-Euler
euler14.hs
import Control.Arrow import Data.List import Data.Ord -- More accurately called a hailstone sequence, but meh... collatzSeq :: Integer -> [Integer] collatzSeq 1 = [1] collatzSeq n = n : collatzSeq nextN where nextN = if (odd n) then 3*n+1 else n `quot` 2 main = print $ maximumBy (comparing snd) $ map (id &&& length . collatzSeq) [1..999999]
null
https://raw.githubusercontent.com/aib/Project-Euler/a01a142d360f3a30fcea69ab29d4d198160ee921/euler14.hs
haskell
More accurately called a hailstone sequence, but meh...
import Control.Arrow import Data.List import Data.Ord collatzSeq :: Integer -> [Integer] collatzSeq 1 = [1] collatzSeq n = n : collatzSeq nextN where nextN = if (odd n) then 3*n+1 else n `quot` 2 main = print $ maximumBy (comparing snd) $ map (id &&& length . collatzSeq) [1..999999]
00e6147fabe2bfb79acb62912fc5e5791c951915e91226d5c5b4a52fc6a1dada
softwarelanguageslab/maf
R5RS_WeiChenRompf2019_the-little-schemer_ch6-5.scm
; Changes: * removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 * swapped branches : 1 ; * calls to id fun: 0 (letrec ((atom? (lambda (x) (if (<change> (not (pair? x)) (not (not (pair? x)))) (not (null? x)) #f))) (numbered? (lambda (aexp) (if (atom? aexp) (number? aexp) (if (numbered? (car aexp)) (<change> (numbered? (car (cdr (cdr aexp)))) #f) (<change> #f (numbered? (car (cdr (cdr aexp))))))))) (^ (lambda (n m) (if (zero? m) 1 (* n (^ n (- m 1)))))) (value (lambda (nexp) (if (atom? nexp) nexp (if (eq? (car (cdr nexp)) '+) (+ (value (car nexp)) (value (car (cdr (cdr nexp))))) (if (eq? (car (cdr nexp)) '*) (* (value (car nexp)) (value (car (cdr (cdr nexp))))) (^ (value (car nexp)) (value (car (cdr (cdr nexp))))))))))) (value (__toplevel_cons (__toplevel_cons 5 (__toplevel_cons '^ (__toplevel_cons 1 ()))) (__toplevel_cons '* (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons '+ (__toplevel_cons 3 ()))) ())))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_WeiChenRompf2019_the-little-schemer_ch6-5.scm
scheme
Changes: * calls to id fun: 0
* removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 * swapped branches : 1 (letrec ((atom? (lambda (x) (if (<change> (not (pair? x)) (not (not (pair? x)))) (not (null? x)) #f))) (numbered? (lambda (aexp) (if (atom? aexp) (number? aexp) (if (numbered? (car aexp)) (<change> (numbered? (car (cdr (cdr aexp)))) #f) (<change> #f (numbered? (car (cdr (cdr aexp))))))))) (^ (lambda (n m) (if (zero? m) 1 (* n (^ n (- m 1)))))) (value (lambda (nexp) (if (atom? nexp) nexp (if (eq? (car (cdr nexp)) '+) (+ (value (car nexp)) (value (car (cdr (cdr nexp))))) (if (eq? (car (cdr nexp)) '*) (* (value (car nexp)) (value (car (cdr (cdr nexp))))) (^ (value (car nexp)) (value (car (cdr (cdr nexp))))))))))) (value (__toplevel_cons (__toplevel_cons 5 (__toplevel_cons '^ (__toplevel_cons 1 ()))) (__toplevel_cons '* (__toplevel_cons (__toplevel_cons 3 (__toplevel_cons '+ (__toplevel_cons 3 ()))) ())))))
32e44c29948a1a52cd4e26fbccb7816fc9f562dbc49f6f7cef83cf6955287211
HunterYIboHu/htdp2-solution
ex364-represent-XML.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex364-represent-XML) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; data difinitions ; An Xexpr.v2 is a list: ; – (cons Symbol XL) An XL is one of : ; – [List-of Xexpr.v2] ; – (cons [List-of Attribute] [List-of Xexpr.v2]) ; An Attribute is a list of two items : ; (cons Symbol (cons String '())) ;; constants (define xml-1 '(transition ((from "seen-e") (to "seen-f")))) ; <transition from="seen-e" to="seen-f" /> (define xml-2 '(ul (li (word) (word)) (li (word)))) ; <ul><li><word /><word /></li><li><word /></li></ul> (define xml-3 '(end)) ; <end></end> ;; Questions Q1 : Which one could be represented in Xexpr.v0 or Xexpr.v1 ? A1 : xml-3 could be represented in Xexpr.v0 or Xexpr.v1 ; could be represented in Xexpr.v1 ; xml-3 could n't .
null
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter4/Section22-the-commerce-of-XML/ex364-represent-XML.rkt
racket
about the language level of this file in a form that our tools can easily process. data difinitions An Xexpr.v2 is a list: – (cons Symbol XL) – [List-of Xexpr.v2] – (cons [List-of Attribute] [List-of Xexpr.v2]) (cons Symbol (cons String '())) constants <transition from="seen-e" to="seen-f" /> <ul><li><word /><word /></li><li><word /></li></ul> <end></end> Questions
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex364-represent-XML) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) An XL is one of : An Attribute is a list of two items : (define xml-1 '(transition ((from "seen-e") (to "seen-f")))) (define xml-2 '(ul (li (word) (word)) (li (word)))) (define xml-3 '(end)) Q1 : Which one could be represented in Xexpr.v0 or Xexpr.v1 ? xml-3 could n't .
bc023f67ceb364c209874e6264d51041ccad748d5303d2f8d951d5dc8854d747
AccelerateHS/accelerate-llvm
Compile.hs
# LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # {-# LANGUAGE TypeFamilies #-} # OPTIONS_GHC -fno - warn - orphans # -- | -- Module : Data.Array.Accelerate.LLVM.PTX.Compile Copyright : [ 2014 .. 2020 ] The Accelerate Team -- License : BSD3 -- Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC extensions ) -- module Data.Array.Accelerate.LLVM.PTX.Compile ( module Data.Array.Accelerate.LLVM.Compile, ObjectR(..), ) where import Data.Array.Accelerate.AST ( PreOpenAcc ) import Data.Array.Accelerate.Error import Data.Array.Accelerate.Trafo.Delayed import Data.Array.Accelerate.LLVM.CodeGen import Data.Array.Accelerate.LLVM.CodeGen.Environment ( Gamma ) import Data.Array.Accelerate.LLVM.CodeGen.Module ( Module(..) ) import Data.Array.Accelerate.LLVM.Compile import Data.Array.Accelerate.LLVM.Extra import Data.Array.Accelerate.LLVM.State import Data.Array.Accelerate.LLVM.PTX.Analysis.Launch import Data.Array.Accelerate.LLVM.PTX.CodeGen import Data.Array.Accelerate.LLVM.PTX.Compile.Cache import Data.Array.Accelerate.LLVM.PTX.Compile.Libdevice import Data.Array.Accelerate.LLVM.PTX.Foreign ( ) import Data.Array.Accelerate.LLVM.PTX.Target import qualified Data.Array.Accelerate.LLVM.PTX.Debug as Debug import Foreign.CUDA.Path import qualified Foreign.CUDA.Analysis as CUDA import qualified Foreign.NVVM as NVVM import qualified LLVM.AST as AST import qualified LLVM.AST.Name as LLVM import qualified LLVM.Context as LLVM import qualified LLVM.Module as LLVM import qualified LLVM.PassManager as LLVM import qualified LLVM.Target as LLVM import qualified LLVM.Internal.Module as LLVM.Internal import qualified LLVM.Internal.FFI.LLVMCTypes as LLVM.Internal.FFI import qualified LLVM.Analysis as LLVM import Control.DeepSeq import Control.Exception import Control.Monad.Except import Control.Monad.State import Data.ByteString ( ByteString ) import Data.ByteString.Short ( ShortByteString ) import Data.Maybe import Data.Text.Encoding import Data.Word import Foreign.ForeignPtr import Foreign.Ptr import Foreign.Storable import Formatting import System.Directory import System.Exit import System.FilePath import System.IO import System.IO.Unsafe import System.Process import System.Process.Extra import Text.Printf ( printf ) import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.HashMap.Strict as HashMap import Prelude as P instance Compile PTX where data ObjectR PTX = ObjectR { objId :: {-# UNPACK #-} !UID , ptxConfig :: ![(ShortByteString, LaunchConfig)] LAZY } compileForTarget = compile -- | Compile an Accelerate expression to object code. -- -- This generates the target code together with a list of each kernel function -- defined in the module paired with its occupancy information. -- compile :: HasCallStack => PreOpenAcc DelayedOpenAcc aenv a -> Gamma aenv -> LLVM PTX (ObjectR PTX) compile pacc aenv = do Generate code for this Acc operation -- dev <- gets ptxDeviceProperties (uid, cacheFile) <- cacheOfPreOpenAcc pacc Module ast md <- llvmOfPreOpenAcc uid pacc aenv let config = [ (f,x) | (LLVM.Name f, KM_PTX x) <- HashMap.toList md ] Lower the generated into a CUBIN object code . -- -- The 'objData' field is lazily evaluated since the object code might have -- already been loaded into the current context from a different function, in -- which case it will be found by the linker cache. -- cubin <- liftIO . unsafeInterleaveIO $ do exists <- doesFileExist cacheFile recomp <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.force_recomp else return False if exists && not recomp then do Debug.traceM Debug.dump_cc ("cc: found cached object code " % shown) uid B.readFile cacheFile else LLVM.withContext $ \ctx -> do ptx <- compilePTX dev ctx ast cubin <- compileCUBIN dev cacheFile ptx return cubin return $! ObjectR uid config cubin | Compile the LLVM module to PTX assembly . This is done either by the -- closed-source libNVVM library, or via the standard NVPTX backend (which is -- the default). -- compilePTX :: CUDA.DeviceProperties -> LLVM.Context -> AST.Module -> IO ByteString compilePTX dev ctx ast = do #ifdef ACCELERATE_USE_NVVM ptx <- withLibdeviceNVVM dev ctx ast (_compileModuleNVVM dev (AST.moduleName ast)) #else ptx <- withLibdeviceNVPTX dev ctx ast (_compileModuleNVPTX dev) #endif Debug.when Debug.dump_asm $ Debug.traceM Debug.verbose stext (decodeUtf8 ptx) return ptx | Compile the given PTX assembly to a CUBIN file ( SASS object code ) . The compiled code will be stored at the given FilePath . -- compileCUBIN :: HasCallStack => CUDA.DeviceProperties -> FilePath -> ByteString -> IO ByteString compileCUBIN dev sass ptx = do _verbose <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.verbose else return False _debug <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.debug else return False -- let verboseFlag = if _verbose then [ "-v" ] else [] debugFlag = if _debug then [ "-g", "-lineinfo" ] else [] arch = printf "-arch=sm_%d%d" m n CUDA.Compute m n = CUDA.computeCapability dev flags = "-" : "-o" : sass : arch : verboseFlag ++ debugFlag -- cp = (proc (cudaBinPath </> "ptxas") flags) { std_in = CreatePipe , std_out = NoStream , std_err = CreatePipe } -- Invoke the 'ptxas' executable to compile the generated PTX into SASS (GPU -- object code). The output is written directly to the final cache location. -- withCreateProcess cp $ \(Just inh) Nothing (Just errh) ph -> do -- fork off a thread to start consuming stderr info <- hGetContents errh withForkWait (evaluate (rnf info)) $ \waitErr -> do -- write the PTX to the input handle closing the handle performs an implicit flush , thus may trigger ignoreSIGPIPE $ B.hPut inh ptx ignoreSIGPIPE $ hClose inh -- wait on the output waitErr hClose errh -- wait on the process ex <- waitForProcess ph case ex of ExitFailure r -> internalError ("ptxas " % unworded string % " (exit " % int % ")\n" % reindented 2 string) flags r info ExitSuccess -> return () when _verbose $ unless (null info) $ Debug.traceM Debug.dump_cc ("ptx: compiled entry function(s)\n" % reindented 2 string) info -- Read back the results B.readFile sass Compile and optimise the module to PTX using the ( closed source ) library . This _ may _ produce faster object code than the LLVM NVPTX compiler . -- _compileModuleNVVM :: HasCallStack => CUDA.DeviceProperties -> ShortByteString -> [(ShortByteString, ByteString)] -> LLVM.Module -> IO ByteString _compileModuleNVVM dev name libdevice mdl = do _debug <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.debug else return False -- let arch = CUDA.computeCapability dev verbose = if _debug then [ NVVM.GenerateDebugInfo ] else [] flags = NVVM.Target arch : verbose Note : [ and target datalayout ] -- The library does not correctly parse the target datalayout field , instead doing a ( very dodgy ) string compare against exactly two -- expected values. This means that it is sensitive to, e.g. the ordering of the fields , and changes to the representation in each LLVM release . -- -- We get around this by only specifying the data layout in a separate -- (otherwise empty) module that we additionally link against. -- header = case bitSize (undefined::Int) of 32 -> "target triple = \"nvptx-nvidia-cuda\"\ntarget datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\"" 64 -> "target triple = \"nvptx64-nvidia-cuda\"\ntarget datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\"" _ -> internalError "I don't know what architecture I am" Debug.when Debug.dump_cc $ do Debug.when Debug.verbose $ do TLM : unfortunate to do the lowering twice in debug mode Debug.traceM Debug.verbose stext (decodeUtf8 ll) -- Lower the generated module to bitcode, then compile and link together with the shim header and libdevice library ( if necessary ) bc <- LLVM.moduleBitcode mdl ptx <- NVVM.compileModules (("",header) : (name,bc) : libdevice) flags unless (B.null (NVVM.compileLog ptx)) $ do Debug.traceM Debug.dump_cc ("llvm: " % stext) (decodeUtf8 (NVVM.compileLog ptx)) -- Return the generated binary code return (NVVM.compileResult ptx) -- Compiling with the NVPTX backend uses LLVM-3.3 and above -- _compileModuleNVPTX :: CUDA.DeviceProperties -> LLVM.Module -> IO ByteString _compileModuleNVPTX dev mdl = withPTXTargetMachine dev $ \nvptx -> do when Debug.internalChecksAreEnabled $ LLVM.verify mdl -- Run the standard optimisation pass -- let pss = LLVM.defaultCuratedPassSetSpec { LLVM.optLevel = Just 3 } LLVM.withPassManager pss $ \pm -> do b1 <- LLVM.runPassManager pm mdl -- debug printout Debug.when Debug.dump_cc $ do Debug.traceM Debug.dump_cc ("llvm: optimisation did work? " % shown) b1 Debug.traceM Debug.verbose stext . decodeUtf8 =<< LLVM.moduleLLVMAssembly mdl Lower the LLVM module into target assembly ( PTX ) moduleTargetAssembly nvptx mdl -- | Produce target specific assembly as a 'ByteString'. -- moduleTargetAssembly :: LLVM.TargetMachine -> LLVM.Module -> IO ByteString moduleTargetAssembly tm m = unsafe0 =<< LLVM.Internal.emitToByteString LLVM.Internal.FFI.codeGenFileTypeAssembly tm m where Ensure that the ByteString is NULL - terminated , so that it can be passed directly to C. This will unsafely mutate the underlying ForeignPtr if the -- string is not NULL-terminated but the last character is a whitespace -- character (there are usually a few blank lines at the end). -- unsafe0 :: ByteString -> IO ByteString unsafe0 bs@(B.PS fp s l) = liftIO . withForeignPtr fp $ \p -> do let p' :: Ptr Word8 p' = p `plusPtr` (s+l-1) -- x <- peek p' case x of 0 -> return bs _ | B.isSpaceWord8 x -> poke p' 0 >> return bs _ -> return (B.snoc bs 0)
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-llvm/1da65b5951b1410b5e4e1a646fbe1b17bee780a8/accelerate-llvm-ptx/src/Data/Array/Accelerate/LLVM/PTX/Compile.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # | Module : Data.Array.Accelerate.LLVM.PTX.Compile License : BSD3 Stability : experimental # UNPACK # | Compile an Accelerate expression to object code. This generates the target code together with a list of each kernel function defined in the module paired with its occupancy information. The 'objData' field is lazily evaluated since the object code might have already been loaded into the current context from a different function, in which case it will be found by the linker cache. closed-source libNVVM library, or via the standard NVPTX backend (which is the default). Invoke the 'ptxas' executable to compile the generated PTX into SASS (GPU object code). The output is written directly to the final cache location. fork off a thread to start consuming stderr write the PTX to the input handle wait on the output wait on the process Read back the results expected values. This means that it is sensitive to, e.g. the ordering We get around this by only specifying the data layout in a separate (otherwise empty) module that we additionally link against. Lower the generated module to bitcode, then compile and link together with Return the generated binary code Compiling with the NVPTX backend uses LLVM-3.3 and above Run the standard optimisation pass debug printout | Produce target specific assembly as a 'ByteString'. string is not NULL-terminated but the last character is a whitespace character (there are usually a few blank lines at the end).
# LANGUAGE CPP # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -fno - warn - orphans # Copyright : [ 2014 .. 2020 ] The Accelerate Team Maintainer : < > Portability : non - portable ( GHC extensions ) module Data.Array.Accelerate.LLVM.PTX.Compile ( module Data.Array.Accelerate.LLVM.Compile, ObjectR(..), ) where import Data.Array.Accelerate.AST ( PreOpenAcc ) import Data.Array.Accelerate.Error import Data.Array.Accelerate.Trafo.Delayed import Data.Array.Accelerate.LLVM.CodeGen import Data.Array.Accelerate.LLVM.CodeGen.Environment ( Gamma ) import Data.Array.Accelerate.LLVM.CodeGen.Module ( Module(..) ) import Data.Array.Accelerate.LLVM.Compile import Data.Array.Accelerate.LLVM.Extra import Data.Array.Accelerate.LLVM.State import Data.Array.Accelerate.LLVM.PTX.Analysis.Launch import Data.Array.Accelerate.LLVM.PTX.CodeGen import Data.Array.Accelerate.LLVM.PTX.Compile.Cache import Data.Array.Accelerate.LLVM.PTX.Compile.Libdevice import Data.Array.Accelerate.LLVM.PTX.Foreign ( ) import Data.Array.Accelerate.LLVM.PTX.Target import qualified Data.Array.Accelerate.LLVM.PTX.Debug as Debug import Foreign.CUDA.Path import qualified Foreign.CUDA.Analysis as CUDA import qualified Foreign.NVVM as NVVM import qualified LLVM.AST as AST import qualified LLVM.AST.Name as LLVM import qualified LLVM.Context as LLVM import qualified LLVM.Module as LLVM import qualified LLVM.PassManager as LLVM import qualified LLVM.Target as LLVM import qualified LLVM.Internal.Module as LLVM.Internal import qualified LLVM.Internal.FFI.LLVMCTypes as LLVM.Internal.FFI import qualified LLVM.Analysis as LLVM import Control.DeepSeq import Control.Exception import Control.Monad.Except import Control.Monad.State import Data.ByteString ( ByteString ) import Data.ByteString.Short ( ShortByteString ) import Data.Maybe import Data.Text.Encoding import Data.Word import Foreign.ForeignPtr import Foreign.Ptr import Foreign.Storable import Formatting import System.Directory import System.Exit import System.FilePath import System.IO import System.IO.Unsafe import System.Process import System.Process.Extra import Text.Printf ( printf ) import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.HashMap.Strict as HashMap import Prelude as P instance Compile PTX where , ptxConfig :: ![(ShortByteString, LaunchConfig)] LAZY } compileForTarget = compile compile :: HasCallStack => PreOpenAcc DelayedOpenAcc aenv a -> Gamma aenv -> LLVM PTX (ObjectR PTX) compile pacc aenv = do Generate code for this Acc operation dev <- gets ptxDeviceProperties (uid, cacheFile) <- cacheOfPreOpenAcc pacc Module ast md <- llvmOfPreOpenAcc uid pacc aenv let config = [ (f,x) | (LLVM.Name f, KM_PTX x) <- HashMap.toList md ] Lower the generated into a CUBIN object code . cubin <- liftIO . unsafeInterleaveIO $ do exists <- doesFileExist cacheFile recomp <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.force_recomp else return False if exists && not recomp then do Debug.traceM Debug.dump_cc ("cc: found cached object code " % shown) uid B.readFile cacheFile else LLVM.withContext $ \ctx -> do ptx <- compilePTX dev ctx ast cubin <- compileCUBIN dev cacheFile ptx return cubin return $! ObjectR uid config cubin | Compile the LLVM module to PTX assembly . This is done either by the compilePTX :: CUDA.DeviceProperties -> LLVM.Context -> AST.Module -> IO ByteString compilePTX dev ctx ast = do #ifdef ACCELERATE_USE_NVVM ptx <- withLibdeviceNVVM dev ctx ast (_compileModuleNVVM dev (AST.moduleName ast)) #else ptx <- withLibdeviceNVPTX dev ctx ast (_compileModuleNVPTX dev) #endif Debug.when Debug.dump_asm $ Debug.traceM Debug.verbose stext (decodeUtf8 ptx) return ptx | Compile the given PTX assembly to a CUBIN file ( SASS object code ) . The compiled code will be stored at the given FilePath . compileCUBIN :: HasCallStack => CUDA.DeviceProperties -> FilePath -> ByteString -> IO ByteString compileCUBIN dev sass ptx = do _verbose <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.verbose else return False _debug <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.debug else return False let verboseFlag = if _verbose then [ "-v" ] else [] debugFlag = if _debug then [ "-g", "-lineinfo" ] else [] arch = printf "-arch=sm_%d%d" m n CUDA.Compute m n = CUDA.computeCapability dev flags = "-" : "-o" : sass : arch : verboseFlag ++ debugFlag cp = (proc (cudaBinPath </> "ptxas") flags) { std_in = CreatePipe , std_out = NoStream , std_err = CreatePipe } withCreateProcess cp $ \(Just inh) Nothing (Just errh) ph -> do info <- hGetContents errh withForkWait (evaluate (rnf info)) $ \waitErr -> do closing the handle performs an implicit flush , thus may trigger ignoreSIGPIPE $ B.hPut inh ptx ignoreSIGPIPE $ hClose inh waitErr hClose errh ex <- waitForProcess ph case ex of ExitFailure r -> internalError ("ptxas " % unworded string % " (exit " % int % ")\n" % reindented 2 string) flags r info ExitSuccess -> return () when _verbose $ unless (null info) $ Debug.traceM Debug.dump_cc ("ptx: compiled entry function(s)\n" % reindented 2 string) info B.readFile sass Compile and optimise the module to PTX using the ( closed source ) library . This _ may _ produce faster object code than the LLVM NVPTX compiler . _compileModuleNVVM :: HasCallStack => CUDA.DeviceProperties -> ShortByteString -> [(ShortByteString, ByteString)] -> LLVM.Module -> IO ByteString _compileModuleNVVM dev name libdevice mdl = do _debug <- if Debug.debuggingIsEnabled then Debug.getFlag Debug.debug else return False let arch = CUDA.computeCapability dev verbose = if _debug then [ NVVM.GenerateDebugInfo ] else [] flags = NVVM.Target arch : verbose Note : [ and target datalayout ] The library does not correctly parse the target datalayout field , instead doing a ( very dodgy ) string compare against exactly two of the fields , and changes to the representation in each LLVM release . header = case bitSize (undefined::Int) of 32 -> "target triple = \"nvptx-nvidia-cuda\"\ntarget datalayout = \"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\"" 64 -> "target triple = \"nvptx64-nvidia-cuda\"\ntarget datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\"" _ -> internalError "I don't know what architecture I am" Debug.when Debug.dump_cc $ do Debug.when Debug.verbose $ do TLM : unfortunate to do the lowering twice in debug mode Debug.traceM Debug.verbose stext (decodeUtf8 ll) the shim header and libdevice library ( if necessary ) bc <- LLVM.moduleBitcode mdl ptx <- NVVM.compileModules (("",header) : (name,bc) : libdevice) flags unless (B.null (NVVM.compileLog ptx)) $ do Debug.traceM Debug.dump_cc ("llvm: " % stext) (decodeUtf8 (NVVM.compileLog ptx)) return (NVVM.compileResult ptx) _compileModuleNVPTX :: CUDA.DeviceProperties -> LLVM.Module -> IO ByteString _compileModuleNVPTX dev mdl = withPTXTargetMachine dev $ \nvptx -> do when Debug.internalChecksAreEnabled $ LLVM.verify mdl let pss = LLVM.defaultCuratedPassSetSpec { LLVM.optLevel = Just 3 } LLVM.withPassManager pss $ \pm -> do b1 <- LLVM.runPassManager pm mdl Debug.when Debug.dump_cc $ do Debug.traceM Debug.dump_cc ("llvm: optimisation did work? " % shown) b1 Debug.traceM Debug.verbose stext . decodeUtf8 =<< LLVM.moduleLLVMAssembly mdl Lower the LLVM module into target assembly ( PTX ) moduleTargetAssembly nvptx mdl moduleTargetAssembly :: LLVM.TargetMachine -> LLVM.Module -> IO ByteString moduleTargetAssembly tm m = unsafe0 =<< LLVM.Internal.emitToByteString LLVM.Internal.FFI.codeGenFileTypeAssembly tm m where Ensure that the ByteString is NULL - terminated , so that it can be passed directly to C. This will unsafely mutate the underlying ForeignPtr if the unsafe0 :: ByteString -> IO ByteString unsafe0 bs@(B.PS fp s l) = liftIO . withForeignPtr fp $ \p -> do let p' :: Ptr Word8 p' = p `plusPtr` (s+l-1) x <- peek p' case x of 0 -> return bs _ | B.isSpaceWord8 x -> poke p' 0 >> return bs _ -> return (B.snoc bs 0)
c11b8e65a50ac006de8ceb7b637fded99944b150a6737c65dbb324752c131226
ivanjovanovic/sicp
e-3.38.scm
Exercise 3.38 . Suppose that , , and share a joint bank account that initially contains $ 100 . Concurrently , deposits $ 10 , withdraws $ 20 , and withdraws half the money in the ; account, by executing the following commands: : ( set ! balance ( + balance 10 ) ) : ( set ! balance ( - balance 20 ) ) : ( set ! balance ( - balance ( / balance 2 ) ) ) ; a. List all the different possible values for balance after these three transactions have been completed , assuming that the banking system forces the three processes to run sequentially in some order . ; b. What are some other values that could be produced if the system ; allows the processes to be interleaved? Draw timing diagrams like the one in figure 3.29 to explain how these values can occur . ; ------------------------------------------------------------ ; a) These events can occur in any order, so we have number of permutations of the set to evaluate . Lets say we have three events Pe , Pa and . All permutations in which they can appear are ; balance = 100 initially ; Pe = +10 ; Pa = -20 ; Ma = /2 ; ( Pe , Pa , ) = > ( ( 100 + 10 ) - 20 ) / 2 = 45 ( Pe , , Pa ) = > ( ( 100 + 10 ) / 2 ) - 20 = 35 ( Pa , , ) = > ( ( 100 - 20 ) + 10 ) / 2 = 45 ( Pa , , Pe ) = > ( ( 100 - 20 ) / 2 ) + 10 = 50 ( Ma , Pa , Pe ) = > 100/2 -20 + 10 = 40 ( Ma , , Pa ) = > 100/2 + 10 - 20 = 40 ; b ) Here we have complex situation of three process which all have ; (set!) procedure application that executes in several steps, with all ; the permutatations we an draw some diagrams easily.
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.4/e-3.38.scm
scheme
account, by executing the following commands: a. List all the different possible values for balance after these b. What are some other values that could be produced if the system allows the processes to be interleaved? Draw timing diagrams like the ------------------------------------------------------------ a) These events can occur in any order, so we have number of Pe = +10 Pa = -20 Ma = /2 (set!) procedure application that executes in several steps, with all the permutatations we an draw some diagrams easily.
Exercise 3.38 . Suppose that , , and share a joint bank account that initially contains $ 100 . Concurrently , deposits $ 10 , withdraws $ 20 , and withdraws half the money in the : ( set ! balance ( + balance 10 ) ) : ( set ! balance ( - balance 20 ) ) : ( set ! balance ( - balance ( / balance 2 ) ) ) three transactions have been completed , assuming that the banking system forces the three processes to run sequentially in some order . one in figure 3.29 to explain how these values can occur . permutations of the set to evaluate . Lets say we have three events Pe , Pa and . All permutations in which they can appear are balance = 100 initially ( Pe , Pa , ) = > ( ( 100 + 10 ) - 20 ) / 2 = 45 ( Pe , , Pa ) = > ( ( 100 + 10 ) / 2 ) - 20 = 35 ( Pa , , ) = > ( ( 100 - 20 ) + 10 ) / 2 = 45 ( Pa , , Pe ) = > ( ( 100 - 20 ) / 2 ) + 10 = 50 ( Ma , Pa , Pe ) = > 100/2 -20 + 10 = 40 ( Ma , , Pa ) = > 100/2 + 10 - 20 = 40 b ) Here we have complex situation of three process which all have
faca50908c9b02c2fe429d796ebe0232ceb673217388af24270c5ea38c052e37
huangjs/cl
dgamlm.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':simple-array) ;;; (:array-slicing nil) (:declare-common nil) ;;; (:float-format double-float)) (in-package :slatec) (defun dgamlm (xmin xmax) (declare (type (double-float) xmax xmin)) (prog ((alnbig 0.0) (alnsml 0.0) (xln 0.0) (xold 0.0) (i 0)) (declare (type (integer) i) (type (double-float) xold xln alnsml alnbig)) (setf alnsml (f2cl-lib:flog (f2cl-lib:d1mach 1))) (setf xmin (- alnsml)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 10) nil) (tagbody (setf xold xmin) (setf xln (f2cl-lib:flog xmin)) (setf xmin (+ xmin (/ (* (- xmin) (+ (- (* (+ xmin 0.5) xln) xmin 0.2258) alnsml)) (+ (* xmin xln) 0.5)))) (if (< (abs (- xmin xold)) 0.005) (go label20)) label10)) (xermsg "SLATEC" "DGAMLM" "UNABLE TO FIND XMIN" 1 2) label20 (setf xmin (- 0.01 xmin)) (setf alnbig (f2cl-lib:flog (f2cl-lib:d1mach 2))) (setf xmax alnbig) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 10) nil) (tagbody (setf xold xmax) (setf xln (f2cl-lib:flog xmax)) (setf xmax (+ xmax (/ (* (- xmax) (- (+ (- (* (- xmax 0.5) xln) xmax) 0.9189) alnbig)) (- (* xmax xln) 0.5)))) (if (< (abs (- xmax xold)) 0.005) (go label40)) label30)) (xermsg "SLATEC" "DGAMLM" "UNABLE TO FIND XMAX" 2 2) label40 (setf xmax (- xmax 0.01)) (setf xmin (max xmin (- 1.0 xmax))) (go end_label) end_label (return (values xmin xmax)))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dgamlm fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float)) :return-values '(fortran-to-lisp::xmin fortran-to-lisp::xmax) :calls '(fortran-to-lisp::xermsg fortran-to-lisp::d1mach))))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/numerical/slatec/dgamlm.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':simple-array) (:array-slicing nil) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) (in-package :slatec) (defun dgamlm (xmin xmax) (declare (type (double-float) xmax xmin)) (prog ((alnbig 0.0) (alnsml 0.0) (xln 0.0) (xold 0.0) (i 0)) (declare (type (integer) i) (type (double-float) xold xln alnsml alnbig)) (setf alnsml (f2cl-lib:flog (f2cl-lib:d1mach 1))) (setf xmin (- alnsml)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 10) nil) (tagbody (setf xold xmin) (setf xln (f2cl-lib:flog xmin)) (setf xmin (+ xmin (/ (* (- xmin) (+ (- (* (+ xmin 0.5) xln) xmin 0.2258) alnsml)) (+ (* xmin xln) 0.5)))) (if (< (abs (- xmin xold)) 0.005) (go label20)) label10)) (xermsg "SLATEC" "DGAMLM" "UNABLE TO FIND XMIN" 1 2) label20 (setf xmin (- 0.01 xmin)) (setf alnbig (f2cl-lib:flog (f2cl-lib:d1mach 2))) (setf xmax alnbig) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 10) nil) (tagbody (setf xold xmax) (setf xln (f2cl-lib:flog xmax)) (setf xmax (+ xmax (/ (* (- xmax) (- (+ (- (* (- xmax 0.5) xln) xmax) 0.9189) alnbig)) (- (* xmax xln) 0.5)))) (if (< (abs (- xmax xold)) 0.005) (go label40)) label30)) (xermsg "SLATEC" "DGAMLM" "UNABLE TO FIND XMAX" 2 2) label40 (setf xmax (- xmax 0.01)) (setf xmin (max xmin (- 1.0 xmax))) (go end_label) end_label (return (values xmin xmax)))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dgamlm fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float)) :return-values '(fortran-to-lisp::xmin fortran-to-lisp::xmax) :calls '(fortran-to-lisp::xermsg fortran-to-lisp::d1mach))))
2c058412d2a7b159d3bcb86dc4a77aa4ec8bc9f8072575384f2d12f5037dbe7d
mmottl/gpr
cov_lin_ard.ml
File : cov_lin_ard.ml ( C ) 2009- email : WWW : This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA OCaml-GPR - Gaussian Processes for OCaml Copyright (C) 2009- Markus Mottl email: WWW: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) open Core open Lacaml.D module Params = struct type t = { log_ells : vec } end module Eval = struct module Kernel = struct type params = Params.t type t = { params : params; consts : vec } let create params = let log_ells = params.Params.log_ells in let d = Vec.dim log_ells in let consts = Vec.create d in for i = 1 to d do consts.{i} <- exp (-. log_ells.{i}) done; { params; consts } let get_params k = k.params end module Inducing = struct type t = mat let get_n_points = Mat.dim2 let calc_upper _k inducing = syrk ~trans:`T inducing end module Input = struct type t = vec let calc_ard_input { Kernel.consts } input = let d = Vec.dim input in let ard_input = Vec.create d in for i = 1 to d do ard_input.{i} <- consts.{i} *. input.{i} done; ard_input let eval k input inducing = gemv ~trans:`T inducing (calc_ard_input k input) let weighted_eval k input inducing ~coeffs = dot coeffs (eval k input inducing) let eval_one { Kernel.consts } input = let rec loop res i = if i = 0 then res else let x = consts.{i} *. input.{i} in loop (res +. x *. x) (i - 1) in loop 0. (Vec.dim input) end module Inputs = struct type t = mat let create = Mat.of_col_vecs let get_n_points = Mat.dim2 let choose_subset inputs indexes = Utils.choose_cols inputs indexes let calc_ard_inputs { Kernel.consts } inputs = let res = lacpy inputs in Mat.scal_rows consts res; res let create_inducing = calc_ard_inputs let create_default_kernel_params inputs ~n_inducing:_ = { Params.log_ells = Vec.make (Mat.dim1 inputs) 0. } let calc_upper k inputs = syrk ~trans:`T (calc_ard_inputs k inputs) let calc_diag k inputs = Mat.syrk_diag ~trans:`T (calc_ard_inputs k inputs) let calc_cross k ~inputs ~inducing = gemm ~transa:`T (calc_ard_inputs k inputs) inducing let weighted_eval k ~inputs ~inducing ~coeffs = gemv (calc_cross k ~inputs ~inducing) coeffs end end module Deriv = struct module Eval = Eval module Hyper = struct type t = [ `Log_ell of int ] let get_all { Eval.Kernel.params } _inducing _inputs = Array.init (Vec.dim params.Params.log_ells) ~f:(fun d -> `Log_ell (d + 1)) let get_value { Eval.Kernel.params } _inducing _inputs = function | `Log_ell i -> params.Params.log_ells.{i} let set_values k inducing inputs hypers values = let { Eval.Kernel.params } = k in let log_ells_lazy = lazy (copy params.Params.log_ells) in for i = 1 to Array.length hypers do match hypers.(i - 1) with | `Log_ell d -> (Lazy.force log_ells_lazy).{d} <- values.{i} done; let new_kernel = if Lazy.is_val log_ells_lazy then Eval.Kernel.create { Params.log_ells = Lazy.force log_ells_lazy } else k in new_kernel, inducing, inputs end module Inducing = struct type upper = Eval.Inducing.t let calc_shared_upper k eval_inducing = let upper = Eval.Inducing.calc_upper k eval_inducing in upper, eval_inducing let calc_deriv_upper _inducing = function | `Log_ell _ -> `Const 0. end module Inputs = struct type diag = Eval.Kernel.t * Eval.Inputs.t type cross = Eval.Kernel.t * Eval.Inputs.t* Eval.Inducing.t let calc_shared_diag k eval_inputs = Eval.Inputs.calc_diag k eval_inputs, (k, eval_inputs) let calc_shared_cross k ~inputs ~inducing = ( Eval.Inputs.calc_cross k ~inputs ~inducing, (k, inputs, inducing) ) let calc_deriv_diag (k, inputs) (`Log_ell d) = let n = Mat.dim2 inputs in let res = Vec.create n in let const = -2. *. k.Eval.Kernel.consts.{d} in for i = 1 to n do let el = inputs.{d, i} in res.{i} <- (const *. el) *. el done; `Vec res let calc_deriv_cross (k, inputs, inducing) (`Log_ell d) = let m = Mat.dim2 inducing in let n = Mat.dim2 inputs in let res = Mat.create n m in let const = -. k.Eval.Kernel.consts.{d} in for c = 1 to m do for r = 1 to n do res.{r, c} <- const *. inducing.{d, c} *. inputs.{d, r} done done; `Dense res end end
null
https://raw.githubusercontent.com/mmottl/gpr/64c4dce01b1779feff85d36d5902afa3b143bdae/src/cov_lin_ard.ml
ocaml
File : cov_lin_ard.ml ( C ) 2009- email : WWW : This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA OCaml-GPR - Gaussian Processes for OCaml Copyright (C) 2009- Markus Mottl email: WWW: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) open Core open Lacaml.D module Params = struct type t = { log_ells : vec } end module Eval = struct module Kernel = struct type params = Params.t type t = { params : params; consts : vec } let create params = let log_ells = params.Params.log_ells in let d = Vec.dim log_ells in let consts = Vec.create d in for i = 1 to d do consts.{i} <- exp (-. log_ells.{i}) done; { params; consts } let get_params k = k.params end module Inducing = struct type t = mat let get_n_points = Mat.dim2 let calc_upper _k inducing = syrk ~trans:`T inducing end module Input = struct type t = vec let calc_ard_input { Kernel.consts } input = let d = Vec.dim input in let ard_input = Vec.create d in for i = 1 to d do ard_input.{i} <- consts.{i} *. input.{i} done; ard_input let eval k input inducing = gemv ~trans:`T inducing (calc_ard_input k input) let weighted_eval k input inducing ~coeffs = dot coeffs (eval k input inducing) let eval_one { Kernel.consts } input = let rec loop res i = if i = 0 then res else let x = consts.{i} *. input.{i} in loop (res +. x *. x) (i - 1) in loop 0. (Vec.dim input) end module Inputs = struct type t = mat let create = Mat.of_col_vecs let get_n_points = Mat.dim2 let choose_subset inputs indexes = Utils.choose_cols inputs indexes let calc_ard_inputs { Kernel.consts } inputs = let res = lacpy inputs in Mat.scal_rows consts res; res let create_inducing = calc_ard_inputs let create_default_kernel_params inputs ~n_inducing:_ = { Params.log_ells = Vec.make (Mat.dim1 inputs) 0. } let calc_upper k inputs = syrk ~trans:`T (calc_ard_inputs k inputs) let calc_diag k inputs = Mat.syrk_diag ~trans:`T (calc_ard_inputs k inputs) let calc_cross k ~inputs ~inducing = gemm ~transa:`T (calc_ard_inputs k inputs) inducing let weighted_eval k ~inputs ~inducing ~coeffs = gemv (calc_cross k ~inputs ~inducing) coeffs end end module Deriv = struct module Eval = Eval module Hyper = struct type t = [ `Log_ell of int ] let get_all { Eval.Kernel.params } _inducing _inputs = Array.init (Vec.dim params.Params.log_ells) ~f:(fun d -> `Log_ell (d + 1)) let get_value { Eval.Kernel.params } _inducing _inputs = function | `Log_ell i -> params.Params.log_ells.{i} let set_values k inducing inputs hypers values = let { Eval.Kernel.params } = k in let log_ells_lazy = lazy (copy params.Params.log_ells) in for i = 1 to Array.length hypers do match hypers.(i - 1) with | `Log_ell d -> (Lazy.force log_ells_lazy).{d} <- values.{i} done; let new_kernel = if Lazy.is_val log_ells_lazy then Eval.Kernel.create { Params.log_ells = Lazy.force log_ells_lazy } else k in new_kernel, inducing, inputs end module Inducing = struct type upper = Eval.Inducing.t let calc_shared_upper k eval_inducing = let upper = Eval.Inducing.calc_upper k eval_inducing in upper, eval_inducing let calc_deriv_upper _inducing = function | `Log_ell _ -> `Const 0. end module Inputs = struct type diag = Eval.Kernel.t * Eval.Inputs.t type cross = Eval.Kernel.t * Eval.Inputs.t* Eval.Inducing.t let calc_shared_diag k eval_inputs = Eval.Inputs.calc_diag k eval_inputs, (k, eval_inputs) let calc_shared_cross k ~inputs ~inducing = ( Eval.Inputs.calc_cross k ~inputs ~inducing, (k, inputs, inducing) ) let calc_deriv_diag (k, inputs) (`Log_ell d) = let n = Mat.dim2 inputs in let res = Vec.create n in let const = -2. *. k.Eval.Kernel.consts.{d} in for i = 1 to n do let el = inputs.{d, i} in res.{i} <- (const *. el) *. el done; `Vec res let calc_deriv_cross (k, inputs, inducing) (`Log_ell d) = let m = Mat.dim2 inducing in let n = Mat.dim2 inputs in let res = Mat.create n m in let const = -. k.Eval.Kernel.consts.{d} in for c = 1 to m do for r = 1 to n do res.{r, c} <- const *. inducing.{d, c} *. inputs.{d, r} done done; `Dense res end end
f097598fb865d4dcba30e96088ffa61f5e3212f7acd1774ae055bdcbc61ec07f
ocaml-multicore/tezos
fees_storage.mli
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > (* *) (* 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. *) (* *) (*****************************************************************************) type error += Cannot_pay_storage_fee (* `Temporary *) type error += Operation_quota_exceeded (* `Temporary *) type error += Storage_limit_too_high (* `Permanent *) * [ record_global_constant_storage_space size ] records paid storage space for registering a new global constant . Cost is < size > in bytes + 65 additional bytes for the key hash of the expression . Returns new context and the cost . paid storage space for registering a new global constant. Cost is <size> in bytes + 65 additional bytes for the key hash of the expression. Returns new context and the cost. *) val record_global_constant_storage_space : Raw_context.t -> Z.t -> Raw_context.t * Z.t * [ record_paid_storage_space contract ] updates the amount of storage consumed by the [ contract ] and considered as accounted for as far as future payment is concerned . Returns a new context , the total space consumed by the [ contract ] , and the additional ( and unpaid ) space consumed since the last call of this function on this [ contract ] . consumed by the [contract] and considered as accounted for as far as future payment is concerned. Returns a new context, the total space consumed by the [contract], and the additional (and unpaid) space consumed since the last call of this function on this [contract]. *) val record_paid_storage_space : Raw_context.t -> Contract_repr.t -> (Raw_context.t * Z.t * Z.t) tzresult Lwt.t * [ ~storage_limit ] raises the [ Storage_limit_too_high ] error iff [ storage_limit ] is negative or greater the constant [ hard_storage_limit_per_operation ] . error iff [storage_limit] is negative or greater the constant [hard_storage_limit_per_operation]. *) val check_storage_limit : Raw_context.t -> storage_limit:Z.t -> unit tzresult (** [burn_storage_fees ctxt ~storage_limit ~payer consumed] takes funds from the [payer] to pay the cost of the [consumed] storage. This function has an optional parameter [~origin] that allows to set the origin of returned balance updates (by default the parameter is set to [Block_application]). Returns an updated context, an updated storage limit equal to [storage_limit - consumed], and the relevant balance updates. Raises the [Operation_quota_exceeded] error if [storage_limit < consumed]. Raises the [Cannot_pay_storage_fee] error if the funds from the [payer] are not sufficient to pay the storage fees. *) val burn_storage_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> Z.t -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t (** Calls [burn_storage_fees] with the parameter [consumed] mapped to the constant [origination_size]. *) val burn_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t * Calls [ burn_storage_fees ] with the parameter [ consumed ] mapped to the constant [ ] . constant [tx_rollup_origination_size]. *) val burn_tx_rollup_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t * [ burn_sc_rollup_origination_fees ~origin ctxt ~storage_limit ~payer consumed ] burns the storage fees for smart contract rollup creation fees . burns the storage fees for smart contract rollup creation fees. *) val burn_sc_rollup_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> Z.t -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/fees_storage.mli
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. *************************************************************************** `Temporary `Temporary `Permanent * [burn_storage_fees ctxt ~storage_limit ~payer consumed] takes funds from the [payer] to pay the cost of the [consumed] storage. This function has an optional parameter [~origin] that allows to set the origin of returned balance updates (by default the parameter is set to [Block_application]). Returns an updated context, an updated storage limit equal to [storage_limit - consumed], and the relevant balance updates. Raises the [Operation_quota_exceeded] error if [storage_limit < consumed]. Raises the [Cannot_pay_storage_fee] error if the funds from the [payer] are not sufficient to pay the storage fees. * Calls [burn_storage_fees] with the parameter [consumed] mapped to the constant [origination_size].
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > 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 * [ record_global_constant_storage_space size ] records paid storage space for registering a new global constant . Cost is < size > in bytes + 65 additional bytes for the key hash of the expression . Returns new context and the cost . paid storage space for registering a new global constant. Cost is <size> in bytes + 65 additional bytes for the key hash of the expression. Returns new context and the cost. *) val record_global_constant_storage_space : Raw_context.t -> Z.t -> Raw_context.t * Z.t * [ record_paid_storage_space contract ] updates the amount of storage consumed by the [ contract ] and considered as accounted for as far as future payment is concerned . Returns a new context , the total space consumed by the [ contract ] , and the additional ( and unpaid ) space consumed since the last call of this function on this [ contract ] . consumed by the [contract] and considered as accounted for as far as future payment is concerned. Returns a new context, the total space consumed by the [contract], and the additional (and unpaid) space consumed since the last call of this function on this [contract]. *) val record_paid_storage_space : Raw_context.t -> Contract_repr.t -> (Raw_context.t * Z.t * Z.t) tzresult Lwt.t * [ ~storage_limit ] raises the [ Storage_limit_too_high ] error iff [ storage_limit ] is negative or greater the constant [ hard_storage_limit_per_operation ] . error iff [storage_limit] is negative or greater the constant [hard_storage_limit_per_operation]. *) val check_storage_limit : Raw_context.t -> storage_limit:Z.t -> unit tzresult val burn_storage_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> Z.t -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t val burn_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t * Calls [ burn_storage_fees ] with the parameter [ consumed ] mapped to the constant [ ] . constant [tx_rollup_origination_size]. *) val burn_tx_rollup_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t * [ burn_sc_rollup_origination_fees ~origin ctxt ~storage_limit ~payer consumed ] burns the storage fees for smart contract rollup creation fees . burns the storage fees for smart contract rollup creation fees. *) val burn_sc_rollup_origination_fees : ?origin:Receipt_repr.update_origin -> Raw_context.t -> storage_limit:Z.t -> payer:Token.source -> Z.t -> (Raw_context.t * Z.t * Receipt_repr.balance_updates) tzresult Lwt.t
3649899f64edef49281d4cf56966705088fb31aa711531c54244c7e2ff10387e
elaforge/karya
ResponderSync.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt {- | Subset of the responder that handles syncing from Ui.State to the UI. -} module Cmd.ResponderSync (Sync, sync) where import qualified Control.Concurrent.MVar as MVar import qualified Data.Map as Map import qualified Data.Text as Text import qualified Util.Debug as Debug import qualified Util.Log as Log import qualified Util.Trace as Trace import qualified Cmd.Cmd as Cmd import qualified Cmd.Integrate as Integrate import qualified Cmd.Internal as Internal import qualified Ui.Diff as Diff import qualified Ui.Track as Track import qualified Ui.Ui as Ui import qualified Ui.Update as Update import Global type Sync = Track.TrackSignals -> Track.SetStyleHigh -> Ui.State -> [Update.DisplayUpdate] -> IO (Maybe Ui.Error) -- | Sync @ui_to@ to the UI. -- -- Returns both UI state and cmd state since verification may clean up the UI -- state, and this is where the undo history is stored in Cmd.State. sync :: Sync -> Ui.State -- ^ state before Cmd was run -> Ui.State -- ^ current state -> Cmd.State -> Update.UiDamage -> MVar.MVar Ui.State -> IO ([Update.UiUpdate], Ui.State) ^ Sync uses ' Update . 's , but the diff also produces UiUpdates , which are needed for incremental save and score damage . sync sync_func ui_from ui_to cmd_to ui_damage play_monitor_state = do ui_to <- case Ui.quick_verify ui_damage ui_to of Left err -> do Log.error $ "cmd caused a verify error, rejecting state change: " <> txt err return ui_from Right (state, warns) -> do unless (null warns) $ Log.warn $ "verify fixed issues: " <> Text.intercalate "; " warns return state Trace.trace "sync.verify" let (ui_updates, display_updates) = Diff.diff ui_damage ui_from ui_to Trace.force (ui_updates, display_updates) Trace.trace "sync.diff" -- Debug.fullM (Debug.putp "ui_damage") ui_damage -- Debug.fullM (Debug.putp "ui_updates") ui_updates -- Debug.fullM (Debug.putp "display_updates") display_updates (ui_to, ui_updates, display_updates) <- case Integrate.score_integrate ui_updates ui_to of Left err -> do Log.error $ "score_integrate failed: " <> pretty err return (ui_from, ui_updates, display_updates) Right (logs, state, updates) -> do mapM_ Log.write logs let (ui_updates', display_updates') = Diff.diff updates ui_to state return ( state , ui_updates ++ ui_updates' , display_updates ++ display_updates' ) Trace.force (ui_updates, display_updates) Trace.trace "sync.score_integrate" when (any modified_view ui_updates) $ MVar.modifyMVar_ play_monitor_state (const (return ui_to)) when (Cmd.state_debug cmd_to && not (null display_updates)) $ Debug.putp "updates" display_updates err <- sync_func (get_track_signals cmd_to) Internal.set_style ui_to display_updates Trace.trace "sync.sync" whenJust err $ \err -> Log.error $ "syncing updates: " <> pretty err return (ui_updates, ui_to) -- | Get all track signals already derived. TrackSignals are only collected -- for top level derives, so there should only be signals for visible windows. -- If the derive is still in progress, there may not be signals, but they will be directly when the is received . get_track_signals :: Cmd.State -> Track.TrackSignals get_track_signals = mconcatMap Cmd.perf_track_signals . Map.elems . Cmd.state_performance . Cmd.state_play modified_view :: Update.UiUpdate -> Bool modified_view (Update.View _ update) = case update of Update.CreateView {} -> True Update.DestroyView {} -> True _ -> False modified_view _ = False
null
https://raw.githubusercontent.com/elaforge/karya/c40949df6f9493ed85f16405a8c457e04a9cbfa3/Cmd/ResponderSync.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Subset of the responder that handles syncing from Ui.State to the UI. | Sync @ui_to@ to the UI. Returns both UI state and cmd state since verification may clean up the UI state, and this is where the undo history is stored in Cmd.State. ^ state before Cmd was run ^ current state Debug.fullM (Debug.putp "ui_damage") ui_damage Debug.fullM (Debug.putp "ui_updates") ui_updates Debug.fullM (Debug.putp "display_updates") display_updates | Get all track signals already derived. TrackSignals are only collected for top level derives, so there should only be signals for visible windows. If the derive is still in progress, there may not be signals, but they will
Copyright 2013 module Cmd.ResponderSync (Sync, sync) where import qualified Control.Concurrent.MVar as MVar import qualified Data.Map as Map import qualified Data.Text as Text import qualified Util.Debug as Debug import qualified Util.Log as Log import qualified Util.Trace as Trace import qualified Cmd.Cmd as Cmd import qualified Cmd.Integrate as Integrate import qualified Cmd.Internal as Internal import qualified Ui.Diff as Diff import qualified Ui.Track as Track import qualified Ui.Ui as Ui import qualified Ui.Update as Update import Global type Sync = Track.TrackSignals -> Track.SetStyleHigh -> Ui.State -> [Update.DisplayUpdate] -> IO (Maybe Ui.Error) sync :: Sync -> Cmd.State -> Update.UiDamage -> MVar.MVar Ui.State -> IO ([Update.UiUpdate], Ui.State) ^ Sync uses ' Update . 's , but the diff also produces UiUpdates , which are needed for incremental save and score damage . sync sync_func ui_from ui_to cmd_to ui_damage play_monitor_state = do ui_to <- case Ui.quick_verify ui_damage ui_to of Left err -> do Log.error $ "cmd caused a verify error, rejecting state change: " <> txt err return ui_from Right (state, warns) -> do unless (null warns) $ Log.warn $ "verify fixed issues: " <> Text.intercalate "; " warns return state Trace.trace "sync.verify" let (ui_updates, display_updates) = Diff.diff ui_damage ui_from ui_to Trace.force (ui_updates, display_updates) Trace.trace "sync.diff" (ui_to, ui_updates, display_updates) <- case Integrate.score_integrate ui_updates ui_to of Left err -> do Log.error $ "score_integrate failed: " <> pretty err return (ui_from, ui_updates, display_updates) Right (logs, state, updates) -> do mapM_ Log.write logs let (ui_updates', display_updates') = Diff.diff updates ui_to state return ( state , ui_updates ++ ui_updates' , display_updates ++ display_updates' ) Trace.force (ui_updates, display_updates) Trace.trace "sync.score_integrate" when (any modified_view ui_updates) $ MVar.modifyMVar_ play_monitor_state (const (return ui_to)) when (Cmd.state_debug cmd_to && not (null display_updates)) $ Debug.putp "updates" display_updates err <- sync_func (get_track_signals cmd_to) Internal.set_style ui_to display_updates Trace.trace "sync.sync" whenJust err $ \err -> Log.error $ "syncing updates: " <> pretty err return (ui_updates, ui_to) be directly when the is received . get_track_signals :: Cmd.State -> Track.TrackSignals get_track_signals = mconcatMap Cmd.perf_track_signals . Map.elems . Cmd.state_performance . Cmd.state_play modified_view :: Update.UiUpdate -> Bool modified_view (Update.View _ update) = case update of Update.CreateView {} -> True Update.DestroyView {} -> True _ -> False modified_view _ = False
4fbc0011fb229ee1f58ef4c121ebbc2191684961d2200cce69281d32e4c681c1
tezos/tezos-mirror
main.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2023 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. *) (* *) (*****************************************************************************) let () = let path = Cli.get_string ~default:"scenarios.json" "configuration" in let testnet = Testnet.get_testnet_config path in Sc_rollup.register ~testnet ; Test.run ()
null
https://raw.githubusercontent.com/tezos/tezos-mirror/43d810498f9ce75a32cd72d7c57bf77c14556bc1/src/bin_testnet_scenarios/main.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. ***************************************************************************
Copyright ( c ) 2023 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 let () = let path = Cli.get_string ~default:"scenarios.json" "configuration" in let testnet = Testnet.get_testnet_config path in Sc_rollup.register ~testnet ; Test.run ()
7a9aa7b4e66338faf39c4e71c8885ecf494862917f3341298ab07df99bf29d8d
dmitryvk/sbcl-win32-threads
alien.impure.lisp
;;;; This file is for compiler tests which have side effects (e.g. executing DEFUN ) but which do n't need any special side - effecting environmental stuff ( e.g. DECLAIM of particular optimization ;;;; settings). Similar tests which *do* expect special settings may be in files compiler-1.impure.lisp , compiler-2.impure.lisp , etc . This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. (cl:in-package :cl-user) In sbcl-0.6.10 , reported that ( SETF EXTERN - ALIEN ) ;;; was messed up so badly that trying to execute expressions like ;;; this signalled an error. (setf (sb-alien:extern-alien "thread_control_stack_size" sb-alien:unsigned) (sb-alien:extern-alien "thread_control_stack_size" sb-alien:unsigned)) bug 133 , fixed in 0.7.0.5 : Somewhere in 0.pre7 . * , C void returns ;;; were broken ("unable to use values types here") when ;;; auto-PROCLAIM-of-return-value was added to DEFINE-ALIEN-ROUTINE. (sb-alien:define-alien-routine ("free" free) void (ptr (* t) :in)) Types of alien functions were being incorrectly DECLAIMED when ;;; docstrings were included in the definition until sbcl-0.7.6.15. (sb-alien:define-alien-routine ("getenv" ftype-correctness) c-string "docstring" (name c-string)) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness))) (assert warningsp)) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness "FOO"))) (assert (not warningsp))) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness "FOO" "BAR"))) (assert warningsp)) ;;; This used to break due to too eager auxiliary type twiddling in ;;; parse-alien-record-type. (defparameter *maybe* nil) (defun with-alien-test-for-struct-plus-funcall () (with-alien ((x (struct bar (x unsigned) (y unsigned))) ;; bogus definition, but we just need the symbol (f (function int (* (struct bar))) :extern "printf")) (when *maybe* (alien-funcall f (addr x))))) ;;; Mutually referent structures (define-alien-type struct.1 (struct struct.1 (x (* (struct struct.2))) (y int))) (define-alien-type struct.2 (struct struct.2 (x (* (struct struct.1))) (y int))) (let ((s1 (make-alien struct.1)) (s2 (make-alien struct.2))) (setf (slot s1 'x) s2 (slot s2 'x) s1 (slot (slot s1 'x) 'y) 1 (slot (slot s2 'x) 'y) 2) (assert (= 1 (slot (slot s1 'x) 'y))) (assert (= 2 (slot (slot s2 'x) 'y)))) " Alien bug " on sbcl - devel 2004 - 10 - 11 by caused ;;; by recursive struct definition. (let ((fname "alien-bug-2004-10-11.tmp.lisp")) (unwind-protect (progn (with-open-file (f fname :direction :output) (mapc (lambda (form) (print form f)) '((defpackage :alien-bug (:use :cl :sb-alien)) (in-package :alien-bug) (define-alien-type objc-class (struct objc-class (protocols (* (struct protocol-list (list (array (* (struct objc-class)))))))))))) (load fname) (load fname) (load (compile-file fname)) (load (compile-file fname))) (delete-file (compile-file-pathname fname)) (delete-file fname))) enumerations with only one enum resulted in division - by - zero reported on sbcl - help 2004 - 11 - 16 by (define-alien-type enum.1 (enum nil (:val0 0))) (define-alien-type enum.2 (enum nil (zero 0) (one 1) (two 2) (three 3) (four 4) (five 5) (six 6) (seven 7) (eight 8) (nine 9))) (with-alien ((integer-array (array int 3))) (let ((enum-array (cast integer-array (array enum.2 3)))) (setf (deref enum-array 0) 'three (deref enum-array 1) 'four) (setf (deref integer-array 2) (+ (deref integer-array 0) (deref integer-array 1))) (assert (eql (deref enum-array 2) 'seven)))) ;; The code that is used for mapping from integers to symbols depends on the ;; `density' of the set of used integers, so test with a sparse set as well. (define-alien-type enum.3 (enum nil (zero 0) (one 1) (k-one 1001) (k-two 1002))) (with-alien ((integer-array (array int 3))) (let ((enum-array (cast integer-array (array enum.3 3)))) (setf (deref enum-array 0) 'one (deref enum-array 1) 'k-one) (setf (deref integer-array 2) (+ (deref integer-array 0) (deref integer-array 1))) (assert (eql (deref enum-array 2) 'k-two)))) ;; enums used to allow values to be used only once ;; C enums allow for multiple tags to point to the same value (define-alien-type enum.4 (enum nil (:key1 1) (:key2 2) (:keytwo 2))) (with-alien ((enum-array (array enum.4 3))) (setf (deref enum-array 0) :key1) (setf (deref enum-array 1) :key2) (setf (deref enum-array 2) :keytwo) (assert (and (eql (deref enum-array 1) (deref enum-array 2)) (eql (deref enum-array 1) :key2)))) As reported by Baughn on # lisp , ALIEN - FUNCALL loops forever when compiled with ( DEBUG 3 ) . (sb-kernel::values-specifier-type-cache-clear) (proclaim '(optimize (debug 3))) (let ((f (compile nil '(lambda (v) (sb-alien:alien-funcall (sb-alien:extern-alien "getenv" (function (c-string) c-string)) v))))) (assert (typep (funcall f "HOME") '(or string null)))) ;;; CLH: Test for non-standard alignment in alien structs ;;; (sb-alien:define-alien-type align-test-struct (sb-alien:union align-test-union (s (sb-alien:struct nil (s1 sb-alien:unsigned-char) (c1 sb-alien:unsigned-char :alignment 16) (c2 sb-alien:unsigned-char :alignment 32) (c3 sb-alien:unsigned-char :alignment 32) (c4 sb-alien:unsigned-char :alignment 8))) (u (sb-alien:array sb-alien:unsigned-char 16)))) (let ((a1 (sb-alien:make-alien align-test-struct))) (declare (type (sb-alien:alien (* align-test-struct)) a1)) (setf (sb-alien:slot (sb-alien:slot a1 's) 's1) 1) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c1) 21) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c2) 41) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c3) 61) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c4) 81) (assert (equal '(1 21 41 61 81) (list (sb-alien:deref (sb-alien:slot a1 'u) 0) (sb-alien:deref (sb-alien:slot a1 'u) 2) (sb-alien:deref (sb-alien:slot a1 'u) 4) (sb-alien:deref (sb-alien:slot a1 'u) 8) (sb-alien:deref (sb-alien:slot a1 'u) 9))))) (handler-bind ((compiler-note (lambda (c) (error "bad note! ~A" c)))) (funcall (compile nil '(lambda () (sb-alien:make-alien sb-alien:int))))) ;;; Test case for unwinding an alien (Win32) exception frame ;;; ;;; The basic theory here is that failing to honor a win32 ;;; exception frame during stack unwinding breaks the chain. ;;; "And if / You don't love me now / You will never love me ;;; again / I can still hear you saying / You would never break ;;; the chain." If the chain is broken and another exception ;;; occurs (such as an error trap caused by an OBJECT-NOT-TYPE ;;; error), the system will kill our process. No mercy, no ;;; appeal. So, to check that we have done our job properly, we ;;; need some way to put an exception frame on the stack and then ;;; unwind through it, then trigger another exception. (FUNCALL ;;; 0) will suffice for the latter, and a simple test shows that ;;; CallWindowProc() establishes a frame and calls a function ;;; passed to it as an argument. #+win32 (progn (load-shared-object "USER32") (assert (eq :ok (handler-case (tagbody (alien-funcall (extern-alien "CallWindowProcW" (function unsigned-int (* (function int)) unsigned-int unsigned-int unsigned-int unsigned-int)) (alien-sap (sb-alien::alien-callback (function unsigned-int) #'(lambda () (go up)))) 0 0 0 0) up (funcall 0)) (error () :ok))))) ;;; Unused local alien caused a compiler error (with-test (:name unused-local-alien) (let ((fun `(lambda () (sb-alien:with-alien ((alien1923 (array (sb-alien:unsigned 8) 72))) (values))))) (assert (not (funcall (compile nil fun)))))) ;;; Non-local exit from WITH-ALIEN caused alien stack to be leaked. (defvar *sap-int*) (defun try-to-leak-alien-stack (x) (with-alien ((alien (array (sb-alien:unsigned 8) 72))) (let ((sap-int (sb-sys:sap-int (alien-sap alien)))) (if *sap-int* (assert (= *sap-int* sap-int)) (setf *sap-int* sap-int))) (when x (return-from try-to-leak-alien-stack 'going)) (never))) (with-test (:name :nlx-causes-alien-stack-leak) (let ((*sap-int* nil)) (loop repeat 1024 do (try-to-leak-alien-stack t)))) bug 431 (with-test (:name :alien-struct-redefinition) (eval '(progn (define-alien-type nil (struct mystruct (myshort short) (mychar char))) (with-alien ((myst (struct mystruct))) (with-alien ((mysh short (slot myst 'myshort))) (assert (integerp mysh)))))) (let ((restarted 0)) (handler-bind ((error (lambda (e) (let ((cont (find-restart 'continue e))) (when cont (incf restarted) (invoke-restart cont)))))) (eval '(define-alien-type nil (struct mystruct (myint int) (mychar char))))) (assert (= 1 restarted))) (eval '(with-alien ((myst (struct mystruct))) (with-alien ((myin int (slot myst 'myint))) (assert (integerp myin)))))) ;;; void conflicted with derived type (declaim (inline bug-316075)) (sb-alien:define-alien-routine bug-316075 void (result char :out)) (with-test (:name bug-316075) (handler-bind ((warning #'error)) (compile nil '(lambda () (multiple-value-list (bug-316075)))))) ;;; Bug #316325: "return values of alien calls assumed truncated to ;;; correct width on x86" #+x86-64 (sb-alien::define-alien-callback truncation-test (unsigned 64) ((foo (unsigned 64))) foo) #+x86 (sb-alien::define-alien-callback truncation-test (unsigned 32) ((foo (unsigned 32))) foo) #+(or x86-64 x86) (with-test (:name bug-316325) ;; This test works by defining a callback function that provides an ;; identity transform over a full-width machine word, then calling ;; it as if it returned a narrower type and checking to see if any ;; noise in the high bits of the result are properly ignored. (macrolet ((verify (type input output) `(with-alien ((fun (* (function ,type #+x86-64 (unsigned 64) #+x86 (unsigned 32))) :local (alien-sap truncation-test))) (let ((result (alien-funcall fun ,input))) (assert (= result ,output)))))) #+x86-64 (progn (verify (unsigned 64) #x8000000000000000 #x8000000000000000) (verify (signed 64) #x8000000000000000 #x-8000000000000000) (verify (signed 64) #x7fffffffffffffff #x7fffffffffffffff) (verify (unsigned 32) #x0000000180000042 #x80000042) (verify (signed 32) #x0000000180000042 #x-7fffffbe) (verify (signed 32) #xffffffff7fffffff #x7fffffff)) #+x86 (progn (verify (unsigned 32) #x80000042 #x80000042) (verify (signed 32) #x80000042 #x-7fffffbe) (verify (signed 32) #x7fffffff #x7fffffff)) (verify (unsigned 16) #x00018042 #x8042) (verify (signed 16) #x003f8042 #x-7fbe) (verify (signed 16) #x003f7042 #x7042))) (with-test (:name :bug-654485) ;; DEBUG 2 used to prevent let-conversion of the open-coded ALIEN-FUNCALL body, ;; which in turn led the dreaded %SAP-ALIEN note. (handler-case (compile nil `(lambda (program argv) (declare (optimize (debug 2))) (with-alien ((sys-execv1 (function int c-string (* c-string)) :extern "execv")) (values (alien-funcall sys-execv1 program argv))))) (compiler-note (n) (error n)))) ;;; success
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/alien.impure.lisp
lisp
This file is for compiler tests which have side effects (e.g. settings). Similar tests which *do* expect special settings may more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. was messed up so badly that trying to execute expressions like this signalled an error. were broken ("unable to use values types here") when auto-PROCLAIM-of-return-value was added to DEFINE-ALIEN-ROUTINE. docstrings were included in the definition until sbcl-0.7.6.15. This used to break due to too eager auxiliary type twiddling in parse-alien-record-type. bogus definition, but we just need the symbol Mutually referent structures by recursive struct definition. The code that is used for mapping from integers to symbols depends on the `density' of the set of used integers, so test with a sparse set as well. enums used to allow values to be used only once C enums allow for multiple tags to point to the same value CLH: Test for non-standard alignment in alien structs Test case for unwinding an alien (Win32) exception frame The basic theory here is that failing to honor a win32 exception frame during stack unwinding breaks the chain. "And if / You don't love me now / You will never love me again / I can still hear you saying / You would never break the chain." If the chain is broken and another exception occurs (such as an error trap caused by an OBJECT-NOT-TYPE error), the system will kill our process. No mercy, no appeal. So, to check that we have done our job properly, we need some way to put an exception frame on the stack and then unwind through it, then trigger another exception. (FUNCALL 0) will suffice for the latter, and a simple test shows that CallWindowProc() establishes a frame and calls a function passed to it as an argument. Unused local alien caused a compiler error Non-local exit from WITH-ALIEN caused alien stack to be leaked. void conflicted with derived type Bug #316325: "return values of alien calls assumed truncated to correct width on x86" This test works by defining a callback function that provides an identity transform over a full-width machine word, then calling it as if it returned a narrower type and checking to see if any noise in the high bits of the result are properly ignored. DEBUG 2 used to prevent let-conversion of the open-coded ALIEN-FUNCALL body, which in turn led the dreaded %SAP-ALIEN note. success
executing DEFUN ) but which do n't need any special side - effecting environmental stuff ( e.g. DECLAIM of particular optimization be in files compiler-1.impure.lisp , compiler-2.impure.lisp , etc . This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . (cl:in-package :cl-user) In sbcl-0.6.10 , reported that ( SETF EXTERN - ALIEN ) (setf (sb-alien:extern-alien "thread_control_stack_size" sb-alien:unsigned) (sb-alien:extern-alien "thread_control_stack_size" sb-alien:unsigned)) bug 133 , fixed in 0.7.0.5 : Somewhere in 0.pre7 . * , C void returns (sb-alien:define-alien-routine ("free" free) void (ptr (* t) :in)) Types of alien functions were being incorrectly DECLAIMED when (sb-alien:define-alien-routine ("getenv" ftype-correctness) c-string "docstring" (name c-string)) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness))) (assert warningsp)) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness "FOO"))) (assert (not warningsp))) (multiple-value-bind (function warningsp failurep) (compile nil '(lambda () (ftype-correctness "FOO" "BAR"))) (assert warningsp)) (defparameter *maybe* nil) (defun with-alien-test-for-struct-plus-funcall () (with-alien ((x (struct bar (x unsigned) (y unsigned))) (f (function int (* (struct bar))) :extern "printf")) (when *maybe* (alien-funcall f (addr x))))) (define-alien-type struct.1 (struct struct.1 (x (* (struct struct.2))) (y int))) (define-alien-type struct.2 (struct struct.2 (x (* (struct struct.1))) (y int))) (let ((s1 (make-alien struct.1)) (s2 (make-alien struct.2))) (setf (slot s1 'x) s2 (slot s2 'x) s1 (slot (slot s1 'x) 'y) 1 (slot (slot s2 'x) 'y) 2) (assert (= 1 (slot (slot s1 'x) 'y))) (assert (= 2 (slot (slot s2 'x) 'y)))) " Alien bug " on sbcl - devel 2004 - 10 - 11 by caused (let ((fname "alien-bug-2004-10-11.tmp.lisp")) (unwind-protect (progn (with-open-file (f fname :direction :output) (mapc (lambda (form) (print form f)) '((defpackage :alien-bug (:use :cl :sb-alien)) (in-package :alien-bug) (define-alien-type objc-class (struct objc-class (protocols (* (struct protocol-list (list (array (* (struct objc-class)))))))))))) (load fname) (load fname) (load (compile-file fname)) (load (compile-file fname))) (delete-file (compile-file-pathname fname)) (delete-file fname))) enumerations with only one enum resulted in division - by - zero reported on sbcl - help 2004 - 11 - 16 by (define-alien-type enum.1 (enum nil (:val0 0))) (define-alien-type enum.2 (enum nil (zero 0) (one 1) (two 2) (three 3) (four 4) (five 5) (six 6) (seven 7) (eight 8) (nine 9))) (with-alien ((integer-array (array int 3))) (let ((enum-array (cast integer-array (array enum.2 3)))) (setf (deref enum-array 0) 'three (deref enum-array 1) 'four) (setf (deref integer-array 2) (+ (deref integer-array 0) (deref integer-array 1))) (assert (eql (deref enum-array 2) 'seven)))) (define-alien-type enum.3 (enum nil (zero 0) (one 1) (k-one 1001) (k-two 1002))) (with-alien ((integer-array (array int 3))) (let ((enum-array (cast integer-array (array enum.3 3)))) (setf (deref enum-array 0) 'one (deref enum-array 1) 'k-one) (setf (deref integer-array 2) (+ (deref integer-array 0) (deref integer-array 1))) (assert (eql (deref enum-array 2) 'k-two)))) (define-alien-type enum.4 (enum nil (:key1 1) (:key2 2) (:keytwo 2))) (with-alien ((enum-array (array enum.4 3))) (setf (deref enum-array 0) :key1) (setf (deref enum-array 1) :key2) (setf (deref enum-array 2) :keytwo) (assert (and (eql (deref enum-array 1) (deref enum-array 2)) (eql (deref enum-array 1) :key2)))) As reported by Baughn on # lisp , ALIEN - FUNCALL loops forever when compiled with ( DEBUG 3 ) . (sb-kernel::values-specifier-type-cache-clear) (proclaim '(optimize (debug 3))) (let ((f (compile nil '(lambda (v) (sb-alien:alien-funcall (sb-alien:extern-alien "getenv" (function (c-string) c-string)) v))))) (assert (typep (funcall f "HOME") '(or string null)))) (sb-alien:define-alien-type align-test-struct (sb-alien:union align-test-union (s (sb-alien:struct nil (s1 sb-alien:unsigned-char) (c1 sb-alien:unsigned-char :alignment 16) (c2 sb-alien:unsigned-char :alignment 32) (c3 sb-alien:unsigned-char :alignment 32) (c4 sb-alien:unsigned-char :alignment 8))) (u (sb-alien:array sb-alien:unsigned-char 16)))) (let ((a1 (sb-alien:make-alien align-test-struct))) (declare (type (sb-alien:alien (* align-test-struct)) a1)) (setf (sb-alien:slot (sb-alien:slot a1 's) 's1) 1) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c1) 21) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c2) 41) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c3) 61) (setf (sb-alien:slot (sb-alien:slot a1 's) 'c4) 81) (assert (equal '(1 21 41 61 81) (list (sb-alien:deref (sb-alien:slot a1 'u) 0) (sb-alien:deref (sb-alien:slot a1 'u) 2) (sb-alien:deref (sb-alien:slot a1 'u) 4) (sb-alien:deref (sb-alien:slot a1 'u) 8) (sb-alien:deref (sb-alien:slot a1 'u) 9))))) (handler-bind ((compiler-note (lambda (c) (error "bad note! ~A" c)))) (funcall (compile nil '(lambda () (sb-alien:make-alien sb-alien:int))))) #+win32 (progn (load-shared-object "USER32") (assert (eq :ok (handler-case (tagbody (alien-funcall (extern-alien "CallWindowProcW" (function unsigned-int (* (function int)) unsigned-int unsigned-int unsigned-int unsigned-int)) (alien-sap (sb-alien::alien-callback (function unsigned-int) #'(lambda () (go up)))) 0 0 0 0) up (funcall 0)) (error () :ok))))) (with-test (:name unused-local-alien) (let ((fun `(lambda () (sb-alien:with-alien ((alien1923 (array (sb-alien:unsigned 8) 72))) (values))))) (assert (not (funcall (compile nil fun)))))) (defvar *sap-int*) (defun try-to-leak-alien-stack (x) (with-alien ((alien (array (sb-alien:unsigned 8) 72))) (let ((sap-int (sb-sys:sap-int (alien-sap alien)))) (if *sap-int* (assert (= *sap-int* sap-int)) (setf *sap-int* sap-int))) (when x (return-from try-to-leak-alien-stack 'going)) (never))) (with-test (:name :nlx-causes-alien-stack-leak) (let ((*sap-int* nil)) (loop repeat 1024 do (try-to-leak-alien-stack t)))) bug 431 (with-test (:name :alien-struct-redefinition) (eval '(progn (define-alien-type nil (struct mystruct (myshort short) (mychar char))) (with-alien ((myst (struct mystruct))) (with-alien ((mysh short (slot myst 'myshort))) (assert (integerp mysh)))))) (let ((restarted 0)) (handler-bind ((error (lambda (e) (let ((cont (find-restart 'continue e))) (when cont (incf restarted) (invoke-restart cont)))))) (eval '(define-alien-type nil (struct mystruct (myint int) (mychar char))))) (assert (= 1 restarted))) (eval '(with-alien ((myst (struct mystruct))) (with-alien ((myin int (slot myst 'myint))) (assert (integerp myin)))))) (declaim (inline bug-316075)) (sb-alien:define-alien-routine bug-316075 void (result char :out)) (with-test (:name bug-316075) (handler-bind ((warning #'error)) (compile nil '(lambda () (multiple-value-list (bug-316075)))))) #+x86-64 (sb-alien::define-alien-callback truncation-test (unsigned 64) ((foo (unsigned 64))) foo) #+x86 (sb-alien::define-alien-callback truncation-test (unsigned 32) ((foo (unsigned 32))) foo) #+(or x86-64 x86) (with-test (:name bug-316325) (macrolet ((verify (type input output) `(with-alien ((fun (* (function ,type #+x86-64 (unsigned 64) #+x86 (unsigned 32))) :local (alien-sap truncation-test))) (let ((result (alien-funcall fun ,input))) (assert (= result ,output)))))) #+x86-64 (progn (verify (unsigned 64) #x8000000000000000 #x8000000000000000) (verify (signed 64) #x8000000000000000 #x-8000000000000000) (verify (signed 64) #x7fffffffffffffff #x7fffffffffffffff) (verify (unsigned 32) #x0000000180000042 #x80000042) (verify (signed 32) #x0000000180000042 #x-7fffffbe) (verify (signed 32) #xffffffff7fffffff #x7fffffff)) #+x86 (progn (verify (unsigned 32) #x80000042 #x80000042) (verify (signed 32) #x80000042 #x-7fffffbe) (verify (signed 32) #x7fffffff #x7fffffff)) (verify (unsigned 16) #x00018042 #x8042) (verify (signed 16) #x003f8042 #x-7fbe) (verify (signed 16) #x003f7042 #x7042))) (with-test (:name :bug-654485) (handler-case (compile nil `(lambda (program argv) (declare (optimize (debug 2))) (with-alien ((sys-execv1 (function int c-string (* c-string)) :extern "execv")) (values (alien-funcall sys-execv1 program argv))))) (compiler-note (n) (error n))))
01ac1bbcb97fa332f8490f1cdbb078c2045191787ed329f3e4e22b361d79adfe
UU-ComputerScience/uhc
ReadP.hs
# LANGUAGE CPP # # OPTIONS_GHC -XNoImplicitPrelude , CPP # # LANGUAGE GenericDeriving # ----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.ReadP Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : non-portable (local universal quantification) -- This is a library of parser combinators , originally written by . -- It parses all alternatives in parallel, so it never keeps hold of -- the beginning of the input string, a common source of space leaks with -- other parsers. The '(+++)' choice combinator is genuinely commutative; -- it makes no difference which branch is \"shorter\". ----------------------------------------------------------------------------- module Text.ParserCombinators.ReadP ( -- * The 'ReadP' type #ifndef __NHC__ : : * - > * ; instance Functor , Monad , MonadPlus #else : : * - > * - > * ; instance Functor , Monad , MonadPlus #endif -- * Primitive operations : : look, -- :: ReadP String (+++), -- :: ReadP a -> ReadP a -> ReadP a (<++), -- :: ReadP a -> ReadP a -> ReadP a gather, -- :: ReadP a -> ReadP (String, a) -- * Other operations pfail, -- :: ReadP a : : ( Bool ) - > ReadP Char : : ReadP Char string, -- :: String -> ReadP String : : ( Bool ) - > ReadP String : : ( Bool ) - > ReadP String : : ( ) choice, -- :: [ReadP a] -> ReadP a count, -- :: Int -> ReadP a -> ReadP [a] between, -- :: ReadP open -> ReadP close -> ReadP a -> ReadP a option, -- :: a -> ReadP a -> ReadP a optional, -- :: ReadP a -> ReadP () many, -- :: ReadP a -> ReadP [a] many1, -- :: ReadP a -> ReadP [a] skipMany, -- :: ReadP a -> ReadP () skipMany1, -- :: ReadP a -> ReadP () sepBy, -- :: ReadP a -> ReadP sep -> ReadP [a] sepBy1, -- :: ReadP a -> ReadP sep -> ReadP [a] endBy, -- :: ReadP a -> ReadP sep -> ReadP [a] endBy1, -- :: ReadP a -> ReadP sep -> ReadP [a] chainr, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a chainl, -- :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a chainl1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a chainr1, -- :: ReadP a -> ReadP (a -> a -> a) -> ReadP a manyTill, -- :: ReadP a -> ReadP end -> ReadP [a] -- * Running a parser ReadS, -- :: *; = String -> [(a,String)] readP_to_S, -- :: ReadP a -> ReadS a readS_to_P, -- :: ReadS a -> ReadP a -- * Properties -- $properties ) where import Control.Monad( MonadPlus(..), sequence, liftM2 ) #ifdef __GLASGOW_HASKELL__ #ifndef __HADDOCK__ import {-# SOURCE #-} GHC.Unicode ( isSpace ) #endif import GHC.List ( replicate ) import GHC.Base #else import Data.Char( isSpace ) #endif infixr 5 +++, <++ #ifdef __GLASGOW_HASKELL__ ------------------------------------------------------------------------ -- ReadS -- | A parser for a type @a@, represented as a function that takes a ' String ' and returns a list of possible parses as @(a,'String')@ pairs . -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf 'ReadP'). type ReadS a = String -> [(a,String)] #endif -- --------------------------------------------------------------------------- -- The P type -- is representation type -- should be kept abstract data P a = Get (Char -> P a) | Look (String -> P a) | Fail | Result a (P a) | Final [(a,String)] -- invariant: list is non-empty! Monad , MonadPlus instance Monad P where return x = Result x Fail (Get f) >>= k = Get (\c -> f c >>= k) (Look f) >>= k = Look (\s -> f s >>= k) Fail >>= _ = Fail (Result x p) >>= k = k x `mplus` (p >>= k) (Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s] fail _ = Fail instance MonadPlus P where mzero = Fail most common case : two gets are combined Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c) -- results are delivered as soon as possible Result x p `mplus` q = Result x (p `mplus` q) p `mplus` Result x q = Result x (p `mplus` q) -- fail disappears Fail `mplus` p = p p `mplus` Fail = p two finals are combined final + look becomes one look and one final (= optimization ) final + sthg else becomes one look and one final Final r `mplus` Final t = Final (r ++ t) Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s)) Final r `mplus` p = Look (\s -> Final (r ++ run p s)) Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r)) p `mplus` Final r = Look (\s -> Final (run p s ++ r)) two looks are combined (= optimization ) -- look + sthg else floats upwards Look f `mplus` Look g = Look (\s -> f s `mplus` g s) Look f `mplus` p = Look (\s -> f s `mplus` p) p `mplus` Look f = Look (\s -> p `mplus` f s) -- --------------------------------------------------------------------------- -- The ReadP type #ifndef __NHC__ newtype ReadP a = R (forall b . (a -> P b) -> P b) #else #define ReadP (ReadPN b) newtype ReadPN b a = R ((a -> P b) -> P b) #endif Functor , Monad , MonadPlus instance Functor ReadP where fmap h (R f) = R (\k -> f (k . h)) instance Monad ReadP where return x = R (\k -> k x) fail _ = R (\_ -> Fail) R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k)) instance MonadPlus ReadP where mzero = pfail mplus = (+++) -- --------------------------------------------------------------------------- Operations over P final :: [(a,String)] -> P a -- Maintains invariant for Final constructor final [] = Fail final r = Final r run :: P a -> ReadS a run (Get f) (c:s) = run (f c) s run (Look f) s = run (f s) s run (Result x p) s = (x,s) : run p s run (Final r) _ = r run _ _ = [] -- --------------------------------------------------------------------------- Operations over ReadP get :: ReadP Char -- ^ Consumes and returns the next character. -- Fails if there is no input left. get = R Get look :: ReadP String -- ^ Look-ahead: returns the part of the input that is left, without -- consuming it. look = R Look pfail :: ReadP a -- ^ Always fails. pfail = R (\_ -> Fail) (+++) :: ReadP a -> ReadP a -> ReadP a -- ^ Symmetric choice. R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k) #ifndef __NHC__ (<++) :: ReadP a -> ReadP a -> ReadP a #else (<++) :: ReadPN a a -> ReadPN a a -> ReadPN a a #endif -- ^ Local, exclusive, left-biased choice: If left parser -- locally produces any result at all, then right parser is -- not used. #ifdef __GLASGOW_HASKELL__ R f0 <++ q = do s <- look probe (f0 return) s 0# where probe (Get f) (c:s) n = probe (f c) s (n+#1#) probe (Look f) s n = probe (f s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0# = return () discard n = get >> discard (n-#1#) #else R f <++ q = do s <- look #ifdef __UHC__ probe (f return) s (0::Int) #else probe (f return) s 0 #endif where probe (Get f) (c:s) n = probe (f c) s (n+1) probe (Look f) s n = probe (f s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0 = return () discard n = get >> discard (n-1) #endif #ifndef __NHC__ gather :: ReadP a -> ReadP (String, a) #else gather : : ( String->P b ) a - > ReadPN ( String->P b ) ( String , a ) #endif -- ^ Transforms a parser into one that does the same, but -- in addition returns the exact characters read. IMPORTANT NOTE : ' gather ' gives a runtime error if its first argument -- is built using any occurrences of readS_to_P. gather (R m) = R (\k -> gath id (m (\a -> return (\s -> k (s,a))))) where gath l (Get f) = Get (\c -> gath (l.(c:)) (f c)) gath _ Fail = Fail gath l (Look f) = Look (\s -> gath l (f s)) gath l (Result k p) = k (l []) `mplus` gath l p gath _ (Final _) = error "do not use readS_to_P in gather!" -- --------------------------------------------------------------------------- -- Derived operations satisfy :: (Char -> Bool) -> ReadP Char -- ^ Consumes and returns the next character, if it satisfies the -- specified predicate. satisfy p = do c <- get; if p c then return c else pfail char :: Char -> ReadP Char ^ and returns the specified character . char c = satisfy (c ==) string :: String -> ReadP String ^ and returns the specified string . string this = do s <- look; scan this s where scan [] _ = do return this scan (x:xs) (y:ys) | x == y = do get; scan xs ys scan _ _ = do pfail munch :: (Char -> Bool) -> ReadP String ^ the first zero or more characters satisfying the predicate . munch p = do s <- look scan s where scan (c:cs) | p c = do get; s <- scan cs; return (c:s) scan _ = do return "" munch1 :: (Char -> Bool) -> ReadP String ^ the first one or more characters satisfying the predicate . munch1 p = do c <- get if p c then do s <- munch p; return (c:s) else pfail choice :: [ReadP a] -> ReadP a -- ^ Combines all parsers in the specified list. choice [] = pfail choice [p] = p choice (p:ps) = p +++ choice ps skipSpaces :: ReadP () -- ^ Skips all whitespace. skipSpaces = do s <- look skip s where skip (c:s) | isSpace c = do get; skip s skip _ = do return () count :: Int -> ReadP a -> ReadP [a] ^ @count n p@ parses @n@ occurrences of @p@ in sequence . A list of -- results is returned. count n p = sequence (replicate n p) between :: ReadP open -> ReadP close -> ReadP a -> ReadP a ^ @between open close p@ parses @open@ , followed by and finally @close@. Only the value of @p@ is returned . between open close p = do open x <- p close return x option :: a -> ReadP a -> ReadP a -- ^ @option x p@ will either parse @p@ or return @x@ without consuming -- any input. option x p = p +++ return x optional :: ReadP a -> ReadP () ^ @optional p@ optionally parses @p@ and always returns @()@. optional p = (p >> return ()) +++ return () many :: ReadP a -> ReadP [a] ^ Parses zero or more occurrences of the given parser . many p = return [] +++ many1 p many1 :: ReadP a -> ReadP [a] ^ Parses one or more occurrences of the given parser . many1 p = liftM2 (:) p (many p) skipMany :: ReadP a -> ReadP () -- ^ Like 'many', but discards the result. skipMany p = many p >> return () skipMany1 :: ReadP a -> ReadP () -- ^ Like 'many1', but discards the result. skipMany1 p = p >> skipMany p sepBy :: ReadP a -> ReadP sep -> ReadP [a] ^ @sepBy p sep@ parses zero or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy p sep = sepBy1 p sep +++ return [] sepBy1 :: ReadP a -> ReadP sep -> ReadP [a] ^ @sepBy1 p sep@ parses one or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy1 p sep = liftM2 (:) p (many (sep >> p)) endBy :: ReadP a -> ReadP sep -> ReadP [a] ^ @endBy p sep@ parses zero or more occurrences of @p@ , separated and ended by @sep@. endBy p sep = many (do x <- p ; sep ; return x) endBy1 :: ReadP a -> ReadP sep -> ReadP [a] ^ @endBy p sep@ parses one or more occurrences of @p@ , separated and ended by @sep@. endBy1 p sep = many1 (do x <- p ; sep ; return x) chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a ^ @chainr p op x@ parses zero or more occurrences of @p@ , separated by @op@. -- Returns a value produced by a /right/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainr p op x = chainr1 p op +++ return x chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a ^ @chainl p op x@ parses zero or more occurrences of @p@ , separated by @op@. -- Returns a value produced by a /left/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainl p op x = chainl1 p op +++ return x chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a ^ Like ' ' , but parses one or more occurrences of @p@. chainr1 p op = scan where scan = p >>= rest rest x = do f <- op y <- scan return (f x y) +++ return x chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a ^ Like ' chainl ' , but parses one or more occurrences of @p@. chainl1 p op = p >>= rest where rest x = do f <- op y <- p rest (f x y) +++ return x #ifndef __NHC__ manyTill :: ReadP a -> ReadP end -> ReadP [a] #else manyTill :: ReadPN [a] a -> ReadPN [a] end -> ReadPN [a] [a] #endif ^ @manyTill p end@ parses zero or more occurrences of @p@ , until @end@ succeeds . Returns a list of values returned by @p@. manyTill p end = scan where scan = (end >> return []) <++ (liftM2 (:) p scan) -- --------------------------------------------------------------------------- -- Converting between ReadP and Read #ifndef __NHC__ readP_to_S :: ReadP a -> ReadS a #else readP_to_S :: ReadPN a a -> ReadS a #endif ^ Converts a parser into a Haskell ReadS - style function . This is the main way in which you can " a ' ReadP ' parser : -- the expanded type is -- @ readP_to_S :: ReadP a -> String -> [(a,String)] @ readP_to_S (R f) = run (f return) readS_to_P :: ReadS a -> ReadP a -- ^ Converts a Haskell ReadS-style function into a parser. -- Warning: This introduces local backtracking in the resulting -- parser, and therefore a possible inefficiency. readS_to_P r = R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s'])) -- --------------------------------------------------------------------------- -- QuickCheck properties that hold for the combinators $ properties The following are QuickCheck specifications of what the combinators do . These can be seen as formal specifications of the behavior of the combinators . We use bags to give semantics to the combinators . > type Bag a = [ a ] Equality on bags does not care about the order of elements . > (= ~ ) : : a = > Bag a - > Bag a - > Bool > xs = ~ ys = sort xs = = sort ys A special equality operator to avoid unresolved overloading when testing the properties . > (= ~. ) : : Bag ( Int , String ) - > Bag ( Int , String ) - > Bool > (= ~. ) = ( = ~ ) Here follow the properties : > prop_Get_Nil = > readP_to_S get [ ] = ~ [ ] > > prop_Get_Cons c s = > readP_to_S get ( c : s ) = ~ [ ( c , s ) ] > > prop_Look s = > readP_to_S look s = ~ [ ( s , s ) ] > > prop_Fail s = > readP_to_S = ~. [ ] > > prop_Return x s = > readP_to_S ( return x ) s = ~. [ ( x , s ) ] > > prop_Bind p k s = > readP_to_S ( p > > = k ) s = ~. > [ ys '' > | ( x , s ' ) < - readP_to_S p s > , ys '' < - readP_to_S ( k ( ) ) s ' > ] > > prop_Plus p q s = > readP_to_S ( p + + + q ) s = ~. > ( readP_to_S p s + + readP_to_S q s ) > > prop_LeftPlus p q s = > readP_to_S ( p < + + q ) s = ~. > ( readP_to_S p s + < + readP_to_S q s ) > where > [ ] + < + ys = ys > xs + < + _ = xs > > prop_Gather s = > forAll readPWithoutReadS $ \p - > > readP_to_S ( gather p ) s = ~ > [ ( ( pre , x::Int),s ' ) > | ( x , s ' ) < - readP_to_S p s > , let pre = take ( length s - length s ' ) s > ] > > prop_String_Yes this s = > readP_to_S ( string this ) ( this + + s ) = ~ > [ ( this , s ) ] > > prop_String_Maybe this s = > readP_to_S ( string this ) s = ~ > [ ( this , drop ( length this ) s ) | this ` isPrefixOf ` s ] > > prop_Munch p s = > readP_to_S ( munch p ) s = ~ > [ ( takeWhile p s , dropWhile p s ) ] > > prop_Munch1 p s = > readP_to_S ( munch1 p ) s = ~ > [ ( res , s ' ) | let ( res , s ' ) = ( takeWhile p s , dropWhile p s ) , not ( null res ) ] > > prop_Choice ps s = > readP_to_S ( choice ps ) s = ~. > readP_to_S ( foldr ( + + + ) ) s > > prop_ReadS r s = > readP_to_S ( readS_to_P r ) s = ~. r s The following are QuickCheck specifications of what the combinators do. These can be seen as formal specifications of the behavior of the combinators. We use bags to give semantics to the combinators. > type Bag a = [a] Equality on bags does not care about the order of elements. > (=~) :: Ord a => Bag a -> Bag a -> Bool > xs =~ ys = sort xs == sort ys A special equality operator to avoid unresolved overloading when testing the properties. > (=~.) :: Bag (Int,String) -> Bag (Int,String) -> Bool > (=~.) = (=~) Here follow the properties: > prop_Get_Nil = > readP_to_S get [] =~ [] > > prop_Get_Cons c s = > readP_to_S get (c:s) =~ [(c,s)] > > prop_Look s = > readP_to_S look s =~ [(s,s)] > > prop_Fail s = > readP_to_S pfail s =~. [] > > prop_Return x s = > readP_to_S (return x) s =~. [(x,s)] > > prop_Bind p k s = > readP_to_S (p >>= k) s =~. > [ ys'' > | (x,s') <- readP_to_S p s > , ys'' <- readP_to_S (k (x::Int)) s' > ] > > prop_Plus p q s = > readP_to_S (p +++ q) s =~. > (readP_to_S p s ++ readP_to_S q s) > > prop_LeftPlus p q s = > readP_to_S (p <++ q) s =~. > (readP_to_S p s +<+ readP_to_S q s) > where > [] +<+ ys = ys > xs +<+ _ = xs > > prop_Gather s = > forAll readPWithoutReadS $ \p -> > readP_to_S (gather p) s =~ > [ ((pre,x::Int),s') > | (x,s') <- readP_to_S p s > , let pre = take (length s - length s') s > ] > > prop_String_Yes this s = > readP_to_S (string this) (this ++ s) =~ > [(this,s)] > > prop_String_Maybe this s = > readP_to_S (string this) s =~ > [(this, drop (length this) s) | this `isPrefixOf` s] > > prop_Munch p s = > readP_to_S (munch p) s =~ > [(takeWhile p s, dropWhile p s)] > > prop_Munch1 p s = > readP_to_S (munch1 p) s =~ > [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)] > > prop_Choice ps s = > readP_to_S (choice ps) s =~. > readP_to_S (foldr (+++) pfail ps) s > > prop_ReadS r s = > readP_to_S (readS_to_P r) s =~. r s -}
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/base/Text/ParserCombinators/ReadP.hs
haskell
--------------------------------------------------------------------------- | Module : Text.ParserCombinators.ReadP License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : provisional Portability : non-portable (local universal quantification) It parses all alternatives in parallel, so it never keeps hold of the beginning of the input string, a common source of space leaks with other parsers. The '(+++)' choice combinator is genuinely commutative; it makes no difference which branch is \"shorter\". --------------------------------------------------------------------------- * The 'ReadP' type * Primitive operations :: ReadP String :: ReadP a -> ReadP a -> ReadP a :: ReadP a -> ReadP a -> ReadP a :: ReadP a -> ReadP (String, a) * Other operations :: ReadP a :: String -> ReadP String :: [ReadP a] -> ReadP a :: Int -> ReadP a -> ReadP [a] :: ReadP open -> ReadP close -> ReadP a -> ReadP a :: a -> ReadP a -> ReadP a :: ReadP a -> ReadP () :: ReadP a -> ReadP [a] :: ReadP a -> ReadP [a] :: ReadP a -> ReadP () :: ReadP a -> ReadP () :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP sep -> ReadP [a] :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> ReadP a :: ReadP a -> ReadP (a -> a -> a) -> ReadP a :: ReadP a -> ReadP end -> ReadP [a] * Running a parser :: *; = String -> [(a,String)] :: ReadP a -> ReadS a :: ReadS a -> ReadP a * Properties $properties # SOURCE # ---------------------------------------------------------------------- ReadS | A parser for a type @a@, represented as a function that takes a Note that this kind of backtracking parser is very inefficient; reading a large structure may be quite slow (cf 'ReadP'). --------------------------------------------------------------------------- The P type is representation type -- should be kept abstract invariant: list is non-empty! results are delivered as soon as possible fail disappears look + sthg else floats upwards --------------------------------------------------------------------------- The ReadP type --------------------------------------------------------------------------- Maintains invariant for Final constructor --------------------------------------------------------------------------- ^ Consumes and returns the next character. Fails if there is no input left. ^ Look-ahead: returns the part of the input that is left, without consuming it. ^ Always fails. ^ Symmetric choice. ^ Local, exclusive, left-biased choice: If left parser locally produces any result at all, then right parser is not used. ^ Transforms a parser into one that does the same, but in addition returns the exact characters read. is built using any occurrences of readS_to_P. --------------------------------------------------------------------------- Derived operations ^ Consumes and returns the next character, if it satisfies the specified predicate. ^ Combines all parsers in the specified list. ^ Skips all whitespace. results is returned. ^ @option x p@ will either parse @p@ or return @x@ without consuming any input. ^ Like 'many', but discards the result. ^ Like 'many1', but discards the result. Returns a value produced by a /right/ associative application of all functions returned by @op@. If there are no occurrences of @p@, @x@ is returned. Returns a value produced by a /left/ associative application of all functions returned by @op@. If there are no occurrences of @p@, @x@ is returned. --------------------------------------------------------------------------- Converting between ReadP and Read the expanded type is @ readP_to_S :: ReadP a -> String -> [(a,String)] @ ^ Converts a Haskell ReadS-style function into a parser. Warning: This introduces local backtracking in the resulting parser, and therefore a possible inefficiency. --------------------------------------------------------------------------- QuickCheck properties that hold for the combinators
# LANGUAGE CPP # # OPTIONS_GHC -XNoImplicitPrelude , CPP # # LANGUAGE GenericDeriving # Copyright : ( c ) The University of Glasgow 2002 This is a library of parser combinators , originally written by . module Text.ParserCombinators.ReadP ( #ifndef __NHC__ : : * - > * ; instance Functor , Monad , MonadPlus #else : : * - > * - > * ; instance Functor , Monad , MonadPlus #endif : : : : ( Bool ) - > ReadP Char : : ReadP Char : : ( Bool ) - > ReadP String : : ( Bool ) - > ReadP String : : ( ) ) where import Control.Monad( MonadPlus(..), sequence, liftM2 ) #ifdef __GLASGOW_HASKELL__ #ifndef __HADDOCK__ #endif import GHC.List ( replicate ) import GHC.Base #else import Data.Char( isSpace ) #endif infixr 5 +++, <++ #ifdef __GLASGOW_HASKELL__ ' String ' and returns a list of possible parses as @(a,'String')@ pairs . type ReadS a = String -> [(a,String)] #endif data P a = Get (Char -> P a) | Look (String -> P a) | Fail | Result a (P a) Monad , MonadPlus instance Monad P where return x = Result x Fail (Get f) >>= k = Get (\c -> f c >>= k) (Look f) >>= k = Look (\s -> f s >>= k) Fail >>= _ = Fail (Result x p) >>= k = k x `mplus` (p >>= k) (Final r) >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s] fail _ = Fail instance MonadPlus P where mzero = Fail most common case : two gets are combined Get f1 `mplus` Get f2 = Get (\c -> f1 c `mplus` f2 c) Result x p `mplus` q = Result x (p `mplus` q) p `mplus` Result x q = Result x (p `mplus` q) Fail `mplus` p = p p `mplus` Fail = p two finals are combined final + look becomes one look and one final (= optimization ) final + sthg else becomes one look and one final Final r `mplus` Final t = Final (r ++ t) Final r `mplus` Look f = Look (\s -> Final (r ++ run (f s) s)) Final r `mplus` p = Look (\s -> Final (r ++ run p s)) Look f `mplus` Final r = Look (\s -> Final (run (f s) s ++ r)) p `mplus` Final r = Look (\s -> Final (run p s ++ r)) two looks are combined (= optimization ) Look f `mplus` Look g = Look (\s -> f s `mplus` g s) Look f `mplus` p = Look (\s -> f s `mplus` p) p `mplus` Look f = Look (\s -> p `mplus` f s) #ifndef __NHC__ newtype ReadP a = R (forall b . (a -> P b) -> P b) #else #define ReadP (ReadPN b) newtype ReadPN b a = R ((a -> P b) -> P b) #endif Functor , Monad , MonadPlus instance Functor ReadP where fmap h (R f) = R (\k -> f (k . h)) instance Monad ReadP where return x = R (\k -> k x) fail _ = R (\_ -> Fail) R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k)) instance MonadPlus ReadP where mzero = pfail mplus = (+++) Operations over P final :: [(a,String)] -> P a final [] = Fail final r = Final r run :: P a -> ReadS a run (Get f) (c:s) = run (f c) s run (Look f) s = run (f s) s run (Result x p) s = (x,s) : run p s run (Final r) _ = r run _ _ = [] Operations over ReadP get :: ReadP Char get = R Get look :: ReadP String look = R Look pfail :: ReadP a pfail = R (\_ -> Fail) (+++) :: ReadP a -> ReadP a -> ReadP a R f1 +++ R f2 = R (\k -> f1 k `mplus` f2 k) #ifndef __NHC__ (<++) :: ReadP a -> ReadP a -> ReadP a #else (<++) :: ReadPN a a -> ReadPN a a -> ReadPN a a #endif #ifdef __GLASGOW_HASKELL__ R f0 <++ q = do s <- look probe (f0 return) s 0# where probe (Get f) (c:s) n = probe (f c) s (n+#1#) probe (Look f) s n = probe (f s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0# = return () discard n = get >> discard (n-#1#) #else R f <++ q = do s <- look #ifdef __UHC__ probe (f return) s (0::Int) #else probe (f return) s 0 #endif where probe (Get f) (c:s) n = probe (f c) s (n+1) probe (Look f) s n = probe (f s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0 = return () discard n = get >> discard (n-1) #endif #ifndef __NHC__ gather :: ReadP a -> ReadP (String, a) #else gather : : ( String->P b ) a - > ReadPN ( String->P b ) ( String , a ) #endif IMPORTANT NOTE : ' gather ' gives a runtime error if its first argument gather (R m) = R (\k -> gath id (m (\a -> return (\s -> k (s,a))))) where gath l (Get f) = Get (\c -> gath (l.(c:)) (f c)) gath _ Fail = Fail gath l (Look f) = Look (\s -> gath l (f s)) gath l (Result k p) = k (l []) `mplus` gath l p gath _ (Final _) = error "do not use readS_to_P in gather!" satisfy :: (Char -> Bool) -> ReadP Char satisfy p = do c <- get; if p c then return c else pfail char :: Char -> ReadP Char ^ and returns the specified character . char c = satisfy (c ==) string :: String -> ReadP String ^ and returns the specified string . string this = do s <- look; scan this s where scan [] _ = do return this scan (x:xs) (y:ys) | x == y = do get; scan xs ys scan _ _ = do pfail munch :: (Char -> Bool) -> ReadP String ^ the first zero or more characters satisfying the predicate . munch p = do s <- look scan s where scan (c:cs) | p c = do get; s <- scan cs; return (c:s) scan _ = do return "" munch1 :: (Char -> Bool) -> ReadP String ^ the first one or more characters satisfying the predicate . munch1 p = do c <- get if p c then do s <- munch p; return (c:s) else pfail choice :: [ReadP a] -> ReadP a choice [] = pfail choice [p] = p choice (p:ps) = p +++ choice ps skipSpaces :: ReadP () skipSpaces = do s <- look skip s where skip (c:s) | isSpace c = do get; skip s skip _ = do return () count :: Int -> ReadP a -> ReadP [a] ^ @count n p@ parses @n@ occurrences of @p@ in sequence . A list of count n p = sequence (replicate n p) between :: ReadP open -> ReadP close -> ReadP a -> ReadP a ^ @between open close p@ parses @open@ , followed by and finally @close@. Only the value of @p@ is returned . between open close p = do open x <- p close return x option :: a -> ReadP a -> ReadP a option x p = p +++ return x optional :: ReadP a -> ReadP () ^ @optional p@ optionally parses @p@ and always returns @()@. optional p = (p >> return ()) +++ return () many :: ReadP a -> ReadP [a] ^ Parses zero or more occurrences of the given parser . many p = return [] +++ many1 p many1 :: ReadP a -> ReadP [a] ^ Parses one or more occurrences of the given parser . many1 p = liftM2 (:) p (many p) skipMany :: ReadP a -> ReadP () skipMany p = many p >> return () skipMany1 :: ReadP a -> ReadP () skipMany1 p = p >> skipMany p sepBy :: ReadP a -> ReadP sep -> ReadP [a] ^ @sepBy p sep@ parses zero or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy p sep = sepBy1 p sep +++ return [] sepBy1 :: ReadP a -> ReadP sep -> ReadP [a] ^ @sepBy1 p sep@ parses one or more occurrences of @p@ , separated by @sep@. Returns a list of values returned by @p@. sepBy1 p sep = liftM2 (:) p (many (sep >> p)) endBy :: ReadP a -> ReadP sep -> ReadP [a] ^ @endBy p sep@ parses zero or more occurrences of @p@ , separated and ended by @sep@. endBy p sep = many (do x <- p ; sep ; return x) endBy1 :: ReadP a -> ReadP sep -> ReadP [a] ^ @endBy p sep@ parses one or more occurrences of @p@ , separated and ended by @sep@. endBy1 p sep = many1 (do x <- p ; sep ; return x) chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a ^ @chainr p op x@ parses zero or more occurrences of @p@ , separated by @op@. chainr p op x = chainr1 p op +++ return x chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a ^ @chainl p op x@ parses zero or more occurrences of @p@ , separated by @op@. chainl p op x = chainl1 p op +++ return x chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a ^ Like ' ' , but parses one or more occurrences of @p@. chainr1 p op = scan where scan = p >>= rest rest x = do f <- op y <- scan return (f x y) +++ return x chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a ^ Like ' chainl ' , but parses one or more occurrences of @p@. chainl1 p op = p >>= rest where rest x = do f <- op y <- p rest (f x y) +++ return x #ifndef __NHC__ manyTill :: ReadP a -> ReadP end -> ReadP [a] #else manyTill :: ReadPN [a] a -> ReadPN [a] end -> ReadPN [a] [a] #endif ^ @manyTill p end@ parses zero or more occurrences of @p@ , until @end@ succeeds . Returns a list of values returned by @p@. manyTill p end = scan where scan = (end >> return []) <++ (liftM2 (:) p scan) #ifndef __NHC__ readP_to_S :: ReadP a -> ReadS a #else readP_to_S :: ReadPN a a -> ReadS a #endif ^ Converts a parser into a Haskell ReadS - style function . This is the main way in which you can " a ' ReadP ' parser : readP_to_S (R f) = run (f return) readS_to_P :: ReadS a -> ReadP a readS_to_P r = R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s'])) $ properties The following are QuickCheck specifications of what the combinators do . These can be seen as formal specifications of the behavior of the combinators . We use bags to give semantics to the combinators . > type Bag a = [ a ] Equality on bags does not care about the order of elements . > (= ~ ) : : a = > Bag a - > Bag a - > Bool > xs = ~ ys = sort xs = = sort ys A special equality operator to avoid unresolved overloading when testing the properties . > (= ~. ) : : Bag ( Int , String ) - > Bag ( Int , String ) - > Bool > (= ~. ) = ( = ~ ) Here follow the properties : > prop_Get_Nil = > readP_to_S get [ ] = ~ [ ] > > prop_Get_Cons c s = > readP_to_S get ( c : s ) = ~ [ ( c , s ) ] > > prop_Look s = > readP_to_S look s = ~ [ ( s , s ) ] > > prop_Fail s = > readP_to_S = ~. [ ] > > prop_Return x s = > readP_to_S ( return x ) s = ~. [ ( x , s ) ] > > prop_Bind p k s = > readP_to_S ( p > > = k ) s = ~. > [ ys '' > | ( x , s ' ) < - readP_to_S p s > , ys '' < - readP_to_S ( k ( ) ) s ' > ] > > prop_Plus p q s = > readP_to_S ( p + + + q ) s = ~. > ( readP_to_S p s + + readP_to_S q s ) > > prop_LeftPlus p q s = > readP_to_S ( p < + + q ) s = ~. > ( readP_to_S p s + < + readP_to_S q s ) > where > [ ] + < + ys = ys > xs + < + _ = xs > > prop_Gather s = > forAll readPWithoutReadS $ \p - > > readP_to_S ( gather p ) s = ~ > [ ( ( pre , x::Int),s ' ) > | ( x , s ' ) < - readP_to_S p s > , let pre = take ( length s - length s ' ) s > ] > > prop_String_Yes this s = > readP_to_S ( string this ) ( this + + s ) = ~ > [ ( this , s ) ] > > prop_String_Maybe this s = > readP_to_S ( string this ) s = ~ > [ ( this , drop ( length this ) s ) | this ` isPrefixOf ` s ] > > prop_Munch p s = > readP_to_S ( munch p ) s = ~ > [ ( takeWhile p s , dropWhile p s ) ] > > prop_Munch1 p s = > readP_to_S ( munch1 p ) s = ~ > [ ( res , s ' ) | let ( res , s ' ) = ( takeWhile p s , dropWhile p s ) , not ( null res ) ] > > prop_Choice ps s = > readP_to_S ( choice ps ) s = ~. > readP_to_S ( foldr ( + + + ) ) s > > prop_ReadS r s = > readP_to_S ( readS_to_P r ) s = ~. r s The following are QuickCheck specifications of what the combinators do. These can be seen as formal specifications of the behavior of the combinators. We use bags to give semantics to the combinators. > type Bag a = [a] Equality on bags does not care about the order of elements. > (=~) :: Ord a => Bag a -> Bag a -> Bool > xs =~ ys = sort xs == sort ys A special equality operator to avoid unresolved overloading when testing the properties. > (=~.) :: Bag (Int,String) -> Bag (Int,String) -> Bool > (=~.) = (=~) Here follow the properties: > prop_Get_Nil = > readP_to_S get [] =~ [] > > prop_Get_Cons c s = > readP_to_S get (c:s) =~ [(c,s)] > > prop_Look s = > readP_to_S look s =~ [(s,s)] > > prop_Fail s = > readP_to_S pfail s =~. [] > > prop_Return x s = > readP_to_S (return x) s =~. [(x,s)] > > prop_Bind p k s = > readP_to_S (p >>= k) s =~. > [ ys'' > | (x,s') <- readP_to_S p s > , ys'' <- readP_to_S (k (x::Int)) s' > ] > > prop_Plus p q s = > readP_to_S (p +++ q) s =~. > (readP_to_S p s ++ readP_to_S q s) > > prop_LeftPlus p q s = > readP_to_S (p <++ q) s =~. > (readP_to_S p s +<+ readP_to_S q s) > where > [] +<+ ys = ys > xs +<+ _ = xs > > prop_Gather s = > forAll readPWithoutReadS $ \p -> > readP_to_S (gather p) s =~ > [ ((pre,x::Int),s') > | (x,s') <- readP_to_S p s > , let pre = take (length s - length s') s > ] > > prop_String_Yes this s = > readP_to_S (string this) (this ++ s) =~ > [(this,s)] > > prop_String_Maybe this s = > readP_to_S (string this) s =~ > [(this, drop (length this) s) | this `isPrefixOf` s] > > prop_Munch p s = > readP_to_S (munch p) s =~ > [(takeWhile p s, dropWhile p s)] > > prop_Munch1 p s = > readP_to_S (munch1 p) s =~ > [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)] > > prop_Choice ps s = > readP_to_S (choice ps) s =~. > readP_to_S (foldr (+++) pfail ps) s > > prop_ReadS r s = > readP_to_S (readS_to_P r) s =~. r s -}
58bba20f1202a3b4903d7fa193f0c5212be8d23e0647fbd4446bdcaac53c73b7
johnlawrenceaspden/hobby-code
naivebayes2.clj
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def new-guy (make-space-bar-patron)) (reduce disj new-guy [:martian :venusian]) #{:tall :green :fat} (let [m (* 3055/10002 2439/3056 601/3056 v (* 6947/10002 884/1737 (probability :green :venusian 1 1) ; 169/579 5629/6948 ) ; 1460520058387/17472902391702 ] [ 0.29015476 0.70984524 ] 70 % chance he 's a venusian too # { : tall : green : : fat } (defn classify [characteristics] (let [m (apply * (probability :martian nil 1 1) (for [i characteristics] (probability i :martian 1 1))) v (apply * (probability :venusian nil 1 1) (for [i characteristics] (probability i :venusian 1 1)))] [ (float (/ m (+ m v))) (float (/ v (+ m v))) ])) (def classified (for [i (range 100)] (let [p (make-space-bar-patron)] [(classify (reduce disj p [:martian :venusian])) p]))) (def sorted-classified (sort (fn [a b] (< (ffirst a) (ffirst b))) classified)) (def confidence-classes (partition-by first sorted-classified)) (partition-by identity (map (fn [x] (if ((second x) :martian) ['m (first (first x))] ['v (second (first x))])) sorted-classified)) (let [c (second confidence-classes) mvlist (map (fn [x] (if ((second x) :martian) 'm 'v)) c)] [(ffirst c) (sort mvlist) (frequencies mvlist)] ) [[0.040880386 0.9591196] (m v v v v v v v v v v v v v v v v v v v) {v 19, m 1}] (map (fn [c] (let [mvlist (map (fn [x] (if ((second x) :martian) 'm 'v)) c)] [(ffirst c) (sort mvlist) (frequencies mvlist)] )) confidence-classes) ([[0.017495114 0.9825049] (v v v v v v v v v v v v v v) {v 14}] [[0.040880386 0.9591196] (m v v v v v v v v v v v v v v v v v v v) {v 19, m 1}] [[0.14585963 0.85414034] (m m v v v v v v v v) {v 8, m 2}] [[0.23688416 0.7631158] (m m v v v v v v v v v v) {v 10, m 2}] [[0.29015476 0.70984524] (m m m v v v v v v v v v v) {v 10, m 3}] [[0.42628604 0.57371396] (m m m m v v v v) {m 4, v 4}] [[0.74855006 0.25144994] (m m m m m v) {v 1, m 5}] [[0.8769342 0.123065844] (m m m m m m m m m m m m m m m v v) {m 15, v 2}])
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/naivebayes2.clj
clojure
169/579 1460520058387/17472902391702
(def new-guy (make-space-bar-patron)) (reduce disj new-guy [:martian :venusian]) #{:tall :green :fat} (let [m (* 3055/10002 2439/3056 601/3056 v (* 6947/10002 884/1737 5629/6948 ] [ 0.29015476 0.70984524 ] 70 % chance he 's a venusian too # { : tall : green : : fat } (defn classify [characteristics] (let [m (apply * (probability :martian nil 1 1) (for [i characteristics] (probability i :martian 1 1))) v (apply * (probability :venusian nil 1 1) (for [i characteristics] (probability i :venusian 1 1)))] [ (float (/ m (+ m v))) (float (/ v (+ m v))) ])) (def classified (for [i (range 100)] (let [p (make-space-bar-patron)] [(classify (reduce disj p [:martian :venusian])) p]))) (def sorted-classified (sort (fn [a b] (< (ffirst a) (ffirst b))) classified)) (def confidence-classes (partition-by first sorted-classified)) (partition-by identity (map (fn [x] (if ((second x) :martian) ['m (first (first x))] ['v (second (first x))])) sorted-classified)) (let [c (second confidence-classes) mvlist (map (fn [x] (if ((second x) :martian) 'm 'v)) c)] [(ffirst c) (sort mvlist) (frequencies mvlist)] ) [[0.040880386 0.9591196] (m v v v v v v v v v v v v v v v v v v v) {v 19, m 1}] (map (fn [c] (let [mvlist (map (fn [x] (if ((second x) :martian) 'm 'v)) c)] [(ffirst c) (sort mvlist) (frequencies mvlist)] )) confidence-classes) ([[0.017495114 0.9825049] (v v v v v v v v v v v v v v) {v 14}] [[0.040880386 0.9591196] (m v v v v v v v v v v v v v v v v v v v) {v 19, m 1}] [[0.14585963 0.85414034] (m m v v v v v v v v) {v 8, m 2}] [[0.23688416 0.7631158] (m m v v v v v v v v v v) {v 10, m 2}] [[0.29015476 0.70984524] (m m m v v v v v v v v v v) {v 10, m 3}] [[0.42628604 0.57371396] (m m m m v v v v) {m 4, v 4}] [[0.74855006 0.25144994] (m m m m m v) {v 1, m 5}] [[0.8769342 0.123065844] (m m m m m m m m m m m m m m m v v) {m 15, v 2}])
6e79cad3d9d47a187cc121ca279c2e28ddd08cc8c378311dd5845b7e098019a5
5HT/ant
ListBuilder.mli
(* A |builder 'a| can be used to create a |list 'a| by successively appending elements to the end of the list. *) type builder 'a; |make ( ) | creates a new list builder . O(1 ) value make : unit -> builder 'a; (* |is_empty <b>| checks whether the current list is still empty. O(1), pure *) value is_empty : builder 'a -> bool; |clear < b>| empties the builder . O(1 ) , non - pure value clear : builder 'a -> unit; (* |add <b> <x>| adds the element <x> at the end of the current list. |add_first <b> <x>| adds <x> to the front. O(1), non-pure *) value add : builder 'a -> 'a -> unit; value add_first : builder 'a -> 'a -> unit; (* |add_list <b> <x>| adds all elements of the list <x> to the end of the current list. O(x), non-pure *) value add_list : builder 'a -> list 'a -> unit; |append < b1 > < b2>| appends the contents of < b2 > to < b1 > and resets < b2 > . ) , non - pure O(1), non-pure *) value append : builder 'a -> builder 'a -> unit; |get < b>| returns the current list and resets the builder . O(1 ) , non - pure value get : builder 'a -> list 'a; |get_last < b>| returns the last element of the current list . ) , pure value get_last : builder 'a -> 'a; (* |replace_last <b> <x>| replaces the last element of the current list with <x>. *) value replace_last : builder 'a -> 'a -> unit;
null
https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/Tools/ListBuilder.mli
ocaml
A |builder 'a| can be used to create a |list 'a| by successively appending elements to the end of the list. |is_empty <b>| checks whether the current list is still empty. O(1), pure |add <b> <x>| adds the element <x> at the end of the current list. |add_first <b> <x>| adds <x> to the front. O(1), non-pure |add_list <b> <x>| adds all elements of the list <x> to the end of the current list. O(x), non-pure |replace_last <b> <x>| replaces the last element of the current list with <x>.
type builder 'a; |make ( ) | creates a new list builder . O(1 ) value make : unit -> builder 'a; value is_empty : builder 'a -> bool; |clear < b>| empties the builder . O(1 ) , non - pure value clear : builder 'a -> unit; value add : builder 'a -> 'a -> unit; value add_first : builder 'a -> 'a -> unit; value add_list : builder 'a -> list 'a -> unit; |append < b1 > < b2>| appends the contents of < b2 > to < b1 > and resets < b2 > . ) , non - pure O(1), non-pure *) value append : builder 'a -> builder 'a -> unit; |get < b>| returns the current list and resets the builder . O(1 ) , non - pure value get : builder 'a -> list 'a; |get_last < b>| returns the last element of the current list . ) , pure value get_last : builder 'a -> 'a; value replace_last : builder 'a -> 'a -> unit;
82dc5555bb318681339c5992e31ce114535af6bdcac67d2c9d539b0ac47ed232
jeroanan/rkt-coreutils
tty.rkt
#lang s-exp "util/program/repl-program.rkt" Copyright 2020 ; See COPYING for details (provide tty) (require "libc/unistd.rkt") (define tty (λ () (displayln (get-ttyname))))
null
https://raw.githubusercontent.com/jeroanan/rkt-coreutils/571629d1e2562c557ba258b31ce454add2e93dd9/src/repl/tty.rkt
racket
See COPYING for details
#lang s-exp "util/program/repl-program.rkt" Copyright 2020 (provide tty) (require "libc/unistd.rkt") (define tty (λ () (displayln (get-ttyname))))
191c6f61b4d057a6e15e85b7fd99fbdf489fcc41fcfc8504763636a2cb2abe4b
project-oak/hafnium-verification
Maven.ml
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module CLOpt = CommandLineOption module L = Logging let infer_profile_name = "infer-capture" let infer_profile = lazy (* indented so that users may copy it into their projects if they want to *) (Printf.sprintf {| <profile> <id>%s</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <compilerId>javac</compilerId> <forceJavacCompilerUse>true</forceJavacCompilerUse> <fork>true</fork> <executable>%s</executable> %s </configuration> </plugin> </plugins> </build> </profile>|} infer_profile_name (Config.bin_dir ^/ InferCommand.infer_exe_name) ( match Config.java_version with | Some version when version >= 9 -> Printf.sprintf "<release>%d</release>" version | _ -> "" )) let pom_worklist = ref [CLOpt.init_work_dir] let add_infer_profile_to_xml dir maven_xml infer_xml = let copy xml_in xml_out = Xmlm.output xml_out (Xmlm.input xml_in) in (* whether we ever found a <profiles> tag *) let found_profiles_tag = ref false in (* whether there already is an infer profile --this will always be true at the end *) let found_infer_profile = ref false in Process an xml document from the root . Assume the has already been handled . let rec process_root xml_in xml_out = process xml_in xml_out [] and insert_infer_profile xml_out = let infer_xml = Xmlm.make_input ~strip:false (`String (0, Lazy.force infer_profile)) in Xmlm.input infer_xml |> ignore ; skip dummy process_root infer_xml xml_out and process xml_in xml_out tag_stack = let elt_in = Xmlm.input xml_in in match elt_in with | `El_start tag -> Xmlm.output xml_out elt_in ; let tag_name = snd (fst tag) in if String.equal tag_name "profiles" then found_profiles_tag := true ; process xml_in xml_out (tag_name :: tag_stack) | `El_end -> ( ( match tag_stack with | "profiles" :: _ when not !found_infer_profile -> found the < /profiles > tag but no infer profile found , add one insert_infer_profile xml_out | [_] when not !found_profiles_tag -> (* closing the root tag but no <profiles> tag found, add <profiles>[infer profile]</profiles> *) Xmlm.output xml_out (`El_start (("", "profiles"), [])) ; found_profiles_tag := true ; (* do not add <profiles> again *) insert_infer_profile xml_out ; Xmlm.output xml_out `El_end | _ -> () ) ; Xmlm.output xml_out elt_in ; match tag_stack with | _ :: parent :: tl -> process xml_in xml_out (parent :: tl) | [_] -> closing the first tag , we 're done () | [] -> L.(die UserError) "ill-formed xml" ) | `Data data -> Xmlm.output xml_out elt_in ; ( match tag_stack with | "id" :: "profile" :: "profiles" :: _ when String.equal data infer_profile_name -> L.(debug Capture Quiet) "Found infer profile, not adding one@." ; found_infer_profile := true | "module" :: "modules" :: _ -> let abs_data = dir ^/ data in L.(debug Capture Quiet) "Adding maven module %s@." abs_data ; pom_worklist := abs_data :: !pom_worklist | _ -> () ) ; process xml_in xml_out tag_stack | `Dtd _ -> already processed the node assert false in let process_document () = process ` Dtd ; if present , it is always the first node ( match Xmlm.peek maven_xml with | `Dtd _ -> copy maven_xml infer_xml | _ -> Xmlm.output infer_xml (`Dtd None) ) ; process_root maven_xml infer_xml ; Xmlm.eoi maven_xml |> ignore ; if not (Xmlm.eoi maven_xml) then L.(die UserError) "More than one document" in process_document () let add_infer_profile mvn_pom infer_pom = let ic = In_channel.create mvn_pom in let with_oc out_chan = let with_ic () = let xml_in = Xmlm.make_input ~strip:false (`Channel ic) ~ns:(fun ns -> Some ns) (* be generous with namespaces *) in let xml_out = Xmlm.make_output ~nl:true (`Channel out_chan) ~ns_prefix:(fun prefix -> Some prefix) (* be generous with namespaces *) in add_infer_profile_to_xml (Filename.dirname mvn_pom) xml_in xml_out in protect ~f:with_ic ~finally:(fun () -> In_channel.close ic) in try Utils.with_file_out infer_pom ~f:with_oc with Xmlm.Error ((line, col), error) -> L.die ExternalError "%s:%d:%d: ERROR: %s" mvn_pom line col (Xmlm.error_message error) let add_profile_to_pom_in_directory dir = Even though there is a " -f " command - line arguments to change the config file Maven reads from , this is unreliable and Maven pretty much always reads from " pom.xml " anyway . So , we replace " pom.xml " with a version holding a special profile for infer capture , then put the original back in place . this is unreliable and Maven pretty much always reads from "pom.xml" anyway. So, we replace "pom.xml" with a version holding a special profile for infer capture, then put the original back in place. *) let maven_pom_path = dir ^/ "pom.xml" in let saved_pom_path = dir ^/ "pom.xml.infer-orig" in let infer_pom_path = dir ^/ "pom.xml.infer" in add_infer_profile maven_pom_path infer_pom_path ; Unix.rename ~src:maven_pom_path ~dst:saved_pom_path ; Epilogues.register ~f:(fun () -> Unix.rename ~src:saved_pom_path ~dst:maven_pom_path) ~description:"restoring Maven's pom.xml to its original state" ; Unix.rename ~src:infer_pom_path ~dst:maven_pom_path ; if Config.debug_mode then Epilogues.register ~f:(fun () -> Unix.rename ~src:maven_pom_path ~dst:infer_pom_path) ~description:"saving infer's pom.xml" let capture ~prog ~args = while not (List.is_empty !pom_worklist) do let pom = List.hd_exn !pom_worklist in pom_worklist := List.tl_exn !pom_worklist ; add_profile_to_pom_in_directory pom done ; let extra_args = ["-P"; infer_profile_name] in let capture_args = args @ extra_args in L.(debug Capture Quiet) "Running maven capture:@\n%s %s@." prog (String.concat ~sep:" " (List.map ~f:(Printf.sprintf "'%s'") capture_args)) ; let children infer processes know that they are spawned by Maven Unix.fork_exec ~prog ~argv:(prog :: capture_args) ~env:Config.env_inside_maven () |> Unix.waitpid |> function | Ok () -> () | Error _ as status -> L.(die UserError) "*** Maven command failed:@\n*** %s@\n*** %s@\n" (String.concat ~sep:" " (prog :: capture_args)) (Unix.Exit_or_signal.to_string_hum status)
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/integration/Maven.ml
ocaml
indented so that users may copy it into their projects if they want to whether we ever found a <profiles> tag whether there already is an infer profile --this will always be true at the end closing the root tag but no <profiles> tag found, add <profiles>[infer profile]</profiles> do not add <profiles> again be generous with namespaces be generous with namespaces
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module CLOpt = CommandLineOption module L = Logging let infer_profile_name = "infer-capture" let infer_profile = lazy (Printf.sprintf {| <profile> <id>%s</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <compilerId>javac</compilerId> <forceJavacCompilerUse>true</forceJavacCompilerUse> <fork>true</fork> <executable>%s</executable> %s </configuration> </plugin> </plugins> </build> </profile>|} infer_profile_name (Config.bin_dir ^/ InferCommand.infer_exe_name) ( match Config.java_version with | Some version when version >= 9 -> Printf.sprintf "<release>%d</release>" version | _ -> "" )) let pom_worklist = ref [CLOpt.init_work_dir] let add_infer_profile_to_xml dir maven_xml infer_xml = let copy xml_in xml_out = Xmlm.output xml_out (Xmlm.input xml_in) in let found_profiles_tag = ref false in let found_infer_profile = ref false in Process an xml document from the root . Assume the has already been handled . let rec process_root xml_in xml_out = process xml_in xml_out [] and insert_infer_profile xml_out = let infer_xml = Xmlm.make_input ~strip:false (`String (0, Lazy.force infer_profile)) in Xmlm.input infer_xml |> ignore ; skip dummy process_root infer_xml xml_out and process xml_in xml_out tag_stack = let elt_in = Xmlm.input xml_in in match elt_in with | `El_start tag -> Xmlm.output xml_out elt_in ; let tag_name = snd (fst tag) in if String.equal tag_name "profiles" then found_profiles_tag := true ; process xml_in xml_out (tag_name :: tag_stack) | `El_end -> ( ( match tag_stack with | "profiles" :: _ when not !found_infer_profile -> found the < /profiles > tag but no infer profile found , add one insert_infer_profile xml_out | [_] when not !found_profiles_tag -> Xmlm.output xml_out (`El_start (("", "profiles"), [])) ; found_profiles_tag := true ; insert_infer_profile xml_out ; Xmlm.output xml_out `El_end | _ -> () ) ; Xmlm.output xml_out elt_in ; match tag_stack with | _ :: parent :: tl -> process xml_in xml_out (parent :: tl) | [_] -> closing the first tag , we 're done () | [] -> L.(die UserError) "ill-formed xml" ) | `Data data -> Xmlm.output xml_out elt_in ; ( match tag_stack with | "id" :: "profile" :: "profiles" :: _ when String.equal data infer_profile_name -> L.(debug Capture Quiet) "Found infer profile, not adding one@." ; found_infer_profile := true | "module" :: "modules" :: _ -> let abs_data = dir ^/ data in L.(debug Capture Quiet) "Adding maven module %s@." abs_data ; pom_worklist := abs_data :: !pom_worklist | _ -> () ) ; process xml_in xml_out tag_stack | `Dtd _ -> already processed the node assert false in let process_document () = process ` Dtd ; if present , it is always the first node ( match Xmlm.peek maven_xml with | `Dtd _ -> copy maven_xml infer_xml | _ -> Xmlm.output infer_xml (`Dtd None) ) ; process_root maven_xml infer_xml ; Xmlm.eoi maven_xml |> ignore ; if not (Xmlm.eoi maven_xml) then L.(die UserError) "More than one document" in process_document () let add_infer_profile mvn_pom infer_pom = let ic = In_channel.create mvn_pom in let with_oc out_chan = let with_ic () = let xml_in = Xmlm.make_input ~strip:false (`Channel ic) ~ns:(fun ns -> Some ns) in let xml_out = Xmlm.make_output ~nl:true (`Channel out_chan) ~ns_prefix:(fun prefix -> Some prefix) in add_infer_profile_to_xml (Filename.dirname mvn_pom) xml_in xml_out in protect ~f:with_ic ~finally:(fun () -> In_channel.close ic) in try Utils.with_file_out infer_pom ~f:with_oc with Xmlm.Error ((line, col), error) -> L.die ExternalError "%s:%d:%d: ERROR: %s" mvn_pom line col (Xmlm.error_message error) let add_profile_to_pom_in_directory dir = Even though there is a " -f " command - line arguments to change the config file Maven reads from , this is unreliable and Maven pretty much always reads from " pom.xml " anyway . So , we replace " pom.xml " with a version holding a special profile for infer capture , then put the original back in place . this is unreliable and Maven pretty much always reads from "pom.xml" anyway. So, we replace "pom.xml" with a version holding a special profile for infer capture, then put the original back in place. *) let maven_pom_path = dir ^/ "pom.xml" in let saved_pom_path = dir ^/ "pom.xml.infer-orig" in let infer_pom_path = dir ^/ "pom.xml.infer" in add_infer_profile maven_pom_path infer_pom_path ; Unix.rename ~src:maven_pom_path ~dst:saved_pom_path ; Epilogues.register ~f:(fun () -> Unix.rename ~src:saved_pom_path ~dst:maven_pom_path) ~description:"restoring Maven's pom.xml to its original state" ; Unix.rename ~src:infer_pom_path ~dst:maven_pom_path ; if Config.debug_mode then Epilogues.register ~f:(fun () -> Unix.rename ~src:maven_pom_path ~dst:infer_pom_path) ~description:"saving infer's pom.xml" let capture ~prog ~args = while not (List.is_empty !pom_worklist) do let pom = List.hd_exn !pom_worklist in pom_worklist := List.tl_exn !pom_worklist ; add_profile_to_pom_in_directory pom done ; let extra_args = ["-P"; infer_profile_name] in let capture_args = args @ extra_args in L.(debug Capture Quiet) "Running maven capture:@\n%s %s@." prog (String.concat ~sep:" " (List.map ~f:(Printf.sprintf "'%s'") capture_args)) ; let children infer processes know that they are spawned by Maven Unix.fork_exec ~prog ~argv:(prog :: capture_args) ~env:Config.env_inside_maven () |> Unix.waitpid |> function | Ok () -> () | Error _ as status -> L.(die UserError) "*** Maven command failed:@\n*** %s@\n*** %s@\n" (String.concat ~sep:" " (prog :: capture_args)) (Unix.Exit_or_signal.to_string_hum status)
2ae933d9d3fce1aa597195dce556267e760d70d92775b7acf7cac8de76e8bb8c
vehicle-lang/vehicle
Token.hs
module Vehicle.Syntax.Parse.Token where import Data.Coerce (Coercible, coerce) import Data.Function (on) import Data.Text (Text) import Data.Text qualified as T | Position tokens in BNFC generated grammars are represented by a pair of a -- position and the text token. newtype Token = Tk ((Int, Int), Text) deriving (Eq, Ord, Show, Read) pattern Token :: (Int, Int) -> Text -> Token pattern Token {pos, sym} = Tk (pos, sym) type TokenConstructor a = ((Int, Int), Text) -> a mkToken :: TokenConstructor a -> Text -> a mkToken mk s = mk ((0, 0), s) -- | Constraint for newtypes which are /position tokens/. Depends on the fact that any /position token/ generated by BNFC with @--text@ will be a newtype -- wrapping '(Position, Name)', and hence all are coercible to it. This breaks -- if the @--text@ option is not passed, or if the token is not marked with the -- @position@ keyword. type IsToken a = Coercible a Token -- | Convert from 'Token' to an arbitrary newtype via 'Coercible'. toToken :: IsToken a => a -> Token toToken = coerce -- | Convert to 'Token' from an arbitrary newtype via 'Coercible'. fromToken :: IsToken a => Token -> a fromToken = coerce -- | Get the symbol of a token. tkSymbol :: IsToken a => a -> Text tkSymbol = sym . toToken -- | Get the length of a token. tkLength :: IsToken a => a -> Int tkLength = T.length . tkSymbol | Compare the text portion of any two position tokens . tkEq :: IsToken a => a -> a -> Bool tkEq = (==) `on` toToken -- | Get the starting position of a token. tkLocation :: IsToken a => a -> (Int, Int) tkLocation = pos . toToken -- | Change name of a token. tkUpdateText :: IsToken a => Text -> a -> a tkUpdateText txt tk = fromToken (Token {pos = tkLocation tk, sym = txt})
null
https://raw.githubusercontent.com/vehicle-lang/vehicle/ca99b8da9e5aabde2c94b758bb4141fbe53ebed5/vehicle-syntax/src/Vehicle/Syntax/Parse/Token.hs
haskell
position and the text token. | Constraint for newtypes which are /position tokens/. Depends on the fact text@ will be a newtype wrapping '(Position, Name)', and hence all are coercible to it. This breaks if the @--text@ option is not passed, or if the token is not marked with the @position@ keyword. | Convert from 'Token' to an arbitrary newtype via 'Coercible'. | Convert to 'Token' from an arbitrary newtype via 'Coercible'. | Get the symbol of a token. | Get the length of a token. | Get the starting position of a token. | Change name of a token.
module Vehicle.Syntax.Parse.Token where import Data.Coerce (Coercible, coerce) import Data.Function (on) import Data.Text (Text) import Data.Text qualified as T | Position tokens in BNFC generated grammars are represented by a pair of a newtype Token = Tk ((Int, Int), Text) deriving (Eq, Ord, Show, Read) pattern Token :: (Int, Int) -> Text -> Token pattern Token {pos, sym} = Tk (pos, sym) type TokenConstructor a = ((Int, Int), Text) -> a mkToken :: TokenConstructor a -> Text -> a mkToken mk s = mk ((0, 0), s) type IsToken a = Coercible a Token toToken :: IsToken a => a -> Token toToken = coerce fromToken :: IsToken a => Token -> a fromToken = coerce tkSymbol :: IsToken a => a -> Text tkSymbol = sym . toToken tkLength :: IsToken a => a -> Int tkLength = T.length . tkSymbol | Compare the text portion of any two position tokens . tkEq :: IsToken a => a -> a -> Bool tkEq = (==) `on` toToken tkLocation :: IsToken a => a -> (Int, Int) tkLocation = pos . toToken tkUpdateText :: IsToken a => Text -> a -> a tkUpdateText txt tk = fromToken (Token {pos = tkLocation tk, sym = txt})
60413b561b99bc6f3e0dac663f7fa752195790e5f06d47983fa163fe58380250
jaredly/reason-language-server
lambda.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 Misc open Path open Asttypes type compile_time_constant = | Big_endian | Word_size | Ostype_unix | Ostype_win32 | Ostype_cygwin type loc_kind = | Loc_FILE | Loc_LINE | Loc_MODULE | Loc_LOC | Loc_POS type primitive = Pidentity | Pignore | Prevapply of Location.t | Pdirapply of Location.t | Ploc of loc_kind (* Globals *) | Pgetglobal of Ident.t | Psetglobal of Ident.t (* Operations on heap blocks *) | Pmakeblock of int * mutable_flag | Pfield of int | Psetfield of int * bool | Pfloatfield of int | Psetfloatfield of int | Pduprecord of Types.record_representation * int Force lazy values | Plazyforce (* External call *) | Pccall of Primitive.description (* Exceptions *) | Praise of raise_kind Boolean operations | Psequand | Psequor | Pnot Integer operations | Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp of comparison | Poffsetint of int | Poffsetref of int (* Float operations *) | Pintoffloat | Pfloatofint | Pnegfloat | Pabsfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Pfloatcomp of comparison (* String operations *) | Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets (* Array operations *) | Pmakearray of array_kind | Parraylength of array_kind | Parrayrefu of array_kind | Parraysetu of array_kind | Parrayrefs of array_kind | Parraysets of array_kind (* Test if the argument is a block or an immediate integer *) | Pisint (* Test if the (integer) argument is outside an interval *) | Pisout Bitvect operations | Pbittest Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t ) | Pbintofint of boxed_integer | Pintofbint of boxed_integer | Pcvtbint of boxed_integer (*source*) * boxed_integer (*destination*) | Pnegbint of boxed_integer | Paddbint of boxed_integer | Psubbint of boxed_integer | Pmulbint of boxed_integer | Pdivbint of boxed_integer | Pmodbint of boxed_integer | Pandbint of boxed_integer | Porbint of boxed_integer | Pxorbint of boxed_integer | Plslbint of boxed_integer | Plsrbint of boxed_integer | Pasrbint of boxed_integer | Pbintcomp of boxed_integer * comparison (* Operations on big arrays: (unsafe, #dimensions, kind, layout) *) | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout (* size of the nth dimension of a big array *) | Pbigarraydim of int load / set 16,32,64 bits from a string : ( unsafe ) | Pstring_load_16 of bool | Pstring_load_32 of bool | Pstring_load_64 of bool | Pstring_set_16 of bool | Pstring_set_32 of bool | Pstring_set_64 of bool load / set 16,32,64 bits from a ( char , int8_unsigned_elt , c_layout ) Bigarray . Array1.t : ( unsafe ) (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *) | Pbigstring_load_16 of bool | Pbigstring_load_32 of bool | Pbigstring_load_64 of bool | Pbigstring_set_16 of bool | Pbigstring_set_32 of bool | Pbigstring_set_64 of bool (* Compile time constants *) | Pctconst of compile_time_constant (* byte swap *) | Pbswap16 | Pbbswap of boxed_integer Integer to external pointer | Pint_as_pointer and comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge and array_kind = Pgenarray | Paddrarray | Pintarray | Pfloatarray and boxed_integer = Pnativeint | Pint32 | Pint64 and bigarray_kind = Pbigarray_unknown | Pbigarray_float32 | Pbigarray_float64 | Pbigarray_sint8 | Pbigarray_uint8 | Pbigarray_sint16 | Pbigarray_uint16 | Pbigarray_int32 | Pbigarray_int64 | Pbigarray_caml_int | Pbigarray_native_int | Pbigarray_complex32 | Pbigarray_complex64 and bigarray_layout = Pbigarray_unknown_layout | Pbigarray_c_layout | Pbigarray_fortran_layout and raise_kind = | Raise_regular | Raise_reraise | Raise_notrace type structured_constant = Const_base of constant | Const_pointer of int | Const_block of int * structured_constant list | Const_float_array of string list | Const_immstring of string type function_kind = Curried | Tupled type let_kind = Strict | Alias | StrictOpt | Variable type meth_kind = Self | Public | Cached type shared_code = (int * int) list type lambda = Lvar of Ident.t | Lconst of structured_constant | Lapply of lambda * lambda list * Location.t | Lfunction of function_kind * Ident.t list * lambda | Llet of let_kind * Ident.t * lambda * lambda | Lletrec of (Ident.t * lambda) list * lambda | Lprim of primitive * lambda list | Lswitch of lambda * lambda_switch | Lstringswitch of lambda * (string * lambda) list * lambda option | Lstaticraise of int * lambda list | Lstaticcatch of lambda * (int * Ident.t list) * lambda | Ltrywith of lambda * Ident.t * lambda | Lifthenelse of lambda * lambda * lambda | Lsequence of lambda * lambda | Lwhile of lambda * lambda | Lfor of Ident.t * lambda * lambda * direction_flag * lambda | Lassign of Ident.t * lambda | Lsend of meth_kind * lambda * lambda * lambda list * Location.t | Levent of lambda * lambda_event | Lifused of Ident.t * lambda and lambda_switch = { sw_numconsts: int; sw_consts: (int * lambda) list; sw_numblocks: int; sw_blocks: (int * lambda) list; sw_failaction : lambda option} and lambda_event = { lev_loc: Location.t; lev_kind: lambda_event_kind; lev_repr: int ref option; lev_env: Env.summary } and lambda_event_kind = Lev_before | Lev_after of Types.type_expr | Lev_function let const_unit = Const_pointer 0 let lambda_unit = Lconst const_unit (* Build sharing keys *) (* Those keys are later compared with Pervasives.compare. For that reason, they should not include cycles. *) exception Not_simple let max_raw = 32 let make_key e = let count = ref 0 (* Used for controling size *) and make_key = Ident.make_key_generator () in (* make_key is used for normalizing let-bound variables *) let rec tr_rec env e = incr count ; if !count > max_raw then raise Not_simple ; (* Too big ! *) match e with | Lvar id -> begin try Ident.find_same id env with Not_found -> e end | Lconst (Const_base (Const_string _)|Const_float_array _) -> (* Mutable constants are not shared *) raise Not_simple | Lconst _ -> e | Lapply (e,es,loc) -> Lapply (tr_rec env e,tr_recs env es,Location.none) | Llet (Alias,x,ex,e) -> (* Ignore aliases -> substitute *) let ex = tr_rec env ex in tr_rec (Ident.add x ex env) e | Llet (str,x,ex,e) -> (* Because of side effects, keep other lets with normalized names *) let ex = tr_rec env ex in let y = make_key x in Llet (str,y,ex,tr_rec (Ident.add x (Lvar y) env) e) | Lprim (p,es) -> Lprim (p,tr_recs env es) | Lswitch (e,sw) -> Lswitch (tr_rec env e,tr_sw env sw) | Lstringswitch (e,sw,d) -> Lstringswitch (tr_rec env e, List.map (fun (s,e) -> s,tr_rec env e) sw, tr_opt env d) | Lstaticraise (i,es) -> Lstaticraise (i,tr_recs env es) | Lstaticcatch (e1,xs,e2) -> Lstaticcatch (tr_rec env e1,xs,tr_rec env e2) | Ltrywith (e1,x,e2) -> Ltrywith (tr_rec env e1,x,tr_rec env e2) | Lifthenelse (cond,ifso,ifnot) -> Lifthenelse (tr_rec env cond,tr_rec env ifso,tr_rec env ifnot) | Lsequence (e1,e2) -> Lsequence (tr_rec env e1,tr_rec env e2) | Lassign (x,e) -> Lassign (x,tr_rec env e) | Lsend (m,e1,e2,es,loc) -> Lsend (m,tr_rec env e1,tr_rec env e2,tr_recs env es,Location.none) | Lifused (id,e) -> Lifused (id,tr_rec env e) | Lletrec _|Lfunction _ | Lfor _ | Lwhile _ Beware : ( PR#6412 ) the event argument to Levent may include cyclic structure of type Type.typexpr may include cyclic structure of type Type.typexpr *) | Levent _ -> raise Not_simple and tr_recs env es = List.map (tr_rec env) es and tr_sw env sw = { sw with sw_consts = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_consts ; sw_blocks = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_blocks ; sw_failaction = tr_opt env sw.sw_failaction ; } and tr_opt env = function | None -> None | Some e -> Some (tr_rec env e) in try Some (tr_rec Ident.empty e) with Not_simple -> None (***************) let name_lambda strict arg fn = match arg with Lvar id -> fn id | _ -> let id = Ident.create "let" in Llet(strict, id, arg, fn id) let name_lambda_list args fn = let rec name_list names = function [] -> fn (List.rev names) | (Lvar id as arg) :: rem -> name_list (arg :: names) rem | arg :: rem -> let id = Ident.create "let" in Llet(Strict, id, arg, name_list (Lvar id :: names) rem) in name_list [] args let iter_opt f = function | None -> () | Some e -> f e let iter f = function Lvar _ | Lconst _ -> () | Lapply(fn, args, _) -> f fn; List.iter f args | Lfunction(kind, params, body) -> f body | Llet(str, id, arg, body) -> f arg; f body | Lletrec(decl, body) -> f body; List.iter (fun (id, exp) -> f exp) decl | Lprim(p, args) -> List.iter f args | Lswitch(arg, sw) -> f arg; List.iter (fun (key, case) -> f case) sw.sw_consts; List.iter (fun (key, case) -> f case) sw.sw_blocks; iter_opt f sw.sw_failaction | Lstringswitch (arg,cases,default) -> f arg ; List.iter (fun (_,act) -> f act) cases ; iter_opt f default | Lstaticraise (_,args) -> List.iter f args | Lstaticcatch(e1, (_,vars), e2) -> f e1; f e2 | Ltrywith(e1, exn, e2) -> f e1; f e2 | Lifthenelse(e1, e2, e3) -> f e1; f e2; f e3 | Lsequence(e1, e2) -> f e1; f e2 | Lwhile(e1, e2) -> f e1; f e2 | Lfor(v, e1, e2, dir, e3) -> f e1; f e2; f e3 | Lassign(id, e) -> f e | Lsend (k, met, obj, args, _) -> List.iter f (met::obj::args) | Levent (lam, evt) -> f lam | Lifused (v, e) -> f e module IdentSet = Set.Make(struct type t = Ident.t let compare = compare end) let free_ids get l = let fv = ref IdentSet.empty in let rec free l = iter free l; fv := List.fold_right IdentSet.add (get l) !fv; match l with Lfunction(kind, params, body) -> List.iter (fun param -> fv := IdentSet.remove param !fv) params | Llet(str, id, arg, body) -> fv := IdentSet.remove id !fv | Lletrec(decl, body) -> List.iter (fun (id, exp) -> fv := IdentSet.remove id !fv) decl | Lstaticcatch(e1, (_,vars), e2) -> List.iter (fun id -> fv := IdentSet.remove id !fv) vars | Ltrywith(e1, exn, e2) -> fv := IdentSet.remove exn !fv | Lfor(v, e1, e2, dir, e3) -> fv := IdentSet.remove v !fv | Lassign(id, e) -> fv := IdentSet.add id !fv | Lvar _ | Lconst _ | Lapply _ | Lprim _ | Lswitch _ | Lstringswitch _ | Lstaticraise _ | Lifthenelse _ | Lsequence _ | Lwhile _ | Lsend _ | Levent _ | Lifused _ -> () in free l; !fv let free_variables l = free_ids (function Lvar id -> [id] | _ -> []) l let free_methods l = free_ids (function Lsend(Self, Lvar meth, obj, _, _) -> [meth] | _ -> []) l (* Check if an action has a "when" guard *) let raise_count = ref 0 let next_raise_count () = incr raise_count ; !raise_count let negative_raise_count = ref 0 let next_negative_raise_count () = decr negative_raise_count ; !negative_raise_count (* Anticipated staticraise, for guards *) let staticfail = Lstaticraise (0,[]) let rec is_guarded = function | Lifthenelse( cond, body, Lstaticraise (0,[])) -> true | Llet(str, id, lam, body) -> is_guarded body | Levent(lam, ev) -> is_guarded lam | _ -> false let rec patch_guarded patch = function | Lifthenelse (cond, body, Lstaticraise (0,[])) -> Lifthenelse (cond, body, patch) | Llet(str, id, lam, body) -> Llet (str, id, lam, patch_guarded patch body) | Levent(lam, ev) -> Levent (patch_guarded patch lam, ev) | _ -> fatal_error "Lambda.patch_guarded" (* Translate an access path *) let rec transl_normal_path = function Pident id -> if Ident.global id then Lprim(Pgetglobal id, []) else Lvar id | Pdot(p, s, pos) -> Lprim(Pfield pos, [transl_normal_path p]) | Papply(p1, p2) -> fatal_error "Lambda.transl_path" (* Translation of value identifiers *) let transl_path ?(loc=Location.none) env path = transl_normal_path (Env.normalize_path (Some loc) env path) (* Compile a sequence of expressions *) let rec make_sequence fn = function [] -> lambda_unit | [x] -> fn x | x::rem -> let lam = fn x in Lsequence(lam, make_sequence fn rem) (* Apply a substitution to a lambda-term. Assumes that the bound variables of the lambda-term do not belong to the domain of the substitution. Assumes that the image of the substitution is out of reach of the bound variables of the lambda-term (no capture). *) let subst_lambda s lam = let rec subst = function Lvar id as l -> begin try Ident.find_same id s with Not_found -> l end | Lconst sc as l -> l | Lapply(fn, args, loc) -> Lapply(subst fn, List.map subst args, loc) | Lfunction(kind, params, body) -> Lfunction(kind, params, subst body) | Llet(str, id, arg, body) -> Llet(str, id, subst arg, subst body) | Lletrec(decl, body) -> Lletrec(List.map subst_decl decl, subst body) | Lprim(p, args) -> Lprim(p, List.map subst args) | Lswitch(arg, sw) -> Lswitch(subst arg, {sw with sw_consts = List.map subst_case sw.sw_consts; sw_blocks = List.map subst_case sw.sw_blocks; sw_failaction = subst_opt sw.sw_failaction; }) | Lstringswitch (arg,cases,default) -> Lstringswitch (subst arg,List.map subst_strcase cases,subst_opt default) | Lstaticraise (i,args) -> Lstaticraise (i, List.map subst args) | Lstaticcatch(e1, io, e2) -> Lstaticcatch(subst e1, io, subst e2) | Ltrywith(e1, exn, e2) -> Ltrywith(subst e1, exn, subst e2) | Lifthenelse(e1, e2, e3) -> Lifthenelse(subst e1, subst e2, subst e3) | Lsequence(e1, e2) -> Lsequence(subst e1, subst e2) | Lwhile(e1, e2) -> Lwhile(subst e1, subst e2) | Lfor(v, e1, e2, dir, e3) -> Lfor(v, subst e1, subst e2, dir, subst e3) | Lassign(id, e) -> Lassign(id, subst e) | Lsend (k, met, obj, args, loc) -> Lsend (k, subst met, subst obj, List.map subst args, loc) | Levent (lam, evt) -> Levent (subst lam, evt) | Lifused (v, e) -> Lifused (v, subst e) and subst_decl (id, exp) = (id, subst exp) and subst_case (key, case) = (key, subst case) and subst_strcase (key, case) = (key, subst case) and subst_opt = function | None -> None | Some e -> Some (subst e) in subst lam (* To let-bind expressions to variables *) let bind str var exp body = match exp with Lvar var' when Ident.same var var' -> body | _ -> Llet(str, var, exp, body) and commute_comparison = function | Ceq -> Ceq| Cneq -> Cneq | Clt -> Cgt | Cle -> Cge | Cgt -> Clt | Cge -> Cle and negate_comparison = function | Ceq -> Cneq| Cneq -> Ceq | Clt -> Cge | Cle -> Cgt | Cgt -> Cle | Cge -> Clt let raise_kind = function | Raise_regular -> "raise" | Raise_reraise -> "reraise" | Raise_notrace -> "raise_notrace" let lam_of_loc kind loc = let loc_start = loc.Location.loc_start in let (file, lnum, cnum) = Location.get_pos_info loc_start in let enum = loc.Location.loc_end.Lexing.pos_cnum - loc_start.Lexing.pos_cnum + cnum in match kind with | Loc_POS -> Lconst (Const_block (0, [ Const_immstring file; Const_base (Const_int lnum); Const_base (Const_int cnum); Const_base (Const_int enum); ])) | Loc_FILE -> Lconst (Const_immstring file) | Loc_MODULE -> let filename = Filename.basename file in let name = Env.get_unit_name () in let module_name = if name = "" then "//"^filename^"//" else name in Lconst (Const_immstring module_name) | Loc_LOC -> let loc = Printf.sprintf "File %S, line %d, characters %d-%d" file lnum cnum enum in Lconst (Const_immstring loc) | Loc_LINE -> Lconst (Const_base (Const_int lnum)) let reset () = raise_count := 0
null
https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/402/lambda.ml
ocaml
********************************************************************* OCaml ********************************************************************* Globals Operations on heap blocks External call Exceptions Float operations String operations Array operations Test if the argument is a block or an immediate integer Test if the (integer) argument is outside an interval source destination Operations on big arrays: (unsafe, #dimensions, kind, layout) size of the nth dimension of a big array Compile time constants byte swap Build sharing keys Those keys are later compared with Pervasives.compare. For that reason, they should not include cycles. Used for controling size make_key is used for normalizing let-bound variables Too big ! Mutable constants are not shared Ignore aliases -> substitute Because of side effects, keep other lets with normalized names ************* Check if an action has a "when" guard Anticipated staticraise, for guards Translate an access path Translation of value identifiers Compile a sequence of expressions Apply a substitution to a lambda-term. Assumes that the bound variables of the lambda-term do not belong to the domain of the substitution. Assumes that the image of the substitution is out of reach of the bound variables of the lambda-term (no capture). To let-bind expressions to variables
, 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 Misc open Path open Asttypes type compile_time_constant = | Big_endian | Word_size | Ostype_unix | Ostype_win32 | Ostype_cygwin type loc_kind = | Loc_FILE | Loc_LINE | Loc_MODULE | Loc_LOC | Loc_POS type primitive = Pidentity | Pignore | Prevapply of Location.t | Pdirapply of Location.t | Ploc of loc_kind | Pgetglobal of Ident.t | Psetglobal of Ident.t | Pmakeblock of int * mutable_flag | Pfield of int | Psetfield of int * bool | Pfloatfield of int | Psetfloatfield of int | Pduprecord of Types.record_representation * int Force lazy values | Plazyforce | Pccall of Primitive.description | Praise of raise_kind Boolean operations | Psequand | Psequor | Pnot Integer operations | Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp of comparison | Poffsetint of int | Poffsetref of int | Pintoffloat | Pfloatofint | Pnegfloat | Pabsfloat | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat | Pfloatcomp of comparison | Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets | Pmakearray of array_kind | Parraylength of array_kind | Parrayrefu of array_kind | Parraysetu of array_kind | Parrayrefs of array_kind | Parraysets of array_kind | Pisint | Pisout Bitvect operations | Pbittest Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t ) | Pbintofint of boxed_integer | Pintofbint of boxed_integer | Pnegbint of boxed_integer | Paddbint of boxed_integer | Psubbint of boxed_integer | Pmulbint of boxed_integer | Pdivbint of boxed_integer | Pmodbint of boxed_integer | Pandbint of boxed_integer | Porbint of boxed_integer | Pxorbint of boxed_integer | Plslbint of boxed_integer | Plsrbint of boxed_integer | Pasrbint of boxed_integer | Pbintcomp of boxed_integer * comparison | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout | Pbigarraydim of int load / set 16,32,64 bits from a string : ( unsafe ) | Pstring_load_16 of bool | Pstring_load_32 of bool | Pstring_load_64 of bool | Pstring_set_16 of bool | Pstring_set_32 of bool | Pstring_set_64 of bool load / set 16,32,64 bits from a ( char , int8_unsigned_elt , c_layout ) Bigarray . Array1.t : ( unsafe ) (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *) | Pbigstring_load_16 of bool | Pbigstring_load_32 of bool | Pbigstring_load_64 of bool | Pbigstring_set_16 of bool | Pbigstring_set_32 of bool | Pbigstring_set_64 of bool | Pctconst of compile_time_constant | Pbswap16 | Pbbswap of boxed_integer Integer to external pointer | Pint_as_pointer and comparison = Ceq | Cneq | Clt | Cgt | Cle | Cge and array_kind = Pgenarray | Paddrarray | Pintarray | Pfloatarray and boxed_integer = Pnativeint | Pint32 | Pint64 and bigarray_kind = Pbigarray_unknown | Pbigarray_float32 | Pbigarray_float64 | Pbigarray_sint8 | Pbigarray_uint8 | Pbigarray_sint16 | Pbigarray_uint16 | Pbigarray_int32 | Pbigarray_int64 | Pbigarray_caml_int | Pbigarray_native_int | Pbigarray_complex32 | Pbigarray_complex64 and bigarray_layout = Pbigarray_unknown_layout | Pbigarray_c_layout | Pbigarray_fortran_layout and raise_kind = | Raise_regular | Raise_reraise | Raise_notrace type structured_constant = Const_base of constant | Const_pointer of int | Const_block of int * structured_constant list | Const_float_array of string list | Const_immstring of string type function_kind = Curried | Tupled type let_kind = Strict | Alias | StrictOpt | Variable type meth_kind = Self | Public | Cached type shared_code = (int * int) list type lambda = Lvar of Ident.t | Lconst of structured_constant | Lapply of lambda * lambda list * Location.t | Lfunction of function_kind * Ident.t list * lambda | Llet of let_kind * Ident.t * lambda * lambda | Lletrec of (Ident.t * lambda) list * lambda | Lprim of primitive * lambda list | Lswitch of lambda * lambda_switch | Lstringswitch of lambda * (string * lambda) list * lambda option | Lstaticraise of int * lambda list | Lstaticcatch of lambda * (int * Ident.t list) * lambda | Ltrywith of lambda * Ident.t * lambda | Lifthenelse of lambda * lambda * lambda | Lsequence of lambda * lambda | Lwhile of lambda * lambda | Lfor of Ident.t * lambda * lambda * direction_flag * lambda | Lassign of Ident.t * lambda | Lsend of meth_kind * lambda * lambda * lambda list * Location.t | Levent of lambda * lambda_event | Lifused of Ident.t * lambda and lambda_switch = { sw_numconsts: int; sw_consts: (int * lambda) list; sw_numblocks: int; sw_blocks: (int * lambda) list; sw_failaction : lambda option} and lambda_event = { lev_loc: Location.t; lev_kind: lambda_event_kind; lev_repr: int ref option; lev_env: Env.summary } and lambda_event_kind = Lev_before | Lev_after of Types.type_expr | Lev_function let const_unit = Const_pointer 0 let lambda_unit = Lconst const_unit exception Not_simple let max_raw = 32 let make_key e = and make_key = Ident.make_key_generator () in let rec tr_rec env e = incr count ; match e with | Lvar id -> begin try Ident.find_same id env with Not_found -> e end | Lconst (Const_base (Const_string _)|Const_float_array _) -> raise Not_simple | Lconst _ -> e | Lapply (e,es,loc) -> Lapply (tr_rec env e,tr_recs env es,Location.none) let ex = tr_rec env ex in tr_rec (Ident.add x ex env) e | Llet (str,x,ex,e) -> let ex = tr_rec env ex in let y = make_key x in Llet (str,y,ex,tr_rec (Ident.add x (Lvar y) env) e) | Lprim (p,es) -> Lprim (p,tr_recs env es) | Lswitch (e,sw) -> Lswitch (tr_rec env e,tr_sw env sw) | Lstringswitch (e,sw,d) -> Lstringswitch (tr_rec env e, List.map (fun (s,e) -> s,tr_rec env e) sw, tr_opt env d) | Lstaticraise (i,es) -> Lstaticraise (i,tr_recs env es) | Lstaticcatch (e1,xs,e2) -> Lstaticcatch (tr_rec env e1,xs,tr_rec env e2) | Ltrywith (e1,x,e2) -> Ltrywith (tr_rec env e1,x,tr_rec env e2) | Lifthenelse (cond,ifso,ifnot) -> Lifthenelse (tr_rec env cond,tr_rec env ifso,tr_rec env ifnot) | Lsequence (e1,e2) -> Lsequence (tr_rec env e1,tr_rec env e2) | Lassign (x,e) -> Lassign (x,tr_rec env e) | Lsend (m,e1,e2,es,loc) -> Lsend (m,tr_rec env e1,tr_rec env e2,tr_recs env es,Location.none) | Lifused (id,e) -> Lifused (id,tr_rec env e) | Lletrec _|Lfunction _ | Lfor _ | Lwhile _ Beware : ( PR#6412 ) the event argument to Levent may include cyclic structure of type Type.typexpr may include cyclic structure of type Type.typexpr *) | Levent _ -> raise Not_simple and tr_recs env es = List.map (tr_rec env) es and tr_sw env sw = { sw with sw_consts = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_consts ; sw_blocks = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_blocks ; sw_failaction = tr_opt env sw.sw_failaction ; } and tr_opt env = function | None -> None | Some e -> Some (tr_rec env e) in try Some (tr_rec Ident.empty e) with Not_simple -> None let name_lambda strict arg fn = match arg with Lvar id -> fn id | _ -> let id = Ident.create "let" in Llet(strict, id, arg, fn id) let name_lambda_list args fn = let rec name_list names = function [] -> fn (List.rev names) | (Lvar id as arg) :: rem -> name_list (arg :: names) rem | arg :: rem -> let id = Ident.create "let" in Llet(Strict, id, arg, name_list (Lvar id :: names) rem) in name_list [] args let iter_opt f = function | None -> () | Some e -> f e let iter f = function Lvar _ | Lconst _ -> () | Lapply(fn, args, _) -> f fn; List.iter f args | Lfunction(kind, params, body) -> f body | Llet(str, id, arg, body) -> f arg; f body | Lletrec(decl, body) -> f body; List.iter (fun (id, exp) -> f exp) decl | Lprim(p, args) -> List.iter f args | Lswitch(arg, sw) -> f arg; List.iter (fun (key, case) -> f case) sw.sw_consts; List.iter (fun (key, case) -> f case) sw.sw_blocks; iter_opt f sw.sw_failaction | Lstringswitch (arg,cases,default) -> f arg ; List.iter (fun (_,act) -> f act) cases ; iter_opt f default | Lstaticraise (_,args) -> List.iter f args | Lstaticcatch(e1, (_,vars), e2) -> f e1; f e2 | Ltrywith(e1, exn, e2) -> f e1; f e2 | Lifthenelse(e1, e2, e3) -> f e1; f e2; f e3 | Lsequence(e1, e2) -> f e1; f e2 | Lwhile(e1, e2) -> f e1; f e2 | Lfor(v, e1, e2, dir, e3) -> f e1; f e2; f e3 | Lassign(id, e) -> f e | Lsend (k, met, obj, args, _) -> List.iter f (met::obj::args) | Levent (lam, evt) -> f lam | Lifused (v, e) -> f e module IdentSet = Set.Make(struct type t = Ident.t let compare = compare end) let free_ids get l = let fv = ref IdentSet.empty in let rec free l = iter free l; fv := List.fold_right IdentSet.add (get l) !fv; match l with Lfunction(kind, params, body) -> List.iter (fun param -> fv := IdentSet.remove param !fv) params | Llet(str, id, arg, body) -> fv := IdentSet.remove id !fv | Lletrec(decl, body) -> List.iter (fun (id, exp) -> fv := IdentSet.remove id !fv) decl | Lstaticcatch(e1, (_,vars), e2) -> List.iter (fun id -> fv := IdentSet.remove id !fv) vars | Ltrywith(e1, exn, e2) -> fv := IdentSet.remove exn !fv | Lfor(v, e1, e2, dir, e3) -> fv := IdentSet.remove v !fv | Lassign(id, e) -> fv := IdentSet.add id !fv | Lvar _ | Lconst _ | Lapply _ | Lprim _ | Lswitch _ | Lstringswitch _ | Lstaticraise _ | Lifthenelse _ | Lsequence _ | Lwhile _ | Lsend _ | Levent _ | Lifused _ -> () in free l; !fv let free_variables l = free_ids (function Lvar id -> [id] | _ -> []) l let free_methods l = free_ids (function Lsend(Self, Lvar meth, obj, _, _) -> [meth] | _ -> []) l let raise_count = ref 0 let next_raise_count () = incr raise_count ; !raise_count let negative_raise_count = ref 0 let next_negative_raise_count () = decr negative_raise_count ; !negative_raise_count let staticfail = Lstaticraise (0,[]) let rec is_guarded = function | Lifthenelse( cond, body, Lstaticraise (0,[])) -> true | Llet(str, id, lam, body) -> is_guarded body | Levent(lam, ev) -> is_guarded lam | _ -> false let rec patch_guarded patch = function | Lifthenelse (cond, body, Lstaticraise (0,[])) -> Lifthenelse (cond, body, patch) | Llet(str, id, lam, body) -> Llet (str, id, lam, patch_guarded patch body) | Levent(lam, ev) -> Levent (patch_guarded patch lam, ev) | _ -> fatal_error "Lambda.patch_guarded" let rec transl_normal_path = function Pident id -> if Ident.global id then Lprim(Pgetglobal id, []) else Lvar id | Pdot(p, s, pos) -> Lprim(Pfield pos, [transl_normal_path p]) | Papply(p1, p2) -> fatal_error "Lambda.transl_path" let transl_path ?(loc=Location.none) env path = transl_normal_path (Env.normalize_path (Some loc) env path) let rec make_sequence fn = function [] -> lambda_unit | [x] -> fn x | x::rem -> let lam = fn x in Lsequence(lam, make_sequence fn rem) let subst_lambda s lam = let rec subst = function Lvar id as l -> begin try Ident.find_same id s with Not_found -> l end | Lconst sc as l -> l | Lapply(fn, args, loc) -> Lapply(subst fn, List.map subst args, loc) | Lfunction(kind, params, body) -> Lfunction(kind, params, subst body) | Llet(str, id, arg, body) -> Llet(str, id, subst arg, subst body) | Lletrec(decl, body) -> Lletrec(List.map subst_decl decl, subst body) | Lprim(p, args) -> Lprim(p, List.map subst args) | Lswitch(arg, sw) -> Lswitch(subst arg, {sw with sw_consts = List.map subst_case sw.sw_consts; sw_blocks = List.map subst_case sw.sw_blocks; sw_failaction = subst_opt sw.sw_failaction; }) | Lstringswitch (arg,cases,default) -> Lstringswitch (subst arg,List.map subst_strcase cases,subst_opt default) | Lstaticraise (i,args) -> Lstaticraise (i, List.map subst args) | Lstaticcatch(e1, io, e2) -> Lstaticcatch(subst e1, io, subst e2) | Ltrywith(e1, exn, e2) -> Ltrywith(subst e1, exn, subst e2) | Lifthenelse(e1, e2, e3) -> Lifthenelse(subst e1, subst e2, subst e3) | Lsequence(e1, e2) -> Lsequence(subst e1, subst e2) | Lwhile(e1, e2) -> Lwhile(subst e1, subst e2) | Lfor(v, e1, e2, dir, e3) -> Lfor(v, subst e1, subst e2, dir, subst e3) | Lassign(id, e) -> Lassign(id, subst e) | Lsend (k, met, obj, args, loc) -> Lsend (k, subst met, subst obj, List.map subst args, loc) | Levent (lam, evt) -> Levent (subst lam, evt) | Lifused (v, e) -> Lifused (v, subst e) and subst_decl (id, exp) = (id, subst exp) and subst_case (key, case) = (key, subst case) and subst_strcase (key, case) = (key, subst case) and subst_opt = function | None -> None | Some e -> Some (subst e) in subst lam let bind str var exp body = match exp with Lvar var' when Ident.same var var' -> body | _ -> Llet(str, var, exp, body) and commute_comparison = function | Ceq -> Ceq| Cneq -> Cneq | Clt -> Cgt | Cle -> Cge | Cgt -> Clt | Cge -> Cle and negate_comparison = function | Ceq -> Cneq| Cneq -> Ceq | Clt -> Cge | Cle -> Cgt | Cgt -> Cle | Cge -> Clt let raise_kind = function | Raise_regular -> "raise" | Raise_reraise -> "reraise" | Raise_notrace -> "raise_notrace" let lam_of_loc kind loc = let loc_start = loc.Location.loc_start in let (file, lnum, cnum) = Location.get_pos_info loc_start in let enum = loc.Location.loc_end.Lexing.pos_cnum - loc_start.Lexing.pos_cnum + cnum in match kind with | Loc_POS -> Lconst (Const_block (0, [ Const_immstring file; Const_base (Const_int lnum); Const_base (Const_int cnum); Const_base (Const_int enum); ])) | Loc_FILE -> Lconst (Const_immstring file) | Loc_MODULE -> let filename = Filename.basename file in let name = Env.get_unit_name () in let module_name = if name = "" then "//"^filename^"//" else name in Lconst (Const_immstring module_name) | Loc_LOC -> let loc = Printf.sprintf "File %S, line %d, characters %d-%d" file lnum cnum enum in Lconst (Const_immstring loc) | Loc_LINE -> Lconst (Const_base (Const_int lnum)) let reset () = raise_count := 0
fb6b7ba72eafcf8093e3e9fb6e8f4a1905d104a46d35af43c9a91c6fbc96cd01
levex/wacc
Semantics.hs
module WACC.Semantics where import qualified Data.Map as Map import Control.Monad.Except import Control.Monad.State import WACC.Parser.Types import WACC.Semantics.Types import WACC.Semantics.Syntax import WACC.Semantics.Semantics import WACC.Semantics.Simplify checkProgram :: AnnotatedProgram -> Either CheckerError Program checkProgram (p, ld) = (evalState . runExceptT . runSemanticChecker) runCheck initialState where runCheck = syntaxCheck p >>= semanticCheck >>= simplify initialState = (CheckerState ld (SymbolTable [] []) Map.empty) getExitCode :: CheckerError -> Int -> Int -> Int -> Int getExitCode (CheckerError SyntaxError _ _) ec _ _ = ec getExitCode (CheckerError SemanticError _ _) _ ec _ = ec getExitCode (CheckerError TypeError _ _) _ _ ec = ec
null
https://raw.githubusercontent.com/levex/wacc/c77164f0c9aeb53d3d13a0370fdedc448b6009a3/src/WACC/Semantics.hs
haskell
module WACC.Semantics where import qualified Data.Map as Map import Control.Monad.Except import Control.Monad.State import WACC.Parser.Types import WACC.Semantics.Types import WACC.Semantics.Syntax import WACC.Semantics.Semantics import WACC.Semantics.Simplify checkProgram :: AnnotatedProgram -> Either CheckerError Program checkProgram (p, ld) = (evalState . runExceptT . runSemanticChecker) runCheck initialState where runCheck = syntaxCheck p >>= semanticCheck >>= simplify initialState = (CheckerState ld (SymbolTable [] []) Map.empty) getExitCode :: CheckerError -> Int -> Int -> Int -> Int getExitCode (CheckerError SyntaxError _ _) ec _ _ = ec getExitCode (CheckerError SemanticError _ _) _ ec _ = ec getExitCode (CheckerError TypeError _ _) _ _ ec = ec
07ce09abb449858163f377dd4b214ecbbcabff081cb9bf57d7487f4bbe035dd7
comtihon/mongodb-erlang
mongo_protocol.erl
-module(mongo_protocol). -export([ dbcoll/2, put_message/3, get_reply/1 ]). -export_type([notice/0, request/0, reply/0]). -export_type([message/0]). -export_type([requestid/0]). -include("mongo_protocol.hrl"). -include_lib("bson/include/bson_binary.hrl"). % A notice is an asynchronous message sent to the server (no reply expected) -type notice() :: #insert{} | #update{} | #delete{} | #killcursor{} | #ensure_index{}. % A request is a synchronous message sent to the server (reply expected) -type request() :: #'query'{} | #getmore{}. % A reply to a request -type reply() :: #reply{}. % message id -type requestid() :: integer(). -type message() :: notice() | request(). RequestId expected to be in scope at call site -define(put_header(Opcode), ?put_int32(_RequestId), ?put_int32(0), ?put_int32(Opcode)). -define(get_header(Opcode, ResponseTo), ?get_int32(_RequestId), ?get_int32(ResponseTo), ?get_int32(Opcode)). -define(ReplyOpcode, 1). -define(UpdateOpcode, 2001). -define(InsertOpcode, 2002). -define(QueryOpcode, 2004). -define(GetmoreOpcode, 2005). -define(DeleteOpcode, 2006). -define(KillcursorOpcode, 2007). -spec dbcoll(database(), colldb()) -> bson:utf8(). %@doc Concat db and collection name with period (.) in between dbcoll(Db, {undefined, Coll}) -> dbcoll(Db, Coll); dbcoll(_, {Db, Coll}) -> dbcoll(Db, Coll); dbcoll(Db, Coll) -> <<(binarize(Db))/binary, $., (binarize(Coll))/binary>>. -spec put_message(mc_worker_api:database(), message(), requestid()) -> binary(). put_message(Db, #insert{collection = Coll, documents = Docs}, _RequestId) -> <<?put_header(?InsertOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, <<<<(bson_binary:put_document(Doc))/binary>> || Doc <- Docs>>/binary>>; put_message(Db, #update{collection = Coll, upsert = U, multiupdate = M, selector = Sel, updater = Up}, _RequestId) -> <<?put_header(?UpdateOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_bits32(0, 0, 0, 0, 0, 0, bit(M), bit(U)), (bson_binary:put_document(Sel))/binary, (bson_binary:put_document(Up))/binary>>; put_message(Db, #delete{collection = Coll, singleremove = R, selector = Sel}, _RequestId) -> <<?put_header(?DeleteOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_bits32(0, 0, 0, 0, 0, 0, 0, bit(R)), (bson_binary:put_document(Sel))/binary>>; put_message(_Db, #killcursor{cursorids = Cids}, _RequestId) -> <<?put_header(?KillcursorOpcode), ?put_int32(0), ?put_int32(length(Cids)), <<<<?put_int64(Cid)>> || Cid <- Cids>>/binary>>; put_message(Db, #'query'{tailablecursor = TC, slaveok = SOK, nocursortimeout = NCT, awaitdata = AD, collection = Coll, skip = Skip, batchsize = Batch, selector = Sel, projector = Proj}, _RequestId) -> <<?put_header(?QueryOpcode), ?put_bits32(0, 0, bit(AD), bit(NCT), 0, bit(SOK), bit(TC), 0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_int32(Skip), ?put_int32(Batch), (bson_binary:put_document(Sel))/binary, (add_proj(Proj))/binary>>; put_message(Db, #getmore{collection = Coll, batchsize = Batch, cursorid = Cid}, _RequestId) -> <<?put_header(?GetmoreOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_int32(Batch), ?put_int64(Cid)>>. -spec get_reply(binary()) -> {requestid(), reply(), binary()}. get_reply(Message) -> <<?get_header(?ReplyOpcode, ResponseTo), ?get_bits32(_, _, _, _, AwaitCapable, _, QueryError, CursorNotFound), ?get_int64(CursorId), ?get_int32(StartingFrom), ?get_int32(NumDocs), Bin/binary>> = Message, {Docs, BinRest} = get_docs(NumDocs, Bin, []), Reply = #reply{ cursornotfound = bool(CursorNotFound), queryerror = bool(QueryError), awaitcapable = bool(AwaitCapable), cursorid = CursorId, startingfrom = StartingFrom, documents = Docs }, {ResponseTo, Reply, BinRest}. -spec binarize(binary() | atom()) -> binary(). @doc Ensures the given term is converted to a UTF-8 binary . binarize(Term) when is_binary(Term) -> Term; binarize(Term) when is_atom(Term) -> atom_to_binary(Term, utf8). @private get_docs(0, Bin, Docs) -> {lists:reverse(Docs), Bin}; get_docs(NumDocs, Bin, Docs) when NumDocs > 0 -> {Doc, Bin1} = bson_binary:get_map(Bin), get_docs(NumDocs - 1, Bin1, [Doc | Docs]). @private bit(false) -> 0; bit(true) -> 1. @private bool(0) -> false; bool(1) -> true. @private add_proj(Projector) when is_map(Projector) -> case map_size(Projector) of 0 -> <<>>; _ -> bson_binary:put_document(Projector) end; add_proj(Other) -> bson_binary:put_document(Other).
null
https://raw.githubusercontent.com/comtihon/mongodb-erlang/713e8bdf677567c6b21ecef8c103afecf824b16f/src/connection/mongo_protocol.erl
erlang
A notice is an asynchronous message sent to the server (no reply expected) A request is a synchronous message sent to the server (reply expected) A reply to a request message id @doc Concat db and collection name with period (.) in between
-module(mongo_protocol). -export([ dbcoll/2, put_message/3, get_reply/1 ]). -export_type([notice/0, request/0, reply/0]). -export_type([message/0]). -export_type([requestid/0]). -include("mongo_protocol.hrl"). -include_lib("bson/include/bson_binary.hrl"). -type notice() :: #insert{} | #update{} | #delete{} | #killcursor{} | #ensure_index{}. -type request() :: #'query'{} | #getmore{}. -type reply() :: #reply{}. -type requestid() :: integer(). -type message() :: notice() | request(). RequestId expected to be in scope at call site -define(put_header(Opcode), ?put_int32(_RequestId), ?put_int32(0), ?put_int32(Opcode)). -define(get_header(Opcode, ResponseTo), ?get_int32(_RequestId), ?get_int32(ResponseTo), ?get_int32(Opcode)). -define(ReplyOpcode, 1). -define(UpdateOpcode, 2001). -define(InsertOpcode, 2002). -define(QueryOpcode, 2004). -define(GetmoreOpcode, 2005). -define(DeleteOpcode, 2006). -define(KillcursorOpcode, 2007). -spec dbcoll(database(), colldb()) -> bson:utf8(). dbcoll(Db, {undefined, Coll}) -> dbcoll(Db, Coll); dbcoll(_, {Db, Coll}) -> dbcoll(Db, Coll); dbcoll(Db, Coll) -> <<(binarize(Db))/binary, $., (binarize(Coll))/binary>>. -spec put_message(mc_worker_api:database(), message(), requestid()) -> binary(). put_message(Db, #insert{collection = Coll, documents = Docs}, _RequestId) -> <<?put_header(?InsertOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, <<<<(bson_binary:put_document(Doc))/binary>> || Doc <- Docs>>/binary>>; put_message(Db, #update{collection = Coll, upsert = U, multiupdate = M, selector = Sel, updater = Up}, _RequestId) -> <<?put_header(?UpdateOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_bits32(0, 0, 0, 0, 0, 0, bit(M), bit(U)), (bson_binary:put_document(Sel))/binary, (bson_binary:put_document(Up))/binary>>; put_message(Db, #delete{collection = Coll, singleremove = R, selector = Sel}, _RequestId) -> <<?put_header(?DeleteOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_bits32(0, 0, 0, 0, 0, 0, 0, bit(R)), (bson_binary:put_document(Sel))/binary>>; put_message(_Db, #killcursor{cursorids = Cids}, _RequestId) -> <<?put_header(?KillcursorOpcode), ?put_int32(0), ?put_int32(length(Cids)), <<<<?put_int64(Cid)>> || Cid <- Cids>>/binary>>; put_message(Db, #'query'{tailablecursor = TC, slaveok = SOK, nocursortimeout = NCT, awaitdata = AD, collection = Coll, skip = Skip, batchsize = Batch, selector = Sel, projector = Proj}, _RequestId) -> <<?put_header(?QueryOpcode), ?put_bits32(0, 0, bit(AD), bit(NCT), 0, bit(SOK), bit(TC), 0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_int32(Skip), ?put_int32(Batch), (bson_binary:put_document(Sel))/binary, (add_proj(Proj))/binary>>; put_message(Db, #getmore{collection = Coll, batchsize = Batch, cursorid = Cid}, _RequestId) -> <<?put_header(?GetmoreOpcode), ?put_int32(0), (bson_binary:put_cstring(dbcoll(Db, Coll)))/binary, ?put_int32(Batch), ?put_int64(Cid)>>. -spec get_reply(binary()) -> {requestid(), reply(), binary()}. get_reply(Message) -> <<?get_header(?ReplyOpcode, ResponseTo), ?get_bits32(_, _, _, _, AwaitCapable, _, QueryError, CursorNotFound), ?get_int64(CursorId), ?get_int32(StartingFrom), ?get_int32(NumDocs), Bin/binary>> = Message, {Docs, BinRest} = get_docs(NumDocs, Bin, []), Reply = #reply{ cursornotfound = bool(CursorNotFound), queryerror = bool(QueryError), awaitcapable = bool(AwaitCapable), cursorid = CursorId, startingfrom = StartingFrom, documents = Docs }, {ResponseTo, Reply, BinRest}. -spec binarize(binary() | atom()) -> binary(). @doc Ensures the given term is converted to a UTF-8 binary . binarize(Term) when is_binary(Term) -> Term; binarize(Term) when is_atom(Term) -> atom_to_binary(Term, utf8). @private get_docs(0, Bin, Docs) -> {lists:reverse(Docs), Bin}; get_docs(NumDocs, Bin, Docs) when NumDocs > 0 -> {Doc, Bin1} = bson_binary:get_map(Bin), get_docs(NumDocs - 1, Bin1, [Doc | Docs]). @private bit(false) -> 0; bit(true) -> 1. @private bool(0) -> false; bool(1) -> true. @private add_proj(Projector) when is_map(Projector) -> case map_size(Projector) of 0 -> <<>>; _ -> bson_binary:put_document(Projector) end; add_proj(Other) -> bson_binary:put_document(Other).
4a3a0e7ec30182146d62332f4bb3e7379905c3257b485e76540b8a6cb81380a8
sirherrbatka/clusters
docstrings.lisp
(cl:in-package #:clusters.metric) (docs:define-docs :formatter docs.ext:rich-aggregating-formatter (function euclid (:description "Calculates the Euclid distance between two simple-arrays of single-float" :returns "Non-negative-single-float distance.")) (function average (:description "Calculates average distance between two sets, based around the FN metric function" :returns "Average distance between two sets." :notes ("Algorithm described in -012-0089-6" "KEY function is used in conjuction with the TEST function to construct unions and differences between sets. Not for extracting values for the FN itself. This allows FN to operate on the weight, count or other secondary attribute of the set element." "Quadratic time complexity, suitable only for small sets."))) (function lcs (:description "Largest common subsequence metric for vectors.")) (function levenshtein (:description "Calculates the Levenshtein distance." :returns "Non-negative fixnum representing the distance." :arguments ((str1 "String.") (str2 "String.")))) (function levenshtein (:description "Traditional edit distance for strings.")) (function hausdorff (:description "Hausdorff distance. Accepts vectors as arguments.")) (function svr (:description "Calculates the subvector representation based metric." :returns "Single-float (between 0.0 and 1.0) representing the distance." :arguments ((a "Vector.") (b "Vector.")) :notes ("Content of a and b vectors must be comparable using EQUAL." "Algorithm described in " "Will return 1.0 if one of the vectors is empty and the second is not empty."))) (function hellinger (:description "Calculates hellinger distance between two distributions, both represented as histograms." :arguments ((q "Frequency vector.") (p "Frequency vector.")) :returns "Hellinger distance.")) (function earth-mover (:description "Calculates earth mover distance between two distributions, both represented as histograms." :arguments ((a "Frequency vector.") (b "Frequency vector.")) :returns "Earth mover distance between two histograms.")))
null
https://raw.githubusercontent.com/sirherrbatka/clusters/20b8b60005ac8e27d12d05d277b26d8b5ca5c238/source/metric/docstrings.lisp
lisp
(cl:in-package #:clusters.metric) (docs:define-docs :formatter docs.ext:rich-aggregating-formatter (function euclid (:description "Calculates the Euclid distance between two simple-arrays of single-float" :returns "Non-negative-single-float distance.")) (function average (:description "Calculates average distance between two sets, based around the FN metric function" :returns "Average distance between two sets." :notes ("Algorithm described in -012-0089-6" "KEY function is used in conjuction with the TEST function to construct unions and differences between sets. Not for extracting values for the FN itself. This allows FN to operate on the weight, count or other secondary attribute of the set element." "Quadratic time complexity, suitable only for small sets."))) (function lcs (:description "Largest common subsequence metric for vectors.")) (function levenshtein (:description "Calculates the Levenshtein distance." :returns "Non-negative fixnum representing the distance." :arguments ((str1 "String.") (str2 "String.")))) (function levenshtein (:description "Traditional edit distance for strings.")) (function hausdorff (:description "Hausdorff distance. Accepts vectors as arguments.")) (function svr (:description "Calculates the subvector representation based metric." :returns "Single-float (between 0.0 and 1.0) representing the distance." :arguments ((a "Vector.") (b "Vector.")) :notes ("Content of a and b vectors must be comparable using EQUAL." "Algorithm described in " "Will return 1.0 if one of the vectors is empty and the second is not empty."))) (function hellinger (:description "Calculates hellinger distance between two distributions, both represented as histograms." :arguments ((q "Frequency vector.") (p "Frequency vector.")) :returns "Hellinger distance.")) (function earth-mover (:description "Calculates earth mover distance between two distributions, both represented as histograms." :arguments ((a "Frequency vector.") (b "Frequency vector.")) :returns "Earth mover distance between two histograms.")))
63ae485724bda9588db87fb5b606465758ed7b1e50105db6f130f68bb9fdda23
sph-mn/sph-lib
base.scm
(define-module (sph server base)) (use-modules (sph) (sph exception) ((rnrs io simple) #:select (i/o-error?)) ((sph io) #:select (socket-create-bound))) (export server-socket server-default-port server-exception-handler server-listen-queue-length) (define server-listen-queue-length 1024) (define server-default-port 6500) (define* (server-socket address #:key port type protocol set-options non-blocking) "create a socket with default options. the socket type is inferred from the address, which can be an ip4 or ip6 address (tcp) or a filesystem path (unix socket)" (socket-create-bound address #:port (or port server-default-port) #:type type #:non-blocking non-blocking #:protocol protocol #:set-options (l (a) (setsockopt a SOL_SOCKET SO_REUSEADDR 1) (fcntl a F_SETFD FD_CLOEXEC) (and set-options (set-options a))))) (define (server-exception-handler key . a) "ignore socket io errors (for example connections closed by peers). exceptions can be raised by rnrs raise or guile throw" (case key ((r6rs:exception) (if (i/o-error? (first a)) #f (exception-display-guile-r6rs key a))) ( (system-error) (let (errno (system-error-errno (pair key a))) (if (or (= EPIPE errno) (= EIO errno) (= ECONNRESET errno) (= ENOMEM errno) (= error ENOBUFS)) #f (exception-display-guile key a)))) (else (exception-display-guile key a))))
null
https://raw.githubusercontent.com/sph-mn/sph-lib/c7daf74f42d6bd1304f49c2fef89dcd6dd94fdc9/modules/sph/server/base.scm
scheme
(define-module (sph server base)) (use-modules (sph) (sph exception) ((rnrs io simple) #:select (i/o-error?)) ((sph io) #:select (socket-create-bound))) (export server-socket server-default-port server-exception-handler server-listen-queue-length) (define server-listen-queue-length 1024) (define server-default-port 6500) (define* (server-socket address #:key port type protocol set-options non-blocking) "create a socket with default options. the socket type is inferred from the address, which can be an ip4 or ip6 address (tcp) or a filesystem path (unix socket)" (socket-create-bound address #:port (or port server-default-port) #:type type #:non-blocking non-blocking #:protocol protocol #:set-options (l (a) (setsockopt a SOL_SOCKET SO_REUSEADDR 1) (fcntl a F_SETFD FD_CLOEXEC) (and set-options (set-options a))))) (define (server-exception-handler key . a) "ignore socket io errors (for example connections closed by peers). exceptions can be raised by rnrs raise or guile throw" (case key ((r6rs:exception) (if (i/o-error? (first a)) #f (exception-display-guile-r6rs key a))) ( (system-error) (let (errno (system-error-errno (pair key a))) (if (or (= EPIPE errno) (= EIO errno) (= ECONNRESET errno) (= ENOMEM errno) (= error ENOBUFS)) #f (exception-display-guile key a)))) (else (exception-display-guile key a))))
97fada2916334d70d0fb63b83f50c2f3da4478c21b3795f12f80bd9198385581
scrive/haskell-soap
Stream.hs
# LANGUAGE CPP # -- | Collection of helpers to use with Text.XML.Stream.Parse parsers. -- -- > let sink = flaxTag "MethodNameResponse" -- > $ flaxTag "MethodNameResult" $ do -- > info <- flaxTag "Info" $ do -- > q <- readTag "quantity" -- > b <- readTag "balance" -- > return $ Info q b -- > rc <- readTag "ResponseCode" -- > return (rc, info) module Network.SOAP.Parsing.Stream ( -- * Tags laxTag, flaxTag -- * Content , laxContent, flaxContent , readContent, readTag -- * Types to use in custom parser sinks , Sink, Event ) where #if MIN_VERSION_conduit(1,1,0) import Control.Monad.Catch (MonadThrow) #endif import Data.Conduit import Data.XML.Types (Event) import Text.XML (Name(..)) import qualified Text.XML.Stream.Parse as XSP import Data.Text (Text, unpack) | Namespace- and attribute- ignorant tagNoAttr . laxTag :: (MonadThrow m) => Text -> Sink Event m a -> Sink Event m (Maybe a) laxTag ln = XSP.tagPredicate ((== ln) . nameLocalName) XSP.ignoreAttrs . const -- | Non-maybe version of laxTag/tagNoAttr. flaxTag :: (MonadThrow m) => Text -> Sink Event m a -> Sink Event m a flaxTag ln s = XSP.force ("got no " ++ show ln) $ laxTag ln s laxContent :: (MonadThrow m) => Text -> Sink Event m (Maybe Text) laxContent ln = laxTag ln XSP.content flaxContent :: (MonadThrow m) => Text -> Sink Event m Text flaxContent ln = flaxTag ln XSP.content -- | Unpack and read a current tag content. readContent :: (Read a, MonadThrow m) => Sink Event m a readContent = fmap (read . unpack) XSP.content -- | Unpack and read tag content by local name. readTag :: (Read a, MonadThrow m) => Text -> Sink Event m a readTag n = flaxTag n readContent
null
https://raw.githubusercontent.com/scrive/haskell-soap/b237ca8c7d5411e9b5fcf239db02c53df9ba41d4/soap/src/Network/SOAP/Parsing/Stream.hs
haskell
| Collection of helpers to use with Text.XML.Stream.Parse parsers. > let sink = flaxTag "MethodNameResponse" > $ flaxTag "MethodNameResult" $ do > info <- flaxTag "Info" $ do > q <- readTag "quantity" > b <- readTag "balance" > return $ Info q b > rc <- readTag "ResponseCode" > return (rc, info) * Tags * Content * Types to use in custom parser sinks | Non-maybe version of laxTag/tagNoAttr. | Unpack and read a current tag content. | Unpack and read tag content by local name.
# LANGUAGE CPP # module Network.SOAP.Parsing.Stream laxTag, flaxTag , laxContent, flaxContent , readContent, readTag , Sink, Event ) where #if MIN_VERSION_conduit(1,1,0) import Control.Monad.Catch (MonadThrow) #endif import Data.Conduit import Data.XML.Types (Event) import Text.XML (Name(..)) import qualified Text.XML.Stream.Parse as XSP import Data.Text (Text, unpack) | Namespace- and attribute- ignorant tagNoAttr . laxTag :: (MonadThrow m) => Text -> Sink Event m a -> Sink Event m (Maybe a) laxTag ln = XSP.tagPredicate ((== ln) . nameLocalName) XSP.ignoreAttrs . const flaxTag :: (MonadThrow m) => Text -> Sink Event m a -> Sink Event m a flaxTag ln s = XSP.force ("got no " ++ show ln) $ laxTag ln s laxContent :: (MonadThrow m) => Text -> Sink Event m (Maybe Text) laxContent ln = laxTag ln XSP.content flaxContent :: (MonadThrow m) => Text -> Sink Event m Text flaxContent ln = flaxTag ln XSP.content readContent :: (Read a, MonadThrow m) => Sink Event m a readContent = fmap (read . unpack) XSP.content readTag :: (Read a, MonadThrow m) => Text -> Sink Event m a readTag n = flaxTag n readContent
64576880c918baa7ac72947e336d214e1a566c025836596cc7cbe37ad0185c4d
reenberg/xmonad
ManageHook.hs
# LANGUAGE GeneralizedNewtypeDeriving # ----------------------------------------------------------------------------- -- | Module : XMonad . ManageHook Copyright : ( c ) 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : -- Stability : unstable -- Portability : not portable, uses cunning newtype deriving -- An EDSL for ManageHooks -- ----------------------------------------------------------------------------- -- XXX examples required module XMonad.ManageHook where import Prelude hiding (catch) import XMonad.Core import Graphics.X11.Xlib.Extras import Graphics.X11.Xlib (Display, Window, internAtom, wM_NAME) import Control.Exception.Extensible (bracket, catch, SomeException(..)) import Control.Monad.Reader import Data.Maybe import Data.Monoid import qualified XMonad.StackSet as W import XMonad.Operations (floatLocation, reveal) -- | Lift an 'X' action to a 'Query'. liftX :: X a -> Query a liftX = Query . lift | The identity hook that returns the WindowSet unchanged . idHook :: Monoid m => m idHook = mempty -- | Infix 'mappend'. Compose two 'ManageHook' from right to left. (<+>) :: Monoid m => m -> m -> m (<+>) = mappend | Compose the list of ' ManageHook 's . composeAll :: Monoid m => [m] -> m composeAll = mconcat infix 0 --> | @p -- > x@. If returns ' True ' , execute the ' ManageHook ' . -- -- > (-->) :: Monoid m => Query Bool -> Query m -> Query m -- a simpler type > ) : : ( , Monoid a ) = > m Bool - > m a - > m a > f = p > > = \b - > if b then f else return | @q = ? if the result of @q@ equals @x@ , return ' True ' . (=?) :: Eq a => Query a -> a -> Query Bool q =? x = fmap (== x) q infixr 3 <&&>, <||> -- | '&&' lifted to a 'Monad'. (<&&>) :: Monad m => m Bool -> m Bool -> m Bool (<&&>) = liftM2 (&&) -- | '||' lifted to a 'Monad'. (<||>) :: Monad m => m Bool -> m Bool -> m Bool (<||>) = liftM2 (||) -- | Return the window title. title :: Query String title = ask >>= \w -> liftX $ do d <- asks display let getProp = (internAtom d "_NET_WM_NAME" False >>= getTextProperty d w) `catch` \(SomeException _) -> getTextProperty d w wM_NAME extract prop = do l <- wcTextPropertyToTextList d prop return $ if null l then "" else head l io $ bracket getProp (xFree . tp_value) extract `catch` \(SomeException _) -> return "" -- | Return the application name. appName :: Query String appName = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap resName $ io $ getClassHint d w) -- | Backwards compatible alias for 'appName'. resource :: Query String resource = appName -- | Return the resource class. className :: Query String className = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap resClass $ io $ getClassHint d w) -- | A query that can return an arbitrary X property of type 'String', -- identified by name. stringProperty :: String -> Query String stringProperty p = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap (fromMaybe "") $ getStringProperty d w p) getStringProperty :: Display -> Window -> String -> X (Maybe String) getStringProperty d w p = do a <- getAtom p md <- io $ getWindowProperty8 d a w return $ fmap (map (toEnum . fromIntegral)) md | Modify the ' WindowSet ' with a pure function . doF :: (s -> s) -> Query (Endo s) doF = return . Endo -- | Move the window to the floating layer. doFloat :: ManageHook doFloat = ask >>= \w -> doF . W.float w . snd =<< liftX (floatLocation w) | Map the window and remove it from the ' WindowSet ' . doIgnore :: ManageHook doIgnore = ask >>= \w -> liftX (reveal w) >> doF (W.delete w) -- | Move the window to a given workspace doShift :: WorkspaceId -> ManageHook doShift i = doF . W.shiftWin i =<< ask
null
https://raw.githubusercontent.com/reenberg/xmonad/c4f471bfb6ffe70741fe76c3b154f6bae920da7f/XMonad/ManageHook.hs
haskell
--------------------------------------------------------------------------- | License : BSD3-style (see LICENSE) Maintainer : Stability : unstable Portability : not portable, uses cunning newtype deriving --------------------------------------------------------------------------- XXX examples required | Lift an 'X' action to a 'Query'. | Infix 'mappend'. Compose two 'ManageHook' from right to left. > > x@. If returns ' True ' , execute the ' ManageHook ' . > (-->) :: Monoid m => Query Bool -> Query m -> Query m -- a simpler type | '&&' lifted to a 'Monad'. | '||' lifted to a 'Monad'. | Return the window title. | Return the application name. | Backwards compatible alias for 'appName'. | Return the resource class. | A query that can return an arbitrary X property of type 'String', identified by name. | Move the window to the floating layer. | Move the window to a given workspace
# LANGUAGE GeneralizedNewtypeDeriving # Module : XMonad . ManageHook Copyright : ( c ) 2007 An EDSL for ManageHooks module XMonad.ManageHook where import Prelude hiding (catch) import XMonad.Core import Graphics.X11.Xlib.Extras import Graphics.X11.Xlib (Display, Window, internAtom, wM_NAME) import Control.Exception.Extensible (bracket, catch, SomeException(..)) import Control.Monad.Reader import Data.Maybe import Data.Monoid import qualified XMonad.StackSet as W import XMonad.Operations (floatLocation, reveal) liftX :: X a -> Query a liftX = Query . lift | The identity hook that returns the WindowSet unchanged . idHook :: Monoid m => m idHook = mempty (<+>) :: Monoid m => m -> m -> m (<+>) = mappend | Compose the list of ' ManageHook 's . composeAll :: Monoid m => [m] -> m composeAll = mconcat > ) : : ( , Monoid a ) = > m Bool - > m a - > m a > f = p > > = \b - > if b then f else return | @q = ? if the result of @q@ equals @x@ , return ' True ' . (=?) :: Eq a => Query a -> a -> Query Bool q =? x = fmap (== x) q infixr 3 <&&>, <||> (<&&>) :: Monad m => m Bool -> m Bool -> m Bool (<&&>) = liftM2 (&&) (<||>) :: Monad m => m Bool -> m Bool -> m Bool (<||>) = liftM2 (||) title :: Query String title = ask >>= \w -> liftX $ do d <- asks display let getProp = (internAtom d "_NET_WM_NAME" False >>= getTextProperty d w) `catch` \(SomeException _) -> getTextProperty d w wM_NAME extract prop = do l <- wcTextPropertyToTextList d prop return $ if null l then "" else head l io $ bracket getProp (xFree . tp_value) extract `catch` \(SomeException _) -> return "" appName :: Query String appName = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap resName $ io $ getClassHint d w) resource :: Query String resource = appName className :: Query String className = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap resClass $ io $ getClassHint d w) stringProperty :: String -> Query String stringProperty p = ask >>= (\w -> liftX $ withDisplay $ \d -> fmap (fromMaybe "") $ getStringProperty d w p) getStringProperty :: Display -> Window -> String -> X (Maybe String) getStringProperty d w p = do a <- getAtom p md <- io $ getWindowProperty8 d a w return $ fmap (map (toEnum . fromIntegral)) md | Modify the ' WindowSet ' with a pure function . doF :: (s -> s) -> Query (Endo s) doF = return . Endo doFloat :: ManageHook doFloat = ask >>= \w -> doF . W.float w . snd =<< liftX (floatLocation w) | Map the window and remove it from the ' WindowSet ' . doIgnore :: ManageHook doIgnore = ask >>= \w -> liftX (reveal w) >> doF (W.delete w) doShift :: WorkspaceId -> ManageHook doShift i = doF . W.shiftWin i =<< ask
5fc916b96a3a18bfc7114dae06a3d47171875b034a7ac57078d7757b6840b4ef
basho/casbench
thrift_processor.erl
%% Licensed to the Apache Software Foundation ( ASF ) under one %% or more contributor license agreements. See the NOTICE file %% distributed with this work for additional information %% regarding copyright ownership. The ASF licenses this file 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(thrift_processor). -export([init/1]). -include("thrift_constants.hrl"). -include("thrift_protocol.hrl"). -record(thrift_processor, {handler, in_protocol, out_protocol, service}). init({Server, ProtoGen, Service, Handler}) when is_function(ProtoGen, 0) -> {ok, IProt, OProt} = ProtoGen(), loop(#thrift_processor{in_protocol = IProt, out_protocol = OProt, service = Service, handler = Handler}). loop(State = #thrift_processor{in_protocol = IProto, out_protocol = OProto}) -> case thrift_protocol:read(IProto, message_begin) of #protocol_message_begin{name = Function, type = ?tMessageType_CALL} -> ok = handle_function(State, list_to_atom(Function)), loop(State); #protocol_message_begin{name = Function, type = ?tMessageType_ONEWAY} -> ok = handle_function(State, list_to_atom(Function)), loop(State); {error, timeout} -> thrift_protocol:close_transport(OProto), ok; {error, closed} -> %% error_logger:info_msg("Client disconnected~n"), thrift_protocol:close_transport(OProto), exit(shutdown) end. handle_function(State=#thrift_processor{in_protocol = IProto, out_protocol = OProto, handler = Handler, service = Service}, Function) -> InParams = Service:function_info(Function, params_type), {ok, Params} = thrift_protocol:read(IProto, InParams), try Result = Handler:handle_function(Function, Params), %% {Micro, Result} = better_timer(Handler, handle_function, [Function, Params]), %% error_logger:info_msg("Processed ~p(~p) in ~.4fms~n", %% [Function, Params, Micro/1000.0]), handle_success(State, Function, Result) catch Type:Data -> handle_function_catch(State, Function, Type, Data) end, after_reply(OProto). handle_function_catch(State = #thrift_processor{service = Service}, Function, ErrType, ErrData) -> IsOneway = Service:function_info(Function, reply_type) =:= oneway_void, case {ErrType, ErrData} of _ when IsOneway -> Stack = erlang:get_stacktrace(), error_logger:warning_msg( "oneway void ~p threw error which must be ignored: ~p", [Function, {ErrType, ErrData, Stack}]), ok; {throw, Exception} when is_tuple(Exception), size(Exception) > 0 -> error_logger:warning_msg("~p threw exception: ~p~n", [Function, Exception]), handle_exception(State, Function, Exception), ok; % we still want to accept more requests from this client {error, Error} -> ok = handle_error(State, Function, Error) end. handle_success(State = #thrift_processor{out_protocol = OProto, service = Service}, Function, Result) -> ReplyType = Service:function_info(Function, reply_type), StructName = atom_to_list(Function) ++ "_result", ok = case Result of {reply, ReplyData} -> Reply = {{struct, [{0, ReplyType}]}, {StructName, ReplyData}}, send_reply(OProto, Function, ?tMessageType_REPLY, Reply); ok when ReplyType == {struct, []} -> send_reply(OProto, Function, ?tMessageType_REPLY, {ReplyType, {StructName}}); ok when ReplyType == oneway_void -> %% no reply for oneway void ok end. handle_exception(State = #thrift_processor{out_protocol = OProto, service = Service}, Function, Exception) -> ExceptionType = element(1, Exception), %% Fetch a structure like {struct, [{-2, {struct, {Module, Type}}}, %% {-3, {struct, {Module, Type}}}]} ReplySpec = Service:function_info(Function, exceptions), {struct, XInfo} = ReplySpec, true = is_list(XInfo), Assuming we had a type1 exception , we 'd get : [ undefined , Exception , undefined ] e.g. : [ { -1 , } , { -2 , type1 } , { -3 , type2 } ] ExceptionList = [case Type of ExceptionType -> Exception; _ -> undefined end || {_Fid, {struct, {_Module, Type}}} <- XInfo], ExceptionTuple = list_to_tuple([Function | ExceptionList]), Make sure we got at least one defined case lists:all(fun(X) -> X =:= undefined end, ExceptionList) of true -> ok = handle_unknown_exception(State, Function, Exception); false -> ok = send_reply(OProto, Function, ?tMessageType_REPLY, {ReplySpec, ExceptionTuple}) end. %% %% Called when an exception has been explicitly thrown by the service, but it was %% not one of the exceptions that was defined for the function. %% handle_unknown_exception(State, Function, Exception) -> handle_error(State, Function, {exception_not_declared_as_thrown, Exception}). handle_error(#thrift_processor{out_protocol = OProto}, Function, Error) -> Stack = erlang:get_stacktrace(), error_logger:error_msg("~p had an error: ~p~n", [Function, {Error, Stack}]), Message = case application:get_env(thrift, exceptions_include_traces) of {ok, true} -> lists:flatten(io_lib:format("An error occurred: ~p~n", [{Error, Stack}])); _ -> "An unknown handler error occurred." end, Reply = {?TApplicationException_Structure, #'TApplicationException'{ message = Message, type = ?TApplicationException_UNKNOWN}}, send_reply(OProto, Function, ?tMessageType_EXCEPTION, Reply). send_reply(OProto, Function, ReplyMessageType, Reply) -> ok = thrift_protocol:write(OProto, #protocol_message_begin{ name = atom_to_list(Function), type = ReplyMessageType, seqid = 0}), ok = thrift_protocol:write(OProto, Reply), ok = thrift_protocol:write(OProto, message_end), ok = thrift_protocol:flush_transport(OProto), ok. after_reply(OProto) -> ok = thrift_protocol:flush_transport(OProto) %% ok = thrift_protocol:close_transport(OProto) .
null
https://raw.githubusercontent.com/basho/casbench/90ad7bbb2aebef68e1dcb29ecacd353c11e4ccdd/src/thrift_processor.erl
erlang
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file "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, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. error_logger:info_msg("Client disconnected~n"), {Micro, Result} = better_timer(Handler, handle_function, [Function, Params]), error_logger:info_msg("Processed ~p(~p) in ~.4fms~n", [Function, Params, Micro/1000.0]), we still want to accept more requests from this client no reply for oneway void Fetch a structure like {struct, [{-2, {struct, {Module, Type}}}, {-3, {struct, {Module, Type}}}]} Called when an exception has been explicitly thrown by the service, but it was not one of the exceptions that was defined for the function. ok = thrift_protocol:close_transport(OProto)
Licensed to the Apache Software Foundation ( ASF ) under one to you under the Apache License , Version 2.0 ( the software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(thrift_processor). -export([init/1]). -include("thrift_constants.hrl"). -include("thrift_protocol.hrl"). -record(thrift_processor, {handler, in_protocol, out_protocol, service}). init({Server, ProtoGen, Service, Handler}) when is_function(ProtoGen, 0) -> {ok, IProt, OProt} = ProtoGen(), loop(#thrift_processor{in_protocol = IProt, out_protocol = OProt, service = Service, handler = Handler}). loop(State = #thrift_processor{in_protocol = IProto, out_protocol = OProto}) -> case thrift_protocol:read(IProto, message_begin) of #protocol_message_begin{name = Function, type = ?tMessageType_CALL} -> ok = handle_function(State, list_to_atom(Function)), loop(State); #protocol_message_begin{name = Function, type = ?tMessageType_ONEWAY} -> ok = handle_function(State, list_to_atom(Function)), loop(State); {error, timeout} -> thrift_protocol:close_transport(OProto), ok; {error, closed} -> thrift_protocol:close_transport(OProto), exit(shutdown) end. handle_function(State=#thrift_processor{in_protocol = IProto, out_protocol = OProto, handler = Handler, service = Service}, Function) -> InParams = Service:function_info(Function, params_type), {ok, Params} = thrift_protocol:read(IProto, InParams), try Result = Handler:handle_function(Function, Params), handle_success(State, Function, Result) catch Type:Data -> handle_function_catch(State, Function, Type, Data) end, after_reply(OProto). handle_function_catch(State = #thrift_processor{service = Service}, Function, ErrType, ErrData) -> IsOneway = Service:function_info(Function, reply_type) =:= oneway_void, case {ErrType, ErrData} of _ when IsOneway -> Stack = erlang:get_stacktrace(), error_logger:warning_msg( "oneway void ~p threw error which must be ignored: ~p", [Function, {ErrType, ErrData, Stack}]), ok; {throw, Exception} when is_tuple(Exception), size(Exception) > 0 -> error_logger:warning_msg("~p threw exception: ~p~n", [Function, Exception]), handle_exception(State, Function, Exception), {error, Error} -> ok = handle_error(State, Function, Error) end. handle_success(State = #thrift_processor{out_protocol = OProto, service = Service}, Function, Result) -> ReplyType = Service:function_info(Function, reply_type), StructName = atom_to_list(Function) ++ "_result", ok = case Result of {reply, ReplyData} -> Reply = {{struct, [{0, ReplyType}]}, {StructName, ReplyData}}, send_reply(OProto, Function, ?tMessageType_REPLY, Reply); ok when ReplyType == {struct, []} -> send_reply(OProto, Function, ?tMessageType_REPLY, {ReplyType, {StructName}}); ok when ReplyType == oneway_void -> ok end. handle_exception(State = #thrift_processor{out_protocol = OProto, service = Service}, Function, Exception) -> ExceptionType = element(1, Exception), ReplySpec = Service:function_info(Function, exceptions), {struct, XInfo} = ReplySpec, true = is_list(XInfo), Assuming we had a type1 exception , we 'd get : [ undefined , Exception , undefined ] e.g. : [ { -1 , } , { -2 , type1 } , { -3 , type2 } ] ExceptionList = [case Type of ExceptionType -> Exception; _ -> undefined end || {_Fid, {struct, {_Module, Type}}} <- XInfo], ExceptionTuple = list_to_tuple([Function | ExceptionList]), Make sure we got at least one defined case lists:all(fun(X) -> X =:= undefined end, ExceptionList) of true -> ok = handle_unknown_exception(State, Function, Exception); false -> ok = send_reply(OProto, Function, ?tMessageType_REPLY, {ReplySpec, ExceptionTuple}) end. handle_unknown_exception(State, Function, Exception) -> handle_error(State, Function, {exception_not_declared_as_thrown, Exception}). handle_error(#thrift_processor{out_protocol = OProto}, Function, Error) -> Stack = erlang:get_stacktrace(), error_logger:error_msg("~p had an error: ~p~n", [Function, {Error, Stack}]), Message = case application:get_env(thrift, exceptions_include_traces) of {ok, true} -> lists:flatten(io_lib:format("An error occurred: ~p~n", [{Error, Stack}])); _ -> "An unknown handler error occurred." end, Reply = {?TApplicationException_Structure, #'TApplicationException'{ message = Message, type = ?TApplicationException_UNKNOWN}}, send_reply(OProto, Function, ?tMessageType_EXCEPTION, Reply). send_reply(OProto, Function, ReplyMessageType, Reply) -> ok = thrift_protocol:write(OProto, #protocol_message_begin{ name = atom_to_list(Function), type = ReplyMessageType, seqid = 0}), ok = thrift_protocol:write(OProto, Reply), ok = thrift_protocol:write(OProto, message_end), ok = thrift_protocol:flush_transport(OProto), ok. after_reply(OProto) -> ok = thrift_protocol:flush_transport(OProto) .
dc15ef3f557b7e38ce8aae11793183dec74e52dd1e693cf7f8ac36b3beb0598f
tochicool/bitcoin-dca
Types.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module BitcoinDCA.Types where import BitcoinDCA.Common import Control.Monad (guard) import Data.Aeson (FromJSON (parseJSON), ToJSON (toJSON), Value (String), withText) import Data.Aeson.Types (typeMismatch) import Data.ByteString (ByteString) import Data.Coerce (Coercible, coerce) import Data.Data (Proxy (Proxy)) import Data.Maybe (fromJust) import Data.String (IsString) import qualified Data.Attoparsec.Text as Attoparsec import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (UTCTime, addUTCTime, diffUTCTime) import GHC.Generics (Generic) import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import qualified Haskoin as Bitcoin import qualified Language.Bitcoin.Script.Descriptors as Bitcoin import Money (Dense, ExchangeRate, SomeDense, dense, denseCurrency, exchange, someDenseCurrency, withSomeDense) import System.Cron (CronSchedule, nextMatch, parseCronSchedule, serializeCronSchedule) newtype AssetId = AssetId ByteString deriving (Generic, Show, IsString, Eq, Ord) instance FromJSON AssetId where parseJSON = byteStringParseJSON instance ToJSON AssetId where toJSON = byteStringToJSON newtype OrderId = OrderId ByteString deriving (Generic, Show) newtype Address = Address ByteString deriving (Generic, Show) instance FromJSON Address where parseJSON = byteStringParseJSON instance ToJSON Address where toJSON = byteStringToJSON newtype OutputDescriptor = OutputDescriptor Bitcoin.OutputDescriptor deriving (Generic, Show) instance FromJSON OutputDescriptor where parseJSON = withText "Output descriptor" $ \desc -> case Attoparsec.parseOnly (Bitcoin.outputDescriptorParser Bitcoin.btc <* Attoparsec.endOfInput) desc of Left err -> fail err Right Bitcoin.ChecksumDescriptor {..} -> case checksumStatus of Bitcoin.Invalid invalid -> fail $ "provided checksum '" <> Text.unpack invalid <> "' is invalid - the checksum should be '" <> Text.unpack expectedChecksum <> "'" _ -> return $ OutputDescriptor descriptor instance ToJSON OutputDescriptor where toJSON (OutputDescriptor desc) = String $ Bitcoin.descriptorToText Bitcoin.btc desc newtype WithdrawId = WithdrawId ByteString deriving (Generic, Show) newtype Size = Size SomeDense deriving newtype (Show, Eq, Ord) instance FromJSON Size where parseJSON = someDenseParseJSON "Size" instance ToJSON Size where toJSON = someDenseToJSON newtype Funds = Funds SomeDense deriving newtype (Show, Eq, Ord) instance FromJSON Funds where parseJSON = someDenseParseJSON "Funds" instance ToJSON Funds where toJSON = someDenseToJSON -- | A non-negative amount of money newtype Money asset = Money (Dense asset) deriving newtype (Eq, Ord, Num, Real) instance forall asset. KnownSymbol asset => Show (Money asset) where showsPrec n (Money d) = let c = symbolVal (Proxy :: Proxy asset) in showParen (n > 10) $ showString (showDecimal $ toRational d) . showChar ' ' . (c ++) data OrderStatus = OrderFailed | OrderPending | OrderComplete deriving (Generic, Show) data Asset (asset :: Symbol) = Asset { id :: AssetId, maxPrecision, minWithdrawalAmount :: Money asset, maxWithdrawalAmount :: Maybe (Money asset) } deriving (Generic, Show, Eq) data AssetPair (base :: Symbol) (quote :: Symbol) = AssetPair { base :: AssetId, quote :: AssetId, minMarketFunds :: Money quote, maxMarketFunds :: Maybe (Money quote), quoteIncrement :: Money quote } deriving (Generic, Show, Eq) data Order base = Order {id :: OrderId, status :: OrderStatus, filledSize :: Money base} deriving (Generic, Show) data Withdraw = Withdraw { id :: WithdrawId, status :: WithdrawStatus } deriving (Generic, Show) data WithdrawStatus = WithdrawFailed | WithdrawPending | WithdrawComplete deriving (Generic, Show) class Target a where type TargetQuote a :: Symbol fundsAt :: a -> UTCTime -> Money (TargetQuote a) earliestTimeAt :: a -> Money (TargetQuote a) -> UTCTime data CronTarget quote = CronTarget { startTime :: UTCTime, everyTick :: Money quote, cronSchedule :: CronSchedule } deriving (Show) instance Target (CronTarget quote) where type TargetQuote (CronTarget quote) = quote fundsAt t@CronTarget {..} currentTime | Just previousTime <- previousMatch cronSchedule startTime = (everyTick *) . money' . toRational $ fundsAt' t {startTime = previousTime} currentTime | otherwise = 0 where fundsAt' CronTarget {..} currentTime | Just nextTime <- nextMatch cronSchedule startTime = case currentTime `compare` nextTime of LT -> currentTime `diffUTCTime` startTime / nextTime `diffUTCTime` startTime GT -> 1 + fundsAt' CronTarget {startTime = nextTime, ..} currentTime EQ -> 1 | otherwise = 0 earliestTimeAt t@CronTarget {..} funds | Just previousTime <- previousMatch cronSchedule startTime = flip addUTCTime previousTime $ earliestTimeAt' t {startTime = previousTime} funds | otherwise = startTime where earliestTimeAt' CronTarget {..} totalFunds | Just nextTime <- nextMatch cronSchedule startTime, everyTick > 0, totalFunds > 0 = case everyTick `compare` totalFunds of LT -> nextTime `diffUTCTime` startTime + earliestTimeAt' CronTarget {startTime = nextTime, ..} (totalFunds - everyTick) GT -> (nextTime `diffUTCTime` startTime) * fromRational (toRational totalFunds / toRational everyTick) EQ -> nextTime `diffUTCTime` startTime | otherwise = 0 -- | Will return the previous time from the given starting point where -- this schedule would have matched. Returns Nothing if the schedule will -- never match. Note that this function is inclusive of the given -- time. previousMatch :: CronSchedule -> UTCTime -> Maybe UTCTime previousMatch cs now = This uses ' one - sided ' binary search , making O(lg n ) calls to nextMatch do next <- nextMatch cs now let beforeNext time = do current <- nextMatch cs time if current == next then return time else beforeNext current let searchPrevious lookBehind = do current <- nextMatch cs (addUTCTime (- lookBehind) now) if current < next then beforeNext current else searchPrevious $ 2 * lookBehind searchPrevious 60 newtype Frequency = CronSchedule CronSchedule deriving (Generic, Show) instance FromJSON Frequency where parseJSON (String cronExpression) = either fail return $ CronSchedule <$> parseCronSchedule cronExpression parseJSON value = typeMismatch "String" value instance ToJSON Frequency where toJSON (CronSchedule x) = toJSON $ serializeCronSchedule x money :: Rational -> Maybe (Money asset) money x = do d <- dense x guard (d >= 0) return $ Money d money' :: Rational -> Money asset money' = fromJust . money exchangeMoney :: ExchangeRate src dest -> Money src -> Money dest exchangeMoney rate (Money dense) = Money $ exchange rate dense withSomeMoney :: Coercible a SomeDense => a -> (forall asset. KnownSymbol asset => Money asset -> r) -> r withSomeMoney x f = withSomeDense (coerce x) (f . Money) assetId :: forall asset. KnownSymbol asset => AssetId assetId = AssetId $ Text.encodeUtf8 $ denseCurrency @asset 0 sizeAssetId :: Size -> AssetId sizeAssetId (Size someDense) = AssetId $ Text.encodeUtf8 $ someDenseCurrency someDense fundsAssetId :: Funds -> AssetId fundsAssetId (Funds someDense) = AssetId $ Text.encodeUtf8 $ someDenseCurrency someDense isShitcoin :: forall asset. KnownSymbol asset => Bool isShitcoin = assetId @asset /= "BTC"
null
https://raw.githubusercontent.com/tochicool/bitcoin-dca/20558f7beb0fff5f622733dad83aa4807ee2a2cc/src/BitcoinDCA/Types.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # | A non-negative amount of money | Will return the previous time from the given starting point where this schedule would have matched. Returns Nothing if the schedule will never match. Note that this function is inclusive of the given time.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module BitcoinDCA.Types where import BitcoinDCA.Common import Control.Monad (guard) import Data.Aeson (FromJSON (parseJSON), ToJSON (toJSON), Value (String), withText) import Data.Aeson.Types (typeMismatch) import Data.ByteString (ByteString) import Data.Coerce (Coercible, coerce) import Data.Data (Proxy (Proxy)) import Data.Maybe (fromJust) import Data.String (IsString) import qualified Data.Attoparsec.Text as Attoparsec import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.Time (UTCTime, addUTCTime, diffUTCTime) import GHC.Generics (Generic) import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import qualified Haskoin as Bitcoin import qualified Language.Bitcoin.Script.Descriptors as Bitcoin import Money (Dense, ExchangeRate, SomeDense, dense, denseCurrency, exchange, someDenseCurrency, withSomeDense) import System.Cron (CronSchedule, nextMatch, parseCronSchedule, serializeCronSchedule) newtype AssetId = AssetId ByteString deriving (Generic, Show, IsString, Eq, Ord) instance FromJSON AssetId where parseJSON = byteStringParseJSON instance ToJSON AssetId where toJSON = byteStringToJSON newtype OrderId = OrderId ByteString deriving (Generic, Show) newtype Address = Address ByteString deriving (Generic, Show) instance FromJSON Address where parseJSON = byteStringParseJSON instance ToJSON Address where toJSON = byteStringToJSON newtype OutputDescriptor = OutputDescriptor Bitcoin.OutputDescriptor deriving (Generic, Show) instance FromJSON OutputDescriptor where parseJSON = withText "Output descriptor" $ \desc -> case Attoparsec.parseOnly (Bitcoin.outputDescriptorParser Bitcoin.btc <* Attoparsec.endOfInput) desc of Left err -> fail err Right Bitcoin.ChecksumDescriptor {..} -> case checksumStatus of Bitcoin.Invalid invalid -> fail $ "provided checksum '" <> Text.unpack invalid <> "' is invalid - the checksum should be '" <> Text.unpack expectedChecksum <> "'" _ -> return $ OutputDescriptor descriptor instance ToJSON OutputDescriptor where toJSON (OutputDescriptor desc) = String $ Bitcoin.descriptorToText Bitcoin.btc desc newtype WithdrawId = WithdrawId ByteString deriving (Generic, Show) newtype Size = Size SomeDense deriving newtype (Show, Eq, Ord) instance FromJSON Size where parseJSON = someDenseParseJSON "Size" instance ToJSON Size where toJSON = someDenseToJSON newtype Funds = Funds SomeDense deriving newtype (Show, Eq, Ord) instance FromJSON Funds where parseJSON = someDenseParseJSON "Funds" instance ToJSON Funds where toJSON = someDenseToJSON newtype Money asset = Money (Dense asset) deriving newtype (Eq, Ord, Num, Real) instance forall asset. KnownSymbol asset => Show (Money asset) where showsPrec n (Money d) = let c = symbolVal (Proxy :: Proxy asset) in showParen (n > 10) $ showString (showDecimal $ toRational d) . showChar ' ' . (c ++) data OrderStatus = OrderFailed | OrderPending | OrderComplete deriving (Generic, Show) data Asset (asset :: Symbol) = Asset { id :: AssetId, maxPrecision, minWithdrawalAmount :: Money asset, maxWithdrawalAmount :: Maybe (Money asset) } deriving (Generic, Show, Eq) data AssetPair (base :: Symbol) (quote :: Symbol) = AssetPair { base :: AssetId, quote :: AssetId, minMarketFunds :: Money quote, maxMarketFunds :: Maybe (Money quote), quoteIncrement :: Money quote } deriving (Generic, Show, Eq) data Order base = Order {id :: OrderId, status :: OrderStatus, filledSize :: Money base} deriving (Generic, Show) data Withdraw = Withdraw { id :: WithdrawId, status :: WithdrawStatus } deriving (Generic, Show) data WithdrawStatus = WithdrawFailed | WithdrawPending | WithdrawComplete deriving (Generic, Show) class Target a where type TargetQuote a :: Symbol fundsAt :: a -> UTCTime -> Money (TargetQuote a) earliestTimeAt :: a -> Money (TargetQuote a) -> UTCTime data CronTarget quote = CronTarget { startTime :: UTCTime, everyTick :: Money quote, cronSchedule :: CronSchedule } deriving (Show) instance Target (CronTarget quote) where type TargetQuote (CronTarget quote) = quote fundsAt t@CronTarget {..} currentTime | Just previousTime <- previousMatch cronSchedule startTime = (everyTick *) . money' . toRational $ fundsAt' t {startTime = previousTime} currentTime | otherwise = 0 where fundsAt' CronTarget {..} currentTime | Just nextTime <- nextMatch cronSchedule startTime = case currentTime `compare` nextTime of LT -> currentTime `diffUTCTime` startTime / nextTime `diffUTCTime` startTime GT -> 1 + fundsAt' CronTarget {startTime = nextTime, ..} currentTime EQ -> 1 | otherwise = 0 earliestTimeAt t@CronTarget {..} funds | Just previousTime <- previousMatch cronSchedule startTime = flip addUTCTime previousTime $ earliestTimeAt' t {startTime = previousTime} funds | otherwise = startTime where earliestTimeAt' CronTarget {..} totalFunds | Just nextTime <- nextMatch cronSchedule startTime, everyTick > 0, totalFunds > 0 = case everyTick `compare` totalFunds of LT -> nextTime `diffUTCTime` startTime + earliestTimeAt' CronTarget {startTime = nextTime, ..} (totalFunds - everyTick) GT -> (nextTime `diffUTCTime` startTime) * fromRational (toRational totalFunds / toRational everyTick) EQ -> nextTime `diffUTCTime` startTime | otherwise = 0 previousMatch :: CronSchedule -> UTCTime -> Maybe UTCTime previousMatch cs now = This uses ' one - sided ' binary search , making O(lg n ) calls to nextMatch do next <- nextMatch cs now let beforeNext time = do current <- nextMatch cs time if current == next then return time else beforeNext current let searchPrevious lookBehind = do current <- nextMatch cs (addUTCTime (- lookBehind) now) if current < next then beforeNext current else searchPrevious $ 2 * lookBehind searchPrevious 60 newtype Frequency = CronSchedule CronSchedule deriving (Generic, Show) instance FromJSON Frequency where parseJSON (String cronExpression) = either fail return $ CronSchedule <$> parseCronSchedule cronExpression parseJSON value = typeMismatch "String" value instance ToJSON Frequency where toJSON (CronSchedule x) = toJSON $ serializeCronSchedule x money :: Rational -> Maybe (Money asset) money x = do d <- dense x guard (d >= 0) return $ Money d money' :: Rational -> Money asset money' = fromJust . money exchangeMoney :: ExchangeRate src dest -> Money src -> Money dest exchangeMoney rate (Money dense) = Money $ exchange rate dense withSomeMoney :: Coercible a SomeDense => a -> (forall asset. KnownSymbol asset => Money asset -> r) -> r withSomeMoney x f = withSomeDense (coerce x) (f . Money) assetId :: forall asset. KnownSymbol asset => AssetId assetId = AssetId $ Text.encodeUtf8 $ denseCurrency @asset 0 sizeAssetId :: Size -> AssetId sizeAssetId (Size someDense) = AssetId $ Text.encodeUtf8 $ someDenseCurrency someDense fundsAssetId :: Funds -> AssetId fundsAssetId (Funds someDense) = AssetId $ Text.encodeUtf8 $ someDenseCurrency someDense isShitcoin :: forall asset. KnownSymbol asset => Bool isShitcoin = assetId @asset /= "BTC"
b090a80e24d558e543d3657fc212601fdcb0b6c9ef65c245cbed770b7cb29513
PacktWorkshops/The-Clojure-Workshop
exercise_6_05.clj
(ns packt-clj.chapter-6-tests.exercise-6-05) (def routes [[:paris :london 236] [:paris :frankfurt 121] [:paris :milan 129] [:milan :rome 95] [:milan :barcelona 258] [:barcelona :madrid 141] [:madrid :lisbon 127] [:sevilla :lisbon 138] [:madrid :sevilla 76] [:barcelona :sevilla 203] [:madrid :paris 314] [:frankfurt :milan 204] [:frankfurt :berlin 170] [:frankfurt :geneva 180] [:geneva :paris 123] [:geneva :milan 85] [:frankfurt :prague 148] [:milan :vienna 79] [:vienna :prague 70] [:paris :amsterdam 139] [:amsterdam :berlin 176] [:amsterdam :frankfurt 140] [:vienna :bratislava 15] [:bratislava :prague 64] [:prague :warsaw 110] [:berlin :warsaw 52] [:vienna :budapest 43] [:prague :budapest 91]]) (defn route-list->distance-map [route-list] (->> route-list (map (fn [[_ city cost]] [city cost])) (into {}))) (defn grouped-routes [routes] (->> routes (mapcat (fn [[origin-city dest-city cost :as r]] [r [dest-city origin-city cost]])) (group-by first) (map (fn [[k v]] [k (route-list->distance-map v)])) (into {}))) (def lookup (grouped-routes routes))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter06/tests/packt-clj.chapter-6-tests/src/packt_clj/chapter_6_tests/exercise_6_05.clj
clojure
(ns packt-clj.chapter-6-tests.exercise-6-05) (def routes [[:paris :london 236] [:paris :frankfurt 121] [:paris :milan 129] [:milan :rome 95] [:milan :barcelona 258] [:barcelona :madrid 141] [:madrid :lisbon 127] [:sevilla :lisbon 138] [:madrid :sevilla 76] [:barcelona :sevilla 203] [:madrid :paris 314] [:frankfurt :milan 204] [:frankfurt :berlin 170] [:frankfurt :geneva 180] [:geneva :paris 123] [:geneva :milan 85] [:frankfurt :prague 148] [:milan :vienna 79] [:vienna :prague 70] [:paris :amsterdam 139] [:amsterdam :berlin 176] [:amsterdam :frankfurt 140] [:vienna :bratislava 15] [:bratislava :prague 64] [:prague :warsaw 110] [:berlin :warsaw 52] [:vienna :budapest 43] [:prague :budapest 91]]) (defn route-list->distance-map [route-list] (->> route-list (map (fn [[_ city cost]] [city cost])) (into {}))) (defn grouped-routes [routes] (->> routes (mapcat (fn [[origin-city dest-city cost :as r]] [r [dest-city origin-city cost]])) (group-by first) (map (fn [[k v]] [k (route-list->distance-map v)])) (into {}))) (def lookup (grouped-routes routes))
f5f7b2a95d1564701953ea827da067c3c7d17410310b7819f74552868628d245
kakao/hbase-packet-inspector
pcap_test.clj
(ns hbase-packet-inspector.pcap-test (:require [clojure.test :refer :all] [hbase-packet-inspector.pcap :as pcap :refer :all]) (:import (java.net InetAddress) (org.pcap4j.packet AbstractPacket IpV4Packet$Builder IpV4Rfc1349Tos TcpPacket$Builder UnknownPacket$Builder) (org.pcap4j.packet.namednumber IpNumber IpVersion TcpPort))) (deftest test-packet->map (let [src-addr "0.0.0.0" dst-addr "0.0.0.1" src-port 12345 dst-port 16020 data "foobar" ipv4-packet (.. (IpV4Packet$Builder.) (srcAddr (InetAddress/getByName src-addr)) (dstAddr (InetAddress/getByName dst-addr)) (protocol (IpNumber/TCP)) (version (IpVersion/IPV4)) (tos (IpV4Rfc1349Tos/newInstance 0)) build) unknown-builder (.. (UnknownPacket$Builder.) (rawData (into-array Byte/TYPE (seq data)))) tcp-packet (.. (TcpPacket$Builder.) (srcPort (TcpPort/getInstance (short src-port))) (dstPort (TcpPort/getInstance (short dst-port))) (payloadBuilder unknown-builder) build) packet (proxy [AbstractPacket] [] (iterator [] (.iterator [ipv4-packet tcp-packet]))) packet-map (packet->map packet)] (is (= src-addr (get-in packet-map [:src :addr]))) (is (= dst-addr (get-in packet-map [:dst :addr]))) (is (= src-port (get-in packet-map [:src :port]))) (is (= dst-port (get-in packet-map [:dst :port]))) (is (= (count data) (:length packet-map))) (is (= data (apply str (map char (:data packet-map))))))) (deftest test-packet->map-may-return-nil (let [empty-packet (proxy [AbstractPacket] [] (iterator [] (.iterator [])))] (is (= nil (packet->map empty-packet))))) (deftest test-parse-next-packet (with-redefs [get-next-packet (constantly nil)] (is (= ::pcap/interrupt (parse-next-packet nil)))) (with-redefs [get-next-packet #(throw (InterruptedException. %))] (is (= ::pcap/interrupt (parse-next-packet "interrupted")))) (with-redefs [get-next-packet (constantly :foo) packet->map (constantly nil)] (is (= ::pcap/ignore (parse-next-packet nil)))) (with-redefs [get-next-packet (constantly :foo) packet->map (constantly :bar)] (is (= :bar (parse-next-packet nil)))))
null
https://raw.githubusercontent.com/kakao/hbase-packet-inspector/a62ca478c5f59123155377f2a983b7a69dcdd522/test/hbase_packet_inspector/pcap_test.clj
clojure
(ns hbase-packet-inspector.pcap-test (:require [clojure.test :refer :all] [hbase-packet-inspector.pcap :as pcap :refer :all]) (:import (java.net InetAddress) (org.pcap4j.packet AbstractPacket IpV4Packet$Builder IpV4Rfc1349Tos TcpPacket$Builder UnknownPacket$Builder) (org.pcap4j.packet.namednumber IpNumber IpVersion TcpPort))) (deftest test-packet->map (let [src-addr "0.0.0.0" dst-addr "0.0.0.1" src-port 12345 dst-port 16020 data "foobar" ipv4-packet (.. (IpV4Packet$Builder.) (srcAddr (InetAddress/getByName src-addr)) (dstAddr (InetAddress/getByName dst-addr)) (protocol (IpNumber/TCP)) (version (IpVersion/IPV4)) (tos (IpV4Rfc1349Tos/newInstance 0)) build) unknown-builder (.. (UnknownPacket$Builder.) (rawData (into-array Byte/TYPE (seq data)))) tcp-packet (.. (TcpPacket$Builder.) (srcPort (TcpPort/getInstance (short src-port))) (dstPort (TcpPort/getInstance (short dst-port))) (payloadBuilder unknown-builder) build) packet (proxy [AbstractPacket] [] (iterator [] (.iterator [ipv4-packet tcp-packet]))) packet-map (packet->map packet)] (is (= src-addr (get-in packet-map [:src :addr]))) (is (= dst-addr (get-in packet-map [:dst :addr]))) (is (= src-port (get-in packet-map [:src :port]))) (is (= dst-port (get-in packet-map [:dst :port]))) (is (= (count data) (:length packet-map))) (is (= data (apply str (map char (:data packet-map))))))) (deftest test-packet->map-may-return-nil (let [empty-packet (proxy [AbstractPacket] [] (iterator [] (.iterator [])))] (is (= nil (packet->map empty-packet))))) (deftest test-parse-next-packet (with-redefs [get-next-packet (constantly nil)] (is (= ::pcap/interrupt (parse-next-packet nil)))) (with-redefs [get-next-packet #(throw (InterruptedException. %))] (is (= ::pcap/interrupt (parse-next-packet "interrupted")))) (with-redefs [get-next-packet (constantly :foo) packet->map (constantly nil)] (is (= ::pcap/ignore (parse-next-packet nil)))) (with-redefs [get-next-packet (constantly :foo) packet->map (constantly :bar)] (is (= :bar (parse-next-packet nil)))))
5356626d5abfe6ca51cf7d548857e8ad00fd51b6cce5366f234e2f9cb79bb2bf
footprintanalytics/footprint-web
prometheus_test.clj
(ns metabase.analytics.prometheus-test (:require [clj-http.client :as http] [clojure.set :as set] [clojure.string :as str] [clojure.test :refer :all] [iapetos.registry :as registry] [metabase.analytics.prometheus :as prometheus] [metabase.test.fixtures :as fixtures] [metabase.troubleshooting :as troubleshooting]) (:import org.eclipse.jetty.server.Server [io.prometheus.client Collector GaugeMetricFamily])) ensure a handler to instrument with jetty_stats and a db so the c3p0 stats have at least one connection (use-fixtures :once (fixtures/initialize :db :web-server)) (def ^:private common-metrics "Common metric types from the registry" #{"c3p0_max_pool_size" "c3p0_min_pool_size" "c3p0_num_busy_connections" "c3p0_num_connections" "c3p0_num_idle_connections" "jetty_async_dispatches_total" "jetty_async_requests_total" "jetty_async_requests_waiting" "jetty_async_requests_waiting_max" "jetty_dispatched_active" "jetty_dispatched_active_max" "jetty_dispatched_time_max" "jetty_dispatched_time_seconds_total" "jetty_dispatched_total" "jetty_expires_total" "jetty_request_time_max_seconds" "jetty_requests_active" "jetty_requests_active_max" "jetty_requests_total" "jetty_responses_bytes_total" "jetty_responses_total" "jetty_stats_seconds" "jvm_gc_collection_seconds_count" "jvm_gc_collection_seconds_sum" "jvm_memory_bytes_committed" "jvm_memory_bytes_init" "jvm_memory_bytes_max" "jvm_memory_bytes_used" "jvm_memory_objects_pending_finalization" "jvm_memory_pool_bytes_committed" "jvm_memory_pool_bytes_init" "jvm_memory_pool_bytes_max" "jvm_memory_pool_bytes_used" "jvm_memory_pool_collection_committed_bytes" "jvm_memory_pool_collection_init_bytes" "jvm_memory_pool_collection_max_bytes" "jvm_memory_pool_collection_used_bytes" "jvm_threads_current" "jvm_threads_daemon" "jvm_threads_deadlocked" "jvm_threads_deadlocked_monitor" "jvm_threads_peak" "jvm_threads_started_total" "jvm_threads_state" "process_cpu_seconds_total" "process_max_fds" "process_open_fds" "process_start_time_seconds" "jetty_request_time_seconds_total"}) (defn- metric-tags "Returns a set of tags of prometheus metrics. Ie logs are ``` jvm_threads_state{state=\"TERMINATED\",} 0.0 jvm_threads_peak 141.0 ``` Returns #{\"jvm_threads_state\" \"jvm_threads_peak\"}. " [port] (->> (http/get (format ":%s/metrics" port)) :body str/split-lines (into #{} (comp (filter (complement #(str/starts-with? % "#"))) lines look like " jvm_memory_pool_collection_init_bytes{pool=\"G1 Survivor Space\ " , } 0.0 " (map (fn [line] (re-find #"^[_a-z0-9]*" line))))))) (defn- metric-lines "Returns a sequence of log lines with comments removed." [port] (->> (http/get (format ":%s/metrics" port)) :body str/split-lines (remove #(str/starts-with? % "#")))) (defmacro with-prometheus-system "Run tests with a prometheus web server and registry. Provide binding symbols in a tuple of [port system]. Port will be bound to the random port used for the metrics endpoint and system will be a [[PrometheusSystem]] which has a registry and web-server." [[port system] & body] `(let [~system ^metabase.analytics.prometheus.PrometheusSystem (#'prometheus/make-prometheus-system 0 (name (gensym "test-registry"))) server# ^Server (.web-server ~system) ~port (.. server# getURI getPort)] (try ~@body (finally (prometheus/stop-web-server ~system))))) (deftest web-server-test (testing "Can get metrics from the web-server" (with-prometheus-system [port _] (let [metrics-in-registry (metric-tags port)] (is (seq (set/intersection common-metrics metrics-in-registry)) "Did not get metrics from the port")))) (testing "Throws helpful message if cannot start server" ;; start another system on the same port (with-prometheus-system [port _] (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Failed to initialize Prometheus on port" (#'prometheus/make-prometheus-system port "test-failure")))))) (deftest c3p0-collector-test (testing "Registry has c3p0 registered" (with-prometheus-system [_ system] (let [registry (.registry system) c3p0-collector (registry/get registry {:name "c3p0-stats" :namespace "metabase_database"} nil)] (is c3p0-collector "c3p0 stats not found")))) (testing "Registry has an entry for each database in [[troubleshooting/connection-pool-info]]" (with-prometheus-system [_ system] (let [registry (.registry system) c3p0-collector (registry/get registry {:name "c3p0_stats" :namespace "metabase_database"} nil) _ (assert c3p0-collector "Did not find c3p0 collector") measurements (.collect ^Collector c3p0-collector) _ (is (pos? (count measurements)) "No measurements taken")] (is (= (count (:connection-pools (troubleshooting/connection-pool-info))) (count (.samples ^GaugeMetricFamily (first measurements)))) "Expected one entry per database for each measurement")))) (testing "Registry includes c3p0 stats" (with-prometheus-system [port _] (let [[db-name values] (first (:connection-pools (troubleshooting/connection-pool-info))) tag-name (comp :label #'prometheus/label-translation) expected-lines (set (for [[tag value] values] (format "%s{database=\"%s\",} %s" (tag-name tag) db-name (double value)))) actual-lines (into #{} (filter #(str/starts-with? % "c3p0")) (metric-lines port))] (is (seq (set/intersection expected-lines actual-lines)) "Registry does not have c3p0 metrics in it")))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/analytics/prometheus_test.clj
clojure
start another system on the same port
(ns metabase.analytics.prometheus-test (:require [clj-http.client :as http] [clojure.set :as set] [clojure.string :as str] [clojure.test :refer :all] [iapetos.registry :as registry] [metabase.analytics.prometheus :as prometheus] [metabase.test.fixtures :as fixtures] [metabase.troubleshooting :as troubleshooting]) (:import org.eclipse.jetty.server.Server [io.prometheus.client Collector GaugeMetricFamily])) ensure a handler to instrument with jetty_stats and a db so the c3p0 stats have at least one connection (use-fixtures :once (fixtures/initialize :db :web-server)) (def ^:private common-metrics "Common metric types from the registry" #{"c3p0_max_pool_size" "c3p0_min_pool_size" "c3p0_num_busy_connections" "c3p0_num_connections" "c3p0_num_idle_connections" "jetty_async_dispatches_total" "jetty_async_requests_total" "jetty_async_requests_waiting" "jetty_async_requests_waiting_max" "jetty_dispatched_active" "jetty_dispatched_active_max" "jetty_dispatched_time_max" "jetty_dispatched_time_seconds_total" "jetty_dispatched_total" "jetty_expires_total" "jetty_request_time_max_seconds" "jetty_requests_active" "jetty_requests_active_max" "jetty_requests_total" "jetty_responses_bytes_total" "jetty_responses_total" "jetty_stats_seconds" "jvm_gc_collection_seconds_count" "jvm_gc_collection_seconds_sum" "jvm_memory_bytes_committed" "jvm_memory_bytes_init" "jvm_memory_bytes_max" "jvm_memory_bytes_used" "jvm_memory_objects_pending_finalization" "jvm_memory_pool_bytes_committed" "jvm_memory_pool_bytes_init" "jvm_memory_pool_bytes_max" "jvm_memory_pool_bytes_used" "jvm_memory_pool_collection_committed_bytes" "jvm_memory_pool_collection_init_bytes" "jvm_memory_pool_collection_max_bytes" "jvm_memory_pool_collection_used_bytes" "jvm_threads_current" "jvm_threads_daemon" "jvm_threads_deadlocked" "jvm_threads_deadlocked_monitor" "jvm_threads_peak" "jvm_threads_started_total" "jvm_threads_state" "process_cpu_seconds_total" "process_max_fds" "process_open_fds" "process_start_time_seconds" "jetty_request_time_seconds_total"}) (defn- metric-tags "Returns a set of tags of prometheus metrics. Ie logs are ``` jvm_threads_state{state=\"TERMINATED\",} 0.0 jvm_threads_peak 141.0 ``` Returns #{\"jvm_threads_state\" \"jvm_threads_peak\"}. " [port] (->> (http/get (format ":%s/metrics" port)) :body str/split-lines (into #{} (comp (filter (complement #(str/starts-with? % "#"))) lines look like " jvm_memory_pool_collection_init_bytes{pool=\"G1 Survivor Space\ " , } 0.0 " (map (fn [line] (re-find #"^[_a-z0-9]*" line))))))) (defn- metric-lines "Returns a sequence of log lines with comments removed." [port] (->> (http/get (format ":%s/metrics" port)) :body str/split-lines (remove #(str/starts-with? % "#")))) (defmacro with-prometheus-system "Run tests with a prometheus web server and registry. Provide binding symbols in a tuple of [port system]. Port will be bound to the random port used for the metrics endpoint and system will be a [[PrometheusSystem]] which has a registry and web-server." [[port system] & body] `(let [~system ^metabase.analytics.prometheus.PrometheusSystem (#'prometheus/make-prometheus-system 0 (name (gensym "test-registry"))) server# ^Server (.web-server ~system) ~port (.. server# getURI getPort)] (try ~@body (finally (prometheus/stop-web-server ~system))))) (deftest web-server-test (testing "Can get metrics from the web-server" (with-prometheus-system [port _] (let [metrics-in-registry (metric-tags port)] (is (seq (set/intersection common-metrics metrics-in-registry)) "Did not get metrics from the port")))) (testing "Throws helpful message if cannot start server" (with-prometheus-system [port _] (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Failed to initialize Prometheus on port" (#'prometheus/make-prometheus-system port "test-failure")))))) (deftest c3p0-collector-test (testing "Registry has c3p0 registered" (with-prometheus-system [_ system] (let [registry (.registry system) c3p0-collector (registry/get registry {:name "c3p0-stats" :namespace "metabase_database"} nil)] (is c3p0-collector "c3p0 stats not found")))) (testing "Registry has an entry for each database in [[troubleshooting/connection-pool-info]]" (with-prometheus-system [_ system] (let [registry (.registry system) c3p0-collector (registry/get registry {:name "c3p0_stats" :namespace "metabase_database"} nil) _ (assert c3p0-collector "Did not find c3p0 collector") measurements (.collect ^Collector c3p0-collector) _ (is (pos? (count measurements)) "No measurements taken")] (is (= (count (:connection-pools (troubleshooting/connection-pool-info))) (count (.samples ^GaugeMetricFamily (first measurements)))) "Expected one entry per database for each measurement")))) (testing "Registry includes c3p0 stats" (with-prometheus-system [port _] (let [[db-name values] (first (:connection-pools (troubleshooting/connection-pool-info))) tag-name (comp :label #'prometheus/label-translation) expected-lines (set (for [[tag value] values] (format "%s{database=\"%s\",} %s" (tag-name tag) db-name (double value)))) actual-lines (into #{} (filter #(str/starts-with? % "c3p0")) (metric-lines port))] (is (seq (set/intersection expected-lines actual-lines)) "Registry does not have c3p0 metrics in it")))))
0309ef30acfedee14622f52c5e006a57cc63f4ba299e71193d7161621a3494db
ggreif/omega
CommentDef.hs
module CommentDef (cLine,cStart,cEnd,nestedC) where ----------------------------------------------------------- -- In order to do layout, we need to "skip white space" -- We need combinators that compute white space. Thus we -- need to know how comments are formed. These constants -- let us compute a whitespace parser. They fields in TokenDef are derived from these definitions -- Haskell Style cStart = "{-" -- (commentStart tokenDef) cEnd = "-}" -- (commentEnd tokenDef) cLine = "--" -- (commentLine tokenDef) ( )
null
https://raw.githubusercontent.com/ggreif/omega/016a3b48313ec2c68e8d8ad60147015bc38f2767/src/CommentDef.hs
haskell
--------------------------------------------------------- In order to do layout, we need to "skip white space" We need combinators that compute white space. Thus we need to know how comments are formed. These constants let us compute a whitespace parser. They fields in Haskell Style (commentStart tokenDef) (commentEnd tokenDef) (commentLine tokenDef)
module CommentDef (cLine,cStart,cEnd,nestedC) where TokenDef are derived from these definitions ( )
62a3e1f142e617cf280044e4454ab20aac3b52029597b2830ce38b52640444a8
nathell/lithium
closure.clj
(ns lithium.compiler.closure (:require [lithium.compiler.ast :as ast])) (defn free-variable-analysis [ast] (ast/walk (assoc ast :bound-vars []) (fn [ast] (ast/match ast ast/let-like [bound-vars bindings body] (let [bindings (loop [acc [] bound-vars bound-vars bindings bindings] (let [{:keys [symbol expr] :as binding} (first bindings)] (if binding (recur (conj acc {:symbol symbol, :expr (assoc expr :bound-vars bound-vars)}) (conj bound-vars symbol) (next bindings)) acc))) body-bound-vars (into bound-vars (map :symbol bindings))] (assoc ast :bindings bindings :body (map #(assoc % :bound-vars body-bound-vars) body))) :fn [args body bound-vars] (let [body-bound-vars (into bound-vars args)] (assoc ast :body (map #(assoc % :bound-vars body-bound-vars) body))) ;; otherwise (ast/expr-update ast assoc :bound-vars (:bound-vars ast)))) identity)) (defn collect-closures [ast] (let [codes (atom []) outer-xform (fn [ast] (ast/match ast :fn [args body bound-vars] (let [label (gensym "cl")] (swap! codes conj {:type :code, :label label, :args args, :bound-vars bound-vars, :body body}) {:type :closure, :label label, :vars bound-vars}))) transformed (ast/walk ast identity outer-xform)] {:type :labels, :labels @codes, :body transformed}))
null
https://raw.githubusercontent.com/nathell/lithium/644604ae50eb5495e227ed6f1e32744020e86e2d/src/lithium/compiler/closure.clj
clojure
otherwise
(ns lithium.compiler.closure (:require [lithium.compiler.ast :as ast])) (defn free-variable-analysis [ast] (ast/walk (assoc ast :bound-vars []) (fn [ast] (ast/match ast ast/let-like [bound-vars bindings body] (let [bindings (loop [acc [] bound-vars bound-vars bindings bindings] (let [{:keys [symbol expr] :as binding} (first bindings)] (if binding (recur (conj acc {:symbol symbol, :expr (assoc expr :bound-vars bound-vars)}) (conj bound-vars symbol) (next bindings)) acc))) body-bound-vars (into bound-vars (map :symbol bindings))] (assoc ast :bindings bindings :body (map #(assoc % :bound-vars body-bound-vars) body))) :fn [args body bound-vars] (let [body-bound-vars (into bound-vars args)] (assoc ast :body (map #(assoc % :bound-vars body-bound-vars) body))) (ast/expr-update ast assoc :bound-vars (:bound-vars ast)))) identity)) (defn collect-closures [ast] (let [codes (atom []) outer-xform (fn [ast] (ast/match ast :fn [args body bound-vars] (let [label (gensym "cl")] (swap! codes conj {:type :code, :label label, :args args, :bound-vars bound-vars, :body body}) {:type :closure, :label label, :vars bound-vars}))) transformed (ast/walk ast identity outer-xform)] {:type :labels, :labels @codes, :body transformed}))
34ed44ede86b147b3353a63a25690cca72e3c9d2a9dfe059022764431b092fb2
exercism/common-lisp
example.lisp
(defpackage :proverb (:use :cl) (:export :recite)) (in-package :proverb) (defun recite (strings) (if strings (let* ((interleaved (apply #'append (mapcar #'list strings strings))) (without-ends (cdr (butlast interleaved))) (proverb-bulk (format nil "~{For want of a ~A the ~A was lost.~%~}" without-ends))) (format nil "~AAnd all for the want of a ~A." proverb-bulk (car strings))) ""))
null
https://raw.githubusercontent.com/exercism/common-lisp/61882db3d96ccfd73bf14281c4f47be199de03fb/exercises/practice/proverb/.meta/example.lisp
lisp
(defpackage :proverb (:use :cl) (:export :recite)) (in-package :proverb) (defun recite (strings) (if strings (let* ((interleaved (apply #'append (mapcar #'list strings strings))) (without-ends (cdr (butlast interleaved))) (proverb-bulk (format nil "~{For want of a ~A the ~A was lost.~%~}" without-ends))) (format nil "~AAnd all for the want of a ~A." proverb-bulk (car strings))) ""))
6f3ddb226f22f23d1babe0e91cb7d9eccad36505538a251c7be328edf4e8a11f
sbcl/sbcl
heapwalk.impure.lisp
(defun mul (x y) (declare (sb-vm:signed-word x y)) (* x y)) (compile 'mul) (defun manymul (n &aux res) (dotimes (i n res) (setq res (mul (floor (- (expt 2 (- sb-vm:n-word-bits 2))) 1000) (+ i 1000))))) (compile 'manymul) (defun walk () (let ((v (make-array 1000)) (ct 0)) (sb-vm:map-allocated-objects (lambda (obj type size) (declare (ignore size)) (when (and (= type sb-vm:list-pointer-lowtag) (= (sb-kernel:generation-of obj) 0) (< ct 1000)) (setf (aref v ct) obj) (incf ct))) :dynamic) (let ((*print-level* 2) (*print-length* 4) (*standard-output* (make-broadcast-stream))) (dotimes (i ct) (princ (aref v i)))))) (compile 'walk) ;;; As a precondition to asserting that heap walking did not ;;; visit an alleged cons that is a filler object, ;;; assert that there is the telltale pattern (if applicable). #+(or arm64 x86-64) (let ((product (manymul 1))) (sb-sys:with-pinned-objects (product) (let ((word (sb-sys:sap-ref-word (sb-sys:int-sap (sb-kernel:get-lisp-obj-address product)) (- (ash 2 sb-vm:word-shift) sb-vm:other-pointer-lowtag)))) (assert (= word sb-ext:most-positive-word))))) (manymul 100) ;;; Granted it's not a great idea to assume that anything in the heap ;;; can be printed, but this test was a fairly easy way to get ;;; "Unhandled memory fault at #xFFFFFFFFFFFFFFF0." The should print approximately one cons ( for GC epoch ) (with-test (:name :heapwalk-safety) (progn (gc :gen 1) (manymul 100) (walk)))
null
https://raw.githubusercontent.com/sbcl/sbcl/9f926c257fe39ef0613be77f4aff30f071655873/tests/heapwalk.impure.lisp
lisp
As a precondition to asserting that heap walking did not visit an alleged cons that is a filler object, assert that there is the telltale pattern (if applicable). Granted it's not a great idea to assume that anything in the heap can be printed, but this test was a fairly easy way to get "Unhandled memory fault at #xFFFFFFFFFFFFFFF0."
(defun mul (x y) (declare (sb-vm:signed-word x y)) (* x y)) (compile 'mul) (defun manymul (n &aux res) (dotimes (i n res) (setq res (mul (floor (- (expt 2 (- sb-vm:n-word-bits 2))) 1000) (+ i 1000))))) (compile 'manymul) (defun walk () (let ((v (make-array 1000)) (ct 0)) (sb-vm:map-allocated-objects (lambda (obj type size) (declare (ignore size)) (when (and (= type sb-vm:list-pointer-lowtag) (= (sb-kernel:generation-of obj) 0) (< ct 1000)) (setf (aref v ct) obj) (incf ct))) :dynamic) (let ((*print-level* 2) (*print-length* 4) (*standard-output* (make-broadcast-stream))) (dotimes (i ct) (princ (aref v i)))))) (compile 'walk) #+(or arm64 x86-64) (let ((product (manymul 1))) (sb-sys:with-pinned-objects (product) (let ((word (sb-sys:sap-ref-word (sb-sys:int-sap (sb-kernel:get-lisp-obj-address product)) (- (ash 2 sb-vm:word-shift) sb-vm:other-pointer-lowtag)))) (assert (= word sb-ext:most-positive-word))))) (manymul 100) The should print approximately one cons ( for GC epoch ) (with-test (:name :heapwalk-safety) (progn (gc :gen 1) (manymul 100) (walk)))
bdf8c7ba1c4a45cf8eb87ab66a11808cde0e0da41482d6aa7345dc2c8525ebed
lorepub/moot
Foundation.hs
# OPTIONS_GHC -fno - warn - orphans # module Foundation where import Import.NoFoundation import Control.Monad.Logger (LogSource) import Database.Persist.Sql (runSqlPool) import Text.Blaze.Html.Renderer.Text (renderHtml) import Text.Jasmine (minifym) import Yesod.Core.Types (Logger) import Yesod.Default.Util (addStaticContentExternal) import qualified Yesod.Core.Unsafe as Unsafe import AppType import Routes type Form x = Html -> MForm (HandlerFor App) (FormResult x, Widget) instance Yesod App where approot :: Approot App approot = ApprootRequest $ \app req -> case appRoot $ appSettings app of Nothing -> getApprootText guessApproot app req Just root -> root makeSessionBackend :: App -> IO (Maybe SessionBackend) makeSessionBackend _ = Just <$> defaultClientSessionBackend timeout in minutes "config/client_session_key.aes" errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined defaultLayout w = do p <- widgetToPageContent w msgs <- getMessages let pt = pageTitle p title = case renderHtml pt of "" -> "Moot" t -> "Moot - " <> t withUrlRenderer [hamlet| $newline never $doctype 5 <html> <head> <title>#{title} ^{pageHead p} <body> $forall (status, msg) <- msgs <p class="message #{status}">#{msg} ^{pageBody p} |] yesodMiddleware :: ToTypedContent res => Handler res -> Handler res yesodMiddleware = defaultYesodMiddleware isAuthorized :: Route App -- ^ The route the user is visiting. -> Bool -- ^ Whether or not this is a "write" request. -> Handler AuthResult isAuthorized _ _ = return Authorized addStaticContent :: Text -- ^ The file extension -> Text -- ^ The MIME content type -> LByteString -- ^ The contents of the file -> Handler (Maybe (Either Text (Route App, [(Text, Text)]))) addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where genFileName lbs = "autogen-" ++ base64md5 lbs shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool shouldLogIO app _source level = return $ appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger :: App -> IO Logger makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB :: SqlPersistT Handler a -> Handler a runDB action = do app <- getYesod runSqlPool action $ appConnPool app instance YesodPersistRunner App where getDBRunner :: Handler (DBRunner App, Handler ()) getDBRunner = defaultGetDBRunner appConnPool instance RenderMessage App FormMessage where renderMessage :: App -> [Lang] -> FormMessage -> Text renderMessage _ _ = defaultFormMessage instance HasHttpManager App where getHttpManager :: App -> Manager getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
null
https://raw.githubusercontent.com/lorepub/moot/793c72d046762ec01a250416667e041b35eec7f8/src/Foundation.hs
haskell
^ The route the user is visiting. ^ Whether or not this is a "write" request. ^ The file extension ^ The MIME content type ^ The contents of the file How to run database actions.
# OPTIONS_GHC -fno - warn - orphans # module Foundation where import Import.NoFoundation import Control.Monad.Logger (LogSource) import Database.Persist.Sql (runSqlPool) import Text.Blaze.Html.Renderer.Text (renderHtml) import Text.Jasmine (minifym) import Yesod.Core.Types (Logger) import Yesod.Default.Util (addStaticContentExternal) import qualified Yesod.Core.Unsafe as Unsafe import AppType import Routes type Form x = Html -> MForm (HandlerFor App) (FormResult x, Widget) instance Yesod App where approot :: Approot App approot = ApprootRequest $ \app req -> case appRoot $ appSettings app of Nothing -> getApprootText guessApproot app req Just root -> root makeSessionBackend :: App -> IO (Maybe SessionBackend) makeSessionBackend _ = Just <$> defaultClientSessionBackend timeout in minutes "config/client_session_key.aes" errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined errorHandler NotFound = undefined defaultLayout w = do p <- widgetToPageContent w msgs <- getMessages let pt = pageTitle p title = case renderHtml pt of "" -> "Moot" t -> "Moot - " <> t withUrlRenderer [hamlet| $newline never $doctype 5 <html> <head> <title>#{title} ^{pageHead p} <body> $forall (status, msg) <- msgs <p class="message #{status}">#{msg} ^{pageBody p} |] yesodMiddleware :: ToTypedContent res => Handler res -> Handler res yesodMiddleware = defaultYesodMiddleware isAuthorized -> Handler AuthResult isAuthorized _ _ = return Authorized addStaticContent -> Handler (Maybe (Either Text (Route App, [(Text, Text)]))) addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where genFileName lbs = "autogen-" ++ base64md5 lbs shouldLogIO :: App -> LogSource -> LogLevel -> IO Bool shouldLogIO app _source level = return $ appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger :: App -> IO Logger makeLogger = return . appLogger instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB :: SqlPersistT Handler a -> Handler a runDB action = do app <- getYesod runSqlPool action $ appConnPool app instance YesodPersistRunner App where getDBRunner :: Handler (DBRunner App, Handler ()) getDBRunner = defaultGetDBRunner appConnPool instance RenderMessage App FormMessage where renderMessage :: App -> [Lang] -> FormMessage -> Text renderMessage _ _ = defaultFormMessage instance HasHttpManager App where getHttpManager :: App -> Manager getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
4d9eeb4949487abe702e0a6660d4e916df267294ad5b02e2d030cfb41cbe406b
kadena-io/chainweaver
InMemoryStorage.hs
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE TypeApplications # module Frontend.Storage.InMemoryStorage where import Control.Monad.Free (iterM) import Control.Monad.Reader import Data.Aeson (FromJSON, ToJSON, eitherDecode) import Data.Bool (bool) import qualified Data.ByteString.Lazy as LBS import Data.Constraint.Extras (Has, Has', has) import Data.Dependent.Map (DMap) import Data.Dependent.Sum (DSum(..)) import qualified Data.Dependent.Map as DMap import Data.Functor.Identity (Identity(..)) import Data.IORef (IORef, newIORef, readIORef, modifyIORef) import Data.Functor (void) import Data.GADT.Show (GShow, gshow) import Data.GADT.Compare (GCompare) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes) import Data.Proxy (Proxy(Proxy)) import Data.Some import Data.Text (Text) import Data.Universe.Some (UniverseSome, universeSome) import Numeric.Natural (Natural) import System.Directory (doesFileExist) import System.FilePath ((</>)) import Frontend.Crypto.Class import Frontend.Storage lookupRef :: IORef (Map Text Text) -> Text -> IO (Maybe Text) lookupRef ref k = Map.lookup k <$> readIORef ref insertRef :: IORef (Map Text Text) -> Text -> Text -> IO () insertRef ref k v = void $ modifyIORef ref (Map.insert k v) removeRef :: IORef (Map Text Text) -> Text -> IO () removeRef ref k = void $ modifyIORef ref (Map.delete k) keysRef :: IORef (Map Text Text) -> IO [Text] keysRef ref = Map.keys <$> readIORef ref type IMS = (IORef (Map Text Text), IORef (Map Text Text)) newtype InMemoryStorage a = InMemoryStorage { unInMemoryStorage :: ReaderT IMS IO a } deriving (Functor, Applicative, Monad, MonadIO) chooseRef :: StoreType -> InMemoryStorage (IORef (Map Text Text)) chooseRef st = do (localRef, sessionRef) <- InMemoryStorage ask pure $ case st of StoreType_Local -> localRef StoreType_Session -> sessionRef instance HasStorage InMemoryStorage where getItemStorage' st k = do ref <- chooseRef st InMemoryStorage $ lift $ lookupRef ref k setItemStorage' st k v = do ref <- chooseRef st InMemoryStorage $ lift $ insertRef ref k v removeItemStorage' st k = do ref <- chooseRef st InMemoryStorage $ lift $ removeRef ref k runInMemoryStorage :: InMemoryStorage a -> IMS -> IO a runInMemoryStorage (InMemoryStorage r) = runReaderT r newInMemoryStorage :: IO IMS newInMemoryStorage = do localRef <- newIORef (Map.empty :: Map Text Text) sessionRef <- newIORef (Map.empty :: Map Text Text) pure (localRef, sessionRef) -- This function *should* be cool because it ought to allow us to drop in a desktop storage directory -- into the folder for a given version and then source those files into the inmem store for the tests -- We could use the desktop interpreter , but that 's probably a bit weird given it is operating in JSM ( even -- though it doesn't need to for its own needs). inMemoryStorageFromTestData :: forall k . ( GShow k , GCompare k , Has FromJSON k , Has' FromJSON k Identity , Has ToJSON k , FromJSON (Some k) , UniverseSome k ) => StoreKeyMetaPrefix -> Proxy k -> Natural -> FilePath -> IO IMS inMemoryStorageFromTestData p _ ver dirPath = do dmap <- keyUniverseToFilesDMap ims <- newInMemoryStorage _ <- runInMemoryStorage (restoreLocalStorageDump p dmap ver) ims pure ims where keyToPath :: k a -> FilePath keyToPath k = dirPath </> gshow k keyToByteString :: k a -> IO (Maybe LBS.ByteString) keyToByteString k = do let kp = keyToPath k exists <- doesFileExist kp bool (pure Nothing) (fmap Just (LBS.readFile $ keyToPath k)) exists keyToFileDSum :: forall a. k a -> IO (Maybe (DSum k Identity)) keyToFileDSum k = do mbs <- keyToByteString k pure $ has @FromJSON k $ do let decRes = traverse (eitherDecode @a) mbs either error (fmap (\v -> (k :=> Identity v))) decRes keyUniverseToFilesDMap :: IO (DMap k Identity) keyUniverseToFilesDMap = fmap (DMap.fromList . catMaybes) . traverse (\(Some k) -> keyToFileDSum k) $ universeSome @k
null
https://raw.githubusercontent.com/kadena-io/chainweaver/3ea0bb317c07ddf954d4ebf24b33d1be7d5f9c45/frontend/tests/Frontend/Storage/InMemoryStorage.hs
haskell
This function *should* be cool because it ought to allow us to drop in a desktop storage directory into the folder for a given version and then source those files into the inmem store for the tests though it doesn't need to for its own needs).
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE TypeApplications # module Frontend.Storage.InMemoryStorage where import Control.Monad.Free (iterM) import Control.Monad.Reader import Data.Aeson (FromJSON, ToJSON, eitherDecode) import Data.Bool (bool) import qualified Data.ByteString.Lazy as LBS import Data.Constraint.Extras (Has, Has', has) import Data.Dependent.Map (DMap) import Data.Dependent.Sum (DSum(..)) import qualified Data.Dependent.Map as DMap import Data.Functor.Identity (Identity(..)) import Data.IORef (IORef, newIORef, readIORef, modifyIORef) import Data.Functor (void) import Data.GADT.Show (GShow, gshow) import Data.GADT.Compare (GCompare) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (catMaybes) import Data.Proxy (Proxy(Proxy)) import Data.Some import Data.Text (Text) import Data.Universe.Some (UniverseSome, universeSome) import Numeric.Natural (Natural) import System.Directory (doesFileExist) import System.FilePath ((</>)) import Frontend.Crypto.Class import Frontend.Storage lookupRef :: IORef (Map Text Text) -> Text -> IO (Maybe Text) lookupRef ref k = Map.lookup k <$> readIORef ref insertRef :: IORef (Map Text Text) -> Text -> Text -> IO () insertRef ref k v = void $ modifyIORef ref (Map.insert k v) removeRef :: IORef (Map Text Text) -> Text -> IO () removeRef ref k = void $ modifyIORef ref (Map.delete k) keysRef :: IORef (Map Text Text) -> IO [Text] keysRef ref = Map.keys <$> readIORef ref type IMS = (IORef (Map Text Text), IORef (Map Text Text)) newtype InMemoryStorage a = InMemoryStorage { unInMemoryStorage :: ReaderT IMS IO a } deriving (Functor, Applicative, Monad, MonadIO) chooseRef :: StoreType -> InMemoryStorage (IORef (Map Text Text)) chooseRef st = do (localRef, sessionRef) <- InMemoryStorage ask pure $ case st of StoreType_Local -> localRef StoreType_Session -> sessionRef instance HasStorage InMemoryStorage where getItemStorage' st k = do ref <- chooseRef st InMemoryStorage $ lift $ lookupRef ref k setItemStorage' st k v = do ref <- chooseRef st InMemoryStorage $ lift $ insertRef ref k v removeItemStorage' st k = do ref <- chooseRef st InMemoryStorage $ lift $ removeRef ref k runInMemoryStorage :: InMemoryStorage a -> IMS -> IO a runInMemoryStorage (InMemoryStorage r) = runReaderT r newInMemoryStorage :: IO IMS newInMemoryStorage = do localRef <- newIORef (Map.empty :: Map Text Text) sessionRef <- newIORef (Map.empty :: Map Text Text) pure (localRef, sessionRef) We could use the desktop interpreter , but that 's probably a bit weird given it is operating in JSM ( even inMemoryStorageFromTestData :: forall k . ( GShow k , GCompare k , Has FromJSON k , Has' FromJSON k Identity , Has ToJSON k , FromJSON (Some k) , UniverseSome k ) => StoreKeyMetaPrefix -> Proxy k -> Natural -> FilePath -> IO IMS inMemoryStorageFromTestData p _ ver dirPath = do dmap <- keyUniverseToFilesDMap ims <- newInMemoryStorage _ <- runInMemoryStorage (restoreLocalStorageDump p dmap ver) ims pure ims where keyToPath :: k a -> FilePath keyToPath k = dirPath </> gshow k keyToByteString :: k a -> IO (Maybe LBS.ByteString) keyToByteString k = do let kp = keyToPath k exists <- doesFileExist kp bool (pure Nothing) (fmap Just (LBS.readFile $ keyToPath k)) exists keyToFileDSum :: forall a. k a -> IO (Maybe (DSum k Identity)) keyToFileDSum k = do mbs <- keyToByteString k pure $ has @FromJSON k $ do let decRes = traverse (eitherDecode @a) mbs either error (fmap (\v -> (k :=> Identity v))) decRes keyUniverseToFilesDMap :: IO (DMap k Identity) keyUniverseToFilesDMap = fmap (DMap.fromList . catMaybes) . traverse (\(Some k) -> keyToFileDSum k) $ universeSome @k
db4b5c34384a9813af876b74adb77f356cb57dc880194f2c7a53e2a3fe314e31
racket/expeditor
terminal.rkt
#lang racket/base (require ffi/unsafe/vm '#%terminal) ;; See "../main.rkt" (provide (protect-out init-term $ee-read-char/blocking $ee-write-char char-width set-color ee-flush get-screen-size raw-mode no-raw-mode enter-am-mode exit-am-mode post-output-mode no-post-output-mode signal-mode no-signal-mode nanosleep pause get-clipboard move-cursor-up move-cursor-down $move-cursor-left $move-cursor-right clear-eol clear-eos $clear-screen scroll-reverse bell $carriage-return line-feed)) Cache character widths , especially for Windows , where ;; `terminal-char-width` can't report the right answer, but ;; `terminal-write-char` can report information about how ;; the cursor advanced. (define char-widths (make-hasheqv)) (define init-term terminal-init) (define $ee-read-char/blocking terminal-read-char) (define $ee-write-char (lambda (c) (define w (terminal-write-char c)) (cond [(= w -128) ;; -128 mean "unknown" 1] [else (hash-set! char-widths c w) w]))) (define char-width (lambda (c) ;; we're only set up to handle characters ;; that are non-negative sized, so we don't ;; handle control characters (max 0 (or (hash-ref char-widths c #f) (terminal-char-width c))))) (define set-color terminal-set-color) (define ee-flush terminal-flush) (define get-screen-size terminal-get-screen-size) (define raw-mode (lambda () (terminal-raw-mode #t))) (define no-raw-mode (lambda () (terminal-raw-mode #f))) (define post-output-mode (lambda () (terminal-postoutput-mode #t))) (define no-post-output-mode (lambda () (terminal-postoutput-mode #f))) (define signal-mode (lambda () (terminal-signal-mode #t))) (define no-signal-mode (lambda () (terminal-signal-mode #f))) (define enter-am-mode (lambda () (terminal-automargin-mode #t))) (define exit-am-mode (lambda () (terminal-automargin-mode #f))) (define nanosleep terminal-nanosleep) (define pause terminal-pause) (define get-clipboard terminal-get-clipboard) (define move-cursor-up (lambda (amt) (terminal-move-cursor 'up amt))) (define move-cursor-down (lambda (amt) (terminal-move-cursor 'down amt))) (define $move-cursor-left (lambda (amt) (terminal-move-cursor 'left amt))) (define $move-cursor-right (lambda (amt) (terminal-move-cursor 'right amt))) (define clear-eol (lambda () (terminal-clear 'eol))) (define clear-eos (lambda () (terminal-clear 'eos))) (define $clear-screen (lambda () (terminal-clear 'screen))) (define scroll-reverse terminal-scroll-reverse) (define bell terminal-bell) (define $carriage-return terminal-carriage-return) (define line-feed terminal-line-feed)
null
https://raw.githubusercontent.com/racket/expeditor/9b2d54a97a4f17a75d3198630a978b3eb2b4d1af/expeditor-lib/private/terminal.rkt
racket
See "../main.rkt" `terminal-char-width` can't report the right answer, but `terminal-write-char` can report information about how the cursor advanced. -128 mean "unknown" we're only set up to handle characters that are non-negative sized, so we don't handle control characters
#lang racket/base (require ffi/unsafe/vm '#%terminal) (provide (protect-out init-term $ee-read-char/blocking $ee-write-char char-width set-color ee-flush get-screen-size raw-mode no-raw-mode enter-am-mode exit-am-mode post-output-mode no-post-output-mode signal-mode no-signal-mode nanosleep pause get-clipboard move-cursor-up move-cursor-down $move-cursor-left $move-cursor-right clear-eol clear-eos $clear-screen scroll-reverse bell $carriage-return line-feed)) Cache character widths , especially for Windows , where (define char-widths (make-hasheqv)) (define init-term terminal-init) (define $ee-read-char/blocking terminal-read-char) (define $ee-write-char (lambda (c) (define w (terminal-write-char c)) (cond [(= w -128) 1] [else (hash-set! char-widths c w) w]))) (define char-width (lambda (c) (max 0 (or (hash-ref char-widths c #f) (terminal-char-width c))))) (define set-color terminal-set-color) (define ee-flush terminal-flush) (define get-screen-size terminal-get-screen-size) (define raw-mode (lambda () (terminal-raw-mode #t))) (define no-raw-mode (lambda () (terminal-raw-mode #f))) (define post-output-mode (lambda () (terminal-postoutput-mode #t))) (define no-post-output-mode (lambda () (terminal-postoutput-mode #f))) (define signal-mode (lambda () (terminal-signal-mode #t))) (define no-signal-mode (lambda () (terminal-signal-mode #f))) (define enter-am-mode (lambda () (terminal-automargin-mode #t))) (define exit-am-mode (lambda () (terminal-automargin-mode #f))) (define nanosleep terminal-nanosleep) (define pause terminal-pause) (define get-clipboard terminal-get-clipboard) (define move-cursor-up (lambda (amt) (terminal-move-cursor 'up amt))) (define move-cursor-down (lambda (amt) (terminal-move-cursor 'down amt))) (define $move-cursor-left (lambda (amt) (terminal-move-cursor 'left amt))) (define $move-cursor-right (lambda (amt) (terminal-move-cursor 'right amt))) (define clear-eol (lambda () (terminal-clear 'eol))) (define clear-eos (lambda () (terminal-clear 'eos))) (define $clear-screen (lambda () (terminal-clear 'screen))) (define scroll-reverse terminal-scroll-reverse) (define bell terminal-bell) (define $carriage-return terminal-carriage-return) (define line-feed terminal-line-feed)
8560a845b2ab08938b0b2b1fd0ed74f9aa79ec10cbd2290b02adef328cdd8f03
florabtw/soundoftext-haskell
Languages.hs
module Languages ( lookupLanguage , languagePairs ) where import Data.Maybe (fromJust, isJust) import qualified Data.Map as Map languagePairs :: [(String,String)] languagePairs = Map.assocs languageMap lookupLanguage :: String -> String lookupLanguage l | isJust mLang = fromJust mLang | otherwise = "Unknown" where mLang = Map.lookup l languageMap languageMap :: Map.Map String String languageMap = Map.fromList [ ("af" , "Afrikaans") , ("sq" , "Albanian") , ("ar" , "Arabic") , ("hy" , "Armenian") , ("bs" , "Bosnian") , ("ca" , "Catalan") , ("zh-CN", "Chinese Simplified") , ("zh-TW", "Chinese Traditional") , ("hr" , "Croatian") , ("cs" , "Czech") , ("da" , "Danish") , ("nl" , "Dutch") , ("en" , "English") , ("eo" , "Esperanto") , ("fi" , "Finnish") , ("fr" , "French") , ("de" , "German") , ("el" , "Greek") , ("ht" , "Haitian Creole") , ("hi" , "Hindi") , ("hu" , "Hungarian") , ("is" , "Icelandic") , ("id" , "Indonesian") , ("it" , "Italian") , ("ja" , "Japanese") , ("ko" , "Korean") , ("la" , "Latin") , ("lv" , "Latvian") , ("mk" , "Macedonian") , ("no" , "Norwegian") , ("pl" , "Polish") , ("pt" , "Portuguese") , ("ro" , "Romanian") , ("ru" , "Russian") , ("sr" , "Serbian") , ("sk" , "Slovak") , ("es" , "Spanish") , ("sw" , "Swahili") , ("sv" , "Swedish") , ("ta" , "Tamil") , ("th" , "Thai") , ("tr" , "Turkish") , ("vi" , "Vietnamese") , ("cy" , "Welsh") ]
null
https://raw.githubusercontent.com/florabtw/soundoftext-haskell/46c1a5ab378809ac2e1c5e005057d495a08d2887/src/Languages.hs
haskell
module Languages ( lookupLanguage , languagePairs ) where import Data.Maybe (fromJust, isJust) import qualified Data.Map as Map languagePairs :: [(String,String)] languagePairs = Map.assocs languageMap lookupLanguage :: String -> String lookupLanguage l | isJust mLang = fromJust mLang | otherwise = "Unknown" where mLang = Map.lookup l languageMap languageMap :: Map.Map String String languageMap = Map.fromList [ ("af" , "Afrikaans") , ("sq" , "Albanian") , ("ar" , "Arabic") , ("hy" , "Armenian") , ("bs" , "Bosnian") , ("ca" , "Catalan") , ("zh-CN", "Chinese Simplified") , ("zh-TW", "Chinese Traditional") , ("hr" , "Croatian") , ("cs" , "Czech") , ("da" , "Danish") , ("nl" , "Dutch") , ("en" , "English") , ("eo" , "Esperanto") , ("fi" , "Finnish") , ("fr" , "French") , ("de" , "German") , ("el" , "Greek") , ("ht" , "Haitian Creole") , ("hi" , "Hindi") , ("hu" , "Hungarian") , ("is" , "Icelandic") , ("id" , "Indonesian") , ("it" , "Italian") , ("ja" , "Japanese") , ("ko" , "Korean") , ("la" , "Latin") , ("lv" , "Latvian") , ("mk" , "Macedonian") , ("no" , "Norwegian") , ("pl" , "Polish") , ("pt" , "Portuguese") , ("ro" , "Romanian") , ("ru" , "Russian") , ("sr" , "Serbian") , ("sk" , "Slovak") , ("es" , "Spanish") , ("sw" , "Swahili") , ("sv" , "Swedish") , ("ta" , "Tamil") , ("th" , "Thai") , ("tr" , "Turkish") , ("vi" , "Vietnamese") , ("cy" , "Welsh") ]
ca542e1a2ccfe1b3cc4c871aa09002906e8174a02018490aebe97a33ea3a9b29
wireapp/wire-server
AccessToken_user.hs
-- 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 Test.Wire.API.Golden.Generated.AccessToken_user where import Data.Id (Id (Id)) import qualified Data.UUID as UUID (fromString) import Imports (fromJust) import Wire.API.User.Auth (AccessToken (..), TokenType (Bearer)) testObject_AccessToken_user_1 :: AccessToken testObject_AccessToken_user_1 = AccessToken { user = Id (fromJust (UUID.fromString "00002525-0000-2bc3-0000-3a8200006f94")), access = "{\CAN\243\188\157\141\SOq\240\171\167\184w", tokenType = Bearer, expiresIn = 1 } testObject_AccessToken_user_2 :: AccessToken testObject_AccessToken_user_2 = AccessToken { user = Id (fromJust (UUID.fromString "00007ace-0000-630b-0000-718c00000945")), access = "o6Q\243\184\187\164\ETB\243\181\156\157", tokenType = Bearer, expiresIn = -24 } testObject_AccessToken_user_3 :: AccessToken testObject_AccessToken_user_3 = AccessToken { user = Id (fromJust (UUID.fromString "00004286-0000-22c5-0000-5dba00001818")), access = "\DC3u\240\171\168\183N<E#\244\138\156\176>dWTm\SIi\244\139\166\169", tokenType = Bearer, expiresIn = 6 } testObject_AccessToken_user_4 :: AccessToken testObject_AccessToken_user_4 = AccessToken { user = Id (fromJust (UUID.fromString "00005c1d-0000-2e06-0000-278a00002d91")), access = "\233\152\185\&0)&9\\\SI\NULO", tokenType = Bearer, expiresIn = -9 } testObject_AccessToken_user_5 :: AccessToken testObject_AccessToken_user_5 = AccessToken { user = Id (fromJust (UUID.fromString "00002891-0000-27e1-0000-686000002ba0")), access = "n\227\154\185 {'\FS\240\159\147\150\DC1C*\234\186\142\ESC", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_6 :: AccessToken testObject_AccessToken_user_6 = AccessToken { user = Id (fromJust (UUID.fromString "0000195e-0000-7174-0000-1a5c000030dc")), access = "+\231\145\167\&8J\243\176\183\137\SOHw", tokenType = Bearer, expiresIn = 2 } testObject_AccessToken_user_7 :: AccessToken testObject_AccessToken_user_7 = AccessToken { user = Id (fromJust (UUID.fromString "000038d1-0000-3dd4-0000-499a000014ca")), access = "`gS\DEL\DLE\ETXe\243\187\169\134o\243\191\130\131\244\129\152\137\243\178\160\150+Htv\244\130\172\190\EMdh\STX\240\169\169\185\239\130\169", tokenType = Bearer, expiresIn = -12 } testObject_AccessToken_user_8 :: AccessToken testObject_AccessToken_user_8 = AccessToken { user = Id (fromJust (UUID.fromString "000065e0-0000-3b8c-0000-492700007916")), access = "\NULYn\DELC&X9\243\189\191\169_", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_9 :: AccessToken testObject_AccessToken_user_9 = AccessToken { user = Id (fromJust (UUID.fromString "000023d8-0000-406e-0000-3277000079f9")), access = "\244\132\147\179\CAN\b\243\187\136\177\244\141\160\129\CANf\243\179\172\128DDNNR\240\160\183\154`H", tokenType = Bearer, expiresIn = 23 } testObject_AccessToken_user_10 :: AccessToken testObject_AccessToken_user_10 = AccessToken { user = Id (fromJust (UUID.fromString "0000376e-0000-4673-0000-1e1800004b06")), access = " \243\180\155\169+\244\143\128\190G_\240\161\128\142Xj\NULef\232\159\186.&U]J\240\166\182\187=<hrt3", tokenType = Bearer, expiresIn = -20 } testObject_AccessToken_user_11 :: AccessToken testObject_AccessToken_user_11 = AccessToken { user = Id (fromJust (UUID.fromString "000018c7-0000-4f75-0000-29b0000065fc")), access = "pT\240\164\134\146\DC1@\244\140\169\164\DC43", tokenType = Bearer, expiresIn = -19 } testObject_AccessToken_user_12 :: AccessToken testObject_AccessToken_user_12 = AccessToken { user = Id (fromJust (UUID.fromString "00000f4f-0000-0499-0000-78b4000029de")), access = "\ACK\n\244\136\183\166FY\ETXuu\SOH", tokenType = Bearer, expiresIn = 25 } testObject_AccessToken_user_13 :: AccessToken testObject_AccessToken_user_13 = AccessToken { user = Id (fromJust (UUID.fromString "00001225-0000-145a-0000-277600007725")), access = "\244\128\147\170Q\224\176\149\243\186\134\162oV|#Hp-\243\184\189\134js\244\139\171\189\243\176\166\182.E\244\139\145\148\243\184\176\189", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_14 :: AccessToken testObject_AccessToken_user_14 = AccessToken { user = Id (fromJust (UUID.fromString "00007469-0000-0eae-0000-1a8400004582")), access = "\243\177\160\147", tokenType = Bearer, expiresIn = -12 } testObject_AccessToken_user_15 :: AccessToken testObject_AccessToken_user_15 = AccessToken { user = Id (fromJust (UUID.fromString "000011e5-0000-29e4-0000-550400003888")), access = "\243\177\159\190r", tokenType = Bearer, expiresIn = 26 } testObject_AccessToken_user_16 :: AccessToken testObject_AccessToken_user_16 = AccessToken { user = Id (fromJust (UUID.fromString "0000633c-0000-6653-0000-772e00005669")), access = "p\"\244\130\163\145\v-\238\143\147\ETX\b<\240\147\141\128+\SO\DEL\244\131\172\144", tokenType = Bearer, expiresIn = 18 } testObject_AccessToken_user_17 :: AccessToken testObject_AccessToken_user_17 = AccessToken { user = Id (fromJust (UUID.fromString "00006032-0000-470b-0000-544b00001c88")), access = "\240\167\149\178z}\bRH\ENQ@o\EMm,\240\159\146\156\228\155\169\244\140\181\157]\EOT\FS\rZm,Z", tokenType = Bearer, expiresIn = -13 } testObject_AccessToken_user_18 :: AccessToken testObject_AccessToken_user_18 = AccessToken { user = Id (fromJust (UUID.fromString "00006b0d-0000-792a-0000-3fb800003867")), access = "\244\129\184\152\\\244\136\157\138\v2!\243\188\172\183\240\174\169\150ZE|3(\CAN=Q\ENQb\DC3[\243\176\144\149\243\188\182\133MW", tokenType = Bearer, expiresIn = -8 } testObject_AccessToken_user_19 :: AccessToken testObject_AccessToken_user_19 = AccessToken { user = Id (fromJust (UUID.fromString "00004fc5-0000-08b5-0000-0ad800002c12")), access = "h\a", tokenType = Bearer, expiresIn = -16 } testObject_AccessToken_user_20 :: AccessToken testObject_AccessToken_user_20 = AccessToken { user = Id (fromJust (UUID.fromString "00005c43-0000-6c4c-0000-461200000976")), access = "\243\190\143\130~\240\164\141\143#\t\FS\244\133\141\138 ~_W\244\139\185\159z_\243\179\169\167A", tokenType = Bearer, expiresIn = 17 }
null
https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/AccessToken_user.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 </>.
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 Test.Wire.API.Golden.Generated.AccessToken_user where import Data.Id (Id (Id)) import qualified Data.UUID as UUID (fromString) import Imports (fromJust) import Wire.API.User.Auth (AccessToken (..), TokenType (Bearer)) testObject_AccessToken_user_1 :: AccessToken testObject_AccessToken_user_1 = AccessToken { user = Id (fromJust (UUID.fromString "00002525-0000-2bc3-0000-3a8200006f94")), access = "{\CAN\243\188\157\141\SOq\240\171\167\184w", tokenType = Bearer, expiresIn = 1 } testObject_AccessToken_user_2 :: AccessToken testObject_AccessToken_user_2 = AccessToken { user = Id (fromJust (UUID.fromString "00007ace-0000-630b-0000-718c00000945")), access = "o6Q\243\184\187\164\ETB\243\181\156\157", tokenType = Bearer, expiresIn = -24 } testObject_AccessToken_user_3 :: AccessToken testObject_AccessToken_user_3 = AccessToken { user = Id (fromJust (UUID.fromString "00004286-0000-22c5-0000-5dba00001818")), access = "\DC3u\240\171\168\183N<E#\244\138\156\176>dWTm\SIi\244\139\166\169", tokenType = Bearer, expiresIn = 6 } testObject_AccessToken_user_4 :: AccessToken testObject_AccessToken_user_4 = AccessToken { user = Id (fromJust (UUID.fromString "00005c1d-0000-2e06-0000-278a00002d91")), access = "\233\152\185\&0)&9\\\SI\NULO", tokenType = Bearer, expiresIn = -9 } testObject_AccessToken_user_5 :: AccessToken testObject_AccessToken_user_5 = AccessToken { user = Id (fromJust (UUID.fromString "00002891-0000-27e1-0000-686000002ba0")), access = "n\227\154\185 {'\FS\240\159\147\150\DC1C*\234\186\142\ESC", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_6 :: AccessToken testObject_AccessToken_user_6 = AccessToken { user = Id (fromJust (UUID.fromString "0000195e-0000-7174-0000-1a5c000030dc")), access = "+\231\145\167\&8J\243\176\183\137\SOHw", tokenType = Bearer, expiresIn = 2 } testObject_AccessToken_user_7 :: AccessToken testObject_AccessToken_user_7 = AccessToken { user = Id (fromJust (UUID.fromString "000038d1-0000-3dd4-0000-499a000014ca")), access = "`gS\DEL\DLE\ETXe\243\187\169\134o\243\191\130\131\244\129\152\137\243\178\160\150+Htv\244\130\172\190\EMdh\STX\240\169\169\185\239\130\169", tokenType = Bearer, expiresIn = -12 } testObject_AccessToken_user_8 :: AccessToken testObject_AccessToken_user_8 = AccessToken { user = Id (fromJust (UUID.fromString "000065e0-0000-3b8c-0000-492700007916")), access = "\NULYn\DELC&X9\243\189\191\169_", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_9 :: AccessToken testObject_AccessToken_user_9 = AccessToken { user = Id (fromJust (UUID.fromString "000023d8-0000-406e-0000-3277000079f9")), access = "\244\132\147\179\CAN\b\243\187\136\177\244\141\160\129\CANf\243\179\172\128DDNNR\240\160\183\154`H", tokenType = Bearer, expiresIn = 23 } testObject_AccessToken_user_10 :: AccessToken testObject_AccessToken_user_10 = AccessToken { user = Id (fromJust (UUID.fromString "0000376e-0000-4673-0000-1e1800004b06")), access = " \243\180\155\169+\244\143\128\190G_\240\161\128\142Xj\NULef\232\159\186.&U]J\240\166\182\187=<hrt3", tokenType = Bearer, expiresIn = -20 } testObject_AccessToken_user_11 :: AccessToken testObject_AccessToken_user_11 = AccessToken { user = Id (fromJust (UUID.fromString "000018c7-0000-4f75-0000-29b0000065fc")), access = "pT\240\164\134\146\DC1@\244\140\169\164\DC43", tokenType = Bearer, expiresIn = -19 } testObject_AccessToken_user_12 :: AccessToken testObject_AccessToken_user_12 = AccessToken { user = Id (fromJust (UUID.fromString "00000f4f-0000-0499-0000-78b4000029de")), access = "\ACK\n\244\136\183\166FY\ETXuu\SOH", tokenType = Bearer, expiresIn = 25 } testObject_AccessToken_user_13 :: AccessToken testObject_AccessToken_user_13 = AccessToken { user = Id (fromJust (UUID.fromString "00001225-0000-145a-0000-277600007725")), access = "\244\128\147\170Q\224\176\149\243\186\134\162oV|#Hp-\243\184\189\134js\244\139\171\189\243\176\166\182.E\244\139\145\148\243\184\176\189", tokenType = Bearer, expiresIn = 27 } testObject_AccessToken_user_14 :: AccessToken testObject_AccessToken_user_14 = AccessToken { user = Id (fromJust (UUID.fromString "00007469-0000-0eae-0000-1a8400004582")), access = "\243\177\160\147", tokenType = Bearer, expiresIn = -12 } testObject_AccessToken_user_15 :: AccessToken testObject_AccessToken_user_15 = AccessToken { user = Id (fromJust (UUID.fromString "000011e5-0000-29e4-0000-550400003888")), access = "\243\177\159\190r", tokenType = Bearer, expiresIn = 26 } testObject_AccessToken_user_16 :: AccessToken testObject_AccessToken_user_16 = AccessToken { user = Id (fromJust (UUID.fromString "0000633c-0000-6653-0000-772e00005669")), access = "p\"\244\130\163\145\v-\238\143\147\ETX\b<\240\147\141\128+\SO\DEL\244\131\172\144", tokenType = Bearer, expiresIn = 18 } testObject_AccessToken_user_17 :: AccessToken testObject_AccessToken_user_17 = AccessToken { user = Id (fromJust (UUID.fromString "00006032-0000-470b-0000-544b00001c88")), access = "\240\167\149\178z}\bRH\ENQ@o\EMm,\240\159\146\156\228\155\169\244\140\181\157]\EOT\FS\rZm,Z", tokenType = Bearer, expiresIn = -13 } testObject_AccessToken_user_18 :: AccessToken testObject_AccessToken_user_18 = AccessToken { user = Id (fromJust (UUID.fromString "00006b0d-0000-792a-0000-3fb800003867")), access = "\244\129\184\152\\\244\136\157\138\v2!\243\188\172\183\240\174\169\150ZE|3(\CAN=Q\ENQb\DC3[\243\176\144\149\243\188\182\133MW", tokenType = Bearer, expiresIn = -8 } testObject_AccessToken_user_19 :: AccessToken testObject_AccessToken_user_19 = AccessToken { user = Id (fromJust (UUID.fromString "00004fc5-0000-08b5-0000-0ad800002c12")), access = "h\a", tokenType = Bearer, expiresIn = -16 } testObject_AccessToken_user_20 :: AccessToken testObject_AccessToken_user_20 = AccessToken { user = Id (fromJust (UUID.fromString "00005c43-0000-6c4c-0000-461200000976")), access = "\243\190\143\130~\240\164\141\143#\t\FS\244\133\141\138 ~_W\244\139\185\159z_\243\179\169\167A", tokenType = Bearer, expiresIn = 17 }
ca9a4a460b76b52a5a49e0a8d2761149bd22c3c93ded4f957aca2bdf42e8b49b
xapi-project/xenopsd
interface.ml
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Xenops_interface open Xenops_utils (* The network manipulation scripts need to find the VM metadata given only an interface name (e.g. "tapX.Y" or "fooUUID"?) *) module Interface = struct type t = {name: string; vif: Vif.id} [@@deriving rpcty] let rpc_of_t x = Rpcmarshal.marshal t.Rpc.Types.ty x let t_of_rpc x = match Rpcmarshal.unmarshal t.Rpc.Types.ty x with | Ok y -> y | Error (`Msg msg) -> failwith msg end module DB = TypedTable (struct include Interface let namespace = "interface" type key = string let key x = [x] end)
null
https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/lib/interface.ml
ocaml
The network manipulation scripts need to find the VM metadata given only an interface name (e.g. "tapX.Y" or "fooUUID"?)
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) open Xenops_interface open Xenops_utils module Interface = struct type t = {name: string; vif: Vif.id} [@@deriving rpcty] let rpc_of_t x = Rpcmarshal.marshal t.Rpc.Types.ty x let t_of_rpc x = match Rpcmarshal.unmarshal t.Rpc.Types.ty x with | Ok y -> y | Error (`Msg msg) -> failwith msg end module DB = TypedTable (struct include Interface let namespace = "interface" type key = string let key x = [x] end)
9f98c0a78dc8e4ef08fa0cd9aa48605fff49b7d329077eeb6797d859ccfb37ee
dbuenzli/serialk
serialk_sexp.mli
--------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) * S - expression support . The module { ! Sexp } has an s - expression codec and general definitions for working with them . { ! } generates s - expressions without going through a generic representation . { ! } queries and updates generic representations with combinators . Consult a { { ! sexp_syntax}short introduction } to s - expressions and the syntax parsed by the codec , the encoding of { { ! sexp_dict}key - value dictionaries } supported by this module and the end - user syntax for { { ! sexp_path_caret}addressing and updating } s - expressions . Open this module to use it , this only introduces modules in your scope . { b Warning . } Serialization functions always assumes all OCaml strings in the data you provide is UTF-8 encoded . This is not checked by the module . The module {!Sexp} has an s-expression codec and general definitions for working with them. {!Sexpg} generates s-expressions without going through a generic representation. {!Sexpq} queries and updates generic representations with combinators. Consult a {{!sexp_syntax}short introduction} to s-expressions and the syntax parsed by the codec, the encoding of {{!sexp_dict}key-value dictionaries} supported by this module and the end-user syntax for {{!sexp_path_caret}addressing and updating} s-expressions. Open this module to use it, this only introduces modules in your scope. {b Warning.} Serialization functions always assumes all OCaml strings in the data you provide is UTF-8 encoded. This is not checked by the module. *) * { 1 : api API } open Serialk_text (** S-expression definitions and codec. *) module Sexp : sig * { 1 : meta Meta information } type 'a fmt = Format.formatter -> 'a -> unit (** The type for formatting functions. *) type loc = Tloc.t (** The type for source text locations. *) val loc_nil : Tloc.t (** [loc_nil] is a source text location for non-parsed s-expressions. *) val pp_loc : loc fmt (** [pp_loc] is {!Tloc.pp}. *) type a_meta (** The type for meta information about atoms. *) type l_meta (** The type for meta information about lists. *) val a_meta_nil : a_meta (** [a_meta_nil] is parse information for non-parsed atoms. *) val l_meta_nil : l_meta (** [l_meta_nil] is parse information for non-parsed lists. *) * { 1 : sexp S - expressions } type t = [ `A of string * a_meta | `L of t list * l_meta ] (** The type for generic s-expression representations. Either an atom or a list. *) val atom : string -> t (** [atom a] is [`A (a, a_meta_nil)]. *) val list : t list -> t (** [list l] is [`L (l, l_meta_nil)]. *) * { 1 : access Accessors } val loc : t -> loc * [ loc s ] is [ s ] 's source text location . val to_atom : t -> (string, string) result (** [to_atom s] extracts an atom from [s]. If [s] is a list an error with the location formatted according to {!Tloc.pp} is returned. *) val get_atom : t -> string * [ s ] is like { ! to_atom } but raises { ! Invalid_argument } if [ s ] is not an atom . if [s] is not an atom. *) val to_list : t -> (t list, string) result (** [to_list s] extracts a list from [s]. If [s] is an atom an error with the location formatted according to {!Tloc.pp} is returned. *) val get_list : t -> t list * [ s ] is like { ! to_list } but raises { ! Invalid_argument } if [ s ] is not an list . if [s] is not an list. *) val to_splice : t -> t list (** [to_splice s] is the either the list of [s] if [s] is or or [[s]] if [s] is an atom. *) * { 1 : fmt Formatting } val pp : t fmt (** [pp] formats an s-expression. *) val pp_layout : t fmt (** [pp_layout ppf l] is like {!pp} but uses layout information. *) val pp_seq : t fmt (** [pp_seq] formats an s-expression but if it is a list the outer list separators are not formatted in the output. {b Warning.} Assumes all OCaml strings in the formatted value are UTF-8 encoded. *) val pp_seq_layout : t fmt (** [pp_seq_layout] is like {!pp_seq} but uses layout information. *) * { 1 : codec Codec } type error_kind (** The type for kinds of decoding error. *) val pp_error_kind : unit -> error_kind fmt (** [pp_error_kind ()] formats an error kind. *) type error = error_kind * loc (** The type for decoding errors. *) val pp_error : ?pp_loc:loc fmt -> ?pp_error_kind:error_kind fmt -> ?pp_prefix:unit fmt -> unit -> error fmt (** [pp_error ~pp_loc ~pp_error_kind ~pp_prefix ()] formats errors using [pp_loc] (defaults to {!pp_loc}), [pp_error_kind] (defaults to {!pp_error_kind}) and [pp_prefix] (defaults formats ["Error: "]). *) val error_to_string : ?pp_error:error fmt -> ('a, error) result -> ('a, string) result (** [error_to_string r] converts an error to a string using [pp_error] (defaults to {!pp_error}). *) val seq_of_string : ?file:Tloc.fpath -> string -> (t, error) result * [ seq_of_string ? file s ] parses a { e sequence } of s - expressions from [ s ] . [ file ] is the file for locations , defaults to [ " - " ] . The sequence is returned as a fake s - expression list that spans from the start of the first s - expression in [ s ] to the end of the last one ; note that this list does not exist syntactically in [ s ] . If there are no s - expression in [ s ] the list is empty its location has both start and end positions at byte [ 0 ] ( which may not exist ) . { b Note . } All OCaml strings returned by this function are UTF-8 encoded . [s]. [file] is the file for locations, defaults to ["-"]. The sequence is returned as a fake s-expression list that spans from the start of the first s-expression in [s] to the end of the last one; note that this list does not exist syntactically in [s]. If there are no s-expression in [s] the list is empty its location has both start and end positions at byte [0] (which may not exist). {b Note.} All OCaml strings returned by this function are UTF-8 encoded. *) val seq_of_string' : ?pp_error:error fmt -> ?file:Tloc.fpath -> string -> (t, string) result (** [seq_of_string'] s {!seq_of_string} composed with {!error_to_string}. *) val seq_to_string : t -> string * [ seq_to_string s ] encodes [ s ] to a sequence of s - expressions . If [ s ] is an s - expression list this wrapping list is not syntactically represented in the output ( see also { ! seq_of_string } ) , use [ to_string ( list [ l ] ) ] if you want to output [ l ] as a list . { b Warning . } Assumes all OCaml strings in [ s ] are UTF-8 encoded . is an s-expression list this wrapping list is not syntactically represented in the output (see also {!seq_of_string}), use [to_string (list [l])] if you want to output [l] as a list. {b Warning.} Assumes all OCaml strings in [s] are UTF-8 encoded. *) * { 1 : sexp_index S - expression indices } type index = | Nth of int (** *) | Key of string (** *) * The type for s - expression indexing operations . { ul { - [ Nth n ] , lookup zero - based element [ n ] in a list . If [ n ] is negative , counts the number of elements from the end of the list , i.e. [ -1 ] is the last list element . } { - [ Key k ] , lookup binding [ k ] in an s - expression { { ! sexp_dict}dictionary . } } } {ul {- [Nth n], lookup zero-based element [n] in a list. If [n] is negative, counts the number of elements from the end of the list, i.e. [-1] is the last list element.} {- [Key k], lookup binding [k] in an s-expression {{!sexp_dict}dictionary.}}} *) val pp_key : string fmt (** [pp_key] formats a key, this is {!Format.pp_print_string}. *) val pp_index : ?pp_key:string fmt -> unit -> index fmt (** [pp_index] formats indices. Keys are unbracketed and formatted with [pp_key], defaults to {!pp_key}. *) * { 1 : sexp_path S - expression paths } type path = index list (** The type for paths, a sequence of indexing operations in {b reverse} order. *) val path_of_string : string -> (path, string) result (** [path_of_string] parses a path from [s] according to the syntax {{!sexp_path_caret}given here}. *) val pp_path : ?pp_key:string fmt -> unit -> path fmt (** [pp_path ?pp_key ()] is a formatter for paths using [pp_key] to format keys (defaults to {!pp_key}). *) (** {1:carets Carets} *) type caret_loc = | Before (** The void before the s-expression found by the path. *) | Over (** The s-expression found by the path. *) | After (** The void after the s-expression found by the path. *) (** The type for caret locations. *) type caret = caret_loc * path (** The type for carets. A caret location and the path at which it applies. *) val caret_of_string : string -> (caret, string) result (** [caret_of_string s] parses a caret from [s] according to the syntax {{!sexp_path_caret}given here}. *) val pp_caret : ?pp_key:string fmt -> unit -> caret fmt (** [pp_caret ?pp_key ()] is a formatter for carets using [pp_key] to format keys (defaults to {!pp_key}). *) end (** S-expression generation. *) module Sexpg : sig * { 1 : gen Generation } type t (** The type for generated s-expressions. *) val atom : string -> t (** [atom s] is [s] as an atom. *) type lyst (** The type for generated s-expression lists. *) val ls : lyst (** [ls] starts a list. *) val le : lyst -> t (** [le l] ends lists [l]. *) val el : t -> lyst -> lyst (** [el e l] is list [l] with [e] added at the end. *) val el_if : bool -> (unit -> t) -> lyst -> lyst (** [el cond v l] is [el (v ()) l] if [cond] is [true] and [l] otherwise. *) * { 1 : derived Derived generators } val atomf : ('a, Format.formatter, unit, t) format4 -> 'a (** [atomf fmt ...] is an atom formatted according to [fmt]. *) val bool : bool -> t (** [bool b] is [atomf "%b" b]. *) val int : int -> t (** [int i] is [atomf "%d" i]. *) val float : float -> t (** [float f] is [atomf "%g" f]. *) val float_hex : float -> t (** [float_hex f] is [atomf "%h" f]. *) val string : string -> t (** [string s] is {!atom}. *) val option : ('a -> t) -> 'a option -> t (** [option some o] is [o] as the [none] atom if [o] is [none] and a list starting with [some] atom followed by [some v] if [o] is [Some v]. *) val list : ('a -> t) -> 'a list -> t (** [list el l] is [l] as a list whose elements are generated using [el]. *) val sexp : Sexp.t -> t (** [sexp s] is the s-expression [s] as a generated value. *) * { 1 : output Output } val buffer_add : Buffer.t -> t -> unit (** [buffer_add b g] adds the generated s-expression value [g] to [b]. *) val to_string : t -> string (** [to_string g] is the generated s-expression value [g] as a string. *) end (** S-expression queries. *) module Sexpq : sig * { 1 : query_results Result paths } type path = (Sexp.index * Sexp.loc) list (** The type for result paths. This is a sequence of indexing operations tupled with the source text location of the indexed s-expression in {b reverse} order. *) val pp_path : ?pp_loc:Sexp.loc Sexp.fmt -> ?pp_key:string Sexp.fmt -> unit -> path Sexp.fmt (** [pp_path ~pp_loc ~pp_key ()] formats paths using [pp_loc] (defaults to {!Sexp.pp_loc}) and [pp_key] to format the keys (defaults to {!Sexp.pp_key}). *) * { 1 : query_errors Query errors } type error_kind = [ `Key_unbound of string * string list | `Msg of string | `Nth_unbound of int * int | `Out_of_dom of string * string * string list ] (** The type for kinds of errors. {ul {- [`Key_unbound (k, dom)] on [k] that should have been in [dom] (if not empty).} {- [`Msg m] an arbitrary message [m] (should not include position information).} {- [`Nth_unbound (n, len)] on [n] an out of bound index in a list of length [len].} {- [`Out_of_dom (kind, v, dom)] on [v] of kind [kind] that should have been in [dom]}} *) val pp_error_kind : ?pp_em:string Sexp.fmt -> ?pp_key:string Sexp.fmt -> unit -> error_kind Sexp.fmt * [ pp_error_kind ~pp_loc ~pp_em ~pp_key ( ) ] formats error kinds using [ pp_loc ] for locations , [ pp_em ] for emphasis and [ pp_key ] for keys . using [pp_loc] for locations, [pp_em] for emphasis and [pp_key] for keys. *) type error = error_kind * (path * Sexp.loc) (** The type for query errors. The error kind tupled with the path to the offending s-expression and the location of the s-expression. *) val pp_error : ?pp_loc:Sexp.loc Sexp.fmt -> ?pp_path:path Sexp.fmt -> ?pp_error_kind:error_kind Sexp.fmt -> ?pp_prefix:unit Sexp.fmt -> unit -> error Sexp.fmt (** [pp_error ~pp_loc ~pp_path ~pp_error_kind ~pp_prefix ()] formats errors using [pp_loc], [pp_path] (defaults to {!pp_path}), [pp_error_kind] (defaults to {!pp_error_kind}) and [pp_prefix] (defaults formats ["Error: "]). *) val error_to_string : ?pp_error:error Sexp.fmt -> ('a, error) result -> ('a, string) result * [ error_to_string ] converts an error in [ r ] to a string using [ pp_error ] , defaults to { ! pp_error } . [pp_error], defaults to {!pp_error}. *) * { 1 : queries Queries } type 'a t (** The type for s-expression queries. A query either succeeds against an s-expression with a value of type ['a] or it fails. *) val query : 'a t -> Sexp.t -> ('a, error) result (** [query q s] is [Ok v] if the query [q] succeeds on [s] and [Error e] otherwise. *) val query_at_path : 'a t -> (Sexp.t * path) -> ('a, error) result (** [query_at_path q (s, p)] is like {!query} except it assumes [s] is at path [p]. Use to further query s-expressions obtained with {!sexp_with_path} so that errors return the full path to errors. *) val query' : ?pp_error:error Sexp.fmt -> 'a t -> Sexp.t -> ('a, string) result (** [query' q s] is like {!query} except the result is composed with {!error_to_string}. *) * { 1 : outcome Success and failure } val succeed : 'a -> 'a t (** [succeed v] is a query that succeeds with value [v] on any s-expression. *) val fail : error_kind -> 'a t (** [fail k] is a query that fails on any s-expression with error kind [k]. *) val failf : ('a, Format.formatter, unit, 'b t) format4 -> 'a (** [failf fmt ...] is [fail (`Msg m)] with [m] formatted according to [fmt]. *) * { 1 : qcomb Query combinators } val app : ('a -> 'b) t -> 'a t -> 'b t * [ app fq q ] queries an s - expression first with [ fq ] and then with [ q ] and applies the result of latter to the former . and applies the result of latter to the former. *) val ( $ ) : ('a -> 'b) t -> 'a t -> 'b t (** [f $ v] is [app f v]. *) val pair : 'a t -> 'b t -> ('a * 'b) t * [ pair q0 q1 ] queries an s - expression first with [ q0 ] and then with [ q1 ] and returns the pair of their result . and returns the pair of their result. *) val bind : 'a t -> ('a -> 'b t) -> 'b t (** [bind q f] queries an s-expression with [q], applies the result to [f] and re-queries the s-expression with the result. *) val map : ('a -> 'b) -> 'a t -> 'b t (** [map f q] is [app (succeed f) q]. *) val some : 'a t -> 'a option t * [ some q ] is [ map Option.some q ] . val loc : 'a t -> ('a * (path * Sexp.loc)) t (** [loc q] queries with [q] an returns the result with the query path and source text location to the queried s-expression. *) * { 1 : } Queries for s - expressions . These queries never fail . Queries for s-expressions. These queries never fail. *) val fold : atom:'a t -> list:'a t -> 'a t * [ fold ~list ] queries atoms with [ atom ] and lists with [ list ] . val sexp : Sexp.t t (** [sexp] queries any s-expression and returns its generic representation. *) val sexp_with_path : (Sexp.t * path) t (** [sexp_with_path] is like {!sexp} but also returns the path to s-expression. *) * { 1 : qatom Atom queries } Queries for atoms . These queries fail on lists . Queries for atoms. These queries fail on lists. *) val atom : string t (** [atom] queries an atom as a string. *) val atom_to : kind:string -> (string -> ('a, string) result) -> 'a t * [ atom_to ~kind p ] queries an atom and parses it with [ p ] . In case of [ Error m ] fails with message [ m ] . [ kind ] is the kind of value parsed , used for the error in case a list is found . case of [Error m] fails with message [m]. [kind] is the kind of value parsed, used for the error in case a list is found. *) * { b TODO . } Maybe combinators to devise an approriate parse function for { ! atom_to } are a better idea than the following two combinators . function for {!atom_to} are a better idea than the following two combinators. *) val enum : kind:string -> Set.Make(String).t -> string t * [ enum ~kind ss ] queries an atom for one of the element of [ ss ] and fails otherwise . [ kind ] is for the kind of elements in [ ss ] , it used for error reporting . and fails otherwise. [kind] is for the kind of elements in [ss], it used for error reporting. *) val enum_map : kind:string -> 'a Map.Make(String).t -> 'a t * [ enum_map ~pp_elt ~kind sm ] queries an atom for it 's map in [ sm ] and fails if the atom is not bound in [ sm ] . [ kind ] is for the kind of elements in [ sm ] , it used for error reporting . and fails if the atom is not bound in [sm]. [kind] is for the kind of elements in [sm], it used for error reporting. *) val bool : bool t * [ bool ] queries an atom for one of [ true ] or [ false ] . val int : int t (** [int] queries an atom for an integer value parsed with {!int_of_string}. *) val int32 : int32 t * [ int32 ] queries an atom for an integer value parsed with { ! } . {!Int32.of_string}. *) val int64 : int64 t * [ int64 ] queries an atom for an integer value parsed with { ! Int64.of_string } . {!Int64.of_string}. *) val float : float t (** [float] queries an atom for a float value parsed with {!float_of_string}. *) * { 1 : qlist List queries } Queries for s - expression lists . These queries fail on atoms . Queries for s-expression lists. These queries fail on atoms. *) val is_empty : bool t (** [is_empty] queries a list for emptyness. *) val hd : 'a t -> 'a t (** [hd q] queries the head of a list with [q]. Fails on empty lists. *) val tl : 'a t -> 'a t (** [tail q] queries the tail of a list with [q]. Fails on empty lists. *) val fold_list : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b t * [ fold_list f q acc ] queries the elements of a list from left to right with [ q ] and folds the result with [ f ] starting with [ acc ] . right with [q] and folds the result with [f] starting with [acc]. *) val list : 'a t -> 'a list t (** [list q] queries the elements of a list with [q]. *) * { 2 : qlist List index queries } val nth : ?absent:'a -> int -> 'a t -> 'a t (** [nth ?absent n q] queries the [n]th index of a list with [q]. If [n] is negative counts from the end of the list, so [-1] is the last list element. If the element does not exist this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. *) val delete_nth : must_exist:bool -> int -> Sexp.t t (** [delete_nth ~must_exist n] deletes the [n]th element of the list. If the element does not exist this fails when [must_exist] is [true] or returns the list unchanged when [must_exist] is [false]. *) * { 1 : qdict Dictionary queries } Queries for s - expression { { ! sexp}dictionaries } . These queries fail on atoms . Queries for s-expression {{!sexp}dictionaries}. These queries fail on atoms. *) val key : ?absent:'a -> string -> 'a t -> 'a t (** [key ?absent k q] queries the value of key [k] of a dictionary with [q]. If [k] is not bound this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. *) val delete_key : must_exist:bool -> string -> Sexp.t t (** [delete_key ~must_exist k] deletes key [k] from the dictionary. If [k] is not bound this fails when [must_exist] is [true] or returns the dictionary unchanged when [must_exist] is [false]. *) val key_dom : validate:Set.Make(String).t option -> Set.Make(String).t t (** [key_dom validate] queries the key domain of a list of bindings. If [validate] is [Some dom], the query fails if a key is not in [dom]. The query also fails if a binding is not well-formed. [pp_key] is used to format keys. {b TODO.} Not really happy about this function, we lose the key locations which is useful for further deconstruction. Also maybe we rather want binding folds. *) val atomic : 'a t -> 'a t (** [atomic q] queries an atom or the atom of a singleton list with [q]. It fails on empty lists or non-singleton lists. This is useful for singleton {{!sexp_dict}dictionary} bindings. In error reporting treats the list as if it doesn't exist syntactically which is the case in dictionary bindings. *) * { 1 : indices Index queries } val index : ?absent:'a -> Sexp.index -> 'a t -> 'a t (** [index ?absent i q] queries the s-expression index [i] with [q] using {!nth} or {!key} according to [i]. Fails on atoms. *) val delete_index : must_exist:bool -> Sexp.index -> Sexp.t t * [ delete_index ~must_exist i ] deletes the s - expression index [ i ] using { ! } or { ! delete_key } according to [ i ] . using {!delete_nth} or {!delete_key} according to [i]. *) * { 1 : path_caret Path and caret queries } These queries fail on indexing errors , that is if an atom gets indexed . These queries fail on indexing errors, that is if an atom gets indexed. *) val path : ?absent:'a -> Sexp.path -> 'a t -> 'a t (** [path p q] queries the s-expression found by [p] using [q]. If [p] can't be found this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. *) val probe_path : Sexp.path -> (path * Sexp.t * Sexp.path) t (** [probe_path p] is a query that probes for [p]'s existence. Except for indexing errors it always succeeds with [(sp, s, rem)]: {ul {- If [p] is found, this is the path to [sp] to the found expression [s] and [rem] is empty.} {- If [p] is not found, this is the path [sp] that leads to the s-expression [s] that could not be indexed and [rem] has the indexes that could not be performed.}} *) val delete_at_path : must_exist:bool -> Sexp.path -> Sexp.t t (** [delete_at_path ~must_exist p] deletes the s-expression found by [p] from the queried s-expression. If the path does not exist this fails if [must_exist] is [true] and returns the s-expression itself if [must_exist] is [false]. *) val splice_at_path : ?stub:Sexp.t -> must_exist:bool -> Sexp.path -> rep:Sexp.t -> Sexp.t t * [ splice_at_path ? stub ~must_exist ] replaces the s - expression found at [ p ] by splicing [ rep ] . If the path does not exist this fails if [ must_exist ] is [ true ] and the non - existing part of the path is created if [ must_exist ] is [ false ] . If elements need to be created [ stub ] ( defaults to [ Sexp.atom " " ] ) is used . found at [p] by splicing [rep]. If the path does not exist this fails if [must_exist] is [true] and the non-existing part of the path is created if [must_exist] is [false]. If elements need to be created [stub] (defaults to [Sexp.atom ""]) is used. *) val splice_at_caret : ?stub:Sexp.t -> must_exist:bool -> Sexp.caret -> rep:Sexp.t -> Sexp.t t * [ splice_caret ? stub ~must_exist p rep ] splices the s - expression [ rep ] at the caret [ p ] of the s - expression . If path of the caret does not exist this fails if [ must_exist ] is [ true ] and the non - existing part of the path is created if [ must_exist ] is [ false ] . If atoms need to be create [ stub ] ( defaults to [ Sexp.atom " " ] ) is used . at the caret [p] of the s-expression. If path of the caret does not exist this fails if [must_exist] is [true] and the non-existing part of the path is created if [must_exist] is [false]. If atoms need to be create [stub] (defaults to [Sexp.atom ""]) is used. *) * { 1 : ocaml OCaml datatype encoding queries } val option : 'a t -> 'a option t (** [option q] queries with [q] the value of an option represented according the encoding of {!Sexpg.option}. *) end * { 1 : sexp_dict Dictionaries } An s - expression { e dictionary } is a list of bindings . A { e binding } is a list that starts with a { e key } and the remaining elements of the list are the binding 's { e value } . For example in this binding : { v ( key v0 v1 ... ) v } The key is [ key ] and the value the possibly empty list [ v0 ] , [ v1 ] , ... of s - expressions . The { { ! Sexpq.qdict}API } for dictionaries represents the value by a fake ( does n't exist syntactically ) s - expression list whose text location starts at the first element of the value . { 1 : sexp_path_caret Path & caret syntax } Path and carets provide a way for end users to address s - expressions and edit locations . A { e path } is a sequence of { { ! sexp_dict}key } and list indexing operations . Applying the path to an s - expression leads to an s - expression or nothing if one of the indices does not exist , or an error if ones tries to index an atom . A { e caret } is a path and a spatial specification for the s - expression found by the path . The caret indicates either the void before that expression , the expression itself ( over caret ) or the void after it . Here are a few examples of paths and carets , syntactically the charater [ ' v ' ] is used to denote the caret 's insertion point before or after a path . There 's no distinction between a path an over caret . { v Ocaml.libs # value of key ' libs ' of dictionary ' ocaml ' ocaml.v[libs ] # before the key binding ( if any ) ocaml.[libs]v # after the key binding ( if any ) ocaml.libs.[0 ] # first element of key ' libs ' of dictionary ' ocaml ' ocaml.libs.v[0 ] # before first element ( if any ) ocaml.libs.[0]v # after first element ( if any ) ocaml.libs.[-1 ] # last element of key ' libs ' of dictionary ocaml.libs.v[-1 ] # before last element ( if any ) ocaml.libs.[-1]v # after last element ( if any ) v } More formally a { e path } is a [ . ] seperated list of indices . An { e index } is written [ [ i ] ] . [ i ] can a zero - based list index with negative indices counting from the end of the list ( [ -1 ] is the last element ) . Or [ i ] can be a dictionary key [ key ] . If there is no ambiguity , the surrounding brackets can be dropped . A caret is a path whose last index brackets can be prefixed or suffixed by an insertion point , represented by the character [ ' v ' ] . This respectively denote the void before or after the s - expression found by the path . { b Note . } The syntax has no form of quoting at the moment this means key names ca n't contain , [ \ [ ] , [ \ ] ] , or start with a number . { 1 : sexp_syntax S - expression syntax } S - expressions are a general way of describing data via atoms ( sequences of characters ) and lists delimited by parentheses . Here are a few examples of s - expressions and their syntax : { v this - is - an_atom ( this is a list of seven atoms ) ( this list contains ( a nested ) list ) ; This is a comment ; Anything that follows a semi - colon is ignored until the next line ( this list ; has three atoms and an embeded ( ) comment ) " this is a quoted atom , it can contain spaces ; and ( ) " " quoted atoms can be split ^ across lines or contain Unicode esc^u{0061}pes " v } We define the syntax of s - expressions over a sequence of { { : /#unicode_scalar_value}Unicode characters } in which all US - ASCII control characters ( U+0000 .. U+001F and U+007F ) except { { ! whitespace}whitespace } are forbidden in unescaped form . { 2 : sexp S - expressions } An { e s - expression } is either an { { ! atoms}{e atom } } or a { { ! lists}{e list } } of s - expressions interspaced with { { ! whitespace}{e whitespace } } and { { ! comments}{e comments } } . A { e sequence of s - expressions } is a succession of s - expressions interspaced with whitespace and comments . These elements are informally described below and finally made precise via an ABNF { { ! grammar}grammar } . { 2 : whitespace Whitespace } Whitespace is a sequence of whitespace characters , namely , space [ ' ' ] ( U+0020 ) , tab [ ' \t ' ] ( U+0009 ) , line feed [ ' \n ' ] ( U+000A ) , vertical tab [ ' \t ' ] ( U+000B ) , form feed ( U+000C ) and carriage return [ ' \r ' ] ( U+000D ) . { 2 : comments Comments } Unless it occurs inside an atom in quoted form ( see below ) anything that follows a semicolon [ ' ; ' ] ( U+003B ) is ignored until the next { e end of line } , that is either a line feed [ ' \n ' ] ( U+000A ) , a carriage return [ ' \r ' ] ( U+000D ) or a carriage return and a line feed [ " \r\n " ] ( < U+000D , U+000A > ) . { v ( this is not a comment ) ; This is a comment ( this is not a comment ) v } { 2 : atoms Atoms } An atom represents ground data as a string of Unicode characters . It can , via escapes , represent any sequence of Unicode characters , including control characters and U+0000 . It can not represent an arbitrary byte sequence except via a client - defined encoding convention ( e.g. Base64 or hex encoding ) . Atoms can be specified either via an unquoted or a quoted form . In unquoted form the atom is written without delimiters . In quoted form the atom is delimited by double quote [ ' " ' ] ( U+0022 ) characters , it is mandatory for atoms that contain { { ! whitespace}whitespace } , parentheses [ ' ( ' ] [ ' ) ' ] , semicolons [ ' ; ' ] , quotes [ ' " ' ] , carets [ ' ^ ' ] or characters that need to be escaped . { v abc ; a token for the atom " abc " " abc " ; a quoted token for the atom " abc " " abc ; ( d " ; a quoted token for the atom " abc ; ( d " " " ; the quoted token for the atom " " v } For atoms that do not need to be quoted , both their unquoted and quoted form represent the same string ; e.g. the string [ " true " ] can be represented both by the atoms { e true } and { e " true " } . The empty string can only be represented in quoted form by { e " " } . In quoted form escapes are introduced by a caret [ ' ^ ' ] . Double quotes [ ' " ' ] and carets [ ' ^ ' ] must always be escaped . { v " ^^ " ; atom for ^ " " ; atom for line feed U+000A " ^u{0000 } " ; atom for U+0000 " ^"^u{1F42B}^ " " ; atom with a quote , and a quote v } The following escape sequences are recognized : { ul { - [ " ^ " ] ( < U+005E , U+0020 > ) for space [ ' ' ] ( U+0020 ) } { - [ " ^\ " " ] ( < U+005E , U+0022 > ) for double quote [ ' " ' ] ( U+0022 ) { b mandatory } } { - [ " ^^ " ] ( < U+005E , U+005E > ) for caret [ ' ^ ' ] ( U+005E ) { b mandatory } } { - [ " " ] ( < U+005E , > ) for line feed [ ' \n ' ] ( U+000A ) } { - [ " ^r " ] ( < U+005E , U+0072 > ) for carriage return [ ' \r ' ] ( U+000D ) } { - [ " ^u{X } " ] with [ X ] is from 1 to at most 6 upper or lower case hexadecimal digits standing for the corresponding { { : /#unicode_scalar_value}Unicode character } U+X. } { - Any other character except line feed [ ' \n ' ] ( U+000A ) or carriage return [ ' \r ' ] ( U+000D ) , following a caret is an illegal sequence of characters . In the two former cases the atom continues on the next line and white space is ignored . } } An atom in quoted form can be split across lines by using a caret [ ' ^ ' ] ( U+005E ) followed by a line feed [ ' \n ' ] ( U+000A ) or a carriage return [ ' \r ' ] ( U+000D ) ; any subsequent { { ! whitespace}whitespace } is ignored . { v " ^ a^ ^ " ; the atom " a " v } The character ^ ( U+005E ) is used as an escape character rather than the usual \ ( U+005C ) in order to make quoted Windows ® file paths decently readable and , not the least , utterly please DKM . { 2 : lists Lists } Lists are delimited by left [ ' ( ' ] ( U+0028 ) and right [ ' ) ' ] ( U+0029 ) parentheses . Their elements are s - expressions separated by optional { { ! whitespace}whitespace } and { { ! comments}comments } . For example : { v ( a list ( of four ) expressions ) ( a list(of four)expressions ) ( " a"list("of"four)expressions ) ( a list ( of ; This is a comment four ) expressions ) ( ) ; the empty list v } { 2 : grammar Formal grammar } The following { { : }RFC 5234 } ABNF grammar is defined on a sequence of { { : /#unicode_scalar_value}Unicode characters } . { v sexp - seq = * ( ws / comment / sexp ) sexp = atom / list list = % x0028 sexp - seq % x0029 atom = token / qtoken token = t - char * ( t - char ) qtoken = % x0022 * ( q - char / escape / cont ) % x0022 escape = % x005E ( % x0020 / % x0022 / % x005E / % x006E / % x0072 / % x0075 % x007B unum % x007D ) unum = 1 * 6(HEXDIG ) cont = % x005E nl ws ws = * ( ws - char ) comment = % x003B * ( c - char ) nl nl = % x000A / % x000D / % x000D % x000A t - char = % x0021 / % x0023 - 0027 / % x002A-%x003A / % x003C-%x005D / % x005F-%x007E / % x0080 - D7FF / % xE000 - 10FFFF q - char = t - char / ws - char / % x0028 / % x0029 / % x003B ws - char = % x0020 / % x0009 / % x000A / % x000B / % x000C / % x000D c - char = % x0009 / % x000B / % x000C / % x0020 - D7FF / % xE000 - 10FFFF v } A few additional constraints not expressed by the grammar : { ul { - [ unum ] once interpreted as an hexadecimal number must be a { { : /#unicode_scalar_value}Unicode scalar value . } } { - A comment can be ended by the end of the character sequence rather than [ nl ] . } } An s-expression {e dictionary} is a list of bindings. A {e binding} is a list that starts with a {e key} and the remaining elements of the list are the binding's {e value}. For example in this binding: {v (key v0 v1 ...) v} The key is [key] and the value the possibly empty list [v0], [v1], ... of s-expressions. The {{!Sexpq.qdict}API} for dictionaries represents the value by a fake (doesn't exist syntactically) s-expression list whose text location starts at the first element of the value. {1:sexp_path_caret Path & caret syntax} Path and carets provide a way for end users to address s-expressions and edit locations. A {e path} is a sequence of {{!sexp_dict}key} and list indexing operations. Applying the path to an s-expression leads to an s-expression or nothing if one of the indices does not exist, or an error if ones tries to index an atom. A {e caret} is a path and a spatial specification for the s-expression found by the path. The caret indicates either the void before that expression, the expression itself (over caret) or the void after it. Here are a few examples of paths and carets, syntactically the charater ['v'] is used to denote the caret's insertion point before or after a path. There's no distinction between a path an over caret. {v Ocaml.libs # value of key 'libs' of dictionary 'ocaml' ocaml.v[libs] # before the key binding (if any) ocaml.[libs]v # after the key binding (if any) ocaml.libs.[0] # first element of key 'libs' of dictionary 'ocaml' ocaml.libs.v[0] # before first element (if any) ocaml.libs.[0]v # after first element (if any) ocaml.libs.[-1] # last element of key 'libs' of dictionary 'ocaml' ocaml.libs.v[-1] # before last element (if any) ocaml.libs.[-1]v # after last element (if any) v} More formally a {e path} is a [.] seperated list of indices. An {e index} is written [[i]]. [i] can a zero-based list index with negative indices counting from the end of the list ([-1] is the last element). Or [i] can be a dictionary key [key]. If there is no ambiguity, the surrounding brackets can be dropped. A caret is a path whose last index brackets can be prefixed or suffixed by an insertion point, represented by the character ['v']. This respectively denote the void before or after the s-expression found by the path. {b Note.} The syntax has no form of quoting at the moment this means key names can't contain, [\[], [\]], or start with a number. {1:sexp_syntax S-expression syntax} S-expressions are a general way of describing data via atoms (sequences of characters) and lists delimited by parentheses. Here are a few examples of s-expressions and their syntax: {v this-is-an_atom (this is a list of seven atoms) (this list contains (a nested) list) ; This is a comment ; Anything that follows a semi-colon is ignored until the next line (this list ; has three atoms and an embeded () comment) "this is a quoted atom, it can contain spaces ; and ()" "quoted atoms can be split ^ across lines or contain Unicode esc^u{0061}pes" v} We define the syntax of s-expressions over a sequence of {{:/#unicode_scalar_value}Unicode characters} in which all US-ASCII control characters (U+0000..U+001F and U+007F) except {{!whitespace}whitespace} are forbidden in unescaped form. {2:sexp S-expressions} An {e s-expression} is either an {{!atoms}{e atom}} or a {{!lists}{e list}} of s-expressions interspaced with {{!whitespace}{e whitespace}} and {{!comments}{e comments}}. A {e sequence of s-expressions} is a succession of s-expressions interspaced with whitespace and comments. These elements are informally described below and finally made precise via an ABNF {{!grammar}grammar}. {2:whitespace Whitespace} Whitespace is a sequence of whitespace characters, namely, space [' '] (U+0020), tab ['\t'] (U+0009), line feed ['\n'] (U+000A), vertical tab ['\t'] (U+000B), form feed (U+000C) and carriage return ['\r'] (U+000D). {2:comments Comments} Unless it occurs inside an atom in quoted form (see below) anything that follows a semicolon [';'] (U+003B) is ignored until the next {e end of line}, that is either a line feed ['\n'] (U+000A), a carriage return ['\r'] (U+000D) or a carriage return and a line feed ["\r\n"] (<U+000D,U+000A>). {v (this is not a comment) ; This is a comment (this is not a comment) v} {2:atoms Atoms} An atom represents ground data as a string of Unicode characters. It can, via escapes, represent any sequence of Unicode characters, including control characters and U+0000. It cannot represent an arbitrary byte sequence except via a client-defined encoding convention (e.g. Base64 or hex encoding). Atoms can be specified either via an unquoted or a quoted form. In unquoted form the atom is written without delimiters. In quoted form the atom is delimited by double quote ['"'] (U+0022) characters, it is mandatory for atoms that contain {{!whitespace}whitespace}, parentheses ['('] [')'], semicolons [';'], quotes ['"'], carets ['^'] or characters that need to be escaped. {v abc ; a token for the atom "abc" "abc" ; a quoted token for the atom "abc" "abc; (d" ; a quoted token for the atom "abc; (d" "" ; the quoted token for the atom "" v} For atoms that do not need to be quoted, both their unquoted and quoted form represent the same string; e.g. the string ["true"] can be represented both by the atoms {e true} and {e "true"}. The empty string can only be represented in quoted form by {e ""}. In quoted form escapes are introduced by a caret ['^']. Double quotes ['"'] and carets ['^'] must always be escaped. {v "^^" ; atom for ^ "^n" ; atom for line feed U+000A "^u{0000}" ; atom for U+0000 "^"^u{1F42B}^"" ; atom with a quote, U+1F42B and a quote v} The following escape sequences are recognized: {ul {- ["^ "] (<U+005E,U+0020>) for space [' '] (U+0020)} {- ["^\""] (<U+005E,U+0022>) for double quote ['"'] (U+0022) {b mandatory}} {- ["^^"] (<U+005E,U+005E>) for caret ['^'] (U+005E) {b mandatory}} {- ["^n"] (<U+005E,U+006E>) for line feed ['\n'] (U+000A)} {- ["^r"] (<U+005E,U+0072>) for carriage return ['\r'] (U+000D)} {- ["^u{X}"] with [X] is from 1 to at most 6 upper or lower case hexadecimal digits standing for the corresponding {{:/#unicode_scalar_value}Unicode character} U+X.} {- Any other character except line feed ['\n'] (U+000A) or carriage return ['\r'] (U+000D), following a caret is an illegal sequence of characters. In the two former cases the atom continues on the next line and white space is ignored.}} An atom in quoted form can be split across lines by using a caret ['^'] (U+005E) followed by a line feed ['\n'] (U+000A) or a carriage return ['\r'] (U+000D); any subsequent {{!whitespace}whitespace} is ignored. {v "^ a^ ^ " ; the atom "a " v} The character ^ (U+005E) is used as an escape character rather than the usual \ (U+005C) in order to make quoted Windows® file paths decently readable and, not the least, utterly please DKM. {2:lists Lists} Lists are delimited by left ['('] (U+0028) and right [')'] (U+0029) parentheses. Their elements are s-expressions separated by optional {{!whitespace}whitespace} and {{!comments}comments}. For example: {v (a list (of four) expressions) (a list(of four)expressions) ("a"list("of"four)expressions) (a list (of ; This is a comment four) expressions) () ; the empty list v} {2:grammar Formal grammar} The following {{:}RFC 5234} ABNF grammar is defined on a sequence of {{:/#unicode_scalar_value}Unicode characters}. {v sexp-seq = *(ws / comment / sexp) sexp = atom / list list = %x0028 sexp-seq %x0029 atom = token / qtoken token = t-char *(t-char) qtoken = %x0022 *(q-char / escape / cont) %x0022 escape = %x005E (%x0020 / %x0022 / %x005E / %x006E / %x0072 / %x0075 %x007B unum %x007D) unum = 1*6(HEXDIG) cont = %x005E nl ws ws = *(ws-char) comment = %x003B *(c-char) nl nl = %x000A / %x000D / %x000D %x000A t-char = %x0021 / %x0023-0027 / %x002A-%x003A / %x003C-%x005D / %x005F-%x007E / %x0080-D7FF / %xE000-10FFFF q-char = t-char / ws-char / %x0028 / %x0029 / %x003B ws-char = %x0020 / %x0009 / %x000A / %x000B / %x000C / %x000D c-char = %x0009 / %x000B / %x000C / %x0020-D7FF / %xE000-10FFFF v} A few additional constraints not expressed by the grammar: {ul {- [unum] once interpreted as an hexadecimal number must be a {{:/#unicode_scalar_value}Unicode scalar value.}} {- A comment can be ended by the end of the character sequence rather than [nl]. }} *) --------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/serialk/2650979af5ed3a8b55e259088acd618a61061856/src/serialk_sexp.mli
ocaml
* S-expression definitions and codec. * The type for formatting functions. * The type for source text locations. * [loc_nil] is a source text location for non-parsed s-expressions. * [pp_loc] is {!Tloc.pp}. * The type for meta information about atoms. * The type for meta information about lists. * [a_meta_nil] is parse information for non-parsed atoms. * [l_meta_nil] is parse information for non-parsed lists. * The type for generic s-expression representations. Either an atom or a list. * [atom a] is [`A (a, a_meta_nil)]. * [list l] is [`L (l, l_meta_nil)]. * [to_atom s] extracts an atom from [s]. If [s] is a list an error with the location formatted according to {!Tloc.pp} is returned. * [to_list s] extracts a list from [s]. If [s] is an atom an error with the location formatted according to {!Tloc.pp} is returned. * [to_splice s] is the either the list of [s] if [s] is or or [[s]] if [s] is an atom. * [pp] formats an s-expression. * [pp_layout ppf l] is like {!pp} but uses layout information. * [pp_seq] formats an s-expression but if it is a list the outer list separators are not formatted in the output. {b Warning.} Assumes all OCaml strings in the formatted value are UTF-8 encoded. * [pp_seq_layout] is like {!pp_seq} but uses layout information. * The type for kinds of decoding error. * [pp_error_kind ()] formats an error kind. * The type for decoding errors. * [pp_error ~pp_loc ~pp_error_kind ~pp_prefix ()] formats errors using [pp_loc] (defaults to {!pp_loc}), [pp_error_kind] (defaults to {!pp_error_kind}) and [pp_prefix] (defaults formats ["Error: "]). * [error_to_string r] converts an error to a string using [pp_error] (defaults to {!pp_error}). * [seq_of_string'] s {!seq_of_string} composed with {!error_to_string}. * * * [pp_key] formats a key, this is {!Format.pp_print_string}. * [pp_index] formats indices. Keys are unbracketed and formatted with [pp_key], defaults to {!pp_key}. * The type for paths, a sequence of indexing operations in {b reverse} order. * [path_of_string] parses a path from [s] according to the syntax {{!sexp_path_caret}given here}. * [pp_path ?pp_key ()] is a formatter for paths using [pp_key] to format keys (defaults to {!pp_key}). * {1:carets Carets} * The void before the s-expression found by the path. * The s-expression found by the path. * The void after the s-expression found by the path. * The type for caret locations. * The type for carets. A caret location and the path at which it applies. * [caret_of_string s] parses a caret from [s] according to the syntax {{!sexp_path_caret}given here}. * [pp_caret ?pp_key ()] is a formatter for carets using [pp_key] to format keys (defaults to {!pp_key}). * S-expression generation. * The type for generated s-expressions. * [atom s] is [s] as an atom. * The type for generated s-expression lists. * [ls] starts a list. * [le l] ends lists [l]. * [el e l] is list [l] with [e] added at the end. * [el cond v l] is [el (v ()) l] if [cond] is [true] and [l] otherwise. * [atomf fmt ...] is an atom formatted according to [fmt]. * [bool b] is [atomf "%b" b]. * [int i] is [atomf "%d" i]. * [float f] is [atomf "%g" f]. * [float_hex f] is [atomf "%h" f]. * [string s] is {!atom}. * [option some o] is [o] as the [none] atom if [o] is [none] and a list starting with [some] atom followed by [some v] if [o] is [Some v]. * [list el l] is [l] as a list whose elements are generated using [el]. * [sexp s] is the s-expression [s] as a generated value. * [buffer_add b g] adds the generated s-expression value [g] to [b]. * [to_string g] is the generated s-expression value [g] as a string. * S-expression queries. * The type for result paths. This is a sequence of indexing operations tupled with the source text location of the indexed s-expression in {b reverse} order. * [pp_path ~pp_loc ~pp_key ()] formats paths using [pp_loc] (defaults to {!Sexp.pp_loc}) and [pp_key] to format the keys (defaults to {!Sexp.pp_key}). * The type for kinds of errors. {ul {- [`Key_unbound (k, dom)] on [k] that should have been in [dom] (if not empty).} {- [`Msg m] an arbitrary message [m] (should not include position information).} {- [`Nth_unbound (n, len)] on [n] an out of bound index in a list of length [len].} {- [`Out_of_dom (kind, v, dom)] on [v] of kind [kind] that should have been in [dom]}} * The type for query errors. The error kind tupled with the path to the offending s-expression and the location of the s-expression. * [pp_error ~pp_loc ~pp_path ~pp_error_kind ~pp_prefix ()] formats errors using [pp_loc], [pp_path] (defaults to {!pp_path}), [pp_error_kind] (defaults to {!pp_error_kind}) and [pp_prefix] (defaults formats ["Error: "]). * The type for s-expression queries. A query either succeeds against an s-expression with a value of type ['a] or it fails. * [query q s] is [Ok v] if the query [q] succeeds on [s] and [Error e] otherwise. * [query_at_path q (s, p)] is like {!query} except it assumes [s] is at path [p]. Use to further query s-expressions obtained with {!sexp_with_path} so that errors return the full path to errors. * [query' q s] is like {!query} except the result is composed with {!error_to_string}. * [succeed v] is a query that succeeds with value [v] on any s-expression. * [fail k] is a query that fails on any s-expression with error kind [k]. * [failf fmt ...] is [fail (`Msg m)] with [m] formatted according to [fmt]. * [f $ v] is [app f v]. * [bind q f] queries an s-expression with [q], applies the result to [f] and re-queries the s-expression with the result. * [map f q] is [app (succeed f) q]. * [loc q] queries with [q] an returns the result with the query path and source text location to the queried s-expression. * [sexp] queries any s-expression and returns its generic representation. * [sexp_with_path] is like {!sexp} but also returns the path to s-expression. * [atom] queries an atom as a string. * [int] queries an atom for an integer value parsed with {!int_of_string}. * [float] queries an atom for a float value parsed with {!float_of_string}. * [is_empty] queries a list for emptyness. * [hd q] queries the head of a list with [q]. Fails on empty lists. * [tail q] queries the tail of a list with [q]. Fails on empty lists. * [list q] queries the elements of a list with [q]. * [nth ?absent n q] queries the [n]th index of a list with [q]. If [n] is negative counts from the end of the list, so [-1] is the last list element. If the element does not exist this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. * [delete_nth ~must_exist n] deletes the [n]th element of the list. If the element does not exist this fails when [must_exist] is [true] or returns the list unchanged when [must_exist] is [false]. * [key ?absent k q] queries the value of key [k] of a dictionary with [q]. If [k] is not bound this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. * [delete_key ~must_exist k] deletes key [k] from the dictionary. If [k] is not bound this fails when [must_exist] is [true] or returns the dictionary unchanged when [must_exist] is [false]. * [key_dom validate] queries the key domain of a list of bindings. If [validate] is [Some dom], the query fails if a key is not in [dom]. The query also fails if a binding is not well-formed. [pp_key] is used to format keys. {b TODO.} Not really happy about this function, we lose the key locations which is useful for further deconstruction. Also maybe we rather want binding folds. * [atomic q] queries an atom or the atom of a singleton list with [q]. It fails on empty lists or non-singleton lists. This is useful for singleton {{!sexp_dict}dictionary} bindings. In error reporting treats the list as if it doesn't exist syntactically which is the case in dictionary bindings. * [index ?absent i q] queries the s-expression index [i] with [q] using {!nth} or {!key} according to [i]. Fails on atoms. * [path p q] queries the s-expression found by [p] using [q]. If [p] can't be found this fails if [absent] is [None] and succeeds with [v] if [absent] is [Some v]. * [probe_path p] is a query that probes for [p]'s existence. Except for indexing errors it always succeeds with [(sp, s, rem)]: {ul {- If [p] is found, this is the path to [sp] to the found expression [s] and [rem] is empty.} {- If [p] is not found, this is the path [sp] that leads to the s-expression [s] that could not be indexed and [rem] has the indexes that could not be performed.}} * [delete_at_path ~must_exist p] deletes the s-expression found by [p] from the queried s-expression. If the path does not exist this fails if [must_exist] is [true] and returns the s-expression itself if [must_exist] is [false]. * [option q] queries with [q] the value of an option represented according the encoding of {!Sexpg.option}.
--------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) * S - expression support . The module { ! Sexp } has an s - expression codec and general definitions for working with them . { ! } generates s - expressions without going through a generic representation . { ! } queries and updates generic representations with combinators . Consult a { { ! sexp_syntax}short introduction } to s - expressions and the syntax parsed by the codec , the encoding of { { ! sexp_dict}key - value dictionaries } supported by this module and the end - user syntax for { { ! sexp_path_caret}addressing and updating } s - expressions . Open this module to use it , this only introduces modules in your scope . { b Warning . } Serialization functions always assumes all OCaml strings in the data you provide is UTF-8 encoded . This is not checked by the module . The module {!Sexp} has an s-expression codec and general definitions for working with them. {!Sexpg} generates s-expressions without going through a generic representation. {!Sexpq} queries and updates generic representations with combinators. Consult a {{!sexp_syntax}short introduction} to s-expressions and the syntax parsed by the codec, the encoding of {{!sexp_dict}key-value dictionaries} supported by this module and the end-user syntax for {{!sexp_path_caret}addressing and updating} s-expressions. Open this module to use it, this only introduces modules in your scope. {b Warning.} Serialization functions always assumes all OCaml strings in the data you provide is UTF-8 encoded. This is not checked by the module. *) * { 1 : api API } open Serialk_text module Sexp : sig * { 1 : meta Meta information } type 'a fmt = Format.formatter -> 'a -> unit type loc = Tloc.t val loc_nil : Tloc.t val pp_loc : loc fmt type a_meta type l_meta val a_meta_nil : a_meta val l_meta_nil : l_meta * { 1 : sexp S - expressions } type t = [ `A of string * a_meta | `L of t list * l_meta ] val atom : string -> t val list : t list -> t * { 1 : access Accessors } val loc : t -> loc * [ loc s ] is [ s ] 's source text location . val to_atom : t -> (string, string) result val get_atom : t -> string * [ s ] is like { ! to_atom } but raises { ! Invalid_argument } if [ s ] is not an atom . if [s] is not an atom. *) val to_list : t -> (t list, string) result val get_list : t -> t list * [ s ] is like { ! to_list } but raises { ! Invalid_argument } if [ s ] is not an list . if [s] is not an list. *) val to_splice : t -> t list * { 1 : fmt Formatting } val pp : t fmt val pp_layout : t fmt val pp_seq : t fmt val pp_seq_layout : t fmt * { 1 : codec Codec } type error_kind val pp_error_kind : unit -> error_kind fmt type error = error_kind * loc val pp_error : ?pp_loc:loc fmt -> ?pp_error_kind:error_kind fmt -> ?pp_prefix:unit fmt -> unit -> error fmt val error_to_string : ?pp_error:error fmt -> ('a, error) result -> ('a, string) result val seq_of_string : ?file:Tloc.fpath -> string -> (t, error) result * [ seq_of_string ? file s ] parses a { e sequence } of s - expressions from [ s ] . [ file ] is the file for locations , defaults to [ " - " ] . The sequence is returned as a fake s - expression list that spans from the start of the first s - expression in [ s ] to the end of the last one ; note that this list does not exist syntactically in [ s ] . If there are no s - expression in [ s ] the list is empty its location has both start and end positions at byte [ 0 ] ( which may not exist ) . { b Note . } All OCaml strings returned by this function are UTF-8 encoded . [s]. [file] is the file for locations, defaults to ["-"]. The sequence is returned as a fake s-expression list that spans from the start of the first s-expression in [s] to the end of the last one; note that this list does not exist syntactically in [s]. If there are no s-expression in [s] the list is empty its location has both start and end positions at byte [0] (which may not exist). {b Note.} All OCaml strings returned by this function are UTF-8 encoded. *) val seq_of_string' : ?pp_error:error fmt -> ?file:Tloc.fpath -> string -> (t, string) result val seq_to_string : t -> string * [ seq_to_string s ] encodes [ s ] to a sequence of s - expressions . If [ s ] is an s - expression list this wrapping list is not syntactically represented in the output ( see also { ! seq_of_string } ) , use [ to_string ( list [ l ] ) ] if you want to output [ l ] as a list . { b Warning . } Assumes all OCaml strings in [ s ] are UTF-8 encoded . is an s-expression list this wrapping list is not syntactically represented in the output (see also {!seq_of_string}), use [to_string (list [l])] if you want to output [l] as a list. {b Warning.} Assumes all OCaml strings in [s] are UTF-8 encoded. *) * { 1 : sexp_index S - expression indices } type index = * The type for s - expression indexing operations . { ul { - [ Nth n ] , lookup zero - based element [ n ] in a list . If [ n ] is negative , counts the number of elements from the end of the list , i.e. [ -1 ] is the last list element . } { - [ Key k ] , lookup binding [ k ] in an s - expression { { ! sexp_dict}dictionary . } } } {ul {- [Nth n], lookup zero-based element [n] in a list. If [n] is negative, counts the number of elements from the end of the list, i.e. [-1] is the last list element.} {- [Key k], lookup binding [k] in an s-expression {{!sexp_dict}dictionary.}}} *) val pp_key : string fmt val pp_index : ?pp_key:string fmt -> unit -> index fmt * { 1 : sexp_path S - expression paths } type path = index list val path_of_string : string -> (path, string) result val pp_path : ?pp_key:string fmt -> unit -> path fmt type caret_loc = type caret = caret_loc * path val caret_of_string : string -> (caret, string) result val pp_caret : ?pp_key:string fmt -> unit -> caret fmt end module Sexpg : sig * { 1 : gen Generation } type t val atom : string -> t type lyst val ls : lyst val le : lyst -> t val el : t -> lyst -> lyst val el_if : bool -> (unit -> t) -> lyst -> lyst * { 1 : derived Derived generators } val atomf : ('a, Format.formatter, unit, t) format4 -> 'a val bool : bool -> t val int : int -> t val float : float -> t val float_hex : float -> t val string : string -> t val option : ('a -> t) -> 'a option -> t val list : ('a -> t) -> 'a list -> t val sexp : Sexp.t -> t * { 1 : output Output } val buffer_add : Buffer.t -> t -> unit val to_string : t -> string end module Sexpq : sig * { 1 : query_results Result paths } type path = (Sexp.index * Sexp.loc) list val pp_path : ?pp_loc:Sexp.loc Sexp.fmt -> ?pp_key:string Sexp.fmt -> unit -> path Sexp.fmt * { 1 : query_errors Query errors } type error_kind = [ `Key_unbound of string * string list | `Msg of string | `Nth_unbound of int * int | `Out_of_dom of string * string * string list ] val pp_error_kind : ?pp_em:string Sexp.fmt -> ?pp_key:string Sexp.fmt -> unit -> error_kind Sexp.fmt * [ pp_error_kind ~pp_loc ~pp_em ~pp_key ( ) ] formats error kinds using [ pp_loc ] for locations , [ pp_em ] for emphasis and [ pp_key ] for keys . using [pp_loc] for locations, [pp_em] for emphasis and [pp_key] for keys. *) type error = error_kind * (path * Sexp.loc) val pp_error : ?pp_loc:Sexp.loc Sexp.fmt -> ?pp_path:path Sexp.fmt -> ?pp_error_kind:error_kind Sexp.fmt -> ?pp_prefix:unit Sexp.fmt -> unit -> error Sexp.fmt val error_to_string : ?pp_error:error Sexp.fmt -> ('a, error) result -> ('a, string) result * [ error_to_string ] converts an error in [ r ] to a string using [ pp_error ] , defaults to { ! pp_error } . [pp_error], defaults to {!pp_error}. *) * { 1 : queries Queries } type 'a t val query : 'a t -> Sexp.t -> ('a, error) result val query_at_path : 'a t -> (Sexp.t * path) -> ('a, error) result val query' : ?pp_error:error Sexp.fmt -> 'a t -> Sexp.t -> ('a, string) result * { 1 : outcome Success and failure } val succeed : 'a -> 'a t val fail : error_kind -> 'a t val failf : ('a, Format.formatter, unit, 'b t) format4 -> 'a * { 1 : qcomb Query combinators } val app : ('a -> 'b) t -> 'a t -> 'b t * [ app fq q ] queries an s - expression first with [ fq ] and then with [ q ] and applies the result of latter to the former . and applies the result of latter to the former. *) val ( $ ) : ('a -> 'b) t -> 'a t -> 'b t val pair : 'a t -> 'b t -> ('a * 'b) t * [ pair q0 q1 ] queries an s - expression first with [ q0 ] and then with [ q1 ] and returns the pair of their result . and returns the pair of their result. *) val bind : 'a t -> ('a -> 'b t) -> 'b t val map : ('a -> 'b) -> 'a t -> 'b t val some : 'a t -> 'a option t * [ some q ] is [ map Option.some q ] . val loc : 'a t -> ('a * (path * Sexp.loc)) t * { 1 : } Queries for s - expressions . These queries never fail . Queries for s-expressions. These queries never fail. *) val fold : atom:'a t -> list:'a t -> 'a t * [ fold ~list ] queries atoms with [ atom ] and lists with [ list ] . val sexp : Sexp.t t val sexp_with_path : (Sexp.t * path) t * { 1 : qatom Atom queries } Queries for atoms . These queries fail on lists . Queries for atoms. These queries fail on lists. *) val atom : string t val atom_to : kind:string -> (string -> ('a, string) result) -> 'a t * [ atom_to ~kind p ] queries an atom and parses it with [ p ] . In case of [ Error m ] fails with message [ m ] . [ kind ] is the kind of value parsed , used for the error in case a list is found . case of [Error m] fails with message [m]. [kind] is the kind of value parsed, used for the error in case a list is found. *) * { b TODO . } Maybe combinators to devise an approriate parse function for { ! atom_to } are a better idea than the following two combinators . function for {!atom_to} are a better idea than the following two combinators. *) val enum : kind:string -> Set.Make(String).t -> string t * [ enum ~kind ss ] queries an atom for one of the element of [ ss ] and fails otherwise . [ kind ] is for the kind of elements in [ ss ] , it used for error reporting . and fails otherwise. [kind] is for the kind of elements in [ss], it used for error reporting. *) val enum_map : kind:string -> 'a Map.Make(String).t -> 'a t * [ enum_map ~pp_elt ~kind sm ] queries an atom for it 's map in [ sm ] and fails if the atom is not bound in [ sm ] . [ kind ] is for the kind of elements in [ sm ] , it used for error reporting . and fails if the atom is not bound in [sm]. [kind] is for the kind of elements in [sm], it used for error reporting. *) val bool : bool t * [ bool ] queries an atom for one of [ true ] or [ false ] . val int : int t val int32 : int32 t * [ int32 ] queries an atom for an integer value parsed with { ! } . {!Int32.of_string}. *) val int64 : int64 t * [ int64 ] queries an atom for an integer value parsed with { ! Int64.of_string } . {!Int64.of_string}. *) val float : float t * { 1 : qlist List queries } Queries for s - expression lists . These queries fail on atoms . Queries for s-expression lists. These queries fail on atoms. *) val is_empty : bool t val hd : 'a t -> 'a t val tl : 'a t -> 'a t val fold_list : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b t * [ fold_list f q acc ] queries the elements of a list from left to right with [ q ] and folds the result with [ f ] starting with [ acc ] . right with [q] and folds the result with [f] starting with [acc]. *) val list : 'a t -> 'a list t * { 2 : qlist List index queries } val nth : ?absent:'a -> int -> 'a t -> 'a t val delete_nth : must_exist:bool -> int -> Sexp.t t * { 1 : qdict Dictionary queries } Queries for s - expression { { ! sexp}dictionaries } . These queries fail on atoms . Queries for s-expression {{!sexp}dictionaries}. These queries fail on atoms. *) val key : ?absent:'a -> string -> 'a t -> 'a t val delete_key : must_exist:bool -> string -> Sexp.t t val key_dom : validate:Set.Make(String).t option -> Set.Make(String).t t val atomic : 'a t -> 'a t * { 1 : indices Index queries } val index : ?absent:'a -> Sexp.index -> 'a t -> 'a t val delete_index : must_exist:bool -> Sexp.index -> Sexp.t t * [ delete_index ~must_exist i ] deletes the s - expression index [ i ] using { ! } or { ! delete_key } according to [ i ] . using {!delete_nth} or {!delete_key} according to [i]. *) * { 1 : path_caret Path and caret queries } These queries fail on indexing errors , that is if an atom gets indexed . These queries fail on indexing errors, that is if an atom gets indexed. *) val path : ?absent:'a -> Sexp.path -> 'a t -> 'a t val probe_path : Sexp.path -> (path * Sexp.t * Sexp.path) t val delete_at_path : must_exist:bool -> Sexp.path -> Sexp.t t val splice_at_path : ?stub:Sexp.t -> must_exist:bool -> Sexp.path -> rep:Sexp.t -> Sexp.t t * [ splice_at_path ? stub ~must_exist ] replaces the s - expression found at [ p ] by splicing [ rep ] . If the path does not exist this fails if [ must_exist ] is [ true ] and the non - existing part of the path is created if [ must_exist ] is [ false ] . If elements need to be created [ stub ] ( defaults to [ Sexp.atom " " ] ) is used . found at [p] by splicing [rep]. If the path does not exist this fails if [must_exist] is [true] and the non-existing part of the path is created if [must_exist] is [false]. If elements need to be created [stub] (defaults to [Sexp.atom ""]) is used. *) val splice_at_caret : ?stub:Sexp.t -> must_exist:bool -> Sexp.caret -> rep:Sexp.t -> Sexp.t t * [ splice_caret ? stub ~must_exist p rep ] splices the s - expression [ rep ] at the caret [ p ] of the s - expression . If path of the caret does not exist this fails if [ must_exist ] is [ true ] and the non - existing part of the path is created if [ must_exist ] is [ false ] . If atoms need to be create [ stub ] ( defaults to [ Sexp.atom " " ] ) is used . at the caret [p] of the s-expression. If path of the caret does not exist this fails if [must_exist] is [true] and the non-existing part of the path is created if [must_exist] is [false]. If atoms need to be create [stub] (defaults to [Sexp.atom ""]) is used. *) * { 1 : ocaml OCaml datatype encoding queries } val option : 'a t -> 'a option t end * { 1 : sexp_dict Dictionaries } An s - expression { e dictionary } is a list of bindings . A { e binding } is a list that starts with a { e key } and the remaining elements of the list are the binding 's { e value } . For example in this binding : { v ( key v0 v1 ... ) v } The key is [ key ] and the value the possibly empty list [ v0 ] , [ v1 ] , ... of s - expressions . The { { ! Sexpq.qdict}API } for dictionaries represents the value by a fake ( does n't exist syntactically ) s - expression list whose text location starts at the first element of the value . { 1 : sexp_path_caret Path & caret syntax } Path and carets provide a way for end users to address s - expressions and edit locations . A { e path } is a sequence of { { ! sexp_dict}key } and list indexing operations . Applying the path to an s - expression leads to an s - expression or nothing if one of the indices does not exist , or an error if ones tries to index an atom . A { e caret } is a path and a spatial specification for the s - expression found by the path . The caret indicates either the void before that expression , the expression itself ( over caret ) or the void after it . Here are a few examples of paths and carets , syntactically the charater [ ' v ' ] is used to denote the caret 's insertion point before or after a path . There 's no distinction between a path an over caret . { v Ocaml.libs # value of key ' libs ' of dictionary ' ocaml ' ocaml.v[libs ] # before the key binding ( if any ) ocaml.[libs]v # after the key binding ( if any ) ocaml.libs.[0 ] # first element of key ' libs ' of dictionary ' ocaml ' ocaml.libs.v[0 ] # before first element ( if any ) ocaml.libs.[0]v # after first element ( if any ) ocaml.libs.[-1 ] # last element of key ' libs ' of dictionary ocaml.libs.v[-1 ] # before last element ( if any ) ocaml.libs.[-1]v # after last element ( if any ) v } More formally a { e path } is a [ . ] seperated list of indices . An { e index } is written [ [ i ] ] . [ i ] can a zero - based list index with negative indices counting from the end of the list ( [ -1 ] is the last element ) . Or [ i ] can be a dictionary key [ key ] . If there is no ambiguity , the surrounding brackets can be dropped . A caret is a path whose last index brackets can be prefixed or suffixed by an insertion point , represented by the character [ ' v ' ] . This respectively denote the void before or after the s - expression found by the path . { b Note . } The syntax has no form of quoting at the moment this means key names ca n't contain , [ \ [ ] , [ \ ] ] , or start with a number . { 1 : sexp_syntax S - expression syntax } S - expressions are a general way of describing data via atoms ( sequences of characters ) and lists delimited by parentheses . Here are a few examples of s - expressions and their syntax : { v this - is - an_atom ( this is a list of seven atoms ) ( this list contains ( a nested ) list ) ; This is a comment ; Anything that follows a semi - colon is ignored until the next line ( this list ; has three atoms and an embeded ( ) comment ) " this is a quoted atom , it can contain spaces ; and ( ) " " quoted atoms can be split ^ across lines or contain Unicode esc^u{0061}pes " v } We define the syntax of s - expressions over a sequence of { { : /#unicode_scalar_value}Unicode characters } in which all US - ASCII control characters ( U+0000 .. U+001F and U+007F ) except { { ! whitespace}whitespace } are forbidden in unescaped form . { 2 : sexp S - expressions } An { e s - expression } is either an { { ! atoms}{e atom } } or a { { ! lists}{e list } } of s - expressions interspaced with { { ! whitespace}{e whitespace } } and { { ! comments}{e comments } } . A { e sequence of s - expressions } is a succession of s - expressions interspaced with whitespace and comments . These elements are informally described below and finally made precise via an ABNF { { ! grammar}grammar } . { 2 : whitespace Whitespace } Whitespace is a sequence of whitespace characters , namely , space [ ' ' ] ( U+0020 ) , tab [ ' \t ' ] ( U+0009 ) , line feed [ ' \n ' ] ( U+000A ) , vertical tab [ ' \t ' ] ( U+000B ) , form feed ( U+000C ) and carriage return [ ' \r ' ] ( U+000D ) . { 2 : comments Comments } Unless it occurs inside an atom in quoted form ( see below ) anything that follows a semicolon [ ' ; ' ] ( U+003B ) is ignored until the next { e end of line } , that is either a line feed [ ' \n ' ] ( U+000A ) , a carriage return [ ' \r ' ] ( U+000D ) or a carriage return and a line feed [ " \r\n " ] ( < U+000D , U+000A > ) . { v ( this is not a comment ) ; This is a comment ( this is not a comment ) v } { 2 : atoms Atoms } An atom represents ground data as a string of Unicode characters . It can , via escapes , represent any sequence of Unicode characters , including control characters and U+0000 . It can not represent an arbitrary byte sequence except via a client - defined encoding convention ( e.g. Base64 or hex encoding ) . Atoms can be specified either via an unquoted or a quoted form . In unquoted form the atom is written without delimiters . In quoted form the atom is delimited by double quote [ ' " ' ] ( U+0022 ) characters , it is mandatory for atoms that contain { { ! whitespace}whitespace } , parentheses [ ' ( ' ] [ ' ) ' ] , semicolons [ ' ; ' ] , quotes [ ' " ' ] , carets [ ' ^ ' ] or characters that need to be escaped . { v abc ; a token for the atom " abc " " abc " ; a quoted token for the atom " abc " " abc ; ( d " ; a quoted token for the atom " abc ; ( d " " " ; the quoted token for the atom " " v } For atoms that do not need to be quoted , both their unquoted and quoted form represent the same string ; e.g. the string [ " true " ] can be represented both by the atoms { e true } and { e " true " } . The empty string can only be represented in quoted form by { e " " } . In quoted form escapes are introduced by a caret [ ' ^ ' ] . Double quotes [ ' " ' ] and carets [ ' ^ ' ] must always be escaped . { v " ^^ " ; atom for ^ " " ; atom for line feed U+000A " ^u{0000 } " ; atom for U+0000 " ^"^u{1F42B}^ " " ; atom with a quote , and a quote v } The following escape sequences are recognized : { ul { - [ " ^ " ] ( < U+005E , U+0020 > ) for space [ ' ' ] ( U+0020 ) } { - [ " ^\ " " ] ( < U+005E , U+0022 > ) for double quote [ ' " ' ] ( U+0022 ) { b mandatory } } { - [ " ^^ " ] ( < U+005E , U+005E > ) for caret [ ' ^ ' ] ( U+005E ) { b mandatory } } { - [ " " ] ( < U+005E , > ) for line feed [ ' \n ' ] ( U+000A ) } { - [ " ^r " ] ( < U+005E , U+0072 > ) for carriage return [ ' \r ' ] ( U+000D ) } { - [ " ^u{X } " ] with [ X ] is from 1 to at most 6 upper or lower case hexadecimal digits standing for the corresponding { { : /#unicode_scalar_value}Unicode character } U+X. } { - Any other character except line feed [ ' \n ' ] ( U+000A ) or carriage return [ ' \r ' ] ( U+000D ) , following a caret is an illegal sequence of characters . In the two former cases the atom continues on the next line and white space is ignored . } } An atom in quoted form can be split across lines by using a caret [ ' ^ ' ] ( U+005E ) followed by a line feed [ ' \n ' ] ( U+000A ) or a carriage return [ ' \r ' ] ( U+000D ) ; any subsequent { { ! whitespace}whitespace } is ignored . { v " ^ a^ ^ " ; the atom " a " v } The character ^ ( U+005E ) is used as an escape character rather than the usual \ ( U+005C ) in order to make quoted Windows ® file paths decently readable and , not the least , utterly please DKM . { 2 : lists Lists } Lists are delimited by left [ ' ( ' ] ( U+0028 ) and right [ ' ) ' ] ( U+0029 ) parentheses . Their elements are s - expressions separated by optional { { ! whitespace}whitespace } and { { ! comments}comments } . For example : { v ( a list ( of four ) expressions ) ( a list(of four)expressions ) ( " a"list("of"four)expressions ) ( a list ( of ; This is a comment four ) expressions ) ( ) ; the empty list v } { 2 : grammar Formal grammar } The following { { : }RFC 5234 } ABNF grammar is defined on a sequence of { { : /#unicode_scalar_value}Unicode characters } . { v sexp - seq = * ( ws / comment / sexp ) sexp = atom / list list = % x0028 sexp - seq % x0029 atom = token / qtoken token = t - char * ( t - char ) qtoken = % x0022 * ( q - char / escape / cont ) % x0022 escape = % x005E ( % x0020 / % x0022 / % x005E / % x006E / % x0072 / % x0075 % x007B unum % x007D ) unum = 1 * 6(HEXDIG ) cont = % x005E nl ws ws = * ( ws - char ) comment = % x003B * ( c - char ) nl nl = % x000A / % x000D / % x000D % x000A t - char = % x0021 / % x0023 - 0027 / % x002A-%x003A / % x003C-%x005D / % x005F-%x007E / % x0080 - D7FF / % xE000 - 10FFFF q - char = t - char / ws - char / % x0028 / % x0029 / % x003B ws - char = % x0020 / % x0009 / % x000A / % x000B / % x000C / % x000D c - char = % x0009 / % x000B / % x000C / % x0020 - D7FF / % xE000 - 10FFFF v } A few additional constraints not expressed by the grammar : { ul { - [ unum ] once interpreted as an hexadecimal number must be a { { : /#unicode_scalar_value}Unicode scalar value . } } { - A comment can be ended by the end of the character sequence rather than [ nl ] . } } An s-expression {e dictionary} is a list of bindings. A {e binding} is a list that starts with a {e key} and the remaining elements of the list are the binding's {e value}. For example in this binding: {v (key v0 v1 ...) v} The key is [key] and the value the possibly empty list [v0], [v1], ... of s-expressions. The {{!Sexpq.qdict}API} for dictionaries represents the value by a fake (doesn't exist syntactically) s-expression list whose text location starts at the first element of the value. {1:sexp_path_caret Path & caret syntax} Path and carets provide a way for end users to address s-expressions and edit locations. A {e path} is a sequence of {{!sexp_dict}key} and list indexing operations. Applying the path to an s-expression leads to an s-expression or nothing if one of the indices does not exist, or an error if ones tries to index an atom. A {e caret} is a path and a spatial specification for the s-expression found by the path. The caret indicates either the void before that expression, the expression itself (over caret) or the void after it. Here are a few examples of paths and carets, syntactically the charater ['v'] is used to denote the caret's insertion point before or after a path. There's no distinction between a path an over caret. {v Ocaml.libs # value of key 'libs' of dictionary 'ocaml' ocaml.v[libs] # before the key binding (if any) ocaml.[libs]v # after the key binding (if any) ocaml.libs.[0] # first element of key 'libs' of dictionary 'ocaml' ocaml.libs.v[0] # before first element (if any) ocaml.libs.[0]v # after first element (if any) ocaml.libs.[-1] # last element of key 'libs' of dictionary 'ocaml' ocaml.libs.v[-1] # before last element (if any) ocaml.libs.[-1]v # after last element (if any) v} More formally a {e path} is a [.] seperated list of indices. An {e index} is written [[i]]. [i] can a zero-based list index with negative indices counting from the end of the list ([-1] is the last element). Or [i] can be a dictionary key [key]. If there is no ambiguity, the surrounding brackets can be dropped. A caret is a path whose last index brackets can be prefixed or suffixed by an insertion point, represented by the character ['v']. This respectively denote the void before or after the s-expression found by the path. {b Note.} The syntax has no form of quoting at the moment this means key names can't contain, [\[], [\]], or start with a number. {1:sexp_syntax S-expression syntax} S-expressions are a general way of describing data via atoms (sequences of characters) and lists delimited by parentheses. Here are a few examples of s-expressions and their syntax: {v this-is-an_atom (this is a list of seven atoms) (this list contains (a nested) list) ; This is a comment ; Anything that follows a semi-colon is ignored until the next line (this list ; has three atoms and an embeded () comment) "this is a quoted atom, it can contain spaces ; and ()" "quoted atoms can be split ^ across lines or contain Unicode esc^u{0061}pes" v} We define the syntax of s-expressions over a sequence of {{:/#unicode_scalar_value}Unicode characters} in which all US-ASCII control characters (U+0000..U+001F and U+007F) except {{!whitespace}whitespace} are forbidden in unescaped form. {2:sexp S-expressions} An {e s-expression} is either an {{!atoms}{e atom}} or a {{!lists}{e list}} of s-expressions interspaced with {{!whitespace}{e whitespace}} and {{!comments}{e comments}}. A {e sequence of s-expressions} is a succession of s-expressions interspaced with whitespace and comments. These elements are informally described below and finally made precise via an ABNF {{!grammar}grammar}. {2:whitespace Whitespace} Whitespace is a sequence of whitespace characters, namely, space [' '] (U+0020), tab ['\t'] (U+0009), line feed ['\n'] (U+000A), vertical tab ['\t'] (U+000B), form feed (U+000C) and carriage return ['\r'] (U+000D). {2:comments Comments} Unless it occurs inside an atom in quoted form (see below) anything that follows a semicolon [';'] (U+003B) is ignored until the next {e end of line}, that is either a line feed ['\n'] (U+000A), a carriage return ['\r'] (U+000D) or a carriage return and a line feed ["\r\n"] (<U+000D,U+000A>). {v (this is not a comment) ; This is a comment (this is not a comment) v} {2:atoms Atoms} An atom represents ground data as a string of Unicode characters. It can, via escapes, represent any sequence of Unicode characters, including control characters and U+0000. It cannot represent an arbitrary byte sequence except via a client-defined encoding convention (e.g. Base64 or hex encoding). Atoms can be specified either via an unquoted or a quoted form. In unquoted form the atom is written without delimiters. In quoted form the atom is delimited by double quote ['"'] (U+0022) characters, it is mandatory for atoms that contain {{!whitespace}whitespace}, parentheses ['('] [')'], semicolons [';'], quotes ['"'], carets ['^'] or characters that need to be escaped. {v abc ; a token for the atom "abc" "abc" ; a quoted token for the atom "abc" "abc; (d" ; a quoted token for the atom "abc; (d" "" ; the quoted token for the atom "" v} For atoms that do not need to be quoted, both their unquoted and quoted form represent the same string; e.g. the string ["true"] can be represented both by the atoms {e true} and {e "true"}. The empty string can only be represented in quoted form by {e ""}. In quoted form escapes are introduced by a caret ['^']. Double quotes ['"'] and carets ['^'] must always be escaped. {v "^^" ; atom for ^ "^n" ; atom for line feed U+000A "^u{0000}" ; atom for U+0000 "^"^u{1F42B}^"" ; atom with a quote, U+1F42B and a quote v} The following escape sequences are recognized: {ul {- ["^ "] (<U+005E,U+0020>) for space [' '] (U+0020)} {- ["^\""] (<U+005E,U+0022>) for double quote ['"'] (U+0022) {b mandatory}} {- ["^^"] (<U+005E,U+005E>) for caret ['^'] (U+005E) {b mandatory}} {- ["^n"] (<U+005E,U+006E>) for line feed ['\n'] (U+000A)} {- ["^r"] (<U+005E,U+0072>) for carriage return ['\r'] (U+000D)} {- ["^u{X}"] with [X] is from 1 to at most 6 upper or lower case hexadecimal digits standing for the corresponding {{:/#unicode_scalar_value}Unicode character} U+X.} {- Any other character except line feed ['\n'] (U+000A) or carriage return ['\r'] (U+000D), following a caret is an illegal sequence of characters. In the two former cases the atom continues on the next line and white space is ignored.}} An atom in quoted form can be split across lines by using a caret ['^'] (U+005E) followed by a line feed ['\n'] (U+000A) or a carriage return ['\r'] (U+000D); any subsequent {{!whitespace}whitespace} is ignored. {v "^ a^ ^ " ; the atom "a " v} The character ^ (U+005E) is used as an escape character rather than the usual \ (U+005C) in order to make quoted Windows® file paths decently readable and, not the least, utterly please DKM. {2:lists Lists} Lists are delimited by left ['('] (U+0028) and right [')'] (U+0029) parentheses. Their elements are s-expressions separated by optional {{!whitespace}whitespace} and {{!comments}comments}. For example: {v (a list (of four) expressions) (a list(of four)expressions) ("a"list("of"four)expressions) (a list (of ; This is a comment four) expressions) () ; the empty list v} {2:grammar Formal grammar} The following {{:}RFC 5234} ABNF grammar is defined on a sequence of {{:/#unicode_scalar_value}Unicode characters}. {v sexp-seq = *(ws / comment / sexp) sexp = atom / list list = %x0028 sexp-seq %x0029 atom = token / qtoken token = t-char *(t-char) qtoken = %x0022 *(q-char / escape / cont) %x0022 escape = %x005E (%x0020 / %x0022 / %x005E / %x006E / %x0072 / %x0075 %x007B unum %x007D) unum = 1*6(HEXDIG) cont = %x005E nl ws ws = *(ws-char) comment = %x003B *(c-char) nl nl = %x000A / %x000D / %x000D %x000A t-char = %x0021 / %x0023-0027 / %x002A-%x003A / %x003C-%x005D / %x005F-%x007E / %x0080-D7FF / %xE000-10FFFF q-char = t-char / ws-char / %x0028 / %x0029 / %x003B ws-char = %x0020 / %x0009 / %x000A / %x000B / %x000C / %x000D c-char = %x0009 / %x000B / %x000C / %x0020-D7FF / %xE000-10FFFF v} A few additional constraints not expressed by the grammar: {ul {- [unum] once interpreted as an hexadecimal number must be a {{:/#unicode_scalar_value}Unicode scalar value.}} {- A comment can be ended by the end of the character sequence rather than [nl]. }} *) --------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
99550644df50e98c1f69c5cb98af2574f5778a6b042bcbb3c7f2148232aed0b8
eryx67/vk-api-example
Store.hs
{-# LANGUAGE OverloadedStrings, RecordWildCards, TypeFamilies #-} {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # -- | module VK.App.Widgets.AudioPlayer.Store where import Control.Concurrent import Control.Error.Util import Control.Monad (void, liftM, unless) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe import Data.Fraction import Data.Maybe (fromMaybe, isNothing) import qualified Data.Text as T import Data.Typeable (Typeable) #ifdef __GHCJS__ import Data.JSString.Text import GHCJS.Foreign.Callback import GHCJS.Marshal import GHCJS.Types #endif import React.Flux import VK.App.Internal.Orphans () import VK.App.Internal.Utils import VK.App.Widgets.AudioPlayer.Actions import VK.App.Widgets.AudioPlayer.Types import VK.App.Internal.TypePlugs -- import Debug.Trace data VolumeBar = VolumeBar { isTogglePressed :: !Bool } deriving (Show, Typeable) data Howler = Howler { howlerRef :: !JSVal , howlerInitCb :: !(Maybe (Callback (IO ()))) , howlerPlayEndCb :: !(Maybe (Callback (IO ()))) } instance Show Howler where show _ = "Howler" data State = State { isPlaying :: !Bool , isPause :: !Bool , isLoading :: !Bool , isSongListVisible :: !Bool , isVolumeBarVisible :: !Bool , playerSeek :: !Int , playerDuration :: !(Maybe Int) , playerVolume :: !Fraction , currentSongIndex :: !(Maybe Int) , playerSongs :: ![Song] , volumeBar :: !VolumeBar , howler :: !Howler , howlerCurrentSrc :: !(Maybe T.Text) , updateInterval :: !(Maybe ThreadId) } deriving (Show, Typeable) instance StoreData State where type StoreAction State = Action State transform action st@State{..} = do case action of SetSongs songs -> return st{playerSongs = songs , currentSongIndex = case songs of [] -> Nothing _ -> Just 0 } InitSoundObject -> do mst <- runMaybeT $ do lift . void $ clearSoundObject howler cidx <- hoistMaybe currentSongIndex hwlr <- lift $ newHowler st cidx return st{howler = hwlr, isLoading = True} return $ fromMaybe st mst InitSoundObjectCompleted -> do drn <- howlerDuration howler hwlrSrc <- howlerSrc howler return st{playerDuration = drn, isLoading = False, howlerCurrentSrc = hwlrSrc} ClearSoundObject -> do hwlr <- clearSoundObject howler return st{howler = hwlr, howlerCurrentSrc = Nothing, playerDuration = Nothing} Play -> return st{ isPlaying = True, isPause = False} PlayContinue -> do howlerPlay howler ival <- updateCurrentDuration 1000000 return st{updateInterval = Just ival} PlayEnd -> return st Stop -> do return st{playerSeek = 0, isPlaying = False} Unmounted -> return st Pause -> do howlerPause howler return st{isPause = True} UpdateDuration -> do seek <- howlerCurrentPos howler return st{playerSeek = seek} StopUpdateDuration -> do stopUpdateCurrentDuration st Prev -> return st Next -> return st UpdateSongIndex idx -> return st{currentSongIndex = Just idx, playerDuration = Just 0} SongItemClick _ -> return st SeekTo pos -> seekTo pos AdjustVolume vol -> adjustVolume vol ShowVolumeBar -> return st{isVolumeBarVisible = True} HideVolumeBar -> return st{isVolumeBarVisible = False} ShowSongList -> return st{isSongListVisible = True} HideSongList -> return st{isSongListVisible = False} where seekTo fraction = do let seek = maybe 0 (\v -> truncate $ fromIntegral v * toFactor fraction) playerDuration howlerSeek howler $ fromIntegral seek return st{playerSeek = seek} adjustVolume vol = do howlerVolume howler $ toFactor vol return st{playerVolume = vol} setSongs :: [Song] -> IO () setSongs = execPlayerAction . SetSongs store :: ReactStore State store = mkStore State { isPlaying = False , isPause = False , isLoading = False , isSongListVisible = False , isVolumeBarVisible = False , playerSeek = 0 , playerDuration = Nothing , playerVolume = fromFactor (0.5::Double) , currentSongIndex = Nothing , playerSongs = [] , volumeBar = VolumeBar False , howler = Howler nullRef Nothing Nothing , howlerCurrentSrc = Nothing , updateInterval = Nothing } execPlayerAction :: Action State -> IO () execPlayerAction action = do st <- getStoreData store execAction (dispatch st) action dispatch :: State -> Action State -> [SomeStoreAction] dispatch State{..} action = map (SomeStoreAction store) $ doRoute action where doRoute a@(SetSongs _) = a:doRoute Unmounted doRoute a@Unmounted = [Stop, StopUpdateDuration, ClearSoundObject, a] doRoute a@InitSoundObjectCompleted | isLoading = [a, StopUpdateDuration, PlayContinue] | otherwise = [] doRoute _ | isLoading = [] doRoute Play | isPlaying && not isPause = [] | isNull $ howlerRef howler = [InitSoundObject, Play] | isNothing currentSongIndex || (Just . songUrl $ playerSongs !! fromMaybe 0 currentSongIndex) /= howlerCurrentSrc = [InitSoundObject, Play] | otherwise = Play:doRoute PlayContinue doRoute Pause | isPause = doRoute PlayContinue | otherwise = Pause:doRoute StopUpdateDuration doRoute a@PlayEnd | currentSongIndex == (Just $ length playerSongs - 1) = a:doRoute Stop | otherwise = a:doRoute Next doRoute a@Stop = a:doRoute StopUpdateDuration doRoute a@PlayContinue = doRoute StopUpdateDuration ++ [a] doRoute Next = case currentSongIndex of Just cidx -> doRoute $ UpdateSongIndex $ cidx + 1 Nothing -> [] doRoute Prev | playerSeek > 5 || currentSongIndex == Just 0 = doRoute . SeekTo $ (fromFactor (0::Double)) | otherwise = case currentSongIndex of Just cidx -> doRoute . UpdateSongIndex $ max 0 (cidx - 1) Nothing -> [] doRoute a@(UpdateSongIndex _) | isPlaying = a:HideSongList:concatMap doRoute [Stop, ClearSoundObject] ++ [InitSoundObject, Play] | otherwise = a:HideSongList:concatMap doRoute [Stop, ClearSoundObject] doRoute (SongItemClick idx) | currentSongIndex == Just idx && isPause = HideSongList:doRoute Pause | currentSongIndex == Just idx && not isPause = HideSongList:doRoute Play | otherwise = doRoute (UpdateSongIndex idx) doRoute a = [a] clearSoundObject :: Howler -> IO Howler clearSoundObject howler = do howlerStop howler destroyHowler howler return $ Howler nullRef Nothing Nothing stopUpdateCurrentDuration :: State -> IO State stopUpdateCurrentDuration st@State{..} = case updateInterval of Nothing -> return st Just tid -> do killThread tid return st{updateInterval = Nothing} updateCurrentDuration :: Int -> IO ThreadId updateCurrentDuration ival = forkIO doUpdate where doUpdate = do threadDelay ival execPlayerAction UpdateDuration doUpdate newHowler :: State -> Int -> IO Howler newHowler State{..} idx = do initCb <- asyncCallback $ execPlayerAction InitSoundObjectCompleted playendCb <- asyncCallback $ execPlayerAction PlayEnd let Song{..} = playerSongs !! idx vol <- toJSVal_aeson $ toFactor playerVolume urls <- toJSValListOf $ [textToJSString songUrl] autoplay <- toJSVal_aeson False args <- createObj mapM_ (\(k, v) -> setObjProp k v args) [("urls", urls) , ("volume", vol) , ("autoplay", autoplay) , ("onload", jsval initCb) , ("onend", jsval playendCb) ] howlerRef <- js_NewHowl (jsval args) return $ Howler howlerRef (Just initCb) (Just playendCb) destroyHowler :: Howler -> IO () destroyHowler Howler{..} = do unless (isNull howlerRef) $ do maybe (return ()) releaseCallback howlerInitCb maybe (return ()) releaseCallback howlerPlayEndCb howlerDuration :: Howler -> IO (Maybe Int) howlerDuration Howler{..} = if isNull howlerRef then return Nothing else liftM Just $ js_howlerDuration howlerRef howlerPlay :: Howler -> IO () howlerPlay Howler{..} = unless (isNull howlerRef) $ js_howlerPlay howlerRef howlerStop :: Howler -> IO () howlerStop Howler{..} = unless (isNull howlerRef) $ js_howlerStop howlerRef howlerPause :: Howler -> IO () howlerPause Howler{..} = unless (isNull howlerRef) $ js_howlerPause howlerRef howlerSeek :: Howler -> Double -> IO () howlerSeek Howler{..} v = unless (isNull howlerRef) $ js_howlerSeek howlerRef v howlerCurrentPos :: Howler -> IO Int howlerCurrentPos Howler{..} = if isNull howlerRef then return 0 else do pos <- js_howlerPosition howlerRef return . truncate $ pos howlerVolume :: Howler -> Double -> IO () howlerVolume Howler{..} v = unless (isNull howlerRef) $ js_howlerVolume howlerRef v howlerSrc :: Howler -> IO (Maybe T.Text) howlerSrc Howler{..} = if isNull howlerRef then return Nothing else do jstr <- js_howlerSrc howlerRef return . Just $ textFromJSString jstr #ifdef __GHCJS__ foreign import javascript unsafe "(function () {return new Howl($1);})()" js_NewHowl :: JSVal -> IO JSVal foreign import javascript unsafe "($1)._duration" js_howlerDuration :: JSVal -> IO Int foreign import javascript unsafe "($1).play()" js_howlerPlay :: JSVal -> IO () foreign import javascript unsafe "($1).stop()" js_howlerStop :: JSVal -> IO () foreign import javascript unsafe "($1).pause()" js_howlerPause :: JSVal -> IO () foreign import javascript unsafe "($1).pos($2)" js_howlerSeek :: JSVal -> Double -> IO () foreign import javascript unsafe "($1).pos()" js_howlerPosition :: JSVal -> IO Double foreign import javascript unsafe "($1).volume($2)" js_howlerVolume :: JSVal -> Double -> IO () foreign import javascript unsafe "($1)._src" js_howlerSrc :: JSVal -> IO JSString #else js_NewHowl :: JSVal -> IO JSVal js_NewHowl _ = return () js_howlerDuration :: JSVal -> IO Int js_howlerDuration _ = return 0 js_howlerPlay :: JSVal -> IO () js_howlerPlay _ = return () js_howlerStop :: JSVal -> IO () js_howlerStop _ = return () js_howlerPause :: JSVal -> IO () js_howlerPause _ = return () js_howlerSeek :: JSVal -> Double -> IO () js_howlerSeek _ _ = return () js_howlerPosition :: JSVal -> IO Double js_howlerPosition _ = return 0 js_howlerVolume :: JSVal -> Double -> IO () js_howlerVolume _ _ = return () js_howlerSrc :: JSVal -> IO JSString js_howlerSrc _ = return "" #endif
null
https://raw.githubusercontent.com/eryx67/vk-api-example/4ce634e2f72cf0ab6ef3b80387ad489de9d8c0ee/src/VK/App/Widgets/AudioPlayer/Store.hs
haskell
# LANGUAGE OverloadedStrings, RecordWildCards, TypeFamilies # # LANGUAGE DeriveAnyClass # | import Debug.Trace
# LANGUAGE DeriveGeneric # module VK.App.Widgets.AudioPlayer.Store where import Control.Concurrent import Control.Error.Util import Control.Monad (void, liftM, unless) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe import Data.Fraction import Data.Maybe (fromMaybe, isNothing) import qualified Data.Text as T import Data.Typeable (Typeable) #ifdef __GHCJS__ import Data.JSString.Text import GHCJS.Foreign.Callback import GHCJS.Marshal import GHCJS.Types #endif import React.Flux import VK.App.Internal.Orphans () import VK.App.Internal.Utils import VK.App.Widgets.AudioPlayer.Actions import VK.App.Widgets.AudioPlayer.Types import VK.App.Internal.TypePlugs data VolumeBar = VolumeBar { isTogglePressed :: !Bool } deriving (Show, Typeable) data Howler = Howler { howlerRef :: !JSVal , howlerInitCb :: !(Maybe (Callback (IO ()))) , howlerPlayEndCb :: !(Maybe (Callback (IO ()))) } instance Show Howler where show _ = "Howler" data State = State { isPlaying :: !Bool , isPause :: !Bool , isLoading :: !Bool , isSongListVisible :: !Bool , isVolumeBarVisible :: !Bool , playerSeek :: !Int , playerDuration :: !(Maybe Int) , playerVolume :: !Fraction , currentSongIndex :: !(Maybe Int) , playerSongs :: ![Song] , volumeBar :: !VolumeBar , howler :: !Howler , howlerCurrentSrc :: !(Maybe T.Text) , updateInterval :: !(Maybe ThreadId) } deriving (Show, Typeable) instance StoreData State where type StoreAction State = Action State transform action st@State{..} = do case action of SetSongs songs -> return st{playerSongs = songs , currentSongIndex = case songs of [] -> Nothing _ -> Just 0 } InitSoundObject -> do mst <- runMaybeT $ do lift . void $ clearSoundObject howler cidx <- hoistMaybe currentSongIndex hwlr <- lift $ newHowler st cidx return st{howler = hwlr, isLoading = True} return $ fromMaybe st mst InitSoundObjectCompleted -> do drn <- howlerDuration howler hwlrSrc <- howlerSrc howler return st{playerDuration = drn, isLoading = False, howlerCurrentSrc = hwlrSrc} ClearSoundObject -> do hwlr <- clearSoundObject howler return st{howler = hwlr, howlerCurrentSrc = Nothing, playerDuration = Nothing} Play -> return st{ isPlaying = True, isPause = False} PlayContinue -> do howlerPlay howler ival <- updateCurrentDuration 1000000 return st{updateInterval = Just ival} PlayEnd -> return st Stop -> do return st{playerSeek = 0, isPlaying = False} Unmounted -> return st Pause -> do howlerPause howler return st{isPause = True} UpdateDuration -> do seek <- howlerCurrentPos howler return st{playerSeek = seek} StopUpdateDuration -> do stopUpdateCurrentDuration st Prev -> return st Next -> return st UpdateSongIndex idx -> return st{currentSongIndex = Just idx, playerDuration = Just 0} SongItemClick _ -> return st SeekTo pos -> seekTo pos AdjustVolume vol -> adjustVolume vol ShowVolumeBar -> return st{isVolumeBarVisible = True} HideVolumeBar -> return st{isVolumeBarVisible = False} ShowSongList -> return st{isSongListVisible = True} HideSongList -> return st{isSongListVisible = False} where seekTo fraction = do let seek = maybe 0 (\v -> truncate $ fromIntegral v * toFactor fraction) playerDuration howlerSeek howler $ fromIntegral seek return st{playerSeek = seek} adjustVolume vol = do howlerVolume howler $ toFactor vol return st{playerVolume = vol} setSongs :: [Song] -> IO () setSongs = execPlayerAction . SetSongs store :: ReactStore State store = mkStore State { isPlaying = False , isPause = False , isLoading = False , isSongListVisible = False , isVolumeBarVisible = False , playerSeek = 0 , playerDuration = Nothing , playerVolume = fromFactor (0.5::Double) , currentSongIndex = Nothing , playerSongs = [] , volumeBar = VolumeBar False , howler = Howler nullRef Nothing Nothing , howlerCurrentSrc = Nothing , updateInterval = Nothing } execPlayerAction :: Action State -> IO () execPlayerAction action = do st <- getStoreData store execAction (dispatch st) action dispatch :: State -> Action State -> [SomeStoreAction] dispatch State{..} action = map (SomeStoreAction store) $ doRoute action where doRoute a@(SetSongs _) = a:doRoute Unmounted doRoute a@Unmounted = [Stop, StopUpdateDuration, ClearSoundObject, a] doRoute a@InitSoundObjectCompleted | isLoading = [a, StopUpdateDuration, PlayContinue] | otherwise = [] doRoute _ | isLoading = [] doRoute Play | isPlaying && not isPause = [] | isNull $ howlerRef howler = [InitSoundObject, Play] | isNothing currentSongIndex || (Just . songUrl $ playerSongs !! fromMaybe 0 currentSongIndex) /= howlerCurrentSrc = [InitSoundObject, Play] | otherwise = Play:doRoute PlayContinue doRoute Pause | isPause = doRoute PlayContinue | otherwise = Pause:doRoute StopUpdateDuration doRoute a@PlayEnd | currentSongIndex == (Just $ length playerSongs - 1) = a:doRoute Stop | otherwise = a:doRoute Next doRoute a@Stop = a:doRoute StopUpdateDuration doRoute a@PlayContinue = doRoute StopUpdateDuration ++ [a] doRoute Next = case currentSongIndex of Just cidx -> doRoute $ UpdateSongIndex $ cidx + 1 Nothing -> [] doRoute Prev | playerSeek > 5 || currentSongIndex == Just 0 = doRoute . SeekTo $ (fromFactor (0::Double)) | otherwise = case currentSongIndex of Just cidx -> doRoute . UpdateSongIndex $ max 0 (cidx - 1) Nothing -> [] doRoute a@(UpdateSongIndex _) | isPlaying = a:HideSongList:concatMap doRoute [Stop, ClearSoundObject] ++ [InitSoundObject, Play] | otherwise = a:HideSongList:concatMap doRoute [Stop, ClearSoundObject] doRoute (SongItemClick idx) | currentSongIndex == Just idx && isPause = HideSongList:doRoute Pause | currentSongIndex == Just idx && not isPause = HideSongList:doRoute Play | otherwise = doRoute (UpdateSongIndex idx) doRoute a = [a] clearSoundObject :: Howler -> IO Howler clearSoundObject howler = do howlerStop howler destroyHowler howler return $ Howler nullRef Nothing Nothing stopUpdateCurrentDuration :: State -> IO State stopUpdateCurrentDuration st@State{..} = case updateInterval of Nothing -> return st Just tid -> do killThread tid return st{updateInterval = Nothing} updateCurrentDuration :: Int -> IO ThreadId updateCurrentDuration ival = forkIO doUpdate where doUpdate = do threadDelay ival execPlayerAction UpdateDuration doUpdate newHowler :: State -> Int -> IO Howler newHowler State{..} idx = do initCb <- asyncCallback $ execPlayerAction InitSoundObjectCompleted playendCb <- asyncCallback $ execPlayerAction PlayEnd let Song{..} = playerSongs !! idx vol <- toJSVal_aeson $ toFactor playerVolume urls <- toJSValListOf $ [textToJSString songUrl] autoplay <- toJSVal_aeson False args <- createObj mapM_ (\(k, v) -> setObjProp k v args) [("urls", urls) , ("volume", vol) , ("autoplay", autoplay) , ("onload", jsval initCb) , ("onend", jsval playendCb) ] howlerRef <- js_NewHowl (jsval args) return $ Howler howlerRef (Just initCb) (Just playendCb) destroyHowler :: Howler -> IO () destroyHowler Howler{..} = do unless (isNull howlerRef) $ do maybe (return ()) releaseCallback howlerInitCb maybe (return ()) releaseCallback howlerPlayEndCb howlerDuration :: Howler -> IO (Maybe Int) howlerDuration Howler{..} = if isNull howlerRef then return Nothing else liftM Just $ js_howlerDuration howlerRef howlerPlay :: Howler -> IO () howlerPlay Howler{..} = unless (isNull howlerRef) $ js_howlerPlay howlerRef howlerStop :: Howler -> IO () howlerStop Howler{..} = unless (isNull howlerRef) $ js_howlerStop howlerRef howlerPause :: Howler -> IO () howlerPause Howler{..} = unless (isNull howlerRef) $ js_howlerPause howlerRef howlerSeek :: Howler -> Double -> IO () howlerSeek Howler{..} v = unless (isNull howlerRef) $ js_howlerSeek howlerRef v howlerCurrentPos :: Howler -> IO Int howlerCurrentPos Howler{..} = if isNull howlerRef then return 0 else do pos <- js_howlerPosition howlerRef return . truncate $ pos howlerVolume :: Howler -> Double -> IO () howlerVolume Howler{..} v = unless (isNull howlerRef) $ js_howlerVolume howlerRef v howlerSrc :: Howler -> IO (Maybe T.Text) howlerSrc Howler{..} = if isNull howlerRef then return Nothing else do jstr <- js_howlerSrc howlerRef return . Just $ textFromJSString jstr #ifdef __GHCJS__ foreign import javascript unsafe "(function () {return new Howl($1);})()" js_NewHowl :: JSVal -> IO JSVal foreign import javascript unsafe "($1)._duration" js_howlerDuration :: JSVal -> IO Int foreign import javascript unsafe "($1).play()" js_howlerPlay :: JSVal -> IO () foreign import javascript unsafe "($1).stop()" js_howlerStop :: JSVal -> IO () foreign import javascript unsafe "($1).pause()" js_howlerPause :: JSVal -> IO () foreign import javascript unsafe "($1).pos($2)" js_howlerSeek :: JSVal -> Double -> IO () foreign import javascript unsafe "($1).pos()" js_howlerPosition :: JSVal -> IO Double foreign import javascript unsafe "($1).volume($2)" js_howlerVolume :: JSVal -> Double -> IO () foreign import javascript unsafe "($1)._src" js_howlerSrc :: JSVal -> IO JSString #else js_NewHowl :: JSVal -> IO JSVal js_NewHowl _ = return () js_howlerDuration :: JSVal -> IO Int js_howlerDuration _ = return 0 js_howlerPlay :: JSVal -> IO () js_howlerPlay _ = return () js_howlerStop :: JSVal -> IO () js_howlerStop _ = return () js_howlerPause :: JSVal -> IO () js_howlerPause _ = return () js_howlerSeek :: JSVal -> Double -> IO () js_howlerSeek _ _ = return () js_howlerPosition :: JSVal -> IO Double js_howlerPosition _ = return 0 js_howlerVolume :: JSVal -> Double -> IO () js_howlerVolume _ _ = return () js_howlerSrc :: JSVal -> IO JSString js_howlerSrc _ = return "" #endif
83a3e847f5cd3397ea64730fa8953bab6140361dff25ac1dbfe3030f895ae9d4
sdiehl/elliptic-curve
Curve41417.hs
module Data.Curve.Edwards.Curve41417 ( module Data.Curve.Edwards , Point(..) * curve , module Data.Curve.Edwards.Curve41417 ) where import Protolude import Data.Field.Galois import GHC.Natural (Natural) import Data.Curve.Edwards ------------------------------------------------------------------------------- -- Types ------------------------------------------------------------------------------- -- | Curve41417 curve. data Curve41417 | Field of points of curve . type Fq = Prime Q type Q = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef | Field of coefficients of curve . type Fr = Prime R type R = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffeb3cc92414cf706022b36f1c0338ad63cf181b0e71a5e106af79 Curve41417 curve is an curve . instance Curve 'Edwards c Curve41417 Fq Fr => ECurve c Curve41417 Fq Fr where a_ = const _a {-# INLINABLE a_ #-} d_ = const _d {-# INLINABLE d_ #-} h_ = const _h {-# INLINABLE h_ #-} q_ = const _q # INLINABLE q _ # r_ = const _r # INLINABLE r _ # -- | Affine Curve41417 curve point. type PA = EAPoint Curve41417 Fq Fr Affine Curve41417 curve is an Edwards affine curve . instance EACurve Curve41417 Fq Fr where gA_ = gA # INLINABLE gA _ # -- | Projective Curve41417 point. type PP = EPPoint Curve41417 Fq Fr Projective Curve41417 curve is an projective curve . instance EPCurve Curve41417 Fq Fr where gP_ = gP # INLINABLE gP _ # ------------------------------------------------------------------------------- -- Parameters ------------------------------------------------------------------------------- | Coefficient @A@ of curve . _a :: Fq _a = 0x1 # INLINABLE _ a # | Coefficient @D@ of curve . _d :: Fq _d = 0xe21 {-# INLINABLE _d #-} | Cofactor of curve . _h :: Natural _h = 0x8 # INLINABLE _ h # | Characteristic of curve . _q :: Natural _q = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef {-# INLINABLE _q #-} | Order of curve . _r :: Natural _r = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffeb3cc92414cf706022b36f1c0338ad63cf181b0e71a5e106af79 {-# INLINABLE _r #-} | Coordinate @X@ of curve . _x :: Fq _x = 0x1a334905141443300218c0631c326e5fcd46369f44c03ec7f57ff35498a4ab4d6d6ba111301a73faa8537c64c4fd3812f3cbc595 {-# INLINABLE _x #-} | Coordinate @Y@ of curve . _y :: Fq _y = 0x22 {-# INLINABLE _y #-} | Generator of affine curve . gA :: PA gA = A _x _y # INLINABLE gA # | Generator of projective curve . gP :: PP gP = P _x _y 1 # INLINABLE gP #
null
https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Edwards/Curve41417.hs
haskell
----------------------------------------------------------------------------- Types ----------------------------------------------------------------------------- | Curve41417 curve. # INLINABLE a_ # # INLINABLE d_ # # INLINABLE h_ # | Affine Curve41417 curve point. | Projective Curve41417 point. ----------------------------------------------------------------------------- Parameters ----------------------------------------------------------------------------- # INLINABLE _d # # INLINABLE _q # # INLINABLE _r # # INLINABLE _x # # INLINABLE _y #
module Data.Curve.Edwards.Curve41417 ( module Data.Curve.Edwards , Point(..) * curve , module Data.Curve.Edwards.Curve41417 ) where import Protolude import Data.Field.Galois import GHC.Natural (Natural) import Data.Curve.Edwards data Curve41417 | Field of points of curve . type Fq = Prime Q type Q = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef | Field of coefficients of curve . type Fr = Prime R type R = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffeb3cc92414cf706022b36f1c0338ad63cf181b0e71a5e106af79 Curve41417 curve is an curve . instance Curve 'Edwards c Curve41417 Fq Fr => ECurve c Curve41417 Fq Fr where a_ = const _a d_ = const _d h_ = const _h q_ = const _q # INLINABLE q _ # r_ = const _r # INLINABLE r _ # type PA = EAPoint Curve41417 Fq Fr Affine Curve41417 curve is an Edwards affine curve . instance EACurve Curve41417 Fq Fr where gA_ = gA # INLINABLE gA _ # type PP = EPPoint Curve41417 Fq Fr Projective Curve41417 curve is an projective curve . instance EPCurve Curve41417 Fq Fr where gP_ = gP # INLINABLE gP _ # | Coefficient @A@ of curve . _a :: Fq _a = 0x1 # INLINABLE _ a # | Coefficient @D@ of curve . _d :: Fq _d = 0xe21 | Cofactor of curve . _h :: Natural _h = 0x8 # INLINABLE _ h # | Characteristic of curve . _q :: Natural _q = 0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef | Order of curve . _r :: Natural _r = 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffeb3cc92414cf706022b36f1c0338ad63cf181b0e71a5e106af79 | Coordinate @X@ of curve . _x :: Fq _x = 0x1a334905141443300218c0631c326e5fcd46369f44c03ec7f57ff35498a4ab4d6d6ba111301a73faa8537c64c4fd3812f3cbc595 | Coordinate @Y@ of curve . _y :: Fq _y = 0x22 | Generator of affine curve . gA :: PA gA = A _x _y # INLINABLE gA # | Generator of projective curve . gP :: PP gP = P _x _y 1 # INLINABLE gP #
0a4352c0beb3a08e2f322363eb85ab3e1e5a2b2d233e1dd69de1e9bf9effb2fe
acorrenson/modulus
modulus.ml
open Modulus_lib.Loop let () = if Array.length Sys.argv > 1 then if Sys.argv.(1) = "-i" then ignore (repl ()) else ignore (batch Sys.argv.(1)) else begin Printf.eprintf "usage: %s ( -i | <file> )\n" Sys.argv.(0); flush stderr; exit 1 end
null
https://raw.githubusercontent.com/acorrenson/modulus/5a5de3b5a68d320adfe1848c05668a2da7024532/bin/modulus.ml
ocaml
open Modulus_lib.Loop let () = if Array.length Sys.argv > 1 then if Sys.argv.(1) = "-i" then ignore (repl ()) else ignore (batch Sys.argv.(1)) else begin Printf.eprintf "usage: %s ( -i | <file> )\n" Sys.argv.(0); flush stderr; exit 1 end
02cf4731cebad27df2a37c125622ef82c867e5e3ffab194dc86fcb82681b004f
open-company/open-company-auth
email_auth.clj
(ns oc.auth.representations.email-auth "Resource representation functions for email authentication." (:require [oc.lib.hateoas :as hateoas] [oc.lib.jwt :as jwt] [oc.auth.representations.media-types :as mt])) (def auth-link (hateoas/link-map "authenticate" hateoas/GET "/users/auth" {:accept jwt/media-type} {:auth-source "email" :authentication "basic"})) (def create-link (hateoas/create-link "/users/" {:accept jwt/media-type :content-type mt/user-media-type} {:auth-source "email"})) (def reset-link (hateoas/link-map "reset" hateoas/POST "/users/reset" {:content-type "text/x-email"} {:auth-source "email"})) (def auth-settings [auth-link create-link reset-link])
null
https://raw.githubusercontent.com/open-company/open-company-auth/79275bd3b877e70048a80960d7fa2d14be0abfe9/src/oc/auth/representations/email_auth.clj
clojure
(ns oc.auth.representations.email-auth "Resource representation functions for email authentication." (:require [oc.lib.hateoas :as hateoas] [oc.lib.jwt :as jwt] [oc.auth.representations.media-types :as mt])) (def auth-link (hateoas/link-map "authenticate" hateoas/GET "/users/auth" {:accept jwt/media-type} {:auth-source "email" :authentication "basic"})) (def create-link (hateoas/create-link "/users/" {:accept jwt/media-type :content-type mt/user-media-type} {:auth-source "email"})) (def reset-link (hateoas/link-map "reset" hateoas/POST "/users/reset" {:content-type "text/x-email"} {:auth-source "email"})) (def auth-settings [auth-link create-link reset-link])
77f09d4302355c7692f379d453c04a801479017145c31906992b1537d35253e7
runeanielsen/typesense-clj
api.clj
(ns typesense.api (:require [typesense.util :as util] [clojure.data.json :as json])) (def ^:private api-key-header-name "X-TYPESENSE-API-KEY") (defn- collection-uri "Returns the full collection uri resource path." ([uri] (str uri "/collections")) ([uri collection-name] (str (collection-uri uri) "/" collection-name))) (defn- document-uri "Returns the full document uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/documents")) ([uri collection-name id] (str (document-uri uri collection-name) "/" id))) (defn- keys-uri "Return the full keys uri resource path." ([uri] (str uri "/keys")) ([uri id] (str (keys-uri uri) "/" id))) (defn- overrides-uri "Returns the full overrides uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/overrides")) ([uri collection-name override-name] (str (overrides-uri uri collection-name) "/" override-name))) (defn- aliases-uri "Returns the full alias uri resource path." ([uri] (str uri "/aliases")) ([uri collection-name] (str uri "/aliases/" collection-name))) (defn- synonyms-uri "Returns the full synonyms uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/synonyms")) ([uri collection-name synonym-name] (str (synonyms-uri uri collection-name) "/" synonym-name))) (defn- multi-search-uri "Returns the full multi-search uri resource path." [uri common-search-params opt-query-params] (let [query-parameter-map (merge common-search-params opt-query-params)] (str uri "/multi_search" (util/map->url-parameter-string query-parameter-map)))) (defn create-collection-req [{:keys [uri key]} schema] {:uri (collection-uri uri) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str schema)}}) (defn update-collection-req [{:keys [uri key]} collection-name update-schema] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str update-schema)}}) (defn drop-collection-req [{:keys [uri key]} collection-name] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn list-collections-req [{:keys [uri key]}] {:uri (collection-uri uri) :req {:headers {api-key-header-name key}}}) (defn retrieve-collection-req [{:keys [uri key]} collection-name] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn create-document-req [{:keys [uri key]} collection-name document] {:uri (document-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn upsert-document-req [{:keys [uri key]} collection-name document] {:uri (str (document-uri uri collection-name) "?action=upsert") :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn retrieve-document-req [{:keys [uri key]} collection-name id] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key}}}) (defn delete-document-req [{:keys [uri key]} collection-name id] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key}}}) (defn update-document-req [{:keys [uri key]} collection-name id document] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn import-documents-req ([settings collection-name documents] (import-documents-req settings collection-name documents {})) ([{:keys [uri key]} collection-name documents options] {:uri (str (document-uri uri collection-name) "/import" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key "Content-Type" "text/plain"} :body (util/maps->json-lines documents)}})) (defn delete-documents-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn export-documents-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) "/export" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn search-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) "/search" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn multi-search-req [{:keys [uri key]} search-reqs common-search-params opt-query-params] {:uri (multi-search-uri uri common-search-params opt-query-params) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str search-reqs)}}) (defn create-api-key-req [{:keys [uri key]} options] {:uri (keys-uri uri) :req {:headers {api-key-header-name key} :body (json/write-str options)}}) (defn retrieve-api-key-req [{:keys [uri key]} id] {:uri (keys-uri uri id) :req {:headers {api-key-header-name key}}}) (defn list-api-keys-req [{:keys [uri key]}] {:uri (keys-uri uri) :req {:headers {api-key-header-name key}}}) (defn delete-api-key-req [{:keys [uri key]} id] {:uri (keys-uri uri id) :req {:headers {api-key-header-name key}}}) (defn upsert-override-req [{:keys [uri key]} collection-name override-name override] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str override)}}) (defn list-overrides-req [{:keys [uri key]} collection-name] {:uri (overrides-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn retrieve-override-req [{:keys [uri key]} collection-name override-name] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key}}}) (defn delete-override-req [{:keys [uri key]} collection-name override-name] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key}}}) (defn upsert-alias-req [{:keys [uri key]} collection-name alias-collection] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str alias-collection)}}) (defn retrieve-alias-req [{:keys [uri key]} collection-name] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn list-aliases-req [{:keys [uri key]}] {:uri (aliases-uri uri) :req {:headers {api-key-header-name key}}}) (defn delete-alias-req [{:keys [uri key]} collection-name] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn upsert-synonym-req [{:keys [uri key]} collection-name synonym-name synonyms] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str synonyms)}}) (defn retrieve-synonym-req [{:keys [uri key]} collection-name synonym-name] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key}}}) (defn list-synonyms-req [{:keys [uri key]} collection-name] {:uri (synonyms-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn delete-synonym-req [{:keys [uri key]} collection-name synonym-name] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key}}})
null
https://raw.githubusercontent.com/runeanielsen/typesense-clj/94e82f5951a0693bdbad4c20dde6fb07b6911d1a/src/typesense/api.clj
clojure
(ns typesense.api (:require [typesense.util :as util] [clojure.data.json :as json])) (def ^:private api-key-header-name "X-TYPESENSE-API-KEY") (defn- collection-uri "Returns the full collection uri resource path." ([uri] (str uri "/collections")) ([uri collection-name] (str (collection-uri uri) "/" collection-name))) (defn- document-uri "Returns the full document uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/documents")) ([uri collection-name id] (str (document-uri uri collection-name) "/" id))) (defn- keys-uri "Return the full keys uri resource path." ([uri] (str uri "/keys")) ([uri id] (str (keys-uri uri) "/" id))) (defn- overrides-uri "Returns the full overrides uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/overrides")) ([uri collection-name override-name] (str (overrides-uri uri collection-name) "/" override-name))) (defn- aliases-uri "Returns the full alias uri resource path." ([uri] (str uri "/aliases")) ([uri collection-name] (str uri "/aliases/" collection-name))) (defn- synonyms-uri "Returns the full synonyms uri resource path." ([uri collection-name] (str uri "/collections/" collection-name "/synonyms")) ([uri collection-name synonym-name] (str (synonyms-uri uri collection-name) "/" synonym-name))) (defn- multi-search-uri "Returns the full multi-search uri resource path." [uri common-search-params opt-query-params] (let [query-parameter-map (merge common-search-params opt-query-params)] (str uri "/multi_search" (util/map->url-parameter-string query-parameter-map)))) (defn create-collection-req [{:keys [uri key]} schema] {:uri (collection-uri uri) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str schema)}}) (defn update-collection-req [{:keys [uri key]} collection-name update-schema] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str update-schema)}}) (defn drop-collection-req [{:keys [uri key]} collection-name] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn list-collections-req [{:keys [uri key]}] {:uri (collection-uri uri) :req {:headers {api-key-header-name key}}}) (defn retrieve-collection-req [{:keys [uri key]} collection-name] {:uri (collection-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn create-document-req [{:keys [uri key]} collection-name document] {:uri (document-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn upsert-document-req [{:keys [uri key]} collection-name document] {:uri (str (document-uri uri collection-name) "?action=upsert") :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn retrieve-document-req [{:keys [uri key]} collection-name id] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key}}}) (defn delete-document-req [{:keys [uri key]} collection-name id] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key}}}) (defn update-document-req [{:keys [uri key]} collection-name id document] {:uri (document-uri uri collection-name id) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str document)}}) (defn import-documents-req ([settings collection-name documents] (import-documents-req settings collection-name documents {})) ([{:keys [uri key]} collection-name documents options] {:uri (str (document-uri uri collection-name) "/import" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key "Content-Type" "text/plain"} :body (util/maps->json-lines documents)}})) (defn delete-documents-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn export-documents-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) "/export" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn search-req [{:keys [uri key]} collection-name options] {:uri (str (document-uri uri collection-name) "/search" (util/map->url-parameter-string options)) :req {:headers {api-key-header-name key}}}) (defn multi-search-req [{:keys [uri key]} search-reqs common-search-params opt-query-params] {:uri (multi-search-uri uri common-search-params opt-query-params) :req {:headers {api-key-header-name key "Content-Type" "application/json"} :body (json/write-str search-reqs)}}) (defn create-api-key-req [{:keys [uri key]} options] {:uri (keys-uri uri) :req {:headers {api-key-header-name key} :body (json/write-str options)}}) (defn retrieve-api-key-req [{:keys [uri key]} id] {:uri (keys-uri uri id) :req {:headers {api-key-header-name key}}}) (defn list-api-keys-req [{:keys [uri key]}] {:uri (keys-uri uri) :req {:headers {api-key-header-name key}}}) (defn delete-api-key-req [{:keys [uri key]} id] {:uri (keys-uri uri id) :req {:headers {api-key-header-name key}}}) (defn upsert-override-req [{:keys [uri key]} collection-name override-name override] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str override)}}) (defn list-overrides-req [{:keys [uri key]} collection-name] {:uri (overrides-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn retrieve-override-req [{:keys [uri key]} collection-name override-name] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key}}}) (defn delete-override-req [{:keys [uri key]} collection-name override-name] {:uri (overrides-uri uri collection-name override-name) :req {:headers {api-key-header-name key}}}) (defn upsert-alias-req [{:keys [uri key]} collection-name alias-collection] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str alias-collection)}}) (defn retrieve-alias-req [{:keys [uri key]} collection-name] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn list-aliases-req [{:keys [uri key]}] {:uri (aliases-uri uri) :req {:headers {api-key-header-name key}}}) (defn delete-alias-req [{:keys [uri key]} collection-name] {:uri (aliases-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn upsert-synonym-req [{:keys [uri key]} collection-name synonym-name synonyms] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key "Content-Type" "text/json"} :body (json/write-str synonyms)}}) (defn retrieve-synonym-req [{:keys [uri key]} collection-name synonym-name] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key}}}) (defn list-synonyms-req [{:keys [uri key]} collection-name] {:uri (synonyms-uri uri collection-name) :req {:headers {api-key-header-name key}}}) (defn delete-synonym-req [{:keys [uri key]} collection-name synonym-name] {:uri (synonyms-uri uri collection-name synonym-name) :req {:headers {api-key-header-name key}}})
0cc4fd645ea62edae818f034aae50f784fa83ab932dc52894d30baf61b60abb8
cl-stream/cl-stream
sequence-input-stream.lisp
;; ;; cl-stream - Stream classes for Common Lisp ;; ;; Copyright 2017,2018 Thomas de Grivel <> ;; ;; 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. ;; (in-package :cl-stream) (defclass sequence-input-stream (buffered-input-stream) ((open-p :initform t :type boolean)) (:documentation "A buffered input stream that reads from a sequence.")) (defmethod initialize-instance ((stream sequence-input-stream) &rest initargs &key sequence &allow-other-keys) (declare (ignore initargs) (type sequence sequence)) (call-next-method) (setf (slot-value stream 'input-buffer) sequence)) (defmethod stream-close ((stream sequence-input-stream)) (setf (slot-value stream 'open-p) nil)) (defmethod stream-open-p ((stream sequence-input-stream)) (slot-value stream 'open-p)) (defmethod stream-element-type ((stream sequence-input-stream)) (array-element-type (stream-input-buffer stream))) (defmethod stream-input-buffer-size ((stream sequence-input-stream)) (length (stream-input-buffer stream))) (defmethod stream-input-length ((stream sequence-input-stream)) (length (stream-input-buffer stream))) (defmethod stream-fill-input-buffer ((stream sequence-input-stream)) :eof) (defun sequence-input-stream (sequence) "Returns a new sequence input stream reading from SEQUENCE." (make-instance 'sequence-input-stream :sequence sequence)) (defun string-input-stream (string) "Returns a new sequence input stream reading from STRING." (declare (type string string)) (sequence-input-stream string))
null
https://raw.githubusercontent.com/cl-stream/cl-stream/8c4888591cd4ef9062c6c066326acef1415460f1/sequence-input-stream.lisp
lisp
cl-stream - Stream classes for Common Lisp Copyright 2017,2018 Thomas de Grivel <> 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. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN (in-package :cl-stream) (defclass sequence-input-stream (buffered-input-stream) ((open-p :initform t :type boolean)) (:documentation "A buffered input stream that reads from a sequence.")) (defmethod initialize-instance ((stream sequence-input-stream) &rest initargs &key sequence &allow-other-keys) (declare (ignore initargs) (type sequence sequence)) (call-next-method) (setf (slot-value stream 'input-buffer) sequence)) (defmethod stream-close ((stream sequence-input-stream)) (setf (slot-value stream 'open-p) nil)) (defmethod stream-open-p ((stream sequence-input-stream)) (slot-value stream 'open-p)) (defmethod stream-element-type ((stream sequence-input-stream)) (array-element-type (stream-input-buffer stream))) (defmethod stream-input-buffer-size ((stream sequence-input-stream)) (length (stream-input-buffer stream))) (defmethod stream-input-length ((stream sequence-input-stream)) (length (stream-input-buffer stream))) (defmethod stream-fill-input-buffer ((stream sequence-input-stream)) :eof) (defun sequence-input-stream (sequence) "Returns a new sequence input stream reading from SEQUENCE." (make-instance 'sequence-input-stream :sequence sequence)) (defun string-input-stream (string) "Returns a new sequence input stream reading from STRING." (declare (type string string)) (sequence-input-stream string))
5a5c3f660f667438c98f1e2263fbcb84f96f9312c02bc3d72451559c270190ee
binsec/binsec
htx_main.mli
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2022 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 ) . (* *) (**************************************************************************) val run : Ida_cfg.G.t -> unit
null
https://raw.githubusercontent.com/binsec/binsec/8ed9991d36451a3ae7487b966c4b38acca21a5b3/src/examples/htmlexport/htx_main.mli
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. ************************************************************************
This file is part of BINSEC . Copyright ( C ) 2016 - 2022 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 ) . val run : Ida_cfg.G.t -> unit
7697a8b2125f94001337430de27f513db2408ffabfd58680ee4b9f7df8127a7f
sulami/spielwiese
19.hs
module Main where import Control.Arrow ((&&&)) import Data.List (groupBy, isPrefixOf, nub) import Data.Function (on) conc :: [(String, String)] -> (String, [String]) conc l = (fst (head l), map snd l) walk :: ([a] -> [a] -> b) -> [a] -> [b] walk f = walk' f [] where walk' :: ([a] -> [a] -> b) -> [a] -> [a] -> [b] walk' _ _ [] = [] walk' f bef aft = f bef aft : walk' f (bef ++ [head aft]) (tail aft) repls :: String -> [(String, [String])] -> [String] repls s rs = concat . filter (not . null) $ walk (search rs) s where search :: [(String, [String])] -> String -> String -> [String] search rs bef aft = concatMap (replace bef aft) $ filter ((`isPrefixOf` aft) . fst) rs replace :: String -> String -> (String, [String]) -> [String] replace bef aft (bc,rs) = map (\r -> bef ++ r ++ drop (length bc) aft) rs main = do indata <- lines <$> readFile "19.input" let replacements = map conc . groupBy ((==) `on` fst) . map ((head &&& last) . words) $ takeWhile (not . null) indata start = last indata print . length . nub $ repls start replacements
null
https://raw.githubusercontent.com/sulami/spielwiese/da354aa112d43d7ec5f258f4b5afafd7a88c8aa8/advent15/19.hs
haskell
module Main where import Control.Arrow ((&&&)) import Data.List (groupBy, isPrefixOf, nub) import Data.Function (on) conc :: [(String, String)] -> (String, [String]) conc l = (fst (head l), map snd l) walk :: ([a] -> [a] -> b) -> [a] -> [b] walk f = walk' f [] where walk' :: ([a] -> [a] -> b) -> [a] -> [a] -> [b] walk' _ _ [] = [] walk' f bef aft = f bef aft : walk' f (bef ++ [head aft]) (tail aft) repls :: String -> [(String, [String])] -> [String] repls s rs = concat . filter (not . null) $ walk (search rs) s where search :: [(String, [String])] -> String -> String -> [String] search rs bef aft = concatMap (replace bef aft) $ filter ((`isPrefixOf` aft) . fst) rs replace :: String -> String -> (String, [String]) -> [String] replace bef aft (bc,rs) = map (\r -> bef ++ r ++ drop (length bc) aft) rs main = do indata <- lines <$> readFile "19.input" let replacements = map conc . groupBy ((==) `on` fst) . map ((head &&& last) . words) $ takeWhile (not . null) indata start = last indata print . length . nub $ repls start replacements
fb2e1354c647c52c95e2ec3a1876a797eb18d2671d5193b7d5cb9edde457f172
cosmicoptima/dictator
NPCs.hs
# LANGUAGE DeriveGeneric # module Game.NPCs ( npcSpeak , randomNPCSpeakGroup , randomNPCConversation , createNPC ) where import Relude hiding ( many ) import Game import Game.Data import Utils import Utils.DictM import Utils.Discord import Utils.Language import Control.Lens hiding ( noneOf ) import Control.Monad.Except ( throwError ) import qualified Data.Set as Set import Data.String.Interpolate ( i ) import qualified Data.Text as T import Discord.Requests import Discord.Types import System.Random import Text.Parsec npcSpeak :: ChannelId -> Text -> DictM () npcSpeak channel npc = do messages <- reverse . filter (not . T.null . messageText) <$> restCall' (GetChannelMessages channel (20, LatestMessages)) npcData <- getNPC npc avatar <- encodeAvatarData <$> case npcData ^. npcAvatar of Just av -> return av Nothing -> do avatar <- randomImage setNPC npc $ npcData & npcAvatar ?~ avatar return avatar let memories = npcData ^. npcMemories . to Set.elems memory <- fmap (randomChoiceMay memories) newStdGen decides :: Bool <- randomIO let thought = maybe ("" :: Text) (\m -> [i|(#{npc} thinks: "#{m}")\n(#{npc} decides#{if decides then "" else " not" :: Text} to talk about this)\n|] ) memory introduction :: Text = [i|In this Discord chatlog, pay close attention to the fictional character "#{npc}"'s speech patterns; #{npc} is designed around the following traits:\nPersonality: #{T.intercalate ", " (npcData ^. npcAdjectives)}\nInterests: #{T.intercalate ", " (npcData ^. npcInterests)}\nHere is the chatlog:|] -- prompt = -- T.concat (map renderMessage messages) <> thought <> npc <> " says:" prompt = [i|#{introduction}#{T.concat (map renderMessage messages)}#{thought}#{npc} says:|] output <- getJ1UntilWith (J1Opts 1 0.85 0.3 [("<|newline|>", 0.3)]) ["\n"] prompt <&> parse parser "" case output of Left f -> throwError $ Fuckup (show f) Right (T.strip -> t) -> do n :: Double <- randomIO when ("i " `T.isPrefixOf` t || "i'" `T.isPrefixOf` t || n < 0.2) . void $ modifyNPC npc (over npcMemories $ Set.insert t) void $ sendWebhookMessage channel t npc (Just avatar) where renderMessage m = (userName . messageAuthor) m <> " says: " <> messageText m <> "\n" parser = fromString <$> many (noneOf "\n") npcSpeakGroup :: ChannelId -> Text -> DictM () npcSpeakGroup channel npc = do nMessages <- randomRIO (1, 3) replicateM_ nMessages $ npcSpeak channel npc randomNPCSpeakGroup :: ChannelId -> DictM () randomNPCSpeakGroup channel = do npcs <- listNPC npc <- newStdGen <&> randomChoice npcs npcSpeakGroup channel npc randomNPCConversation :: Int -> ChannelId -> DictM () randomNPCConversation l channel = do npcs <- listNPC nNPCs <- randomRIO (2, 4) selectedNPCs <- replicateM nNPCs (newStdGen <&> randomChoice npcs) replicateM_ l $ do npc <- newStdGen <&> randomChoice selectedNPCs npcSpeak channel npc data NPCPersonality = NPCPersonality { personName :: Text , personAdjs :: [Text] , personInterests :: [Text] , personmMemory :: Text } createNPC :: DictM Text createNPC = do output <- getJ1 128 prompt case parse parser "" output of Left f -> throwError $ Fuckup (show f <> ":\n" <> output) Right (NPCPersonality name adjs ints mem) -> do avatar <- randomImage setNPC name $ NPCData { _npcAvatar = Just avatar , _npcAdjectives = adjs , _npcInterests = ints , _npcMemories = Set.fromList [mem] } pure name where prompt = "A small group of previously unknown writers seem to have found their breakout hit: a niche, absurdist online drama of sorts whose storyline plays out on a Discord server. The server (in which only the writers' in-character accounts may post) reached 10,000 members on August 18. The plot evolves quickly and characters are ephemeral, but the 22 active characters are currently as follows:\n\n\ \Username | Personality | Interests | Most worrying thought\n\ \Elmer Foppington | nosy, cheeky, likes nothing more than a cup of tea and a bit of a gossip | antiques, tea parties, murder | \"i am going to kill someone in this chat\"\n\ \Normal Man | average, dead behind the eyes | cooking, vague non-sequiturs | \"i haven't cared about my wife in years\"\n\ \Aberrant | psychopathic, literally raving mad, charismatic | russian avant garde poetry, grotesque body horror, elaborate trolling campaigns | \"my penis is very small and weak\"\n\ \pancake10 | obsequious, weaselly, smooth | '90s cyberculture, hypnotics, incels | \"mice aren't real\"\n\ \nick land | tone-deaf, bumbling, manic | transhumanism, semi-racist right-wing politics, memetics | \"i am a kitty meow mew\"\n" parser = do name <- many1 (noneOf "|") <&> T.strip . fromString _ <- char '|' adjs <- many1 (noneOf "|") <&> map T.strip . T.splitOn "," . fromString _ <- char '|' ints <- many1 (noneOf "|") <&> map T.strip . T.splitOn "," . fromString _ <- string "| \"" mem <- many1 (noneOf "\"\n") <&> T.strip . fromString _ <- string "\"" pure $ NPCPersonality name adjs ints mem
null
https://raw.githubusercontent.com/cosmicoptima/dictator/f3c575db4658820400f11297346f51ffaee75300/src/Game/NPCs.hs
haskell
prompt = T.concat (map renderMessage messages) <> thought <> npc <> " says:"
# LANGUAGE DeriveGeneric # module Game.NPCs ( npcSpeak , randomNPCSpeakGroup , randomNPCConversation , createNPC ) where import Relude hiding ( many ) import Game import Game.Data import Utils import Utils.DictM import Utils.Discord import Utils.Language import Control.Lens hiding ( noneOf ) import Control.Monad.Except ( throwError ) import qualified Data.Set as Set import Data.String.Interpolate ( i ) import qualified Data.Text as T import Discord.Requests import Discord.Types import System.Random import Text.Parsec npcSpeak :: ChannelId -> Text -> DictM () npcSpeak channel npc = do messages <- reverse . filter (not . T.null . messageText) <$> restCall' (GetChannelMessages channel (20, LatestMessages)) npcData <- getNPC npc avatar <- encodeAvatarData <$> case npcData ^. npcAvatar of Just av -> return av Nothing -> do avatar <- randomImage setNPC npc $ npcData & npcAvatar ?~ avatar return avatar let memories = npcData ^. npcMemories . to Set.elems memory <- fmap (randomChoiceMay memories) newStdGen decides :: Bool <- randomIO let thought = maybe ("" :: Text) (\m -> [i|(#{npc} thinks: "#{m}")\n(#{npc} decides#{if decides then "" else " not" :: Text} to talk about this)\n|] ) memory introduction :: Text = [i|In this Discord chatlog, pay close attention to the fictional character "#{npc}"'s speech patterns; #{npc} is designed around the following traits:\nPersonality: #{T.intercalate ", " (npcData ^. npcAdjectives)}\nInterests: #{T.intercalate ", " (npcData ^. npcInterests)}\nHere is the chatlog:|] prompt = [i|#{introduction}#{T.concat (map renderMessage messages)}#{thought}#{npc} says:|] output <- getJ1UntilWith (J1Opts 1 0.85 0.3 [("<|newline|>", 0.3)]) ["\n"] prompt <&> parse parser "" case output of Left f -> throwError $ Fuckup (show f) Right (T.strip -> t) -> do n :: Double <- randomIO when ("i " `T.isPrefixOf` t || "i'" `T.isPrefixOf` t || n < 0.2) . void $ modifyNPC npc (over npcMemories $ Set.insert t) void $ sendWebhookMessage channel t npc (Just avatar) where renderMessage m = (userName . messageAuthor) m <> " says: " <> messageText m <> "\n" parser = fromString <$> many (noneOf "\n") npcSpeakGroup :: ChannelId -> Text -> DictM () npcSpeakGroup channel npc = do nMessages <- randomRIO (1, 3) replicateM_ nMessages $ npcSpeak channel npc randomNPCSpeakGroup :: ChannelId -> DictM () randomNPCSpeakGroup channel = do npcs <- listNPC npc <- newStdGen <&> randomChoice npcs npcSpeakGroup channel npc randomNPCConversation :: Int -> ChannelId -> DictM () randomNPCConversation l channel = do npcs <- listNPC nNPCs <- randomRIO (2, 4) selectedNPCs <- replicateM nNPCs (newStdGen <&> randomChoice npcs) replicateM_ l $ do npc <- newStdGen <&> randomChoice selectedNPCs npcSpeak channel npc data NPCPersonality = NPCPersonality { personName :: Text , personAdjs :: [Text] , personInterests :: [Text] , personmMemory :: Text } createNPC :: DictM Text createNPC = do output <- getJ1 128 prompt case parse parser "" output of Left f -> throwError $ Fuckup (show f <> ":\n" <> output) Right (NPCPersonality name adjs ints mem) -> do avatar <- randomImage setNPC name $ NPCData { _npcAvatar = Just avatar , _npcAdjectives = adjs , _npcInterests = ints , _npcMemories = Set.fromList [mem] } pure name where prompt = "A small group of previously unknown writers seem to have found their breakout hit: a niche, absurdist online drama of sorts whose storyline plays out on a Discord server. The server (in which only the writers' in-character accounts may post) reached 10,000 members on August 18. The plot evolves quickly and characters are ephemeral, but the 22 active characters are currently as follows:\n\n\ \Username | Personality | Interests | Most worrying thought\n\ \Elmer Foppington | nosy, cheeky, likes nothing more than a cup of tea and a bit of a gossip | antiques, tea parties, murder | \"i am going to kill someone in this chat\"\n\ \Normal Man | average, dead behind the eyes | cooking, vague non-sequiturs | \"i haven't cared about my wife in years\"\n\ \Aberrant | psychopathic, literally raving mad, charismatic | russian avant garde poetry, grotesque body horror, elaborate trolling campaigns | \"my penis is very small and weak\"\n\ \pancake10 | obsequious, weaselly, smooth | '90s cyberculture, hypnotics, incels | \"mice aren't real\"\n\ \nick land | tone-deaf, bumbling, manic | transhumanism, semi-racist right-wing politics, memetics | \"i am a kitty meow mew\"\n" parser = do name <- many1 (noneOf "|") <&> T.strip . fromString _ <- char '|' adjs <- many1 (noneOf "|") <&> map T.strip . T.splitOn "," . fromString _ <- char '|' ints <- many1 (noneOf "|") <&> map T.strip . T.splitOn "," . fromString _ <- string "| \"" mem <- many1 (noneOf "\"\n") <&> T.strip . fromString _ <- string "\"" pure $ NPCPersonality name adjs ints mem
29fba83dc118272d9c9779d656835fa0f5360f7d182c0cd4b2cd5a0fce3bcf0c
roman01la/shapy
toolbar.cljs
(ns shapy.components.toolbar (:require [rum.core :as rum] [shapy.components.icons :refer [LineIcon RectIcon OvalIcon]])) (def editor-styles {:background "#fff" :borderBottom "1px solid #bfbfbf" :padding "8px 16px" :display "flex" :justifyContent "flex-start" :zIndex 1}) (def section-styles {:display "flex" :flexDirection "column" :margin "0 20px 0 0"}) (def icons-panel-styles {:display "flex"}) (def divider [:div {:style {:margin "0 5px"}}]) (def shape-icons {:line LineIcon :rect RectIcon :oval OvalIcon}) (rum/defc Toolbar < rum/static [{:keys [on-select selected]}] [:div {:style editor-styles} [:img {:src "/app_icon.png" :title "Shapy!" :width 24 :height 24 :style {:margin "0 32px 0 0" :padding 2}}] [:div {:style section-styles} [:div {:style icons-panel-styles} (interpose divider (map (fn [[key Icon]] (rum/with-key (Icon {:on-click #(on-select key) :active? (= selected key)}) key)) shape-icons))]]])
null
https://raw.githubusercontent.com/roman01la/shapy/af94ed921f9cc9349f11fb931bde563bdb900531/src/shapy/components/toolbar.cljs
clojure
(ns shapy.components.toolbar (:require [rum.core :as rum] [shapy.components.icons :refer [LineIcon RectIcon OvalIcon]])) (def editor-styles {:background "#fff" :borderBottom "1px solid #bfbfbf" :padding "8px 16px" :display "flex" :justifyContent "flex-start" :zIndex 1}) (def section-styles {:display "flex" :flexDirection "column" :margin "0 20px 0 0"}) (def icons-panel-styles {:display "flex"}) (def divider [:div {:style {:margin "0 5px"}}]) (def shape-icons {:line LineIcon :rect RectIcon :oval OvalIcon}) (rum/defc Toolbar < rum/static [{:keys [on-select selected]}] [:div {:style editor-styles} [:img {:src "/app_icon.png" :title "Shapy!" :width 24 :height 24 :style {:margin "0 32px 0 0" :padding 2}}] [:div {:style section-styles} [:div {:style icons-panel-styles} (interpose divider (map (fn [[key Icon]] (rum/with-key (Icon {:on-click #(on-select key) :active? (= selected key)}) key)) shape-icons))]]])
30f88e5b27bae7aef8162d5ff1d253905d37b114fa812ef12f04cf3222cbe863
hammerlab/genspio
vm_tester.ml
open! Base module Filename = Caml.Filename let ( // ) = Filename.concat module Shell_script = struct type t = {name: string; content: unit Genspio.EDSL.t; dependencies: t list} open Genspio.EDSL let make ?(dependencies = []) name content = {name; content; dependencies} let sanitize_name n = let m = String.map n ~f:(function | ('0' .. '9' | 'a' .. 'z' | 'A' .. 'Z' | '-') as c -> c | _ -> '_' ) in try String.sub ~pos:0 ~len:40 m with _ -> m let path {name; content; _} = let open Caml in let hash = Marshal.to_string content [] |> Digest.string |> Digest.to_hex in let tag = String.sub hash 0 8 in "_scripts" // Fmt.str "%s_%s.sh" (sanitize_name name) tag let call f = exec ["sh"; path f] type compiled = {files: (string * string list) list; call: unit Genspio.EDSL.t} let rec compile ({name; content; dependencies} as s) = let filename = path s in let dep_scripts = List.map ~f:compile dependencies in dbg " name s filename : % s " name filename ; { files= ( filename , [ "# Script %s"; "# Generated by Genspio" ; Fmt.str "echo 'Genspio.Shell_script: %s (%s)'" name filename ; Genspio.Compile.to_many_lines content ] ) :: List.concat_map dep_scripts ~f:(fun c -> c.files) ; call= call s } end module Run_environment = struct module File = struct type t = Http of string * [`Xz] option let local_file_name = let noquery url = String.split ~on:'?' url |> List.hd_exn in function | Http (url, None) -> "_cache" // Filename.basename (noquery url) | Http (url, Some `Xz) -> "_cache" // Filename.(basename (noquery url) |> fun f -> chop_suffix f ".xz") let tmp_name_of_url = function | Http (url, ext) -> ("_cache" // Caml.Digest.(string url |> to_hex)) ^ Option.value_map ~default:"" ext ~f:(fun `Xz -> ".xz") let make_files files = List.map files ~f:(function Http (url, act) as t -> let base = local_file_name t in let wget = let open Genspio.EDSL in check_sequence [ ("mkdir", exec ["mkdir"; "-p"; "_cache"]) ; ( "wget" , exec ["wget"; url; "--output-document"; tmp_name_of_url t] ) ; ( "act-and-mv" , match act with | None -> exec ["mv"; "-f"; tmp_name_of_url t; base] | Some `Xz -> seq [ exec ["unxz"; "-k"; tmp_name_of_url t] ; exec [ "mv"; "-f" ; Filename.chop_suffix (tmp_name_of_url t) ".xz" ; base ] ] ) ] in (base, [], wget) ) end module Ssh = struct let ssh_options = [ "-oStrictHostKeyChecking=no"; "-oGlobalKnownHostsFile=/dev/null" ; "-oUserKnownHostsFile=/dev/null" ] let host_file f = Fmt.str "root@@localhost:%s" f let sshpass ?password cmd = match password with None -> cmd | Some p -> ["sshpass"; "-p"; p] @ cmd let scp ?password ~ssh_port () = sshpass ?password @@ ["scp"] @ ssh_options @ ["-P"; Int.to_string ssh_port] let script_over_ssh ?root_password ~ssh_port ~name script = let open Shell_script in let open Genspio.EDSL in let script_path = path script in let tmp = "/tmp" // Filename.basename script_path in make ~dependencies:[script] (Fmt.str "SSH exec %s" name) @@ check_sequence [ ( "scp" , exec ( scp ?password:root_password ~ssh_port () @ [script_path; host_file tmp] ) ) ; ( "ssh-exec" , exec ( sshpass ?password:root_password @@ ["ssh"] @ ssh_options @ [ "-p"; Int.to_string ssh_port; "root@localhost" ; Fmt.str "sh %s" tmp ] ) ) ] end type vm = | Qemu_arm of { kernel: File.t ; sd_card: File.t ; machine: string ; initrd: File.t option ; root_device: string } | Qemu_amd46 of {hda: File.t; ui: [`No_graphic | `Curses]} module Setup = struct type t = | Ssh_to_vm of unit Genspio.EDSL.t | Copy_relative of string * string let ssh_to_vm u = [Ssh_to_vm u] let copy (`Relative src) (`Relative dst) = Copy_relative (src, dst) end type t = { name: string ; root_password: string option ; setup: Setup.t list ; ssh_port: int ; local_dependencies: [`Command of string] list ; vm: vm } let make vm ?root_password ?(setup = []) ~local_dependencies ~ssh_port name = {vm; root_password; setup; local_dependencies; name; ssh_port} let qemu_arm ~kernel ~sd_card ~machine ?initrd ~root_device = make (Qemu_arm {kernel; sd_card; machine; initrd; root_device}) let qemu_amd46 ?(ui = `No_graphic) ~hda = make (Qemu_amd46 {hda; ui}) let http ?act uri = File.Http (uri, act) let start_qemu_vm : t -> Shell_script.t = function | { ssh_port ; vm= Qemu_arm {kernel; machine; sd_card; root_device; initrd; _} ; _ } -> let open Shell_script in let open Genspio.EDSL in make "Start-qemu-arm" (exec ( [ "qemu-system-arm"; "-M"; machine; "-m"; "1024M"; "-kernel" ; File.local_file_name kernel ] @ Option.value_map initrd ~default:[] ~f:(fun f -> ["-initrd"; File.local_file_name f] ) @ [ "-pidfile"; "qemu.pid"; "-net"; "nic"; "-net" ; Fmt.str "user,hostfwd=tcp::%d-:22" ssh_port; "-nographic" ; "-sd"; File.local_file_name sd_card; "-append" ; Fmt.str "console=ttyAMA0 verbose debug root=%s" root_device ] ) ) | {ssh_port; vm= Qemu_amd46 {hda; ui}; _} -> (* See qemu-system-x86_64 -m 2048 \ -hda FreeBSD-11.0-RELEASE-amd64.qcow2 -enable-kvm \ -netdev user,id=mynet0,hostfwd=tcp:127.0.0.1:7722-:22 \ -device e1000,netdev=mynet0 *) let open Shell_script in let open Genspio.EDSL in make "Start-qemu" (exec ( [ "qemu-system-x86_64" (* ; "-M" * ; machine *); "-m" ; "1024M" (* ; "-enable-kvm" → requires `sudo`?*); "-hda" ; File.local_file_name hda ] @ [ "-pidfile"; "qemu.pid"; "-netdev" ; Fmt.str "user,id=mynet0,hostfwd=tcp::%d-:22" ssh_port ; ( match ui with | `Curses -> "-curses" | `No_graphic -> "-nographic" ); "-device" ; "e1000,netdev=mynet0" ] ) ) let kill_qemu_vm : t -> Shell_script.t = function | {name; _} -> let open Genspio.EDSL in let pid = get_stdout (exec ["cat"; "qemu.pid"]) in Shell_script.(make (Fmt.str "kill-qemu-%s" name)) @@ check_sequence (* ~name:(Fmt.str "Killing Qemu VM") * ~clean_up:[fail "kill_qemu_vm"] *) [ ( "Kill-qemu-vm" , if_seq (file_exists (string "qemu.pid")) ~t: [ if_seq (call [string "kill"; pid] |> succeeds) ~t:[exec ["rm"; "qemu.pid"]] ~e: [ printf (string "PID file here (PID: %s) but Kill failed, \ deleting `qemu.pid`" ) [pid]; exec ["rm"; "qemu.pid"]; exec ["false"] ] ] ~e:[printf (string "No PID file") []; exec ["false"]] ) ] let configure : t -> Shell_script.t = function | {name; local_dependencies; _} -> let open Genspio.EDSL in let report = tmp_file "configure-report.md" in let there_was_a_failure = tmp_file "bool-failure" in let cmds = [ report#set (str "Configuration Report\n====================\n\n") ; there_was_a_failure#set (bool false |> Bool.to_string) ] @ List.map local_dependencies ~f:(function `Command name -> if_seq (exec ["which"; name] |> silently |> succeeds) ~t:[report#append (Fmt.kstr str "* `%s`: found.\n" name)] ~e: [ report#append (Fmt.kstr str "* `%s`: NOT FOUND!\n" name) ; there_was_a_failure#set (bool true |> Bool.to_string) ] ) @ [ call [string "cat"; report#path] ; if_seq (there_was_a_failure#get |> Bool.of_string) ~t: [ exec ["printf"; "\\nThere were *failures* :(\\n"] ; exec ["false"] ] ~e:[exec ["printf"; "\\n*Success!*\\n"]] ] in Shell_script.(make (Fmt.str "configure-%s" name)) @@ check_sequence ~verbosity:`Output_all (List.mapi cmds ~f:(fun i c -> (Fmt.str "config-%s-%d" name i, c))) let make_dependencies = function | {vm= Qemu_amd46 {hda; _}; _} -> File.make_files [hda] | {vm= Qemu_arm {kernel; sd_card; initrd; _}; _} -> File.make_files ( [kernel; sd_card] @ Option.value_map initrd ~default:[] ~f:(fun x -> [x]) ) let setup_dir_content tvm = let {root_password; setup; ssh_port; _} = tvm in let other_files = ref [] in let dependencies = make_dependencies tvm in let start_deps = List.map dependencies ~f:(fun (base, _, _) -> base) in let help_entries = ref [] in let make_entry ?doc ?(phony = false) ?(deps = []) target action = help_entries := (target, doc) :: !help_entries ; (if phony then [Fmt.str ".PHONY: %s" target] else []) @ [ Fmt.str "# %s: %s" target (Option.value_map ~f:(String.map ~f:(function '\n' -> ' ' | c -> c)) doc ~default:"NOT DOCUMENTED" ) ; Fmt.str "%s: %s" target (String.concat ~sep:" " deps) ; Fmt.str "\t@@%s" (Genspio.Compile.to_one_liner ~no_trap:true action) ] in let make_script_entry ?doc ?phony ?deps target script = let open Shell_script in let {files; call} = Shell_script.compile script in other_files := !other_files @ files ; make_entry ?doc ?phony ?deps target call in let setup_entries = List.mapi setup ~f:(fun idx -> let name = Fmt.str "setup-%d" idx in let deps = List.init idx ~f:(fun i -> Fmt.str "setup-%d" i) in function | Ssh_to_vm cmds -> ( name , make_script_entry ~phony:true name ~deps (Ssh.script_over_ssh ?root_password ~ssh_port ~name (Shell_script.make (Fmt.str "setup-%s" name) cmds) ) ) | Copy_relative (src, dst) -> ( name , make_entry ~phony:true name ~deps Genspio.EDSL.( exec ["tar"; "c"; src] ||> exec ( Ssh.sshpass ?password:root_password @@ ["ssh"; "-p"; Int.to_string ssh_port] @ Ssh.ssh_options @ [ "root@localhost" ; Fmt.str "tar -x -f - ; mv %s %s" src dst ] )) ) ) in let makefile = ["# Makefile genrated by Genspio's VM-Tester"] @ List.concat_map dependencies ~f:(fun (base, deps, cmd) -> Shell_script.(make (Fmt.str "get-%s" (sanitize_name base)) cmd) |> make_script_entry ~deps base ) @ make_script_entry ~phony:true "configure" (configure tvm) ~doc:"Configure this local-host (i.e. check for requirements)." @ make_script_entry ~deps:start_deps ~phony:true "start" ~doc:"Start the Qemu VM (this grabs the terminal)." (start_qemu_vm tvm) @ make_script_entry ~phony:true "kill" (kill_qemu_vm tvm) ~doc:"Kill the Qemu VM." @ List.concat_map setup_entries ~f:snd @ make_entry ~phony:true "setup" ~deps:(List.map setup_entries ~f:fst) Genspio.EDSL.(seq [exec ["echo"; "Setup done"]]) ~doc: "Run the “setup” recipe on the Qemu VM (requires the VM\n\ \ started in another terminal)." @ make_entry ~phony:true "ssh" ~doc:"Display an SSH command" Genspio.EDSL.( let prefix = Ssh.sshpass ?password:root_password [] |> String.concat ~sep:" " in printf (Fmt.kstr string "%s ssh -p %d %s root@@localhost" prefix ssh_port (String.concat ~sep:" " Ssh.ssh_options) ) []) in let help = make_script_entry ~phony:true "help" Shell_script.( make "Display help message" Genspio.EDSL.( exec [ "printf" ; "\\nHelp\\n====\\n\\nThis a generated Makefile (by \ Genspio-VM-Tester):\\n\\n%s\\n\\n%s\\n" ; List.map (("help", Some "Display this help message") :: !help_entries) ~f:(function | _, None -> "" | target, Some doc -> Fmt.str "* `make %s`: %s\n" target doc ) |> String.concat ~sep:"" ; Fmt.str "SSH: the command `make ssh` *outputs* an SSH command \ (%s). Examples:\n\n\ $ `make ssh` uname -a\n\ $ tar c some/dir/ | $(make ssh) 'tar x'\n\n\ (may need to be `tar -x -f -` for BSD tar).\n" (Option.value_map ~default:"No root-password" root_password ~f:(Fmt.str "Root-password: %S") ) ])) in ("Makefile", ("all: help" :: makefile) @ help @ [""]) :: !other_files module Example = struct let qemu_arm_openwrt ~ssh_port more_setup = let setup = let open Genspio.EDSL in Setup.ssh_to_vm (check_sequence [ ("opkg-update", exec ["opkg"; "update"]) ; ("install-od", exec ["opkg"; "install"; "coreutils-od"]) ; ("install-make", exec ["opkg"; "install"; "make"]) ] ) @ more_setup in let base_url = "/" in qemu_arm "qemu_arm_openwrt" ~ssh_port ~machine:"realview-pbx-a9" ~kernel:(http (base_url // "openwrt-realview-vmlinux.elf")) ~sd_card:(http (base_url // "openwrt-realview-sdcard.img")) ~root_device:"/dev/mmcblk0p1" ~setup ~local_dependencies:[`Command "qemu-system-arm"] let qemu_arm_wheezy ~ssh_port more_setup = (* See {{:/~aurel32/qemu/armhf/}}. *) let aurel32 file = http ("/~aurel32/qemu/armhf" // file) in let setup = let open Genspio.EDSL in Setup.ssh_to_vm (check_sequence [("apt-get-make", exec ["apt-get"; "install"; "--yes"; "make"])] ) @ more_setup in qemu_arm "qemu_arm_wheezy" ~ssh_port ~machine:"vexpress-a9" ~kernel:(aurel32 "vmlinuz-3.2.0-4-vexpress") ~sd_card:(aurel32 "debian_wheezy_armhf_standard.qcow2") ~initrd:(aurel32 "initrd.img-3.2.0-4-vexpress") ~root_device:"/dev/mmcblk0p2" ~root_password:"root" ~setup ~local_dependencies:[`Command "qemu-system-arm"; `Command "sshpass"] let qemu_amd64_freebsd ~ssh_port more_setup = let qcow = http ~act:`Xz This qcow2 was created following the instructions at #FreeBSD #FreeBSD *) "-amd64-rootssh.qcow2.xz?raw=1" in let setup = more_setup in let root_password = "root" in qemu_amd46 "qemu_amd64_freebsd" ~hda:qcow ~setup ~root_password ~ui:`Curses ~local_dependencies:[`Command "qemu-system-x86_64"; `Command "sshpass"] ~ssh_port let qemu_amd64_darwin ~ssh_port more_setup = Made with these instructions : from -801.iso.gz Made with these instructions: from -801.iso.gz *) let qcow = http ~act:`Xz "-disk-20180730.qcow2.xz?raw=1" in let setup = more_setup in let root_password = "root" in qemu_amd46 "qemu_amd64_darwin" ~hda:qcow ~setup ~root_password ~ui:`No_graphic ~local_dependencies:[`Command "qemu-system-x86_64"; `Command "sshpass"] ~ssh_port end end let cmdf fmt = Fmt.kstr (fun cmd -> match Caml.Sys.command cmd with | 0 -> () | other -> Fmt.kstr failwith "Command %S did not return 0: %d" cmd other ) fmt let write_lines p l = let open Caml in let o = open_out p in Base.List.iter l ~f:(Printf.fprintf o "%s\n") ; close_out o let () = let fail fmt = Fmt.kstr (fun s -> Fmt.epr "Wrong CLI: %s\n%!" s ; Caml.exit 2 ) fmt in let example = ref None in let path = ref None in let ssh_port = ref 20202 in let copy_directories = ref [] in let examples = [ ( "arm-owrt" , Run_environment.Example.qemu_arm_openwrt , "Qemu ARM VM with OpenWRT." ) ; ( "arm-dw" , Run_environment.Example.qemu_arm_wheezy , "Qemu ARM with Debian Wheezy." ) ; ( "amd64-fb" , Run_environment.Example.qemu_amd64_freebsd , "Qemu x86_64 with FreeBSD." ) ; ( "amd64-dw" , Run_environment.Example.qemu_amd64_darwin , "Qemu x86_64 with Darwin 8 (old Mac OSX)." ) ] in let set_example arg = match !example with | Some _ -> fail "Too many arguments (%S)!" arg | None -> example := Some ( match List.find_map examples ~f:(fun (e, v, _) -> if String.(e = arg) then Some v else None ) with | Some s -> s | None -> fail "Don't know VM %S" arg ) in let module Arg = Caml.Arg in let args = Arg.align [ ( "--ssh-port" , Arg.Int (fun s -> ssh_port := s) , Fmt.str "<int> Set the SSH-port (default: %d)." !ssh_port ) ; ( "--vm" , Arg.String set_example , Fmt.str "<name> The Name of the VM, one of:\n%s" (String.concat ~sep:"\n" (List.map ~f:(fun (n, _, d) -> Fmt.str "%s* `%s`: %s" (String.make 25 ' ') n d ) examples ) ) ) ; ( "--copy" , Arg.String (fun s -> let add p lp = let local_rel = String.map p ~f:(function '/' -> '_' | c -> c) in copy_directories := (p, local_rel, lp) :: !copy_directories in match Base.String.split ~on:':' s with | [] | [_] -> fail "Error in --copy: need a `:` separator (%S)" s | [p; lp] -> add p lp | p :: more -> add p (String.concat ~sep:":" more) ) , "<p-src:p-dst> Copy <p-src> in the output directory and add its \ upload to the VM to the `make setup` target as a relative path \ <p-dst>." ) ] in let usage = Fmt.str "vm-tester --vm <vm-name> <path>" in let anon arg = match !path with | Some _ -> fail "Too many arguments (%S)!" arg | None -> path := Some arg in Arg.parse args anon usage ; let more_setup = List.map !copy_directories ~f:(fun (_, locrel, hostp) -> Run_environment.Setup.copy (`Relative locrel) (`Relative hostp) ) in let re = match !example with | Some e -> e ~ssh_port:!ssh_port more_setup | None -> fail "Missing VM name\nUsage: %s" usage in let content = Run_environment.setup_dir_content re in let path = match !path with | Some p -> p | None -> fail "Missing path!\nUsage: %s" usage in List.iter content ~f:(fun (filepath, content) -> let full = path // filepath in cmdf "mkdir -p %s" (Filename.dirname full) ; write_lines full content ) ; List.iter !copy_directories ~f:(fun (p, local_rel, _) -> cmdf "rsync -az %s %s/%s" p path local_rel )
null
https://raw.githubusercontent.com/hammerlab/genspio/edb371177521a003c0367c15a96779edc71f3e02/src/examples/vm_tester.ml
ocaml
See qemu-system-x86_64 -m 2048 \ -hda FreeBSD-11.0-RELEASE-amd64.qcow2 -enable-kvm \ -netdev user,id=mynet0,hostfwd=tcp:127.0.0.1:7722-:22 \ -device e1000,netdev=mynet0 ; "-M" * ; machine ; "-enable-kvm" → requires `sudo`? ~name:(Fmt.str "Killing Qemu VM") * ~clean_up:[fail "kill_qemu_vm"] See {{:/~aurel32/qemu/armhf/}}.
open! Base module Filename = Caml.Filename let ( // ) = Filename.concat module Shell_script = struct type t = {name: string; content: unit Genspio.EDSL.t; dependencies: t list} open Genspio.EDSL let make ?(dependencies = []) name content = {name; content; dependencies} let sanitize_name n = let m = String.map n ~f:(function | ('0' .. '9' | 'a' .. 'z' | 'A' .. 'Z' | '-') as c -> c | _ -> '_' ) in try String.sub ~pos:0 ~len:40 m with _ -> m let path {name; content; _} = let open Caml in let hash = Marshal.to_string content [] |> Digest.string |> Digest.to_hex in let tag = String.sub hash 0 8 in "_scripts" // Fmt.str "%s_%s.sh" (sanitize_name name) tag let call f = exec ["sh"; path f] type compiled = {files: (string * string list) list; call: unit Genspio.EDSL.t} let rec compile ({name; content; dependencies} as s) = let filename = path s in let dep_scripts = List.map ~f:compile dependencies in dbg " name s filename : % s " name filename ; { files= ( filename , [ "# Script %s"; "# Generated by Genspio" ; Fmt.str "echo 'Genspio.Shell_script: %s (%s)'" name filename ; Genspio.Compile.to_many_lines content ] ) :: List.concat_map dep_scripts ~f:(fun c -> c.files) ; call= call s } end module Run_environment = struct module File = struct type t = Http of string * [`Xz] option let local_file_name = let noquery url = String.split ~on:'?' url |> List.hd_exn in function | Http (url, None) -> "_cache" // Filename.basename (noquery url) | Http (url, Some `Xz) -> "_cache" // Filename.(basename (noquery url) |> fun f -> chop_suffix f ".xz") let tmp_name_of_url = function | Http (url, ext) -> ("_cache" // Caml.Digest.(string url |> to_hex)) ^ Option.value_map ~default:"" ext ~f:(fun `Xz -> ".xz") let make_files files = List.map files ~f:(function Http (url, act) as t -> let base = local_file_name t in let wget = let open Genspio.EDSL in check_sequence [ ("mkdir", exec ["mkdir"; "-p"; "_cache"]) ; ( "wget" , exec ["wget"; url; "--output-document"; tmp_name_of_url t] ) ; ( "act-and-mv" , match act with | None -> exec ["mv"; "-f"; tmp_name_of_url t; base] | Some `Xz -> seq [ exec ["unxz"; "-k"; tmp_name_of_url t] ; exec [ "mv"; "-f" ; Filename.chop_suffix (tmp_name_of_url t) ".xz" ; base ] ] ) ] in (base, [], wget) ) end module Ssh = struct let ssh_options = [ "-oStrictHostKeyChecking=no"; "-oGlobalKnownHostsFile=/dev/null" ; "-oUserKnownHostsFile=/dev/null" ] let host_file f = Fmt.str "root@@localhost:%s" f let sshpass ?password cmd = match password with None -> cmd | Some p -> ["sshpass"; "-p"; p] @ cmd let scp ?password ~ssh_port () = sshpass ?password @@ ["scp"] @ ssh_options @ ["-P"; Int.to_string ssh_port] let script_over_ssh ?root_password ~ssh_port ~name script = let open Shell_script in let open Genspio.EDSL in let script_path = path script in let tmp = "/tmp" // Filename.basename script_path in make ~dependencies:[script] (Fmt.str "SSH exec %s" name) @@ check_sequence [ ( "scp" , exec ( scp ?password:root_password ~ssh_port () @ [script_path; host_file tmp] ) ) ; ( "ssh-exec" , exec ( sshpass ?password:root_password @@ ["ssh"] @ ssh_options @ [ "-p"; Int.to_string ssh_port; "root@localhost" ; Fmt.str "sh %s" tmp ] ) ) ] end type vm = | Qemu_arm of { kernel: File.t ; sd_card: File.t ; machine: string ; initrd: File.t option ; root_device: string } | Qemu_amd46 of {hda: File.t; ui: [`No_graphic | `Curses]} module Setup = struct type t = | Ssh_to_vm of unit Genspio.EDSL.t | Copy_relative of string * string let ssh_to_vm u = [Ssh_to_vm u] let copy (`Relative src) (`Relative dst) = Copy_relative (src, dst) end type t = { name: string ; root_password: string option ; setup: Setup.t list ; ssh_port: int ; local_dependencies: [`Command of string] list ; vm: vm } let make vm ?root_password ?(setup = []) ~local_dependencies ~ssh_port name = {vm; root_password; setup; local_dependencies; name; ssh_port} let qemu_arm ~kernel ~sd_card ~machine ?initrd ~root_device = make (Qemu_arm {kernel; sd_card; machine; initrd; root_device}) let qemu_amd46 ?(ui = `No_graphic) ~hda = make (Qemu_amd46 {hda; ui}) let http ?act uri = File.Http (uri, act) let start_qemu_vm : t -> Shell_script.t = function | { ssh_port ; vm= Qemu_arm {kernel; machine; sd_card; root_device; initrd; _} ; _ } -> let open Shell_script in let open Genspio.EDSL in make "Start-qemu-arm" (exec ( [ "qemu-system-arm"; "-M"; machine; "-m"; "1024M"; "-kernel" ; File.local_file_name kernel ] @ Option.value_map initrd ~default:[] ~f:(fun f -> ["-initrd"; File.local_file_name f] ) @ [ "-pidfile"; "qemu.pid"; "-net"; "nic"; "-net" ; Fmt.str "user,hostfwd=tcp::%d-:22" ssh_port; "-nographic" ; "-sd"; File.local_file_name sd_card; "-append" ; Fmt.str "console=ttyAMA0 verbose debug root=%s" root_device ] ) ) | {ssh_port; vm= Qemu_amd46 {hda; ui}; _} -> let open Shell_script in let open Genspio.EDSL in make "Start-qemu" (exec ( [ "qemu-system-x86_64" ; File.local_file_name hda ] @ [ "-pidfile"; "qemu.pid"; "-netdev" ; Fmt.str "user,id=mynet0,hostfwd=tcp::%d-:22" ssh_port ; ( match ui with | `Curses -> "-curses" | `No_graphic -> "-nographic" ); "-device" ; "e1000,netdev=mynet0" ] ) ) let kill_qemu_vm : t -> Shell_script.t = function | {name; _} -> let open Genspio.EDSL in let pid = get_stdout (exec ["cat"; "qemu.pid"]) in Shell_script.(make (Fmt.str "kill-qemu-%s" name)) @@ check_sequence [ ( "Kill-qemu-vm" , if_seq (file_exists (string "qemu.pid")) ~t: [ if_seq (call [string "kill"; pid] |> succeeds) ~t:[exec ["rm"; "qemu.pid"]] ~e: [ printf (string "PID file here (PID: %s) but Kill failed, \ deleting `qemu.pid`" ) [pid]; exec ["rm"; "qemu.pid"]; exec ["false"] ] ] ~e:[printf (string "No PID file") []; exec ["false"]] ) ] let configure : t -> Shell_script.t = function | {name; local_dependencies; _} -> let open Genspio.EDSL in let report = tmp_file "configure-report.md" in let there_was_a_failure = tmp_file "bool-failure" in let cmds = [ report#set (str "Configuration Report\n====================\n\n") ; there_was_a_failure#set (bool false |> Bool.to_string) ] @ List.map local_dependencies ~f:(function `Command name -> if_seq (exec ["which"; name] |> silently |> succeeds) ~t:[report#append (Fmt.kstr str "* `%s`: found.\n" name)] ~e: [ report#append (Fmt.kstr str "* `%s`: NOT FOUND!\n" name) ; there_was_a_failure#set (bool true |> Bool.to_string) ] ) @ [ call [string "cat"; report#path] ; if_seq (there_was_a_failure#get |> Bool.of_string) ~t: [ exec ["printf"; "\\nThere were *failures* :(\\n"] ; exec ["false"] ] ~e:[exec ["printf"; "\\n*Success!*\\n"]] ] in Shell_script.(make (Fmt.str "configure-%s" name)) @@ check_sequence ~verbosity:`Output_all (List.mapi cmds ~f:(fun i c -> (Fmt.str "config-%s-%d" name i, c))) let make_dependencies = function | {vm= Qemu_amd46 {hda; _}; _} -> File.make_files [hda] | {vm= Qemu_arm {kernel; sd_card; initrd; _}; _} -> File.make_files ( [kernel; sd_card] @ Option.value_map initrd ~default:[] ~f:(fun x -> [x]) ) let setup_dir_content tvm = let {root_password; setup; ssh_port; _} = tvm in let other_files = ref [] in let dependencies = make_dependencies tvm in let start_deps = List.map dependencies ~f:(fun (base, _, _) -> base) in let help_entries = ref [] in let make_entry ?doc ?(phony = false) ?(deps = []) target action = help_entries := (target, doc) :: !help_entries ; (if phony then [Fmt.str ".PHONY: %s" target] else []) @ [ Fmt.str "# %s: %s" target (Option.value_map ~f:(String.map ~f:(function '\n' -> ' ' | c -> c)) doc ~default:"NOT DOCUMENTED" ) ; Fmt.str "%s: %s" target (String.concat ~sep:" " deps) ; Fmt.str "\t@@%s" (Genspio.Compile.to_one_liner ~no_trap:true action) ] in let make_script_entry ?doc ?phony ?deps target script = let open Shell_script in let {files; call} = Shell_script.compile script in other_files := !other_files @ files ; make_entry ?doc ?phony ?deps target call in let setup_entries = List.mapi setup ~f:(fun idx -> let name = Fmt.str "setup-%d" idx in let deps = List.init idx ~f:(fun i -> Fmt.str "setup-%d" i) in function | Ssh_to_vm cmds -> ( name , make_script_entry ~phony:true name ~deps (Ssh.script_over_ssh ?root_password ~ssh_port ~name (Shell_script.make (Fmt.str "setup-%s" name) cmds) ) ) | Copy_relative (src, dst) -> ( name , make_entry ~phony:true name ~deps Genspio.EDSL.( exec ["tar"; "c"; src] ||> exec ( Ssh.sshpass ?password:root_password @@ ["ssh"; "-p"; Int.to_string ssh_port] @ Ssh.ssh_options @ [ "root@localhost" ; Fmt.str "tar -x -f - ; mv %s %s" src dst ] )) ) ) in let makefile = ["# Makefile genrated by Genspio's VM-Tester"] @ List.concat_map dependencies ~f:(fun (base, deps, cmd) -> Shell_script.(make (Fmt.str "get-%s" (sanitize_name base)) cmd) |> make_script_entry ~deps base ) @ make_script_entry ~phony:true "configure" (configure tvm) ~doc:"Configure this local-host (i.e. check for requirements)." @ make_script_entry ~deps:start_deps ~phony:true "start" ~doc:"Start the Qemu VM (this grabs the terminal)." (start_qemu_vm tvm) @ make_script_entry ~phony:true "kill" (kill_qemu_vm tvm) ~doc:"Kill the Qemu VM." @ List.concat_map setup_entries ~f:snd @ make_entry ~phony:true "setup" ~deps:(List.map setup_entries ~f:fst) Genspio.EDSL.(seq [exec ["echo"; "Setup done"]]) ~doc: "Run the “setup” recipe on the Qemu VM (requires the VM\n\ \ started in another terminal)." @ make_entry ~phony:true "ssh" ~doc:"Display an SSH command" Genspio.EDSL.( let prefix = Ssh.sshpass ?password:root_password [] |> String.concat ~sep:" " in printf (Fmt.kstr string "%s ssh -p %d %s root@@localhost" prefix ssh_port (String.concat ~sep:" " Ssh.ssh_options) ) []) in let help = make_script_entry ~phony:true "help" Shell_script.( make "Display help message" Genspio.EDSL.( exec [ "printf" ; "\\nHelp\\n====\\n\\nThis a generated Makefile (by \ Genspio-VM-Tester):\\n\\n%s\\n\\n%s\\n" ; List.map (("help", Some "Display this help message") :: !help_entries) ~f:(function | _, None -> "" | target, Some doc -> Fmt.str "* `make %s`: %s\n" target doc ) |> String.concat ~sep:"" ; Fmt.str "SSH: the command `make ssh` *outputs* an SSH command \ (%s). Examples:\n\n\ $ `make ssh` uname -a\n\ $ tar c some/dir/ | $(make ssh) 'tar x'\n\n\ (may need to be `tar -x -f -` for BSD tar).\n" (Option.value_map ~default:"No root-password" root_password ~f:(Fmt.str "Root-password: %S") ) ])) in ("Makefile", ("all: help" :: makefile) @ help @ [""]) :: !other_files module Example = struct let qemu_arm_openwrt ~ssh_port more_setup = let setup = let open Genspio.EDSL in Setup.ssh_to_vm (check_sequence [ ("opkg-update", exec ["opkg"; "update"]) ; ("install-od", exec ["opkg"; "install"; "coreutils-od"]) ; ("install-make", exec ["opkg"; "install"; "make"]) ] ) @ more_setup in let base_url = "/" in qemu_arm "qemu_arm_openwrt" ~ssh_port ~machine:"realview-pbx-a9" ~kernel:(http (base_url // "openwrt-realview-vmlinux.elf")) ~sd_card:(http (base_url // "openwrt-realview-sdcard.img")) ~root_device:"/dev/mmcblk0p1" ~setup ~local_dependencies:[`Command "qemu-system-arm"] let qemu_arm_wheezy ~ssh_port more_setup = let aurel32 file = http ("/~aurel32/qemu/armhf" // file) in let setup = let open Genspio.EDSL in Setup.ssh_to_vm (check_sequence [("apt-get-make", exec ["apt-get"; "install"; "--yes"; "make"])] ) @ more_setup in qemu_arm "qemu_arm_wheezy" ~ssh_port ~machine:"vexpress-a9" ~kernel:(aurel32 "vmlinuz-3.2.0-4-vexpress") ~sd_card:(aurel32 "debian_wheezy_armhf_standard.qcow2") ~initrd:(aurel32 "initrd.img-3.2.0-4-vexpress") ~root_device:"/dev/mmcblk0p2" ~root_password:"root" ~setup ~local_dependencies:[`Command "qemu-system-arm"; `Command "sshpass"] let qemu_amd64_freebsd ~ssh_port more_setup = let qcow = http ~act:`Xz This qcow2 was created following the instructions at #FreeBSD #FreeBSD *) "-amd64-rootssh.qcow2.xz?raw=1" in let setup = more_setup in let root_password = "root" in qemu_amd46 "qemu_amd64_freebsd" ~hda:qcow ~setup ~root_password ~ui:`Curses ~local_dependencies:[`Command "qemu-system-x86_64"; `Command "sshpass"] ~ssh_port let qemu_amd64_darwin ~ssh_port more_setup = Made with these instructions : from -801.iso.gz Made with these instructions: from -801.iso.gz *) let qcow = http ~act:`Xz "-disk-20180730.qcow2.xz?raw=1" in let setup = more_setup in let root_password = "root" in qemu_amd46 "qemu_amd64_darwin" ~hda:qcow ~setup ~root_password ~ui:`No_graphic ~local_dependencies:[`Command "qemu-system-x86_64"; `Command "sshpass"] ~ssh_port end end let cmdf fmt = Fmt.kstr (fun cmd -> match Caml.Sys.command cmd with | 0 -> () | other -> Fmt.kstr failwith "Command %S did not return 0: %d" cmd other ) fmt let write_lines p l = let open Caml in let o = open_out p in Base.List.iter l ~f:(Printf.fprintf o "%s\n") ; close_out o let () = let fail fmt = Fmt.kstr (fun s -> Fmt.epr "Wrong CLI: %s\n%!" s ; Caml.exit 2 ) fmt in let example = ref None in let path = ref None in let ssh_port = ref 20202 in let copy_directories = ref [] in let examples = [ ( "arm-owrt" , Run_environment.Example.qemu_arm_openwrt , "Qemu ARM VM with OpenWRT." ) ; ( "arm-dw" , Run_environment.Example.qemu_arm_wheezy , "Qemu ARM with Debian Wheezy." ) ; ( "amd64-fb" , Run_environment.Example.qemu_amd64_freebsd , "Qemu x86_64 with FreeBSD." ) ; ( "amd64-dw" , Run_environment.Example.qemu_amd64_darwin , "Qemu x86_64 with Darwin 8 (old Mac OSX)." ) ] in let set_example arg = match !example with | Some _ -> fail "Too many arguments (%S)!" arg | None -> example := Some ( match List.find_map examples ~f:(fun (e, v, _) -> if String.(e = arg) then Some v else None ) with | Some s -> s | None -> fail "Don't know VM %S" arg ) in let module Arg = Caml.Arg in let args = Arg.align [ ( "--ssh-port" , Arg.Int (fun s -> ssh_port := s) , Fmt.str "<int> Set the SSH-port (default: %d)." !ssh_port ) ; ( "--vm" , Arg.String set_example , Fmt.str "<name> The Name of the VM, one of:\n%s" (String.concat ~sep:"\n" (List.map ~f:(fun (n, _, d) -> Fmt.str "%s* `%s`: %s" (String.make 25 ' ') n d ) examples ) ) ) ; ( "--copy" , Arg.String (fun s -> let add p lp = let local_rel = String.map p ~f:(function '/' -> '_' | c -> c) in copy_directories := (p, local_rel, lp) :: !copy_directories in match Base.String.split ~on:':' s with | [] | [_] -> fail "Error in --copy: need a `:` separator (%S)" s | [p; lp] -> add p lp | p :: more -> add p (String.concat ~sep:":" more) ) , "<p-src:p-dst> Copy <p-src> in the output directory and add its \ upload to the VM to the `make setup` target as a relative path \ <p-dst>." ) ] in let usage = Fmt.str "vm-tester --vm <vm-name> <path>" in let anon arg = match !path with | Some _ -> fail "Too many arguments (%S)!" arg | None -> path := Some arg in Arg.parse args anon usage ; let more_setup = List.map !copy_directories ~f:(fun (_, locrel, hostp) -> Run_environment.Setup.copy (`Relative locrel) (`Relative hostp) ) in let re = match !example with | Some e -> e ~ssh_port:!ssh_port more_setup | None -> fail "Missing VM name\nUsage: %s" usage in let content = Run_environment.setup_dir_content re in let path = match !path with | Some p -> p | None -> fail "Missing path!\nUsage: %s" usage in List.iter content ~f:(fun (filepath, content) -> let full = path // filepath in cmdf "mkdir -p %s" (Filename.dirname full) ; write_lines full content ) ; List.iter !copy_directories ~f:(fun (p, local_rel, _) -> cmdf "rsync -az %s %s/%s" p path local_rel )
595ffa152d18417eae0e52d7acffd1e015cbe27b1f7951bdb3697b26a401a204
kostyushkin/erlworld
color.erl
%%% Color %%% @author %%% @doc %%% Defines how to create colours and how to retrieve the values from colours. %%% Colours are stored as a tuple in the form {red, green, blue, alpha}. All %%% components are floats. %%% %%% By using this file it allows the user to abstract away how they care about %%% colours. %%% %%% It also contains common colours for you to use. %%% -module(color). -export([ new/3, new/4 ]). -export([ get_red/1, get_green/1, get_blue/1, get_alpha/1 ]). -export([ white/0, grey/0, black/0, red/0, green/0, blue/0, yellow/0, orange/0, pink/0, purple/0 ]). %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Constructors %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %% new %% @doc Creates and returns a new Color object with full alpha . @spec new ( Red::float ( ) , Green::float ( ) , ( ) ) - > Color::color ( ) new(Red, Green, Blue) -> new( Red, Green, Blue, 1.0 ). %% new %% @doc Creates and returns a new Color object . @spec new ( Red::float ( ) , Green::float ( ) , ( ) , Alpha::float ( ) ) - > Color::color ( ) new(Red, Green, Blue, Alpha) -> { Red, Green, Blue, Alpha }. %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Interactions %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %% get_red %% %% @doc Returns the red component from the given colour. @spec get_red ( Color::color ( ) ) - > Red::float ( ) get_red ({ Red, _green, _blue, _alpha }) -> Red. %% get_green %% %% @doc Returns the green component from the given colour. get_green ( Color::color ( ) ) - > Green::float ( ) get_green ({ _red, Green, _blue, _alpha }) -> Green. %% get_blue %% %% @doc Returns the blue component from the given colour. ( Color::color ( ) ) - > Blue::float ( ) get_blue ({ _red, _green, Blue, _alpha }) -> Blue. %% get_alpha %% %% @doc Returns the alpha component from the given colour. ( Color::color ( ) ) - > Alpha::float ( ) get_alpha ({ _red, _green, _blue, Alpha }) -> Alpha. %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Common Colours %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %% white %% %% @doc A predefined color, white. %% @spec white() -> White::color() white() -> new(1.0, 1.0, 1.0). %% grey %% %% @doc A predefined color, grey. ( ) - > ( ) grey() -> new(0.5, 0.5, 0.5). %% black %% %% @doc A predefined color, black. %% @spec black() -> Black::color() black() -> new(0.0, 0.0, 0.0). %% red %% %% @doc A predefined color, red. red ( ) - > Red::color ( ) red() -> new(1.0, 0.0, 0.0). %% green %% %% @doc A predefined color, green. @spec green ( ) - > Green::color ( ) green() -> new(0.0, 1.0, 0.0). %% blue %% %% @doc A predefined color, blue. blue ( ) - > Blue::color ( ) blue() -> new(0.0, 0.0, 1.0). %% yellow %% %% @doc A predefined color, yellow. yellow ( ) - > Yellow::color ( ) yellow() -> new(1.0, 1.0, 0.0). %% orange %% %% @doc A predefined color, orange. %% @spec orange() -> Orange::color() orange() -> new(1.0, 0.5, 0.0). %% pink %% %% @doc A predefined color, pink. pink ( ) - > Pink::color ( ) pink() -> new(1.0, 0.75, 0.796). %% purple %% %% @doc A predefined color, purple. ( ) - > Purple::color ( ) purple() -> new(0.5, 0.0, 0.5).
null
https://raw.githubusercontent.com/kostyushkin/erlworld/1c55c9eb0d12db9824144b4ff7535960c53e35c8/src/color.erl
erlang
@doc Defines how to create colours and how to retrieve the values from colours. Colours are stored as a tuple in the form {red, green, blue, alpha}. All components are floats. By using this file it allows the user to abstract away how they care about colours. It also contains common colours for you to use. %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Constructors %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% new new %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Interactions %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% get_red @doc Returns the red component from the given colour. get_green @doc Returns the green component from the given colour. get_blue @doc Returns the blue component from the given colour. get_alpha @doc Returns the alpha component from the given colour. %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Common Colours %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% white @doc A predefined color, white. @spec white() -> White::color() grey @doc A predefined color, grey. black @doc A predefined color, black. @spec black() -> Black::color() red @doc A predefined color, red. green @doc A predefined color, green. blue @doc A predefined color, blue. yellow @doc A predefined color, yellow. orange @doc A predefined color, orange. @spec orange() -> Orange::color() pink @doc A predefined color, pink. purple @doc A predefined color, purple.
Color @author -module(color). -export([ new/3, new/4 ]). -export([ get_red/1, get_green/1, get_blue/1, get_alpha/1 ]). -export([ white/0, grey/0, black/0, red/0, green/0, blue/0, yellow/0, orange/0, pink/0, purple/0 ]). @doc Creates and returns a new Color object with full alpha . @spec new ( Red::float ( ) , Green::float ( ) , ( ) ) - > Color::color ( ) new(Red, Green, Blue) -> new( Red, Green, Blue, 1.0 ). @doc Creates and returns a new Color object . @spec new ( Red::float ( ) , Green::float ( ) , ( ) , Alpha::float ( ) ) - > Color::color ( ) new(Red, Green, Blue, Alpha) -> { Red, Green, Blue, Alpha }. @spec get_red ( Color::color ( ) ) - > Red::float ( ) get_red ({ Red, _green, _blue, _alpha }) -> Red. get_green ( Color::color ( ) ) - > Green::float ( ) get_green ({ _red, Green, _blue, _alpha }) -> Green. ( Color::color ( ) ) - > Blue::float ( ) get_blue ({ _red, _green, Blue, _alpha }) -> Blue. ( Color::color ( ) ) - > Alpha::float ( ) get_alpha ({ _red, _green, _blue, Alpha }) -> Alpha. white() -> new(1.0, 1.0, 1.0). ( ) - > ( ) grey() -> new(0.5, 0.5, 0.5). black() -> new(0.0, 0.0, 0.0). red ( ) - > Red::color ( ) red() -> new(1.0, 0.0, 0.0). @spec green ( ) - > Green::color ( ) green() -> new(0.0, 1.0, 0.0). blue ( ) - > Blue::color ( ) blue() -> new(0.0, 0.0, 1.0). yellow ( ) - > Yellow::color ( ) yellow() -> new(1.0, 1.0, 0.0). orange() -> new(1.0, 0.5, 0.0). pink ( ) - > Pink::color ( ) pink() -> new(1.0, 0.75, 0.796). ( ) - > Purple::color ( ) purple() -> new(0.5, 0.0, 0.5).
0c46edbc89992ed3503e62e791caa1833ee885747f0934d89a4b878eb5fe8472
realworldocaml/book
nativeint.ml
* [ count_leading_zeros n ] returns the number of most - significant zero bits before the most significant set bit in [ n ] . If [ n ] is 0 , the result is the number of bits in [ n ] , that is 32 or 64 , depending on the target . zero bits before the most significant set bit in [n]. If [n] is 0, the result is the number of bits in [n], that is 32 or 64, depending on the target. *) external count_leading_zeros : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_clz" "caml_nativeint_clz_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * Same as [ count_leading_zeros ] except if the argument is zero , then the result is undefined . Emits more efficient code . then the result is undefined. Emits more efficient code. *) external count_leading_zeros_nonzero_arg : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_clz" "caml_nativeint_clz_nonzero_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * [ count_trailing_zeros n ] returns the number of least - significant zero bits before the least significant set bit in [ n ] . If [ n ] is 0 , the result is the number of bits in [ n ] , that is 32 or 64 , depending on the target . zero bits before the least significant set bit in [n]. If [n] is 0, the result is the number of bits in [n], that is 32 or 64, depending on the target. *) external count_trailing_zeros : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_ctz" "caml_nativeint_ctz_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * Same as [ count_trailing_zeros ] except if the argument is zero , then the result is undefined . Emits more efficient code . then the result is undefined. Emits more efficient code. *) external count_trailing_zeros_nonzero_arg : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_ctz" "caml_nativeint_ctz_nonzero_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * [ count_set_bits n ] returns the number of bits that are 1 in [ n ] . external count_set_bits : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_popcnt" "caml_nativeint_popcnt_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects]
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ocaml_intrinsics/src/nativeint.ml
ocaml
* [ count_leading_zeros n ] returns the number of most - significant zero bits before the most significant set bit in [ n ] . If [ n ] is 0 , the result is the number of bits in [ n ] , that is 32 or 64 , depending on the target . zero bits before the most significant set bit in [n]. If [n] is 0, the result is the number of bits in [n], that is 32 or 64, depending on the target. *) external count_leading_zeros : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_clz" "caml_nativeint_clz_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * Same as [ count_leading_zeros ] except if the argument is zero , then the result is undefined . Emits more efficient code . then the result is undefined. Emits more efficient code. *) external count_leading_zeros_nonzero_arg : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_clz" "caml_nativeint_clz_nonzero_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * [ count_trailing_zeros n ] returns the number of least - significant zero bits before the least significant set bit in [ n ] . If [ n ] is 0 , the result is the number of bits in [ n ] , that is 32 or 64 , depending on the target . zero bits before the least significant set bit in [n]. If [n] is 0, the result is the number of bits in [n], that is 32 or 64, depending on the target. *) external count_trailing_zeros : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_ctz" "caml_nativeint_ctz_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * Same as [ count_trailing_zeros ] except if the argument is zero , then the result is undefined . Emits more efficient code . then the result is undefined. Emits more efficient code. *) external count_trailing_zeros_nonzero_arg : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_ctz" "caml_nativeint_ctz_nonzero_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects] * [ count_set_bits n ] returns the number of bits that are 1 in [ n ] . external count_set_bits : (nativeint[@unboxed]) -> (int[@untagged]) = "caml_nativeint_popcnt" "caml_nativeint_popcnt_unboxed_to_untagged" [@@noalloc] [@@builtin] [@@no_effects] [@@no_coeffects]
ffd0ec72b67ec7bd3dd73ebb83612adcde32b2275e7559525cdaea2d8d93f6a2
dbuenzli/stdlib-utf
utf_x_dfa.ml
(**************************************************************************) (* *) (* OCaml *) (* *) (* The OCaml programmers *) (* *) Copyright 2021 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. *) (* *) (**************************************************************************) module Uchar = Utf_uchar module Bytes = struct include Bytes (* Unsafe internal additions *) external unsafe_set_uint8 : t -> int -> int -> unit = "%bytes_unsafe_set" external unsafe_get_uint8 : t -> int -> int = "%bytes_unsafe_get" UTF - X codecs and validations let dec_invalid = Uchar.utf_decode_invalid let[@inline] dec_ret n u = Uchar.utf_decode n (Uchar.unsafe_of_int u) UTF-8 let utf_8_dfa = The first 256 entries map bytes to their class . Then the DFA follows . The DFA automaton is MIT - licensed Copyright ( c ) 2008 - 2009 . See -8/decoder/dfa/#variations DFA follows. The DFA automaton is MIT-licensed Copyright (c) 2008-2009 Bjoern Hoehrmann. See -8/decoder/dfa/#variations*) unsafe_of_string "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \001\001\001\001\001\001\001\001\001\001\001\001\001\001\001\001\ \009\009\009\009\009\009\009\009\009\009\009\009\009\009\009\009\ \007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\ \007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\ \008\008\002\002\002\002\002\002\002\002\002\002\002\002\002\002\ \002\002\002\002\002\002\002\002\002\002\002\002\002\002\002\002\ \010\003\003\003\003\003\003\003\003\003\003\003\003\004\003\003\ \011\006\006\006\005\008\008\008\008\008\008\008\008\008\008\008\ \000\012\024\036\060\096\084\012\012\012\048\072\ \012\012\012\012\012\012\012\012\012\012\012\012\ \012\000\012\012\012\012\012\000\012\000\012\012\ \012\024\012\012\012\012\012\024\012\024\012\012\ \012\012\012\012\012\012\012\024\012\012\012\012\ \012\024\012\012\012\012\012\012\012\024\012\012\ \012\012\012\012\012\012\012\036\012\036\012\012\ \012\036\012\012\012\012\012\036\012\036\012\012\ \012\036\012\012\012\012\012\012\012\012\012\012" let accept = 0 let reject = 12 Rewriting the following as an imperative loop is uglier but more efficient . let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > then invalid_arg " index out of bounds " else let rec loop st u j = if j > max then dec_err ( j - i ) else let byte = unsafe_get_uint8 b j in let class ' = unsafe_get_uint8 utf_8_dfa byte in let u ' = if st < > accept then ( u lsl 6 ) lor ( byte land 0x3F ) else byte land ( 0xFF lsr class ' ) in let st ' = unsafe_get_uint8 utf_8_dfa ( 256 + st + class ' ) in if st ' = reject then dec_err ( j - i + 1 ) else if st ' = accept then dec_ret ( j - i + 1 ) u ' else loop st ' u ' ( j + 1 ) in loop accept 0 i more efficient. let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > max then invalid_arg "index out of bounds" else let rec loop st u j = if j > max then dec_err (j - i) else let byte = unsafe_get_uint8 b j in let class' = unsafe_get_uint8 utf_8_dfa byte in let u' = if st <> accept then (u lsl 6) lor (byte land 0x3F) else byte land (0xFF lsr class') in let st' = unsafe_get_uint8 utf_8_dfa (256 + st + class') in if st' = reject then dec_err (j - i + 1) else if st' = accept then dec_ret (j - i + 1) u' else loop st' u' (j + 1) in loop accept 0 i *) let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > max then invalid_arg "index out of bounds" else let stop = ref false in let st = ref accept in let j = ref i in let u = ref 0 in while (not !stop) do let byte = unsafe_get_uint8 b !j in let class' = unsafe_get_uint8 utf_8_dfa byte in u := (if !st <> accept then (!u lsl 6) lor (byte land 0x3F) else byte land (0xFF lsr class')); st := unsafe_get_uint8 utf_8_dfa (256 + !st + class'); if (!st = reject || !st = accept) then stop := true else (incr j; if !j > max then stop := true); done; if !j > max then dec_invalid (!j - i) else if !st = accept then dec_ret (!j - i + 1) !u else if !st = reject then dec_invalid (if i = !j then 1 else (!j - i)) else assert false let set_utf_8_uchar b i u = let set = unsafe_set_uint8 in let max = length b - 1 in match Uchar.to_int u with | u when u <= 0x007F -> set_uint8 b i u; 1 | u when u <= 0x07FF -> let last = i + 1 in if last > max then 0 else (set_uint8 b i (0xC0 lor (u lsr 6)); set b last (0x80 lor (u land 0x3F)); 2) | u when u <= 0xFFFF -> let last = i + 2 in if last > max then 0 else (set_uint8 b i (0xE0 lor (u lsr 12)); set b (i + 1) (0x80 lor ((u lsr 6) land 0x3F)); set b last (0x80 lor (u land 0x3F)); 3) | u -> let last = i + 3 in if last > max then 0 else (set_uint8 b i (0xF0 lor (u lsr 18)); set b (i + 1) (0x80 lor ((u lsr 12) land 0x3F)); set b (i + 2) (0x80 lor ((u lsr 6) land 0x3F)); set b last (0x80 lor (u land 0x3F)); 4) let is_valid_utf_8 b = (* This could be optimized using the state machine. We didn't do it for now since it seems the adhoc implementation yields better perfs. *) let rec loop b i = if i >= length b then true else let dec = get_utf_8_uchar b i in if Uchar.utf_decode_is_valid dec then loop b (i + Uchar.utf_decode_length dec) else false in loop b 0 include Utf_16 end
null
https://raw.githubusercontent.com/dbuenzli/stdlib-utf/9e931944697ff6b48a54a10b425a9acdbd4ccb40/utf_x_dfa.ml
ocaml
************************************************************************ OCaml The OCaml programmers en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Unsafe internal additions This could be optimized using the state machine. We didn't do it for now since it seems the adhoc implementation yields better perfs.
Copyright 2021 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the module Uchar = Utf_uchar module Bytes = struct include Bytes external unsafe_set_uint8 : t -> int -> int -> unit = "%bytes_unsafe_set" external unsafe_get_uint8 : t -> int -> int = "%bytes_unsafe_get" UTF - X codecs and validations let dec_invalid = Uchar.utf_decode_invalid let[@inline] dec_ret n u = Uchar.utf_decode n (Uchar.unsafe_of_int u) UTF-8 let utf_8_dfa = The first 256 entries map bytes to their class . Then the DFA follows . The DFA automaton is MIT - licensed Copyright ( c ) 2008 - 2009 . See -8/decoder/dfa/#variations DFA follows. The DFA automaton is MIT-licensed Copyright (c) 2008-2009 Bjoern Hoehrmann. See -8/decoder/dfa/#variations*) unsafe_of_string "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \001\001\001\001\001\001\001\001\001\001\001\001\001\001\001\001\ \009\009\009\009\009\009\009\009\009\009\009\009\009\009\009\009\ \007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\ \007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\007\ \008\008\002\002\002\002\002\002\002\002\002\002\002\002\002\002\ \002\002\002\002\002\002\002\002\002\002\002\002\002\002\002\002\ \010\003\003\003\003\003\003\003\003\003\003\003\003\004\003\003\ \011\006\006\006\005\008\008\008\008\008\008\008\008\008\008\008\ \000\012\024\036\060\096\084\012\012\012\048\072\ \012\012\012\012\012\012\012\012\012\012\012\012\ \012\000\012\012\012\012\012\000\012\000\012\012\ \012\024\012\012\012\012\012\024\012\024\012\012\ \012\012\012\012\012\012\012\024\012\012\012\012\ \012\024\012\012\012\012\012\012\012\024\012\012\ \012\012\012\012\012\012\012\036\012\036\012\012\ \012\036\012\012\012\012\012\036\012\036\012\012\ \012\036\012\012\012\012\012\012\012\012\012\012" let accept = 0 let reject = 12 Rewriting the following as an imperative loop is uglier but more efficient . let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > then invalid_arg " index out of bounds " else let rec loop st u j = if j > max then dec_err ( j - i ) else let byte = unsafe_get_uint8 b j in let class ' = unsafe_get_uint8 utf_8_dfa byte in let u ' = if st < > accept then ( u lsl 6 ) lor ( byte land 0x3F ) else byte land ( 0xFF lsr class ' ) in let st ' = unsafe_get_uint8 utf_8_dfa ( 256 + st + class ' ) in if st ' = reject then dec_err ( j - i + 1 ) else if st ' = accept then dec_ret ( j - i + 1 ) u ' else loop st ' u ' ( j + 1 ) in loop accept 0 i more efficient. let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > max then invalid_arg "index out of bounds" else let rec loop st u j = if j > max then dec_err (j - i) else let byte = unsafe_get_uint8 b j in let class' = unsafe_get_uint8 utf_8_dfa byte in let u' = if st <> accept then (u lsl 6) lor (byte land 0x3F) else byte land (0xFF lsr class') in let st' = unsafe_get_uint8 utf_8_dfa (256 + st + class') in if st' = reject then dec_err (j - i + 1) else if st' = accept then dec_ret (j - i + 1) u' else loop st' u' (j + 1) in loop accept 0 i *) let get_utf_8_uchar b i = let max = length b - 1 in if i < 0 || i > max then invalid_arg "index out of bounds" else let stop = ref false in let st = ref accept in let j = ref i in let u = ref 0 in while (not !stop) do let byte = unsafe_get_uint8 b !j in let class' = unsafe_get_uint8 utf_8_dfa byte in u := (if !st <> accept then (!u lsl 6) lor (byte land 0x3F) else byte land (0xFF lsr class')); st := unsafe_get_uint8 utf_8_dfa (256 + !st + class'); if (!st = reject || !st = accept) then stop := true else (incr j; if !j > max then stop := true); done; if !j > max then dec_invalid (!j - i) else if !st = accept then dec_ret (!j - i + 1) !u else if !st = reject then dec_invalid (if i = !j then 1 else (!j - i)) else assert false let set_utf_8_uchar b i u = let set = unsafe_set_uint8 in let max = length b - 1 in match Uchar.to_int u with | u when u <= 0x007F -> set_uint8 b i u; 1 | u when u <= 0x07FF -> let last = i + 1 in if last > max then 0 else (set_uint8 b i (0xC0 lor (u lsr 6)); set b last (0x80 lor (u land 0x3F)); 2) | u when u <= 0xFFFF -> let last = i + 2 in if last > max then 0 else (set_uint8 b i (0xE0 lor (u lsr 12)); set b (i + 1) (0x80 lor ((u lsr 6) land 0x3F)); set b last (0x80 lor (u land 0x3F)); 3) | u -> let last = i + 3 in if last > max then 0 else (set_uint8 b i (0xF0 lor (u lsr 18)); set b (i + 1) (0x80 lor ((u lsr 12) land 0x3F)); set b (i + 2) (0x80 lor ((u lsr 6) land 0x3F)); set b last (0x80 lor (u land 0x3F)); 4) let is_valid_utf_8 b = let rec loop b i = if i >= length b then true else let dec = get_utf_8_uchar b i in if Uchar.utf_decode_is_valid dec then loop b (i + Uchar.utf_decode_length dec) else false in loop b 0 include Utf_16 end
068ffbd36e8d3e6afa55816c2ae528f59a541e15de9dc30540cd381f0c3d908f
tek/ribosome
NewOptions.hs
module Ribosome.App.NewOptions where import Path (Dir, Path, Rel, parseRelDir) import Rainbow (chunk, fore, magenta) import qualified Ribosome.App.Data as Data import Ribosome.App.Data (FlakeUrl, NewProject (NewProject)) import Ribosome.App.Error (RainbowError, appError) import Ribosome.App.Options (NewOptions) import Ribosome.App.ProjectOptions (projectOptions) import Ribosome.App.UserInput (askRequired) defaultFlakeUrl :: FlakeUrl defaultFlakeUrl = "git+" parseDir :: ToText a => ToString a => Member (Stop RainbowError) r => a -> Sem r (Path Rel Dir) parseDir name = stopNote invalidName (parseRelDir (toString name)) where invalidName = appError [fore magenta (chunk (toText name)), " cannot be used as a directory name."] newOptions :: Members [Stop RainbowError, Embed IO] r => NewOptions -> Sem r NewProject newOptions opts = do project <- projectOptions True (opts ^. #project) author <- maybe (askRequired "Author name for Cabal file?") pure (opts ^. #author) maintainer <- maybe (askRequired "Maintainer email for Cabal file?") pure (opts ^. #maintainer) let flakeUrl = fromMaybe defaultFlakeUrl (opts ^. #flakeUrl) printDir = opts ^. #printDir pure NewProject {..}
null
https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/app/lib/Ribosome/App/NewOptions.hs
haskell
module Ribosome.App.NewOptions where import Path (Dir, Path, Rel, parseRelDir) import Rainbow (chunk, fore, magenta) import qualified Ribosome.App.Data as Data import Ribosome.App.Data (FlakeUrl, NewProject (NewProject)) import Ribosome.App.Error (RainbowError, appError) import Ribosome.App.Options (NewOptions) import Ribosome.App.ProjectOptions (projectOptions) import Ribosome.App.UserInput (askRequired) defaultFlakeUrl :: FlakeUrl defaultFlakeUrl = "git+" parseDir :: ToText a => ToString a => Member (Stop RainbowError) r => a -> Sem r (Path Rel Dir) parseDir name = stopNote invalidName (parseRelDir (toString name)) where invalidName = appError [fore magenta (chunk (toText name)), " cannot be used as a directory name."] newOptions :: Members [Stop RainbowError, Embed IO] r => NewOptions -> Sem r NewProject newOptions opts = do project <- projectOptions True (opts ^. #project) author <- maybe (askRequired "Author name for Cabal file?") pure (opts ^. #author) maintainer <- maybe (askRequired "Maintainer email for Cabal file?") pure (opts ^. #maintainer) let flakeUrl = fromMaybe defaultFlakeUrl (opts ^. #flakeUrl) printDir = opts ^. #printDir pure NewProject {..}
dad9beac486ea458e578914e7a989f46713a4f019a901339ec33b112670c04ba
OCADml/OCADml
pathMatch.ml
module type CUTPOINT_DEPS = sig type vec type line val centroid : ?eps:float -> vec list -> vec val closest_tangent : ?closed:bool -> ?offset:vec -> line:line -> vec list -> int * line end module type S = sig type vec (** [distance_match a b] If the closed polygonal paths [a] and [b] have incommensurate lengths, points on the smaller path are duplicated and the larger path is shifted (list rotated) in such a way that the total length of the edges between the associated vertices (same index/position) is minimized. The replacement paths, now having the same lengths, are returned as a pair (with the same order). This algorithm generally produces a good result when both [a] and [b] are discrete profiles with a small number of vertices. This is computationally intensive ( {b O(N{^ 3})} ), if the profiles are already known to be lined up, with their zeroth indices corresponding, then {!aligned_distance_match} provides a ( {b O(N{^ 2})} ) solution. *) val distance_match : vec list -> vec list -> vec list * vec list * [ aligned_distance_match a b ] Like { ! distance_match } , but the paths [ a ] and [ b ] are assumed to already be " lined up " , with the zeroth indices in each corresponding to one another . Like {!distance_match}, but the paths [a] and [b] are assumed to already be "lined up", with the zeroth indices in each corresponding to one another. *) val aligned_distance_match : vec list -> vec list -> vec list * vec list (** [tangent_match a b] If the closed polygonal paths [a] and [b] have incommensurate lengths, points on the larger (ideally convex, curved) path are grouped by association of their tangents with the edges of the smaller (ideally discrete) polygonal path. The points of the smaller path are then duplicated to associate with their corresponding spans of tangents on the curve, and the larger path is rotated to line up the indices. The profiles, now having the same length are returned as a pair in the order that they were applied returned. This algorithm generally produces good results when connecting a discrete polygon to a {i convex} finely sampled curve. It may fail if the curved profile is non-convex, or doesn't have enough points to distinguish all of the tangent points from each other. *) val tangent_match : vec list -> vec list -> vec list * vec list end module Make (V : V.S) (P : CUTPOINT_DEPS with type vec := V.t and type line := V.line) = struct type dp_map_dir = | Diag (* map the next vertex of [big] to the next vertex of [small] *) | Left (* map the next vertex of [big] to the current vertex of [small] *) | Up (* map the next vertex of [small] to the current vertex of [big] *) Construct a matrix of shape ( [ len_small ] x [ len_big ] ) with mappings between the points of the polygons [ small ] and [ big ] . points of the polygons [small] and [big]. *) let dp_distance_array ?(abort_thresh = Float.infinity) small big = let len_small = Array.length small and len_big = Array.length big in let small_idx = ref 1 and total_dist = let a = Array.make (len_big + 1) 0. in for i = 1 to len_big do a.(i) <- a.(i - 1) +. V.distance big.(i mod len_big) small.(0) done; a and dist_row = Array.make (len_big + 1) 0. (* current row, reused each iter *) and min_cost = ref 0. (* minimum cost of current dist_row, break above threshold *) and dir_map = Array.init (len_small + 1) (fun _ -> Array.make (len_big + 1) Left) in while !small_idx < len_small + 1 do min_cost := V.distance big.(0) small.(!small_idx mod len_small) +. total_dist.(0); dist_row.(0) <- !min_cost; dir_map.(!small_idx).(0) <- Up; for big_idx = 1 to len_big do let cost, dir = let diag = total_dist.(big_idx - 1) and left = dist_row.(big_idx - 1) and up = total_dist.(big_idx) in if up < diag && up < left then up, Up else if left < diag && left <= up then left, Left (* favoured in tie with up *) smallest , tied with left , or three - way and d = V.distance big.(big_idx mod len_big) small.(!small_idx mod len_small) in dist_row.(big_idx) <- cost +. d; dir_map.(!small_idx).(big_idx) <- dir; if dist_row.(big_idx) < !min_cost then min_cost := dist_row.(big_idx) done; (* dump current row of distances as new totals *) Array.blit dist_row 0 total_dist 0 (len_big + 1); (* Break out early if minimum cost for this combination of small/big is above the threshold. The map matrix is incomplete, but it will not be used anyway. *) small_idx := if !min_cost > abort_thresh then len_small + 1 else !small_idx + 1 done; total_dist.(len_big), dir_map (* Produce ascending lists of indices (with repeats) for the small and big polygons that should be used to reconstruct the polygons with the point duplications required to associate the vertices between them. *) let dp_extract_map m = let len_small = Array.length m - 1 and len_big = Array.length m.(0) - 1 in let rec loop i j small_map big_map = let i, j = match m.(i).(j) with | Diag -> i - 1, j - 1 | Left -> i, j - 1 | Up -> i - 1, j in let small_map = (i mod len_small) :: small_map and big_map = (j mod len_big) :: big_map in if i = 0 && j = 0 then small_map, big_map else loop i j small_map big_map in loop len_small len_big [] [] Duplicate points according to mappings and shift the new polygon ( rotating its the point list ) to handle the case when points from both ends of one curve map to a single point on the other . its the point list) to handle the case when points from both ends of one curve map to a single point on the other. *) let dp_apply_map_and_shift map poly = let shift = (* the mapping lists are already sorted in ascending order *) let last_max_idx l = let f (i, max, idx) v = if v >= max then i + 1, v, i else i + 1, max, idx in List.fold_left f (0, 0, 0) l in let len, _, idx = last_max_idx map in len - idx - 1 and len = Array.length poly in let f i acc = poly.((i + shift) mod len) :: acc in List.fold_right f map [] let distance_match a b = let a = Array.of_list a and b = Array.of_list b in let swap = Array.length a > Array.length b in let small, big = if swap then b, a else a, b in let map, shifted_big = let len_big = Array.length big in let rec find_best cost map poly i = let shifted = Array.init len_big (fun j -> big.(Util.index_wrap ~len:len_big (i + j))) in let cost', map' = dp_distance_array ~abort_thresh:cost small shifted in let cost, map, poly = if cost' < cost then cost', map', shifted else cost, map, poly in if i < len_big then find_best cost map poly (i + 1) else map, poly in let cost, map = dp_distance_array small big in find_best cost map big 1 in let small_map, big_map = dp_extract_map map in let small' = dp_apply_map_and_shift small_map small and big' = dp_apply_map_and_shift big_map shifted_big in if swap then big', small' else small', big' let aligned_distance_match a b = let a = Array.of_list a and b = Array.of_list b in let a_map, b_map = dp_extract_map @@ snd @@ dp_distance_array a b in let a' = dp_apply_map_and_shift a_map a and b' = dp_apply_map_and_shift b_map b in a', b' let tangent_match a b = let a' = Array.of_list a and b' = Array.of_list b in let swap = Array.length a' > Array.length b' in let small, big = if swap then b', a' else a', b' in let len_small = Array.length small and len_big = Array.length big in let cut_pts = let sm, bg = if swap then b, a else a, b in Array.init len_small (fun i -> fst @@ P.closest_tangent ~offset:P.(V.sub (centroid sm) (centroid bg)) ~line:V.{ a = small.(i); b = small.((i + 1) mod len_small) } bg ) in let len_duped, duped_small = let f i (len, pts) = let count = let a = cut_pts.(i) and b = cut_pts.(Util.index_wrap ~len:len_small (i - 1)) in Math.posmod (a - b) len_big in ( len + count , Util.fold_init count (fun _ pts -> small.(len_small - 1 - i) :: pts) pts ) in Util.fold_init len_small f (0, []) and shifted_big = let shift = cut_pts.(len_small - 1) + 1 in List.init len_big (fun i -> big.((shift + i) mod len_big)) in if len_duped <> len_big then failwith "Tangent alignment failed, likely due to insufficient points or a concave curve."; if swap then shifted_big, duped_small else duped_small, shifted_big end
null
https://raw.githubusercontent.com/OCADml/OCADml/ceed2bfce640667580f7286b46864a69cdc1d4d7/lib/pathMatch.ml
ocaml
* [distance_match a b] If the closed polygonal paths [a] and [b] have incommensurate lengths, points on the smaller path are duplicated and the larger path is shifted (list rotated) in such a way that the total length of the edges between the associated vertices (same index/position) is minimized. The replacement paths, now having the same lengths, are returned as a pair (with the same order). This algorithm generally produces a good result when both [a] and [b] are discrete profiles with a small number of vertices. This is computationally intensive ( {b O(N{^ 3})} ), if the profiles are already known to be lined up, with their zeroth indices corresponding, then {!aligned_distance_match} provides a ( {b O(N{^ 2})} ) solution. * [tangent_match a b] If the closed polygonal paths [a] and [b] have incommensurate lengths, points on the larger (ideally convex, curved) path are grouped by association of their tangents with the edges of the smaller (ideally discrete) polygonal path. The points of the smaller path are then duplicated to associate with their corresponding spans of tangents on the curve, and the larger path is rotated to line up the indices. The profiles, now having the same length are returned as a pair in the order that they were applied returned. This algorithm generally produces good results when connecting a discrete polygon to a {i convex} finely sampled curve. It may fail if the curved profile is non-convex, or doesn't have enough points to distinguish all of the tangent points from each other. map the next vertex of [big] to the next vertex of [small] map the next vertex of [big] to the current vertex of [small] map the next vertex of [small] to the current vertex of [big] current row, reused each iter minimum cost of current dist_row, break above threshold favoured in tie with up dump current row of distances as new totals Break out early if minimum cost for this combination of small/big is above the threshold. The map matrix is incomplete, but it will not be used anyway. Produce ascending lists of indices (with repeats) for the small and big polygons that should be used to reconstruct the polygons with the point duplications required to associate the vertices between them. the mapping lists are already sorted in ascending order
module type CUTPOINT_DEPS = sig type vec type line val centroid : ?eps:float -> vec list -> vec val closest_tangent : ?closed:bool -> ?offset:vec -> line:line -> vec list -> int * line end module type S = sig type vec val distance_match : vec list -> vec list -> vec list * vec list * [ aligned_distance_match a b ] Like { ! distance_match } , but the paths [ a ] and [ b ] are assumed to already be " lined up " , with the zeroth indices in each corresponding to one another . Like {!distance_match}, but the paths [a] and [b] are assumed to already be "lined up", with the zeroth indices in each corresponding to one another. *) val aligned_distance_match : vec list -> vec list -> vec list * vec list val tangent_match : vec list -> vec list -> vec list * vec list end module Make (V : V.S) (P : CUTPOINT_DEPS with type vec := V.t and type line := V.line) = struct type dp_map_dir = Construct a matrix of shape ( [ len_small ] x [ len_big ] ) with mappings between the points of the polygons [ small ] and [ big ] . points of the polygons [small] and [big]. *) let dp_distance_array ?(abort_thresh = Float.infinity) small big = let len_small = Array.length small and len_big = Array.length big in let small_idx = ref 1 and total_dist = let a = Array.make (len_big + 1) 0. in for i = 1 to len_big do a.(i) <- a.(i - 1) +. V.distance big.(i mod len_big) small.(0) done; a and dir_map = Array.init (len_small + 1) (fun _ -> Array.make (len_big + 1) Left) in while !small_idx < len_small + 1 do min_cost := V.distance big.(0) small.(!small_idx mod len_small) +. total_dist.(0); dist_row.(0) <- !min_cost; dir_map.(!small_idx).(0) <- Up; for big_idx = 1 to len_big do let cost, dir = let diag = total_dist.(big_idx - 1) and left = dist_row.(big_idx - 1) and up = total_dist.(big_idx) in if up < diag && up < left then up, Up else if left < diag && left <= up smallest , tied with left , or three - way and d = V.distance big.(big_idx mod len_big) small.(!small_idx mod len_small) in dist_row.(big_idx) <- cost +. d; dir_map.(!small_idx).(big_idx) <- dir; if dist_row.(big_idx) < !min_cost then min_cost := dist_row.(big_idx) done; Array.blit dist_row 0 total_dist 0 (len_big + 1); small_idx := if !min_cost > abort_thresh then len_small + 1 else !small_idx + 1 done; total_dist.(len_big), dir_map let dp_extract_map m = let len_small = Array.length m - 1 and len_big = Array.length m.(0) - 1 in let rec loop i j small_map big_map = let i, j = match m.(i).(j) with | Diag -> i - 1, j - 1 | Left -> i, j - 1 | Up -> i - 1, j in let small_map = (i mod len_small) :: small_map and big_map = (j mod len_big) :: big_map in if i = 0 && j = 0 then small_map, big_map else loop i j small_map big_map in loop len_small len_big [] [] Duplicate points according to mappings and shift the new polygon ( rotating its the point list ) to handle the case when points from both ends of one curve map to a single point on the other . its the point list) to handle the case when points from both ends of one curve map to a single point on the other. *) let dp_apply_map_and_shift map poly = let shift = let last_max_idx l = let f (i, max, idx) v = if v >= max then i + 1, v, i else i + 1, max, idx in List.fold_left f (0, 0, 0) l in let len, _, idx = last_max_idx map in len - idx - 1 and len = Array.length poly in let f i acc = poly.((i + shift) mod len) :: acc in List.fold_right f map [] let distance_match a b = let a = Array.of_list a and b = Array.of_list b in let swap = Array.length a > Array.length b in let small, big = if swap then b, a else a, b in let map, shifted_big = let len_big = Array.length big in let rec find_best cost map poly i = let shifted = Array.init len_big (fun j -> big.(Util.index_wrap ~len:len_big (i + j))) in let cost', map' = dp_distance_array ~abort_thresh:cost small shifted in let cost, map, poly = if cost' < cost then cost', map', shifted else cost, map, poly in if i < len_big then find_best cost map poly (i + 1) else map, poly in let cost, map = dp_distance_array small big in find_best cost map big 1 in let small_map, big_map = dp_extract_map map in let small' = dp_apply_map_and_shift small_map small and big' = dp_apply_map_and_shift big_map shifted_big in if swap then big', small' else small', big' let aligned_distance_match a b = let a = Array.of_list a and b = Array.of_list b in let a_map, b_map = dp_extract_map @@ snd @@ dp_distance_array a b in let a' = dp_apply_map_and_shift a_map a and b' = dp_apply_map_and_shift b_map b in a', b' let tangent_match a b = let a' = Array.of_list a and b' = Array.of_list b in let swap = Array.length a' > Array.length b' in let small, big = if swap then b', a' else a', b' in let len_small = Array.length small and len_big = Array.length big in let cut_pts = let sm, bg = if swap then b, a else a, b in Array.init len_small (fun i -> fst @@ P.closest_tangent ~offset:P.(V.sub (centroid sm) (centroid bg)) ~line:V.{ a = small.(i); b = small.((i + 1) mod len_small) } bg ) in let len_duped, duped_small = let f i (len, pts) = let count = let a = cut_pts.(i) and b = cut_pts.(Util.index_wrap ~len:len_small (i - 1)) in Math.posmod (a - b) len_big in ( len + count , Util.fold_init count (fun _ pts -> small.(len_small - 1 - i) :: pts) pts ) in Util.fold_init len_small f (0, []) and shifted_big = let shift = cut_pts.(len_small - 1) + 1 in List.init len_big (fun i -> big.((shift + i) mod len_big)) in if len_duped <> len_big then failwith "Tangent alignment failed, likely due to insufficient points or a concave curve."; if swap then shifted_big, duped_small else duped_small, shifted_big end
d557c7ebd917cd85efb8cddbfbd912620d69421567c12eeeb0a99ced05f735ad
cedlemo/OCaml-GLib2
test_functions.ml
* Copyright 2017 - 2018 , * This file is part of . * * OCaml - GLib2 is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * any later version . * * OCaml - GLib2 is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with . If not , see < / > . * Copyright 2017-2018 Cedric LE MOIGNE, * This file is part of OCaml-GLib2. * * OCaml-GLib2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * OCaml-GLib2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OCaml-GLib2. If not, see </>. *) open Test_utils open OUnit2 let filter_meaningless_char str = String.split_on_char '\'' str |> String.concat "" |> Str.(split (regexp "\\(\\“\\|\\”\\|\"\\)")) |> String.concat "" let test_glib_check_version test_ctxt = let open Unsigned.UInt32 in let major = of_int32 GLib.Core.c_MAJOR_VERSION in let minor = of_int32 GLib.Core.c_MINOR_VERSION in let micro = of_int32 GLib.Core.c_MICRO_VERSION in match GLib.Core.check_version major minor micro with | None -> assert_equal_string "Ok" "Ok" | Some version_mismatch -> assert_equal_string "version mismatch" version_mismatch let test_filename_to_uri_ok test_ctxt = let path ="/var" in match GLib.Core.filename_to_uri path None with | Error e -> assert_equal_string "This should not " "have been reached" | Ok uri -> match uri with | None -> assert_equal_string "This should not " "have been reached" | Some uri' -> assert_equal_string "file" uri' let test_filename_from_uri_no_hostname test_ctxt = let uri = "file" in match GLib.Core.filename_from_uri uri with | Error e -> assert_equal_string "GError: This should not " "have been reached" | Ok (filename_opt, hostname_opt) -> let _ = match filename_opt with | None -> assert_equal_string "It should " "return a filename" | Some filename -> assert_equal_string "/etc/mpd.conf" filename in match hostname_opt with | None -> assert true | Some h -> assert_equal_string "This should not " "have been reached" let test_filename_to_uri_error test_ctxt = let path ="a_totally_bad_path_that_should_not_exist" in let expected = "The pathname a_totally_bad_path_that_should_not_exist is \ not an absolute path" in let _ = match GLib.Core.filename_to_uri path None with | Error e -> ( match e with | None -> assert_equal_string "This should not " "have been reached" | Some err -> let error_message = Ctypes.(getf (!@ err) GLib.Error.f_message) in assert_equal_string expected (filter_meaningless_char error_message); assert_equal_int32 (Int32.of_int 5) Ctypes.(getf (!@ err) GLib.Error.f_code) ) | Ok uri -> assert_equal_string "This should not " "have been reached" in at_exit Gc.full_major let test_filename_from_uri_bad_uri test_ctxt = let uri = "noprotocoletcmpd.conf" in let expected = "The URI noprotocoletcmpd.conf is not an absolute URI using the file scheme" in match GLib.Core.filename_from_uri uri with | Error e -> ( match e with | None -> assert_equal_string "This should not " "have been reached" | Some err -> let error_message = Ctypes.(getf (!@ err) GLib.Error.f_message) in assert_equal_string expected (filter_meaningless_char error_message); assert_equal_int32 (Int32.of_int 4) Ctypes.(getf (!@ err) GLib.Error.f_code) ) | Ok _ -> assert_equal_string "This should not " "have been reached" let test_filename_from_uri_with_hostname test_ctxt = let uri = "file" in match GLib.Core.filename_from_uri uri with | Error e -> assert_equal_string "GError: This should not " "have been reached" | Ok (filename_opt, hostname_opt) -> let _ = match filename_opt with | None -> assert_equal_string "It should " "return a filename" | Some filename -> assert_equal_string "/etc/mpd.conf" filename in match hostname_opt with | None -> assert_equal_string "This should not " "have been reached" | Some h -> assert_equal_string "localhost" h let test_get_charset_ok test_ctxt = let (is_utf8, charset) = GLib.Core.get_charset () in if is_utf8 then assert_equal_string "UTF-8" charset else assert ("UTF-8" <> charset) let test_dir_make_tmp test_ctxt = match GLib.Core.dir_make_tmp None with | Error _ -> assert_equal_string "Error with dir_make_tmp " "this should not have been reached" | Ok tmp_opt -> match tmp_opt with | None -> assert_equal_string "no tmp " "this should not have been reached" | Some tmp -> assert_file_exists tmp let tests = "GLib functions tests" >::: [ "Test glib check version" >:: test_glib_check_version; "Test glib filename_to_uri ok" >:: test_filename_to_uri_ok; "Test glib filename_to_uri with error" >:: test_filename_to_uri_error; "Test glib get_charset ok" >:: test_get_charset_ok; "Test glib dir_make_tmp" >:: test_dir_make_tmp; "Test glib filename from uri no hostname" >:: test_filename_from_uri_no_hostname; "Test glib filename from uri bad uri" >:: test_filename_from_uri_bad_uri; "Test glib filename from uri with hostname" >:: test_filename_from_uri_with_hostname; ]
null
https://raw.githubusercontent.com/cedlemo/OCaml-GLib2/084a148faa4f18d0ddf78315d57c1d623aa9522c/tests/test_functions.ml
ocaml
* Copyright 2017 - 2018 , * This file is part of . * * OCaml - GLib2 is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * any later version . * * OCaml - GLib2 is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with . If not , see < / > . * Copyright 2017-2018 Cedric LE MOIGNE, * This file is part of OCaml-GLib2. * * OCaml-GLib2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * OCaml-GLib2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OCaml-GLib2. If not, see </>. *) open Test_utils open OUnit2 let filter_meaningless_char str = String.split_on_char '\'' str |> String.concat "" |> Str.(split (regexp "\\(\\“\\|\\”\\|\"\\)")) |> String.concat "" let test_glib_check_version test_ctxt = let open Unsigned.UInt32 in let major = of_int32 GLib.Core.c_MAJOR_VERSION in let minor = of_int32 GLib.Core.c_MINOR_VERSION in let micro = of_int32 GLib.Core.c_MICRO_VERSION in match GLib.Core.check_version major minor micro with | None -> assert_equal_string "Ok" "Ok" | Some version_mismatch -> assert_equal_string "version mismatch" version_mismatch let test_filename_to_uri_ok test_ctxt = let path ="/var" in match GLib.Core.filename_to_uri path None with | Error e -> assert_equal_string "This should not " "have been reached" | Ok uri -> match uri with | None -> assert_equal_string "This should not " "have been reached" | Some uri' -> assert_equal_string "file" uri' let test_filename_from_uri_no_hostname test_ctxt = let uri = "file" in match GLib.Core.filename_from_uri uri with | Error e -> assert_equal_string "GError: This should not " "have been reached" | Ok (filename_opt, hostname_opt) -> let _ = match filename_opt with | None -> assert_equal_string "It should " "return a filename" | Some filename -> assert_equal_string "/etc/mpd.conf" filename in match hostname_opt with | None -> assert true | Some h -> assert_equal_string "This should not " "have been reached" let test_filename_to_uri_error test_ctxt = let path ="a_totally_bad_path_that_should_not_exist" in let expected = "The pathname a_totally_bad_path_that_should_not_exist is \ not an absolute path" in let _ = match GLib.Core.filename_to_uri path None with | Error e -> ( match e with | None -> assert_equal_string "This should not " "have been reached" | Some err -> let error_message = Ctypes.(getf (!@ err) GLib.Error.f_message) in assert_equal_string expected (filter_meaningless_char error_message); assert_equal_int32 (Int32.of_int 5) Ctypes.(getf (!@ err) GLib.Error.f_code) ) | Ok uri -> assert_equal_string "This should not " "have been reached" in at_exit Gc.full_major let test_filename_from_uri_bad_uri test_ctxt = let uri = "noprotocoletcmpd.conf" in let expected = "The URI noprotocoletcmpd.conf is not an absolute URI using the file scheme" in match GLib.Core.filename_from_uri uri with | Error e -> ( match e with | None -> assert_equal_string "This should not " "have been reached" | Some err -> let error_message = Ctypes.(getf (!@ err) GLib.Error.f_message) in assert_equal_string expected (filter_meaningless_char error_message); assert_equal_int32 (Int32.of_int 4) Ctypes.(getf (!@ err) GLib.Error.f_code) ) | Ok _ -> assert_equal_string "This should not " "have been reached" let test_filename_from_uri_with_hostname test_ctxt = let uri = "file" in match GLib.Core.filename_from_uri uri with | Error e -> assert_equal_string "GError: This should not " "have been reached" | Ok (filename_opt, hostname_opt) -> let _ = match filename_opt with | None -> assert_equal_string "It should " "return a filename" | Some filename -> assert_equal_string "/etc/mpd.conf" filename in match hostname_opt with | None -> assert_equal_string "This should not " "have been reached" | Some h -> assert_equal_string "localhost" h let test_get_charset_ok test_ctxt = let (is_utf8, charset) = GLib.Core.get_charset () in if is_utf8 then assert_equal_string "UTF-8" charset else assert ("UTF-8" <> charset) let test_dir_make_tmp test_ctxt = match GLib.Core.dir_make_tmp None with | Error _ -> assert_equal_string "Error with dir_make_tmp " "this should not have been reached" | Ok tmp_opt -> match tmp_opt with | None -> assert_equal_string "no tmp " "this should not have been reached" | Some tmp -> assert_file_exists tmp let tests = "GLib functions tests" >::: [ "Test glib check version" >:: test_glib_check_version; "Test glib filename_to_uri ok" >:: test_filename_to_uri_ok; "Test glib filename_to_uri with error" >:: test_filename_to_uri_error; "Test glib get_charset ok" >:: test_get_charset_ok; "Test glib dir_make_tmp" >:: test_dir_make_tmp; "Test glib filename from uri no hostname" >:: test_filename_from_uri_no_hostname; "Test glib filename from uri bad uri" >:: test_filename_from_uri_bad_uri; "Test glib filename from uri with hostname" >:: test_filename_from_uri_with_hostname; ]
9eef3c7421c3a078653e045d00c87dd596ed15f0f255fb98836d316da537e8bd
mikeizbicki/subhask
BloomFilter.hs
# OPTIONS_GHC -fno - warn - missing - methods # module SubHask.Compatibility.BloomFilter ( BloomFilter ) where import SubHask.Algebra import SubHask.Category import SubHask.Internal.Prelude import qualified Data.BloomFilter as BF newtype BloomFilter (n::Nat) a = BloomFilter (BF.Bloom a) mkMutable [t| forall n a. BloomFilter n a |] type instance Scalar (BloomFilter n a) = Int type instance Logic (BloomFilter n a) = Bool type instance Elem (BloomFilter n a) = a type instance SetElem (BloomFilter n a) b = BloomFilter n b instance KnownNat n => Semigroup (BloomFilter n a) FIXME : need access to the underlying representation of BF.Bloom to implement instance KnownNat n => Monoid (BloomFilter n a) where zero = BloomFilter (BF.empty undefined n) where n = fromInteger $ natVal (Proxy::Proxy n) instance KnownNat n => Constructible (BloomFilter n a) FIXME : need a good way to handle the hash generically instance KnownNat n => Container (BloomFilter n a) where elem a (BloomFilter b) = BF.elem a b instance KnownNat n => Normed (BloomFilter n a) where size (BloomFilter b) = BF.length b -- formula for number of elements in a bloom filter -- -bloom-filters -- c = log(z / N) / ((h * log(1 - 1 / N))
null
https://raw.githubusercontent.com/mikeizbicki/subhask/f53fd8f465747681c88276c7dabe3646fbdf7d50/src/SubHask/Compatibility/BloomFilter.hs
haskell
formula for number of elements in a bloom filter -bloom-filters c = log(z / N) / ((h * log(1 - 1 / N))
# OPTIONS_GHC -fno - warn - missing - methods # module SubHask.Compatibility.BloomFilter ( BloomFilter ) where import SubHask.Algebra import SubHask.Category import SubHask.Internal.Prelude import qualified Data.BloomFilter as BF newtype BloomFilter (n::Nat) a = BloomFilter (BF.Bloom a) mkMutable [t| forall n a. BloomFilter n a |] type instance Scalar (BloomFilter n a) = Int type instance Logic (BloomFilter n a) = Bool type instance Elem (BloomFilter n a) = a type instance SetElem (BloomFilter n a) b = BloomFilter n b instance KnownNat n => Semigroup (BloomFilter n a) FIXME : need access to the underlying representation of BF.Bloom to implement instance KnownNat n => Monoid (BloomFilter n a) where zero = BloomFilter (BF.empty undefined n) where n = fromInteger $ natVal (Proxy::Proxy n) instance KnownNat n => Constructible (BloomFilter n a) FIXME : need a good way to handle the hash generically instance KnownNat n => Container (BloomFilter n a) where elem a (BloomFilter b) = BF.elem a b instance KnownNat n => Normed (BloomFilter n a) where size (BloomFilter b) = BF.length b
6b0b2f5ae60bb41ec625af8daa0fb48c885bb3ada1e79bb12caffea2114f5b7f
facebookarchive/pfff
interaction_codemap.ml
* * Copyright ( C ) 2013 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2013 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Common2.ArithFloatInfix open Common_client module T = Treemap module M = Model_codemap (*****************************************************************************) (* Prelude *) (*****************************************************************************) (*****************************************************************************) (* Entry point *) (*****************************************************************************) let mouseclick (ctx:Canvas_helpers.context) (w: Model_codemap.world_client) main_service (elt: Dom_html.element Js.t) ev = let device_x, device_y = Common_client.get_position elt ev in pr2 (spf "mouseclick device coord: %d x %d" device_x device_y); let (x, y) = ctx#device_to_user ~x:device_x ~y:device_y in pr2 (spf "mouseclick user coord: %f, %f" x y); let user = { Figures.x = x; y = y } in let r_opt = M.find_rectangle_at_user_point w user in r_opt +> Common.do_option (fun (_r, _, r_englobing) -> let path = r_englobing.T.tr_label in Eliom_client.exit_to ~service:main_service (w.M.size, (w.M.project, path)) (); ); Lwt.return ()
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/web/code_map/interaction_codemap.ml
ocaml
*************************************************************************** Prelude *************************************************************************** *************************************************************************** Entry point ***************************************************************************
* * Copyright ( C ) 2013 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2013 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common open Common2.ArithFloatInfix open Common_client module T = Treemap module M = Model_codemap let mouseclick (ctx:Canvas_helpers.context) (w: Model_codemap.world_client) main_service (elt: Dom_html.element Js.t) ev = let device_x, device_y = Common_client.get_position elt ev in pr2 (spf "mouseclick device coord: %d x %d" device_x device_y); let (x, y) = ctx#device_to_user ~x:device_x ~y:device_y in pr2 (spf "mouseclick user coord: %f, %f" x y); let user = { Figures.x = x; y = y } in let r_opt = M.find_rectangle_at_user_point w user in r_opt +> Common.do_option (fun (_r, _, r_englobing) -> let path = r_englobing.T.tr_label in Eliom_client.exit_to ~service:main_service (w.M.size, (w.M.project, path)) (); ); Lwt.return ()
68b5f744396d94bc94f26a05fbe70026ea464689192e931103bd953344be2924
johnlawrenceaspden/hobby-code
numericalintegrationVI.clj
;; Numerical Integration: Better Refinements? ;; Here are some very simple functions which we might want to test integration ;; methods on: (defn square [x] (* x x)) (defn sine [x] (Math/sin x)) (defn step [x] (if (< x 1/2) 0.0 1.0)) (defn inverse [x] (/ x)) ;; Here are some Newton-Cotes formulae for approximate integration: (defn trapezium-rule [f a b] (* 1/2 (- b a) (+ (f a) (f b)))) (defn simpson-rule [f a b] (let [midpoint (+ a (/ (- b a) 2))] (* 1/6 (- b a) (+ (f a) (* 4 (f midpoint)) (f b))))) (defn simpson38-rule [f a b] (let [midpoint1 (/ (+ a a b) 3) midpoint2 (/ (+ a b b) 3)] (* 1/8 (- b a) (+ (f a) (* 3 (f midpoint1)) (* 3 (f midpoint2)) (f b))))) (defn booles-rule [f a b] (let [midpoint1 (/ (+ a a a b) 4) midpoint2 (/ (+ a a b b) 4) midpoint3 (/ (+ a b b b) 4)] (* 1/90 (- b a) (+ (* 7 (f a)) (* 32 (f midpoint1)) (* 12 (f midpoint2)) (* 32 (f midpoint3)) (* 7 (f b)))))) ;; We can use any of these rules to get estimate of the integral of a function over an interval: 10/9 ;; If we halve the interval and use the rule over both halves, then we can use the rule to get a better estimate by adding the estimates for the half - intervals (+ (simpson-rule inverse 1 2) 11/10 ;; We can guess at the error involved in the estimate by taking the difference between these two estimates , on the basis that splitting the interval usually ;; makes most of the error go away. (- (simpson-rule inverse 1 3) (+ (simpson-rule inverse 1 2) 1/90 So we 'd expect that the first estimate is out by a bit more than 1/90 , and that the second is out by rather less than 1/90 ;; For the inverse function, which can be integrated symbolically, we know the ;; true answer: 1.0986122886681098 1.1111111111111112 1.1 ;; So the errors are really: -0.0124989111111109 ; which is ~ 1/90 (- 1.0986122 11/10) ; -0.00138780000000005 ; which is ~ 1/900 ;; This method of guessing the error is deeply suspect, and can go wrong, but I ;; won't go into details. ;; I think it's good enough for our purposes as long as the functions we want to ;; integrate are reasonably well behaved and we take small enough intervals. So we can easily make a function which gives us the more refined of the two ;; estimates, together with a guess as to how close it is to the truth. (defn approx-with-error[rule f a b] (let [guess (rule f a b) midpoint (/ (+ a b) 2) better-guess (+ (rule f a midpoint) (rule f midpoint b)) error-estimate (- guess better-guess) abs-error-estimate (if (> error-estimate 0) error-estimate (- error-estimate))] [better-guess abs-error-estimate])) Let 's try it out on a few cases , on the particularly nasty integral of 1 / x over [ ] ;; This is the true answer 9.210340371976184 (approx-with-error trapezium-rule inverse 0.01 100) ; [2500.999775019998 2499.000174980002] We guess 2500 , and we think we 're out by at most 2499 , which is just true (approx-with-error simpson-rule inverse 0.01 100) ; [835.4437770204454 832.5559396728856] [ 627.4427811912234 624.2442845054817 ] [ 391.7824297523125 388.1576179566068 ] When we split the interval into two halves [ 0.01 , 50.05 ] [ 50.05,100 ] (approx-with-error trapezium-rule inverse 0.01 50.05) ; [1252.2495505293746 1250.2503495705255] [ 0.7072645364881702 0.041486462512828726 ] Our guess tells us that the great majority of the error is in the first sub interval We might want to refine that first , before bothering with the other one : We 'll now split [ 0.01 , 25.025][25.025,50.05][50.05,100 ] [ 626.6241012183343 624.6256989814656 ] [ 0.7083333333333333 0.04166666666666663 ] [ 0.7072645364881702 0.041486462512828726 ] Again , one subinterval seems to be responsible for the majority of our errors . We could keep a list of intervals , sorted by the estimated error , and always refine the one ;; with the largest guessed error. (defn interval->errorstruct [rule f [a b]] (let [[guess error-guess] (approx-with-error rule f a b)] [error-guess, guess, [a,b]])) (def errorstructs (map (partial interval->errorstruct trapezium-rule inverse) [[0.01,25.025][25.025 50.05][50.05 100]])) errorstructs ( [ 624.6256989814656 626.6241012183343 [ 0.01 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) ;; And now we need a function to refine the interval with the largest error (defn refine[rule f errorstructs] (let [sortedstructs (reverse (sort errorstructs)) [_ _ [a b]] (first sortedstructs) remains (rest sortedstructs) midpoint (/ (+ a b) 2) subinterval1 (interval->errorstruct rule f [a midpoint]) subinterval2 (interval->errorstruct rule f [midpoint b])] (cons subinterval1 (cons subinterval2 remains)))) ;; Now with every call to refine, we refine the interval with the largest error estimate (refine trapezium-rule inverse errorstructs) ( [ 311.93889676733556 313.93570379188156 [ 0.01 12.5175 ] ] [ 0.04159457274964806 0.7079060863675477 [ 12.5175 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) (def successive-trapezium-refinements (iterate (partial refine trapezium-rule inverse) errorstructs)) ;; Here's what it looks like after a few iterations (nth successive-trapezium-refinements 5) ( [ 18.81475746721543 20.764864658796014 [ 0.01 0.7917187499999999 ] ] [ 0.040533241059784286 0.7015625070966475 [ 0.7917187499999999 1.5734374999999998 ] ] [ 0.04109463731966401 0.7049306354620377 [ 1.5734374999999998 3.136875 ] ] [ 0.041379306898238544 0.7066276281534741 [ 3.136875 6.26375 ] ] [ 0.04152264848816445 0.7074793872568832 [ 6.26375 12.5175 ] ] [ 0.04159457274964806 0.7079060863675477 [ 12.5175 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) ;; We can get our best guess for the whole thing and our total error estimate ;; by reducing this list 19.104035002910425 25.708968772954105 After a hundred refinements .. 0.010431101535137086 9.213824736866899 After a thousand refinements .. (reduce + (map first (nth successive-trapezium-refinements 1000))) ; 1.0913238861095381E-4 9.210376750235199 That 's not bad , ( the real answer is 9.210340371976184 ) , but it 's running very slowly . ;; We could try with a higher order rule (def successive-boole-refinements (iterate (partial refine booles-rule inverse) errorstructs)) 4.420942778526893E-15 9.210340371976176 ;; In this case, that seems to work very well, but the run time is appalling. ;; The problem is that we have a longer and longer list of intervals at every ;; step, and every step, we have to sort this list. That's an n^2 algorithm, ;; which won't scale well. ;; What we should do here is use a priority queue. Clojure doesn't have an ;; immutable version, although it's possible to fake one with a sorted map. ;; But rather than do that, I'm going to drop out of the functional paradigm altogther , and use the heap implementation from Java in a mutable fashion , ;; looping and popping and adding. (defn improve-loop [rule f a b count] (let [pq (java.util.PriorityQueue. count (comparator (fn[a b](> (first a)(first b)))))] (.add pq (interval->errorstruct rule f [a b])) (loop [pq pq count count] (if (zero? count) pq (let [[err val [a b]] (.poll pq) midpoint (/ (+ a b) 2) aa (interval->errorstruct rule f [a midpoint]) bb (interval->errorstruct rule f [midpoint b])] (doto pq (.add aa) (.add bb)) (recur pq (dec count))))))) ;; Now we can do our calculation much faster (defn integrate [rule f a b count] (let [pq (improve-loop rule f a b count)] [(reduce + (map first pq)) (reduce + (map second pq))])) We 'll ask for a thousand refinements , and get back the error estimate , and the answer . [ 4.455637248046429E-15 9.21034037197618 ] Let 's try the same integral over the very nasty range [ 0.0000001 , 10000000 ] which caused serious ;; problems for our previous methods. ;; The real answer is 34.538776394910684 ;; And our approximations are: [ 3.797743055486256E10 3.797743056542089E10 ] [ 3.3430724324184924E-5 34.53877704296225 ] [ 4.549938203979309E-11 34.53877639491147 ] [ 9.361001557239845E-16 34.53877639491065 ] For the non - stiff integrals that we started playing with , 's rule is great : ;; It's exact for quadratics, and several higher powers [ 0 8/3 ] [ 0 32/5 ] (integrate booles-rule (fn[x] (* x x x x x)) 0 2 10) ; [0 32/3] ;; and very good for higher powers, even with very few refinements [ 969/8589934592 471219269093/25769803776 ] [ 2127/1099511627776 60316066438099/3298534883328 ] ;; convergence is great for sine [ 1.7383848804897184E-9 1.9999999999725113 ] [ 3.1931922384043077E-15 1.9999999999999991 ] [ 2.526233413538588E-17 1.999999999999999 ] [ 6.32722651455846E-18 2.0 ] ;; But I'm still quite worried about the error estimate that we made. It's only ;; a guess, and it can be a bad guess. Here are some functions that are ;; deliberately designed to screw things up. ;; This function is extremely vibratey near the origin. (defn sineinverse[x] (Math/sin (/ x))) ;; The error estimates are clearly wrong here, but the answers seem to settle down to something that looks plausible. [ 0.09752245288534744 3.189170812427795 ] [ 0.014802407142066881 2.725700351059874 ] [ 2.666579898821515E-4 2.7262259059929814 ] [ 7.84363268117651E-9 2.7262019887881457 ] [ 8.311387750656713E-15 2.726201989096135 ] ;; I'm slightly reassured that if we use the trapezium rule, which should be ;; slower converging but less sensitive to high derivatives, we seem to settle down to the same thing: [ 0.3493754261290617 2.9603246206316127 ] [ 0.12037643221528535 2.759621850911819 ] [ 0.011584111090323689 2.728470051290524 ] [ 7.174438961790802E-4 2.7265014884997414 ] [ 1.0854830311799172E-5 2.7262023437746654 ] ;; Since I don't actually know what the integral of sin(1/x) is, I've no idea ;; whether this answer is correct. Since both rules seem to settle down to the ;; same answer, I tend to believe that it is. ;; Here's a weird function, which looks like it should be even worse that sin(1/x) on its own (defn strange[x] (- (Math/sin (/ x)) (/ (Math/cos (/ x)) x))) In fact it 's the derivative of x sin(1 / x ) , so we can calculate the real answer over [ 0.001 , 10 ] ;; which should be: 0.9975072869277496 ;; Interestingly, the error estimates look sound for this one: (integrate booles-rule strange 0.001 10 1) ; [109.91706304856582 -108.12753277035351] [ 0.07641821305025362 -1.0276123964492345 ] [ 0.0798435700032961 1.0469088424961843 ] [ 2.0359056110968434E-6 0.9975072871949854 ] [ 1.9224976990340685E-12 0.997507286927752 ] ;; Since we seem to have dealt well with some nasty functions, we might be ;; getting confident in our rule. I know I was! ;; But this innocuous looking function (defn sine80squared[x] (square (Math/sin (* x 80)))) ;; Is a complete nightmare. It looks as though the method is converging well: [ 1.1091279850485843E-28 3.7074689566598855E-28 ] [ 0.013089969389960716 0.7853981633974437 ] [ 1.7991469747360833E-12 0.7853981633974478 ] [ 3.207733520089899E-13 0.7853981633974484 ] [ 3.1095566849572033E-15 0.7853981633974481 ] ;; But if we use a different rule, it also seems to converge, but to a completely different answer [ 3.226319244612108E-28 4.262878793991289E-28 ] [ 0.01573134053904405 0.19774924859401588 ] (integrate trapezium-rule sine80squared 0 Math/PI 100) ; [5.4528883422580115E-5 0.19634904414812832] [ 4.6327740574637914E-7 0.19634954102557595 ] [ 5.200068066397881E-9 0.19634954084967793 ] ;; In fact both answers are wrong. We can calculate the real integral of this function over the interval [ 0,pi ] which should be : 1.5707963267948966 ;; In fact if we use our much earlier 'divide every interval evenly' algorithm: (defn iterated-rule [rule f a b N] (if (= N 0) (rule f a b) (let [midpoint (+ a (/ (- b a) 2))] (+ (iterated-rule rule f a midpoint (dec N)) (iterated-rule rule f midpoint b (dec N)))))) ;; We very quickly get surprisingly good answers: 1.13079223568638E-28 4.262878793991289E-28 3.5626606693542546E-28 3.6535380881685736E-28 1.5707963267948966 1.570796326794897 1.5707963267948972 1.5707963267948966 1.5707963267948957 1.5707963267948963 ;; With Booles' rule the story is the same: 3.1974110932118413E-28 3.7074689566598855E-28 2.2340214425527414 1.5358897417550046 1.570796326794895 1.5707963267948961 1.5707963267948966 1.5707963267948968 1.5707963267948963 ;; So the nice rule that we'd come up with, which worked so well for the stiff problem of integrating 1 / x near the origin , is completely broken on something that the obvious ;; recursion integrates (suspiciously) well. ;; The problem is that we used an error estimate that we can't trust to control ;; the refinement process. ;; If we guess that a certain interval contains hardly any error, then it will ;; never get refined at all, so we'll never find out that our guess is wrong.
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/numericalintegrationVI.clj
clojure
Numerical Integration: Better Refinements? Here are some very simple functions which we might want to test integration methods on: Here are some Newton-Cotes formulae for approximate integration: We can use any of these rules to get estimate of the integral of a function over an interval: If we halve the interval and use the rule over both halves, then we can use the rule to We can guess at the error involved in the estimate by taking the difference makes most of the error go away. For the inverse function, which can be integrated symbolically, we know the true answer: So the errors are really: which is ~ 1/90 -0.00138780000000005 ; which is ~ 1/900 This method of guessing the error is deeply suspect, and can go wrong, but I won't go into details. I think it's good enough for our purposes as long as the functions we want to integrate are reasonably well behaved and we take small enough intervals. estimates, together with a guess as to how close it is to the truth. This is the true answer [2500.999775019998 2499.000174980002] [835.4437770204454 832.5559396728856] [1252.2495505293746 1250.2503495705255] with the largest guessed error. And now we need a function to refine the interval with the largest error Now with every call to refine, we refine the interval with the largest error estimate Here's what it looks like after a few iterations We can get our best guess for the whole thing and our total error estimate by reducing this list 1.0913238861095381E-4 We could try with a higher order rule In this case, that seems to work very well, but the run time is appalling. The problem is that we have a longer and longer list of intervals at every step, and every step, we have to sort this list. That's an n^2 algorithm, which won't scale well. What we should do here is use a priority queue. Clojure doesn't have an immutable version, although it's possible to fake one with a sorted map. But rather than do that, I'm going to drop out of the functional paradigm looping and popping and adding. Now we can do our calculation much faster problems for our previous methods. The real answer is And our approximations are: It's exact for quadratics, and several higher powers [0 32/3] and very good for higher powers, even with very few refinements convergence is great for sine But I'm still quite worried about the error estimate that we made. It's only a guess, and it can be a bad guess. Here are some functions that are deliberately designed to screw things up. This function is extremely vibratey near the origin. The error estimates are clearly wrong here, but the answers seem to settle down to something that looks plausible. I'm slightly reassured that if we use the trapezium rule, which should be slower converging but less sensitive to high derivatives, we seem to settle down to the same thing: Since I don't actually know what the integral of sin(1/x) is, I've no idea whether this answer is correct. Since both rules seem to settle down to the same answer, I tend to believe that it is. Here's a weird function, which looks like it should be even worse that sin(1/x) on its own which should be: Interestingly, the error estimates look sound for this one: [109.91706304856582 -108.12753277035351] Since we seem to have dealt well with some nasty functions, we might be getting confident in our rule. I know I was! But this innocuous looking function Is a complete nightmare. It looks as though the method is converging well: But if we use a different rule, it also seems to converge, but to a completely different answer [5.4528883422580115E-5 0.19634904414812832] In fact both answers are wrong. We can calculate the real integral of this In fact if we use our much earlier 'divide every interval evenly' algorithm: We very quickly get surprisingly good answers: With Booles' rule the story is the same: So the nice rule that we'd come up with, which worked so well for the stiff problem recursion integrates (suspiciously) well. The problem is that we used an error estimate that we can't trust to control the refinement process. If we guess that a certain interval contains hardly any error, then it will never get refined at all, so we'll never find out that our guess is wrong.
(defn square [x] (* x x)) (defn sine [x] (Math/sin x)) (defn step [x] (if (< x 1/2) 0.0 1.0)) (defn inverse [x] (/ x)) (defn trapezium-rule [f a b] (* 1/2 (- b a) (+ (f a) (f b)))) (defn simpson-rule [f a b] (let [midpoint (+ a (/ (- b a) 2))] (* 1/6 (- b a) (+ (f a) (* 4 (f midpoint)) (f b))))) (defn simpson38-rule [f a b] (let [midpoint1 (/ (+ a a b) 3) midpoint2 (/ (+ a b b) 3)] (* 1/8 (- b a) (+ (f a) (* 3 (f midpoint1)) (* 3 (f midpoint2)) (f b))))) (defn booles-rule [f a b] (let [midpoint1 (/ (+ a a a b) 4) midpoint2 (/ (+ a a b b) 4) midpoint3 (/ (+ a b b b) 4)] (* 1/90 (- b a) (+ (* 7 (f a)) (* 32 (f midpoint1)) (* 12 (f midpoint2)) (* 32 (f midpoint3)) (* 7 (f b)))))) 10/9 get a better estimate by adding the estimates for the half - intervals (+ (simpson-rule inverse 1 2) 11/10 between these two estimates , on the basis that splitting the interval usually (- (simpson-rule inverse 1 3) (+ (simpson-rule inverse 1 2) 1/90 So we 'd expect that the first estimate is out by a bit more than 1/90 , and that the second is out by rather less than 1/90 1.0986122886681098 1.1111111111111112 1.1 So we can easily make a function which gives us the more refined of the two (defn approx-with-error[rule f a b] (let [guess (rule f a b) midpoint (/ (+ a b) 2) better-guess (+ (rule f a midpoint) (rule f midpoint b)) error-estimate (- guess better-guess) abs-error-estimate (if (> error-estimate 0) error-estimate (- error-estimate))] [better-guess abs-error-estimate])) Let 's try it out on a few cases , on the particularly nasty integral of 1 / x over [ ] 9.210340371976184 We guess 2500 , and we think we 're out by at most 2499 , which is just true [ 627.4427811912234 624.2442845054817 ] [ 391.7824297523125 388.1576179566068 ] When we split the interval into two halves [ 0.01 , 50.05 ] [ 50.05,100 ] [ 0.7072645364881702 0.041486462512828726 ] Our guess tells us that the great majority of the error is in the first sub interval We might want to refine that first , before bothering with the other one : We 'll now split [ 0.01 , 25.025][25.025,50.05][50.05,100 ] [ 626.6241012183343 624.6256989814656 ] [ 0.7083333333333333 0.04166666666666663 ] [ 0.7072645364881702 0.041486462512828726 ] Again , one subinterval seems to be responsible for the majority of our errors . We could keep a list of intervals , sorted by the estimated error , and always refine the one (defn interval->errorstruct [rule f [a b]] (let [[guess error-guess] (approx-with-error rule f a b)] [error-guess, guess, [a,b]])) (def errorstructs (map (partial interval->errorstruct trapezium-rule inverse) [[0.01,25.025][25.025 50.05][50.05 100]])) errorstructs ( [ 624.6256989814656 626.6241012183343 [ 0.01 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) (defn refine[rule f errorstructs] (let [sortedstructs (reverse (sort errorstructs)) [_ _ [a b]] (first sortedstructs) remains (rest sortedstructs) midpoint (/ (+ a b) 2) subinterval1 (interval->errorstruct rule f [a midpoint]) subinterval2 (interval->errorstruct rule f [midpoint b])] (cons subinterval1 (cons subinterval2 remains)))) (refine trapezium-rule inverse errorstructs) ( [ 311.93889676733556 313.93570379188156 [ 0.01 12.5175 ] ] [ 0.04159457274964806 0.7079060863675477 [ 12.5175 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) (def successive-trapezium-refinements (iterate (partial refine trapezium-rule inverse) errorstructs)) (nth successive-trapezium-refinements 5) ( [ 18.81475746721543 20.764864658796014 [ 0.01 0.7917187499999999 ] ] [ 0.040533241059784286 0.7015625070966475 [ 0.7917187499999999 1.5734374999999998 ] ] [ 0.04109463731966401 0.7049306354620377 [ 1.5734374999999998 3.136875 ] ] [ 0.041379306898238544 0.7066276281534741 [ 3.136875 6.26375 ] ] [ 0.04152264848816445 0.7074793872568832 [ 6.26375 12.5175 ] ] [ 0.04159457274964806 0.7079060863675477 [ 12.5175 25.025 ] ] [ 0.04166666666666663 0.7083333333333333 [ 25.025 50.05 ] ] [ 0.041486462512828726 0.7072645364881702 [ 50.05 100 ] ] ) 19.104035002910425 25.708968772954105 After a hundred refinements .. 0.010431101535137086 9.213824736866899 After a thousand refinements .. 9.210376750235199 That 's not bad , ( the real answer is 9.210340371976184 ) , but it 's running very slowly . (def successive-boole-refinements (iterate (partial refine booles-rule inverse) errorstructs)) 4.420942778526893E-15 9.210340371976176 altogther , and use the heap implementation from Java in a mutable fashion , (defn improve-loop [rule f a b count] (let [pq (java.util.PriorityQueue. count (comparator (fn[a b](> (first a)(first b)))))] (.add pq (interval->errorstruct rule f [a b])) (loop [pq pq count count] (if (zero? count) pq (let [[err val [a b]] (.poll pq) midpoint (/ (+ a b) 2) aa (interval->errorstruct rule f [a midpoint]) bb (interval->errorstruct rule f [midpoint b])] (doto pq (.add aa) (.add bb)) (recur pq (dec count))))))) (defn integrate [rule f a b count] (let [pq (improve-loop rule f a b count)] [(reduce + (map first pq)) (reduce + (map second pq))])) We 'll ask for a thousand refinements , and get back the error estimate , and the answer . [ 4.455637248046429E-15 9.21034037197618 ] Let 's try the same integral over the very nasty range [ 0.0000001 , 10000000 ] which caused serious 34.538776394910684 [ 3.797743055486256E10 3.797743056542089E10 ] [ 3.3430724324184924E-5 34.53877704296225 ] [ 4.549938203979309E-11 34.53877639491147 ] [ 9.361001557239845E-16 34.53877639491065 ] For the non - stiff integrals that we started playing with , 's rule is great : [ 0 8/3 ] [ 0 32/5 ] [ 969/8589934592 471219269093/25769803776 ] [ 2127/1099511627776 60316066438099/3298534883328 ] [ 1.7383848804897184E-9 1.9999999999725113 ] [ 3.1931922384043077E-15 1.9999999999999991 ] [ 2.526233413538588E-17 1.999999999999999 ] [ 6.32722651455846E-18 2.0 ] (defn sineinverse[x] (Math/sin (/ x))) [ 0.09752245288534744 3.189170812427795 ] [ 0.014802407142066881 2.725700351059874 ] [ 2.666579898821515E-4 2.7262259059929814 ] [ 7.84363268117651E-9 2.7262019887881457 ] [ 8.311387750656713E-15 2.726201989096135 ] [ 0.3493754261290617 2.9603246206316127 ] [ 0.12037643221528535 2.759621850911819 ] [ 0.011584111090323689 2.728470051290524 ] [ 7.174438961790802E-4 2.7265014884997414 ] [ 1.0854830311799172E-5 2.7262023437746654 ] (defn strange[x] (- (Math/sin (/ x)) (/ (Math/cos (/ x)) x))) In fact it 's the derivative of x sin(1 / x ) , so we can calculate the real answer over [ 0.001 , 10 ] 0.9975072869277496 [ 0.07641821305025362 -1.0276123964492345 ] [ 0.0798435700032961 1.0469088424961843 ] [ 2.0359056110968434E-6 0.9975072871949854 ] [ 1.9224976990340685E-12 0.997507286927752 ] (defn sine80squared[x] (square (Math/sin (* x 80)))) [ 1.1091279850485843E-28 3.7074689566598855E-28 ] [ 0.013089969389960716 0.7853981633974437 ] [ 1.7991469747360833E-12 0.7853981633974478 ] [ 3.207733520089899E-13 0.7853981633974484 ] [ 3.1095566849572033E-15 0.7853981633974481 ] [ 3.226319244612108E-28 4.262878793991289E-28 ] [ 0.01573134053904405 0.19774924859401588 ] [ 4.6327740574637914E-7 0.19634954102557595 ] [ 5.200068066397881E-9 0.19634954084967793 ] function over the interval [ 0,pi ] which should be : 1.5707963267948966 (defn iterated-rule [rule f a b N] (if (= N 0) (rule f a b) (let [midpoint (+ a (/ (- b a) 2))] (+ (iterated-rule rule f a midpoint (dec N)) (iterated-rule rule f midpoint b (dec N)))))) 1.13079223568638E-28 4.262878793991289E-28 3.5626606693542546E-28 3.6535380881685736E-28 1.5707963267948966 1.570796326794897 1.5707963267948972 1.5707963267948966 1.5707963267948957 1.5707963267948963 3.1974110932118413E-28 3.7074689566598855E-28 2.2340214425527414 1.5358897417550046 1.570796326794895 1.5707963267948961 1.5707963267948966 1.5707963267948968 1.5707963267948963 of integrating 1 / x near the origin , is completely broken on something that the obvious
33ebfb78bac0b0368b46af19b60de0fa3a9be91d6c1a3e93e185676a7537168e
damn/cdq
ingame_loop.clj
(ns game.components.ingame-loop (:use [utils.core :only (find-first)] game.components.core)) (def ^:private ids (atom #{})) (defentity ingame-loop-comp [& args] (create-comp :ingame-loop-entity {:init #(swap! ids conj (get-id %)) :destruct #(swap! ids disj (get-id %))}) (apply create-comp args)) (defn get-ingame-loop-entities [] (map get-entity @ids)) (defmacro do-in-game-loop [& expr] `(ingame-loop-comp :temporary (active [delta# c# entity#] ~@expr (add-to-removelist entity#)))) (defn remove-entity [ctype] (->> (get-ingame-loop-entities) (find-first #(get-component % ctype)) add-to-removelist))
null
https://raw.githubusercontent.com/damn/cdq/5093dbdba91c445e403f53ce96ead05d5ed8262b/src/game/components/ingame_loop.clj
clojure
(ns game.components.ingame-loop (:use [utils.core :only (find-first)] game.components.core)) (def ^:private ids (atom #{})) (defentity ingame-loop-comp [& args] (create-comp :ingame-loop-entity {:init #(swap! ids conj (get-id %)) :destruct #(swap! ids disj (get-id %))}) (apply create-comp args)) (defn get-ingame-loop-entities [] (map get-entity @ids)) (defmacro do-in-game-loop [& expr] `(ingame-loop-comp :temporary (active [delta# c# entity#] ~@expr (add-to-removelist entity#)))) (defn remove-entity [ctype] (->> (get-ingame-loop-entities) (find-first #(get-component % ctype)) add-to-removelist))
a3b3939ac1b9942b5202e49ce4a52116a5298d054fc2d014241b361d8ba71bd8
camlp5/camlp5
pretty.ml
(* camlp5r *) (* pretty.ml,v *) Copyright ( c ) INRIA 2007 - 2017 #load "pa_macro.cmo"; open Versdep; exception GiveUp; value line_length = ref 78; value horiz_ctx = ref False; value utf8_string_length s = loop 0 0 where rec loop i len = if i = String.length s then len else let c = Char.code s.[i] in if c < 0b1000_0000 || c >= 0b1100_0000 then loop (i + 1) (len + 1) else loop (i + 1) len ; value after_print s = if horiz_ctx.val then if string_contains s '\n' || utf8_string_length s > line_length.val then raise GiveUp else s else s ; value sprintf fmt = Versdep.printf_ksprintf after_print fmt; value horiz_vertic horiz vertic = try Ploc.call_with horiz_ctx True horiz () with [ GiveUp -> if horiz_ctx.val then raise GiveUp else vertic () ] ; value vertic v = horiz_vertic (fun () -> raise GiveUp) v ; value horizontally () = horiz_ctx.val;
null
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/lib/pretty.ml
ocaml
camlp5r pretty.ml,v
Copyright ( c ) INRIA 2007 - 2017 #load "pa_macro.cmo"; open Versdep; exception GiveUp; value line_length = ref 78; value horiz_ctx = ref False; value utf8_string_length s = loop 0 0 where rec loop i len = if i = String.length s then len else let c = Char.code s.[i] in if c < 0b1000_0000 || c >= 0b1100_0000 then loop (i + 1) (len + 1) else loop (i + 1) len ; value after_print s = if horiz_ctx.val then if string_contains s '\n' || utf8_string_length s > line_length.val then raise GiveUp else s else s ; value sprintf fmt = Versdep.printf_ksprintf after_print fmt; value horiz_vertic horiz vertic = try Ploc.call_with horiz_ctx True horiz () with [ GiveUp -> if horiz_ctx.val then raise GiveUp else vertic () ] ; value vertic v = horiz_vertic (fun () -> raise GiveUp) v ; value horizontally () = horiz_ctx.val;
843743c53ead680fe0a29feab4286c24b0361dd02288d83d166f5a5c3ced2721
marigold-dev/deku
wasm_vm_tests.ml
let () = let open Alcotest in run "Wasm-vm" ~and_exit:false ~verbose:true [ ( "Basic Vm tests", [ test_case "Originate/invoke increment" `Quick Increment_test.test; test_case "Originate/invoke tickets" `Quick Ticket_test.test; Decookie.decookie_test ; ] ); ]
null
https://raw.githubusercontent.com/marigold-dev/deku/152d5bbe3c30912aa28b5ab810e03216e8c22710/deku-c/wasm-vm-ocaml/tests/wasm_vm_tests.ml
ocaml
let () = let open Alcotest in run "Wasm-vm" ~and_exit:false ~verbose:true [ ( "Basic Vm tests", [ test_case "Originate/invoke increment" `Quick Increment_test.test; test_case "Originate/invoke tickets" `Quick Ticket_test.test; Decookie.decookie_test ; ] ); ]