_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
|
---|---|---|---|---|---|---|---|---|
9b0236f4b2e21586abb5473624731650716c2ee071f80033eb97116f25f9b17f | FestCat/festival-ca | nitech_us_slt_arctic_lexicon.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
CMU lexicon for US English
;;;
;;; Load any necessary files here
(require 'postlex)
(setup_cmu_lex)
(define (nitech_us_slt_arctic::select_lexicon)
"(nitech_us_slt_arctic::select_lexicon)
Set up the CMU lexicon for US English."
(lex.select "cmu")
Post lexical rules
(set! postlex_rules_hooks (list postlex_apos_s_check))
(set! postlex_vowel_reduce_cart_tree nil) ; no reduction
)
(define (nitech_us_slt_arctic::reset_lexicon)
"(nitech_us_slt_arctic::reset_lexicon)
Reset lexicon information."
t
)
(provide 'nitech_us_slt_arctic_lexicon)
| null | https://raw.githubusercontent.com/FestCat/festival-ca/f6b2d9bf4fc4f77b80890ebb95770075ad36ccaf/src/data/festvox.orig/nitech_us_slt_arctic_lexicon.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
Load any necessary files here
no reduction | CMU lexicon for US English
(require 'postlex)
(setup_cmu_lex)
(define (nitech_us_slt_arctic::select_lexicon)
"(nitech_us_slt_arctic::select_lexicon)
Set up the CMU lexicon for US English."
(lex.select "cmu")
Post lexical rules
(set! postlex_rules_hooks (list postlex_apos_s_check))
)
(define (nitech_us_slt_arctic::reset_lexicon)
"(nitech_us_slt_arctic::reset_lexicon)
Reset lexicon information."
t
)
(provide 'nitech_us_slt_arctic_lexicon)
|
6afc12935f022adb8f17dd6c5bf4d1de94afab8d5fd5439bf661dd9b449e676c | ocaml/odoc | root.ml |
* Copyright ( c ) 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2014 Leo White <>
*
* 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.
*)
let contains_double_underscore s =
let len = String.length s in
let rec aux i =
if i > len - 2 then false
else if s.[i] = '_' && s.[i + 1] = '_' then true
else aux (i + 1)
in
aux 0
module Package = struct
type t = string
module Table = Hashtbl.Make (struct
type nonrec t = t
let equal : t -> t -> bool = ( = )
let hash : t -> int = Hashtbl.hash
end)
end
module Odoc_file = struct
type compilation_unit = { name : string; hidden : bool }
type t = Page of string | Compilation_unit of compilation_unit
let create_unit ~force_hidden name =
let hidden = force_hidden || contains_double_underscore name in
Compilation_unit { name; hidden }
let create_page name = Page name
let name = function Page name | Compilation_unit { name; _ } -> name
let hidden = function Page _ -> false | Compilation_unit m -> m.hidden
end
type t = {
id : Paths.Identifier.OdocId.t;
file : Odoc_file.t;
digest : Digest.t;
}
let equal : t -> t -> bool = ( = )
let hash : t -> int = Hashtbl.hash
let to_string t =
let rec pp fmt (id : Paths.Identifier.OdocId.t) =
match id.iv with
| `LeafPage (parent, name) | `Page (parent, name) -> (
match parent with
| Some p ->
Format.fprintf fmt "%a::%a" pp
(p :> Paths.Identifier.OdocId.t)
Names.PageName.fmt name
| None -> Format.fprintf fmt "%a" Names.PageName.fmt name)
| `Root (Some parent, name) ->
Format.fprintf fmt "%a::%a" pp
(parent :> Paths.Identifier.OdocId.t)
Names.ModuleName.fmt name
| `Root (None, name) -> Format.fprintf fmt "%a" Names.ModuleName.fmt name
in
Format.asprintf "%a" pp t.id
let compare x y = String.compare x.digest y.digest
module Hash_table = Hashtbl.Make (struct
type nonrec t = t
let equal = equal
let hash = hash
end)
| null | https://raw.githubusercontent.com/ocaml/odoc/704ce161a32b6830c824ec4b9cc87b113b9228bd/src/model/root.ml | ocaml |
* Copyright ( c ) 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2014 Leo White <>
*
* 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.
*)
let contains_double_underscore s =
let len = String.length s in
let rec aux i =
if i > len - 2 then false
else if s.[i] = '_' && s.[i + 1] = '_' then true
else aux (i + 1)
in
aux 0
module Package = struct
type t = string
module Table = Hashtbl.Make (struct
type nonrec t = t
let equal : t -> t -> bool = ( = )
let hash : t -> int = Hashtbl.hash
end)
end
module Odoc_file = struct
type compilation_unit = { name : string; hidden : bool }
type t = Page of string | Compilation_unit of compilation_unit
let create_unit ~force_hidden name =
let hidden = force_hidden || contains_double_underscore name in
Compilation_unit { name; hidden }
let create_page name = Page name
let name = function Page name | Compilation_unit { name; _ } -> name
let hidden = function Page _ -> false | Compilation_unit m -> m.hidden
end
type t = {
id : Paths.Identifier.OdocId.t;
file : Odoc_file.t;
digest : Digest.t;
}
let equal : t -> t -> bool = ( = )
let hash : t -> int = Hashtbl.hash
let to_string t =
let rec pp fmt (id : Paths.Identifier.OdocId.t) =
match id.iv with
| `LeafPage (parent, name) | `Page (parent, name) -> (
match parent with
| Some p ->
Format.fprintf fmt "%a::%a" pp
(p :> Paths.Identifier.OdocId.t)
Names.PageName.fmt name
| None -> Format.fprintf fmt "%a" Names.PageName.fmt name)
| `Root (Some parent, name) ->
Format.fprintf fmt "%a::%a" pp
(parent :> Paths.Identifier.OdocId.t)
Names.ModuleName.fmt name
| `Root (None, name) -> Format.fprintf fmt "%a" Names.ModuleName.fmt name
in
Format.asprintf "%a" pp t.id
let compare x y = String.compare x.digest y.digest
module Hash_table = Hashtbl.Make (struct
type nonrec t = t
let equal = equal
let hash = hash
end)
|
|
d8901e6e9b62e87363fd61cff29cf35a1b4e7e2ed0ea735d37e354d4e6245a4a | atennapel/tinka-hs | Surface.hs | module Surface where
import Data.List (intercalate)
import Text.Megaparsec (SourcePos)
import Data.Maybe (fromMaybe)
import Common
data SLevel
= SLVar Name
| SLS SLevel
| SLMax SLevel SLevel
| SLNat Int
showSLevelS :: SLevel -> String
showSLevelS l@(SLNat _) = show l
showSLevelS l@(SLVar _) = show l
showSLevelS l = "(" ++ show l ++ ")"
instance Show SLevel where
show (SLVar x) = x
show (SLNat i) = show i
show (SLS l) = "S " ++ showSLevelS l
show (SLMax a b) = "max " ++ showSLevelS a ++ " " ++ showSLevelS b
data SProjType = SFst | SSnd | SIndex Ix | SNamed Name
deriving (Eq)
instance Show SProjType where
show SFst = "._1"
show SSnd = "._2"
show (SIndex i) = "." ++ show i
show (SNamed x) = "." ++ x
type STy = STm
data STm
= SVar Name
| SApp STm STm (Either (Name, Impl) Icit)
| SLam Name (Either (Name, Impl) Icit) (Maybe STy) STm
| SPi Name Icit STm STm
| SAppLvl STm SLevel (Maybe Name)
| SLamLvl Name (Maybe Name) STm
| SPiLvl Name STm
| SProj STm SProjType
| SPair STm STm
| SSigma Name STm STm
| SCon STm
| SRefl
| SLet Name Bool (Maybe STy) STm STm
| SType SLevel
| SHole (Maybe Name)
| SNatLit Integer
| SLabelLit Name
| SPos SourcePos STm
showSTmS :: STm -> String
showSTmS t@(SVar _) = show t
showSTmS t@SRefl = show t
showSTmS t@(SType (SLNat 0)) = show t
showSTmS t@(SPair _ _) = show t
showSTmS t@(SHole _) = show t
showSTmS t@(SNatLit _) = show t
showSTmS t@(SLabelLit _) = show t
showSTmS (SPos _ t) = showSTmS t
showSTmS t = "(" ++ show t ++ ")"
showSTmApp :: STm -> String
showSTmApp t =
let (f, as) = go t in
showSTmS f ++ " " ++ unwords (map showAppArgument $ reverse as)
where
go :: STm -> (STm, [Either (SLevel, Maybe Name) (STm, Either (Name, Impl) Icit)])
go (SApp f a i) = let (f', as) = go f in (f', Right (a, i) : as)
go (SAppLvl f a i) = let (f', as) = go f in (f', Left (a, i) : as)
go (SPos _ s) = go s
go t = (t, [])
showAppArgument :: Either (SLevel, Maybe Name) (STm, Either (Name, Impl) Icit) -> String
showAppArgument (Right (a, Right Expl)) = showSTmS a
showAppArgument (Right (a, Right (Impl ImplUnif))) = "{" ++ show a ++ "}"
showAppArgument (Right (a, Right (Impl ImplInst))) = "{{" ++ show a ++ "}}"
showAppArgument (Right (a, Left (x, ImplUnif))) = "{" ++ showName x ++ " = " ++ show a ++ "}"
showAppArgument (Right (a, Left (x, ImplInst))) = "{{" ++ showName x ++ " = " ++ show a ++ "}}"
showAppArgument (Left (a, Just x)) = "<" ++ x ++ " = " ++ show a ++ ">"
showAppArgument (Left (a, Nothing)) = "<" ++ show a ++ ">"
showSTmLam :: STm -> String
showSTmLam t =
let (xs, b) = go t in
"\\" ++ unwords (map showAbsParameter xs) ++ ". " ++ show b
where
go :: STm -> ([(Name, Either (Maybe Name) (Either (Name, Impl) Icit, Maybe STy))], STm)
go (SLam x i t b) = let (as, b') = go b in ((x, Right (i, t)) : as, b')
go (SLamLvl x i b) = let (as, b') = go b in ((x, Left i) : as, b')
go (SPos _ s) = go s
go t = ([], t)
showAbsParameter :: (Name, Either (Maybe Name) (Either (Name, Impl) Icit, Maybe STy)) -> String
showAbsParameter (x, Right (Right Expl, Nothing)) = showName x
showAbsParameter (x, Right (Right Expl, Just t)) = "(" ++ showName x ++ " : " ++ show t ++ ")"
showAbsParameter (x, Right (Right (Impl ImplUnif), Nothing)) = "{" ++ showName x ++ "}"
showAbsParameter (x, Right (Right (Impl ImplInst), Nothing)) = "{{" ++ showName x ++ "}}"
showAbsParameter (x, Right (Right (Impl ImplUnif), Just t)) = "{" ++ showName x ++ " : " ++ show t ++ "}"
showAbsParameter (x, Right (Right (Impl ImplInst), Just t)) = "{{" ++ showName x ++ " : " ++ show t ++ "}}"
showAbsParameter (x, Right (Left (y, ImplUnif), Nothing)) = "{" ++ showName x ++ " = " ++ y ++ "}"
showAbsParameter (x, Right (Left (y, ImplInst), Nothing)) = "{{" ++ showName x ++ " = " ++ y ++ "}}"
showAbsParameter (x, Right (Left (y, ImplUnif), Just t)) = "{" ++ showName x ++ " : " ++ show t ++ " = " ++ y ++ "}"
showAbsParameter (x, Right (Left (y, ImplInst), Just t)) = "{{" ++ showName x ++ " : " ++ show t ++ " = " ++ y ++ "}}"
showAbsParameter (x, Left (Just y)) = "<" ++ x ++ " = " ++ y ++ ">"
showAbsParameter (x, Left Nothing) = "<" ++ x ++ ">"
showSTmPi :: STm -> String
showSTmPi t =
let (ps, b) = go t in
intercalate " -> " (map showParam ps) ++ " -> " ++ showApp b
where
go :: STm -> ([(Name, Maybe (STm, Icit))], STm)
go (SPi x i t b) = let (ps, b') = go b in ((x, Just (t, i)) : ps, b')
go (SPiLvl x b) = let (ps, b') = go b in ((x, Nothing) : ps, b')
go (SPos _ s) = go s
go t = ([], t)
showApp :: STm -> String
showApp t@SApp {} = show t
showApp t@SAppLvl {} = show t
showApp t@(SType _) = show t
showApp (SPos _ s) = showApp s
showApp t = showSTmS t
showParam :: (Name, Maybe (STm, Icit)) -> String
showParam ("_", Just (t, Expl)) = showApp t
showParam (x, Just (t, Expl)) = "(" ++ showName x ++ " : " ++ show t ++ ")"
showParam (x, Just (t, Impl ImplUnif)) = "{" ++ showName x ++ " : " ++ show t ++ "}"
showParam (x, Just (t, Impl ImplInst)) = "{{" ++ showName x ++ " : " ++ show t ++ "}}"
showParam (x, Nothing) = "<" ++ x ++ ">"
showSTmPair :: STm -> String
showSTmPair s =
let ps = flattenPair s in
case last ps of
SVar "[]" -> "[" ++ intercalate ", " (map show $ init ps) ++ "]"
SRefl -> "[" ++ intercalate ", " (map show $ init ps) ++ "]"
_ -> "(" ++ intercalate ", " (map show ps) ++ ")"
where
flattenPair :: STm -> [STm]
flattenPair (SPair a b) = a : flattenPair b
flattenPair (SPos _ s) = flattenPair s
flattenPair s = [s]
showSTmProj :: STm -> String
showSTmProj s =
let (s', ps) = flattenProj s in
showSTmS s' ++ intercalate "" (map show ps)
where
flattenProj :: STm -> (STm, [SProjType])
flattenProj s = go s []
where
go (SProj b p) ps = go b (p : ps)
go (SPos _ s) ps = go s ps
go s ps = (s, ps)
showSTmSigma :: STm -> String
showSTmSigma t =
let (ps, b) = go t in
intercalate " ** " (map showParam ps) ++ " ** " ++ showApp b
where
go :: STm -> ([(Name, STm)], STm)
go (SSigma x t b) = let (ps, b') = go b in ((x, t) : ps, b')
go (SPos _ s) = go s
go t = ([], t)
showApp :: STm -> String
showApp t@SApp {} = show t
showApp t@SAppLvl {} = show t
showApp t@(SType _) = show t
showApp (SPos _ s) = showApp s
showApp t = showSTmS t
showParam :: (Name, STm) -> String
showParam ("_", t) = showApp t
showParam (x, t) = "(" ++ showName x ++ " : " ++ show t ++ ")"
instance Show STm where
show (SPos _ t) = show t
show (SVar x) = showName x
show (SHole x) = "_" ++ fromMaybe "" x
show t@SApp {} = showSTmApp t
show t@SLam {} = showSTmLam t
show t@SPi {} = showSTmPi t
show t@SAppLvl {} = showSTmApp t
show t@SLamLvl {} = showSTmLam t
show t@(SPiLvl _ _) = showSTmPi t
show t@(SProj _ _) = showSTmProj t
show t@(SPair _ _) = showSTmPair t
show t@(SSigma _ _ _) = showSTmSigma t
show (SCon t) = "Con " ++ showSTmS t
show SRefl = "Refl"
show (SLet x i (Just t) v b) = "let " ++ (if i then "instance " else "") ++ showName x ++ " : " ++ show t ++ " = " ++ show v ++ "; " ++ show b
show (SLet x i Nothing v b) = "let " ++ (if i then "instance " else "") ++ showName x ++ " = " ++ show v ++ "; " ++ show b
show (SType (SLNat 0)) = "Type"
show (SType l) = "Type " ++ showSLevelS l
show (SNatLit i) = show i
show (SLabelLit x) = "'" ++ x
data Decl
= Def Name Bool (Maybe STy) STm
| Import String
instance Show Decl where
show (Def x inst (Just ty) tm) = (if inst then "instance " else "") ++ showName x ++ " : " ++ show ty ++ " = " ++ show tm
show (Def x inst Nothing tm) = (if inst then "instance " else "") ++ showName x ++ " = " ++ show tm
show (Import x) = "import " ++ x
type Decls = [Decl]
showDecls :: Decls -> String
showDecls [] = ""
showDecls (hd : tl) = show hd ++ "\n" ++ showDecls tl
declNames :: Decls -> [String]
declNames [] = []
declNames (Def x _ _ _ : t) = x : declNames t
declNames (_ : t) = declNames t
countNames :: Decls -> Int
countNames = length . declNames
imports :: Decls -> [String]
imports [] = []
imports (Import x : t) = x : imports t
imports (_ : t) = imports t
| null | https://raw.githubusercontent.com/atennapel/tinka-hs/555f862ba4099120a05a9db4eda8947f25c9bfe3/src/Surface.hs | haskell | module Surface where
import Data.List (intercalate)
import Text.Megaparsec (SourcePos)
import Data.Maybe (fromMaybe)
import Common
data SLevel
= SLVar Name
| SLS SLevel
| SLMax SLevel SLevel
| SLNat Int
showSLevelS :: SLevel -> String
showSLevelS l@(SLNat _) = show l
showSLevelS l@(SLVar _) = show l
showSLevelS l = "(" ++ show l ++ ")"
instance Show SLevel where
show (SLVar x) = x
show (SLNat i) = show i
show (SLS l) = "S " ++ showSLevelS l
show (SLMax a b) = "max " ++ showSLevelS a ++ " " ++ showSLevelS b
data SProjType = SFst | SSnd | SIndex Ix | SNamed Name
deriving (Eq)
instance Show SProjType where
show SFst = "._1"
show SSnd = "._2"
show (SIndex i) = "." ++ show i
show (SNamed x) = "." ++ x
type STy = STm
data STm
= SVar Name
| SApp STm STm (Either (Name, Impl) Icit)
| SLam Name (Either (Name, Impl) Icit) (Maybe STy) STm
| SPi Name Icit STm STm
| SAppLvl STm SLevel (Maybe Name)
| SLamLvl Name (Maybe Name) STm
| SPiLvl Name STm
| SProj STm SProjType
| SPair STm STm
| SSigma Name STm STm
| SCon STm
| SRefl
| SLet Name Bool (Maybe STy) STm STm
| SType SLevel
| SHole (Maybe Name)
| SNatLit Integer
| SLabelLit Name
| SPos SourcePos STm
showSTmS :: STm -> String
showSTmS t@(SVar _) = show t
showSTmS t@SRefl = show t
showSTmS t@(SType (SLNat 0)) = show t
showSTmS t@(SPair _ _) = show t
showSTmS t@(SHole _) = show t
showSTmS t@(SNatLit _) = show t
showSTmS t@(SLabelLit _) = show t
showSTmS (SPos _ t) = showSTmS t
showSTmS t = "(" ++ show t ++ ")"
showSTmApp :: STm -> String
showSTmApp t =
let (f, as) = go t in
showSTmS f ++ " " ++ unwords (map showAppArgument $ reverse as)
where
go :: STm -> (STm, [Either (SLevel, Maybe Name) (STm, Either (Name, Impl) Icit)])
go (SApp f a i) = let (f', as) = go f in (f', Right (a, i) : as)
go (SAppLvl f a i) = let (f', as) = go f in (f', Left (a, i) : as)
go (SPos _ s) = go s
go t = (t, [])
showAppArgument :: Either (SLevel, Maybe Name) (STm, Either (Name, Impl) Icit) -> String
showAppArgument (Right (a, Right Expl)) = showSTmS a
showAppArgument (Right (a, Right (Impl ImplUnif))) = "{" ++ show a ++ "}"
showAppArgument (Right (a, Right (Impl ImplInst))) = "{{" ++ show a ++ "}}"
showAppArgument (Right (a, Left (x, ImplUnif))) = "{" ++ showName x ++ " = " ++ show a ++ "}"
showAppArgument (Right (a, Left (x, ImplInst))) = "{{" ++ showName x ++ " = " ++ show a ++ "}}"
showAppArgument (Left (a, Just x)) = "<" ++ x ++ " = " ++ show a ++ ">"
showAppArgument (Left (a, Nothing)) = "<" ++ show a ++ ">"
showSTmLam :: STm -> String
showSTmLam t =
let (xs, b) = go t in
"\\" ++ unwords (map showAbsParameter xs) ++ ". " ++ show b
where
go :: STm -> ([(Name, Either (Maybe Name) (Either (Name, Impl) Icit, Maybe STy))], STm)
go (SLam x i t b) = let (as, b') = go b in ((x, Right (i, t)) : as, b')
go (SLamLvl x i b) = let (as, b') = go b in ((x, Left i) : as, b')
go (SPos _ s) = go s
go t = ([], t)
showAbsParameter :: (Name, Either (Maybe Name) (Either (Name, Impl) Icit, Maybe STy)) -> String
showAbsParameter (x, Right (Right Expl, Nothing)) = showName x
showAbsParameter (x, Right (Right Expl, Just t)) = "(" ++ showName x ++ " : " ++ show t ++ ")"
showAbsParameter (x, Right (Right (Impl ImplUnif), Nothing)) = "{" ++ showName x ++ "}"
showAbsParameter (x, Right (Right (Impl ImplInst), Nothing)) = "{{" ++ showName x ++ "}}"
showAbsParameter (x, Right (Right (Impl ImplUnif), Just t)) = "{" ++ showName x ++ " : " ++ show t ++ "}"
showAbsParameter (x, Right (Right (Impl ImplInst), Just t)) = "{{" ++ showName x ++ " : " ++ show t ++ "}}"
showAbsParameter (x, Right (Left (y, ImplUnif), Nothing)) = "{" ++ showName x ++ " = " ++ y ++ "}"
showAbsParameter (x, Right (Left (y, ImplInst), Nothing)) = "{{" ++ showName x ++ " = " ++ y ++ "}}"
showAbsParameter (x, Right (Left (y, ImplUnif), Just t)) = "{" ++ showName x ++ " : " ++ show t ++ " = " ++ y ++ "}"
showAbsParameter (x, Right (Left (y, ImplInst), Just t)) = "{{" ++ showName x ++ " : " ++ show t ++ " = " ++ y ++ "}}"
showAbsParameter (x, Left (Just y)) = "<" ++ x ++ " = " ++ y ++ ">"
showAbsParameter (x, Left Nothing) = "<" ++ x ++ ">"
showSTmPi :: STm -> String
showSTmPi t =
let (ps, b) = go t in
intercalate " -> " (map showParam ps) ++ " -> " ++ showApp b
where
go :: STm -> ([(Name, Maybe (STm, Icit))], STm)
go (SPi x i t b) = let (ps, b') = go b in ((x, Just (t, i)) : ps, b')
go (SPiLvl x b) = let (ps, b') = go b in ((x, Nothing) : ps, b')
go (SPos _ s) = go s
go t = ([], t)
showApp :: STm -> String
showApp t@SApp {} = show t
showApp t@SAppLvl {} = show t
showApp t@(SType _) = show t
showApp (SPos _ s) = showApp s
showApp t = showSTmS t
showParam :: (Name, Maybe (STm, Icit)) -> String
showParam ("_", Just (t, Expl)) = showApp t
showParam (x, Just (t, Expl)) = "(" ++ showName x ++ " : " ++ show t ++ ")"
showParam (x, Just (t, Impl ImplUnif)) = "{" ++ showName x ++ " : " ++ show t ++ "}"
showParam (x, Just (t, Impl ImplInst)) = "{{" ++ showName x ++ " : " ++ show t ++ "}}"
showParam (x, Nothing) = "<" ++ x ++ ">"
showSTmPair :: STm -> String
showSTmPair s =
let ps = flattenPair s in
case last ps of
SVar "[]" -> "[" ++ intercalate ", " (map show $ init ps) ++ "]"
SRefl -> "[" ++ intercalate ", " (map show $ init ps) ++ "]"
_ -> "(" ++ intercalate ", " (map show ps) ++ ")"
where
flattenPair :: STm -> [STm]
flattenPair (SPair a b) = a : flattenPair b
flattenPair (SPos _ s) = flattenPair s
flattenPair s = [s]
showSTmProj :: STm -> String
showSTmProj s =
let (s', ps) = flattenProj s in
showSTmS s' ++ intercalate "" (map show ps)
where
flattenProj :: STm -> (STm, [SProjType])
flattenProj s = go s []
where
go (SProj b p) ps = go b (p : ps)
go (SPos _ s) ps = go s ps
go s ps = (s, ps)
showSTmSigma :: STm -> String
showSTmSigma t =
let (ps, b) = go t in
intercalate " ** " (map showParam ps) ++ " ** " ++ showApp b
where
go :: STm -> ([(Name, STm)], STm)
go (SSigma x t b) = let (ps, b') = go b in ((x, t) : ps, b')
go (SPos _ s) = go s
go t = ([], t)
showApp :: STm -> String
showApp t@SApp {} = show t
showApp t@SAppLvl {} = show t
showApp t@(SType _) = show t
showApp (SPos _ s) = showApp s
showApp t = showSTmS t
showParam :: (Name, STm) -> String
showParam ("_", t) = showApp t
showParam (x, t) = "(" ++ showName x ++ " : " ++ show t ++ ")"
instance Show STm where
show (SPos _ t) = show t
show (SVar x) = showName x
show (SHole x) = "_" ++ fromMaybe "" x
show t@SApp {} = showSTmApp t
show t@SLam {} = showSTmLam t
show t@SPi {} = showSTmPi t
show t@SAppLvl {} = showSTmApp t
show t@SLamLvl {} = showSTmLam t
show t@(SPiLvl _ _) = showSTmPi t
show t@(SProj _ _) = showSTmProj t
show t@(SPair _ _) = showSTmPair t
show t@(SSigma _ _ _) = showSTmSigma t
show (SCon t) = "Con " ++ showSTmS t
show SRefl = "Refl"
show (SLet x i (Just t) v b) = "let " ++ (if i then "instance " else "") ++ showName x ++ " : " ++ show t ++ " = " ++ show v ++ "; " ++ show b
show (SLet x i Nothing v b) = "let " ++ (if i then "instance " else "") ++ showName x ++ " = " ++ show v ++ "; " ++ show b
show (SType (SLNat 0)) = "Type"
show (SType l) = "Type " ++ showSLevelS l
show (SNatLit i) = show i
show (SLabelLit x) = "'" ++ x
data Decl
= Def Name Bool (Maybe STy) STm
| Import String
instance Show Decl where
show (Def x inst (Just ty) tm) = (if inst then "instance " else "") ++ showName x ++ " : " ++ show ty ++ " = " ++ show tm
show (Def x inst Nothing tm) = (if inst then "instance " else "") ++ showName x ++ " = " ++ show tm
show (Import x) = "import " ++ x
type Decls = [Decl]
showDecls :: Decls -> String
showDecls [] = ""
showDecls (hd : tl) = show hd ++ "\n" ++ showDecls tl
declNames :: Decls -> [String]
declNames [] = []
declNames (Def x _ _ _ : t) = x : declNames t
declNames (_ : t) = declNames t
countNames :: Decls -> Int
countNames = length . declNames
imports :: Decls -> [String]
imports [] = []
imports (Import x : t) = x : imports t
imports (_ : t) = imports t
|
|
428ccdd4b1b4f1daaff9453df5ae4f7e1cea03c53495a790a73c3a2b65b986a9 | nuprl/gradual-typing-performance | main.rkt | #lang racket/base
(require benchmark-util
(only-in racket/file file->lines file->string))
(require (submod "lcs.rkt" unsafe))
(define LARGE_TEST "../base/prufock.txt")
(define SMALL_TEST "../base/hunt.txt")
(define KCFA_TYPED "../base/kcfa-typed.rkt")
LCS on all pairs of lines in a file
(define (main testfile)
(define lines (file->lines testfile))
(for* ([a lines] [b lines])
(longest-common-substring a b))
(void))
( time ( main SMALL_TEST ) ) ; 150ms
( time ( main KCFA_TYPED ) ) ;
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/boundary-configurations/suffixtree/configuration001000-a/main.rkt | racket | 150ms
| #lang racket/base
(require benchmark-util
(only-in racket/file file->lines file->string))
(require (submod "lcs.rkt" unsafe))
(define LARGE_TEST "../base/prufock.txt")
(define SMALL_TEST "../base/hunt.txt")
(define KCFA_TYPED "../base/kcfa-typed.rkt")
LCS on all pairs of lines in a file
(define (main testfile)
(define lines (file->lines testfile))
(for* ([a lines] [b lines])
(longest-common-substring a b))
(void))
|
f26fe0d6320fc18341ea7c0f3dc85322448facc4c54dbf3bd200cfa815377622 | databrary/databrary | File.hs | {-# LANGUAGE OverloadedStrings #-}
module HTTP.File
( fileResponse
, serveFile
) where
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import Data.Monoid ((<>))
import Network.HTTP.Types (ResponseHeaders, hLastModified, hContentType, hCacheControl, hIfModifiedSince, notModified304, hIfRange)
import System.Posix.Types (FileOffset)
import Ops
import Has
import Files
import HTTP.Request
import HTTP
import Action
import Model.Format
fileResponse :: RawFilePath -> Format -> Maybe BS.ByteString -> BS.ByteString -> Handler (ResponseHeaders, Maybe FileOffset)
fileResponse file fmt save etag = do
(sz, mt) <- maybeAction =<< liftIO (fileInfo file)
let fh =
[ ("etag", quoteHTTP etag)
, (hLastModified, formatHTTPTimestamp mt)
, (hContentType, formatMimeType fmt)
, ("content-disposition", maybe "inline" (\n -> "attachment; filename="
<> quoteHTTP (addFormatExtension n fmt)) save)
, (hCacheControl, "max-age=31556926, private")
]
req <- peek
let ifnm = map unquoteHTTP $ (splitHTTP =<<) $ lookupRequestHeaders "if-none-match" req
notmod
| null ifnm = any (mt <=) $ (parseHTTPTimestamp =<<) $ lookupRequestHeader hIfModifiedSince req
| otherwise = any (\m -> m == "*" || m == etag) ifnm
when notmod $ result $ emptyResponse notModified304 fh
return (fh,
-- allow range detection or force full file:
any ((etag /=) . unquoteHTTP) (lookupRequestHeader hIfRange req) `thenUse` sz)
serveFile :: RawFilePath -> Format -> Maybe BS.ByteString -> BS.ByteString -> Handler Response
serveFile file fmt save etag = do
(h, part) <- fileResponse file fmt save etag
fp <- liftIO $ unRawFilePath file
return $ okResponse h (fp, part)
| null | https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/src/HTTP/File.hs | haskell | # LANGUAGE OverloadedStrings #
allow range detection or force full file: | module HTTP.File
( fileResponse
, serveFile
) where
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import Data.Monoid ((<>))
import Network.HTTP.Types (ResponseHeaders, hLastModified, hContentType, hCacheControl, hIfModifiedSince, notModified304, hIfRange)
import System.Posix.Types (FileOffset)
import Ops
import Has
import Files
import HTTP.Request
import HTTP
import Action
import Model.Format
fileResponse :: RawFilePath -> Format -> Maybe BS.ByteString -> BS.ByteString -> Handler (ResponseHeaders, Maybe FileOffset)
fileResponse file fmt save etag = do
(sz, mt) <- maybeAction =<< liftIO (fileInfo file)
let fh =
[ ("etag", quoteHTTP etag)
, (hLastModified, formatHTTPTimestamp mt)
, (hContentType, formatMimeType fmt)
, ("content-disposition", maybe "inline" (\n -> "attachment; filename="
<> quoteHTTP (addFormatExtension n fmt)) save)
, (hCacheControl, "max-age=31556926, private")
]
req <- peek
let ifnm = map unquoteHTTP $ (splitHTTP =<<) $ lookupRequestHeaders "if-none-match" req
notmod
| null ifnm = any (mt <=) $ (parseHTTPTimestamp =<<) $ lookupRequestHeader hIfModifiedSince req
| otherwise = any (\m -> m == "*" || m == etag) ifnm
when notmod $ result $ emptyResponse notModified304 fh
return (fh,
any ((etag /=) . unquoteHTTP) (lookupRequestHeader hIfRange req) `thenUse` sz)
serveFile :: RawFilePath -> Format -> Maybe BS.ByteString -> BS.ByteString -> Handler Response
serveFile file fmt save etag = do
(h, part) <- fileResponse file fmt save etag
fp <- liftIO $ unRawFilePath file
return $ okResponse h (fp, part)
|
3ec53b8be374b9caa91d3a284b90f21cb082da6de1b7efb5b7135eaffd2fb091 | qmuli/qmuli | Stream.hs | # LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Qi.Test.Config.DDB.Stream where
import Control . Lens
import Control . Monad ( void )
import Data . Aeson
import Data . Aeson . Encode . Pretty ( encodePretty )
import Data . Aeson . Lens ( key , nth )
import qualified Data . ByteString . Lazy . Char8 as LBS
import Data . Default ( def )
import Test . Tasty . Hspec
import Qi . Config . AWS.DDB ( DdbAttrDef ( .. ) , DdbAttrType ( .. ) ,
DdbProvCap ( .. ) )
import Qi . Program . Config . Interface ( ConfigProgram , ddbStreamLambda ,
ddbTable )
import Qi . Program . Lambda . Interface ( DdbStreamLambdaProgram )
import Config ( getConfig , getOutputs ,
getResources , getTemplate )
import Protolude
import Util
configProgram : : ConfigProgram ( )
configProgram = do
table < - ddbTable " things " ( DdbAttrDef " name " S ) def
void $ ddbStreamLambda " ddbStreamLambda " table handler def
handler
: : DdbStreamLambdaProgram
handler _ = panic " handler not implemented "
expectedLambdaPhysicalName , expectedDdbTableLogicalName , expectedDdbTableEventSourceMappingLogicalName : : Text
expectedLambdaPhysicalName = " testApp_ddbStreamLambda "
expectedDdbTableLogicalName = " thingsDynamoDBTable "
expectedDdbTableEventSourceMappingLogicalName = " thingsDynamoDBTableEventSourceMapping "
spec : : Spec
spec = describe " Template " $ do
let template = getTemplate $ getConfig configProgram
it " saves test template " $
LBS.writeFile " tests / artifacts / ddb_stream_test_template.json " $ encodePretty template
context " Resources " $ do
let resources = getResources template
-- Table
------------
context " Table " $ do
let resource = getValueUnderKey expectedDdbTableLogicalName resources
-- Properties
context " Properties " $ do
let properties = getValueUnderKey " Properties " resource
it " specifies correct " $
properties ` shouldContainKVPair ` ( " StreamSpecification " , object [
( " StreamViewType " , String " NEW_AND_OLD_IMAGES " )
] )
-- EventSourceMapping
---------
it " has the expected EventSourceMapping resource under the correct logical name " $
resources ` shouldContainKey ` expectedDdbTableEventSourceMappingLogicalName
context " EventSourceMapping " $ do
let resource = getValueUnderKey expectedDdbTableEventSourceMappingLogicalName resources
it " contains correct resource type " $
resource ` shouldContainKVPair ` ( " Type " , String " AWS::Lambda::EventSourceMapping " )
-- Properties
context " Properties " $ do
let properties = getValueUnderKey " Properties " resource
it " specifies EventSourceArn " $
properties ` shouldContainKVPair ` ( " EventSourceArn " , object [
( " Fn::GetAtt " , Array [ String " thingsDynamoDBTable " , String " StreamArn " ] )
] )
it " specifies FunctionName " $
properties ` shouldContainKVPair ` ( " FunctionName " , String expectedLambdaPhysicalName )
-- TODO : this test fails , check if this was removed
{ -
it " specifies StartingPosition " $
properties ` shouldContainKVPair ` ( " StartingPosition " , String " LATEST " )
import Control.Lens
import Control.Monad (void)
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Aeson.Lens (key, nth)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Default (def)
import Test.Tasty.Hspec
import Qi.Config.AWS.DDB (DdbAttrDef (..), DdbAttrType (..),
DdbProvCap (..))
import Qi.Program.Config.Interface (ConfigProgram, ddbStreamLambda,
ddbTable)
import Qi.Program.Lambda.Interface (DdbStreamLambdaProgram)
import Config (getConfig, getOutputs,
getResources, getTemplate)
import Protolude
import Util
configProgram :: ConfigProgram ()
configProgram = do
table <- ddbTable "things" (DdbAttrDef "name" S) def
void $ ddbStreamLambda "ddbStreamLambda" table handler def
handler
:: DdbStreamLambdaProgram
handler _ = panic "handler not implemented"
expectedLambdaPhysicalName, expectedDdbTableLogicalName, expectedDdbTableEventSourceMappingLogicalName :: Text
expectedLambdaPhysicalName = "testApp_ddbStreamLambda"
expectedDdbTableLogicalName = "thingsDynamoDBTable"
expectedDdbTableEventSourceMappingLogicalName = "thingsDynamoDBTableEventSourceMapping"
spec :: Spec
spec = describe "Template" $ do
let template = getTemplate $ getConfig configProgram
it "saves test template" $
LBS.writeFile "tests/artifacts/ddb_stream_test_template.json" $ encodePretty template
context "Resources" $ do
let resources = getResources template
-- Table
------------
context "Table" $ do
let resource = getValueUnderKey expectedDdbTableLogicalName resources
-- Properties
context "Properties" $ do
let properties = getValueUnderKey "Properties" resource
it "specifies correct KeySchema" $
properties `shouldContainKVPair` ("StreamSpecification", object [
("StreamViewType", String "NEW_AND_OLD_IMAGES")
])
-- EventSourceMapping
---------
it "has the expected EventSourceMapping resource under the correct logical name" $
resources `shouldContainKey` expectedDdbTableEventSourceMappingLogicalName
context "EventSourceMapping" $ do
let resource = getValueUnderKey expectedDdbTableEventSourceMappingLogicalName resources
it "contains correct resource type" $
resource `shouldContainKVPair` ("Type", String "AWS::Lambda::EventSourceMapping")
-- Properties
context "Properties" $ do
let properties = getValueUnderKey "Properties" resource
it "specifies EventSourceArn" $
properties `shouldContainKVPair` ("EventSourceArn", object [
("Fn::GetAtt", Array [String "thingsDynamoDBTable", String "StreamArn"])
])
it "specifies FunctionName" $
properties `shouldContainKVPair` ("FunctionName", String expectedLambdaPhysicalName)
-- TODO: this test fails, check if this was removed
{-
it "specifies StartingPosition" $
properties `shouldContainKVPair` ("StartingPosition", String "LATEST")
-}
-}
| null | https://raw.githubusercontent.com/qmuli/qmuli/6ca147f94642b81ab3978d502397efb60a50215b/tests/Qi/Test/Config/DDB/Stream.hs | haskell | # LANGUAGE OverloadedStrings #
Table
----------
Properties
EventSourceMapping
-------
Properties
TODO : this test fails , check if this was removed
Table
----------
Properties
EventSourceMapping
-------
Properties
TODO: this test fails, check if this was removed
it "specifies StartingPosition" $
properties `shouldContainKVPair` ("StartingPosition", String "LATEST")
| # LANGUAGE OverloadedLists #
# LANGUAGE ScopedTypeVariables #
module Qi.Test.Config.DDB.Stream where
import Control . Lens
import Control . Monad ( void )
import Data . Aeson
import Data . Aeson . Encode . Pretty ( encodePretty )
import Data . Aeson . Lens ( key , nth )
import qualified Data . ByteString . Lazy . Char8 as LBS
import Data . Default ( def )
import Test . Tasty . Hspec
import Qi . Config . AWS.DDB ( DdbAttrDef ( .. ) , DdbAttrType ( .. ) ,
DdbProvCap ( .. ) )
import Qi . Program . Config . Interface ( ConfigProgram , ddbStreamLambda ,
ddbTable )
import Qi . Program . Lambda . Interface ( DdbStreamLambdaProgram )
import Config ( getConfig , getOutputs ,
getResources , getTemplate )
import Protolude
import Util
configProgram : : ConfigProgram ( )
configProgram = do
table < - ddbTable " things " ( DdbAttrDef " name " S ) def
void $ ddbStreamLambda " ddbStreamLambda " table handler def
handler
: : DdbStreamLambdaProgram
handler _ = panic " handler not implemented "
expectedLambdaPhysicalName , expectedDdbTableLogicalName , expectedDdbTableEventSourceMappingLogicalName : : Text
expectedLambdaPhysicalName = " testApp_ddbStreamLambda "
expectedDdbTableLogicalName = " thingsDynamoDBTable "
expectedDdbTableEventSourceMappingLogicalName = " thingsDynamoDBTableEventSourceMapping "
spec : : Spec
spec = describe " Template " $ do
let template = getTemplate $ getConfig configProgram
it " saves test template " $
LBS.writeFile " tests / artifacts / ddb_stream_test_template.json " $ encodePretty template
context " Resources " $ do
let resources = getResources template
context " Table " $ do
let resource = getValueUnderKey expectedDdbTableLogicalName resources
context " Properties " $ do
let properties = getValueUnderKey " Properties " resource
it " specifies correct " $
properties ` shouldContainKVPair ` ( " StreamSpecification " , object [
( " StreamViewType " , String " NEW_AND_OLD_IMAGES " )
] )
it " has the expected EventSourceMapping resource under the correct logical name " $
resources ` shouldContainKey ` expectedDdbTableEventSourceMappingLogicalName
context " EventSourceMapping " $ do
let resource = getValueUnderKey expectedDdbTableEventSourceMappingLogicalName resources
it " contains correct resource type " $
resource ` shouldContainKVPair ` ( " Type " , String " AWS::Lambda::EventSourceMapping " )
context " Properties " $ do
let properties = getValueUnderKey " Properties " resource
it " specifies EventSourceArn " $
properties ` shouldContainKVPair ` ( " EventSourceArn " , object [
( " Fn::GetAtt " , Array [ String " thingsDynamoDBTable " , String " StreamArn " ] )
] )
it " specifies FunctionName " $
properties ` shouldContainKVPair ` ( " FunctionName " , String expectedLambdaPhysicalName )
{ -
it " specifies StartingPosition " $
properties ` shouldContainKVPair ` ( " StartingPosition " , String " LATEST " )
import Control.Lens
import Control.Monad (void)
import Data.Aeson
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Aeson.Lens (key, nth)
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Default (def)
import Test.Tasty.Hspec
import Qi.Config.AWS.DDB (DdbAttrDef (..), DdbAttrType (..),
DdbProvCap (..))
import Qi.Program.Config.Interface (ConfigProgram, ddbStreamLambda,
ddbTable)
import Qi.Program.Lambda.Interface (DdbStreamLambdaProgram)
import Config (getConfig, getOutputs,
getResources, getTemplate)
import Protolude
import Util
configProgram :: ConfigProgram ()
configProgram = do
table <- ddbTable "things" (DdbAttrDef "name" S) def
void $ ddbStreamLambda "ddbStreamLambda" table handler def
handler
:: DdbStreamLambdaProgram
handler _ = panic "handler not implemented"
expectedLambdaPhysicalName, expectedDdbTableLogicalName, expectedDdbTableEventSourceMappingLogicalName :: Text
expectedLambdaPhysicalName = "testApp_ddbStreamLambda"
expectedDdbTableLogicalName = "thingsDynamoDBTable"
expectedDdbTableEventSourceMappingLogicalName = "thingsDynamoDBTableEventSourceMapping"
spec :: Spec
spec = describe "Template" $ do
let template = getTemplate $ getConfig configProgram
it "saves test template" $
LBS.writeFile "tests/artifacts/ddb_stream_test_template.json" $ encodePretty template
context "Resources" $ do
let resources = getResources template
context "Table" $ do
let resource = getValueUnderKey expectedDdbTableLogicalName resources
context "Properties" $ do
let properties = getValueUnderKey "Properties" resource
it "specifies correct KeySchema" $
properties `shouldContainKVPair` ("StreamSpecification", object [
("StreamViewType", String "NEW_AND_OLD_IMAGES")
])
it "has the expected EventSourceMapping resource under the correct logical name" $
resources `shouldContainKey` expectedDdbTableEventSourceMappingLogicalName
context "EventSourceMapping" $ do
let resource = getValueUnderKey expectedDdbTableEventSourceMappingLogicalName resources
it "contains correct resource type" $
resource `shouldContainKVPair` ("Type", String "AWS::Lambda::EventSourceMapping")
context "Properties" $ do
let properties = getValueUnderKey "Properties" resource
it "specifies EventSourceArn" $
properties `shouldContainKVPair` ("EventSourceArn", object [
("Fn::GetAtt", Array [String "thingsDynamoDBTable", String "StreamArn"])
])
it "specifies FunctionName" $
properties `shouldContainKVPair` ("FunctionName", String expectedLambdaPhysicalName)
-}
|
f919175ff1f8c4775a6a0975b5b1938399c44eee6b485e3c42019b182af9621e | janestreet/accessor | import.ml | include Accessor.O
| null | https://raw.githubusercontent.com/janestreet/accessor/e905e32c808dfda6950be29987a4bf4f2595fbfc/test_helpers/import.ml | ocaml | include Accessor.O
|
|
275fa8afa8e18fae4715f92ff26787fe18a0ea4744cf398bc59adbe8a0400b4a | rcherrueau/APE | lam+ref.rkt | #lang racket/base
(require (prefix-in r: racket/base)
"utils.rkt")
;; Lambda Calculus + Reference
;;
;; x ∈ Variables (a, b, c, ...)
;;
Expression
;; e ::= x (Variable)
;; | (λ x e) (Abstraction)
;; | (e e) (Application)
;; | r (Mutable Reference)
;;
;; Mutable Reference
;; r ::= (ref e) (Reference)
;; | (set! x e) (Assignment)
| ( deref x ) ( Dereference )
(extends-lang "lam.rkt")
;; Reference
(define-syntax-rule (ref EXP)
(r:box EXP))
;; Assignment
(define-syntax-rule (set! VAR EXP)
(r:set-box! VAR EXP))
Dereference
(define-syntax-rule (deref VAR)
(r:unbox VAR))
(provide (all-defined-out))
| null | https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/pan/attic/lam%2Bref.rkt | racket | Lambda Calculus + Reference
x ∈ Variables (a, b, c, ...)
e ::= x (Variable)
| (λ x e) (Abstraction)
| (e e) (Application)
| r (Mutable Reference)
Mutable Reference
r ::= (ref e) (Reference)
| (set! x e) (Assignment)
Reference
Assignment | #lang racket/base
(require (prefix-in r: racket/base)
"utils.rkt")
Expression
| ( deref x ) ( Dereference )
(extends-lang "lam.rkt")
(define-syntax-rule (ref EXP)
(r:box EXP))
(define-syntax-rule (set! VAR EXP)
(r:set-box! VAR EXP))
Dereference
(define-syntax-rule (deref VAR)
(r:unbox VAR))
(provide (all-defined-out))
|
fcd96adf5aedf5b697d0460eeedad8093aacf8fff18aec3766c278c79533a5dd | Mayvenn/storefront | frontend_transitions.cljs | (ns storefront.frontend-transitions
(:require [adventure.keypaths :as adventure.keypaths]
[catalog.products :as products]
catalog.categories
[cemerick.url :as url]
[clojure.string :as string]
[spice.core :as spice]
[spice.date :as date]
[spice.maps :as maps]
[storefront.accessors.nav :as nav]
[storefront.accessors.orders :as orders]
catalog.keypaths
[storefront.events :as events]
[storefront.keypaths :as keypaths]
[storefront.state :as state]
[storefront.transitions
:refer [transition-state
sign-in-user
clear-fields]
:as transitions]))
(defn clear-nav-traversal
[app-state]
(assoc-in app-state
keypaths/current-traverse-nav
nil))
(defn collapse-menus
([app-state] (collapse-menus app-state nil))
([app-state menus]
(reduce (fn [state menu] (assoc-in state menu false))
app-state
(or menus keypaths/menus))))
(defn clear-field-errors [app-state]
(assoc-in app-state keypaths/errors {}))
(defmethod transition-state events/control-account-profile-submit [_ _event _args app-state]
(let [password (get-in app-state keypaths/manage-account-password)
field-errors (cond-> {}
(> 6 (count password))
(merge (group-by :path [{:path ["password"] :long-message "New password must be at least 6 characters"}])))]
(if (and (seq password) (seq field-errors))
(assoc-in app-state keypaths/errors {:field-errors field-errors :error-code "invalid-input" :error-message "Oops! Please fix the errors below."})
(clear-field-errors app-state))))
(defn clear-flash [app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/flash-now-success nil)
(assoc-in keypaths/flash-now-failure nil)))
(defn add-return-event [app-state]
(let [[return-event return-args] (get-in app-state keypaths/navigation-message)]
(if (nav/return-blacklisted? return-event)
app-state
(assoc-in app-state keypaths/return-navigation-message [return-event return-args]))))
(defn add-pending-promo-code [app-state args]
(let [{{sha :sha} :query-params} args]
(if sha
(assoc-in app-state keypaths/pending-promo-code sha)
app-state)))
(defn add-affiliate-stylist-id
[app-state {{affiliate-stylist-id :affiliate_stylist_id} :query-params}]
(if affiliate-stylist-id
(assoc-in app-state adventure.keypaths/adventure-affiliate-stylist-id (spice/parse-int affiliate-stylist-id))
app-state))
(defn default-credit-card-name [app-state {:keys [first-name last-name]}]
(if-not (string/blank? (get-in app-state keypaths/checkout-credit-card-name))
app-state
(let [default (->> [first-name last-name]
(remove string/blank?)
(string/join " "))]
(if (string/blank? default)
app-state
(assoc-in app-state keypaths/checkout-credit-card-name default)))))
(defmethod transition-state events/stash-nav-stack-item [_ _ stack-item app-state]
(assoc-in app-state keypaths/navigation-stashed-stack-item stack-item))
(def max-nav-stack-depth 5)
(defn push-nav-stack [app-state stack-keypath stack-item]
(let [leaving-nav (get-in app-state keypaths/navigation-message)
item (merge {:navigation-message leaving-nav} stack-item)
nav-stack (get-in app-state stack-keypath nil)]
(take max-nav-stack-depth (conj nav-stack item))))
(defn ^:private str->int [s radix]
(js/parseInt s radix))
(defmethod transition-state events/app-start
[_ _ _ app-state]
(let [session-n (-> (get-in app-state keypaths/session-id) (subs 0 2) (str->int 36))]
(cond-> app-state
FIXME(corey ): abstract this a / b test bucketer
;; (and (= 1 (mod session-n 2))
( not ( contains ? ( set ( get - in app - state keypaths / features ) ) : feature - slug ) ) )
( assoc - in ( / features : feature - slug ) true )
)))
(defmethod transition-state events/navigation-save [_ _ stack-item app-state]
;; Going to a new page; add an element to the undo stack, and discard the redo stack
(let [nav-undo-stack (push-nav-stack app-state keypaths/navigation-undo-stack stack-item)]
(-> app-state
(assoc-in keypaths/navigation-undo-stack nav-undo-stack)
(assoc-in keypaths/navigation-redo-stack nil))))
(defmethod transition-state events/navigation-undo [_ _ stack-item app-state]
Going to prior page ; pop an element from the undo stack , push one onto the redo stack
(let [nav-redo-stack (push-nav-stack app-state keypaths/navigation-redo-stack stack-item)]
(-> app-state
(update-in keypaths/navigation-undo-stack rest)
(assoc-in keypaths/navigation-redo-stack nav-redo-stack))))
(defmethod transition-state events/navigation-redo [_ _ stack-item app-state]
;; Going to next page; pop an element from the redo stack, push one onto the undo stack
(let [nav-undo-stack (push-nav-stack app-state keypaths/navigation-undo-stack stack-item)]
(-> app-state
(assoc-in keypaths/navigation-undo-stack nav-undo-stack)
(update-in keypaths/navigation-redo-stack rest))))
(defmethod transition-state events/redirect [_ event _ app-state]
(assoc-in app-state keypaths/redirecting? true))
(defn clear-completed-order [app-state]
(cond-> app-state
(nav/auth-events (get-in app-state keypaths/navigation-event))
(assoc-in keypaths/completed-order nil)))
(defn prefill-guest-email-address [app-state]
(update-in app-state keypaths/checkout-guest-email
#(or (not-empty %1) %2)
(get-in app-state keypaths/order-user-email)))
;; TODO ask product about this
(def ^:private adventure-slug->video
{"we-are-mayvenn" {:youtube-id "hWJjyy5POTE"}
"free-install" {:youtube-id "oR1keQ-31yc"}})
(defmethod transition-state events/navigate-landing-page
[_ event {:keys [query-params]} app-state]
(when-let [video-id (:video query-params)]
(assoc-in app-state adventure.keypaths/adventure-home-video
(if (= "close" video-id)
nil
{:youtube-id video-id}))))
(defn clean-up-open-category-panels
[app-state
[current-nav-event current-nav-event-args]
[_ previous-nav-event-args]]
(cond-> app-state
(or (not= current-nav-event events/navigate-category)
(not= (:catalog/category-id current-nav-event-args)
(:catalog/category-id previous-nav-event-args)))
(-> (assoc-in keypaths/hide-header? false)
(assoc-in catalog.keypaths/category-panel nil))))
(defn clear-detailed-product-related-addons
[app-state [previous-nav-event _]]
(cond-> app-state
(= previous-nav-event events/navigate-product-details)
(assoc-in catalog.keypaths/detailed-product-related-addons nil)))
(defn update-flash [app-state caused-by]
(cond-> app-state
(not= caused-by :module-load)
(->
clear-flash
(assoc-in keypaths/flash-now-success (get-in app-state keypaths/flash-later-success))
(assoc-in keypaths/flash-now-failure (get-in app-state keypaths/flash-later-failure))
(assoc-in keypaths/flash-later-success nil)
(assoc-in keypaths/flash-later-failure nil))))
(defmethod transition-state events/navigate [_ event args app-state]
(let [args (dissoc args :nav-stack-item)
uri (url/url js/window.location)
new-nav-message [event args]
previous-nav-message (get-in app-state keypaths/navigation-message)]
(-> app-state
collapse-menus
add-return-event
(assoc-in keypaths/footer-email-submitted nil)
(assoc-in keypaths/homepage-email-submitted nil)
(clean-up-open-category-panels new-nav-message previous-nav-message)
(clear-detailed-product-related-addons previous-nav-message)
(add-pending-promo-code args)
(add-affiliate-stylist-id args)
clear-completed-order
(assoc-in keypaths/flyout-stuck-open? false)
(update-flash (:navigate/caused-by args))
(update-in keypaths/ui dissoc :navigation-stashed-stack-item)
(update-in keypaths/models-hdyhau dissoc :to-submit)
(assoc-in keypaths/navigation-uri uri)
;; order is important from here on
(assoc-in keypaths/redirecting? false)
(assoc-in keypaths/navigation-message new-nav-message))))
(def ^:private hostname (comp :host url/url))
(defmethod transition-state events/navigate-cart
[_ event _ app-state]
(-> app-state
(assoc-in keypaths/cart-paypal-redirect false)
(assoc-in keypaths/promo-code-entry-open? false)))
(defmethod transition-state events/navigate-account-manage [_ event args app-state]
(assoc-in app-state
keypaths/manage-account-email
(get-in app-state keypaths/user-email)))
(defmethod transition-state events/control-commission-order-expand [_ _ {:keys [number]} app-state]
(assoc-in app-state keypaths/expanded-commission-order-id #{number}))
(defn ensure-direct-load-of-checkout-auth-advances-to-checkout-flow [app-state]
(let [direct-load? (= [events/navigate-home {}]
(get-in app-state keypaths/return-navigation-message))
previously-upsell? (= [events/navigate-checkout-add nil]
(get-in app-state keypaths/return-navigation-message))]
(cond-> app-state
(or direct-load?
previously-upsell?)
(assoc-in keypaths/return-navigation-message [events/navigate-checkout-address {}]))))
(defmethod transition-state events/navigate-checkout-returning-or-guest [_ event args app-state]
(let [phone-marketing-opt-in (get-in app-state keypaths/order-phone-marketing-opt-in)
phone-transactional-opt-in (get-in app-state keypaths/order-phone-transactional-opt-in)]
(-> app-state
ensure-direct-load-of-checkout-auth-advances-to-checkout-flow
(assoc-in keypaths/checkout-phone-transactional-opt-in phone-transactional-opt-in)
(assoc-in keypaths/checkout-phone-marketing-opt-in phone-marketing-opt-in))))
(defmethod transition-state events/navigate-sign-in [_ event args app-state]
(if-let [signed-in-email (get-in app-state keypaths/user-email)]
(assoc-in app-state keypaths/sign-in-email signed-in-email)
app-state))
(defmethod transition-state events/navigate-checkout-sign-in [_ event args app-state]
(ensure-direct-load-of-checkout-auth-advances-to-checkout-flow app-state))
;; When you navigate to the checkout payment and are fully covered by store
;; credit (and can use it) Choose store-credit as your payment method (changing
;; to a different payment method is guarded in the UI)
(defmethod transition-state events/navigate-checkout-payment [_ event args app-state]
(let [order (get-in app-state keypaths/order)
billing-address (get-in app-state (conj keypaths/order :billing-address))
user (get-in app-state keypaths/user)
covered-by-store-credit-and-can-use-store-credit?
(and (orders/fully-covered-by-store-credit? order user)
(orders/can-use-store-credit? order user))]
(assoc-in (default-credit-card-name app-state billing-address)
keypaths/checkout-selected-payment-methods
(cond
covered-by-store-credit-and-can-use-store-credit?
{:store-credit {}}
(not covered-by-store-credit-and-can-use-store-credit?)
(orders/form-payment-methods order user)
:else
{}))))
(defn ensure-cart-has-shipping-method [app-state]
(-> app-state
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first (get-in app-state keypaths/shipping-methods))
(orders/shipping-item (:order app-state))))))
(defmethod transition-state events/navigate-checkout-address [_ event args app-state]
(let [phone-marketing-opt-in (get-in app-state keypaths/order-phone-marketing-opt-in)
phone-transactional-opt-in (get-in app-state keypaths/order-phone-transactional-opt-in)]
(-> app-state
prefill-guest-email-address
(assoc-in keypaths/checkout-phone-transactional-opt-in phone-transactional-opt-in)
(assoc-in keypaths/checkout-phone-marketing-opt-in phone-marketing-opt-in))))
(defmethod transition-state events/navigate-checkout-confirmation [_ event args app-state]
(let [{east-coast-hour-str :hour
east-coast-weekday :weekday} (->> (date/now)
(.formatToParts
(js/Intl.DateTimeFormat
"en-US" #js
{:timeZone "America/New_York"
:weekday "short"
:hour "numeric"
:hour12 false}))
js->clj
(mapv js->clj)
(mapv (fn [{:strs [type value]}]
{(keyword type) value}))
(reduce merge {}))
parsed-east-coast-hour (spice/parse-int east-coast-hour-str)
mon-thu? (contains? #{"Mon" "Tue" "Wed" "Thu"} east-coast-weekday)
fri? (= "Fri" east-coast-weekday)
in-window? (or (and fri? (< parsed-east-coast-hour 10))
(and mon-thu? (< parsed-east-coast-hour 13)))
was-in-window? (-> app-state (get-in keypaths/checkout-shipping) :note (= :in-shipping-window))]
(-> app-state
ensure-cart-has-shipping-method
(assoc-in keypaths/checkout-shipping {:note (cond
in-window? :in-shipping-window
was-in-window? :was-in-shipping-window
:else nil)
:east-coast-weekday east-coast-weekday
:now (date/now)})
(update-in keypaths/checkout-credit-card-existing-cards empty))))
(defmethod transition-state events/navigate-order-complete [_ event args app-state]
(when-not (get-in app-state keypaths/user-id)
(add-return-event app-state)))
(defmethod transition-state events/control-menu-expand
[_ event {keypath :keypath} app-state]
(-> (reduce (fn [state menu] (assoc-in state menu (= menu keypath)))
app-state
keypaths/menus)
(assoc-in keypaths/slideout-nav-selected-tab :menu)))
(defmethod transition-state events/control-menu-collapse-all
[_ _ {:keys [menus]} app-state]
(-> app-state
clear-nav-traversal
(collapse-menus menus)))
(defmethod transition-state events/control-change-state
[_ event {:keys [keypath value]} app-state]
(assoc-in app-state keypath (if (fn? value) (value) value)))
(defmethod transition-state events/control-focus
[_ event {:keys [keypath]} app-state]
(assoc-in app-state keypaths/ui-focus keypath))
(defmethod transition-state events/control-blur
[_ event _ app-state]
(assoc-in app-state keypaths/ui-focus nil))
(defmethod transition-state events/control-counter-inc [_ event args app-state]
(update-in app-state (:path args) inc))
(defmethod transition-state events/control-counter-dec [_ event args app-state]
(update-in app-state (:path args) (comp (partial max 1) dec)))
(defmethod transition-state events/control-checkout-shipping-method-select
[_ event shipping-method app-state]
(assoc-in app-state keypaths/checkout-selected-shipping-method shipping-method))
(defmethod transition-state events/control-checkout-update-addresses-submit [_ event {:keys [become-guest?]} app-state]
(cond-> app-state
become-guest? (assoc-in keypaths/checkout-as-guest true)))
(defmethod transition-state events/control-checkout-cart-paypal-setup [_ event args app-state]
(assoc-in app-state keypaths/cart-paypal-redirect true))
(defmethod transition-state events/api-start
[_ event request app-state]
(update-in app-state keypaths/api-requests conj request))
(defmethod transition-state events/api-end
[_ event {:keys [request-id app-version] :as request} app-state]
(-> app-state
(update-in keypaths/app-version #(or % app-version))
(update-in keypaths/api-requests (partial remove (comp #{request-id} :request-id)))))
(defmethod transitions/transition-state events/api-success-store-gallery-fetch [_ event {:keys [images]} app-state]
(assoc-in app-state keypaths/store-gallery-images images))
(defmethod transition-state events/api-success-get-saved-cards [_ event {:keys [cards default-card]} app-state]
(let [valid-id? (set (conj (map :id cards) "add-new-card"))]
(cond-> app-state
:start
(assoc-in keypaths/checkout-credit-card-existing-cards cards)
(not (valid-id? (get-in app-state keypaths/checkout-credit-card-selected-id)))
(assoc-in keypaths/checkout-credit-card-selected-id nil)
:finally
(update-in keypaths/checkout-credit-card-selected-id #(or % (:id default-card))))))
(defmethod transition-state events/api-success-facets
[_ event {:keys [facets]} app-state]
(assoc-in app-state keypaths/v2-facets (map #(update % :facet/slug keyword) facets)))
(defmethod transition-state events/api-success-states [_ event {:keys [states]} app-state]
(assoc-in app-state keypaths/states states))
(defn line-items-same? [prev-order order]
(and (= (:number prev-order) (:number order))
(= (->> prev-order orders/all-line-items (map (juxt :sku :quantity)))
(->> order orders/all-line-items (map (juxt :sku :quantity))))))
(defmethod transition-state events/save-order
[_ event {:keys [order]} app-state]
(if (orders/incomplete? order)
(let [previous-order (get-in app-state keypaths/order)]
(cond-> (-> app-state
(assoc-in keypaths/order order)
(update-in keypaths/checkout-billing-address merge (:billing-address order))
(update-in keypaths/checkout-shipping-address merge (:shipping-address order))
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first (get-in app-state keypaths/shipping-methods))
(orders/shipping-item order)))
prefill-guest-email-address)
(not (line-items-same? previous-order order))
(assoc-in keypaths/cart-recently-added-skus (orders/recently-added-sku-ids->quantities previous-order order))))
(assoc-in app-state keypaths/order nil)))
(defmethod transition-state events/clear-order [_ event _ app-state]
(assoc-in app-state keypaths/order nil))
(defmethod transition-state events/api-success-auth [_ event {:keys [user order]} app-state]
(-> app-state
(sign-in-user user)
(clear-fields keypaths/sign-up-email
keypaths/sign-up-password
keypaths/sign-in-email
keypaths/sign-in-password
keypaths/reset-password-password
keypaths/reset-password-token)))
(defmethod transition-state events/api-success-forgot-password [_ event args app-state]
(clear-fields app-state keypaths/forgot-password-email))
(defmethod transition-state events/api-success-decrease-quantity [_ event args app-state]
(assoc-in app-state keypaths/browse-variant-quantity 1))
(defmethod transition-state events/api-success-shared-cart-create [_ event {:keys [cart]} app-state]
(let [domain (cond-> (.-host js/location)
(= "retail-location" (get-in app-state keypaths/store-experience))
(clojure.string/replace-first #"^.*?\." "shop."))]
(-> app-state
(assoc-in keypaths/shared-cart-url (str (.-protocol js/location) "//" domain "/c/" (:number cart)))
(assoc-in keypaths/popup :share-cart))))
(defn derive-all-looks
[cms-data]
(assoc-in cms-data [:ugc-collection :all-looks]
(->> (:ugc-collection cms-data)
vals
(mapcat :looks)
(maps/index-by (comp keyword :content/id)))))
(defmethod transition-state events/api-success-fetch-cms-keypath
[_ event more-cms-data app-state]
(let [existing-cms-data (get-in app-state keypaths/cms)
combined-cms-data (maps/deep-merge existing-cms-data more-cms-data)]
(assoc-in app-state
keypaths/cms
(assoc-in combined-cms-data
[:ugc-collection :all-looks]
(maps/index-by (comp keyword :content/id)
(mapcat :looks
(vals (:ugc-collection combined-cms-data))))))))
(defmethod transition-state events/control-cancel-editing-gallery [_ event args app-state]
(assoc-in app-state keypaths/editing-gallery? false))
(defmethod transition-state events/control-edit-gallery [_ event args app-state]
(assoc-in app-state keypaths/editing-gallery? true))
(defmethod transition-state events/api-success-manage-account [_ event args app-state]
(-> app-state
(sign-in-user args)
(clear-fields keypaths/manage-account-email
keypaths/manage-account-password)))
(defmethod transition-state events/api-success-shipping-methods [_ events {:keys [shipping-methods]} app-state]
(-> app-state
(assoc-in keypaths/shipping-methods shipping-methods)
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first shipping-methods)
(orders/shipping-item (:order app-state))))))
(defn update-account-address [app-state {:keys [billing-address shipping-address]}]
(-> app-state
(merge {:billing-address billing-address
:shipping-address shipping-address})
(default-credit-card-name billing-address)))
(def vals-empty? (comp (partial every? string/blank?) vals))
(defmethod transition-state events/autocomplete-update-address
[_ _ {:keys [address address-keypath]} app-state]
(update-in app-state address-keypath merge address))
(defmethod transition-state events/api-success-account [_ event {:keys [billing-address shipping-address] :as args} app-state]
(-> app-state
(sign-in-user args)
(update-account-address args)
(assoc-in keypaths/checkout-billing-address billing-address)
(assoc-in keypaths/checkout-shipping-address shipping-address)))
(defmethod transition-state events/api-success-update-order-add-promotion-code [_ event args app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/cart-coupon-code "")
(assoc-in keypaths/pending-promo-code nil)))
(defmethod transition-state events/api-success-update-order-remove-promotion-code [_ event args app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/cart-coupon-code "")))
(defmethod transition-state events/api-success-sms-number [_ event args app-state]
(assoc-in app-state keypaths/sms-number (:number args)))
(defmethod transition-state events/order-completed [_ event order app-state]
(-> app-state
(assoc-in keypaths/sign-up-email (get-in app-state keypaths/checkout-guest-email))
(assoc-in keypaths/checkout state/initial-checkout-state)
(assoc-in keypaths/cart state/initial-cart-state)
(assoc-in keypaths/completed-order order)))
(defmethod transition-state events/api-success-promotions [_ event {promotions :promotions} app-state]
(update-in app-state keypaths/promotions #(-> (concat % promotions) set vec)))
(defmethod transition-state events/api-success-get-static-content
[_ event args app-state]
(assoc-in app-state keypaths/static args))
(defmethod transition-state events/api-success-cache [_ event new-data app-state]
(update-in app-state keypaths/api-cache merge new-data))
(defmethod transition-state events/api-failure-errors [_ event errors app-state]
(-> app-state
clear-flash
(assoc-in keypaths/errors (update errors :field-errors (partial group-by :path)))))
(defmethod transition-state events/api-failure-order-not-created-from-shared-cart [_ event args app-state]
(when-let [error-message (get-in app-state keypaths/error-message)]
(assoc-in app-state keypaths/flash-later-failure {:message error-message})))
(defmethod transition-state events/api-failure-pending-promo-code [_ event args app-state]
(assoc-in app-state keypaths/pending-promo-code nil))
(defmethod transition-state events/flash-show-success [_ _ {:keys [message]} app-state]
(-> app-state
clear-flash
(assoc-in keypaths/flash-now-success {:message message})))
(defmethod transition-state events/flash-show-failure [_ _ {:keys [message]} app-state]
(-> app-state
clear-flash
(assoc-in keypaths/flash-now-failure {:message message})))
(defmethod transition-state events/flash-later-show-success [_ _ {:keys [message]} app-state]
(assoc-in app-state keypaths/flash-later-success {:message message}))
(defmethod transition-state events/flash-later-show-failure [_ _ {:keys [message]} app-state]
(assoc-in app-state keypaths/flash-later-failure {:message message}))
(defmethod transition-state events/flash-dismiss [_ event args app-state]
(clear-flash app-state))
(defmethod transition-state events/bucketed-for [_ event {:keys [experiment]} app-state]
(-> app-state
(update-in keypaths/experiments-bucketed conj experiment)))
(defmethod transition-state events/enable-feature [_ event {:keys [feature]} app-state]
(cond-> app-state
(and (string? feature)
(not (contains? (set (get-in app-state keypaths/features)) feature)))
(assoc-in (conj keypaths/features (keyword feature)) true)
(and (vector? feature)
(->> (get-in app-state keypaths/features) keys (some (partial = (first feature))) not))
(assoc-in (conj keypaths/features (first feature)) (last feature))))
(defmethod transition-state events/clear-features [_ event _ app-state]
(update-in app-state keypaths/features empty))
(defmethod transition-state events/inserted-google-maps [_ event args app-state]
(assoc-in app-state keypaths/loaded-google-maps true))
(defmethod transition-state events/inserted-quadpay [_ event _ app-state]
(assoc-in app-state keypaths/loaded-quadpay true))
(defmethod transition-state events/inserted-stripe [_ event _ app-state]
(assoc-in app-state keypaths/loaded-stripe true))
(defmethod transition-state events/inserted-uploadcare [_ _ _ app-state]
(assoc-in app-state keypaths/loaded-uploadcare true))
(defmethod transition-state events/stripe-component-mounted [_ event {:keys [card-element]} app-state]
(assoc-in app-state keypaths/stripe-card-element card-element))
(defmethod transition-state events/stripe-component-will-unmount [_ event _ app-state]
(update-in app-state keypaths/stripe-card-element dissoc))
(defmethod transition-state events/sign-out [_ event args app-state]
(-> app-state
transitions/clear-sensitive-info
(assoc-in keypaths/v2-dashboard state/initial-dashboard-state)
(assoc-in keypaths/user {})
(assoc-in keypaths/completed-order nil)
(assoc-in keypaths/stylist state/initial-stylist-state)
(assoc-in keypaths/checkout state/initial-checkout-state)
(assoc-in keypaths/billing-address {})
(assoc-in keypaths/shipping-address {})))
(defmethod transition-state events/stripe-failure-create-token [_ event stripe-response app-state]
(let [{:keys [code message]} (:error stripe-response)]
(assoc-in app-state keypaths/errors
{:error-code code
:error-message message})))
(defmethod transitions/transition-state events/faq-section-selected [_ _ {:keys [index]} app-state]
(let [expanded-index (get-in app-state keypaths/faq-expanded-section)]
(if (= index expanded-index)
(assoc-in app-state keypaths/faq-expanded-section nil)
(assoc-in app-state keypaths/faq-expanded-section index))))
(defmethod transition-state events/api-success-user-stylist-service-menu-fetch [_ event {:keys [menu]} app-state]
(cond-> app-state
menu (assoc-in keypaths/user-stylist-service-menu menu)))
(defmethod transition-state events/api-success-user-stylist-offered-services
[_ event {:keys [menu]} app-state]
(cond-> app-state
(seq menu)
(assoc-in keypaths/user-stylist-offered-services
(maps/index-by (comp keyword :offered-service-slug) menu))))
(defmethod transition-state events/stringer-browser-identified
[_ _ {:keys [id]} app-state]
(assoc-in app-state keypaths/stringer-browser-id id))
(defmethod transition-state events/module-loaded [_ _ {:keys [module-name]} app-state]
(when module-name
(update app-state :modules (fnil conj #{}) module-name)))
(defmethod transition-state events/api-success-get-skus
[_ event args app-state]
(update-in app-state keypaths/v2-skus #(merge (-> args :skus products/index-skus) %)))
(defmethod transition-state events/api-success-fetch-geo-location-from-ip
[_ event args app-state]
(update-in app-state keypaths/account-profile-ip-addresses #(conj % args)))
| null | https://raw.githubusercontent.com/Mayvenn/storefront/38fc7a2ef1e77addc185319e9e846ae20b803fe1/src-cljs/storefront/frontend_transitions.cljs | clojure | (and (= 1 (mod session-n 2))
Going to a new page; add an element to the undo stack, and discard the redo stack
pop an element from the undo stack , push one onto the redo stack
Going to next page; pop an element from the redo stack, push one onto the undo stack
TODO ask product about this
order is important from here on
When you navigate to the checkout payment and are fully covered by store
credit (and can use it) Choose store-credit as your payment method (changing
to a different payment method is guarded in the UI) | (ns storefront.frontend-transitions
(:require [adventure.keypaths :as adventure.keypaths]
[catalog.products :as products]
catalog.categories
[cemerick.url :as url]
[clojure.string :as string]
[spice.core :as spice]
[spice.date :as date]
[spice.maps :as maps]
[storefront.accessors.nav :as nav]
[storefront.accessors.orders :as orders]
catalog.keypaths
[storefront.events :as events]
[storefront.keypaths :as keypaths]
[storefront.state :as state]
[storefront.transitions
:refer [transition-state
sign-in-user
clear-fields]
:as transitions]))
(defn clear-nav-traversal
[app-state]
(assoc-in app-state
keypaths/current-traverse-nav
nil))
(defn collapse-menus
([app-state] (collapse-menus app-state nil))
([app-state menus]
(reduce (fn [state menu] (assoc-in state menu false))
app-state
(or menus keypaths/menus))))
(defn clear-field-errors [app-state]
(assoc-in app-state keypaths/errors {}))
(defmethod transition-state events/control-account-profile-submit [_ _event _args app-state]
(let [password (get-in app-state keypaths/manage-account-password)
field-errors (cond-> {}
(> 6 (count password))
(merge (group-by :path [{:path ["password"] :long-message "New password must be at least 6 characters"}])))]
(if (and (seq password) (seq field-errors))
(assoc-in app-state keypaths/errors {:field-errors field-errors :error-code "invalid-input" :error-message "Oops! Please fix the errors below."})
(clear-field-errors app-state))))
(defn clear-flash [app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/flash-now-success nil)
(assoc-in keypaths/flash-now-failure nil)))
(defn add-return-event [app-state]
(let [[return-event return-args] (get-in app-state keypaths/navigation-message)]
(if (nav/return-blacklisted? return-event)
app-state
(assoc-in app-state keypaths/return-navigation-message [return-event return-args]))))
(defn add-pending-promo-code [app-state args]
(let [{{sha :sha} :query-params} args]
(if sha
(assoc-in app-state keypaths/pending-promo-code sha)
app-state)))
(defn add-affiliate-stylist-id
[app-state {{affiliate-stylist-id :affiliate_stylist_id} :query-params}]
(if affiliate-stylist-id
(assoc-in app-state adventure.keypaths/adventure-affiliate-stylist-id (spice/parse-int affiliate-stylist-id))
app-state))
(defn default-credit-card-name [app-state {:keys [first-name last-name]}]
(if-not (string/blank? (get-in app-state keypaths/checkout-credit-card-name))
app-state
(let [default (->> [first-name last-name]
(remove string/blank?)
(string/join " "))]
(if (string/blank? default)
app-state
(assoc-in app-state keypaths/checkout-credit-card-name default)))))
(defmethod transition-state events/stash-nav-stack-item [_ _ stack-item app-state]
(assoc-in app-state keypaths/navigation-stashed-stack-item stack-item))
(def max-nav-stack-depth 5)
(defn push-nav-stack [app-state stack-keypath stack-item]
(let [leaving-nav (get-in app-state keypaths/navigation-message)
item (merge {:navigation-message leaving-nav} stack-item)
nav-stack (get-in app-state stack-keypath nil)]
(take max-nav-stack-depth (conj nav-stack item))))
(defn ^:private str->int [s radix]
(js/parseInt s radix))
(defmethod transition-state events/app-start
[_ _ _ app-state]
(let [session-n (-> (get-in app-state keypaths/session-id) (subs 0 2) (str->int 36))]
(cond-> app-state
FIXME(corey ): abstract this a / b test bucketer
( not ( contains ? ( set ( get - in app - state keypaths / features ) ) : feature - slug ) ) )
( assoc - in ( / features : feature - slug ) true )
)))
(defmethod transition-state events/navigation-save [_ _ stack-item app-state]
(let [nav-undo-stack (push-nav-stack app-state keypaths/navigation-undo-stack stack-item)]
(-> app-state
(assoc-in keypaths/navigation-undo-stack nav-undo-stack)
(assoc-in keypaths/navigation-redo-stack nil))))
(defmethod transition-state events/navigation-undo [_ _ stack-item app-state]
(let [nav-redo-stack (push-nav-stack app-state keypaths/navigation-redo-stack stack-item)]
(-> app-state
(update-in keypaths/navigation-undo-stack rest)
(assoc-in keypaths/navigation-redo-stack nav-redo-stack))))
(defmethod transition-state events/navigation-redo [_ _ stack-item app-state]
(let [nav-undo-stack (push-nav-stack app-state keypaths/navigation-undo-stack stack-item)]
(-> app-state
(assoc-in keypaths/navigation-undo-stack nav-undo-stack)
(update-in keypaths/navigation-redo-stack rest))))
(defmethod transition-state events/redirect [_ event _ app-state]
(assoc-in app-state keypaths/redirecting? true))
(defn clear-completed-order [app-state]
(cond-> app-state
(nav/auth-events (get-in app-state keypaths/navigation-event))
(assoc-in keypaths/completed-order nil)))
(defn prefill-guest-email-address [app-state]
(update-in app-state keypaths/checkout-guest-email
#(or (not-empty %1) %2)
(get-in app-state keypaths/order-user-email)))
(def ^:private adventure-slug->video
{"we-are-mayvenn" {:youtube-id "hWJjyy5POTE"}
"free-install" {:youtube-id "oR1keQ-31yc"}})
(defmethod transition-state events/navigate-landing-page
[_ event {:keys [query-params]} app-state]
(when-let [video-id (:video query-params)]
(assoc-in app-state adventure.keypaths/adventure-home-video
(if (= "close" video-id)
nil
{:youtube-id video-id}))))
(defn clean-up-open-category-panels
[app-state
[current-nav-event current-nav-event-args]
[_ previous-nav-event-args]]
(cond-> app-state
(or (not= current-nav-event events/navigate-category)
(not= (:catalog/category-id current-nav-event-args)
(:catalog/category-id previous-nav-event-args)))
(-> (assoc-in keypaths/hide-header? false)
(assoc-in catalog.keypaths/category-panel nil))))
(defn clear-detailed-product-related-addons
[app-state [previous-nav-event _]]
(cond-> app-state
(= previous-nav-event events/navigate-product-details)
(assoc-in catalog.keypaths/detailed-product-related-addons nil)))
(defn update-flash [app-state caused-by]
(cond-> app-state
(not= caused-by :module-load)
(->
clear-flash
(assoc-in keypaths/flash-now-success (get-in app-state keypaths/flash-later-success))
(assoc-in keypaths/flash-now-failure (get-in app-state keypaths/flash-later-failure))
(assoc-in keypaths/flash-later-success nil)
(assoc-in keypaths/flash-later-failure nil))))
(defmethod transition-state events/navigate [_ event args app-state]
(let [args (dissoc args :nav-stack-item)
uri (url/url js/window.location)
new-nav-message [event args]
previous-nav-message (get-in app-state keypaths/navigation-message)]
(-> app-state
collapse-menus
add-return-event
(assoc-in keypaths/footer-email-submitted nil)
(assoc-in keypaths/homepage-email-submitted nil)
(clean-up-open-category-panels new-nav-message previous-nav-message)
(clear-detailed-product-related-addons previous-nav-message)
(add-pending-promo-code args)
(add-affiliate-stylist-id args)
clear-completed-order
(assoc-in keypaths/flyout-stuck-open? false)
(update-flash (:navigate/caused-by args))
(update-in keypaths/ui dissoc :navigation-stashed-stack-item)
(update-in keypaths/models-hdyhau dissoc :to-submit)
(assoc-in keypaths/navigation-uri uri)
(assoc-in keypaths/redirecting? false)
(assoc-in keypaths/navigation-message new-nav-message))))
(def ^:private hostname (comp :host url/url))
(defmethod transition-state events/navigate-cart
[_ event _ app-state]
(-> app-state
(assoc-in keypaths/cart-paypal-redirect false)
(assoc-in keypaths/promo-code-entry-open? false)))
(defmethod transition-state events/navigate-account-manage [_ event args app-state]
(assoc-in app-state
keypaths/manage-account-email
(get-in app-state keypaths/user-email)))
(defmethod transition-state events/control-commission-order-expand [_ _ {:keys [number]} app-state]
(assoc-in app-state keypaths/expanded-commission-order-id #{number}))
(defn ensure-direct-load-of-checkout-auth-advances-to-checkout-flow [app-state]
(let [direct-load? (= [events/navigate-home {}]
(get-in app-state keypaths/return-navigation-message))
previously-upsell? (= [events/navigate-checkout-add nil]
(get-in app-state keypaths/return-navigation-message))]
(cond-> app-state
(or direct-load?
previously-upsell?)
(assoc-in keypaths/return-navigation-message [events/navigate-checkout-address {}]))))
(defmethod transition-state events/navigate-checkout-returning-or-guest [_ event args app-state]
(let [phone-marketing-opt-in (get-in app-state keypaths/order-phone-marketing-opt-in)
phone-transactional-opt-in (get-in app-state keypaths/order-phone-transactional-opt-in)]
(-> app-state
ensure-direct-load-of-checkout-auth-advances-to-checkout-flow
(assoc-in keypaths/checkout-phone-transactional-opt-in phone-transactional-opt-in)
(assoc-in keypaths/checkout-phone-marketing-opt-in phone-marketing-opt-in))))
(defmethod transition-state events/navigate-sign-in [_ event args app-state]
(if-let [signed-in-email (get-in app-state keypaths/user-email)]
(assoc-in app-state keypaths/sign-in-email signed-in-email)
app-state))
(defmethod transition-state events/navigate-checkout-sign-in [_ event args app-state]
(ensure-direct-load-of-checkout-auth-advances-to-checkout-flow app-state))
(defmethod transition-state events/navigate-checkout-payment [_ event args app-state]
(let [order (get-in app-state keypaths/order)
billing-address (get-in app-state (conj keypaths/order :billing-address))
user (get-in app-state keypaths/user)
covered-by-store-credit-and-can-use-store-credit?
(and (orders/fully-covered-by-store-credit? order user)
(orders/can-use-store-credit? order user))]
(assoc-in (default-credit-card-name app-state billing-address)
keypaths/checkout-selected-payment-methods
(cond
covered-by-store-credit-and-can-use-store-credit?
{:store-credit {}}
(not covered-by-store-credit-and-can-use-store-credit?)
(orders/form-payment-methods order user)
:else
{}))))
(defn ensure-cart-has-shipping-method [app-state]
(-> app-state
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first (get-in app-state keypaths/shipping-methods))
(orders/shipping-item (:order app-state))))))
(defmethod transition-state events/navigate-checkout-address [_ event args app-state]
(let [phone-marketing-opt-in (get-in app-state keypaths/order-phone-marketing-opt-in)
phone-transactional-opt-in (get-in app-state keypaths/order-phone-transactional-opt-in)]
(-> app-state
prefill-guest-email-address
(assoc-in keypaths/checkout-phone-transactional-opt-in phone-transactional-opt-in)
(assoc-in keypaths/checkout-phone-marketing-opt-in phone-marketing-opt-in))))
(defmethod transition-state events/navigate-checkout-confirmation [_ event args app-state]
(let [{east-coast-hour-str :hour
east-coast-weekday :weekday} (->> (date/now)
(.formatToParts
(js/Intl.DateTimeFormat
"en-US" #js
{:timeZone "America/New_York"
:weekday "short"
:hour "numeric"
:hour12 false}))
js->clj
(mapv js->clj)
(mapv (fn [{:strs [type value]}]
{(keyword type) value}))
(reduce merge {}))
parsed-east-coast-hour (spice/parse-int east-coast-hour-str)
mon-thu? (contains? #{"Mon" "Tue" "Wed" "Thu"} east-coast-weekday)
fri? (= "Fri" east-coast-weekday)
in-window? (or (and fri? (< parsed-east-coast-hour 10))
(and mon-thu? (< parsed-east-coast-hour 13)))
was-in-window? (-> app-state (get-in keypaths/checkout-shipping) :note (= :in-shipping-window))]
(-> app-state
ensure-cart-has-shipping-method
(assoc-in keypaths/checkout-shipping {:note (cond
in-window? :in-shipping-window
was-in-window? :was-in-shipping-window
:else nil)
:east-coast-weekday east-coast-weekday
:now (date/now)})
(update-in keypaths/checkout-credit-card-existing-cards empty))))
(defmethod transition-state events/navigate-order-complete [_ event args app-state]
(when-not (get-in app-state keypaths/user-id)
(add-return-event app-state)))
(defmethod transition-state events/control-menu-expand
[_ event {keypath :keypath} app-state]
(-> (reduce (fn [state menu] (assoc-in state menu (= menu keypath)))
app-state
keypaths/menus)
(assoc-in keypaths/slideout-nav-selected-tab :menu)))
(defmethod transition-state events/control-menu-collapse-all
[_ _ {:keys [menus]} app-state]
(-> app-state
clear-nav-traversal
(collapse-menus menus)))
(defmethod transition-state events/control-change-state
[_ event {:keys [keypath value]} app-state]
(assoc-in app-state keypath (if (fn? value) (value) value)))
(defmethod transition-state events/control-focus
[_ event {:keys [keypath]} app-state]
(assoc-in app-state keypaths/ui-focus keypath))
(defmethod transition-state events/control-blur
[_ event _ app-state]
(assoc-in app-state keypaths/ui-focus nil))
(defmethod transition-state events/control-counter-inc [_ event args app-state]
(update-in app-state (:path args) inc))
(defmethod transition-state events/control-counter-dec [_ event args app-state]
(update-in app-state (:path args) (comp (partial max 1) dec)))
(defmethod transition-state events/control-checkout-shipping-method-select
[_ event shipping-method app-state]
(assoc-in app-state keypaths/checkout-selected-shipping-method shipping-method))
(defmethod transition-state events/control-checkout-update-addresses-submit [_ event {:keys [become-guest?]} app-state]
(cond-> app-state
become-guest? (assoc-in keypaths/checkout-as-guest true)))
(defmethod transition-state events/control-checkout-cart-paypal-setup [_ event args app-state]
(assoc-in app-state keypaths/cart-paypal-redirect true))
(defmethod transition-state events/api-start
[_ event request app-state]
(update-in app-state keypaths/api-requests conj request))
(defmethod transition-state events/api-end
[_ event {:keys [request-id app-version] :as request} app-state]
(-> app-state
(update-in keypaths/app-version #(or % app-version))
(update-in keypaths/api-requests (partial remove (comp #{request-id} :request-id)))))
(defmethod transitions/transition-state events/api-success-store-gallery-fetch [_ event {:keys [images]} app-state]
(assoc-in app-state keypaths/store-gallery-images images))
(defmethod transition-state events/api-success-get-saved-cards [_ event {:keys [cards default-card]} app-state]
(let [valid-id? (set (conj (map :id cards) "add-new-card"))]
(cond-> app-state
:start
(assoc-in keypaths/checkout-credit-card-existing-cards cards)
(not (valid-id? (get-in app-state keypaths/checkout-credit-card-selected-id)))
(assoc-in keypaths/checkout-credit-card-selected-id nil)
:finally
(update-in keypaths/checkout-credit-card-selected-id #(or % (:id default-card))))))
(defmethod transition-state events/api-success-facets
[_ event {:keys [facets]} app-state]
(assoc-in app-state keypaths/v2-facets (map #(update % :facet/slug keyword) facets)))
(defmethod transition-state events/api-success-states [_ event {:keys [states]} app-state]
(assoc-in app-state keypaths/states states))
(defn line-items-same? [prev-order order]
(and (= (:number prev-order) (:number order))
(= (->> prev-order orders/all-line-items (map (juxt :sku :quantity)))
(->> order orders/all-line-items (map (juxt :sku :quantity))))))
(defmethod transition-state events/save-order
[_ event {:keys [order]} app-state]
(if (orders/incomplete? order)
(let [previous-order (get-in app-state keypaths/order)]
(cond-> (-> app-state
(assoc-in keypaths/order order)
(update-in keypaths/checkout-billing-address merge (:billing-address order))
(update-in keypaths/checkout-shipping-address merge (:shipping-address order))
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first (get-in app-state keypaths/shipping-methods))
(orders/shipping-item order)))
prefill-guest-email-address)
(not (line-items-same? previous-order order))
(assoc-in keypaths/cart-recently-added-skus (orders/recently-added-sku-ids->quantities previous-order order))))
(assoc-in app-state keypaths/order nil)))
(defmethod transition-state events/clear-order [_ event _ app-state]
(assoc-in app-state keypaths/order nil))
(defmethod transition-state events/api-success-auth [_ event {:keys [user order]} app-state]
(-> app-state
(sign-in-user user)
(clear-fields keypaths/sign-up-email
keypaths/sign-up-password
keypaths/sign-in-email
keypaths/sign-in-password
keypaths/reset-password-password
keypaths/reset-password-token)))
(defmethod transition-state events/api-success-forgot-password [_ event args app-state]
(clear-fields app-state keypaths/forgot-password-email))
(defmethod transition-state events/api-success-decrease-quantity [_ event args app-state]
(assoc-in app-state keypaths/browse-variant-quantity 1))
(defmethod transition-state events/api-success-shared-cart-create [_ event {:keys [cart]} app-state]
(let [domain (cond-> (.-host js/location)
(= "retail-location" (get-in app-state keypaths/store-experience))
(clojure.string/replace-first #"^.*?\." "shop."))]
(-> app-state
(assoc-in keypaths/shared-cart-url (str (.-protocol js/location) "//" domain "/c/" (:number cart)))
(assoc-in keypaths/popup :share-cart))))
(defn derive-all-looks
[cms-data]
(assoc-in cms-data [:ugc-collection :all-looks]
(->> (:ugc-collection cms-data)
vals
(mapcat :looks)
(maps/index-by (comp keyword :content/id)))))
(defmethod transition-state events/api-success-fetch-cms-keypath
[_ event more-cms-data app-state]
(let [existing-cms-data (get-in app-state keypaths/cms)
combined-cms-data (maps/deep-merge existing-cms-data more-cms-data)]
(assoc-in app-state
keypaths/cms
(assoc-in combined-cms-data
[:ugc-collection :all-looks]
(maps/index-by (comp keyword :content/id)
(mapcat :looks
(vals (:ugc-collection combined-cms-data))))))))
(defmethod transition-state events/control-cancel-editing-gallery [_ event args app-state]
(assoc-in app-state keypaths/editing-gallery? false))
(defmethod transition-state events/control-edit-gallery [_ event args app-state]
(assoc-in app-state keypaths/editing-gallery? true))
(defmethod transition-state events/api-success-manage-account [_ event args app-state]
(-> app-state
(sign-in-user args)
(clear-fields keypaths/manage-account-email
keypaths/manage-account-password)))
(defmethod transition-state events/api-success-shipping-methods [_ events {:keys [shipping-methods]} app-state]
(-> app-state
(assoc-in keypaths/shipping-methods shipping-methods)
(assoc-in keypaths/checkout-selected-shipping-method
(merge (first shipping-methods)
(orders/shipping-item (:order app-state))))))
(defn update-account-address [app-state {:keys [billing-address shipping-address]}]
(-> app-state
(merge {:billing-address billing-address
:shipping-address shipping-address})
(default-credit-card-name billing-address)))
(def vals-empty? (comp (partial every? string/blank?) vals))
(defmethod transition-state events/autocomplete-update-address
[_ _ {:keys [address address-keypath]} app-state]
(update-in app-state address-keypath merge address))
(defmethod transition-state events/api-success-account [_ event {:keys [billing-address shipping-address] :as args} app-state]
(-> app-state
(sign-in-user args)
(update-account-address args)
(assoc-in keypaths/checkout-billing-address billing-address)
(assoc-in keypaths/checkout-shipping-address shipping-address)))
(defmethod transition-state events/api-success-update-order-add-promotion-code [_ event args app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/cart-coupon-code "")
(assoc-in keypaths/pending-promo-code nil)))
(defmethod transition-state events/api-success-update-order-remove-promotion-code [_ event args app-state]
(-> app-state
clear-field-errors
(assoc-in keypaths/cart-coupon-code "")))
(defmethod transition-state events/api-success-sms-number [_ event args app-state]
(assoc-in app-state keypaths/sms-number (:number args)))
(defmethod transition-state events/order-completed [_ event order app-state]
(-> app-state
(assoc-in keypaths/sign-up-email (get-in app-state keypaths/checkout-guest-email))
(assoc-in keypaths/checkout state/initial-checkout-state)
(assoc-in keypaths/cart state/initial-cart-state)
(assoc-in keypaths/completed-order order)))
(defmethod transition-state events/api-success-promotions [_ event {promotions :promotions} app-state]
(update-in app-state keypaths/promotions #(-> (concat % promotions) set vec)))
(defmethod transition-state events/api-success-get-static-content
[_ event args app-state]
(assoc-in app-state keypaths/static args))
(defmethod transition-state events/api-success-cache [_ event new-data app-state]
(update-in app-state keypaths/api-cache merge new-data))
(defmethod transition-state events/api-failure-errors [_ event errors app-state]
(-> app-state
clear-flash
(assoc-in keypaths/errors (update errors :field-errors (partial group-by :path)))))
(defmethod transition-state events/api-failure-order-not-created-from-shared-cart [_ event args app-state]
(when-let [error-message (get-in app-state keypaths/error-message)]
(assoc-in app-state keypaths/flash-later-failure {:message error-message})))
(defmethod transition-state events/api-failure-pending-promo-code [_ event args app-state]
(assoc-in app-state keypaths/pending-promo-code nil))
(defmethod transition-state events/flash-show-success [_ _ {:keys [message]} app-state]
(-> app-state
clear-flash
(assoc-in keypaths/flash-now-success {:message message})))
(defmethod transition-state events/flash-show-failure [_ _ {:keys [message]} app-state]
(-> app-state
clear-flash
(assoc-in keypaths/flash-now-failure {:message message})))
(defmethod transition-state events/flash-later-show-success [_ _ {:keys [message]} app-state]
(assoc-in app-state keypaths/flash-later-success {:message message}))
(defmethod transition-state events/flash-later-show-failure [_ _ {:keys [message]} app-state]
(assoc-in app-state keypaths/flash-later-failure {:message message}))
(defmethod transition-state events/flash-dismiss [_ event args app-state]
(clear-flash app-state))
(defmethod transition-state events/bucketed-for [_ event {:keys [experiment]} app-state]
(-> app-state
(update-in keypaths/experiments-bucketed conj experiment)))
(defmethod transition-state events/enable-feature [_ event {:keys [feature]} app-state]
(cond-> app-state
(and (string? feature)
(not (contains? (set (get-in app-state keypaths/features)) feature)))
(assoc-in (conj keypaths/features (keyword feature)) true)
(and (vector? feature)
(->> (get-in app-state keypaths/features) keys (some (partial = (first feature))) not))
(assoc-in (conj keypaths/features (first feature)) (last feature))))
(defmethod transition-state events/clear-features [_ event _ app-state]
(update-in app-state keypaths/features empty))
(defmethod transition-state events/inserted-google-maps [_ event args app-state]
(assoc-in app-state keypaths/loaded-google-maps true))
(defmethod transition-state events/inserted-quadpay [_ event _ app-state]
(assoc-in app-state keypaths/loaded-quadpay true))
(defmethod transition-state events/inserted-stripe [_ event _ app-state]
(assoc-in app-state keypaths/loaded-stripe true))
(defmethod transition-state events/inserted-uploadcare [_ _ _ app-state]
(assoc-in app-state keypaths/loaded-uploadcare true))
(defmethod transition-state events/stripe-component-mounted [_ event {:keys [card-element]} app-state]
(assoc-in app-state keypaths/stripe-card-element card-element))
(defmethod transition-state events/stripe-component-will-unmount [_ event _ app-state]
(update-in app-state keypaths/stripe-card-element dissoc))
(defmethod transition-state events/sign-out [_ event args app-state]
(-> app-state
transitions/clear-sensitive-info
(assoc-in keypaths/v2-dashboard state/initial-dashboard-state)
(assoc-in keypaths/user {})
(assoc-in keypaths/completed-order nil)
(assoc-in keypaths/stylist state/initial-stylist-state)
(assoc-in keypaths/checkout state/initial-checkout-state)
(assoc-in keypaths/billing-address {})
(assoc-in keypaths/shipping-address {})))
(defmethod transition-state events/stripe-failure-create-token [_ event stripe-response app-state]
(let [{:keys [code message]} (:error stripe-response)]
(assoc-in app-state keypaths/errors
{:error-code code
:error-message message})))
(defmethod transitions/transition-state events/faq-section-selected [_ _ {:keys [index]} app-state]
(let [expanded-index (get-in app-state keypaths/faq-expanded-section)]
(if (= index expanded-index)
(assoc-in app-state keypaths/faq-expanded-section nil)
(assoc-in app-state keypaths/faq-expanded-section index))))
(defmethod transition-state events/api-success-user-stylist-service-menu-fetch [_ event {:keys [menu]} app-state]
(cond-> app-state
menu (assoc-in keypaths/user-stylist-service-menu menu)))
(defmethod transition-state events/api-success-user-stylist-offered-services
[_ event {:keys [menu]} app-state]
(cond-> app-state
(seq menu)
(assoc-in keypaths/user-stylist-offered-services
(maps/index-by (comp keyword :offered-service-slug) menu))))
(defmethod transition-state events/stringer-browser-identified
[_ _ {:keys [id]} app-state]
(assoc-in app-state keypaths/stringer-browser-id id))
(defmethod transition-state events/module-loaded [_ _ {:keys [module-name]} app-state]
(when module-name
(update app-state :modules (fnil conj #{}) module-name)))
(defmethod transition-state events/api-success-get-skus
[_ event args app-state]
(update-in app-state keypaths/v2-skus #(merge (-> args :skus products/index-skus) %)))
(defmethod transition-state events/api-success-fetch-geo-location-from-ip
[_ event args app-state]
(update-in app-state keypaths/account-profile-ip-addresses #(conj % args)))
|
a907c1b5a3cd3e790ca3b6ae85b522fb91095a1c645e6e73196c5fdb77295b5d | tomgr/libcspm | PrettyPrint.hs | module Util.PrettyPrint (
module Text.PrettyPrint.HughesPJ,
PrettyPrintable (prettyPrint),
bytestring,
tabWidth,
tabIndent,
shortDouble,
commaSeparatedInt,
angles, bars, list, dotSep,
speakNth,
punctuateFront,
)
where
import qualified Data.ByteString.Char8 as B
import Numeric
import Text.PrettyPrint.HughesPJ
class PrettyPrintable a where
prettyPrint :: a -> Doc
bytestring :: B.ByteString -> Doc
bytestring = text . B.unpack
-- | The width, in spaces, of a tab character.
tabWidth :: Int
tabWidth = 4
| Pretty prints an integer and separates it into groups of 3 , separated by
-- commas.
commaSeparatedInt :: Int -> Doc
commaSeparatedInt =
let
breakIntoGroupsOf3 (c1:c2:c3:c4:cs) =
[c3,c2,c1] : breakIntoGroupsOf3 (c4:cs)
breakIntoGroupsOf3 cs = [reverse cs]
in
fcat . punctuate comma . reverse . map text
. breakIntoGroupsOf3 . reverse . show
-- | Show a double `d` printing only `places` places after the decimal place.
shortDouble :: Int -> Double -> Doc
shortDouble places d = text (showGFloat (Just places) d "")
| Indent a document by ` tabWidth ` characters , on each line
-- (uses `nest`).
tabIndent :: Doc -> Doc
tabIndent = nest tabWidth
| Surrounds a ` Doc ` with ' < ' and ' > ' .
angles :: Doc -> Doc
angles d = char '<' <> d <> char '>'
| Surrounds a ` Doc ` with ' | ' .
bars :: Doc -> Doc
bars d = char '|' <> d <> char '|'
-- | Separates a list of `Doc`s by '.'.
dotSep :: [Doc] -> Doc
dotSep docs = fcat (punctuate (text ".") docs)
-- | Separates a list of `Doc`s by ','.
list :: [Doc] -> Doc
list docs = fsep (punctuate (text ",") docs)
| Converts a number into ' first ' , ' second ' etc .
speakNth :: Int -> Doc
speakNth 1 = text "first"
speakNth 2 = text "second"
speakNth 3 = text "third"
speakNth 4 = text "fourth"
speakNth 5 = text "fifth"
speakNth 6 = text "sixth"
speakNth n = hcat [ int n, text suffix ]
where
suffix
11,12,13 are non - std
| last_dig == 1 = "st"
| last_dig == 2 = "nd"
| last_dig == 3 = "rd"
| otherwise = "th"
last_dig = n `rem` 10
| Equivalent to [ d1 , sep < > d2 , sep < > d3 , ... ] .
punctuateFront :: Doc -> [Doc] -> [Doc]
punctuateFront _ [] = []
punctuateFront sep (x:xs) = x:[sep <> x | x <- xs]
| null | https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/Util/PrettyPrint.hs | haskell | | The width, in spaces, of a tab character.
commas.
| Show a double `d` printing only `places` places after the decimal place.
(uses `nest`).
| Separates a list of `Doc`s by '.'.
| Separates a list of `Doc`s by ','. | module Util.PrettyPrint (
module Text.PrettyPrint.HughesPJ,
PrettyPrintable (prettyPrint),
bytestring,
tabWidth,
tabIndent,
shortDouble,
commaSeparatedInt,
angles, bars, list, dotSep,
speakNth,
punctuateFront,
)
where
import qualified Data.ByteString.Char8 as B
import Numeric
import Text.PrettyPrint.HughesPJ
class PrettyPrintable a where
prettyPrint :: a -> Doc
bytestring :: B.ByteString -> Doc
bytestring = text . B.unpack
tabWidth :: Int
tabWidth = 4
| Pretty prints an integer and separates it into groups of 3 , separated by
commaSeparatedInt :: Int -> Doc
commaSeparatedInt =
let
breakIntoGroupsOf3 (c1:c2:c3:c4:cs) =
[c3,c2,c1] : breakIntoGroupsOf3 (c4:cs)
breakIntoGroupsOf3 cs = [reverse cs]
in
fcat . punctuate comma . reverse . map text
. breakIntoGroupsOf3 . reverse . show
shortDouble :: Int -> Double -> Doc
shortDouble places d = text (showGFloat (Just places) d "")
| Indent a document by ` tabWidth ` characters , on each line
tabIndent :: Doc -> Doc
tabIndent = nest tabWidth
| Surrounds a ` Doc ` with ' < ' and ' > ' .
angles :: Doc -> Doc
angles d = char '<' <> d <> char '>'
| Surrounds a ` Doc ` with ' | ' .
bars :: Doc -> Doc
bars d = char '|' <> d <> char '|'
dotSep :: [Doc] -> Doc
dotSep docs = fcat (punctuate (text ".") docs)
list :: [Doc] -> Doc
list docs = fsep (punctuate (text ",") docs)
| Converts a number into ' first ' , ' second ' etc .
speakNth :: Int -> Doc
speakNth 1 = text "first"
speakNth 2 = text "second"
speakNth 3 = text "third"
speakNth 4 = text "fourth"
speakNth 5 = text "fifth"
speakNth 6 = text "sixth"
speakNth n = hcat [ int n, text suffix ]
where
suffix
11,12,13 are non - std
| last_dig == 1 = "st"
| last_dig == 2 = "nd"
| last_dig == 3 = "rd"
| otherwise = "th"
last_dig = n `rem` 10
| Equivalent to [ d1 , sep < > d2 , sep < > d3 , ... ] .
punctuateFront :: Doc -> [Doc] -> [Doc]
punctuateFront _ [] = []
punctuateFront sep (x:xs) = x:[sep <> x | x <- xs]
|
d2dd6919c1d5231c63fe1cb4416b0510e134f8a4f293231019773251ba5b9575 | triffon/fp-2022-23 | 12.count-atoms.rkt | (define (atom? x)
(and (not (null? x))
(not (pair? x))))
(define (count-atoms dl)
(cond ((null? dl) 0)
((atom? dl) 1)
(else (+ (count-atoms (car dl))
(count-atoms (cdr dl))))))
| null | https://raw.githubusercontent.com/triffon/fp-2022-23/b6991b5be25fb65d1e44b49ff612eb4e63f7caae/exercises/cs2/05.scheme.fold-deeplists/solutions/12.count-atoms.rkt | racket | (define (atom? x)
(and (not (null? x))
(not (pair? x))))
(define (count-atoms dl)
(cond ((null? dl) 0)
((atom? dl) 1)
(else (+ (count-atoms (car dl))
(count-atoms (cdr dl))))))
|
|
817c36393c7a8e6cbdc5d06bd2f27d914552a6f3d36b6e221b07dd8b5d5904bd | joyofclojure/book-source | macro_tunes.clj | (ns joy.macro-tunes
"Functions for computing tunes full of notes at compile time")
(defn pair-to-note
"Return a note map for the given tone and duration"
[[tone duration]]
{:cent (* 100 tone)
:duration duration
:volume 0.4})
(defn consecutive-notes
"Take a sequences of note maps that have no :delay, and return them
with correct :delay's so that they will play in the order given."
[notes]
(reductions (fn [{:keys [delay duration]} note]
(assoc note
:delay (+ delay duration)))
{:delay 0 :duration 0}
notes))
(defn notes [tone-pairs]
"Returns a sequence of note maps at moderate tempo for the given
sequence of tone-pairs."
(let [bpm 360
bps (/ bpm 60)]
(->> tone-pairs
(map pair-to-note)
consecutive-notes
(map #(update-in % [:delay] (comp double /) bps))
(map #(update-in % [:duration] (comp double /) bps)))))
(defn magical-theme
"A sequence of notes for a magical theme"
[]
(notes
(concat
[[11 2] [16 3] [19 1] [18 2] [16 4] [23 2]]
[[21 6] [18 6] [16 3] [19 1] [18 2] [14 4] [17 2] [11 10]]
[[11 2] [16 3] [19 1] [18 2] [16 4] [23 2]]
[[26 4] [25 2] [24 4] [20 2] [24 3] [23 1] [22 2] [10 4] [19 2] [16 10]])))
(defmacro magical-theme-macro []
(vec (magical-theme)))
| null | https://raw.githubusercontent.com/joyofclojure/book-source/b76ef15248dac88c7b1c77c2d461f3aa522a1461/src/clj/joy/macro_tunes.clj | clojure | (ns joy.macro-tunes
"Functions for computing tunes full of notes at compile time")
(defn pair-to-note
"Return a note map for the given tone and duration"
[[tone duration]]
{:cent (* 100 tone)
:duration duration
:volume 0.4})
(defn consecutive-notes
"Take a sequences of note maps that have no :delay, and return them
with correct :delay's so that they will play in the order given."
[notes]
(reductions (fn [{:keys [delay duration]} note]
(assoc note
:delay (+ delay duration)))
{:delay 0 :duration 0}
notes))
(defn notes [tone-pairs]
"Returns a sequence of note maps at moderate tempo for the given
sequence of tone-pairs."
(let [bpm 360
bps (/ bpm 60)]
(->> tone-pairs
(map pair-to-note)
consecutive-notes
(map #(update-in % [:delay] (comp double /) bps))
(map #(update-in % [:duration] (comp double /) bps)))))
(defn magical-theme
"A sequence of notes for a magical theme"
[]
(notes
(concat
[[11 2] [16 3] [19 1] [18 2] [16 4] [23 2]]
[[21 6] [18 6] [16 3] [19 1] [18 2] [14 4] [17 2] [11 10]]
[[11 2] [16 3] [19 1] [18 2] [16 4] [23 2]]
[[26 4] [25 2] [24 4] [20 2] [24 3] [23 1] [22 2] [10 4] [19 2] [16 10]])))
(defmacro magical-theme-macro []
(vec (magical-theme)))
|
|
f523e5404ea9acbdfbf523ad9bf0e996c6161a8da582ab7d30c11392700be980 | ocaml-sf/learn-ocaml-corpus | trail_off_by_one.ml | (* ------------------------------------------------------------------------------ *)
(* Building formulae. *)
let var x =
FVar x
let falsity =
FConst false
let truth =
FConst true
let const sense =
if sense then truth else falsity
(* [FConst sense] would work too, but would allocate memory *)
let neg f =
match f with
| FConst sense ->
const (not sense)
| FNeg f ->
f
| _ ->
FNeg f
let conn sense f1 f2 =
match f1, f2 with
| FConst sense', f
| f, FConst sense' ->
if sense = sense' then
f
else
FConst sense'
| _, _ ->
FConn (sense, f1, f2)
let conj f1 f2 =
conn true f1 f2
let disj f1 f2 =
conn false f1 f2
(* ------------------------------------------------------------------------------ *)
(* Evaluating formulae. *)
let rec eval (env : env) (f : formula) : bool =
match f with
| FConst b ->
b
| FConn (true, f1, f2) ->
eval env f1 && eval env f2
| FConn (false, f1, f2) ->
eval env f1 || eval env f2
| FNeg f ->
not (eval env f)
| FVar x ->
env x
let foreach_env (n : int) (body : env -> unit) : unit =
(* We assume [n < Sys.word_size - 1]. *)
for i = 0 to 1 lsl n - 1 do
let env x =
assert (0 <= x && x < n);
i land (1 lsl x) <> 0
in
body env
done
let satisfiable (n : int) (f : formula) : bool =
let exception SAT in
try
foreach_env n (fun env ->
if eval env f then
raise SAT
);
false
with SAT ->
true
let valid (n : int) (f : formula) : bool =
not (satisfiable n (neg f))
(* ------------------------------------------------------------------------------ *)
(* Converting formulae to conjunctive normal form. *)
module CNF (X : sig
type clause
val empty: clause
val cons: bool -> var -> clause -> clause
val new_var: unit -> var
val new_clause: clause -> unit
end)
= struct
open X
(* The conjunction of the clauses emitted by [decompose s f c] must be logically
equivalent to the formula [s.f \/ c]. *)
(* It is permitted to assume that [c] is small and therefore to duplicate
it. It is not permitted to duplicate [f]. *)
let rec decompose (s : bool) (f : formula) (c : clause) : unit =
match f with
| FConst s' when s = s' ->
(* The formula [s.f] is True, therefore the disjunction [s.f \/ c] is
true. No clauses need be emitted. *)
()
| FConn (s', f1, f2) when s = s' ->
(* The formula [s.f] can be written as a conjunction [s.f1 /\ s.f2].
The disjunction [_ \/ c] can be distributed onto this conjunction.
Thus, the formula [s.f \/ c] is logically equivalent to the
conjunction of [s.f1 \/ c] and [s.f2 \/ c]. *)
decompose s f1 c;
decompose s f2 c
| FNeg f1 ->
(* The formula [s.f] is equivalent to [(not s).f1]. *)
decompose (not s) f1 c
| _ ->
(* The formula [s.f] is False or a disjunction or a variable.
Transform it into a single clause and emit this clause. *)
new_clause (clause s f c)
(* The clause returned by [clause s f c], in conjunction with any
emitted clauses, must be logically equivalent to [s.f \/ c]. *)
and clause (s : bool) (f : formula) (c : clause) : clause =
match f with
| FConst s' when s <> s' ->
(* The formula [s.f] is False, so [s.f \/ c] is equivalent to [c]. *)
(* Thus, we return [c]. Note, however, that [FConst _] can appear
only at the toplevel of a formula, so the fact that we are here
implies that [c] must be [empty]. *)
assert (c == empty);
c
| FConn (s', f1, f2) when s <> s' ->
(* The formula [s.f] can be written as the disjunction [s.f1 \/ s.f2].
Therefore [s.f \/ c] is equivalent to [s.f1 \/ s.f2 \/ c]. *)
clause s f1 (clause s f2 c)
| FNeg f1 ->
(* The formula [s.f] is equivalent to [(not s).f1]. *)
clause (not s) f1 c
| FVar x ->
(* [s.x \/ c] is a valid clause. Return it. *)
cons s x c
| FConst s' ->
assert (s = s');
(* The formula [s.f] is True. Our assumption is violated. *)
assert false
| FConn (s', f1, f2) ->
assert (s = s');
The formula [ s.f ] is a conjunction . It can not appear in a clause .
We must create a proxy , that is , a fresh variable [ x ] that stands
for [ s.f ] , and use [ x ] in the current clause . We emit auxiliary
clauses to indicate that [ x ] implies [ s.f ] . As noted by Plaisted
and , the reverse implication is not necessary .
We must create a proxy, that is, a fresh variable [x] that stands
for [s.f], and use [x] in the current clause. We emit auxiliary
clauses to indicate that [x] implies [s.f]. As noted by Plaisted
and Greenbaum, the reverse implication is not necessary. *)
let x = new_var () in
(* Emit clauses to indicate that [x] implies [s.f]. Because this
implication is equivalent to [s.f \/ ~x], a single call to
[decompose s f (cons false x empty)] works. *)
Because [ s.f ] is equivalent to the conjunction of [ s.f1 ] and
[ s.f2 ] , this call can be written as a sequence of two recursive
calls , as follows . This makes it apparent that the recursive
calls concern subformulae .
[s.f2], this call can be written as a sequence of two recursive
calls, as follows. This makes it apparent that the recursive
calls concern subformulae. *)
decompose s f1 (cons false x empty);
decompose s f2 (cons false x empty);
(* Use [x] to stand for [s.f] in this clause. *)
cons true x c
(* The main entry point. *)
let cnf (f : formula) : unit =
decompose true f empty
end
(* -------------------------------------------------------------------------- *)
Recreation : determining whether two sorted lists have a common element .
let rec intersect (xs : int list) (ys : int list) : bool =
match xs, ys with
| [], _
| _, [] ->
false
| x :: xs, y :: ys ->
x = y ||
x < y && intersect xs (y :: ys) ||
y < x && intersect (x :: xs) ys
(* -------------------------------------------------------------------------- *)
(* Counting. *)
let postincrement (c : int ref) : int =
let x = !c in
c := x + 1;
x
(* ------------------------------------------------------------------------------ *)
(* Representing a set of clauses in memory. *)
exception UNSAT
module Clauses () = struct
(* A clause is represented as a list of literals. *)
type literal = bool * var
type clause = literal list
let empty : clause =
[]
let cons p x clause : clause =
(p, x) :: clause
(* Clauses are numbered and are stored in an infinite array. *)
let clauses : clause option InfiniteArray.t =
InfiniteArray.make None
(* The counter [c] is used to allocate new clauses. *)
let c : int ref =
ref 0
let new_clause (clause : clause) : unit =
If [ clause ] contains x \/ ~x , drop this clause altogether .
let neg =
clause
|> List.filter (fun (p, _x) -> not p)
|> List.map snd
|> List.sort compare
and pos =
clause
|> List.filter (fun (p, _x) -> p)
|> List.map snd
|> List.sort compare
in
if intersect neg pos then
()
(* If this clause has length 0, fail immediately. *)
else if clause = [] then
raise UNSAT
else begin
(* Allocate a new clause index. *)
let i = postincrement c in
(* Record this clause. *)
InfiniteArray.set clauses i (Some clause);
end
let count_clauses () : int =
!c
(* The counter [v] is used to allocate new variables. *)
let v : var ref =
ref 0
let new_var () : var =
postincrement v
let count_vars () : int =
!v
end
(* ------------------------------------------------------------------------------ *)
module Trail () : sig
val push: (unit -> unit) -> unit
type checkpoint
val record: unit -> checkpoint
val revert: checkpoint -> unit
end = struct
(* A trivial undo action. *)
let nothing () = ()
(* A stack of undo actions. *)
let actions = InfiniteArray.make nothing
(* The current stack level. *)
let current = ref 0
(* Installing a new undo action. *)
let push action =
InfiniteArray.set actions (postincrement current) action
(* Recording the current level. *)
type checkpoint = int
let record () = !current
(* Going back to a previously recorded stack level. *)
let revert i =
for j = !current downto i+1 do (* wrong *)
let action = InfiniteArray.get actions j in
action();
done;
current := i
end
(* ------------------------------------------------------------------------------ *)
(* TEMPORARY *)
module SAT (X : sig val f: formula end) () : sig end = struct
open X
module C = Clauses()
open C
module F = CNF(C)
open F
let () = F.cnf f
let unresolved : bool InfiniteArray.t =
InfiniteArray.make true
let rec pick x =
if x < count_vars() then
if InfiniteArray.get unresolved x then Some x else pick (x+1)
else
None
let pick () =
pick 0
The array [ value ] maps every resolved variable [ x ] to its Boolean value .
let value : bool InfiniteArray.t =
InfiniteArray.make false
module Trail = Trail()
let mark_resolved x =
InfiniteArray.set unresolved x false;
Trail.push (fun () ->
InfiniteArray.set unresolved x true
)
let update_clause i clause =
let current = InfiniteArray.get clauses i in
InfiniteArray.set clauses i clause;
Trail.push (fun () ->
InfiniteArray.set clauses i current
)
end
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/sat/wrong/trail_off_by_one.ml | ocaml | ------------------------------------------------------------------------------
Building formulae.
[FConst sense] would work too, but would allocate memory
------------------------------------------------------------------------------
Evaluating formulae.
We assume [n < Sys.word_size - 1].
------------------------------------------------------------------------------
Converting formulae to conjunctive normal form.
The conjunction of the clauses emitted by [decompose s f c] must be logically
equivalent to the formula [s.f \/ c].
It is permitted to assume that [c] is small and therefore to duplicate
it. It is not permitted to duplicate [f].
The formula [s.f] is True, therefore the disjunction [s.f \/ c] is
true. No clauses need be emitted.
The formula [s.f] can be written as a conjunction [s.f1 /\ s.f2].
The disjunction [_ \/ c] can be distributed onto this conjunction.
Thus, the formula [s.f \/ c] is logically equivalent to the
conjunction of [s.f1 \/ c] and [s.f2 \/ c].
The formula [s.f] is equivalent to [(not s).f1].
The formula [s.f] is False or a disjunction or a variable.
Transform it into a single clause and emit this clause.
The clause returned by [clause s f c], in conjunction with any
emitted clauses, must be logically equivalent to [s.f \/ c].
The formula [s.f] is False, so [s.f \/ c] is equivalent to [c].
Thus, we return [c]. Note, however, that [FConst _] can appear
only at the toplevel of a formula, so the fact that we are here
implies that [c] must be [empty].
The formula [s.f] can be written as the disjunction [s.f1 \/ s.f2].
Therefore [s.f \/ c] is equivalent to [s.f1 \/ s.f2 \/ c].
The formula [s.f] is equivalent to [(not s).f1].
[s.x \/ c] is a valid clause. Return it.
The formula [s.f] is True. Our assumption is violated.
Emit clauses to indicate that [x] implies [s.f]. Because this
implication is equivalent to [s.f \/ ~x], a single call to
[decompose s f (cons false x empty)] works.
Use [x] to stand for [s.f] in this clause.
The main entry point.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Counting.
------------------------------------------------------------------------------
Representing a set of clauses in memory.
A clause is represented as a list of literals.
Clauses are numbered and are stored in an infinite array.
The counter [c] is used to allocate new clauses.
If this clause has length 0, fail immediately.
Allocate a new clause index.
Record this clause.
The counter [v] is used to allocate new variables.
------------------------------------------------------------------------------
A trivial undo action.
A stack of undo actions.
The current stack level.
Installing a new undo action.
Recording the current level.
Going back to a previously recorded stack level.
wrong
------------------------------------------------------------------------------
TEMPORARY |
let var x =
FVar x
let falsity =
FConst false
let truth =
FConst true
let const sense =
if sense then truth else falsity
let neg f =
match f with
| FConst sense ->
const (not sense)
| FNeg f ->
f
| _ ->
FNeg f
let conn sense f1 f2 =
match f1, f2 with
| FConst sense', f
| f, FConst sense' ->
if sense = sense' then
f
else
FConst sense'
| _, _ ->
FConn (sense, f1, f2)
let conj f1 f2 =
conn true f1 f2
let disj f1 f2 =
conn false f1 f2
let rec eval (env : env) (f : formula) : bool =
match f with
| FConst b ->
b
| FConn (true, f1, f2) ->
eval env f1 && eval env f2
| FConn (false, f1, f2) ->
eval env f1 || eval env f2
| FNeg f ->
not (eval env f)
| FVar x ->
env x
let foreach_env (n : int) (body : env -> unit) : unit =
for i = 0 to 1 lsl n - 1 do
let env x =
assert (0 <= x && x < n);
i land (1 lsl x) <> 0
in
body env
done
let satisfiable (n : int) (f : formula) : bool =
let exception SAT in
try
foreach_env n (fun env ->
if eval env f then
raise SAT
);
false
with SAT ->
true
let valid (n : int) (f : formula) : bool =
not (satisfiable n (neg f))
module CNF (X : sig
type clause
val empty: clause
val cons: bool -> var -> clause -> clause
val new_var: unit -> var
val new_clause: clause -> unit
end)
= struct
open X
let rec decompose (s : bool) (f : formula) (c : clause) : unit =
match f with
| FConst s' when s = s' ->
()
| FConn (s', f1, f2) when s = s' ->
decompose s f1 c;
decompose s f2 c
| FNeg f1 ->
decompose (not s) f1 c
| _ ->
new_clause (clause s f c)
and clause (s : bool) (f : formula) (c : clause) : clause =
match f with
| FConst s' when s <> s' ->
assert (c == empty);
c
| FConn (s', f1, f2) when s <> s' ->
clause s f1 (clause s f2 c)
| FNeg f1 ->
clause (not s) f1 c
| FVar x ->
cons s x c
| FConst s' ->
assert (s = s');
assert false
| FConn (s', f1, f2) ->
assert (s = s');
The formula [ s.f ] is a conjunction . It can not appear in a clause .
We must create a proxy , that is , a fresh variable [ x ] that stands
for [ s.f ] , and use [ x ] in the current clause . We emit auxiliary
clauses to indicate that [ x ] implies [ s.f ] . As noted by Plaisted
and , the reverse implication is not necessary .
We must create a proxy, that is, a fresh variable [x] that stands
for [s.f], and use [x] in the current clause. We emit auxiliary
clauses to indicate that [x] implies [s.f]. As noted by Plaisted
and Greenbaum, the reverse implication is not necessary. *)
let x = new_var () in
Because [ s.f ] is equivalent to the conjunction of [ s.f1 ] and
[ s.f2 ] , this call can be written as a sequence of two recursive
calls , as follows . This makes it apparent that the recursive
calls concern subformulae .
[s.f2], this call can be written as a sequence of two recursive
calls, as follows. This makes it apparent that the recursive
calls concern subformulae. *)
decompose s f1 (cons false x empty);
decompose s f2 (cons false x empty);
cons true x c
let cnf (f : formula) : unit =
decompose true f empty
end
Recreation : determining whether two sorted lists have a common element .
let rec intersect (xs : int list) (ys : int list) : bool =
match xs, ys with
| [], _
| _, [] ->
false
| x :: xs, y :: ys ->
x = y ||
x < y && intersect xs (y :: ys) ||
y < x && intersect (x :: xs) ys
let postincrement (c : int ref) : int =
let x = !c in
c := x + 1;
x
exception UNSAT
module Clauses () = struct
type literal = bool * var
type clause = literal list
let empty : clause =
[]
let cons p x clause : clause =
(p, x) :: clause
let clauses : clause option InfiniteArray.t =
InfiniteArray.make None
let c : int ref =
ref 0
let new_clause (clause : clause) : unit =
If [ clause ] contains x \/ ~x , drop this clause altogether .
let neg =
clause
|> List.filter (fun (p, _x) -> not p)
|> List.map snd
|> List.sort compare
and pos =
clause
|> List.filter (fun (p, _x) -> p)
|> List.map snd
|> List.sort compare
in
if intersect neg pos then
()
else if clause = [] then
raise UNSAT
else begin
let i = postincrement c in
InfiniteArray.set clauses i (Some clause);
end
let count_clauses () : int =
!c
let v : var ref =
ref 0
let new_var () : var =
postincrement v
let count_vars () : int =
!v
end
module Trail () : sig
val push: (unit -> unit) -> unit
type checkpoint
val record: unit -> checkpoint
val revert: checkpoint -> unit
end = struct
let nothing () = ()
let actions = InfiniteArray.make nothing
let current = ref 0
let push action =
InfiniteArray.set actions (postincrement current) action
type checkpoint = int
let record () = !current
let revert i =
let action = InfiniteArray.get actions j in
action();
done;
current := i
end
module SAT (X : sig val f: formula end) () : sig end = struct
open X
module C = Clauses()
open C
module F = CNF(C)
open F
let () = F.cnf f
let unresolved : bool InfiniteArray.t =
InfiniteArray.make true
let rec pick x =
if x < count_vars() then
if InfiniteArray.get unresolved x then Some x else pick (x+1)
else
None
let pick () =
pick 0
The array [ value ] maps every resolved variable [ x ] to its Boolean value .
let value : bool InfiniteArray.t =
InfiniteArray.make false
module Trail = Trail()
let mark_resolved x =
InfiniteArray.set unresolved x false;
Trail.push (fun () ->
InfiniteArray.set unresolved x true
)
let update_clause i clause =
let current = InfiniteArray.get clauses i in
InfiniteArray.set clauses i clause;
Trail.push (fun () ->
InfiniteArray.set clauses i current
)
end
|
e99526ffa8119c071d7da6324214d2c43a23c63fbf994011548bc805fa7db1d0 | LaurentMazare/tensorflow-ocaml | protobuf.mli | type t
val of_string : string -> t
val to_string : t -> string
val read_file : string -> t
| null | https://raw.githubusercontent.com/LaurentMazare/tensorflow-ocaml/52c5f1dec1a8b7dc9bc6ef06abbc07da6cd90d39/src/wrapper/protobuf.mli | ocaml | type t
val of_string : string -> t
val to_string : t -> string
val read_file : string -> t
|
|
3e9f61568524db7866bbb24a951201c31743d26882140ceecaade85c66607c44 | onedata/op-worker | luma_test_utils.erl | %%%-------------------------------------------------------------------
@author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% Utility functions for luma tests
%%% @end
%%%-------------------------------------------------------------------
-module(luma_test_utils).
-author("Wojciech Geisler").
-include("luma_test_utils.hrl").
-include("modules/storage/helpers/helpers.hrl").
-export([run_test_for_all_storage_configs/5, clear_luma_db_for_all_storages/1,
mock_stat_on_space_mount_dir/1, setup_local_feed_luma/3, mock_storage_is_imported/1]).
% LUMA API
-export([map_to_storage_creds/4, map_to_storage_creds/5, map_to_display_creds/4,
map_uid_to_onedata_user/4, map_acl_user_to_onedata_user/3, map_acl_group_to_onedata_group/3,
clear_luma_db/2]).
-export([new_ceph_user_ctx/2, new_cephrados_user_ctx/2, new_posix_user_ctx/2,
new_s3_user_ctx/2, new_swift_user_ctx/2, new_glusterfs_user_ctx/2,
new_webdav_user_ctx/2, new_nulldevice_user_ctx/2]).
-type user_ctx() :: helper:user_ctx().
%%%===================================================================
%%% API functions
%%%===================================================================
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, StorageConfigs) when is_list(StorageConfigs) ->
lists:foreach(fun(StorageLumaConfig) ->
Name = maps:get(name, StorageLumaConfig),
try
run_test(TestFun, Module, Config, StorageLumaConfig)
catch
Error:Reason:Stacktrace ->
ct:pal("Testcase \"~p\" failed for config ~p due to ~p:~p~nStacktrace: ~p",
[TestCase, Name, Error, Reason, Stacktrace]
),
ct:fail("Failed testcase")
end
end, StorageConfigs);
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, StorageConfig) ->
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, [StorageConfig]).
run_test(TestFun, Module, Config, StorageConfig) ->
Config2 = Module:init_per_testcase(Config),
try
TestFun(Config, StorageConfig)
after
Module:end_per_testcase(Config2)
end.
clear_luma_db_for_all_storages(Worker) ->
StorageIds = lists:usort(lists:map(fun(StorageLumaConfig) ->
Storage = maps:get(storage_record, StorageLumaConfig),
storage:get_id(Storage)
end, ?ALL_STORAGE_CONFIGS )),
lists:foreach(fun(StorageId) ->
clear_luma_db(Worker, StorageId)
end, StorageIds).
mock_stat_on_space_mount_dir(Worker) ->
ok = test_utils:mock_new(Worker, storage_file_ctx),
ok = test_utils:mock_expect(Worker, storage_file_ctx, stat, fun(StFileCtx) ->
{#statbuf{st_uid = ?SPACE_MOUNT_UID, st_gid = ?SPACE_MOUNT_GID}, StFileCtx}
end).
mock_storage_is_imported(Worker) ->
IsImportedFun = fun(StorageId) ->
ImportedStorageDocs = [maps:get(storage_record, SC) || SC <- ?IMPORTED_STORAGE_CONFIGS],
ImportedStorageIds = [Id || #document{key = Id} <- ImportedStorageDocs],
lists:member(StorageId, ImportedStorageIds)
end,
ok = test_utils:mock_new(Worker, storage),
ok = test_utils:mock_expect(Worker, storage, is_imported, fun
(#document{key = StorageId}) -> IsImportedFun(StorageId);
(StorageId) when is_binary(StorageId) -> IsImportedFun(StorageId)
end).
setup_local_feed_luma(Worker, Config, LocalFeedConfigFile) ->
% in this test suite storages are mocked, therefore we have to call
function for setting mappings in LUMA with local feed manually
StorageDocs = lists:foldl(fun(StorageConfig, Acc) ->
Doc = maps:get(storage_record, StorageConfig),
Acc#{storage:get_id(Doc) => Doc}
end, #{}, ?LOCAL_FEED_LUMA_STORAGE_CONFIGS),
ok = test_utils:mock_new(Worker, storage_config),
ok = test_utils:mock_expect(Worker, storage_config, get, fun(StorageId) ->
{ok, maps:get(StorageId, StorageDocs)}
end),
initializer:setup_luma_local_feed(Worker, Config, LocalFeedConfigFile).
%%%===================================================================
%%% LUMA API functions
%%%===================================================================
map_to_storage_creds(Worker, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_storage_credentials, [UserId, SpaceId, Storage]).
map_to_storage_creds(Worker, SessId, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_storage_credentials, [SessId, UserId, SpaceId, Storage]).
map_to_display_creds(Worker, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_display_credentials, [UserId, SpaceId, Storage]).
map_uid_to_onedata_user(Worker, Uid, SpaceId, Storage) ->
rpc:call(Worker, luma, map_uid_to_onedata_user, [Uid, SpaceId, Storage]).
map_acl_user_to_onedata_user(Worker, AclUser, Storage) ->
rpc:call(Worker, luma, map_acl_user_to_onedata_user, [AclUser, Storage]).
map_acl_group_to_onedata_group(Worker, AclGroup, Storage) ->
rpc:call(Worker, luma, map_acl_group_to_onedata_group, [AclGroup, Storage]).
clear_luma_db(Worker, StorageId) ->
ok = rpc:call(Worker, luma, clear_db, [StorageId]).
%%%===================================================================
%%% Helpers API functions
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
Constructs Ceph storage helper user context record .
%% @end
%%--------------------------------------------------------------------
-spec new_ceph_user_ctx(binary(), binary()) -> user_ctx().
new_ceph_user_ctx(Username, Key) ->
#{
<<"username">> => Username,
<<"key">> => Key
}.
%%--------------------------------------------------------------------
%% @doc
Constructs CephRados storage helper user context record .
%% @end
%%--------------------------------------------------------------------
-spec new_cephrados_user_ctx(binary(), binary()) -> user_ctx().
new_cephrados_user_ctx(Username, Key) ->
#{
<<"username">> => Username,
<<"key">> => Key
}.
%%--------------------------------------------------------------------
%% @doc
Constructs POSIX storage helper user context record .
%% @end
%%--------------------------------------------------------------------
-spec new_posix_user_ctx(integer(), integer()) -> user_ctx().
new_posix_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
%%--------------------------------------------------------------------
%% @doc
%% Constructs S3 storage helper user context record.
%% @end
%%--------------------------------------------------------------------
-spec new_s3_user_ctx(binary(), binary()) -> user_ctx().
new_s3_user_ctx(AccessKey, SecretKey) ->
#{
<<"accessKey">> => AccessKey,
<<"secretKey">> => SecretKey
}.
%%--------------------------------------------------------------------
%% @doc
Constructs Swift storage helper user context record .
%% @end
%%--------------------------------------------------------------------
-spec new_swift_user_ctx(binary(), binary()) -> user_ctx().
new_swift_user_ctx(Username, Password) ->
#{
<<"username">> => Username,
<<"password">> => Password
}.
%%--------------------------------------------------------------------
%% @doc
Constructs GlusterFS storage helper user context record .
%% @end
%%--------------------------------------------------------------------
-spec new_glusterfs_user_ctx(integer(), integer()) -> user_ctx().
new_glusterfs_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
%%--------------------------------------------------------------------
%% @doc
%% Constructs WebDAV storage helper user context record.
%% @end
%%--------------------------------------------------------------------
-spec new_webdav_user_ctx(binary(), binary()) -> user_ctx().
new_webdav_user_ctx(CredentialsType = <<"none">>, _Credentials) ->
#{
<<"credentialsType">> => CredentialsType
};
new_webdav_user_ctx(CredentialsType, Credentials) ->
#{
<<"credentialsType">> => CredentialsType,
<<"credentials">> => Credentials
}.
%%--------------------------------------------------------------------
%% @doc
%% Constructs Null Device storage helper user context record.
%% @end
%%--------------------------------------------------------------------
-spec new_nulldevice_user_ctx(integer(), integer()) -> user_ctx().
new_nulldevice_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
| null | https://raw.githubusercontent.com/onedata/op-worker/b0e4045090b180f28c79d40b9b334d7411ec3ca5/test_distributed/luma_test_utils.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
Utility functions for luma tests
@end
-------------------------------------------------------------------
LUMA API
===================================================================
API functions
===================================================================
in this test suite storages are mocked, therefore we have to call
===================================================================
LUMA API functions
===================================================================
===================================================================
Helpers API functions
===================================================================
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Constructs S3 storage helper user context record.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Constructs WebDAV storage helper user context record.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Constructs Null Device storage helper user context record.
@end
-------------------------------------------------------------------- | @author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(luma_test_utils).
-author("Wojciech Geisler").
-include("luma_test_utils.hrl").
-include("modules/storage/helpers/helpers.hrl").
-export([run_test_for_all_storage_configs/5, clear_luma_db_for_all_storages/1,
mock_stat_on_space_mount_dir/1, setup_local_feed_luma/3, mock_storage_is_imported/1]).
-export([map_to_storage_creds/4, map_to_storage_creds/5, map_to_display_creds/4,
map_uid_to_onedata_user/4, map_acl_user_to_onedata_user/3, map_acl_group_to_onedata_group/3,
clear_luma_db/2]).
-export([new_ceph_user_ctx/2, new_cephrados_user_ctx/2, new_posix_user_ctx/2,
new_s3_user_ctx/2, new_swift_user_ctx/2, new_glusterfs_user_ctx/2,
new_webdav_user_ctx/2, new_nulldevice_user_ctx/2]).
-type user_ctx() :: helper:user_ctx().
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, StorageConfigs) when is_list(StorageConfigs) ->
lists:foreach(fun(StorageLumaConfig) ->
Name = maps:get(name, StorageLumaConfig),
try
run_test(TestFun, Module, Config, StorageLumaConfig)
catch
Error:Reason:Stacktrace ->
ct:pal("Testcase \"~p\" failed for config ~p due to ~p:~p~nStacktrace: ~p",
[TestCase, Name, Error, Reason, Stacktrace]
),
ct:fail("Failed testcase")
end
end, StorageConfigs);
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, StorageConfig) ->
run_test_for_all_storage_configs(TestCase, TestFun, Module, Config, [StorageConfig]).
run_test(TestFun, Module, Config, StorageConfig) ->
Config2 = Module:init_per_testcase(Config),
try
TestFun(Config, StorageConfig)
after
Module:end_per_testcase(Config2)
end.
clear_luma_db_for_all_storages(Worker) ->
StorageIds = lists:usort(lists:map(fun(StorageLumaConfig) ->
Storage = maps:get(storage_record, StorageLumaConfig),
storage:get_id(Storage)
end, ?ALL_STORAGE_CONFIGS )),
lists:foreach(fun(StorageId) ->
clear_luma_db(Worker, StorageId)
end, StorageIds).
mock_stat_on_space_mount_dir(Worker) ->
ok = test_utils:mock_new(Worker, storage_file_ctx),
ok = test_utils:mock_expect(Worker, storage_file_ctx, stat, fun(StFileCtx) ->
{#statbuf{st_uid = ?SPACE_MOUNT_UID, st_gid = ?SPACE_MOUNT_GID}, StFileCtx}
end).
mock_storage_is_imported(Worker) ->
IsImportedFun = fun(StorageId) ->
ImportedStorageDocs = [maps:get(storage_record, SC) || SC <- ?IMPORTED_STORAGE_CONFIGS],
ImportedStorageIds = [Id || #document{key = Id} <- ImportedStorageDocs],
lists:member(StorageId, ImportedStorageIds)
end,
ok = test_utils:mock_new(Worker, storage),
ok = test_utils:mock_expect(Worker, storage, is_imported, fun
(#document{key = StorageId}) -> IsImportedFun(StorageId);
(StorageId) when is_binary(StorageId) -> IsImportedFun(StorageId)
end).
setup_local_feed_luma(Worker, Config, LocalFeedConfigFile) ->
function for setting mappings in LUMA with local feed manually
StorageDocs = lists:foldl(fun(StorageConfig, Acc) ->
Doc = maps:get(storage_record, StorageConfig),
Acc#{storage:get_id(Doc) => Doc}
end, #{}, ?LOCAL_FEED_LUMA_STORAGE_CONFIGS),
ok = test_utils:mock_new(Worker, storage_config),
ok = test_utils:mock_expect(Worker, storage_config, get, fun(StorageId) ->
{ok, maps:get(StorageId, StorageDocs)}
end),
initializer:setup_luma_local_feed(Worker, Config, LocalFeedConfigFile).
map_to_storage_creds(Worker, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_storage_credentials, [UserId, SpaceId, Storage]).
map_to_storage_creds(Worker, SessId, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_storage_credentials, [SessId, UserId, SpaceId, Storage]).
map_to_display_creds(Worker, UserId, SpaceId, Storage) ->
rpc:call(Worker, luma, map_to_display_credentials, [UserId, SpaceId, Storage]).
map_uid_to_onedata_user(Worker, Uid, SpaceId, Storage) ->
rpc:call(Worker, luma, map_uid_to_onedata_user, [Uid, SpaceId, Storage]).
map_acl_user_to_onedata_user(Worker, AclUser, Storage) ->
rpc:call(Worker, luma, map_acl_user_to_onedata_user, [AclUser, Storage]).
map_acl_group_to_onedata_group(Worker, AclGroup, Storage) ->
rpc:call(Worker, luma, map_acl_group_to_onedata_group, [AclGroup, Storage]).
clear_luma_db(Worker, StorageId) ->
ok = rpc:call(Worker, luma, clear_db, [StorageId]).
Constructs Ceph storage helper user context record .
-spec new_ceph_user_ctx(binary(), binary()) -> user_ctx().
new_ceph_user_ctx(Username, Key) ->
#{
<<"username">> => Username,
<<"key">> => Key
}.
Constructs CephRados storage helper user context record .
-spec new_cephrados_user_ctx(binary(), binary()) -> user_ctx().
new_cephrados_user_ctx(Username, Key) ->
#{
<<"username">> => Username,
<<"key">> => Key
}.
Constructs POSIX storage helper user context record .
-spec new_posix_user_ctx(integer(), integer()) -> user_ctx().
new_posix_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
-spec new_s3_user_ctx(binary(), binary()) -> user_ctx().
new_s3_user_ctx(AccessKey, SecretKey) ->
#{
<<"accessKey">> => AccessKey,
<<"secretKey">> => SecretKey
}.
Constructs Swift storage helper user context record .
-spec new_swift_user_ctx(binary(), binary()) -> user_ctx().
new_swift_user_ctx(Username, Password) ->
#{
<<"username">> => Username,
<<"password">> => Password
}.
Constructs GlusterFS storage helper user context record .
-spec new_glusterfs_user_ctx(integer(), integer()) -> user_ctx().
new_glusterfs_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
-spec new_webdav_user_ctx(binary(), binary()) -> user_ctx().
new_webdav_user_ctx(CredentialsType = <<"none">>, _Credentials) ->
#{
<<"credentialsType">> => CredentialsType
};
new_webdav_user_ctx(CredentialsType, Credentials) ->
#{
<<"credentialsType">> => CredentialsType,
<<"credentials">> => Credentials
}.
-spec new_nulldevice_user_ctx(integer(), integer()) -> user_ctx().
new_nulldevice_user_ctx(Uid, Gid) ->
#{
<<"uid">> => integer_to_binary(Uid),
<<"gid">> => integer_to_binary(Gid)
}.
|
a25d0d76ac9f03a3bc949e3c83fe8643c9f6fee7108bf0366a74779541d9d6b4 | bennofs/haskell-generate | Monad.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE CPP #
module Language.Haskell.Generate.Monad
( Generate(..), ExpG
, runGenerate, newName
, returnE
, useValue, useCon, useVar
, caseE
, applyE, applyE2, applyE3, applyE4, applyE5, applyE6
, (<>$)
, GenExp(..)
, ModuleM(..)
, ModuleG
, FunRef(..)
, Name(..)
, exportFun
, addDecl
, runModuleM
, generateModule
, generateExp
)
where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import Control.Monad.Trans.Writer
import qualified Data.Set as S
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.SrcLoc
import Language.Haskell.Exts.Syntax
import Language.Haskell.Generate.Expression
import Prelude
--------------------------------------------------------------------------------
-- Generate expressions
-- | This monad keeps track of a counter for generating unique names and the set of modules
-- that are needed for the expression.
newtype Generate a = Generate { unGenerate :: StateT Integer (Writer (S.Set ModuleName)) a } deriving (Functor, Applicative, Monad)
-- | Extract the set of modules and the value from a Generate action.
runGenerate :: Generate a -> (a, S.Set ModuleName)
runGenerate (Generate a) = runWriter $ evalStateT a 0
-- | This is a type alias for a Generate action that returns an expression of type 't'.
type ExpG t = Generate (Expression t)
-- | Use a haskell-src-exts Exp as the result of a Generate action.
returnE :: Exp -> ExpG t
returnE = return . Expression
-- | Pretty print the expression generated by a given action.
generateExp :: ExpG t -> String
generateExp = prettyPrint . runExpression . fst . runGenerate
-- | Generate a case expression.
caseE :: ExpG x -> [(Pat, ExpG t)] -> ExpG t
caseE v alt = do
v' <- v
#if MIN_VERSION_haskell_src_exts(1,17,0)
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') Nothing) a) alt
#elif MIN_VERSION_haskell_src_exts(1,16,0)
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') (BDecls [])) a) alt
#else
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedAlt $ runExpression a') (BDecls [])) a) alt
#endif
return $ Expression $ Case (runExpression v') alt'
-- | Import a function from a module. This function is polymorphic in the type of the resulting expression,
-- you should probably only use this function to define type-restricted specializations.
--
-- Example:
--
-- > addInt :: ExpG (Int -> Int -> Int) -- Here we restricted the type to something sensible
-- > addInt = useValue "Prelude" $ Symbol "+"
--
useValue :: String -> Name -> ExpG a
useValue md name = Generate $ do
lift $ tell $ S.singleton $ ModuleName md
return $ Expression $ Var $ Qual (ModuleName md) name
-- | Import a value constructor from a module. Returns the qualified name of the constructor.
useCon :: String -> Name -> Generate QName
useCon md name = Generate $ do
lift $ tell $ S.singleton $ ModuleName md
return $ Qual (ModuleName md) name
-- | Use the value of a variable with the given name.
useVar :: Name -> ExpG t
useVar name = return $ Expression $ Var $ UnQual name
-- | Generate a new unique variable name with the given prefix. Note that this new variable name
-- is only unique relative to other variable names generated by this function.
newName :: String -> Generate Name
newName pref = Generate $ do
i <- get <* modify succ
return $ Ident $ pref ++ show i
-- | Generate a expression from a haskell value. This can for example be used to create lambdas:
--
> > > putStrLn $ generateExp $ expr ( \x f - > f < > $ x )
-- \ pvar_0 -> \ pvar_1 -> pvar_1 pvar_0
--
-- Or string literals:
--
-- >>> putStrLn $ generateExp $ expr "I'm a string!"
-- ['I', '\'', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', '!']
--
class GenExp t where
type GenExpType t :: *
-- | This function generates the haskell expression from the given haskell value.
expr :: t -> ExpG (GenExpType t)
instance GenExp (ExpG a) where
type GenExpType (ExpG a) = a
expr = id
instance GenExp (Expression t) where
type GenExpType (Expression t) = t
expr = return
instance GenExp Char where
type GenExpType Char = Char
expr = return . Expression . Lit . Char
instance GenExp Integer where
type GenExpType Integer = Integer
expr = return . Expression . Lit . Int
instance GenExp Rational where
type GenExpType Rational = Rational
expr = return . Expression . Lit . Frac
instance GenExp a => GenExp [a] where
type GenExpType [a] = [GenExpType a]
expr = Generate . fmap (Expression . List . map runExpression) . mapM (unGenerate . expr)
instance GenExp x => GenExp (ExpG a -> x) where
type GenExpType (ExpG a -> x) = a -> GenExpType x
expr f = do
pvarName <- newName "pvar_"
body <- expr $ f $ return $ Expression $ Var $ UnQual pvarName
return $ Expression $ Lambda noLoc [PVar pvarName] $ runExpression body
--------------------------------------------------------------------------------
-- Apply functions
-- | Apply a function in a haskell expression to a value.
applyE :: ExpG (a -> b) -> ExpG a -> ExpG b
applyE a b = wrap $ liftM (foldl1 App) $ sequence [unwrap a, unwrap b]
where wrap = fmap Expression
unwrap = fmap runExpression
-- | Operator for 'applyE'.
(<>$) :: ExpG (a -> b) -> ExpG a -> ExpG b
(<>$) = applyE
infixl 1 <>$
| ApplyE for 2 arguments
applyE2 :: ExpG (a -> b -> c) -> ExpG a -> ExpG b -> ExpG c
applyE2 a b c = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 3 arguments
applyE3 :: ExpG (a -> b -> c -> d) -> ExpG a -> ExpG b -> ExpG c -> ExpG d
applyE3 a b c d = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 4 arguments
applyE4 :: ExpG (a -> b -> c -> d -> e) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e
applyE4 a b c d e = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 5 arguments
applyE5 :: ExpG (a -> b -> c -> d -> e -> f) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f
applyE5 a b c d e f = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 6 arguments
applyE6 :: ExpG (a -> b -> c -> d -> e -> f -> g) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f -> ExpG g
applyE6 a b c d e f g = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f,unwrap g]
where wrap = fmap Expression
unwrap = fmap runExpression
--------------------------------------------------------------------------------
-- Generate modules
-- | A module keeps track of the needed imports, but also has a list of declarations in it.
newtype ModuleM a = ModuleM (Writer (S.Set ModuleName, [Decl]) a) deriving (Functor, Applicative, Monad)
-- | This is the resulting type of a function generating a module. It is a ModuleM action returning the export list.
type ModuleG = ModuleM (Maybe [ExportSpec])
| A reference to a function . With a reference to a function , you can apply it ( by lifting it into using ' expr ' ) to some value
-- or export it using 'exportFun'.
data FunRef t = FunRef Name
instance GenExp (FunRef t) where
type GenExpType (FunRef t) = t
expr (FunRef n) = return $ Expression $ Var $ UnQual n
| Generate a ExportSpec for a given function item .
exportFun :: FunRef t -> ExportSpec
#if MIN_VERSION_haskell_src_exts(1,16,0) && !MIN_VERSION_haskell_src_exts(1,17,0)
exportFun (FunRef name) = EVar NoNamespace (UnQual name)
#else
exportFun (FunRef name) = EVar (UnQual name)
#endif
-- | Add a declaration to the module. Return a reference to it that can be used to either apply the function to some values or export it.
addDecl :: Name -> ExpG t -> ModuleM (FunRef t)
addDecl name e = ModuleM $ do
let (body, mods) = runGenerate e
#if MIN_VERSION_haskell_src_exts(1,17,0)
tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) Nothing]])
#else
tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) $ BDecls []]])
#endif
return $ FunRef name
-- | Extract the Module from a module generator.
runModuleM :: ModuleG -> String -> Module
runModuleM (ModuleM act) name =
#if MIN_VERSION_haskell_src_exts(1,16,0)
Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False False Nothing Nothing Nothing) $ S.toList imps) decls
#else
Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False Nothing Nothing Nothing) $ S.toList imps) decls
#endif
where (export, (imps, decls)) = runWriter act
-- | Generate the source code for a module.
generateModule :: ModuleG -> String -> String
generateModule = fmap prettyPrint . runModuleM
| null | https://raw.githubusercontent.com/bennofs/haskell-generate/2e472a850f989d2086e2b708a98a9c355f14c25a/src/Language/Haskell/Generate/Monad.hs | haskell | ------------------------------------------------------------------------------
Generate expressions
| This monad keeps track of a counter for generating unique names and the set of modules
that are needed for the expression.
| Extract the set of modules and the value from a Generate action.
| This is a type alias for a Generate action that returns an expression of type 't'.
| Use a haskell-src-exts Exp as the result of a Generate action.
| Pretty print the expression generated by a given action.
| Generate a case expression.
| Import a function from a module. This function is polymorphic in the type of the resulting expression,
you should probably only use this function to define type-restricted specializations.
Example:
> addInt :: ExpG (Int -> Int -> Int) -- Here we restricted the type to something sensible
> addInt = useValue "Prelude" $ Symbol "+"
| Import a value constructor from a module. Returns the qualified name of the constructor.
| Use the value of a variable with the given name.
| Generate a new unique variable name with the given prefix. Note that this new variable name
is only unique relative to other variable names generated by this function.
| Generate a expression from a haskell value. This can for example be used to create lambdas:
\ pvar_0 -> \ pvar_1 -> pvar_1 pvar_0
Or string literals:
>>> putStrLn $ generateExp $ expr "I'm a string!"
['I', '\'', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', '!']
| This function generates the haskell expression from the given haskell value.
------------------------------------------------------------------------------
Apply functions
| Apply a function in a haskell expression to a value.
| Operator for 'applyE'.
------------------------------------------------------------------------------
Generate modules
| A module keeps track of the needed imports, but also has a list of declarations in it.
| This is the resulting type of a function generating a module. It is a ModuleM action returning the export list.
or export it using 'exportFun'.
| Add a declaration to the module. Return a reference to it that can be used to either apply the function to some values or export it.
| Extract the Module from a module generator.
| Generate the source code for a module. | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE CPP #
module Language.Haskell.Generate.Monad
( Generate(..), ExpG
, runGenerate, newName
, returnE
, useValue, useCon, useVar
, caseE
, applyE, applyE2, applyE3, applyE4, applyE5, applyE6
, (<>$)
, GenExp(..)
, ModuleM(..)
, ModuleG
, FunRef(..)
, Name(..)
, exportFun
, addDecl
, runModuleM
, generateModule
, generateExp
)
where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import Control.Monad.Trans.Writer
import qualified Data.Set as S
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.SrcLoc
import Language.Haskell.Exts.Syntax
import Language.Haskell.Generate.Expression
import Prelude
newtype Generate a = Generate { unGenerate :: StateT Integer (Writer (S.Set ModuleName)) a } deriving (Functor, Applicative, Monad)
runGenerate :: Generate a -> (a, S.Set ModuleName)
runGenerate (Generate a) = runWriter $ evalStateT a 0
type ExpG t = Generate (Expression t)
returnE :: Exp -> ExpG t
returnE = return . Expression
generateExp :: ExpG t -> String
generateExp = prettyPrint . runExpression . fst . runGenerate
caseE :: ExpG x -> [(Pat, ExpG t)] -> ExpG t
caseE v alt = do
v' <- v
#if MIN_VERSION_haskell_src_exts(1,17,0)
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') Nothing) a) alt
#elif MIN_VERSION_haskell_src_exts(1,16,0)
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') (BDecls [])) a) alt
#else
alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedAlt $ runExpression a') (BDecls [])) a) alt
#endif
return $ Expression $ Case (runExpression v') alt'
useValue :: String -> Name -> ExpG a
useValue md name = Generate $ do
lift $ tell $ S.singleton $ ModuleName md
return $ Expression $ Var $ Qual (ModuleName md) name
useCon :: String -> Name -> Generate QName
useCon md name = Generate $ do
lift $ tell $ S.singleton $ ModuleName md
return $ Qual (ModuleName md) name
useVar :: Name -> ExpG t
useVar name = return $ Expression $ Var $ UnQual name
newName :: String -> Generate Name
newName pref = Generate $ do
i <- get <* modify succ
return $ Ident $ pref ++ show i
> > > putStrLn $ generateExp $ expr ( \x f - > f < > $ x )
class GenExp t where
type GenExpType t :: *
expr :: t -> ExpG (GenExpType t)
instance GenExp (ExpG a) where
type GenExpType (ExpG a) = a
expr = id
instance GenExp (Expression t) where
type GenExpType (Expression t) = t
expr = return
instance GenExp Char where
type GenExpType Char = Char
expr = return . Expression . Lit . Char
instance GenExp Integer where
type GenExpType Integer = Integer
expr = return . Expression . Lit . Int
instance GenExp Rational where
type GenExpType Rational = Rational
expr = return . Expression . Lit . Frac
instance GenExp a => GenExp [a] where
type GenExpType [a] = [GenExpType a]
expr = Generate . fmap (Expression . List . map runExpression) . mapM (unGenerate . expr)
instance GenExp x => GenExp (ExpG a -> x) where
type GenExpType (ExpG a -> x) = a -> GenExpType x
expr f = do
pvarName <- newName "pvar_"
body <- expr $ f $ return $ Expression $ Var $ UnQual pvarName
return $ Expression $ Lambda noLoc [PVar pvarName] $ runExpression body
applyE :: ExpG (a -> b) -> ExpG a -> ExpG b
applyE a b = wrap $ liftM (foldl1 App) $ sequence [unwrap a, unwrap b]
where wrap = fmap Expression
unwrap = fmap runExpression
(<>$) :: ExpG (a -> b) -> ExpG a -> ExpG b
(<>$) = applyE
infixl 1 <>$
| ApplyE for 2 arguments
applyE2 :: ExpG (a -> b -> c) -> ExpG a -> ExpG b -> ExpG c
applyE2 a b c = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 3 arguments
applyE3 :: ExpG (a -> b -> c -> d) -> ExpG a -> ExpG b -> ExpG c -> ExpG d
applyE3 a b c d = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 4 arguments
applyE4 :: ExpG (a -> b -> c -> d -> e) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e
applyE4 a b c d e = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 5 arguments
applyE5 :: ExpG (a -> b -> c -> d -> e -> f) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f
applyE5 a b c d e f = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f]
where wrap = fmap Expression
unwrap = fmap runExpression
| Apply a function to 6 arguments
applyE6 :: ExpG (a -> b -> c -> d -> e -> f -> g) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f -> ExpG g
applyE6 a b c d e f g = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f,unwrap g]
where wrap = fmap Expression
unwrap = fmap runExpression
newtype ModuleM a = ModuleM (Writer (S.Set ModuleName, [Decl]) a) deriving (Functor, Applicative, Monad)
type ModuleG = ModuleM (Maybe [ExportSpec])
| A reference to a function . With a reference to a function , you can apply it ( by lifting it into using ' expr ' ) to some value
data FunRef t = FunRef Name
instance GenExp (FunRef t) where
type GenExpType (FunRef t) = t
expr (FunRef n) = return $ Expression $ Var $ UnQual n
| Generate a ExportSpec for a given function item .
exportFun :: FunRef t -> ExportSpec
#if MIN_VERSION_haskell_src_exts(1,16,0) && !MIN_VERSION_haskell_src_exts(1,17,0)
exportFun (FunRef name) = EVar NoNamespace (UnQual name)
#else
exportFun (FunRef name) = EVar (UnQual name)
#endif
addDecl :: Name -> ExpG t -> ModuleM (FunRef t)
addDecl name e = ModuleM $ do
let (body, mods) = runGenerate e
#if MIN_VERSION_haskell_src_exts(1,17,0)
tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) Nothing]])
#else
tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) $ BDecls []]])
#endif
return $ FunRef name
runModuleM :: ModuleG -> String -> Module
runModuleM (ModuleM act) name =
#if MIN_VERSION_haskell_src_exts(1,16,0)
Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False False Nothing Nothing Nothing) $ S.toList imps) decls
#else
Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False Nothing Nothing Nothing) $ S.toList imps) decls
#endif
where (export, (imps, decls)) = runWriter act
generateModule :: ModuleG -> String -> String
generateModule = fmap prettyPrint . runModuleM
|
29984cd0401f2aee362adc9f428267ea2a8d1a54f4130cf6cd9e328bc97f9f6c | Gbury/dolmen | dolmen_tptp_v6_3_0.mli |
(* This file is free software, part of dolmen. See file "LICENSE" formore information *)
(** TPTP language input *)
module type Id = Ast.Id
module type Term = Ast.Term
module type Statement = Ast.Statement
* Implementation requirement for the TPTP format .
module Make
(L : Dolmen_intf.Location.S)
(I : Id)
(T : Term with type location := L.t and type id := I.t)
(S : Statement with type location := L.t and type id := I.t and type term := T.t) :
Dolmen_intf.Language.S with type statement = S.t and type file := L.file
* Functor to generate a parser for the TPTP format .
| null | https://raw.githubusercontent.com/Gbury/dolmen/55566c8db8a9c7636743b49a8c0bfaa061bbeb0c/src/languages/tptp/v6.3.0/dolmen_tptp_v6_3_0.mli | ocaml | This file is free software, part of dolmen. See file "LICENSE" formore information
* TPTP language input |
module type Id = Ast.Id
module type Term = Ast.Term
module type Statement = Ast.Statement
* Implementation requirement for the TPTP format .
module Make
(L : Dolmen_intf.Location.S)
(I : Id)
(T : Term with type location := L.t and type id := I.t)
(S : Statement with type location := L.t and type id := I.t and type term := T.t) :
Dolmen_intf.Language.S with type statement = S.t and type file := L.file
* Functor to generate a parser for the TPTP format .
|
18c748a4883f8e6f86092796c2f7182db4acb81685596bd0bc92736e7a8c4b43 | ept/compsci | lambda2comb.ml |
* Convert a lambda calculus expression into an equivalent combinator expression .
* Pretty - prints terms at various stages of their evolution .
* ( c ) < > , 2008 - 03 - 08
* Convert a lambda calculus expression into an equivalent combinator expression.
* Pretty-prints terms at various stages of their evolution.
* (c) Martin Kleppmann <>, 2008-03-08
*)
datatype expr =
CONST of string
| VAR of string
| LAM of string * expr
| APP of expr * expr
| S | K | Y | I | B | C;
Tests whether a given expression ( second argument ) contains a particular
free variable ( first argument ) .
free variable (first argument). *)
fun hasFreeVar x (VAR y) = x = y
| hasFreeVar x (LAM(y,m)) = if x = y then false else (hasFreeVar x m)
| hasFreeVar x (APP(m,n)) = (hasFreeVar x m) orelse (hasFreeVar x n)
| hasFreeVar _ _ = false;
Tests whether two given expressions are syntactically equal .
fun exprEqual (CONST x) (CONST y) = x = y
| exprEqual (VAR x) (VAR y) = x = y
| exprEqual (LAM(x,m)) (LAM(y,n)) = (x = y) andalso (exprEqual m n)
| exprEqual (APP(a,b)) (APP(c,d)) = (exprEqual a c) andalso (exprEqual b d)
| exprEqual a b = a = b;
advanced translation from lambda calculus to combinators
( may need to be applied multiple times in order to complete -- this is done
by the lambdaToComb function ) .
(may need to be applied multiple times in order to complete -- this is done
by the lambdaToComb function). *)
fun conversionStep (LAM(x, CONST y)) = APP(K, CONST y)
| conversionStep (LAM(x, VAR y)) = if x = y then I else APP(K, VAR y)
| conversionStep (LAM(x, LAM(y, m))) =
let val n = LAM(y, m) in
if (hasFreeVar x n) then (LAM(x, conversionStep n)) else (APP(K, conversionStep n)) end
| conversionStep (LAM(x, APP(a, b))) =
let val varLeft = hasFreeVar x a
and varRight = hasFreeVar x b
in if varLeft then
if varRight then APP(APP(S, LAM(x, a)), LAM(x, b))
else APP(APP(C, LAM(x, a)), b)
else
if varRight then APP(APP(B, a), LAM(x, b))
else APP(K, APP(a, b))
end
| conversionStep (APP(m, n)) = APP(conversionStep m, conversionStep n)
| conversionStep m = m;
(* Translate a lambda calculus expression into a combinator expression.
Applies conversionStep repeatedly until no change in the expression is detected. *)
fun lambdaToComb ex =
let val ex2 = conversionStep ex
in if (exprEqual ex ex2) then ex2 else (lambdaToComb ex2) end;
(* Returns true if the lambda expression is just a constant or a variable, false otherwise. *)
fun isPrimitive (APP(_,_)) = false
| isPrimitive (LAM(_,_)) = false
| isPrimitive _ = true;
(* Returns true if the lambda expression is a constant or a variable,
or if the outermost node is a function application. False otherwise. *)
fun isPrimOrApp (APP(_,_)) = true
| isPrimOrApp x = isPrimitive x;
(* Pretty-prints a lambda or combinator expression. *)
fun prettyPrint (CONST c) = c
| prettyPrint (VAR x) = x
| prettyPrint (LAM(x,m)) = "^" ^ x ^ ". " ^ (prettyPrint m)
| prettyPrint (APP(m,n)) = (maybeBrackets1 m) ^ " " ^ (maybeBrackets2 n)
| prettyPrint S = "S"
| prettyPrint K = "K"
| prettyPrint Y = "Y"
| prettyPrint I = "I"
| prettyPrint B = "B"
| prettyPrint C = "C"
and maybeBrackets1 m =
let val primM = isPrimOrApp m
in (if primM then "" else "(") ^ (prettyPrint m) ^ (if primM then "" else ")") end
and maybeBrackets2 m =
let val primM = isPrimitive m
in (if primM then "" else "(") ^ (prettyPrint m) ^ (if primM then "" else ")") end;
(* Pretty-prints the conversion from a lambda expression to a combinator expression,
step by step. *)
fun printSteps (ex, str) =
let val ex2 = conversionStep ex
in if (exprEqual ex ex2) then str
else (printSteps (ex2, str ^ "\n" ^ (prettyPrint ex2) ^ "\n")) end;
(* EXAMPLE OF USE *)
(* A very verbose definition of the factorial function in lambda calculus *)
val fact =
APP(
Y,
LAM("f",
LAM("x",
APP(
APP(
APP(
CONST "if",
APP(
APP(
CONST "=",
VAR "x"
),
CONST "0"
)
),
CONST "1"
),
APP(
APP(
CONST "*",
VAR "x"
),
APP(
VAR "f",
APP(
APP(
CONST "-",
VAR "x"
),
CONST "1"
)
)
)
)
)
)
);
(* Print the original lambda calculus expression *)
print ("\n\nThe factorial function in lambda calculus:\n"
^ (prettyPrint fact) ^ "\n\n"
^ (printSteps(fact, "Translating into combinators, step by step:\n")) ^ "\n\n");
| null | https://raw.githubusercontent.com/ept/compsci/ed666bb4cf52ac2af5c2d13894870bdc23dca237/lambda_calculus/lambda2comb.ml | ocaml | Translate a lambda calculus expression into a combinator expression.
Applies conversionStep repeatedly until no change in the expression is detected.
Returns true if the lambda expression is just a constant or a variable, false otherwise.
Returns true if the lambda expression is a constant or a variable,
or if the outermost node is a function application. False otherwise.
Pretty-prints a lambda or combinator expression.
Pretty-prints the conversion from a lambda expression to a combinator expression,
step by step.
EXAMPLE OF USE
A very verbose definition of the factorial function in lambda calculus
Print the original lambda calculus expression |
* Convert a lambda calculus expression into an equivalent combinator expression .
* Pretty - prints terms at various stages of their evolution .
* ( c ) < > , 2008 - 03 - 08
* Convert a lambda calculus expression into an equivalent combinator expression.
* Pretty-prints terms at various stages of their evolution.
* (c) Martin Kleppmann <>, 2008-03-08
*)
datatype expr =
CONST of string
| VAR of string
| LAM of string * expr
| APP of expr * expr
| S | K | Y | I | B | C;
Tests whether a given expression ( second argument ) contains a particular
free variable ( first argument ) .
free variable (first argument). *)
fun hasFreeVar x (VAR y) = x = y
| hasFreeVar x (LAM(y,m)) = if x = y then false else (hasFreeVar x m)
| hasFreeVar x (APP(m,n)) = (hasFreeVar x m) orelse (hasFreeVar x n)
| hasFreeVar _ _ = false;
Tests whether two given expressions are syntactically equal .
fun exprEqual (CONST x) (CONST y) = x = y
| exprEqual (VAR x) (VAR y) = x = y
| exprEqual (LAM(x,m)) (LAM(y,n)) = (x = y) andalso (exprEqual m n)
| exprEqual (APP(a,b)) (APP(c,d)) = (exprEqual a c) andalso (exprEqual b d)
| exprEqual a b = a = b;
advanced translation from lambda calculus to combinators
( may need to be applied multiple times in order to complete -- this is done
by the lambdaToComb function ) .
(may need to be applied multiple times in order to complete -- this is done
by the lambdaToComb function). *)
fun conversionStep (LAM(x, CONST y)) = APP(K, CONST y)
| conversionStep (LAM(x, VAR y)) = if x = y then I else APP(K, VAR y)
| conversionStep (LAM(x, LAM(y, m))) =
let val n = LAM(y, m) in
if (hasFreeVar x n) then (LAM(x, conversionStep n)) else (APP(K, conversionStep n)) end
| conversionStep (LAM(x, APP(a, b))) =
let val varLeft = hasFreeVar x a
and varRight = hasFreeVar x b
in if varLeft then
if varRight then APP(APP(S, LAM(x, a)), LAM(x, b))
else APP(APP(C, LAM(x, a)), b)
else
if varRight then APP(APP(B, a), LAM(x, b))
else APP(K, APP(a, b))
end
| conversionStep (APP(m, n)) = APP(conversionStep m, conversionStep n)
| conversionStep m = m;
fun lambdaToComb ex =
let val ex2 = conversionStep ex
in if (exprEqual ex ex2) then ex2 else (lambdaToComb ex2) end;
fun isPrimitive (APP(_,_)) = false
| isPrimitive (LAM(_,_)) = false
| isPrimitive _ = true;
fun isPrimOrApp (APP(_,_)) = true
| isPrimOrApp x = isPrimitive x;
fun prettyPrint (CONST c) = c
| prettyPrint (VAR x) = x
| prettyPrint (LAM(x,m)) = "^" ^ x ^ ". " ^ (prettyPrint m)
| prettyPrint (APP(m,n)) = (maybeBrackets1 m) ^ " " ^ (maybeBrackets2 n)
| prettyPrint S = "S"
| prettyPrint K = "K"
| prettyPrint Y = "Y"
| prettyPrint I = "I"
| prettyPrint B = "B"
| prettyPrint C = "C"
and maybeBrackets1 m =
let val primM = isPrimOrApp m
in (if primM then "" else "(") ^ (prettyPrint m) ^ (if primM then "" else ")") end
and maybeBrackets2 m =
let val primM = isPrimitive m
in (if primM then "" else "(") ^ (prettyPrint m) ^ (if primM then "" else ")") end;
fun printSteps (ex, str) =
let val ex2 = conversionStep ex
in if (exprEqual ex ex2) then str
else (printSteps (ex2, str ^ "\n" ^ (prettyPrint ex2) ^ "\n")) end;
val fact =
APP(
Y,
LAM("f",
LAM("x",
APP(
APP(
APP(
CONST "if",
APP(
APP(
CONST "=",
VAR "x"
),
CONST "0"
)
),
CONST "1"
),
APP(
APP(
CONST "*",
VAR "x"
),
APP(
VAR "f",
APP(
APP(
CONST "-",
VAR "x"
),
CONST "1"
)
)
)
)
)
)
);
print ("\n\nThe factorial function in lambda calculus:\n"
^ (prettyPrint fact) ^ "\n\n"
^ (printSteps(fact, "Translating into combinators, step by step:\n")) ^ "\n\n");
|
5db80e599865cd5ead2e62757a409fc405f92cf7c6b1ea6cfaeb76f045124d37 | Yume-Labs/prism | core.clj | (ns prism.core
(:gen-class)
(:require [clojure.core.async :refer [chan]]
[clojure.java.io :refer [file]]
[clojure.edn :as edn]
[prism.db :refer [get-production-node retrieve-config]]
[prism.preflight :refer [check-config]]
[prism.pregenerate :refer [generate-collection]]
[prism.decisions :refer [decision-resolver]]
[prism.outcomes :refer [outcome-resolver]]
[prism.structure :refer [structure-resolver]]
[prism.metadata :refer [metadata-writer]]
[prism.render :refer [image-renderer]]
[prism.done :refer [done-checker]]))
(defn do-generate
[node collection config assets-root]
(check-config config)
(let [in-ch (chan)]
(.mkdir (java.io.File. (str assets-root "/" collection)))
(->> in-ch
(decision-resolver node collection config)
(outcome-resolver node collection config)
(structure-resolver node collection config)
(metadata-writer node collection config assets-root)
(image-renderer node collection config assets-root)
(done-checker config))
(generate-collection node collection config in-ch)))
(defn validate-collection-name
[node name]
(if (or (= "test" name) (= "sample" name))
(do (println "'test' and 'sample' are reserved names.")
(println "Please try something else:")
nil)
(if (or (.exists (file (str "assets/" name)))
(not (nil? (retrieve-config node name))))
(do (println (str "'" name "' is already in use."))
(println "Please choose another collection name:")
nil)
name)))
(defn validate-config-file-location
[loc]
(if (and (.exists (file loc))
(edn/read-string (slurp loc)))
(edn/read-string (slurp loc))
(do (println "There doesn't seem to be a config file there.")
(println "Please choose another config file:")
nil)))
(defn get-collection-name
[node]
(println "First, we need a collection name.")
(println "This needs to be something you haven't used before:")
(loop [collection-name nil]
(if (not (nil? collection-name))
collection-name
(let [candidate (read-line)]
(recur (validate-collection-name node candidate))))))
(defn get-config-file
[]
(println "")
(println "Great, now we need to choose a config file!")
(println "You should type the file location relative to the Prism root,")
(println "if you don't have a config file, try 'config/sample.edn':")
(loop [config-file nil]
(if (not (nil? config-file))
config-file
(let [candidate (read-line)]
(recur (validate-config-file-location candidate))))))
(defn -main
"Application main ingress function."
[& args]
(let [splash (slurp "splash.txt")
node (get-production-node)]
(println splash)
(let [collection (get-collection-name node)
config (get-config-file)
assets-root "assets"]
(do-generate node collection config assets-root))))
| null | https://raw.githubusercontent.com/Yume-Labs/prism/1dd2c0f4eac8bbd32877a40617b36c1319d8f114/src/prism/core.clj | clojure | (ns prism.core
(:gen-class)
(:require [clojure.core.async :refer [chan]]
[clojure.java.io :refer [file]]
[clojure.edn :as edn]
[prism.db :refer [get-production-node retrieve-config]]
[prism.preflight :refer [check-config]]
[prism.pregenerate :refer [generate-collection]]
[prism.decisions :refer [decision-resolver]]
[prism.outcomes :refer [outcome-resolver]]
[prism.structure :refer [structure-resolver]]
[prism.metadata :refer [metadata-writer]]
[prism.render :refer [image-renderer]]
[prism.done :refer [done-checker]]))
(defn do-generate
[node collection config assets-root]
(check-config config)
(let [in-ch (chan)]
(.mkdir (java.io.File. (str assets-root "/" collection)))
(->> in-ch
(decision-resolver node collection config)
(outcome-resolver node collection config)
(structure-resolver node collection config)
(metadata-writer node collection config assets-root)
(image-renderer node collection config assets-root)
(done-checker config))
(generate-collection node collection config in-ch)))
(defn validate-collection-name
[node name]
(if (or (= "test" name) (= "sample" name))
(do (println "'test' and 'sample' are reserved names.")
(println "Please try something else:")
nil)
(if (or (.exists (file (str "assets/" name)))
(not (nil? (retrieve-config node name))))
(do (println (str "'" name "' is already in use."))
(println "Please choose another collection name:")
nil)
name)))
(defn validate-config-file-location
[loc]
(if (and (.exists (file loc))
(edn/read-string (slurp loc)))
(edn/read-string (slurp loc))
(do (println "There doesn't seem to be a config file there.")
(println "Please choose another config file:")
nil)))
(defn get-collection-name
[node]
(println "First, we need a collection name.")
(println "This needs to be something you haven't used before:")
(loop [collection-name nil]
(if (not (nil? collection-name))
collection-name
(let [candidate (read-line)]
(recur (validate-collection-name node candidate))))))
(defn get-config-file
[]
(println "")
(println "Great, now we need to choose a config file!")
(println "You should type the file location relative to the Prism root,")
(println "if you don't have a config file, try 'config/sample.edn':")
(loop [config-file nil]
(if (not (nil? config-file))
config-file
(let [candidate (read-line)]
(recur (validate-config-file-location candidate))))))
(defn -main
"Application main ingress function."
[& args]
(let [splash (slurp "splash.txt")
node (get-production-node)]
(println splash)
(let [collection (get-collection-name node)
config (get-config-file)
assets-root "assets"]
(do-generate node collection config assets-root))))
|
|
1ba3e9fe720db2f6572f8774740077bd7913611e4154d3ed0085abcfe0b21d79 | ghc/packages-dph | Vector.hs | module Vector
(solveV)
where
import Common
import Data.Vector.Unboxed
import Prelude hiding (map,filter,minimum)
# NOINLINE solveV #
solveV
:: Vector Vec3 -- ^ vertices of the surface
^ triangles , each 3 vertex indices
-> Vector Vec3 -- ^ rays to cast
-> Double -- ^ time
-> Vector Colour -- ^ the colours of the ray results - in the same order as input rays
solveV vertices triangles rays time
= map cast' rays
where
matrix = rotateY 0 -- (time / 4)
tris' = map (triangleFull . tri vertices matrix) triangles
cast' = cast tris'
cast
:: Vector TriangleFull -- ^ triangles with pluecker coords etc precomputed
-> Vec3 -- ^ ray
-> Colour
cast triangles ray
= let r' = ((0,0,0), ray)
(dist,tri) = mincast triangles r'
in if dist < arbitraryLargeDouble
then lights triangles (ray `vsmul` (dist*0.999)) (colourOfTriangleF tri)
else (0,0,0)
mincast :: Vector TriangleFull
-> Line
-> (Double,TriangleFull)
mincast triangles ray
= let pl = plueckerOfLine ray
ch = map (check ray pl) triangles
mi = minIndex ch
dist = ch ! mi
tri = triangles ! mi
in (dist, tri)
lights :: Vector TriangleFull
-> Vec3
-> Colour
-> Colour
lights triangles pt colour
= let (d1,_) = mincast triangles (pt,(-10,-10,-10))
(d2,_) = mincast triangles (pt,(50, 50, 0))
(d3,_) = mincast triangles (pt,((-5), 50, 0))
fix i = if i < 1
then 0
else 1
in colour `vsmul` ((fix d1 + fix d2 + fix d3) / 3)
tri :: Vector Vec3 -> Matrix3 -> (Int,Int,Int,Colour) -> Triangle
tri v matrix (a,b,c,colour) = (get a, get b, get c, colour)
where
{-# INLINE get #-}
get i = trans_disp matrix (v `unsafeIndex` i)
| null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-examples/examples/spectral/Pluecker/Vector.hs | haskell | ^ vertices of the surface
^ rays to cast
^ time
^ the colours of the ray results - in the same order as input rays
(time / 4)
^ triangles with pluecker coords etc precomputed
^ ray
# INLINE get # | module Vector
(solveV)
where
import Common
import Data.Vector.Unboxed
import Prelude hiding (map,filter,minimum)
# NOINLINE solveV #
solveV
^ triangles , each 3 vertex indices
solveV vertices triangles rays time
= map cast' rays
where
tris' = map (triangleFull . tri vertices matrix) triangles
cast' = cast tris'
cast
-> Colour
cast triangles ray
= let r' = ((0,0,0), ray)
(dist,tri) = mincast triangles r'
in if dist < arbitraryLargeDouble
then lights triangles (ray `vsmul` (dist*0.999)) (colourOfTriangleF tri)
else (0,0,0)
mincast :: Vector TriangleFull
-> Line
-> (Double,TriangleFull)
mincast triangles ray
= let pl = plueckerOfLine ray
ch = map (check ray pl) triangles
mi = minIndex ch
dist = ch ! mi
tri = triangles ! mi
in (dist, tri)
lights :: Vector TriangleFull
-> Vec3
-> Colour
-> Colour
lights triangles pt colour
= let (d1,_) = mincast triangles (pt,(-10,-10,-10))
(d2,_) = mincast triangles (pt,(50, 50, 0))
(d3,_) = mincast triangles (pt,((-5), 50, 0))
fix i = if i < 1
then 0
else 1
in colour `vsmul` ((fix d1 + fix d2 + fix d3) / 3)
tri :: Vector Vec3 -> Matrix3 -> (Int,Int,Int,Colour) -> Triangle
tri v matrix (a,b,c,colour) = (get a, get b, get c, colour)
where
get i = trans_disp matrix (v `unsafeIndex` i)
|
3c5e6c25cac71607253adcb71afc0ea674ac73c9db909d4b8e87cd0dab29a4b4 | re-ops/re-cipes | matrix.clj | (ns re-cipes.apps.matrix
(:require
[re-cipes.docker.nginx]
[re-cipes.docker.re-dock]
[re-cog.facts.datalog :refer (hostname fqdn)]
[re-cog.resources.exec :refer [run]]
[re-cog.resources.permissions :refer (set-file-acl)]
[re-cog.resources.ufw :refer (add-rule)]
[re-cog.resources.nginx :refer (site-enabled)]
[re-cog.resources.service :refer (on-boot)]
[re-cog.resources.file :refer (copy symlink directory file line yaml-set chmod)]
[re-cog.common.recipe :refer (require-recipe)]))
(require-recipe)
(def-inline {:depends [#'re-cipes.docker.server/services #'re-cipes.docker.re-dock/volume #'re-cipes.docker.re-dock/repo]}
setup
"setup Matrix"
[]
(let [repo "/etc/docker/re-dock/matrix"
dest "/etc/docker/compose/matrix"
{:keys [password]} (configuration :matrix :postgres)]
(copy (<< "~{repo}/matrix.yml") (<< "~{repo}/docker-compose.yml"))
(symlink dest repo)
(on-boot "docker-compose@matrix" :enable)))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall #'re-cipes.apps.matrix/setup]}
element
"Element"
[]
(let [external-port 8443
file "config.json"
dest "/etc/docker/compose/matrix"
{:keys [nginx]} (configuration)]
(site-enabled nginx "element" external-port 8080 {})
(add-rule external-port :allow {})
(template (<< "/tmp/resources/templates/matrix/element/~{file}.mustache") (<< "~{dest}/~{file}") {:hostname (hostname) :fqdn (fqdn)})))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall]} synapse-proxy
"Synapse proxy"
[]
(let [external-port 443
{:keys [nginx]} (configuration)]
(site-enabled nginx "synapse" external-port 8008 {:http-2 true})
(add-rule external-port :allow {})))
(def-inline {:depends [#'re-cipes.apps.matrix/setup]} generate
"Generate configuration"
[]
(let [host (fqdn)
parent "/etc/docker/compose/matrix/matrix"
dest (<< "~{parent}/synapse")
config (<< "~{dest}/homeserver.yaml")]
(letfn [(pip []
(script
("/usr/bin/pip3" "install" "matrix-synapse")))
(configure []
(script ("/usr/bin/python3" "-m" "synapse.app.homeserver" "--server-name" ~host
"--config-path" ~config "--config-directory" ~dest "--generate-config" "--report-stats=no")))]
(package "python3-pip" :present)
(directory parent :present)
(directory dest :present)
(run pip)
(file config :absent)
(run configure)
(set-file-acl "re-ops" "rw" dest)
(chmod dest "o+rw" {:recursive true}))))
(def-inline {:depends [#'re-cipes.apps.matrix/setup]} env
"Docker env file"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
parent "/etc/docker/compose/matrix/"
env (<< "~{parent}/.env")]
(file env :present)
(line env (<< "POSTGRES_PASSWORD=~{password}") :present)))
(def-inline {:depends [#'re-cipes.apps.matrix/generate]} configure
"General Configuration"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
dest "/etc/docker/compose/matrix/matrix/synapse"
homeserver (<< "~{dest}/homeserver.yaml")]
(set-file-acl "re-ops" "rw" dest)
(chmod dest "o+rw" {:recursive true})
(yaml-set (<< "~{dest}/~(fqdn).log.config") [:handlers :file :filename] (<< "/data/homeserver.log"))
(yaml-set homeserver [:log_config] (<< "/data/~(fqdn).log.config"))
(yaml-set homeserver [:signing_key_path] (<< "/data/~(fqdn).signing.key"))
(yaml-set homeserver [:media_store_path] (<< "/data/media_store"))
(yaml-set homeserver [:pid_file] (<< "/data/homeserver.pid"))
(yaml-set homeserver [:listeners 0 :bind_addresses] ["0.0.0.0"])))
(def-inline {:depends [#'re-cipes.apps.matrix/generate]} database
"DB Configuration"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
dest "/etc/docker/compose/matrix/matrix/synapse"
homeserver (<< "~{dest}/homeserver.yaml")]
(yaml-set homeserver [:database :name] "psycopg2")
(yaml-set homeserver [:database :txn_limit] 10000)
(yaml-set homeserver [:database :args :user] "synapse_user")
(yaml-set homeserver [:database :args :password] password)
(yaml-set homeserver [:database :args :database] "synapse")
(yaml-set homeserver [:database :args :host] "postgres")
(yaml-set homeserver [:database :args :port] 5432)
(yaml-set homeserver [:database :args :cp_min] 5)
(yaml-set homeserver [:database :args :cp_max] 10)))
| null | https://raw.githubusercontent.com/re-ops/re-cipes/161318f8d2785a4eabfbcfe2ea76d8c4aa7db899/src/re_cipes/apps/matrix.clj | clojure | (ns re-cipes.apps.matrix
(:require
[re-cipes.docker.nginx]
[re-cipes.docker.re-dock]
[re-cog.facts.datalog :refer (hostname fqdn)]
[re-cog.resources.exec :refer [run]]
[re-cog.resources.permissions :refer (set-file-acl)]
[re-cog.resources.ufw :refer (add-rule)]
[re-cog.resources.nginx :refer (site-enabled)]
[re-cog.resources.service :refer (on-boot)]
[re-cog.resources.file :refer (copy symlink directory file line yaml-set chmod)]
[re-cog.common.recipe :refer (require-recipe)]))
(require-recipe)
(def-inline {:depends [#'re-cipes.docker.server/services #'re-cipes.docker.re-dock/volume #'re-cipes.docker.re-dock/repo]}
setup
"setup Matrix"
[]
(let [repo "/etc/docker/re-dock/matrix"
dest "/etc/docker/compose/matrix"
{:keys [password]} (configuration :matrix :postgres)]
(copy (<< "~{repo}/matrix.yml") (<< "~{repo}/docker-compose.yml"))
(symlink dest repo)
(on-boot "docker-compose@matrix" :enable)))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall #'re-cipes.apps.matrix/setup]}
element
"Element"
[]
(let [external-port 8443
file "config.json"
dest "/etc/docker/compose/matrix"
{:keys [nginx]} (configuration)]
(site-enabled nginx "element" external-port 8080 {})
(add-rule external-port :allow {})
(template (<< "/tmp/resources/templates/matrix/element/~{file}.mustache") (<< "~{dest}/~{file}") {:hostname (hostname) :fqdn (fqdn)})))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall]} synapse-proxy
"Synapse proxy"
[]
(let [external-port 443
{:keys [nginx]} (configuration)]
(site-enabled nginx "synapse" external-port 8008 {:http-2 true})
(add-rule external-port :allow {})))
(def-inline {:depends [#'re-cipes.apps.matrix/setup]} generate
"Generate configuration"
[]
(let [host (fqdn)
parent "/etc/docker/compose/matrix/matrix"
dest (<< "~{parent}/synapse")
config (<< "~{dest}/homeserver.yaml")]
(letfn [(pip []
(script
("/usr/bin/pip3" "install" "matrix-synapse")))
(configure []
(script ("/usr/bin/python3" "-m" "synapse.app.homeserver" "--server-name" ~host
"--config-path" ~config "--config-directory" ~dest "--generate-config" "--report-stats=no")))]
(package "python3-pip" :present)
(directory parent :present)
(directory dest :present)
(run pip)
(file config :absent)
(run configure)
(set-file-acl "re-ops" "rw" dest)
(chmod dest "o+rw" {:recursive true}))))
(def-inline {:depends [#'re-cipes.apps.matrix/setup]} env
"Docker env file"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
parent "/etc/docker/compose/matrix/"
env (<< "~{parent}/.env")]
(file env :present)
(line env (<< "POSTGRES_PASSWORD=~{password}") :present)))
(def-inline {:depends [#'re-cipes.apps.matrix/generate]} configure
"General Configuration"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
dest "/etc/docker/compose/matrix/matrix/synapse"
homeserver (<< "~{dest}/homeserver.yaml")]
(set-file-acl "re-ops" "rw" dest)
(chmod dest "o+rw" {:recursive true})
(yaml-set (<< "~{dest}/~(fqdn).log.config") [:handlers :file :filename] (<< "/data/homeserver.log"))
(yaml-set homeserver [:log_config] (<< "/data/~(fqdn).log.config"))
(yaml-set homeserver [:signing_key_path] (<< "/data/~(fqdn).signing.key"))
(yaml-set homeserver [:media_store_path] (<< "/data/media_store"))
(yaml-set homeserver [:pid_file] (<< "/data/homeserver.pid"))
(yaml-set homeserver [:listeners 0 :bind_addresses] ["0.0.0.0"])))
(def-inline {:depends [#'re-cipes.apps.matrix/generate]} database
"DB Configuration"
[]
(let [{:keys [password]} (configuration :matrix :postgres)
dest "/etc/docker/compose/matrix/matrix/synapse"
homeserver (<< "~{dest}/homeserver.yaml")]
(yaml-set homeserver [:database :name] "psycopg2")
(yaml-set homeserver [:database :txn_limit] 10000)
(yaml-set homeserver [:database :args :user] "synapse_user")
(yaml-set homeserver [:database :args :password] password)
(yaml-set homeserver [:database :args :database] "synapse")
(yaml-set homeserver [:database :args :host] "postgres")
(yaml-set homeserver [:database :args :port] 5432)
(yaml-set homeserver [:database :args :cp_min] 5)
(yaml-set homeserver [:database :args :cp_max] 10)))
|
|
a1184a79ff4a00ab0e90c63a50a2d433cfbc52e32086a9edd9db59e0094e3812 | yesodweb/yesod | French.hs | {-# LANGUAGE OverloadedStrings #-}
module Yesod.Form.I18n.French (frenchFormMessage) where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
frenchFormMessage :: FormMessage -> Text
frenchFormMessage (MsgInvalidInteger t) = "Entier invalide : " `Data.Monoid.mappend` t
frenchFormMessage (MsgInvalidNumber t) = "Nombre invalide : " `mappend` t
frenchFormMessage (MsgInvalidEntry t) = "Entrée invalide : " `mappend` t
frenchFormMessage MsgInvalidTimeFormat = "Heure invalide (elle doit être au format HH:MM ou HH:MM:SS"
frenchFormMessage MsgInvalidDay = "Date invalide (elle doit être au format AAAA-MM-JJ"
frenchFormMessage (MsgInvalidUrl t) = "Adresse Internet invalide : " `mappend` t
frenchFormMessage (MsgInvalidEmail t) = "Adresse électronique invalide : " `mappend` t
frenchFormMessage (MsgInvalidHour t) = "Heure invalide : " `mappend` t
frenchFormMessage (MsgInvalidMinute t) = "Minutes invalides : " `mappend` t
frenchFormMessage (MsgInvalidSecond t) = "Secondes invalides " `mappend` t
frenchFormMessage MsgCsrfWarning = "Afin d'empêcher les attaques CSRF, veuillez ré-envoyer ce formulaire"
frenchFormMessage MsgValueRequired = "Ce champ est requis"
frenchFormMessage (MsgInputNotFound t) = "Entrée non trouvée : " `mappend` t
frenchFormMessage MsgSelectNone = "<Rien>"
frenchFormMessage (MsgInvalidBool t) = "Booléen invalide : " `mappend` t
frenchFormMessage MsgBoolYes = "Oui"
frenchFormMessage MsgBoolNo = "Non"
frenchFormMessage MsgDelete = "Détruire ?"
frenchFormMessage (MsgInvalidHexColorFormat t) = "Couleur non valide, doit être au format hexadécimal #rrggbb: " `mappend` t
| null | https://raw.githubusercontent.com/yesodweb/yesod/48d05fd6ab12ad440e1f2aa32684ed08b23f0613/yesod-form/Yesod/Form/I18n/French.hs | haskell | # LANGUAGE OverloadedStrings # | module Yesod.Form.I18n.French (frenchFormMessage) where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
frenchFormMessage :: FormMessage -> Text
frenchFormMessage (MsgInvalidInteger t) = "Entier invalide : " `Data.Monoid.mappend` t
frenchFormMessage (MsgInvalidNumber t) = "Nombre invalide : " `mappend` t
frenchFormMessage (MsgInvalidEntry t) = "Entrée invalide : " `mappend` t
frenchFormMessage MsgInvalidTimeFormat = "Heure invalide (elle doit être au format HH:MM ou HH:MM:SS"
frenchFormMessage MsgInvalidDay = "Date invalide (elle doit être au format AAAA-MM-JJ"
frenchFormMessage (MsgInvalidUrl t) = "Adresse Internet invalide : " `mappend` t
frenchFormMessage (MsgInvalidEmail t) = "Adresse électronique invalide : " `mappend` t
frenchFormMessage (MsgInvalidHour t) = "Heure invalide : " `mappend` t
frenchFormMessage (MsgInvalidMinute t) = "Minutes invalides : " `mappend` t
frenchFormMessage (MsgInvalidSecond t) = "Secondes invalides " `mappend` t
frenchFormMessage MsgCsrfWarning = "Afin d'empêcher les attaques CSRF, veuillez ré-envoyer ce formulaire"
frenchFormMessage MsgValueRequired = "Ce champ est requis"
frenchFormMessage (MsgInputNotFound t) = "Entrée non trouvée : " `mappend` t
frenchFormMessage MsgSelectNone = "<Rien>"
frenchFormMessage (MsgInvalidBool t) = "Booléen invalide : " `mappend` t
frenchFormMessage MsgBoolYes = "Oui"
frenchFormMessage MsgBoolNo = "Non"
frenchFormMessage MsgDelete = "Détruire ?"
frenchFormMessage (MsgInvalidHexColorFormat t) = "Couleur non valide, doit être au format hexadécimal #rrggbb: " `mappend` t
|
bc03549d82fb37309020305fcc4bf8f22626728146c103578f4328c22a9f10ed | openmusic-project/openmusic | maquetteinterface.lisp | ;=========================================================================
OpenMusic : Visual Programming Language for Music Composition
;
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
;
This file is part of the OpenMusic environment sources
;
OpenMusic 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.
;
OpenMusic 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 OpenMusic . If not , see < / > .
;
;=========================================================================
Music package
authors , , ,
;=========================================================================
(in-package :om)
(defmethod allowed-in-maq-p ((self score-element)) t)
(defmethod allowed-in-maq-p ((self voice)) t)
(defmethod allowed-in-maq-p ((self poly)) t)
(defmethod allowed-in-maq-p ((self measure)) t)
(defmethod allowed-in-maq-p ((self chord)) t)
(defmethod allowed-in-maq-p ((self note)) t)
(defmethod allow-strech-p ((self sequence*) (factor number)) factor)
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/87bdbf0635d8febb0c49f52c59a388b205775583/OPENMUSIC/code/projects/musicproject/container/maquetteinterface.lisp | lisp | =========================================================================
(at your option) any later version.
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.
=========================================================================
=========================================================================
| OpenMusic : Visual Programming Language for Music Composition
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
This file is part of the OpenMusic environment sources
OpenMusic 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
OpenMusic is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with OpenMusic . If not , see < / > .
Music package
authors , , ,
(in-package :om)
(defmethod allowed-in-maq-p ((self score-element)) t)
(defmethod allowed-in-maq-p ((self voice)) t)
(defmethod allowed-in-maq-p ((self poly)) t)
(defmethod allowed-in-maq-p ((self measure)) t)
(defmethod allowed-in-maq-p ((self chord)) t)
(defmethod allowed-in-maq-p ((self note)) t)
(defmethod allow-strech-p ((self sequence*) (factor number)) factor)
|
9732061c9bf955ad91653130a32aeefab2e40cdc7240cff79b378be2cf1d59d1 | haskell-github/github | ListStarred.hs | module ListStarred where
import qualified Github.Repos.Starring as Github
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
main = do
possibleRepos <- Github.reposStarredBy Nothing "mike-burns"
putStrLn $ either (("Error: "++) . show)
(intercalate "\n\n" . map formatRepo)
possibleRepos
formatRepo repo =
(Github.repoName repo) ++ "\t" ++
(fromMaybe "" $ Github.repoDescription repo) ++ "\n" ++
(Github.repoHtmlUrl repo) ++ "\n" ++
(fromMaybe "" $ Github.repoCloneUrl repo) ++ "\t" ++
(formatDate $ Github.repoUpdatedAt repo) ++ "\n" ++
formatLanguage (Github.repoLanguage repo)
formatDate (Just date) = show . Github.fromDate $ date
formatDate Nothing = ""
formatLanguage (Just language) = "language: " ++ language ++ "\t"
formatLanguage Nothing = ""
| null | https://raw.githubusercontent.com/haskell-github/github/81d9b658c33a706f18418211a78d2690752518a4/samples/Repos/Starring/ListStarred.hs | haskell | module ListStarred where
import qualified Github.Repos.Starring as Github
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
main = do
possibleRepos <- Github.reposStarredBy Nothing "mike-burns"
putStrLn $ either (("Error: "++) . show)
(intercalate "\n\n" . map formatRepo)
possibleRepos
formatRepo repo =
(Github.repoName repo) ++ "\t" ++
(fromMaybe "" $ Github.repoDescription repo) ++ "\n" ++
(Github.repoHtmlUrl repo) ++ "\n" ++
(fromMaybe "" $ Github.repoCloneUrl repo) ++ "\t" ++
(formatDate $ Github.repoUpdatedAt repo) ++ "\n" ++
formatLanguage (Github.repoLanguage repo)
formatDate (Just date) = show . Github.fromDate $ date
formatDate Nothing = ""
formatLanguage (Just language) = "language: " ++ language ++ "\t"
formatLanguage Nothing = ""
|
|
3744161faf9ec6121d8aa4e9b51bf332a333fc19bac78cbfe05c8e95fb291542 | lispnik/iup | temperature.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload "iup"))
(defpackage #:iup-examples.temperature
(:use #:common-lisp)
(:export #:temperature))
(in-package #:iup-examples.temperature)
(defun temperature ()
(iup:with-iup ()
(let* ((celsius-label (iup:label :title "Celsius = "))
(farenheit-label (iup:label :title "Farenheit"))
(celsius (iup:text :value "" :size 50 :mask iup:+mask-float+))
(farenheit (iup:text :value "" :size 50 :mask iup:+mask-float+))
(hbox (iup:hbox
(list celsius celsius-label farenheit farenheit-label)
:alignment "ACENTER"
:gap 10
:margin "10x10"))
(dialog (iup:dialog hbox :title "Temperature Converter")))
(setf (iup:callback celsius :valuechanged_cb)
#'(lambda (self)
(let ((celsius (ignore-errors (iup:attribute self :value 'number))))
(when celsius
(setf (iup:attribute farenheit :value)
(format nil "~2$" (+ (* celsius 9/5) 32)))))
iup::+default+)
(iup:callback farenheit :valuechanged_cb)
#'(lambda (self)
(let ((farenheit (ignore-errors (iup:attribute self :value 'number))))
(when farenheit
(setf (iup:attribute celsius :value)
(format nil "~2$" (* (- farenheit 32 ) 5/9)))))
iup::+default+))
(iup:show dialog)
(iup:main-loop))))
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(temperature))
#-sbcl
(temperature)
| null | https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/examples/7guis/temperature.lisp | lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload "iup"))
(defpackage #:iup-examples.temperature
(:use #:common-lisp)
(:export #:temperature))
(in-package #:iup-examples.temperature)
(defun temperature ()
(iup:with-iup ()
(let* ((celsius-label (iup:label :title "Celsius = "))
(farenheit-label (iup:label :title "Farenheit"))
(celsius (iup:text :value "" :size 50 :mask iup:+mask-float+))
(farenheit (iup:text :value "" :size 50 :mask iup:+mask-float+))
(hbox (iup:hbox
(list celsius celsius-label farenheit farenheit-label)
:alignment "ACENTER"
:gap 10
:margin "10x10"))
(dialog (iup:dialog hbox :title "Temperature Converter")))
(setf (iup:callback celsius :valuechanged_cb)
#'(lambda (self)
(let ((celsius (ignore-errors (iup:attribute self :value 'number))))
(when celsius
(setf (iup:attribute farenheit :value)
(format nil "~2$" (+ (* celsius 9/5) 32)))))
iup::+default+)
(iup:callback farenheit :valuechanged_cb)
#'(lambda (self)
(let ((farenheit (ignore-errors (iup:attribute self :value 'number))))
(when farenheit
(setf (iup:attribute celsius :value)
(format nil "~2$" (* (- farenheit 32 ) 5/9)))))
iup::+default+))
(iup:show dialog)
(iup:main-loop))))
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(temperature))
#-sbcl
(temperature)
|
|
a65099b968547ce15d20db4415def2b940e8088135f3e6ab52c14e662c264bd6 | OCamlPro/typerex-lint | sUMisc.ml | let pair a b = a,b
| null | https://raw.githubusercontent.com/OCamlPro/typerex-lint/6d9e994c8278fb65e1f7de91d74876531691120c/libs/ocplib-sempatch/lib/std_utils/sUMisc.ml | ocaml | let pair a b = a,b
|
|
765ec95dc170dde894e7a32d30f1042582948d593734480ee668b37bac586476 | manavpatnaik/haskell | 8_concat_lists_recursive.hs | concatList :: [Int] -> [Int] -> [Int]
concatList [] lst = lst
concatList (x : xs) lst = x : (concatList xs lst)
main = do
print(concatList [1,2] [3,4])
print(concatList [1,2,3] [4,5,6]) | null | https://raw.githubusercontent.com/manavpatnaik/haskell/af45c3eb5c3461aa77cf25610dfcb3b41c7f7ef9/basic-programs/8_concat_lists_recursive.hs | haskell | concatList :: [Int] -> [Int] -> [Int]
concatList [] lst = lst
concatList (x : xs) lst = x : (concatList xs lst)
main = do
print(concatList [1,2] [3,4])
print(concatList [1,2,3] [4,5,6]) |
|
d359f339febc04820a0b18e7287d24d2547209bf48cdec2e3c17174f066bf691 | nikodemus/SBCL | gate.lisp |
;;;;
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package :sb-concurrency)
FIXME : On Linux a direct futex - based implementation would be more
;;;; efficient.
(defstruct (gate (:constructor %make-gate)
(:copier nil)
(:predicate gatep))
"GATE type. Gates are syncronization constructs suitable for making
multiple threads wait for single event before proceeding.
Use WAIT-ON-GATE to wait for a gate to open, OPEN-GATE to open one,
and CLOSE-GATE to close an open gate. GATE-OPEN-P can be used to test
the state of a gate without blocking."
(mutex (missing-arg) :type mutex)
(queue (missing-arg) :type waitqueue)
(state :closed :type (member :open :closed))
(name nil :type (or null simple-string)))
(setf (documentation 'gatep 'function)
"Returns true if the argument is a GATE."
(documentation 'gate-name 'function)
"Name of a GATE. SETFable.")
(defmethod print-object ((gate gate) stream)
(print-unreadable-object (gate stream :type t :identity t)
(format stream "~@[~S ~]~((~A)~)"
(gate-name gate)
(gate-state gate))))
(defun make-gate (&key name open)
"Makes a new gate. Gate will be initially open if OPEN is true, and closed if OPEN
is NIL (the default.) NAME, if provided, is the name of the gate, used when printing
the gate."
(flet ((generate-name (thing)
(when name
(format nil "gate ~S's ~A" name thing))))
(%make-gate
:name name
:mutex (make-mutex :name (generate-name "lock"))
:queue (make-waitqueue :name (generate-name "condition variable"))
:state (if open :open :closed))))
(defun open-gate (gate)
"Opens GATE. Returns T if the gate was previously closed, and NIL
if the gate was already open."
(declare (gate gate))
(let (closed)
(with-mutex ((gate-mutex gate))
(sb-sys:without-interrupts
(setf closed (eq :closed (gate-state gate))
(gate-state gate) :open)
(condition-broadcast (gate-queue gate))))
closed))
(defun close-gate (gate)
"Closes GATE. Returns T if the gate was previously open, and NIL
if the gate was already closed."
(declare (gate gate))
(let (open)
(with-mutex ((gate-mutex gate))
(setf open (eq :open (gate-state gate))
(gate-state gate) :closed))
open))
(defun wait-on-gate (gate &key timeout)
"Waits for GATE to open, or TIMEOUT seconds to pass. Returns T
if the gate was opened in time, and NIL otherwise."
(declare (gate gate))
(with-mutex ((gate-mutex gate))
(loop until (eq :open (gate-state gate))
do (or (condition-wait (gate-queue gate) (gate-mutex gate)
:timeout timeout)
(return-from wait-on-gate nil))))
t)
(defun gate-open-p (gate)
"Returns true if GATE is open."
(declare (gate gate))
(eq :open (gate-state gate)))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/contrib/sb-concurrency/gate.lisp | lisp |
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
efficient. |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package :sb-concurrency)
FIXME : On Linux a direct futex - based implementation would be more
(defstruct (gate (:constructor %make-gate)
(:copier nil)
(:predicate gatep))
"GATE type. Gates are syncronization constructs suitable for making
multiple threads wait for single event before proceeding.
Use WAIT-ON-GATE to wait for a gate to open, OPEN-GATE to open one,
and CLOSE-GATE to close an open gate. GATE-OPEN-P can be used to test
the state of a gate without blocking."
(mutex (missing-arg) :type mutex)
(queue (missing-arg) :type waitqueue)
(state :closed :type (member :open :closed))
(name nil :type (or null simple-string)))
(setf (documentation 'gatep 'function)
"Returns true if the argument is a GATE."
(documentation 'gate-name 'function)
"Name of a GATE. SETFable.")
(defmethod print-object ((gate gate) stream)
(print-unreadable-object (gate stream :type t :identity t)
(format stream "~@[~S ~]~((~A)~)"
(gate-name gate)
(gate-state gate))))
(defun make-gate (&key name open)
"Makes a new gate. Gate will be initially open if OPEN is true, and closed if OPEN
is NIL (the default.) NAME, if provided, is the name of the gate, used when printing
the gate."
(flet ((generate-name (thing)
(when name
(format nil "gate ~S's ~A" name thing))))
(%make-gate
:name name
:mutex (make-mutex :name (generate-name "lock"))
:queue (make-waitqueue :name (generate-name "condition variable"))
:state (if open :open :closed))))
(defun open-gate (gate)
"Opens GATE. Returns T if the gate was previously closed, and NIL
if the gate was already open."
(declare (gate gate))
(let (closed)
(with-mutex ((gate-mutex gate))
(sb-sys:without-interrupts
(setf closed (eq :closed (gate-state gate))
(gate-state gate) :open)
(condition-broadcast (gate-queue gate))))
closed))
(defun close-gate (gate)
"Closes GATE. Returns T if the gate was previously open, and NIL
if the gate was already closed."
(declare (gate gate))
(let (open)
(with-mutex ((gate-mutex gate))
(setf open (eq :open (gate-state gate))
(gate-state gate) :closed))
open))
(defun wait-on-gate (gate &key timeout)
"Waits for GATE to open, or TIMEOUT seconds to pass. Returns T
if the gate was opened in time, and NIL otherwise."
(declare (gate gate))
(with-mutex ((gate-mutex gate))
(loop until (eq :open (gate-state gate))
do (or (condition-wait (gate-queue gate) (gate-mutex gate)
:timeout timeout)
(return-from wait-on-gate nil))))
t)
(defun gate-open-p (gate)
"Returns true if GATE is open."
(declare (gate gate))
(eq :open (gate-state gate)))
|
6a228e056d2d491f2362f4a30343c82186d8f2fd527b64893f3bf9e606fb58cf | magnars/prone | code_excerpt.cljs | (ns prone.ui.components.code-excerpt
(:require [quiescent.core :as q :include-macros true]
[quiescent.dom :as d]))
(def source-classes {:clj "language-clojure"
:java "language-java"})
(q/defcomponent CodeExcerpt [source-loc]
(d/header {:className "trace_info clearfix"}
(d/div {:className "title"}
(d/h2 {:className "name"} (:method-name source-loc))
(d/div {:className "location"}
(d/span {:className "filename"}
(:class-path-url source-loc))))
(if-let [source-code (-> source-loc :source :code)]
(d/div {:className "code_block clearfix"}
(d/pre {:className "line-numbers code"
:data-line (:line-number source-loc)
:data-start (inc (-> source-loc :source :offset))
:data-line-offset (-> source-loc :source :offset)}
(d/code {:className (source-classes (:lang source-loc))} source-code)))
(d/div {:className "source-failure"}
(-> source-loc :source :failure)))))
| null | https://raw.githubusercontent.com/magnars/prone/50ed099bb95ad3dfa6d70d506f62faf0fdccebf8/src/prone/ui/components/code_excerpt.cljs | clojure | (ns prone.ui.components.code-excerpt
(:require [quiescent.core :as q :include-macros true]
[quiescent.dom :as d]))
(def source-classes {:clj "language-clojure"
:java "language-java"})
(q/defcomponent CodeExcerpt [source-loc]
(d/header {:className "trace_info clearfix"}
(d/div {:className "title"}
(d/h2 {:className "name"} (:method-name source-loc))
(d/div {:className "location"}
(d/span {:className "filename"}
(:class-path-url source-loc))))
(if-let [source-code (-> source-loc :source :code)]
(d/div {:className "code_block clearfix"}
(d/pre {:className "line-numbers code"
:data-line (:line-number source-loc)
:data-start (inc (-> source-loc :source :offset))
:data-line-offset (-> source-loc :source :offset)}
(d/code {:className (source-classes (:lang source-loc))} source-code)))
(d/div {:className "source-failure"}
(-> source-loc :source :failure)))))
|
|
b4a805261bc73be405b5740b9c48bde6c9f4fa42e3c8015455ae223c325ae012 | AdaCore/why3 | gnat_ast_to_ptree.ml | open Why3
open Ptree
open Gnat_ast
open Ptree_constructors
let debug = Debug.register_info_flag "gnat_ast" ~desc:"Output@ mlw@ file"
let () = Debug.set_flag debug
[@@@warning "-42"]
exception Conversion_error of {node_id: int; message: string}
let conversion_error node_id message () = raise (Conversion_error {node_id; message})
(** {1 Auxiliaries for conversion} *)
module Opt = struct
let map f = function
| None -> None
| Some x -> Some (f x)
let get default = function
| Some x -> x
| None -> default
let force err = function
| Some x -> x
| None -> err ()
let to_list = function
| None -> []
| Some x -> [x]
end
module List = struct
include List
let rec map_and_last for_not_last for_last l =
match l with
| [] -> []
| [x] -> [for_last x]
| x :: xs -> for_not_last x :: map_and_last for_not_last for_last xs
let rec map_last for_last l =
match l with
| [] -> []
| [x] -> [for_last x]
| x :: xs -> x :: map_last for_last xs
let rec get_last err = function
| [x] -> x
| _ :: xs -> get_last err xs
| [] -> err ()
let filter_map f l =
map (Opt.force (fun () -> assert false))
(filter ((<>) None)
(map f l))
end
* { 1 Conversion functions from Gnat / JSON to Ptree }
let bigint_of_uint (Uint str) =
BigInt.of_string str
let ident_add_suffix suffix id =
{id with id_str=id.id_str^suffix}
let mk_label = function
| No_symbol -> None
| Symbol s -> Some (ATstr (Ident.create_attribute s))
let mk_location = function
| Source_ptr r ->
let loc = Loc.user_position r.filename r.line 0 r.line 0 in
Some (mk_pos loc)
| No_location -> None
let mk_idents ~notation attrs =
let f = Opt.get (fun s -> s) notation in
List.map_and_last
(mk_ident [])
(fun s -> mk_ident attrs (f s))
let string_of_symbol = function
| Symbol s -> Some s
| No_symbol -> None
let strings_of_name (node : name_id) =
let Name r = node.desc in
let module_string =
match r.module_ with
| Some {desc=Module r} ->
string_of_symbol r.name
| _ -> None in
let namespace_string = string_of_symbol r.namespace in
let symb_string = string_of_symbol r.symb in
Opt.(to_list module_string @ to_list namespace_string @ to_list symb_string)
let name_of_identifier (node: identifier_id) =
let Identifier r = node.desc in
r.name
let force_one err = function
| [x] -> x
| _ -> err ()
let mk_module_qident (node: module_id) =
let Module m = node.desc in
let file = mk_idents ~notation:None [] (Opt.to_list (string_of_symbol m.file)) in
let name = mk_idents ~notation:None [] (Opt.to_list (string_of_symbol m.name)) in
mk_qualid (file @ name)
let mk_idents_of_name ~notation attrs (node: name_id) =
mk_idents ~notation attrs (strings_of_name node)
let mk_idents_of_identifier ~notation attrs (node: identifier_id) =
mk_idents ~notation attrs (strings_of_name (name_of_identifier node))
let mk_ident_of_symbol id ~notation attrs sym =
let notation = Opt.get (fun s -> s) notation in
mk_ident attrs (notation (Opt.force (conversion_error id "empty symbol") (string_of_symbol sym)))
let mk_idents_of_type (node: type_id) =
let Type r = node.desc in
let idents = mk_idents_of_name ~notation:None [] r.name in
if r.is_mutable then
List.map_last (ident_add_suffix "__ref") idents
else
idents
let mk_pattern_of_ident id =
let w_id = List.get_last
(conversion_error id.info.id "empty pattern")
(mk_idents_of_identifier ~notation:None [] id) in
mk_pat (Pvar w_id)
module Include_Decl = struct
(* The purpose of this model is to allow suppression of duplicate imports in
Why3 theories. This requires a canonical representation of typical
imports, and a compare function for this type, so that we can use OCaml
sets to remove duplicates.
*)
type t = Use_export of qualid | Use_import of qualid * ident option
let ident_compare a b = Stdlib.compare a.id_str b.id_str
let ident_opt_compare a b =
match a, b with
| None, Some _ -> -1
| Some _, None -> 1
| Some ia, Some ib -> ident_compare ia ib
| None, None -> 0
let rec qualid_compare a b =
match a, b with
| Qident _ , Qdot _ -> -1
| Qdot _ , Qident _ -> 1
| Qident ia, Qident ib -> ident_compare ia ib
| Qdot (qa, ia), Qdot (qb, ib) ->
let c = qualid_compare qa qb in
if c <> 0 then c else ident_compare ia ib
let compare a b =
match a, b with
| Use_export _ , Use_import _ -> -1
| Use_import _ , Use_export _ -> 1
| Use_export qa, Use_export qb -> qualid_compare qa qb
| Use_import (qa, ioa), Use_import (qb, iob) ->
let c = qualid_compare qa qb in
if c <> 0 then c else ident_opt_compare ioa iob
let mk_include_declaration d =
match d with
| Use_export qid -> D.mk_useexport qid
| Use_import (qid, oi) -> D.mk_useimport false [qid, oi]
let mk_include_variant (node : include_declaration_id) =
let Include_declaration r = node.desc in
let qid = mk_module_qident r.module_ in
match r.use_kind with
| Import -> Use_import (qid, None)
| Export -> Use_export qid
| Clone_default ->
let Module m = r.module_.desc in
Use_import (qid, Some (mk_ident_of_symbol node.info.id ~notation:None [] m.name))
end
module Include_type_set = Set.Make (Include_Decl)
let mk_pty_of_type (node : type_id) =
Ty.mk_idapp (mk_qualid (mk_idents_of_type node)) []
let term_connector = function
| Or_else -> `Or_asym
| And_then -> `And_asym
| Imply -> `Implies
| Equivalent -> `Iff
| Or -> `Or
| And -> `And
let expr_connector id = function
| And_then -> `And_asym
| Or_else -> `Or_asym
| _ -> conversion_error id "unexpected expression operator" ()
let unroll_name (node : name_id) =
let Name {module_; symb} = node.desc in
let aux (node: module_id) =
let Module r = node.desc in
string_of_symbol r.file, string_of_symbol r.name in
Opt.map aux module_, string_of_symbol symb
let is_infix_identifier (node : identifier_id) =
let Identifier r = node.desc in
let Name r = r.name.desc in
r.infix
(** Test if node is an unquantified OP1 *)
let is_op1 (node: identifier_id) =
match List.rev (strings_of_name (name_of_identifier node)) with
| s :: _ ->
(* see why3/src/parser/parser.mly, lexer.mll *)
List.exists (String.contains s)
['='; '<'; '>']
| _ -> conversion_error node.info.id "empty operator identifier" ()
* Test if node is an potentially quantified OP234
let is_op234 (node: identifier_id) =
match List.rev (strings_of_name (name_of_identifier node)) with
| s :: _ ->
(* see why3/src/parser/parser.mly, lexer.mll *)
List.exists (String.contains s)
['+'; '-'; '*'; '/'; '\\'; '%'; '!'; '$'; '&'; '?'; '@'; '^'; '|']
| _ -> conversion_error node.info.id "empty operator identifier" ()
let mk_comment_attr = function
| No_symbol -> None
| Symbol s -> Some (mk_str ("GNAT-comment:"^s))
module Curr = struct
let loc_ref = ref No_location
let marker_ref = ref No_symbol
let with_ curr f =
let push (loc, marker) =
loc_ref := loc;
marker_ref := marker in
let pop () =
let loc, marker = No_location, No_symbol in
loc_ref := loc;
marker_ref := marker in
push curr;
let res = f () in
pop ();
res
let mk_attrs () =
match !loc_ref with
| No_location ->
[]
| Source_ptr r ->
let filename =
match !marker_ref with
| No_symbol -> r.filename
| Symbol s -> "'@"^s^"@'"^r.filename in
Opt.(to_list (mk_location (Source_ptr {r with filename})))
end
let is_true t = match t.term_desc with
| Ttrue -> true
| _ -> false
let no_vcs_in_spec spec =
spec.sp_post = [] && spec.sp_xpost = [] && spec.sp_variant = []
* Check ( syntactically ) if an expression has no side - effects ( assignments , and ,
potentially , applications ) , and does not trigger any VCs , i.e. it does not contain any
application ( idapp , apply , infix , or innfix , any , which may generate preconditions ) ,
declaration ( fun , rec , which may generate postconditions ) , or logical statement
( absurd , assert , check ) .
potentially, applications), and does not trigger any VCs, i.e. it does not contain any
application (idapp, apply, infix, or innfix, any, which may generate preconditions),
declaration (fun, rec, which may generate postconditions), or logical statement
(absurd, assert, check). *)
let rec no_vcs_no_side_effects e = match e.expr_desc with
| Eref | Etrue | Efalse | Econst _ | Eident _ | Easref _ ->
true
| Eidapp _ | Eapply _ | Einfix _ | Einnfix _ ->
false (* VCs from preconditions of the callee, possible side-effects *)
| Elet (_, _, _, e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Erec (funs, e) ->
let aux (_, _, _, _, _, _, _, spec, e) =
no_vcs_in_spec spec && no_vcs_no_side_effects e in
List.for_all aux funs && no_vcs_no_side_effects e
| Efun (_, _, _, _, spec, e) ->
no_vcs_in_spec spec && no_vcs_no_side_effects e
| Eany (_, _, _, _, _, spec) ->
spec.sp_pre = [] (* existence *)
| Etuple es ->
List.for_all no_vcs_no_side_effects es
| Erecord fs ->
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) fs
| Eupdate (e, fs) ->
no_vcs_no_side_effects e &&
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) fs
| Eassign _ ->
false
| Esequence (e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Eif (e1, e2, e3) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2 && no_vcs_no_side_effects e3
| Ewhile (e1, inv, var, e2) ->
inv = [] && var = [] &&
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Eand (e1, e2) | Eor (e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Enot e ->
no_vcs_no_side_effects e
| Ematch (e, regs, exns) ->
no_vcs_no_side_effects e &&
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) regs &&
List.for_all (fun (_, _, e) -> no_vcs_no_side_effects e) exns
| Eabsurd ->
false
| Epure _ | Eidpur _ | Eraise (_, None) ->
true
| Eraise (_, Some e) | Eexn (_, _, _, e) | Eoptexn (_, _, e) ->
no_vcs_no_side_effects e
| Efor (_, e1, _, e2, inv, e3) ->
inv = [] && no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2 && no_vcs_no_side_effects e3
| Eassert (Expr.(Assert|Check), _) -> false
| Eassert (Expr.Assume, _) -> true
| Escope (_, e) | Elabel (_, e) | Ecast (e, _) | Eghost e | Eattr (_, e) ->
no_vcs_no_side_effects e
The conversion from Gnat_ast to is parameterized in [ ' a]/[t ] by the targeted type
( [ Ptree.expr ] or [ Ptree.term ] ) and the corresponding smart constructors from
[ PtreeConstructors ] . Nodes that are converted to different syntaxes in expressions and
terms ar differentiated using [ E_or_T.expr_or_term ] . Nodes that can not be converted to
the target type raise an exception [ Failure ] ( but that should only happen when there is
a problem in the generated [ Gnat_ast ] ) .
([Ptree.expr] or [Ptree.term]) and the corresponding smart constructors from
[PtreeConstructors]. Nodes that are converted to different syntaxes in expressions and
terms ar differentiated using [E_or_T.expr_or_term]. Nodes that cannot be converted to
the target type raise an exception [Failure] (but that should only happen when there is
a problem in the generated [Gnat_ast]). *)
let next_call_id =
let counter = ref 0 in
fun () -> incr counter; !counter
let mk_call_id_str () =
mk_str (Format.sprintf "rac:call_id:%d" (next_call_id ()))
let process_call : 'a . (module E_or_T with type t = 'a) -> 'b why_node_id -> identifier_id -> 'a list -> 'a =
fun (type t) (module E_or_T : E_or_T with type t = t) (node : 'b why_node_id) id args : t ->
Convert unquantified op1 operations (= , < , etc . ) to innfix , binary only
let open E_or_T in
if is_infix_identifier id && is_op1 id then begin
let op =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_infix) [] id) in
match args with
| [arg0;arg1] -> mk_innfix arg0 op arg1
| _ -> conversion_error node.info.id "op1 operations must be binary" ()
end
(* Convert unqualified op234 prefix operations (/, *, !, etc.) *)
else if is_infix_identifier id && is_op234 id then begin
match args with
| [_] ->
let qid =
let ident =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_prefix) [] id) in
mk_qualid [ident] in
mk_attr (mk_call_id_str ())
(mk_idapp qid args)
| [_;_] ->
let qid =
let ident =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_infix) [] id) in
mk_qualid [ident] in
mk_attr (mk_call_id_str ())
(mk_idapp qid args)
| _ ->
conversion_error node.info.id "operations with op234 operators must be unary or binary" ()
end else (begin
if is_infix_identifier id then
Format.ksprintf (conversion_error node.info.id) "infix identifier %s must be op1 or op234"
(String.concat "." (strings_of_name (name_of_identifier id))) ();
let notation =
if is_op1 id || is_op234 id then
match List.length args with
| 1 -> Some Ident.op_prefix
| 2 -> Some Ident.op_infix
| _ -> conversion_error node.info.id "operations with op234 operators must be unary or binary" ()
else None in
let f = mk_var (mk_qualid (mk_idents_of_identifier ~notation [] id)) in
mk_attr (mk_call_id_str ())
(List.fold_left (mk_apply ?loc:None) f args)
end)
let rec mk_of_expr : 'a . (module E_or_T with type t = 'a) -> expr_id -> 'a =
Signature type ^^^^^ variable [ ' a ] required to make [ mk_of_expr ] strongly polymorphic
fun (type t) (module E_or_T : E_or_T with type t = t) (node: expr_id) : t ->
let open E_or_T in
let mk_of_expr (node : expr_id) = (* Shortcut for direct recursive call *)
mk_of_expr (module E_or_T: E_or_T with type t = t) node in
let expr_only cat expr = (* Shortcut for nodes that can only translated to a expression *)
expr_or_term ~info:(Format.sprintf "(%s with ID %d)" cat node.info.id) ~expr:(fun () -> expr) () in
let term_only cat term = (* Shortcut for nodes that can only translated to a expression *)
expr_or_term ~info:(Format.sprintf "(%s with ID %d)" cat node.info.id) ~term:(fun () -> term) () in
let mk_field_association (node: field_association_id) =
let Field_association r = node.desc in
mk_qualid (mk_idents_of_name ~notation:None [] (name_of_identifier r.field)),
mk_of_expr r.value in
let mk_binder_of_identifier attrs pty node =
let id =
let err = conversion_error node.info.id "qualified or empty identifier" in
force_one err (mk_idents_of_identifier ~notation:None attrs node) in
get_pos (), Some id, false, Some pty in
let mk_identifier_labels (node : identifier_id) =
let Identifier r = node.desc in
List.filter_map mk_label r.labels in
let mk_seqs l =
let not_unit = function
| {expr_desc = Etuple []} -> false
| _ -> true in
let statements = List.filter not_unit l in
let firsts, last =
match List.rev statements with
| [] -> [], E.mk_tuple []
| last :: firsts -> List.rev firsts, last in
List.fold_right (E.mk_seq ?loc:None) firsts last in
let mk_comment s e =
match mk_comment_attr s with
| None -> e
| Some a -> E.mk_attr a e in
let mk_const_of_ureal id (Ureal r) =
(* gnat/ureal.ads *)
if r.base = 0 then
let Uint numerator = r.numerator in
let mk_const r = mk_const (Constant.ConstReal r) in
if BigInt.(eq one (bigint_of_uint r.denominator)) then
mk_const
(Number.real_literal ~radix:10 ~neg:r.negative ~int:numerator ~frac:"0" ~exp:None)
else
conversion_error id "ureal with base = 0 and denominator /= 1" ()
( \ * Which operator /. for reals ? * \ )
* let Uint denominator = r.denominator in
* mk_idapp
* ( mk_qualid [ mk_ident [ ] ( Ident.op_infix " /. " ) ] )
* ( List.map mk_const
* [ Number.real_literal ~radix:10 ~neg : r.negative ~int : numerator ~frac:"0 " ~exp : None ;
* Number.real_literal ~radix:10 ~neg : false ~int : denominator ~frac:"0 " ~exp : None ] )
* let Uint denominator = r.denominator in
* mk_idapp
* (mk_qualid [mk_ident [] (Ident.op_infix "/.")])
* (List.map mk_const
* [Number.real_literal ~radix:10 ~neg:r.negative ~int:numerator ~frac:"0" ~exp:None;
* Number.real_literal ~radix:10 ~neg:false ~int:denominator ~frac:"0" ~exp:None]) *)
else
let int =
let int = bigint_of_uint r.numerator in
if r.negative then BigInt.minus int else int in
let exp = BigInt.(minus (bigint_of_uint r.denominator)) in
match r.base with
| 2 ->
mk_const (Constant.real_const ~pow2:exp ~pow5:BigInt.zero int)
| 10 ->
mk_const (Constant.real_const ~pow2:exp ~pow5:exp int)
| 16 ->
let pow2 = BigInt.mul_int 4 exp in
mk_const (Constant.real_const ~pow2 ~pow5:BigInt.zero int)
| _ ->
conversion_error id ("unsupported base "^string_of_int r.base^" for ureal") () in
let curr_attrs = Curr.mk_attrs () in
let res = match node.desc with
Preds ,
| Universal_quantif r ->
term_only "universal quantif"
(let for_trigger (node : trigger_id) =
let Trigger r = node.desc in
List.map mk_term_of_expr (list_of_nonempty r.terms) in
let for_triggers (node : triggers_id) =
let Triggers r = node.desc in
List.map for_trigger (list_of_nonempty r.triggers) in
let curr_attrs = Curr.mk_attrs () in
let binders =
List.map (mk_binder_of_identifier (curr_attrs @ List.filter_map mk_label r.labels) (mk_pty_of_type r.var_type))
(list_of_nonempty r.variables) in
let triggers = Opt.(get [] (map for_triggers r.triggers)) in
let body = mk_term_of_pred r.pred in
T.mk_quant Dterm.DTforall binders triggers body)
| Existential_quantif r ->
term_only "existential quantif"
(let binders =
List.map
(mk_binder_of_identifier (List.filter_map mk_label r.labels)
(mk_pty_of_type r.var_type))
(list_of_nonempty r.variables) in
let body = mk_term_of_pred r.pred in
T.mk_quant Dterm.DTexists binders [] body)
Preds , Progs ,
| Not r ->
mk_not (mk_of_expr r.right)
| Connection r ->
let module M = struct
type 'a tree = Node of 'a | Binop of 'a tree * 'a tree
let rec map node binop = function
| Node x -> node x
| Binop (t1, t2) ->
let x1 = map node binop t1 in
let x2 = map node binop t2 in
binop x1 x2
let mk_tree = function
| [] -> None
| exprs ->
let a = Array.of_list exprs in
let rec aux from to_ =
assert (to_ - from > 0);
if to_ - from = 1 then
Node a.(from)
else
let mid = (from + to_ + 1) / 2 in
Binop (aux from mid, aux mid to_) in
Some (aux 0 (Array.length a))
end in
expr_or_term
~expr:(fun () ->
let op = expr_connector node.info.id r.op in
let e1 =
let left = mk_expr_of_expr r.left in
let right = mk_expr_of_expr r.right in
E.mk_binop left op right in
Opt.(get e1
(map (E.mk_binop e1 op)
(map (M.map mk_expr_of_expr (fun e -> E.mk_binop e op))
(M.mk_tree r.more_right)))))
~term:(fun () ->
let op = term_connector r.op in
let t1 =
let left = mk_term_of_expr r.left in
let right = mk_term_of_expr r.right in
T.mk_binnop left op right in
Opt.(get t1
(map (T.mk_binnop t1 op)
(map (M.map mk_term_of_expr (fun t -> T.mk_binnop t op))
(M.mk_tree r.more_right))))) ()
| Label r ->
let labels = List.filter_map mk_label r.labels in
let body = mk_of_expr r.def in
mk_attrs labels body
| Loc_label r ->
Curr.with_ (r.sloc, r.marker)
(fun () ->
let curr_attrs = Curr.mk_attrs () in
let body = mk_of_expr r.def in
mk_attrs curr_attrs body)
Preds , Terms , Progs ,
FIXGNAT sometimes the symbol contains a function application , e.g. " uint_in_range x " [ sic ! ]
| Identifier ({name={desc=Name ({symb=Symbol s} as name_r)} as name} as ident_r)
when String.index_opt s ' ' <> None -> begin
match String.split_on_char ' ' s with
| s' :: args ->
let node' = {
node with desc = Identifier {
ident_r with name = {name with desc=Name {
name_r with symb = Symbol s'}}}} in
let f = mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] node')) in
let args = List.(map (mk_var ?loc:None) (map mk_qualid (map (fun s -> [mk_ident [] s]) args))) in
List.fold_left (mk_apply ?loc:None) f args
| _ -> assert false
end
| Identifier {name={desc=Name {symb=Symbol "absurd"}}} ->
expr_only "identifier"
E.(mk_absurd ())
| Identifier {name={desc=Name {symb=Symbol "()"}}} ->
mk_tuple []
| Identifier r ->
mk_var (mk_qualid (mk_idents_of_name ~notation:None [] r.name))
| Tagged ({tag=No_symbol} as r) ->
term_only "tagged"
(mk_term_of_expr r.def)
| Tagged ({tag=Symbol s} as r) ->
term_only "tagged"
(let body = mk_term_of_expr r.def in
let id =
let s = if s = "old" then "'Old" else s in
mk_ident [] s in
T.mk_at body id)
| Call r ->
let args = List.map mk_of_expr r.args in
process_call (module E_or_T: E_or_T with type t = t) node r.name args
| Literal r ->
if node.info.domain = Pred then
mk_truth (match r.value with True -> true | False -> false)
else
mk_var (mk_qualid [mk_ident [] (match r.value with True -> "True" | False -> "False")])
| Binding r ->
let id =
force_one (conversion_error r.name.info.id "qualified or empty identifier")
(mk_idents_of_identifier ~notation:None
(mk_identifier_labels r.name) r.name) in
expr_or_term
~expr:(fun () ->
let def = mk_expr_of_expr r.def in
let body = mk_expr_of_expr r.context in
if id.id_str = "_" && no_vcs_no_side_effects def
then body
else E.mk_let id def body)
~term:(fun () ->
let def = mk_term_of_expr r.def in
let body = mk_term_of_expr r.context in
T.mk_let id def body) ()
| Elsif _ ->
conversion_error node.info.id "unexpected elsif" ()
| Epsilon r ->
term_only "epsilon"
(let id =
force_one (conversion_error r.name.info.id "qualified or empty idenfitier")
(mk_idents_of_identifier ~notation:None [] r.name) in
let pty = mk_pty_of_type r.typ in
let body = mk_term_of_pred r.pred in
T.mk_eps id pty body)
| Conditional r ->
let rec mk_elsifs = function
| [] ->
let open Opt in
get (expr_or_term
~expr:(fun () -> E.mk_tuple [])
~term:(fun () -> T.mk_truth true) ())
(map mk_of_expr r.else_part)
| {desc=Elsif r'} :: elsifs ->
let condition' = mk_of_expr r'.condition in
let then_part' = mk_of_expr r'.then_part in
let elsif_parts' = mk_elsifs elsifs in
mk_if condition' then_part' elsif_parts'
| _ ->
conversion_error node.info.id "unexpected elsif" ()
in
let condition = mk_of_expr r.condition in
let then_part = mk_of_expr r.then_part in
let elsif_parts = mk_elsifs r.elsif_parts in
mk_if condition then_part elsif_parts
Terms , Progs , Exprs
| Integer_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = Ty.mk_atomic_type ["int"] in
mk_cast const pty
| Range_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = mk_pty_of_type r.typ in
mk_cast const pty
| Modular_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty =
let Type r = r.typ.desc in
match unroll_name r.name with
| Some (Some "_gnatprove_standard", Some (("BV8"|"BV16"|"BV32"|"BV64"|"BV128" as s))), Some "t" ->
Ty.mk_atomic_type [s; "t"]
| _ ->
conversion_error node.info.id "unknown module constant" () in
mk_cast const pty
| Fixed_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = Ty.mk_atomic_type ["int"] in
mk_cast const pty
| Real_constant r ->
mk_const_of_ureal node.info.id r.value
| Float_constant r ->
let prefix =
let Type r = r.typ.desc in
match unroll_name r.name with
| Some (Some "_gnatprove_standard", Some ("Float32"|"Float64"|"Float80" as s)), Some "t" ->
mk_ident [] s
| _ ->
conversion_error node.info.id "float_constant must be Float32.t, Float64.t or Float80.t" ()
in
let const =
let Ureal r' = r.value in
if r'.negative then
(* negate the casted negation [neg (-r : t)]] *)
mk_apply (mk_var (mk_qualid [prefix; mk_ident [] "neg"]))
(mk_cast
(mk_const_of_ureal node.info.id (Ureal {r' with negative=false}))
(Ty.mk_idapp (mk_qualid [prefix; mk_ident [] "t"]) []))
else
mk_const_of_ureal node.info.id r.value in
let pty = Ty.mk_idapp (mk_qualid [prefix; mk_ident [] "t"]) [] in
mk_cast const pty
| Comment r ->
(* Using [()] won't play well in terms *)
expr_only "comment"
(let body = E.mk_tuple [] in
mk_comment r.comment body)
| Deref r ->
let qid = mk_qualid (List.map_last (ident_add_suffix "__content") (mk_idents_of_type r.typ)) in
let arg = mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] r.right)) in
mk_idapp qid [arg]
| Record_access r ->
let qid = mk_qualid (mk_idents_of_identifier ~notation:None [] r.field) in
let arg = mk_of_expr r.name in
mk_idapp qid [arg]
| Record_update r ->
let record = mk_of_expr r.name in
let assocs = List.map mk_field_association (list_of_nonempty r.updates) in
mk_update record assocs
| Record_aggregate r ->
let assocs = List.map mk_field_association (list_of_nonempty r.associations) in
mk_record assocs
Progs ,
| Any_expr r ->
expr_only "any expr"
(let open E in
let id = mk_ident [] "_f" in
let value =
let pty = mk_pty_of_type r.return_type in
let spec =
let open Opt in
let pre =
let curr_attrs = Curr.mk_attrs () in
to_list
(map requires
(map (T.mk_attrs (List.filter_map mk_label r.labels @ curr_attrs))
(map mk_term_of_pred r.pre))) in
let post =
let curr_attrs = Curr.mk_attrs () in
to_list
(map (ensures ?loc:None)
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.post))) in
let reads, writes, xpost = Opt.(get ([], [], []) (map mk_effects r.effects)) in
mk_spec ~pre ~post ~reads ~writes ~xpost () in
let any = mk_any [] Expr.RKnone (Some pty) P.(mk_wild ()) Ity.MaskVisible spec in
mk_attr (mk_call_id_str ()) any in
let body = mk_var (Qident id) in
mk_let id value body)
| Assignment r ->
expr_only "assignment"
(let open E in
let left = mk_attrs (List.filter_map mk_label r.labels)
(mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] r.name))) in
let field = mk_qualid (List.map_last (ident_add_suffix "__content") (mk_idents_of_type r.typ)) in
let value = mk_expr_of_prog r.value in
mk_assign left (Some field) value)
| Binding_ref r ->
expr_only "binding ref"
(let open E in
let id =
force_one (conversion_error r.name.info.id "quantified or empty name")
(mk_idents_of_identifier ~notation:None (mk_identifier_labels r.name) r.name) in
let ref =
let field =
let typ =
Opt.force (conversion_error r.name.info.id "missing type")
(let Identifier r = r.name.desc in r.typ) in
mk_qualid
(List.map_last (ident_add_suffix "__content")
(mk_idents_of_type typ)) in
let value = mk_expr_of_prog r.def in
mk_record [field, value] in
let body = mk_expr_of_prog r.context in
mk_let id ref body)
| Loop r ->
Loops in the GNAT AST are of the form
loop
code before invariants
invariants / variants
code after invariants
end
We transform these loops into Why3 loops of the form
code before
while True loop
invariant
compute old values for variants
code after
code before
compute new values for variants , compare with old values
end
loop
code before invariants
invariants/variants
code after invariants
end
We transform these loops into Why3 loops of the form
code before
while True loop
invariant
compute old values for variants
code after
code before
compute new values for variants, compare with old values
end
*)
expr_only "loop"
(let true_expr = E.mk_var (mk_qualid [(mk_ident [] "True")]) in
let false_pred = T.mk_var (mk_qualid [mk_ident [] "False"]) in
let invariants = List.(map (T.name_term "LoopInvariant") (map mk_term_of_pred r.invariants)) in
let mk_variant_ident ~old (v : variant_id) =
let base = if old then "loop_var" else "loop_var_new" in
(* creating a unique tmp var for this loop variant, by using the node id *)
mk_ident [] (base ^ "___" ^ string_of_int v.info.id) in
let check_variant (v : variant_id) (vardefs, pred) =
(* checking a single variant; we compare the old value (stored in
the tmp var) to the new value computed by the term. The
comparison operator is provided in the tree.
The accumulator contains the check coditions if this variant
doesn't progress (stays the same). *)
let Variant r = v.desc in
let new_expr = mk_expr_of_term r.expr in
let new_var = mk_variant_ident ~old:false v in
let new_var_term = T.mk_var (mk_qualid [new_var]) in
let old = T.mk_var (mk_qualid [mk_variant_ident ~old:true v]) in
let expr = process_call (module T) v r.cmp_op [new_var_term;old] in
let eq = mk_ident [] (Ident.op_infix "=") in
let res =
T.mk_attrs (List.filter_map mk_label r.labels)
(T.mk_binop
expr
`Or_asym
(T.mk_binop (T.mk_infix new_var_term eq old) `And_asym pred)) in
(new_var, new_expr) :: vardefs, res
in
(* checking all variants of a given Variants node is just a fold
which starts at the end, starting with the false condition. *)
let check_variants (v : variants_id) =
let Variants v = v.desc in
let vardefs, pred =
List.fold_right check_variant (v.variants.elt0 :: v.variants.elts)
([], false_pred) in
let assert_ = E.mk_assert Expr.Assert pred in
List.fold_left (fun acc (v, def) -> E.mk_let v def acc) assert_ vardefs
in
(* Each Variants node is checked indepently of the others, so here
we just map over the list of Variants nodes.
*)
let check_variants =
List.fold_right (E.mk_seq ?loc:None)
(List.map check_variants r.variants)
(E.mk_tuple []) in
(* we introduce the temp vars to hold the old values of the variant
nodes. We can do this in a single fold (no need to group by
Variants). *)
let intro_vars =
List.fold_right (fun (v : variants_id) acc ->
let Variants vs = v.desc in
List.fold_right (fun v acc ->
let Variant r = v.desc in
let value = mk_expr_of_term r.expr in
E.mk_let (mk_variant_ident ~old:true v) value acc)
(vs.variants.elt0 :: vs.variants.elts) acc) r.variants in
let code_after = mk_expr_of_prog r.code_after in
let code_before = mk_expr_of_prog r.code_before in
let loop_body =
mk_seqs
[mk_comment
(Symbol "gnat_ast_to_ptree: code after the loop invariant")
code_after;
mk_comment (Symbol "gnat_ast_to_ptree: code before the loop invariant")
code_before;
mk_comment (Symbol "gnat_ast_to_ptree: code checking the variants")
check_variants
] in
let loop_body = intro_vars loop_body in
let loop = E.mk_while true_expr invariants [] loop_body in
E.mk_seq code_before loop)
| Statement_sequence r ->
expr_only "statement sequence"
(let rec flatten_seq (node: prog_id) =
match node.desc with
| Statement_sequence r ->
flatten_seqs r.statements
| _ -> [node]
and flatten_seqs (nodes: prog_list) =
List.(concat (map flatten_seq (list_of_nonempty nodes))) in
mk_seqs (List.map mk_expr_of_prog (flatten_seqs r.statements)))
| Abstract_expr r ->
(* begin ensures { <r.post> } let _ = <r.expr> in () end *)
expr_only "abstract expr"
E.(let post = mk_term_of_pred r.post in
let expr = mk_expr_of_prog r.expr in
if is_true post && no_vcs_no_side_effects expr then
mk_tuple []
else
let pat = P.mk_wild () in
let spec =
let post = [ensures post] in
mk_spec ~post () in
let body =
let id = mk_ident [] "_" in
let body = mk_tuple [] in
mk_attr (mk_call_id_str ()) (mk_let id expr body) in
mk_fun [] None pat Ity.MaskVisible spec body)
| Assert r ->
expr_only "assert"
(let assert_kind, str =
match r.assert_kind with
| Assert -> Expr.Assert, "Assert"
| Check -> Expr.Check, "Check"
| Assume -> Expr.Assume, "Assume" in
let body =
let curr_attrs = Curr.mk_attrs () in
T.(name_term str (mk_attrs curr_attrs (mk_term_of_pred r.pred))) in
E.(mk_assert assert_kind body))
| Raise r ->
expr_only "raise"
(let e = E.mk_raise
(mk_qualid (mk_idents_of_name ~notation:None [] r.name))
(Option.map mk_expr_of_expr r.arg) in
match r.typ with
| None -> e
| Some typ ->
let pty = mk_pty_of_type typ in
E.mk_cast e pty)
| Try_block r ->
expr_only "try block"
(let expr = mk_expr_of_prog r.prog in
let exn_handlers =
let aux (node: handler_id) =
let Handler r = node.desc in
mk_qualid (mk_idents_of_name ~notation:None [] r.name),
Opt.map mk_pattern_of_ident r.arg_id,
mk_expr_of_prog r.def in
List.map aux (list_of_nonempty r.handler) in
E.mk_match expr [] exn_handlers)
in
let res =
match node.desc with
| Raise _ | Loop _ | Abstract_expr _ | Any_expr _ | Assert _ | Assignment _ | Binding_ref _ | Try_block _ ->
mk_attrs curr_attrs res
| _ -> res in
res
(* Instantiate [MkOfExpr] for terms and expressions and tie the knot with the other specialized functions *)
and mk_expr_of_expr (node : expr_id) : expr =
mk_of_expr (module E) node
and mk_term_of_expr (node : expr_id) : term =
mk_of_expr (module T) node
and mk_expr_of_term (node : term_id) : expr =
match node.desc with
| Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _ | Literal _
| Binding _ | Elsif _ | Epsilon _ | Conditional _ | Integer_constant _
| Range_constant _ | Modular_constant _ | Fixed_constant _ | Real_constant _
| Float_constant _ | Comment _ | Deref _ | Record_access _
| Record_update _ | Record_aggregate _ as desc ->
mk_expr_of_expr {node with desc}
and mk_expr_of_prog (node : prog_id) =
match node.desc with
| Not _ | Connection _ | Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _
| Literal _ | Binding _ | Elsif _ | Epsilon _ | Conditional _ | Integer_constant _
| Range_constant _ | Modular_constant _ | Fixed_constant _ | Real_constant _
| Float_constant _ | Comment _ | Deref _ | Record_access _ | Record_update _
| Record_aggregate _ | Any_expr _ | Assignment _ | Binding_ref _ | Loop _
| Statement_sequence _ | Abstract_expr _ | Assert _ | Raise _ | Try_block _ as desc ->
mk_expr_of_expr {node with desc}
and mk_term_of_pred (node : pred_id) : term =
match node.desc with
| Universal_quantif _ | Existential_quantif _ | Not _ | Connection _
| Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _ | Literal _
| Binding _ | Elsif _ | Epsilon _ | Conditional _ as desc ->
mk_term_of_expr {node with desc}
and mk_effects (effects: effects_id) =
let Effects r = effects.desc in
let reads =
List.(map mk_qualid
(map (mk_idents_of_identifier ~notation:None [])
r.reads)) in
let writes =
List.(map (T.mk_var ?loc:None)
(map mk_qualid
(map (mk_idents_of_identifier ~notation:None [])
r.writes))) in
let xpost =
if r.raises = []
then []
else
let aux re =
match re.desc with
| Raise_effect re_desc ->
let pat = match re_desc.arg_id with
| Some v_id -> mk_pattern_of_ident v_id
| None -> mk_pat (Ptuple []) in
(mk_qualid (mk_idents_of_name ~notation:None [] re_desc.name),
Option.map (fun post -> (pat, mk_term_of_pred post)) re_desc.post)
| _ -> conversion_error re.info.id "ill-formed raises effect" () in
[ get_pos (), List.map aux r.raises ] in
reads, writes, xpost
let mk_function_decl (node: function_decl_id) =
let Function_decl r = node.desc in
let ident =
force_one
(conversion_error r.name.info.id "quantified or empty function name")
(mk_idents_of_identifier ~notation:None
(List.filter_map mk_label r.labels @
Opt.(to_list (mk_location r.location)))
r.name) in
let res_pty =
Opt.map mk_pty_of_type r.return_type in
let params =
let aux (node: binder_id) : param =
let Binder r = node.desc in
get_pos (),
Opt.(map (force_one (conversion_error node.info.id "qualified or empty parameter name"))
(map (mk_idents_of_identifier ~notation:None [])
r.name)),
false,
mk_pty_of_type r.arg_type in
List.map aux r.binders in
let binders =
let aux (loc, id, gh, pty) : binder =
loc, id, gh, Some pty in
List.map aux params in
let decl = {
ld_ident = ident; ld_params = params; ld_type = res_pty;
ld_loc = get_pos (); ld_def = None;
} in
match node.info.domain with
| Term ->
(* function <id> <params> : <res_ty> <*)
[D.mk_logic [{decl with ld_def = Opt.map mk_term_of_expr r.def}]]
| Pterm ->
if params = [] then
(* val constant <id> : <res_ty> [ensures {result = <def>}] *)
let mk_post def =
ensures
T.(let left = mk_var (Qident result_ident) in
let op = mk_ident [] (Ident.op_infix "=") in
let right =
let curr_attrs = Curr.mk_attrs () in
mk_attrs curr_attrs (mk_term_of_expr def) in
mk_infix left op right) in
let value =
let pat = P.mk_wild () in
let spec = mk_spec ~post:Opt.(to_list (map mk_post r.def)) () in
E.mk_any [] Expr.RKnone res_pty pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKfunc value]
else if r.def = None then
(* val function <id> <params> : <res_ty> *)
let value =
let pat = P.mk_wild () in
let spec = mk_spec () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKfunc value]
else
(* function <id> <params> : <res_ty> = <def>
val <id> <params> : <res_typ> ensures { result = <id> <params> }*)
let arg_for_param (_, id, _, pty) =
T.(mk_cast (mk_var (Qident (Opt.get (mk_ident [] "???") id))) pty) in
let logic_decl =
D.mk_logic [{decl with ld_def=Opt.map mk_term_of_expr r.def}] in
let let_decl =
let value =
let pat = P.mk_wild () in
let spec =
let post =
[ensures (* result = <id> <params> *)
T.(let left = mk_var (Qident result_ident) in
let op = mk_ident [] (Ident.op_infix "=") in
let right =
let p = mk_var (Qident {ident with id_ats= []}) in
let args = List.map arg_for_param params in
List.fold_left (mk_apply ?loc:None) p args in
mk_infix left op right)] in
mk_spec ~post () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec in
D.mk_let ident false Expr.RKnone value in
[logic_decl; let_decl]
| Prog ->
Curr.with_ (r.location, No_symbol)
(fun () ->
let spec =
let pre = let open Opt in
let curr_attrs = Curr.mk_attrs () in
to_list
(map requires
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.pre))) in
let post = let open Opt in
let curr_attrs = Curr.mk_attrs () in
to_list
(map (ensures ?loc:None)
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.post))) in
let reads, writes, xpost = Opt.(get ([], [], []) (map mk_effects r.effects)) in
(mk_spec ~pre ~post ~reads ~writes ~xpost ()) in
let expr =
match r.def with
| None ->
(* val <id> <params> : <res_ty> <spec> *)
let pat = P.mk_wild () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec
| Some def ->
(* let <id> <params> : <res_ty> <spec> = [@vc:divergent] <def> *)
let pat = P.mk_wild () in
let body =
let attr = mk_str "vc:divergent" in
let body = mk_expr_of_expr def in
E.mk_attr attr body in
E.mk_fun binders res_pty pat Ity.MaskVisible spec body
in
[D.mk_let ident false Expr.RKnone expr])
| Pred ->
let opt_def = Opt.map mk_term_of_expr r.def in
begin match opt_def with
| None ->
(* val predicate <id> <params> *)
let any = E.mk_any params Expr.RKnone None (P.mk_wild ()) Ity.MaskVisible (mk_spec ()) in
[D.mk_let ident false Expr.RKpred any]
| Some def ->
let mk_arg_of_param node (_, id_opt, _, pty) =
match id_opt with
| Some id -> T.(mk_cast (mk_var (Qident id)) pty)
| None -> conversion_error node.info.id "missing parameter name" () in
let predicate_def =
(* predicate <id> <params> = <def> *)
let def =
Opt.(get def
(map (fun pos -> T.mk_attr pos def)
(mk_location r.location))) in
D.mk_logic [{decl with ld_type=None; ld_def=Some def}] in
let val_def =
(* val <id> <params> : bool ensures { result = <id> <params> }*)
let value =
let pat = P.mk_wild () in
let pty = Ty.mk_atomic_type ["bool"] in
let spec =
let post = [
ensures
T.(let left = mk_term (Tident (Qident result_ident)) in
let right =
let p = mk_var (Qident {ident with id_ats= []}) in
let args = List.map2 mk_arg_of_param r.binders params in
List.fold_left (mk_apply ?loc:None) p args in
mk_binop left `Iff right)
] in
mk_spec ~post () in
E.mk_any params Expr.RKnone (Some pty) pat Ity.MaskVisible spec in
D.mk_let ident false Expr.RKnone value in
[predicate_def; val_def]
end
let mk_record_binder (node : record_binder_id) =
let Record_binder r = node.desc in
let ident =
let name = Opt.force (conversion_error node.info.id "missing name") r.name in
let idents = mk_idents_of_identifier ~notation:None (List.filter_map mk_label r.labels) name in
force_one (conversion_error node.info.id "quantified or empty name") idents in
let pty = mk_pty_of_type r.arg_type in
{f_ident = ident; f_pty = pty; f_mutable = r.is_mutable;
f_ghost = false; f_loc = get_pos ()}
let rec mk_declaration (node : declaration_id) =
match node.desc with
| Type_decl r ->
let ident =
force_one (conversion_error node.info.id "quantified or empty name")
(mk_idents_of_name ~notation:None (List.filter_map mk_label r.labels) r.name) in
let args =
let aux node ids =
force_one (conversion_error node.info.id "quantified or empty argument name") ids in
List.(map2 aux r.args (map (mk_idents_of_identifier ~notation:None []) r.args)) in
let def, vis =
match r.definition with
| None ->
TDrecord [], Ptree.Abstract (* empty type definition *)
| Some definition ->
let def =
match definition.desc with
| Transparent_type_definition r ->
TDalias (mk_pty_of_type r.type_definition)
| Record_definition r ->
TDrecord
(List.map mk_record_binder
(list_of_nonempty r.fields))
| Range_type_definition r ->
TDrange (bigint_of_uint r.first, bigint_of_uint r.last)
| Record_binder _ -> (* This should not be here *)
conversion_error definition.info.id "record binder in type definition" () in
def, Ptree.Public in
[D.mk_type [{
td_ident = ident; td_params = args; td_def = def; td_mut = false;
td_loc = get_pos (); td_inv = []; td_wit = None; td_vis = vis
}]]
| Function_decl _ as desc ->
mk_function_decl {info=node.info; desc}
| Global_ref_declaration r ->
(* val <ident> : <ref_typ> *)
let ident =
let labels =
List.filter_map mk_label r.labels @
Opt.(to_list (mk_location r.location)) in
force_one (conversion_error r.name.info.id "quantified or empty name of global reference")
(mk_idents_of_identifier ~notation:None labels r.name) in
let pty =
let qid = mk_qualid (List.map_last (ident_add_suffix "__ref")
(mk_idents_of_type r.ref_type)) in
Ty.mk_idapp qid [] in
let value =
let pat = P.mk_wild () in
let spec = mk_spec () in
E.mk_any [] Expr.RKnone (Some pty) pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKnone value]
| Meta_declaration r ->
let name =
Opt.force (conversion_error node.info.id "empty name symbol in meta declaration")
(string_of_symbol r.name) in
let parameter =
Opt.force (conversion_error node.info.id "empty parameter symbol in meta declaration")
(string_of_symbol r.parameter) in
let id = mk_ident [] name in
let metarg =
match String.split_on_char ' ' parameter with
| "function" :: strs -> Mfs (Qident (mk_ident [] (String.concat " " strs)))
| _ -> conversion_error node.info.id
("meta declaration "^parameter^" not yet support (please report)") () in
[D.mk_meta id [metarg]]
| Clone_declaration r -> begin
let mk_clone_substitution (node : clone_substitution_id) =
let Clone_substitution r = node.desc in
let qident1 =
let notation =
let Name r = r.orig_name.desc in
if r.infix then Some Ident.op_infix else None in
mk_qualid (mk_idents_of_name ~notation [] r.orig_name) in
let qident2 =
let notation =
let Name r = r.image.desc in
if r.infix then Some Ident.op_infix else None in
mk_qualid (mk_idents_of_name ~notation [] r.image) in
match r.kind with
| Type_subst ->
CStsym (qident1, [], PTtyapp (qident2, []))
| Function ->
CSfsym (qident1, qident2)
| Predicate ->
CSpsym (qident1, qident2)
| Namepace | Lemma | Goal ->
failwith "Not implemented: mk_declaration Clone_declaration" in
match r.clone_kind with
| Export ->
if r.as_name <> No_symbol then
failwith "mk_declaration: clone export as";
let qid = mk_module_qident r.origin in
let substs =
CSprop Decl.Paxiom (* axiom . *) ::
List.map mk_clone_substitution r.substitutions in
[D.mk_cloneexport qid substs]
| Import | Clone_default ->
let qid = mk_module_qident r.origin in
let as_name =
if r.as_name <> No_symbol
then Some (mk_ident_of_symbol node.info.id ~notation:None [] r.as_name)
else None in
let substs =
CSprop Decl.Paxiom (* axiom . *) ::
List.map mk_clone_substitution r.substitutions in
[D.mk_cloneimport true qid as_name substs]
end
| Axiom r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [mk_str "useraxiom"] r.name in
let body = mk_term_of_pred r.def in
let meta =
match r.dep with
| None -> []
| Some x ->
let Axiom_dep axr = x.desc in
let dep_id = mk_qualid (mk_idents_of_identifier ~notation:None [] axr.name) in
let meta_id = mk_ident [] "remove_unused:dependency" in
let meta_arg =
match axr.kind with
| Axdep_func -> Why3.Ptree.Mfs dep_id
| Axdep_pred -> Why3.Ptree.Mps dep_id in
[ D.mk_meta meta_id
[Why3.Ptree.Max (mk_qualid [id]); meta_arg ] ]
in
D.mk_prop Decl.Paxiom id body :: meta
| Goal r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [] r.name in
let body = mk_term_of_pred r.def in
[D.mk_prop Decl.Pgoal id body]
| Namespace_declaration r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [] r.name in
let decls = List.concat (List.map mk_declaration r.declarations) in
[D.mk_scope false id decls]
| Exception_declaration r ->
let id =
force_one (conversion_error node.info.id "quantified or empty name in exception declaration")
(mk_idents_of_name ~notation:None [] r.name) in
let pty = Opt.(get (Ty.mk_tuple []) (map mk_pty_of_type r.arg)) in
[D.mk_exn id pty Ity.MaskVisible]
let mk_theory_declaration (node : theory_declaration_id) =
match node.desc with
| Theory_declaration r ->
(* Ignore [r.kind], because theory and module is the same *)
let name =
let curr_attrs = Opt.to_list (mk_comment_attr r.comment) in
mk_ident_of_symbol node.info.id ~notation:None curr_attrs r.name in
let include_vars = List.map Include_Decl.mk_include_variant r.includes in
let includes, _ =
List.fold_left (fun (l, seen) x ->
if Include_type_set.mem x seen then l, seen
else ((Include_Decl.mk_include_declaration x)::l, Include_type_set.add x seen))
([],Include_type_set.empty)
include_vars in
let declarations = List.concat (List.map mk_declaration r.declarations) in
[name, List.rev_append includes declarations]
let mlw_file nodes =
Modules (List.concat (List.map mk_theory_declaration nodes))
* { 1 JSON auxiliaries }
(** Pretty-print a JSON path *)
let pp_path fmt =
let open Format in
let pp_sep _ () = () in
let pp fmt d = fprintf fmt "[%d]" d in
fprintf fmt ".%a" (pp_print_list ~pp_sep pp)
(** Recursively find the path to a JSON element *)
let find_path needle node =
let exception Found of int list in
let rec aux path node =
if node == needle then
raise (Found (List.rev path))
else
match node with
| `Null | `String _ | `Int _ | `Bool _ -> ()
| `List l -> List.iteri (fun i -> aux (i :: path)) l
| _ -> Format.kasprintf failwith "find_path: %a" pp_path (List.rev path) in
try
aux [] node;
raise Not_found
with Found path ->
path
* { 1 Registration of Gnat / JSON parser }
exception Unexpected_json of string * int list
The locations in the generated ptree are unique but useless because they do not
correspond to any concrete syntax . In case of a typing error in the generated
ptree , we instruct the mlw - printer to mark the corresponding node by [ ( * XXX
correspond to any concrete syntax. In case of a typing error in the generated
ptree, we instruct the mlw-printer to mark the corresponding node by [(*XXX*)],
using [Mlw_printer.set_marker]. The exception [Located_by_marker (file, e)]
is then reported to the user with a hint to the marker in the given file. *)
exception Located_by_marker of string * exn
let gnat_json_format : Env.fformat = "gnat-json"
let gnat_json_file_ext : string = "gnat-json"
let read_channel env path filename c =
let json = Yojson.Safe.from_channel c in
let gnat_file =
let open Gnat_ast in
try From_json.file_from_json json
with From_json.Unexpected_Json (s, node) ->
raise (Unexpected_json (s, find_path node json)) in
Debug printing of intermediate GNAT ast
if Debug.test_flag debug then begin
let out = open_out (filename^".gnat_ast") in
Format.fprintf (Format.formatter_of_out_channel out) "%a@."
Gnat_ast_pretty.pp_file gnat_file
end;
let mlw_file = mlw_file gnat_file.theory_declarations in
let mlw_filename = Strings.remove_suffix ("."^gnat_json_file_ext) filename^".mlw" in
Defer printing of mlw file until after the typing , to set the marker of located
exceptions
exceptions *)
let print_mlw_file ?mark () =
let pp = Mlw_printer.pp_mlw_file ~attr:true in
let pp = match mark with
| None -> pp
| Some (msg, pos) -> Mlw_printer.with_marker ~msg pos pp in
let out = open_out mlw_filename in
Format.fprintf (Format.formatter_of_out_channel out) "%a@." pp mlw_file;
close_out out in
match Typing.type_mlw_file env path filename mlw_file with
| res ->
if Debug.test_flag debug then
print_mlw_file ();
res
| exception Loc.Located (pos, e) ->
The positions in the generated ptree are useless - we set the marker for
printing the mlw file and report that .
printing the mlw file and report that. *)
let msg = Format.asprintf " ERROR %a: @?" Exn_printer.exn_printer e in
print_mlw_file ~mark:(msg, pos) ();
raise (Located_by_marker (mlw_filename, e))
| exception e ->
print_mlw_file ();
raise e
let () =
Env.register_format ~desc:"Gnat@ AST@ in@ JSON@ format"
Pmodule.mlw_language gnat_json_format [gnat_json_file_ext] read_channel
let () =
Exn_printer.register
(fun fmt exn -> match exn with
| Unexpected_json (s, path) ->
(* Errors in the conversion from JSON to Gnat_ast are reported with their path,
because the id is not guaranteed to be available. *)
Format.fprintf fmt "Unexpected Json for %s at path %a@."
s pp_path path
| Conversion_error r ->
Errors in the conversion from Gnat_ast to Why3 Ptree are reported with their
i d.
id. *)
Format.fprintf fmt "Conversion error for node with ID %d: %s" r.node_id r.message
| Located_by_marker (filename, e) ->
Located errors ( i.e. typing errors ) are reported with an hint on the marker , which
is inserted into the mlw file by the mlw - printer .
is inserted into the mlw file by the mlw-printer. *)
Format.fprintf fmt "File %s, marked by (* ERROR: *)(...):@\n%a"
filename Exn_printer.exn_printer e
| _ -> raise exn)
| null | https://raw.githubusercontent.com/AdaCore/why3/97be0f6354f4c5a85896746847192d828cc462d6/plugins/gnat_json/gnat_ast_to_ptree.ml | ocaml | * {1 Auxiliaries for conversion}
The purpose of this model is to allow suppression of duplicate imports in
Why3 theories. This requires a canonical representation of typical
imports, and a compare function for this type, so that we can use OCaml
sets to remove duplicates.
* Test if node is an unquantified OP1
see why3/src/parser/parser.mly, lexer.mll
see why3/src/parser/parser.mly, lexer.mll
VCs from preconditions of the callee, possible side-effects
existence
Convert unqualified op234 prefix operations (/, *, !, etc.)
Shortcut for direct recursive call
Shortcut for nodes that can only translated to a expression
Shortcut for nodes that can only translated to a expression
gnat/ureal.ads
negate the casted negation [neg (-r : t)]]
Using [()] won't play well in terms
creating a unique tmp var for this loop variant, by using the node id
checking a single variant; we compare the old value (stored in
the tmp var) to the new value computed by the term. The
comparison operator is provided in the tree.
The accumulator contains the check coditions if this variant
doesn't progress (stays the same).
checking all variants of a given Variants node is just a fold
which starts at the end, starting with the false condition.
Each Variants node is checked indepently of the others, so here
we just map over the list of Variants nodes.
we introduce the temp vars to hold the old values of the variant
nodes. We can do this in a single fold (no need to group by
Variants).
begin ensures { <r.post> } let _ = <r.expr> in () end
Instantiate [MkOfExpr] for terms and expressions and tie the knot with the other specialized functions
function <id> <params> : <res_ty> <
val constant <id> : <res_ty> [ensures {result = <def>}]
val function <id> <params> : <res_ty>
function <id> <params> : <res_ty> = <def>
val <id> <params> : <res_typ> ensures { result = <id> <params> }
result = <id> <params>
val <id> <params> : <res_ty> <spec>
let <id> <params> : <res_ty> <spec> = [@vc:divergent] <def>
val predicate <id> <params>
predicate <id> <params> = <def>
val <id> <params> : bool ensures { result = <id> <params> }
empty type definition
This should not be here
val <ident> : <ref_typ>
axiom .
axiom .
Ignore [r.kind], because theory and module is the same
* Pretty-print a JSON path
* Recursively find the path to a JSON element
XXX
Errors in the conversion from JSON to Gnat_ast are reported with their path,
because the id is not guaranteed to be available. | open Why3
open Ptree
open Gnat_ast
open Ptree_constructors
let debug = Debug.register_info_flag "gnat_ast" ~desc:"Output@ mlw@ file"
let () = Debug.set_flag debug
[@@@warning "-42"]
exception Conversion_error of {node_id: int; message: string}
let conversion_error node_id message () = raise (Conversion_error {node_id; message})
module Opt = struct
let map f = function
| None -> None
| Some x -> Some (f x)
let get default = function
| Some x -> x
| None -> default
let force err = function
| Some x -> x
| None -> err ()
let to_list = function
| None -> []
| Some x -> [x]
end
module List = struct
include List
let rec map_and_last for_not_last for_last l =
match l with
| [] -> []
| [x] -> [for_last x]
| x :: xs -> for_not_last x :: map_and_last for_not_last for_last xs
let rec map_last for_last l =
match l with
| [] -> []
| [x] -> [for_last x]
| x :: xs -> x :: map_last for_last xs
let rec get_last err = function
| [x] -> x
| _ :: xs -> get_last err xs
| [] -> err ()
let filter_map f l =
map (Opt.force (fun () -> assert false))
(filter ((<>) None)
(map f l))
end
* { 1 Conversion functions from Gnat / JSON to Ptree }
let bigint_of_uint (Uint str) =
BigInt.of_string str
let ident_add_suffix suffix id =
{id with id_str=id.id_str^suffix}
let mk_label = function
| No_symbol -> None
| Symbol s -> Some (ATstr (Ident.create_attribute s))
let mk_location = function
| Source_ptr r ->
let loc = Loc.user_position r.filename r.line 0 r.line 0 in
Some (mk_pos loc)
| No_location -> None
let mk_idents ~notation attrs =
let f = Opt.get (fun s -> s) notation in
List.map_and_last
(mk_ident [])
(fun s -> mk_ident attrs (f s))
let string_of_symbol = function
| Symbol s -> Some s
| No_symbol -> None
let strings_of_name (node : name_id) =
let Name r = node.desc in
let module_string =
match r.module_ with
| Some {desc=Module r} ->
string_of_symbol r.name
| _ -> None in
let namespace_string = string_of_symbol r.namespace in
let symb_string = string_of_symbol r.symb in
Opt.(to_list module_string @ to_list namespace_string @ to_list symb_string)
let name_of_identifier (node: identifier_id) =
let Identifier r = node.desc in
r.name
let force_one err = function
| [x] -> x
| _ -> err ()
let mk_module_qident (node: module_id) =
let Module m = node.desc in
let file = mk_idents ~notation:None [] (Opt.to_list (string_of_symbol m.file)) in
let name = mk_idents ~notation:None [] (Opt.to_list (string_of_symbol m.name)) in
mk_qualid (file @ name)
let mk_idents_of_name ~notation attrs (node: name_id) =
mk_idents ~notation attrs (strings_of_name node)
let mk_idents_of_identifier ~notation attrs (node: identifier_id) =
mk_idents ~notation attrs (strings_of_name (name_of_identifier node))
let mk_ident_of_symbol id ~notation attrs sym =
let notation = Opt.get (fun s -> s) notation in
mk_ident attrs (notation (Opt.force (conversion_error id "empty symbol") (string_of_symbol sym)))
let mk_idents_of_type (node: type_id) =
let Type r = node.desc in
let idents = mk_idents_of_name ~notation:None [] r.name in
if r.is_mutable then
List.map_last (ident_add_suffix "__ref") idents
else
idents
let mk_pattern_of_ident id =
let w_id = List.get_last
(conversion_error id.info.id "empty pattern")
(mk_idents_of_identifier ~notation:None [] id) in
mk_pat (Pvar w_id)
module Include_Decl = struct
type t = Use_export of qualid | Use_import of qualid * ident option
let ident_compare a b = Stdlib.compare a.id_str b.id_str
let ident_opt_compare a b =
match a, b with
| None, Some _ -> -1
| Some _, None -> 1
| Some ia, Some ib -> ident_compare ia ib
| None, None -> 0
let rec qualid_compare a b =
match a, b with
| Qident _ , Qdot _ -> -1
| Qdot _ , Qident _ -> 1
| Qident ia, Qident ib -> ident_compare ia ib
| Qdot (qa, ia), Qdot (qb, ib) ->
let c = qualid_compare qa qb in
if c <> 0 then c else ident_compare ia ib
let compare a b =
match a, b with
| Use_export _ , Use_import _ -> -1
| Use_import _ , Use_export _ -> 1
| Use_export qa, Use_export qb -> qualid_compare qa qb
| Use_import (qa, ioa), Use_import (qb, iob) ->
let c = qualid_compare qa qb in
if c <> 0 then c else ident_opt_compare ioa iob
let mk_include_declaration d =
match d with
| Use_export qid -> D.mk_useexport qid
| Use_import (qid, oi) -> D.mk_useimport false [qid, oi]
let mk_include_variant (node : include_declaration_id) =
let Include_declaration r = node.desc in
let qid = mk_module_qident r.module_ in
match r.use_kind with
| Import -> Use_import (qid, None)
| Export -> Use_export qid
| Clone_default ->
let Module m = r.module_.desc in
Use_import (qid, Some (mk_ident_of_symbol node.info.id ~notation:None [] m.name))
end
module Include_type_set = Set.Make (Include_Decl)
let mk_pty_of_type (node : type_id) =
Ty.mk_idapp (mk_qualid (mk_idents_of_type node)) []
let term_connector = function
| Or_else -> `Or_asym
| And_then -> `And_asym
| Imply -> `Implies
| Equivalent -> `Iff
| Or -> `Or
| And -> `And
let expr_connector id = function
| And_then -> `And_asym
| Or_else -> `Or_asym
| _ -> conversion_error id "unexpected expression operator" ()
let unroll_name (node : name_id) =
let Name {module_; symb} = node.desc in
let aux (node: module_id) =
let Module r = node.desc in
string_of_symbol r.file, string_of_symbol r.name in
Opt.map aux module_, string_of_symbol symb
let is_infix_identifier (node : identifier_id) =
let Identifier r = node.desc in
let Name r = r.name.desc in
r.infix
let is_op1 (node: identifier_id) =
match List.rev (strings_of_name (name_of_identifier node)) with
| s :: _ ->
List.exists (String.contains s)
['='; '<'; '>']
| _ -> conversion_error node.info.id "empty operator identifier" ()
* Test if node is an potentially quantified OP234
let is_op234 (node: identifier_id) =
match List.rev (strings_of_name (name_of_identifier node)) with
| s :: _ ->
List.exists (String.contains s)
['+'; '-'; '*'; '/'; '\\'; '%'; '!'; '$'; '&'; '?'; '@'; '^'; '|']
| _ -> conversion_error node.info.id "empty operator identifier" ()
let mk_comment_attr = function
| No_symbol -> None
| Symbol s -> Some (mk_str ("GNAT-comment:"^s))
module Curr = struct
let loc_ref = ref No_location
let marker_ref = ref No_symbol
let with_ curr f =
let push (loc, marker) =
loc_ref := loc;
marker_ref := marker in
let pop () =
let loc, marker = No_location, No_symbol in
loc_ref := loc;
marker_ref := marker in
push curr;
let res = f () in
pop ();
res
let mk_attrs () =
match !loc_ref with
| No_location ->
[]
| Source_ptr r ->
let filename =
match !marker_ref with
| No_symbol -> r.filename
| Symbol s -> "'@"^s^"@'"^r.filename in
Opt.(to_list (mk_location (Source_ptr {r with filename})))
end
let is_true t = match t.term_desc with
| Ttrue -> true
| _ -> false
let no_vcs_in_spec spec =
spec.sp_post = [] && spec.sp_xpost = [] && spec.sp_variant = []
* Check ( syntactically ) if an expression has no side - effects ( assignments , and ,
potentially , applications ) , and does not trigger any VCs , i.e. it does not contain any
application ( idapp , apply , infix , or innfix , any , which may generate preconditions ) ,
declaration ( fun , rec , which may generate postconditions ) , or logical statement
( absurd , assert , check ) .
potentially, applications), and does not trigger any VCs, i.e. it does not contain any
application (idapp, apply, infix, or innfix, any, which may generate preconditions),
declaration (fun, rec, which may generate postconditions), or logical statement
(absurd, assert, check). *)
let rec no_vcs_no_side_effects e = match e.expr_desc with
| Eref | Etrue | Efalse | Econst _ | Eident _ | Easref _ ->
true
| Eidapp _ | Eapply _ | Einfix _ | Einnfix _ ->
| Elet (_, _, _, e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Erec (funs, e) ->
let aux (_, _, _, _, _, _, _, spec, e) =
no_vcs_in_spec spec && no_vcs_no_side_effects e in
List.for_all aux funs && no_vcs_no_side_effects e
| Efun (_, _, _, _, spec, e) ->
no_vcs_in_spec spec && no_vcs_no_side_effects e
| Eany (_, _, _, _, _, spec) ->
| Etuple es ->
List.for_all no_vcs_no_side_effects es
| Erecord fs ->
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) fs
| Eupdate (e, fs) ->
no_vcs_no_side_effects e &&
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) fs
| Eassign _ ->
false
| Esequence (e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Eif (e1, e2, e3) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2 && no_vcs_no_side_effects e3
| Ewhile (e1, inv, var, e2) ->
inv = [] && var = [] &&
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Eand (e1, e2) | Eor (e1, e2) ->
no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2
| Enot e ->
no_vcs_no_side_effects e
| Ematch (e, regs, exns) ->
no_vcs_no_side_effects e &&
List.for_all (fun (_, e) -> no_vcs_no_side_effects e) regs &&
List.for_all (fun (_, _, e) -> no_vcs_no_side_effects e) exns
| Eabsurd ->
false
| Epure _ | Eidpur _ | Eraise (_, None) ->
true
| Eraise (_, Some e) | Eexn (_, _, _, e) | Eoptexn (_, _, e) ->
no_vcs_no_side_effects e
| Efor (_, e1, _, e2, inv, e3) ->
inv = [] && no_vcs_no_side_effects e1 && no_vcs_no_side_effects e2 && no_vcs_no_side_effects e3
| Eassert (Expr.(Assert|Check), _) -> false
| Eassert (Expr.Assume, _) -> true
| Escope (_, e) | Elabel (_, e) | Ecast (e, _) | Eghost e | Eattr (_, e) ->
no_vcs_no_side_effects e
The conversion from Gnat_ast to is parameterized in [ ' a]/[t ] by the targeted type
( [ Ptree.expr ] or [ Ptree.term ] ) and the corresponding smart constructors from
[ PtreeConstructors ] . Nodes that are converted to different syntaxes in expressions and
terms ar differentiated using [ E_or_T.expr_or_term ] . Nodes that can not be converted to
the target type raise an exception [ Failure ] ( but that should only happen when there is
a problem in the generated [ Gnat_ast ] ) .
([Ptree.expr] or [Ptree.term]) and the corresponding smart constructors from
[PtreeConstructors]. Nodes that are converted to different syntaxes in expressions and
terms ar differentiated using [E_or_T.expr_or_term]. Nodes that cannot be converted to
the target type raise an exception [Failure] (but that should only happen when there is
a problem in the generated [Gnat_ast]). *)
let next_call_id =
let counter = ref 0 in
fun () -> incr counter; !counter
let mk_call_id_str () =
mk_str (Format.sprintf "rac:call_id:%d" (next_call_id ()))
let process_call : 'a . (module E_or_T with type t = 'a) -> 'b why_node_id -> identifier_id -> 'a list -> 'a =
fun (type t) (module E_or_T : E_or_T with type t = t) (node : 'b why_node_id) id args : t ->
Convert unquantified op1 operations (= , < , etc . ) to innfix , binary only
let open E_or_T in
if is_infix_identifier id && is_op1 id then begin
let op =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_infix) [] id) in
match args with
| [arg0;arg1] -> mk_innfix arg0 op arg1
| _ -> conversion_error node.info.id "op1 operations must be binary" ()
end
else if is_infix_identifier id && is_op234 id then begin
match args with
| [_] ->
let qid =
let ident =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_prefix) [] id) in
mk_qualid [ident] in
mk_attr (mk_call_id_str ())
(mk_idapp qid args)
| [_;_] ->
let qid =
let ident =
List.get_last (conversion_error node.info.id "empty operator name")
(mk_idents_of_identifier ~notation:(Some Ident.op_infix) [] id) in
mk_qualid [ident] in
mk_attr (mk_call_id_str ())
(mk_idapp qid args)
| _ ->
conversion_error node.info.id "operations with op234 operators must be unary or binary" ()
end else (begin
if is_infix_identifier id then
Format.ksprintf (conversion_error node.info.id) "infix identifier %s must be op1 or op234"
(String.concat "." (strings_of_name (name_of_identifier id))) ();
let notation =
if is_op1 id || is_op234 id then
match List.length args with
| 1 -> Some Ident.op_prefix
| 2 -> Some Ident.op_infix
| _ -> conversion_error node.info.id "operations with op234 operators must be unary or binary" ()
else None in
let f = mk_var (mk_qualid (mk_idents_of_identifier ~notation [] id)) in
mk_attr (mk_call_id_str ())
(List.fold_left (mk_apply ?loc:None) f args)
end)
let rec mk_of_expr : 'a . (module E_or_T with type t = 'a) -> expr_id -> 'a =
Signature type ^^^^^ variable [ ' a ] required to make [ mk_of_expr ] strongly polymorphic
fun (type t) (module E_or_T : E_or_T with type t = t) (node: expr_id) : t ->
let open E_or_T in
mk_of_expr (module E_or_T: E_or_T with type t = t) node in
expr_or_term ~info:(Format.sprintf "(%s with ID %d)" cat node.info.id) ~expr:(fun () -> expr) () in
expr_or_term ~info:(Format.sprintf "(%s with ID %d)" cat node.info.id) ~term:(fun () -> term) () in
let mk_field_association (node: field_association_id) =
let Field_association r = node.desc in
mk_qualid (mk_idents_of_name ~notation:None [] (name_of_identifier r.field)),
mk_of_expr r.value in
let mk_binder_of_identifier attrs pty node =
let id =
let err = conversion_error node.info.id "qualified or empty identifier" in
force_one err (mk_idents_of_identifier ~notation:None attrs node) in
get_pos (), Some id, false, Some pty in
let mk_identifier_labels (node : identifier_id) =
let Identifier r = node.desc in
List.filter_map mk_label r.labels in
let mk_seqs l =
let not_unit = function
| {expr_desc = Etuple []} -> false
| _ -> true in
let statements = List.filter not_unit l in
let firsts, last =
match List.rev statements with
| [] -> [], E.mk_tuple []
| last :: firsts -> List.rev firsts, last in
List.fold_right (E.mk_seq ?loc:None) firsts last in
let mk_comment s e =
match mk_comment_attr s with
| None -> e
| Some a -> E.mk_attr a e in
let mk_const_of_ureal id (Ureal r) =
if r.base = 0 then
let Uint numerator = r.numerator in
let mk_const r = mk_const (Constant.ConstReal r) in
if BigInt.(eq one (bigint_of_uint r.denominator)) then
mk_const
(Number.real_literal ~radix:10 ~neg:r.negative ~int:numerator ~frac:"0" ~exp:None)
else
conversion_error id "ureal with base = 0 and denominator /= 1" ()
( \ * Which operator /. for reals ? * \ )
* let Uint denominator = r.denominator in
* mk_idapp
* ( mk_qualid [ mk_ident [ ] ( Ident.op_infix " /. " ) ] )
* ( List.map mk_const
* [ Number.real_literal ~radix:10 ~neg : r.negative ~int : numerator ~frac:"0 " ~exp : None ;
* Number.real_literal ~radix:10 ~neg : false ~int : denominator ~frac:"0 " ~exp : None ] )
* let Uint denominator = r.denominator in
* mk_idapp
* (mk_qualid [mk_ident [] (Ident.op_infix "/.")])
* (List.map mk_const
* [Number.real_literal ~radix:10 ~neg:r.negative ~int:numerator ~frac:"0" ~exp:None;
* Number.real_literal ~radix:10 ~neg:false ~int:denominator ~frac:"0" ~exp:None]) *)
else
let int =
let int = bigint_of_uint r.numerator in
if r.negative then BigInt.minus int else int in
let exp = BigInt.(minus (bigint_of_uint r.denominator)) in
match r.base with
| 2 ->
mk_const (Constant.real_const ~pow2:exp ~pow5:BigInt.zero int)
| 10 ->
mk_const (Constant.real_const ~pow2:exp ~pow5:exp int)
| 16 ->
let pow2 = BigInt.mul_int 4 exp in
mk_const (Constant.real_const ~pow2 ~pow5:BigInt.zero int)
| _ ->
conversion_error id ("unsupported base "^string_of_int r.base^" for ureal") () in
let curr_attrs = Curr.mk_attrs () in
let res = match node.desc with
Preds ,
| Universal_quantif r ->
term_only "universal quantif"
(let for_trigger (node : trigger_id) =
let Trigger r = node.desc in
List.map mk_term_of_expr (list_of_nonempty r.terms) in
let for_triggers (node : triggers_id) =
let Triggers r = node.desc in
List.map for_trigger (list_of_nonempty r.triggers) in
let curr_attrs = Curr.mk_attrs () in
let binders =
List.map (mk_binder_of_identifier (curr_attrs @ List.filter_map mk_label r.labels) (mk_pty_of_type r.var_type))
(list_of_nonempty r.variables) in
let triggers = Opt.(get [] (map for_triggers r.triggers)) in
let body = mk_term_of_pred r.pred in
T.mk_quant Dterm.DTforall binders triggers body)
| Existential_quantif r ->
term_only "existential quantif"
(let binders =
List.map
(mk_binder_of_identifier (List.filter_map mk_label r.labels)
(mk_pty_of_type r.var_type))
(list_of_nonempty r.variables) in
let body = mk_term_of_pred r.pred in
T.mk_quant Dterm.DTexists binders [] body)
Preds , Progs ,
| Not r ->
mk_not (mk_of_expr r.right)
| Connection r ->
let module M = struct
type 'a tree = Node of 'a | Binop of 'a tree * 'a tree
let rec map node binop = function
| Node x -> node x
| Binop (t1, t2) ->
let x1 = map node binop t1 in
let x2 = map node binop t2 in
binop x1 x2
let mk_tree = function
| [] -> None
| exprs ->
let a = Array.of_list exprs in
let rec aux from to_ =
assert (to_ - from > 0);
if to_ - from = 1 then
Node a.(from)
else
let mid = (from + to_ + 1) / 2 in
Binop (aux from mid, aux mid to_) in
Some (aux 0 (Array.length a))
end in
expr_or_term
~expr:(fun () ->
let op = expr_connector node.info.id r.op in
let e1 =
let left = mk_expr_of_expr r.left in
let right = mk_expr_of_expr r.right in
E.mk_binop left op right in
Opt.(get e1
(map (E.mk_binop e1 op)
(map (M.map mk_expr_of_expr (fun e -> E.mk_binop e op))
(M.mk_tree r.more_right)))))
~term:(fun () ->
let op = term_connector r.op in
let t1 =
let left = mk_term_of_expr r.left in
let right = mk_term_of_expr r.right in
T.mk_binnop left op right in
Opt.(get t1
(map (T.mk_binnop t1 op)
(map (M.map mk_term_of_expr (fun t -> T.mk_binnop t op))
(M.mk_tree r.more_right))))) ()
| Label r ->
let labels = List.filter_map mk_label r.labels in
let body = mk_of_expr r.def in
mk_attrs labels body
| Loc_label r ->
Curr.with_ (r.sloc, r.marker)
(fun () ->
let curr_attrs = Curr.mk_attrs () in
let body = mk_of_expr r.def in
mk_attrs curr_attrs body)
Preds , Terms , Progs ,
FIXGNAT sometimes the symbol contains a function application , e.g. " uint_in_range x " [ sic ! ]
| Identifier ({name={desc=Name ({symb=Symbol s} as name_r)} as name} as ident_r)
when String.index_opt s ' ' <> None -> begin
match String.split_on_char ' ' s with
| s' :: args ->
let node' = {
node with desc = Identifier {
ident_r with name = {name with desc=Name {
name_r with symb = Symbol s'}}}} in
let f = mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] node')) in
let args = List.(map (mk_var ?loc:None) (map mk_qualid (map (fun s -> [mk_ident [] s]) args))) in
List.fold_left (mk_apply ?loc:None) f args
| _ -> assert false
end
| Identifier {name={desc=Name {symb=Symbol "absurd"}}} ->
expr_only "identifier"
E.(mk_absurd ())
| Identifier {name={desc=Name {symb=Symbol "()"}}} ->
mk_tuple []
| Identifier r ->
mk_var (mk_qualid (mk_idents_of_name ~notation:None [] r.name))
| Tagged ({tag=No_symbol} as r) ->
term_only "tagged"
(mk_term_of_expr r.def)
| Tagged ({tag=Symbol s} as r) ->
term_only "tagged"
(let body = mk_term_of_expr r.def in
let id =
let s = if s = "old" then "'Old" else s in
mk_ident [] s in
T.mk_at body id)
| Call r ->
let args = List.map mk_of_expr r.args in
process_call (module E_or_T: E_or_T with type t = t) node r.name args
| Literal r ->
if node.info.domain = Pred then
mk_truth (match r.value with True -> true | False -> false)
else
mk_var (mk_qualid [mk_ident [] (match r.value with True -> "True" | False -> "False")])
| Binding r ->
let id =
force_one (conversion_error r.name.info.id "qualified or empty identifier")
(mk_idents_of_identifier ~notation:None
(mk_identifier_labels r.name) r.name) in
expr_or_term
~expr:(fun () ->
let def = mk_expr_of_expr r.def in
let body = mk_expr_of_expr r.context in
if id.id_str = "_" && no_vcs_no_side_effects def
then body
else E.mk_let id def body)
~term:(fun () ->
let def = mk_term_of_expr r.def in
let body = mk_term_of_expr r.context in
T.mk_let id def body) ()
| Elsif _ ->
conversion_error node.info.id "unexpected elsif" ()
| Epsilon r ->
term_only "epsilon"
(let id =
force_one (conversion_error r.name.info.id "qualified or empty idenfitier")
(mk_idents_of_identifier ~notation:None [] r.name) in
let pty = mk_pty_of_type r.typ in
let body = mk_term_of_pred r.pred in
T.mk_eps id pty body)
| Conditional r ->
let rec mk_elsifs = function
| [] ->
let open Opt in
get (expr_or_term
~expr:(fun () -> E.mk_tuple [])
~term:(fun () -> T.mk_truth true) ())
(map mk_of_expr r.else_part)
| {desc=Elsif r'} :: elsifs ->
let condition' = mk_of_expr r'.condition in
let then_part' = mk_of_expr r'.then_part in
let elsif_parts' = mk_elsifs elsifs in
mk_if condition' then_part' elsif_parts'
| _ ->
conversion_error node.info.id "unexpected elsif" ()
in
let condition = mk_of_expr r.condition in
let then_part = mk_of_expr r.then_part in
let elsif_parts = mk_elsifs r.elsif_parts in
mk_if condition then_part elsif_parts
Terms , Progs , Exprs
| Integer_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = Ty.mk_atomic_type ["int"] in
mk_cast const pty
| Range_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = mk_pty_of_type r.typ in
mk_cast const pty
| Modular_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty =
let Type r = r.typ.desc in
match unroll_name r.name with
| Some (Some "_gnatprove_standard", Some (("BV8"|"BV16"|"BV32"|"BV64"|"BV128" as s))), Some "t" ->
Ty.mk_atomic_type [s; "t"]
| _ ->
conversion_error node.info.id "unknown module constant" () in
mk_cast const pty
| Fixed_constant r ->
let const = mk_const (Constant.int_const (bigint_of_uint r.value)) in
let pty = Ty.mk_atomic_type ["int"] in
mk_cast const pty
| Real_constant r ->
mk_const_of_ureal node.info.id r.value
| Float_constant r ->
let prefix =
let Type r = r.typ.desc in
match unroll_name r.name with
| Some (Some "_gnatprove_standard", Some ("Float32"|"Float64"|"Float80" as s)), Some "t" ->
mk_ident [] s
| _ ->
conversion_error node.info.id "float_constant must be Float32.t, Float64.t or Float80.t" ()
in
let const =
let Ureal r' = r.value in
if r'.negative then
mk_apply (mk_var (mk_qualid [prefix; mk_ident [] "neg"]))
(mk_cast
(mk_const_of_ureal node.info.id (Ureal {r' with negative=false}))
(Ty.mk_idapp (mk_qualid [prefix; mk_ident [] "t"]) []))
else
mk_const_of_ureal node.info.id r.value in
let pty = Ty.mk_idapp (mk_qualid [prefix; mk_ident [] "t"]) [] in
mk_cast const pty
| Comment r ->
expr_only "comment"
(let body = E.mk_tuple [] in
mk_comment r.comment body)
| Deref r ->
let qid = mk_qualid (List.map_last (ident_add_suffix "__content") (mk_idents_of_type r.typ)) in
let arg = mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] r.right)) in
mk_idapp qid [arg]
| Record_access r ->
let qid = mk_qualid (mk_idents_of_identifier ~notation:None [] r.field) in
let arg = mk_of_expr r.name in
mk_idapp qid [arg]
| Record_update r ->
let record = mk_of_expr r.name in
let assocs = List.map mk_field_association (list_of_nonempty r.updates) in
mk_update record assocs
| Record_aggregate r ->
let assocs = List.map mk_field_association (list_of_nonempty r.associations) in
mk_record assocs
Progs ,
| Any_expr r ->
expr_only "any expr"
(let open E in
let id = mk_ident [] "_f" in
let value =
let pty = mk_pty_of_type r.return_type in
let spec =
let open Opt in
let pre =
let curr_attrs = Curr.mk_attrs () in
to_list
(map requires
(map (T.mk_attrs (List.filter_map mk_label r.labels @ curr_attrs))
(map mk_term_of_pred r.pre))) in
let post =
let curr_attrs = Curr.mk_attrs () in
to_list
(map (ensures ?loc:None)
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.post))) in
let reads, writes, xpost = Opt.(get ([], [], []) (map mk_effects r.effects)) in
mk_spec ~pre ~post ~reads ~writes ~xpost () in
let any = mk_any [] Expr.RKnone (Some pty) P.(mk_wild ()) Ity.MaskVisible spec in
mk_attr (mk_call_id_str ()) any in
let body = mk_var (Qident id) in
mk_let id value body)
| Assignment r ->
expr_only "assignment"
(let open E in
let left = mk_attrs (List.filter_map mk_label r.labels)
(mk_var (mk_qualid (mk_idents_of_identifier ~notation:None [] r.name))) in
let field = mk_qualid (List.map_last (ident_add_suffix "__content") (mk_idents_of_type r.typ)) in
let value = mk_expr_of_prog r.value in
mk_assign left (Some field) value)
| Binding_ref r ->
expr_only "binding ref"
(let open E in
let id =
force_one (conversion_error r.name.info.id "quantified or empty name")
(mk_idents_of_identifier ~notation:None (mk_identifier_labels r.name) r.name) in
let ref =
let field =
let typ =
Opt.force (conversion_error r.name.info.id "missing type")
(let Identifier r = r.name.desc in r.typ) in
mk_qualid
(List.map_last (ident_add_suffix "__content")
(mk_idents_of_type typ)) in
let value = mk_expr_of_prog r.def in
mk_record [field, value] in
let body = mk_expr_of_prog r.context in
mk_let id ref body)
| Loop r ->
Loops in the GNAT AST are of the form
loop
code before invariants
invariants / variants
code after invariants
end
We transform these loops into Why3 loops of the form
code before
while True loop
invariant
compute old values for variants
code after
code before
compute new values for variants , compare with old values
end
loop
code before invariants
invariants/variants
code after invariants
end
We transform these loops into Why3 loops of the form
code before
while True loop
invariant
compute old values for variants
code after
code before
compute new values for variants, compare with old values
end
*)
expr_only "loop"
(let true_expr = E.mk_var (mk_qualid [(mk_ident [] "True")]) in
let false_pred = T.mk_var (mk_qualid [mk_ident [] "False"]) in
let invariants = List.(map (T.name_term "LoopInvariant") (map mk_term_of_pred r.invariants)) in
let mk_variant_ident ~old (v : variant_id) =
let base = if old then "loop_var" else "loop_var_new" in
mk_ident [] (base ^ "___" ^ string_of_int v.info.id) in
let check_variant (v : variant_id) (vardefs, pred) =
let Variant r = v.desc in
let new_expr = mk_expr_of_term r.expr in
let new_var = mk_variant_ident ~old:false v in
let new_var_term = T.mk_var (mk_qualid [new_var]) in
let old = T.mk_var (mk_qualid [mk_variant_ident ~old:true v]) in
let expr = process_call (module T) v r.cmp_op [new_var_term;old] in
let eq = mk_ident [] (Ident.op_infix "=") in
let res =
T.mk_attrs (List.filter_map mk_label r.labels)
(T.mk_binop
expr
`Or_asym
(T.mk_binop (T.mk_infix new_var_term eq old) `And_asym pred)) in
(new_var, new_expr) :: vardefs, res
in
let check_variants (v : variants_id) =
let Variants v = v.desc in
let vardefs, pred =
List.fold_right check_variant (v.variants.elt0 :: v.variants.elts)
([], false_pred) in
let assert_ = E.mk_assert Expr.Assert pred in
List.fold_left (fun acc (v, def) -> E.mk_let v def acc) assert_ vardefs
in
let check_variants =
List.fold_right (E.mk_seq ?loc:None)
(List.map check_variants r.variants)
(E.mk_tuple []) in
let intro_vars =
List.fold_right (fun (v : variants_id) acc ->
let Variants vs = v.desc in
List.fold_right (fun v acc ->
let Variant r = v.desc in
let value = mk_expr_of_term r.expr in
E.mk_let (mk_variant_ident ~old:true v) value acc)
(vs.variants.elt0 :: vs.variants.elts) acc) r.variants in
let code_after = mk_expr_of_prog r.code_after in
let code_before = mk_expr_of_prog r.code_before in
let loop_body =
mk_seqs
[mk_comment
(Symbol "gnat_ast_to_ptree: code after the loop invariant")
code_after;
mk_comment (Symbol "gnat_ast_to_ptree: code before the loop invariant")
code_before;
mk_comment (Symbol "gnat_ast_to_ptree: code checking the variants")
check_variants
] in
let loop_body = intro_vars loop_body in
let loop = E.mk_while true_expr invariants [] loop_body in
E.mk_seq code_before loop)
| Statement_sequence r ->
expr_only "statement sequence"
(let rec flatten_seq (node: prog_id) =
match node.desc with
| Statement_sequence r ->
flatten_seqs r.statements
| _ -> [node]
and flatten_seqs (nodes: prog_list) =
List.(concat (map flatten_seq (list_of_nonempty nodes))) in
mk_seqs (List.map mk_expr_of_prog (flatten_seqs r.statements)))
| Abstract_expr r ->
expr_only "abstract expr"
E.(let post = mk_term_of_pred r.post in
let expr = mk_expr_of_prog r.expr in
if is_true post && no_vcs_no_side_effects expr then
mk_tuple []
else
let pat = P.mk_wild () in
let spec =
let post = [ensures post] in
mk_spec ~post () in
let body =
let id = mk_ident [] "_" in
let body = mk_tuple [] in
mk_attr (mk_call_id_str ()) (mk_let id expr body) in
mk_fun [] None pat Ity.MaskVisible spec body)
| Assert r ->
expr_only "assert"
(let assert_kind, str =
match r.assert_kind with
| Assert -> Expr.Assert, "Assert"
| Check -> Expr.Check, "Check"
| Assume -> Expr.Assume, "Assume" in
let body =
let curr_attrs = Curr.mk_attrs () in
T.(name_term str (mk_attrs curr_attrs (mk_term_of_pred r.pred))) in
E.(mk_assert assert_kind body))
| Raise r ->
expr_only "raise"
(let e = E.mk_raise
(mk_qualid (mk_idents_of_name ~notation:None [] r.name))
(Option.map mk_expr_of_expr r.arg) in
match r.typ with
| None -> e
| Some typ ->
let pty = mk_pty_of_type typ in
E.mk_cast e pty)
| Try_block r ->
expr_only "try block"
(let expr = mk_expr_of_prog r.prog in
let exn_handlers =
let aux (node: handler_id) =
let Handler r = node.desc in
mk_qualid (mk_idents_of_name ~notation:None [] r.name),
Opt.map mk_pattern_of_ident r.arg_id,
mk_expr_of_prog r.def in
List.map aux (list_of_nonempty r.handler) in
E.mk_match expr [] exn_handlers)
in
let res =
match node.desc with
| Raise _ | Loop _ | Abstract_expr _ | Any_expr _ | Assert _ | Assignment _ | Binding_ref _ | Try_block _ ->
mk_attrs curr_attrs res
| _ -> res in
res
and mk_expr_of_expr (node : expr_id) : expr =
mk_of_expr (module E) node
and mk_term_of_expr (node : expr_id) : term =
mk_of_expr (module T) node
and mk_expr_of_term (node : term_id) : expr =
match node.desc with
| Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _ | Literal _
| Binding _ | Elsif _ | Epsilon _ | Conditional _ | Integer_constant _
| Range_constant _ | Modular_constant _ | Fixed_constant _ | Real_constant _
| Float_constant _ | Comment _ | Deref _ | Record_access _
| Record_update _ | Record_aggregate _ as desc ->
mk_expr_of_expr {node with desc}
and mk_expr_of_prog (node : prog_id) =
match node.desc with
| Not _ | Connection _ | Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _
| Literal _ | Binding _ | Elsif _ | Epsilon _ | Conditional _ | Integer_constant _
| Range_constant _ | Modular_constant _ | Fixed_constant _ | Real_constant _
| Float_constant _ | Comment _ | Deref _ | Record_access _ | Record_update _
| Record_aggregate _ | Any_expr _ | Assignment _ | Binding_ref _ | Loop _
| Statement_sequence _ | Abstract_expr _ | Assert _ | Raise _ | Try_block _ as desc ->
mk_expr_of_expr {node with desc}
and mk_term_of_pred (node : pred_id) : term =
match node.desc with
| Universal_quantif _ | Existential_quantif _ | Not _ | Connection _
| Label _ | Loc_label _ | Identifier _ | Tagged _ | Call _ | Literal _
| Binding _ | Elsif _ | Epsilon _ | Conditional _ as desc ->
mk_term_of_expr {node with desc}
and mk_effects (effects: effects_id) =
let Effects r = effects.desc in
let reads =
List.(map mk_qualid
(map (mk_idents_of_identifier ~notation:None [])
r.reads)) in
let writes =
List.(map (T.mk_var ?loc:None)
(map mk_qualid
(map (mk_idents_of_identifier ~notation:None [])
r.writes))) in
let xpost =
if r.raises = []
then []
else
let aux re =
match re.desc with
| Raise_effect re_desc ->
let pat = match re_desc.arg_id with
| Some v_id -> mk_pattern_of_ident v_id
| None -> mk_pat (Ptuple []) in
(mk_qualid (mk_idents_of_name ~notation:None [] re_desc.name),
Option.map (fun post -> (pat, mk_term_of_pred post)) re_desc.post)
| _ -> conversion_error re.info.id "ill-formed raises effect" () in
[ get_pos (), List.map aux r.raises ] in
reads, writes, xpost
let mk_function_decl (node: function_decl_id) =
let Function_decl r = node.desc in
let ident =
force_one
(conversion_error r.name.info.id "quantified or empty function name")
(mk_idents_of_identifier ~notation:None
(List.filter_map mk_label r.labels @
Opt.(to_list (mk_location r.location)))
r.name) in
let res_pty =
Opt.map mk_pty_of_type r.return_type in
let params =
let aux (node: binder_id) : param =
let Binder r = node.desc in
get_pos (),
Opt.(map (force_one (conversion_error node.info.id "qualified or empty parameter name"))
(map (mk_idents_of_identifier ~notation:None [])
r.name)),
false,
mk_pty_of_type r.arg_type in
List.map aux r.binders in
let binders =
let aux (loc, id, gh, pty) : binder =
loc, id, gh, Some pty in
List.map aux params in
let decl = {
ld_ident = ident; ld_params = params; ld_type = res_pty;
ld_loc = get_pos (); ld_def = None;
} in
match node.info.domain with
| Term ->
[D.mk_logic [{decl with ld_def = Opt.map mk_term_of_expr r.def}]]
| Pterm ->
if params = [] then
let mk_post def =
ensures
T.(let left = mk_var (Qident result_ident) in
let op = mk_ident [] (Ident.op_infix "=") in
let right =
let curr_attrs = Curr.mk_attrs () in
mk_attrs curr_attrs (mk_term_of_expr def) in
mk_infix left op right) in
let value =
let pat = P.mk_wild () in
let spec = mk_spec ~post:Opt.(to_list (map mk_post r.def)) () in
E.mk_any [] Expr.RKnone res_pty pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKfunc value]
else if r.def = None then
let value =
let pat = P.mk_wild () in
let spec = mk_spec () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKfunc value]
else
let arg_for_param (_, id, _, pty) =
T.(mk_cast (mk_var (Qident (Opt.get (mk_ident [] "???") id))) pty) in
let logic_decl =
D.mk_logic [{decl with ld_def=Opt.map mk_term_of_expr r.def}] in
let let_decl =
let value =
let pat = P.mk_wild () in
let spec =
let post =
T.(let left = mk_var (Qident result_ident) in
let op = mk_ident [] (Ident.op_infix "=") in
let right =
let p = mk_var (Qident {ident with id_ats= []}) in
let args = List.map arg_for_param params in
List.fold_left (mk_apply ?loc:None) p args in
mk_infix left op right)] in
mk_spec ~post () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec in
D.mk_let ident false Expr.RKnone value in
[logic_decl; let_decl]
| Prog ->
Curr.with_ (r.location, No_symbol)
(fun () ->
let spec =
let pre = let open Opt in
let curr_attrs = Curr.mk_attrs () in
to_list
(map requires
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.pre))) in
let post = let open Opt in
let curr_attrs = Curr.mk_attrs () in
to_list
(map (ensures ?loc:None)
(map (T.mk_attrs curr_attrs)
(map mk_term_of_pred r.post))) in
let reads, writes, xpost = Opt.(get ([], [], []) (map mk_effects r.effects)) in
(mk_spec ~pre ~post ~reads ~writes ~xpost ()) in
let expr =
match r.def with
| None ->
let pat = P.mk_wild () in
E.mk_any params Expr.RKnone res_pty pat Ity.MaskVisible spec
| Some def ->
let pat = P.mk_wild () in
let body =
let attr = mk_str "vc:divergent" in
let body = mk_expr_of_expr def in
E.mk_attr attr body in
E.mk_fun binders res_pty pat Ity.MaskVisible spec body
in
[D.mk_let ident false Expr.RKnone expr])
| Pred ->
let opt_def = Opt.map mk_term_of_expr r.def in
begin match opt_def with
| None ->
let any = E.mk_any params Expr.RKnone None (P.mk_wild ()) Ity.MaskVisible (mk_spec ()) in
[D.mk_let ident false Expr.RKpred any]
| Some def ->
let mk_arg_of_param node (_, id_opt, _, pty) =
match id_opt with
| Some id -> T.(mk_cast (mk_var (Qident id)) pty)
| None -> conversion_error node.info.id "missing parameter name" () in
let predicate_def =
let def =
Opt.(get def
(map (fun pos -> T.mk_attr pos def)
(mk_location r.location))) in
D.mk_logic [{decl with ld_type=None; ld_def=Some def}] in
let val_def =
let value =
let pat = P.mk_wild () in
let pty = Ty.mk_atomic_type ["bool"] in
let spec =
let post = [
ensures
T.(let left = mk_term (Tident (Qident result_ident)) in
let right =
let p = mk_var (Qident {ident with id_ats= []}) in
let args = List.map2 mk_arg_of_param r.binders params in
List.fold_left (mk_apply ?loc:None) p args in
mk_binop left `Iff right)
] in
mk_spec ~post () in
E.mk_any params Expr.RKnone (Some pty) pat Ity.MaskVisible spec in
D.mk_let ident false Expr.RKnone value in
[predicate_def; val_def]
end
let mk_record_binder (node : record_binder_id) =
let Record_binder r = node.desc in
let ident =
let name = Opt.force (conversion_error node.info.id "missing name") r.name in
let idents = mk_idents_of_identifier ~notation:None (List.filter_map mk_label r.labels) name in
force_one (conversion_error node.info.id "quantified or empty name") idents in
let pty = mk_pty_of_type r.arg_type in
{f_ident = ident; f_pty = pty; f_mutable = r.is_mutable;
f_ghost = false; f_loc = get_pos ()}
let rec mk_declaration (node : declaration_id) =
match node.desc with
| Type_decl r ->
let ident =
force_one (conversion_error node.info.id "quantified or empty name")
(mk_idents_of_name ~notation:None (List.filter_map mk_label r.labels) r.name) in
let args =
let aux node ids =
force_one (conversion_error node.info.id "quantified or empty argument name") ids in
List.(map2 aux r.args (map (mk_idents_of_identifier ~notation:None []) r.args)) in
let def, vis =
match r.definition with
| None ->
| Some definition ->
let def =
match definition.desc with
| Transparent_type_definition r ->
TDalias (mk_pty_of_type r.type_definition)
| Record_definition r ->
TDrecord
(List.map mk_record_binder
(list_of_nonempty r.fields))
| Range_type_definition r ->
TDrange (bigint_of_uint r.first, bigint_of_uint r.last)
conversion_error definition.info.id "record binder in type definition" () in
def, Ptree.Public in
[D.mk_type [{
td_ident = ident; td_params = args; td_def = def; td_mut = false;
td_loc = get_pos (); td_inv = []; td_wit = None; td_vis = vis
}]]
| Function_decl _ as desc ->
mk_function_decl {info=node.info; desc}
| Global_ref_declaration r ->
let ident =
let labels =
List.filter_map mk_label r.labels @
Opt.(to_list (mk_location r.location)) in
force_one (conversion_error r.name.info.id "quantified or empty name of global reference")
(mk_idents_of_identifier ~notation:None labels r.name) in
let pty =
let qid = mk_qualid (List.map_last (ident_add_suffix "__ref")
(mk_idents_of_type r.ref_type)) in
Ty.mk_idapp qid [] in
let value =
let pat = P.mk_wild () in
let spec = mk_spec () in
E.mk_any [] Expr.RKnone (Some pty) pat Ity.MaskVisible spec in
[D.mk_let ident false Expr.RKnone value]
| Meta_declaration r ->
let name =
Opt.force (conversion_error node.info.id "empty name symbol in meta declaration")
(string_of_symbol r.name) in
let parameter =
Opt.force (conversion_error node.info.id "empty parameter symbol in meta declaration")
(string_of_symbol r.parameter) in
let id = mk_ident [] name in
let metarg =
match String.split_on_char ' ' parameter with
| "function" :: strs -> Mfs (Qident (mk_ident [] (String.concat " " strs)))
| _ -> conversion_error node.info.id
("meta declaration "^parameter^" not yet support (please report)") () in
[D.mk_meta id [metarg]]
| Clone_declaration r -> begin
let mk_clone_substitution (node : clone_substitution_id) =
let Clone_substitution r = node.desc in
let qident1 =
let notation =
let Name r = r.orig_name.desc in
if r.infix then Some Ident.op_infix else None in
mk_qualid (mk_idents_of_name ~notation [] r.orig_name) in
let qident2 =
let notation =
let Name r = r.image.desc in
if r.infix then Some Ident.op_infix else None in
mk_qualid (mk_idents_of_name ~notation [] r.image) in
match r.kind with
| Type_subst ->
CStsym (qident1, [], PTtyapp (qident2, []))
| Function ->
CSfsym (qident1, qident2)
| Predicate ->
CSpsym (qident1, qident2)
| Namepace | Lemma | Goal ->
failwith "Not implemented: mk_declaration Clone_declaration" in
match r.clone_kind with
| Export ->
if r.as_name <> No_symbol then
failwith "mk_declaration: clone export as";
let qid = mk_module_qident r.origin in
let substs =
List.map mk_clone_substitution r.substitutions in
[D.mk_cloneexport qid substs]
| Import | Clone_default ->
let qid = mk_module_qident r.origin in
let as_name =
if r.as_name <> No_symbol
then Some (mk_ident_of_symbol node.info.id ~notation:None [] r.as_name)
else None in
let substs =
List.map mk_clone_substitution r.substitutions in
[D.mk_cloneimport true qid as_name substs]
end
| Axiom r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [mk_str "useraxiom"] r.name in
let body = mk_term_of_pred r.def in
let meta =
match r.dep with
| None -> []
| Some x ->
let Axiom_dep axr = x.desc in
let dep_id = mk_qualid (mk_idents_of_identifier ~notation:None [] axr.name) in
let meta_id = mk_ident [] "remove_unused:dependency" in
let meta_arg =
match axr.kind with
| Axdep_func -> Why3.Ptree.Mfs dep_id
| Axdep_pred -> Why3.Ptree.Mps dep_id in
[ D.mk_meta meta_id
[Why3.Ptree.Max (mk_qualid [id]); meta_arg ] ]
in
D.mk_prop Decl.Paxiom id body :: meta
| Goal r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [] r.name in
let body = mk_term_of_pred r.def in
[D.mk_prop Decl.Pgoal id body]
| Namespace_declaration r ->
let id = mk_ident_of_symbol node.info.id ~notation:None [] r.name in
let decls = List.concat (List.map mk_declaration r.declarations) in
[D.mk_scope false id decls]
| Exception_declaration r ->
let id =
force_one (conversion_error node.info.id "quantified or empty name in exception declaration")
(mk_idents_of_name ~notation:None [] r.name) in
let pty = Opt.(get (Ty.mk_tuple []) (map mk_pty_of_type r.arg)) in
[D.mk_exn id pty Ity.MaskVisible]
let mk_theory_declaration (node : theory_declaration_id) =
match node.desc with
| Theory_declaration r ->
let name =
let curr_attrs = Opt.to_list (mk_comment_attr r.comment) in
mk_ident_of_symbol node.info.id ~notation:None curr_attrs r.name in
let include_vars = List.map Include_Decl.mk_include_variant r.includes in
let includes, _ =
List.fold_left (fun (l, seen) x ->
if Include_type_set.mem x seen then l, seen
else ((Include_Decl.mk_include_declaration x)::l, Include_type_set.add x seen))
([],Include_type_set.empty)
include_vars in
let declarations = List.concat (List.map mk_declaration r.declarations) in
[name, List.rev_append includes declarations]
let mlw_file nodes =
Modules (List.concat (List.map mk_theory_declaration nodes))
* { 1 JSON auxiliaries }
let pp_path fmt =
let open Format in
let pp_sep _ () = () in
let pp fmt d = fprintf fmt "[%d]" d in
fprintf fmt ".%a" (pp_print_list ~pp_sep pp)
let find_path needle node =
let exception Found of int list in
let rec aux path node =
if node == needle then
raise (Found (List.rev path))
else
match node with
| `Null | `String _ | `Int _ | `Bool _ -> ()
| `List l -> List.iteri (fun i -> aux (i :: path)) l
| _ -> Format.kasprintf failwith "find_path: %a" pp_path (List.rev path) in
try
aux [] node;
raise Not_found
with Found path ->
path
* { 1 Registration of Gnat / JSON parser }
exception Unexpected_json of string * int list
The locations in the generated ptree are unique but useless because they do not
correspond to any concrete syntax . In case of a typing error in the generated
ptree , we instruct the mlw - printer to mark the corresponding node by [ ( * XXX
correspond to any concrete syntax. In case of a typing error in the generated
using [Mlw_printer.set_marker]. The exception [Located_by_marker (file, e)]
is then reported to the user with a hint to the marker in the given file. *)
exception Located_by_marker of string * exn
let gnat_json_format : Env.fformat = "gnat-json"
let gnat_json_file_ext : string = "gnat-json"
let read_channel env path filename c =
let json = Yojson.Safe.from_channel c in
let gnat_file =
let open Gnat_ast in
try From_json.file_from_json json
with From_json.Unexpected_Json (s, node) ->
raise (Unexpected_json (s, find_path node json)) in
Debug printing of intermediate GNAT ast
if Debug.test_flag debug then begin
let out = open_out (filename^".gnat_ast") in
Format.fprintf (Format.formatter_of_out_channel out) "%a@."
Gnat_ast_pretty.pp_file gnat_file
end;
let mlw_file = mlw_file gnat_file.theory_declarations in
let mlw_filename = Strings.remove_suffix ("."^gnat_json_file_ext) filename^".mlw" in
Defer printing of mlw file until after the typing , to set the marker of located
exceptions
exceptions *)
let print_mlw_file ?mark () =
let pp = Mlw_printer.pp_mlw_file ~attr:true in
let pp = match mark with
| None -> pp
| Some (msg, pos) -> Mlw_printer.with_marker ~msg pos pp in
let out = open_out mlw_filename in
Format.fprintf (Format.formatter_of_out_channel out) "%a@." pp mlw_file;
close_out out in
match Typing.type_mlw_file env path filename mlw_file with
| res ->
if Debug.test_flag debug then
print_mlw_file ();
res
| exception Loc.Located (pos, e) ->
The positions in the generated ptree are useless - we set the marker for
printing the mlw file and report that .
printing the mlw file and report that. *)
let msg = Format.asprintf " ERROR %a: @?" Exn_printer.exn_printer e in
print_mlw_file ~mark:(msg, pos) ();
raise (Located_by_marker (mlw_filename, e))
| exception e ->
print_mlw_file ();
raise e
let () =
Env.register_format ~desc:"Gnat@ AST@ in@ JSON@ format"
Pmodule.mlw_language gnat_json_format [gnat_json_file_ext] read_channel
let () =
Exn_printer.register
(fun fmt exn -> match exn with
| Unexpected_json (s, path) ->
Format.fprintf fmt "Unexpected Json for %s at path %a@."
s pp_path path
| Conversion_error r ->
Errors in the conversion from Gnat_ast to Why3 Ptree are reported with their
i d.
id. *)
Format.fprintf fmt "Conversion error for node with ID %d: %s" r.node_id r.message
| Located_by_marker (filename, e) ->
Located errors ( i.e. typing errors ) are reported with an hint on the marker , which
is inserted into the mlw file by the mlw - printer .
is inserted into the mlw file by the mlw-printer. *)
Format.fprintf fmt "File %s, marked by (* ERROR: *)(...):@\n%a"
filename Exn_printer.exn_printer e
| _ -> raise exn)
|
96e651edb8173d87376443e18e4e6fd98ce8cf1c86f104a65a1d5fbb61a8d45d | dgtized/shimmers | rtree_test.cljc | (ns shimmers.algorithm.rtree-test
(:require
[clojure.set :as set]
[clojure.test :as t :refer [deftest is] :include-macros true]
[shimmers.algorithm.rtree :as sut]
[thi.ng.geom.circle :as gc]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.utils :as gu]))
(deftest creation
(is (nil? (sut/create [])))
(let [circles (repeatedly 10 #(gc/circle (rand-int 100) (rand-int 100) (rand-int 10)))
bounds (gu/coll-bounds circles)
tree (sut/create circles)
search (sut/search-intersection tree bounds)
example (first circles)]
(is (= (set circles) (set search)))
(is (= (set circles) (set (sut/search-intersection tree (rect/rect 0 0 100 100)))))
(is (set/subset? (set [example]) (set (sut/search-intersection tree (g/bounds example)))))))
(comment (t/run-tests))
(comment (sut/create (repeatedly 30 #(gc/circle (rand-int 100) (rand-int 100) 1))))
| null | https://raw.githubusercontent.com/dgtized/shimmers/57288e7faa60d9e04e2c515ef93c7016864b0d53/test/shimmers/algorithm/rtree_test.cljc | clojure | (ns shimmers.algorithm.rtree-test
(:require
[clojure.set :as set]
[clojure.test :as t :refer [deftest is] :include-macros true]
[shimmers.algorithm.rtree :as sut]
[thi.ng.geom.circle :as gc]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.utils :as gu]))
(deftest creation
(is (nil? (sut/create [])))
(let [circles (repeatedly 10 #(gc/circle (rand-int 100) (rand-int 100) (rand-int 10)))
bounds (gu/coll-bounds circles)
tree (sut/create circles)
search (sut/search-intersection tree bounds)
example (first circles)]
(is (= (set circles) (set search)))
(is (= (set circles) (set (sut/search-intersection tree (rect/rect 0 0 100 100)))))
(is (set/subset? (set [example]) (set (sut/search-intersection tree (g/bounds example)))))))
(comment (t/run-tests))
(comment (sut/create (repeatedly 30 #(gc/circle (rand-int 100) (rand-int 100) 1))))
|
|
724124cf4d6cd8812e74bc67cfd9abfc50d08e009d3685300e1e09a4204b5c25 | wdebeaum/step | contribute.lisp | ;;;;
;;;; W::contribute
;;;;
(define-words :pos W::v :TEMPL AGENT-AFFECTED-XP-NP-TEMPL
:words (
(W::contribute
(wordfeats (W::morph (:forms (-vb) :nom w::contribution)))
(SENSES
((LF-PARENT ont::donate-give)
(example "He contributed five dollars [to the donation]")
(SEM (F::Cause F::Agentive) (F::Aspect F::bounded) (F::Time-span F::extended))
;(TEMPL AGENT-affected-goal-OPTIONAL-TEMPL)
(TEMPL AGENT-AFFECTED-AFFECTEDR-XP-OPTIONAL-TEMPL)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/a28ce9dc0acd732be9cf762ffdf7cbcb501d4200/src/LexiconManager/Data/new/contribute.lisp | lisp |
W::contribute
(TEMPL AGENT-affected-goal-OPTIONAL-TEMPL) |
(define-words :pos W::v :TEMPL AGENT-AFFECTED-XP-NP-TEMPL
:words (
(W::contribute
(wordfeats (W::morph (:forms (-vb) :nom w::contribution)))
(SENSES
((LF-PARENT ont::donate-give)
(example "He contributed five dollars [to the donation]")
(SEM (F::Cause F::Agentive) (F::Aspect F::bounded) (F::Time-span F::extended))
(TEMPL AGENT-AFFECTED-AFFECTEDR-XP-OPTIONAL-TEMPL)
)
)
)
))
|
cdcce1fbc4756605e7db2305fb07c392780cb68533f53869809fc0457a61e269 | metaocaml/ber-metaocaml | gpr1223.ml | TEST
flags = " -short - paths "
modules = " "
* toplevel
flags = " -short-paths "
modules = "gpr1223_foo.mli gpr1223_bar.mli"
* toplevel
*)
let y = Gpr1223_bar.N.O.T;;
let x = Gpr1223_bar.M.T;;
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-short-paths/gpr1223.ml | ocaml | TEST
flags = " -short - paths "
modules = " "
* toplevel
flags = " -short-paths "
modules = "gpr1223_foo.mli gpr1223_bar.mli"
* toplevel
*)
let y = Gpr1223_bar.N.O.T;;
let x = Gpr1223_bar.M.T;;
|
|
c53509d8223523a104251a9e47851d4d792e26127f4be895f11c12887e5d7203 | monadbobo/ocaml-core | fqueue.mli | * A simple polymorphic functional queue .
Amortized running times assumes that enqueue / dequeue are used sequentially , threading
the changing Fqueue through the calls .
Amortized running times assumes that enqueue/dequeue are used sequentially, threading
the changing Fqueue through the calls. *)
exception Empty
type 'a t with bin_io, sexp
(** test via asserts whether invariants hold *)
val test_invariants : 'a t -> unit
(** The empty queue *)
val empty : 'a t
(** [enqueue t x] returns a queue with adds [x] to the end of [t]. Complexity: O(1) *)
val enqueue : 'a t -> 'a -> 'a t
(** enqueue a single element on the *top* of the queue. Complexity: amortized O(1) *)
val enqueue_top : 'a t -> 'a -> 'a t
(** returns the bottom (most-recently enqueued element). Raises [Empty] if no element is
found. Complexity: O(1) *)
val bot_exn : 'a t -> 'a
(** like [bot_exn], but returns result optionally, without exception. Complexity: O(1) *)
val bot : 'a t -> 'a option
(** Like [bot_exn], except returns top (least-recently enqueued element. Complexity:
O(1) *)
val top_exn : 'a t -> 'a
(** like [top_exn], but returns result optionally, without exception, Complexity: O(1) *)
val top : 'a t -> 'a option
(** [dequeue_exn t] removes and returns the front of [t], raising [Empty] if [t]
is empty. Complexity: amortized O(1)*)
val dequeue_exn : 'a t -> 'a * 'a t
* Like [ dequeue_exn ] , but returns result optionally , without exception . Complexity :
amortized O(1 )
amortized O(1) *)
val dequeue : 'a t -> ('a * 'a t) option
(** Returns version of queue with top element removed. Complexity: amortized O(1) *)
val discard_exn : 'a t -> 'a t
(** [to_list t] returns a list of the elements in [t] in order from least-recently-added
(at the head) to most-recently added (at the tail). Complexity: O(n) *)
val to_list : 'a t -> 'a list
(** complexity: O(1) *)
val length : 'a t -> int
(** complexity: O(1) *)
val is_empty : 'a t -> bool
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/fqueue.mli | ocaml | * test via asserts whether invariants hold
* The empty queue
* [enqueue t x] returns a queue with adds [x] to the end of [t]. Complexity: O(1)
* enqueue a single element on the *top* of the queue. Complexity: amortized O(1)
* returns the bottom (most-recently enqueued element). Raises [Empty] if no element is
found. Complexity: O(1)
* like [bot_exn], but returns result optionally, without exception. Complexity: O(1)
* Like [bot_exn], except returns top (least-recently enqueued element. Complexity:
O(1)
* like [top_exn], but returns result optionally, without exception, Complexity: O(1)
* [dequeue_exn t] removes and returns the front of [t], raising [Empty] if [t]
is empty. Complexity: amortized O(1)
* Returns version of queue with top element removed. Complexity: amortized O(1)
* [to_list t] returns a list of the elements in [t] in order from least-recently-added
(at the head) to most-recently added (at the tail). Complexity: O(n)
* complexity: O(1)
* complexity: O(1) | * A simple polymorphic functional queue .
Amortized running times assumes that enqueue / dequeue are used sequentially , threading
the changing Fqueue through the calls .
Amortized running times assumes that enqueue/dequeue are used sequentially, threading
the changing Fqueue through the calls. *)
exception Empty
type 'a t with bin_io, sexp
val test_invariants : 'a t -> unit
val empty : 'a t
val enqueue : 'a t -> 'a -> 'a t
val enqueue_top : 'a t -> 'a -> 'a t
val bot_exn : 'a t -> 'a
val bot : 'a t -> 'a option
val top_exn : 'a t -> 'a
val top : 'a t -> 'a option
val dequeue_exn : 'a t -> 'a * 'a t
* Like [ dequeue_exn ] , but returns result optionally , without exception . Complexity :
amortized O(1 )
amortized O(1) *)
val dequeue : 'a t -> ('a * 'a t) option
val discard_exn : 'a t -> 'a t
val to_list : 'a t -> 'a list
val length : 'a t -> int
val is_empty : 'a t -> bool
|
1b19b39f097f358740bdba0dce3f218c590a9bbb301d493b8fbde3a7537a90e6 | beala/symbolic | Util.hs | module Util where
import Foundation
import qualified Data.Bits as B
wordToInt :: Word32 -> Int
wordToInt = fromIntegral . toInteger
wordToSignedInt :: Word32 -> Int
wordToSignedInt w =
if isNegative w then
(-(wordToInt (twosComplement w)))
else
wordToInt w
wordToBool :: Word32 -> Bool
wordToBool 0 = False
wordToBool _ = True
boolToWord :: Bool -> Word32
boolToWord True = 1
boolToWord False = 0
twosComplement :: Word32 -> Word32
twosComplement i = 1 + B.complement i
isNegative :: Word32 -> Bool
isNegative w = B.testBit w 31
valName :: Int -> String
valName i = "val_" <> (show i)
| null | https://raw.githubusercontent.com/beala/symbolic/439bd8670d9e337a7d6a566b3af9d80ec239eafe/src/Util.hs | haskell | module Util where
import Foundation
import qualified Data.Bits as B
wordToInt :: Word32 -> Int
wordToInt = fromIntegral . toInteger
wordToSignedInt :: Word32 -> Int
wordToSignedInt w =
if isNegative w then
(-(wordToInt (twosComplement w)))
else
wordToInt w
wordToBool :: Word32 -> Bool
wordToBool 0 = False
wordToBool _ = True
boolToWord :: Bool -> Word32
boolToWord True = 1
boolToWord False = 0
twosComplement :: Word32 -> Word32
twosComplement i = 1 + B.complement i
isNegative :: Word32 -> Bool
isNegative w = B.testBit w 31
valName :: Int -> String
valName i = "val_" <> (show i)
|
|
cf77581e5b186107a1f913f696ce788df48d555b2757b02029b5a2e911b43930 | realworldocaml/book | mode.ml | open! Stdune
type t =
| Byte
| Native
let equal x y =
match (x, y) with
| Byte, Byte -> true
| Byte, _ | _, Byte -> false
| Native, Native -> true
let compare x y =
match (x, y) with
| Byte, Byte -> Eq
| Byte, _ -> Lt
| _, Byte -> Gt
| Native, Native -> Eq
let all = [ Byte; Native ]
let decode =
let open Dune_sexp.Decoder in
enum [ ("byte", Byte); ("native", Native) ]
let choose byte native = function
| Byte -> byte
| Native -> native
let to_string = choose "byte" "native"
let encode t = Dune_sexp.Encoder.string (to_string t)
let to_dyn t = Dyn.variant (to_string t) []
let compiled_unit_ext = choose (Cm_kind.ext Cmo) (Cm_kind.ext Cmx)
let compiled_lib_ext = choose ".cma" ".cmxa"
let plugin_ext = choose ".cma" ".cmxs"
let variant = choose Variant.byte Variant.native
let cm_kind = choose Cm_kind.Cmo Cmx
let exe_ext = choose ".bc" ".exe"
let of_cm_kind : Cm_kind.t -> t = function
| Cmi | Cmo -> Byte
| Cmx -> Native
module Dict = struct
let mode_equal = equal
type 'a t =
{ byte : 'a
; native : 'a
}
let equal f { byte; native } t = f byte t.byte && f native t.native
let for_all { byte; native } ~f = f byte && f native
let to_dyn to_dyn { byte; native } =
let open Dyn in
record [ ("byte", to_dyn byte); ("native", to_dyn native) ]
let get t = function
| Byte -> t.byte
| Native -> t.native
let of_func f = { byte = f ~mode:Byte; native = f ~mode:Native }
let map2 a b ~f = { byte = f a.byte b.byte; native = f a.native b.native }
let map t ~f = { byte = f t.byte; native = f t.native }
let mapi t ~f = { byte = f Byte t.byte; native = f Native t.native }
let iteri t ~f =
f Byte t.byte;
f Native t.native
let make_both x = { byte = x; native = x }
let make ~byte ~native = { byte; native }
module Set = struct
type nonrec t = bool t
let equal = equal Bool.equal
let to_dyn { byte; native } =
let open Dyn in
record [ ("byte", bool byte); ("native", bool native) ]
let all = { byte = true; native = true }
let to_list t =
let l = [] in
let l = if t.native then Native :: l else l in
let l = if t.byte then Byte :: l else l in
l
let of_list l =
{ byte = List.mem l Byte ~equal:mode_equal
; native = List.mem l Native ~equal:mode_equal
}
let encode t = List.map ~f:encode (to_list t)
let is_empty t = not (t.byte || t.native)
let iter_concurrently t ~f =
let open Memo.O in
let+ () = Memo.when_ t.byte (fun () -> f Byte)
and+ () = Memo.when_ t.native (fun () -> f Native) in
()
end
module List = struct
type nonrec 'a t = 'a list t
let empty = { byte = []; native = [] }
let encode f { byte; native } =
let open Dune_sexp.Encoder in
record_fields [ field_l "byte" f byte; field_l "native" f native ]
let decode f =
let open Dune_sexp.Decoder in
fields
(let+ byte = field ~default:[] "byte" (repeat f)
and+ native = field ~default:[] "native" (repeat f) in
{ byte; native })
end
end
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/ocaml/mode.ml | ocaml | open! Stdune
type t =
| Byte
| Native
let equal x y =
match (x, y) with
| Byte, Byte -> true
| Byte, _ | _, Byte -> false
| Native, Native -> true
let compare x y =
match (x, y) with
| Byte, Byte -> Eq
| Byte, _ -> Lt
| _, Byte -> Gt
| Native, Native -> Eq
let all = [ Byte; Native ]
let decode =
let open Dune_sexp.Decoder in
enum [ ("byte", Byte); ("native", Native) ]
let choose byte native = function
| Byte -> byte
| Native -> native
let to_string = choose "byte" "native"
let encode t = Dune_sexp.Encoder.string (to_string t)
let to_dyn t = Dyn.variant (to_string t) []
let compiled_unit_ext = choose (Cm_kind.ext Cmo) (Cm_kind.ext Cmx)
let compiled_lib_ext = choose ".cma" ".cmxa"
let plugin_ext = choose ".cma" ".cmxs"
let variant = choose Variant.byte Variant.native
let cm_kind = choose Cm_kind.Cmo Cmx
let exe_ext = choose ".bc" ".exe"
let of_cm_kind : Cm_kind.t -> t = function
| Cmi | Cmo -> Byte
| Cmx -> Native
module Dict = struct
let mode_equal = equal
type 'a t =
{ byte : 'a
; native : 'a
}
let equal f { byte; native } t = f byte t.byte && f native t.native
let for_all { byte; native } ~f = f byte && f native
let to_dyn to_dyn { byte; native } =
let open Dyn in
record [ ("byte", to_dyn byte); ("native", to_dyn native) ]
let get t = function
| Byte -> t.byte
| Native -> t.native
let of_func f = { byte = f ~mode:Byte; native = f ~mode:Native }
let map2 a b ~f = { byte = f a.byte b.byte; native = f a.native b.native }
let map t ~f = { byte = f t.byte; native = f t.native }
let mapi t ~f = { byte = f Byte t.byte; native = f Native t.native }
let iteri t ~f =
f Byte t.byte;
f Native t.native
let make_both x = { byte = x; native = x }
let make ~byte ~native = { byte; native }
module Set = struct
type nonrec t = bool t
let equal = equal Bool.equal
let to_dyn { byte; native } =
let open Dyn in
record [ ("byte", bool byte); ("native", bool native) ]
let all = { byte = true; native = true }
let to_list t =
let l = [] in
let l = if t.native then Native :: l else l in
let l = if t.byte then Byte :: l else l in
l
let of_list l =
{ byte = List.mem l Byte ~equal:mode_equal
; native = List.mem l Native ~equal:mode_equal
}
let encode t = List.map ~f:encode (to_list t)
let is_empty t = not (t.byte || t.native)
let iter_concurrently t ~f =
let open Memo.O in
let+ () = Memo.when_ t.byte (fun () -> f Byte)
and+ () = Memo.when_ t.native (fun () -> f Native) in
()
end
module List = struct
type nonrec 'a t = 'a list t
let empty = { byte = []; native = [] }
let encode f { byte; native } =
let open Dune_sexp.Encoder in
record_fields [ field_l "byte" f byte; field_l "native" f native ]
let decode f =
let open Dune_sexp.Decoder in
fields
(let+ byte = field ~default:[] "byte" (repeat f)
and+ native = field ~default:[] "native" (repeat f) in
{ byte; native })
end
end
|
|
4ca35565b44c7660e4dc578dfcf1b0db31e9a0e3e8bfba273af0e76b4d40757d | frenetic-lang/netcore-1.0 | Query1.hs | module Query1 where
import Frenetic.NetCore
import System.IO (hFlush, stdout)
main addr = do
let f (sw, n) = do
putStrLn ("Counter is: " ++ show n)
hFlush stdout
let pol = Any ==> [Forward AllPorts unmodified] <+>
Any ==> [CountPackets 0 1000 f]
controller addr pol
| null | https://raw.githubusercontent.com/frenetic-lang/netcore-1.0/976b08b740027e8ed19f2d55b1e77f663bee6f02/examples/Query1.hs | haskell | module Query1 where
import Frenetic.NetCore
import System.IO (hFlush, stdout)
main addr = do
let f (sw, n) = do
putStrLn ("Counter is: " ++ show n)
hFlush stdout
let pol = Any ==> [Forward AllPorts unmodified] <+>
Any ==> [CountPackets 0 1000 f]
controller addr pol
|
|
491a45a57e95cf3e8742d6d3a16ecceb4413c125e7ef94e26e69aa30d4284346 | juxt/shop | ajax.cljs | (ns tutorial.vent.frontend.ajax
(:require
[cljs.reader :refer [read-string]]))
(defmulti page-fetch :name)
(defmethod page-fetch :default
[_]
nil)
(defn fetch-page
[page state*]
(some-> (page-fetch page)
(.then (fn [data] (.text data)))
(.then (fn [text] (read-string text)))
(.then (fn [x] (swap! state*
(fn [state]
(if (= page (:page state))
(assoc-in state [:page :data] x)
state)))))))
| null | https://raw.githubusercontent.com/juxt/shop/c23fc55bca1852bfbabb681a72debc12373c3a36/examples/tutorial.vent/src/tutorial/vent/frontend/ajax.cljs | clojure | (ns tutorial.vent.frontend.ajax
(:require
[cljs.reader :refer [read-string]]))
(defmulti page-fetch :name)
(defmethod page-fetch :default
[_]
nil)
(defn fetch-page
[page state*]
(some-> (page-fetch page)
(.then (fn [data] (.text data)))
(.then (fn [text] (read-string text)))
(.then (fn [x] (swap! state*
(fn [state]
(if (= page (:page state))
(assoc-in state [:page :data] x)
state)))))))
|
|
0c0791796c04091463fb054b5f7943c2fb0f3005523c3e9fc3eeb64a31c4e587 | gafiatulin/codewars | SJF.hs | Scheduling ( Shortest Job First or SJF )
-- /
module Codewars.Kata.SJF where
import Data.List (sort)
type CC = Integer
type Job = CC
type Index = Int
sjf :: [Job] -> Index -> CC
sjf xs i = sum . (\(before, after) -> (fst . head $ after) : map fst before ) . span ((/=i) . snd) . sort . zip xs $ [0..]
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/SJF.hs | haskell | / | Scheduling ( Shortest Job First or SJF )
module Codewars.Kata.SJF where
import Data.List (sort)
type CC = Integer
type Job = CC
type Index = Int
sjf :: [Job] -> Index -> CC
sjf xs i = sum . (\(before, after) -> (fst . head $ after) : map fst before ) . span ((/=i) . snd) . sort . zip xs $ [0..]
|
21fa68df73795a135406979717d5ea00f322227436dcca02cd3275fffd29254f | MLstate/opalang | qmlTracker.ml |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
(* THIS FILE HAS A DOCUMENTED MLI *)
(* depends *)
module Format = Base.Format
(* refactoring in progress *)
(* shorthands *)
module Q = QmlAst
let contains_tracker e =
QmlAstWalk.Expr.exists
(function
| Q.Directive (_, `tracker _, _, _) -> true
| _ -> false) e
module Printer =
struct
let code fmt code =
Format.fprintf fmt "/* printer: --print code */@\n@\n" ;
QmlPrint.pp#code fmt code ;
Format.fprintf fmt "@."
let light_ident fmt code =
Format.fprintf fmt "/* printer: --print light_ident */@\n@\n" ;
QmlPrint.pp_light_ident#code fmt code ;
Format.fprintf fmt "@."
let very_light_ident fmt code =
Format.fprintf fmt "/* printer: --print very_light_ident */@\n@\n" ;
QmlPrint.pp_very_light_ident#code fmt code ;
Format.fprintf fmt "@."
let code_with_type fmt annotmap code =
Format.fprintf fmt "/* printer: --print code_with_type */@\n@\n" ;
(new QmlPrint.printer_with_type annotmap)#code fmt code ;
Format.fprintf fmt "@."
let code_for_ei fmt annotmap code =
Format.fprintf fmt "/* printer: --print code_for_ei */@\n@\n" ;
(new QmlPrint.printer_for_ei annotmap)#code fmt code ;
Format.fprintf fmt "@."
< ! > beware uses this formating .
Do not change it or please update opatrack
Do not change it or please update opatrack *)
let size fmt code =
let i =
QmlAstWalk.CodeExpr.fold
(QmlAstWalk.Expr.fold (fun acc _ -> acc + 1)) 0 code in
Format.fprintf fmt
"%d declarations@\n%d nodes@." (List.length code) i
let declaration fmt code =
Format.fprintf fmt "/* printer: --print declaration */@\n@\n" ;
QmlPrint.pp_declaration#code fmt code ;
Format.fprintf fmt "@."
let annotation fmt code =
Format.fprintf fmt "/* printer: --print annotation */@\n@\n";
QmlPrint.pp_annotation#code fmt code;
Format.fprintf fmt "@."
(* ************************************************************************ *)
* { b } : Printer for position in source code .
{ b Visibility } : Not exported outside this module .
{b Visibility} : Not exported outside this module. *)
(* ************************************************************************ *)
let position fmt code =
Format.fprintf fmt "/* printer: --print position */@\n@\n";
QmlPrint.pp_position#code fmt code;
Format.fprintf fmt "@."
let tracked fmt code =
Format.fprintf fmt "/* printer: --print tracked */" ;
let bind kw rec_ (s, e) =
let val_ = if !kw then (kw := false; "val"^rec_) else "and" in
Format.fprintf fmt "@\n@\n@\n@\n@\n/* %s %s */@\n@\n%s %s =@ %a@\n"
val_ (Ident.stident s) val_ (Ident.stident s) QmlPrint.pp#expr e
in
let is_tracked = List.exists (fun (_, e) -> contains_tracker e) in
List.iter
(function
| Q.NewVal (_, b) ->
if is_tracked b then List.iter (bind (ref true) "") b
| Q.NewValRec (_, b) ->
if is_tracked b then List.iter (bind (ref true) " rec") b
| _ -> ()
) code;
Format.fprintf fmt "@."
let gamma fmt gamma =
Format.fprintf fmt "/* printer: --print gamma*/@.";
QmlTypes.Env.pp fmt gamma;
Format.fprintf fmt "@."
end
let define = PassHandler.define_printer
let code_id = define "code"
let light_ident_id = define "light_ident"
let very_light_ident_id = define "very_light_ident"
let with_type_id = define "with_type"
let for_ei_id = define "for_ei"
let size_id = define "size"
let declaration_id = define "declaration"
let annotation_id = define "annotation"
let position_id = define "position"
let tracked_id = define "tracked"
let gamma_id = define "gamma"
let stdlib_gamma_id = define "stdlib_gamma"
let printers extract _ =
let make_code fct fmt env =
let _, _, code = extract env in
fct fmt code in
let make_ac fct fmt env =
let annotmap, _, code = extract env in
fct fmt annotmap code in
let make_gamma fct fmt env =
let _, (gamma, _), _ = extract env in
fct fmt gamma in
let make_stdlib_gamma fct fmt env =
let _, (_, stdlib_gamma), _ = extract env in
fct fmt stdlib_gamma in
[
code_id, make_code Printer.code ;
light_ident_id, make_code Printer.light_ident ;
very_light_ident_id, make_code Printer.very_light_ident ;
declaration_id, make_code Printer.declaration ;
annotation_id, make_code Printer.annotation;
(* Source code positions printer registered. *)
position_id, make_code Printer.position;
size_id, make_code Printer.size ;
with_type_id, make_ac Printer.code_with_type;
for_ei_id, make_ac Printer.code_for_ei;
gamma_id, make_gamma Printer.gamma;
stdlib_gamma_id, make_stdlib_gamma Printer.gamma;
(* waiting for flexibility in passhander options *)
(* tracked_id, make Printer.tracked ; *)
]
module Tracker =
struct
let pp_print_expr = QmlPrint.pp#expr
let pp_print_code_elt = QmlPrint.pp#code_elt
let directive iter =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter.PassTracker.track (PassTracker.filename t) pp_print_expr e
| _ -> ()))
(* We keep the full code_elt for each val
it is a duplication, but it speed up searching
anyway, the folder _tracks can be cleaned *)
let val_ iter = List.iter
(function
| Q.NewVal (_, binds)
| ( Q.NewValRec (_, binds) ) as elt -> List.iter
(fun (s, _) ->
let filename = Ident.stident s in
iter.PassTracker.track filename pp_print_code_elt elt
) binds
| _ -> ())
end
let define = PassHandler.define_tracker
let directive_id = define "track"
let val_id = define "val"
let trackers extract _ =
let make fct fmt env = fct fmt (extract env) in
[
directive_id, make Tracker.directive ;
val_id, make Tracker.val_ ;
]
(* iterator on `track directive with something else that expr *)
module WIP =
struct
other iterators : wip
type ('tracked, 'env) iter_tracker =
( 'env -> QmlAst.code ) ->
(PassTracker.t -> 'tracked PassHandler.printer -> 'tracked -> unit) -> 'env -> unit
let pp_print_expr = QmlPrint.pp#expr
let pp_print_annot fmt annot =
Format.pp_print_string fmt (Annot.to_string annot)
let pp_print_ty = QmlPrint.pp#ty
let iter_tracker extract iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter.PassTracker.track (PassTracker.filename t) pp_print_expr e
| _ -> ()))
(extract env)
let iter_annot_tracker extract iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter t pp_print_annot (Q.QAnnot.expr e)
| _ -> () ))
(extract env)
let iter_ty_tracker extract_annotmap extract_code iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> (
let annot = Q.QAnnot.expr e in
match QmlAnnotMap.find_ty_opt annot (extract_annotmap env) with
| Some ty -> iter t pp_print_ty ty
| None -> iter t
(fun fmt _ ->
Format.fprintf fmt "Annot Not Found: %a. The expr is:@\n%a"
pp_print_annot annot pp_print_expr e)
(QmlAst.TypeConst QmlAst.TyNull)
)
| _ -> () )
)
(extract_code env)
end
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/libqmlcompil/qmlTracker.ml | ocaml | THIS FILE HAS A DOCUMENTED MLI
depends
refactoring in progress
shorthands
************************************************************************
************************************************************************
Source code positions printer registered.
waiting for flexibility in passhander options
tracked_id, make Printer.tracked ;
We keep the full code_elt for each val
it is a duplication, but it speed up searching
anyway, the folder _tracks can be cleaned
iterator on `track directive with something else that expr |
Copyright © 2011 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
module Format = Base.Format
module Q = QmlAst
let contains_tracker e =
QmlAstWalk.Expr.exists
(function
| Q.Directive (_, `tracker _, _, _) -> true
| _ -> false) e
module Printer =
struct
let code fmt code =
Format.fprintf fmt "/* printer: --print code */@\n@\n" ;
QmlPrint.pp#code fmt code ;
Format.fprintf fmt "@."
let light_ident fmt code =
Format.fprintf fmt "/* printer: --print light_ident */@\n@\n" ;
QmlPrint.pp_light_ident#code fmt code ;
Format.fprintf fmt "@."
let very_light_ident fmt code =
Format.fprintf fmt "/* printer: --print very_light_ident */@\n@\n" ;
QmlPrint.pp_very_light_ident#code fmt code ;
Format.fprintf fmt "@."
let code_with_type fmt annotmap code =
Format.fprintf fmt "/* printer: --print code_with_type */@\n@\n" ;
(new QmlPrint.printer_with_type annotmap)#code fmt code ;
Format.fprintf fmt "@."
let code_for_ei fmt annotmap code =
Format.fprintf fmt "/* printer: --print code_for_ei */@\n@\n" ;
(new QmlPrint.printer_for_ei annotmap)#code fmt code ;
Format.fprintf fmt "@."
< ! > beware uses this formating .
Do not change it or please update opatrack
Do not change it or please update opatrack *)
let size fmt code =
let i =
QmlAstWalk.CodeExpr.fold
(QmlAstWalk.Expr.fold (fun acc _ -> acc + 1)) 0 code in
Format.fprintf fmt
"%d declarations@\n%d nodes@." (List.length code) i
let declaration fmt code =
Format.fprintf fmt "/* printer: --print declaration */@\n@\n" ;
QmlPrint.pp_declaration#code fmt code ;
Format.fprintf fmt "@."
let annotation fmt code =
Format.fprintf fmt "/* printer: --print annotation */@\n@\n";
QmlPrint.pp_annotation#code fmt code;
Format.fprintf fmt "@."
* { b } : Printer for position in source code .
{ b Visibility } : Not exported outside this module .
{b Visibility} : Not exported outside this module. *)
let position fmt code =
Format.fprintf fmt "/* printer: --print position */@\n@\n";
QmlPrint.pp_position#code fmt code;
Format.fprintf fmt "@."
let tracked fmt code =
Format.fprintf fmt "/* printer: --print tracked */" ;
let bind kw rec_ (s, e) =
let val_ = if !kw then (kw := false; "val"^rec_) else "and" in
Format.fprintf fmt "@\n@\n@\n@\n@\n/* %s %s */@\n@\n%s %s =@ %a@\n"
val_ (Ident.stident s) val_ (Ident.stident s) QmlPrint.pp#expr e
in
let is_tracked = List.exists (fun (_, e) -> contains_tracker e) in
List.iter
(function
| Q.NewVal (_, b) ->
if is_tracked b then List.iter (bind (ref true) "") b
| Q.NewValRec (_, b) ->
if is_tracked b then List.iter (bind (ref true) " rec") b
| _ -> ()
) code;
Format.fprintf fmt "@."
let gamma fmt gamma =
Format.fprintf fmt "/* printer: --print gamma*/@.";
QmlTypes.Env.pp fmt gamma;
Format.fprintf fmt "@."
end
let define = PassHandler.define_printer
let code_id = define "code"
let light_ident_id = define "light_ident"
let very_light_ident_id = define "very_light_ident"
let with_type_id = define "with_type"
let for_ei_id = define "for_ei"
let size_id = define "size"
let declaration_id = define "declaration"
let annotation_id = define "annotation"
let position_id = define "position"
let tracked_id = define "tracked"
let gamma_id = define "gamma"
let stdlib_gamma_id = define "stdlib_gamma"
let printers extract _ =
let make_code fct fmt env =
let _, _, code = extract env in
fct fmt code in
let make_ac fct fmt env =
let annotmap, _, code = extract env in
fct fmt annotmap code in
let make_gamma fct fmt env =
let _, (gamma, _), _ = extract env in
fct fmt gamma in
let make_stdlib_gamma fct fmt env =
let _, (_, stdlib_gamma), _ = extract env in
fct fmt stdlib_gamma in
[
code_id, make_code Printer.code ;
light_ident_id, make_code Printer.light_ident ;
very_light_ident_id, make_code Printer.very_light_ident ;
declaration_id, make_code Printer.declaration ;
annotation_id, make_code Printer.annotation;
position_id, make_code Printer.position;
size_id, make_code Printer.size ;
with_type_id, make_ac Printer.code_with_type;
for_ei_id, make_ac Printer.code_for_ei;
gamma_id, make_gamma Printer.gamma;
stdlib_gamma_id, make_stdlib_gamma Printer.gamma;
]
module Tracker =
struct
let pp_print_expr = QmlPrint.pp#expr
let pp_print_code_elt = QmlPrint.pp#code_elt
let directive iter =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter.PassTracker.track (PassTracker.filename t) pp_print_expr e
| _ -> ()))
let val_ iter = List.iter
(function
| Q.NewVal (_, binds)
| ( Q.NewValRec (_, binds) ) as elt -> List.iter
(fun (s, _) ->
let filename = Ident.stident s in
iter.PassTracker.track filename pp_print_code_elt elt
) binds
| _ -> ())
end
let define = PassHandler.define_tracker
let directive_id = define "track"
let val_id = define "val"
let trackers extract _ =
let make fct fmt env = fct fmt (extract env) in
[
directive_id, make Tracker.directive ;
val_id, make Tracker.val_ ;
]
module WIP =
struct
other iterators : wip
type ('tracked, 'env) iter_tracker =
( 'env -> QmlAst.code ) ->
(PassTracker.t -> 'tracked PassHandler.printer -> 'tracked -> unit) -> 'env -> unit
let pp_print_expr = QmlPrint.pp#expr
let pp_print_annot fmt annot =
Format.pp_print_string fmt (Annot.to_string annot)
let pp_print_ty = QmlPrint.pp#ty
let iter_tracker extract iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter.PassTracker.track (PassTracker.filename t) pp_print_expr e
| _ -> ()))
(extract env)
let iter_annot_tracker extract iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> iter t pp_print_annot (Q.QAnnot.expr e)
| _ -> () ))
(extract env)
let iter_ty_tracker extract_annotmap extract_code iter env =
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (_, `tracker t, [e], _) -> (
let annot = Q.QAnnot.expr e in
match QmlAnnotMap.find_ty_opt annot (extract_annotmap env) with
| Some ty -> iter t pp_print_ty ty
| None -> iter t
(fun fmt _ ->
Format.fprintf fmt "Annot Not Found: %a. The expr is:@\n%a"
pp_print_annot annot pp_print_expr e)
(QmlAst.TypeConst QmlAst.TyNull)
)
| _ -> () )
)
(extract_code env)
end
|
6cea417d6d29599a5bedb903e961b850ed9d784b57cf680fabb6fef40cf6ba74 | mwand/eopl3 | environments.scm | (module environments (lib "eopl.ss" "eopl")
(require "data-structures.scm")
(provide init-env empty-env extend-env apply-env)
;;;;;;;;;;;;;;;; initial environment ;;;;;;;;;;;;;;;;
;; init-env : () -> Env
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
;; (init-env) builds an environment in which i is bound to the
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
;;;;;;;;;;;;;;;; environment constructors and observers ;;;;;;;;;;;;;;;;
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(eopl:error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec* (p-names b-vars p-bodies saved-env)
(cond
((location search-sym p-names)
=> (lambda (n)
(proc-val
(procedure
(list-ref b-vars n)
(list-ref p-bodies n)
env))))
(else (apply-env saved-env search-sym)))))))
;; location : Sym * Listof(Sym) -> Maybe(Int)
( location sym syms ) returns the location of sym in syms or # f is
sym is not in syms . We can specify this as follows :
if ( )
then ( list - ref ( location sym syms ) ) = sym
;; else (location sym syms) = #f
(define location
(lambda (sym syms)
(cond
((null? syms) #f)
((eqv? sym (car syms)) 0)
((location sym (cdr syms))
=> (lambda (n)
(+ n 1)))
(else #f))))
) | null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter4/explicit-refs/environments.scm | scheme | initial environment ;;;;;;;;;;;;;;;;
init-env : () -> Env
(init-env) builds an environment in which i is bound to the
environment constructors and observers ;;;;;;;;;;;;;;;;
location : Sym * Listof(Sym) -> Maybe(Int)
else (location sym syms) = #f | (module environments (lib "eopl.ss" "eopl")
(require "data-structures.scm")
(provide init-env empty-env extend-env apply-env)
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(eopl:error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec* (p-names b-vars p-bodies saved-env)
(cond
((location search-sym p-names)
=> (lambda (n)
(proc-val
(procedure
(list-ref b-vars n)
(list-ref p-bodies n)
env))))
(else (apply-env saved-env search-sym)))))))
( location sym syms ) returns the location of sym in syms or # f is
sym is not in syms . We can specify this as follows :
if ( )
then ( list - ref ( location sym syms ) ) = sym
(define location
(lambda (sym syms)
(cond
((null? syms) #f)
((eqv? sym (car syms)) 0)
((location sym (cdr syms))
=> (lambda (n)
(+ n 1)))
(else #f))))
) |
1eff0b578a0da74a0673196f9837ffddf891891948dcfb01dc6dc23d36318c1a | AccelerateHS/accelerate | Either.hs | # LANGUAGE GADTs #
{-# LANGUAGE PatternSynonyms #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
-- |
-- Module : Data.Array.Accelerate.Pattern.Either
Copyright : [ 2018 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.Pattern.Either (
Either, pattern Left_, pattern Right_,
) where
import Data.Array.Accelerate.Pattern.TH
mkPattern ''Either
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate/63e53be22aef32cd0b3b6f108e637716a92b72dc/src/Data/Array/Accelerate/Pattern/Either.hs | haskell | # LANGUAGE PatternSynonyms #
|
Module : Data.Array.Accelerate.Pattern.Either
License : BSD3
Stability : experimental
| # LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
Copyright : [ 2018 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.Pattern.Either (
Either, pattern Left_, pattern Right_,
) where
import Data.Array.Accelerate.Pattern.TH
mkPattern ''Either
|
392da8204cba64119a2f0258f668ae0f809d195253c3becc47705605fff67157 | ashinn/chibi-scheme | stty.scm | Copyright ( c ) 2011 . All rights reserved .
;; BSD-style license:
> A high - level interface to stty and ioctl .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; symbolic representation of attributes
(define stty-lookup (make-hash-table eq?))
(for-each
(lambda (c) (hash-table-set! stty-lookup (car c) (cdr c)))
ripped from the stty man page , then trimmed down to what seemed
;; available on most systems
`(;; characters
( dsusp char , VDSUSP ) ; will send a terminal stop signal
CHAR will send an EOF ( terminate input )
(eol char ,VEOL) ; CHAR will end the line
alternate for ending the line
(erase char ,VERASE) ; CHAR will erase the last character typed
(intr char ,VINTR) ; CHAR will send an interrupt signal
(kill char ,VKILL) ; CHAR will erase the current line
(lnext char ,VLNEXT) ; CHAR will enter the next character quoted
(quit char ,VQUIT) ; CHAR will send a quit signal
(rprnt char ,VREPRINT) ; CHAR will redraw the current line
(start char ,VSTART) ; CHAR will restart output after stopping it
(stop char ,VSTOP) ; CHAR will stop the output
(susp char ,VSUSP) ; CHAR will send a terminal stop signal
(werase char ,VWERASE) ; CHAR will erase the last word typed
;; special settings
(cols special #f) ; tell the kernel that the terminal has N columns
(columns special #f) ; same as cols N
(ispeed special #f) ; set the input speed to N
(line special #f) ; use line discipline N
(min special #f) ; with -icanon, set N characters minimum for a completed read
(ospeed special #f) ; set the output speed to N
(rows special #f) ; tell the kernel that the terminal has N rows
(size special #f) ; print the number of rows and columns according to the kernel
(speed special #f) ; print the terminal speed
with -icanon , set read timeout of N tenths of a second
;; control settings
(clocal control ,CLOCAL) ; disable modem control signals
(cread control ,CREAD) ; allow input to be received
enable RTS / CTS handshaking
set character size to 5 bits
set character size to 6 bits
set character size to 7 bits
set character size to 8 bits
use two stop bits per character ( one with ` - ' )
(hup control ,HUPCL) ; send a hangup signal when the last process closes the tty
(hupcl control ,HUPCL) ; same as [-]hup
(parenb control ,PARENB) ; generate parity bit in output and expect parity bit in input
(parodd control ,PARODD) ; set odd parity (even with `-')
;; input settings
(brkint input ,BRKINT) ; breaks cause an interrupt signal
(icrnl input ,ICRNL) ; translate carriage return to newline
(ignbrk input ,IGNBRK) ; ignore break characters
(igncr input ,IGNCR) ; ignore carriage return
(ignpar input ,IGNPAR) ; ignore characters with parity errors
(imaxbel input ,IMAXBEL) ; * beep and do not flush a full input buffer on a character
(inlcr input ,INLCR) ; translate newline to carriage return
(inpck input ,INPCK) ; enable input parity checking
clear high ( 8th ) bit of input characters
;;(iuclc input ,IUCLC) ; * translate uppercase characters to lowercase
(ixany input ,IXANY) ; * let any character restart output, not only start character
(ixoff input ,IXOFF) ; enable sending of start/stop characters
enable / XOFF flow control
mark parity errors ( with a 255 - 0 - character sequence )
(tandem input ,IXOFF) ; same as [-]ixoff
;; output settings
( output , ) ; backspace delay style , N in [ 0 .. 1 ]
( bs1 output , BS1 ) ; backspace delay style , N in [ 0 .. 1 ]
( cr0 output , CR0 ) ; carriage return delay style , N in [ 0 .. 3 ]
( cr1 output , CR1 ) ; carriage return delay style , N in [ 0 .. 3 ]
( cr2 output , CR2 ) ; carriage return delay style , N in [ 0 .. 3 ]
( cr3 output , CR3 ) ; carriage return delay style , N in [ 0 .. 3 ]
( ff0 output , FF0 ) ; form feed delay style , N in [ 0 .. 1 ]
( ff1 output , ) ; form feed delay style , N in [ 0 .. 1 ]
( nl0 output , NL0 ) ; newline delay style , N in [ 0 .. 1 ]
( nl1 output , NL1 ) ; newline delay style , N in [ 0 .. 1 ]
(ocrnl output ,OCRNL) ; translate carriage return to newline
;;(ofdel output ,OFDEL) ; use delete characters for fill instead of null characters
( ofill output , OFILL ) ; use fill ( padding ) characters instead of timing for delays
;;(olcuc output ,OLCUC) ; translate lowercase characters to uppercase
(onlcr output ,ONLCR) ; translate newline to carriage return-newline
(onlret output ,ONLRET) ; newline performs a carriage return
do not print carriage returns in the first column
(opost output ,OPOST) ; postprocess output
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
same as
;;(-tabs output #f) ; same as tab3
( vt0 output , ) ; vertical tab delay style , N in [ 0 .. 1 ]
( vt1 output , VT1 ) ; vertical tab delay style , N in [ 0 .. 1 ]
;; local settings
(crterase local ,ECHOE) ; echo erase characters as backspace-space-backspace
(crtkill local ,ECHOKE) ; kill all line by obeying the echoprt and echoe settings
;;(-crtkill local #f) ; kill all line by obeying the echoctl and echok settings
(ctlecho local ,ECHOCTL) ; echo control characters in hat notation (`^c')
(echo local ,ECHO) ; echo input characters
(echoctl local ,ECHOCTL) ; same as [-]ctlecho
same as [ -]crterase
( echok local , ECHOK ) ; echo a newline after a kill character
(echoke local ,ECHOKE) ; same as [-]crtkill
(echonl local ,ECHONL) ; echo newline even if not echoing other characters
;;(echoprt local ,ECHOPRT) ; echo erased characters backward, between `\' and '/'
enable erase , kill , werase , and rprnt special characters
( iexten local , IEXTEN ) ; enable non - POSIX special characters
(isig local ,ISIG) ; enable interrupt, quit, and suspend special characters
(noflsh local ,NOFLSH) ; disable flushing after interrupt and quit special characters
( prterase local , ECHOPRT ) ; same as [ -]echoprt
(tostop local ,TOSTOP) ; stop background jobs that try to write to the terminal
( xcase local , XCASE ) ; with icanon , escape with ` \ ' for uppercase characters
;; combination settings
(LCASE combine (lcase))
(cbreak combine (not icanon))
(cooked combine (brkint ignpar istrip icrnl ixon opost isig icanon))
also eof and eol characters
; to their default values
(crt combine (echoe echoctl echoke))
(dec combine (echoe echoctl echoke (not ixany)))
also intr ^c erase kill ^u
(decctlq combine (ixany))
(ek combine ()) ; erase and kill characters to their default values
(evenp combine (parenb (not parodd) cs7))
;;(-evenp combine #f) ; same as -parenb cs8
(lcase combine (xcase iuclc olcuc))
(litout combine (cs8 (not parenb istrip opost)))
( -litout combine # f ) ; same as parenb istrip opost cs7
(nl combine (not icrnl onlcr))
( -nl combine # f ) ; same as icrnl -inlcr -igncr onlcr -ocrnl -onlret
(oddp combine (parenb parodd cs7))
(parity combine (evenp)) ; same as [-]evenp
(pass8 combine (cs8 (not parenb istrip)))
( -pass8 combine # f ) ; same as parenb istrip cs7
(raw combine (not ignbrk brkint ignpar parmrk
inpck istrip inlcr igncr icrnl))
( ixon combine ( ) ) ; ;
( time combine # f ) ; 0
;;(-raw combine #f) ; same as cooked
(sane combine (cread brkint icrnl imaxbel opost onlcr
nl0 cr0 bs0 vt0 ff0 ;
echo echoe echoctl echoke ;; iexten echok
iuclc
olcuc
echonl noflsh tostop echoprt))) ;; xcase
; plus all special characters to
; their default values
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; high-level interface
;;> \subsubsubsection{\scheme{(stty [port] args ...)}}
;;> Set the terminal attributes for \var{port} (default
> \scheme{(current - output - port ) } ) to } .
;;> Attributes are specified symbolically using the
;;> names from the \rawcode{stty(1)} command. In addition,
;;> (not args ...) may be used to negate the listed symbols.
(define (stty . args)
(let* ((port (if (and (pair? args) (port? (car args)))
(car args)
(current-output-port)))
(attr (get-terminal-attributes port)))
;; parse change requests
(let lp ((lst (if (and (pair? args) (port? (car args))) (cdr args) args))
(iflag (term-attrs-iflag attr))
(oflag (term-attrs-oflag attr))
(cflag (term-attrs-cflag attr))
(lflag (term-attrs-lflag attr))
(invert? #f)
(return (lambda (iflag oflag cflag lflag)
(term-attrs-iflag-set! attr iflag)
(term-attrs-oflag-set! attr oflag)
(term-attrs-cflag-set! attr cflag)
(term-attrs-lflag-set! attr lflag)
(set-terminal-attributes! port TCSANOW attr))))
(define (join old new)
(if invert? (bitwise-and old (bitwise-not new)) (bitwise-ior old new)))
(cond
((pair? lst)
(let ((command (car lst)))
(cond
((pair? command) ;; recurse on sub-expr
(lp command iflag oflag cflag lflag invert?
(lambda (i o c l) (lp (cdr lst) i o c l invert? return))))
((eq? command 'not) ;; toggle current setting
(lp (cdr lst) iflag oflag cflag lflag (not invert?) return))
(else
(let ((x (hash-table-ref/default stty-lookup command #f)))
(case (and x (car x))
((input)
(lp (cdr lst) (join iflag (cadr x)) oflag cflag lflag invert? return))
((output)
(lp (cdr lst) iflag (join oflag (cadr x)) cflag lflag invert? return))
((control)
(lp (cdr lst) iflag oflag (join cflag (cadr x)) lflag invert? return))
((local)
(lp (cdr lst) iflag oflag cflag (join lflag (cadr x)) invert? return))
((char)
( term - attrs - cc - set ! attr ( cadr x ) ( or ( cadr lst ) 0 ) )
(lp (cddr lst) iflag oflag cflag lflag invert? return))
((combine)
(lp (cadr x) iflag oflag cflag lflag invert?
(lambda (i o c l) (lp (cdr lst) i o c l invert? return))))
((special)
(error "special settings not yet supported" command))
(else
(error "unknown stty command" command))))))))
(else
(return iflag oflag cflag lflag))))))
;;> Run \var{thunk} with the \scheme{stty} \var{setting}s in effect
;;> during its dynamic extent, resetting the original settings
;;> when it returns.
(define (with-stty setting thunk . o)
(let* ((port (if (pair? o) (car o) (current-input-port)))
(orig-attrs (get-terminal-attributes port)))
(cond
(orig-attrs
(dynamic-wind
(lambda () (stty port setting))
thunk
(lambda () (set-terminal-attributes! port TCSANOW orig-attrs))))
(else
;; No terminal attributes means this isn't a tty.
(thunk)))))
;;> Run \var{thunk} with the "raw" (no canonical or echo) options
;;> needed for a terminal application.
(define (with-raw-io port thunk)
(with-stty '(not icanon isig echo) thunk port))
> Returns the current terminal width in characters of } ,
;;> which must be a port or a file descriptor.
(define (get-terminal-width x)
(let ((ws (ioctl x TIOCGWINSZ)))
(and ws (winsize-col ws))))
;;> Returns the current terminal dimensions, as a list of character width
> and height , of \var{x } , which must be a port or a file descriptor .
(define (get-terminal-dimensions x)
(let ((ws (ioctl x TIOCGWINSZ)))
(and ws (list (winsize-col ws) (winsize-row ws)))))
| null | https://raw.githubusercontent.com/ashinn/chibi-scheme/8b27ce97265e5028c61b2386a86a2c43c1cfba0d/lib/chibi/stty.scm | scheme | BSD-style license:
symbolic representation of attributes
available on most systems
characters
will send a terminal stop signal
CHAR will end the line
CHAR will erase the last character typed
CHAR will send an interrupt signal
CHAR will erase the current line
CHAR will enter the next character quoted
CHAR will send a quit signal
CHAR will redraw the current line
CHAR will restart output after stopping it
CHAR will stop the output
CHAR will send a terminal stop signal
CHAR will erase the last word typed
special settings
tell the kernel that the terminal has N columns
same as cols N
set the input speed to N
use line discipline N
with -icanon, set N characters minimum for a completed read
set the output speed to N
tell the kernel that the terminal has N rows
print the number of rows and columns according to the kernel
print the terminal speed
control settings
disable modem control signals
allow input to be received
send a hangup signal when the last process closes the tty
same as [-]hup
generate parity bit in output and expect parity bit in input
set odd parity (even with `-')
input settings
breaks cause an interrupt signal
translate carriage return to newline
ignore break characters
ignore carriage return
ignore characters with parity errors
* beep and do not flush a full input buffer on a character
translate newline to carriage return
enable input parity checking
(iuclc input ,IUCLC) ; * translate uppercase characters to lowercase
* let any character restart output, not only start character
enable sending of start/stop characters
same as [-]ixoff
output settings
backspace delay style , N in [ 0 .. 1 ]
backspace delay style , N in [ 0 .. 1 ]
carriage return delay style , N in [ 0 .. 3 ]
carriage return delay style , N in [ 0 .. 3 ]
carriage return delay style , N in [ 0 .. 3 ]
carriage return delay style , N in [ 0 .. 3 ]
form feed delay style , N in [ 0 .. 1 ]
form feed delay style , N in [ 0 .. 1 ]
newline delay style , N in [ 0 .. 1 ]
newline delay style , N in [ 0 .. 1 ]
translate carriage return to newline
(ofdel output ,OFDEL) ; use delete characters for fill instead of null characters
use fill ( padding ) characters instead of timing for delays
(olcuc output ,OLCUC) ; translate lowercase characters to uppercase
translate newline to carriage return-newline
newline performs a carriage return
postprocess output
(-tabs output #f) ; same as tab3
vertical tab delay style , N in [ 0 .. 1 ]
vertical tab delay style , N in [ 0 .. 1 ]
local settings
echo erase characters as backspace-space-backspace
kill all line by obeying the echoprt and echoe settings
(-crtkill local #f) ; kill all line by obeying the echoctl and echok settings
echo control characters in hat notation (`^c')
echo input characters
same as [-]ctlecho
echo a newline after a kill character
same as [-]crtkill
echo newline even if not echoing other characters
(echoprt local ,ECHOPRT) ; echo erased characters backward, between `\' and '/'
enable non - POSIX special characters
enable interrupt, quit, and suspend special characters
disable flushing after interrupt and quit special characters
same as [ -]echoprt
stop background jobs that try to write to the terminal
with icanon , escape with ` \ ' for uppercase characters
combination settings
to their default values
erase and kill characters to their default values
(-evenp combine #f) ; same as -parenb cs8
same as parenb istrip opost cs7
same as icrnl -inlcr -igncr onlcr -ocrnl -onlret
same as [-]evenp
same as parenb istrip cs7
;
0
(-raw combine #f) ; same as cooked
iexten echok
xcase
plus all special characters to
their default values
high-level interface
> \subsubsubsection{\scheme{(stty [port] args ...)}}
> Set the terminal attributes for \var{port} (default
> Attributes are specified symbolically using the
> names from the \rawcode{stty(1)} command. In addition,
> (not args ...) may be used to negate the listed symbols.
parse change requests
recurse on sub-expr
toggle current setting
> Run \var{thunk} with the \scheme{stty} \var{setting}s in effect
> during its dynamic extent, resetting the original settings
> when it returns.
No terminal attributes means this isn't a tty.
> Run \var{thunk} with the "raw" (no canonical or echo) options
> needed for a terminal application.
> which must be a port or a file descriptor.
> Returns the current terminal dimensions, as a list of character width | Copyright ( c ) 2011 . All rights reserved .
> A high - level interface to stty and ioctl .
(define stty-lookup (make-hash-table eq?))
(for-each
(lambda (c) (hash-table-set! stty-lookup (car c) (cdr c)))
ripped from the stty man page , then trimmed down to what seemed
CHAR will send an EOF ( terminate input )
alternate for ending the line
with -icanon , set read timeout of N tenths of a second
enable RTS / CTS handshaking
set character size to 5 bits
set character size to 6 bits
set character size to 7 bits
set character size to 8 bits
use two stop bits per character ( one with ` - ' )
clear high ( 8th ) bit of input characters
enable / XOFF flow control
mark parity errors ( with a 255 - 0 - character sequence )
do not print carriage returns in the first column
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
horizontal tab delay style , N in [ 0 .. 3 ]
same as
same as [ -]crterase
enable erase , kill , werase , and rprnt special characters
(LCASE combine (lcase))
(cbreak combine (not icanon))
(cooked combine (brkint ignpar istrip icrnl ixon opost isig icanon))
also eof and eol characters
(crt combine (echoe echoctl echoke))
(dec combine (echoe echoctl echoke (not ixany)))
also intr ^c erase kill ^u
(decctlq combine (ixany))
(evenp combine (parenb (not parodd) cs7))
(lcase combine (xcase iuclc olcuc))
(litout combine (cs8 (not parenb istrip opost)))
(nl combine (not icrnl onlcr))
(oddp combine (parenb parodd cs7))
(pass8 combine (cs8 (not parenb istrip)))
(raw combine (not ignbrk brkint ignpar parmrk
inpck istrip inlcr igncr icrnl))
(sane combine (cread brkint icrnl imaxbel opost onlcr
iuclc
olcuc
))
> \scheme{(current - output - port ) } ) to } .
(define (stty . args)
(let* ((port (if (and (pair? args) (port? (car args)))
(car args)
(current-output-port)))
(attr (get-terminal-attributes port)))
(let lp ((lst (if (and (pair? args) (port? (car args))) (cdr args) args))
(iflag (term-attrs-iflag attr))
(oflag (term-attrs-oflag attr))
(cflag (term-attrs-cflag attr))
(lflag (term-attrs-lflag attr))
(invert? #f)
(return (lambda (iflag oflag cflag lflag)
(term-attrs-iflag-set! attr iflag)
(term-attrs-oflag-set! attr oflag)
(term-attrs-cflag-set! attr cflag)
(term-attrs-lflag-set! attr lflag)
(set-terminal-attributes! port TCSANOW attr))))
(define (join old new)
(if invert? (bitwise-and old (bitwise-not new)) (bitwise-ior old new)))
(cond
((pair? lst)
(let ((command (car lst)))
(cond
(lp command iflag oflag cflag lflag invert?
(lambda (i o c l) (lp (cdr lst) i o c l invert? return))))
(lp (cdr lst) iflag oflag cflag lflag (not invert?) return))
(else
(let ((x (hash-table-ref/default stty-lookup command #f)))
(case (and x (car x))
((input)
(lp (cdr lst) (join iflag (cadr x)) oflag cflag lflag invert? return))
((output)
(lp (cdr lst) iflag (join oflag (cadr x)) cflag lflag invert? return))
((control)
(lp (cdr lst) iflag oflag (join cflag (cadr x)) lflag invert? return))
((local)
(lp (cdr lst) iflag oflag cflag (join lflag (cadr x)) invert? return))
((char)
( term - attrs - cc - set ! attr ( cadr x ) ( or ( cadr lst ) 0 ) )
(lp (cddr lst) iflag oflag cflag lflag invert? return))
((combine)
(lp (cadr x) iflag oflag cflag lflag invert?
(lambda (i o c l) (lp (cdr lst) i o c l invert? return))))
((special)
(error "special settings not yet supported" command))
(else
(error "unknown stty command" command))))))))
(else
(return iflag oflag cflag lflag))))))
(define (with-stty setting thunk . o)
(let* ((port (if (pair? o) (car o) (current-input-port)))
(orig-attrs (get-terminal-attributes port)))
(cond
(orig-attrs
(dynamic-wind
(lambda () (stty port setting))
thunk
(lambda () (set-terminal-attributes! port TCSANOW orig-attrs))))
(else
(thunk)))))
(define (with-raw-io port thunk)
(with-stty '(not icanon isig echo) thunk port))
> Returns the current terminal width in characters of } ,
(define (get-terminal-width x)
(let ((ws (ioctl x TIOCGWINSZ)))
(and ws (winsize-col ws))))
> and height , of \var{x } , which must be a port or a file descriptor .
(define (get-terminal-dimensions x)
(let ((ws (ioctl x TIOCGWINSZ)))
(and ws (list (winsize-col ws) (winsize-row ws)))))
|
5c9fb650103ff8f7d7ec86e9fc0bbaa2c60e06738793cf9c4997aad112ee8be6 | chrisdone/ircbrowse | Types.hs | # LANGUAGE ScopedTypeVariables #
# LANGUAGE MultiParamTypeClasses #
module Ircbrowse.Types where
import Ircbrowse.Data
import Ircbrowse.Types.Import
import Ircbrowse.Monads
import Control.Applicative
import Data.Text
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Network.Mail.Mime (Address)
import Snap.App.Cache
import Snap.App.Types
import Data.Time
-- | Site-wide configuration.
data Config = Config
{ configPostgres :: !ConnectInfo
, configDomain :: !String
, configAdmin :: !Address
, configSiteAddy :: !Address
, configCacheDir :: !FilePath
, configLogDir :: !FilePath
}
instance AppConfig Config where
getConfigDomain = configDomain
instance CacheDir Config where
getCacheDir = configCacheDir
data PState = PState
-- | Statistics.
data Stats = Stats
{ stEventCount :: !Integer
, stMsgCount :: !Integer
, stNickCount :: !Integer
, stActiveTimes :: ![(Integer,Integer)]
, stDailyActivity :: ![(Integer,Integer)]
, stActiveNicks :: ![(String,Integer)]
, stNetworks :: ![(String,String)]
, stChannels :: ![(String,String)]
, stActivityByYear :: ![(Integer,Integer)]
, stConversationByYear :: ![(Integer,Integer)]
} deriving Show
instance Default Stats where
def = Stats
{ stEventCount = 0
, stMsgCount = 0
, stNickCount = 0
, stActiveNicks = []
, stActiveTimes = []
, stDailyActivity = []
, stNetworks = []
, stChannels = []
, stConversationByYear = []
, stActivityByYear = []
}
instance AppLiftModel Config PState where
liftModel action = do
conn <- env controllerStateConn
anns <- env controllerState
conf <- env controllerStateConfig
let st = ModelState conn anns conf
io $ runReaderT (runModel action) st
data Range = Range
{ rangeFrom :: !Day, rangeTo :: !Day }
deriving (Eq,Show)
data CacheKey
= StatsOverview Channel
| Overview
| NickCloud Channel
| Social (Maybe Channel)
| BrowseDay Channel Day Text
| BrowseToday Channel Text
| Profile Text Bool
| AllNicks Channel Text
| UniquePDFs Channel
| Calendar Channel
| Channel Channel
instance Key CacheKey where
keyToString (Calendar channel) = norm $ "calendar-" ++ showChan channel ++ ".html"
keyToString (BrowseToday channel mode) = norm $ "browse-today-" ++ showChan channel ++ "-" ++ unpack mode ++ ".html"
keyToString (BrowseDay channel day mode) = norm $ "browse-day-" ++ showDay day ++ "-" ++ showChan channel ++ "-" ++ unpack mode ++ ".html"
keyToString (UniquePDFs channel) = norm $ "unique-pdfs-" ++ showChan channel ++ ".html"
keyToString (StatsOverview channel) = norm $ contexted "overview" (Just channel)
keyToString Overview = norm $ "overview.html"
keyToString (NickCloud channel) = norm $ contexted "nick-cloud" (Just channel)
keyToString (Social channel) = norm $ contexted "social" channel
keyToString (Profile nick recent) = norm $
"profile-" ++ unpack nick ++ "-" ++ (if recent then "recent" else "all") ++
".html"
keyToString (AllNicks channel mode) = norm $
"nicks-" ++ showChan channel ++ "-" ++ unpack mode ++
".html"
keyToString (Channel channel) = norm $ "channel-" ++ showChan channel ++ ".html"
norm :: [Char] -> [Char]
norm = go where
go (x:xs) | isDigit x || isLetter x || x == '.' || x == '-' = x : go xs
| otherwise = show (fromEnum x) ++ go xs
go [] = []
contexted :: [Char] -> Maybe Channel -> [Char]
contexted name channel =
name ++ "-" ++ opt (fmap showChan channel) ++ ".html"
where opt Nothing = "_"
opt (Just x) = x
showDay :: Day -> String
showDay = formatTime defaultTimeLocale "%Y-%m-%d"
data Event = Event
{ eventId :: !Int
, eventTimestamp :: !ZonedTime
, eventNetwork :: !Int
, eventChannel :: !Int
, eventType :: !Text
, eventNick :: !(Maybe Text)
, eventText :: !Text
} deriving (Show)
instance FromRow Event where
fromRow = Event <$> field <*> field <*> field <*> field <*> field <*> field <*> field
| null | https://raw.githubusercontent.com/chrisdone/ircbrowse/d956aaf185500792224b6b0c209eb67c179322a4/src/Ircbrowse/Types.hs | haskell | | Site-wide configuration.
| Statistics. | # LANGUAGE ScopedTypeVariables #
# LANGUAGE MultiParamTypeClasses #
module Ircbrowse.Types where
import Ircbrowse.Data
import Ircbrowse.Types.Import
import Ircbrowse.Monads
import Control.Applicative
import Data.Text
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Network.Mail.Mime (Address)
import Snap.App.Cache
import Snap.App.Types
import Data.Time
data Config = Config
{ configPostgres :: !ConnectInfo
, configDomain :: !String
, configAdmin :: !Address
, configSiteAddy :: !Address
, configCacheDir :: !FilePath
, configLogDir :: !FilePath
}
instance AppConfig Config where
getConfigDomain = configDomain
instance CacheDir Config where
getCacheDir = configCacheDir
data PState = PState
data Stats = Stats
{ stEventCount :: !Integer
, stMsgCount :: !Integer
, stNickCount :: !Integer
, stActiveTimes :: ![(Integer,Integer)]
, stDailyActivity :: ![(Integer,Integer)]
, stActiveNicks :: ![(String,Integer)]
, stNetworks :: ![(String,String)]
, stChannels :: ![(String,String)]
, stActivityByYear :: ![(Integer,Integer)]
, stConversationByYear :: ![(Integer,Integer)]
} deriving Show
instance Default Stats where
def = Stats
{ stEventCount = 0
, stMsgCount = 0
, stNickCount = 0
, stActiveNicks = []
, stActiveTimes = []
, stDailyActivity = []
, stNetworks = []
, stChannels = []
, stConversationByYear = []
, stActivityByYear = []
}
instance AppLiftModel Config PState where
liftModel action = do
conn <- env controllerStateConn
anns <- env controllerState
conf <- env controllerStateConfig
let st = ModelState conn anns conf
io $ runReaderT (runModel action) st
data Range = Range
{ rangeFrom :: !Day, rangeTo :: !Day }
deriving (Eq,Show)
data CacheKey
= StatsOverview Channel
| Overview
| NickCloud Channel
| Social (Maybe Channel)
| BrowseDay Channel Day Text
| BrowseToday Channel Text
| Profile Text Bool
| AllNicks Channel Text
| UniquePDFs Channel
| Calendar Channel
| Channel Channel
instance Key CacheKey where
keyToString (Calendar channel) = norm $ "calendar-" ++ showChan channel ++ ".html"
keyToString (BrowseToday channel mode) = norm $ "browse-today-" ++ showChan channel ++ "-" ++ unpack mode ++ ".html"
keyToString (BrowseDay channel day mode) = norm $ "browse-day-" ++ showDay day ++ "-" ++ showChan channel ++ "-" ++ unpack mode ++ ".html"
keyToString (UniquePDFs channel) = norm $ "unique-pdfs-" ++ showChan channel ++ ".html"
keyToString (StatsOverview channel) = norm $ contexted "overview" (Just channel)
keyToString Overview = norm $ "overview.html"
keyToString (NickCloud channel) = norm $ contexted "nick-cloud" (Just channel)
keyToString (Social channel) = norm $ contexted "social" channel
keyToString (Profile nick recent) = norm $
"profile-" ++ unpack nick ++ "-" ++ (if recent then "recent" else "all") ++
".html"
keyToString (AllNicks channel mode) = norm $
"nicks-" ++ showChan channel ++ "-" ++ unpack mode ++
".html"
keyToString (Channel channel) = norm $ "channel-" ++ showChan channel ++ ".html"
norm :: [Char] -> [Char]
norm = go where
go (x:xs) | isDigit x || isLetter x || x == '.' || x == '-' = x : go xs
| otherwise = show (fromEnum x) ++ go xs
go [] = []
contexted :: [Char] -> Maybe Channel -> [Char]
contexted name channel =
name ++ "-" ++ opt (fmap showChan channel) ++ ".html"
where opt Nothing = "_"
opt (Just x) = x
showDay :: Day -> String
showDay = formatTime defaultTimeLocale "%Y-%m-%d"
data Event = Event
{ eventId :: !Int
, eventTimestamp :: !ZonedTime
, eventNetwork :: !Int
, eventChannel :: !Int
, eventType :: !Text
, eventNick :: !(Maybe Text)
, eventText :: !Text
} deriving (Show)
instance FromRow Event where
fromRow = Event <$> field <*> field <*> field <*> field <*> field <*> field <*> field
|
89a7e9e021507f8e1fb8acd7cdba83213ad7351f2156bfad03fefe503ed99844 | camllight/camllight | communication.mli | (****************** Low level communication with the runtime ***************)
#open "obj";;
#open "value";;
#open "primitives";;
(*** Writing/reading data (values and objects). ***)
(* Reading/writing boxed values. *)
value output_val : out_channel -> VALUE -> unit
= 2 "output_val";;
value input_val : in_channel -> VALUE
= 1 "input_val";;
(* Read a boxed object. *)
value input_object : in_channel -> OBJECT
= 1 "input_object";;
(* Read an object. *)
value copy_remote_object : in_channel -> 'a
= 1 "copy_remote_object";;
(* Read an object header. *)
value input_header : in_channel -> int * int
= 1 "input_header";;
(*** Current connection. ***)
value set_current_connection : IO_CHANNEL -> unit;;
(*** Reports. ***)
type REPORT_TYPE =
Rep_event
| Rep_breakpoint
| Rep_exited
| Rep_trap
| Rep_exc;;
type REPORT =
{Rep_type : REPORT_TYPE;
Rep_event_count : int;
Rep_stack_pointer : int;
Rep_program_pointer : int};;
type CHECKPOINT_REPORT =
Checkpoint_done of int
| Checkpoint_failed;;
(*** Primitives. ***)
(* Set an event at `position'. *)
value set_event : int -> unit;;
(* Change the instruction at `position'. *)
(* Return the previous instruction. *)
(* (used for breakpoints). *)
value set_instr : int -> char -> char;;
(* Create a new checkpoint (the current process forks). *)
value do_checkpoint : unit -> CHECKPOINT_REPORT;;
(* Step `event_count' events. *)
value go : int -> REPORT;;
Same as ` go ' but use ` first_instruction ' as first instruction
(* instead of the one at current program pointer. *)
(* (restart after having stop on a breakpoint). *)
value restart : char -> int -> REPORT;;
(* Select the frame number `frame_number'. *)
(* Return corresponding frame pointer and program counter. *)
value move_frame : int -> (int * int) option;;
(* Set the trap barrier at `position'. *)
(* The program will stop if an exception reaches the trap barrier. *)
Zero is top of stack .
value set_trap_barrier : int -> unit;;
(* Get a local variable. *)
(* (in fact, the corresponding element of the environment). *)
value get_local : int -> VALUE;;
(* Get a global variable. *)
value get_global : int -> VALUE;;
(* Set a global variable to the invalid value, to flag it as uninitialized *)
value mark_global_uninitialized : int -> unit;;
(* Get the value of the accumulator. *)
value get_accu : unit -> VALUE;;
(* Retrieve an object (box it). *)
value get_obj : VALUE -> OBJECT;;
(* Copy an object from the program memory space to the debugger one. *)
(* The object must be unstructured (so as not be traversed by the garbage collector). *)
value copy_obj : VALUE -> obj;;
(* Return the adress of the code of the given closure. *)
value get_closure_code : VALUE -> int;;
(* Get the header of an object. *)
(* Return a pair tag-size. *)
value get_header : VALUE -> int * int;;
(* Get the n-th field of an object. *)
value get_field : VALUE -> int -> VALUE;;
(* Set the n-th field of an object (unused yet). *)
value set_field : VALUE -> int -> VALUE -> unit;;
(* Kill the given process. *)
value stop : IO_CHANNEL -> unit;;
(* Ask a process to wait for its child which has been killed. *)
(* (so as to eliminate zombies). *)
value wait_child : IO_CHANNEL -> unit;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/debugger/communication.mli | ocaml | ***************** Low level communication with the runtime **************
** Writing/reading data (values and objects). **
Reading/writing boxed values.
Read a boxed object.
Read an object.
Read an object header.
** Current connection. **
** Reports. **
** Primitives. **
Set an event at `position'.
Change the instruction at `position'.
Return the previous instruction.
(used for breakpoints).
Create a new checkpoint (the current process forks).
Step `event_count' events.
instead of the one at current program pointer.
(restart after having stop on a breakpoint).
Select the frame number `frame_number'.
Return corresponding frame pointer and program counter.
Set the trap barrier at `position'.
The program will stop if an exception reaches the trap barrier.
Get a local variable.
(in fact, the corresponding element of the environment).
Get a global variable.
Set a global variable to the invalid value, to flag it as uninitialized
Get the value of the accumulator.
Retrieve an object (box it).
Copy an object from the program memory space to the debugger one.
The object must be unstructured (so as not be traversed by the garbage collector).
Return the adress of the code of the given closure.
Get the header of an object.
Return a pair tag-size.
Get the n-th field of an object.
Set the n-th field of an object (unused yet).
Kill the given process.
Ask a process to wait for its child which has been killed.
(so as to eliminate zombies). |
#open "obj";;
#open "value";;
#open "primitives";;
value output_val : out_channel -> VALUE -> unit
= 2 "output_val";;
value input_val : in_channel -> VALUE
= 1 "input_val";;
value input_object : in_channel -> OBJECT
= 1 "input_object";;
value copy_remote_object : in_channel -> 'a
= 1 "copy_remote_object";;
value input_header : in_channel -> int * int
= 1 "input_header";;
value set_current_connection : IO_CHANNEL -> unit;;
type REPORT_TYPE =
Rep_event
| Rep_breakpoint
| Rep_exited
| Rep_trap
| Rep_exc;;
type REPORT =
{Rep_type : REPORT_TYPE;
Rep_event_count : int;
Rep_stack_pointer : int;
Rep_program_pointer : int};;
type CHECKPOINT_REPORT =
Checkpoint_done of int
| Checkpoint_failed;;
value set_event : int -> unit;;
value set_instr : int -> char -> char;;
value do_checkpoint : unit -> CHECKPOINT_REPORT;;
value go : int -> REPORT;;
Same as ` go ' but use ` first_instruction ' as first instruction
value restart : char -> int -> REPORT;;
value move_frame : int -> (int * int) option;;
Zero is top of stack .
value set_trap_barrier : int -> unit;;
value get_local : int -> VALUE;;
value get_global : int -> VALUE;;
value mark_global_uninitialized : int -> unit;;
value get_accu : unit -> VALUE;;
value get_obj : VALUE -> OBJECT;;
value copy_obj : VALUE -> obj;;
value get_closure_code : VALUE -> int;;
value get_header : VALUE -> int * int;;
value get_field : VALUE -> int -> VALUE;;
value set_field : VALUE -> int -> VALUE -> unit;;
value stop : IO_CHANNEL -> unit;;
value wait_child : IO_CHANNEL -> unit;;
|
3e3bd3077e57684c6065c6c1365995c5c6d66ca0613b12001e89cd202868ba8b | morloc-project/morloc | Typecheck.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ViewPatterns #
|
Module : Morloc . Frontend . : Core inference module
Copyright : ( c ) , 2021
License : GPL-3
Maintainer :
Stability : experimental
Module : Morloc.Frontend.Typecheck
Description : Core inference module
Copyright : (c) Zebulun Arendsee, 2021
License : GPL-3
Maintainer :
Stability : experimental
-}
module Morloc.Frontend.Typecheck (typecheck, resolveTypes) where
import Morloc.Frontend.Namespace
import Morloc.Typecheck.Internal
import Morloc.Pretty
import Morloc.Data.Doc
import qualified Morloc.Frontend.Lang.DefaultTypes as MLD
import qualified Morloc.Data.GMap as GMap
import qualified Morloc.Monad as MM
import qualified Morloc.Data.Text as MT
import qualified Control.Monad.State as CMS
import qualified Data.Map as Map
import Data.Bifunctor (first)
| Each SAnno object in the input list represents one exported function .
-- Modules, scopes, imports and everything else are abstracted away.
--
-- Check the general types, do nothing to the concrete types which may only be
-- solved after segregation. Later the concrete types will need to be checked
-- for type consistency and correctness of packers.
typecheck
:: [SAnno Int Many Int]
-> MorlocMonad [SAnno (Indexed TypeU) Many Int]
typecheck xs = error . MT.unpack . render . . map ( prettySAnno viaShow viaShow ) $ xs
typecheck = mapM run where
run :: SAnno Int Many Int -> MorlocMonad (SAnno (Indexed TypeU) Many Int)
run e0 = do
standardize names for lambda bound variables ( e.g. , , x1 ... )
let g0 = Gamma {gammaCounter = 0, gammaContext = []}
((_, g1), e1) = renameSAnno (Map.empty, g0) e0
(g2, _, e2) <- synthG' g1 e1
say "-------- leaving frontend typechecker ------------------"
say "g2:"
seeGamma g2
say "e2:"
peakGen e2
say "========================================================"
return $ mapSAnno (fmap normalizeType) id . applyGen g2 $ e2
-- TypeU --> Type
resolveTypes :: SAnno (Indexed TypeU) Many Int -> SAnno (Indexed Type) Many Int
resolveTypes (SAnno (Many es) (Idx i t))
= SAnno (Many (map (first f) es)) (Idx i (typeOf t)) where
f :: SExpr (Indexed TypeU) Many Int -> SExpr (Indexed Type) Many Int
f (AccS x k) = AccS (resolveTypes x) k
f (AppS x xs) = AppS (resolveTypes x) (map resolveTypes xs)
f (LamS vs x) = LamS vs (resolveTypes x)
f (LstS xs) = LstS (map resolveTypes xs)
f (TupS xs) = TupS (map resolveTypes xs)
f (NamS rs) = NamS (zip (map fst rs) (map (resolveTypes . snd) rs))
f (RealS x) = RealS x
f (IntS x) = IntS x
f (LogS x) = LogS x
f (StrS x) = StrS x
f (CallS x) = CallS x
f UniS = UniS
f (VarS x) = VarS x
-- lookup a general type associated with an index
-- standardize naming of qualifiers
lookupType :: Int -> Gamma -> MorlocMonad (Maybe (Gamma, TypeU))
lookupType i g = do
m <- CMS.gets stateSignatures
return $ case GMap.lookup i m of
GMapJust (TermTypes (Just (EType t _ _)) _ _) -> Just $ rename g t
_ -> Nothing
-- prepare a general, indexed typechecking error
gerr :: Int -> TypeError -> MorlocMonad a
gerr i e = MM.throwError $ IndexedError i (GeneralTypeError e)
synthG
:: Gamma
-> SAnno Int Many Int
-> MorlocMonad
( Gamma
, TypeU
, SAnno (Indexed TypeU) Many Int
)
-- it is possible to export just a type signature
synthG g (SAnno (Many []) i) = do
maybeType <- lookupType i g
case maybeType of
(Just (g', t)) -> return (g', t, SAnno (Many []) (Idx i t))
-- if a term is associated with no expression or type
Nothing -> do
maybeName <- CMS.gets (Map.lookup i . stateName)
case maybeName of
-- This branch is entered for exported type definitions
-- FIXME: return all definitions and their parameters, check parameter count
(Just (EV v)) -> return (g, VarU (TV Nothing v), SAnno (Many []) (Idx i (VarU (TV Nothing v))))
Nothing -> error ("Shit output for index " <> show i)-- this should not happen
synthG g0 (SAnno (Many ((e0, j):es)) i) = do
-- Check for any existing type signature annotations
maybeType <- lookupType i g0
(g1, t1, e1) <- case maybeType of
-- If there are no annotations, synthesize
Nothing -> synthE' i g0 e0
-- If there are annotations ...
(Just (g', t)) -> case e0 of
-- If the annotation is of a variable name, return the annotation. Calling
-- check would just re-synthesize the same type and check that it was
-- equal to itself.
(VarS v) -> return (g', t, VarS v)
-- Otherwise check the annotation type
_ -> checkE' i g' e0 t
Check all other implementations against the first one
(g2, t2, SAnno (Many es') _) <- checkG' g1 (SAnno (Many es) i) t1
-- finally cons the head element back and apply everything we learned
let finalExpr = applyGen g2 $ SAnno (Many ((e1, j):es')) (Idx i t2)
return (g2, t2, finalExpr)
checkG
:: Gamma
-> SAnno Int Many Int
-> TypeU
-> MorlocMonad
( Gamma
, TypeU
, SAnno (Indexed TypeU) Many Int
)
checkG g (SAnno (Many []) i) t = return (g, t, SAnno (Many []) (Idx i t))
checkG g0 (SAnno (Many ((e, j):es)) i) t0 = do
(g1, t1, e') <- checkE' i g0 e t0
(g2, t2, SAnno (Many es') idType) <- checkG' g1 (SAnno (Many es) i) t1
return (g2, t2, SAnno (Many ((e', j):es')) idType)
synthE
:: Int
-> Gamma
-> SExpr Int Many Int
-> MorlocMonad
( Gamma
, TypeU
, SExpr (Indexed TypeU) Many Int
)
synthE _ g UniS = return (g, MLD.defaultGeneralType UniS, UniS)
synthE _ g (RealS x) = return (g, MLD.defaultGeneralType (RealS x), RealS x)
synthE _ g (IntS x) = return (g, MLD.defaultGeneralType (IntS x), IntS x)
synthE _ g (LogS x) = return (g, MLD.defaultGeneralType (LogS x), LogS x)
synthE _ g (StrS x) = return (g, MLD.defaultGeneralType (StrS x), StrS x)
synthE i g (AccS e k) = do
(g1, t1, e1) <- synthG' g e
valType <- case t1 of
(NamU _ _ _ rs) -> case lookup k rs of
Nothing -> gerr i (KeyError k t1)
(Just t) -> return t
_ -> gerr i (KeyError k t1)
return (g1, valType, AccS e1 k)
-- -->E0
synthE _ g (AppS f []) = do
(g1, t1, f1) <- synthG' g f
return (g1, t1, AppS f1 [])
-- -->E
synthE i g0 (AppS f xs0) = do
-- synthesize the type of the function
(g1, funType0, funExpr0) <- synthG g0 f
-- eta expand
mayExpanded <- etaExpand g1 f xs0 funType0
case mayExpanded of
-- If the term was eta-expanded, retypecheck it
(Just (g', x')) -> synthE i g' x'
-- Otherwise proceed
Nothing -> do
-- extend the function type with the type of the expressions it is applied to
(g2, funType1, inputExprs) <- application' i g1 xs0 (normalizeType funType0)
-- determine the type after application
appliedType <- case funType1 of
(FunU ts t) -> case drop (length inputExprs) ts of
[] -> return t -- full application
rs -> return $ FunU rs t -- partial application
_ -> error "impossible"
-- put the AppS back together with the synthesized function and input expressions
return (g2, apply g2 appliedType, AppS (applyGen g2 funExpr0) inputExprs)
-- -->I==>
synthE i g0 f@(LamS vs x) = do
(g1, bodyType, _) <- synthG g0 x
let n = nfargs bodyType
if n > 0
then do
(g2, f2) <- expand n g1 f
say $ "Expanded in -->I==>:" <+> prettySExpr (const "") (const "") f2
synthE i g2 f2
else do
-- create existentials for everything and pass it off to check
let (g2, ts) = statefulMap (\g' v -> newvar (unEVar v <> "_x") Nothing g') g1 vs
(g3, ft) = newvar "o_" Nothing g2
finalType = FunU ts ft
checkE' i g3 f finalType
where
nfargs :: TypeU -> Int
nfargs (FunU ts _) = length ts
nfargs (ForallU _ f') = nfargs f'
nfargs _ = 0
-- List
synthE _ g (LstS []) =
let (g1, itemType) = newvar "itemType_" Nothing g
listType = head $ MLD.defaultList Nothing itemType
in return (g1, listType, LstS [])
synthE i g (LstS (e:es)) = do
(g1, itemType, itemExpr) <- synthG' g e
(g2, listType, listExpr) <- checkE' i g1 (LstS es) (head $ MLD.defaultList Nothing itemType)
case listExpr of
(LstS es') -> return (g2, listType, LstS (itemExpr:es'))
_ -> error "impossible"
-- Tuple
synthE _ g (TupS []) =
let t = head $ MLD.defaultTuple Nothing []
in return (g, t, TupS [])
synthE i g (TupS (e:es)) = do
-- synthesize head
(g1, itemType, itemExpr) <- synthG' g e
-- synthesize tail
(g2, tupleType, tupleExpr) <- synthE' i g1 (TupS es)
-- merge the head and tail
t3 <- case tupleType of
(AppU _ ts) -> return . head $ MLD.defaultTuple Nothing (apply g2 itemType : ts)
_ -> error "impossible" -- the general tuple will always be (AppU _ _)
xs' <- case tupleExpr of
(TupS xs') -> return xs'
_ -> error "impossible" -- synth does not change data constructors
return (g2, t3, TupS (itemExpr:xs'))
-- Records
synthE _ g (NamS []) = return (g, head $ MLD.defaultRecord Nothing [], NamS [])
synthE i g0 (NamS ((k,x):rs)) = do
say $ "Entering synthE NamS (k=" <> pretty k <> ")"
seeGamma g0
say "-------- syn"
-- type the head
(g1, headType, headExpr) <- synthG' g0 x
-- type the tail
(g2, tailType, tailExpr) <- synthE' i g1 (NamS rs)
say $ "Exiting synthE NamS (k=" <> pretty k <> ")"
say $ " k type:" <+> pretty headType
seeGamma g2
say "-------- syn"
-- merge the head with tail
t <- case tailType of
(NamU o1 n1 ps1 rs1) -> return $ NamU o1 n1 ps1 ((k, apply g2 headType):rs1)
the synthE on NamS will always return NamU type
tailExprs <- case tailExpr of
(NamS xs') -> return xs'
_ -> error "impossible" -- synth does not change data constructors
return (g2, t, NamS ((k, headExpr):tailExprs))
-- Sources are axiomatic. They are they type they are said to be.
synthE i g (CallS src) = do
maybeType <- lookupType i g
(g', t) <- case maybeType of
Just x -> return x
-- no, then I don't know what it is and will return an existential
-- if this existential is never solved, then it will become universal later
Nothing -> return $ newvar "src_" Nothing g
return (g', t, CallS src)
-- Any morloc variables should have been expanded by treeify. Any bound
-- variables should be checked against. I think (this needs formalization).
synthE i g (VarS v) = do
-- is this a bound variable that has already been solved
(g', t') <- case lookupE v g of
-- yes, return the solved type
(Just t) -> return (g, t)
Nothing -> do
-- no, so is it a variable that has a type annotation?
maybeType <- lookupType i g
case maybeType of
Just x -> return x
-- no, then I don't know what it is and will return an existential
-- if this existential is never solved, then it will become universal later
Nothing -> return $ newvar (unEVar v <> "_u") Nothing g
return (g', t', VarS v)
etaExpand :: Gamma -> SAnno Int Many Int -> [SAnno Int Many Int] -> TypeU -> MorlocMonad (Maybe (Gamma, SExpr Int Many Int))
etaExpand g0 f0 xs0@(length -> termSize) (normalizeType -> FunU (length -> typeSize) _)
| termSize == typeSize = return Nothing
| otherwise = Just <$> etaExpandE g0 (AppS f0 xs0)
where
etaExpandE :: Gamma -> SExpr Int Many Int -> MorlocMonad (Gamma, SExpr Int Many Int)
etaExpandE g e@(AppS _ _) = tryExpand (typeSize - termSize) g e
etaExpandE g e@(LamS vs _) = tryExpand (typeSize - termSize - length vs) g e
etaExpandE g e = return (g, e)
tryExpand n g e
-- A partially applied term intended to return a function (e.g., `(\x y -> add x y) x |- Real -> Real`)
-- A fully applied term
| n <= 0 = return (g, e)
| otherwise = expand n g e
etaExpand _ _ _ _ = return Nothing
expand :: Int -> Gamma -> SExpr Int Many Int -> MorlocMonad (Gamma, SExpr Int Many Int)
expand 0 g x = return (g, x)
expand n g e@(AppS _ _) = do
newIndex <- MM.getCounter
let (g', v') = evarname g "v"
e' <- applyExistential v' e
let x' = LamS [v'] (SAnno (Many [(e', newIndex)]) newIndex)
expand (n-1) g' x'
expand n g (LamS vs' (SAnno (Many es0') t)) = do
let (g', v') = evarname g "v"
es1' <- mapM (applyExistential v' . fst) es0'
expand (n-1) g' (LamS (vs' <> [v']) (SAnno (Many (zip es1' (map snd es0'))) t))
expand _ g x = return (g, x)
applyExistential :: EVar -> SExpr Int Many Int -> MorlocMonad (SExpr Int Many Int)
applyExistential v' (AppS f xs') = do
newIndex <- MM.getCounter
return $ AppS f (xs' <> [SAnno (Many [(VarS v', newIndex)]) newIndex])
-- possibly illegal application, will type check after expansion
applyExistential v' e = do
appIndex <- MM.getCounter
varIndex <- MM.getCounter
return $ AppS (SAnno (Many [(e, appIndex)]) appIndex) [SAnno (Many [(VarS v', varIndex)]) varIndex]
application
:: Int
-> Gamma
-> [SAnno Int Many Int] -- the expressions that are passed to the function
-> TypeU -- the function type
-> MorlocMonad
( Gamma
, TypeU -- output function type
, [SAnno (Indexed TypeU) Many Int] -- @e@, with type annotation
)
-- g1 |- e <= A -| g2
-- ----------------------------------------- -->App
-- g1 |- A->C o e =>> C -| g2
application i g0 es0 (FunU as0 b0) = do
(g1, as1, es1, remainder) <- zipCheck i g0 es0 as0
let es2 = map (applyGen g1) es1
funType = apply g1 $ FunU (as1 <> remainder) b0
say $ "remainder:" <+> vsep (map pretty remainder)
return (g1, funType, es2)
-- g1,Ea |- [Ea/a]A o e =>> C -| g2
-- ----------------------------------------- Forall App
-- g1 |- Forall x.A o e =>> C -| g2
application i g0 es (ForallU v s) = application' i (g0 +> v) es (substitute v s)
g1[Ea2 , Ea1 , Ea = Ea1->Ea2 ] |- e < = Ea1 -| g2
-- ----------------------------------------- EaApp
-- g1[Ea] |- Ea o e =>> Ea2 -| g2
application i g0 es (ExistU v@(TV _ s) [] _) =
case access1 v (gammaContext g0) of
-- replace <t0> with <t0>:<ea1> -> <ea2>
Just (rs, _, ls) -> do
let (g1, veas) = statefulMap (\g _ -> tvarname g "a_" Nothing) g0 es
(g2, vea) = tvarname g1 (s <> "o_") Nothing
eas = [ExistU v' [] [] | v' <- veas]
ea = ExistU vea [] []
f = FunU eas ea
g3 = g2 {gammaContext = rs <> [SolvedG v f] <> map index eas <> [index ea] <> ls}
(g4, _, es', _) <- zipCheck i g3 es eas
return (g4, apply g4 f, map (applyGen g4) es')
-- if the variable has already been solved, use solved value
Nothing -> case lookupU v g0 of
(Just (FunU ts t)) -> do
(g1, ts', es', _) <- zipCheck i g0 es ts
return (g1, apply g1 (FunU ts' t), es')
_ -> gerr i ApplicationOfNonFunction
application i _ _ _ = do
gerr i ApplicationOfNonFunction
-- Tip together the arguments passed to an application
zipCheck
:: Int
-> Gamma
-> [SAnno Int Many Int]
-> [TypeU]
-> MorlocMonad
( Gamma
, [TypeU]
, [SAnno (Indexed TypeU) Many Int]
, [TypeU] -- remainder
)
check the first elements , cdr down the remaining values
zipCheck i g0 (x0:xs0) (t0:ts0) = do
(g1, t1, x1) <- checkG' g0 x0 t0
(g2, ts1, xs1, remainder) <- zipCheck i g1 xs0 ts0
return (g2, t1:ts1, x1:xs1, remainder)
-- If there are fewer arguments than types, this may be OK, just partial application
zipCheck _ g0 [] ts = return (g0, [], [], ts)
-- If there are fewer types than arguments, then die
zipCheck i _ _ [] = gerr i TooManyArguments
checkE
:: Int
-> Gamma
-> SExpr Int Many Int
-> TypeU
-> MorlocMonad
( Gamma
, TypeU
, SExpr (Indexed TypeU) Many Int
)
checkE i g1 (LstS (e:es)) (AppU v [t]) = do
(g2, t2, e') <- checkG' g1 e t
-- LstS [] will go to the normal Sub case
(g3, t3, LstS es') <- checkE i g2 (LstS es) (AppU v [t2])
return (g3, t3, LstS (map (applyGen g3) (e':es')))
checkE i g0 e0@(LamS vs body) t@(FunU as b)
| length vs == length as = do
let g1 = g0 ++> zipWith AnnG vs as
(g2, t2, e2) <- checkG' g1 body b
let t3 = apply g2 (FunU as t2)
e3 = applyCon g2 (LamS vs e2)
return (g2, t3, e3)
| otherwise = do
(g', e') <- expand (length as - length vs) g0 e0
checkE i g' e' t
checkE i g1 e1 (ForallU v a) = checkE' i (g1 +> v) e1 (substitute v a)
-- Sub
checkE i g1 e1 b = do
(g2, a, e2) <- synthE' i g1 e1
let a' = apply g2 a
b' = apply g2 b
g3 <- subtype' i a' b' g2
return (g3, apply g3 b', e2)
subtype' :: Int -> TypeU -> TypeU -> Gamma -> MorlocMonad Gamma
subtype' i a b g = do
say $ parens (pretty a) <+> "<:" <+> parens (pretty b)
case subtype a b g of
(Left err') -> gerr i err'
(Right x) -> return x
---- debugging
enter :: Doc ann -> MorlocMonad ()
enter d = do
depth <- MM.incDepth
debugLog $ pretty (replicate depth '-') <> ">" <+> d <> "\n"
say :: Doc ann -> MorlocMonad ()
say d = do
depth <- MM.getDepth
debugLog $ pretty (replicate depth ' ') <> ":" <+> d <> "\n"
seeGamma :: Gamma -> MorlocMonad ()
seeGamma g = say $ nest 4 $ "Gamma:" <> line <> vsep (map pretty (gammaContext g))
seeType :: TypeU -> MorlocMonad ()
seeType t = say $ pretty t
leave :: Doc ann -> MorlocMonad ()
leave d = do
depth <- MM.decDepth
debugLog $ "<" <> pretty (replicate (depth+1) '-') <+> d <> "\n"
debugLog :: Doc ann -> MorlocMonad ()
debugLog d = do
verbosity <- MM.gets stateVerbosity
when (verbosity > 0) $ (liftIO . putDoc) d
synthG' g x = do
enter "synthG"
r <- synthG g x
leave "synthG"
return r
checkG' g x t = do
enter "checkG"
r <- checkG g x t
leave "checkG"
return r
synthE' i g x = do
enter "synthE"
peak x
seeGamma g
r@(g', t, x') <- synthE i g x
leave "synthE"
peak x'
seeGamma g'
seeType t
return r
checkE' i g x t = do
enter "checkE"
peak x
seeType t
seeGamma g
r@(g', t', x') <- checkE i g x t
leave "checkE"
peak x'
seeType t'
seeGamma g'
return r
application' i g es t = do
enter "application"
seeGamma g
seeType t
mapM_ peakGen es
r@(g',t',es') <- application i g es t
leave "application"
seeGamma g'
seeType t'
mapM_ peakGen es'
return r
peak :: Foldable f => SExpr g f c -> MorlocMonad ()
peak = say . prettySExpr (const "") (const "")
-- peak x = say $ f x where
peakGen :: Foldable f => SAnno g f c -> MorlocMonad ()
peakGen = say . prettySAnno (const "") (const "")
-- peak x = say $ f x where
-- apply context to a SAnno
applyGen :: (Functor gf, Functor f, Applicable g)
=> Gamma -> SAnno (gf g) f c -> SAnno (gf g) f c
applyGen g = mapSAnno (fmap (apply g)) id
applyCon :: (Functor gf, Functor f, Applicable g)
=> Gamma -> SExpr (gf g) f c -> SExpr (gf g) f c
applyCon g = mapSExpr (fmap (apply g)) id
| null | https://raw.githubusercontent.com/morloc-project/morloc/c4e76083afaaaeae2bb53a65fe23604200fdf2e0/library/Morloc/Frontend/Typecheck.hs | haskell | # LANGUAGE OverloadedStrings #
Modules, scopes, imports and everything else are abstracted away.
Check the general types, do nothing to the concrete types which may only be
solved after segregation. Later the concrete types will need to be checked
for type consistency and correctness of packers.
TypeU --> Type
lookup a general type associated with an index
standardize naming of qualifiers
prepare a general, indexed typechecking error
it is possible to export just a type signature
if a term is associated with no expression or type
This branch is entered for exported type definitions
FIXME: return all definitions and their parameters, check parameter count
this should not happen
Check for any existing type signature annotations
If there are no annotations, synthesize
If there are annotations ...
If the annotation is of a variable name, return the annotation. Calling
check would just re-synthesize the same type and check that it was
equal to itself.
Otherwise check the annotation type
finally cons the head element back and apply everything we learned
-->E0
-->E
synthesize the type of the function
eta expand
If the term was eta-expanded, retypecheck it
Otherwise proceed
extend the function type with the type of the expressions it is applied to
determine the type after application
full application
partial application
put the AppS back together with the synthesized function and input expressions
-->I==>
create existentials for everything and pass it off to check
List
Tuple
synthesize head
synthesize tail
merge the head and tail
the general tuple will always be (AppU _ _)
synth does not change data constructors
Records
type the head
type the tail
merge the head with tail
synth does not change data constructors
Sources are axiomatic. They are they type they are said to be.
no, then I don't know what it is and will return an existential
if this existential is never solved, then it will become universal later
Any morloc variables should have been expanded by treeify. Any bound
variables should be checked against. I think (this needs formalization).
is this a bound variable that has already been solved
yes, return the solved type
no, so is it a variable that has a type annotation?
no, then I don't know what it is and will return an existential
if this existential is never solved, then it will become universal later
A partially applied term intended to return a function (e.g., `(\x y -> add x y) x |- Real -> Real`)
A fully applied term
possibly illegal application, will type check after expansion
the expressions that are passed to the function
the function type
output function type
@e@, with type annotation
g1 |- e <= A -| g2
----------------------------------------- -->App
g1 |- A->C o e =>> C -| g2
g1,Ea |- [Ea/a]A o e =>> C -| g2
----------------------------------------- Forall App
g1 |- Forall x.A o e =>> C -| g2
----------------------------------------- EaApp
g1[Ea] |- Ea o e =>> Ea2 -| g2
replace <t0> with <t0>:<ea1> -> <ea2>
if the variable has already been solved, use solved value
Tip together the arguments passed to an application
remainder
If there are fewer arguments than types, this may be OK, just partial application
If there are fewer types than arguments, then die
LstS [] will go to the normal Sub case
Sub
-- debugging
peak x = say $ f x where
peak x = say $ f x where
apply context to a SAnno | # LANGUAGE ViewPatterns #
|
Module : Morloc . Frontend . : Core inference module
Copyright : ( c ) , 2021
License : GPL-3
Maintainer :
Stability : experimental
Module : Morloc.Frontend.Typecheck
Description : Core inference module
Copyright : (c) Zebulun Arendsee, 2021
License : GPL-3
Maintainer :
Stability : experimental
-}
module Morloc.Frontend.Typecheck (typecheck, resolveTypes) where
import Morloc.Frontend.Namespace
import Morloc.Typecheck.Internal
import Morloc.Pretty
import Morloc.Data.Doc
import qualified Morloc.Frontend.Lang.DefaultTypes as MLD
import qualified Morloc.Data.GMap as GMap
import qualified Morloc.Monad as MM
import qualified Morloc.Data.Text as MT
import qualified Control.Monad.State as CMS
import qualified Data.Map as Map
import Data.Bifunctor (first)
| Each SAnno object in the input list represents one exported function .
typecheck
:: [SAnno Int Many Int]
-> MorlocMonad [SAnno (Indexed TypeU) Many Int]
typecheck xs = error . MT.unpack . render . . map ( prettySAnno viaShow viaShow ) $ xs
typecheck = mapM run where
run :: SAnno Int Many Int -> MorlocMonad (SAnno (Indexed TypeU) Many Int)
run e0 = do
standardize names for lambda bound variables ( e.g. , , x1 ... )
let g0 = Gamma {gammaCounter = 0, gammaContext = []}
((_, g1), e1) = renameSAnno (Map.empty, g0) e0
(g2, _, e2) <- synthG' g1 e1
say "-------- leaving frontend typechecker ------------------"
say "g2:"
seeGamma g2
say "e2:"
peakGen e2
say "========================================================"
return $ mapSAnno (fmap normalizeType) id . applyGen g2 $ e2
resolveTypes :: SAnno (Indexed TypeU) Many Int -> SAnno (Indexed Type) Many Int
resolveTypes (SAnno (Many es) (Idx i t))
= SAnno (Many (map (first f) es)) (Idx i (typeOf t)) where
f :: SExpr (Indexed TypeU) Many Int -> SExpr (Indexed Type) Many Int
f (AccS x k) = AccS (resolveTypes x) k
f (AppS x xs) = AppS (resolveTypes x) (map resolveTypes xs)
f (LamS vs x) = LamS vs (resolveTypes x)
f (LstS xs) = LstS (map resolveTypes xs)
f (TupS xs) = TupS (map resolveTypes xs)
f (NamS rs) = NamS (zip (map fst rs) (map (resolveTypes . snd) rs))
f (RealS x) = RealS x
f (IntS x) = IntS x
f (LogS x) = LogS x
f (StrS x) = StrS x
f (CallS x) = CallS x
f UniS = UniS
f (VarS x) = VarS x
lookupType :: Int -> Gamma -> MorlocMonad (Maybe (Gamma, TypeU))
lookupType i g = do
m <- CMS.gets stateSignatures
return $ case GMap.lookup i m of
GMapJust (TermTypes (Just (EType t _ _)) _ _) -> Just $ rename g t
_ -> Nothing
gerr :: Int -> TypeError -> MorlocMonad a
gerr i e = MM.throwError $ IndexedError i (GeneralTypeError e)
synthG
:: Gamma
-> SAnno Int Many Int
-> MorlocMonad
( Gamma
, TypeU
, SAnno (Indexed TypeU) Many Int
)
synthG g (SAnno (Many []) i) = do
maybeType <- lookupType i g
case maybeType of
(Just (g', t)) -> return (g', t, SAnno (Many []) (Idx i t))
Nothing -> do
maybeName <- CMS.gets (Map.lookup i . stateName)
case maybeName of
(Just (EV v)) -> return (g, VarU (TV Nothing v), SAnno (Many []) (Idx i (VarU (TV Nothing v))))
synthG g0 (SAnno (Many ((e0, j):es)) i) = do
maybeType <- lookupType i g0
(g1, t1, e1) <- case maybeType of
Nothing -> synthE' i g0 e0
(Just (g', t)) -> case e0 of
(VarS v) -> return (g', t, VarS v)
_ -> checkE' i g' e0 t
Check all other implementations against the first one
(g2, t2, SAnno (Many es') _) <- checkG' g1 (SAnno (Many es) i) t1
let finalExpr = applyGen g2 $ SAnno (Many ((e1, j):es')) (Idx i t2)
return (g2, t2, finalExpr)
checkG
:: Gamma
-> SAnno Int Many Int
-> TypeU
-> MorlocMonad
( Gamma
, TypeU
, SAnno (Indexed TypeU) Many Int
)
checkG g (SAnno (Many []) i) t = return (g, t, SAnno (Many []) (Idx i t))
checkG g0 (SAnno (Many ((e, j):es)) i) t0 = do
(g1, t1, e') <- checkE' i g0 e t0
(g2, t2, SAnno (Many es') idType) <- checkG' g1 (SAnno (Many es) i) t1
return (g2, t2, SAnno (Many ((e', j):es')) idType)
synthE
:: Int
-> Gamma
-> SExpr Int Many Int
-> MorlocMonad
( Gamma
, TypeU
, SExpr (Indexed TypeU) Many Int
)
synthE _ g UniS = return (g, MLD.defaultGeneralType UniS, UniS)
synthE _ g (RealS x) = return (g, MLD.defaultGeneralType (RealS x), RealS x)
synthE _ g (IntS x) = return (g, MLD.defaultGeneralType (IntS x), IntS x)
synthE _ g (LogS x) = return (g, MLD.defaultGeneralType (LogS x), LogS x)
synthE _ g (StrS x) = return (g, MLD.defaultGeneralType (StrS x), StrS x)
synthE i g (AccS e k) = do
(g1, t1, e1) <- synthG' g e
valType <- case t1 of
(NamU _ _ _ rs) -> case lookup k rs of
Nothing -> gerr i (KeyError k t1)
(Just t) -> return t
_ -> gerr i (KeyError k t1)
return (g1, valType, AccS e1 k)
synthE _ g (AppS f []) = do
(g1, t1, f1) <- synthG' g f
return (g1, t1, AppS f1 [])
synthE i g0 (AppS f xs0) = do
(g1, funType0, funExpr0) <- synthG g0 f
mayExpanded <- etaExpand g1 f xs0 funType0
case mayExpanded of
(Just (g', x')) -> synthE i g' x'
Nothing -> do
(g2, funType1, inputExprs) <- application' i g1 xs0 (normalizeType funType0)
appliedType <- case funType1 of
(FunU ts t) -> case drop (length inputExprs) ts of
_ -> error "impossible"
return (g2, apply g2 appliedType, AppS (applyGen g2 funExpr0) inputExprs)
synthE i g0 f@(LamS vs x) = do
(g1, bodyType, _) <- synthG g0 x
let n = nfargs bodyType
if n > 0
then do
(g2, f2) <- expand n g1 f
say $ "Expanded in -->I==>:" <+> prettySExpr (const "") (const "") f2
synthE i g2 f2
else do
let (g2, ts) = statefulMap (\g' v -> newvar (unEVar v <> "_x") Nothing g') g1 vs
(g3, ft) = newvar "o_" Nothing g2
finalType = FunU ts ft
checkE' i g3 f finalType
where
nfargs :: TypeU -> Int
nfargs (FunU ts _) = length ts
nfargs (ForallU _ f') = nfargs f'
nfargs _ = 0
synthE _ g (LstS []) =
let (g1, itemType) = newvar "itemType_" Nothing g
listType = head $ MLD.defaultList Nothing itemType
in return (g1, listType, LstS [])
synthE i g (LstS (e:es)) = do
(g1, itemType, itemExpr) <- synthG' g e
(g2, listType, listExpr) <- checkE' i g1 (LstS es) (head $ MLD.defaultList Nothing itemType)
case listExpr of
(LstS es') -> return (g2, listType, LstS (itemExpr:es'))
_ -> error "impossible"
synthE _ g (TupS []) =
let t = head $ MLD.defaultTuple Nothing []
in return (g, t, TupS [])
synthE i g (TupS (e:es)) = do
(g1, itemType, itemExpr) <- synthG' g e
(g2, tupleType, tupleExpr) <- synthE' i g1 (TupS es)
t3 <- case tupleType of
(AppU _ ts) -> return . head $ MLD.defaultTuple Nothing (apply g2 itemType : ts)
xs' <- case tupleExpr of
(TupS xs') -> return xs'
return (g2, t3, TupS (itemExpr:xs'))
synthE _ g (NamS []) = return (g, head $ MLD.defaultRecord Nothing [], NamS [])
synthE i g0 (NamS ((k,x):rs)) = do
say $ "Entering synthE NamS (k=" <> pretty k <> ")"
seeGamma g0
say "-------- syn"
(g1, headType, headExpr) <- synthG' g0 x
(g2, tailType, tailExpr) <- synthE' i g1 (NamS rs)
say $ "Exiting synthE NamS (k=" <> pretty k <> ")"
say $ " k type:" <+> pretty headType
seeGamma g2
say "-------- syn"
t <- case tailType of
(NamU o1 n1 ps1 rs1) -> return $ NamU o1 n1 ps1 ((k, apply g2 headType):rs1)
the synthE on NamS will always return NamU type
tailExprs <- case tailExpr of
(NamS xs') -> return xs'
return (g2, t, NamS ((k, headExpr):tailExprs))
synthE i g (CallS src) = do
maybeType <- lookupType i g
(g', t) <- case maybeType of
Just x -> return x
Nothing -> return $ newvar "src_" Nothing g
return (g', t, CallS src)
synthE i g (VarS v) = do
(g', t') <- case lookupE v g of
(Just t) -> return (g, t)
Nothing -> do
maybeType <- lookupType i g
case maybeType of
Just x -> return x
Nothing -> return $ newvar (unEVar v <> "_u") Nothing g
return (g', t', VarS v)
etaExpand :: Gamma -> SAnno Int Many Int -> [SAnno Int Many Int] -> TypeU -> MorlocMonad (Maybe (Gamma, SExpr Int Many Int))
etaExpand g0 f0 xs0@(length -> termSize) (normalizeType -> FunU (length -> typeSize) _)
| termSize == typeSize = return Nothing
| otherwise = Just <$> etaExpandE g0 (AppS f0 xs0)
where
etaExpandE :: Gamma -> SExpr Int Many Int -> MorlocMonad (Gamma, SExpr Int Many Int)
etaExpandE g e@(AppS _ _) = tryExpand (typeSize - termSize) g e
etaExpandE g e@(LamS vs _) = tryExpand (typeSize - termSize - length vs) g e
etaExpandE g e = return (g, e)
tryExpand n g e
| n <= 0 = return (g, e)
| otherwise = expand n g e
etaExpand _ _ _ _ = return Nothing
expand :: Int -> Gamma -> SExpr Int Many Int -> MorlocMonad (Gamma, SExpr Int Many Int)
expand 0 g x = return (g, x)
expand n g e@(AppS _ _) = do
newIndex <- MM.getCounter
let (g', v') = evarname g "v"
e' <- applyExistential v' e
let x' = LamS [v'] (SAnno (Many [(e', newIndex)]) newIndex)
expand (n-1) g' x'
expand n g (LamS vs' (SAnno (Many es0') t)) = do
let (g', v') = evarname g "v"
es1' <- mapM (applyExistential v' . fst) es0'
expand (n-1) g' (LamS (vs' <> [v']) (SAnno (Many (zip es1' (map snd es0'))) t))
expand _ g x = return (g, x)
applyExistential :: EVar -> SExpr Int Many Int -> MorlocMonad (SExpr Int Many Int)
applyExistential v' (AppS f xs') = do
newIndex <- MM.getCounter
return $ AppS f (xs' <> [SAnno (Many [(VarS v', newIndex)]) newIndex])
applyExistential v' e = do
appIndex <- MM.getCounter
varIndex <- MM.getCounter
return $ AppS (SAnno (Many [(e, appIndex)]) appIndex) [SAnno (Many [(VarS v', varIndex)]) varIndex]
application
:: Int
-> Gamma
-> MorlocMonad
( Gamma
)
application i g0 es0 (FunU as0 b0) = do
(g1, as1, es1, remainder) <- zipCheck i g0 es0 as0
let es2 = map (applyGen g1) es1
funType = apply g1 $ FunU (as1 <> remainder) b0
say $ "remainder:" <+> vsep (map pretty remainder)
return (g1, funType, es2)
application i g0 es (ForallU v s) = application' i (g0 +> v) es (substitute v s)
g1[Ea2 , Ea1 , Ea = Ea1->Ea2 ] |- e < = Ea1 -| g2
application i g0 es (ExistU v@(TV _ s) [] _) =
case access1 v (gammaContext g0) of
Just (rs, _, ls) -> do
let (g1, veas) = statefulMap (\g _ -> tvarname g "a_" Nothing) g0 es
(g2, vea) = tvarname g1 (s <> "o_") Nothing
eas = [ExistU v' [] [] | v' <- veas]
ea = ExistU vea [] []
f = FunU eas ea
g3 = g2 {gammaContext = rs <> [SolvedG v f] <> map index eas <> [index ea] <> ls}
(g4, _, es', _) <- zipCheck i g3 es eas
return (g4, apply g4 f, map (applyGen g4) es')
Nothing -> case lookupU v g0 of
(Just (FunU ts t)) -> do
(g1, ts', es', _) <- zipCheck i g0 es ts
return (g1, apply g1 (FunU ts' t), es')
_ -> gerr i ApplicationOfNonFunction
application i _ _ _ = do
gerr i ApplicationOfNonFunction
zipCheck
:: Int
-> Gamma
-> [SAnno Int Many Int]
-> [TypeU]
-> MorlocMonad
( Gamma
, [TypeU]
, [SAnno (Indexed TypeU) Many Int]
)
check the first elements , cdr down the remaining values
zipCheck i g0 (x0:xs0) (t0:ts0) = do
(g1, t1, x1) <- checkG' g0 x0 t0
(g2, ts1, xs1, remainder) <- zipCheck i g1 xs0 ts0
return (g2, t1:ts1, x1:xs1, remainder)
zipCheck _ g0 [] ts = return (g0, [], [], ts)
zipCheck i _ _ [] = gerr i TooManyArguments
checkE
:: Int
-> Gamma
-> SExpr Int Many Int
-> TypeU
-> MorlocMonad
( Gamma
, TypeU
, SExpr (Indexed TypeU) Many Int
)
checkE i g1 (LstS (e:es)) (AppU v [t]) = do
(g2, t2, e') <- checkG' g1 e t
(g3, t3, LstS es') <- checkE i g2 (LstS es) (AppU v [t2])
return (g3, t3, LstS (map (applyGen g3) (e':es')))
checkE i g0 e0@(LamS vs body) t@(FunU as b)
| length vs == length as = do
let g1 = g0 ++> zipWith AnnG vs as
(g2, t2, e2) <- checkG' g1 body b
let t3 = apply g2 (FunU as t2)
e3 = applyCon g2 (LamS vs e2)
return (g2, t3, e3)
| otherwise = do
(g', e') <- expand (length as - length vs) g0 e0
checkE i g' e' t
checkE i g1 e1 (ForallU v a) = checkE' i (g1 +> v) e1 (substitute v a)
checkE i g1 e1 b = do
(g2, a, e2) <- synthE' i g1 e1
let a' = apply g2 a
b' = apply g2 b
g3 <- subtype' i a' b' g2
return (g3, apply g3 b', e2)
subtype' :: Int -> TypeU -> TypeU -> Gamma -> MorlocMonad Gamma
subtype' i a b g = do
say $ parens (pretty a) <+> "<:" <+> parens (pretty b)
case subtype a b g of
(Left err') -> gerr i err'
(Right x) -> return x
enter :: Doc ann -> MorlocMonad ()
enter d = do
depth <- MM.incDepth
debugLog $ pretty (replicate depth '-') <> ">" <+> d <> "\n"
say :: Doc ann -> MorlocMonad ()
say d = do
depth <- MM.getDepth
debugLog $ pretty (replicate depth ' ') <> ":" <+> d <> "\n"
seeGamma :: Gamma -> MorlocMonad ()
seeGamma g = say $ nest 4 $ "Gamma:" <> line <> vsep (map pretty (gammaContext g))
seeType :: TypeU -> MorlocMonad ()
seeType t = say $ pretty t
leave :: Doc ann -> MorlocMonad ()
leave d = do
depth <- MM.decDepth
debugLog $ "<" <> pretty (replicate (depth+1) '-') <+> d <> "\n"
debugLog :: Doc ann -> MorlocMonad ()
debugLog d = do
verbosity <- MM.gets stateVerbosity
when (verbosity > 0) $ (liftIO . putDoc) d
synthG' g x = do
enter "synthG"
r <- synthG g x
leave "synthG"
return r
checkG' g x t = do
enter "checkG"
r <- checkG g x t
leave "checkG"
return r
synthE' i g x = do
enter "synthE"
peak x
seeGamma g
r@(g', t, x') <- synthE i g x
leave "synthE"
peak x'
seeGamma g'
seeType t
return r
checkE' i g x t = do
enter "checkE"
peak x
seeType t
seeGamma g
r@(g', t', x') <- checkE i g x t
leave "checkE"
peak x'
seeType t'
seeGamma g'
return r
application' i g es t = do
enter "application"
seeGamma g
seeType t
mapM_ peakGen es
r@(g',t',es') <- application i g es t
leave "application"
seeGamma g'
seeType t'
mapM_ peakGen es'
return r
peak :: Foldable f => SExpr g f c -> MorlocMonad ()
peak = say . prettySExpr (const "") (const "")
peakGen :: Foldable f => SAnno g f c -> MorlocMonad ()
peakGen = say . prettySAnno (const "") (const "")
applyGen :: (Functor gf, Functor f, Applicable g)
=> Gamma -> SAnno (gf g) f c -> SAnno (gf g) f c
applyGen g = mapSAnno (fmap (apply g)) id
applyCon :: (Functor gf, Functor f, Applicable g)
=> Gamma -> SExpr (gf g) f c -> SExpr (gf g) f c
applyCon g = mapSExpr (fmap (apply g)) id
|
cfbd303bd12586ec9e4ca503032a031b43c2d063198dd369d550ed3e9cd49471 | metaocaml/ber-metaocaml | typetexp.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Typechecking of type expressions for the core language *)
open Types
val valid_tyvar_name : string -> bool
val transl_simple_type:
Env.t -> bool -> Parsetree.core_type -> Typedtree.core_type
val transl_simple_type_univars:
Env.t -> Parsetree.core_type -> Typedtree.core_type
val transl_simple_type_delayed:
Env.t -> Parsetree.core_type -> Typedtree.core_type * (unit -> unit)
(* Translate a type, but leave type variables unbound. Returns
the type and a function that binds the type variable. *)
val transl_type_scheme:
Env.t -> Parsetree.core_type -> Typedtree.core_type
val reset_type_variables: unit -> unit
val type_variable: Location.t -> string -> type_expr
val transl_type_param:
Env.t -> Parsetree.core_type -> Typedtree.core_type
type variable_context
val narrow: unit -> variable_context
val widen: variable_context -> unit
exception Already_bound
type error =
Unbound_type_variable of string
| Undefined_type_constructor of Path.t
| Type_arity_mismatch of Longident.t * int * int
| Bound_type_variable of string
| Recursive_type
| Unbound_row_variable of Longident.t
| Type_mismatch of Ctype.Unification_trace.t
| Alias_type_mismatch of Ctype.Unification_trace.t
| Present_has_conjunction of string
| Present_has_no_type of string
| Constructor_mismatch of type_expr * type_expr
| Not_a_variant of type_expr
| Variant_tags of string * string
| Invalid_variable_name of string
| Cannot_quantify of string * type_expr
| Multiple_constraints_on_type of Longident.t
| Method_mismatch of string * type_expr * type_expr
| Opened_object of Path.t option
| Not_an_object of type_expr
exception Error of Location.t * Env.t * error
val report_error: Env.t -> Format.formatter -> error -> unit
Support for first - class modules .
from
(Location.t -> Env.t -> Longident.t -> Path.t) ref
from
(Env.t -> Parsetree.module_type -> Typedtree.module_type) ref
val create_package_mty:
Location.t -> Env.t -> Parsetree.package_type ->
(Longident.t Asttypes.loc * Parsetree.core_type) list *
Parsetree.module_type
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/typing/typetexp.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Typechecking of type expressions for the core language
Translate a type, but leave type variables unbound. Returns
the type and a function that binds the type variable. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Types
val valid_tyvar_name : string -> bool
val transl_simple_type:
Env.t -> bool -> Parsetree.core_type -> Typedtree.core_type
val transl_simple_type_univars:
Env.t -> Parsetree.core_type -> Typedtree.core_type
val transl_simple_type_delayed:
Env.t -> Parsetree.core_type -> Typedtree.core_type * (unit -> unit)
val transl_type_scheme:
Env.t -> Parsetree.core_type -> Typedtree.core_type
val reset_type_variables: unit -> unit
val type_variable: Location.t -> string -> type_expr
val transl_type_param:
Env.t -> Parsetree.core_type -> Typedtree.core_type
type variable_context
val narrow: unit -> variable_context
val widen: variable_context -> unit
exception Already_bound
type error =
Unbound_type_variable of string
| Undefined_type_constructor of Path.t
| Type_arity_mismatch of Longident.t * int * int
| Bound_type_variable of string
| Recursive_type
| Unbound_row_variable of Longident.t
| Type_mismatch of Ctype.Unification_trace.t
| Alias_type_mismatch of Ctype.Unification_trace.t
| Present_has_conjunction of string
| Present_has_no_type of string
| Constructor_mismatch of type_expr * type_expr
| Not_a_variant of type_expr
| Variant_tags of string * string
| Invalid_variable_name of string
| Cannot_quantify of string * type_expr
| Multiple_constraints_on_type of Longident.t
| Method_mismatch of string * type_expr * type_expr
| Opened_object of Path.t option
| Not_an_object of type_expr
exception Error of Location.t * Env.t * error
val report_error: Env.t -> Format.formatter -> error -> unit
Support for first - class modules .
from
(Location.t -> Env.t -> Longident.t -> Path.t) ref
from
(Env.t -> Parsetree.module_type -> Typedtree.module_type) ref
val create_package_mty:
Location.t -> Env.t -> Parsetree.package_type ->
(Longident.t Asttypes.loc * Parsetree.core_type) list *
Parsetree.module_type
|
2de4f70e120df7199c6c3d48db2a043cfa8ab97122e95b660be61fed06feff1f | threatgrid/ctim | campaigns.cljc | (ns ctim.examples.campaigns
(:require [ctim.schemas.common :as c]))
(def campaign-maximal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:names ["foo" "bar"]
:schema_version c/ctim-schema-version
:revision 1
:external_ids ["-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
"-20e0b949-2bbe-4b5d-8916-dd1cf5acd7d8"]
:external_references
[{:source_name "source"
:external_id "T1067"
:url ""
:hashes ["#section1"]
:description "Description text"}]
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:language "language"
:title "campaign"
:description "description"
:short_description "short description"
:source "source"
:source_uri "/"
:tlp "red"
:campaign_type "anything goes here"
:intended_effect ["Theft"]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}
:status "Future"
:confidence "High"
:activity [{:date_time #inst "2016-02-11T00:40:48.212-00:00"
:description "activity"}]})
(def campaign-minimal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:schema_version c/ctim-schema-version
:title "campaign"
:description "description"
:short_description "short description"
:campaign_type "anything goes here"
:valid_time {}})
(def new-campaign-maximal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:names ["foo" "bar"]
:schema_version c/ctim-schema-version
:revision 1
:external_ids ["-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
"-20e0b949-2bbe-4b5d-8916-dd1cf5acd7d8"]
:external_references
[{:source_name "source"
:external_id "T1067"
:url ""
:hashes ["#section1"]
:description "Description text"}]
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:language "language"
:title "campaign"
:description "description"
:short_description "short description"
:source "source"
:source_uri "/"
:tlp "red"
:campaign_type "anything goes here"
:intended_effect ["Theft"]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}
:status "Future"
:confidence "High"
:activity [{:date_time #inst "2016-02-11T00:40:48.212-00:00"
:description "activity"}]})
(def new-campaign-minimal
{:title "campaign"
:description "description"
:short_description "short description"
:campaign_type "anything goes here"})
| null | https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/src/ctim/examples/campaigns.cljc | clojure | (ns ctim.examples.campaigns
(:require [ctim.schemas.common :as c]))
(def campaign-maximal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:names ["foo" "bar"]
:schema_version c/ctim-schema-version
:revision 1
:external_ids ["-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
"-20e0b949-2bbe-4b5d-8916-dd1cf5acd7d8"]
:external_references
[{:source_name "source"
:external_id "T1067"
:url ""
:hashes ["#section1"]
:description "Description text"}]
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:language "language"
:title "campaign"
:description "description"
:short_description "short description"
:source "source"
:source_uri "/"
:tlp "red"
:campaign_type "anything goes here"
:intended_effect ["Theft"]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}
:status "Future"
:confidence "High"
:activity [{:date_time #inst "2016-02-11T00:40:48.212-00:00"
:description "activity"}]})
(def campaign-minimal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:schema_version c/ctim-schema-version
:title "campaign"
:description "description"
:short_description "short description"
:campaign_type "anything goes here"
:valid_time {}})
(def new-campaign-maximal
{:id "-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
:type "campaign"
:names ["foo" "bar"]
:schema_version c/ctim-schema-version
:revision 1
:external_ids ["-b1f8e40a-0e99-48fc-bb12-32a65421cfb5"
"-20e0b949-2bbe-4b5d-8916-dd1cf5acd7d8"]
:external_references
[{:source_name "source"
:external_id "T1067"
:url ""
:hashes ["#section1"]
:description "Description text"}]
:timestamp #inst "2016-02-11T00:40:48.212-00:00"
:language "language"
:title "campaign"
:description "description"
:short_description "short description"
:source "source"
:source_uri "/"
:tlp "red"
:campaign_type "anything goes here"
:intended_effect ["Theft"]
:valid_time {:start_time #inst "2016-02-11T00:40:48.212-00:00"
:end_time #inst "2016-07-11T00:40:48.212-00:00"}
:status "Future"
:confidence "High"
:activity [{:date_time #inst "2016-02-11T00:40:48.212-00:00"
:description "activity"}]})
(def new-campaign-minimal
{:title "campaign"
:description "description"
:short_description "short description"
:campaign_type "anything goes here"})
|
|
4ac255b48f7d8ab9a8f526ba8bb87d22972d0eb09cd0a8922dd677f9ac4fa9a1 | 3b/3bgl-misc | ttf-extrude-example.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
Render 3d characters using and - tess , with geometry
drawn through VBO / VAO
(defpackage #:glu-ttf-extrude-example
(:use :cl :glu-ttf-extrude :zpb-ttf :alexandria :basecode)
(:export #:ttf-tess-window))
(in-package #:glu-ttf-extrude-example)
(defclass ttf-tess-window (basecode-glut perspective-projection basecode-clear
fps-graph basecode-draw-ground-plane
freelook-camera)
((vbos :accessor vbos :initform nil)
(vaos :accessor vaos :initform nil)
(counts :accessor counts :initform nil)
(font-path :accessor font-path :initarg :font-path)
(mesh-count :accessor mesh-count :initarg :mesh-count)
(angle :accessor angle :initform 0.0)
(wireframe :accessor wireframe :initform nil))
(:default-initargs :width 640 :height 480 :title "ttf-extrude"
:mesh-count 2000
:look-at-eye '(-5 10 -15)))
(defmethod free-buffers ((w ttf-tess-window))
(gl:delete-buffers (vbos w))
(gl:delete-vertex-arrays (vaos w)))
(defmethod load-glyphs ((w ttf-tess-window))
(declare (optimize debug))
(free-buffers w)
(let ((s (random most-positive-fixnum)))
(format t "seed = ~s~%" s)
(setf *random-state* (sb-ext:seed-random-state s)))
(with-font-loader (loader (font-path w))
;; we pick some random characters from the font, up to the number
;; specified in the class instance, or the number available
;; whichever is lower
(format t "total glyphs = ~s~%" (glyph-count loader))
(let* ((c (min (glyph-count loader)
(mesh-count w)))
;; select C glyphs at random (not very efficiently, but
;; we only need to do it once...)
(glyphs (loop for i in (iota (glyph-count loader))
#++(shuffle (iota (glyph-count loader)))
for g = (index-glyph i loader)
when (plusp (code-point g))
collect g
and count 1 into count
while (< count c)))
for each character , we want 2 VBOs and a VAO
(buffers (gl:gen-buffers (* c 2)))
(vaos (gl:gen-vertex-arrays c))
(counts (make-array c :initial-element 0)))
(setf (vbos w) buffers
(vaos w) vaos
(counts w) counts)
;; loop through all of the characters, triangulate and extrude them,
;; then build the VBOs/VAOs from the triangle data
(loop
for i from 0
for va in vaos
for (vb ib) on buffers by #'cddr
for glyph in glyphs
for extruded = (extrude-glyph glyph loader)
do
and build the VBOs and VAO
(setf (aref (counts w) i)
(fill-buffers extruded vb ib va))))))
(defmethod basecode-init ((w ttf-tess-window))
(declare (optimize debug))
(glut:set-key-repeat :key-repeat-off)
(load-glyphs w))
(defmethod glut:tick ((w ttf-tess-window))
(glut:post-redisplay))
(defparameter *tris* 0)
(defparameter *w* nil)
(defmethod basecode-draw ((w ttf-tess-window))
(declare (optimize debug))
(setf *w* w)
(let ((seconds-per-revolution 6))
(incf (angle w)
(/ (* 2 pi) (* 5 seconds-per-revolution))))
(gl:clear-color 0.0 0.0 0.2 1.0)
(gl:with-pushed-matrix* (:modelview)
(let ((tris 0)
(dz 1))
(flet ((rx ()
(gl:with-pushed-matrix* (:modelview)
(gl:rotate (* 2 (angle w)) 0 0 1)
(gl:light :light0 :position (list 10 0 10 1.0)))))
(gl:enable :line-smooth :point-smooth :polygon-smooth :blend
:depth-test :lighting :light0 :multisample)
(gl:point-size 1)
(gl:blend-func :src-alpha :one-minus-src-alpha)
(gl:enable :cull-face)
(gl:light :light0 :position (list 0.2 0.7 0.2 1.0))
(dotimes (x dz)
(gl:translate 0 0 (/ (1+ x) 2.2))
(gl:with-pushed-matrix* (:modelview)
(rx)
(loop for vao in (vaos w)
for i from 0
for count across (counts w)
for tx = 0.55
for ty = 1
for d = 80
for dh = 25
for x = (mod i d)
for y = (mod (floor i d) dh)
for z = (floor i (* d dh))
do
(gl:with-pushed-matrix* (:modelview)
(incf tris count)
(gl:translate (* (- x (* d 0.5)) tx)
(* y ty)
(* (+ z (* dz -0.5)) 1))
(gl:bind-vertex-array vao)
(gl:point-size 5)
(gl:disable :lighting)
(gl:color 0 1 0 0.4)
#++(gl:draw-elements :points (gl:make-null-gl-array :unsigned-short) :count count)
(if (wireframe w)
(progn
(gl:disable :lighting)
(gl:color 0 0 0 1)
(gl:polygon-mode :front-and-back :fill)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count)
(gl:line-width 1.5)
(gl:color 0 1 0 1)
(gl:polygon-mode :front-and-back :line)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count))
(progn
(gl:color 1 0 0 1)
(gl:enable :lighting)
(gl:polygon-mode :front-and-back :fill)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count))))))))
(setf *tris* tris))))
(defmethod glut:keyboard :after ((w ttf-tess-window) key x y)
(declare (ignore x y) (optimize debug))
(with-simple-restart (continue "Continue")
(case key
(#\m (print (gl:get* :front-face)))
(#\1 (setf (wireframe w) (not (wireframe w))))
(#\space (time (load-glyphs w))))))
(defmethod glut:close :before ((w ttf-tess-window))
(free-buffers w))
(defun ttf-tess ()
(let ((w (make-instance 'ttf-tess-window
:font-path
(or (probe-file "/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf")
(probe-file "c:/windows/fonts/consola.ttf")
(probe-file "c:/windows/fonts/georgia.ttf")))))
(unwind-protect
(basecode-run w)
(glut:destroy-window (glut:id w)))))
;; (ttf-tess)
| null | https://raw.githubusercontent.com/3b/3bgl-misc/e3bf2781d603feb6b44e5c4ec20f06225648ffd9/ttf/ttf-extrude-example.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
we pick some random characters from the font, up to the number
specified in the class instance, or the number available
whichever is lower
select C glyphs at random (not very efficiently, but
we only need to do it once...)
loop through all of the characters, triangulate and extrude them,
then build the VBOs/VAOs from the triangle data
(ttf-tess) | Render 3d characters using and - tess , with geometry
drawn through VBO / VAO
(defpackage #:glu-ttf-extrude-example
(:use :cl :glu-ttf-extrude :zpb-ttf :alexandria :basecode)
(:export #:ttf-tess-window))
(in-package #:glu-ttf-extrude-example)
(defclass ttf-tess-window (basecode-glut perspective-projection basecode-clear
fps-graph basecode-draw-ground-plane
freelook-camera)
((vbos :accessor vbos :initform nil)
(vaos :accessor vaos :initform nil)
(counts :accessor counts :initform nil)
(font-path :accessor font-path :initarg :font-path)
(mesh-count :accessor mesh-count :initarg :mesh-count)
(angle :accessor angle :initform 0.0)
(wireframe :accessor wireframe :initform nil))
(:default-initargs :width 640 :height 480 :title "ttf-extrude"
:mesh-count 2000
:look-at-eye '(-5 10 -15)))
(defmethod free-buffers ((w ttf-tess-window))
(gl:delete-buffers (vbos w))
(gl:delete-vertex-arrays (vaos w)))
(defmethod load-glyphs ((w ttf-tess-window))
(declare (optimize debug))
(free-buffers w)
(let ((s (random most-positive-fixnum)))
(format t "seed = ~s~%" s)
(setf *random-state* (sb-ext:seed-random-state s)))
(with-font-loader (loader (font-path w))
(format t "total glyphs = ~s~%" (glyph-count loader))
(let* ((c (min (glyph-count loader)
(mesh-count w)))
(glyphs (loop for i in (iota (glyph-count loader))
#++(shuffle (iota (glyph-count loader)))
for g = (index-glyph i loader)
when (plusp (code-point g))
collect g
and count 1 into count
while (< count c)))
for each character , we want 2 VBOs and a VAO
(buffers (gl:gen-buffers (* c 2)))
(vaos (gl:gen-vertex-arrays c))
(counts (make-array c :initial-element 0)))
(setf (vbos w) buffers
(vaos w) vaos
(counts w) counts)
(loop
for i from 0
for va in vaos
for (vb ib) on buffers by #'cddr
for glyph in glyphs
for extruded = (extrude-glyph glyph loader)
do
and build the VBOs and VAO
(setf (aref (counts w) i)
(fill-buffers extruded vb ib va))))))
(defmethod basecode-init ((w ttf-tess-window))
(declare (optimize debug))
(glut:set-key-repeat :key-repeat-off)
(load-glyphs w))
(defmethod glut:tick ((w ttf-tess-window))
(glut:post-redisplay))
(defparameter *tris* 0)
(defparameter *w* nil)
(defmethod basecode-draw ((w ttf-tess-window))
(declare (optimize debug))
(setf *w* w)
(let ((seconds-per-revolution 6))
(incf (angle w)
(/ (* 2 pi) (* 5 seconds-per-revolution))))
(gl:clear-color 0.0 0.0 0.2 1.0)
(gl:with-pushed-matrix* (:modelview)
(let ((tris 0)
(dz 1))
(flet ((rx ()
(gl:with-pushed-matrix* (:modelview)
(gl:rotate (* 2 (angle w)) 0 0 1)
(gl:light :light0 :position (list 10 0 10 1.0)))))
(gl:enable :line-smooth :point-smooth :polygon-smooth :blend
:depth-test :lighting :light0 :multisample)
(gl:point-size 1)
(gl:blend-func :src-alpha :one-minus-src-alpha)
(gl:enable :cull-face)
(gl:light :light0 :position (list 0.2 0.7 0.2 1.0))
(dotimes (x dz)
(gl:translate 0 0 (/ (1+ x) 2.2))
(gl:with-pushed-matrix* (:modelview)
(rx)
(loop for vao in (vaos w)
for i from 0
for count across (counts w)
for tx = 0.55
for ty = 1
for d = 80
for dh = 25
for x = (mod i d)
for y = (mod (floor i d) dh)
for z = (floor i (* d dh))
do
(gl:with-pushed-matrix* (:modelview)
(incf tris count)
(gl:translate (* (- x (* d 0.5)) tx)
(* y ty)
(* (+ z (* dz -0.5)) 1))
(gl:bind-vertex-array vao)
(gl:point-size 5)
(gl:disable :lighting)
(gl:color 0 1 0 0.4)
#++(gl:draw-elements :points (gl:make-null-gl-array :unsigned-short) :count count)
(if (wireframe w)
(progn
(gl:disable :lighting)
(gl:color 0 0 0 1)
(gl:polygon-mode :front-and-back :fill)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count)
(gl:line-width 1.5)
(gl:color 0 1 0 1)
(gl:polygon-mode :front-and-back :line)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count))
(progn
(gl:color 1 0 0 1)
(gl:enable :lighting)
(gl:polygon-mode :front-and-back :fill)
(gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count count))))))))
(setf *tris* tris))))
(defmethod glut:keyboard :after ((w ttf-tess-window) key x y)
(declare (ignore x y) (optimize debug))
(with-simple-restart (continue "Continue")
(case key
(#\m (print (gl:get* :front-face)))
(#\1 (setf (wireframe w) (not (wireframe w))))
(#\space (time (load-glyphs w))))))
(defmethod glut:close :before ((w ttf-tess-window))
(free-buffers w))
(defun ttf-tess ()
(let ((w (make-instance 'ttf-tess-window
:font-path
(or (probe-file "/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf")
(probe-file "c:/windows/fonts/consola.ttf")
(probe-file "c:/windows/fonts/georgia.ttf")))))
(unwind-protect
(basecode-run w)
(glut:destroy-window (glut:id w)))))
|
c83617f6f91f79ecfcdc6c53776899bf403d91ee6403675d85a73c9df6faeaf9 | kazu-yamamoto/cab | Printer.hs | # LANGUAGE CPP #
module Distribution.Cab.Printer (
printDeps
, printRevDeps
, extraInfo
) where
import Control.Monad
import Data.Function
import Data.List
import Data.Map (Map)
import qualified Data.Map as M
import Distribution.Cab.PkgDB
import Distribution.Cab.Version
import Distribution.Cab.Utils (UnitId, installedUnitId, lookupUnitId)
import Distribution.InstalledPackageInfo (author, depends, license)
import Distribution.License (License(..))
import Distribution.Simple.PackageIndex (allPackages)
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.License (licenseFromSPDX)
#endif
----------------------------------------------------------------
type RevDB = Map UnitId [UnitId]
makeRevDepDB :: PkgDB -> RevDB
makeRevDepDB db = M.fromList revdeps
where
pkgs = allPackages db
deps = map idDeps pkgs
idDeps pkg = (installedUnitId pkg, depends pkg)
kvs = sort $ concatMap decomp deps
decomp (k,vs) = map (\v -> (v,k)) vs
kvss = groupBy ((==) `on` fst) kvs
comp xs = (fst (head xs), map snd xs)
revdeps = map comp kvss
----------------------------------------------------------------
printDeps :: Bool -> Bool -> PkgDB -> Int -> PkgInfo -> IO ()
printDeps rec info db n pkgi = mapM_ (printDep rec info db n) $ depends pkgi
printDep :: Bool -> Bool -> PkgDB -> Int -> UnitId -> IO ()
printDep rec info db n uid = case lookupUnitId db uid of
Nothing -> return ()
Just uniti -> do
putStr $ prefix ++ fullNameOfPkgInfo uniti
extraInfo info uniti
putStrLn ""
when rec $ printDeps rec info db (n+1) uniti
where
prefix = replicate (n * 4) ' '
----------------------------------------------------------------
printRevDeps :: Bool -> Bool -> PkgDB -> Int -> PkgInfo -> IO ()
printRevDeps rec info db n pkgi = printRevDeps' rec info db revdb n pkgi
where
revdb = makeRevDepDB db
printRevDeps' :: Bool -> Bool -> PkgDB -> RevDB -> Int -> PkgInfo -> IO ()
printRevDeps' rec info db revdb n pkgi = case M.lookup unitid revdb of
Nothing -> return ()
Just unitids -> mapM_ (printRevDep' rec info db revdb n) unitids
where
unitid = installedUnitId pkgi
printRevDep' :: Bool -> Bool -> PkgDB -> RevDB -> Int -> UnitId -> IO ()
printRevDep' rec info db revdb n uid = case lookupUnitId db uid of
Nothing -> return ()
Just uniti -> do
putStr $ prefix ++ fullNameOfPkgInfo uniti
extraInfo info uniti
putStrLn ""
when rec $ printRevDeps' rec info db revdb (n+1) uniti
where
prefix = replicate (n * 4) ' '
----------------------------------------------------------------
extraInfo :: Bool -> PkgInfo -> IO ()
extraInfo False _ = return ()
extraInfo True pkgi = putStr $ " " ++ lcns ++ " \"" ++ show auth ++ "\""
where
lcns = showLicense (pkgInfoLicense pkgi)
auth = author pkgi
pkgInfoLicense :: PkgInfo -> License
#if MIN_VERSION_Cabal(2,2,0)
pkgInfoLicense = either licenseFromSPDX id . license
#else
pkgInfoLicense = license
#endif
showLicense :: License -> String
showLicense (GPL (Just v)) = "GPL" ++ versionToString v
showLicense (GPL Nothing) = "GPL"
showLicense (LGPL (Just v)) = "LGPL" ++ versionToString v
showLicense (LGPL Nothing) = "LGPL"
showLicense (UnknownLicense s) = s
showLicense x = show x
| null | https://raw.githubusercontent.com/kazu-yamamoto/cab/a7bdc7129b079b2d980e529c6ad8c4c6e0456d23/Distribution/Cab/Printer.hs | haskell | --------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
-------------------------------------------------------------- | # LANGUAGE CPP #
module Distribution.Cab.Printer (
printDeps
, printRevDeps
, extraInfo
) where
import Control.Monad
import Data.Function
import Data.List
import Data.Map (Map)
import qualified Data.Map as M
import Distribution.Cab.PkgDB
import Distribution.Cab.Version
import Distribution.Cab.Utils (UnitId, installedUnitId, lookupUnitId)
import Distribution.InstalledPackageInfo (author, depends, license)
import Distribution.License (License(..))
import Distribution.Simple.PackageIndex (allPackages)
#if MIN_VERSION_Cabal(2,2,0)
import Distribution.License (licenseFromSPDX)
#endif
type RevDB = Map UnitId [UnitId]
makeRevDepDB :: PkgDB -> RevDB
makeRevDepDB db = M.fromList revdeps
where
pkgs = allPackages db
deps = map idDeps pkgs
idDeps pkg = (installedUnitId pkg, depends pkg)
kvs = sort $ concatMap decomp deps
decomp (k,vs) = map (\v -> (v,k)) vs
kvss = groupBy ((==) `on` fst) kvs
comp xs = (fst (head xs), map snd xs)
revdeps = map comp kvss
printDeps :: Bool -> Bool -> PkgDB -> Int -> PkgInfo -> IO ()
printDeps rec info db n pkgi = mapM_ (printDep rec info db n) $ depends pkgi
printDep :: Bool -> Bool -> PkgDB -> Int -> UnitId -> IO ()
printDep rec info db n uid = case lookupUnitId db uid of
Nothing -> return ()
Just uniti -> do
putStr $ prefix ++ fullNameOfPkgInfo uniti
extraInfo info uniti
putStrLn ""
when rec $ printDeps rec info db (n+1) uniti
where
prefix = replicate (n * 4) ' '
printRevDeps :: Bool -> Bool -> PkgDB -> Int -> PkgInfo -> IO ()
printRevDeps rec info db n pkgi = printRevDeps' rec info db revdb n pkgi
where
revdb = makeRevDepDB db
printRevDeps' :: Bool -> Bool -> PkgDB -> RevDB -> Int -> PkgInfo -> IO ()
printRevDeps' rec info db revdb n pkgi = case M.lookup unitid revdb of
Nothing -> return ()
Just unitids -> mapM_ (printRevDep' rec info db revdb n) unitids
where
unitid = installedUnitId pkgi
printRevDep' :: Bool -> Bool -> PkgDB -> RevDB -> Int -> UnitId -> IO ()
printRevDep' rec info db revdb n uid = case lookupUnitId db uid of
Nothing -> return ()
Just uniti -> do
putStr $ prefix ++ fullNameOfPkgInfo uniti
extraInfo info uniti
putStrLn ""
when rec $ printRevDeps' rec info db revdb (n+1) uniti
where
prefix = replicate (n * 4) ' '
extraInfo :: Bool -> PkgInfo -> IO ()
extraInfo False _ = return ()
extraInfo True pkgi = putStr $ " " ++ lcns ++ " \"" ++ show auth ++ "\""
where
lcns = showLicense (pkgInfoLicense pkgi)
auth = author pkgi
pkgInfoLicense :: PkgInfo -> License
#if MIN_VERSION_Cabal(2,2,0)
pkgInfoLicense = either licenseFromSPDX id . license
#else
pkgInfoLicense = license
#endif
showLicense :: License -> String
showLicense (GPL (Just v)) = "GPL" ++ versionToString v
showLicense (GPL Nothing) = "GPL"
showLicense (LGPL (Just v)) = "LGPL" ++ versionToString v
showLicense (LGPL Nothing) = "LGPL"
showLicense (UnknownLicense s) = s
showLicense x = show x
|
e2956b66822471d08ababcd8c5a65a9450619c0c722d4e7bf795787249b0f0c3 | logicmoo/logicmoo_nlu | cogbot-init.lisp | ( load " / cogbot - init.lisp " )
;; DMiles likes to watch
(in-package "CYC")
(define FORCE-PRINT (string) (print string) (force-output))
(force-print ";; start loading cynd/cogbot-init.lisp")
(csetq *silent-progress?* NIL) ;this adds some printouts
(csetq *dump-verbose* T) ;this adds some printouts
(csetq *recan-verbose?* T)
(csetq *tm-load-verbose?* T)
(csetq *sunit-verbose* T)
(csetq *sme-lexwiz-verbose?* T)
(csetq *verbose-print-pph-phrases?* T)
(csetq *it-failing-verbose* T)
(csetq *it-verbose* T)
(csetq *psp-verbose?* T)
(define foc (string) (ret (find-or-create-constant string)))
;; makes it more like common lisp .. (but leaks functions)
(defmacro lambda (args &rest body) (ret `#'(define ,(gensym "LAMBDA") ,args ,@body)))
(in-package :SLI)
(defmacro sl:define (name arglist &body body &environment env)
(let ((*top-level-environment* env))
(must (valid-function-definition-symbol name) "~S ~S is not written in valid SubL." 'sl:define name)
( must ( valid - define - arglist arglist ) " ~S arglist inappropriate --- ~S. " name )
(must (valid-function-body name body) "~S body is not written in valid SubL." name)
(unless (tree-member 'sl:ret body)
(warn "~%Function ~S will not return a value." name))
(multiple-value-bind (body declarations doc-string)
(ex::strip-declarations-and-doc-string body)
`(progn
(when *translator-loaded*
(funcall *translator-arglist-change-callback* ',name ',arglist))
(defun ,name ,arglist
,@(when declarations
`((declare ,@declarations)))
,@(when doc-string (list doc-string))
(macrolet ((sl:ret (value)
`(return-from ,',name ,value)))
,@(when sl::*call-profiling-enabled?*
`((sl::possibly-note-function-entry ',name)))
,@body
nil))))))
(in-package :CYC)
(define cbnl-assert (sent &rest flags)
(csetq flags (flatten (cons flags *VocabularyMt*)))
(clet ((mt (car (member-if #'MT? flags)))
(cmd `(ke-assert-now ,(list 'quote sent) ,mt ,(fif (member :default flags) :default :monotonic) ,(fif (member :BACKWARD flags) :backward :forward))))
(punless (eval cmd)
(format t "~&~s~& ; ERROR: ~s~&" cmd (HL-EXPLANATION-OF-WHY-NOT-WFF sent Mt))
(force-output))))
(define cbnl-retract (sent &rest mts)
(clet (askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?sim-retract-Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?sim-retract-Mt sent)))
(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(print (length mts))
(cdolist (sent mts) (ke-unassert-now (third sent)(second sent)))
(ret mts)))
(set-the-cyclist "CycAdministrator")
(force-print ";; done loading cynd/cogbot-init.lisp")
| null | https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/e2c/cynd/cogbot-init.lisp | lisp | DMiles likes to watch
this adds some printouts
this adds some printouts
makes it more like common lisp .. (but leaks functions) | ( load " / cogbot - init.lisp " )
(in-package "CYC")
(define FORCE-PRINT (string) (print string) (force-output))
(force-print ";; start loading cynd/cogbot-init.lisp")
(csetq *recan-verbose?* T)
(csetq *tm-load-verbose?* T)
(csetq *sunit-verbose* T)
(csetq *sme-lexwiz-verbose?* T)
(csetq *verbose-print-pph-phrases?* T)
(csetq *it-failing-verbose* T)
(csetq *it-verbose* T)
(csetq *psp-verbose?* T)
(define foc (string) (ret (find-or-create-constant string)))
(defmacro lambda (args &rest body) (ret `#'(define ,(gensym "LAMBDA") ,args ,@body)))
(in-package :SLI)
(defmacro sl:define (name arglist &body body &environment env)
(let ((*top-level-environment* env))
(must (valid-function-definition-symbol name) "~S ~S is not written in valid SubL." 'sl:define name)
( must ( valid - define - arglist arglist ) " ~S arglist inappropriate --- ~S. " name )
(must (valid-function-body name body) "~S body is not written in valid SubL." name)
(unless (tree-member 'sl:ret body)
(warn "~%Function ~S will not return a value." name))
(multiple-value-bind (body declarations doc-string)
(ex::strip-declarations-and-doc-string body)
`(progn
(when *translator-loaded*
(funcall *translator-arglist-change-callback* ',name ',arglist))
(defun ,name ,arglist
,@(when declarations
`((declare ,@declarations)))
,@(when doc-string (list doc-string))
(macrolet ((sl:ret (value)
`(return-from ,',name ,value)))
,@(when sl::*call-profiling-enabled?*
`((sl::possibly-note-function-entry ',name)))
,@body
nil))))))
(in-package :CYC)
(define cbnl-assert (sent &rest flags)
(csetq flags (flatten (cons flags *VocabularyMt*)))
(clet ((mt (car (member-if #'MT? flags)))
(cmd `(ke-assert-now ,(list 'quote sent) ,mt ,(fif (member :default flags) :default :monotonic) ,(fif (member :BACKWARD flags) :backward :forward))))
(punless (eval cmd)
(format t "~&~s~& ; ERROR: ~s~&" cmd (HL-EXPLANATION-OF-WHY-NOT-WFF sent Mt))
(force-output))))
(define cbnl-retract (sent &rest mts)
(clet (askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?sim-retract-Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?sim-retract-Mt sent)))
(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(print (length mts))
(cdolist (sent mts) (ke-unassert-now (third sent)(second sent)))
(ret mts)))
(set-the-cyclist "CycAdministrator")
(force-print ";; done loading cynd/cogbot-init.lisp")
|
4fbf7d4faf0a3dd298bc7d858df77fc06470f5fdc45b216ac6933e93aee4f2b4 | SimonHauguel/Paso | ParserData.hs | module Paso.Parser.ParserData where
import qualified Text.Megaparsec as MG
import Paso.Lexer.Stream
import Data.Void ( Void ) -- TODO Remove to custom error handling
import Data.Text ( pack )
import Paso.Lexer.Tokenise
type Parser = MG.Parsec Void LexStream -- TODO Put custom Type Error instead of Void
testPars :: Show a => Parser a -> String -> IO ()
testPars p s = case tokenise "test" (pack s) of
Right res -> MG.parseTest p res
Left err -> putStrLn $ MG.errorBundlePretty err
| null | https://raw.githubusercontent.com/SimonHauguel/Paso/49c67ef67a97e5c4ed9dbfc0cc11d547806f8cfe/src/Paso/Parser/ParserData.hs | haskell | TODO Remove to custom error handling
TODO Put custom Type Error instead of Void | module Paso.Parser.ParserData where
import qualified Text.Megaparsec as MG
import Paso.Lexer.Stream
import Data.Text ( pack )
import Paso.Lexer.Tokenise
testPars :: Show a => Parser a -> String -> IO ()
testPars p s = case tokenise "test" (pack s) of
Right res -> MG.parseTest p res
Left err -> putStrLn $ MG.errorBundlePretty err
|
490839a52daf72806ea8448ba13ca9707c0d39cbe724de3de4271e8b58f0d013 | OlivierSohn/hamazed | Render.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE OverloadedStrings #-}
module Imj.Profile.Render
( writeHtmlReport
, resultsToHtml
reexport
, FilePath
) where
import Imj.Prelude hiding(div)
import Data.Text(pack)
import Data.UUID(UUID)
import Text.Blaze.Html5
import qualified Text.Blaze.Html5.Attributes as A
import Imj.Graphics.Color.Types
import Imj.File
import Imj.Graphics.Text.ColorString
import Imj.Profile.Intent
import Imj.Profile.Render.Blaze
import Imj.Profile.Render.Clay
import Imj.Profile.Results
writeHtmlReport :: UUID
-> Html
-> UserIntent
-> IO ()
writeHtmlReport key h intent = do
name <- renderResultsHtml key intentStr h
putStrLn $ colored ("Wrote Chrome-compatible html report: " <> pack name) yellow
where
intentStr = case intent of
Cancel -> "The test was interrupted."
Report _ -> "The test is still running."
Run -> "The test has finished." -- because we write a report only at the end, or on 'Report'
Pause _ -> "The test is paused" -- should not happen
renderResultsHtml :: UUID
-> String
-> Html
-> IO FilePath
renderResultsHtml k status resultsAndSubresults = do
deleteOrRename dir k
renderCss (dir <> "/" <> cssName) mkCss
renderHtml (dir <> "/html/results") $
fromHeaderBody
(do
pageTitle "Test report"
meta ! A.httpEquiv " refresh " ! A.content " 2 "
cssHeader $ "../" <> cssName
scripts)
(do
bodyHeader
resultsAndSubresults)
where
dir = "report"
bodyHeader = do
div
! A.style (colorAttribute msgColor)
$ do
br
p "Chrome-compatible html report."
br
div
! A.style (colorAttribute statusColor)
! A.class_ "stick"
$ string status
div br
where
statusColor = LayeredColor (gray 13) black
msgColor = LayeredColor (gray 3) (gray 13)
pageTitle x = title $ string x
cssName = "results.css"
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/c0df1bb60a8538ac75e413d2f5bf0bf050e5bc37/imj-profile/src/Imj/Profile/Render.hs | haskell | # LANGUAGE OverloadedStrings #
because we write a report only at the end, or on 'Report'
should not happen | # LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
module Imj.Profile.Render
( writeHtmlReport
, resultsToHtml
reexport
, FilePath
) where
import Imj.Prelude hiding(div)
import Data.Text(pack)
import Data.UUID(UUID)
import Text.Blaze.Html5
import qualified Text.Blaze.Html5.Attributes as A
import Imj.Graphics.Color.Types
import Imj.File
import Imj.Graphics.Text.ColorString
import Imj.Profile.Intent
import Imj.Profile.Render.Blaze
import Imj.Profile.Render.Clay
import Imj.Profile.Results
writeHtmlReport :: UUID
-> Html
-> UserIntent
-> IO ()
writeHtmlReport key h intent = do
name <- renderResultsHtml key intentStr h
putStrLn $ colored ("Wrote Chrome-compatible html report: " <> pack name) yellow
where
intentStr = case intent of
Cancel -> "The test was interrupted."
Report _ -> "The test is still running."
renderResultsHtml :: UUID
-> String
-> Html
-> IO FilePath
renderResultsHtml k status resultsAndSubresults = do
deleteOrRename dir k
renderCss (dir <> "/" <> cssName) mkCss
renderHtml (dir <> "/html/results") $
fromHeaderBody
(do
pageTitle "Test report"
meta ! A.httpEquiv " refresh " ! A.content " 2 "
cssHeader $ "../" <> cssName
scripts)
(do
bodyHeader
resultsAndSubresults)
where
dir = "report"
bodyHeader = do
div
! A.style (colorAttribute msgColor)
$ do
br
p "Chrome-compatible html report."
br
div
! A.style (colorAttribute statusColor)
! A.class_ "stick"
$ string status
div br
where
statusColor = LayeredColor (gray 13) black
msgColor = LayeredColor (gray 3) (gray 13)
pageTitle x = title $ string x
cssName = "results.css"
|
16722b31c510392c2b0757231d0590f5168ef7106bfb4606b72c389fa4f08cff | cognitect-labs/pedestal.kafka | kafka.clj | (ns com.cognitect.kafka
(:require [clojure.spec :as s]
[com.cognitect.kafka.common :as common]
[com.cognitect.kafka.connector :as connector]
[com.cognitect.kafka.producer :as producer]
[com.cognitect.kafka.consumer :as consumer]
[com.cognitect.kafka.topic :as topic]
[com.cognitect.kafka.parser :as parser]
[io.pedestal.log :as log]))
(s/def ::start-fn fn?)
(s/def ::stop-fn fn?)
(s/def ::service-map-in (s/keys :req [::topic/topics]
:opt [::consumer/configuration ::producer/configuration ::start-fn ::stop-fn ::consumer]))
(s/def ::service-map-stopped (s/keys :req [::start-fn]))
(s/def ::service-map-started (s/keys :req [::stop-fn]
:opt [::consumer-loop]))
(defmacro service-fn [k]
`(fn [service-map#]
(if-let [f# (get service-map# ~k)]
(f# service-map#)
service-map#)))
(declare starter)
(defn- stopper
[service-map]
{:pre [(s/valid? ::service-map-in service-map)]
:post [(s/valid? ::service-map-stopped %)]}
(let [shutdown-result (consumer/stop-consumer (::consumer-loop service-map))]
(-> service-map
(assoc ::consumer-shutdown shutdown-result)
(dissoc ::consumer-loop ::stop-fn)
(assoc ::start-fn (fn [& _] (assert false "This service cannot be restarted."))))))
(def stop (service-fn ::stop-fn))
(s/fdef stop
:args (s/cat :service-map ::service-map-in)
:ret ::service-map-stopped)
(defn- starter
[service-map]
{:pre [(s/valid? ::service-map-in service-map)]
:post [(s/valid? ::service-map-started %)]}
(let [created? (not (some? (::consumer service-map)))
consumer (or (::consumer service-map) (consumer/create-consumer (::consumer/configuration service-map)))
loop (consumer/start-consumer consumer created? service-map)]
(-> service-map
(assoc ::consumer consumer
::consumer-created? created?
::consumer-loop loop
::stop-fn stopper)
(dissoc ::start-fn))))
(def start (service-fn ::start-fn))
(s/fdef start
:args (s/cat :service-map ::service-map-in)
:ret ::service-map-started)
(defn configuration-problems
[service-map]
(when-not (s/valid? ::service-map-in service-map)
(s/explain-data ::service-map-in service-map)))
(defn kafka-server
[service-map]
(assoc service-map ::start-fn starter))
(comment
(def printerceptor
{:name ::printerceptor
:enter (fn [context]
(println (:message context))
context)})
(def service-map {::topic/topics [{::topic/name "smoketest" ::topic/parallelism 1}]
::consumer/configuration {::common/bootstrap.servers "localhost:9092"
::common/group.id "development"
::consumer/key.deserializer consumer/string-deserializer
::consumer/value.deserializer consumer/string-deserializer
::consumer/enable.auto.commit "true"
::consumer/auto.commit.interval.ms "1000"
::consumer/session.timeout.ms "30000"}
::consumer/interceptors [printerceptor]
})
(def s (-> service-map kafka-server start))
(stop s)
)
;; ----------------------------------------
;; Interceptors
(def commit-sync
{:name ::commit-sync
:enter
(fn [context]
(consumer/commit-sync context)
context)})
(def commit-message
{:name ::commit-per-message
:enter
(fn [context]
(consumer/commit-message-offset context)
context)})
(def edn-value parser/edn-value)
(def json-value parser/json-value)
(def transit-json-value parser/transit-json-value)
(def transit-msgpack-value parser/transit-msgpack-value)
(comment
(def service-map {::topic/topics [{::topic/name "smoketest" ::topic/parallelism 1}]
::consumer/configuration {::common/bootstrap.servers "localhost:9092"
::common/group.id "development-2"
::consumer/key.deserializer consumer/string-deserializer
::consumer/value.deserializer consumer/string-deserializer
::consumer/enable.auto.commit "false"
::consumer/session.timeout.ms "30000"}
::consumer/interceptors [(edn-value) printerceptor commit-message]
})
(def s (-> service-map kafka-server start))
(stop s)
)
| null | https://raw.githubusercontent.com/cognitect-labs/pedestal.kafka/91e826112b2f2bdc6a366a66b6a3cc07f7fca20b/src/com/cognitect/kafka.clj | clojure | ----------------------------------------
Interceptors | (ns com.cognitect.kafka
(:require [clojure.spec :as s]
[com.cognitect.kafka.common :as common]
[com.cognitect.kafka.connector :as connector]
[com.cognitect.kafka.producer :as producer]
[com.cognitect.kafka.consumer :as consumer]
[com.cognitect.kafka.topic :as topic]
[com.cognitect.kafka.parser :as parser]
[io.pedestal.log :as log]))
(s/def ::start-fn fn?)
(s/def ::stop-fn fn?)
(s/def ::service-map-in (s/keys :req [::topic/topics]
:opt [::consumer/configuration ::producer/configuration ::start-fn ::stop-fn ::consumer]))
(s/def ::service-map-stopped (s/keys :req [::start-fn]))
(s/def ::service-map-started (s/keys :req [::stop-fn]
:opt [::consumer-loop]))
(defmacro service-fn [k]
`(fn [service-map#]
(if-let [f# (get service-map# ~k)]
(f# service-map#)
service-map#)))
(declare starter)
(defn- stopper
[service-map]
{:pre [(s/valid? ::service-map-in service-map)]
:post [(s/valid? ::service-map-stopped %)]}
(let [shutdown-result (consumer/stop-consumer (::consumer-loop service-map))]
(-> service-map
(assoc ::consumer-shutdown shutdown-result)
(dissoc ::consumer-loop ::stop-fn)
(assoc ::start-fn (fn [& _] (assert false "This service cannot be restarted."))))))
(def stop (service-fn ::stop-fn))
(s/fdef stop
:args (s/cat :service-map ::service-map-in)
:ret ::service-map-stopped)
(defn- starter
[service-map]
{:pre [(s/valid? ::service-map-in service-map)]
:post [(s/valid? ::service-map-started %)]}
(let [created? (not (some? (::consumer service-map)))
consumer (or (::consumer service-map) (consumer/create-consumer (::consumer/configuration service-map)))
loop (consumer/start-consumer consumer created? service-map)]
(-> service-map
(assoc ::consumer consumer
::consumer-created? created?
::consumer-loop loop
::stop-fn stopper)
(dissoc ::start-fn))))
(def start (service-fn ::start-fn))
(s/fdef start
:args (s/cat :service-map ::service-map-in)
:ret ::service-map-started)
(defn configuration-problems
[service-map]
(when-not (s/valid? ::service-map-in service-map)
(s/explain-data ::service-map-in service-map)))
(defn kafka-server
[service-map]
(assoc service-map ::start-fn starter))
(comment
(def printerceptor
{:name ::printerceptor
:enter (fn [context]
(println (:message context))
context)})
(def service-map {::topic/topics [{::topic/name "smoketest" ::topic/parallelism 1}]
::consumer/configuration {::common/bootstrap.servers "localhost:9092"
::common/group.id "development"
::consumer/key.deserializer consumer/string-deserializer
::consumer/value.deserializer consumer/string-deserializer
::consumer/enable.auto.commit "true"
::consumer/auto.commit.interval.ms "1000"
::consumer/session.timeout.ms "30000"}
::consumer/interceptors [printerceptor]
})
(def s (-> service-map kafka-server start))
(stop s)
)
(def commit-sync
{:name ::commit-sync
:enter
(fn [context]
(consumer/commit-sync context)
context)})
(def commit-message
{:name ::commit-per-message
:enter
(fn [context]
(consumer/commit-message-offset context)
context)})
(def edn-value parser/edn-value)
(def json-value parser/json-value)
(def transit-json-value parser/transit-json-value)
(def transit-msgpack-value parser/transit-msgpack-value)
(comment
(def service-map {::topic/topics [{::topic/name "smoketest" ::topic/parallelism 1}]
::consumer/configuration {::common/bootstrap.servers "localhost:9092"
::common/group.id "development-2"
::consumer/key.deserializer consumer/string-deserializer
::consumer/value.deserializer consumer/string-deserializer
::consumer/enable.auto.commit "false"
::consumer/session.timeout.ms "30000"}
::consumer/interceptors [(edn-value) printerceptor commit-message]
})
(def s (-> service-map kafka-server start))
(stop s)
)
|
9fb110376f5a14d6576126eed73ef978b47b6c964a01af0b5e790ecf5ee8412f | racket/htdp | world-mouse.rkt | #lang scheme
(require htdp/world)
(with-handlers ((exn? (lambda (x) #t)))
(place-image (circle 3 'solid 'red) 1.2 3.14 (empty-scene 100 100)))
(define (ms w x y e)
(if (eq? e 'button-down) (list x y) w))
(define (rd w)
(local ((define mt (empty-scene 300 300))
(define x1 (first w))
(define y1 (second w))
(define tx (text (format "(~s,~s)" x1 y1) 22 'red))
(define cr (circle 3 'solid 'red))
(define m1 (place-image tx 50 50 mt))
(define m2 (place-image cr x1 y1 m1)))
m2))
(big-bang 300 300 1 (list 50 50))
(on-redraw rd)
(on-mouse-event ms)
| null | https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-test/htdp/tests/world-mouse.rkt | racket | #lang scheme
(require htdp/world)
(with-handlers ((exn? (lambda (x) #t)))
(place-image (circle 3 'solid 'red) 1.2 3.14 (empty-scene 100 100)))
(define (ms w x y e)
(if (eq? e 'button-down) (list x y) w))
(define (rd w)
(local ((define mt (empty-scene 300 300))
(define x1 (first w))
(define y1 (second w))
(define tx (text (format "(~s,~s)" x1 y1) 22 'red))
(define cr (circle 3 'solid 'red))
(define m1 (place-image tx 50 50 mt))
(define m2 (place-image cr x1 y1 m1)))
m2))
(big-bang 300 300 1 (list 50 50))
(on-redraw rd)
(on-mouse-event ms)
|
|
ec3ecd14749714bfa373cca7c65e14c501113dd0dbb4b52ac94e64d380ce177f | Idorobots/spartan | modules.rkt | #lang racket
;; Runtime support for modules.
(provide &make-structure &structure-binding &structure-ref)
(define (&make-structure . defs)
;; FIXME Yeah, an alist... Don't judge me...
(list &make-structure defs))
(define &structure-binding cons)
(define (&structure-ref s f)
(cdr (assoc f (cadr s))))
| null | https://raw.githubusercontent.com/Idorobots/spartan/ef3b032906655585d284f1c9a33a58f1e35cb180/src/runtime/modules.rkt | racket | Runtime support for modules.
FIXME Yeah, an alist... Don't judge me... | #lang racket
(provide &make-structure &structure-binding &structure-ref)
(define (&make-structure . defs)
(list &make-structure defs))
(define &structure-binding cons)
(define (&structure-ref s f)
(cdr (assoc f (cadr s))))
|
b53468e8c9ecc2d84868d140d52f4704d5ad46e20f1d11a4ff782d699e42d788 | dgtized/shimmers | intersection_test.cljc | (ns shimmers.math.geometry.intersection-test
(:require
[clojure.test :as t :refer [deftest is] :include-macros true]
[shimmers.math.geometry.intersection :as sut]
[thi.ng.geom.circle :as gc]
[thi.ng.geom.vector :as gv]))
(deftest circle-segment-isec
(is (sut/circle-segment-intersect? (gc/circle [1 1] 1) (gv/vec2 1 1) (gv/vec2 2 2)))
(is (sut/circle-segment-intersect? (gc/circle [1 1] 1) (gv/vec2 1 1) (gv/vec2 2 0))))
(deftest circle-ray
(is (= {:type :impale
:isec [(gv/vec2 1 0) (gv/vec2 3 0)]
:points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2) (gv/vec2 5 0))))
(is (= {:type :impale
:isec [(gv/vec2 3 0) (gv/vec2 1 0)]
:points [(gv/vec2 3 0) (gv/vec2 1 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 5 0) (gv/vec2))))
(is (= {:type :exit
:isec [(gv/vec2 1 0)]
:points [(gv/vec2 3 0) (gv/vec2 1 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 2 0) (gv/vec2))))
(is (= {:type :poke
:isec [(gv/vec2 1 0)]
:points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2) (gv/vec2 1 0))))
(is (= {:type :past :isec [] :points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 4 0) (gv/vec2 5 0))))
(is (= {:type :before :isec [] :points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 -1 0) (gv/vec2))))
(is (= {:type :inside :isec [] :points [(gv/vec2 0 0) (gv/vec2 4 0)]}
(sut/circle-ray (gc/circle [2 0] 2) (gv/vec2 1 0) (gv/vec2 3 0))))
(is (= {:type :inside :isec [] :points [(gv/vec2 2 -2) (gv/vec2 2 2)]}
(sut/circle-ray (gc/circle [2 0] 2) (gv/vec2 2 0) (gv/vec2 2 1)))
"vertical inside")
FIXME : why discrepency between clj / cljs
(is (= #?(:cljs {:type :tangent :isec [(gv/vec2 1 0)] :points [(gv/vec2 1 0)]}
:clj nil)
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 1 0) (gv/vec2 1 1)))))
(comment (t/run-tests))
| null | https://raw.githubusercontent.com/dgtized/shimmers/57288e7faa60d9e04e2c515ef93c7016864b0d53/test/shimmers/math/geometry/intersection_test.cljc | clojure | (ns shimmers.math.geometry.intersection-test
(:require
[clojure.test :as t :refer [deftest is] :include-macros true]
[shimmers.math.geometry.intersection :as sut]
[thi.ng.geom.circle :as gc]
[thi.ng.geom.vector :as gv]))
(deftest circle-segment-isec
(is (sut/circle-segment-intersect? (gc/circle [1 1] 1) (gv/vec2 1 1) (gv/vec2 2 2)))
(is (sut/circle-segment-intersect? (gc/circle [1 1] 1) (gv/vec2 1 1) (gv/vec2 2 0))))
(deftest circle-ray
(is (= {:type :impale
:isec [(gv/vec2 1 0) (gv/vec2 3 0)]
:points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2) (gv/vec2 5 0))))
(is (= {:type :impale
:isec [(gv/vec2 3 0) (gv/vec2 1 0)]
:points [(gv/vec2 3 0) (gv/vec2 1 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 5 0) (gv/vec2))))
(is (= {:type :exit
:isec [(gv/vec2 1 0)]
:points [(gv/vec2 3 0) (gv/vec2 1 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 2 0) (gv/vec2))))
(is (= {:type :poke
:isec [(gv/vec2 1 0)]
:points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2) (gv/vec2 1 0))))
(is (= {:type :past :isec [] :points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 4 0) (gv/vec2 5 0))))
(is (= {:type :before :isec [] :points [(gv/vec2 1 0) (gv/vec2 3 0)]}
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 -1 0) (gv/vec2))))
(is (= {:type :inside :isec [] :points [(gv/vec2 0 0) (gv/vec2 4 0)]}
(sut/circle-ray (gc/circle [2 0] 2) (gv/vec2 1 0) (gv/vec2 3 0))))
(is (= {:type :inside :isec [] :points [(gv/vec2 2 -2) (gv/vec2 2 2)]}
(sut/circle-ray (gc/circle [2 0] 2) (gv/vec2 2 0) (gv/vec2 2 1)))
"vertical inside")
FIXME : why discrepency between clj / cljs
(is (= #?(:cljs {:type :tangent :isec [(gv/vec2 1 0)] :points [(gv/vec2 1 0)]}
:clj nil)
(sut/circle-ray (gc/circle [2 0] 1) (gv/vec2 1 0) (gv/vec2 1 1)))))
(comment (t/run-tests))
|
|
968ca879e6be59aa04594c6ebedefc07c34ce71033dffd5d8f37bad47c25b6be | serokell/ariadne | Logging.hs | | Configuration of logging in .
module Ariadne.Config.Logging
( defaultLoggingConfig
, loggingFieldModifier
, LoggingConfig (..)
, lcPathL
) where
import Control.Lens (makeLensesWith)
import qualified Data.HashMap.Strict.InsOrd as Map
import qualified Dhall as D
import Dhall.Core (Expr(..))
import Dhall.Parser (Src(..))
import Dhall.TypeCheck (X)
import System.FilePath ((</>))
import Ariadne.Config.DhallUtil (injectFilePath, interpretFilePath, parseField)
import Ariadne.Util (postfixLFields)
defaultLoggingConfig :: FilePath -> LoggingConfig
defaultLoggingConfig dataDir =
LoggingConfig {lcPath = dataDir </> "logs"}
parseFieldLogging ::
Map.InsOrdHashMap D.Text (Expr Src X) -> D.Text -> D.Type a -> Maybe a
parseFieldLogging = parseField loggingFieldModifier
loggingFieldModifier :: D.Text -> D.Text
loggingFieldModifier = f
where
f "lcPath" = "path"
f x = x
data LoggingConfig = LoggingConfig
{ lcPath :: FilePath
} deriving (Eq, Show)
makeLensesWith postfixLFields ''LoggingConfig
instance D.Interpret LoggingConfig where
autoWith _ = D.Type extractOut expectedOut
where
extractOut (RecordLit fields) = do
lcPath <- parseFieldLogging fields "lcPath" interpretFilePath
return LoggingConfig {..}
extractOut _ = Nothing
expectedOut =
Record
(Map.fromList
[(loggingFieldModifier "lcPath", D.expected interpretFilePath)])
instance D.Inject LoggingConfig where
injectWith _ = injectLoggingConfig
injectLoggingConfig :: D.InputType LoggingConfig
injectLoggingConfig = D.InputType {..}
where
embed LoggingConfig {..} = RecordLit
(Map.fromList
[ (loggingFieldModifier "lcPath",
D.embed injectFilePath lcPath)
])
declared = Record
(Map.fromList
[ (loggingFieldModifier "lcPath", D.declared injectFilePath)
])
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Config/Logging.hs | haskell | | Configuration of logging in .
module Ariadne.Config.Logging
( defaultLoggingConfig
, loggingFieldModifier
, LoggingConfig (..)
, lcPathL
) where
import Control.Lens (makeLensesWith)
import qualified Data.HashMap.Strict.InsOrd as Map
import qualified Dhall as D
import Dhall.Core (Expr(..))
import Dhall.Parser (Src(..))
import Dhall.TypeCheck (X)
import System.FilePath ((</>))
import Ariadne.Config.DhallUtil (injectFilePath, interpretFilePath, parseField)
import Ariadne.Util (postfixLFields)
defaultLoggingConfig :: FilePath -> LoggingConfig
defaultLoggingConfig dataDir =
LoggingConfig {lcPath = dataDir </> "logs"}
parseFieldLogging ::
Map.InsOrdHashMap D.Text (Expr Src X) -> D.Text -> D.Type a -> Maybe a
parseFieldLogging = parseField loggingFieldModifier
loggingFieldModifier :: D.Text -> D.Text
loggingFieldModifier = f
where
f "lcPath" = "path"
f x = x
data LoggingConfig = LoggingConfig
{ lcPath :: FilePath
} deriving (Eq, Show)
makeLensesWith postfixLFields ''LoggingConfig
instance D.Interpret LoggingConfig where
autoWith _ = D.Type extractOut expectedOut
where
extractOut (RecordLit fields) = do
lcPath <- parseFieldLogging fields "lcPath" interpretFilePath
return LoggingConfig {..}
extractOut _ = Nothing
expectedOut =
Record
(Map.fromList
[(loggingFieldModifier "lcPath", D.expected interpretFilePath)])
instance D.Inject LoggingConfig where
injectWith _ = injectLoggingConfig
injectLoggingConfig :: D.InputType LoggingConfig
injectLoggingConfig = D.InputType {..}
where
embed LoggingConfig {..} = RecordLit
(Map.fromList
[ (loggingFieldModifier "lcPath",
D.embed injectFilePath lcPath)
])
declared = Record
(Map.fromList
[ (loggingFieldModifier "lcPath", D.declared injectFilePath)
])
|
|
4a18b66b1220898778bbf8c5b3d76c7015a62a4af480005073cc86ea49df5dce | fulcrologic/semantic-ui-wrapper | ui_dropdown_divider.cljc | (ns com.fulcrologic.semantic-ui.modules.dropdown.ui-dropdown-divider
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$DropdownDivider" :as DropdownDivider])))
(def ui-dropdown-divider
"A dropdown menu can contain dividers to separate related content.
Props:
- as (elementType): An element type to render as (string or function).
- className (string): Additional classes."
#?(:cljs (h/factory-apply DropdownDivider)))
| null | https://raw.githubusercontent.com/fulcrologic/semantic-ui-wrapper/7bd53f445bc4ca7e052c69596dc089282671df6c/src/main/com/fulcrologic/semantic_ui/modules/dropdown/ui_dropdown_divider.cljc | clojure | (ns com.fulcrologic.semantic-ui.modules.dropdown.ui-dropdown-divider
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$DropdownDivider" :as DropdownDivider])))
(def ui-dropdown-divider
"A dropdown menu can contain dividers to separate related content.
Props:
- as (elementType): An element type to render as (string or function).
- className (string): Additional classes."
#?(:cljs (h/factory-apply DropdownDivider)))
|
|
8b0c6d4cdad9a063da509c203d7e5feac4aaef03d3c73a3cbbd48d3c07673fb4 | racket/gui | load.rkt | #lang racket/base
(require "test-suite-utils.rkt")
(module test racket/base)
(load-framework-automatically #f)
(define (test/load file exp)
(test
(string->symbol file)
void?
`(let ([mred-name ((current-module-name-resolver) 'mred #f #f #t)]
[orig-namespace (current-namespace)])
(parameterize ([current-namespace (make-base-namespace)])
(namespace-attach-module orig-namespace mred-name)
(eval '(require (lib ,file "framework")))
(with-handlers ([(lambda (x) #t)
(lambda (x)
(if (exn? x)
(exn-message x)
(format "~s" x)))])
(eval ',exp)
(void))))))
(test/load "gui-utils.rkt" 'gui-utils:next-untitled-name)
(test/load "test.rkt" 'test:run-interval)
(test/load "splash.rkt" 'start-splash)
(test/load "framework-sig.rkt" '(begin (eval '(require mzlib/unit))
(eval '(define-signature dummy-signature^ ((open framework^))))))
(test/load "framework-unit.rkt" 'framework@)
(test/load "framework.rkt" '(list test:button-push
gui-utils:next-untitled-name
frame:basic-mixin))
;; ensures that all of the names in the signature are provided
;; by (require framework)
(test/load
"framework.rkt"
;; these extra evals let me submit multiple, independent top-level
;; expressions in the newly created namespace.
'(begin (eval '(require mzlib/unit))
(eval '(require (for-syntax scheme/base)))
(eval '(require (for-syntax scheme/unit-exptime)))
(eval '(define-syntax (signature->symbols stx)
(syntax-case stx ()
[(_ sig)
(let-values ([(_1 eles _2 _3) (signature-members #'sig #'whatever)])
(with-syntax ([eles eles])
#''eles))])))
(eval '(require framework/framework-sig))
(eval '(for-each eval (signature->symbols framework^)))))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-test/framework/tests/load.rkt | racket | ensures that all of the names in the signature are provided
by (require framework)
these extra evals let me submit multiple, independent top-level
expressions in the newly created namespace. | #lang racket/base
(require "test-suite-utils.rkt")
(module test racket/base)
(load-framework-automatically #f)
(define (test/load file exp)
(test
(string->symbol file)
void?
`(let ([mred-name ((current-module-name-resolver) 'mred #f #f #t)]
[orig-namespace (current-namespace)])
(parameterize ([current-namespace (make-base-namespace)])
(namespace-attach-module orig-namespace mred-name)
(eval '(require (lib ,file "framework")))
(with-handlers ([(lambda (x) #t)
(lambda (x)
(if (exn? x)
(exn-message x)
(format "~s" x)))])
(eval ',exp)
(void))))))
(test/load "gui-utils.rkt" 'gui-utils:next-untitled-name)
(test/load "test.rkt" 'test:run-interval)
(test/load "splash.rkt" 'start-splash)
(test/load "framework-sig.rkt" '(begin (eval '(require mzlib/unit))
(eval '(define-signature dummy-signature^ ((open framework^))))))
(test/load "framework-unit.rkt" 'framework@)
(test/load "framework.rkt" '(list test:button-push
gui-utils:next-untitled-name
frame:basic-mixin))
(test/load
"framework.rkt"
'(begin (eval '(require mzlib/unit))
(eval '(require (for-syntax scheme/base)))
(eval '(require (for-syntax scheme/unit-exptime)))
(eval '(define-syntax (signature->symbols stx)
(syntax-case stx ()
[(_ sig)
(let-values ([(_1 eles _2 _3) (signature-members #'sig #'whatever)])
(with-syntax ([eles eles])
#''eles))])))
(eval '(require framework/framework-sig))
(eval '(for-each eval (signature->symbols framework^)))))
|
9fc038616c59a99479e0c689d9faf1d6debf30487a326f56a143373f1351ad2f | snmsts/cl-langserver | slynk-profiler.lisp | (defpackage :ls-profiler
(:use :cl)
(:import-from :ls-base :defslyfun :from-string :to-string)
(:export #:toggle-timing
#:untime-spec
#:clear-timing-tree
#:untime-all
#:timed-spec-p
#:time-spec))
(in-package :ls-profiler)
(defvar *timing-lock* (ls-backend:make-lock :name "slynk-timings lock"))
(defvar *current-timing* nil)
(defvar *timed-spec-lists* (make-array 10
:fill-pointer 0
:adjustable t))
(defun started-timing ())
(defmethod timed-specs ()
(aref *timed-spec-lists* (1- (fill-pointer *timed-spec-lists*))))
(defmethod (setf timed-specs) (value)
(setf (aref *timed-spec-lists* (1- (fill-pointer *timed-spec-lists*))) value))
(defclass timing ()
((parent :reader parent-of :initform *current-timing* )
(origin :initarg :origin :reader origin-of
:initform (error "must provide an ORIGIN for this TIMING"))
(start :reader start-of :initform (get-internal-real-time))
(end :accessor end-of :initform nil)))
(defclass timed-spec ()
((spec :initarg :spec :accessor spec-of
:initform (error "must provide a spec"))
(stats :accessor stats-of)
(total :accessor total-of)
(subtimings :accessor subtimings-of)
(owntimings :accessor owntimings-of)))
(defun get-singleton-create (spec)
(let ((existing (find spec (timed-specs) :test #'equal :key #'spec-of)))
(if existing
(reinitialize-instance existing)
(let ((new (make-instance 'timed-spec :spec spec)))
(push new (timed-specs))
new))))
(defmethod shared-initialize :after ((ts timed-spec) slot-names &rest initargs)
(declare (ignore slot-names))
(setf (stats-of ts) (make-hash-table)
(total-of ts) 0
(subtimings-of ts) nil
(owntimings-of ts) nil)
(loop for otherts in (remove ts (timed-specs))
do (setf (gethash ts (stats-of otherts)) 0)
(setf (gethash otherts (stats-of ts)) 0)))
(defmethod initialize-instance :after ((tm timing) &rest initargs)
(declare (ignore initargs))
(push tm (owntimings-of (origin-of tm)))
(let ((parent (parent-of tm)))
(when parent
(push tm (subtimings-of (origin-of parent))))))
(defmethod (setf end-of) :after (value (tm timing))
(let* ((parent (parent-of tm))
(parent-origin (and parent (origin-of parent)))
(origin (origin-of tm))
(tm1 (pop (owntimings-of origin)))
(tm2 (and parent
(pop (subtimings-of parent-origin))))
(delta (- value (start-of tm))))
(assert (eq tm tm1) nil "Hmm something's gone wrong in the owns")
(assert (or (null tm2)
(eq tm tm2)) nil "Something's gone wrong in the subs")
(when (null (owntimings-of origin))
(incf (total-of origin) delta))
(when (and parent-origin
(null (subtimings-of parent-origin)))
(incf (gethash origin (stats-of parent-origin))
delta))))
(defmethod duration ((tm timing))
(/ (- (or (end-of tm)
(get-internal-real-time))
(start-of tm))
internal-time-units-per-second))
(defmethod print-object ((tm timing) stream)
(print-unreadable-object (tm stream :type t :identity t)
(format stream "~a: ~f~a"
(spec-of (origin-of tm))
(duration tm)
(if (not (end-of tm)) "(unfinished)" ""))))
(defmethod print-object ((e timed-spec) stream)
(print-unreadable-object (e stream :type t)
(format stream "~a ~fs" (spec-of e)
(/ (total-of e)
internal-time-units-per-second))))
(defslyfun time-spec (spec)
(when (timed-spec-p spec)
(warn "~a is apparently already timed! Untiming and retiming." spec)
(untime-spec spec))
(let ((timed-spec (get-singleton-create spec)))
(flet ((before-hook (args)
(declare (ignore args))
(setf *current-timing*
(make-instance 'timing :origin timed-spec)))
(after-hook (retlist)
(declare (ignore retlist))
(let* ((timing *current-timing*))
(when timing
(setf (end-of timing) (get-internal-real-time))
(setf *current-timing* (parent-of timing))))))
(ls-backend:wrap spec 'timings
:before #'before-hook
:after #'after-hook)
(format nil "~a is now timed for timing dialog" spec))))
(defslyfun untime-spec (spec)
(ls-backend:unwrap spec 'timings)
(let ((moribund (find spec (timed-specs) :test #'equal :key #'spec-of)))
(setf (timed-specs) (remove moribund (timed-specs)))
(loop for otherts in (timed-specs)
do (remhash moribund (stats-of otherts))))
(format nil "~a is now untimed for timing dialog" spec))
(defslyfun toggle-timing (spec)
(if (timed-spec-p spec)
(untime-spec spec)
(time-spec spec)))
(defslyfun timed-spec-p (spec)
(find spec (timed-specs) :test #'equal :key #'spec-of))
(defslyfun untime-all ()
(mapcar #'untime-spec (timed-specs)))
;;;; Reporting to emacs
;;;
(defun describe-timing-for-emacs (timed-spec)
(declare (ignore timed-spec))
`not-implemented)
(defslyfun report-latest-timings ()
(loop for spec in (timed-specs)
append (loop for partial being the hash-values of (stats-of spec)
for path being the hash-keys of (stats-of spec)
collect (list (ls-base::slynk-pprint-to-line spec) partial
(ls-base::slynk-pprint-to-line path)))))
(defun print-tree ()
(loop for ts in (timed-specs)
for total = (total-of ts)
do (format t "~%~a~%~%" ts)
(when (plusp total)
(loop for partial being the hash-values of (stats-of ts)
for path being the hash-keys of (stats-of ts)
when (plusp partial)
sum partial into total-partials
and
do (format t " ~8fs ~4f% ~a ~%"
(/ partial
internal-time-units-per-second)
(* 100 (/ partial
total))
(spec-of path))
finally
(format t " ~8fs ~4f% ~a ~%"
(/ (- total total-partials)
internal-time-units-per-second)
(* 100 (/ (- total total-partials)
total))
'other)))))
(defslyfun clear-timing-tree ()
(setq *current-timing* nil)
(loop for ts in (timed-specs)
do (reinitialize-instance ts)))
(provide :ls-profiler)
| null | https://raw.githubusercontent.com/snmsts/cl-langserver/3b1246a5d0bd58459e7a64708f820bf718cf7175/src/contrib/slynk-profiler.lisp | lisp | Reporting to emacs
| (defpackage :ls-profiler
(:use :cl)
(:import-from :ls-base :defslyfun :from-string :to-string)
(:export #:toggle-timing
#:untime-spec
#:clear-timing-tree
#:untime-all
#:timed-spec-p
#:time-spec))
(in-package :ls-profiler)
(defvar *timing-lock* (ls-backend:make-lock :name "slynk-timings lock"))
(defvar *current-timing* nil)
(defvar *timed-spec-lists* (make-array 10
:fill-pointer 0
:adjustable t))
(defun started-timing ())
(defmethod timed-specs ()
(aref *timed-spec-lists* (1- (fill-pointer *timed-spec-lists*))))
(defmethod (setf timed-specs) (value)
(setf (aref *timed-spec-lists* (1- (fill-pointer *timed-spec-lists*))) value))
(defclass timing ()
((parent :reader parent-of :initform *current-timing* )
(origin :initarg :origin :reader origin-of
:initform (error "must provide an ORIGIN for this TIMING"))
(start :reader start-of :initform (get-internal-real-time))
(end :accessor end-of :initform nil)))
(defclass timed-spec ()
((spec :initarg :spec :accessor spec-of
:initform (error "must provide a spec"))
(stats :accessor stats-of)
(total :accessor total-of)
(subtimings :accessor subtimings-of)
(owntimings :accessor owntimings-of)))
(defun get-singleton-create (spec)
(let ((existing (find spec (timed-specs) :test #'equal :key #'spec-of)))
(if existing
(reinitialize-instance existing)
(let ((new (make-instance 'timed-spec :spec spec)))
(push new (timed-specs))
new))))
(defmethod shared-initialize :after ((ts timed-spec) slot-names &rest initargs)
(declare (ignore slot-names))
(setf (stats-of ts) (make-hash-table)
(total-of ts) 0
(subtimings-of ts) nil
(owntimings-of ts) nil)
(loop for otherts in (remove ts (timed-specs))
do (setf (gethash ts (stats-of otherts)) 0)
(setf (gethash otherts (stats-of ts)) 0)))
(defmethod initialize-instance :after ((tm timing) &rest initargs)
(declare (ignore initargs))
(push tm (owntimings-of (origin-of tm)))
(let ((parent (parent-of tm)))
(when parent
(push tm (subtimings-of (origin-of parent))))))
(defmethod (setf end-of) :after (value (tm timing))
(let* ((parent (parent-of tm))
(parent-origin (and parent (origin-of parent)))
(origin (origin-of tm))
(tm1 (pop (owntimings-of origin)))
(tm2 (and parent
(pop (subtimings-of parent-origin))))
(delta (- value (start-of tm))))
(assert (eq tm tm1) nil "Hmm something's gone wrong in the owns")
(assert (or (null tm2)
(eq tm tm2)) nil "Something's gone wrong in the subs")
(when (null (owntimings-of origin))
(incf (total-of origin) delta))
(when (and parent-origin
(null (subtimings-of parent-origin)))
(incf (gethash origin (stats-of parent-origin))
delta))))
(defmethod duration ((tm timing))
(/ (- (or (end-of tm)
(get-internal-real-time))
(start-of tm))
internal-time-units-per-second))
(defmethod print-object ((tm timing) stream)
(print-unreadable-object (tm stream :type t :identity t)
(format stream "~a: ~f~a"
(spec-of (origin-of tm))
(duration tm)
(if (not (end-of tm)) "(unfinished)" ""))))
(defmethod print-object ((e timed-spec) stream)
(print-unreadable-object (e stream :type t)
(format stream "~a ~fs" (spec-of e)
(/ (total-of e)
internal-time-units-per-second))))
(defslyfun time-spec (spec)
(when (timed-spec-p spec)
(warn "~a is apparently already timed! Untiming and retiming." spec)
(untime-spec spec))
(let ((timed-spec (get-singleton-create spec)))
(flet ((before-hook (args)
(declare (ignore args))
(setf *current-timing*
(make-instance 'timing :origin timed-spec)))
(after-hook (retlist)
(declare (ignore retlist))
(let* ((timing *current-timing*))
(when timing
(setf (end-of timing) (get-internal-real-time))
(setf *current-timing* (parent-of timing))))))
(ls-backend:wrap spec 'timings
:before #'before-hook
:after #'after-hook)
(format nil "~a is now timed for timing dialog" spec))))
(defslyfun untime-spec (spec)
(ls-backend:unwrap spec 'timings)
(let ((moribund (find spec (timed-specs) :test #'equal :key #'spec-of)))
(setf (timed-specs) (remove moribund (timed-specs)))
(loop for otherts in (timed-specs)
do (remhash moribund (stats-of otherts))))
(format nil "~a is now untimed for timing dialog" spec))
(defslyfun toggle-timing (spec)
(if (timed-spec-p spec)
(untime-spec spec)
(time-spec spec)))
(defslyfun timed-spec-p (spec)
(find spec (timed-specs) :test #'equal :key #'spec-of))
(defslyfun untime-all ()
(mapcar #'untime-spec (timed-specs)))
(defun describe-timing-for-emacs (timed-spec)
(declare (ignore timed-spec))
`not-implemented)
(defslyfun report-latest-timings ()
(loop for spec in (timed-specs)
append (loop for partial being the hash-values of (stats-of spec)
for path being the hash-keys of (stats-of spec)
collect (list (ls-base::slynk-pprint-to-line spec) partial
(ls-base::slynk-pprint-to-line path)))))
(defun print-tree ()
(loop for ts in (timed-specs)
for total = (total-of ts)
do (format t "~%~a~%~%" ts)
(when (plusp total)
(loop for partial being the hash-values of (stats-of ts)
for path being the hash-keys of (stats-of ts)
when (plusp partial)
sum partial into total-partials
and
do (format t " ~8fs ~4f% ~a ~%"
(/ partial
internal-time-units-per-second)
(* 100 (/ partial
total))
(spec-of path))
finally
(format t " ~8fs ~4f% ~a ~%"
(/ (- total total-partials)
internal-time-units-per-second)
(* 100 (/ (- total total-partials)
total))
'other)))))
(defslyfun clear-timing-tree ()
(setq *current-timing* nil)
(loop for ts in (timed-specs)
do (reinitialize-instance ts)))
(provide :ls-profiler)
|
0ed39dc0cac1ccbec0c1d1b3b742fb7c0805fe50e507f43d08390f5891d5e190 | buntine/Simply-Scheme-Exercises | 19-3.scm | Write the three - argument version of accumulate that we described .
;
> ( three - arg - accumulate + 0 ' ( 4 5 6 ) )
15
;
> ( three - arg - accumulate + 0 ' ( ) )
0
;
> ( three - arg - accumulate cons ' ( ) ' ( a b c d e ) )
; (A B C D E)
(define (three-arg-accumulate func null-value sent)
(if (empty? sent)
null-value
(func (car sent)
(three-arg-accumulate func null-value (cdr sent)))))
| null | https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/19-implementing-higher-order-functions/19-3.scm | scheme |
(A B C D E) | Write the three - argument version of accumulate that we described .
> ( three - arg - accumulate + 0 ' ( 4 5 6 ) )
15
> ( three - arg - accumulate + 0 ' ( ) )
0
> ( three - arg - accumulate cons ' ( ) ' ( a b c d e ) )
(define (three-arg-accumulate func null-value sent)
(if (empty? sent)
null-value
(func (car sent)
(three-arg-accumulate func null-value (cdr sent)))))
|
c17da0046890cb3b72c9a523247bee7a1d1675584b3c1f58b060a3bb45f45e88 | NorfairKing/smos | Gen.hs | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Cursor.Report.Entry.Gen where
import Cursor.Forest
import Cursor.Forest.Gen ()
import Cursor.Text.Gen ()
import Cursor.Tree
import Data.Foldable
import Data.GenValidity
import Data.GenValidity.Path ()
import Data.Maybe
import Lens.Micro
import Path
import Smos.Cursor.Report.Entry
import Smos.Data
import Smos.Data.Gen ()
import Test.QuickCheck
instance GenValid a => GenValid (EntryReportCursor a) where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
instance GenValid EntryReportCursorSelection where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
instance GenValid a => GenValid (EntryReportEntryCursor a) where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
genNonEmptyValidEntryReportCursorWith ::
(Path Rel File -> ForestCursor Entry Entry -> [a]) ->
([EntryReportEntryCursor a] -> [EntryReportEntryCursor a]) ->
Gen Entry ->
Gen (EntryReportCursor a)
genNonEmptyValidEntryReportCursorWith func finalise gen = makeEntryReportCursor . finalise <$> (toList <$> genNonEmptyOf (genValidEntryReportEntryCursorWith func gen))
genValidEntryReportCursorWith ::
(Path Rel File -> ForestCursor Entry Entry -> [a]) ->
([EntryReportEntryCursor a] -> [EntryReportEntryCursor a]) ->
Gen Entry ->
Gen (EntryReportCursor a)
genValidEntryReportCursorWith func finalise gen = makeEntryReportCursor . finalise <$> genListOf (genValidEntryReportEntryCursorWith func gen)
genValidEntryReportEntryCursorWith :: (Path Rel File -> ForestCursor Entry Entry -> [a]) -> Gen Entry -> Gen (EntryReportEntryCursor a)
genValidEntryReportEntryCursorWith func gen =
( do
rf <- genValid
fc <- genValid
e <- gen
pure (rf, fc & forestCursorSelectedTreeL . treeCursorCurrentL .~ e)
)
`suchThatMap` ( \(rf, fc) -> do
val <- listToMaybe (func rf fc)
pure $ makeEntryReportEntryCursor rf fc val
)
| null | https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos-report-cursor-gen/src/Smos/Cursor/Report/Entry/Gen.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Cursor.Report.Entry.Gen where
import Cursor.Forest
import Cursor.Forest.Gen ()
import Cursor.Text.Gen ()
import Cursor.Tree
import Data.Foldable
import Data.GenValidity
import Data.GenValidity.Path ()
import Data.Maybe
import Lens.Micro
import Path
import Smos.Cursor.Report.Entry
import Smos.Data
import Smos.Data.Gen ()
import Test.QuickCheck
instance GenValid a => GenValid (EntryReportCursor a) where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
instance GenValid EntryReportCursorSelection where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
instance GenValid a => GenValid (EntryReportEntryCursor a) where
genValid = genValidStructurallyWithoutExtraChecking
shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
genNonEmptyValidEntryReportCursorWith ::
(Path Rel File -> ForestCursor Entry Entry -> [a]) ->
([EntryReportEntryCursor a] -> [EntryReportEntryCursor a]) ->
Gen Entry ->
Gen (EntryReportCursor a)
genNonEmptyValidEntryReportCursorWith func finalise gen = makeEntryReportCursor . finalise <$> (toList <$> genNonEmptyOf (genValidEntryReportEntryCursorWith func gen))
genValidEntryReportCursorWith ::
(Path Rel File -> ForestCursor Entry Entry -> [a]) ->
([EntryReportEntryCursor a] -> [EntryReportEntryCursor a]) ->
Gen Entry ->
Gen (EntryReportCursor a)
genValidEntryReportCursorWith func finalise gen = makeEntryReportCursor . finalise <$> genListOf (genValidEntryReportEntryCursorWith func gen)
genValidEntryReportEntryCursorWith :: (Path Rel File -> ForestCursor Entry Entry -> [a]) -> Gen Entry -> Gen (EntryReportEntryCursor a)
genValidEntryReportEntryCursorWith func gen =
( do
rf <- genValid
fc <- genValid
e <- gen
pure (rf, fc & forestCursorSelectedTreeL . treeCursorCurrentL .~ e)
)
`suchThatMap` ( \(rf, fc) -> do
val <- listToMaybe (func rf fc)
pure $ makeEntryReportEntryCursor rf fc val
)
|
|
2842cccf380c8e0eb62f9a994229e1d195bd8c51f3ac2c722eb1cc7830f59e50 | lowasser/TrieMap | TrieBench.hs | # OPTIONS -fasm #
module TrieBench (main) where
import Criterion.Main
import Data.TrieSet
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import Control.Monad.Primitive
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Random (getRandomR, RandT, StdGen, evalRandT, mkStdGen)
import qualified Data.ByteString.Char8 as BS
import qualified Progression.Main as P
import Control.DeepSeq
import Data.List (sort)
import Prelude hiding (filter)
instance NFData BS.ByteString where
rnf xs = xs `seq` ()
shuffle :: V.Vector a -> V.Vector a
shuffle = V.modify (\ mv -> evalRandT (shuffleM mv) (mkStdGen 0))
shuffleM :: PrimMonad m => VM.MVector (PrimState m) a -> RandT StdGen m ()
shuffleM xs = forM_ [0..VM.length xs - 1] $ \ i -> do
j <- getRandomR (0, VM.length xs - 1)
lift $ VM.swap xs i j
tSortBench strings = toList (fromList strings)
tIntersectBench (strings, revs) = size (intersection strings revs)
tLookupBench (strings, s1, s2) = (s1 `member` strings, s2 `member` strings)
tUnionBench (strings, revs) = size strings + size revs - size (union strings revs)
tDiffBench (strings, revs) = size strings - size (difference strings revs)
tFilterBench strings = size (filter (\ str -> not (BS.null str) && BS.last str /= 's') strings)
tSplitBench strings = case split (BS.pack "logical") strings of
(l, r) -> size l - size r
tEnds strings = case deleteFindMin strings of
(l, strs') -> case deleteFindMax strs' of
(r, strs'') -> size strs'' + BS.length l - BS.length r
tFromList strings = size (fromList strings)
tToList strs = sum [BS.length str | str <- toList strs]
tFDAL strings = size (fromDistinctAscList strings)
tInsert strs = size (insert (BS.pack "scientifitude") strs)
tIndex strs = elemAt (31415926 `rem` size strs) strs
tNeighborhood (strs, str) = case splitMember str strs of
(l, x, r) -> (findMax l, x, findMin r)
nf' f a = f a `deepseq` nf f a
tBenches strings revs = bgroup ""
[bench "Lookup" (nf' tLookupBench (strSet, someStr1, someStr2)),
bench "Neighborhood" (nf' tNeighborhood (strSet, someStr2)),
revSet `seq` bench "Intersect" (nf' tIntersectBench (strSet, revSet)),
bench "Sort" (nf' tSortBench strings),
bench "Union" (nf' tUnionBench (strSet, revSet)),
bench "Difference" (nf' tDiffBench (strSet, revSet)),
bench "Filter" (nf' tFilterBench strSet),
bench "Split" (nf' tSplitBench strSet),
bench "Index" (nf' tIndex strSet),
bench "Min/Max" (nf' tEnds strSet),
bench "ToList" (nf' tToList strSet),
bench "Insert" (nf' tInsert strSet),
bench "FromList" (nf' tFromList strings),
bench "FromDistinctAscList" (nf' tFDAL strSort)]
where !strSet = fromList strings; !revSet = fromList revs; !strSort = sort strings
someStr1 = strings !! (314159 `rem` n); someStr2 = revs !! (314159 `rem` n)
n = length strings
main :: IO ()
main = do
strings <- liftM BS.lines (BS.readFile "dictionary.txt")
let !strings' = V.toList (shuffle (V.fromList strings))
let !revs' = Prelude.map BS.reverse strings'
let benches = tBenches strings' revs'
strings' `deepseq` revs' `deepseq` P.defaultMain benches
| null | https://raw.githubusercontent.com/lowasser/TrieMap/1ab52b8d83469974a629f2aa577a85de3f9e867a/TrieBench.hs | haskell | # OPTIONS -fasm #
module TrieBench (main) where
import Criterion.Main
import Data.TrieSet
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import Control.Monad.Primitive
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Random (getRandomR, RandT, StdGen, evalRandT, mkStdGen)
import qualified Data.ByteString.Char8 as BS
import qualified Progression.Main as P
import Control.DeepSeq
import Data.List (sort)
import Prelude hiding (filter)
instance NFData BS.ByteString where
rnf xs = xs `seq` ()
shuffle :: V.Vector a -> V.Vector a
shuffle = V.modify (\ mv -> evalRandT (shuffleM mv) (mkStdGen 0))
shuffleM :: PrimMonad m => VM.MVector (PrimState m) a -> RandT StdGen m ()
shuffleM xs = forM_ [0..VM.length xs - 1] $ \ i -> do
j <- getRandomR (0, VM.length xs - 1)
lift $ VM.swap xs i j
tSortBench strings = toList (fromList strings)
tIntersectBench (strings, revs) = size (intersection strings revs)
tLookupBench (strings, s1, s2) = (s1 `member` strings, s2 `member` strings)
tUnionBench (strings, revs) = size strings + size revs - size (union strings revs)
tDiffBench (strings, revs) = size strings - size (difference strings revs)
tFilterBench strings = size (filter (\ str -> not (BS.null str) && BS.last str /= 's') strings)
tSplitBench strings = case split (BS.pack "logical") strings of
(l, r) -> size l - size r
tEnds strings = case deleteFindMin strings of
(l, strs') -> case deleteFindMax strs' of
(r, strs'') -> size strs'' + BS.length l - BS.length r
tFromList strings = size (fromList strings)
tToList strs = sum [BS.length str | str <- toList strs]
tFDAL strings = size (fromDistinctAscList strings)
tInsert strs = size (insert (BS.pack "scientifitude") strs)
tIndex strs = elemAt (31415926 `rem` size strs) strs
tNeighborhood (strs, str) = case splitMember str strs of
(l, x, r) -> (findMax l, x, findMin r)
nf' f a = f a `deepseq` nf f a
tBenches strings revs = bgroup ""
[bench "Lookup" (nf' tLookupBench (strSet, someStr1, someStr2)),
bench "Neighborhood" (nf' tNeighborhood (strSet, someStr2)),
revSet `seq` bench "Intersect" (nf' tIntersectBench (strSet, revSet)),
bench "Sort" (nf' tSortBench strings),
bench "Union" (nf' tUnionBench (strSet, revSet)),
bench "Difference" (nf' tDiffBench (strSet, revSet)),
bench "Filter" (nf' tFilterBench strSet),
bench "Split" (nf' tSplitBench strSet),
bench "Index" (nf' tIndex strSet),
bench "Min/Max" (nf' tEnds strSet),
bench "ToList" (nf' tToList strSet),
bench "Insert" (nf' tInsert strSet),
bench "FromList" (nf' tFromList strings),
bench "FromDistinctAscList" (nf' tFDAL strSort)]
where !strSet = fromList strings; !revSet = fromList revs; !strSort = sort strings
someStr1 = strings !! (314159 `rem` n); someStr2 = revs !! (314159 `rem` n)
n = length strings
main :: IO ()
main = do
strings <- liftM BS.lines (BS.readFile "dictionary.txt")
let !strings' = V.toList (shuffle (V.fromList strings))
let !revs' = Prelude.map BS.reverse strings'
let benches = tBenches strings' revs'
strings' `deepseq` revs' `deepseq` P.defaultMain benches
|
|
b5eec05a720d52ae6ca2634307eaf7c1f69c4a08bbdb03a06b286f8db204b948 | matsen/pplacer | nbc.mli | open Ppatteries
exception Invalid_base of char
val bases: string
val informative: char -> bool
val word_to_int: string -> int
val int_to_word: ?word_length:int -> int -> string
val gen_count_by_seq: int -> (int -> unit) -> string -> unit
val max_word_length: int
val random_winner_max_index: ('a, 'b, 'c) Bigarray.Array1.t -> int
module Preclassifier: sig
type 'a t
exception Tax_id_not_found of Tax_id.t
val make: (int, 'a) Bigarray.kind -> int -> Tax_id.t array -> 'a t
val tax_id_idx: 'a t -> Tax_id.t -> int
val add_seq: 'a t -> Tax_id.t -> string -> unit
end
module Classifier: sig
type t
type rank = Rank of int | Auto_rank | All_ranks
val make: ?n_boot:int -> ?map_file:(Unix.file_descr * bool) -> ?rng:Random.State.t -> 'a Preclassifier.t -> t
val classify: t -> ?like_rdp:bool -> ?random_tie_break:bool -> string -> Tax_id.t
val bootstrap: t -> ?like_rdp:bool -> ?random_tie_break:bool -> string -> float Tax_id.TaxIdMap.t
val of_refpkg:
?ref_aln:Alignment.t -> ?n_boot:int -> ?map_file:(Unix.file_descr * bool) -> ?rng:Random.State.t ->
int -> rank -> Refpkg.t -> t
end
| null | https://raw.githubusercontent.com/matsen/pplacer/f40a363e962cca7131f1f2d372262e0081ff1190/pplacer_src/nbc.mli | ocaml | open Ppatteries
exception Invalid_base of char
val bases: string
val informative: char -> bool
val word_to_int: string -> int
val int_to_word: ?word_length:int -> int -> string
val gen_count_by_seq: int -> (int -> unit) -> string -> unit
val max_word_length: int
val random_winner_max_index: ('a, 'b, 'c) Bigarray.Array1.t -> int
module Preclassifier: sig
type 'a t
exception Tax_id_not_found of Tax_id.t
val make: (int, 'a) Bigarray.kind -> int -> Tax_id.t array -> 'a t
val tax_id_idx: 'a t -> Tax_id.t -> int
val add_seq: 'a t -> Tax_id.t -> string -> unit
end
module Classifier: sig
type t
type rank = Rank of int | Auto_rank | All_ranks
val make: ?n_boot:int -> ?map_file:(Unix.file_descr * bool) -> ?rng:Random.State.t -> 'a Preclassifier.t -> t
val classify: t -> ?like_rdp:bool -> ?random_tie_break:bool -> string -> Tax_id.t
val bootstrap: t -> ?like_rdp:bool -> ?random_tie_break:bool -> string -> float Tax_id.TaxIdMap.t
val of_refpkg:
?ref_aln:Alignment.t -> ?n_boot:int -> ?map_file:(Unix.file_descr * bool) -> ?rng:Random.State.t ->
int -> rank -> Refpkg.t -> t
end
|
|
adf7ee82a22e2c3cb98ddc88c84b76153ff94a31f92ea2710af556b47284eeb4 | clash-lang/clash-compiler | Deriving.hs | |
Copyright : ( C ) 2018 - 2022 , Google Inc
2019 , Myrtle Software Ltd
2023 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : QBayLogic B.V. < >
Copyright : (C) 2018-2022, Google Inc
2019, Myrtle Software Ltd
2023, QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : QBayLogic B.V. <>
-}
# LANGUAGE CPP #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Clash.Clocks.Deriving (deriveClocksInstances) where
import Control.Monad (foldM)
import Clash.Explicit.Signal (unsafeSynchronizer)
import Clash.Signal.Internal
import Language.Haskell.TH.Compat
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Lib
import Unsafe.Coerce (unsafeCoerce)
conPatternNoTypes :: Name -> [Pat] -> Pat
#if MIN_VERSION_template_haskell(2,18,0)
conPatternNoTypes nm pats = ConP nm [] pats
#else
conPatternNoTypes nm pats = ConP nm pats
#endif
-- Derive instance for /n/ clocks
derive' :: Int -> Q Dec
derive' n = do
( Clock d0 , Clock d1 , )
instType0 <- foldM (\a n' -> AppT a <$> clkType n') (TupleT $ n + 1) [1..n]
instType1 <- AppT instType0 <$> lockType
let instHead = AppT (ConT $ mkName "Clocks") instType1
cxtRHS0 <-
foldM (\a n' -> AppT a <$> knownDomainCxt n') (TupleT $ n + 1) [1..n]
cxtRHS1 <- AppT cxtRHS0 <$> lockKnownDomainCxt
#if MIN_VERSION_template_haskell(2,15,0)
let cxtLHS = AppT (ConT $ mkName "ClocksCxt") instType1
let cxtTy = TySynInstD (TySynEqn Nothing cxtLHS cxtRHS1)
#else
let cxtTy = TySynInstD (mkName "ClocksCxt") (TySynEqn [instType1] cxtRHS1)
#endif
-- Function definition of 'clocks'
let clk = mkName "clk"
let rst = mkName "rst"
-- Implementation of 'clocks'
lockImpl <- [| unsafeSynchronizer clockGen clockGen
(unsafeToLowPolarity $(varE rst)) |]
let
noInline = PragmaD $ InlineP (mkName "clocks") NoInline FunLike AllPhases
clkImpls = replicate n (clkImpl clk)
instTuple = mkTupE $ clkImpls ++ [lockImpl]
funcBody = NormalB instTuple
errMsg = "clocks: dynamic clocks unsupported"
errBody = NormalB ((VarE 'error) `AppE` (LitE (StringL errMsg)))
instFunc = FunD (mkName "clocks")
[ Clause
[ AsP
clk
(conPatternNoTypes 'Clock [WildP, conPatternNoTypes 'Nothing []])
, VarP rst]
funcBody
[]
, Clause [WildP, WildP] errBody []
]
return $ InstanceD Nothing [] instHead [cxtTy, instFunc, noInline]
where
-- | Generate type @Clock dom@ with fresh @dom@ variable
clkType n' =
let c = varT $ mkName ("c" ++ show n') in
[t| Clock $c |]
knownDomainCxt n' =
let c = varT $ mkName ("c" ++ show n') in
[t| KnownDomain $c |]
| Generate type @Signal dom ' Bool@ with fresh @dom@ variable
lockType =
let c = varT $ mkName "pllLock" in
[t| Signal $c Bool |]
lockKnownDomainCxt =
let p = varT $ mkName "pllLock" in
[t| KnownDomain $p |]
clkImpl clk = AppE (VarE 'unsafeCoerce) (VarE clk)
-- Derive instances for up to and including to /n/ clocks
deriveClocksInstances :: Int -> Q [Dec]
deriveClocksInstances n = mapM derive' [1..n]
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/c60353ef28bece4a62f4425ff78b0bd96ed69e40/clash-prelude/src/Clash/Clocks/Deriving.hs | haskell | Derive instance for /n/ clocks
Function definition of 'clocks'
Implementation of 'clocks'
| Generate type @Clock dom@ with fresh @dom@ variable
Derive instances for up to and including to /n/ clocks | |
Copyright : ( C ) 2018 - 2022 , Google Inc
2019 , Myrtle Software Ltd
2023 , QBayLogic B.V.
License : BSD2 ( see the file LICENSE )
Maintainer : QBayLogic B.V. < >
Copyright : (C) 2018-2022, Google Inc
2019, Myrtle Software Ltd
2023, QBayLogic B.V.
License : BSD2 (see the file LICENSE)
Maintainer : QBayLogic B.V. <>
-}
# LANGUAGE CPP #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Clash.Clocks.Deriving (deriveClocksInstances) where
import Control.Monad (foldM)
import Clash.Explicit.Signal (unsafeSynchronizer)
import Clash.Signal.Internal
import Language.Haskell.TH.Compat
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Lib
import Unsafe.Coerce (unsafeCoerce)
conPatternNoTypes :: Name -> [Pat] -> Pat
#if MIN_VERSION_template_haskell(2,18,0)
conPatternNoTypes nm pats = ConP nm [] pats
#else
conPatternNoTypes nm pats = ConP nm pats
#endif
derive' :: Int -> Q Dec
derive' n = do
( Clock d0 , Clock d1 , )
instType0 <- foldM (\a n' -> AppT a <$> clkType n') (TupleT $ n + 1) [1..n]
instType1 <- AppT instType0 <$> lockType
let instHead = AppT (ConT $ mkName "Clocks") instType1
cxtRHS0 <-
foldM (\a n' -> AppT a <$> knownDomainCxt n') (TupleT $ n + 1) [1..n]
cxtRHS1 <- AppT cxtRHS0 <$> lockKnownDomainCxt
#if MIN_VERSION_template_haskell(2,15,0)
let cxtLHS = AppT (ConT $ mkName "ClocksCxt") instType1
let cxtTy = TySynInstD (TySynEqn Nothing cxtLHS cxtRHS1)
#else
let cxtTy = TySynInstD (mkName "ClocksCxt") (TySynEqn [instType1] cxtRHS1)
#endif
let clk = mkName "clk"
let rst = mkName "rst"
lockImpl <- [| unsafeSynchronizer clockGen clockGen
(unsafeToLowPolarity $(varE rst)) |]
let
noInline = PragmaD $ InlineP (mkName "clocks") NoInline FunLike AllPhases
clkImpls = replicate n (clkImpl clk)
instTuple = mkTupE $ clkImpls ++ [lockImpl]
funcBody = NormalB instTuple
errMsg = "clocks: dynamic clocks unsupported"
errBody = NormalB ((VarE 'error) `AppE` (LitE (StringL errMsg)))
instFunc = FunD (mkName "clocks")
[ Clause
[ AsP
clk
(conPatternNoTypes 'Clock [WildP, conPatternNoTypes 'Nothing []])
, VarP rst]
funcBody
[]
, Clause [WildP, WildP] errBody []
]
return $ InstanceD Nothing [] instHead [cxtTy, instFunc, noInline]
where
clkType n' =
let c = varT $ mkName ("c" ++ show n') in
[t| Clock $c |]
knownDomainCxt n' =
let c = varT $ mkName ("c" ++ show n') in
[t| KnownDomain $c |]
| Generate type @Signal dom ' Bool@ with fresh @dom@ variable
lockType =
let c = varT $ mkName "pllLock" in
[t| Signal $c Bool |]
lockKnownDomainCxt =
let p = varT $ mkName "pllLock" in
[t| KnownDomain $p |]
clkImpl clk = AppE (VarE 'unsafeCoerce) (VarE clk)
deriveClocksInstances :: Int -> Q [Dec]
deriveClocksInstances n = mapM derive' [1..n]
|
dd78980c6f75651ddc9a669e376345275d3ac5641fb6ad5c7cf32f6bf04e927d | jnear/compiler-construction-assignments | r5_1.rkt | ((lambda: ([x : Integer]) : Integer x) 42)
| null | https://raw.githubusercontent.com/jnear/compiler-construction-assignments/17a1edbd59627341622203056180d9af7830756d/tests/r5_1.rkt | racket | ((lambda: ([x : Integer]) : Integer x) 42)
|
|
1de79f7beb2a27cd80c36d8231daeb7dc5d70943e5f4721f1e1fadc229bee635 | dstarcev/stepic-haskell | Task5.hs | module Module3.Task5 where
sum3 :: Num a => [a] -> [a] -> [a] -> [a]
sum3 = iter []
where
iter a [] [] [] = reverse a
iter a [] a2 a3 = iter a [0] a2 a3
iter a a1 [] a3 = iter a a1 [0] a3
iter a a1 a2 [] = iter a a1 a2 [0]
iter a (x1:xs1) (x2:xs2) (x3:xs3) =
iter (x1 + x2 + x3 : a) xs1 xs2 xs3
| null | https://raw.githubusercontent.com/dstarcev/stepic-haskell/6a8cf4b3cc17333ac4175e825db57dbe151ebae0/src/Module3/Task5.hs | haskell | module Module3.Task5 where
sum3 :: Num a => [a] -> [a] -> [a] -> [a]
sum3 = iter []
where
iter a [] [] [] = reverse a
iter a [] a2 a3 = iter a [0] a2 a3
iter a a1 [] a3 = iter a a1 [0] a3
iter a a1 a2 [] = iter a a1 a2 [0]
iter a (x1:xs1) (x2:xs2) (x3:xs3) =
iter (x1 + x2 + x3 : a) xs1 xs2 xs3
|
|
adbf859e9ba6d6321d31796cd8c7ef5811404a4f10b8819713d2bb569871fead | DSiSc/why3 | why3__BigInt.ml |
open Why3__BigInt_compat
type t = Why3__BigInt_compat.big_int
let compare = compare_big_int
let zero = zero_big_int
let one = unit_big_int
let succ = succ_big_int
let pred = pred_big_int
let add_int = add_int_big_int
let mul_int = mult_int_big_int
let add = add_big_int
let sub = sub_big_int
let mul = mult_big_int
let minus = minus_big_int
let sign = sign_big_int
let eq = eq_big_int
let lt = lt_big_int
let gt = gt_big_int
let le = le_big_int
let ge = ge_big_int
let lt_nat x y = le zero y && lt x y
let lex (x1,x2) (y1,y2) = lt x1 y1 || eq x1 y1 && lt x2 y2
let euclidean_div_mod x y =
if sign y = 0 then zero, zero else quomod_big_int x y
let euclidean_div x y = fst (euclidean_div_mod x y)
let euclidean_mod x y = snd (euclidean_div_mod x y)
let computer_div_mod x y =
let (q,r) as qr = euclidean_div_mod x y in
(* when y <> 0, we have x = q*y + r with 0 <= r < |y| *)
if sign x >= 0 || sign r = 0 then qr
else
if sign y < 0
then (pred q, add r y)
else (succ q, sub r y)
let computer_div x y = fst (computer_div_mod x y)
let computer_mod x y = snd (computer_div_mod x y)
let min = min_big_int
let max = max_big_int
let abs = abs_big_int
let pow_int_pos = power_int_positive_int
let to_string = string_of_big_int
let of_string = big_int_of_string
let to_int = int_of_big_int
let of_int = big_int_of_int
let to_int32 = int32_of_big_int
let of_int32 = big_int_of_int32
let to_int64 = int64_of_big_int
let of_int64 = big_int_of_int64
let power x y =
try power_big_int_positive_big_int x y
with Invalid_argument _ -> zero
let print n = Pervasives.print_string (to_string n)
let chr n = Pervasives.char_of_int (to_int n)
let code c = of_int (Pervasives.int_of_char c)
let random_int n =
try let n = int64_of_big_int n in
if n >= 0L then big_int_of_int64 (Random.int64 n) else raise Exit
with _ -> invalid_arg "Why3__BigInt.random"
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/lib/ocaml/why3__BigInt.ml | ocaml | when y <> 0, we have x = q*y + r with 0 <= r < |y| |
open Why3__BigInt_compat
type t = Why3__BigInt_compat.big_int
let compare = compare_big_int
let zero = zero_big_int
let one = unit_big_int
let succ = succ_big_int
let pred = pred_big_int
let add_int = add_int_big_int
let mul_int = mult_int_big_int
let add = add_big_int
let sub = sub_big_int
let mul = mult_big_int
let minus = minus_big_int
let sign = sign_big_int
let eq = eq_big_int
let lt = lt_big_int
let gt = gt_big_int
let le = le_big_int
let ge = ge_big_int
let lt_nat x y = le zero y && lt x y
let lex (x1,x2) (y1,y2) = lt x1 y1 || eq x1 y1 && lt x2 y2
let euclidean_div_mod x y =
if sign y = 0 then zero, zero else quomod_big_int x y
let euclidean_div x y = fst (euclidean_div_mod x y)
let euclidean_mod x y = snd (euclidean_div_mod x y)
let computer_div_mod x y =
let (q,r) as qr = euclidean_div_mod x y in
if sign x >= 0 || sign r = 0 then qr
else
if sign y < 0
then (pred q, add r y)
else (succ q, sub r y)
let computer_div x y = fst (computer_div_mod x y)
let computer_mod x y = snd (computer_div_mod x y)
let min = min_big_int
let max = max_big_int
let abs = abs_big_int
let pow_int_pos = power_int_positive_int
let to_string = string_of_big_int
let of_string = big_int_of_string
let to_int = int_of_big_int
let of_int = big_int_of_int
let to_int32 = int32_of_big_int
let of_int32 = big_int_of_int32
let to_int64 = int64_of_big_int
let of_int64 = big_int_of_int64
let power x y =
try power_big_int_positive_big_int x y
with Invalid_argument _ -> zero
let print n = Pervasives.print_string (to_string n)
let chr n = Pervasives.char_of_int (to_int n)
let code c = of_int (Pervasives.int_of_char c)
let random_int n =
try let n = int64_of_big_int n in
if n >= 0L then big_int_of_int64 (Random.int64 n) else raise Exit
with _ -> invalid_arg "Why3__BigInt.random"
|
93afd82b75d6f64f8d0e154200ea9cf4e309d79c37a184dd5e2c250c1b0f3721 | cryptosense/pkcs11 | pkcs11_CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE.mli | * Salt used in [ CKM_PKCS5_PBKD2 ] ( [ CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE ] )
type t = P11_ulong.t [@@deriving eq, ord]
val _CKZ_SALT_SPECIFIED : t
val make : P11_pkcs5_pbkdf2_salt_source_type.t -> t
val view : t -> P11_pkcs5_pbkdf2_salt_source_type.t
val typ : t Ctypes.typ
| null | https://raw.githubusercontent.com/cryptosense/pkcs11/93c39c7a31c87f68f0beabf75ef90d85a782a983/driver/pkcs11_CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE.mli | ocaml | * Salt used in [ CKM_PKCS5_PBKD2 ] ( [ CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE ] )
type t = P11_ulong.t [@@deriving eq, ord]
val _CKZ_SALT_SPECIFIED : t
val make : P11_pkcs5_pbkdf2_salt_source_type.t -> t
val view : t -> P11_pkcs5_pbkdf2_salt_source_type.t
val typ : t Ctypes.typ
|
|
6d2569311a3e646c53ef2c7e6e492e1f97c4e4f2c96adc9b6a9b614786296476 | avsm/eeww | test_caml_parallel.ml | (* TEST
include runtime_events
*)
open Runtime_events
let majors = Atomic.make 0
let minors = Atomic.make 0
let got_start = ref false
let lost_events_count = ref 0
let lost_events domain_id num_events =
lost_events_count := !lost_events_count + num_events
let lifecycle domain_id ts lifecycle_event data =
match lifecycle_event with
| EV_RING_START ->
begin
assert(match data with
| Some(pid) -> true
| None -> false);
got_start := true
end
| _ -> ()
type phase_record = { mutable major: int; mutable minor: int }
let domain_tbl : (int, phase_record) Hashtbl.t = Hashtbl.create 5
let find_or_create_phase_count domain_id =
match Hashtbl.find_opt domain_tbl domain_id with
| None ->
begin
let new_count = { major = 0; minor = 0} in
Hashtbl.add domain_tbl domain_id new_count;
new_count
end
| Some(pc) -> pc
let runtime_begin domain_id ts phase =
let phase_count = find_or_create_phase_count domain_id in
match phase with
| EV_MAJOR ->
begin
assert(phase_count.major >= 0);
phase_count.major <- phase_count.major + 1;
end
| EV_MINOR ->
begin
assert(phase_count.minor == 0);
phase_count.minor <- 1
end
| _ -> ()
let runtime_end domain_id ts phase =
let phase_count = find_or_create_phase_count domain_id in
match phase with
| EV_MAJOR ->
begin
assert(phase_count.major >= 1);
phase_count.major <- phase_count.major - 1;
Atomic.incr majors
end
| EV_MINOR ->
begin
assert(phase_count.minor == 1);
phase_count.minor <- 0;
Atomic.incr minors
end
| _ -> ()
let num_domains = 3
let num_minors = 30
let () =
start ();
let cursor = create_cursor None in
let gc_churn_f () =
let list_ref = ref [] in
for j = 0 to num_minors do
list_ref := [];
for a = 0 to 100 do
list_ref := (Sys.opaque_identity(ref 42)) :: !list_ref
done;
Gc.minor ();
done
in
let domains_list = List.init num_domains (fun _ -> Domain.spawn gc_churn_f) in
let _ = List.iter Domain.join domains_list in
let callbacks = Callbacks.create ~runtime_begin ~runtime_end ~lifecycle
~lost_events () in
ignore(read_poll cursor callbacks None);
assert(!got_start);
assert(Atomic.get minors >= num_minors);
assert(!lost_events_count == 0)
| null | https://raw.githubusercontent.com/avsm/eeww/23ca8b36127b337512e13c6fb8e86b3a7254d4f9/boot/ocaml/testsuite/tests/lib-runtime-events/test_caml_parallel.ml | ocaml | TEST
include runtime_events
| open Runtime_events
let majors = Atomic.make 0
let minors = Atomic.make 0
let got_start = ref false
let lost_events_count = ref 0
let lost_events domain_id num_events =
lost_events_count := !lost_events_count + num_events
let lifecycle domain_id ts lifecycle_event data =
match lifecycle_event with
| EV_RING_START ->
begin
assert(match data with
| Some(pid) -> true
| None -> false);
got_start := true
end
| _ -> ()
type phase_record = { mutable major: int; mutable minor: int }
let domain_tbl : (int, phase_record) Hashtbl.t = Hashtbl.create 5
let find_or_create_phase_count domain_id =
match Hashtbl.find_opt domain_tbl domain_id with
| None ->
begin
let new_count = { major = 0; minor = 0} in
Hashtbl.add domain_tbl domain_id new_count;
new_count
end
| Some(pc) -> pc
let runtime_begin domain_id ts phase =
let phase_count = find_or_create_phase_count domain_id in
match phase with
| EV_MAJOR ->
begin
assert(phase_count.major >= 0);
phase_count.major <- phase_count.major + 1;
end
| EV_MINOR ->
begin
assert(phase_count.minor == 0);
phase_count.minor <- 1
end
| _ -> ()
let runtime_end domain_id ts phase =
let phase_count = find_or_create_phase_count domain_id in
match phase with
| EV_MAJOR ->
begin
assert(phase_count.major >= 1);
phase_count.major <- phase_count.major - 1;
Atomic.incr majors
end
| EV_MINOR ->
begin
assert(phase_count.minor == 1);
phase_count.minor <- 0;
Atomic.incr minors
end
| _ -> ()
let num_domains = 3
let num_minors = 30
let () =
start ();
let cursor = create_cursor None in
let gc_churn_f () =
let list_ref = ref [] in
for j = 0 to num_minors do
list_ref := [];
for a = 0 to 100 do
list_ref := (Sys.opaque_identity(ref 42)) :: !list_ref
done;
Gc.minor ();
done
in
let domains_list = List.init num_domains (fun _ -> Domain.spawn gc_churn_f) in
let _ = List.iter Domain.join domains_list in
let callbacks = Callbacks.create ~runtime_begin ~runtime_end ~lifecycle
~lost_events () in
ignore(read_poll cursor callbacks None);
assert(!got_start);
assert(Atomic.get minors >= num_minors);
assert(!lost_events_count == 0)
|
cc735b9d650f4b01da9aecc63c1f003ebef199087c153776fd2f6f7d5f4e9aea | simonstl/introducing-erlang-2nd | drop.erl | -module(drop).
-export([fall_velocity/1]).
fall_velocity(Distance) -> math:sqrt(2 * 9.8 * Distance). | null | https://raw.githubusercontent.com/simonstl/introducing-erlang-2nd/607e9c85fb767cf5519d331ef6ed549aee51fe61/ch02/ex4-combined/drop.erl | erlang | -module(drop).
-export([fall_velocity/1]).
fall_velocity(Distance) -> math:sqrt(2 * 9.8 * Distance). |
|
509a04d76b114b6a1332a43ba298a3a769daf0b0702fe6e4fd537c730d59fe38 | tonymorris/geo-osm | MaxlatL.hs | -- | Values with a @maxlat@ string accessor.
module Data.Geo.OSM.Lens.MaxlatL where
import Control.Lens.Lens
class MaxlatL a where
maxlatL ::
Lens' a String
| null | https://raw.githubusercontent.com/tonymorris/geo-osm/776542be2fd30a05f0f9e867128eca5ad5d66bec/src/Data/Geo/OSM/Lens/MaxlatL.hs | haskell | | Values with a @maxlat@ string accessor. | module Data.Geo.OSM.Lens.MaxlatL where
import Control.Lens.Lens
class MaxlatL a where
maxlatL ::
Lens' a String
|
872f547dcaaf54f088644bd1d21548b562b6a38801611efedc7b7e87cd548ee3 | mitchellwrosen/dohaskell | Tag.hs | module Model.Tag where
import Import
import Model.Resource
-- | Get all tags.
fetchAllTagsDB :: YesodDB App [Entity Tag]
fetchAllTagsDB = selectList [] []
| Get a map of TagId to the number of Resources with that tag .
fetchTagCountsDB :: YesodDB App (Map TagId Int)
fetchTagCountsDB = fetchResourceFieldCountsDB ResourceTagTagId
-- | Get the year range of all Resources of with a specific Tag. If none of the
-- Resources with that Tag have any published year, then the Tag will not exist
-- in the returned map.
fetchTagYearRangesDB :: YesodDB App (Map TagId (Int, Int))
fetchTagYearRangesDB = fetchResourceFieldYearRangesDB ResourceTagResId ResourceTagTagId
| null | https://raw.githubusercontent.com/mitchellwrosen/dohaskell/69aea7a42112557ac3e835b9dbdb9bf60a81f780/src/Model/Tag.hs | haskell | | Get all tags.
| Get the year range of all Resources of with a specific Tag. If none of the
Resources with that Tag have any published year, then the Tag will not exist
in the returned map. | module Model.Tag where
import Import
import Model.Resource
fetchAllTagsDB :: YesodDB App [Entity Tag]
fetchAllTagsDB = selectList [] []
| Get a map of TagId to the number of Resources with that tag .
fetchTagCountsDB :: YesodDB App (Map TagId Int)
fetchTagCountsDB = fetchResourceFieldCountsDB ResourceTagTagId
fetchTagYearRangesDB :: YesodDB App (Map TagId (Int, Int))
fetchTagYearRangesDB = fetchResourceFieldYearRangesDB ResourceTagResId ResourceTagTagId
|
df95c4dd7e8ed7c8b82264a5b5c40ae97922865373ba249a6d2fbb1c168f31a9 | maximedenes/native-coq | gmap.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Maps using the generic comparison function of ocaml . Code borrowed from
the ocaml standard library ( Copyright 1996 , INRIA ) .
the ocaml standard library (Copyright 1996, INRIA). *)
type ('a,'b) t =
Empty
| Node of ('a,'b) t * 'a * 'b * ('a,'b) t * int
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let height = function
Empty -> 0
| Node(_,_,_,_,h) -> h
let create l x d r =
let hl = height l and hr = height r in
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let bal l x d r =
let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node(ll, lv, ld, lr, _) ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node(lrl, lrv, lrd, lrr, _)->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node(rl, rv, rd, rr, _) ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node(rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let rec add x data = function
Empty ->
Node(Empty, x, data, Empty, 1)
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
Node(l, x, data, r, h)
else if c < 0 then
bal (add x data l) v d r
else
bal l v d (add x data r)
let rec find x = function
Empty ->
raise Not_found
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node(Empty, x, d, r, _) -> (x, d)
| Node(l, x, d, r, _) -> min_binding l
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node(Empty, x, d, r, _) -> r
| Node(l, x, d, r, _) -> bal (remove_min_binding l) x d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
merge l r
else if c < 0 then
bal (remove x l) v d r
else
bal l v d (remove x r)
let rec iter f = function
Empty -> ()
| Node(l, v, d, r, _) ->
iter f l; f v d; iter f r
let rec map f = function
Empty -> Empty
| Node(l, v, d, r, h) -> Node(map f l, v, f d, map f r, h)
(* Maintien de fold_right par compatibilité (changé en fold_left dans
ocaml-3.09.0) *)
let rec fold f m accu =
match m with
Empty -> accu
| Node(l, v, d, r, _) ->
fold f l (f v d (fold f r accu))
(* Added with respect to ocaml standard library. *)
let dom m = fold (fun x _ acc -> x::acc) m []
let rng m = fold (fun _ y acc -> y::acc) m []
let to_list m = fold (fun x y acc -> (x,y)::acc) m []
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/lib/gmap.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Maintien de fold_right par compatibilité (changé en fold_left dans
ocaml-3.09.0)
Added with respect to ocaml standard library. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Maps using the generic comparison function of ocaml . Code borrowed from
the ocaml standard library ( Copyright 1996 , INRIA ) .
the ocaml standard library (Copyright 1996, INRIA). *)
type ('a,'b) t =
Empty
| Node of ('a,'b) t * 'a * 'b * ('a,'b) t * int
let empty = Empty
let is_empty = function Empty -> true | _ -> false
let height = function
Empty -> 0
| Node(_,_,_,_,h) -> h
let create l x d r =
let hl = height l and hr = height r in
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let bal l x d r =
let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
if hl > hr + 2 then begin
match l with
Empty -> invalid_arg "Map.bal"
| Node(ll, lv, ld, lr, _) ->
if height ll >= height lr then
create ll lv ld (create lr x d r)
else begin
match lr with
Empty -> invalid_arg "Map.bal"
| Node(lrl, lrv, lrd, lrr, _)->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)
end
end else if hr > hl + 2 then begin
match r with
Empty -> invalid_arg "Map.bal"
| Node(rl, rv, rd, rr, _) ->
if height rr >= height rl then
create (create l x d rl) rv rd rr
else begin
match rl with
Empty -> invalid_arg "Map.bal"
| Node(rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)
end
end else
Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
let rec add x data = function
Empty ->
Node(Empty, x, data, Empty, 1)
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
Node(l, x, data, r, h)
else if c < 0 then
bal (add x data l) v d r
else
bal l v d (add x data r)
let rec find x = function
Empty ->
raise Not_found
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
if c = 0 then d
else find x (if c < 0 then l else r)
let rec mem x = function
Empty ->
false
| Node(l, v, d, r, _) ->
let c = Pervasives.compare x v in
c = 0 || mem x (if c < 0 then l else r)
let rec min_binding = function
Empty -> raise Not_found
| Node(Empty, x, d, r, _) -> (x, d)
| Node(l, x, d, r, _) -> min_binding l
let rec remove_min_binding = function
Empty -> invalid_arg "Map.remove_min_elt"
| Node(Empty, x, d, r, _) -> r
| Node(l, x, d, r, _) -> bal (remove_min_binding l) x d r
let merge t1 t2 =
match (t1, t2) with
(Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let (x, d) = min_binding t2 in
bal t1 x d (remove_min_binding t2)
let rec remove x = function
Empty ->
Empty
| Node(l, v, d, r, h) ->
let c = Pervasives.compare x v in
if c = 0 then
merge l r
else if c < 0 then
bal (remove x l) v d r
else
bal l v d (remove x r)
let rec iter f = function
Empty -> ()
| Node(l, v, d, r, _) ->
iter f l; f v d; iter f r
let rec map f = function
Empty -> Empty
| Node(l, v, d, r, h) -> Node(map f l, v, f d, map f r, h)
let rec fold f m accu =
match m with
Empty -> accu
| Node(l, v, d, r, _) ->
fold f l (f v d (fold f r accu))
let dom m = fold (fun x _ acc -> x::acc) m []
let rng m = fold (fun _ y acc -> y::acc) m []
let to_list m = fold (fun x y acc -> (x,y)::acc) m []
|
cf7004a7d9f47a25fb4b5d47c90dd745b4637dd89f6c25ee9f52bdd4a7e5fbb1 | system-f/fp-course | Validation.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module Course.Validation where
import qualified Prelude as P(String)
import Course.Core
-- $setup
-- >>> import Test.QuickCheck
> > > import qualified Prelude as P(fmap , either )
> > > instance Arbitrary a = > Arbitrary ( Validation a ) where arbitrary = ( P.either Error Value ) arbitrary
data Validation a = Error Err | Value a
deriving (Eq, Show)
type Err = P.String
-- | Returns whether or not the given validation is an error.
--
-- >>> isError (Error "message")
-- True
--
> > > isError ( Value 7 )
-- False
--
prop > \x - > isError x /= isValue x
isError :: Validation a -> Bool
isError (Error _) = True
isError (Value _) = False
-- | Returns whether or not the given validation is a value.
--
-- >>> isValue (Error "message")
-- False
--
> > > isValue ( Value 7 )
-- True
--
prop > \x - > isValue x /= isError x
isValue :: Validation a -> Bool
isValue = not . isError
-- | Maps a function on a validation's value side.
--
-- >>> mapValidation (+10) (Error "message")
-- Error "message"
--
> > > mapValidation ( +10 ) ( Value 7 )
Value 17
--
prop > \x - > mapValidation i d x = = x
mapValidation :: (a -> b) -> Validation a -> Validation b
mapValidation _ (Error s) = Error s
mapValidation f (Value a) = Value (f a)
-- | Binds a function on a validation's value side to a new validation.
--
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Error " message " )
-- Error "message"
--
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Value 7 )
-- Error "odd"
--
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Value 8)
Value 18
--
-- prop> \x -> bindValidation Value x == x
bindValidation :: (a -> Validation b) -> Validation a -> Validation b
bindValidation _ (Error s) = Error s
bindValidation f (Value a) = f a
-- | Returns a validation's value side or the given default if it is an error.
--
> > > valueOr ( Error " message " ) 3
3
--
> > > valueOr ( Value 7 ) 3
7
--
prop > \x - > isValue x || valueOr x n = = n
valueOr :: Validation a -> a -> a
valueOr (Error _) a = a
valueOr (Value a) _ = a
-- | Returns a validation's error side or the given default if it is a value.
--
-- >>> errorOr (Error "message") "q"
-- "message"
--
> > > errorOr ( Value 7 ) " q "
-- "q"
--
prop > \x - > isError x || errorOr x e = = e
errorOr :: Validation a -> Err -> Err
errorOr (Error e) _ = e
errorOr (Value _) a = a
valueValidation :: a -> Validation a
valueValidation = Value
| null | https://raw.githubusercontent.com/system-f/fp-course/e929bc909a1701f67d218ed7974e9732d1e8dd32/src/Course/Validation.hs | haskell | $setup
>>> import Test.QuickCheck
| Returns whether or not the given validation is an error.
>>> isError (Error "message")
True
False
| Returns whether or not the given validation is a value.
>>> isValue (Error "message")
False
True
| Maps a function on a validation's value side.
>>> mapValidation (+10) (Error "message")
Error "message"
| Binds a function on a validation's value side to a new validation.
Error "message"
Error "odd"
prop> \x -> bindValidation Value x == x
| Returns a validation's value side or the given default if it is an error.
| Returns a validation's error side or the given default if it is a value.
>>> errorOr (Error "message") "q"
"message"
"q"
| # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module Course.Validation where
import qualified Prelude as P(String)
import Course.Core
> > > import qualified Prelude as P(fmap , either )
> > > instance Arbitrary a = > Arbitrary ( Validation a ) where arbitrary = ( P.either Error Value ) arbitrary
data Validation a = Error Err | Value a
deriving (Eq, Show)
type Err = P.String
> > > isError ( Value 7 )
prop > \x - > isError x /= isValue x
isError :: Validation a -> Bool
isError (Error _) = True
isError (Value _) = False
> > > isValue ( Value 7 )
prop > \x - > isValue x /= isError x
isValue :: Validation a -> Bool
isValue = not . isError
> > > mapValidation ( +10 ) ( Value 7 )
Value 17
prop > \x - > mapValidation i d x = = x
mapValidation :: (a -> b) -> Validation a -> Validation b
mapValidation _ (Error s) = Error s
mapValidation f (Value a) = Value (f a)
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Error " message " )
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Value 7 )
> > > ( \n - > if even n then Value ( n + 10 ) else Error " odd " ) ( Value 8)
Value 18
bindValidation :: (a -> Validation b) -> Validation a -> Validation b
bindValidation _ (Error s) = Error s
bindValidation f (Value a) = f a
> > > valueOr ( Error " message " ) 3
3
> > > valueOr ( Value 7 ) 3
7
prop > \x - > isValue x || valueOr x n = = n
valueOr :: Validation a -> a -> a
valueOr (Error _) a = a
valueOr (Value a) _ = a
> > > errorOr ( Value 7 ) " q "
prop > \x - > isError x || errorOr x e = = e
errorOr :: Validation a -> Err -> Err
errorOr (Error e) _ = e
errorOr (Value _) a = a
valueValidation :: a -> Validation a
valueValidation = Value
|
3480b6ebdac22e569a1421dcf62e173f534953284a80e9c5e3f747bbca6f2dc8 | k0dev/erlang-notes | killer.erl | -module(killer).
-export([start/0]).
start() -> spawn(fun() -> kill() end).
kill() ->
receive
stop -> io:format("the killer has been stopped~n");
{Pid, force} -> exit(Pid, kill),
kill();
Pid -> exit(Pid, "You have been killed"),
kill()
end.
Esempio di esecuzione :
%
% > c(killer).
% {ok,killer}
% > K = killer:start().
< 0.89.0 >
% > self().
< 0.82.0 >
> K ! < 0.82.0 > .
% ** exception exit: "You have been killed"
% > self().
% <0.92.0>
% > is_process_alive(K).
% true
%
% process_flag(trap_exit, true).
% false
% > K ! self().
% <0.92.0>
> receive { ' EXIT ' , Pid , Why } - > { Pid , Why } end .
{ < 0.89.0>,"You have been killed " }
Dopo trap_exit a true , killer
viene trasformato in un semplice messaggio inviato alla mailbox .
Dalla documentazione ufficiale scopriamo però che :
" If is the atom kill , that is , if exit(Pid , kill ) is called , an untrappable
exit signal is sent to the process that is identified by Pid , which unconditionally
% exits with exit reason killed"
Quindi esiste unstoppable , infatti :
% > c(killer).
% {ok,killer}
% > K = killer:start().
< 0.89.0 >
% > process_flag(trap_exit, true).
% false
% > K ! {self(), force}.
% ** exception exit: killed
| null | https://raw.githubusercontent.com/k0dev/erlang-notes/0c07941cc0182902e5386a58b513bb937e733e76/code/examples/concurrency/killer.erl | erlang |
> c(killer).
{ok,killer}
> K = killer:start().
> self().
** exception exit: "You have been killed"
> self().
<0.92.0>
> is_process_alive(K).
true
process_flag(trap_exit, true).
false
> K ! self().
<0.92.0>
exits with exit reason killed"
> c(killer).
{ok,killer}
> K = killer:start().
> process_flag(trap_exit, true).
false
> K ! {self(), force}.
** exception exit: killed | -module(killer).
-export([start/0]).
start() -> spawn(fun() -> kill() end).
kill() ->
receive
stop -> io:format("the killer has been stopped~n");
{Pid, force} -> exit(Pid, kill),
kill();
Pid -> exit(Pid, "You have been killed"),
kill()
end.
Esempio di esecuzione :
< 0.89.0 >
< 0.82.0 >
> K ! < 0.82.0 > .
> receive { ' EXIT ' , Pid , Why } - > { Pid , Why } end .
{ < 0.89.0>,"You have been killed " }
Dopo trap_exit a true , killer
viene trasformato in un semplice messaggio inviato alla mailbox .
Dalla documentazione ufficiale scopriamo però che :
" If is the atom kill , that is , if exit(Pid , kill ) is called , an untrappable
exit signal is sent to the process that is identified by Pid , which unconditionally
Quindi esiste unstoppable , infatti :
< 0.89.0 >
|
92fbfb92672939889769211392ba7e98899c265d05f28523b44dadf09f1ae250 | lspitzner/brittany | Test112.hs | foo = if True
then
-- iiiiii
"a "
else
"b "
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test112.hs | haskell | iiiiii | foo = if True
then
"a "
else
"b "
|
87531b044a9ebb508c76291b38db5557f5359ae2062569b8d266528e3ae05197 | clojure/core.typed.analyzer.jvm | infer_tag.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
;copied from tools.analyzer.jvm
; - changed :pass-info for `infer-tag`
; - use analyzer.env
(ns clojure.core.typed.analyzer.passes.jvm.infer-tag
(:require [clojure.tools.analyzer.utils :refer [arglist-for-arity]]
[clojure.tools.analyzer.jvm.utils :as u]
[clojure.core.typed.analyzer.env :as env]
[clojure.set :as set]
[clojure.tools.analyzer.passes.jvm.annotate-tag :as annotate-tag]
[clojure.tools.analyzer.passes.jvm.annotate-host-info :as annotate-host-info]
[clojure.core.typed.analyzer.passes.jvm.analyze-host-expr :as analyze-host-expr]
[clojure.core.typed.analyzer.passes.jvm.fix-case-test :as fix-case-test]))
(defmulti -infer-tag :op)
(defmethod -infer-tag :default [ast] ast)
(defmethod -infer-tag :binding
[{:keys [init atom] :as ast}]
(if init
(let [info (select-keys init [:return-tag :arglists])]
(swap! atom merge info)
(merge ast info))
ast))
(defmethod -infer-tag :local
[ast]
(let [atom @(:atom ast)]
(merge atom
ast
{:o-tag (:tag atom)})))
(defmethod -infer-tag :var
[{:keys [var form] :as ast}]
(let [{:keys [tag arglists]} (:meta ast)
arglists (if (= 'quote (first arglists))
(second arglists)
arglists)
form-tag (:tag (meta form))]
;;if (not dynamic)
(merge ast
{:o-tag Object}
(when-let [tag (or form-tag tag)]
(if (fn? @var)
{:tag clojure.lang.AFunction :return-tag tag}
{:tag tag}))
(when arglists
{:arglists arglists}))))
(defmethod -infer-tag :def
[{:keys [var init name] :as ast}]
(let [info (merge (select-keys init [:return-tag :arglists :tag])
(select-keys (meta name) [:tag :arglists]))]
(when (and (seq info)
(not (:dynamic (meta name)))
(= :global (-> (env/deref-env) :passes-opts :infer-tag/level)))
(alter-meta! var merge (set/rename-keys info {:return-tag :tag})))
(merge ast info {:tag clojure.lang.Var :o-tag clojure.lang.Var})))
(defmethod -infer-tag :quote
[ast]
(let [tag (-> ast :expr :tag)]
(assoc ast :tag tag :o-tag tag)))
(defmethod -infer-tag :new
[ast]
(let [t (-> ast :class :val)]
(assoc ast :o-tag t :tag t)))
(defmethod -infer-tag :with-meta
[{:keys [expr] :as ast}]
(merge ast (select-keys expr [:return-tag :arglists])
{:tag (or (:tag expr) Object) :o-tag Object})) ;;trying to be smart here
(defmethod -infer-tag :recur
[ast]
(assoc ast :ignore-tag true))
(defmethod -infer-tag :do
[{:keys [ret] :as ast}]
(merge ast (select-keys ret [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag ret)}))
(defmethod -infer-tag :let
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag body)}))
(defmethod -infer-tag :letfn
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag body)}))
(defmethod -infer-tag :loop
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists])
{:o-tag (:tag body)}
(let [tag (:tag body)]
(if (#{Void Void/TYPE} tag)
(assoc ast :tag Object)
(assoc ast :tag tag)))))
(defn =-arglists? [a1 a2]
(let [tag (fn [x] (-> x meta :tag u/maybe-class))]
(and (= a1 a2)
(every? true? (mapv (fn [a1 a2]
(and (= (tag a1) (tag a2))
(= (mapv tag a1)
(mapv tag a2))))
a1 a2)))))
(defmethod -infer-tag :if
[{:keys [then else] :as ast}]
(let [then-tag (:tag then)
else-tag (:tag else)
ignore-then? (:ignore-tag then)
ignore-else? (:ignore-tag else)]
(cond
(and then-tag
(or ignore-else? (= then-tag else-tag)))
(merge ast
{:tag then-tag :o-tag then-tag}
(when-let [return-tag (:return-tag then)]
(when (or ignore-else?
(= return-tag (:return-tag else)))
{:return-tag return-tag}))
(when-let [arglists (:arglists then)]
(when (or ignore-else?
(=-arglists? arglists (:arglists else)))
{:arglists arglists})))
(and else-tag ignore-then?)
(merge ast
{:tag else-tag :o-tag else-tag}
(when-let [return-tag (:return-tag else)]
{:return-tag return-tag})
(when-let [arglists (:arglists else)]
{:arglists arglists}))
(and (:ignore-tag then) (:ignore-tag else))
(assoc ast :ignore-tag true)
:else
ast)))
(defmethod -infer-tag :throw
[ast]
(assoc ast :ignore-tag true))
(defmethod -infer-tag :case
[{:keys [thens default] :as ast}]
(let [thens (conj (mapv :then thens) default)
exprs (seq (remove :ignore-tag thens))
tag (:tag (first exprs))]
(cond
(and tag
(every? #(= (:tag %) tag) exprs))
(merge ast
{:tag tag :o-tag tag}
(when-let [return-tag (:return-tag (first exprs))]
(when (every? #(= (:return-tag %) return-tag) exprs)
{:return-tag return-tag}))
(when-let [arglists (:arglists (first exprs))]
(when (every? #(=-arglists? (:arglists %) arglists) exprs)
{:arglists arglists})))
(every? :ignore-tag thens)
(assoc ast :ignore-tag true)
:else
ast)))
(defmethod -infer-tag :try
[{:keys [body catches] :as ast}]
(let [{:keys [tag return-tag arglists]} body
catches (remove :ignore-tag (mapv :body catches))]
(merge ast
(when (and tag (every? #(= % tag) (mapv :tag catches)))
{:tag tag :o-tag tag})
(when (and return-tag (every? #(= % return-tag) (mapv :return-tag catches)))
{:return-tag return-tag})
(when (and arglists (every? #(=-arglists? % arglists) (mapv :arglists catches)))
{:arglists arglists}))))
(defmethod -infer-tag :fn-method
[{:keys [form body params local] :as ast}]
(let [annotated-tag (or (:tag (meta (first form)))
(:tag (meta (:form local))))
body-tag (:tag body)
tag (or annotated-tag body-tag)
tag (if (#{Void Void/TYPE} tag)
Object
tag)]
(merge (if (not= tag body-tag)
(assoc-in ast [:body :tag] (u/maybe-class tag))
ast)
(when tag
{:tag tag
:o-tag tag})
{:arglist (with-meta (vec (mapcat (fn [{:keys [form variadic?]}]
(if variadic? ['& form] [form]))
params))
(when tag {:tag tag}))})))
(defmethod -infer-tag :fn
[{:keys [local methods] :as ast}]
(merge ast
{:arglists (seq (mapv :arglist methods))
:tag clojure.lang.AFunction
:o-tag clojure.lang.AFunction}
(when-let [tag (or (:tag (meta (:form local)))
(and (apply = (mapv :tag methods))
(:tag (first methods))))]
{:return-tag tag})))
(defmethod -infer-tag :invoke
[{:keys [fn args] :as ast}]
(if (:arglists fn)
(let [argc (count args)
arglist (arglist-for-arity fn argc)
tag (or (:tag (meta arglist))
(:return-tag fn)
(and (= :var (:op fn))
(:tag (:meta fn))))]
(merge ast
(when tag
{:tag tag
:o-tag tag})))
(if-let [tag (:return-tag fn)]
(assoc ast :tag tag :o-tag tag)
ast)))
(defmethod -infer-tag :method
[{:keys [form body params] :as ast}]
(let [tag (or (:tag (meta (first form)))
(:tag (meta (second form))))
body-tag (:tag body)]
(assoc ast :tag (or tag body-tag) :o-tag body-tag)))
(defmethod -infer-tag :reify
[{:keys [class-name] :as ast}]
(assoc ast :tag class-name :o-tag class-name))
(defmethod -infer-tag :set!
[ast]
(let [t (:tag (:target ast))]
(assoc ast :tag t :o-tag t)))
;;redefine passes mainly to move dependency on `uniquify-locals`
;; to `uniquify2/uniquify-locals`
(defn infer-tag
"Performs local type inference on the AST adds, when possible,
one or more of the following keys to the AST:
* :o-tag represents the current type of the
expression represented by the node
* :tag represents the type the expression represented by the
node is required to have, possibly the same as :o-tag
* :return-tag implies that the node will return a function whose
invocation will result in a object of this type
* :arglists implies that the node will return a function with
this arglists
* :ignore-tag true when the node is untyped, does not imply that
all untyped node will have this
Passes opts:
* :infer-tag/level If :global, infer-tag will perform Var tag
inference"
{:pass-info {:walk :post :depends #{#'annotate-tag/annotate-tag
#'annotate-host-info/annotate-host-info
;;replace
#'fix-case-test/fix-case-test
;;replace
#'analyze-host-expr/analyze-host-expr}
; trim is incompatible with core.typed
#_#_:after #{#'trim}}}
[{:keys [tag form] :as ast}]
(let [tag (or tag (:tag (meta form)))
ast (-infer-tag ast)]
(merge ast
(when tag
{:tag tag})
(when-let [o-tag (:o-tag ast)]
{:o-tag o-tag}))))
| null | https://raw.githubusercontent.com/clojure/core.typed.analyzer.jvm/7246adac3bb5565ae0a785f430a2121226e7d1cb/src/main/clojure/clojure/core/typed/analyzer/passes/jvm/infer_tag.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
copied from tools.analyzer.jvm
- changed :pass-info for `infer-tag`
- use analyzer.env
if (not dynamic)
trying to be smart here
redefine passes mainly to move dependency on `uniquify-locals`
to `uniquify2/uniquify-locals`
replace
replace
trim is incompatible with core.typed | Copyright ( c ) , contributors .
(ns clojure.core.typed.analyzer.passes.jvm.infer-tag
(:require [clojure.tools.analyzer.utils :refer [arglist-for-arity]]
[clojure.tools.analyzer.jvm.utils :as u]
[clojure.core.typed.analyzer.env :as env]
[clojure.set :as set]
[clojure.tools.analyzer.passes.jvm.annotate-tag :as annotate-tag]
[clojure.tools.analyzer.passes.jvm.annotate-host-info :as annotate-host-info]
[clojure.core.typed.analyzer.passes.jvm.analyze-host-expr :as analyze-host-expr]
[clojure.core.typed.analyzer.passes.jvm.fix-case-test :as fix-case-test]))
(defmulti -infer-tag :op)
(defmethod -infer-tag :default [ast] ast)
(defmethod -infer-tag :binding
[{:keys [init atom] :as ast}]
(if init
(let [info (select-keys init [:return-tag :arglists])]
(swap! atom merge info)
(merge ast info))
ast))
(defmethod -infer-tag :local
[ast]
(let [atom @(:atom ast)]
(merge atom
ast
{:o-tag (:tag atom)})))
(defmethod -infer-tag :var
[{:keys [var form] :as ast}]
(let [{:keys [tag arglists]} (:meta ast)
arglists (if (= 'quote (first arglists))
(second arglists)
arglists)
form-tag (:tag (meta form))]
(merge ast
{:o-tag Object}
(when-let [tag (or form-tag tag)]
(if (fn? @var)
{:tag clojure.lang.AFunction :return-tag tag}
{:tag tag}))
(when arglists
{:arglists arglists}))))
(defmethod -infer-tag :def
[{:keys [var init name] :as ast}]
(let [info (merge (select-keys init [:return-tag :arglists :tag])
(select-keys (meta name) [:tag :arglists]))]
(when (and (seq info)
(not (:dynamic (meta name)))
(= :global (-> (env/deref-env) :passes-opts :infer-tag/level)))
(alter-meta! var merge (set/rename-keys info {:return-tag :tag})))
(merge ast info {:tag clojure.lang.Var :o-tag clojure.lang.Var})))
(defmethod -infer-tag :quote
[ast]
(let [tag (-> ast :expr :tag)]
(assoc ast :tag tag :o-tag tag)))
(defmethod -infer-tag :new
[ast]
(let [t (-> ast :class :val)]
(assoc ast :o-tag t :tag t)))
(defmethod -infer-tag :with-meta
[{:keys [expr] :as ast}]
(merge ast (select-keys expr [:return-tag :arglists])
(defmethod -infer-tag :recur
[ast]
(assoc ast :ignore-tag true))
(defmethod -infer-tag :do
[{:keys [ret] :as ast}]
(merge ast (select-keys ret [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag ret)}))
(defmethod -infer-tag :let
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag body)}))
(defmethod -infer-tag :letfn
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists :ignore-tag :tag])
{:o-tag (:tag body)}))
(defmethod -infer-tag :loop
[{:keys [body] :as ast}]
(merge ast (select-keys body [:return-tag :arglists])
{:o-tag (:tag body)}
(let [tag (:tag body)]
(if (#{Void Void/TYPE} tag)
(assoc ast :tag Object)
(assoc ast :tag tag)))))
(defn =-arglists? [a1 a2]
(let [tag (fn [x] (-> x meta :tag u/maybe-class))]
(and (= a1 a2)
(every? true? (mapv (fn [a1 a2]
(and (= (tag a1) (tag a2))
(= (mapv tag a1)
(mapv tag a2))))
a1 a2)))))
(defmethod -infer-tag :if
[{:keys [then else] :as ast}]
(let [then-tag (:tag then)
else-tag (:tag else)
ignore-then? (:ignore-tag then)
ignore-else? (:ignore-tag else)]
(cond
(and then-tag
(or ignore-else? (= then-tag else-tag)))
(merge ast
{:tag then-tag :o-tag then-tag}
(when-let [return-tag (:return-tag then)]
(when (or ignore-else?
(= return-tag (:return-tag else)))
{:return-tag return-tag}))
(when-let [arglists (:arglists then)]
(when (or ignore-else?
(=-arglists? arglists (:arglists else)))
{:arglists arglists})))
(and else-tag ignore-then?)
(merge ast
{:tag else-tag :o-tag else-tag}
(when-let [return-tag (:return-tag else)]
{:return-tag return-tag})
(when-let [arglists (:arglists else)]
{:arglists arglists}))
(and (:ignore-tag then) (:ignore-tag else))
(assoc ast :ignore-tag true)
:else
ast)))
(defmethod -infer-tag :throw
[ast]
(assoc ast :ignore-tag true))
(defmethod -infer-tag :case
[{:keys [thens default] :as ast}]
(let [thens (conj (mapv :then thens) default)
exprs (seq (remove :ignore-tag thens))
tag (:tag (first exprs))]
(cond
(and tag
(every? #(= (:tag %) tag) exprs))
(merge ast
{:tag tag :o-tag tag}
(when-let [return-tag (:return-tag (first exprs))]
(when (every? #(= (:return-tag %) return-tag) exprs)
{:return-tag return-tag}))
(when-let [arglists (:arglists (first exprs))]
(when (every? #(=-arglists? (:arglists %) arglists) exprs)
{:arglists arglists})))
(every? :ignore-tag thens)
(assoc ast :ignore-tag true)
:else
ast)))
(defmethod -infer-tag :try
[{:keys [body catches] :as ast}]
(let [{:keys [tag return-tag arglists]} body
catches (remove :ignore-tag (mapv :body catches))]
(merge ast
(when (and tag (every? #(= % tag) (mapv :tag catches)))
{:tag tag :o-tag tag})
(when (and return-tag (every? #(= % return-tag) (mapv :return-tag catches)))
{:return-tag return-tag})
(when (and arglists (every? #(=-arglists? % arglists) (mapv :arglists catches)))
{:arglists arglists}))))
(defmethod -infer-tag :fn-method
[{:keys [form body params local] :as ast}]
(let [annotated-tag (or (:tag (meta (first form)))
(:tag (meta (:form local))))
body-tag (:tag body)
tag (or annotated-tag body-tag)
tag (if (#{Void Void/TYPE} tag)
Object
tag)]
(merge (if (not= tag body-tag)
(assoc-in ast [:body :tag] (u/maybe-class tag))
ast)
(when tag
{:tag tag
:o-tag tag})
{:arglist (with-meta (vec (mapcat (fn [{:keys [form variadic?]}]
(if variadic? ['& form] [form]))
params))
(when tag {:tag tag}))})))
(defmethod -infer-tag :fn
[{:keys [local methods] :as ast}]
(merge ast
{:arglists (seq (mapv :arglist methods))
:tag clojure.lang.AFunction
:o-tag clojure.lang.AFunction}
(when-let [tag (or (:tag (meta (:form local)))
(and (apply = (mapv :tag methods))
(:tag (first methods))))]
{:return-tag tag})))
(defmethod -infer-tag :invoke
[{:keys [fn args] :as ast}]
(if (:arglists fn)
(let [argc (count args)
arglist (arglist-for-arity fn argc)
tag (or (:tag (meta arglist))
(:return-tag fn)
(and (= :var (:op fn))
(:tag (:meta fn))))]
(merge ast
(when tag
{:tag tag
:o-tag tag})))
(if-let [tag (:return-tag fn)]
(assoc ast :tag tag :o-tag tag)
ast)))
(defmethod -infer-tag :method
[{:keys [form body params] :as ast}]
(let [tag (or (:tag (meta (first form)))
(:tag (meta (second form))))
body-tag (:tag body)]
(assoc ast :tag (or tag body-tag) :o-tag body-tag)))
(defmethod -infer-tag :reify
[{:keys [class-name] :as ast}]
(assoc ast :tag class-name :o-tag class-name))
(defmethod -infer-tag :set!
[ast]
(let [t (:tag (:target ast))]
(assoc ast :tag t :o-tag t)))
(defn infer-tag
"Performs local type inference on the AST adds, when possible,
one or more of the following keys to the AST:
* :o-tag represents the current type of the
expression represented by the node
* :tag represents the type the expression represented by the
node is required to have, possibly the same as :o-tag
* :return-tag implies that the node will return a function whose
invocation will result in a object of this type
* :arglists implies that the node will return a function with
this arglists
* :ignore-tag true when the node is untyped, does not imply that
all untyped node will have this
Passes opts:
* :infer-tag/level If :global, infer-tag will perform Var tag
inference"
{:pass-info {:walk :post :depends #{#'annotate-tag/annotate-tag
#'annotate-host-info/annotate-host-info
#'fix-case-test/fix-case-test
#'analyze-host-expr/analyze-host-expr}
#_#_:after #{#'trim}}}
[{:keys [tag form] :as ast}]
(let [tag (or tag (:tag (meta form)))
ast (-infer-tag ast)]
(merge ast
(when tag
{:tag tag})
(when-let [o-tag (:o-tag ast)]
{:o-tag o-tag}))))
|
42f6fe7024e5a13ef461eb9913ff5bd7630b8c317688efb3cafcf894b968adcb | inhabitedtype/ocaml-aws | restoreDBInstanceFromS3.mli | open Types
type input = RestoreDBInstanceFromS3Message.t
type output = RestoreDBInstanceFromS3Result.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/restoreDBInstanceFromS3.mli | ocaml | open Types
type input = RestoreDBInstanceFromS3Message.t
type output = RestoreDBInstanceFromS3Result.t
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
|
|
0f8d19fbedf1806596e805e618e77c2676086480dcecbbf2a2c625836d1f7a51 | schell/gelatin | GLFW.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
module Gelatin.GLFW (
Rez(..),
-- * Startup
startupGLFWBackend,
newWindow,
-- * Rendering
renderWithGLFW,
updateWindowGLFW,
-- * Re-exports
module GL,
module GLFW
) where
import Gelatin.GL as GL
import Control.Monad
import Control.Arrow (second)
import Data.Hashable
import Data.Bits ((.|.))
import Graphics.UI.GLFW as GLFW
import Linear hiding (rotate)
import System.Exit
import System.IO
import GHC.Generics
-- | Creates a window. This can only be called after initializing with
` initGelatin ` .
newWindow :: Int -- ^ Width
-> Int -- ^ Height
-> String -- ^ Title
-> Maybe Monitor -- ^ The monitor to fullscreen into.
-> Maybe Window -- ^ A window to share OpenGL contexts with.
-> IO Window
newWindow ww wh ws mmon mwin = do
defaultWindowHints
windowHint $ WindowHint'OpenGLDebugContext True
windowHint $ WindowHint'OpenGLProfile OpenGLProfile'Core
windowHint $ WindowHint'OpenGLForwardCompat True
windowHint $ WindowHint'ContextVersionMajor 3
windowHint $ WindowHint'ContextVersionMinor 3
windowHint $ WindowHint'DepthBits 16
mwin' <- createWindow ww wh ws mmon mwin
makeContextCurrent mwin'
case mwin' of
Nothing -> do putStrLn "could not create window"
exitFailure
Just win -> return win
calculateDpi :: Window -> IO Int
calculateDpi win = do
mMonitor <- getPrimaryMonitor
-- Calculate the dpi of the primary monitor.
case mMonitor of
I 've choosen 128 as the default DPI because of my macbook 15 "
-- -Schell
Nothing -> return 128
Just m -> do (w, h) <- getMonitorPhysicalSize m
mvmode <- getVideoMode m
case mvmode of
Nothing -> return 128
Just (VideoMode vw vh _ _ _ _) -> do
let mm2 = fromIntegral $ w*h :: Double
px = sqrt $ (fromIntegral vw :: Double)
* fromIntegral vh
inches = sqrt $ mm2 / (25.4 * 25.4)
let dpi = floor $ px / inches
return dpi
-- | Completes all initialization, creates a new window and returns
-- the resource record and the new window. If any part of the process fails the
-- program will exit with failure.
startupGLFWBackend :: Int -- ^ Window width
-> Int -- ^ Window height
-> String -- ^ Window title
-> Maybe Monitor -- ^ The monitor to fullscreen into
-> Maybe Window -- ^ A window to share OpenGL contexts with
-> IO (Rez, Window)
startupGLFWBackend ww wh ws mmon mwin = do
setErrorCallback $ Just $ \_ -> hPutStrLn stderr
initd <- GLFW.init
unless initd $ do putStrLn "could not initialize glfw"
exitFailure
w <- newWindow ww wh ws mmon mwin
sh <- loadSumShader
glEnable GL_BLEND
glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
let ctx = Context { ctxFramebufferSize = getFramebufferSize w
, ctxWindowSize = getWindowSize w
, ctxScreenDpi = calculateDpi w
}
return (Rez sh ctx, w)
updateWindowGLFW :: Window -> IO ()
updateWindowGLFW = swapBuffers
renderWithGLFW :: Window -> Rez -> Cache IO PictureTransform
-> Picture GLuint () -> IO (Cache IO PictureTransform)
renderWithGLFW window rez cache pic = do
clearFrame rez
(r, newCache) <- compilePictureRenderer rez cache pic
snd r mempty
updateWindowGLFW window
cleanPictureRendererCache newCache pic
| null | https://raw.githubusercontent.com/schell/gelatin/04c1c83d4297eac4f4cc5e8e5c805b1600b3ee98/gelatin-glfw/src/Gelatin/GLFW.hs | haskell | * Startup
* Rendering
* Re-exports
| Creates a window. This can only be called after initializing with
^ Width
^ Height
^ Title
^ The monitor to fullscreen into.
^ A window to share OpenGL contexts with.
Calculate the dpi of the primary monitor.
-Schell
| Completes all initialization, creates a new window and returns
the resource record and the new window. If any part of the process fails the
program will exit with failure.
^ Window width
^ Window height
^ Window title
^ The monitor to fullscreen into
^ A window to share OpenGL contexts with | # LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
module Gelatin.GLFW (
Rez(..),
startupGLFWBackend,
newWindow,
renderWithGLFW,
updateWindowGLFW,
module GL,
module GLFW
) where
import Gelatin.GL as GL
import Control.Monad
import Control.Arrow (second)
import Data.Hashable
import Data.Bits ((.|.))
import Graphics.UI.GLFW as GLFW
import Linear hiding (rotate)
import System.Exit
import System.IO
import GHC.Generics
` initGelatin ` .
-> IO Window
newWindow ww wh ws mmon mwin = do
defaultWindowHints
windowHint $ WindowHint'OpenGLDebugContext True
windowHint $ WindowHint'OpenGLProfile OpenGLProfile'Core
windowHint $ WindowHint'OpenGLForwardCompat True
windowHint $ WindowHint'ContextVersionMajor 3
windowHint $ WindowHint'ContextVersionMinor 3
windowHint $ WindowHint'DepthBits 16
mwin' <- createWindow ww wh ws mmon mwin
makeContextCurrent mwin'
case mwin' of
Nothing -> do putStrLn "could not create window"
exitFailure
Just win -> return win
calculateDpi :: Window -> IO Int
calculateDpi win = do
mMonitor <- getPrimaryMonitor
case mMonitor of
I 've choosen 128 as the default DPI because of my macbook 15 "
Nothing -> return 128
Just m -> do (w, h) <- getMonitorPhysicalSize m
mvmode <- getVideoMode m
case mvmode of
Nothing -> return 128
Just (VideoMode vw vh _ _ _ _) -> do
let mm2 = fromIntegral $ w*h :: Double
px = sqrt $ (fromIntegral vw :: Double)
* fromIntegral vh
inches = sqrt $ mm2 / (25.4 * 25.4)
let dpi = floor $ px / inches
return dpi
-> IO (Rez, Window)
startupGLFWBackend ww wh ws mmon mwin = do
setErrorCallback $ Just $ \_ -> hPutStrLn stderr
initd <- GLFW.init
unless initd $ do putStrLn "could not initialize glfw"
exitFailure
w <- newWindow ww wh ws mmon mwin
sh <- loadSumShader
glEnable GL_BLEND
glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
let ctx = Context { ctxFramebufferSize = getFramebufferSize w
, ctxWindowSize = getWindowSize w
, ctxScreenDpi = calculateDpi w
}
return (Rez sh ctx, w)
updateWindowGLFW :: Window -> IO ()
updateWindowGLFW = swapBuffers
renderWithGLFW :: Window -> Rez -> Cache IO PictureTransform
-> Picture GLuint () -> IO (Cache IO PictureTransform)
renderWithGLFW window rez cache pic = do
clearFrame rez
(r, newCache) <- compilePictureRenderer rez cache pic
snd r mempty
updateWindowGLFW window
cleanPictureRendererCache newCache pic
|
2d25c252a8ca69724c992c6c18ed6718fb99cc89e03f2d7325b1a5fb9d7b8f19 | slegrand45/examples_ocsigen | types.ml | type horiz_position = Left | Middle | Right
type vert_position = Top | Center | Bottom
type diag_position = Left_top_right_bottom | Right_top_left_bottom
type cell_position = horiz_position * vert_position
type player = Player_x | Player_o
type cell_state = Played of player | Empty
type cell = { pos : cell_position; state : cell_state }
type game_board = { cells : cell list }
type player_x_pos = Player_x_pos of cell_position
type player_o_pos = Player_o_pos of cell_position
type valid_moves_for_player_x = player_x_pos list
type valid_moves_for_player_o = player_o_pos list
type game_state =
Player_x_to_move of game_board * valid_moves_for_player_x
| Player_o_to_move of game_board * valid_moves_for_player_o
| Game_won of game_board * player
| Game_tied of game_board
type rs = game_state React.signal
type rf = ?step:React.step -> game_state -> unit
type rp = rs * rf
| null | https://raw.githubusercontent.com/slegrand45/examples_ocsigen/e2f5efe57caf7a644795ac6b14f6d6e04168e4be/jsoo/tic-tac-toe/types.ml | ocaml | type horiz_position = Left | Middle | Right
type vert_position = Top | Center | Bottom
type diag_position = Left_top_right_bottom | Right_top_left_bottom
type cell_position = horiz_position * vert_position
type player = Player_x | Player_o
type cell_state = Played of player | Empty
type cell = { pos : cell_position; state : cell_state }
type game_board = { cells : cell list }
type player_x_pos = Player_x_pos of cell_position
type player_o_pos = Player_o_pos of cell_position
type valid_moves_for_player_x = player_x_pos list
type valid_moves_for_player_o = player_o_pos list
type game_state =
Player_x_to_move of game_board * valid_moves_for_player_x
| Player_o_to_move of game_board * valid_moves_for_player_o
| Game_won of game_board * player
| Game_tied of game_board
type rs = game_state React.signal
type rf = ?step:React.step -> game_state -> unit
type rp = rs * rf
|
|
fd566340fbb96dfb53429c3551d8b6d3db66b22fe1c396c688befae8a9c9ef19 | jacius/lispbuilder | fps.lisp |
(in-package #:lispbuilder-sdl)
(defgeneric (setf target-frame-rate) (rate fpsmngr)
(:documentation "Set the target frame rate for the game loop.
RATE > 0 will lock the game loop to the specified frame rate, and
calculate the average frame rate over a number of frames.
RATE = 0 will unlock the frame rate, and calculate the average
frame rate over a number of frames.
RATE < 0 will unlock the frame rate. The average frane rate is
not calculated"))
(defgeneric process-timestep (fpsmngr fn)
(:documentation "Manages the timestep. Called once per game loop."))
(defclass fps-manager ()
((world :accessor world :initform 1000)
(index :accessor index :initform 0)
(window :accessor average-window :initform nil)
(not-through-p :accessor not-through-p :initform nil)
( calculated : accessor average - fps : initform 0 )
(current-ticks :accessor current-ticks :initform (sdl-cffi::sdl-get-ticks))
(last-ticks :accessor last-ticks :initform (sdl-cffi::sdl-get-ticks))
(delta-ticks :accessor delta-ticks :initform 0))
(:default-initargs
:window 60))
(defclass fps-fixed (fps-manager)
((target-frame-rate :reader target-frame-rate)
(frame-count :accessor frame-count :initform 0 :initarg :frame-count)
(rate-ticks :accessor rate-ticks)
(delay-ticks :accessor delay-ticks :initform (sdl-cffi::sdl-get-ticks))
(upper-limit :accessor upper-limit :initform 1000 :initarg :upper-limit)
(lower-limit :accessor lower-limit :initform 1 :initarg :lower-limit)
(max-dt :initform 500 :initarg :max-dt))
(:default-initargs
:target-frame-rate 30))
(defclass fps-timestep (fps-manager)
((fps-ticks
:accessor fps-ticks
:type integer
:initform 0
:initarg :time)
(dt
:reader _dt_
:initform 10
:initarg :dt)
(max-dt
:initform 100
:initarg :max-dt)
(accumulator
:accessor accumulator
:type integer
:initform 0
:initarg :accumulator)))
(defclass fps-mixed (fps-timestep fps-fixed)
((fps-ticks
:accessor fps-ticks
:type integer
:initform 0
:initarg :time)
(dt
:reader _dt_
:initform 10
:initarg :dt)
(max-dt
:initform 100
:initarg :max-dt)
(accumulator
:accessor accumulator
:type integer
:initform 0
:initarg :accumulator)))
(defclass fps-unlocked (fps-timestep)
((physics-hook-function
:accessor ps-fn
:initform #'(lambda (fps-time dt)
(declare (ignorable fps-time dt))
nil)
:initarg :ps-fn)))
(defmethod initialize-instance :after ((self fps-manager)
&key
window
&allow-other-keys)
(when window
(setf (average-window self) (make-array window :initial-element 0))))
(defmethod initialize-instance :after ((self fps-fixed)
&key
target-frame-rate
&allow-other-keys)
(when target-frame-rate
(setf (target-frame-rate self) target-frame-rate)))
(defgeneric _average-fps_ (fps-manager))
(defmethod _average-fps_ ((self fps-manager))
(with-slots (not-through-p) self
(if not-through-p
not-through-p
(let ((window-length (1- (length (average-window self)))))
(loop :repeat window-length
:with window = (average-window self)
:with index = (index self)
:with i-start = (if (< index window-length) (1+ index) 0)
:with j-start = (if (< i-start window-length) (1+ i-start) 0)
:for i = i-start :then (if (< i window-length) (1+ i) 0)
:for j = j-start :then (if (< j window-length) (1+ j) 0)
:summing (- (svref window j)
(svref window i)) :into total
:finally (return (/ 1000 (/ total window-length))))))))
(defun calculate-time-scale (fps-manager delta-ticks)
(/ delta-ticks (world fps-manager)))
(defmethod _dt_ ((self fps-fixed))
(calculate-time-scale self (delta-ticks self)))
(defmethod (setf target-frame-rate) :around (rate (self fps-fixed))
(with-slots (target-frame-rate) self
(if (and (numberp rate) (zerop rate))
Zero is the same as NIL
(setf target-frame-rate nil)
(setf target-frame-rate rate))
(setf (not-through-p self) target-frame-rate)
(call-next-method)
target-frame-rate))
(defmethod (setf target-frame-rate) (rate (self fps-fixed))
(declare (ignorable rate))
(with-slots (target-frame-rate) self
(if (numberp target-frame-rate)
(when (and (>= target-frame-rate (lower-limit self))
(<= target-frame-rate (upper-limit self)))
(setf (frame-count self) 0
(rate-ticks self) (truncate (/ 1000 target-frame-rate)))))))
(defmethod (setf target-frame-rate) (rate (self fps-timestep))
(declare (ignorable rate self))
nil)
(defmethod (setf target-frame-rate) (rate (self fps-mixed))
(declare (ignorable rate))
(with-slots (target-frame-rate) self
(if (numberp target-frame-rate)
(when (and (>= target-frame-rate (lower-limit self))
(<= target-frame-rate (upper-limit self)))
(setf (frame-count self) 0
(rate-ticks self) (truncate (/ 1000 target-frame-rate)))))))
(defmethod process-timestep :around ((self fps-manager) fn)
(declare (ignorable fn))
(with-slots (current-ticks delta-ticks last-ticks index window not-through-p)
self
(setf current-ticks (sdl-cffi::sdl-get-ticks)
delta-ticks (- current-ticks last-ticks))
(setf (svref window index) current-ticks)
(when not-through-p
(when (>= index (1- (length window)))
(setf not-through-p nil)))
(call-next-method)
(unless (< (incf index) (length window))
(setf index 0))
(setf last-ticks current-ticks)))
(defmethod process-timestep ((self fps-manager) fn)
(when fn (funcall fn)))
;;;; --------------------------
;;;; Lock the game loop to a specified rate
;;;; This is a reimplementation of the algorithm for SDL_gfx
;;;; From /
(defmethod process-timestep :after ((self fps-fixed) fn)
(declare (ignorable fn))
(with-slots (target-frame-rate frame-count rate-ticks current-ticks delay-ticks
max-dt) self
;; Delay game loop, if necessary
(when target-frame-rate
(incf frame-count)
(let ((delta (truncate (- (+ delay-ticks (* frame-count rate-ticks))
current-ticks))))
(if (> delta 0)
(sdl-cffi::sdl-delay (if (> delta max-dt) max-dt delta))
(setf frame-count 0
delay-ticks current-ticks))))))
;;;; --------------------------
;;;; Lock timestep to Specified Rate
;;;; From -physics/fix-your-timestep/
(defmethod process-timestep :before ((self fps-unlocked) fn)
(declare (ignorable fn))
(with-slots (fps-ticks delta-ticks dt max-dt accumulator physics-hook-function)
self
(incf accumulator (if (> delta-ticks max-dt) max-dt delta-ticks))
(loop until (< accumulator dt) do
(progn
(when physics-hook-function
(funcall physics-hook-function fps-ticks dt))
(incf fps-ticks dt)
(decf accumulator dt)))))
(defun (setf frame-rate) (rate &optional (fpsmanager *default-fpsmanager*))
(setf (target-frame-rate fpsmanager) rate))
( defun ( setf frame - rate ) ( rate & optional fpsmanager )
( setf ( target - frame - rate * default - fpsmanager * ) rate ) )
(defun frame-rate (&optional (fpsmanager *default-fpsmanager*))
"Manage the target frame rate for the game loop.
`RATE` > `0` will lock the game loop to the specified frame rate, and
calculate the average frame rate over a number of frames.
`RATE` = `0` will unlock the frame rate, and calculate the average
frame rate over a number of frames.
`RATE` < `0` will unlock the frame rate. The average frane rate is
not calculated.
See [WITH-EVENTS](#with-events), and [AVERAGE-FPS](#average-fps)."
(target-frame-rate fpsmanager))
(defun time-scale (&optional (fpsmanager *default-fpsmanager*))
(calculate-time-scale fpsmanager (delta-ticks fpsmanager)))
(defun frame-time (&optional (fpsmanager *default-fpsmanager*))
"Returns how long current frame time is"
(calculate-time-scale fpsmanager (delta-ticks fpsmanager)))
(defun average-fps (&optional (fpsmanager *default-fpsmanager*))
"Returns the average frame rate of the event loop calculated over a sliding window
of 'n' frames."
(_average-fps_ fpsmanager))
(defun dt (&optional (fpsmanager *default-fpsmanager*))
(_dt_ fpsmanager))
(defun max-dt (&optional (fpsmanager *default-fpsmanager*))
(slot-value fpsmanager 'max-dt))
(defun ticks (&optional (fpsmanager *default-fpsmanager*))
(fps-ticks fpsmanager))
(defun physics-hook-p (&optional (fpsmanager *default-fpsmanager*))
(ps-fn fpsmanager))
(defun set-physics-hook (fn &optional (fpsmanager *default-fpsmanager*))
(setf (ps-fn fpsmanager) fn))
(defsetf physics-hook-p set-physics-hook)
(defun system-ticks ()
(sdl-cffi::sdl-get-ticks))
;;;; --------------------------
;;;; Lock timestep to Specified Rate
;;;; From -physics/fix-your-timestep/
(defmacro with-timestep (&body body)
`(progn
(incf (accumulator *default-fpsmanager*) (if (> (delta-ticks *default-fpsmanager*)
(max-dt *default-fpsmanager*))
(max-dt *default-fpsmanager*)
(delta-ticks *default-fpsmanager*)))
(loop until (< (accumulator *default-fpsmanager*) (dt *default-fpsmanager*)) do
(progn
,@body
(incf (fps-ticks *default-fpsmanager*) (dt *default-fpsmanager*))
(decf (accumulator *default-fpsmanager*) (dt *default-fpsmanager*))))))
(defmacro with-frame-rate (&body body)
;;
;; around
(let ((self (gensym "self-"))
(delta (gensym "delta-")))
`(let ((,self *default-fpsmanager*)
(,delta nil))
(setf (current-ticks ,self) (sdl-cffi::sdl-get-ticks)
(delta-ticks ,self) (- (current-ticks ,self) (last-ticks ,self)))
(setf (svref (average-window ,self) (index ,self)) (current-ticks ,self))
(when (not-through-p ,self)
(when (>= (index ,self) (1- (length (average-window ,self))))
(setf (not-through-p ,self) nil)))
;; call-next-method
,@body
;;
;; after
(when (target-frame-rate ,self)
(incf (frame-count ,self))
(let ((,delta (truncate (- (+ (delay-ticks ,self) (* (frame-count ,self)
(rate-ticks ,self)))
(current-ticks ,self)))))
(if (> ,delta 0)
(sdl-cffi::sdl-delay (if (> ,delta (max-dt ,self))
(max-dt ,self)
,delta))
(setf (frame-count ,self) 0
(delay-ticks ,self) (current-ticks ,self)))))
;;
;; around
(unless (< (incf (index ,self)) (length (average-window ,self)))
(setf (index ,self) 0))
(setf (last-ticks ,self) (current-ticks ,self)))))
| null | https://raw.githubusercontent.com/jacius/lispbuilder/e693651b95f6818e3cab70f0074af9f9511584c3/lispbuilder-sdl/sdl/fps.lisp | lisp | --------------------------
Lock the game loop to a specified rate
This is a reimplementation of the algorithm for SDL_gfx
From /
Delay game loop, if necessary
--------------------------
Lock timestep to Specified Rate
From -physics/fix-your-timestep/
--------------------------
Lock timestep to Specified Rate
From -physics/fix-your-timestep/
around
call-next-method
after
around |
(in-package #:lispbuilder-sdl)
(defgeneric (setf target-frame-rate) (rate fpsmngr)
(:documentation "Set the target frame rate for the game loop.
RATE > 0 will lock the game loop to the specified frame rate, and
calculate the average frame rate over a number of frames.
RATE = 0 will unlock the frame rate, and calculate the average
frame rate over a number of frames.
RATE < 0 will unlock the frame rate. The average frane rate is
not calculated"))
(defgeneric process-timestep (fpsmngr fn)
(:documentation "Manages the timestep. Called once per game loop."))
(defclass fps-manager ()
((world :accessor world :initform 1000)
(index :accessor index :initform 0)
(window :accessor average-window :initform nil)
(not-through-p :accessor not-through-p :initform nil)
( calculated : accessor average - fps : initform 0 )
(current-ticks :accessor current-ticks :initform (sdl-cffi::sdl-get-ticks))
(last-ticks :accessor last-ticks :initform (sdl-cffi::sdl-get-ticks))
(delta-ticks :accessor delta-ticks :initform 0))
(:default-initargs
:window 60))
(defclass fps-fixed (fps-manager)
((target-frame-rate :reader target-frame-rate)
(frame-count :accessor frame-count :initform 0 :initarg :frame-count)
(rate-ticks :accessor rate-ticks)
(delay-ticks :accessor delay-ticks :initform (sdl-cffi::sdl-get-ticks))
(upper-limit :accessor upper-limit :initform 1000 :initarg :upper-limit)
(lower-limit :accessor lower-limit :initform 1 :initarg :lower-limit)
(max-dt :initform 500 :initarg :max-dt))
(:default-initargs
:target-frame-rate 30))
(defclass fps-timestep (fps-manager)
((fps-ticks
:accessor fps-ticks
:type integer
:initform 0
:initarg :time)
(dt
:reader _dt_
:initform 10
:initarg :dt)
(max-dt
:initform 100
:initarg :max-dt)
(accumulator
:accessor accumulator
:type integer
:initform 0
:initarg :accumulator)))
(defclass fps-mixed (fps-timestep fps-fixed)
((fps-ticks
:accessor fps-ticks
:type integer
:initform 0
:initarg :time)
(dt
:reader _dt_
:initform 10
:initarg :dt)
(max-dt
:initform 100
:initarg :max-dt)
(accumulator
:accessor accumulator
:type integer
:initform 0
:initarg :accumulator)))
(defclass fps-unlocked (fps-timestep)
((physics-hook-function
:accessor ps-fn
:initform #'(lambda (fps-time dt)
(declare (ignorable fps-time dt))
nil)
:initarg :ps-fn)))
(defmethod initialize-instance :after ((self fps-manager)
&key
window
&allow-other-keys)
(when window
(setf (average-window self) (make-array window :initial-element 0))))
(defmethod initialize-instance :after ((self fps-fixed)
&key
target-frame-rate
&allow-other-keys)
(when target-frame-rate
(setf (target-frame-rate self) target-frame-rate)))
(defgeneric _average-fps_ (fps-manager))
(defmethod _average-fps_ ((self fps-manager))
(with-slots (not-through-p) self
(if not-through-p
not-through-p
(let ((window-length (1- (length (average-window self)))))
(loop :repeat window-length
:with window = (average-window self)
:with index = (index self)
:with i-start = (if (< index window-length) (1+ index) 0)
:with j-start = (if (< i-start window-length) (1+ i-start) 0)
:for i = i-start :then (if (< i window-length) (1+ i) 0)
:for j = j-start :then (if (< j window-length) (1+ j) 0)
:summing (- (svref window j)
(svref window i)) :into total
:finally (return (/ 1000 (/ total window-length))))))))
(defun calculate-time-scale (fps-manager delta-ticks)
(/ delta-ticks (world fps-manager)))
(defmethod _dt_ ((self fps-fixed))
(calculate-time-scale self (delta-ticks self)))
(defmethod (setf target-frame-rate) :around (rate (self fps-fixed))
(with-slots (target-frame-rate) self
(if (and (numberp rate) (zerop rate))
Zero is the same as NIL
(setf target-frame-rate nil)
(setf target-frame-rate rate))
(setf (not-through-p self) target-frame-rate)
(call-next-method)
target-frame-rate))
(defmethod (setf target-frame-rate) (rate (self fps-fixed))
(declare (ignorable rate))
(with-slots (target-frame-rate) self
(if (numberp target-frame-rate)
(when (and (>= target-frame-rate (lower-limit self))
(<= target-frame-rate (upper-limit self)))
(setf (frame-count self) 0
(rate-ticks self) (truncate (/ 1000 target-frame-rate)))))))
(defmethod (setf target-frame-rate) (rate (self fps-timestep))
(declare (ignorable rate self))
nil)
(defmethod (setf target-frame-rate) (rate (self fps-mixed))
(declare (ignorable rate))
(with-slots (target-frame-rate) self
(if (numberp target-frame-rate)
(when (and (>= target-frame-rate (lower-limit self))
(<= target-frame-rate (upper-limit self)))
(setf (frame-count self) 0
(rate-ticks self) (truncate (/ 1000 target-frame-rate)))))))
(defmethod process-timestep :around ((self fps-manager) fn)
(declare (ignorable fn))
(with-slots (current-ticks delta-ticks last-ticks index window not-through-p)
self
(setf current-ticks (sdl-cffi::sdl-get-ticks)
delta-ticks (- current-ticks last-ticks))
(setf (svref window index) current-ticks)
(when not-through-p
(when (>= index (1- (length window)))
(setf not-through-p nil)))
(call-next-method)
(unless (< (incf index) (length window))
(setf index 0))
(setf last-ticks current-ticks)))
(defmethod process-timestep ((self fps-manager) fn)
(when fn (funcall fn)))
(defmethod process-timestep :after ((self fps-fixed) fn)
(declare (ignorable fn))
(with-slots (target-frame-rate frame-count rate-ticks current-ticks delay-ticks
max-dt) self
(when target-frame-rate
(incf frame-count)
(let ((delta (truncate (- (+ delay-ticks (* frame-count rate-ticks))
current-ticks))))
(if (> delta 0)
(sdl-cffi::sdl-delay (if (> delta max-dt) max-dt delta))
(setf frame-count 0
delay-ticks current-ticks))))))
(defmethod process-timestep :before ((self fps-unlocked) fn)
(declare (ignorable fn))
(with-slots (fps-ticks delta-ticks dt max-dt accumulator physics-hook-function)
self
(incf accumulator (if (> delta-ticks max-dt) max-dt delta-ticks))
(loop until (< accumulator dt) do
(progn
(when physics-hook-function
(funcall physics-hook-function fps-ticks dt))
(incf fps-ticks dt)
(decf accumulator dt)))))
(defun (setf frame-rate) (rate &optional (fpsmanager *default-fpsmanager*))
(setf (target-frame-rate fpsmanager) rate))
( defun ( setf frame - rate ) ( rate & optional fpsmanager )
( setf ( target - frame - rate * default - fpsmanager * ) rate ) )
(defun frame-rate (&optional (fpsmanager *default-fpsmanager*))
"Manage the target frame rate for the game loop.
`RATE` > `0` will lock the game loop to the specified frame rate, and
calculate the average frame rate over a number of frames.
`RATE` = `0` will unlock the frame rate, and calculate the average
frame rate over a number of frames.
`RATE` < `0` will unlock the frame rate. The average frane rate is
not calculated.
See [WITH-EVENTS](#with-events), and [AVERAGE-FPS](#average-fps)."
(target-frame-rate fpsmanager))
(defun time-scale (&optional (fpsmanager *default-fpsmanager*))
(calculate-time-scale fpsmanager (delta-ticks fpsmanager)))
(defun frame-time (&optional (fpsmanager *default-fpsmanager*))
"Returns how long current frame time is"
(calculate-time-scale fpsmanager (delta-ticks fpsmanager)))
(defun average-fps (&optional (fpsmanager *default-fpsmanager*))
"Returns the average frame rate of the event loop calculated over a sliding window
of 'n' frames."
(_average-fps_ fpsmanager))
(defun dt (&optional (fpsmanager *default-fpsmanager*))
(_dt_ fpsmanager))
(defun max-dt (&optional (fpsmanager *default-fpsmanager*))
(slot-value fpsmanager 'max-dt))
(defun ticks (&optional (fpsmanager *default-fpsmanager*))
(fps-ticks fpsmanager))
(defun physics-hook-p (&optional (fpsmanager *default-fpsmanager*))
(ps-fn fpsmanager))
(defun set-physics-hook (fn &optional (fpsmanager *default-fpsmanager*))
(setf (ps-fn fpsmanager) fn))
(defsetf physics-hook-p set-physics-hook)
(defun system-ticks ()
(sdl-cffi::sdl-get-ticks))
(defmacro with-timestep (&body body)
`(progn
(incf (accumulator *default-fpsmanager*) (if (> (delta-ticks *default-fpsmanager*)
(max-dt *default-fpsmanager*))
(max-dt *default-fpsmanager*)
(delta-ticks *default-fpsmanager*)))
(loop until (< (accumulator *default-fpsmanager*) (dt *default-fpsmanager*)) do
(progn
,@body
(incf (fps-ticks *default-fpsmanager*) (dt *default-fpsmanager*))
(decf (accumulator *default-fpsmanager*) (dt *default-fpsmanager*))))))
(defmacro with-frame-rate (&body body)
(let ((self (gensym "self-"))
(delta (gensym "delta-")))
`(let ((,self *default-fpsmanager*)
(,delta nil))
(setf (current-ticks ,self) (sdl-cffi::sdl-get-ticks)
(delta-ticks ,self) (- (current-ticks ,self) (last-ticks ,self)))
(setf (svref (average-window ,self) (index ,self)) (current-ticks ,self))
(when (not-through-p ,self)
(when (>= (index ,self) (1- (length (average-window ,self))))
(setf (not-through-p ,self) nil)))
,@body
(when (target-frame-rate ,self)
(incf (frame-count ,self))
(let ((,delta (truncate (- (+ (delay-ticks ,self) (* (frame-count ,self)
(rate-ticks ,self)))
(current-ticks ,self)))))
(if (> ,delta 0)
(sdl-cffi::sdl-delay (if (> ,delta (max-dt ,self))
(max-dt ,self)
,delta))
(setf (frame-count ,self) 0
(delay-ticks ,self) (current-ticks ,self)))))
(unless (< (incf (index ,self)) (length (average-window ,self)))
(setf (index ,self) 0))
(setf (last-ticks ,self) (current-ticks ,self)))))
|
78cb980fc631d71fdec91e7277fe9a6380d847967352aa5cb882e2999f41d4b3 | D00mch/PWA-clojure | config.clj | (ns pwa.config
(:require
[cprop.core :refer [load-config]]
[cprop.source :as source]
[mount.core :refer [args defstate]]))
(defstate env
:start
(load-config
:merge
[(args)
(source/from-system-props)
(source/from-env)]))
| null | https://raw.githubusercontent.com/D00mch/PWA-clojure/39ab4d3690c7a8ddbdd8095d65a782961f92c183/src/clj/pwa/config.clj | clojure | (ns pwa.config
(:require
[cprop.core :refer [load-config]]
[cprop.source :as source]
[mount.core :refer [args defstate]]))
(defstate env
:start
(load-config
:merge
[(args)
(source/from-system-props)
(source/from-env)]))
|
|
e290d22733ed939b24f32bfb6380349939605d897ed46cdc4e33e209c77486a7 | swarmpit/swarmpit | page_403.cljs | (ns swarmpit.component.page-403
(:require [rum.core :as rum]
[sablono.core :refer-macros [html]]
[material.components :as comp]
[swarmpit.routes :as routes]))
(rum/defc form < rum/static []
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-context
(comp/container
{:maxWidth "sm"
:className "Swarmpit-container"}
(comp/box
{:className "Swarmpit-404"}
(comp/typography
{:variant "h2"} (html [:span [:b "403"] " Forbidden"]))
(html [:p "You are not authorized for selected action"])
(comp/box
{:className "Swarmpit-form-buttons"}
(comp/button
{:href (routes/path-for-frontend :login)
:color "default"
:variant "outlined"}
"Go to login page"))))]])))
| null | https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/page_403.cljs | clojure | (ns swarmpit.component.page-403
(:require [rum.core :as rum]
[sablono.core :refer-macros [html]]
[material.components :as comp]
[swarmpit.routes :as routes]))
(rum/defc form < rum/static []
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-context
(comp/container
{:maxWidth "sm"
:className "Swarmpit-container"}
(comp/box
{:className "Swarmpit-404"}
(comp/typography
{:variant "h2"} (html [:span [:b "403"] " Forbidden"]))
(html [:p "You are not authorized for selected action"])
(comp/box
{:className "Swarmpit-form-buttons"}
(comp/button
{:href (routes/path-for-frontend :login)
:color "default"
:variant "outlined"}
"Go to login page"))))]])))
|
|
8ab8985e2a7f88b6ac9d0e8489ed101ee2ce16c116683b9e16b883b87e82ca8e | joachimdb/dl4clj | graves_lstm.clj | (ns ^{:doc "see "}
dl4clj.nn.conf.layers.graves-lstm
(:require [dl4clj.nn.conf.layers.base-recurrent-layer :as br-layer])
(:import [org.deeplearning4j.nn.conf.layers GravesLSTM$Builder]))
(defn builder [{:keys [forget-gate-bias-init] ;; (double)
:or {}
:as opts}]
(let [builder ^GravesLSTM$Builder (br-layer/builder (GravesLSTM$Builder.) opts)]
(when forget-gate-bias-init
(.forgetGateBiasInit builder forget-gate-bias-init))
builder))
(defn graves-lstm
([]
(graves-lstm {}))
([{:keys [forget-gate-bias-init] ;; (double)
:or {}
:as opts}]
(.build ^GravesLSTM$Builder (builder opts))))
(comment
;; Example usages:
(graves-lstm-layer)
(graves-lstm-layer {:activation "softmax"
:adam-mean-decay 0.3
:adam-var-decay 0.5
:bias-init 0.3
:dist (dl4clj.nn.conf.distribution.binomial-distribution/binomial-distribution 10 0.4)
:drop-out 0.01
:gradient-normalization :clip-l2-per-layer
:gradient-normalization-threshold 0.1
:l1 0.02
:l2 0.002
:learning-rate 0.95
:learning-rate-after {1000 0.5}
:learning-rate-score-based-decay-rate 0.001
:momentum 0.9
:momentum-after {10000 1.5}
:name "test"
:rho 0.5
:rms-decay 0.01
:updater :adam
:weight-init :normalized
:n-in 30
:n-out 30
:forget-gate-bias-init 0.12})
)
| null | https://raw.githubusercontent.com/joachimdb/dl4clj/fe9af7c886b80df5e18cd79923fbc6955ddc2694/src/dl4clj/nn/conf/layers/graves_lstm.clj | clojure | (double)
(double)
Example usages: | (ns ^{:doc "see "}
dl4clj.nn.conf.layers.graves-lstm
(:require [dl4clj.nn.conf.layers.base-recurrent-layer :as br-layer])
(:import [org.deeplearning4j.nn.conf.layers GravesLSTM$Builder]))
:or {}
:as opts}]
(let [builder ^GravesLSTM$Builder (br-layer/builder (GravesLSTM$Builder.) opts)]
(when forget-gate-bias-init
(.forgetGateBiasInit builder forget-gate-bias-init))
builder))
(defn graves-lstm
([]
(graves-lstm {}))
:or {}
:as opts}]
(.build ^GravesLSTM$Builder (builder opts))))
(comment
(graves-lstm-layer)
(graves-lstm-layer {:activation "softmax"
:adam-mean-decay 0.3
:adam-var-decay 0.5
:bias-init 0.3
:dist (dl4clj.nn.conf.distribution.binomial-distribution/binomial-distribution 10 0.4)
:drop-out 0.01
:gradient-normalization :clip-l2-per-layer
:gradient-normalization-threshold 0.1
:l1 0.02
:l2 0.002
:learning-rate 0.95
:learning-rate-after {1000 0.5}
:learning-rate-score-based-decay-rate 0.001
:momentum 0.9
:momentum-after {10000 1.5}
:name "test"
:rho 0.5
:rms-decay 0.01
:updater :adam
:weight-init :normalized
:n-in 30
:n-out 30
:forget-gate-bias-init 0.12})
)
|
241248dfd5b832d4a46864be9a6fc8beba41afdefb9dad3fe77927019265a5cd | qkrgud55/ocamlmulti | str.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : str.mli 12922 2012 - 09 - 11 14:40:43Z doligez $
(** Regular expressions and high-level string processing *)
* { 6 Regular expressions }
type regexp
(** The type of compiled regular expressions. *)
val regexp : string -> regexp
* Compile a regular expression . The following constructs are
recognized :
- [ . ] Matches any character except newline .
- [ * ] ( postfix ) Matches the preceding expression zero , one or
several times
- [ + ] ( postfix ) Matches the preceding expression one or
several times
- [ ? ] ( postfix ) Matches the preceding expression once or
not at all
- [ [ .. ] ] Character set . Ranges are denoted with [ - ] , as in [ [ a - z ] ] .
An initial [ ^ ] , as in [ [ ^0 - 9 ] ] , complements the set .
To include a [ \ ] ] character in a set , make it the first
character of the set . To include a [ - ] character in a set ,
make it the first or the last character of the set .
- [ ^ ] Matches at beginning of line ( either at the beginning of
the matched string , or just after a newline character ) .
- [ $ ] Matches at end of line ( either at the end of the matched
string , or just before a newline character ) .
- [ \| ] ( infix ) Alternative between two expressions .
- [ \( .. \ ) ] Grouping and naming of the enclosed expression .
- [ \1 ] The text matched by the first [ \( ... \ ) ] expression
( [ \2 ] for the second expression , and so on up to [ \9 ] ) .
- [ \b ] Matches word boundaries .
- [ \ ] Quotes special characters . The special characters
are [ $ ^\.*+ ? [ ] ] .
recognized:
- [. ] Matches any character except newline.
- [* ] (postfix) Matches the preceding expression zero, one or
several times
- [+ ] (postfix) Matches the preceding expression one or
several times
- [? ] (postfix) Matches the preceding expression once or
not at all
- [[..] ] Character set. Ranges are denoted with [-], as in [[a-z]].
An initial [^], as in [[^0-9]], complements the set.
To include a [\]] character in a set, make it the first
character of the set. To include a [-] character in a set,
make it the first or the last character of the set.
- [^ ] Matches at beginning of line (either at the beginning of
the matched string, or just after a newline character).
- [$ ] Matches at end of line (either at the end of the matched
string, or just before a newline character).
- [\| ] (infix) Alternative between two expressions.
- [\(..\)] Grouping and naming of the enclosed expression.
- [\1 ] The text matched by the first [\(...\)] expression
([\2] for the second expression, and so on up to [\9]).
- [\b ] Matches word boundaries.
- [\ ] Quotes special characters. The special characters
are [$^\.*+?[]].
*)
val regexp_case_fold : string -> regexp
(** Same as [regexp], but the compiled expression will match text
in a case-insensitive way: uppercase and lowercase letters will
be considered equivalent. *)
val quote : string -> string
(** [Str.quote s] returns a regexp string that matches exactly
[s] and nothing else. *)
val regexp_string : string -> regexp
* [ Str.regexp_string s ] returns a regular expression
that matches exactly [ s ] and nothing else .
that matches exactly [s] and nothing else.*)
val regexp_string_case_fold : string -> regexp
(** [Str.regexp_string_case_fold] is similar to {!Str.regexp_string},
but the regexp matches in a case-insensitive way. *)
* { 6 String matching and searching }
val string_match : regexp -> string -> int -> bool
* [ string_match r s start ] tests whether a substring of [ s ] that
starts at position [ start ] matches the regular expression [ r ] .
The first character of a string has position [ 0 ] , as usual .
starts at position [start] matches the regular expression [r].
The first character of a string has position [0], as usual. *)
val search_forward : regexp -> string -> int -> int
* [ search_forward r s start ] searches the string [ s ] for a substring
matching the regular expression [ r ] . The search starts at position
[ start ] and proceeds towards the end of the string .
Return the position of the first character of the matched
substring .
@raise Not_found if no substring matches .
matching the regular expression [r]. The search starts at position
[start] and proceeds towards the end of the string.
Return the position of the first character of the matched
substring.
@raise Not_found if no substring matches. *)
val search_backward : regexp -> string -> int -> int
* [ search_backward r s last ] searches the string [ s ] for a
substring matching the regular expression [ r ] . The search first
considers substrings that start at position [ last ] and proceeds
towards the beginning of string . Return the position of the first
character of the matched substring .
@raise Not_found if no substring matches .
substring matching the regular expression [r]. The search first
considers substrings that start at position [last] and proceeds
towards the beginning of string. Return the position of the first
character of the matched substring.
@raise Not_found if no substring matches. *)
val string_partial_match : regexp -> string -> int -> bool
(** Similar to {!Str.string_match}, but also returns true if
the argument string is a prefix of a string that matches.
This includes the case of a true complete match. *)
val matched_string : string -> string
* [ matched_string s ] returns the substring of [ s ] that was matched
by the last call to one of the following matching or searching
functions :
- { ! Str.string_match }
- { ! Str.search_forward }
- { ! Str.search_backward }
- { ! Str.string_partial_match }
- { ! Str.global_substitute }
- { ! Str.substitute_first }
provided that none of the following functions was called inbetween :
- { ! Str.global_replace }
- { ! Str.replace_first }
- { ! Str.split }
- { ! Str.bounded_split }
- { ! Str.split_delim }
- { ! Str.bounded_split_delim }
- { ! Str.full_split }
- { ! Str.bounded_full_split }
Note : in the case of [ global_substitute ] and [ substitute_first ] ,
a call to [ matched_string ] is only valid within the [ subst ] argument ,
not after [ global_substitute ] or [ substitute_first ] returns .
The user must make sure that the parameter [ s ] is the same string
that was passed to the matching or searching function .
by the last call to one of the following matching or searching
functions:
- {!Str.string_match}
- {!Str.search_forward}
- {!Str.search_backward}
- {!Str.string_partial_match}
- {!Str.global_substitute}
- {!Str.substitute_first}
provided that none of the following functions was called inbetween:
- {!Str.global_replace}
- {!Str.replace_first}
- {!Str.split}
- {!Str.bounded_split}
- {!Str.split_delim}
- {!Str.bounded_split_delim}
- {!Str.full_split}
- {!Str.bounded_full_split}
Note: in the case of [global_substitute] and [substitute_first],
a call to [matched_string] is only valid within the [subst] argument,
not after [global_substitute] or [substitute_first] returns.
The user must make sure that the parameter [s] is the same string
that was passed to the matching or searching function. *)
val match_beginning : unit -> int
* [ match_beginning ( ) ] returns the position of the first character
of the substring that was matched by the last call to a matching
or searching function ( see { ! Str.matched_string } for details ) .
of the substring that was matched by the last call to a matching
or searching function (see {!Str.matched_string} for details). *)
val match_end : unit -> int
(** [match_end()] returns the position of the character following the
last character of the substring that was matched by the last call
to a matching or searching function (see {!Str.matched_string} for
details). *)
val matched_group : int -> string -> string
* [ matched_group n s ] returns the substring of [ s ] that was matched
by the [ n]th group [ \( ... \ ) ] of the regular expression that was
matched by the last call to a matching or searching function ( see
{ ! Str.matched_string } for details ) .
The user must make sure that the parameter [ s ] is the same string
that was passed to the matching or searching function .
@raise Not_found if the [ n]th group
of the regular expression was not matched . This can happen
with groups inside alternatives [ \| ] , options [ ? ]
or repetitions [ * ] . For instance , the empty string will match
[ ) * ] , but [ matched_group 1 " " ] will raise [ Not_found ]
because the first group itself was not matched .
by the [n]th group [\(...\)] of the regular expression that was
matched by the last call to a matching or searching function (see
{!Str.matched_string} for details).
The user must make sure that the parameter [s] is the same string
that was passed to the matching or searching function.
@raise Not_found if the [n]th group
of the regular expression was not matched. This can happen
with groups inside alternatives [\|], options [?]
or repetitions [*]. For instance, the empty string will match
[\(a\)*], but [matched_group 1 ""] will raise [Not_found]
because the first group itself was not matched. *)
val group_beginning : int -> int
* [ group_beginning n ] returns the position of the first character
of the substring that was matched by the [ n]th group of
the regular expression that was matched by the last call to a
matching or searching function ( see { ! Str.matched_string } for details ) .
@raise Not_found if the [ n]th group of the regular expression
was not matched .
@raise Invalid_argument if there are fewer than [ n ] groups in
the regular expression .
of the substring that was matched by the [n]th group of
the regular expression that was matched by the last call to a
matching or searching function (see {!Str.matched_string} for details).
@raise Not_found if the [n]th group of the regular expression
was not matched.
@raise Invalid_argument if there are fewer than [n] groups in
the regular expression. *)
val group_end : int -> int
* [ group_end n ] returns
the position of the character following the last character of
substring that was matched by the [ n]th group of the regular
expression that was matched by the last call to a matching or
searching function ( see { ! Str.matched_string } for details ) .
@raise Not_found if the [ n]th group of the regular expression
was not matched .
@raise Invalid_argument if there are fewer than [ n ] groups in
the regular expression .
the position of the character following the last character of
substring that was matched by the [n]th group of the regular
expression that was matched by the last call to a matching or
searching function (see {!Str.matched_string} for details).
@raise Not_found if the [n]th group of the regular expression
was not matched.
@raise Invalid_argument if there are fewer than [n] groups in
the regular expression. *)
(** {6 Replacement} *)
val global_replace : regexp -> string -> string -> string
(** [global_replace regexp templ s] returns a string identical to [s],
except that all substrings of [s] that match [regexp] have been
replaced by [templ]. The replacement template [templ] can contain
[\1], [\2], etc; these sequences will be replaced by the text
matched by the corresponding group in the regular expression.
[\0] stands for the text matched by the whole regular expression. *)
val replace_first : regexp -> string -> string -> string
* Same as { ! Str.global_replace } , except that only the first substring
matching the regular expression is replaced .
matching the regular expression is replaced. *)
val global_substitute : regexp -> (string -> string) -> string -> string
(** [global_substitute regexp subst s] returns a string identical
to [s], except that all substrings of [s] that match [regexp]
have been replaced by the result of function [subst]. The
function [subst] is called once for each matching substring,
and receives [s] (the whole text) as argument. *)
val substitute_first : regexp -> (string -> string) -> string -> string
* Same as { ! Str.global_substitute } , except that only the first substring
matching the regular expression is replaced .
matching the regular expression is replaced. *)
val replace_matched : string -> string -> string
* [ replace_matched repl s ] returns the replacement text [ repl ]
in which [ \1 ] , [ \2 ] , etc . have been replaced by the text
matched by the corresponding groups in the regular expression
that was matched by the last call to a matching or searching
function ( see { ! Str.matched_string } for details ) .
[ s ] must be the same string that was passed to the matching or
searching function .
in which [\1], [\2], etc. have been replaced by the text
matched by the corresponding groups in the regular expression
that was matched by the last call to a matching or searching
function (see {!Str.matched_string} for details).
[s] must be the same string that was passed to the matching or
searching function. *)
* { 6 Splitting }
val split : regexp -> string -> string list
(** [split r s] splits [s] into substrings, taking as delimiters
the substrings that match [r], and returns the list of substrings.
For instance, [split (regexp "[ \t]+") s] splits [s] into
blank-separated words. An occurrence of the delimiter at the
beginning or at the end of the string is ignored. *)
val bounded_split : regexp -> string -> int -> string list
(** Same as {!Str.split}, but splits into at most [n] substrings,
where [n] is the extra integer parameter. *)
val split_delim : regexp -> string -> string list
* Same as { ! Str.split } but occurrences of the
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result .
For instance , [ split_delim ( regexp " " ) " abc " ]
returns [ [ " " ; " abc " ; " " ] ] , while [ split ] with the same
arguments returns [ [ " abc " ] ] .
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result.
For instance, [split_delim (regexp " ") " abc "]
returns [[""; "abc"; ""]], while [split] with the same
arguments returns [["abc"]]. *)
val bounded_split_delim : regexp -> string -> int -> string list
* Same as { ! } , but occurrences of the
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result .
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result. *)
type split_result =
Text of string
| Delim of string
val full_split : regexp -> string -> split_result list
* Same as { ! Str.split_delim } , but returns
the delimiters as well as the substrings contained between
delimiters . The former are tagged [ Delim ] in the result list ;
the latter are tagged [ Text ] . For instance ,
[ full_split ( regexp " [ { } ] " ) " { ab } " ] returns
[ [ Delim " { " ; Text " ab " ; " } " ] ] .
the delimiters as well as the substrings contained between
delimiters. The former are tagged [Delim] in the result list;
the latter are tagged [Text]. For instance,
[full_split (regexp "[{}]") "{ab}"] returns
[[Delim "{"; Text "ab"; Delim "}"]]. *)
val bounded_full_split : regexp -> string -> int -> split_result list
(** Same as {!Str.bounded_split_delim}, but returns
the delimiters as well as the substrings contained between
delimiters. The former are tagged [Delim] in the result list;
the latter are tagged [Text]. *)
* { 6 Extracting substrings }
val string_before : string -> int -> string
(** [string_before s n] returns the substring of all characters of [s]
that precede position [n] (excluding the character at
position [n]). *)
val string_after : string -> int -> string
(** [string_after s n] returns the substring of all characters of [s]
that follow position [n] (including the character at
position [n]). *)
val first_chars : string -> int -> string
* [ first_chars s n ] returns the first [ n ] characters of [ s ] .
This is the same function as { ! Str.string_before } .
This is the same function as {!Str.string_before}. *)
val last_chars : string -> int -> string
(** [last_chars s n] returns the last [n] characters of [s]. *)
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/otherlibs/str/str.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../../LICENSE.
*********************************************************************
* Regular expressions and high-level string processing
* The type of compiled regular expressions.
* Same as [regexp], but the compiled expression will match text
in a case-insensitive way: uppercase and lowercase letters will
be considered equivalent.
* [Str.quote s] returns a regexp string that matches exactly
[s] and nothing else.
* [Str.regexp_string_case_fold] is similar to {!Str.regexp_string},
but the regexp matches in a case-insensitive way.
* Similar to {!Str.string_match}, but also returns true if
the argument string is a prefix of a string that matches.
This includes the case of a true complete match.
* [match_end()] returns the position of the character following the
last character of the substring that was matched by the last call
to a matching or searching function (see {!Str.matched_string} for
details).
* {6 Replacement}
* [global_replace regexp templ s] returns a string identical to [s],
except that all substrings of [s] that match [regexp] have been
replaced by [templ]. The replacement template [templ] can contain
[\1], [\2], etc; these sequences will be replaced by the text
matched by the corresponding group in the regular expression.
[\0] stands for the text matched by the whole regular expression.
* [global_substitute regexp subst s] returns a string identical
to [s], except that all substrings of [s] that match [regexp]
have been replaced by the result of function [subst]. The
function [subst] is called once for each matching substring,
and receives [s] (the whole text) as argument.
* [split r s] splits [s] into substrings, taking as delimiters
the substrings that match [r], and returns the list of substrings.
For instance, [split (regexp "[ \t]+") s] splits [s] into
blank-separated words. An occurrence of the delimiter at the
beginning or at the end of the string is ignored.
* Same as {!Str.split}, but splits into at most [n] substrings,
where [n] is the extra integer parameter.
* Same as {!Str.bounded_split_delim}, but returns
the delimiters as well as the substrings contained between
delimiters. The former are tagged [Delim] in the result list;
the latter are tagged [Text].
* [string_before s n] returns the substring of all characters of [s]
that precede position [n] (excluding the character at
position [n]).
* [string_after s n] returns the substring of all characters of [s]
that follow position [n] (including the character at
position [n]).
* [last_chars s n] returns the last [n] characters of [s]. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : str.mli 12922 2012 - 09 - 11 14:40:43Z doligez $
* { 6 Regular expressions }
type regexp
val regexp : string -> regexp
* Compile a regular expression . The following constructs are
recognized :
- [ . ] Matches any character except newline .
- [ * ] ( postfix ) Matches the preceding expression zero , one or
several times
- [ + ] ( postfix ) Matches the preceding expression one or
several times
- [ ? ] ( postfix ) Matches the preceding expression once or
not at all
- [ [ .. ] ] Character set . Ranges are denoted with [ - ] , as in [ [ a - z ] ] .
An initial [ ^ ] , as in [ [ ^0 - 9 ] ] , complements the set .
To include a [ \ ] ] character in a set , make it the first
character of the set . To include a [ - ] character in a set ,
make it the first or the last character of the set .
- [ ^ ] Matches at beginning of line ( either at the beginning of
the matched string , or just after a newline character ) .
- [ $ ] Matches at end of line ( either at the end of the matched
string , or just before a newline character ) .
- [ \| ] ( infix ) Alternative between two expressions .
- [ \( .. \ ) ] Grouping and naming of the enclosed expression .
- [ \1 ] The text matched by the first [ \( ... \ ) ] expression
( [ \2 ] for the second expression , and so on up to [ \9 ] ) .
- [ \b ] Matches word boundaries .
- [ \ ] Quotes special characters . The special characters
are [ $ ^\.*+ ? [ ] ] .
recognized:
- [. ] Matches any character except newline.
- [* ] (postfix) Matches the preceding expression zero, one or
several times
- [+ ] (postfix) Matches the preceding expression one or
several times
- [? ] (postfix) Matches the preceding expression once or
not at all
- [[..] ] Character set. Ranges are denoted with [-], as in [[a-z]].
An initial [^], as in [[^0-9]], complements the set.
To include a [\]] character in a set, make it the first
character of the set. To include a [-] character in a set,
make it the first or the last character of the set.
- [^ ] Matches at beginning of line (either at the beginning of
the matched string, or just after a newline character).
- [$ ] Matches at end of line (either at the end of the matched
string, or just before a newline character).
- [\| ] (infix) Alternative between two expressions.
- [\(..\)] Grouping and naming of the enclosed expression.
- [\1 ] The text matched by the first [\(...\)] expression
([\2] for the second expression, and so on up to [\9]).
- [\b ] Matches word boundaries.
- [\ ] Quotes special characters. The special characters
are [$^\.*+?[]].
*)
val regexp_case_fold : string -> regexp
val quote : string -> string
val regexp_string : string -> regexp
* [ Str.regexp_string s ] returns a regular expression
that matches exactly [ s ] and nothing else .
that matches exactly [s] and nothing else.*)
val regexp_string_case_fold : string -> regexp
* { 6 String matching and searching }
val string_match : regexp -> string -> int -> bool
* [ string_match r s start ] tests whether a substring of [ s ] that
starts at position [ start ] matches the regular expression [ r ] .
The first character of a string has position [ 0 ] , as usual .
starts at position [start] matches the regular expression [r].
The first character of a string has position [0], as usual. *)
val search_forward : regexp -> string -> int -> int
* [ search_forward r s start ] searches the string [ s ] for a substring
matching the regular expression [ r ] . The search starts at position
[ start ] and proceeds towards the end of the string .
Return the position of the first character of the matched
substring .
@raise Not_found if no substring matches .
matching the regular expression [r]. The search starts at position
[start] and proceeds towards the end of the string.
Return the position of the first character of the matched
substring.
@raise Not_found if no substring matches. *)
val search_backward : regexp -> string -> int -> int
* [ search_backward r s last ] searches the string [ s ] for a
substring matching the regular expression [ r ] . The search first
considers substrings that start at position [ last ] and proceeds
towards the beginning of string . Return the position of the first
character of the matched substring .
@raise Not_found if no substring matches .
substring matching the regular expression [r]. The search first
considers substrings that start at position [last] and proceeds
towards the beginning of string. Return the position of the first
character of the matched substring.
@raise Not_found if no substring matches. *)
val string_partial_match : regexp -> string -> int -> bool
val matched_string : string -> string
* [ matched_string s ] returns the substring of [ s ] that was matched
by the last call to one of the following matching or searching
functions :
- { ! Str.string_match }
- { ! Str.search_forward }
- { ! Str.search_backward }
- { ! Str.string_partial_match }
- { ! Str.global_substitute }
- { ! Str.substitute_first }
provided that none of the following functions was called inbetween :
- { ! Str.global_replace }
- { ! Str.replace_first }
- { ! Str.split }
- { ! Str.bounded_split }
- { ! Str.split_delim }
- { ! Str.bounded_split_delim }
- { ! Str.full_split }
- { ! Str.bounded_full_split }
Note : in the case of [ global_substitute ] and [ substitute_first ] ,
a call to [ matched_string ] is only valid within the [ subst ] argument ,
not after [ global_substitute ] or [ substitute_first ] returns .
The user must make sure that the parameter [ s ] is the same string
that was passed to the matching or searching function .
by the last call to one of the following matching or searching
functions:
- {!Str.string_match}
- {!Str.search_forward}
- {!Str.search_backward}
- {!Str.string_partial_match}
- {!Str.global_substitute}
- {!Str.substitute_first}
provided that none of the following functions was called inbetween:
- {!Str.global_replace}
- {!Str.replace_first}
- {!Str.split}
- {!Str.bounded_split}
- {!Str.split_delim}
- {!Str.bounded_split_delim}
- {!Str.full_split}
- {!Str.bounded_full_split}
Note: in the case of [global_substitute] and [substitute_first],
a call to [matched_string] is only valid within the [subst] argument,
not after [global_substitute] or [substitute_first] returns.
The user must make sure that the parameter [s] is the same string
that was passed to the matching or searching function. *)
val match_beginning : unit -> int
* [ match_beginning ( ) ] returns the position of the first character
of the substring that was matched by the last call to a matching
or searching function ( see { ! Str.matched_string } for details ) .
of the substring that was matched by the last call to a matching
or searching function (see {!Str.matched_string} for details). *)
val match_end : unit -> int
val matched_group : int -> string -> string
* [ matched_group n s ] returns the substring of [ s ] that was matched
by the [ n]th group [ \( ... \ ) ] of the regular expression that was
matched by the last call to a matching or searching function ( see
{ ! Str.matched_string } for details ) .
The user must make sure that the parameter [ s ] is the same string
that was passed to the matching or searching function .
@raise Not_found if the [ n]th group
of the regular expression was not matched . This can happen
with groups inside alternatives [ \| ] , options [ ? ]
or repetitions [ * ] . For instance , the empty string will match
[ ) * ] , but [ matched_group 1 " " ] will raise [ Not_found ]
because the first group itself was not matched .
by the [n]th group [\(...\)] of the regular expression that was
matched by the last call to a matching or searching function (see
{!Str.matched_string} for details).
The user must make sure that the parameter [s] is the same string
that was passed to the matching or searching function.
@raise Not_found if the [n]th group
of the regular expression was not matched. This can happen
with groups inside alternatives [\|], options [?]
or repetitions [*]. For instance, the empty string will match
[\(a\)*], but [matched_group 1 ""] will raise [Not_found]
because the first group itself was not matched. *)
val group_beginning : int -> int
* [ group_beginning n ] returns the position of the first character
of the substring that was matched by the [ n]th group of
the regular expression that was matched by the last call to a
matching or searching function ( see { ! Str.matched_string } for details ) .
@raise Not_found if the [ n]th group of the regular expression
was not matched .
@raise Invalid_argument if there are fewer than [ n ] groups in
the regular expression .
of the substring that was matched by the [n]th group of
the regular expression that was matched by the last call to a
matching or searching function (see {!Str.matched_string} for details).
@raise Not_found if the [n]th group of the regular expression
was not matched.
@raise Invalid_argument if there are fewer than [n] groups in
the regular expression. *)
val group_end : int -> int
* [ group_end n ] returns
the position of the character following the last character of
substring that was matched by the [ n]th group of the regular
expression that was matched by the last call to a matching or
searching function ( see { ! Str.matched_string } for details ) .
@raise Not_found if the [ n]th group of the regular expression
was not matched .
@raise Invalid_argument if there are fewer than [ n ] groups in
the regular expression .
the position of the character following the last character of
substring that was matched by the [n]th group of the regular
expression that was matched by the last call to a matching or
searching function (see {!Str.matched_string} for details).
@raise Not_found if the [n]th group of the regular expression
was not matched.
@raise Invalid_argument if there are fewer than [n] groups in
the regular expression. *)
val global_replace : regexp -> string -> string -> string
val replace_first : regexp -> string -> string -> string
* Same as { ! Str.global_replace } , except that only the first substring
matching the regular expression is replaced .
matching the regular expression is replaced. *)
val global_substitute : regexp -> (string -> string) -> string -> string
val substitute_first : regexp -> (string -> string) -> string -> string
* Same as { ! Str.global_substitute } , except that only the first substring
matching the regular expression is replaced .
matching the regular expression is replaced. *)
val replace_matched : string -> string -> string
* [ replace_matched repl s ] returns the replacement text [ repl ]
in which [ \1 ] , [ \2 ] , etc . have been replaced by the text
matched by the corresponding groups in the regular expression
that was matched by the last call to a matching or searching
function ( see { ! Str.matched_string } for details ) .
[ s ] must be the same string that was passed to the matching or
searching function .
in which [\1], [\2], etc. have been replaced by the text
matched by the corresponding groups in the regular expression
that was matched by the last call to a matching or searching
function (see {!Str.matched_string} for details).
[s] must be the same string that was passed to the matching or
searching function. *)
* { 6 Splitting }
val split : regexp -> string -> string list
val bounded_split : regexp -> string -> int -> string list
val split_delim : regexp -> string -> string list
* Same as { ! Str.split } but occurrences of the
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result .
For instance , [ split_delim ( regexp " " ) " abc " ]
returns [ [ " " ; " abc " ; " " ] ] , while [ split ] with the same
arguments returns [ [ " abc " ] ] .
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result.
For instance, [split_delim (regexp " ") " abc "]
returns [[""; "abc"; ""]], while [split] with the same
arguments returns [["abc"]]. *)
val bounded_split_delim : regexp -> string -> int -> string list
* Same as { ! } , but occurrences of the
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result .
delimiter at the beginning and at the end of the string are
recognized and returned as empty strings in the result. *)
type split_result =
Text of string
| Delim of string
val full_split : regexp -> string -> split_result list
* Same as { ! Str.split_delim } , but returns
the delimiters as well as the substrings contained between
delimiters . The former are tagged [ Delim ] in the result list ;
the latter are tagged [ Text ] . For instance ,
[ full_split ( regexp " [ { } ] " ) " { ab } " ] returns
[ [ Delim " { " ; Text " ab " ; " } " ] ] .
the delimiters as well as the substrings contained between
delimiters. The former are tagged [Delim] in the result list;
the latter are tagged [Text]. For instance,
[full_split (regexp "[{}]") "{ab}"] returns
[[Delim "{"; Text "ab"; Delim "}"]]. *)
val bounded_full_split : regexp -> string -> int -> split_result list
* { 6 Extracting substrings }
val string_before : string -> int -> string
val string_after : string -> int -> string
val first_chars : string -> int -> string
* [ first_chars s n ] returns the first [ n ] characters of [ s ] .
This is the same function as { ! Str.string_before } .
This is the same function as {!Str.string_before}. *)
val last_chars : string -> int -> string
|
17acd4c9b7b4b073f3e7fe4e4d7fbf70e99721100a02f3d4a5a1b9b39e112629 | metaocaml/ber-metaocaml | t050-pushgetglobal.ml | TEST
include tool - ocaml - lib
flags = " -w a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
let _ = () in 0.01;;
*
0
1 PUSHGETGLOBAL 0.01
3 POP 1
5 ATOM0
6 SETGLOBAL T050 - pushgetglobal
8 STOP
*
0 CONST0
1 PUSHGETGLOBAL 0.01
3 POP 1
5 ATOM0
6 SETGLOBAL T050-pushgetglobal
8 STOP
**)
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/tool-ocaml/t050-pushgetglobal.ml | ocaml | TEST
include tool - ocaml - lib
flags = " -w a "
ocaml_script_as_argument = " true "
* setup - ocaml - build - env
* *
include tool-ocaml-lib
flags = "-w a"
ocaml_script_as_argument = "true"
* setup-ocaml-build-env
** ocaml
*)
let _ = () in 0.01;;
*
0
1 PUSHGETGLOBAL 0.01
3 POP 1
5 ATOM0
6 SETGLOBAL T050 - pushgetglobal
8 STOP
*
0 CONST0
1 PUSHGETGLOBAL 0.01
3 POP 1
5 ATOM0
6 SETGLOBAL T050-pushgetglobal
8 STOP
**)
|
|
7949aad37a1de16d2ddadabcca85f3c47216266ac67c1a7e6f1bd02d239c8dfc | teamwalnut/graphql-ppx | main.ml | let suites =
[
("Argument named 'query'", Arg_named_query.tests);
("Custom decoder", Custom_decoder.tests);
("Custom scalars", Custom_scalars.tests);
("Enum input", Enum_input.tests);
("Fragment definition", Fragment_definition.tests);
("Interface", Interface.tests);
("Lists", Lists.tests);
("List arguments", List_args.tests);
("List inputs", List_inputs.tests);
("Mutations", Mutation.tests);
("Nested decoding", Nested.tests);
("Nonrecursive input", Nonrecursive_input.tests);
("Records", Record.tests);
("Recursive input", Recursive_input.tests);
("Scalars", Scalars.tests);
("Scalar arguments", Scalars_args.tests);
("Scalar inputs", Scalars_input.tests);
("Skip directives", Skip_directives.tests);
("Typename", Typename.tests);
("Unions", Union.tests);
("Partial unions", Union_partial.tests);
("Variant conversion", Variant.tests);
("Fragment union serialization", Fragment_union_serialization.tests);
("Typename", Implicit_typename.tests);
]
;;
let indent = "- " in
let print_success s =
print_endline (indent ^ "✅ " ^ Cli_colors.green ^ s ^ Cli_colors.reset)
in
let print_error s =
print_endline (indent ^ Cli_colors.red ^ "❌ " ^ s ^ Cli_colors.reset)
in
let failure = ref false in
suites
|> List.iter (fun (suite_name, tests) ->
print_endline (suite_name ^ Cli_colors.reset);
tests
|> List.iter (fun (test_name, test) ->
match test () with
| Test_shared.Pass -> print_success test_name
| Fail reason ->
print_error test_name;
(Format.fprintf Format.std_formatter " %s") reason
| CompareFail (a, b) ->
print_error test_name;
(Format.fprintf Format.std_formatter " expected: @[%a@]@." a) ();
(Format.fprintf Format.std_formatter " got: @[%a@]@." b) ();
failure := true));
if !failure then exit 1 else ()
| null | https://raw.githubusercontent.com/teamwalnut/graphql-ppx/eb8648d1552fbc11989b9197ef41a7a958b2545f/tests_native/main.ml | ocaml | let suites =
[
("Argument named 'query'", Arg_named_query.tests);
("Custom decoder", Custom_decoder.tests);
("Custom scalars", Custom_scalars.tests);
("Enum input", Enum_input.tests);
("Fragment definition", Fragment_definition.tests);
("Interface", Interface.tests);
("Lists", Lists.tests);
("List arguments", List_args.tests);
("List inputs", List_inputs.tests);
("Mutations", Mutation.tests);
("Nested decoding", Nested.tests);
("Nonrecursive input", Nonrecursive_input.tests);
("Records", Record.tests);
("Recursive input", Recursive_input.tests);
("Scalars", Scalars.tests);
("Scalar arguments", Scalars_args.tests);
("Scalar inputs", Scalars_input.tests);
("Skip directives", Skip_directives.tests);
("Typename", Typename.tests);
("Unions", Union.tests);
("Partial unions", Union_partial.tests);
("Variant conversion", Variant.tests);
("Fragment union serialization", Fragment_union_serialization.tests);
("Typename", Implicit_typename.tests);
]
;;
let indent = "- " in
let print_success s =
print_endline (indent ^ "✅ " ^ Cli_colors.green ^ s ^ Cli_colors.reset)
in
let print_error s =
print_endline (indent ^ Cli_colors.red ^ "❌ " ^ s ^ Cli_colors.reset)
in
let failure = ref false in
suites
|> List.iter (fun (suite_name, tests) ->
print_endline (suite_name ^ Cli_colors.reset);
tests
|> List.iter (fun (test_name, test) ->
match test () with
| Test_shared.Pass -> print_success test_name
| Fail reason ->
print_error test_name;
(Format.fprintf Format.std_formatter " %s") reason
| CompareFail (a, b) ->
print_error test_name;
(Format.fprintf Format.std_formatter " expected: @[%a@]@." a) ();
(Format.fprintf Format.std_formatter " got: @[%a@]@." b) ();
failure := true));
if !failure then exit 1 else ()
|
|
481278f6572c55f89746ff2f2542eaffc443400925997b2e7e2f5faec389aa19 | klutometis/clrs | figure-23.4.scm | (require-extension check)
(require 'section)
(import section-23.2)
(let* ((MST (minimum-spanning-tree/kruskal (figure-23.1)))
(edge-labels
(map
(lambda (edge)
(let ((whence-label (node-label (edge-whence edge)))
(whither-label (node-label (edge-whither edge))))
(cons whence-label whither-label))) MST)))
(check
edge-labels
=> '((d . e) (b . c) (c . d) (a . b)
(c . f) (f . g) (i . c) (g . h))))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/23.2/figure-23.4.scm | scheme | (require-extension check)
(require 'section)
(import section-23.2)
(let* ((MST (minimum-spanning-tree/kruskal (figure-23.1)))
(edge-labels
(map
(lambda (edge)
(let ((whence-label (node-label (edge-whence edge)))
(whither-label (node-label (edge-whither edge))))
(cons whence-label whither-label))) MST)))
(check
edge-labels
=> '((d . e) (b . c) (c . d) (a . b)
(c . f) (f . g) (i . c) (g . h))))
|
|
2b6e041ba9fb39ca6118a654f485f8ba57cf6420ad41351c2206332f66e0514e | blockfrost/blockfrost-haskell | Network.hs | # LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Cardano.Network
where
import Data.Aeson (decode, eitherDecode, encode)
import Data.Text (Text)
import qualified Money
import Test.Hspec
import Test.Tasty.Hspec
import Text.RawString.QQ
import Blockfrost.Types
spec_network :: Spec
spec_network = do
it "parses network sample" $ do
eitherDecode networkSample
`shouldBe`
Right networkExpected
networkSample = [r|
{
"supply": {
"max": "45000000000000000",
"total": "32890715183299160",
"circulating": "32412601976210393",
"locked": "125006953355",
"treasury": "98635632000000",
"reserves": "46635632000000"
},
"stake": {
"live": "23204950463991654",
"active": "22210233523456321"
}
}
|]
networkExpected =
Network
NetworkSupply
{ _supplyMax = 45_000_000_000_000_000
, _supplyTotal = 32_890_715_183_299_160
, _supplyCirculating = 32_412_601_976_210_393
, _supplyLocked = 125_006_953_355
, _supplyTreasury = 98_635_632_000_000
, _supplyReserves = 46_635_632_000_000
}
NetworkStake
{ _stakeLive = 23_204_950_463_991_654
, _stakeActive = 22_210_233_523_456_321
}
| null | https://raw.githubusercontent.com/blockfrost/blockfrost-haskell/c3812a14a5c0071a17972d9f2ba66ac56ebcbb8a/blockfrost-api/test/Cardano/Network.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NumericUnderscores #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
module Cardano.Network
where
import Data.Aeson (decode, eitherDecode, encode)
import Data.Text (Text)
import qualified Money
import Test.Hspec
import Test.Tasty.Hspec
import Text.RawString.QQ
import Blockfrost.Types
spec_network :: Spec
spec_network = do
it "parses network sample" $ do
eitherDecode networkSample
`shouldBe`
Right networkExpected
networkSample = [r|
{
"supply": {
"max": "45000000000000000",
"total": "32890715183299160",
"circulating": "32412601976210393",
"locked": "125006953355",
"treasury": "98635632000000",
"reserves": "46635632000000"
},
"stake": {
"live": "23204950463991654",
"active": "22210233523456321"
}
}
|]
networkExpected =
Network
NetworkSupply
{ _supplyMax = 45_000_000_000_000_000
, _supplyTotal = 32_890_715_183_299_160
, _supplyCirculating = 32_412_601_976_210_393
, _supplyLocked = 125_006_953_355
, _supplyTreasury = 98_635_632_000_000
, _supplyReserves = 46_635_632_000_000
}
NetworkStake
{ _stakeLive = 23_204_950_463_991_654
, _stakeActive = 22_210_233_523_456_321
}
|
bb8a9cd2f66d13868f22fa3e051d762fd49aafdfd6d5d24fb80e92a87d5ac907 | mfelleisen/Fish | run-server-client.rkt | #lang racket
(provide
LOCALHOST
#; {Port# -> Void}
;; runs the server locally on port `p`
run-server
#; {Port# [Listof Player] -> Void}
run-clients
{ [ InputPort OutputPort - > Void ] - > ( values InputPort OutputPort [ - > Void ] ) }
local-setup
#; {N N -> Void}
#; (report-results passsed total-test-count)
report-results
#; {-> Port#}
get-starter-port
#; {Port# -> Void}
set-starter-port)
;; ---------------------------------------------------------------------------------------------------
(require Fish/Remote/server)
(require Fish/Remote/client)
(require SwDev/Testing/make-client)
(require SwDev/Testing/communication)
;; ---------------------------------------------------------------------------------------------------
(define LOCALHOST "127.0.0.1")
(define BASE 12345)
(define PORT-STARTER-FILE "port-starter-file.rktl")
;; ---------------------------------------------------------------------------------------------------
(define (run-server config #:house (house-players '[]))
(match-define [list winners cheats-and-failures] (server config house-players))
(send-message `[,(~a winners) ,(~a cheats-and-failures)]))
;; ---------------------------------------------------------------------------------------------------
(define (run-clients port players ip)
(unless (port/c port)
(error 'xclient "port number expected, given ~e" port))
(define named
(for/list ([p players] [i (in-naturals)])
(define name (~a "P" (integer->string i)))
(if (not p) (list #f #f) (list name p))))
(client named port #t ip))
(define (integer->string i)
(cond
[(<= 0 i 9) (digit->string i)]
[else
(define mod (modulo i 10))
(define rem (remainder i 10))
(string-append (digit->string rem) (integer->string mod))]))
(define (digit->string i)
(list-ref '["z" "o" "tw" "th" "fo" "fi" "si" "se" "e" "nine"] i))
;; ---------------------------------------------------------------------------------------------------
(define (local-setup f)
(define cust (make-custodian))
(define-values (in out) (make-pipe))
(parameterize ([current-custodian cust])
(thread
(λ ()
(parameterize ([current-input-port (open-input-string "")]
[current-output-port out])
(f)))))
(define (tear-down)
(close-input-port in)
(close-output-port out)
(custodian-shutdown-all cust))
(values in out tear-down))
;; ---------------------------------------------------------------------------------------------------
(define (report-results passed total-test-count)
(displayln
`((passed ,passed)
(total ,total-test-count)
(partial-score ,passed))))
;; ---------------------------------------------------------------------------------------------------
(define (get-starter-port)
(if (file-exists? PORT-STARTER-FILE)
(with-input-from-file PORT-STARTER-FILE read)
BASE))
(define (set-starter-port port)
(with-output-to-file PORT-STARTER-FILE (λ () (writeln port)) #:exists 'replace))
| null | https://raw.githubusercontent.com/mfelleisen/Fish/a2b73f6d5312c42c4700c8ecd7a073fe18bd83e4/Scripts/Private/run-server-client.rkt | racket | {Port# -> Void}
runs the server locally on port `p`
{Port# [Listof Player] -> Void}
{N N -> Void}
(report-results passsed total-test-count)
{-> Port#}
{Port# -> Void}
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------- | #lang racket
(provide
LOCALHOST
run-server
run-clients
{ [ InputPort OutputPort - > Void ] - > ( values InputPort OutputPort [ - > Void ] ) }
local-setup
report-results
get-starter-port
set-starter-port)
(require Fish/Remote/server)
(require Fish/Remote/client)
(require SwDev/Testing/make-client)
(require SwDev/Testing/communication)
(define LOCALHOST "127.0.0.1")
(define BASE 12345)
(define PORT-STARTER-FILE "port-starter-file.rktl")
(define (run-server config #:house (house-players '[]))
(match-define [list winners cheats-and-failures] (server config house-players))
(send-message `[,(~a winners) ,(~a cheats-and-failures)]))
(define (run-clients port players ip)
(unless (port/c port)
(error 'xclient "port number expected, given ~e" port))
(define named
(for/list ([p players] [i (in-naturals)])
(define name (~a "P" (integer->string i)))
(if (not p) (list #f #f) (list name p))))
(client named port #t ip))
(define (integer->string i)
(cond
[(<= 0 i 9) (digit->string i)]
[else
(define mod (modulo i 10))
(define rem (remainder i 10))
(string-append (digit->string rem) (integer->string mod))]))
(define (digit->string i)
(list-ref '["z" "o" "tw" "th" "fo" "fi" "si" "se" "e" "nine"] i))
(define (local-setup f)
(define cust (make-custodian))
(define-values (in out) (make-pipe))
(parameterize ([current-custodian cust])
(thread
(λ ()
(parameterize ([current-input-port (open-input-string "")]
[current-output-port out])
(f)))))
(define (tear-down)
(close-input-port in)
(close-output-port out)
(custodian-shutdown-all cust))
(values in out tear-down))
(define (report-results passed total-test-count)
(displayln
`((passed ,passed)
(total ,total-test-count)
(partial-score ,passed))))
(define (get-starter-port)
(if (file-exists? PORT-STARTER-FILE)
(with-input-from-file PORT-STARTER-FILE read)
BASE))
(define (set-starter-port port)
(with-output-to-file PORT-STARTER-FILE (λ () (writeln port)) #:exists 'replace))
|
badf5bc5aa3ff5ae76a05cb2d4f502957309782213babeaf11e89507ab1b4a73 | projectcs13/sensor-cloud | streamProcess.erl | @author
@author
%% [www.csproj13.student.it.uu.se]
%% @version 1.0
[ Copyright information ]
%%
%% @doc == streamProcess ==
%% This module represents a stream process which subscribes to data points from
%% the pub/sub system for a specified resource and publish it back into the
%% pub/sub system for the specified stream
%%
%% @end
-module(streamProcess).
-include_lib("amqp_client.hrl").
-include_lib("pubsub.hrl").
-export([create/2]).
%% ====================================================================
%% API functions
%% ====================================================================
%% @doc
%% Function: create/2
%% Purpose: Used to initialize the stream process which subscribes to the
%% exchange beloning to the specified resource and publish it into
%% the exchange for the specified stream.
: StreamId - The i d of a stream .
%% ResourceId - The id of a resource.
%% Returns: Return ok.
%% Side effects: Non terminating loop receiving datapoints from the pub/sub
%% system for a resource with id 'ResourceId' and sending data
%% into the pub/sub system for a stream with id 'StreamId'.
%%
%% @end
-spec create(string(), string()) -> ok.
create(StreamId, ResourceId) ->
Exchange name binarys
ResourceExchange = list_to_binary("resources."++ResourceId),
StreamExchange = list_to_binary("streams."++StreamId),
Connect
{ok, Connection} =
amqp_connection:start(#amqp_params_network{host = "localhost"}),
%% Open In and OUT channels
{ok, ChannelIn} = amqp_connection:open_channel(Connection),
{ok, ChannelOut} = amqp_connection:open_channel(Connection),
%% Declare INPUT exchange and queue
amqp_channel:call(ChannelIn, #'exchange.declare'{exchange = ResourceExchange, type = <<"fanout">>}),
#'queue.declare_ok'{queue = QueueIn} = amqp_channel:call(ChannelIn, #'queue.declare'{exclusive = true}),
amqp_channel:call(ChannelIn, #'queue.bind'{exchange = ResourceExchange, queue = QueueIn}),
Subscribe to INPUT queue
amqp_channel:subscribe(ChannelIn, #'basic.consume'{queue = QueueIn, no_ack = true}, self()),
receive
#'basic.consume_ok'{} -> ok
end,
%% Declare OUTPUT exchange
io:format("Listening to ~p~n", [binary_to_list(ResourceExchange)]),
amqp_channel:call(ChannelOut, #'exchange.declare'{exchange = StreamExchange, type = <<"fanout">>}),
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange}).
%% ====================================================================
Internal functions
%% ====================================================================
%% @doc
%% Function: loop/3
%% Purpose: Used to receive data points from the pub/sub system from a specified
%% exchange and publish it into the pub/sub system for the exchange
%% of the specified stream.
: StreamId - The i d of a stream ,
%% ChannelIn - The channel on which we are subscribing to data points,
%% PubInfo - A tuple holding the channel for publishing and which exchange
%% to publish to.
%% Returns: Return ok.
%% Side effects: Non terminating loop receiving data points from the pub/sub
system and publishing it to the exchange specified in .
%%
%% @end
-spec loop(string(), pid(), tuple()) -> ok.
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange}) ->
%% Receive from the subscribeTopic!
receive
{#'basic.deliver'{}, #amqp_msg{payload = Body}} ->
Propagete
send(ChannelOut, StreamExchange, Body),
io : : { \"timestamp\ " : ~p , \"value\ " : ~p } - > ~p ~ n " , [ TimeStamp , Value , StreamExchange ] ) ;
Recurse
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange})
end.
%% @doc
%% Function: send/3
%% Purpose: Used to publish a message into specified exchange in the pub/sub
%% system on the specified channel.
: Channel - The channel on which we publish ,
%% Exchange - The exchange we publish to,
%% Message - The message that we want to publish.
%% Returns: Return ok.
Side effects : Publish the message ' Message ' into the exchange ' Exchange ' .
%%
%% @end
-spec send(pid(), string(), binary()) -> ok.
send(Channel, Exchange, Message) ->
amqp_channel:cast(Channel,
#'basic.publish'{exchange = Exchange},
#amqp_msg{payload = Message}).
%% HOW TO SEND TO A STREAMPROCESS
% StreamId = "1",
% ResourceId = "1",
% Exchange = list_to_binary("resources."++ResourceId),
%
{ ok , Connection } = amqp_connection : start(#amqp_params_network{host = " localhost " } ) ,
% {ok, Channel} = amqp_connection:open_channel(Connection),
%
% amqp_channel:call(Channel,
% #'exchange.declare'{exchange = Exchange,
type = < < " fanout " > > } ) ,
%
% PID = spawn(streamProcess, create, [StreamId, ResourceId]),
% io:format("Node Created: ~p~n", [PID]),
%
% %% Needed for the RabbitMQ to have time to set up the system.
timer : sleep(1000 ) ,
%
% amqp_channel:cast(Channel,
% #'basic.publish'{exchange = Exchange},
# amqp_msg{payload = term_to_binary({post , } ) } ) ,
%
ok = amqp_channel : ) ,
% ok = amqp_connection:close(Connection),
| null | https://raw.githubusercontent.com/projectcs13/sensor-cloud/0302bd74b2e62fddbd832fb4c7a27b9c62852b90/src/pubsub/streamProcess.erl | erlang | [www.csproj13.student.it.uu.se]
@version 1.0
@doc == streamProcess ==
This module represents a stream process which subscribes to data points from
the pub/sub system for a specified resource and publish it back into the
pub/sub system for the specified stream
@end
====================================================================
API functions
====================================================================
@doc
Function: create/2
Purpose: Used to initialize the stream process which subscribes to the
exchange beloning to the specified resource and publish it into
the exchange for the specified stream.
ResourceId - The id of a resource.
Returns: Return ok.
Side effects: Non terminating loop receiving datapoints from the pub/sub
system for a resource with id 'ResourceId' and sending data
into the pub/sub system for a stream with id 'StreamId'.
@end
Open In and OUT channels
Declare INPUT exchange and queue
Declare OUTPUT exchange
====================================================================
====================================================================
@doc
Function: loop/3
Purpose: Used to receive data points from the pub/sub system from a specified
exchange and publish it into the pub/sub system for the exchange
of the specified stream.
ChannelIn - The channel on which we are subscribing to data points,
PubInfo - A tuple holding the channel for publishing and which exchange
to publish to.
Returns: Return ok.
Side effects: Non terminating loop receiving data points from the pub/sub
@end
Receive from the subscribeTopic!
@doc
Function: send/3
Purpose: Used to publish a message into specified exchange in the pub/sub
system on the specified channel.
Exchange - The exchange we publish to,
Message - The message that we want to publish.
Returns: Return ok.
@end
HOW TO SEND TO A STREAMPROCESS
StreamId = "1",
ResourceId = "1",
Exchange = list_to_binary("resources."++ResourceId),
{ok, Channel} = amqp_connection:open_channel(Connection),
amqp_channel:call(Channel,
#'exchange.declare'{exchange = Exchange,
PID = spawn(streamProcess, create, [StreamId, ResourceId]),
io:format("Node Created: ~p~n", [PID]),
%% Needed for the RabbitMQ to have time to set up the system.
amqp_channel:cast(Channel,
#'basic.publish'{exchange = Exchange},
ok = amqp_connection:close(Connection), | @author
@author
[ Copyright information ]
-module(streamProcess).
-include_lib("amqp_client.hrl").
-include_lib("pubsub.hrl").
-export([create/2]).
: StreamId - The i d of a stream .
-spec create(string(), string()) -> ok.
create(StreamId, ResourceId) ->
Exchange name binarys
ResourceExchange = list_to_binary("resources."++ResourceId),
StreamExchange = list_to_binary("streams."++StreamId),
Connect
{ok, Connection} =
amqp_connection:start(#amqp_params_network{host = "localhost"}),
{ok, ChannelIn} = amqp_connection:open_channel(Connection),
{ok, ChannelOut} = amqp_connection:open_channel(Connection),
amqp_channel:call(ChannelIn, #'exchange.declare'{exchange = ResourceExchange, type = <<"fanout">>}),
#'queue.declare_ok'{queue = QueueIn} = amqp_channel:call(ChannelIn, #'queue.declare'{exclusive = true}),
amqp_channel:call(ChannelIn, #'queue.bind'{exchange = ResourceExchange, queue = QueueIn}),
Subscribe to INPUT queue
amqp_channel:subscribe(ChannelIn, #'basic.consume'{queue = QueueIn, no_ack = true}, self()),
receive
#'basic.consume_ok'{} -> ok
end,
io:format("Listening to ~p~n", [binary_to_list(ResourceExchange)]),
amqp_channel:call(ChannelOut, #'exchange.declare'{exchange = StreamExchange, type = <<"fanout">>}),
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange}).
Internal functions
: StreamId - The i d of a stream ,
system and publishing it to the exchange specified in .
-spec loop(string(), pid(), tuple()) -> ok.
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange}) ->
receive
{#'basic.deliver'{}, #amqp_msg{payload = Body}} ->
Propagete
send(ChannelOut, StreamExchange, Body),
io : : { \"timestamp\ " : ~p , \"value\ " : ~p } - > ~p ~ n " , [ TimeStamp , Value , StreamExchange ] ) ;
Recurse
loop(StreamId, ChannelIn, {ChannelOut, StreamExchange})
end.
: Channel - The channel on which we publish ,
Side effects : Publish the message ' Message ' into the exchange ' Exchange ' .
-spec send(pid(), string(), binary()) -> ok.
send(Channel, Exchange, Message) ->
amqp_channel:cast(Channel,
#'basic.publish'{exchange = Exchange},
#amqp_msg{payload = Message}).
{ ok , Connection } = amqp_connection : start(#amqp_params_network{host = " localhost " } ) ,
type = < < " fanout " > > } ) ,
timer : sleep(1000 ) ,
# amqp_msg{payload = term_to_binary({post , } ) } ) ,
ok = amqp_channel : ) ,
|
5644f57905375cf455d9149b7df7d3dee254fbd267266a7371a37400f3db0dd0 | kupl/FixML | sub20.ml | type formula =
| True
| False
| Not of formula
| AndAlso of formula * formula
| OrElse of formula * formula
| Imply of formula * formula
| Equal of exp * exp
and exp =
| Num of int
| Plus of exp * exp
| Minus of exp * exp
let rec eval : formula -> bool = fun f -> match f with | True -> true | False -> false | Not x -> not(eval x) | AndAlso(x, y) -> (eval x) && (eval y) | OrElse(x, y) -> (eval x) || (eval y) | Imply(x, y) -> not(eval x) || (eval y) | Equal(x, y) -> x = y;;
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/formula/formula1/submissions/sub20.ml | ocaml | type formula =
| True
| False
| Not of formula
| AndAlso of formula * formula
| OrElse of formula * formula
| Imply of formula * formula
| Equal of exp * exp
and exp =
| Num of int
| Plus of exp * exp
| Minus of exp * exp
let rec eval : formula -> bool = fun f -> match f with | True -> true | False -> false | Not x -> not(eval x) | AndAlso(x, y) -> (eval x) && (eval y) | OrElse(x, y) -> (eval x) || (eval y) | Imply(x, y) -> not(eval x) || (eval y) | Equal(x, y) -> x = y;;
|
|
eda6efc1126c06f4bc36a5d8f0f38b0316395b8148e0afefe5048d1d76777764 | hdbc/hdbc-sqlite3 | Testbasics.hs | module Testbasics(tests) where
import Test.HUnit
import Database.HDBC
import TestUtils
import System.IO
import Control.Exception hiding (catch)
openClosedb = sqlTestCase $
do dbh <- connectDB
disconnect dbh
multiFinish = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
r <- execute sth []
assertEqual "basic count" 0 r
finish sth
finish sth
finish sth
)
basicQueries = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
execute sth [] >>= (0 @=?)
r <- fetchAllRows sth
assertEqual "converted from" [["2"]] (map (map fromSql) r)
assertEqual "int32 compare" [[SqlInt32 2]] r
assertEqual "iToSql compare" [[iToSql 2]] r
assertEqual "num compare" [[toSql (2::Int)]] r
assertEqual "nToSql compare" [[nToSql (2::Int)]] r
assertEqual "string compare" [[SqlString "2"]] r
)
createTable = dbTestCase (\dbh ->
do run dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT)" []
commit dbh
)
dropTable = dbTestCase (\dbh ->
do run dbh "DROP TABLE hdbctest1" []
commit dbh
)
runReplace = dbTestCase (\dbh ->
do r <- run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
assertEqual "insert retval" 1 r
run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r2
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
rv2 <- execute sth []
assertEqual "select retval" 0 rv2
r <- fetchAllRows sth
assertEqual "" [r1, r2] r
)
where r1 = [toSql "runReplace", iToSql 1, iToSql 1234, SqlString "testdata"]
r2 = [toSql "runReplace", iToSql 2, iToSql 2, SqlNull]
executeReplace = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
execute sth [iToSql 1, iToSql 1234, toSql "Foo"]
execute sth [SqlInt32 2, SqlNull, toSql "Bar"]
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
execute sth [SqlString "executeReplace"]
r <- fetchAllRows sth
assertEqual "result"
[[toSql "executeReplace", iToSql 1, toSql "1234",
toSql "Foo"],
[toSql "executeReplace", iToSql 2, SqlNull,
toSql "Bar"]]
r
)
testExecuteMany = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
execute sth []
r <- fetchAllRows sth
assertEqual "" rows r
)
where rows = [map toSql ["1", "1234", "foo"],
map toSql ["2", "1341", "bar"],
[toSql "3", SqlNull, SqlNull]]
testFetchAllRows = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('fetchAllRows', ?, NULL, NULL)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'fetchAllRows' ORDER BY testid"
execute sth []
results <- fetchAllRows sth
assertEqual "" rows results
)
where rows = map (\x -> [iToSql x]) [1..9]
testFetchAllRows' = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('fetchAllRows2', ?, NULL, NULL)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'fetchAllRows2' ORDER BY testid"
execute sth []
results <- fetchAllRows' sth
assertEqual "" rows results
)
where rows = map (\x -> [iToSql x]) [1..9]
basicTransactions = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
execute sth [iToSql 0]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
-- Now try a rollback
executeMany sth rows
rollback dbh
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "rollback" [[toSql "0"]])
-- Now try another commit
executeMany sth rows
commit dbh
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "final commit" ([SqlString "0"]:rows))
)
where rows = map (\x -> [iToSql $ x]) [1..9]
testWithTransaction = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
execute sth [toSql "0"]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
-- Let's try a rollback.
catch (withTransaction dbh (\_ -> do executeMany sth rows
fail "Foo"))
(\_ -> return ())
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "rollback" [[SqlString "0"]])
-- And now a commit.
withTransaction dbh (\_ -> executeMany sth rows)
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "final commit" ([iToSql 0]:rows))
)
where rows = map (\x -> [iToSql x]) [1..9]
tests = TestList
[
TestLabel "openClosedb" openClosedb,
TestLabel "multiFinish" multiFinish,
TestLabel "basicQueries" basicQueries,
TestLabel "createTable" createTable,
TestLabel "runReplace" runReplace,
TestLabel "executeReplace" executeReplace,
TestLabel "executeMany" testExecuteMany,
TestLabel "fetchAllRows" testFetchAllRows,
TestLabel "fetchAllRows'" testFetchAllRows',
TestLabel "basicTransactions" basicTransactions,
TestLabel "withTransaction" testWithTransaction,
TestLabel "dropTable" dropTable
]
| null | https://raw.githubusercontent.com/hdbc/hdbc-sqlite3/6446abb80d4bbc182bb1ea289c821594ca21ed25/testsrc/Testbasics.hs | haskell | Now try a rollback
Now try another commit
Let's try a rollback.
And now a commit. | module Testbasics(tests) where
import Test.HUnit
import Database.HDBC
import TestUtils
import System.IO
import Control.Exception hiding (catch)
openClosedb = sqlTestCase $
do dbh <- connectDB
disconnect dbh
multiFinish = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
r <- execute sth []
assertEqual "basic count" 0 r
finish sth
finish sth
finish sth
)
basicQueries = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
execute sth [] >>= (0 @=?)
r <- fetchAllRows sth
assertEqual "converted from" [["2"]] (map (map fromSql) r)
assertEqual "int32 compare" [[SqlInt32 2]] r
assertEqual "iToSql compare" [[iToSql 2]] r
assertEqual "num compare" [[toSql (2::Int)]] r
assertEqual "nToSql compare" [[nToSql (2::Int)]] r
assertEqual "string compare" [[SqlString "2"]] r
)
createTable = dbTestCase (\dbh ->
do run dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT)" []
commit dbh
)
dropTable = dbTestCase (\dbh ->
do run dbh "DROP TABLE hdbctest1" []
commit dbh
)
runReplace = dbTestCase (\dbh ->
do r <- run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
assertEqual "insert retval" 1 r
run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r2
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
rv2 <- execute sth []
assertEqual "select retval" 0 rv2
r <- fetchAllRows sth
assertEqual "" [r1, r2] r
)
where r1 = [toSql "runReplace", iToSql 1, iToSql 1234, SqlString "testdata"]
r2 = [toSql "runReplace", iToSql 2, iToSql 2, SqlNull]
executeReplace = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
execute sth [iToSql 1, iToSql 1234, toSql "Foo"]
execute sth [SqlInt32 2, SqlNull, toSql "Bar"]
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
execute sth [SqlString "executeReplace"]
r <- fetchAllRows sth
assertEqual "result"
[[toSql "executeReplace", iToSql 1, toSql "1234",
toSql "Foo"],
[toSql "executeReplace", iToSql 2, SqlNull,
toSql "Bar"]]
r
)
testExecuteMany = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
execute sth []
r <- fetchAllRows sth
assertEqual "" rows r
)
where rows = [map toSql ["1", "1234", "foo"],
map toSql ["2", "1341", "bar"],
[toSql "3", SqlNull, SqlNull]]
testFetchAllRows = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('fetchAllRows', ?, NULL, NULL)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'fetchAllRows' ORDER BY testid"
execute sth []
results <- fetchAllRows sth
assertEqual "" rows results
)
where rows = map (\x -> [iToSql x]) [1..9]
testFetchAllRows' = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('fetchAllRows2', ?, NULL, NULL)"
executeMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'fetchAllRows2' ORDER BY testid"
execute sth []
results <- fetchAllRows' sth
assertEqual "" rows results
)
where rows = map (\x -> [iToSql x]) [1..9]
basicTransactions = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
execute sth [iToSql 0]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
executeMany sth rows
rollback dbh
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "rollback" [[toSql "0"]])
executeMany sth rows
commit dbh
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "final commit" ([SqlString "0"]:rows))
)
where rows = map (\x -> [iToSql $ x]) [1..9]
testWithTransaction = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
execute sth [toSql "0"]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
catch (withTransaction dbh (\_ -> do executeMany sth rows
fail "Foo"))
(\_ -> return ())
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "rollback" [[SqlString "0"]])
withTransaction dbh (\_ -> executeMany sth rows)
execute qrysth []
fetchAllRows qrysth >>= (assertEqual "final commit" ([iToSql 0]:rows))
)
where rows = map (\x -> [iToSql x]) [1..9]
tests = TestList
[
TestLabel "openClosedb" openClosedb,
TestLabel "multiFinish" multiFinish,
TestLabel "basicQueries" basicQueries,
TestLabel "createTable" createTable,
TestLabel "runReplace" runReplace,
TestLabel "executeReplace" executeReplace,
TestLabel "executeMany" testExecuteMany,
TestLabel "fetchAllRows" testFetchAllRows,
TestLabel "fetchAllRows'" testFetchAllRows',
TestLabel "basicTransactions" basicTransactions,
TestLabel "withTransaction" testWithTransaction,
TestLabel "dropTable" dropTable
]
|
1a5c04d704c1e56f17035d903312764a8efb30eba6f959751a4767ed649cfaea | kindista/kindista | unsubscribe.lisp | Copyright 2012 - 2016 CommonGoods Network , Inc.
;;;
This file is part of Kindista .
;;;
Kindista 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.
;;;
Kindista 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 Kindista . If not , see < / > .
(in-package :kindista)
(defun updated-notifications-handler ()
(send-updated-notifications-confirmation-email (getf (cddddr *notice*)
:userid)
(getf (cddddr *notice*)
:groupid)))
(defun send-updated-notifications-confirmation-email (userid &optional groupid)
(let* ((user (db userid))
(group (db groupid))
(name (getf (or group user) :name))
(preferences (user-communication-preferences userid
:user user
:groupid groupid)))
(cl-smtp:send-email +mail-server+
"Kindista <>"
(car (getf user :emails))
"You have successfully updated your Kindista Communication Preferences"
(unsubscribe-confirmation-email-text (getf user :name)
preferences
(when group name))
:html-message (unsubscribe-confirmation-email-html
(getf user :name)
preferences
(when group name)))))
(defun user-communication-preferences
(userid
&key (user (db userid))
(groupid)
(group (db groupid))
(entity (or (getf group :name) "you"))
&aux (preferences))
(flet ((record-option (option text)
(if (if group
(find userid (getf group option))
(getf user option))
(asetf (getf preferences :subscribed)
(push text it))
(asetf (getf preferences :unsubscribed)
(push text it)))))
(record-option :notify-gratitude
(s+ "when someone posts gratitude about " entity))
(record-option :notify-inventory-expiration
(s+ "when " (if group
(s+ entity "'s")
"your")
" offers and requests are about to expire"))
(record-option :notify-message
(s+ "when someone sends "
entity
" a message or responds to "
(if group "its" "your")
" offers/requests"))
(unless group
(record-option :notify-expired-invites
"when invitatations you send for your friends to join Kindista expire" )
(record-option :notify-new-contact
"when someone sends you to their list of contacts")
(record-option :notify-group-membership-invites
"when someone invites you to join a group on Kindista (e.g. a business, non-profit, or other organization I belong to within my community)")
(record-option :notify-reminders
"occasional suggestions about how you can get the most out of Kindista")
(record-option :notify-kindista
"updates and information about Kindista"))
(when group
(record-option :notify-membership-request
(s+ "when someone wants to join "
entity
" on Kindista"))))
preferences)
(defun unsubscribe-confirmation-email-text (name preferences &optional groupname)
(strcat*
"Hi " name ","
#\linefeed #\linefeed
"You have successfully updated your Kindista communication preferences"
(when groupname (strcat " for " groupname))
"."
#\linefeed #\linefeed
(when (getf preferences :subscribed)
(strcat*
"You are currently subscribed to receive the following notifications from Kindista:"
(apply #'strcat*
(loop for item in (getf preferences :subscribed)
collect (strcat #\linefeed "- " item)))
#\linefeed #\linefeed))
(awhen (getf preferences :unsubscribed)
(strcat*
"You have opted out of receiving the following notifications from Kindista:"
(apply #'strcat*
(loop for item in (getf preferences :unsubscribed)
collect (strcat #\linefeed "- " item)))
#\linefeed #\linefeed))
"Please contact us immediately if you did not recently update your communication preferences "
"on Kindista and you believe this email was sent in error."
#\linefeed #\linefeed
"Thank you for sharing your gifts with us!"
#\linefeed
"-The Kindista Team"))
(defun unsubscribe-confirmation-email-html (name preferences &optional groupname)
(html-email-base
(html
(:p :style *style-p*
"Hi " (str name) ",")
(:p :style *style-p*
"You have sucessfully updated your Kindista communication preferences"
(when groupname
(htm " for " (:strong (str groupname))))
".")
(awhen (getf preferences :subscribed)
(htm
(:p :style *style-p*
"You are currently "
(:strong "subscribed")
" to receive the following notifications from Kindista:")
(:ul
(dolist (item (getf preferences :subscribed))
(htm (:li (str item)))))))
(awhen (getf preferences :unsubscribed)
(htm
(:p :style *style-p*
"You have "
(:strong "opted out")
" and "
(:strong "will not")
" be receiving the following notifications from Kindista:")
(:ul
(dolist (item (getf preferences :unsubscribed))
(htm (:li (str item)))))))
(:p :style *style-p*
"Please contact us immediately if you did not recently update your communication preferences "
"on Kindista and you believe this email was sent in error.")
(:p :style *style-p* "Thank you for sharing your gifts with us!")
(:p "-The Kindista Team"))))
| null | https://raw.githubusercontent.com/kindista/kindista/60da1325e628841721200aa00e4de5f9687c0adb/src/email/unsubscribe.lisp | lisp |
(at your option) any later version.
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
License for more details.
| Copyright 2012 - 2016 CommonGoods Network , Inc.
This file is part of Kindista .
Kindista 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
Kindista is distributed in the hope that it will be useful , but WITHOUT
You should have received a copy of the GNU Affero General Public License
along with Kindista . If not , see < / > .
(in-package :kindista)
(defun updated-notifications-handler ()
(send-updated-notifications-confirmation-email (getf (cddddr *notice*)
:userid)
(getf (cddddr *notice*)
:groupid)))
(defun send-updated-notifications-confirmation-email (userid &optional groupid)
(let* ((user (db userid))
(group (db groupid))
(name (getf (or group user) :name))
(preferences (user-communication-preferences userid
:user user
:groupid groupid)))
(cl-smtp:send-email +mail-server+
"Kindista <>"
(car (getf user :emails))
"You have successfully updated your Kindista Communication Preferences"
(unsubscribe-confirmation-email-text (getf user :name)
preferences
(when group name))
:html-message (unsubscribe-confirmation-email-html
(getf user :name)
preferences
(when group name)))))
(defun user-communication-preferences
(userid
&key (user (db userid))
(groupid)
(group (db groupid))
(entity (or (getf group :name) "you"))
&aux (preferences))
(flet ((record-option (option text)
(if (if group
(find userid (getf group option))
(getf user option))
(asetf (getf preferences :subscribed)
(push text it))
(asetf (getf preferences :unsubscribed)
(push text it)))))
(record-option :notify-gratitude
(s+ "when someone posts gratitude about " entity))
(record-option :notify-inventory-expiration
(s+ "when " (if group
(s+ entity "'s")
"your")
" offers and requests are about to expire"))
(record-option :notify-message
(s+ "when someone sends "
entity
" a message or responds to "
(if group "its" "your")
" offers/requests"))
(unless group
(record-option :notify-expired-invites
"when invitatations you send for your friends to join Kindista expire" )
(record-option :notify-new-contact
"when someone sends you to their list of contacts")
(record-option :notify-group-membership-invites
"when someone invites you to join a group on Kindista (e.g. a business, non-profit, or other organization I belong to within my community)")
(record-option :notify-reminders
"occasional suggestions about how you can get the most out of Kindista")
(record-option :notify-kindista
"updates and information about Kindista"))
(when group
(record-option :notify-membership-request
(s+ "when someone wants to join "
entity
" on Kindista"))))
preferences)
(defun unsubscribe-confirmation-email-text (name preferences &optional groupname)
(strcat*
"Hi " name ","
#\linefeed #\linefeed
"You have successfully updated your Kindista communication preferences"
(when groupname (strcat " for " groupname))
"."
#\linefeed #\linefeed
(when (getf preferences :subscribed)
(strcat*
"You are currently subscribed to receive the following notifications from Kindista:"
(apply #'strcat*
(loop for item in (getf preferences :subscribed)
collect (strcat #\linefeed "- " item)))
#\linefeed #\linefeed))
(awhen (getf preferences :unsubscribed)
(strcat*
"You have opted out of receiving the following notifications from Kindista:"
(apply #'strcat*
(loop for item in (getf preferences :unsubscribed)
collect (strcat #\linefeed "- " item)))
#\linefeed #\linefeed))
"Please contact us immediately if you did not recently update your communication preferences "
"on Kindista and you believe this email was sent in error."
#\linefeed #\linefeed
"Thank you for sharing your gifts with us!"
#\linefeed
"-The Kindista Team"))
(defun unsubscribe-confirmation-email-html (name preferences &optional groupname)
(html-email-base
(html
(:p :style *style-p*
"Hi " (str name) ",")
(:p :style *style-p*
"You have sucessfully updated your Kindista communication preferences"
(when groupname
(htm " for " (:strong (str groupname))))
".")
(awhen (getf preferences :subscribed)
(htm
(:p :style *style-p*
"You are currently "
(:strong "subscribed")
" to receive the following notifications from Kindista:")
(:ul
(dolist (item (getf preferences :subscribed))
(htm (:li (str item)))))))
(awhen (getf preferences :unsubscribed)
(htm
(:p :style *style-p*
"You have "
(:strong "opted out")
" and "
(:strong "will not")
" be receiving the following notifications from Kindista:")
(:ul
(dolist (item (getf preferences :unsubscribed))
(htm (:li (str item)))))))
(:p :style *style-p*
"Please contact us immediately if you did not recently update your communication preferences "
"on Kindista and you believe this email was sent in error.")
(:p :style *style-p* "Thank you for sharing your gifts with us!")
(:p "-The Kindista Team"))))
|
b942c7f7aae9a9f8175cd35fc3694e8ffe987243fbe5a879564f2d1434f8dd04 | MyDataFlow/ttalk-server | cluster_commands_SUITE.erl | %%==============================================================================
Copyright 2014 Erlang Solutions Ltd.
%%
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(cluster_commands_SUITE).
-compile(export_all).
-import(distributed_helper, [add_node_to_cluster/1,
remove_node_from_cluster/1,
is_sm_distributed/0]).
-import(ejabberdctl_helper, [ejabberdctl/3, rpc_call/3]).
-include_lib("common_test/include/ct.hrl").
%%--------------------------------------------------------------------
%% Suite configuration
%%--------------------------------------------------------------------
all() ->
[{group, clustered},
{group, ejabberdctl}].
groups() ->
[{clustered, [], [one_to_one_message]},
{ejabberdctl, [], [set_master_test]}].
suite() ->
escalus:suite().
%%--------------------------------------------------------------------
Init & teardown
%%--------------------------------------------------------------------
init_per_suite(Config) ->
Config1 = escalus:init_per_suite(Config),
Node = ct:get_config(ejabberd2_node),
Config2 = ejabberd_node_utils:init(Node, Config1),
ejabberd_node_utils:backup_config_file(Node, Config2),
MainDomain = ct:get_config(ejabberd_domain),
Ch = [{hosts, "[\"" ++ binary_to_list(MainDomain) ++ "\"]"}],
ejabberd_node_utils:modify_config_file(Node, "reltool_vars/node2_vars.config", Ch, Config2),
ejabberd_node_utils:call_ctl(Node, reload_local, Config2),
{ok, EjdWD} = escalus_ejabberd:rpc(file, get_cwd, []),
CtlPath = case filelib:is_file(EjdWD ++ "/bin/ejabberdctl") of
true -> EjdWD ++ "/bin/ejabberdctl";
false -> EjdWD ++ "/bin/mongooseimctl"
end,
escalus:init_per_suite([{ctl_path, CtlPath} | Config2]).
end_per_suite(Config) ->
Node = ct:get_config(ejabberd2_node),
ejabberd_node_utils:restore_config_file(Node, Config),
ejabberd_node_utils:restart_application(Node, ejabberd),
escalus:end_per_suite(Config).
init_per_group(Group, Config) when Group == clustered orelse Group == ejabberdctl ->
Config1 = add_node_to_cluster(Config),
case is_sm_distributed() of
true ->
escalus:create_users(Config1, {by_name, [alice, clusterguy]});
{false, Backend} ->
ct:pal("Backend ~p doesn't support distributed tests", [Backend]),
remove_node_from_cluster(Config1),
{skip, nondistributed_sm}
end;
init_per_group(_GroupName, Config) ->
escalus:create_users(Config).
end_per_group(Group, Config) when Group == clustered orelse Group == ejabberdctl ->
escalus:delete_users(Config, {by_name, [alice, clusterguy]}),
remove_node_from_cluster(Config);
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
%%--------------------------------------------------------------------
%% Message tests
%%--------------------------------------------------------------------
one_to_one_message(ConfigIn) ->
Given connected to node one and ClusterGuy connected to node two
Metrics = [{[data, dist], [{recv_oct, '>'}, {send_oct, '>'}]}],
Config = [{mongoose_metrics, Metrics} | ConfigIn],
escalus:story(Config, [{alice, 1}, {clusterguy, 1}], fun(Alice, ClusterGuy) ->
When sends a message to ClusterGuy
Msg1 = escalus_stanza:chat_to(ClusterGuy, <<"Hi!">>),
escalus:send(Alice, Msg1),
%% Then he receives it
Stanza1 = escalus:wait_for_stanza(ClusterGuy, 5000),
escalus:assert(is_chat_message, [<<"Hi!">>], Stanza1),
When ClusterGuy sends a response
Msg2 = escalus_stanza:chat_to(Alice, <<"Oh hi!">>),
escalus:send(ClusterGuy, Msg2),
Then also receives it
Stanza2 = escalus:wait_for_stanza(Alice, 5000),
escalus:assert(is_chat_message, [<<"Oh hi!">>], Stanza2)
end).
%%--------------------------------------------------------------------
Ejabberdctl tests
%%--------------------------------------------------------------------
set_master_test(ConfigIn) ->
TableName = passwd,
NodeList = nodes(),
ejabberdctl("set_master", ["self"], ConfigIn),
[MasterNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]),
true = lists:member(MasterNode, NodeList),
RestNodesList = lists:delete(MasterNode, NodeList),
OtherNode = hd(RestNodesList),
ejabberdctl("set_master", [atom_to_list(OtherNode)], ConfigIn),
[OtherNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]),
ejabberdctl("set_master", ["self"], ConfigIn),
[MasterNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/test/ejabberd_tests/tests/cluster_commands_SUITE.erl | erlang | ==============================================================================
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
--------------------------------------------------------------------
Suite configuration
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Message tests
--------------------------------------------------------------------
Then he receives it
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright 2014 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(cluster_commands_SUITE).
-compile(export_all).
-import(distributed_helper, [add_node_to_cluster/1,
remove_node_from_cluster/1,
is_sm_distributed/0]).
-import(ejabberdctl_helper, [ejabberdctl/3, rpc_call/3]).
-include_lib("common_test/include/ct.hrl").
all() ->
[{group, clustered},
{group, ejabberdctl}].
groups() ->
[{clustered, [], [one_to_one_message]},
{ejabberdctl, [], [set_master_test]}].
suite() ->
escalus:suite().
Init & teardown
init_per_suite(Config) ->
Config1 = escalus:init_per_suite(Config),
Node = ct:get_config(ejabberd2_node),
Config2 = ejabberd_node_utils:init(Node, Config1),
ejabberd_node_utils:backup_config_file(Node, Config2),
MainDomain = ct:get_config(ejabberd_domain),
Ch = [{hosts, "[\"" ++ binary_to_list(MainDomain) ++ "\"]"}],
ejabberd_node_utils:modify_config_file(Node, "reltool_vars/node2_vars.config", Ch, Config2),
ejabberd_node_utils:call_ctl(Node, reload_local, Config2),
{ok, EjdWD} = escalus_ejabberd:rpc(file, get_cwd, []),
CtlPath = case filelib:is_file(EjdWD ++ "/bin/ejabberdctl") of
true -> EjdWD ++ "/bin/ejabberdctl";
false -> EjdWD ++ "/bin/mongooseimctl"
end,
escalus:init_per_suite([{ctl_path, CtlPath} | Config2]).
end_per_suite(Config) ->
Node = ct:get_config(ejabberd2_node),
ejabberd_node_utils:restore_config_file(Node, Config),
ejabberd_node_utils:restart_application(Node, ejabberd),
escalus:end_per_suite(Config).
init_per_group(Group, Config) when Group == clustered orelse Group == ejabberdctl ->
Config1 = add_node_to_cluster(Config),
case is_sm_distributed() of
true ->
escalus:create_users(Config1, {by_name, [alice, clusterguy]});
{false, Backend} ->
ct:pal("Backend ~p doesn't support distributed tests", [Backend]),
remove_node_from_cluster(Config1),
{skip, nondistributed_sm}
end;
init_per_group(_GroupName, Config) ->
escalus:create_users(Config).
end_per_group(Group, Config) when Group == clustered orelse Group == ejabberdctl ->
escalus:delete_users(Config, {by_name, [alice, clusterguy]}),
remove_node_from_cluster(Config);
end_per_group(_GroupName, Config) ->
escalus:delete_users(Config).
init_per_testcase(CaseName, Config) ->
escalus:init_per_testcase(CaseName, Config).
end_per_testcase(CaseName, Config) ->
escalus:end_per_testcase(CaseName, Config).
one_to_one_message(ConfigIn) ->
Given connected to node one and ClusterGuy connected to node two
Metrics = [{[data, dist], [{recv_oct, '>'}, {send_oct, '>'}]}],
Config = [{mongoose_metrics, Metrics} | ConfigIn],
escalus:story(Config, [{alice, 1}, {clusterguy, 1}], fun(Alice, ClusterGuy) ->
When sends a message to ClusterGuy
Msg1 = escalus_stanza:chat_to(ClusterGuy, <<"Hi!">>),
escalus:send(Alice, Msg1),
Stanza1 = escalus:wait_for_stanza(ClusterGuy, 5000),
escalus:assert(is_chat_message, [<<"Hi!">>], Stanza1),
When ClusterGuy sends a response
Msg2 = escalus_stanza:chat_to(Alice, <<"Oh hi!">>),
escalus:send(ClusterGuy, Msg2),
Then also receives it
Stanza2 = escalus:wait_for_stanza(Alice, 5000),
escalus:assert(is_chat_message, [<<"Oh hi!">>], Stanza2)
end).
Ejabberdctl tests
set_master_test(ConfigIn) ->
TableName = passwd,
NodeList = nodes(),
ejabberdctl("set_master", ["self"], ConfigIn),
[MasterNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]),
true = lists:member(MasterNode, NodeList),
RestNodesList = lists:delete(MasterNode, NodeList),
OtherNode = hd(RestNodesList),
ejabberdctl("set_master", [atom_to_list(OtherNode)], ConfigIn),
[OtherNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]),
ejabberdctl("set_master", ["self"], ConfigIn),
[MasterNode] = rpc_call(mnesia, table_info, [TableName, master_nodes]).
|
327306f2106fc0010e858c8aff5d59d9d01735ac30f48c62c6a98c70a1e12e79 | andy128k/cl-gobject-introspection | gui.lisp | (in-package :flood-game-example)
(defvar *glib* (gir:require-namespace "GLib"))
(defvar *gtk* (gir:require-namespace "Gtk" "3.0"))
(defmacro with-gtk-event-loop=window+drawing-area
((window-symbol drawing-area-symbol
&key
protected-final-code
(window-title "Untitled"))
&body code)
(let ((code `((gir:invoke (*gtk* 'init) nil)
(let ((,window-symbol (gir:invoke (*gtk* "Window" 'new)
(gir:nget *gtk*
"WindowType"
:toplevel)))
(,drawing-area-symbol (gir:invoke (*gtk* "DrawingArea"
'new))))
(setf (gir:property ,window-symbol 'title)
,window-title)
(gir:invoke (,window-symbol "set_default_size")
900 900)
(gir:connect ,window-symbol :destroy
(lambda (win)
(declare (ignore win))
(gir:invoke (*gtk* 'main-quit))))
,@code
(gir:invoke (,window-symbol 'add)
,drawing-area-symbol)
(gir:invoke (,window-symbol 'show-all))
(gir:invoke (*gtk* 'main))
(null ,window-symbol)))))
(if protected-final-code
`(unwind-protect (progn ,@code)
,@protected-final-code)
`(progn ,@code))))
(defmacro with-area-drawer-form ((drawing-area context-bind
&optional (drawing-area-bind
(gensym "DRAWING-AREA-")
drawing-area-bind-p))
&body code)
(let ((context-ptr-sym (gensym "CONTEXT-POINTER-"))
(size-requesters (list (gensym "WIDTH-REQUESTER-")
(gensym "HEIGHT-REQUESTER-"))))
(flet (($size-setting-form (&rest hwlist)
(mapcan (lambda (sym requester)
(list sym `(funcall ,requester)))
hwlist
size-requesters)))
`(let (,context-bind
,@(mapcar (lambda (gir-method size-requester)
`(,size-requester (gir:nget ,drawing-area
,gir-method)))
'("get_allocated_width"
"get_allocated_height")
size-requesters))
(lambda (,drawing-area-bind ,context-ptr-sym)
,@(unless drawing-area-bind-p
`((declare (ignore ,drawing-area-bind))))
(if ,context-bind
(with-slots ((h cairo:height)
(w cairo:width))
,context-bind
(setf ,@($size-setting-form 'w 'h)))
(setf ,context-bind
(make-instance 'cairo:context
:pointer ,context-ptr-sym
,@($size-setting-form
:width
:height))))
(cairo:with-context (,context-bind)
,@code))))))
(cffi:defcallback timeout-func :boolean ((data :pointer))
(funcall (gir:trampoline-get-function data)))
(defun gtk-window-with-cairo-painting (drawer)
(let ((timeout-id nil))
(with-gtk-event-loop=window+drawing-area
(window drawing-area
:window-title "Flood game example"
:protected-final-code
((when timeout-id
(gir:invoke (*glib* 'source-remove) timeout-id))))
(gir:connect window :realize
(lambda (window)
(flet (($redraw ()
(gir:invoke (window :queue-draw))
t))
(setf timeout-id
(gir:invoke (*glib* 'timeout-add)
0
300
(cffi:callback timeout-func)
(gir:make-trampoline #'$redraw)
(cffi:callback gir:destroy-trampoline))))))
(gir:connect drawing-area :draw
(with-area-drawer-form (drawing-area context)
drawing-area
(funcall drawer context))))))
| null | https://raw.githubusercontent.com/andy128k/cl-gobject-introspection/13f7ea0c4b33ec0f91eed5131d271dc74f6ea3d2/examples/flood-game/src/gui.lisp | lisp | (in-package :flood-game-example)
(defvar *glib* (gir:require-namespace "GLib"))
(defvar *gtk* (gir:require-namespace "Gtk" "3.0"))
(defmacro with-gtk-event-loop=window+drawing-area
((window-symbol drawing-area-symbol
&key
protected-final-code
(window-title "Untitled"))
&body code)
(let ((code `((gir:invoke (*gtk* 'init) nil)
(let ((,window-symbol (gir:invoke (*gtk* "Window" 'new)
(gir:nget *gtk*
"WindowType"
:toplevel)))
(,drawing-area-symbol (gir:invoke (*gtk* "DrawingArea"
'new))))
(setf (gir:property ,window-symbol 'title)
,window-title)
(gir:invoke (,window-symbol "set_default_size")
900 900)
(gir:connect ,window-symbol :destroy
(lambda (win)
(declare (ignore win))
(gir:invoke (*gtk* 'main-quit))))
,@code
(gir:invoke (,window-symbol 'add)
,drawing-area-symbol)
(gir:invoke (,window-symbol 'show-all))
(gir:invoke (*gtk* 'main))
(null ,window-symbol)))))
(if protected-final-code
`(unwind-protect (progn ,@code)
,@protected-final-code)
`(progn ,@code))))
(defmacro with-area-drawer-form ((drawing-area context-bind
&optional (drawing-area-bind
(gensym "DRAWING-AREA-")
drawing-area-bind-p))
&body code)
(let ((context-ptr-sym (gensym "CONTEXT-POINTER-"))
(size-requesters (list (gensym "WIDTH-REQUESTER-")
(gensym "HEIGHT-REQUESTER-"))))
(flet (($size-setting-form (&rest hwlist)
(mapcan (lambda (sym requester)
(list sym `(funcall ,requester)))
hwlist
size-requesters)))
`(let (,context-bind
,@(mapcar (lambda (gir-method size-requester)
`(,size-requester (gir:nget ,drawing-area
,gir-method)))
'("get_allocated_width"
"get_allocated_height")
size-requesters))
(lambda (,drawing-area-bind ,context-ptr-sym)
,@(unless drawing-area-bind-p
`((declare (ignore ,drawing-area-bind))))
(if ,context-bind
(with-slots ((h cairo:height)
(w cairo:width))
,context-bind
(setf ,@($size-setting-form 'w 'h)))
(setf ,context-bind
(make-instance 'cairo:context
:pointer ,context-ptr-sym
,@($size-setting-form
:width
:height))))
(cairo:with-context (,context-bind)
,@code))))))
(cffi:defcallback timeout-func :boolean ((data :pointer))
(funcall (gir:trampoline-get-function data)))
(defun gtk-window-with-cairo-painting (drawer)
(let ((timeout-id nil))
(with-gtk-event-loop=window+drawing-area
(window drawing-area
:window-title "Flood game example"
:protected-final-code
((when timeout-id
(gir:invoke (*glib* 'source-remove) timeout-id))))
(gir:connect window :realize
(lambda (window)
(flet (($redraw ()
(gir:invoke (window :queue-draw))
t))
(setf timeout-id
(gir:invoke (*glib* 'timeout-add)
0
300
(cffi:callback timeout-func)
(gir:make-trampoline #'$redraw)
(cffi:callback gir:destroy-trampoline))))))
(gir:connect drawing-area :draw
(with-area-drawer-form (drawing-area context)
drawing-area
(funcall drawer context))))))
|
|
b479a199c5f8595ab076fc4845edff8386968e6de3dea287870f6b1e2a195654 | nmaehlmann/mallRL | TileImage.hs | module TileImage where
import Data.Array
import SDL.Vect
import Foreign.C.Types
import Data.Word
import Position
type Glyph = (V2 CInt)
type Color = V3 Word8
data Tile = Tile Glyph Color Color
deriving (Show, Eq)
data TileImage = TileImage (Array Position Tile)
deriving (Eq) | null | https://raw.githubusercontent.com/nmaehlmann/mallRL/1ae9add37ee390d645e380b77694d868a90fa70c/app/TileImage.hs | haskell | module TileImage where
import Data.Array
import SDL.Vect
import Foreign.C.Types
import Data.Word
import Position
type Glyph = (V2 CInt)
type Color = V3 Word8
data Tile = Tile Glyph Color Color
deriving (Show, Eq)
data TileImage = TileImage (Array Position Tile)
deriving (Eq) |
|
197d78e47bf01dca49d12f9a52122586f84849d8e342a1c33c89da1bc73e49e7 | puppetlabs/puppetserver | puppet_server_config.clj | (ns puppetlabs.services.protocols.puppet-server-config)
(defprotocol PuppetServerConfigService
"The configuration service for puppetserver. This is built on top of
Trapperkeeper's normal configuration service. It adds a few features -
most importantly, it merges in settings from the Puppet's 'settings' in ruby.
It also adds a set of required configuration values and validates them
during service initialization.
Note that this is an exact copy of the API from Trapperkeeper's built-in
configuration service's."
(get-config [this]
"Returns a map containing all of the configuration values")
(get-in-config [this ks] [this ks default]
"Returns the individual configuration value from the nested
configuration structure, where ks is a sequence of keys.
Returns nil if the key is not present, or the default value if
supplied."))
| null | https://raw.githubusercontent.com/puppetlabs/puppetserver/2d6ca01b4b72716ca543b606f752261b969e401b/src/clj/puppetlabs/services/protocols/puppet_server_config.clj | clojure | (ns puppetlabs.services.protocols.puppet-server-config)
(defprotocol PuppetServerConfigService
"The configuration service for puppetserver. This is built on top of
Trapperkeeper's normal configuration service. It adds a few features -
most importantly, it merges in settings from the Puppet's 'settings' in ruby.
It also adds a set of required configuration values and validates them
during service initialization.
Note that this is an exact copy of the API from Trapperkeeper's built-in
configuration service's."
(get-config [this]
"Returns a map containing all of the configuration values")
(get-in-config [this ks] [this ks default]
"Returns the individual configuration value from the nested
configuration structure, where ks is a sequence of keys.
Returns nil if the key is not present, or the default value if
supplied."))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.