_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 |
|---|---|---|---|---|---|---|---|---|
df5e3e6b30d1118728ef1333975def2d5aa079271267047b0a065e7d7faa34d9 | adomokos/haskell-katas | Ex41_FaApplicativesSpec.hs | module Ex41_FaApplicativesSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
{-
functor definition
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
Applicative instance implementation for Maybe
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
(<$>) :: (Functor f) => (a -> b) -> f a -> f b
f <$> x = fmap f x
-}
spec :: Spec
spec =
describe "Applicative" $ do
it "applies function inside the Just" $ do pending
-- Hint: use lambda expression
-- (fmap (___)) (fmap (*) (Just 3))
` shouldBe ` ( Just 6 )
_ _ _ < $ > _ _ _ < * > Just 3 ` shouldBe ` Just 6
it "applies function in list" $ do pending
-- let a = fmap ___ ___
fmap ( \f - > f 9 ) a ` shouldBe ` [ 9,18,27,36 ]
it "works with Maybe" $ do pending
_ _ _ _ _ _ < * > Just 9
` shouldBe ` Just 12
-- pure (___) <*> Just ___
` shouldBe ` Just 13
-- Just (++"hahah") <*> ___
` shouldBe ` Nothing
-- ___ <*> Just "woot"
` shouldBe ` ( Nothing : : Maybe String )
it "operates on several functors with a single function" $ do pending
pure ( _ _ _ ) < * > Just _ _ _ < * > Just 5
` shouldBe ` Just 8
-- pure (+) <*> Just ___ <*> ___
` shouldBe ` ( Nothing : : Maybe Int )
it "can use <$> as fmap with an infix operator" $ do pending
-- (___) <$> Just ___ <*> Just "volta"
` shouldBe ` Just " johntravolta "
( _ _ _ ) " johntra " " " ` shouldBe ` " johntravolta "
it "works with a list of functions" $ do pending
-- [___] <*> [1,2,3]
` shouldBe ` [ 0,0,0,101,102,103,1,4,9 ]
[ ( _ ) , ( _ ) ] < * > [ 1,2 ] < * > [ 3,4 ]
` shouldBe ` [ 4,5,5,6,3,4,6,8 ]
it "can be used as a replacement for list comprehensions" $ do pending
example ...
[ x*y | x < - [ 2,5,10 ] , y < - [ 8,10,11 ] ]
` shouldBe ` [ 16,20,22,40,50,55,80,100,110 ]
[x*y | x <- [2,5,10], y <- [8,10,11]]
`shouldBe` [16,20,22,40,50,55,80,100,110] -}
-- (___) <$> [___] <*> [___]
` shouldBe ` [ 16,20,22,40,50,55,80,100,110 ]
Keep only the values that are greater than 50 of the product
( filter ( _ _ _ ) $ ( _ _ _ ) < $ > [ 2,5,10 ] < * > [ 8,10,11 ] )
` shouldBe ` [ 55,80,100,110 ]
| null | https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Ex41_FaApplicativesSpec.hs | haskell |
functor definition
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
Applicative instance implementation for Maybe
instance Applicative Maybe where
pure = Just
Nothing <*> _ = Nothing
(Just f) <*> something = fmap f something
(<$>) :: (Functor f) => (a -> b) -> f a -> f b
f <$> x = fmap f x
Hint: use lambda expression
(fmap (___)) (fmap (*) (Just 3))
let a = fmap ___ ___
pure (___) <*> Just ___
Just (++"hahah") <*> ___
___ <*> Just "woot"
pure (+) <*> Just ___ <*> ___
(___) <$> Just ___ <*> Just "volta"
[___] <*> [1,2,3]
(___) <$> [___] <*> [___] | module Ex41_FaApplicativesSpec
( spec
) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "Applicative" $ do
it "applies function inside the Just" $ do pending
` shouldBe ` ( Just 6 )
_ _ _ < $ > _ _ _ < * > Just 3 ` shouldBe ` Just 6
it "applies function in list" $ do pending
fmap ( \f - > f 9 ) a ` shouldBe ` [ 9,18,27,36 ]
it "works with Maybe" $ do pending
_ _ _ _ _ _ < * > Just 9
` shouldBe ` Just 12
` shouldBe ` Just 13
` shouldBe ` Nothing
` shouldBe ` ( Nothing : : Maybe String )
it "operates on several functors with a single function" $ do pending
pure ( _ _ _ ) < * > Just _ _ _ < * > Just 5
` shouldBe ` Just 8
` shouldBe ` ( Nothing : : Maybe Int )
it "can use <$> as fmap with an infix operator" $ do pending
` shouldBe ` Just " johntravolta "
( _ _ _ ) " johntra " " " ` shouldBe ` " johntravolta "
it "works with a list of functions" $ do pending
` shouldBe ` [ 0,0,0,101,102,103,1,4,9 ]
[ ( _ ) , ( _ ) ] < * > [ 1,2 ] < * > [ 3,4 ]
` shouldBe ` [ 4,5,5,6,3,4,6,8 ]
it "can be used as a replacement for list comprehensions" $ do pending
example ...
[ x*y | x < - [ 2,5,10 ] , y < - [ 8,10,11 ] ]
` shouldBe ` [ 16,20,22,40,50,55,80,100,110 ]
[x*y | x <- [2,5,10], y <- [8,10,11]]
`shouldBe` [16,20,22,40,50,55,80,100,110] -}
` shouldBe ` [ 16,20,22,40,50,55,80,100,110 ]
Keep only the values that are greater than 50 of the product
( filter ( _ _ _ ) $ ( _ _ _ ) < $ > [ 2,5,10 ] < * > [ 8,10,11 ] )
` shouldBe ` [ 55,80,100,110 ]
|
f46fdcc20e46b49f5a968a18951966c337319a5945aaefd73df7de2b77bb71fc | bendyworks/api-server | UserSpec.hs | # LANGUAGE QuasiQuotes #
module Api.Controllers.UserSpec (main, spec) where
import Control.Applicative ((<$>))
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromJust)
import Data.Monoid ((<>))
import Hasql (q, single)
import Api.Mappers.Resource as Resource
import Api.Mappers.User as User
import Api.Mappers.PendingUserResource as Pending
import Api.Types.Resource
import Api.Types.Fields
import Api.Types.PendingUserResource
import Api.Types.User
import Network.HTTP.Types
import SpecHelper
import Test.Hspec hiding (shouldBe, shouldSatisfy, pendingWith)
import Test.Hspec.Wai hiding (request)
main :: IO ()
main = hspec spec
spec :: Spec
spec = before resetDb $ withApiApp $ do
describe "POST /users" $ do
let request = SRequest
{ method = POST
, route = "/users"
, headers = []
, params = [] }
it "returns a user's Login via JSON" $ withQuery $ \query -> do
responseWithLogin <- sendReq request
let login = fromJsonBody responseWithLogin
(UserID uid) = login_userId login
users <- liftIO $ query $ single $
[q| SELECT COUNT(id) FROM users WHERE id = ? |] uid
return responseWithLogin `shouldRespondWith` 200
fromJust users `shouldBe` Identity (1 :: Int)
describe "GET /verify/:uuid" $ do
let request = SRequest
{ method = GET
, route = "/verify/xxx"
, headers = []
, params = [] }
context "UUID references an existing PendingUserResource" $ do
context "Email of PendingUserResource doesn't match an existing resource" $
it "connects the User with a new Resource" $ withQuery $ \query -> do
let email = ResourceEmail $ mockEmail ""
(login, pend) <- liftIO $ query $ do
login <- fromJust <$> User.insert
pend <- fromJust <$> Pending.insert (PendingUCFields (login_userId login) email)
return (login, pend)
let success200 = request { route = "/verify/" <> toBytes (pend_uuid pend) }
sendReq success200 `shouldRespondWith` 200
(newRes, delPend, user) <- liftIO $ query $ do
delPend <- Pending.findByUuid (pend_uuid pend)
newRes <- fromJust <$> Resource.findByEmail email
user <- fromJust <$> User.findByLogin login
return (newRes, delPend, user)
delPend `shouldBe` Nothing
user_resourceId user `shouldBe` Just (res_id newRes)
context "Email of PendingUserResource matches an existing resource" $
it "connects the User to the existing Resource" $ withQuery $ \query -> do
(login, pend, resource) <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
let fields = PendingUCFields (login_userId login) (res_email mockResFields)
pend <- fromJust <$> Pending.insert fields
return (login, pend, resource)
let success200 = request { route = "/verify/" <> toBytes (pend_uuid pend) }
sendReq success200 `shouldRespondWith` 200
user <- liftIO $ query $ fromJust <$> User.findByLogin login
user_resourceId user `shouldBe` Just (res_id resource)
context "UUID doesn't reference an existing PendingUserResource" $
it "returns a 404" $
sendReq request `shouldRespondWith` 404
describe "POST /users/:user_id" $ do
let request = SRequest
{ method = POST
, route = "/users/1"
, headers = []
, params = [] }
context "without an authenticated user" $
it "returns a 401" $
sendReq request `shouldRespondWith` 401
context "with an authenticated user" $ do
context "without valid params" $ do
it "returns a 422 with invalid params" $ withQuery $ \query -> do
login <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return login
let malformed422 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [ authParam login
, ("resource", "invalid_email")
] }
sendReq malformed422 `shouldRespondWith` 422
it "returns a 422 with missing params" $ withQuery $ \query -> do
login <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return login
let malformed422 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [authParam login] }
sendReq malformed422 `shouldRespondWith` 422
context "with valid params" $ do
it "creates a new PendingUserResource" $ withQuery $ \query -> do
(login, resource) <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return (login, resource)
let success200 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [ authParam login
, ("resource_email", toBytes . res_email $ res_fields resource)
] }
sendReq success200 `shouldRespondWith` 200
count <- liftIO $ query $ single [q| SELECT COUNT(id) from pending_user_resources |]
fromJust count `shouldBe` Identity (1 :: Int)
it "sends a verification email with a PendingUUID" $
pendingWith "need way to test mailer contents"
| null | https://raw.githubusercontent.com/bendyworks/api-server/9dd6d7c2599bd1c5a7e898a417a7aeb319415dd2/test/Api/Controllers/UserSpec.hs | haskell | # LANGUAGE QuasiQuotes #
module Api.Controllers.UserSpec (main, spec) where
import Control.Applicative ((<$>))
import Data.Functor.Identity (Identity (..))
import Data.Maybe (fromJust)
import Data.Monoid ((<>))
import Hasql (q, single)
import Api.Mappers.Resource as Resource
import Api.Mappers.User as User
import Api.Mappers.PendingUserResource as Pending
import Api.Types.Resource
import Api.Types.Fields
import Api.Types.PendingUserResource
import Api.Types.User
import Network.HTTP.Types
import SpecHelper
import Test.Hspec hiding (shouldBe, shouldSatisfy, pendingWith)
import Test.Hspec.Wai hiding (request)
main :: IO ()
main = hspec spec
spec :: Spec
spec = before resetDb $ withApiApp $ do
describe "POST /users" $ do
let request = SRequest
{ method = POST
, route = "/users"
, headers = []
, params = [] }
it "returns a user's Login via JSON" $ withQuery $ \query -> do
responseWithLogin <- sendReq request
let login = fromJsonBody responseWithLogin
(UserID uid) = login_userId login
users <- liftIO $ query $ single $
[q| SELECT COUNT(id) FROM users WHERE id = ? |] uid
return responseWithLogin `shouldRespondWith` 200
fromJust users `shouldBe` Identity (1 :: Int)
describe "GET /verify/:uuid" $ do
let request = SRequest
{ method = GET
, route = "/verify/xxx"
, headers = []
, params = [] }
context "UUID references an existing PendingUserResource" $ do
context "Email of PendingUserResource doesn't match an existing resource" $
it "connects the User with a new Resource" $ withQuery $ \query -> do
let email = ResourceEmail $ mockEmail ""
(login, pend) <- liftIO $ query $ do
login <- fromJust <$> User.insert
pend <- fromJust <$> Pending.insert (PendingUCFields (login_userId login) email)
return (login, pend)
let success200 = request { route = "/verify/" <> toBytes (pend_uuid pend) }
sendReq success200 `shouldRespondWith` 200
(newRes, delPend, user) <- liftIO $ query $ do
delPend <- Pending.findByUuid (pend_uuid pend)
newRes <- fromJust <$> Resource.findByEmail email
user <- fromJust <$> User.findByLogin login
return (newRes, delPend, user)
delPend `shouldBe` Nothing
user_resourceId user `shouldBe` Just (res_id newRes)
context "Email of PendingUserResource matches an existing resource" $
it "connects the User to the existing Resource" $ withQuery $ \query -> do
(login, pend, resource) <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
let fields = PendingUCFields (login_userId login) (res_email mockResFields)
pend <- fromJust <$> Pending.insert fields
return (login, pend, resource)
let success200 = request { route = "/verify/" <> toBytes (pend_uuid pend) }
sendReq success200 `shouldRespondWith` 200
user <- liftIO $ query $ fromJust <$> User.findByLogin login
user_resourceId user `shouldBe` Just (res_id resource)
context "UUID doesn't reference an existing PendingUserResource" $
it "returns a 404" $
sendReq request `shouldRespondWith` 404
describe "POST /users/:user_id" $ do
let request = SRequest
{ method = POST
, route = "/users/1"
, headers = []
, params = [] }
context "without an authenticated user" $
it "returns a 401" $
sendReq request `shouldRespondWith` 401
context "with an authenticated user" $ do
context "without valid params" $ do
it "returns a 422 with invalid params" $ withQuery $ \query -> do
login <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return login
let malformed422 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [ authParam login
, ("resource", "invalid_email")
] }
sendReq malformed422 `shouldRespondWith` 422
it "returns a 422 with missing params" $ withQuery $ \query -> do
login <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return login
let malformed422 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [authParam login] }
sendReq malformed422 `shouldRespondWith` 422
context "with valid params" $ do
it "creates a new PendingUserResource" $ withQuery $ \query -> do
(login, resource) <- liftIO $ query $ do
login <- fromJust <$> User.insert
resource <- fromJust <$> Resource.insert mockResFields
_ <- User.update $ User (login_userId login) (Just $ res_id resource)
return (login, resource)
let success200 = request
{ route = "/users/" <> toBytes (login_userId login)
, headers = [authHeader login, formHeader]
, params = [ authParam login
, ("resource_email", toBytes . res_email $ res_fields resource)
] }
sendReq success200 `shouldRespondWith` 200
count <- liftIO $ query $ single [q| SELECT COUNT(id) from pending_user_resources |]
fromJust count `shouldBe` Identity (1 :: Int)
it "sends a verification email with a PendingUUID" $
pendingWith "need way to test mailer contents"
| |
2b87149b8d3e1437159b3270646326e623fd1ad40e7530d1fc281ae18af5f757 | mpelleau/AbSolute | apron_domain.ml | open Csp
open Tools
open Apron
open Apronext
let scalar_mul_sqrt2 =
let sqrt2_mpqf = Scalarext.of_float 0.707106781186548 in
fun s -> Scalarext.mul s sqrt2_mpqf
type point = float array
Compute the square of the euclidian distance between two points .
let sq_dist p1 p2 =
let sum = ref 0. in
Array.iter2 (fun a b -> sum := !sum +. ((a -. b) ** 2.)) p1 p2 ;
!sum
(* compute the most distant pair of points of an array of points, and the
corresponding distance*)
let most_distant_pair (pts : point array) : point * point * float =
fold_on_combination_2
(fun ((_, _, dist) as old) p1 p2 ->
let dist' = sq_dist p1 p2 in
if dist' > dist then (p1, p2, dist') else old)
(pts.(0), pts.(0), 0.)
pts
module type ADomain = sig
type t
val manager_alloc : unit -> t Manager.t
end
(* Translation functor for csp.prog to apron values*)
module SyntaxTranslator (D : ADomain) = struct
type internal_constr = Tcons1.t
let man = D.manager_alloc ()
let of_expr env (e : Expr.t) : Texpr1.t =
let open Expr in
let rec aux = function
| Funcall (name, args) -> (
match (name, args) with
| "sqrt", [x] -> Texprext.sqrt (aux x)
| name, _ -> fail_fmt "%s not supported by apron" name )
| Var v -> Texprext.var env (Var.of_string v)
| Cst c -> Texprext.cst env (Coeff.s_of_mpqf c)
| Neg e -> Texprext.neg (aux e)
| Binary (o, e1, e2) ->
( match o with
| ADD -> Texprext.add
| SUB -> Texprext.sub
| DIV -> Texprext.div
| MUL -> Texprext.mul
| POW -> Texprext.pow )
(aux e1) (aux e2)
in
aux e
let of_cmp_expr elem (e1, op, e2) =
let env = Abstract1.env elem in
let open Constraint in
let e1 = of_expr env e1 and e2 = of_expr env e2 in
match op with
| EQ -> Tconsext.eq e1 e2
| NEQ -> Tconsext.diseq e1 e2
| GEQ -> Tconsext.geq e1 e2
| GT -> Tconsext.gt e1 e2
| LEQ -> Tconsext.leq e1 e2
| LT -> Tconsext.lt e1 e2
let apron_to_var abs =
let env = Abstract1.env abs in
let iv, rv = Environment.vars env in
let ivars = Array.map Var.to_string iv in
let rvars = Array.map Var.to_string rv in
(Array.to_list ivars, Array.to_list rvars)
let rec to_expr = function
| Texpr1.Cst c -> Expr.of_mpqf (Coeffext.to_mpqf c)
| Texpr1.Var v -> Expr.var (Var.to_string v)
| Texpr1.Unop (Texpr1.Sqrt, e, _, _) -> Expr.Funcall ("sqrt", [to_expr e])
| Texpr1.Unop (Texpr1.Neg, e, _, _) -> Expr.Neg (to_expr e)
| Texpr1.Unop (Texpr1.Cast, _, _, _) -> failwith "cast should not occur"
| Texpr1.Binop (op, e1, e2, _, _) ->
let o =
match op with
| Texpr1.Add -> Expr.ADD
| Texpr1.Sub -> Expr.SUB
| Texpr1.Mul -> Expr.MUL
| Texpr1.Pow -> Expr.POW
| Texpr1.Div -> Expr.DIV
| Texpr1.Mod -> failwith "Mod not yet supported with AbSolute"
in
Binary (o, to_expr e1, to_expr e2)
let apron_to_bexpr tcons =
let apron_to_cmp op =
match op with
| Tcons1.EQ -> Constraint.EQ
| Tcons1.DISEQ -> Constraint.NEQ
| Tcons1.SUPEQ -> Constraint.GEQ
| Tcons1.SUP -> Constraint.GT
| _ -> failwith "operation not yet supported with AbSolute"
in
let typ = apron_to_cmp (Tcons1.get_typ tcons) in
let exp = to_expr (Texpr1.to_expr (Tcons1.get_texpr1 tcons)) in
(exp, typ, Expr.zero)
let to_constraint abs : Constraint.t =
let cons = Abstractext.to_tcons_array man abs in
let l = Tcons1.array_length cons in
let rec loop acc i =
if i = l then acc
else
loop
(Constraint.And (acc, Cmp (apron_to_bexpr (Tcons1.array_get cons i))))
(i + 1)
in
loop (Constraint.Cmp (Tcons1.array_get cons 0 |> apron_to_bexpr)) 1
end
(*****************************************************************)
(* Some types and values that all the domains of apron can share *)
(* These are generic and can be redefined in the actuals domains *)
(*****************************************************************)
module Make (AP : ADomain) = struct
module A = Abstractext
module E = Environmentext
type t = AP.t A.t
include SyntaxTranslator (AP)
let empty = A.top man E.empty
let internalize ?elem c =
match elem with
| None ->
invalid_arg
"apron constraint conversion requires an abstract element to setup \
the environment"
| Some e -> of_cmp_expr e c
let externalize = apron_to_bexpr
let vars abs =
let iv, rv = E.vars (A.env abs) in
let iv = Array.fold_left (fun a v -> (Int, Var.to_string v) :: a) [] iv in
Array.fold_left (fun a v -> (Real, Var.to_string v) :: a) iv rv
let dom_to_texpr env =
let open Dom in
function
| Top -> assert false
| Finite (b1, b2) -> Texpr1.cst env (Coeff.i_of_mpqf b1 b2)
| Minf _ -> assert false
| Inf _ -> assert false
| Set _ -> assert false
let add_var abs (typ, v, dom) =
let e = A.env abs in
let e' = if typ = Int then E.add_int_s v e else E.add_real_s v e in
let abs = A.change_environment man abs e' false in
let texpr = dom_to_texpr e' dom in
A.assign_texpr man abs (Var.of_string v) texpr None
let var_bounds abs v =
let var = Var.of_string v in
let i = A.bound_variable man abs var in
Intervalext.to_mpqf i
let rm_var abs v =
let var = Var.of_string v in
let e = E.remove (A.env abs) (Array.of_list [var]) in
A.change_environment man abs e false
let is_empty a = A.is_bottom man a
let join a b = (A.join man a b, false)
let weak_join a b =
let l_a = A.to_lincons_array man a in
let l_b = A.to_lincons_array man b in
let sat_a =
Linconsext.array_fold
(fun acc c -> if A.sat_lincons man b c then c :: acc else acc)
[] l_a
in
let sat_b =
Linconsext.array_fold
(fun acc c -> if A.sat_lincons man a c then c :: acc else acc)
[] l_b
in
( A.of_lincons_array man a.env
(List.rev_append sat_a sat_b |> Linconsext.array_of_list)
, false )
let join a b = if !Constant.join = "weak" then weak_join a b else join a b
let join_list l =
let a = Array.of_list l in
(A.join_array man a, false)
let meet a b =
let m = A.meet man a b in
if is_empty m then None else Some m
let diff = None
let filter abs c =
let a = A.filter_tcons man abs c in
if is_empty a then Consistency.Unsat
else
let succ = is_empty (A.filter_tcons man a (Tconsext.neg c)) in
Consistency.Filtered (a, succ)
let print = A.print
let pman = Polka.manager_alloc_strict ()
(** computes the smallest enclosing polyhedron *)
let to_poly abs env =
let abs' = A.change_environment man abs env false in
A.to_lincons_array man abs' |> A.of_lincons_array pman env
(** interval evaluation of an expression within an abtract domain *)
let forward_eval abs cons =
let ap_expr = of_expr (A.env abs) cons in
A.bound_texpr man abs ap_expr |> Intervalext.to_mpqf
(* Given `largest abs = (v, i, d)`, `largest` extracts the variable `v` from
`abs` * with the largest interval `i` = [l, u], and `d` the dimension of
the * interval (`u - l` with appropriate rounding). *)
let largest abs : Var.t * Interval.t * Q.t =
let env = A.env abs in
let box = A.to_box man abs in
let tab = box.A.interval_array in
let len = Array.length tab in
let rec aux idx i_max diam_max itv_max =
if idx >= len then (i_max, diam_max, itv_max)
else
let e = tab.(idx) in
let diam = Intervalext.range_mpqf e in
if Mpqf.cmp diam diam_max > 0 then aux (idx + 1) idx diam e
else aux (idx + 1) i_max diam_max itv_max
in
let a, b, c = aux 0 0 Q.zero tab.(0) in
(E.var_of_dim env a, c, b)
(* Compute the minimal and the maximal diameter of an array on intervals *)
let rec minmax tab i max i_max min =
if i >= Array.length tab then (Scalar.of_mpqf max, i_max, Scalar.of_mpqf min)
else
let dim = Intervalext.range_mpqf tab.(i) in
if Mpqf.cmp dim max > 0 then minmax tab (i + 1) dim i min
else if Mpqf.cmp min dim > 0 then minmax tab (i + 1) max i_max dim
else minmax tab (i + 1) max i_max min
let p1 = ( p11 , p12 , ... , ) and p2 = ( p21 , p22 , ... , p2n ) two points
* The vector p1p2 is ( p21 - p11 , p22 - p12 , ... , p2n - p1n ) and the orthogonal line
* to the vector p1p2 passing by the center of the vector has for equation :
* ( p21 - p11)(x1 - b1 ) + ( p22 - p12)(x2 - b2 ) + ... + ( p2n - p1n)(xn - bn ) = 0
* with b = ( ( p11+p21)/2 , ( p12+p22)/2 , ... , ( p1n+p2n)/2 )
* The vector p1p2 is (p21-p11, p22-p12, ..., p2n-p1n) and the orthogonal line
* to the vector p1p2 passing by the center of the vector has for equation:
* (p21-p11)(x1-b1) + (p22-p12)(x2-b2) + ... + (p2n-p1n)(xn-bn) = 0
* with b = ((p11+p21)/2, (p12+p22)/2, ..., (p1n+p2n)/2) *)
let generate_linexpr env p1 p2 =
let size = E.size env in
let rec loop i l1 l2 cst =
if i >= size then (List.rev l1, List.rev l2, cst)
else
let ci = p2.(i) -. p1.(i) in
let cst' = cst +. ((p1.(i) +. p2.(i)) *. ci) in
let ci' = 2. *. ci in
let c = Coeff.s_of_float ci' in
let list1' = (c, E.var_of_dim env i) :: l1 in
let list2' = (Coeff.neg c, E.var_of_dim env i) :: l2 in
loop (i + 1) list1' list2' cst'
in
loop 0 [] [] 0.
let split abs (e1, e2) =
let meet_linexpr abs expr =
let cons = Linconsext.make expr Lincons1.SUPEQ in
A.filter_lincons man abs cons
in
let abs1 = meet_linexpr abs e1 in
let abs2 = meet_linexpr abs e2 in
[abs1; abs2]
let volume abs =
let b = A.to_box man abs in
b.A.interval_array
|> Array.fold_left
(fun v i -> v *. (Intervalext.range i |> Scalarext.to_float))
1.
Polyhedric version of some operations
let get_expr prec (polyad : Polka.strict Polka.t A.t) =
let poly = A.to_generator_array pman polyad in
let env = poly.Generator1.array_env in
let p1, p2, dist = Generatorext.to_float_array poly |> most_distant_pair in
if dist <= prec then raise Signature.TooSmall
else
let list1, list2, cst = generate_linexpr env p1 p2 in
let linexp = Linexpr1.make env in
Linexpr1.set_list linexp list1 (Some (Coeff.s_of_float (-.cst))) ;
let linexp' = Linexpr1.make env in
Linexpr1.set_list linexp' list2 (Some (Coeff.s_of_float cst)) ;
(linexp, linexp')
(* Sanity checking functions *)
* given an abstract value [ e ] and an instance [ i ] , verifies if
[ i \in \gamma(e ) ]
[i \in \gamma(e)] *)
let is_abstraction poly instance =
let env = A.env poly in
let var, texpr =
VarMap.fold
(fun k v (acc1, acc2) ->
let k = Var.of_string k in
let v = Texpr1.cst env (Coeff.s_of_mpqf v) in
(k :: acc1, v :: acc2))
instance ([], [])
in
let var = Array.of_list var and tar = Array.of_list texpr in
let poly_subst = A.substitute_texpr_array man poly var tar None in
A.is_top man poly_subst
(** Random uniform value within an interval, according to the type *)
let spawn_itv typ (i : Interval.t) =
let inf, sup = Intervalext.to_mpqf i in
match typ with
| Environment.INT ->
let size = Q.sub sup inf |> Q.ceil in
let r = Q.of_int (Random.int (size + 1)) in
Q.add inf r
| Environment.REAL ->
let r = Q.of_float (Random.float 1.) in
Q.(add inf (mul (sub sup inf) r))
(** spawns an instance within a box *)
let spawn_box box =
let env = box.A.box1_env in
let itvs = box.A.interval_array in
let instance, _ =
Array.fold_left
(fun (acc, idx) i ->
let v = E.var_of_dim env idx in
let typ = E.typ_of_var env v in
let instance = VarMap.add (Var.to_string v) (spawn_itv typ i) acc in
(instance, idx + 1))
(VarMap.empty, 0) itvs
in
instance
(** Takes an integer and compute a spawner function. The integer * corresponds
to the number of tries allowed to proceed to the * generation. The bigger
it is, the more uniform the spawner will be. A * spawner returns a
randomly uniformly chosen instanciation of the * variables. if the
polyhedron has a nul (or very small) volume, (e.g * equalities in the
constraints) uniformity is not guaranteed *)
let spawner (nb_try : int) poly =
let env = A.env poly in
let rec retry poly n idx =
let b = A.to_box man poly in
let instance = spawn_box b in
if is_abstraction poly instance then instance
else if n >= nb_try then
(* in case we didnt find an instance, we fix a variable and retry. we
give up on uniformity to enforce termination *)
let v = E.var_of_dim env idx in
let typ = E.typ_of_var env v in
let v_itv = A.bound_variable man poly v in
let v = Texpr1.var env (E.var_of_dim env idx) in
let value = Texpr1.cst env (Coeff.s_of_mpqf (spawn_itv typ v_itv)) in
let tcons = Tconsext.eq v value in
let poly = A.filter_tcons man poly tcons in
retry poly 0 (idx + 1)
else retry poly (n + 1) idx
in
retry poly 0 0
let spawn = spawner 10
let render abs = Picasso.Drawable.of_pol (to_poly abs A.(abs.env))
end
| null | https://raw.githubusercontent.com/mpelleau/AbSolute/9cad027f71b245618bbb566183d165c1c87e79e8/lib/domains/numeric/apron_domain.ml | ocaml | compute the most distant pair of points of an array of points, and the
corresponding distance
Translation functor for csp.prog to apron values
***************************************************************
Some types and values that all the domains of apron can share
These are generic and can be redefined in the actuals domains
***************************************************************
* computes the smallest enclosing polyhedron
* interval evaluation of an expression within an abtract domain
Given `largest abs = (v, i, d)`, `largest` extracts the variable `v` from
`abs` * with the largest interval `i` = [l, u], and `d` the dimension of
the * interval (`u - l` with appropriate rounding).
Compute the minimal and the maximal diameter of an array on intervals
Sanity checking functions
* Random uniform value within an interval, according to the type
* spawns an instance within a box
* Takes an integer and compute a spawner function. The integer * corresponds
to the number of tries allowed to proceed to the * generation. The bigger
it is, the more uniform the spawner will be. A * spawner returns a
randomly uniformly chosen instanciation of the * variables. if the
polyhedron has a nul (or very small) volume, (e.g * equalities in the
constraints) uniformity is not guaranteed
in case we didnt find an instance, we fix a variable and retry. we
give up on uniformity to enforce termination | open Csp
open Tools
open Apron
open Apronext
let scalar_mul_sqrt2 =
let sqrt2_mpqf = Scalarext.of_float 0.707106781186548 in
fun s -> Scalarext.mul s sqrt2_mpqf
type point = float array
Compute the square of the euclidian distance between two points .
let sq_dist p1 p2 =
let sum = ref 0. in
Array.iter2 (fun a b -> sum := !sum +. ((a -. b) ** 2.)) p1 p2 ;
!sum
let most_distant_pair (pts : point array) : point * point * float =
fold_on_combination_2
(fun ((_, _, dist) as old) p1 p2 ->
let dist' = sq_dist p1 p2 in
if dist' > dist then (p1, p2, dist') else old)
(pts.(0), pts.(0), 0.)
pts
module type ADomain = sig
type t
val manager_alloc : unit -> t Manager.t
end
module SyntaxTranslator (D : ADomain) = struct
type internal_constr = Tcons1.t
let man = D.manager_alloc ()
let of_expr env (e : Expr.t) : Texpr1.t =
let open Expr in
let rec aux = function
| Funcall (name, args) -> (
match (name, args) with
| "sqrt", [x] -> Texprext.sqrt (aux x)
| name, _ -> fail_fmt "%s not supported by apron" name )
| Var v -> Texprext.var env (Var.of_string v)
| Cst c -> Texprext.cst env (Coeff.s_of_mpqf c)
| Neg e -> Texprext.neg (aux e)
| Binary (o, e1, e2) ->
( match o with
| ADD -> Texprext.add
| SUB -> Texprext.sub
| DIV -> Texprext.div
| MUL -> Texprext.mul
| POW -> Texprext.pow )
(aux e1) (aux e2)
in
aux e
let of_cmp_expr elem (e1, op, e2) =
let env = Abstract1.env elem in
let open Constraint in
let e1 = of_expr env e1 and e2 = of_expr env e2 in
match op with
| EQ -> Tconsext.eq e1 e2
| NEQ -> Tconsext.diseq e1 e2
| GEQ -> Tconsext.geq e1 e2
| GT -> Tconsext.gt e1 e2
| LEQ -> Tconsext.leq e1 e2
| LT -> Tconsext.lt e1 e2
let apron_to_var abs =
let env = Abstract1.env abs in
let iv, rv = Environment.vars env in
let ivars = Array.map Var.to_string iv in
let rvars = Array.map Var.to_string rv in
(Array.to_list ivars, Array.to_list rvars)
let rec to_expr = function
| Texpr1.Cst c -> Expr.of_mpqf (Coeffext.to_mpqf c)
| Texpr1.Var v -> Expr.var (Var.to_string v)
| Texpr1.Unop (Texpr1.Sqrt, e, _, _) -> Expr.Funcall ("sqrt", [to_expr e])
| Texpr1.Unop (Texpr1.Neg, e, _, _) -> Expr.Neg (to_expr e)
| Texpr1.Unop (Texpr1.Cast, _, _, _) -> failwith "cast should not occur"
| Texpr1.Binop (op, e1, e2, _, _) ->
let o =
match op with
| Texpr1.Add -> Expr.ADD
| Texpr1.Sub -> Expr.SUB
| Texpr1.Mul -> Expr.MUL
| Texpr1.Pow -> Expr.POW
| Texpr1.Div -> Expr.DIV
| Texpr1.Mod -> failwith "Mod not yet supported with AbSolute"
in
Binary (o, to_expr e1, to_expr e2)
let apron_to_bexpr tcons =
let apron_to_cmp op =
match op with
| Tcons1.EQ -> Constraint.EQ
| Tcons1.DISEQ -> Constraint.NEQ
| Tcons1.SUPEQ -> Constraint.GEQ
| Tcons1.SUP -> Constraint.GT
| _ -> failwith "operation not yet supported with AbSolute"
in
let typ = apron_to_cmp (Tcons1.get_typ tcons) in
let exp = to_expr (Texpr1.to_expr (Tcons1.get_texpr1 tcons)) in
(exp, typ, Expr.zero)
let to_constraint abs : Constraint.t =
let cons = Abstractext.to_tcons_array man abs in
let l = Tcons1.array_length cons in
let rec loop acc i =
if i = l then acc
else
loop
(Constraint.And (acc, Cmp (apron_to_bexpr (Tcons1.array_get cons i))))
(i + 1)
in
loop (Constraint.Cmp (Tcons1.array_get cons 0 |> apron_to_bexpr)) 1
end
module Make (AP : ADomain) = struct
module A = Abstractext
module E = Environmentext
type t = AP.t A.t
include SyntaxTranslator (AP)
let empty = A.top man E.empty
let internalize ?elem c =
match elem with
| None ->
invalid_arg
"apron constraint conversion requires an abstract element to setup \
the environment"
| Some e -> of_cmp_expr e c
let externalize = apron_to_bexpr
let vars abs =
let iv, rv = E.vars (A.env abs) in
let iv = Array.fold_left (fun a v -> (Int, Var.to_string v) :: a) [] iv in
Array.fold_left (fun a v -> (Real, Var.to_string v) :: a) iv rv
let dom_to_texpr env =
let open Dom in
function
| Top -> assert false
| Finite (b1, b2) -> Texpr1.cst env (Coeff.i_of_mpqf b1 b2)
| Minf _ -> assert false
| Inf _ -> assert false
| Set _ -> assert false
let add_var abs (typ, v, dom) =
let e = A.env abs in
let e' = if typ = Int then E.add_int_s v e else E.add_real_s v e in
let abs = A.change_environment man abs e' false in
let texpr = dom_to_texpr e' dom in
A.assign_texpr man abs (Var.of_string v) texpr None
let var_bounds abs v =
let var = Var.of_string v in
let i = A.bound_variable man abs var in
Intervalext.to_mpqf i
let rm_var abs v =
let var = Var.of_string v in
let e = E.remove (A.env abs) (Array.of_list [var]) in
A.change_environment man abs e false
let is_empty a = A.is_bottom man a
let join a b = (A.join man a b, false)
let weak_join a b =
let l_a = A.to_lincons_array man a in
let l_b = A.to_lincons_array man b in
let sat_a =
Linconsext.array_fold
(fun acc c -> if A.sat_lincons man b c then c :: acc else acc)
[] l_a
in
let sat_b =
Linconsext.array_fold
(fun acc c -> if A.sat_lincons man a c then c :: acc else acc)
[] l_b
in
( A.of_lincons_array man a.env
(List.rev_append sat_a sat_b |> Linconsext.array_of_list)
, false )
let join a b = if !Constant.join = "weak" then weak_join a b else join a b
let join_list l =
let a = Array.of_list l in
(A.join_array man a, false)
let meet a b =
let m = A.meet man a b in
if is_empty m then None else Some m
let diff = None
let filter abs c =
let a = A.filter_tcons man abs c in
if is_empty a then Consistency.Unsat
else
let succ = is_empty (A.filter_tcons man a (Tconsext.neg c)) in
Consistency.Filtered (a, succ)
let print = A.print
let pman = Polka.manager_alloc_strict ()
let to_poly abs env =
let abs' = A.change_environment man abs env false in
A.to_lincons_array man abs' |> A.of_lincons_array pman env
let forward_eval abs cons =
let ap_expr = of_expr (A.env abs) cons in
A.bound_texpr man abs ap_expr |> Intervalext.to_mpqf
let largest abs : Var.t * Interval.t * Q.t =
let env = A.env abs in
let box = A.to_box man abs in
let tab = box.A.interval_array in
let len = Array.length tab in
let rec aux idx i_max diam_max itv_max =
if idx >= len then (i_max, diam_max, itv_max)
else
let e = tab.(idx) in
let diam = Intervalext.range_mpqf e in
if Mpqf.cmp diam diam_max > 0 then aux (idx + 1) idx diam e
else aux (idx + 1) i_max diam_max itv_max
in
let a, b, c = aux 0 0 Q.zero tab.(0) in
(E.var_of_dim env a, c, b)
let rec minmax tab i max i_max min =
if i >= Array.length tab then (Scalar.of_mpqf max, i_max, Scalar.of_mpqf min)
else
let dim = Intervalext.range_mpqf tab.(i) in
if Mpqf.cmp dim max > 0 then minmax tab (i + 1) dim i min
else if Mpqf.cmp min dim > 0 then minmax tab (i + 1) max i_max dim
else minmax tab (i + 1) max i_max min
let p1 = ( p11 , p12 , ... , ) and p2 = ( p21 , p22 , ... , p2n ) two points
* The vector p1p2 is ( p21 - p11 , p22 - p12 , ... , p2n - p1n ) and the orthogonal line
* to the vector p1p2 passing by the center of the vector has for equation :
* ( p21 - p11)(x1 - b1 ) + ( p22 - p12)(x2 - b2 ) + ... + ( p2n - p1n)(xn - bn ) = 0
* with b = ( ( p11+p21)/2 , ( p12+p22)/2 , ... , ( p1n+p2n)/2 )
* The vector p1p2 is (p21-p11, p22-p12, ..., p2n-p1n) and the orthogonal line
* to the vector p1p2 passing by the center of the vector has for equation:
* (p21-p11)(x1-b1) + (p22-p12)(x2-b2) + ... + (p2n-p1n)(xn-bn) = 0
* with b = ((p11+p21)/2, (p12+p22)/2, ..., (p1n+p2n)/2) *)
let generate_linexpr env p1 p2 =
let size = E.size env in
let rec loop i l1 l2 cst =
if i >= size then (List.rev l1, List.rev l2, cst)
else
let ci = p2.(i) -. p1.(i) in
let cst' = cst +. ((p1.(i) +. p2.(i)) *. ci) in
let ci' = 2. *. ci in
let c = Coeff.s_of_float ci' in
let list1' = (c, E.var_of_dim env i) :: l1 in
let list2' = (Coeff.neg c, E.var_of_dim env i) :: l2 in
loop (i + 1) list1' list2' cst'
in
loop 0 [] [] 0.
let split abs (e1, e2) =
let meet_linexpr abs expr =
let cons = Linconsext.make expr Lincons1.SUPEQ in
A.filter_lincons man abs cons
in
let abs1 = meet_linexpr abs e1 in
let abs2 = meet_linexpr abs e2 in
[abs1; abs2]
let volume abs =
let b = A.to_box man abs in
b.A.interval_array
|> Array.fold_left
(fun v i -> v *. (Intervalext.range i |> Scalarext.to_float))
1.
Polyhedric version of some operations
let get_expr prec (polyad : Polka.strict Polka.t A.t) =
let poly = A.to_generator_array pman polyad in
let env = poly.Generator1.array_env in
let p1, p2, dist = Generatorext.to_float_array poly |> most_distant_pair in
if dist <= prec then raise Signature.TooSmall
else
let list1, list2, cst = generate_linexpr env p1 p2 in
let linexp = Linexpr1.make env in
Linexpr1.set_list linexp list1 (Some (Coeff.s_of_float (-.cst))) ;
let linexp' = Linexpr1.make env in
Linexpr1.set_list linexp' list2 (Some (Coeff.s_of_float cst)) ;
(linexp, linexp')
* given an abstract value [ e ] and an instance [ i ] , verifies if
[ i \in \gamma(e ) ]
[i \in \gamma(e)] *)
let is_abstraction poly instance =
let env = A.env poly in
let var, texpr =
VarMap.fold
(fun k v (acc1, acc2) ->
let k = Var.of_string k in
let v = Texpr1.cst env (Coeff.s_of_mpqf v) in
(k :: acc1, v :: acc2))
instance ([], [])
in
let var = Array.of_list var and tar = Array.of_list texpr in
let poly_subst = A.substitute_texpr_array man poly var tar None in
A.is_top man poly_subst
let spawn_itv typ (i : Interval.t) =
let inf, sup = Intervalext.to_mpqf i in
match typ with
| Environment.INT ->
let size = Q.sub sup inf |> Q.ceil in
let r = Q.of_int (Random.int (size + 1)) in
Q.add inf r
| Environment.REAL ->
let r = Q.of_float (Random.float 1.) in
Q.(add inf (mul (sub sup inf) r))
let spawn_box box =
let env = box.A.box1_env in
let itvs = box.A.interval_array in
let instance, _ =
Array.fold_left
(fun (acc, idx) i ->
let v = E.var_of_dim env idx in
let typ = E.typ_of_var env v in
let instance = VarMap.add (Var.to_string v) (spawn_itv typ i) acc in
(instance, idx + 1))
(VarMap.empty, 0) itvs
in
instance
let spawner (nb_try : int) poly =
let env = A.env poly in
let rec retry poly n idx =
let b = A.to_box man poly in
let instance = spawn_box b in
if is_abstraction poly instance then instance
else if n >= nb_try then
let v = E.var_of_dim env idx in
let typ = E.typ_of_var env v in
let v_itv = A.bound_variable man poly v in
let v = Texpr1.var env (E.var_of_dim env idx) in
let value = Texpr1.cst env (Coeff.s_of_mpqf (spawn_itv typ v_itv)) in
let tcons = Tconsext.eq v value in
let poly = A.filter_tcons man poly tcons in
retry poly 0 (idx + 1)
else retry poly (n + 1) idx
in
retry poly 0 0
let spawn = spawner 10
let render abs = Picasso.Drawable.of_pol (to_poly abs A.(abs.env))
end
|
0e151f62f3d405cb9a98f744f5fe317a035ea3feffab2f8c9bb2b35725f7c7f4 | nuvla/api-server | resource_metadata_value_scope_enumeration_test.cljc | (ns sixsq.nuvla.server.resources.spec.resource-metadata-value-scope-enumeration-test
(:require
[clojure.test :refer [deftest]]
[sixsq.nuvla.server.resources.spec.resource-metadata-value-scope-enumeration :as spec]
[sixsq.nuvla.server.resources.spec.spec-test-utils :as stu]))
(def valid {:values ["68000" "Alpha" "ARM" "PA_RISC"]
:default "Alpha"})
(deftest check-value-scope-unit
(stu/is-valid ::spec/enumeration valid)
(doseq [k #{:default}]
(stu/is-valid ::spec/enumeration (dissoc valid k)))
(doseq [k #{:values}]
(stu/is-invalid ::spec/enumeration (dissoc valid k)))
(stu/is-invalid ::spec/enumeration (assoc valid :badAttribute 1))
(stu/is-invalid ::spec/enumeration (assoc valid :default ["cannot" "be" "collection"]))
(stu/is-invalid ::spec/enumeration (assoc valid :values [])))
| null | https://raw.githubusercontent.com/nuvla/api-server/a64a61b227733f1a0a945003edf5abaf5150a15c/code/test/sixsq/nuvla/server/resources/spec/resource_metadata_value_scope_enumeration_test.cljc | clojure | (ns sixsq.nuvla.server.resources.spec.resource-metadata-value-scope-enumeration-test
(:require
[clojure.test :refer [deftest]]
[sixsq.nuvla.server.resources.spec.resource-metadata-value-scope-enumeration :as spec]
[sixsq.nuvla.server.resources.spec.spec-test-utils :as stu]))
(def valid {:values ["68000" "Alpha" "ARM" "PA_RISC"]
:default "Alpha"})
(deftest check-value-scope-unit
(stu/is-valid ::spec/enumeration valid)
(doseq [k #{:default}]
(stu/is-valid ::spec/enumeration (dissoc valid k)))
(doseq [k #{:values}]
(stu/is-invalid ::spec/enumeration (dissoc valid k)))
(stu/is-invalid ::spec/enumeration (assoc valid :badAttribute 1))
(stu/is-invalid ::spec/enumeration (assoc valid :default ["cannot" "be" "collection"]))
(stu/is-invalid ::spec/enumeration (assoc valid :values [])))
| |
3cc75ba879fd42c7337d86493fd270ce8175c3b7398404871929993b941a9959 | nikita-volkov/hasql | PTI.hs | module Hasql.Private.PTI where
import qualified Database.PostgreSQL.LibPQ as LibPQ
import Hasql.Private.Prelude hiding (bool)
-- | A Postgresql type info
data PTI = PTI {ptiOID :: !OID, ptiArrayOID :: !(Maybe OID)}
-- | A Word32 and a LibPQ representation of an OID
data OID = OID {oidWord32 :: !Word32, oidPQ :: !LibPQ.Oid, oidFormat :: !LibPQ.Format}
mkOID :: LibPQ.Format -> Word32 -> OID
mkOID format x =
OID x ((LibPQ.Oid . fromIntegral) x) format
mkPTI :: LibPQ.Format -> Word32 -> Maybe Word32 -> PTI
mkPTI format oid arrayOID =
PTI (mkOID format oid) (fmap (mkOID format) arrayOID)
-- * Constants
abstime = mkPTI LibPQ.Binary 702 (Just 1023)
aclitem = mkPTI LibPQ.Binary 1033 (Just 1034)
bit = mkPTI LibPQ.Binary 1560 (Just 1561)
bool = mkPTI LibPQ.Binary 16 (Just 1000)
box = mkPTI LibPQ.Binary 603 (Just 1020)
bpchar = mkPTI LibPQ.Binary 1042 (Just 1014)
bytea = mkPTI LibPQ.Binary 17 (Just 1001)
char = mkPTI LibPQ.Binary 18 (Just 1002)
cid = mkPTI LibPQ.Binary 29 (Just 1012)
cidr = mkPTI LibPQ.Binary 650 (Just 651)
circle = mkPTI LibPQ.Binary 718 (Just 719)
cstring = mkPTI LibPQ.Binary 2275 (Just 1263)
date = mkPTI LibPQ.Binary 1082 (Just 1182)
daterange = mkPTI LibPQ.Binary 3912 (Just 3913)
float4 = mkPTI LibPQ.Binary 700 (Just 1021)
float8 = mkPTI LibPQ.Binary 701 (Just 1022)
gtsvector = mkPTI LibPQ.Binary 3642 (Just 3644)
inet = mkPTI LibPQ.Binary 869 (Just 1041)
int2 = mkPTI LibPQ.Binary 21 (Just 1005)
int2vector = mkPTI LibPQ.Binary 22 (Just 1006)
int4 = mkPTI LibPQ.Binary 23 (Just 1007)
int4range = mkPTI LibPQ.Binary 3904 (Just 3905)
int8 = mkPTI LibPQ.Binary 20 (Just 1016)
int8range = mkPTI LibPQ.Binary 3926 (Just 3927)
interval = mkPTI LibPQ.Binary 1186 (Just 1187)
json = mkPTI LibPQ.Binary 114 (Just 199)
jsonb = mkPTI LibPQ.Binary 3802 (Just 3807)
line = mkPTI LibPQ.Binary 628 (Just 629)
lseg = mkPTI LibPQ.Binary 601 (Just 1018)
macaddr = mkPTI LibPQ.Binary 829 (Just 1040)
money = mkPTI LibPQ.Binary 790 (Just 791)
name = mkPTI LibPQ.Binary 19 (Just 1003)
numeric = mkPTI LibPQ.Binary 1700 (Just 1231)
numrange = mkPTI LibPQ.Binary 3906 (Just 3907)
oid = mkPTI LibPQ.Binary 26 (Just 1028)
oidvector = mkPTI LibPQ.Binary 30 (Just 1013)
path = mkPTI LibPQ.Binary 602 (Just 1019)
point = mkPTI LibPQ.Binary 600 (Just 1017)
polygon = mkPTI LibPQ.Binary 604 (Just 1027)
record = mkPTI LibPQ.Binary 2249 (Just 2287)
refcursor = mkPTI LibPQ.Binary 1790 (Just 2201)
regclass = mkPTI LibPQ.Binary 2205 (Just 2210)
regconfig = mkPTI LibPQ.Binary 3734 (Just 3735)
regdictionary = mkPTI LibPQ.Binary 3769 (Just 3770)
regoper = mkPTI LibPQ.Binary 2203 (Just 2208)
regoperator = mkPTI LibPQ.Binary 2204 (Just 2209)
regproc = mkPTI LibPQ.Binary 24 (Just 1008)
regprocedure = mkPTI LibPQ.Binary 2202 (Just 2207)
regtype = mkPTI LibPQ.Binary 2206 (Just 2211)
reltime = mkPTI LibPQ.Binary 703 (Just 1024)
text = mkPTI LibPQ.Binary 25 (Just 1009)
tid = mkPTI LibPQ.Binary 27 (Just 1010)
time = mkPTI LibPQ.Binary 1083 (Just 1183)
timestamp = mkPTI LibPQ.Binary 1114 (Just 1115)
timestamptz = mkPTI LibPQ.Binary 1184 (Just 1185)
timetz = mkPTI LibPQ.Binary 1266 (Just 1270)
tinterval = mkPTI LibPQ.Binary 704 (Just 1025)
tsquery = mkPTI LibPQ.Binary 3615 (Just 3645)
tsrange = mkPTI LibPQ.Binary 3908 (Just 3909)
tstzrange = mkPTI LibPQ.Binary 3910 (Just 3911)
tsvector = mkPTI LibPQ.Binary 3614 (Just 3643)
txid_snapshot = mkPTI LibPQ.Binary 2970 (Just 2949)
textUnknown = mkPTI LibPQ.Text 705 (Just 705)
binaryUnknown = mkPTI LibPQ.Binary 705 (Just 705)
uuid = mkPTI LibPQ.Binary 2950 (Just 2951)
varbit = mkPTI LibPQ.Binary 1562 (Just 1563)
varchar = mkPTI LibPQ.Binary 1043 (Just 1015)
void = mkPTI LibPQ.Binary 2278 Nothing
xid = mkPTI LibPQ.Binary 28 (Just 1011)
xml = mkPTI LibPQ.Binary 142 (Just 143)
| null | https://raw.githubusercontent.com/nikita-volkov/hasql/fa707dd7931390538cc1f67f86e49ef90a758ec4/library/Hasql/Private/PTI.hs | haskell | | A Postgresql type info
| A Word32 and a LibPQ representation of an OID
* Constants | module Hasql.Private.PTI where
import qualified Database.PostgreSQL.LibPQ as LibPQ
import Hasql.Private.Prelude hiding (bool)
data PTI = PTI {ptiOID :: !OID, ptiArrayOID :: !(Maybe OID)}
data OID = OID {oidWord32 :: !Word32, oidPQ :: !LibPQ.Oid, oidFormat :: !LibPQ.Format}
mkOID :: LibPQ.Format -> Word32 -> OID
mkOID format x =
OID x ((LibPQ.Oid . fromIntegral) x) format
mkPTI :: LibPQ.Format -> Word32 -> Maybe Word32 -> PTI
mkPTI format oid arrayOID =
PTI (mkOID format oid) (fmap (mkOID format) arrayOID)
abstime = mkPTI LibPQ.Binary 702 (Just 1023)
aclitem = mkPTI LibPQ.Binary 1033 (Just 1034)
bit = mkPTI LibPQ.Binary 1560 (Just 1561)
bool = mkPTI LibPQ.Binary 16 (Just 1000)
box = mkPTI LibPQ.Binary 603 (Just 1020)
bpchar = mkPTI LibPQ.Binary 1042 (Just 1014)
bytea = mkPTI LibPQ.Binary 17 (Just 1001)
char = mkPTI LibPQ.Binary 18 (Just 1002)
cid = mkPTI LibPQ.Binary 29 (Just 1012)
cidr = mkPTI LibPQ.Binary 650 (Just 651)
circle = mkPTI LibPQ.Binary 718 (Just 719)
cstring = mkPTI LibPQ.Binary 2275 (Just 1263)
date = mkPTI LibPQ.Binary 1082 (Just 1182)
daterange = mkPTI LibPQ.Binary 3912 (Just 3913)
float4 = mkPTI LibPQ.Binary 700 (Just 1021)
float8 = mkPTI LibPQ.Binary 701 (Just 1022)
gtsvector = mkPTI LibPQ.Binary 3642 (Just 3644)
inet = mkPTI LibPQ.Binary 869 (Just 1041)
int2 = mkPTI LibPQ.Binary 21 (Just 1005)
int2vector = mkPTI LibPQ.Binary 22 (Just 1006)
int4 = mkPTI LibPQ.Binary 23 (Just 1007)
int4range = mkPTI LibPQ.Binary 3904 (Just 3905)
int8 = mkPTI LibPQ.Binary 20 (Just 1016)
int8range = mkPTI LibPQ.Binary 3926 (Just 3927)
interval = mkPTI LibPQ.Binary 1186 (Just 1187)
json = mkPTI LibPQ.Binary 114 (Just 199)
jsonb = mkPTI LibPQ.Binary 3802 (Just 3807)
line = mkPTI LibPQ.Binary 628 (Just 629)
lseg = mkPTI LibPQ.Binary 601 (Just 1018)
macaddr = mkPTI LibPQ.Binary 829 (Just 1040)
money = mkPTI LibPQ.Binary 790 (Just 791)
name = mkPTI LibPQ.Binary 19 (Just 1003)
numeric = mkPTI LibPQ.Binary 1700 (Just 1231)
numrange = mkPTI LibPQ.Binary 3906 (Just 3907)
oid = mkPTI LibPQ.Binary 26 (Just 1028)
oidvector = mkPTI LibPQ.Binary 30 (Just 1013)
path = mkPTI LibPQ.Binary 602 (Just 1019)
point = mkPTI LibPQ.Binary 600 (Just 1017)
polygon = mkPTI LibPQ.Binary 604 (Just 1027)
record = mkPTI LibPQ.Binary 2249 (Just 2287)
refcursor = mkPTI LibPQ.Binary 1790 (Just 2201)
regclass = mkPTI LibPQ.Binary 2205 (Just 2210)
regconfig = mkPTI LibPQ.Binary 3734 (Just 3735)
regdictionary = mkPTI LibPQ.Binary 3769 (Just 3770)
regoper = mkPTI LibPQ.Binary 2203 (Just 2208)
regoperator = mkPTI LibPQ.Binary 2204 (Just 2209)
regproc = mkPTI LibPQ.Binary 24 (Just 1008)
regprocedure = mkPTI LibPQ.Binary 2202 (Just 2207)
regtype = mkPTI LibPQ.Binary 2206 (Just 2211)
reltime = mkPTI LibPQ.Binary 703 (Just 1024)
text = mkPTI LibPQ.Binary 25 (Just 1009)
tid = mkPTI LibPQ.Binary 27 (Just 1010)
time = mkPTI LibPQ.Binary 1083 (Just 1183)
timestamp = mkPTI LibPQ.Binary 1114 (Just 1115)
timestamptz = mkPTI LibPQ.Binary 1184 (Just 1185)
timetz = mkPTI LibPQ.Binary 1266 (Just 1270)
tinterval = mkPTI LibPQ.Binary 704 (Just 1025)
tsquery = mkPTI LibPQ.Binary 3615 (Just 3645)
tsrange = mkPTI LibPQ.Binary 3908 (Just 3909)
tstzrange = mkPTI LibPQ.Binary 3910 (Just 3911)
tsvector = mkPTI LibPQ.Binary 3614 (Just 3643)
txid_snapshot = mkPTI LibPQ.Binary 2970 (Just 2949)
textUnknown = mkPTI LibPQ.Text 705 (Just 705)
binaryUnknown = mkPTI LibPQ.Binary 705 (Just 705)
uuid = mkPTI LibPQ.Binary 2950 (Just 2951)
varbit = mkPTI LibPQ.Binary 1562 (Just 1563)
varchar = mkPTI LibPQ.Binary 1043 (Just 1015)
void = mkPTI LibPQ.Binary 2278 Nothing
xid = mkPTI LibPQ.Binary 28 (Just 1011)
xml = mkPTI LibPQ.Binary 142 (Just 143)
|
f4f6e85c488b6a69ea99886e42e88b55d88ef3ce4d85b5ddcbe0c1a58e3f282b | teropa/nlp | score_tests.clj | (ns teropa.nlp.metrics.score-tests
(:use teropa.nlp.metrics.score)
(:use clojure.test))
(deftest accuracy-tests
(is (= 2 (accuracy [1 2 3 4 5]
[1 2 6 7 8])))
(is (= 0 (accuracy [5 4 3 2 1]
[1 2 6 7 8]))))
(deftest measure-tests
(let [r #{1 2 3 4 5 9 10}
t #{1 2 6 7 8}]
(is (= (/ 2 5) (precision r t)))
(is (= (/ 2 7) (recall r t)))
(is (= (/ 1 3) (f-measure r t)))))
(run-tests)
| null | https://raw.githubusercontent.com/teropa/nlp/f89bc5a15b516208de1cfe2abe9692b7ed9a43e2/test/teropa/nlp/metrics/score_tests.clj | clojure | (ns teropa.nlp.metrics.score-tests
(:use teropa.nlp.metrics.score)
(:use clojure.test))
(deftest accuracy-tests
(is (= 2 (accuracy [1 2 3 4 5]
[1 2 6 7 8])))
(is (= 0 (accuracy [5 4 3 2 1]
[1 2 6 7 8]))))
(deftest measure-tests
(let [r #{1 2 3 4 5 9 10}
t #{1 2 6 7 8}]
(is (= (/ 2 5) (precision r t)))
(is (= (/ 2 7) (recall r t)))
(is (= (/ 1 3) (f-measure r t)))))
(run-tests)
| |
4019379b4751a096b89c8725bcdf3ec435b71f2ce33310c25ba0a1eb6f6b4334 | ucsd-progsys/nate | editor.ml | (*************************************************************************)
(* *)
(* Objective Caml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . 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 : editor.ml , v 1.41 2006/01/04 16:55:50 doligez Exp $
open StdLabels
open Tk
open Parsetree
open Location
open Jg_tk
open Mytypes
let lex_on_load = ref true
and type_on_load = ref false
let compiler_preferences master =
let tl = Jg_toplevel.titled "Compiler" in
Wm.transient_set tl ~master;
let mk_chkbutton ~text ~ref ~invert =
let variable = Textvariable.create ~on:tl () in
if (if invert then not !ref else !ref) then
Textvariable.set variable "1";
Checkbutton.create tl ~text ~variable,
(fun () ->
ref := Textvariable.get variable = (if invert then "0" else "1"))
in
let use_pp = ref (!Clflags.preprocessor <> None) in
let chkbuttons, setflags = List.split
(List.map
~f:(fun (text, ref, invert) -> mk_chkbutton ~text ~ref ~invert)
[ "No pervasives", Clflags.nopervasives, false;
"No warnings", Typecheck.nowarnings, false;
"No labels", Clflags.classic, false;
"Recursive types", Clflags.recursive_types, false;
"Lex on load", lex_on_load, false;
"Type on load", type_on_load, false;
"Preprocessor", use_pp, false ])
in
let pp_command = Entry.create tl (* ~state:(if !use_pp then `Normal else`Disabled) *) in
begin match !Clflags.preprocessor with None -> ()
| Some pp -> Entry.insert pp_command ~index:(`Num 0) ~text:pp
end;
let buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok" ~padx:20 ~command:
begin fun () ->
List.iter ~f:(fun f -> f ()) setflags;
Clflags.preprocessor :=
if !use_pp then Some (Entry.get pp_command) else None;
destroy tl
end
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel"
in
pack chkbuttons ~side:`Top ~anchor:`W;
pack [pp_command] ~side:`Top ~anchor:`E;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true;
pack [buttons] ~side:`Bottom ~fill:`X
let rec exclude txt = function
[] -> []
| x :: l -> if txt.number = x.number then l else x :: exclude txt l
let goto_line tw =
let tl = Jg_toplevel.titled "Go to" in
Wm.transient_set tl ~master:(Winfo.toplevel tw);
Jg_bind.escape_destroy tl;
let ef = Frame.create tl in
let fl = Frame.create ef
and fi = Frame.create ef in
let ll = Label.create fl ~text:"Line ~number:"
and il = Entry.create fi ~width:10
and lc = Label.create fl ~text:"Col ~number:"
and ic = Entry.create fi ~width:10
and get_int ew =
try int_of_string (Entry.get ew)
with Failure "int_of_string" -> 0
in
let buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok" ~command:
begin fun () ->
let l = get_int il
and c = get_int ic in
Text.mark_set tw ~mark:"insert" ~index:(`Linechar (l,0), [`Char c]);
Text.see tw ~index:(`Mark "insert", []);
destroy tl
end
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel" in
Focus.set il;
List.iter [il; ic] ~f:
begin fun w ->
Jg_bind.enter_focus w;
Jg_bind.return_invoke w ~button:ok
end;
pack [ll; lc] ~side:`Top ~anchor:`W;
pack [il; ic] ~side:`Top ~fill:`X ~expand:true;
pack [fl; fi] ~side:`Left ~fill:`X ~expand:true;
pack [ok; cancel] ~side:`Left ~fill:`X ~expand:true;
pack [ef; buttons] ~side:`Top ~fill:`X ~expand:true
let select_shell txt =
let shells = Shell.get_all () in
let shells = List.sort shells ~cmp:compare in
let tl = Jg_toplevel.titled "Select Shell" in
Jg_bind.escape_destroy tl;
Wm.transient_set tl ~master:(Winfo.toplevel txt.tw);
let label = Label.create tl ~text:"Send to:"
and box = Listbox.create tl
and frame = Frame.create tl in
Jg_bind.enter_focus box;
let cancel = Jg_button.create_destroyer tl ~parent:frame ~text:"Cancel"
and ok = Button.create frame ~text:"Ok" ~command:
begin fun () ->
try
let name = Listbox.get box ~index:`Active in
txt.shell <- Some (name, List.assoc name shells);
destroy tl
with Not_found -> txt.shell <- None; destroy tl
end
in
Listbox.insert box ~index:`End ~texts:(List.map ~f:fst shells);
Listbox.configure box ~height:(List.length shells);
bind box ~events:[`KeyPressDetail"Return"] ~breakable:true
~action:(fun _ -> Button.invoke ok; break ());
bind box ~events:[`Modified([`Double],`ButtonPressDetail 1)] ~breakable:true
~fields:[`MouseX;`MouseY]
~action:(fun ev ->
Listbox.activate box ~index:(`Atxy (ev.ev_MouseX, ev.ev_MouseY));
Button.invoke ok; break ());
pack [label] ~side:`Top ~anchor:`W;
pack [box] ~side:`Top ~fill:`Both;
pack [frame] ~side:`Bottom ~fill:`X ~expand:true;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true
open Parser
let send_phrase txt =
if txt.shell = None then begin
match Shell.get_all () with [] -> ()
| [sh] -> txt.shell <- Some sh
| l -> select_shell txt
end;
match txt.shell with None -> ()
| Some (_,sh) ->
try
let i1,i2 = Text.tag_nextrange txt.tw ~tag:"sel" ~start:tstart in
let phrase = Text.get txt.tw ~start:(i1,[]) ~stop:(i2,[]) in
sh#send phrase;
if Str.string_match (Str.regexp ";;") phrase 0
then sh#send "\n" else sh#send ";;\n"
with Not_found | Protocol.TkError _ ->
let text = Text.get txt.tw ~start:tstart ~stop:tend in
let buffer = Lexing.from_string text in
let start = ref 0
and block_start = ref []
and pend = ref (-1)
and after = ref false in
while !pend = -1 do
let token = Lexer.token buffer in
let pos =
if token = SEMISEMI then Lexing.lexeme_end buffer
else Lexing.lexeme_start buffer
in
let bol = (pos = 0) || text.[pos-1] = '\n' in
if not !after &&
Text.compare txt.tw ~index:(tpos pos) ~op:(if bol then `Gt else `Ge)
~index:(`Mark"insert",[])
then begin
after := true;
let anon, real =
List.partition !block_start ~f:(fun x -> x = -1) in
block_start := anon;
if real <> [] then start := List.hd real;
end;
match token with
CLASS | EXTERNAL | EXCEPTION | FUNCTOR
| LET | MODULE | OPEN | TYPE | VAL | SHARP when bol ->
if !block_start = [] then
if !after then pend := pos else start := pos
else block_start := pos :: List.tl !block_start
| SEMISEMI ->
if !block_start = [] then
if !after then pend := Lexing.lexeme_start buffer
else start := pos
else block_start := pos :: List.tl !block_start
| BEGIN | OBJECT ->
block_start := -1 :: !block_start
| STRUCT | SIG ->
block_start := Lexing.lexeme_end buffer :: !block_start
| END ->
if !block_start = [] then
if !after then pend := pos else ()
else block_start := List.tl !block_start
| EOF ->
pend := pos
| _ ->
()
done;
let phrase = String.sub text ~pos:!start ~len:(!pend - !start) in
sh#send phrase;
sh#send ";;\n"
let search_pos_window txt ~x ~y =
if txt.type_info = [] && txt.psignature = [] then () else
let `Linechar (l, c) = Text.index txt.tw ~index:(`Atxy(x,y), []) in
let text = Jg_text.get_all txt.tw in
let pos = Searchpos.lines_to_chars l ~text + c in
try if txt.type_info <> [] then begin match
Searchpos.search_pos_info txt.type_info ~pos
with [] -> ()
| (kind, env, loc) :: _ -> Searchpos.view_type kind ~env
end else begin match
Searchpos.search_pos_signature txt.psignature ~pos ~env:!Searchid.start_env
with [] -> ()
| ((kind, lid), env, loc) :: _ ->
Searchpos.view_decl lid ~kind ~env
end
with Not_found -> ()
let search_pos_menu txt ~x ~y =
if txt.type_info = [] && txt.psignature = [] then () else
let `Linechar (l, c) = Text.index txt.tw ~index:(`Atxy(x,y), []) in
let text = Jg_text.get_all txt.tw in
let pos = Searchpos.lines_to_chars l ~text + c in
try if txt.type_info <> [] then begin match
Searchpos.search_pos_info txt.type_info ~pos
with [] -> ()
| (kind, env, loc) :: _ ->
let menu = Searchpos.view_type_menu kind ~env ~parent:txt.tw in
let x = x + Winfo.rootx txt.tw and y = y + Winfo.rooty txt.tw - 10 in
Menu.popup menu ~x ~y
end else begin match
Searchpos.search_pos_signature txt.psignature ~pos ~env:!Searchid.start_env
with [] -> ()
| ((kind, lid), env, loc) :: _ ->
let menu = Searchpos.view_decl_menu lid ~kind ~env ~parent:txt.tw in
let x = x + Winfo.rootx txt.tw and y = y + Winfo.rooty txt.tw - 10 in
Menu.popup menu ~x ~y
end
with Not_found -> ()
let string_width s =
let width = ref 0 in
for i = 0 to String.length s - 1 do
if s.[i] = '\t' then width := (!width / 8 + 1) * 8
else incr width
done;
!width
let indent_line =
let ins = `Mark"insert" and reg = Str.regexp "[ \t]*" in
fun tw ->
let `Linechar(l,c) = Text.index tw ~index:(ins,[])
and line = Text.get tw ~start:(ins,[`Linestart]) ~stop:(ins,[`Lineend]) in
ignore (Str.string_match reg line 0);
let len = Str.match_end () in
if len < c then Text.insert tw ~index:(ins,[]) ~text:"\t" else
let width = string_width (Str.matched_string line) in
Text.mark_set tw ~mark:"insert" ~index:(ins,[`Linestart;`Char len]);
let indent =
if l <= 1 then 2 else
let previous =
Text.get tw ~start:(ins,[`Line(-1);`Linestart])
~stop:(ins,[`Line(-1);`Lineend]) in
ignore (Str.string_match reg previous 0);
let previous = Str.matched_string previous in
let width_previous = string_width previous in
if width_previous <= width then 2 else width_previous - width
in
Text.insert tw ~index:(ins,[]) ~text:(String.make indent ' ')
(* The editor class *)
class editor ~top ~menus = object (self)
val file_menu = new Jg_menu.c "File" ~parent:menus
val edit_menu = new Jg_menu.c "Edit" ~parent:menus
val compiler_menu = new Jg_menu.c "Compiler" ~parent:menus
val module_menu = new Jg_menu.c "Modules" ~parent:menus
val window_menu = new Jg_menu.c "Windows" ~parent:menus
initializer
Menu.add_checkbutton menus ~state:`Disabled
~onvalue:"modified" ~offvalue:"unchanged"
val mutable current_dir = Unix.getcwd ()
val mutable error_messages = []
val mutable windows = []
val mutable current_tw = Text.create top
val vwindow = Textvariable.create ~on:top ()
val mutable window_counter = 0
method has_window name =
List.exists windows ~f:(fun x -> x.name = name)
method reset_window_menu =
Menu.delete window_menu#menu ~first:(`Num 0) ~last:`End;
List.iter
(List.sort windows ~cmp:
(fun w1 w2 ->
compare (Filename.basename w1.name) (Filename.basename w2.name)))
~f:
begin fun txt ->
Menu.add_radiobutton window_menu#menu
~label:(Filename.basename txt.name)
~variable:vwindow ~value:txt.number
~command:(fun () -> self#set_edit txt)
end
method set_file_name txt =
Menu.configure_checkbutton menus `Last
~label:(Filename.basename txt.name)
~variable:txt.modified
method set_edit txt =
if windows <> [] then
Pack.forget [(List.hd windows).frame];
windows <- txt :: exclude txt windows;
self#reset_window_menu;
current_tw <- txt.tw;
self#set_file_name txt;
Textvariable.set vwindow txt.number;
Text.yview txt.tw ~scroll:(`Page 0);
pack [txt.frame] ~fill:`Both ~expand:true ~side:`Bottom
method new_window name =
let tl, tw, sb = Jg_text.create_with_scrollbar top in
Text.configure tw ~background:`White;
Jg_bind.enter_focus tw;
window_counter <- window_counter + 1;
let txt =
{ name = name; tw = tw; frame = tl;
number = string_of_int window_counter;
modified = Textvariable.create ~on:tw ();
shell = None;
structure = []; type_info = []; signature = []; psignature = [] }
in
let control c = Char.chr (Char.code c - 96) in
bind tw ~events:[`Modified([`Alt], `KeyPress)] ~action:ignore;
bind tw ~events:[`KeyPress] ~fields:[`Char]
~action:(fun ev ->
if ev.ev_Char <> "" &&
(ev.ev_Char.[0] >= ' ' ||
List.mem ev.ev_Char.[0]
(List.map ~f:control ['d'; 'h'; 'i'; 'k'; 'o'; 't'; 'w'; 'y']))
then Textvariable.set txt.modified "modified");
bind tw ~events:[`KeyPressDetail"Tab"] ~breakable:true
~action:(fun _ ->
indent_line tw;
Textvariable.set txt.modified "modified";
break ());
bind tw ~events:[`Modified([`Control],`KeyPressDetail"k")]
~action:(fun _ ->
let text =
Text.get tw ~start:(`Mark"insert",[]) ~stop:(`Mark"insert",[`Lineend])
in ignore (Str.string_match (Str.regexp "[ \t]*") text 0);
if Str.match_end () <> String.length text then begin
Clipboard.clear ();
Clipboard.append ~data:text ()
end);
bind tw ~events:[`KeyRelease] ~fields:[`Char]
~action:(fun ev ->
if ev.ev_Char <> "" then
Lexical.tag tw ~start:(`Mark"insert", [`Linestart])
~stop:(`Mark"insert", [`Lineend]));
bind tw ~events:[`Motion] ~action:(fun _ -> Focus.set tw);
bind tw ~events:[`ButtonPressDetail 2]
~action:(fun _ ->
Textvariable.set txt.modified "modified";
Lexical.tag txt.tw ~start:(`Mark"insert", [`Linestart])
~stop:(`Mark"insert", [`Lineend]));
bind tw ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~fields:[`MouseX;`MouseY]
~action:(fun ev -> search_pos_window txt ~x:ev.ev_MouseX ~y:ev.ev_MouseY);
bind tw ~events:[`ButtonPressDetail 3] ~fields:[`MouseX;`MouseY]
~action:(fun ev -> search_pos_menu txt ~x:ev.ev_MouseX ~y:ev.ev_MouseY);
pack [sb] ~fill:`Y ~side:`Right;
pack [tw] ~fill:`Both ~expand:true ~side:`Left;
self#set_edit txt;
Textvariable.set txt.modified "unchanged";
Lexical.init_tags txt.tw
method clear_errors () =
Text.tag_remove current_tw ~tag:"error" ~start:tstart ~stop:tend;
List.iter error_messages
~f:(fun tl -> try destroy tl with Protocol.TkError _ -> ());
error_messages <- []
method typecheck () =
self#clear_errors ();
error_messages <- Typecheck.f (List.hd windows)
method lex () =
List.iter [ Widget.default_toplevel; top ]
~f:(Toplevel.configure ~cursor:(`Xcursor "watch"));
Text.configure current_tw ~cursor:(`Xcursor "watch");
ignore (Timer.add ~ms:1 ~callback:
begin fun () ->
Text.tag_remove current_tw ~tag:"error" ~start:tstart ~stop:tend;
Lexical.tag current_tw;
Text.configure current_tw ~cursor:(`Xcursor "xterm");
List.iter [ Widget.default_toplevel; top ]
~f:(Toplevel.configure ~cursor:(`Xcursor ""))
end)
method save_text ?name:l txt =
let l = match l with None -> [txt.name] | Some l -> l in
if l = [] then () else
let name = List.hd l in
if txt.name <> name then current_dir <- Filename.dirname name;
try
if Sys.file_exists name then
if txt.name = name then begin
let backup = name ^ "~" in
if Sys.file_exists backup then Sys.remove backup;
try Sys.rename name backup with Sys_error _ -> ()
end else begin
match Jg_message.ask ~master:top ~title:"Save"
("File `" ^ name ^ "' exists. Overwrite it?")
with `Yes -> Sys.remove name
| `No -> raise (Sys_error "")
| `Cancel -> raise Exit
end;
let file = open_out name in
let text = Text.get txt.tw ~start:tstart ~stop:(tposend 1) in
output_string file text;
close_out file;
txt.name <- name;
self#set_file_name txt
with
Sys_error _ ->
Jg_message.info ~master:top ~title:"Error"
("Could not save `" ^ name ^ "'.")
| Exit -> ()
method load_text l =
if l = [] then () else
let name = List.hd l in
try
let index =
try
self#set_edit (List.find windows ~f:(fun x -> x.name = name));
let txt = List.hd windows in
if Textvariable.get txt.modified = "modified" then
begin match Jg_message.ask ~master:top ~title:"Open"
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
Textvariable.set txt.modified "unchanged";
(Text.index current_tw ~index:(`Mark"insert", []), [])
with Not_found -> self#new_window name; tstart
in
current_dir <- Filename.dirname name;
let file = open_in name
and tw = current_tw
and len = ref 0
and buf = String.create 4096 in
Text.delete tw ~start:tstart ~stop:tend;
while
len := input file buf 0 4096;
!len > 0
do
Jg_text.output tw ~buf ~pos:0 ~len:!len
done;
close_in file;
Text.mark_set tw ~mark:"insert" ~index;
Text.see tw ~index;
if Filename.check_suffix name ".ml" ||
Filename.check_suffix name ".mli"
then begin
if !lex_on_load then self#lex ();
if !type_on_load then self#typecheck ()
end
with
Sys_error _ | Exit -> ()
method close_window txt =
try
if Textvariable.get txt.modified = "modified" then
begin match Jg_message.ask ~master:top ~title:"Close"
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
windows <- exclude txt windows;
if windows = [] then
self#new_window (current_dir ^ "/untitled")
else self#set_edit (List.hd windows);
destroy txt.frame
with Exit -> ()
method open_file () =
Fileselect.f ~title:"Open File" ~action:self#load_text
~dir:current_dir ~filter:("*.{ml,mli}") ~sync:true ()
method save_file () = self#save_text (List.hd windows)
method close_file () = self#close_window (List.hd windows)
method quit ?(cancel=true) () =
try
List.iter windows ~f:
begin fun txt ->
if Textvariable.get txt.modified = "modified" then
match Jg_message.ask ~master:top ~title:"Quit" ~cancel
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
bind top ~events:[`Destroy];
destroy top
with Exit -> ()
method reopen ~file ~pos =
if not (Winfo.ismapped top) then Wm.deiconify top;
match file with None -> ()
| Some file ->
self#load_text [file];
Text.mark_set current_tw ~mark:"insert" ~index:(tpos pos);
try
let index =
Text.search current_tw ~switches:[`Backwards] ~pattern:"*)"
~start:(tpos pos) ~stop:(tpos pos ~modi:[`Line(-1)]) in
let index =
Text.search current_tw ~switches:[`Backwards] ~pattern:"(*"
~start:(index,[]) ~stop:(tpos pos ~modi:[`Line(-20)]) in
let s = Text.get current_tw ~start:(index,[`Line(-1);`Linestart])
~stop:(index,[`Line(-1);`Lineend]) in
for i = 0 to String.length s - 1 do
match s.[i] with '\t'|' ' -> () | _ -> raise Not_found
done;
Text.yview_index current_tw ~index:(index,[`Line(-1)])
with _ ->
Text.yview_index current_tw ~index:(tpos pos ~modi:[`Line(-2)])
initializer
Create a first window
self#new_window (current_dir ^ "/untitled");
(* Bindings for the main window *)
List.iter
[ [`Control], "s", (fun () -> Jg_text.search_string current_tw);
[`Control], "g", (fun () -> goto_line current_tw);
[`Alt], "s", self#save_file;
[`Alt], "x", (fun () -> send_phrase (List.hd windows));
[`Alt], "l", self#lex;
[`Alt], "t", self#typecheck ]
~f:begin fun (modi,key,act) ->
bind top ~events:[`Modified(modi, `KeyPressDetail key)] ~breakable:true
~action:(fun _ -> act (); break ())
end;
bind top ~events:[`Destroy] ~fields:[`Widget] ~action:
begin fun ev ->
if Widget.name ev.ev_Widget = Widget.name top
then self#quit ~cancel:false ()
end;
(* File menu *)
file_menu#add_command "Open File..." ~command:self#open_file;
file_menu#add_command "Reopen"
~command:(fun () -> self#load_text [(List.hd windows).name]);
file_menu#add_command "Save File" ~command:self#save_file ~accelerator:"M-s";
file_menu#add_command "Save As..." ~underline:5 ~command:
begin fun () ->
let txt = List.hd windows in
Fileselect.f ~title:"Save as File"
~action:(fun name -> self#save_text txt ~name)
~dir:(Filename.dirname txt.name)
~filter:"*.{ml,mli}"
~file:(Filename.basename txt.name)
~sync:true ~usepath:false ()
end;
file_menu#add_command "Close File" ~command:self#close_file;
file_menu#add_command "Close Window" ~command:self#quit ~underline:6;
(* Edit menu *)
edit_menu#add_command "Paste selection" ~command:
begin fun () ->
Text.insert current_tw ~index:(`Mark"insert",[])
~text:(Selection.get ~displayof:top ())
end;
edit_menu#add_command "Goto..." ~accelerator:"C-g"
~command:(fun () -> goto_line current_tw);
edit_menu#add_command "Search..." ~accelerator:"C-s"
~command:(fun () -> Jg_text.search_string current_tw);
edit_menu#add_command "To shell" ~accelerator:"M-x"
~command:(fun () -> send_phrase (List.hd windows));
edit_menu#add_command "Select shell..."
~command:(fun () -> select_shell (List.hd windows));
Compiler menu
compiler_menu#add_command "Preferences..."
~command:(fun () -> compiler_preferences top);
compiler_menu#add_command "Lex" ~accelerator:"M-l"
~command:self#lex;
compiler_menu#add_command "Typecheck" ~accelerator:"M-t"
~command:self#typecheck;
compiler_menu#add_command "Clear errors"
~command:self#clear_errors;
compiler_menu#add_command "Signature..." ~command:
begin fun () ->
let txt = List.hd windows in if txt.signature <> [] then
let basename = Filename.basename txt.name in
let modname = String.capitalize
(try Filename.chop_extension basename with _ -> basename) in
let env =
Env.add_module (Ident.create modname)
(Types.Tmty_signature txt.signature)
Env.initial
in Viewer.view_defined (Longident.Lident modname) ~env ~show_all:true
end;
(* Modules *)
module_menu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir:current_dir);
module_menu#add_command "Reset cache"
~command:(fun () -> Setpath.exec_update_hooks (); Env.reset_cache ());
module_menu#add_command "Search symbol..."
~command:Viewer.search_symbol;
module_menu#add_command "Close all"
~command:Viewer.close_all_views;
end
(* The main function starts here ! *)
let already_open : editor list ref = ref []
let editor ?file ?(pos=0) ?(reuse=false) () =
if !already_open <> [] &&
let ed = List.hd !already_open
try
let name = match file with Some f - > f | None - > raise Not_found in
List.find ! already_open ~f:(fun ed - > ed#has_window name )
with Not_found - > List.hd ! already_open
let name = match file with Some f -> f | None -> raise Not_found in
List.find !already_open ~f:(fun ed -> ed#has_window name)
with Not_found -> List.hd !already_open *)
in try
ed#reopen ~file ~pos;
true
with Protocol.TkError _ ->
List.filter ! already_open ~f :(( < > ) ed )
false
then () else
let top = Jg_toplevel.titled "OCamlBrowser Editor" in
let menus = Jg_menu.menubar top in
let ed = new editor ~top ~menus in
already_open := !already_open @ [ed];
if file <> None then ed#reopen ~file ~pos
let f ?file ?pos ?(opendialog=false) () =
if opendialog then
Fileselect.f ~title:"Open File"
~action:(function [file] -> editor ~file () | _ -> ())
~filter:("*.{ml,mli}") ~sync:true ()
else editor ?file ?pos ~reuse:(file <> None) ()
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/browser/editor.ml | ocaml | ***********************************************************************
Objective Caml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
***********************************************************************
~state:(if !use_pp then `Normal else`Disabled)
The editor class
Bindings for the main window
File menu
Edit menu
Modules
The main function starts here ! | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ I d : editor.ml , v 1.41 2006/01/04 16:55:50 doligez Exp $
open StdLabels
open Tk
open Parsetree
open Location
open Jg_tk
open Mytypes
let lex_on_load = ref true
and type_on_load = ref false
let compiler_preferences master =
let tl = Jg_toplevel.titled "Compiler" in
Wm.transient_set tl ~master;
let mk_chkbutton ~text ~ref ~invert =
let variable = Textvariable.create ~on:tl () in
if (if invert then not !ref else !ref) then
Textvariable.set variable "1";
Checkbutton.create tl ~text ~variable,
(fun () ->
ref := Textvariable.get variable = (if invert then "0" else "1"))
in
let use_pp = ref (!Clflags.preprocessor <> None) in
let chkbuttons, setflags = List.split
(List.map
~f:(fun (text, ref, invert) -> mk_chkbutton ~text ~ref ~invert)
[ "No pervasives", Clflags.nopervasives, false;
"No warnings", Typecheck.nowarnings, false;
"No labels", Clflags.classic, false;
"Recursive types", Clflags.recursive_types, false;
"Lex on load", lex_on_load, false;
"Type on load", type_on_load, false;
"Preprocessor", use_pp, false ])
in
begin match !Clflags.preprocessor with None -> ()
| Some pp -> Entry.insert pp_command ~index:(`Num 0) ~text:pp
end;
let buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok" ~padx:20 ~command:
begin fun () ->
List.iter ~f:(fun f -> f ()) setflags;
Clflags.preprocessor :=
if !use_pp then Some (Entry.get pp_command) else None;
destroy tl
end
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel"
in
pack chkbuttons ~side:`Top ~anchor:`W;
pack [pp_command] ~side:`Top ~anchor:`E;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true;
pack [buttons] ~side:`Bottom ~fill:`X
let rec exclude txt = function
[] -> []
| x :: l -> if txt.number = x.number then l else x :: exclude txt l
let goto_line tw =
let tl = Jg_toplevel.titled "Go to" in
Wm.transient_set tl ~master:(Winfo.toplevel tw);
Jg_bind.escape_destroy tl;
let ef = Frame.create tl in
let fl = Frame.create ef
and fi = Frame.create ef in
let ll = Label.create fl ~text:"Line ~number:"
and il = Entry.create fi ~width:10
and lc = Label.create fl ~text:"Col ~number:"
and ic = Entry.create fi ~width:10
and get_int ew =
try int_of_string (Entry.get ew)
with Failure "int_of_string" -> 0
in
let buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok" ~command:
begin fun () ->
let l = get_int il
and c = get_int ic in
Text.mark_set tw ~mark:"insert" ~index:(`Linechar (l,0), [`Char c]);
Text.see tw ~index:(`Mark "insert", []);
destroy tl
end
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel" in
Focus.set il;
List.iter [il; ic] ~f:
begin fun w ->
Jg_bind.enter_focus w;
Jg_bind.return_invoke w ~button:ok
end;
pack [ll; lc] ~side:`Top ~anchor:`W;
pack [il; ic] ~side:`Top ~fill:`X ~expand:true;
pack [fl; fi] ~side:`Left ~fill:`X ~expand:true;
pack [ok; cancel] ~side:`Left ~fill:`X ~expand:true;
pack [ef; buttons] ~side:`Top ~fill:`X ~expand:true
let select_shell txt =
let shells = Shell.get_all () in
let shells = List.sort shells ~cmp:compare in
let tl = Jg_toplevel.titled "Select Shell" in
Jg_bind.escape_destroy tl;
Wm.transient_set tl ~master:(Winfo.toplevel txt.tw);
let label = Label.create tl ~text:"Send to:"
and box = Listbox.create tl
and frame = Frame.create tl in
Jg_bind.enter_focus box;
let cancel = Jg_button.create_destroyer tl ~parent:frame ~text:"Cancel"
and ok = Button.create frame ~text:"Ok" ~command:
begin fun () ->
try
let name = Listbox.get box ~index:`Active in
txt.shell <- Some (name, List.assoc name shells);
destroy tl
with Not_found -> txt.shell <- None; destroy tl
end
in
Listbox.insert box ~index:`End ~texts:(List.map ~f:fst shells);
Listbox.configure box ~height:(List.length shells);
bind box ~events:[`KeyPressDetail"Return"] ~breakable:true
~action:(fun _ -> Button.invoke ok; break ());
bind box ~events:[`Modified([`Double],`ButtonPressDetail 1)] ~breakable:true
~fields:[`MouseX;`MouseY]
~action:(fun ev ->
Listbox.activate box ~index:(`Atxy (ev.ev_MouseX, ev.ev_MouseY));
Button.invoke ok; break ());
pack [label] ~side:`Top ~anchor:`W;
pack [box] ~side:`Top ~fill:`Both;
pack [frame] ~side:`Bottom ~fill:`X ~expand:true;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true
open Parser
let send_phrase txt =
if txt.shell = None then begin
match Shell.get_all () with [] -> ()
| [sh] -> txt.shell <- Some sh
| l -> select_shell txt
end;
match txt.shell with None -> ()
| Some (_,sh) ->
try
let i1,i2 = Text.tag_nextrange txt.tw ~tag:"sel" ~start:tstart in
let phrase = Text.get txt.tw ~start:(i1,[]) ~stop:(i2,[]) in
sh#send phrase;
if Str.string_match (Str.regexp ";;") phrase 0
then sh#send "\n" else sh#send ";;\n"
with Not_found | Protocol.TkError _ ->
let text = Text.get txt.tw ~start:tstart ~stop:tend in
let buffer = Lexing.from_string text in
let start = ref 0
and block_start = ref []
and pend = ref (-1)
and after = ref false in
while !pend = -1 do
let token = Lexer.token buffer in
let pos =
if token = SEMISEMI then Lexing.lexeme_end buffer
else Lexing.lexeme_start buffer
in
let bol = (pos = 0) || text.[pos-1] = '\n' in
if not !after &&
Text.compare txt.tw ~index:(tpos pos) ~op:(if bol then `Gt else `Ge)
~index:(`Mark"insert",[])
then begin
after := true;
let anon, real =
List.partition !block_start ~f:(fun x -> x = -1) in
block_start := anon;
if real <> [] then start := List.hd real;
end;
match token with
CLASS | EXTERNAL | EXCEPTION | FUNCTOR
| LET | MODULE | OPEN | TYPE | VAL | SHARP when bol ->
if !block_start = [] then
if !after then pend := pos else start := pos
else block_start := pos :: List.tl !block_start
| SEMISEMI ->
if !block_start = [] then
if !after then pend := Lexing.lexeme_start buffer
else start := pos
else block_start := pos :: List.tl !block_start
| BEGIN | OBJECT ->
block_start := -1 :: !block_start
| STRUCT | SIG ->
block_start := Lexing.lexeme_end buffer :: !block_start
| END ->
if !block_start = [] then
if !after then pend := pos else ()
else block_start := List.tl !block_start
| EOF ->
pend := pos
| _ ->
()
done;
let phrase = String.sub text ~pos:!start ~len:(!pend - !start) in
sh#send phrase;
sh#send ";;\n"
let search_pos_window txt ~x ~y =
if txt.type_info = [] && txt.psignature = [] then () else
let `Linechar (l, c) = Text.index txt.tw ~index:(`Atxy(x,y), []) in
let text = Jg_text.get_all txt.tw in
let pos = Searchpos.lines_to_chars l ~text + c in
try if txt.type_info <> [] then begin match
Searchpos.search_pos_info txt.type_info ~pos
with [] -> ()
| (kind, env, loc) :: _ -> Searchpos.view_type kind ~env
end else begin match
Searchpos.search_pos_signature txt.psignature ~pos ~env:!Searchid.start_env
with [] -> ()
| ((kind, lid), env, loc) :: _ ->
Searchpos.view_decl lid ~kind ~env
end
with Not_found -> ()
let search_pos_menu txt ~x ~y =
if txt.type_info = [] && txt.psignature = [] then () else
let `Linechar (l, c) = Text.index txt.tw ~index:(`Atxy(x,y), []) in
let text = Jg_text.get_all txt.tw in
let pos = Searchpos.lines_to_chars l ~text + c in
try if txt.type_info <> [] then begin match
Searchpos.search_pos_info txt.type_info ~pos
with [] -> ()
| (kind, env, loc) :: _ ->
let menu = Searchpos.view_type_menu kind ~env ~parent:txt.tw in
let x = x + Winfo.rootx txt.tw and y = y + Winfo.rooty txt.tw - 10 in
Menu.popup menu ~x ~y
end else begin match
Searchpos.search_pos_signature txt.psignature ~pos ~env:!Searchid.start_env
with [] -> ()
| ((kind, lid), env, loc) :: _ ->
let menu = Searchpos.view_decl_menu lid ~kind ~env ~parent:txt.tw in
let x = x + Winfo.rootx txt.tw and y = y + Winfo.rooty txt.tw - 10 in
Menu.popup menu ~x ~y
end
with Not_found -> ()
let string_width s =
let width = ref 0 in
for i = 0 to String.length s - 1 do
if s.[i] = '\t' then width := (!width / 8 + 1) * 8
else incr width
done;
!width
let indent_line =
let ins = `Mark"insert" and reg = Str.regexp "[ \t]*" in
fun tw ->
let `Linechar(l,c) = Text.index tw ~index:(ins,[])
and line = Text.get tw ~start:(ins,[`Linestart]) ~stop:(ins,[`Lineend]) in
ignore (Str.string_match reg line 0);
let len = Str.match_end () in
if len < c then Text.insert tw ~index:(ins,[]) ~text:"\t" else
let width = string_width (Str.matched_string line) in
Text.mark_set tw ~mark:"insert" ~index:(ins,[`Linestart;`Char len]);
let indent =
if l <= 1 then 2 else
let previous =
Text.get tw ~start:(ins,[`Line(-1);`Linestart])
~stop:(ins,[`Line(-1);`Lineend]) in
ignore (Str.string_match reg previous 0);
let previous = Str.matched_string previous in
let width_previous = string_width previous in
if width_previous <= width then 2 else width_previous - width
in
Text.insert tw ~index:(ins,[]) ~text:(String.make indent ' ')
class editor ~top ~menus = object (self)
val file_menu = new Jg_menu.c "File" ~parent:menus
val edit_menu = new Jg_menu.c "Edit" ~parent:menus
val compiler_menu = new Jg_menu.c "Compiler" ~parent:menus
val module_menu = new Jg_menu.c "Modules" ~parent:menus
val window_menu = new Jg_menu.c "Windows" ~parent:menus
initializer
Menu.add_checkbutton menus ~state:`Disabled
~onvalue:"modified" ~offvalue:"unchanged"
val mutable current_dir = Unix.getcwd ()
val mutable error_messages = []
val mutable windows = []
val mutable current_tw = Text.create top
val vwindow = Textvariable.create ~on:top ()
val mutable window_counter = 0
method has_window name =
List.exists windows ~f:(fun x -> x.name = name)
method reset_window_menu =
Menu.delete window_menu#menu ~first:(`Num 0) ~last:`End;
List.iter
(List.sort windows ~cmp:
(fun w1 w2 ->
compare (Filename.basename w1.name) (Filename.basename w2.name)))
~f:
begin fun txt ->
Menu.add_radiobutton window_menu#menu
~label:(Filename.basename txt.name)
~variable:vwindow ~value:txt.number
~command:(fun () -> self#set_edit txt)
end
method set_file_name txt =
Menu.configure_checkbutton menus `Last
~label:(Filename.basename txt.name)
~variable:txt.modified
method set_edit txt =
if windows <> [] then
Pack.forget [(List.hd windows).frame];
windows <- txt :: exclude txt windows;
self#reset_window_menu;
current_tw <- txt.tw;
self#set_file_name txt;
Textvariable.set vwindow txt.number;
Text.yview txt.tw ~scroll:(`Page 0);
pack [txt.frame] ~fill:`Both ~expand:true ~side:`Bottom
method new_window name =
let tl, tw, sb = Jg_text.create_with_scrollbar top in
Text.configure tw ~background:`White;
Jg_bind.enter_focus tw;
window_counter <- window_counter + 1;
let txt =
{ name = name; tw = tw; frame = tl;
number = string_of_int window_counter;
modified = Textvariable.create ~on:tw ();
shell = None;
structure = []; type_info = []; signature = []; psignature = [] }
in
let control c = Char.chr (Char.code c - 96) in
bind tw ~events:[`Modified([`Alt], `KeyPress)] ~action:ignore;
bind tw ~events:[`KeyPress] ~fields:[`Char]
~action:(fun ev ->
if ev.ev_Char <> "" &&
(ev.ev_Char.[0] >= ' ' ||
List.mem ev.ev_Char.[0]
(List.map ~f:control ['d'; 'h'; 'i'; 'k'; 'o'; 't'; 'w'; 'y']))
then Textvariable.set txt.modified "modified");
bind tw ~events:[`KeyPressDetail"Tab"] ~breakable:true
~action:(fun _ ->
indent_line tw;
Textvariable.set txt.modified "modified";
break ());
bind tw ~events:[`Modified([`Control],`KeyPressDetail"k")]
~action:(fun _ ->
let text =
Text.get tw ~start:(`Mark"insert",[]) ~stop:(`Mark"insert",[`Lineend])
in ignore (Str.string_match (Str.regexp "[ \t]*") text 0);
if Str.match_end () <> String.length text then begin
Clipboard.clear ();
Clipboard.append ~data:text ()
end);
bind tw ~events:[`KeyRelease] ~fields:[`Char]
~action:(fun ev ->
if ev.ev_Char <> "" then
Lexical.tag tw ~start:(`Mark"insert", [`Linestart])
~stop:(`Mark"insert", [`Lineend]));
bind tw ~events:[`Motion] ~action:(fun _ -> Focus.set tw);
bind tw ~events:[`ButtonPressDetail 2]
~action:(fun _ ->
Textvariable.set txt.modified "modified";
Lexical.tag txt.tw ~start:(`Mark"insert", [`Linestart])
~stop:(`Mark"insert", [`Lineend]));
bind tw ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~fields:[`MouseX;`MouseY]
~action:(fun ev -> search_pos_window txt ~x:ev.ev_MouseX ~y:ev.ev_MouseY);
bind tw ~events:[`ButtonPressDetail 3] ~fields:[`MouseX;`MouseY]
~action:(fun ev -> search_pos_menu txt ~x:ev.ev_MouseX ~y:ev.ev_MouseY);
pack [sb] ~fill:`Y ~side:`Right;
pack [tw] ~fill:`Both ~expand:true ~side:`Left;
self#set_edit txt;
Textvariable.set txt.modified "unchanged";
Lexical.init_tags txt.tw
method clear_errors () =
Text.tag_remove current_tw ~tag:"error" ~start:tstart ~stop:tend;
List.iter error_messages
~f:(fun tl -> try destroy tl with Protocol.TkError _ -> ());
error_messages <- []
method typecheck () =
self#clear_errors ();
error_messages <- Typecheck.f (List.hd windows)
method lex () =
List.iter [ Widget.default_toplevel; top ]
~f:(Toplevel.configure ~cursor:(`Xcursor "watch"));
Text.configure current_tw ~cursor:(`Xcursor "watch");
ignore (Timer.add ~ms:1 ~callback:
begin fun () ->
Text.tag_remove current_tw ~tag:"error" ~start:tstart ~stop:tend;
Lexical.tag current_tw;
Text.configure current_tw ~cursor:(`Xcursor "xterm");
List.iter [ Widget.default_toplevel; top ]
~f:(Toplevel.configure ~cursor:(`Xcursor ""))
end)
method save_text ?name:l txt =
let l = match l with None -> [txt.name] | Some l -> l in
if l = [] then () else
let name = List.hd l in
if txt.name <> name then current_dir <- Filename.dirname name;
try
if Sys.file_exists name then
if txt.name = name then begin
let backup = name ^ "~" in
if Sys.file_exists backup then Sys.remove backup;
try Sys.rename name backup with Sys_error _ -> ()
end else begin
match Jg_message.ask ~master:top ~title:"Save"
("File `" ^ name ^ "' exists. Overwrite it?")
with `Yes -> Sys.remove name
| `No -> raise (Sys_error "")
| `Cancel -> raise Exit
end;
let file = open_out name in
let text = Text.get txt.tw ~start:tstart ~stop:(tposend 1) in
output_string file text;
close_out file;
txt.name <- name;
self#set_file_name txt
with
Sys_error _ ->
Jg_message.info ~master:top ~title:"Error"
("Could not save `" ^ name ^ "'.")
| Exit -> ()
method load_text l =
if l = [] then () else
let name = List.hd l in
try
let index =
try
self#set_edit (List.find windows ~f:(fun x -> x.name = name));
let txt = List.hd windows in
if Textvariable.get txt.modified = "modified" then
begin match Jg_message.ask ~master:top ~title:"Open"
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
Textvariable.set txt.modified "unchanged";
(Text.index current_tw ~index:(`Mark"insert", []), [])
with Not_found -> self#new_window name; tstart
in
current_dir <- Filename.dirname name;
let file = open_in name
and tw = current_tw
and len = ref 0
and buf = String.create 4096 in
Text.delete tw ~start:tstart ~stop:tend;
while
len := input file buf 0 4096;
!len > 0
do
Jg_text.output tw ~buf ~pos:0 ~len:!len
done;
close_in file;
Text.mark_set tw ~mark:"insert" ~index;
Text.see tw ~index;
if Filename.check_suffix name ".ml" ||
Filename.check_suffix name ".mli"
then begin
if !lex_on_load then self#lex ();
if !type_on_load then self#typecheck ()
end
with
Sys_error _ | Exit -> ()
method close_window txt =
try
if Textvariable.get txt.modified = "modified" then
begin match Jg_message.ask ~master:top ~title:"Close"
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
windows <- exclude txt windows;
if windows = [] then
self#new_window (current_dir ^ "/untitled")
else self#set_edit (List.hd windows);
destroy txt.frame
with Exit -> ()
method open_file () =
Fileselect.f ~title:"Open File" ~action:self#load_text
~dir:current_dir ~filter:("*.{ml,mli}") ~sync:true ()
method save_file () = self#save_text (List.hd windows)
method close_file () = self#close_window (List.hd windows)
method quit ?(cancel=true) () =
try
List.iter windows ~f:
begin fun txt ->
if Textvariable.get txt.modified = "modified" then
match Jg_message.ask ~master:top ~title:"Quit" ~cancel
("`" ^ Filename.basename txt.name ^ "' modified. Save it?")
with `Yes -> self#save_text txt
| `No -> ()
| `Cancel -> raise Exit
end;
bind top ~events:[`Destroy];
destroy top
with Exit -> ()
method reopen ~file ~pos =
if not (Winfo.ismapped top) then Wm.deiconify top;
match file with None -> ()
| Some file ->
self#load_text [file];
Text.mark_set current_tw ~mark:"insert" ~index:(tpos pos);
try
let index =
Text.search current_tw ~switches:[`Backwards] ~pattern:"*)"
~start:(tpos pos) ~stop:(tpos pos ~modi:[`Line(-1)]) in
let index =
Text.search current_tw ~switches:[`Backwards] ~pattern:"(*"
~start:(index,[]) ~stop:(tpos pos ~modi:[`Line(-20)]) in
let s = Text.get current_tw ~start:(index,[`Line(-1);`Linestart])
~stop:(index,[`Line(-1);`Lineend]) in
for i = 0 to String.length s - 1 do
match s.[i] with '\t'|' ' -> () | _ -> raise Not_found
done;
Text.yview_index current_tw ~index:(index,[`Line(-1)])
with _ ->
Text.yview_index current_tw ~index:(tpos pos ~modi:[`Line(-2)])
initializer
Create a first window
self#new_window (current_dir ^ "/untitled");
List.iter
[ [`Control], "s", (fun () -> Jg_text.search_string current_tw);
[`Control], "g", (fun () -> goto_line current_tw);
[`Alt], "s", self#save_file;
[`Alt], "x", (fun () -> send_phrase (List.hd windows));
[`Alt], "l", self#lex;
[`Alt], "t", self#typecheck ]
~f:begin fun (modi,key,act) ->
bind top ~events:[`Modified(modi, `KeyPressDetail key)] ~breakable:true
~action:(fun _ -> act (); break ())
end;
bind top ~events:[`Destroy] ~fields:[`Widget] ~action:
begin fun ev ->
if Widget.name ev.ev_Widget = Widget.name top
then self#quit ~cancel:false ()
end;
file_menu#add_command "Open File..." ~command:self#open_file;
file_menu#add_command "Reopen"
~command:(fun () -> self#load_text [(List.hd windows).name]);
file_menu#add_command "Save File" ~command:self#save_file ~accelerator:"M-s";
file_menu#add_command "Save As..." ~underline:5 ~command:
begin fun () ->
let txt = List.hd windows in
Fileselect.f ~title:"Save as File"
~action:(fun name -> self#save_text txt ~name)
~dir:(Filename.dirname txt.name)
~filter:"*.{ml,mli}"
~file:(Filename.basename txt.name)
~sync:true ~usepath:false ()
end;
file_menu#add_command "Close File" ~command:self#close_file;
file_menu#add_command "Close Window" ~command:self#quit ~underline:6;
edit_menu#add_command "Paste selection" ~command:
begin fun () ->
Text.insert current_tw ~index:(`Mark"insert",[])
~text:(Selection.get ~displayof:top ())
end;
edit_menu#add_command "Goto..." ~accelerator:"C-g"
~command:(fun () -> goto_line current_tw);
edit_menu#add_command "Search..." ~accelerator:"C-s"
~command:(fun () -> Jg_text.search_string current_tw);
edit_menu#add_command "To shell" ~accelerator:"M-x"
~command:(fun () -> send_phrase (List.hd windows));
edit_menu#add_command "Select shell..."
~command:(fun () -> select_shell (List.hd windows));
Compiler menu
compiler_menu#add_command "Preferences..."
~command:(fun () -> compiler_preferences top);
compiler_menu#add_command "Lex" ~accelerator:"M-l"
~command:self#lex;
compiler_menu#add_command "Typecheck" ~accelerator:"M-t"
~command:self#typecheck;
compiler_menu#add_command "Clear errors"
~command:self#clear_errors;
compiler_menu#add_command "Signature..." ~command:
begin fun () ->
let txt = List.hd windows in if txt.signature <> [] then
let basename = Filename.basename txt.name in
let modname = String.capitalize
(try Filename.chop_extension basename with _ -> basename) in
let env =
Env.add_module (Ident.create modname)
(Types.Tmty_signature txt.signature)
Env.initial
in Viewer.view_defined (Longident.Lident modname) ~env ~show_all:true
end;
module_menu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir:current_dir);
module_menu#add_command "Reset cache"
~command:(fun () -> Setpath.exec_update_hooks (); Env.reset_cache ());
module_menu#add_command "Search symbol..."
~command:Viewer.search_symbol;
module_menu#add_command "Close all"
~command:Viewer.close_all_views;
end
let already_open : editor list ref = ref []
let editor ?file ?(pos=0) ?(reuse=false) () =
if !already_open <> [] &&
let ed = List.hd !already_open
try
let name = match file with Some f - > f | None - > raise Not_found in
List.find ! already_open ~f:(fun ed - > ed#has_window name )
with Not_found - > List.hd ! already_open
let name = match file with Some f -> f | None -> raise Not_found in
List.find !already_open ~f:(fun ed -> ed#has_window name)
with Not_found -> List.hd !already_open *)
in try
ed#reopen ~file ~pos;
true
with Protocol.TkError _ ->
List.filter ! already_open ~f :(( < > ) ed )
false
then () else
let top = Jg_toplevel.titled "OCamlBrowser Editor" in
let menus = Jg_menu.menubar top in
let ed = new editor ~top ~menus in
already_open := !already_open @ [ed];
if file <> None then ed#reopen ~file ~pos
let f ?file ?pos ?(opendialog=false) () =
if opendialog then
Fileselect.f ~title:"Open File"
~action:(function [file] -> editor ~file () | _ -> ())
~filter:("*.{ml,mli}") ~sync:true ()
else editor ?file ?pos ~reuse:(file <> None) ()
|
b7aa93d41a6f1e61fec69b9f1ccbc68f05b85e5db1fa146a6c1f7dadcf6c82eb | ekmett/hask | Tensor.hs | # LANGUAGE KindSignatures , PolyKinds , MultiParamTypeClasses , FunctionalDependencies , ConstraintKinds , NoImplicitPrelude , TypeFamilies , TypeOperators , FlexibleContexts , FlexibleInstances , UndecidableInstances , UndecidableSuperClasses , RankNTypes , GADTs , ScopedTypeVariables , DataKinds , AllowAmbiguousTypes , LambdaCase , DefaultSignatures , EmptyCase #
module Hask.Tensor
(
-- * Tensors
Semitensor(..), I, Tensor'(..), Tensor, semitensorClosed
-- * Monoids
, Semigroup(..), Monoid'(..), Monoid
* Comonoids ( Opmonoids )
, Cosemigroup(..), Comonoid'(..), Comonoid
) where
import Hask.Category
import Hask.Iso
import Data.Void
--------------------------------------------------------------------------------
* Monoidal Tensors and Monoids
--------------------------------------------------------------------------------
class (Bifunctor p, Dom p ~ Dom2 p, Dom p ~ Cod2 p) => Semitensor p where
associate :: (Ob (Dom p) a, Ob (Dom p) b, Ob (Dom p) c, Ob (Dom p) a', Ob (Dom p) b', Ob (Dom p) c')
=> Iso (Dom p) (Dom p) (->)
(p (p a b) c) (p (p a' b') c')
(p a (p b c)) (p a' (p b' c'))
semitensorClosed :: forall c t x y. (Semitensor t, Category c, Dom t ~ c, Ob c x, Ob c y) => Dict (Ob c (t x y))
semitensorClosed = case ob :: Ob c x :- FunctorOf c c (t x) of
Sub Dict -> case ob :: Ob c y :- Ob c (t x y) of
Sub Dict -> Dict
type family I (p :: i -> i -> i) :: i
class Semitensor p => Tensor' p where
lambda :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p (I p) a) (p (I p) a') a a'
rho :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p a (I p)) (p a' (I p)) a a'
class (Monoid' p (I p), Tensor' p) => Tensor p
instance (Monoid' p (I p), Tensor' p) => Tensor p
class Semitensor p => Semigroup p m where
mu :: Dom p (p m m) m
class (Semigroup p m, Tensor' p) => Monoid' p m where
eta :: NatId p -> Dom p (I p) m
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
class Semitensor p => Cosemigroup p w where
delta :: Dom p w (p w w)
class (Cosemigroup p w, Tensor' p) => Comonoid' p w where
epsilon :: NatId p -> Dom p w (I p)
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
--------------------------------------------------------------------------------
-- * (&)
--------------------------------------------------------------------------------
class (p, q) => p & q
instance (p, q) => p & q
instance Functor (&) where
type Dom (&) = (:-)
type Cod (&) = Nat (:-) (:-)
fmap f = Nat $ Sub $ Dict \\ f
instance Functor ((&) a) where
type Dom ((&) a) = (:-)
type Cod ((&) a) = (:-)
fmap f = Sub $ Dict \\ f
instance Semitensor (&) where
associate = dimap (Sub Dict) (Sub Dict)
type instance I (&) = (() :: Constraint)
instance Tensor' (&) where
lambda = dimap (Sub Dict) (Sub Dict)
rho = dimap (Sub Dict) (Sub Dict)
instance Semigroup (&) a where
mu = Sub Dict
instance Monoid' (&) (() :: Constraint) where
eta _ = Sub Dict
instance Cosemigroup (&) a where
delta = Sub Dict
instance Comonoid' (&) a where
epsilon _ = Sub Dict
--------------------------------------------------------------------------------
-- * (,) and ()
--------------------------------------------------------------------------------
instance Semitensor (,) where
associate = dimap (\((a,b),c) -> (a,(b,c))) (\(a,(b,c)) -> ((a,b),c))
type instance I (,) = ()
instance Tensor' (,) where
lambda = dimap (\ ~(_,a) -> a) ((,)())
rho = dimap (\ ~(a,_) -> a) (\a -> (a,()))
instance Semigroup (,) () where
mu ((),()) = ()
instance Monoid' (,) () where
eta _ = id
instance Cosemigroup (,) a where
delta a = (a,a)
instance Comonoid' (,) a where
epsilon _ _ = ()
--------------------------------------------------------------------------------
-- * Either and Void
--------------------------------------------------------------------------------
instance Semitensor Either where
associate = dimap hither yon where
hither (Left (Left a)) = Left a
hither (Left (Right b)) = Right (Left b)
hither (Right c) = Right (Right c)
yon (Left a) = Left (Left a)
yon (Right (Left b)) = Left (Right b)
yon (Right (Right c)) = Right c
type instance I Either = Void
instance Tensor' Either where
lambda = dimap (\(Right a) -> a) Right
rho = dimap (\(Left a) -> a) Left
instance Semigroup (,) Void where
mu (a,_) = a
instance Semigroup Either Void where
mu (Left a) = a
mu (Right b) = b
instance Monoid' Either Void where
eta _ = absurd
instance Cosemigroup Either Void where
delta = absurd
instance Comonoid' Either Void where
epsilon _ = id
| null | https://raw.githubusercontent.com/ekmett/hask/54ea964af8e0c1673ac2699492f4c07d977cb3c8/src/Hask/Tensor.hs | haskell | * Tensors
* Monoids
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
* (&)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
* (,) and ()
------------------------------------------------------------------------------
------------------------------------------------------------------------------
* Either and Void
------------------------------------------------------------------------------ | # LANGUAGE KindSignatures , PolyKinds , MultiParamTypeClasses , FunctionalDependencies , ConstraintKinds , NoImplicitPrelude , TypeFamilies , TypeOperators , FlexibleContexts , FlexibleInstances , UndecidableInstances , UndecidableSuperClasses , RankNTypes , GADTs , ScopedTypeVariables , DataKinds , AllowAmbiguousTypes , LambdaCase , DefaultSignatures , EmptyCase #
module Hask.Tensor
(
Semitensor(..), I, Tensor'(..), Tensor, semitensorClosed
, Semigroup(..), Monoid'(..), Monoid
* Comonoids ( Opmonoids )
, Cosemigroup(..), Comonoid'(..), Comonoid
) where
import Hask.Category
import Hask.Iso
import Data.Void
* Monoidal Tensors and Monoids
class (Bifunctor p, Dom p ~ Dom2 p, Dom p ~ Cod2 p) => Semitensor p where
associate :: (Ob (Dom p) a, Ob (Dom p) b, Ob (Dom p) c, Ob (Dom p) a', Ob (Dom p) b', Ob (Dom p) c')
=> Iso (Dom p) (Dom p) (->)
(p (p a b) c) (p (p a' b') c')
(p a (p b c)) (p a' (p b' c'))
semitensorClosed :: forall c t x y. (Semitensor t, Category c, Dom t ~ c, Ob c x, Ob c y) => Dict (Ob c (t x y))
semitensorClosed = case ob :: Ob c x :- FunctorOf c c (t x) of
Sub Dict -> case ob :: Ob c y :- Ob c (t x y) of
Sub Dict -> Dict
type family I (p :: i -> i -> i) :: i
class Semitensor p => Tensor' p where
lambda :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p (I p) a) (p (I p) a') a a'
rho :: (Ob (Dom p) a, Ob (Dom p) a') => Iso (Dom p) (Dom p) (->) (p a (I p)) (p a' (I p)) a a'
class (Monoid' p (I p), Tensor' p) => Tensor p
instance (Monoid' p (I p), Tensor' p) => Tensor p
class Semitensor p => Semigroup p m where
mu :: Dom p (p m m) m
class (Semigroup p m, Tensor' p) => Monoid' p m where
eta :: NatId p -> Dom p (I p) m
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Monoid' p m) => Monoid p m
class Semitensor p => Cosemigroup p w where
delta :: Dom p w (p w w)
class (Cosemigroup p w, Tensor' p) => Comonoid' p w where
epsilon :: NatId p -> Dom p w (I p)
class (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
instance (Monoid' p (I p), Comonoid' p (I p), Tensor' p, Comonoid' p w) => Comonoid p w
class (p, q) => p & q
instance (p, q) => p & q
instance Functor (&) where
type Dom (&) = (:-)
type Cod (&) = Nat (:-) (:-)
fmap f = Nat $ Sub $ Dict \\ f
instance Functor ((&) a) where
type Dom ((&) a) = (:-)
type Cod ((&) a) = (:-)
fmap f = Sub $ Dict \\ f
instance Semitensor (&) where
associate = dimap (Sub Dict) (Sub Dict)
type instance I (&) = (() :: Constraint)
instance Tensor' (&) where
lambda = dimap (Sub Dict) (Sub Dict)
rho = dimap (Sub Dict) (Sub Dict)
instance Semigroup (&) a where
mu = Sub Dict
instance Monoid' (&) (() :: Constraint) where
eta _ = Sub Dict
instance Cosemigroup (&) a where
delta = Sub Dict
instance Comonoid' (&) a where
epsilon _ = Sub Dict
instance Semitensor (,) where
associate = dimap (\((a,b),c) -> (a,(b,c))) (\(a,(b,c)) -> ((a,b),c))
type instance I (,) = ()
instance Tensor' (,) where
lambda = dimap (\ ~(_,a) -> a) ((,)())
rho = dimap (\ ~(a,_) -> a) (\a -> (a,()))
instance Semigroup (,) () where
mu ((),()) = ()
instance Monoid' (,) () where
eta _ = id
instance Cosemigroup (,) a where
delta a = (a,a)
instance Comonoid' (,) a where
epsilon _ _ = ()
instance Semitensor Either where
associate = dimap hither yon where
hither (Left (Left a)) = Left a
hither (Left (Right b)) = Right (Left b)
hither (Right c) = Right (Right c)
yon (Left a) = Left (Left a)
yon (Right (Left b)) = Left (Right b)
yon (Right (Right c)) = Right c
type instance I Either = Void
instance Tensor' Either where
lambda = dimap (\(Right a) -> a) Right
rho = dimap (\(Left a) -> a) Left
instance Semigroup (,) Void where
mu (a,_) = a
instance Semigroup Either Void where
mu (Left a) = a
mu (Right b) = b
instance Monoid' Either Void where
eta _ = absurd
instance Cosemigroup Either Void where
delta = absurd
instance Comonoid' Either Void where
epsilon _ = id
|
94115d3641b92aa064c6a5b262901f4d4968a3d18e41d3f4d91dee9b4e5d4e1f | monadbobo/ocaml-core | table_new.ml | pp camlp4o -I ` ocamlfind query sexplib ` -I ` ocamlfind query type_conv ` -I ` ocamlfind query bin_prot ` pa_type_conv.cmo pa_sexp_conv.cmo pa_bin_prot.cmo
open Core.Std
module Avltree = struct
type ('k, 'v) t =
| Empty
| Node of ('k, 'v) t * 'k * 'v * int * ('k, 'v) t
| Leaf of 'k * 'v
We do this ' crazy ' magic because we want to remove a level of
indirection in the tree . If we did n't do this , we 'd need to use a
record , and then the variant would be a block with a pointer to
the record . Where as now the ' record ' is tagged with the
constructor , thus removing a level of indirection . This is even
reasonably safe , certainly no more dangerous than a C binding .
The extra checking is probably free , since the block will already
be in L1 cache , and the branch predictor is very likely to
predict correctly .
indirection in the tree. If we didn't do this, we'd need to use a
record, and then the variant would be a block with a pointer to
the record. Where as now the 'record' is tagged with the
constructor, thus removing a level of indirection. This is even
reasonably safe, certainly no more dangerous than a C binding.
The extra checking is probably free, since the block will already
be in L1 cache, and the branch predictor is very likely to
predict correctly. *)
let set_field f n v = Obj.set_field (Obj.repr f) n (Obj.repr v)
let update_left (n: ('k, 'v) t) (u: ('k, 'v) t) : unit =
match n with
| Node _ -> set_field n 0 u
| _ -> assert false
let update_right (n: ('k, 'v) t) (u: ('k, 'v) t) : unit =
match n with
| Node _ -> set_field n 4 u
| _ -> assert false
let update_val (n : ('k, 'v) t) (u: 'v) : unit =
match n with
| Node _ -> set_field n 2 u
| _ -> assert false
let update_height (n: ('k, 'v) t) (u: int) : unit =
match n with
| Node _ -> set_field n 3 u
| _ -> assert false
let update_leaf_val (n: ('k, 'v) t) (u: 'v) : unit =
match n with
| Leaf _ -> set_field n 1 u
| _ -> assert false
let invariant t compare =
let rec binary_tree = function
| Empty | Leaf _ -> ()
| Node (left, key, _value, _height, right) ->
begin match left with
| Empty -> ()
| Leaf (left_key, _)
| Node (_, left_key, _, _, _) ->
assert (compare left_key key < 0)
end;
begin match right with
| Empty -> ()
| Leaf (right_key, _)
| Node (_, right_key, _, _, _) ->
assert (compare right_key key > 0)
end;
assert (compare key key = 0);
binary_tree left;
binary_tree right
in
let rec height = function
| Empty -> 0
| Leaf _ -> 1
| Node (left, _k, _v, _h, right) ->
Int.max (height left) (height right) + 1
in
let rec balanced = function
| Empty | Leaf _ -> ()
| Node (left, _k, _v, _h, right) ->
assert (abs (height left - height right) < 3);
balanced left;
balanced right
in
binary_tree t;
balanced t
let empty = Empty
let height = function
| Empty -> 0
| Leaf _ -> 1
| Node (_l, _k, _v, height, _r) -> height
let update_height n =
match n with
| Node (left, _, _, _, right) ->
let new_height = (Int.max (height left) (height right)) + 1 in
update_height n new_height
| _ -> assert false
let balance tree =
match tree with
| Empty | Leaf _ -> tree
| Node (left, _k, _v, _h, right) as root_node ->
let hl = height left and hr = height right in
+ 2 is critically important , lowering it to 1 will break the Leaf
assumptions in the code below , and will force us to promote leaf
nodes in the balance routine . It 's also faster , since it will
balance less often .
assumptions in the code below, and will force us to promote leaf
nodes in the balance routine. It's also faster, since it will
balance less often. *)
if hl > hr + 2 then begin
match left with
It can not be a leaf , because even if right is empty , a leaf
is only height 1
is only height 1 *)
| Empty | Leaf _ -> assert false
| Node (left_node_left, _, _, _, left_node_right) as left_node ->
if height left_node_left >= height left_node_right then begin
update_left root_node left_node_right;
update_right left_node root_node;
update_height root_node;
update_height left_node;
left_node
end else begin
if right is a leaf , then left must be empty . That means
height is 2 . Even if hr is empty we still ca n't get here .
height is 2. Even if hr is empty we still can't get here. *)
match left_node_right with
| Empty | Leaf _ -> assert false
| Node (lr_left, _, _, _, lr_right) as lr_node ->
update_right left_node lr_left;
update_left root_node lr_right;
update_right lr_node root_node;
update_left lr_node left_node;
update_height left_node;
update_height root_node;
update_height lr_node;
lr_node
end
end else if hr > hl + 2 then begin
(* see above for an explanation of why right cannot be a leaf *)
match right with
| Empty | Leaf _ -> assert false
| Node (right_node_left, _, _, _, right_node_right) as right_node ->
if height right_node_right >= height right_node_left then begin
update_right root_node right_node_left;
update_left right_node root_node;
update_height root_node;
update_height right_node;
right_node
end else begin
(* see above for an explanation of why this cannot be a leaf *)
match right_node_left with
| Empty | Leaf _ -> assert false
| Node (rl_left, _, _, _, rl_right) as rl_node ->
update_left right_node rl_right;
update_right root_node rl_left;
update_left rl_node root_node;
update_right rl_node right;
update_height right_node;
update_height root_node;
update_height rl_node;
rl_node
end
end else
tree
;;
let set_left node tree =
let tree = balance tree in
match node with
| Node (left, _, _, _, _) ->
if phys_equal left tree then ()
else
update_left node tree;
update_height node
| _ -> assert false
let set_right node tree =
let tree = balance tree in
match node with
| Node (_, _, _, _, right) ->
if phys_equal right tree then ()
else
update_right node tree;
update_height node
| _ -> assert false
let balance_root tree =
let tree = balance tree in
begin match tree with
| Empty | Leaf _ -> ()
| Node _ as node -> update_height node
end;
tree
let new_node k v = Node (Empty, k, v, 1, Empty)
let add =
let rec add t added compare k v =
match t with
| Empty ->
added := true;
Leaf (k, v)
| Leaf (k', _) ->
let c = compare k' k in
This compare is reversed on purpose , we are pretending
that the leaf was just inserted instead of the other way
round , that way we only allocate one node .
that the leaf was just inserted instead of the other way
round, that way we only allocate one node. *)
if c = 0 then begin
added := false;
update_leaf_val t v;
t
end else begin
(* going to be the new root node *)
let node = new_node k v in
added := true;
if c < 0 then set_left node t
else set_right node t;
node
end
| Node (left, k', _, _, right) ->
let c = compare k k' in
if c = 0 then begin
added := false;
update_val t v;
end else if c < 0 then
set_left t (add left added compare k v)
else
set_right t (add right added compare k v);
t
in
fun t compare ~added ~key ~data ->
balance_root (add t added compare key data)
let rec find t compare k =
A little manual unrolling of the recursion .
This is really worth 5 % on average
This is really worth 5% on average *)
match t with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else if c < 0 then begin
match left with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else find (if c < 0 then left else right) compare k
end else begin
match right with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else find (if c < 0 then left else right) compare k
end
;;
let mem t compare k = Option.is_some (find t compare k)
let rec min_elt tree =
match tree with
| Empty -> Empty
| Leaf _ -> tree
| Node (Empty, _, _, _, _) -> tree
| Node (left, _, _, _, _) -> min_elt left
let rec remove_min_elt tree =
match tree with
| Empty -> assert false
| Leaf _ -> Empty (* This must be the root *)
| Node (Empty, _, _, _, right) -> right
| Node (Leaf _, _, _, _, _) as node -> set_left node Empty; tree
| Node (left, _, _, _, _) as node ->
set_left node (remove_min_elt left); tree
let merge =
let do_merge t1 t2 node =
set_right node (remove_min_elt t2);
set_left node t1;
node
in
fun t1 t2 ->
match (t1, t2) with
| (Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let tree = min_elt t2 in
match tree with
| Empty -> Empty
| Leaf (k, v) ->
let node = new_node k v in
do_merge t1 t2 node
| Node _ as node -> do_merge t1 t2 node
let remove =
let rec remove t removed compare k =
match t with
| Empty ->
removed := false;
Empty
| Leaf (k', _) ->
if compare k k' = 0 then begin
removed := true;
Empty
end else begin
removed := false;
t
end
| Node (left, k', _, _, right) ->
let c = compare k k' in
if c = 0 then begin
removed := true;
merge left right
end else if c < 0 then begin
set_left t (remove left removed compare k);
t
end else begin
set_right t (remove right removed compare k);
t
end
in
fun t ~removed ~compare k -> balance_root (remove t removed compare k)
(* estokes: for a real tree implementation we probably want fold_right,
that way the elements come in order, but this is a hashtbl,
so we don't care. *)
let rec fold t ~init ~f =
match t with
| Empty -> init
| Leaf (key, data) -> f ~key ~data init
| Node (left, key, data, _, right) ->
let init = f ~key ~data init in
fold right ~init:(fold left ~init ~f) ~f
let iter t ~f = fold t ~init:() ~f:(fun ~key ~data () -> f ~key ~data)
end
module X = Table_new_intf
module T : X.Basic = struct
type ('k, 'v) t = {
mutable table : ('k, 'v) Avltree.t array;
mutable array_length: int;
mutable length : int;
mutable params : X.params;
added_or_removed : bool ref;
hashable: 'k X.hashable;
}
let create ?(params = X.default_params) hashable =
let size = Int.min (Int.max 1 params.X.initial_size) Sys.max_array_length in
{ table = Array.create size Avltree.empty;
array_length = size;
length = 0;
params = params;
added_or_removed = ref false;
hashable = hashable; }
;;
let hashable t = t.hashable
let get_params t = t.params
let set_params t p = t.params <- p
let slot t key = t.hashable.X.hash key mod t.array_length
let really_add t ~key ~data =
let i = slot t key in
let root = t.table.(i) in
let new_root =
The avl tree might replace the entry , in that case the table
did not get bigger , so we should not increment length , we
pass in the bool ref t.added so that it can tell us whether
it added or replaced . We do it this way to avoid extra
allocation . Since the bool is an immediate it does not go
through the write barrier .
did not get bigger, so we should not increment length, we
pass in the bool ref t.added so that it can tell us whether
it added or replaced. We do it this way to avoid extra
allocation. Since the bool is an immediate it does not go
through the write barrier. *)
Avltree.add root t.hashable.X.compare ~added:t.added_or_removed ~key ~data
in
if t.added_or_removed.contents then
t.length <- t.length + 1;
if not (phys_equal new_root root) then
t.table.(i) <- new_root
;;
let maybe_resize_table t =
let should_grow =
t.params.X.grow &&
t.length >= t.array_length * t.params.X.load_factor
in
if should_grow then begin
let new_array_length =
Int.min (t.array_length * t.params.X.load_factor) Sys.max_array_length
in
if new_array_length > t.array_length then begin
let new_table =
Array.init new_array_length ~f:(fun _ -> Avltree.empty)
in
let old_table = t.table in
t.array_length <- new_array_length;
t.table <- new_table;
t.length <- 0;
for i = 0 to Array.length old_table - 1 do
Avltree.iter old_table.(i) ~f:(fun ~key ~data ->
really_add t ~key ~data)
done
end
end
;;
let add t ~key ~data =
maybe_resize_table t;
really_add t ~key ~data
;;
let clear t =
for i = 0 to t.array_length - 1 do
t.table.(i) <- Avltree.empty;
done;
t.length <- 0
;;
let find t key = Avltree.find t.table.(slot t key) t.hashable.X.compare key
let mem t key = Avltree.mem t.table.(slot t key) t.hashable.X.compare key
let remove t key =
let i = slot t key in
let root = t.table.(i) in
let new_root =
Avltree.remove root
~removed:t.added_or_removed ~compare:t.hashable.X.compare key
in
if not (phys_equal root new_root) then
t.table.(i) <- new_root;
if t.added_or_removed.contents then
t.length <- t.length - 1
;;
let length t = t.length
let fold =
this is done recursivly to avoid the write barrier in the case
that the accumulator is a structured block , Array.fold does
this with a for loop and a ref cell , when it is fixed , we can
use it .
that the accumulator is a structured block, Array.fold does
this with a for loop and a ref cell, when it is fixed, we can
use it. *)
let rec loop buckets i len init f =
if i < len then
loop buckets (i + 1) len (Avltree.fold buckets.(i) ~init ~f) f
else
init
in
fun t ~init ~f -> loop t.table 0 t.array_length init f
;;
let invariant t =
assert (Array.length t.table = t.array_length);
let real_len = fold t ~init:0 ~f:(fun ~key:_ ~data:_ i -> i + 1) in
assert (real_len = t.length);
for i = 0 to t.array_length - 1 do
Avltree.invariant t.table.(i) t.hashable.X.compare
done
;;
end
include Table_new_intf.Make (T)
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib_test/hashtbl/table_new.ml | ocaml | see above for an explanation of why right cannot be a leaf
see above for an explanation of why this cannot be a leaf
going to be the new root node
This must be the root
estokes: for a real tree implementation we probably want fold_right,
that way the elements come in order, but this is a hashtbl,
so we don't care. | pp camlp4o -I ` ocamlfind query sexplib ` -I ` ocamlfind query type_conv ` -I ` ocamlfind query bin_prot ` pa_type_conv.cmo pa_sexp_conv.cmo pa_bin_prot.cmo
open Core.Std
module Avltree = struct
type ('k, 'v) t =
| Empty
| Node of ('k, 'v) t * 'k * 'v * int * ('k, 'v) t
| Leaf of 'k * 'v
We do this ' crazy ' magic because we want to remove a level of
indirection in the tree . If we did n't do this , we 'd need to use a
record , and then the variant would be a block with a pointer to
the record . Where as now the ' record ' is tagged with the
constructor , thus removing a level of indirection . This is even
reasonably safe , certainly no more dangerous than a C binding .
The extra checking is probably free , since the block will already
be in L1 cache , and the branch predictor is very likely to
predict correctly .
indirection in the tree. If we didn't do this, we'd need to use a
record, and then the variant would be a block with a pointer to
the record. Where as now the 'record' is tagged with the
constructor, thus removing a level of indirection. This is even
reasonably safe, certainly no more dangerous than a C binding.
The extra checking is probably free, since the block will already
be in L1 cache, and the branch predictor is very likely to
predict correctly. *)
let set_field f n v = Obj.set_field (Obj.repr f) n (Obj.repr v)
let update_left (n: ('k, 'v) t) (u: ('k, 'v) t) : unit =
match n with
| Node _ -> set_field n 0 u
| _ -> assert false
let update_right (n: ('k, 'v) t) (u: ('k, 'v) t) : unit =
match n with
| Node _ -> set_field n 4 u
| _ -> assert false
let update_val (n : ('k, 'v) t) (u: 'v) : unit =
match n with
| Node _ -> set_field n 2 u
| _ -> assert false
let update_height (n: ('k, 'v) t) (u: int) : unit =
match n with
| Node _ -> set_field n 3 u
| _ -> assert false
let update_leaf_val (n: ('k, 'v) t) (u: 'v) : unit =
match n with
| Leaf _ -> set_field n 1 u
| _ -> assert false
let invariant t compare =
let rec binary_tree = function
| Empty | Leaf _ -> ()
| Node (left, key, _value, _height, right) ->
begin match left with
| Empty -> ()
| Leaf (left_key, _)
| Node (_, left_key, _, _, _) ->
assert (compare left_key key < 0)
end;
begin match right with
| Empty -> ()
| Leaf (right_key, _)
| Node (_, right_key, _, _, _) ->
assert (compare right_key key > 0)
end;
assert (compare key key = 0);
binary_tree left;
binary_tree right
in
let rec height = function
| Empty -> 0
| Leaf _ -> 1
| Node (left, _k, _v, _h, right) ->
Int.max (height left) (height right) + 1
in
let rec balanced = function
| Empty | Leaf _ -> ()
| Node (left, _k, _v, _h, right) ->
assert (abs (height left - height right) < 3);
balanced left;
balanced right
in
binary_tree t;
balanced t
let empty = Empty
let height = function
| Empty -> 0
| Leaf _ -> 1
| Node (_l, _k, _v, height, _r) -> height
let update_height n =
match n with
| Node (left, _, _, _, right) ->
let new_height = (Int.max (height left) (height right)) + 1 in
update_height n new_height
| _ -> assert false
let balance tree =
match tree with
| Empty | Leaf _ -> tree
| Node (left, _k, _v, _h, right) as root_node ->
let hl = height left and hr = height right in
+ 2 is critically important , lowering it to 1 will break the Leaf
assumptions in the code below , and will force us to promote leaf
nodes in the balance routine . It 's also faster , since it will
balance less often .
assumptions in the code below, and will force us to promote leaf
nodes in the balance routine. It's also faster, since it will
balance less often. *)
if hl > hr + 2 then begin
match left with
It can not be a leaf , because even if right is empty , a leaf
is only height 1
is only height 1 *)
| Empty | Leaf _ -> assert false
| Node (left_node_left, _, _, _, left_node_right) as left_node ->
if height left_node_left >= height left_node_right then begin
update_left root_node left_node_right;
update_right left_node root_node;
update_height root_node;
update_height left_node;
left_node
end else begin
if right is a leaf , then left must be empty . That means
height is 2 . Even if hr is empty we still ca n't get here .
height is 2. Even if hr is empty we still can't get here. *)
match left_node_right with
| Empty | Leaf _ -> assert false
| Node (lr_left, _, _, _, lr_right) as lr_node ->
update_right left_node lr_left;
update_left root_node lr_right;
update_right lr_node root_node;
update_left lr_node left_node;
update_height left_node;
update_height root_node;
update_height lr_node;
lr_node
end
end else if hr > hl + 2 then begin
match right with
| Empty | Leaf _ -> assert false
| Node (right_node_left, _, _, _, right_node_right) as right_node ->
if height right_node_right >= height right_node_left then begin
update_right root_node right_node_left;
update_left right_node root_node;
update_height root_node;
update_height right_node;
right_node
end else begin
match right_node_left with
| Empty | Leaf _ -> assert false
| Node (rl_left, _, _, _, rl_right) as rl_node ->
update_left right_node rl_right;
update_right root_node rl_left;
update_left rl_node root_node;
update_right rl_node right;
update_height right_node;
update_height root_node;
update_height rl_node;
rl_node
end
end else
tree
;;
let set_left node tree =
let tree = balance tree in
match node with
| Node (left, _, _, _, _) ->
if phys_equal left tree then ()
else
update_left node tree;
update_height node
| _ -> assert false
let set_right node tree =
let tree = balance tree in
match node with
| Node (_, _, _, _, right) ->
if phys_equal right tree then ()
else
update_right node tree;
update_height node
| _ -> assert false
let balance_root tree =
let tree = balance tree in
begin match tree with
| Empty | Leaf _ -> ()
| Node _ as node -> update_height node
end;
tree
let new_node k v = Node (Empty, k, v, 1, Empty)
let add =
let rec add t added compare k v =
match t with
| Empty ->
added := true;
Leaf (k, v)
| Leaf (k', _) ->
let c = compare k' k in
This compare is reversed on purpose , we are pretending
that the leaf was just inserted instead of the other way
round , that way we only allocate one node .
that the leaf was just inserted instead of the other way
round, that way we only allocate one node. *)
if c = 0 then begin
added := false;
update_leaf_val t v;
t
end else begin
let node = new_node k v in
added := true;
if c < 0 then set_left node t
else set_right node t;
node
end
| Node (left, k', _, _, right) ->
let c = compare k k' in
if c = 0 then begin
added := false;
update_val t v;
end else if c < 0 then
set_left t (add left added compare k v)
else
set_right t (add right added compare k v);
t
in
fun t compare ~added ~key ~data ->
balance_root (add t added compare key data)
let rec find t compare k =
A little manual unrolling of the recursion .
This is really worth 5 % on average
This is really worth 5% on average *)
match t with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else if c < 0 then begin
match left with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else find (if c < 0 then left else right) compare k
end else begin
match right with
| Empty -> None
| Leaf (k', v) ->
if compare k k' = 0 then Some v
else None
| Node (left, k', v, _, right) ->
let c = compare k k' in
if c = 0 then Some v
else find (if c < 0 then left else right) compare k
end
;;
let mem t compare k = Option.is_some (find t compare k)
let rec min_elt tree =
match tree with
| Empty -> Empty
| Leaf _ -> tree
| Node (Empty, _, _, _, _) -> tree
| Node (left, _, _, _, _) -> min_elt left
let rec remove_min_elt tree =
match tree with
| Empty -> assert false
| Node (Empty, _, _, _, right) -> right
| Node (Leaf _, _, _, _, _) as node -> set_left node Empty; tree
| Node (left, _, _, _, _) as node ->
set_left node (remove_min_elt left); tree
let merge =
let do_merge t1 t2 node =
set_right node (remove_min_elt t2);
set_left node t1;
node
in
fun t1 t2 ->
match (t1, t2) with
| (Empty, t) -> t
| (t, Empty) -> t
| (_, _) ->
let tree = min_elt t2 in
match tree with
| Empty -> Empty
| Leaf (k, v) ->
let node = new_node k v in
do_merge t1 t2 node
| Node _ as node -> do_merge t1 t2 node
let remove =
let rec remove t removed compare k =
match t with
| Empty ->
removed := false;
Empty
| Leaf (k', _) ->
if compare k k' = 0 then begin
removed := true;
Empty
end else begin
removed := false;
t
end
| Node (left, k', _, _, right) ->
let c = compare k k' in
if c = 0 then begin
removed := true;
merge left right
end else if c < 0 then begin
set_left t (remove left removed compare k);
t
end else begin
set_right t (remove right removed compare k);
t
end
in
fun t ~removed ~compare k -> balance_root (remove t removed compare k)
let rec fold t ~init ~f =
match t with
| Empty -> init
| Leaf (key, data) -> f ~key ~data init
| Node (left, key, data, _, right) ->
let init = f ~key ~data init in
fold right ~init:(fold left ~init ~f) ~f
let iter t ~f = fold t ~init:() ~f:(fun ~key ~data () -> f ~key ~data)
end
module X = Table_new_intf
module T : X.Basic = struct
type ('k, 'v) t = {
mutable table : ('k, 'v) Avltree.t array;
mutable array_length: int;
mutable length : int;
mutable params : X.params;
added_or_removed : bool ref;
hashable: 'k X.hashable;
}
let create ?(params = X.default_params) hashable =
let size = Int.min (Int.max 1 params.X.initial_size) Sys.max_array_length in
{ table = Array.create size Avltree.empty;
array_length = size;
length = 0;
params = params;
added_or_removed = ref false;
hashable = hashable; }
;;
let hashable t = t.hashable
let get_params t = t.params
let set_params t p = t.params <- p
let slot t key = t.hashable.X.hash key mod t.array_length
let really_add t ~key ~data =
let i = slot t key in
let root = t.table.(i) in
let new_root =
The avl tree might replace the entry , in that case the table
did not get bigger , so we should not increment length , we
pass in the bool ref t.added so that it can tell us whether
it added or replaced . We do it this way to avoid extra
allocation . Since the bool is an immediate it does not go
through the write barrier .
did not get bigger, so we should not increment length, we
pass in the bool ref t.added so that it can tell us whether
it added or replaced. We do it this way to avoid extra
allocation. Since the bool is an immediate it does not go
through the write barrier. *)
Avltree.add root t.hashable.X.compare ~added:t.added_or_removed ~key ~data
in
if t.added_or_removed.contents then
t.length <- t.length + 1;
if not (phys_equal new_root root) then
t.table.(i) <- new_root
;;
let maybe_resize_table t =
let should_grow =
t.params.X.grow &&
t.length >= t.array_length * t.params.X.load_factor
in
if should_grow then begin
let new_array_length =
Int.min (t.array_length * t.params.X.load_factor) Sys.max_array_length
in
if new_array_length > t.array_length then begin
let new_table =
Array.init new_array_length ~f:(fun _ -> Avltree.empty)
in
let old_table = t.table in
t.array_length <- new_array_length;
t.table <- new_table;
t.length <- 0;
for i = 0 to Array.length old_table - 1 do
Avltree.iter old_table.(i) ~f:(fun ~key ~data ->
really_add t ~key ~data)
done
end
end
;;
let add t ~key ~data =
maybe_resize_table t;
really_add t ~key ~data
;;
let clear t =
for i = 0 to t.array_length - 1 do
t.table.(i) <- Avltree.empty;
done;
t.length <- 0
;;
let find t key = Avltree.find t.table.(slot t key) t.hashable.X.compare key
let mem t key = Avltree.mem t.table.(slot t key) t.hashable.X.compare key
let remove t key =
let i = slot t key in
let root = t.table.(i) in
let new_root =
Avltree.remove root
~removed:t.added_or_removed ~compare:t.hashable.X.compare key
in
if not (phys_equal root new_root) then
t.table.(i) <- new_root;
if t.added_or_removed.contents then
t.length <- t.length - 1
;;
let length t = t.length
let fold =
this is done recursivly to avoid the write barrier in the case
that the accumulator is a structured block , Array.fold does
this with a for loop and a ref cell , when it is fixed , we can
use it .
that the accumulator is a structured block, Array.fold does
this with a for loop and a ref cell, when it is fixed, we can
use it. *)
let rec loop buckets i len init f =
if i < len then
loop buckets (i + 1) len (Avltree.fold buckets.(i) ~init ~f) f
else
init
in
fun t ~init ~f -> loop t.table 0 t.array_length init f
;;
let invariant t =
assert (Array.length t.table = t.array_length);
let real_len = fold t ~init:0 ~f:(fun ~key:_ ~data:_ i -> i + 1) in
assert (real_len = t.length);
for i = 0 to t.array_length - 1 do
Avltree.invariant t.table.(i) t.hashable.X.compare
done
;;
end
include Table_new_intf.Make (T)
|
75d76ca71fc4f2574e31c860eb588cb59a4b2a8c3b1d9698c4302afdc97c2d68 | metabase/metabase | util_test.clj | (ns metabase-enterprise.util-test
(:require
[metabase.public-settings.premium-features :refer [defenterprise defenterprise-schema]]
[schema.core :as s]))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Defenterprise Macro |
;;; +----------------------------------------------------------------------------------------------------------------+
;; These `defenterprise` calls define the EE versions of test functions which are used in
;; `metabase.public-settings.premium-features-test`, for testing the `defenterprise` macro itself
(defenterprise greeting
"Returns an special greeting for anyone running the Enterprise Edition, regardless of token."
:feature :none
[username]
(format "Hi %s, you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise greeting-with-valid-token
"Returns an extra special greeting for a user if the instance has a valid premium features token. Else, returns the
default (OSS) greeting."
:feature :any
[username]
(format "Hi %s, you're an EE customer with a valid token!" (name username)))
(defenterprise special-greeting
"Returns an extra special greeting for a user if the instance has a :special-greeting feature token. Else,
returns the default (OSS) greeting."
:feature :special-greeting
[username]
(format "Hi %s, you're an extra special EE customer!" (name username)))
(defn- special-greeting-fallback
[username]
(format "Hi %s, you're an EE customer but not extra special." (name username)))
(defenterprise special-greeting-or-custom
"Returns an extra special greeting for a user if the instance has a :special-greeting feature token. Else,
returns a custom greeting for enterprise users without the token."
:feature :special-greeting
:fallback special-greeting-fallback
[username]
(format "Hi %s, you're an extra special EE customer!" (name username)))
(defenterprise-schema greeting-with-schema :- s/Str
"Returns a greeting for a user, with schemas for the argument and return value."
:feature :none
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise-schema greeting-with-invalid-oss-return-schema :- s/Str
"Returns a greeting for a user."
:feature :none
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise-schema greeting-with-invalid-ee-return-schema :- s/Keyword
"Returns a greeting for a user."
:feature :custom-feature
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
| null | https://raw.githubusercontent.com/metabase/metabase/1f809593c2298ccf9c4070df3fa39d718eddb5d6/enterprise/backend/test/metabase_enterprise/util_test.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| Defenterprise Macro |
+----------------------------------------------------------------------------------------------------------------+
These `defenterprise` calls define the EE versions of test functions which are used in
`metabase.public-settings.premium-features-test`, for testing the `defenterprise` macro itself | (ns metabase-enterprise.util-test
(:require
[metabase.public-settings.premium-features :refer [defenterprise defenterprise-schema]]
[schema.core :as s]))
(defenterprise greeting
"Returns an special greeting for anyone running the Enterprise Edition, regardless of token."
:feature :none
[username]
(format "Hi %s, you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise greeting-with-valid-token
"Returns an extra special greeting for a user if the instance has a valid premium features token. Else, returns the
default (OSS) greeting."
:feature :any
[username]
(format "Hi %s, you're an EE customer with a valid token!" (name username)))
(defenterprise special-greeting
"Returns an extra special greeting for a user if the instance has a :special-greeting feature token. Else,
returns the default (OSS) greeting."
:feature :special-greeting
[username]
(format "Hi %s, you're an extra special EE customer!" (name username)))
(defn- special-greeting-fallback
[username]
(format "Hi %s, you're an EE customer but not extra special." (name username)))
(defenterprise special-greeting-or-custom
"Returns an extra special greeting for a user if the instance has a :special-greeting feature token. Else,
returns a custom greeting for enterprise users without the token."
:feature :special-greeting
:fallback special-greeting-fallback
[username]
(format "Hi %s, you're an extra special EE customer!" (name username)))
(defenterprise-schema greeting-with-schema :- s/Str
"Returns a greeting for a user, with schemas for the argument and return value."
:feature :none
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise-schema greeting-with-invalid-oss-return-schema :- s/Str
"Returns a greeting for a user."
:feature :none
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
(defenterprise-schema greeting-with-invalid-ee-return-schema :- s/Keyword
"Returns a greeting for a user."
:feature :custom-feature
[username :- s/Keyword]
(format "Hi %s, the schema was valid, and you're running the Enterprise Edition of Metabase!" (name username)))
|
269852afd38ef2082952f42773fc66b272e876f6b779ff9d0a804a7608098b35 | mattmundell/nightshade | edload.lisp | ;;; Function load-editor, which loads the editor.
(defun load-editor ()
(load "ed:exports")
(load "ed:struct")
; (load "ed:struct-ed")
(load "ed:charmacs")
(load "ed:key-event")
(ext::re-initialize-key-events)
(load "ed:keysym-defs")
(load "ed:input")
(load "ed:line")
(load "ed:ring")
(load "ed:vars")
(load "ed:buffer")
(load "ed:macros")
(load "ed:interp")
(load "ed:syntax")
(load "ed:htext1")
(load "ed:htext2")
(load "ed:htext3")
(load "ed:htext4")
(load "ed:at-point")
(load "ed:files")
(load "ed:parse")
(load "ed:search1")
(load "ed:search2")
#+clx (load "ed:hunk-draw")
; (load "ed:bit-stream")
(load "ed:window")
(load "ed:screen")
(load "ed:winimage")
(load "ed:linimage")
(load "ed:display")
(load "ed:termcap")
(load "ed:rompsite")
#+clx (load "ed:bit-display")
(load "ed:tty-disp-rt")
(load "ed:tty-display")
; (load "ed:tty-stream")
(load "ed:pop-up-stream")
#+clx (load "ed:bit-screen")
(load "ed:tty-screen")
(load "ed:cursor")
(load "ed:font")
(load "ed:streams")
(load "ed:main")
(load "ed:hacks")
(load "ed:echo")
(load "ed:echocoms")
(load "ed:command")
(load "ed:indent")
(load "ed:comments")
(load "ed:morecoms")
(load "ed:undo")
(load "ed:killcoms")
(load "ed:searchcoms")
(load "ed:charsets")
(load "ed:charcoms")
(load "ed:filecoms")
(load "ed:doccoms")
(load "ed:srccom")
(load "ed:group")
(load "ed:fill")
(load "ed:text")
(load "ed:lispmode")
(load "ed:ts-buf")
(load "ed:ts-stream")
(load "ed:eval-server")
(load "ed:lispbuf")
(load "ed:lispeval")
(load "ed:spell-rt")
(load "ed:spell-corr")
(load "ed:spell-aug")
(load "ed:spellcoms")
(load "ed:overwrite")
(load "ed:abbrev")
(load "ed:dabbrev")
(load "ed:icom")
(load "ed:kbdmac")
(load "ed:defsyn")
(load "ed:scribe")
(load "ed:c")
(load "ed:pascal")
(load "ed:shell-script")
(load "ed:python")
(load "ed:make")
(load "ed:m4")
(load "ed:tex")
(load "ed:roff")
(load "ed:sgml")
(load "ed:edit-defs")
(load "ed:auto-save")
(load "ed:register")
#+clx (load "ed:xcoms")
(load "ed:unixcoms")
(load "ed:mh")
(load "ed:highlight")
(load "ed:dired")
(load "ed:diredcoms")
(load "ed:bufed")
(load "ed:paged")
(load "ed:completion")
(load "ed:shell")
(load "ed:telnet")
(load "ed:inspect")
(load "ed:netnews")
(load "ed:compile")
(load "ed:debug")
(load "ed:netnews")
(load "ed:parse-scribe")
(load "ed:doc")
(ed::get-doc-directory)
(load "ed:info")
(load "ed:csv")
(load "ed:db")
(load "ed:calendar")
(load "ed:sort")
(load "ed:www")
(load "ed:outline")
(load "ed:buildcoms")
(load "ed:rest")
(load "ed:enriched")
(load "ed:changelog")
(load "ed:build")
(load "ed:line-end")
(load "ed:refresh")
(load "ed:testcoms")
(load "ed:hex")
(load "ed:ed-integrity")
(load "ed:edi-integrity")
(load "ed:bindings"))
| null | https://raw.githubusercontent.com/mattmundell/nightshade/68e960eff95e007462f2613beabc6cac11e0dfa1/src/tools/edload.lisp | lisp | Function load-editor, which loads the editor.
(load "ed:struct-ed")
(load "ed:bit-stream")
(load "ed:tty-stream") |
(defun load-editor ()
(load "ed:exports")
(load "ed:struct")
(load "ed:charmacs")
(load "ed:key-event")
(ext::re-initialize-key-events)
(load "ed:keysym-defs")
(load "ed:input")
(load "ed:line")
(load "ed:ring")
(load "ed:vars")
(load "ed:buffer")
(load "ed:macros")
(load "ed:interp")
(load "ed:syntax")
(load "ed:htext1")
(load "ed:htext2")
(load "ed:htext3")
(load "ed:htext4")
(load "ed:at-point")
(load "ed:files")
(load "ed:parse")
(load "ed:search1")
(load "ed:search2")
#+clx (load "ed:hunk-draw")
(load "ed:window")
(load "ed:screen")
(load "ed:winimage")
(load "ed:linimage")
(load "ed:display")
(load "ed:termcap")
(load "ed:rompsite")
#+clx (load "ed:bit-display")
(load "ed:tty-disp-rt")
(load "ed:tty-display")
(load "ed:pop-up-stream")
#+clx (load "ed:bit-screen")
(load "ed:tty-screen")
(load "ed:cursor")
(load "ed:font")
(load "ed:streams")
(load "ed:main")
(load "ed:hacks")
(load "ed:echo")
(load "ed:echocoms")
(load "ed:command")
(load "ed:indent")
(load "ed:comments")
(load "ed:morecoms")
(load "ed:undo")
(load "ed:killcoms")
(load "ed:searchcoms")
(load "ed:charsets")
(load "ed:charcoms")
(load "ed:filecoms")
(load "ed:doccoms")
(load "ed:srccom")
(load "ed:group")
(load "ed:fill")
(load "ed:text")
(load "ed:lispmode")
(load "ed:ts-buf")
(load "ed:ts-stream")
(load "ed:eval-server")
(load "ed:lispbuf")
(load "ed:lispeval")
(load "ed:spell-rt")
(load "ed:spell-corr")
(load "ed:spell-aug")
(load "ed:spellcoms")
(load "ed:overwrite")
(load "ed:abbrev")
(load "ed:dabbrev")
(load "ed:icom")
(load "ed:kbdmac")
(load "ed:defsyn")
(load "ed:scribe")
(load "ed:c")
(load "ed:pascal")
(load "ed:shell-script")
(load "ed:python")
(load "ed:make")
(load "ed:m4")
(load "ed:tex")
(load "ed:roff")
(load "ed:sgml")
(load "ed:edit-defs")
(load "ed:auto-save")
(load "ed:register")
#+clx (load "ed:xcoms")
(load "ed:unixcoms")
(load "ed:mh")
(load "ed:highlight")
(load "ed:dired")
(load "ed:diredcoms")
(load "ed:bufed")
(load "ed:paged")
(load "ed:completion")
(load "ed:shell")
(load "ed:telnet")
(load "ed:inspect")
(load "ed:netnews")
(load "ed:compile")
(load "ed:debug")
(load "ed:netnews")
(load "ed:parse-scribe")
(load "ed:doc")
(ed::get-doc-directory)
(load "ed:info")
(load "ed:csv")
(load "ed:db")
(load "ed:calendar")
(load "ed:sort")
(load "ed:www")
(load "ed:outline")
(load "ed:buildcoms")
(load "ed:rest")
(load "ed:enriched")
(load "ed:changelog")
(load "ed:build")
(load "ed:line-end")
(load "ed:refresh")
(load "ed:testcoms")
(load "ed:hex")
(load "ed:ed-integrity")
(load "ed:edi-integrity")
(load "ed:bindings"))
|
252ddc2ba6f57ff63941ed60e3241389ef57bacf36f3f3343b8d1561ecb4fa80 | grin-compiler/grin | CSE.hs | # LANGUAGE LambdaCase , TupleSections , ViewPatterns #
module Transformations.ExtendedSyntax.Optimising.CSE where
-- HINT: common sub-expression elimination
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Functor.Foldable as Foldable
import Text.Printf
import Lens.Micro ((^.))
import Lens.Micro.Extra (isn't)
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.TypeEnv
import Grin.ExtendedSyntax.EffectMap
import Transformations.ExtendedSyntax.Util
type Env = (Map SimpleExp SimpleExp)
TODO : track if function parameters with location type can be updated in the called function to improve CSE
TODO : remove skipUnit , it does nothing with the new syntax ( SDVE will get rid of the unused unit - binds )
TODO : CSE could be taught to remember pattern binds :
( k1)@n0 < - pure ( CInt k0 )
n1 < - pure ( CInt k0 )
n2 < - pure ( CInt k1 )
could be transformed to :
( k1)@n0 < - pure ( CInt k0 )
n1 < - pure n0
n2 < - pure n0
TODO: CSE could be taught to remember pattern binds:
(CInt k1)@n0 <- pure (CInt k0)
n1 <- pure (CInt k0)
n2 <- pure (CInt k1)
could be transformed to:
(CInt k1)@n0 <- pure (CInt k0)
n1 <- pure n0
n2 <- pure n0
-}
commonSubExpressionElimination :: TypeEnv -> EffectMap -> Exp -> Exp
commonSubExpressionElimination typeEnv effMap e = hylo skipUnit builder (mempty, e) where
builder :: (Env, Exp) -> ExpF (Env, Exp)
builder (env, subst env -> exp) = case exp of
EBind leftExp bPat rightExp -> EBindF (env, leftExp) bPat (newEnv, rightExp) where
newEnv = case leftExp of
-- HINT: also save fetch (the inverse operation) for store and update
SUpdate ptr var -> Map.insert (SFetch ptr) (SReturn (Var var)) env
SStore var
-- TODO: AsPat
| VarPat ptr <- bPat -> Map.insert (SFetch ptr) (SReturn (Var var)) extEnvKeepOld
-- HINT: location parameters might be updated in the called function, so forget their content
SApp defName args -> foldr
Map.delete
(if (hasTrueSideEffect defName effMap) then env else extEnvKeepOld)
[SFetch var | var <- args, isLocation var]
SReturn val | isn't _Var val -> extEnvKeepOld
SFetch{} -> extEnvKeepOld
_ -> env
extEnvKeepOld = Map.insertWith (\new old -> old) leftExp (SReturn . Var $ bPat ^. _BPatVar) env
-- TODO: Investigate this. Will the fetched variable, and the variable to be updated with
-- always have the same name? If not, will copy propagation solve it?
SUpdate ptr var | Just (SReturn (Var fetchedVar)) <- Map.lookup (SFetch ptr) env
, fetchedVar == var
-> SReturnF Unit
ECase scrut alts -> ECaseF scrut [(altEnv env scrut cpat, alt) | alt@(Alt cpat _altName _) <- alts]
_ -> (env,) <$> project exp
isLocation :: Name -> Bool
isLocation name = case variableType typeEnv name of
T_SimpleType T_Location{} -> True
_ -> False
altEnv :: Env -> Name -> CPat -> Env
altEnv env scrut cpat = case cpat of
When we use scrutinee variable already HPT will include all the
-- possible values, instead of the matching one. As result it will
-- overapproximate the values more than needed.
NOTE : We could extend the env with ( ConstTagNode tag args ) - > SReturn val ]
HPT would _ not _ overapproximate the possible type of the variable ,
-- since it restricts the scrutinee to the alternative's domain
LitPat lit -> Map.insertWith (\new old -> old) (SReturn (Lit lit)) (SReturn (Var scrut)) env
DefaultPat -> env
| null | https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/src/Transformations/ExtendedSyntax/Optimising/CSE.hs | haskell | HINT: common sub-expression elimination
HINT: also save fetch (the inverse operation) for store and update
TODO: AsPat
HINT: location parameters might be updated in the called function, so forget their content
TODO: Investigate this. Will the fetched variable, and the variable to be updated with
always have the same name? If not, will copy propagation solve it?
possible values, instead of the matching one. As result it will
overapproximate the values more than needed.
since it restricts the scrutinee to the alternative's domain | # LANGUAGE LambdaCase , TupleSections , ViewPatterns #
module Transformations.ExtendedSyntax.Optimising.CSE where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Functor.Foldable as Foldable
import Text.Printf
import Lens.Micro ((^.))
import Lens.Micro.Extra (isn't)
import Grin.ExtendedSyntax.Grin
import Grin.ExtendedSyntax.TypeEnv
import Grin.ExtendedSyntax.EffectMap
import Transformations.ExtendedSyntax.Util
type Env = (Map SimpleExp SimpleExp)
TODO : track if function parameters with location type can be updated in the called function to improve CSE
TODO : remove skipUnit , it does nothing with the new syntax ( SDVE will get rid of the unused unit - binds )
TODO : CSE could be taught to remember pattern binds :
( k1)@n0 < - pure ( CInt k0 )
n1 < - pure ( CInt k0 )
n2 < - pure ( CInt k1 )
could be transformed to :
( k1)@n0 < - pure ( CInt k0 )
n1 < - pure n0
n2 < - pure n0
TODO: CSE could be taught to remember pattern binds:
(CInt k1)@n0 <- pure (CInt k0)
n1 <- pure (CInt k0)
n2 <- pure (CInt k1)
could be transformed to:
(CInt k1)@n0 <- pure (CInt k0)
n1 <- pure n0
n2 <- pure n0
-}
commonSubExpressionElimination :: TypeEnv -> EffectMap -> Exp -> Exp
commonSubExpressionElimination typeEnv effMap e = hylo skipUnit builder (mempty, e) where
builder :: (Env, Exp) -> ExpF (Env, Exp)
builder (env, subst env -> exp) = case exp of
EBind leftExp bPat rightExp -> EBindF (env, leftExp) bPat (newEnv, rightExp) where
newEnv = case leftExp of
SUpdate ptr var -> Map.insert (SFetch ptr) (SReturn (Var var)) env
SStore var
| VarPat ptr <- bPat -> Map.insert (SFetch ptr) (SReturn (Var var)) extEnvKeepOld
SApp defName args -> foldr
Map.delete
(if (hasTrueSideEffect defName effMap) then env else extEnvKeepOld)
[SFetch var | var <- args, isLocation var]
SReturn val | isn't _Var val -> extEnvKeepOld
SFetch{} -> extEnvKeepOld
_ -> env
extEnvKeepOld = Map.insertWith (\new old -> old) leftExp (SReturn . Var $ bPat ^. _BPatVar) env
SUpdate ptr var | Just (SReturn (Var fetchedVar)) <- Map.lookup (SFetch ptr) env
, fetchedVar == var
-> SReturnF Unit
ECase scrut alts -> ECaseF scrut [(altEnv env scrut cpat, alt) | alt@(Alt cpat _altName _) <- alts]
_ -> (env,) <$> project exp
isLocation :: Name -> Bool
isLocation name = case variableType typeEnv name of
T_SimpleType T_Location{} -> True
_ -> False
altEnv :: Env -> Name -> CPat -> Env
altEnv env scrut cpat = case cpat of
When we use scrutinee variable already HPT will include all the
NOTE : We could extend the env with ( ConstTagNode tag args ) - > SReturn val ]
HPT would _ not _ overapproximate the possible type of the variable ,
LitPat lit -> Map.insertWith (\new old -> old) (SReturn (Lit lit)) (SReturn (Var scrut)) env
DefaultPat -> env
|
bd7b44f9018aa5832a70583623ad3274b866a0f998beffb9f02647b215935ae5 | auser/beehive | bee_store_tests.erl | -module (bee_store_tests).
-include_lib("eunit/include/eunit.hrl").
setup() ->
ok.
teardown(_X) ->
ok.
starting_test_() ->
{spawn,
{setup,
fun setup/0,
fun teardown/1,
[
fun test_startup/0
]
}
}.
test_startup() ->
passed. | null | https://raw.githubusercontent.com/auser/beehive/dfe257701b21c56a50af73c8203ecac60ed21991/lib/erlang/apps/beehive_router/test/bee_store_tests.erl | erlang | -module (bee_store_tests).
-include_lib("eunit/include/eunit.hrl").
setup() ->
ok.
teardown(_X) ->
ok.
starting_test_() ->
{spawn,
{setup,
fun setup/0,
fun teardown/1,
[
fun test_startup/0
]
}
}.
test_startup() ->
passed. | |
beb267b786db04bf9b00a4a3a3166f392d706c6f47f7eaf4b0338a7a443162bc | mfoemmel/erlang-otp | wxGenericDirCtrl.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
%% @doc See external documentation: <a href="">wxGenericDirCtrl</a>.
%% <p>This class is derived (and can use functions) from:
%% <br />{@link wxControl}
%% <br />{@link wxWindow}
%% <br />{@link wxEvtHandler}
%% </p>
%% @type wxGenericDirCtrl(). An object reference, The representation is internal
%% and can be changed without notice. It can't be used for comparsion
%% stored on disc or distributed for use on other nodes.
-module(wxGenericDirCtrl).
-include("wxe.hrl").
-export([collapseTree/1,create/2,create/3,destroy/1,expandPath/2,getDefaultPath/1,
getFilePath/1,getFilter/1,getFilterIndex/1,getPath/1,getRootId/1,getTreeCtrl/1,
init/1,new/0,new/1,new/2,reCreateTree/1,setDefaultPath/2,setFilter/2,
setFilterIndex/2,setPath/2]).
%% inherited exports
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2,
clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2,
connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1,
getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1,
getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1,
getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1,
hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1,
layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2,
move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,
navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2,
popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,
refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,
screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,
setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,
setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3,
setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4,
setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,
show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,
update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]).
%% @hidden
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > ( )
%% @doc See <a href="#wxgenericdirctrlwxgenericdirctrl">external documentation</a>.
new() ->
wxe_util:construct(?wxGenericDirCtrl_new_0,
<<>>).
( Parent::wxWindow : wxWindow ( ) ) - > ( )
%% @equiv new(Parent, [])
new(Parent)
when is_record(Parent, wx_ref) ->
new(Parent, []).
( Parent::wxWindow : wxWindow ( ) , [ Option ] ) - > ( )
Option = { i d , integer ( ) } | , string ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } | { filter , string ( ) } | { defaultFilter , integer ( ) }
%% @doc See <a href="#wxgenericdirctrlwxgenericdirctrl">external documentation</a>.
new(#wx_ref{type=ParentT,ref=ParentRef}, Options)
when is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({id, Id}, Acc) -> [<<1:32/?UI,Id:32/?UI>>|Acc];
({dir, Dir}, Acc) -> Dir_UC = unicode:characters_to_binary([Dir,0]),[<<2:32/?UI,(byte_size(Dir_UC)):32/?UI,(Dir_UC)/binary, 0:(((8- ((0+byte_size(Dir_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<3:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<4:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<5:32/?UI,Style:32/?UI>>|Acc];
({filter, Filter}, Acc) -> Filter_UC = unicode:characters_to_binary([Filter,0]),[<<6:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({defaultFilter, DefaultFilter}, Acc) -> [<<7:32/?UI,DefaultFilter:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxGenericDirCtrl_new_2,
<<ParentRef:32/?UI, 0:32,BinOpt/binary>>).
%% @spec (This::wxGenericDirCtrl(), Parent::wxWindow:wxWindow()) -> bool()
%% @equiv create(This,Parent, [])
create(This,Parent)
when is_record(This, wx_ref),is_record(Parent, wx_ref) ->
create(This,Parent, []).
%% @spec (This::wxGenericDirCtrl(), Parent::wxWindow:wxWindow(), [Option]) -> bool()
Option = { i d , integer ( ) } | , string ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } | { filter , string ( ) } | { defaultFilter , integer ( ) }
%% @doc See <a href="#wxgenericdirctrlcreate">external documentation</a>.
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxGenericDirCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({id, Id}, Acc) -> [<<1:32/?UI,Id:32/?UI>>|Acc];
({dir, Dir}, Acc) -> Dir_UC = unicode:characters_to_binary([Dir,0]),[<<2:32/?UI,(byte_size(Dir_UC)):32/?UI,(Dir_UC)/binary, 0:(((8- ((0+byte_size(Dir_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<3:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<4:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<5:32/?UI,Style:32/?UI>>|Acc];
({filter, Filter}, Acc) -> Filter_UC = unicode:characters_to_binary([Filter,0]),[<<6:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({defaultFilter, DefaultFilter}, Acc) -> [<<7:32/?UI,DefaultFilter:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxGenericDirCtrl_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI, BinOpt/binary>>).
%% @spec (This::wxGenericDirCtrl()) -> ok
%% @doc See <a href="#wxgenericdirctrlinit">external documentation</a>.
init(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_Init,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> ok
%% @doc See <a href="#wxgenericdirctrlcollapsetree">external documentation</a>.
collapseTree(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_CollapseTree,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl(), Path::string()) -> bool()
%% @doc See <a href="#wxgenericdirctrlexpandpath">external documentation</a>.
expandPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:call(?wxGenericDirCtrl_ExpandPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
%% @spec (This::wxGenericDirCtrl()) -> string()
%% @doc See <a href="#wxgenericdirctrlgetdefaultpath">external documentation</a>.
getDefaultPath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetDefaultPath,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> string()
%% @doc See <a href="#wxgenericdirctrlgetpath">external documentation</a>.
getPath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetPath,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> string()
%% @doc See <a href="#wxgenericdirctrlgetfilepath">external documentation</a>.
getFilePath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilePath,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> string()
%% @doc See <a href="#wxgenericdirctrlgetfilter">external documentation</a>.
getFilter(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilter,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> integer()
%% @doc See <a href="#wxgenericdirctrlgetfilterindex">external documentation</a>.
getFilterIndex(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilterIndex,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> wxTreeItemId()
%% @doc See <a href="#wxgenericdirctrlgetrootid">external documentation</a>.
getRootId(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetRootId,
<<ThisRef:32/?UI>>).
@spec ( This::wxGenericDirCtrl ( ) ) - > wxTreeCtrl : wxTreeCtrl ( )
%% @doc See <a href="#wxgenericdirctrlgettreectrl">external documentation</a>.
getTreeCtrl(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetTreeCtrl,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl()) -> ok
%% @doc See <a href="#wxgenericdirctrlrecreatetree">external documentation</a>.
reCreateTree(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_ReCreateTree,
<<ThisRef:32/?UI>>).
%% @spec (This::wxGenericDirCtrl(), Path::string()) -> ok
%% @doc See <a href="#wxgenericdirctrlsetdefaultpath">external documentation</a>.
setDefaultPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:cast(?wxGenericDirCtrl_SetDefaultPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
@spec ( This::wxGenericDirCtrl ( ) , ( ) ) - > ok
@doc See < a href=" / manuals / stable / wx_wxgenericdirctrl.html#wxgenericdirctrlsetfilter">external documentation</a > .
setFilter(#wx_ref{type=ThisT,ref=ThisRef},Filter)
when is_list(Filter) ->
?CLASS(ThisT,wxGenericDirCtrl),
Filter_UC = unicode:characters_to_binary([Filter,0]),
wxe_util:cast(?wxGenericDirCtrl_SetFilter,
<<ThisRef:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>).
%% @spec (This::wxGenericDirCtrl(), N::integer()) -> ok
%% @doc See <a href="#wxgenericdirctrlsetfilterindex">external documentation</a>.
setFilterIndex(#wx_ref{type=ThisT,ref=ThisRef},N)
when is_integer(N) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_SetFilterIndex,
<<ThisRef:32/?UI,N:32/?UI>>).
%% @spec (This::wxGenericDirCtrl(), Path::string()) -> ok
%% @doc See <a href="#wxgenericdirctrlsetpath">external documentation</a>.
setPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:cast(?wxGenericDirCtrl_SetPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
%% @spec (This::wxGenericDirCtrl()) -> ok
%% @doc Destroys this object, do not use object again
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxGenericDirCtrl),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
%% From wxControl
%% @hidden
setLabel(This,Label) -> wxControl:setLabel(This,Label).
%% @hidden
getLabel(This) -> wxControl:getLabel(This).
%% From wxWindow
%% @hidden
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
%% @hidden
validate(This) -> wxWindow:validate(This).
%% @hidden
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
%% @hidden
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
%% @hidden
update(This) -> wxWindow:update(This).
%% @hidden
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
%% @hidden
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
%% @hidden
thaw(This) -> wxWindow:thaw(This).
%% @hidden
show(This, Options) -> wxWindow:show(This, Options).
%% @hidden
show(This) -> wxWindow:show(This).
%% @hidden
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
%% @hidden
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
%% @hidden
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
%% @hidden
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
%% @hidden
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
%% @hidden
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
%% @hidden
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
%% @hidden
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
%% @hidden
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
%% @hidden
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
%% @hidden
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
%% @hidden
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
%% @hidden
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
%% @hidden
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
%% @hidden
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
%% @hidden
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
%% @hidden
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
%% @hidden
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
%% @hidden
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
%% @hidden
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
%% @hidden
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
%% @hidden
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
%% @hidden
setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
%% @hidden
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
%% @hidden
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
%% @hidden
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
%% @hidden
setName(This,Name) -> wxWindow:setName(This,Name).
%% @hidden
setId(This,Winid) -> wxWindow:setId(This,Winid).
%% @hidden
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
%% @hidden
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
%% @hidden
setFont(This,Font) -> wxWindow:setFont(This,Font).
%% @hidden
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
%% @hidden
setFocus(This) -> wxWindow:setFocus(This).
%% @hidden
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
%% @hidden
setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
%% @hidden
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
%% @hidden
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
%% @hidden
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
%% @hidden
setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize).
%% @hidden
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
%% @hidden
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
%% @hidden
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
%% @hidden
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
%% @hidden
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
%% @hidden
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
%% @hidden
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
%% @hidden
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
%% @hidden
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
%% @hidden
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
%% @hidden
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
%% @hidden
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
%% @hidden
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
%% @hidden
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
%% @hidden
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
%% @hidden
screenToClient(This) -> wxWindow:screenToClient(This).
%% @hidden
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
%% @hidden
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
%% @hidden
releaseMouse(This) -> wxWindow:releaseMouse(This).
%% @hidden
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
%% @hidden
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
%% @hidden
refresh(This, Options) -> wxWindow:refresh(This, Options).
%% @hidden
refresh(This) -> wxWindow:refresh(This).
%% @hidden
raise(This) -> wxWindow:raise(This).
%% @hidden
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
%% @hidden
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
%% @hidden
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
%% @hidden
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
%% @hidden
popEventHandler(This) -> wxWindow:popEventHandler(This).
%% @hidden
pageUp(This) -> wxWindow:pageUp(This).
%% @hidden
pageDown(This) -> wxWindow:pageDown(This).
%% @hidden
navigate(This, Options) -> wxWindow:navigate(This, Options).
%% @hidden
navigate(This) -> wxWindow:navigate(This).
%% @hidden
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
%% @hidden
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
%% @hidden
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
%% @hidden
move(This,X,Y) -> wxWindow:move(This,X,Y).
%% @hidden
move(This,Pt) -> wxWindow:move(This,Pt).
%% @hidden
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
%% @hidden
makeModal(This) -> wxWindow:makeModal(This).
%% @hidden
lower(This) -> wxWindow:lower(This).
%% @hidden
lineUp(This) -> wxWindow:lineUp(This).
%% @hidden
lineDown(This) -> wxWindow:lineDown(This).
%% @hidden
layout(This) -> wxWindow:layout(This).
%% @hidden
isTopLevel(This) -> wxWindow:isTopLevel(This).
%% @hidden
isShown(This) -> wxWindow:isShown(This).
%% @hidden
isRetained(This) -> wxWindow:isRetained(This).
%% @hidden
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
%% @hidden
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
%% @hidden
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
%% @hidden
isEnabled(This) -> wxWindow:isEnabled(This).
%% @hidden
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
%% @hidden
initDialog(This) -> wxWindow:initDialog(This).
%% @hidden
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
%% @hidden
hide(This) -> wxWindow:hide(This).
%% @hidden
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
%% @hidden
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
%% @hidden
hasCapture(This) -> wxWindow:hasCapture(This).
%% @hidden
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
%% @hidden
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
%% @hidden
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
%% @hidden
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
%% @hidden
getToolTip(This) -> wxWindow:getToolTip(This).
%% @hidden
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
%% @hidden
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
%% @hidden
getSizer(This) -> wxWindow:getSizer(This).
%% @hidden
getSize(This) -> wxWindow:getSize(This).
%% @hidden
getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient).
%% @hidden
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
%% @hidden
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
%% @hidden
getScreenRect(This) -> wxWindow:getScreenRect(This).
%% @hidden
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
%% @hidden
getRect(This) -> wxWindow:getRect(This).
%% @hidden
getPosition(This) -> wxWindow:getPosition(This).
%% @hidden
getParent(This) -> wxWindow:getParent(This).
%% @hidden
getName(This) -> wxWindow:getName(This).
%% @hidden
getMinSize(This) -> wxWindow:getMinSize(This).
%% @hidden
getMaxSize(This) -> wxWindow:getMaxSize(This).
%% @hidden
getId(This) -> wxWindow:getId(This).
%% @hidden
getHelpText(This) -> wxWindow:getHelpText(This).
%% @hidden
getHandle(This) -> wxWindow:getHandle(This).
%% @hidden
getGrandParent(This) -> wxWindow:getGrandParent(This).
%% @hidden
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
%% @hidden
getFont(This) -> wxWindow:getFont(This).
%% @hidden
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
%% @hidden
getEventHandler(This) -> wxWindow:getEventHandler(This).
%% @hidden
getDropTarget(This) -> wxWindow:getDropTarget(This).
%% @hidden
getCursor(This) -> wxWindow:getCursor(This).
%% @hidden
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
%% @hidden
getClientSize(This) -> wxWindow:getClientSize(This).
%% @hidden
getChildren(This) -> wxWindow:getChildren(This).
%% @hidden
getCharWidth(This) -> wxWindow:getCharWidth(This).
%% @hidden
getCharHeight(This) -> wxWindow:getCharHeight(This).
%% @hidden
getCaret(This) -> wxWindow:getCaret(This).
%% @hidden
getBestSize(This) -> wxWindow:getBestSize(This).
%% @hidden
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
%% @hidden
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
%% @hidden
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
%% @hidden
freeze(This) -> wxWindow:freeze(This).
%% @hidden
fitInside(This) -> wxWindow:fitInside(This).
%% @hidden
fit(This) -> wxWindow:fit(This).
%% @hidden
findWindow(This,Winid) -> wxWindow:findWindow(This,Winid).
%% @hidden
enable(This, Options) -> wxWindow:enable(This, Options).
%% @hidden
enable(This) -> wxWindow:enable(This).
%% @hidden
disable(This) -> wxWindow:disable(This).
%% @hidden
destroyChildren(This) -> wxWindow:destroyChildren(This).
%% @hidden
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
%% @hidden
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
%% @hidden
close(This, Options) -> wxWindow:close(This, Options).
%% @hidden
close(This) -> wxWindow:close(This).
%% @hidden
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
%% @hidden
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
%% @hidden
clearBackground(This) -> wxWindow:clearBackground(This).
%% @hidden
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
%% @hidden
centreOnParent(This) -> wxWindow:centreOnParent(This).
%% @hidden
centre(This, Options) -> wxWindow:centre(This, Options).
%% @hidden
centre(This) -> wxWindow:centre(This).
%% @hidden
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
%% @hidden
centerOnParent(This) -> wxWindow:centerOnParent(This).
%% @hidden
center(This, Options) -> wxWindow:center(This, Options).
%% @hidden
center(This) -> wxWindow:center(This).
%% @hidden
captureMouse(This) -> wxWindow:captureMouse(This).
%% @hidden
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
%% From wxEvtHandler
%% @hidden
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
%% @hidden
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
%% @hidden
disconnect(This) -> wxEvtHandler:disconnect(This).
%% @hidden
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
%% @hidden
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxGenericDirCtrl.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
@doc See external documentation: <a href="">wxGenericDirCtrl</a>.
<p>This class is derived (and can use functions) from:
<br />{@link wxControl}
<br />{@link wxWindow}
<br />{@link wxEvtHandler}
</p>
@type wxGenericDirCtrl(). An object reference, The representation is internal
and can be changed without notice. It can't be used for comparsion
stored on disc or distributed for use on other nodes.
inherited exports
@hidden
@doc See <a href="#wxgenericdirctrlwxgenericdirctrl">external documentation</a>.
@equiv new(Parent, [])
@doc See <a href="#wxgenericdirctrlwxgenericdirctrl">external documentation</a>.
@spec (This::wxGenericDirCtrl(), Parent::wxWindow:wxWindow()) -> bool()
@equiv create(This,Parent, [])
@spec (This::wxGenericDirCtrl(), Parent::wxWindow:wxWindow(), [Option]) -> bool()
@doc See <a href="#wxgenericdirctrlcreate">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> ok
@doc See <a href="#wxgenericdirctrlinit">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> ok
@doc See <a href="#wxgenericdirctrlcollapsetree">external documentation</a>.
@spec (This::wxGenericDirCtrl(), Path::string()) -> bool()
@doc See <a href="#wxgenericdirctrlexpandpath">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> string()
@doc See <a href="#wxgenericdirctrlgetdefaultpath">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> string()
@doc See <a href="#wxgenericdirctrlgetpath">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> string()
@doc See <a href="#wxgenericdirctrlgetfilepath">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> string()
@doc See <a href="#wxgenericdirctrlgetfilter">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> integer()
@doc See <a href="#wxgenericdirctrlgetfilterindex">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> wxTreeItemId()
@doc See <a href="#wxgenericdirctrlgetrootid">external documentation</a>.
@doc See <a href="#wxgenericdirctrlgettreectrl">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> ok
@doc See <a href="#wxgenericdirctrlrecreatetree">external documentation</a>.
@spec (This::wxGenericDirCtrl(), Path::string()) -> ok
@doc See <a href="#wxgenericdirctrlsetdefaultpath">external documentation</a>.
@spec (This::wxGenericDirCtrl(), N::integer()) -> ok
@doc See <a href="#wxgenericdirctrlsetfilterindex">external documentation</a>.
@spec (This::wxGenericDirCtrl(), Path::string()) -> ok
@doc See <a href="#wxgenericdirctrlsetpath">external documentation</a>.
@spec (This::wxGenericDirCtrl()) -> ok
@doc Destroys this object, do not use object again
From wxControl
@hidden
@hidden
From wxWindow
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
From wxEvtHandler
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2008 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(wxGenericDirCtrl).
-include("wxe.hrl").
-export([collapseTree/1,create/2,create/3,destroy/1,expandPath/2,getDefaultPath/1,
getFilePath/1,getFilter/1,getFilterIndex/1,getPath/1,getRootId/1,getTreeCtrl/1,
init/1,new/0,new/1,new/2,reCreateTree/1,setDefaultPath/2,setFilter/2,
setFilterIndex/2,setPath/2]).
-export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1,
centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2,
clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2,
connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2,
destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3,
enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1,
getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1,
getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1,
getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1,
getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1,
getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1,
getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2,
getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2,
getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1,
getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1,
hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1,
isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1,
layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2,
move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1,
navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2,
popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2,
refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1,
screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4,
setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2,
setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2,
setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2,
setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2,
setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2,
setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6,
setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3,
setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3,
setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3,
setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4,
setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1,
show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1,
update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]).
parent_class(wxControl) -> true;
parent_class(wxWindow) -> true;
parent_class(wxEvtHandler) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
( ) - > ( )
new() ->
wxe_util:construct(?wxGenericDirCtrl_new_0,
<<>>).
( Parent::wxWindow : wxWindow ( ) ) - > ( )
new(Parent)
when is_record(Parent, wx_ref) ->
new(Parent, []).
( Parent::wxWindow : wxWindow ( ) , [ Option ] ) - > ( )
Option = { i d , integer ( ) } | , string ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } | { filter , string ( ) } | { defaultFilter , integer ( ) }
new(#wx_ref{type=ParentT,ref=ParentRef}, Options)
when is_list(Options) ->
?CLASS(ParentT,wxWindow),
MOpts = fun({id, Id}, Acc) -> [<<1:32/?UI,Id:32/?UI>>|Acc];
({dir, Dir}, Acc) -> Dir_UC = unicode:characters_to_binary([Dir,0]),[<<2:32/?UI,(byte_size(Dir_UC)):32/?UI,(Dir_UC)/binary, 0:(((8- ((0+byte_size(Dir_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<3:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<4:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<5:32/?UI,Style:32/?UI>>|Acc];
({filter, Filter}, Acc) -> Filter_UC = unicode:characters_to_binary([Filter,0]),[<<6:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({defaultFilter, DefaultFilter}, Acc) -> [<<7:32/?UI,DefaultFilter:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:construct(?wxGenericDirCtrl_new_2,
<<ParentRef:32/?UI, 0:32,BinOpt/binary>>).
create(This,Parent)
when is_record(This, wx_ref),is_record(Parent, wx_ref) ->
create(This,Parent, []).
Option = { i d , integer ( ) } | , string ( ) } | { pos , { X::integer(),Y::integer ( ) } } | { size , { W::integer(),H::integer ( ) } } | { style , integer ( ) } | { filter , string ( ) } | { defaultFilter , integer ( ) }
create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}, Options)
when is_list(Options) ->
?CLASS(ThisT,wxGenericDirCtrl),
?CLASS(ParentT,wxWindow),
MOpts = fun({id, Id}, Acc) -> [<<1:32/?UI,Id:32/?UI>>|Acc];
({dir, Dir}, Acc) -> Dir_UC = unicode:characters_to_binary([Dir,0]),[<<2:32/?UI,(byte_size(Dir_UC)):32/?UI,(Dir_UC)/binary, 0:(((8- ((0+byte_size(Dir_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({pos, {PosX,PosY}}, Acc) -> [<<3:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc];
({size, {SizeW,SizeH}}, Acc) -> [<<4:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc];
({style, Style}, Acc) -> [<<5:32/?UI,Style:32/?UI>>|Acc];
({filter, Filter}, Acc) -> Filter_UC = unicode:characters_to_binary([Filter,0]),[<<6:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>|Acc];
({defaultFilter, DefaultFilter}, Acc) -> [<<7:32/?UI,DefaultFilter:32/?UI>>|Acc];
(BadOpt, _) -> erlang:error({badoption, BadOpt}) end,
BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)),
wxe_util:call(?wxGenericDirCtrl_Create,
<<ThisRef:32/?UI,ParentRef:32/?UI, BinOpt/binary>>).
init(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_Init,
<<ThisRef:32/?UI>>).
collapseTree(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_CollapseTree,
<<ThisRef:32/?UI>>).
expandPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:call(?wxGenericDirCtrl_ExpandPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
getDefaultPath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetDefaultPath,
<<ThisRef:32/?UI>>).
getPath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetPath,
<<ThisRef:32/?UI>>).
getFilePath(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilePath,
<<ThisRef:32/?UI>>).
getFilter(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilter,
<<ThisRef:32/?UI>>).
getFilterIndex(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetFilterIndex,
<<ThisRef:32/?UI>>).
getRootId(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetRootId,
<<ThisRef:32/?UI>>).
@spec ( This::wxGenericDirCtrl ( ) ) - > wxTreeCtrl : wxTreeCtrl ( )
getTreeCtrl(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:call(?wxGenericDirCtrl_GetTreeCtrl,
<<ThisRef:32/?UI>>).
reCreateTree(#wx_ref{type=ThisT,ref=ThisRef}) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_ReCreateTree,
<<ThisRef:32/?UI>>).
setDefaultPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:cast(?wxGenericDirCtrl_SetDefaultPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
@spec ( This::wxGenericDirCtrl ( ) , ( ) ) - > ok
@doc See < a href=" / manuals / stable / wx_wxgenericdirctrl.html#wxgenericdirctrlsetfilter">external documentation</a > .
setFilter(#wx_ref{type=ThisT,ref=ThisRef},Filter)
when is_list(Filter) ->
?CLASS(ThisT,wxGenericDirCtrl),
Filter_UC = unicode:characters_to_binary([Filter,0]),
wxe_util:cast(?wxGenericDirCtrl_SetFilter,
<<ThisRef:32/?UI,(byte_size(Filter_UC)):32/?UI,(Filter_UC)/binary, 0:(((8- ((0+byte_size(Filter_UC)) band 16#7)) band 16#7))/unit:8>>).
setFilterIndex(#wx_ref{type=ThisT,ref=ThisRef},N)
when is_integer(N) ->
?CLASS(ThisT,wxGenericDirCtrl),
wxe_util:cast(?wxGenericDirCtrl_SetFilterIndex,
<<ThisRef:32/?UI,N:32/?UI>>).
setPath(#wx_ref{type=ThisT,ref=ThisRef},Path)
when is_list(Path) ->
?CLASS(ThisT,wxGenericDirCtrl),
Path_UC = unicode:characters_to_binary([Path,0]),
wxe_util:cast(?wxGenericDirCtrl_SetPath,
<<ThisRef:32/?UI,(byte_size(Path_UC)):32/?UI,(Path_UC)/binary, 0:(((8- ((0+byte_size(Path_UC)) band 16#7)) band 16#7))/unit:8>>).
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxGenericDirCtrl),
wxe_util:destroy(?DESTROY_OBJECT,Obj),
ok.
setLabel(This,Label) -> wxControl:setLabel(This,Label).
getLabel(This) -> wxControl:getLabel(This).
warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y).
validate(This) -> wxWindow:validate(This).
updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options).
updateWindowUI(This) -> wxWindow:updateWindowUI(This).
update(This) -> wxWindow:update(This).
transferDataToWindow(This) -> wxWindow:transferDataToWindow(This).
transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This).
thaw(This) -> wxWindow:thaw(This).
show(This, Options) -> wxWindow:show(This, Options).
show(This) -> wxWindow:show(This).
shouldInheritColours(This) -> wxWindow:shouldInheritColours(This).
setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant).
setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style).
setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style).
setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options).
setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH).
setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize).
setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y).
setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size).
setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip).
setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme).
setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options).
setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer).
setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options).
setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer).
setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options).
setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH).
setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize).
setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options).
setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height).
setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height).
setSize(This,Rect) -> wxWindow:setSize(This,Rect).
setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options).
setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos).
setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options).
setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range).
setPalette(This,Pal) -> wxWindow:setPalette(This,Pal).
setName(This,Name) -> wxWindow:setName(This,Name).
setId(This,Winid) -> wxWindow:setId(This,Winid).
setHelpText(This,Text) -> wxWindow:setHelpText(This,Text).
setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour).
setFont(This,Font) -> wxWindow:setFont(This,Font).
setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This).
setFocus(This) -> wxWindow:setFocus(This).
setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle).
setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget).
setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour).
setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font).
setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour).
setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize).
setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize).
setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor).
setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer).
setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height).
setClientSize(This,Size) -> wxWindow:setClientSize(This,Size).
setCaret(This,Caret) -> wxWindow:setCaret(This,Caret).
setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style).
setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour).
setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout).
setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel).
scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options).
scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy).
scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages).
scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines).
screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt).
screenToClient(This) -> wxWindow:screenToClient(This).
reparent(This,NewParent) -> wxWindow:reparent(This,NewParent).
removeChild(This,Child) -> wxWindow:removeChild(This,Child).
releaseMouse(This) -> wxWindow:releaseMouse(This).
refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options).
refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect).
refresh(This, Options) -> wxWindow:refresh(This, Options).
refresh(This) -> wxWindow:refresh(This).
raise(This) -> wxWindow:raise(This).
popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y).
popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options).
popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu).
popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options).
popEventHandler(This) -> wxWindow:popEventHandler(This).
pageUp(This) -> wxWindow:pageUp(This).
pageDown(This) -> wxWindow:pageDown(This).
navigate(This, Options) -> wxWindow:navigate(This, Options).
navigate(This) -> wxWindow:navigate(This).
moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win).
moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win).
move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options).
move(This,X,Y) -> wxWindow:move(This,X,Y).
move(This,Pt) -> wxWindow:move(This,Pt).
makeModal(This, Options) -> wxWindow:makeModal(This, Options).
makeModal(This) -> wxWindow:makeModal(This).
lower(This) -> wxWindow:lower(This).
lineUp(This) -> wxWindow:lineUp(This).
lineDown(This) -> wxWindow:lineDown(This).
layout(This) -> wxWindow:layout(This).
isTopLevel(This) -> wxWindow:isTopLevel(This).
isShown(This) -> wxWindow:isShown(This).
isRetained(This) -> wxWindow:isRetained(This).
isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H).
isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y).
isExposed(This,Pt) -> wxWindow:isExposed(This,Pt).
isEnabled(This) -> wxWindow:isEnabled(This).
invalidateBestSize(This) -> wxWindow:invalidateBestSize(This).
initDialog(This) -> wxWindow:initDialog(This).
inheritAttributes(This) -> wxWindow:inheritAttributes(This).
hide(This) -> wxWindow:hide(This).
hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This).
hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient).
hasCapture(This) -> wxWindow:hasCapture(This).
getWindowVariant(This) -> wxWindow:getWindowVariant(This).
getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This).
getVirtualSize(This) -> wxWindow:getVirtualSize(This).
getUpdateRegion(This) -> wxWindow:getUpdateRegion(This).
getToolTip(This) -> wxWindow:getToolTip(This).
getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options).
getTextExtent(This,String) -> wxWindow:getTextExtent(This,String).
getSizer(This) -> wxWindow:getSizer(This).
getSize(This) -> wxWindow:getSize(This).
getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient).
getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient).
getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient).
getScreenRect(This) -> wxWindow:getScreenRect(This).
getScreenPosition(This) -> wxWindow:getScreenPosition(This).
getRect(This) -> wxWindow:getRect(This).
getPosition(This) -> wxWindow:getPosition(This).
getParent(This) -> wxWindow:getParent(This).
getName(This) -> wxWindow:getName(This).
getMinSize(This) -> wxWindow:getMinSize(This).
getMaxSize(This) -> wxWindow:getMaxSize(This).
getId(This) -> wxWindow:getId(This).
getHelpText(This) -> wxWindow:getHelpText(This).
getHandle(This) -> wxWindow:getHandle(This).
getGrandParent(This) -> wxWindow:getGrandParent(This).
getForegroundColour(This) -> wxWindow:getForegroundColour(This).
getFont(This) -> wxWindow:getFont(This).
getExtraStyle(This) -> wxWindow:getExtraStyle(This).
getEventHandler(This) -> wxWindow:getEventHandler(This).
getDropTarget(This) -> wxWindow:getDropTarget(This).
getCursor(This) -> wxWindow:getCursor(This).
getContainingSizer(This) -> wxWindow:getContainingSizer(This).
getClientSize(This) -> wxWindow:getClientSize(This).
getChildren(This) -> wxWindow:getChildren(This).
getCharWidth(This) -> wxWindow:getCharWidth(This).
getCharHeight(This) -> wxWindow:getCharHeight(This).
getCaret(This) -> wxWindow:getCaret(This).
getBestSize(This) -> wxWindow:getBestSize(This).
getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This).
getBackgroundColour(This) -> wxWindow:getBackgroundColour(This).
getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This).
freeze(This) -> wxWindow:freeze(This).
fitInside(This) -> wxWindow:fitInside(This).
fit(This) -> wxWindow:fit(This).
findWindow(This,Winid) -> wxWindow:findWindow(This,Winid).
enable(This, Options) -> wxWindow:enable(This, Options).
enable(This) -> wxWindow:enable(This).
disable(This) -> wxWindow:disable(This).
destroyChildren(This) -> wxWindow:destroyChildren(This).
convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz).
convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz).
close(This, Options) -> wxWindow:close(This, Options).
close(This) -> wxWindow:close(This).
clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y).
clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt).
clearBackground(This) -> wxWindow:clearBackground(This).
centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options).
centreOnParent(This) -> wxWindow:centreOnParent(This).
centre(This, Options) -> wxWindow:centre(This, Options).
centre(This) -> wxWindow:centre(This).
centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options).
centerOnParent(This) -> wxWindow:centerOnParent(This).
center(This, Options) -> wxWindow:center(This, Options).
center(This) -> wxWindow:center(This).
captureMouse(This) -> wxWindow:captureMouse(This).
cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size).
disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options).
disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType).
disconnect(This) -> wxEvtHandler:disconnect(This).
connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options).
connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
|
0fc4495011a8a8a8a3c41f68eb31b1569d003a68fdb4f7cd01a3e4de57edc28b | justinethier/cyclone | when.scm | (import (scheme base) (scheme write))
;(define-syntax my-when
; (syntax-rules ()
( ( my - when test result1 result2 ... )
; (if test
( begin result1 result2 ... ) ) ) ) )
(define-syntax my-when2
(syntax-rules ()
((my-when test result1 result2 ...)
(list result2 ...))))
(write
(my-when2 #t 1))
;
; (define my-when2*
; (lambda (expr$28 rename$29 compare$30)
; (car ((lambda (tmp$42)
; (if tmp$42
; tmp$42
; (cons (error "no expansion for" expr$28) #f)))
; ((lambda (v.1$36)
; (if (pair? v.1$36)
( ( lambda ( )
; ((lambda (test)
; ((lambda (v.3$38)
; (if (pair? v.3$38)
; ((lambda (v.4$39)
; ((lambda (result1)
; ((lambda (v.5$40)
; (if (list? v.5$40)
( ( lambda ( )
; (cons (cons-source
; (rename$29 'list)
; (cons-source test '() '(test))
; '(list test))
; #f))
; v.5$40)
; #f))
; (cdr v.3$38)))
; v.4$39))
; (car v.3$38))
; #f))
; (cdr v.1$36)))
) )
; (car v.1$36))
; #f))
; (cdr expr$28))))))
;; TODO: seems broken
;(define-syntax my-when4
; (syntax-rules ()
( ( my - when test result1 result2 ... )
; (let-syntax
( ( second
; (syntax-rules ()
( ( second a b c )
; b))))
( second 33 44 55 ) ) ) ) )
;(write
; (my-when4 't 1 2 3))
;; The symbol?? macro from oleg:
;; #macro-symbol-p
(define-syntax symbol??
(syntax-rules ()
((symbol?? (x . y) kt kf) kf) ; It's a pair, not a symbol
((symbol?? #(x ...) kt kf) kf) ; It's a vector, not a symbol
((symbol?? maybe-symbol kt kf)
(let-syntax
((test
(syntax-rules ()
((test maybe-symbol t f) t)
((test x t f) f))))
(test abracadabra kt kf)))))
(write (symbol?? a #t #f))
(write (symbol?? "a" #t #f))
(write
(let-syntax
((second
(syntax-rules ()
((second a b c)
b))))
(second 33 44 55)))
(write
(my-when2
't
1
(let-syntax
((my-when3
(syntax-rules ()
((my-when3 test result1 result2 ...)
(list result2 ...)))))
(my-when3 33 44 55))
2
3))
;(write
; (my-when2 '(my-when2 't 1 2 3) (lambda (a) a) (lambda X #f)))
;(write
( my - when2 ' ( my - when2 " testing " 1 ) ( lambda ( a ) a ) ( lambda X # f ) ) )
| null | https://raw.githubusercontent.com/justinethier/cyclone/a1c2a8f282f37ce180a5921ae26a5deb04768269/tests/when.scm | scheme | (define-syntax my-when
(syntax-rules ()
(if test
(define my-when2*
(lambda (expr$28 rename$29 compare$30)
(car ((lambda (tmp$42)
(if tmp$42
tmp$42
(cons (error "no expansion for" expr$28) #f)))
((lambda (v.1$36)
(if (pair? v.1$36)
((lambda (test)
((lambda (v.3$38)
(if (pair? v.3$38)
((lambda (v.4$39)
((lambda (result1)
((lambda (v.5$40)
(if (list? v.5$40)
(cons (cons-source
(rename$29 'list)
(cons-source test '() '(test))
'(list test))
#f))
v.5$40)
#f))
(cdr v.3$38)))
v.4$39))
(car v.3$38))
#f))
(cdr v.1$36)))
(car v.1$36))
#f))
(cdr expr$28))))))
TODO: seems broken
(define-syntax my-when4
(syntax-rules ()
(let-syntax
(syntax-rules ()
b))))
(write
(my-when4 't 1 2 3))
The symbol?? macro from oleg:
#macro-symbol-p
It's a pair, not a symbol
It's a vector, not a symbol
(write
(my-when2 '(my-when2 't 1 2 3) (lambda (a) a) (lambda X #f)))
(write | (import (scheme base) (scheme write))
( ( my - when test result1 result2 ... )
( begin result1 result2 ... ) ) ) ) )
(define-syntax my-when2
(syntax-rules ()
((my-when test result1 result2 ...)
(list result2 ...))))
(write
(my-when2 #t 1))
( ( lambda ( )
( ( lambda ( )
) )
( ( my - when test result1 result2 ... )
( ( second
( ( second a b c )
( second 33 44 55 ) ) ) ) )
(define-syntax symbol??
(syntax-rules ()
((symbol?? maybe-symbol kt kf)
(let-syntax
((test
(syntax-rules ()
((test maybe-symbol t f) t)
((test x t f) f))))
(test abracadabra kt kf)))))
(write (symbol?? a #t #f))
(write (symbol?? "a" #t #f))
(write
(let-syntax
((second
(syntax-rules ()
((second a b c)
b))))
(second 33 44 55)))
(write
(my-when2
't
1
(let-syntax
((my-when3
(syntax-rules ()
((my-when3 test result1 result2 ...)
(list result2 ...)))))
(my-when3 33 44 55))
2
3))
( my - when2 ' ( my - when2 " testing " 1 ) ( lambda ( a ) a ) ( lambda X # f ) ) )
|
161ab7e2427bd9d7e7d78871c7253296668bcc0fcc67f843c562340dc84e3f7c | dundalek/closh | scripting_test.cljc | (ns closh.scripting-test
(:require [clojure.test :refer [deftest are]]
[closh.zero.core :refer [shx]]
[closh.zero.pipeline :refer [process-output process-value pipe]]))
(def sci? #?(:clj (System/getenv "__CLOSH_USE_SCI_EVAL__")
:cljs false))
(def sci-complete? #?(:clj (System/getenv "__CLOSH_USE_SCI_COMPLETE__")
:cljs false))
(defn closh [& args]
(shx "clojure" (concat (if sci?
["-M:sci" "-m" "closh.zero.frontend.sci"]
["-m" "closh.zero.frontend.rebel"])
args)))
(deftest scripting-test
(are [x y] (= x (process-output y))
"a b\n"
(closh "-e" "echo a b")
"a b\n"
(pipe (shx "echo" ["echo a b"])
(closh "-"))
"3\n"
(pipe (shx "echo" ["echo (+ 1 2)"])
(closh "-"))
"bar\n"
(closh "fixtures/script-mode-tests/bar.cljc")
"foo\nbar\n"
(closh "fixtures/script-mode-tests/foo.cljc")
"Hi World\n"
(closh "-i" "fixtures/script-mode-tests/cmd.cljc" "-e" "my-hello World")
"Hello World\n"
(closh "-i" "fixtures/script-mode-tests/cmd2.cljc")
"(\"a\" \"b\")\n"
(closh "fixtures/script-mode-tests/args.cljc" "a" "b")
"a b\n"
(closh "fixtures/script-mode-tests/cond.cljc")
TODO metadata reader for sci
"true"
(closh "-e" (if sci?
"(print (:dynamic (meta (with-meta {} {:dynamic true}))))"
"(print (:dynamic (meta ^:dynamic {})))"))))
(when (or (not sci?)
sci-complete?)
(deftest scripting-errors-test
(are [result regex cmd] (= result (->> (:stderr (process-value cmd))
(re-find regex)
(second)))
"5:3"
#"/throw1\.cljc:(\d+:\d+)"
(closh "fixtures/script-mode-tests/throw1.cljc")
"4:2"
#"Syntax error compiling at \(REPL:(\d+:\d+)\)"
(pipe "\n\n\n (throw (Exception. \"my exception message\"))" (closh "-"))
TODO
" 2:4 "
; (if (System/getenv "__CLOSH_USE_SCI_EVAL__")
; #"Syntax error reading source at \(REPL:(\d+:\d+)\)"
; #"Syntax error \(ExceptionInfo\) compiling at \(REPL:(\d+:\d+)\)")
( pipe " \n ) " ( closh " - " ) )
"5:1"
#"/throw2\.cljc:(\d+:\d+)"
(closh "fixtures/script-mode-tests/throw2.cljc")
"3"
#"Execution error at .* \(REPL:(\d+)\)"
(closh "-e" "\n\n(throw (Exception. \"my exception message\"))"))))
" 2 "
; #"Execution error at .* \(REPL:(\d+)\)"
( closh " -e " " \n ) " ) ) )
| null | https://raw.githubusercontent.com/dundalek/closh/b1a7fd310b6511048fbacb8e496f574c8ccfa291/test/closh/scripting_test.cljc | clojure | (if (System/getenv "__CLOSH_USE_SCI_EVAL__")
#"Syntax error reading source at \(REPL:(\d+:\d+)\)"
#"Syntax error \(ExceptionInfo\) compiling at \(REPL:(\d+:\d+)\)")
#"Execution error at .* \(REPL:(\d+)\)" | (ns closh.scripting-test
(:require [clojure.test :refer [deftest are]]
[closh.zero.core :refer [shx]]
[closh.zero.pipeline :refer [process-output process-value pipe]]))
(def sci? #?(:clj (System/getenv "__CLOSH_USE_SCI_EVAL__")
:cljs false))
(def sci-complete? #?(:clj (System/getenv "__CLOSH_USE_SCI_COMPLETE__")
:cljs false))
(defn closh [& args]
(shx "clojure" (concat (if sci?
["-M:sci" "-m" "closh.zero.frontend.sci"]
["-m" "closh.zero.frontend.rebel"])
args)))
(deftest scripting-test
(are [x y] (= x (process-output y))
"a b\n"
(closh "-e" "echo a b")
"a b\n"
(pipe (shx "echo" ["echo a b"])
(closh "-"))
"3\n"
(pipe (shx "echo" ["echo (+ 1 2)"])
(closh "-"))
"bar\n"
(closh "fixtures/script-mode-tests/bar.cljc")
"foo\nbar\n"
(closh "fixtures/script-mode-tests/foo.cljc")
"Hi World\n"
(closh "-i" "fixtures/script-mode-tests/cmd.cljc" "-e" "my-hello World")
"Hello World\n"
(closh "-i" "fixtures/script-mode-tests/cmd2.cljc")
"(\"a\" \"b\")\n"
(closh "fixtures/script-mode-tests/args.cljc" "a" "b")
"a b\n"
(closh "fixtures/script-mode-tests/cond.cljc")
TODO metadata reader for sci
"true"
(closh "-e" (if sci?
"(print (:dynamic (meta (with-meta {} {:dynamic true}))))"
"(print (:dynamic (meta ^:dynamic {})))"))))
(when (or (not sci?)
sci-complete?)
(deftest scripting-errors-test
(are [result regex cmd] (= result (->> (:stderr (process-value cmd))
(re-find regex)
(second)))
"5:3"
#"/throw1\.cljc:(\d+:\d+)"
(closh "fixtures/script-mode-tests/throw1.cljc")
"4:2"
#"Syntax error compiling at \(REPL:(\d+:\d+)\)"
(pipe "\n\n\n (throw (Exception. \"my exception message\"))" (closh "-"))
TODO
" 2:4 "
( pipe " \n ) " ( closh " - " ) )
"5:1"
#"/throw2\.cljc:(\d+:\d+)"
(closh "fixtures/script-mode-tests/throw2.cljc")
"3"
#"Execution error at .* \(REPL:(\d+)\)"
(closh "-e" "\n\n(throw (Exception. \"my exception message\"))"))))
" 2 "
( closh " -e " " \n ) " ) ) )
|
867264ae796c23ab6b092cf640d7b377559b75d2d9ad598a77f8f926b1c17645 | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.AmountOfMoney.KA.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.AmountOfMoney.KA.Corpus
tests :: TestTree
tests = testGroup "KA Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/AmountOfMoney/KA/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.AmountOfMoney.KA.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Testing.Asserts
import Duckling.AmountOfMoney.KA.Corpus
tests :: TestTree
tests = testGroup "KA Tests"
[ makeCorpusTest [Seal AmountOfMoney] corpus
]
|
bdb49dcdde2b23b611501bb745f1a215b79e8aaf1e82220d2fe778c4f18e45bc | input-output-hk/cardano-ledger | Hash.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
module Cardano.Chain.Genesis.Hash (
GenesisHash (..),
)
where
import Cardano.Crypto.Hashing (Hash)
import Cardano.Crypto.Raw (Raw)
import Cardano.Ledger.Binary (DecCBOR, EncCBOR)
import Cardano.Prelude
import Data.Aeson (ToJSON)
import NoThunks.Class (NoThunks (..))
newtype GenesisHash = GenesisHash
{ unGenesisHash :: Hash Raw
}
deriving (Eq, Generic, NFData, DecCBOR, EncCBOR, NoThunks)
deriving instance Show GenesisHash
-- Used for debugging purposes only
instance ToJSON GenesisHash
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/49a84725c4c2ecabc80f6dac215881bc23920962/eras/byron/ledger/impl/src/Cardano/Chain/Genesis/Hash.hs | haskell | Used for debugging purposes only | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
module Cardano.Chain.Genesis.Hash (
GenesisHash (..),
)
where
import Cardano.Crypto.Hashing (Hash)
import Cardano.Crypto.Raw (Raw)
import Cardano.Ledger.Binary (DecCBOR, EncCBOR)
import Cardano.Prelude
import Data.Aeson (ToJSON)
import NoThunks.Class (NoThunks (..))
newtype GenesisHash = GenesisHash
{ unGenesisHash :: Hash Raw
}
deriving (Eq, Generic, NFData, DecCBOR, EncCBOR, NoThunks)
deriving instance Show GenesisHash
instance ToJSON GenesisHash
|
1e5b34f6c5de3d288338065a9325c30c9e9b75a948a76d3b124bca82588fec63 | Ptival/chick | List.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
module Diff.List
( Diff (..),
nKeeps,
nRemoves,
patch,
)
where
import Data.Aeson (ToJSON)
import Data.Bifunctor (Bifunctor, bimap)
import Diff.Utils (permute)
import GHC.Generics (Generic)
import Polysemy (Member, Sem)
import Polysemy.Error (Error, throw)
import Polysemy.Trace (Trace)
import PrettyPrinting.PrettyPrintable
( PrettyPrintable (prettyDoc),
)
import qualified Prettyprinter as Doc
import Text.Printf (printf)
data Diff t δt
= Insert t (Diff t δt)
| Keep (Diff t δt)
| Modify δt (Diff t δt)
| Permute [Int] (Diff t δt)
| Remove (Diff t δt)
| Replace [t]
| Same
deriving (Eq, Generic)
instance
( ToJSON t,
ToJSON δt
) =>
ToJSON (Diff t δt)
instance
( Show t,
Show δt
) =>
Show (Diff t δt)
where
show = \case
Insert t δ -> printf "Insert (%s)\n%s" (show t) (show δ)
Keep δ -> printf "Keep\n%s" (show δ)
Modify δt δ -> printf "Modify (%s)\n%s" (show δt) (show δ)
Permute p δ -> printf "Permute (%s)\n%s" (show p) (show δ)
Remove δ -> printf "Remove\n%s" (show δ)
Replace l -> printf "Replace (%s)" (show l)
Same -> "Same"
instance
( PrettyPrintable l t,
PrettyPrintable l δt
) =>
PrettyPrintable l (Diff t δt)
where
prettyDoc = \case
Insert t δ -> Doc.fillSep ["Insert", go t, go δ]
Keep δ -> Doc.fillSep ["Keep", go δ]
Modify δt δ -> Doc.fillSep ["Modify", go δt, go δ]
Permute p δ -> Doc.fillSep ["Permute", Doc.pretty (show p), go δ]
Remove δ -> Doc.fillSep ["Remove", go δ]
Replace l -> Doc.fillSep ["Replace", Doc.encloseSep Doc.lbracket Doc.rbracket Doc.comma (map (prettyDoc @l) l)]
Same -> "Same"
where
go :: PrettyPrintable l x => x -> Doc.Doc ()
go x = Doc.fillSep [Doc.lparen, prettyDoc @l x, Doc.rparen]
instance Bifunctor Diff where
bimap fa fb = \case
Same -> Same
Insert a δ -> Insert (fa a) (bimap fa fb δ)
Modify b δ -> Modify (fb b) (bimap fa fb δ)
Permute p δ -> Permute p (bimap fa fb δ)
Keep δ -> Keep (bimap fa fb δ)
Remove δ -> Remove (bimap fa fb δ)
Replace la -> Replace (map fa la)
patch ::
Member (Error String) r =>
Member Trace r =>
PrettyPrintable l a = >
PrettyPrintable l δa = >
(a -> δa -> Sem r a) ->
[a] ->
Diff a δa ->
Sem r [a]
patch patchElem = go
where
trace ( printf " Diff . List / patch(l : % s , δ : % s ) "
( display . . rbracket comma $ map prettyDoc la )
-- (prettyStr δa)
-- ) >>
failWith :: Member (Error String) r => String -> Sem r a
failWith s = throw (printf "[Diff.List.patch] %s" s :: String)
go l = \case
Same -> return l
Insert e δ -> (e :) <$> go l δ
Modify δe δ -> case l of
h : t -> do
ph <- patchElem h δe
pt <- go t δ
return $ ph : pt
_ -> failWith "Modify, empty list"
Permute p δ ->
let ll = length l
in if ll > length p || ll < maximum p
then failWith "Permut, permutation exceeds list size"
else go (permute p l) δ
Keep δ -> case l of
h : t -> (h :) <$> go t δ
_ -> failWith "Keep, empty list"
Remove δ -> case l of
[] -> failWith "Remove, empty list"
_ : t -> go t δ
Replace r -> return r
nKeeps :: Int -> Diff τ δτ -> Diff τ δτ
nKeeps 0 = id
nKeeps n = Keep . nKeeps (n - 1)
nRemoves :: Int -> Diff τ δτ -> Diff τ δτ
nRemoves 0 = id
nRemoves n = Remove . nRemoves (n - 1)
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/Diff/List.hs | haskell | # LANGUAGE OverloadedStrings #
(prettyStr δa)
) >> | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
module Diff.List
( Diff (..),
nKeeps,
nRemoves,
patch,
)
where
import Data.Aeson (ToJSON)
import Data.Bifunctor (Bifunctor, bimap)
import Diff.Utils (permute)
import GHC.Generics (Generic)
import Polysemy (Member, Sem)
import Polysemy.Error (Error, throw)
import Polysemy.Trace (Trace)
import PrettyPrinting.PrettyPrintable
( PrettyPrintable (prettyDoc),
)
import qualified Prettyprinter as Doc
import Text.Printf (printf)
data Diff t δt
= Insert t (Diff t δt)
| Keep (Diff t δt)
| Modify δt (Diff t δt)
| Permute [Int] (Diff t δt)
| Remove (Diff t δt)
| Replace [t]
| Same
deriving (Eq, Generic)
instance
( ToJSON t,
ToJSON δt
) =>
ToJSON (Diff t δt)
instance
( Show t,
Show δt
) =>
Show (Diff t δt)
where
show = \case
Insert t δ -> printf "Insert (%s)\n%s" (show t) (show δ)
Keep δ -> printf "Keep\n%s" (show δ)
Modify δt δ -> printf "Modify (%s)\n%s" (show δt) (show δ)
Permute p δ -> printf "Permute (%s)\n%s" (show p) (show δ)
Remove δ -> printf "Remove\n%s" (show δ)
Replace l -> printf "Replace (%s)" (show l)
Same -> "Same"
instance
( PrettyPrintable l t,
PrettyPrintable l δt
) =>
PrettyPrintable l (Diff t δt)
where
prettyDoc = \case
Insert t δ -> Doc.fillSep ["Insert", go t, go δ]
Keep δ -> Doc.fillSep ["Keep", go δ]
Modify δt δ -> Doc.fillSep ["Modify", go δt, go δ]
Permute p δ -> Doc.fillSep ["Permute", Doc.pretty (show p), go δ]
Remove δ -> Doc.fillSep ["Remove", go δ]
Replace l -> Doc.fillSep ["Replace", Doc.encloseSep Doc.lbracket Doc.rbracket Doc.comma (map (prettyDoc @l) l)]
Same -> "Same"
where
go :: PrettyPrintable l x => x -> Doc.Doc ()
go x = Doc.fillSep [Doc.lparen, prettyDoc @l x, Doc.rparen]
instance Bifunctor Diff where
bimap fa fb = \case
Same -> Same
Insert a δ -> Insert (fa a) (bimap fa fb δ)
Modify b δ -> Modify (fb b) (bimap fa fb δ)
Permute p δ -> Permute p (bimap fa fb δ)
Keep δ -> Keep (bimap fa fb δ)
Remove δ -> Remove (bimap fa fb δ)
Replace la -> Replace (map fa la)
patch ::
Member (Error String) r =>
Member Trace r =>
PrettyPrintable l a = >
PrettyPrintable l δa = >
(a -> δa -> Sem r a) ->
[a] ->
Diff a δa ->
Sem r [a]
patch patchElem = go
where
trace ( printf " Diff . List / patch(l : % s , δ : % s ) "
( display . . rbracket comma $ map prettyDoc la )
failWith :: Member (Error String) r => String -> Sem r a
failWith s = throw (printf "[Diff.List.patch] %s" s :: String)
go l = \case
Same -> return l
Insert e δ -> (e :) <$> go l δ
Modify δe δ -> case l of
h : t -> do
ph <- patchElem h δe
pt <- go t δ
return $ ph : pt
_ -> failWith "Modify, empty list"
Permute p δ ->
let ll = length l
in if ll > length p || ll < maximum p
then failWith "Permut, permutation exceeds list size"
else go (permute p l) δ
Keep δ -> case l of
h : t -> (h :) <$> go t δ
_ -> failWith "Keep, empty list"
Remove δ -> case l of
[] -> failWith "Remove, empty list"
_ : t -> go t δ
Replace r -> return r
nKeeps :: Int -> Diff τ δτ -> Diff τ δτ
nKeeps 0 = id
nKeeps n = Keep . nKeeps (n - 1)
nRemoves :: Int -> Diff τ δτ -> Diff τ δτ
nRemoves 0 = id
nRemoves n = Remove . nRemoves (n - 1)
|
f148bce7586eb40e9202d8a81f94068afaa0b8965f9ef0dc934983533ad425f3 | thheller/shadow-experiments | db_test.clj | (ns shadow.experiments.grove.db-test
(:require
[shadow.experiments.grove.db :as db]
[clojure.pprint :refer (pprint)]
[clojure.test :as t :refer (deftest is)]))
(def schema
(db/configure
{:a
{:type :entity
:attrs {:a-id [:primary-key number?]
:many [:many :b]
:single [:one :b]}}
:b
{:type :entity
:attrs {:b-id [:primary-key number?]
:c :c}}
:c
{:type :entity
:attrs {:c-id [:primary-key number?]}}}))
(def sample-data
[{:a-id 1
:a-value "a"
:many [{:b-id 1
:b-value "b"
:c {:c-id 1 :c true}}
{:b-id 2
:b-value "c"}]
:single {:b-id 1
:b-value "x"}}])
(deftest building-a-db-normalizer
(let [before
(with-meta
{:foo "bar"}
{::db/schema schema})
after
(db/merge-seq before :a sample-data [::foo])]
(pprint after)
(pprint (db/query {} after [{:a [:a-value]}]))
))
| null | https://raw.githubusercontent.com/thheller/shadow-experiments/a2170c2214778b6b9a9253166383396d64d395a4/src/test/shadow/experiments/grove/db_test.clj | clojure | (ns shadow.experiments.grove.db-test
(:require
[shadow.experiments.grove.db :as db]
[clojure.pprint :refer (pprint)]
[clojure.test :as t :refer (deftest is)]))
(def schema
(db/configure
{:a
{:type :entity
:attrs {:a-id [:primary-key number?]
:many [:many :b]
:single [:one :b]}}
:b
{:type :entity
:attrs {:b-id [:primary-key number?]
:c :c}}
:c
{:type :entity
:attrs {:c-id [:primary-key number?]}}}))
(def sample-data
[{:a-id 1
:a-value "a"
:many [{:b-id 1
:b-value "b"
:c {:c-id 1 :c true}}
{:b-id 2
:b-value "c"}]
:single {:b-id 1
:b-value "x"}}])
(deftest building-a-db-normalizer
(let [before
(with-meta
{:foo "bar"}
{::db/schema schema})
after
(db/merge-seq before :a sample-data [::foo])]
(pprint after)
(pprint (db/query {} after [{:a [:a-value]}]))
))
| |
e28206db0e371e845f1537c8efeaafb59ff11c24361ad9de677c4acef8f0a3fc | isovector/cornelis | InfoWin.hs | {-# LANGUAGE OverloadedStrings #-}
module Cornelis.InfoWin (closeInfoWindows, showInfoWindow, buildInfoBuffer) where
import Prelude hiding (Left, Right)
import Control.Monad (unless)
import Control.Monad.State.Class
import Cornelis.Pretty
import Cornelis.Types
import Cornelis.Utils (withBufferStuff, windowsForBuffer, savingCurrentWindow, visibleBuffers)
import Data.Foldable (for_)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Traversable (for)
import qualified Data.Vector as V
import Neovim
import Neovim.API.Text
import Prettyprinter (layoutPretty, LayoutOptions (LayoutOptions), PageWidth (AvailablePerLine))
import Prettyprinter.Render.Text (renderStrict)
cornelisWindowVar :: Text
cornelisWindowVar = "cornelis_window"
getBufferVariableOfWindow :: NvimObject o => Text -> Window -> Neovim env (Maybe o)
getBufferVariableOfWindow variableName window = do
window_is_valid window >>= \case
False -> pure Nothing
True -> do
buffer <- window_get_buffer window
let getVariableValue = Just . fromObjectUnsafe <$> buffer_get_var buffer variableName
getVariableValue `catchNeovimException` const (pure Nothing)
closeInfoWindowsForUnseenBuffers :: Neovim CornelisEnv ()
closeInfoWindowsForUnseenBuffers = do
seen <- S.fromList . fmap snd <$> visibleBuffers
bufs <- gets cs_buffers
let known = M.keysSet bufs
unseen = known S.\\ seen
for_ unseen $ \b -> do
for_ (M.lookup b bufs) $ \bs -> do
ws <- windowsForBuffer $ iw_buffer $ bs_info_win bs
for_ ws $ flip nvim_win_close True
closeInfoWindows :: Neovim env ()
closeInfoWindows = do
ws <- vim_get_windows
for_ ws $ \w -> getBufferVariableOfWindow cornelisWindowVar w >>= \case
Just True -> nvim_win_close w True
_ -> pure ()
closeInfoWindowForBuffer :: BufferStuff -> Neovim CornelisEnv ()
closeInfoWindowForBuffer bs = do
let InfoBuffer ib = bs_info_win bs
ws <- windowsForBuffer ib
for_ ws $ flip nvim_win_close True
showInfoWindow :: Buffer -> Doc HighlightGroup -> Neovim CornelisEnv ()
showInfoWindow b doc = withBufferStuff b $ \bs -> do
let ib = bs_info_win bs
closeInfoWindowsForUnseenBuffers
vis <- visibleBuffers
ns <- asks ce_namespace
-- Check if the info win still exists, and if so, just modify it
found <- fmap or $
for vis $ \(w, vb) -> do
case vb == iw_buffer ib of
False -> pure False
True -> do
writeInfoBuffer ns ib doc
resizeInfoWin w ib
pure True
-- Otherwise we need to rebuild it
unless found $ do
closeInfoWindowForBuffer bs
writeInfoBuffer ns ib doc
ws <- windowsForBuffer b
for_ ws $ buildInfoWindow ib
buildInfoBuffer :: Neovim env InfoBuffer
buildInfoBuffer = do
b <-
-- not listed in the buffer list, is throwaway
nvim_create_buf False True
-- Setup things in the buffer
void $ buffer_set_var b cornelisWindowVar $ ObjectBool True
nvim_buf_set_option b "modifiable" $ ObjectBool False
nvim_buf_set_option b "filetype" $ ObjectString "agdainfo"
pure $ InfoBuffer b
buildInfoWindow :: InfoBuffer -> Window -> Neovim CornelisEnv Window
buildInfoWindow (InfoBuffer split_buf) w = savingCurrentWindow $ do
nvim_set_current_win w
max_height <- asks $ T.pack . show . cc_max_height . ce_config
max_width <- asks $ T.pack . show . cc_max_width . ce_config
asks (cc_split_location . ce_config) >>= \case
Vertical -> vim_command $ max_width <> " vsplit"
Horizontal -> vim_command $ max_height <> " split"
OnLeft -> vim_command $ "topleft " <> max_width <> " vsplit"
OnRight -> vim_command $ "botright " <> max_width <> " vsplit"
OnTop -> vim_command $ "topleft " <> max_height <> " split"
OnBottom -> vim_command $ "botright " <> max_height <> " split"
split_win <- nvim_get_current_win
nvim_win_set_buf split_win split_buf
-- Setup things in the window
nvim_win_set_option split_win "relativenumber" $ ObjectBool False
nvim_win_set_option split_win "number" $ ObjectBool False
resizeInfoWin split_win (InfoBuffer split_buf)
pure split_win
resizeInfoWin :: Window -> InfoBuffer -> Neovim CornelisEnv ()
resizeInfoWin w ib = do
t <- nvim_buf_get_lines (iw_buffer ib) 0 (-1) False
max_size <- asks $ cc_max_height . ce_config
let size = min max_size $ fromIntegral $ V.length t
asks (cc_split_location . ce_config) >>= \case
Vertical -> pure ()
Horizontal -> window_set_height w size
OnLeft -> pure ()
OnRight -> pure ()
OnTop -> window_set_height w size
OnBottom -> window_set_height w size
writeInfoBuffer :: Int64 -> InfoBuffer -> Doc HighlightGroup -> Neovim env ()
writeInfoBuffer ns iw doc = do
-- TODO(sandy): Bad choice for a window, but good enough?
w <- nvim_get_current_win
width <- window_get_width w
let sds = layoutPretty (LayoutOptions (AvailablePerLine (fromIntegral width) 0.8)) doc
(hls, sds') = renderWithHlGroups sds
s = T.lines $ renderStrict sds'
let b = iw_buffer iw
nvim_buf_set_option b "modifiable" $ ObjectBool True
buffer_set_lines b 0 (-1) True $ V.fromList s
for_ (concatMap spanInfoHighlights hls) $ \(InfoHighlight (l, sc) ec hg) ->
nvim_buf_add_highlight
b ns
(T.pack $ show hg)
l sc ec
nvim_buf_set_option b "modifiable" $ ObjectBool False
| null | https://raw.githubusercontent.com/isovector/cornelis/fa235e44630f749fb82ff420e0fe7213d943ae7f/src/Cornelis/InfoWin.hs | haskell | # LANGUAGE OverloadedStrings #
Check if the info win still exists, and if so, just modify it
Otherwise we need to rebuild it
not listed in the buffer list, is throwaway
Setup things in the buffer
Setup things in the window
TODO(sandy): Bad choice for a window, but good enough? |
module Cornelis.InfoWin (closeInfoWindows, showInfoWindow, buildInfoBuffer) where
import Prelude hiding (Left, Right)
import Control.Monad (unless)
import Control.Monad.State.Class
import Cornelis.Pretty
import Cornelis.Types
import Cornelis.Utils (withBufferStuff, windowsForBuffer, savingCurrentWindow, visibleBuffers)
import Data.Foldable (for_)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Traversable (for)
import qualified Data.Vector as V
import Neovim
import Neovim.API.Text
import Prettyprinter (layoutPretty, LayoutOptions (LayoutOptions), PageWidth (AvailablePerLine))
import Prettyprinter.Render.Text (renderStrict)
cornelisWindowVar :: Text
cornelisWindowVar = "cornelis_window"
getBufferVariableOfWindow :: NvimObject o => Text -> Window -> Neovim env (Maybe o)
getBufferVariableOfWindow variableName window = do
window_is_valid window >>= \case
False -> pure Nothing
True -> do
buffer <- window_get_buffer window
let getVariableValue = Just . fromObjectUnsafe <$> buffer_get_var buffer variableName
getVariableValue `catchNeovimException` const (pure Nothing)
closeInfoWindowsForUnseenBuffers :: Neovim CornelisEnv ()
closeInfoWindowsForUnseenBuffers = do
seen <- S.fromList . fmap snd <$> visibleBuffers
bufs <- gets cs_buffers
let known = M.keysSet bufs
unseen = known S.\\ seen
for_ unseen $ \b -> do
for_ (M.lookup b bufs) $ \bs -> do
ws <- windowsForBuffer $ iw_buffer $ bs_info_win bs
for_ ws $ flip nvim_win_close True
closeInfoWindows :: Neovim env ()
closeInfoWindows = do
ws <- vim_get_windows
for_ ws $ \w -> getBufferVariableOfWindow cornelisWindowVar w >>= \case
Just True -> nvim_win_close w True
_ -> pure ()
closeInfoWindowForBuffer :: BufferStuff -> Neovim CornelisEnv ()
closeInfoWindowForBuffer bs = do
let InfoBuffer ib = bs_info_win bs
ws <- windowsForBuffer ib
for_ ws $ flip nvim_win_close True
showInfoWindow :: Buffer -> Doc HighlightGroup -> Neovim CornelisEnv ()
showInfoWindow b doc = withBufferStuff b $ \bs -> do
let ib = bs_info_win bs
closeInfoWindowsForUnseenBuffers
vis <- visibleBuffers
ns <- asks ce_namespace
found <- fmap or $
for vis $ \(w, vb) -> do
case vb == iw_buffer ib of
False -> pure False
True -> do
writeInfoBuffer ns ib doc
resizeInfoWin w ib
pure True
unless found $ do
closeInfoWindowForBuffer bs
writeInfoBuffer ns ib doc
ws <- windowsForBuffer b
for_ ws $ buildInfoWindow ib
buildInfoBuffer :: Neovim env InfoBuffer
buildInfoBuffer = do
b <-
nvim_create_buf False True
void $ buffer_set_var b cornelisWindowVar $ ObjectBool True
nvim_buf_set_option b "modifiable" $ ObjectBool False
nvim_buf_set_option b "filetype" $ ObjectString "agdainfo"
pure $ InfoBuffer b
buildInfoWindow :: InfoBuffer -> Window -> Neovim CornelisEnv Window
buildInfoWindow (InfoBuffer split_buf) w = savingCurrentWindow $ do
nvim_set_current_win w
max_height <- asks $ T.pack . show . cc_max_height . ce_config
max_width <- asks $ T.pack . show . cc_max_width . ce_config
asks (cc_split_location . ce_config) >>= \case
Vertical -> vim_command $ max_width <> " vsplit"
Horizontal -> vim_command $ max_height <> " split"
OnLeft -> vim_command $ "topleft " <> max_width <> " vsplit"
OnRight -> vim_command $ "botright " <> max_width <> " vsplit"
OnTop -> vim_command $ "topleft " <> max_height <> " split"
OnBottom -> vim_command $ "botright " <> max_height <> " split"
split_win <- nvim_get_current_win
nvim_win_set_buf split_win split_buf
nvim_win_set_option split_win "relativenumber" $ ObjectBool False
nvim_win_set_option split_win "number" $ ObjectBool False
resizeInfoWin split_win (InfoBuffer split_buf)
pure split_win
resizeInfoWin :: Window -> InfoBuffer -> Neovim CornelisEnv ()
resizeInfoWin w ib = do
t <- nvim_buf_get_lines (iw_buffer ib) 0 (-1) False
max_size <- asks $ cc_max_height . ce_config
let size = min max_size $ fromIntegral $ V.length t
asks (cc_split_location . ce_config) >>= \case
Vertical -> pure ()
Horizontal -> window_set_height w size
OnLeft -> pure ()
OnRight -> pure ()
OnTop -> window_set_height w size
OnBottom -> window_set_height w size
writeInfoBuffer :: Int64 -> InfoBuffer -> Doc HighlightGroup -> Neovim env ()
writeInfoBuffer ns iw doc = do
w <- nvim_get_current_win
width <- window_get_width w
let sds = layoutPretty (LayoutOptions (AvailablePerLine (fromIntegral width) 0.8)) doc
(hls, sds') = renderWithHlGroups sds
s = T.lines $ renderStrict sds'
let b = iw_buffer iw
nvim_buf_set_option b "modifiable" $ ObjectBool True
buffer_set_lines b 0 (-1) True $ V.fromList s
for_ (concatMap spanInfoHighlights hls) $ \(InfoHighlight (l, sc) ec hg) ->
nvim_buf_add_highlight
b ns
(T.pack $ show hg)
l sc ec
nvim_buf_set_option b "modifiable" $ ObjectBool False
|
d4169a6de64b0ae3e3c4c4e7156433faaf59a60a3a19298838e2c1fe5974cff2 | input-output-hk/plutus | Common.hs | -- editorconfig-checker-disable-file
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module DeBruijn.Common where
import Data.Semigroup
import PlutusCore.MkPlc
import UntypedPlutusCore as UPLC
timesT :: Index -> (a -> a) -> a -> a
timesT n = appEndo . stimes n . Endo
-- a big debruijn index for testing.
-- the actual number does not matter, as long as it is sufficiently large to not interfere with the rest of the test code.
ix99 :: DeBruijn
ix99 = DeBruijn 999999
-- An out-of-scope variable in these tests.
outVar :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
outVar = Var () ix99
true :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
true = mkConstant @Bool () True
-- A helper that just places index 0 to the binder (the only "reasonable" index for the binders)
lamAbs0 :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
lamAbs0 = LamAbs () (DeBruijn 0)
-- A helper that constructs a lamabs with the binder having a nonsensical index.
See NOTE : [ indices of Binders ]
lamAbs99 :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
lamAbs99 = LamAbs () ix99
constFun :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
constFun = lamAbs0 $ lamAbs0 $ Var () $ DeBruijn 2
delayforce :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
delayforce t = Delay () $ Force () t
| null | https://raw.githubusercontent.com/input-output-hk/plutus/c8d4364d0e639fef4d5b93f7d6c0912d992b54f9/plutus-core/untyped-plutus-core/test/DeBruijn/Common.hs | haskell | editorconfig-checker-disable-file
a big debruijn index for testing.
the actual number does not matter, as long as it is sufficiently large to not interfere with the rest of the test code.
An out-of-scope variable in these tests.
A helper that just places index 0 to the binder (the only "reasonable" index for the binders)
A helper that constructs a lamabs with the binder having a nonsensical index. | # LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module DeBruijn.Common where
import Data.Semigroup
import PlutusCore.MkPlc
import UntypedPlutusCore as UPLC
timesT :: Index -> (a -> a) -> a -> a
timesT n = appEndo . stimes n . Endo
ix99 :: DeBruijn
ix99 = DeBruijn 999999
outVar :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
outVar = Var () ix99
true :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
true = mkConstant @Bool () True
lamAbs0 :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
lamAbs0 = LamAbs () (DeBruijn 0)
See NOTE : [ indices of Binders ]
lamAbs99 :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
lamAbs99 = LamAbs () ix99
constFun :: UPLC.Term DeBruijn DefaultUni DefaultFun ()
constFun = lamAbs0 $ lamAbs0 $ Var () $ DeBruijn 2
delayforce :: (t ~ UPLC.Term DeBruijn DefaultUni DefaultFun ()) => t -> t
delayforce t = Delay () $ Force () t
|
ed9e06ad313c8a167bc44efc9223c6fc2fb952c1fbd0b11f75858539ca3d0af9 | silky/quipper | Clifford.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE BangPatterns #-}
-- | This module contains an implementation of a quantum simulator that
uses the stabilizer states of the group ( i.e. the group ) ,
-- to provide efficient simulation of quantum circuits constructed from
elements of the group . The module provides an implementation
of the group operators { x , y , z , h , s , controlled - x } which form a
generating set for the group .
module Libraries.Stabilizers.Clifford where
import Prelude hiding (lookup,negate)
import Libraries.Stabilizers.Pauli
import Data.List (foldl')
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad.State
import System.Random
import Quantum.Synthesis.Ring (Cplx (..), i)
-- | A qubit is defined as an integer reference.
type Qubit = Int
-- | The state of the system is a representation of a stabilizer tableau.
-- note this isn't a record, so as to help with strictness annotations
data Tableau = ST Qubit !(Map Qubit Sign) !(Map (Qubit,Qubit) Pauli) !(Map Qubit Sign) !(Map (Qubit,Qubit) Pauli)
| Accessor function for the next_qubit field of a
next_qubit :: Tableau -> Qubit
next_qubit (ST nq _ _ _ _) = nq
| Accessor function for the sign field of a
sign :: Tableau -> Map Qubit Sign
sign (ST _ s _ _ _) = s
| Accessor function for the tableau field of a
tableau :: Tableau -> Map (Qubit,Qubit) Pauli
tableau (ST _ _ t _ _) = t
| Accessor function for the de_sign field of a
de_sign :: Tableau -> Map Qubit Sign
de_sign (ST _ _ _ de_s _) = de_s
| Accessor function for the de_tableau field of a
de_tableau :: Tableau -> Map (Qubit,Qubit) Pauli
de_tableau (ST _ _ _ _ de_t) = de_t
-- | A local Map lookup function that throws an error if the key doesn't exist.
lookup :: (Ord k,Show k, Show v) => k -> Map k v -> v
lookup k m =
case Map.lookup k m of
Just b -> b
Nothing -> error ("key: " ++ show k ++ " not in map: " ++ show m)
-- | A tableau can be shown, by enumerating over the qubits in scope.
instance Show Tableau where
show tab = unlines $ ("Stabilizer:":map show_row qs) ++ ("Destabilizer:":map show_de_row qs)
where
qs :: [Qubit]
qs = [0..(next_qubit tab) - 1]
show_row :: Qubit -> String
show_row q_row = show (lookup q_row (sign tab))
++ unwords (map (show_pauli q_row) qs)
show_pauli :: Qubit -> Qubit -> String
show_pauli q_row q_column = show (lookup (q_row,q_column) (tableau tab))
show_de_row :: Qubit -> String
show_de_row q_row = show (lookup q_row (de_sign tab))
++ unwords (map (show_de_pauli q_row) qs)
show_de_pauli :: Qubit -> Qubit -> String
show_de_pauli q_row q_column = show (lookup (q_row,q_column) (de_tableau tab))
-- | An initial (empty) tableau.
empty_tableau :: Tableau
empty_tableau = ST 0 Map.empty Map.empty Map.empty Map.empty
-- | A new qubit in the state |0〉 or |1〉 can be added to a tableau.
add_qubit :: Bool -> Tableau -> Tableau
add_qubit b tab = ST (nq + 1) sign' tableau' de_sign' de_tableau'
where
nq = next_qubit tab
sign' = Map.insert nq (if b then Minus else Plus) (sign tab)
de_sign' = Map.insert nq Plus (de_sign tab)
tableau' = foldl' insertI (foldl' insertZ (tableau tab) [0..nq]) [0..nq-1]
de_tableau' = foldl' insertI (foldl' insertX (de_tableau tab) [0..nq]) [0..nq-1]
insertZ :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertZ tab cq = Map.insert (nq,cq) (if nq == cq then Z else I) tab
insertX :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertX tab cq = Map.insert (nq,cq) (if nq == cq then X else I) tab
insertI :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertI tab cq = Map.insert (cq,nq) I tab
| A ( ) unitary can be defined as a function acting on Pauli operators .
type Unitary = Pauli -> (Sign,Pauli)
instance Eq Unitary where
u1 == u2 = and [ u1 x == u2 x | x <- ixyz]
where ixyz = [I,X,Y,Z]
for a unitary U , the action on each Pauli ( P ) should be defined
as the result of UPU * . A complete set of generators for the
group is defined below , so defining a Unitary should n't be required
-- at the user-level
-- | The minimal definition of a unitary requires the actions on /X/ and /Z/.
data MinPauli = Xmin | Zmin
-- | The minimal definition of a unitary requires the actions on /X/ and /Z/.
type MinUnitary = MinPauli -> (Sign,Pauli)
-- | The definition of a 'Unitary' can be constructed from a 'MinimalUnitary'.
from_minimal :: MinUnitary -> Unitary
from_minimal f I = (Plus,I)
from_minimal f X = f Xmin
from_minimal f Z = f Zmin
from_minimal f Y = (sign,pauli)
where
(sx,px) = f Xmin
(sz,pz) = f Zmin
(spc,pauli) = commute px pz
sign = signPlus_to_sign $ multiply_signPlus (multiply_signPlus (One sx) (One sz)) (multiply_signPlus (PlusI) (spc))
| It is possible to construct a ' Unitary ' from a 2×2 - matrix .
from_matrix :: (Floating r, Eq r, Show r) => Matrix1 (Cplx r) -> Unitary
from_matrix m = from_minimal minimal
where
minimal xy = sp
where
xy' = case xy of
Xmin -> X
Zmin -> Z
m_dagger = transpose1 m
sp = fromMatrix1 $ multiplyMatrix1 m (multiplyMatrix1 (toMatrix1 xy') m_dagger)
-- | A unitary can be applied to a qubit in a given tableau. By folding through each row
apply_unitary :: Unitary -> Qubit -> Tableau -> Tableau
apply_unitary u q_column tab = foldl' (apply_unitary_row u q_column) tab [0..nq-1]
where
nq = next_qubit tab
-- | Apply the unitary to the given column, in the given row.
apply_unitary_row :: Unitary -> Qubit -> Tableau -> Qubit -> Tableau
apply_unitary_row u q_column tab q_row = ST (next_qubit tab) sign' tableau' de_sign' de_tableau'
where
s = sign tab
current_sign = lookup q_row s
t = tableau tab
current_pauli = lookup (q_row,q_column) t
(change_sign,new_pauli) = u current_pauli
new_sign = if negative change_sign then negate current_sign else current_sign
sign' = Map.insert q_row new_sign s
tableau' = Map.insert (q_row,q_column) new_pauli t
de_s = de_sign tab
de_current_sign = lookup q_row de_s
de_t = de_tableau tab
de_current_pauli = lookup (q_row,q_column) de_t
(de_change_sign,de_new_pauli) = u de_current_pauli
de_new_sign = if negative de_change_sign then negate de_current_sign else de_current_sign
de_sign' = Map.insert q_row de_new_sign de_s
de_tableau' = Map.insert (q_row,q_column) de_new_pauli de_t
| A two - qubit ( ) unitary can be defined as a function acting
on a pair of Pauli operators .
type Unitary2 = (Pauli,Pauli) -> (Sign,Pauli,Pauli)
instance Eq Unitary2 where
u1 == u2 = and [ u1 (x,y) == u2 (x,y) | x <- ixyz, y <- ixyz]
where ixyz = [I,X,Y,Z]
| The minimal definition of a two - qubit unitary requires the actions on /IX/ , /XI/ , /IZ/ , and /ZI/.
data MinPauli2 = IX | XI | IZ | ZI
| The minimal definition of a two - qubit unitary requires the actions on /IX/ , /XI/ , /IZ/ , and /ZI/.
type MinUnitary2 = MinPauli2 -> (Sign,Pauli,Pauli)
-- | The definition of a 'Unitary2' can be constructed from a 'MinimalUnitary2'.
from_minimal2 :: MinUnitary2 -> Unitary2
from_minimal2 f (I,I) = (Plus,I,I)
from_minimal2 f (I,X) = f IX
from_minimal2 f (X,I) = f XI
from_minimal2 f (I,Z) = f IZ
from_minimal2 f (Z,I) = f ZI
from_minimal2 f (I,Y) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (I,X)
(siz,piz1,piz2) = from_minimal2 f (I,Z)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (PlusI) (multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2)))
from_minimal2 f (Y,I) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (X,I)
(siz,piz1,piz2) = from_minimal2 f (Z,I)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (PlusI) (multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2)))
from_minimal2 f (pauli1,pauli2) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (pauli1,I)
(siz,piz1,piz2) = from_minimal2 f (I,pauli2)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2))
| It is possible to construct a ' Unitary2 ' from a 4×4 - matrix .
from_matrix2 :: (Floating r, Eq r, Show r) => Matrix2 (Cplx r) -> Unitary2
from_matrix2 m = from_minimal2 minimal
where
minimal xy = sp
where
xy' = case xy of
IX -> (I,X)
XI -> (X,I)
IZ -> (I,Z)
ZI -> (Z,I)
m_dagger = transpose2 m
sp = fromMatrix2 $ multiplyMatrix2 m (multiplyMatrix2 (toMatrix2 xy') m_dagger)
| It is possible to construct a ' Unitary2 ' from controlling a 2×2 - matrix .
from_matrix_controlled :: (Floating r, Show r, Eq r) => Matrix1 (Cplx r) -> Unitary2
from_matrix_controlled m1 = from_matrix2 (control1 m1)
| A two - qubit unitary can be applied to a pair of qubits in a given tableau .
apply_unitary2 :: Unitary2 -> (Qubit,Qubit) -> Tableau -> Tableau
apply_unitary2 u (q1,q2) tab = foldl' apply_unitary2' tab [0..nq-1]
where
nq = next_qubit tab
apply_unitary2' :: Tableau -> Qubit -> Tableau
apply_unitary2' tab q_row = ST (next_qubit tab) sign' tableau'' de_sign' de_tableau''
where
s = sign tab
current_sign = lookup q_row s
t = tableau tab
current_pauli1 = lookup (q_row,q1) t
current_pauli2 = lookup (q_row,q2) t
(change_sign,new_pauli1,new_pauli2) = u (current_pauli1,current_pauli2)
new_sign = if negative change_sign then negate current_sign else current_sign
sign' = Map.insert q_row new_sign s
tableau' = Map.insert (q_row,q1) new_pauli1 t
tableau'' = Map.insert (q_row,q2) new_pauli2 tableau'
de_s = de_sign tab
de_current_sign = lookup q_row de_s
de_t = de_tableau tab
de_current_pauli1 = lookup (q_row,q1) de_t
de_current_pauli2 = lookup (q_row,q2) de_t
(de_change_sign,de_new_pauli1,de_new_pauli2) = u (de_current_pauli1,de_current_pauli2)
de_new_sign = if negative de_change_sign then negate de_current_sign else de_current_sign
de_sign' = Map.insert q_row de_new_sign de_s
de_tableau' = Map.insert (q_row,q1) de_new_pauli1 de_t
de_tableau'' = Map.insert (q_row,q2) de_new_pauli2 de_tableau'
-- | A measurement, in the computational basis, can be made of a qubit
in the Tableau , returning the measurement result , and the resulting
Tableau .
measure :: Qubit -> Tableau -> IO (Bool,Tableau)
measure q tab = case anticommute_with_z of
[] -> -- all of the stabilizers commute with z, so the measurement is
-- deterministic and doesn't change the tableau,
-- but we need to calculate the result!
the stabilzer either contains Z_q or -Z_q
case (filter (\(row,_) -> row == z_row) z_rows) of
in this case , we need to see whether the generators form Z_q or -Z_q
let tab' = reduce q tab
(res,_) <- measure q tab'
return (res,tab)
[(_,row)] -> return (negative (lookup row s),tab)
_ -> error "measure: multiple Zs found" -- should never occur!
where
z_row :: [Pauli]
z_row = map (\q_col -> if q_col == q then Z else I) [0..(nq-1)]
z_rows :: [([Pauli],Qubit)]
z_rows = map (\q_row -> ((map (\q_col ->(lookup (q_row,q_col) t)) [0..(nq-1)]),q_row)) [0..(nq-1)]
exaclty one anti - commutes , measurement result is 50/50
let de_s' = Map.insert q_row (lookup q_row s) de_s
let de_t' = foldl' (\de_t q' -> Map.insert (q_row,q') (lookup (q_row,q') t) de_t) de_t [0..(nq-1)]
b <- randomIO
let eigen_value = if b then Minus else Plus
let s' = Map.insert q_row eigen_value s
let t' = foldl' (\t q' -> Map.insert (q_row,q') (if q == q' then Z else I) t) t [0..(nq-1)]
let tab' = ST nq s' t' de_s' de_t'
return (negative eigen_value,tab')
more than one anti - commutes , so we update the set of stabilizers with the product of the first two anti - commuters
measure q (multiply q_row2 q_row1 tab)
where
nq = next_qubit tab
t = tableau tab
s = sign tab
de_t = de_tableau tab
de_s = de_sign tab
gs = map (\q_row -> (lookup (q_row,q) t,q_row)) [0..(nq-1)]
anticommute_with_z = filter (\(ixyz,_) -> ixyz == X || ixyz == Y) gs
-- | This function reduces a tableau so that it contains either plus
-- or minus /Z/[sub /q/]. Note that it is only called in the case
-- where /Z/[sub /q/] is generated by the tableau (i.e., during
-- measurement).
reduce :: Qubit -> Tableau -> Tableau
reduce qubit tab = foldl' (\t q -> multiply r q t) tab ows
where
nq = next_qubit tab
t = tableau tab
de_t = de_tableau tab
(r:ows) = filter (\q_row -> isXY (lookup (q_row,qubit) de_t) ) [0..nq-1]
isXY p = p == X || p == Y
| Multiply the stabilizers for the two given rows , in the given tableau , and
update the first row with the result of the multiplication .
multiply :: Qubit -> Qubit -> Tableau -> Tableau
multiply q_row1 q_row2 tab = ST nq s' t' (de_sign tab) (de_tableau tab)
where
nq = next_qubit tab
t = tableau tab
s = sign tab
sign1 = lookup q_row1 s
sign2 = lookup q_row2 s
sp = One (multiply_sign sign1 sign2)
(t',sp') = foldl' mul_col (t,sp) [0..(nq-1)]
s' = Map.insert q_row1 (signPlus_to_sign sp') s
mul_col :: (Map (Qubit,Qubit) Pauli, SignPlus) -> Qubit -> (Map (Qubit,Qubit) Pauli, SignPlus)
mul_col (tab,sp) q_col = (Map.insert (q_row1,q_col) p' tab,multiply_signPlus sp sp')
where
p1 = lookup (q_row1,q_col) tab
p2 = lookup (q_row2,q_col) tab
(sp',p') = commute p1 p2
---------------------------------------
Generators for the group --
---------------------------------------
All Clifford group operators can be defined in terms of the
following gates . The Monadic interface can be used for this
-- purpose. For example.
| The Pauli /X/ operator is a group unitary .
x :: Unitary
x I = (Plus,I)
x X = (Plus,X)
x Y = (Minus,Y)
x Z = (Minus,Z)
-- | We can (equivalently) define Pauli-/X/ as a 'MinUnitary'.
x_min :: MinUnitary
x_min Xmin = (Plus,X)
x_min Zmin = (Minus,Z)
-- | We can (equivalently) construct Pauli-/X/ from a 'MinUnitary'.
x' :: Unitary
x' = from_minimal x_min
-- | We can (equivalently) construct Pauli-/X/ from a matrix.
x'' :: Unitary
x'' = from_matrix (0,1,1,0)
| The Pauli /Y/-operator is a group unitary .
y :: Unitary
y I = (Plus,I)
y X = (Minus,X)
y Y = (Plus,Y)
y Z = (Minus,Z)
-- | We can (equivalently) define Pauli-/Y/ as a 'MinUnitary'.
y_min :: MinUnitary
y_min Xmin = (Minus,X)
y_min Zmin = (Minus,Z)
-- | We can (equivalently) construct Pauli-/Y/ from a 'MinUnitary'.
y' :: Unitary
y' = from_minimal y_min
-- | We can (equivalently) construct Pauli-/Y/ from a matrix.
y'' :: Unitary
y'' = from_matrix (0,-i,i,0)
| The Pauli /Z/-operator is a group unitary .
z :: Unitary
z I = (Plus,I)
z X = (Minus,X)
z Y = (Minus,Y)
z Z = (Plus,Z)
-- | We can (equivalently) define Pauli-/Z/ as a 'MinUnitary'.
z_min :: MinUnitary
z_min Xmin = (Minus,X)
z_min Zmin = (Plus,Z)
-- | We can (equivalently) construct Pauli-/Z/ from a 'MinUnitary'.
z' :: Unitary
z' = from_minimal z_min
-- | We can (equivalently) construct Pauli-/Z/ from a matrix.
z'' :: Unitary
z'' = from_matrix (1,0,0,-1)
| The Hadamard - gate is a group unitary .
h :: Unitary
h I = (Plus,I)
h X = (Plus,Z)
h Y = (Minus,Y)
h Z = (Plus,X)
| We can ( equivalently ) define Hadamard as a ' MinUnitary ' .
h_min :: MinUnitary
h_min Xmin = (Plus,Z)
h_min Zmin = (Plus,X)
| We can ( equivalently ) construct Hadamard from a ' MinUnitary ' .
h' :: Unitary
h' = from_minimal h_min
| We can ( equivalently ) construct Hadamard from a matrix .
-- Although rounding errors break this!!!
h'' :: Unitary
h'' = from_matrix $ scale1 (Cplx (1/sqrt 2) 0) (1,1,1,-1)
| The phase - gate is a group unitary .
s :: Unitary
s I = (Plus,I)
s X = (Plus,Y)
s Y = (Minus,X)
s Z = (Plus,Z)
-- | We can (equivalently) define phase gate as a 'MinUnitary'.
s_min :: MinUnitary
s_min Xmin = (Plus,Y)
s_min Zmin = (Plus,Z)
-- | We can (equivalently) construct phase gate from a 'MinUnitary'.
s' :: Unitary
s' = from_minimal s_min
-- | We can (equivalently) construct phase gate from a matrix.
s'' :: Unitary
s'' = from_matrix (1,0,0,i)
| The phase - gate is a group unitary .
e :: Unitary
e I = (Plus,I)
e X = (Plus,Y)
e Y = (Plus,Z)
e Z = (Plus,X)
-- | We can (equivalently) define phase gate as a 'MinUnitary'.
e_min :: MinUnitary
e_min Xmin = (Plus,Y)
e_min Zmin = (Plus,X)
-- | We can (equivalently) construct phase gate from a 'MinUnitary'.
e' :: Unitary
e' = from_minimal e_min
-- | We can (equivalently) construct phase gate from a matrix.
e'' :: Unitary
e'' = from_matrix ((-1+i)/2, (1+i)/2, (-1+i)/2, (-1-i)/2)
| The controlled - not is a Clifford group 2 - qubit unitary .
cnot :: Unitary2
cnot (I,I) = (Plus,I,I)
cnot (I,X) = (Plus,I,X)
cnot (I,Y) = (Plus,Z,Y)
cnot (I,Z) = (Plus,Z,Z)
cnot (X,I) = (Plus,X,X)
cnot (X,X) = (Plus,X,I)
cnot (X,Y) = (Plus,Y,Z)
cnot (X,Z) = (Minus,Y,Y)
cnot (Y,I) = (Plus,Y,X)
cnot (Y,X) = (Plus,Y,I)
cnot (Y,Y) = (Minus,X,Z)
cnot (Y,Z) = (Plus,X,Y)
cnot (Z,I) = (Plus,Z,I)
cnot (Z,X) = (Plus,Z,X)
cnot (Z,Y) = (Plus,I,Y)
cnot (Z,Z) = (Plus,I,Z)
| We can ( equivalently ) define CNot as a ' MinUnitary2 ' .
cnot_min :: MinUnitary2
cnot_min IX = (Plus,I,X)
cnot_min XI = (Plus,X,X)
cnot_min IZ = (Plus,Z,Z)
cnot_min ZI = (Plus,Z,I)
| We can ( equivalently ) construct CNot from a ' MinUnitary2 ' .
cnot' :: Unitary2
cnot' = from_minimal2 cnot_min
| We can ( equivalently ) construct CNot from a matrix .
cnot'' :: Unitary2
cnot'' = from_matrix2 ((1,0,0,1),(0,0,0,0),(0,0,0,0),(0,1,1,0))
| The controlled-/Z/ is a Clifford group 2 - qubit unitary .
cz :: Unitary2
cz (I,I) = (Plus,I,I)
cz (I,X) = (Plus,Z,X)
cz (I,Y) = (Plus,Z,Y)
cz (I,Z) = (Plus,I,Z)
cz (X,I) = (Plus,X,Z)
cz (X,X) = (Plus,Y,Y)
cz (X,Y) = (Minus,Y,X)
cz (X,Z) = (Plus,X,I)
cz (Y,I) = (Plus,Y,Z)
cz (Y,X) = (Minus,X,Y)
cz (Y,Y) = (Plus,X,X)
cz (Y,Z) = (Plus,Y,I)
cz (Z,I) = (Plus,Z,I)
cz (Z,X) = (Plus,I,X)
cz (Z,Y) = (Plus,I,Y)
cz (Z,Z) = (Plus,Z,Z)
-- | We can (equivalently) define controlled-/Z/ as a 'MinUnitary2'.
cz_min :: MinUnitary2
cz_min IX = (Plus,Z,X)
cz_min XI = (Plus,X,Z)
cz_min IZ = (Plus,I,Z)
cz_min ZI = (Plus,Z,I)
-- | We can (equivalently) construct controlled-/Z/ from a 'MinUnitary2'.
cz' :: Unitary2
cz' = from_minimal2 cz_min
-- | We can (equivalently) construct controlled-/Z/ from a matrix.
cz'' :: Unitary2
cz'' = from_matrix2 ((1,0,0,1),(0,0,0,0),(0,0,0,0),(1,0,0,-1))
------------------------------------------------------------------
A Monadic Interface for constructing Clifford group circuits --
------------------------------------------------------------------
Larger group circuits can be defined in terms of the
-- following operations. It is envisaged that a Quipper Transformer
-- can be defined to translate appropriate Quipper circuits (i.e.
circuits that only use Clifford group operators ) into a
CliffordCirc so that it can be simulated ( efficiently ) .
| A group circuit is implicitly simulated using
a state monad over a ' ' .
type CliffordCirc a = StateT Tableau IO a
-- | Initialize a new qubit.
init_qubit :: Bool -> CliffordCirc Qubit
init_qubit b = do
tab <- get
let nq = next_qubit tab
put (add_qubit b tab)
return nq
-- | Initialize multiple qubits.
init_qubits :: [Bool] -> CliffordCirc [Qubit]
init_qubits = mapM init_qubit
-- | Apply a Pauli-/X/ gate to the given qubit.
gate_X :: Qubit -> CliffordCirc ()
gate_X q = do
tab <- get
put (apply_unitary x q tab)
-- | Apply a Pauli-/Y/ gate to the given qubit.
gate_Y :: Qubit -> CliffordCirc ()
gate_Y q = do
tab <- get
put (apply_unitary y q tab)
-- | Apply a Pauli-/Z/ gate to the given qubit.
gate_Z :: Qubit -> CliffordCirc ()
gate_Z q = do
tab <- get
put (apply_unitary z q tab)
| Apply a Hadamard gate to the given qubit .
gate_H :: Qubit -> CliffordCirc ()
gate_H q = do
tab <- get
put (apply_unitary h q tab)
-- | Apply a phase gate to the given qubit.
gate_S :: Qubit -> CliffordCirc ()
gate_S q = do
tab <- get
put (apply_unitary s q tab)
-- | Apply a given 'Unitary' to the given qubit.
gate_Unitary :: Unitary -> Qubit -> CliffordCirc ()
gate_Unitary u q = do
tab <- get
put (apply_unitary u q tab)
-- | Apply a controlled-/X/ gate to the given qubits.
controlled_X :: Qubit -> Qubit -> CliffordCirc ()
controlled_X q1 q2 = do
tab <- get
put (apply_unitary2 cnot (q1,q2) tab)
-- | Apply a controlled-/Z/ gate to the given qubits.
controlled_Z :: Qubit -> Qubit -> CliffordCirc ()
controlled_Z q1 q2 = do
tab <- get
put (apply_unitary2 cz (q1,q2) tab)
-- | Apply a given 'Unitary2' to the given qubits
gate_Unitary2 :: Unitary2 -> Qubit -> Qubit -> CliffordCirc ()
gate_Unitary2 u q1 q2 = do
tab <- get
put (apply_unitary2 u (q1,q2) tab)
-- | Measure the given qubit in the computational basis.
measure_qubit :: Qubit -> CliffordCirc Bool
measure_qubit q = do
tab <- get
(res,tab') <- lift $ measure q tab
put tab'
return res
-- | Measure the given list of qubits.
measure_qubits :: [Qubit] -> CliffordCirc [Bool]
measure_qubits = mapM measure_qubit
-- | For testing purposes, we can show the tableau during a simulation.
show_tableau :: CliffordCirc ()
show_tableau = do
tab <- get
lift $ putStrLn (show tab)
----------------------------------------------------
-- Evaluation and Simulation of Clifford circuits --
----------------------------------------------------
| Return the evaluated ' ' for the given circuit .
eval :: CliffordCirc a -> IO Tableau
eval cc = execStateT cc empty_tableau
-- | Return the result of simulating the given circuit.
sim :: CliffordCirc a -> IO a
sim cc = evalStateT cc empty_tableau
---------------------------------
Some test circuits --
---------------------------------
| A swap gate can be defined in terms of three controlled - not gates .
swap :: Qubit -> Qubit -> CliffordCirc ()
swap q1 q2 = do
controlled_X q1 q2
controlled_X q2 q1
controlled_X q1 q2
-- | A controlled-/Z/ gate can (equivalently) be defined in terms of
Hadamard and controlled-/X/.
controlled_Z' :: Qubit -> Qubit -> CliffordCirc ()
controlled_Z' q1 q2 = do
gate_H q2
controlled_X q1 q2
gate_H q2
| Each of the four Bell states can be generated , indexed by a pair
-- of boolean values.
bell :: (Bool,Bool) -> CliffordCirc (Qubit,Qubit)
bell (bx,by) = do
x <- init_qubit bx
y <- init_qubit by
gate_H x
controlled_X x y
return (x,y)
| Create a Bell state , and measure it .
measure_bell00 :: CliffordCirc (Bool,Bool)
measure_bell00 = do
(bx,by) <- bell (False,False)
mx <- measure_qubit bx
my <- measure_qubit by
return (mx,my)
-- | A single-qubit operation can be controlled by a classical boolean value.
controlled_if :: Bool -> (Qubit -> CliffordCirc ()) -> Qubit -> CliffordCirc ()
controlled_if b u q = if b then u q else return ()
-- | A simple, single qubit, teleportation circuit.
teleport :: Qubit -> CliffordCirc Qubit
teleport q1 = do
(q2,q3) <- bell (False,False)
controlled_X q1 q2
gate_H q1
[b1,b2] <- measure_qubits [q1,q2]
controlled_if b2 gate_X q3
controlled_if b1 gate_Z q3
return q3
-- | A wrapper around the teleportation circuit that initializes a qubit
-- in the given boolean state, and measures the teleported qubit.
test_teleport :: Bool -> CliffordCirc Bool
test_teleport b = do
q <- init_qubit b
q' <- teleport q
measure_qubit q'
-- | Measure an equal superposition.
random_bool :: CliffordCirc Bool
random_bool = do
q <- init_qubit False
gate_H q
measure_qubit q
| null | https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/Libraries/Stabilizers/Clifford.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
======================================================================
# LANGUAGE TypeSynonymInstances #
# LANGUAGE BangPatterns #
| This module contains an implementation of a quantum simulator that
to provide efficient simulation of quantum circuits constructed from
| A qubit is defined as an integer reference.
| The state of the system is a representation of a stabilizer tableau.
note this isn't a record, so as to help with strictness annotations
| A local Map lookup function that throws an error if the key doesn't exist.
| A tableau can be shown, by enumerating over the qubits in scope.
| An initial (empty) tableau.
| A new qubit in the state |0〉 or |1〉 can be added to a tableau.
at the user-level
| The minimal definition of a unitary requires the actions on /X/ and /Z/.
| The minimal definition of a unitary requires the actions on /X/ and /Z/.
| The definition of a 'Unitary' can be constructed from a 'MinimalUnitary'.
| A unitary can be applied to a qubit in a given tableau. By folding through each row
| Apply the unitary to the given column, in the given row.
| The definition of a 'Unitary2' can be constructed from a 'MinimalUnitary2'.
| A measurement, in the computational basis, can be made of a qubit
all of the stabilizers commute with z, so the measurement is
deterministic and doesn't change the tableau,
but we need to calculate the result!
should never occur!
| This function reduces a tableau so that it contains either plus
or minus /Z/[sub /q/]. Note that it is only called in the case
where /Z/[sub /q/] is generated by the tableau (i.e., during
measurement).
-------------------------------------
-------------------------------------
purpose. For example.
| We can (equivalently) define Pauli-/X/ as a 'MinUnitary'.
| We can (equivalently) construct Pauli-/X/ from a 'MinUnitary'.
| We can (equivalently) construct Pauli-/X/ from a matrix.
| We can (equivalently) define Pauli-/Y/ as a 'MinUnitary'.
| We can (equivalently) construct Pauli-/Y/ from a 'MinUnitary'.
| We can (equivalently) construct Pauli-/Y/ from a matrix.
| We can (equivalently) define Pauli-/Z/ as a 'MinUnitary'.
| We can (equivalently) construct Pauli-/Z/ from a 'MinUnitary'.
| We can (equivalently) construct Pauli-/Z/ from a matrix.
Although rounding errors break this!!!
| We can (equivalently) define phase gate as a 'MinUnitary'.
| We can (equivalently) construct phase gate from a 'MinUnitary'.
| We can (equivalently) construct phase gate from a matrix.
| We can (equivalently) define phase gate as a 'MinUnitary'.
| We can (equivalently) construct phase gate from a 'MinUnitary'.
| We can (equivalently) construct phase gate from a matrix.
| We can (equivalently) define controlled-/Z/ as a 'MinUnitary2'.
| We can (equivalently) construct controlled-/Z/ from a 'MinUnitary2'.
| We can (equivalently) construct controlled-/Z/ from a matrix.
----------------------------------------------------------------
----------------------------------------------------------------
following operations. It is envisaged that a Quipper Transformer
can be defined to translate appropriate Quipper circuits (i.e.
| Initialize a new qubit.
| Initialize multiple qubits.
| Apply a Pauli-/X/ gate to the given qubit.
| Apply a Pauli-/Y/ gate to the given qubit.
| Apply a Pauli-/Z/ gate to the given qubit.
| Apply a phase gate to the given qubit.
| Apply a given 'Unitary' to the given qubit.
| Apply a controlled-/X/ gate to the given qubits.
| Apply a controlled-/Z/ gate to the given qubits.
| Apply a given 'Unitary2' to the given qubits
| Measure the given qubit in the computational basis.
| Measure the given list of qubits.
| For testing purposes, we can show the tableau during a simulation.
--------------------------------------------------
Evaluation and Simulation of Clifford circuits --
--------------------------------------------------
| Return the result of simulating the given circuit.
-------------------------------
-------------------------------
| A controlled-/Z/ gate can (equivalently) be defined in terms of
of boolean values.
| A single-qubit operation can be controlled by a classical boolean value.
| A simple, single qubit, teleportation circuit.
| A wrapper around the teleportation circuit that initializes a qubit
in the given boolean state, and measures the teleported qubit.
| Measure an equal superposition. | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
# LANGUAGE FlexibleInstances #
uses the stabilizer states of the group ( i.e. the group ) ,
elements of the group . The module provides an implementation
of the group operators { x , y , z , h , s , controlled - x } which form a
generating set for the group .
module Libraries.Stabilizers.Clifford where
import Prelude hiding (lookup,negate)
import Libraries.Stabilizers.Pauli
import Data.List (foldl')
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad.State
import System.Random
import Quantum.Synthesis.Ring (Cplx (..), i)
type Qubit = Int
data Tableau = ST Qubit !(Map Qubit Sign) !(Map (Qubit,Qubit) Pauli) !(Map Qubit Sign) !(Map (Qubit,Qubit) Pauli)
| Accessor function for the next_qubit field of a
next_qubit :: Tableau -> Qubit
next_qubit (ST nq _ _ _ _) = nq
| Accessor function for the sign field of a
sign :: Tableau -> Map Qubit Sign
sign (ST _ s _ _ _) = s
| Accessor function for the tableau field of a
tableau :: Tableau -> Map (Qubit,Qubit) Pauli
tableau (ST _ _ t _ _) = t
| Accessor function for the de_sign field of a
de_sign :: Tableau -> Map Qubit Sign
de_sign (ST _ _ _ de_s _) = de_s
| Accessor function for the de_tableau field of a
de_tableau :: Tableau -> Map (Qubit,Qubit) Pauli
de_tableau (ST _ _ _ _ de_t) = de_t
lookup :: (Ord k,Show k, Show v) => k -> Map k v -> v
lookup k m =
case Map.lookup k m of
Just b -> b
Nothing -> error ("key: " ++ show k ++ " not in map: " ++ show m)
instance Show Tableau where
show tab = unlines $ ("Stabilizer:":map show_row qs) ++ ("Destabilizer:":map show_de_row qs)
where
qs :: [Qubit]
qs = [0..(next_qubit tab) - 1]
show_row :: Qubit -> String
show_row q_row = show (lookup q_row (sign tab))
++ unwords (map (show_pauli q_row) qs)
show_pauli :: Qubit -> Qubit -> String
show_pauli q_row q_column = show (lookup (q_row,q_column) (tableau tab))
show_de_row :: Qubit -> String
show_de_row q_row = show (lookup q_row (de_sign tab))
++ unwords (map (show_de_pauli q_row) qs)
show_de_pauli :: Qubit -> Qubit -> String
show_de_pauli q_row q_column = show (lookup (q_row,q_column) (de_tableau tab))
empty_tableau :: Tableau
empty_tableau = ST 0 Map.empty Map.empty Map.empty Map.empty
add_qubit :: Bool -> Tableau -> Tableau
add_qubit b tab = ST (nq + 1) sign' tableau' de_sign' de_tableau'
where
nq = next_qubit tab
sign' = Map.insert nq (if b then Minus else Plus) (sign tab)
de_sign' = Map.insert nq Plus (de_sign tab)
tableau' = foldl' insertI (foldl' insertZ (tableau tab) [0..nq]) [0..nq-1]
de_tableau' = foldl' insertI (foldl' insertX (de_tableau tab) [0..nq]) [0..nq-1]
insertZ :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertZ tab cq = Map.insert (nq,cq) (if nq == cq then Z else I) tab
insertX :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertX tab cq = Map.insert (nq,cq) (if nq == cq then X else I) tab
insertI :: Map (Qubit,Qubit) Pauli -> Qubit -> Map (Qubit,Qubit) Pauli
insertI tab cq = Map.insert (cq,nq) I tab
| A ( ) unitary can be defined as a function acting on Pauli operators .
type Unitary = Pauli -> (Sign,Pauli)
instance Eq Unitary where
u1 == u2 = and [ u1 x == u2 x | x <- ixyz]
where ixyz = [I,X,Y,Z]
for a unitary U , the action on each Pauli ( P ) should be defined
as the result of UPU * . A complete set of generators for the
group is defined below , so defining a Unitary should n't be required
data MinPauli = Xmin | Zmin
type MinUnitary = MinPauli -> (Sign,Pauli)
from_minimal :: MinUnitary -> Unitary
from_minimal f I = (Plus,I)
from_minimal f X = f Xmin
from_minimal f Z = f Zmin
from_minimal f Y = (sign,pauli)
where
(sx,px) = f Xmin
(sz,pz) = f Zmin
(spc,pauli) = commute px pz
sign = signPlus_to_sign $ multiply_signPlus (multiply_signPlus (One sx) (One sz)) (multiply_signPlus (PlusI) (spc))
| It is possible to construct a ' Unitary ' from a 2×2 - matrix .
from_matrix :: (Floating r, Eq r, Show r) => Matrix1 (Cplx r) -> Unitary
from_matrix m = from_minimal minimal
where
minimal xy = sp
where
xy' = case xy of
Xmin -> X
Zmin -> Z
m_dagger = transpose1 m
sp = fromMatrix1 $ multiplyMatrix1 m (multiplyMatrix1 (toMatrix1 xy') m_dagger)
apply_unitary :: Unitary -> Qubit -> Tableau -> Tableau
apply_unitary u q_column tab = foldl' (apply_unitary_row u q_column) tab [0..nq-1]
where
nq = next_qubit tab
apply_unitary_row :: Unitary -> Qubit -> Tableau -> Qubit -> Tableau
apply_unitary_row u q_column tab q_row = ST (next_qubit tab) sign' tableau' de_sign' de_tableau'
where
s = sign tab
current_sign = lookup q_row s
t = tableau tab
current_pauli = lookup (q_row,q_column) t
(change_sign,new_pauli) = u current_pauli
new_sign = if negative change_sign then negate current_sign else current_sign
sign' = Map.insert q_row new_sign s
tableau' = Map.insert (q_row,q_column) new_pauli t
de_s = de_sign tab
de_current_sign = lookup q_row de_s
de_t = de_tableau tab
de_current_pauli = lookup (q_row,q_column) de_t
(de_change_sign,de_new_pauli) = u de_current_pauli
de_new_sign = if negative de_change_sign then negate de_current_sign else de_current_sign
de_sign' = Map.insert q_row de_new_sign de_s
de_tableau' = Map.insert (q_row,q_column) de_new_pauli de_t
| A two - qubit ( ) unitary can be defined as a function acting
on a pair of Pauli operators .
type Unitary2 = (Pauli,Pauli) -> (Sign,Pauli,Pauli)
instance Eq Unitary2 where
u1 == u2 = and [ u1 (x,y) == u2 (x,y) | x <- ixyz, y <- ixyz]
where ixyz = [I,X,Y,Z]
| The minimal definition of a two - qubit unitary requires the actions on /IX/ , /XI/ , /IZ/ , and /ZI/.
data MinPauli2 = IX | XI | IZ | ZI
| The minimal definition of a two - qubit unitary requires the actions on /IX/ , /XI/ , /IZ/ , and /ZI/.
type MinUnitary2 = MinPauli2 -> (Sign,Pauli,Pauli)
from_minimal2 :: MinUnitary2 -> Unitary2
from_minimal2 f (I,I) = (Plus,I,I)
from_minimal2 f (I,X) = f IX
from_minimal2 f (X,I) = f XI
from_minimal2 f (I,Z) = f IZ
from_minimal2 f (Z,I) = f ZI
from_minimal2 f (I,Y) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (I,X)
(siz,piz1,piz2) = from_minimal2 f (I,Z)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (PlusI) (multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2)))
from_minimal2 f (Y,I) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (X,I)
(siz,piz1,piz2) = from_minimal2 f (Z,I)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (PlusI) (multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2)))
from_minimal2 f (pauli1,pauli2) = (sign,p1,p2)
where
(six,pix1,pix2) = from_minimal2 f (pauli1,I)
(siz,piz1,piz2) = from_minimal2 f (I,pauli2)
(spc1,p1) = commute pix1 piz1
(spc2,p2) = commute pix2 piz2
sign = signPlus_to_sign $ multiply_signPlus (multiply_signPlus (One six) (One siz)) (multiply_signPlus (spc1) (spc2))
| It is possible to construct a ' Unitary2 ' from a 4×4 - matrix .
from_matrix2 :: (Floating r, Eq r, Show r) => Matrix2 (Cplx r) -> Unitary2
from_matrix2 m = from_minimal2 minimal
where
minimal xy = sp
where
xy' = case xy of
IX -> (I,X)
XI -> (X,I)
IZ -> (I,Z)
ZI -> (Z,I)
m_dagger = transpose2 m
sp = fromMatrix2 $ multiplyMatrix2 m (multiplyMatrix2 (toMatrix2 xy') m_dagger)
| It is possible to construct a ' Unitary2 ' from controlling a 2×2 - matrix .
from_matrix_controlled :: (Floating r, Show r, Eq r) => Matrix1 (Cplx r) -> Unitary2
from_matrix_controlled m1 = from_matrix2 (control1 m1)
| A two - qubit unitary can be applied to a pair of qubits in a given tableau .
apply_unitary2 :: Unitary2 -> (Qubit,Qubit) -> Tableau -> Tableau
apply_unitary2 u (q1,q2) tab = foldl' apply_unitary2' tab [0..nq-1]
where
nq = next_qubit tab
apply_unitary2' :: Tableau -> Qubit -> Tableau
apply_unitary2' tab q_row = ST (next_qubit tab) sign' tableau'' de_sign' de_tableau''
where
s = sign tab
current_sign = lookup q_row s
t = tableau tab
current_pauli1 = lookup (q_row,q1) t
current_pauli2 = lookup (q_row,q2) t
(change_sign,new_pauli1,new_pauli2) = u (current_pauli1,current_pauli2)
new_sign = if negative change_sign then negate current_sign else current_sign
sign' = Map.insert q_row new_sign s
tableau' = Map.insert (q_row,q1) new_pauli1 t
tableau'' = Map.insert (q_row,q2) new_pauli2 tableau'
de_s = de_sign tab
de_current_sign = lookup q_row de_s
de_t = de_tableau tab
de_current_pauli1 = lookup (q_row,q1) de_t
de_current_pauli2 = lookup (q_row,q2) de_t
(de_change_sign,de_new_pauli1,de_new_pauli2) = u (de_current_pauli1,de_current_pauli2)
de_new_sign = if negative de_change_sign then negate de_current_sign else de_current_sign
de_sign' = Map.insert q_row de_new_sign de_s
de_tableau' = Map.insert (q_row,q1) de_new_pauli1 de_t
de_tableau'' = Map.insert (q_row,q2) de_new_pauli2 de_tableau'
in the Tableau , returning the measurement result , and the resulting
Tableau .
measure :: Qubit -> Tableau -> IO (Bool,Tableau)
measure q tab = case anticommute_with_z of
the stabilzer either contains Z_q or -Z_q
case (filter (\(row,_) -> row == z_row) z_rows) of
in this case , we need to see whether the generators form Z_q or -Z_q
let tab' = reduce q tab
(res,_) <- measure q tab'
return (res,tab)
[(_,row)] -> return (negative (lookup row s),tab)
where
z_row :: [Pauli]
z_row = map (\q_col -> if q_col == q then Z else I) [0..(nq-1)]
z_rows :: [([Pauli],Qubit)]
z_rows = map (\q_row -> ((map (\q_col ->(lookup (q_row,q_col) t)) [0..(nq-1)]),q_row)) [0..(nq-1)]
exaclty one anti - commutes , measurement result is 50/50
let de_s' = Map.insert q_row (lookup q_row s) de_s
let de_t' = foldl' (\de_t q' -> Map.insert (q_row,q') (lookup (q_row,q') t) de_t) de_t [0..(nq-1)]
b <- randomIO
let eigen_value = if b then Minus else Plus
let s' = Map.insert q_row eigen_value s
let t' = foldl' (\t q' -> Map.insert (q_row,q') (if q == q' then Z else I) t) t [0..(nq-1)]
let tab' = ST nq s' t' de_s' de_t'
return (negative eigen_value,tab')
more than one anti - commutes , so we update the set of stabilizers with the product of the first two anti - commuters
measure q (multiply q_row2 q_row1 tab)
where
nq = next_qubit tab
t = tableau tab
s = sign tab
de_t = de_tableau tab
de_s = de_sign tab
gs = map (\q_row -> (lookup (q_row,q) t,q_row)) [0..(nq-1)]
anticommute_with_z = filter (\(ixyz,_) -> ixyz == X || ixyz == Y) gs
reduce :: Qubit -> Tableau -> Tableau
reduce qubit tab = foldl' (\t q -> multiply r q t) tab ows
where
nq = next_qubit tab
t = tableau tab
de_t = de_tableau tab
(r:ows) = filter (\q_row -> isXY (lookup (q_row,qubit) de_t) ) [0..nq-1]
isXY p = p == X || p == Y
| Multiply the stabilizers for the two given rows , in the given tableau , and
update the first row with the result of the multiplication .
multiply :: Qubit -> Qubit -> Tableau -> Tableau
multiply q_row1 q_row2 tab = ST nq s' t' (de_sign tab) (de_tableau tab)
where
nq = next_qubit tab
t = tableau tab
s = sign tab
sign1 = lookup q_row1 s
sign2 = lookup q_row2 s
sp = One (multiply_sign sign1 sign2)
(t',sp') = foldl' mul_col (t,sp) [0..(nq-1)]
s' = Map.insert q_row1 (signPlus_to_sign sp') s
mul_col :: (Map (Qubit,Qubit) Pauli, SignPlus) -> Qubit -> (Map (Qubit,Qubit) Pauli, SignPlus)
mul_col (tab,sp) q_col = (Map.insert (q_row1,q_col) p' tab,multiply_signPlus sp sp')
where
p1 = lookup (q_row1,q_col) tab
p2 = lookup (q_row2,q_col) tab
(sp',p') = commute p1 p2
All Clifford group operators can be defined in terms of the
following gates . The Monadic interface can be used for this
| The Pauli /X/ operator is a group unitary .
x :: Unitary
x I = (Plus,I)
x X = (Plus,X)
x Y = (Minus,Y)
x Z = (Minus,Z)
x_min :: MinUnitary
x_min Xmin = (Plus,X)
x_min Zmin = (Minus,Z)
x' :: Unitary
x' = from_minimal x_min
x'' :: Unitary
x'' = from_matrix (0,1,1,0)
| The Pauli /Y/-operator is a group unitary .
y :: Unitary
y I = (Plus,I)
y X = (Minus,X)
y Y = (Plus,Y)
y Z = (Minus,Z)
y_min :: MinUnitary
y_min Xmin = (Minus,X)
y_min Zmin = (Minus,Z)
y' :: Unitary
y' = from_minimal y_min
y'' :: Unitary
y'' = from_matrix (0,-i,i,0)
| The Pauli /Z/-operator is a group unitary .
z :: Unitary
z I = (Plus,I)
z X = (Minus,X)
z Y = (Minus,Y)
z Z = (Plus,Z)
z_min :: MinUnitary
z_min Xmin = (Minus,X)
z_min Zmin = (Plus,Z)
z' :: Unitary
z' = from_minimal z_min
z'' :: Unitary
z'' = from_matrix (1,0,0,-1)
| The Hadamard - gate is a group unitary .
h :: Unitary
h I = (Plus,I)
h X = (Plus,Z)
h Y = (Minus,Y)
h Z = (Plus,X)
| We can ( equivalently ) define Hadamard as a ' MinUnitary ' .
h_min :: MinUnitary
h_min Xmin = (Plus,Z)
h_min Zmin = (Plus,X)
| We can ( equivalently ) construct Hadamard from a ' MinUnitary ' .
h' :: Unitary
h' = from_minimal h_min
| We can ( equivalently ) construct Hadamard from a matrix .
h'' :: Unitary
h'' = from_matrix $ scale1 (Cplx (1/sqrt 2) 0) (1,1,1,-1)
| The phase - gate is a group unitary .
s :: Unitary
s I = (Plus,I)
s X = (Plus,Y)
s Y = (Minus,X)
s Z = (Plus,Z)
s_min :: MinUnitary
s_min Xmin = (Plus,Y)
s_min Zmin = (Plus,Z)
s' :: Unitary
s' = from_minimal s_min
s'' :: Unitary
s'' = from_matrix (1,0,0,i)
| The phase - gate is a group unitary .
e :: Unitary
e I = (Plus,I)
e X = (Plus,Y)
e Y = (Plus,Z)
e Z = (Plus,X)
e_min :: MinUnitary
e_min Xmin = (Plus,Y)
e_min Zmin = (Plus,X)
e' :: Unitary
e' = from_minimal e_min
e'' :: Unitary
e'' = from_matrix ((-1+i)/2, (1+i)/2, (-1+i)/2, (-1-i)/2)
| The controlled - not is a Clifford group 2 - qubit unitary .
cnot :: Unitary2
cnot (I,I) = (Plus,I,I)
cnot (I,X) = (Plus,I,X)
cnot (I,Y) = (Plus,Z,Y)
cnot (I,Z) = (Plus,Z,Z)
cnot (X,I) = (Plus,X,X)
cnot (X,X) = (Plus,X,I)
cnot (X,Y) = (Plus,Y,Z)
cnot (X,Z) = (Minus,Y,Y)
cnot (Y,I) = (Plus,Y,X)
cnot (Y,X) = (Plus,Y,I)
cnot (Y,Y) = (Minus,X,Z)
cnot (Y,Z) = (Plus,X,Y)
cnot (Z,I) = (Plus,Z,I)
cnot (Z,X) = (Plus,Z,X)
cnot (Z,Y) = (Plus,I,Y)
cnot (Z,Z) = (Plus,I,Z)
| We can ( equivalently ) define CNot as a ' MinUnitary2 ' .
cnot_min :: MinUnitary2
cnot_min IX = (Plus,I,X)
cnot_min XI = (Plus,X,X)
cnot_min IZ = (Plus,Z,Z)
cnot_min ZI = (Plus,Z,I)
| We can ( equivalently ) construct CNot from a ' MinUnitary2 ' .
cnot' :: Unitary2
cnot' = from_minimal2 cnot_min
| We can ( equivalently ) construct CNot from a matrix .
cnot'' :: Unitary2
cnot'' = from_matrix2 ((1,0,0,1),(0,0,0,0),(0,0,0,0),(0,1,1,0))
| The controlled-/Z/ is a Clifford group 2 - qubit unitary .
cz :: Unitary2
cz (I,I) = (Plus,I,I)
cz (I,X) = (Plus,Z,X)
cz (I,Y) = (Plus,Z,Y)
cz (I,Z) = (Plus,I,Z)
cz (X,I) = (Plus,X,Z)
cz (X,X) = (Plus,Y,Y)
cz (X,Y) = (Minus,Y,X)
cz (X,Z) = (Plus,X,I)
cz (Y,I) = (Plus,Y,Z)
cz (Y,X) = (Minus,X,Y)
cz (Y,Y) = (Plus,X,X)
cz (Y,Z) = (Plus,Y,I)
cz (Z,I) = (Plus,Z,I)
cz (Z,X) = (Plus,I,X)
cz (Z,Y) = (Plus,I,Y)
cz (Z,Z) = (Plus,Z,Z)
cz_min :: MinUnitary2
cz_min IX = (Plus,Z,X)
cz_min XI = (Plus,X,Z)
cz_min IZ = (Plus,I,Z)
cz_min ZI = (Plus,Z,I)
cz' :: Unitary2
cz' = from_minimal2 cz_min
cz'' :: Unitary2
cz'' = from_matrix2 ((1,0,0,1),(0,0,0,0),(0,0,0,0),(1,0,0,-1))
Larger group circuits can be defined in terms of the
circuits that only use Clifford group operators ) into a
CliffordCirc so that it can be simulated ( efficiently ) .
| A group circuit is implicitly simulated using
a state monad over a ' ' .
type CliffordCirc a = StateT Tableau IO a
init_qubit :: Bool -> CliffordCirc Qubit
init_qubit b = do
tab <- get
let nq = next_qubit tab
put (add_qubit b tab)
return nq
init_qubits :: [Bool] -> CliffordCirc [Qubit]
init_qubits = mapM init_qubit
gate_X :: Qubit -> CliffordCirc ()
gate_X q = do
tab <- get
put (apply_unitary x q tab)
gate_Y :: Qubit -> CliffordCirc ()
gate_Y q = do
tab <- get
put (apply_unitary y q tab)
gate_Z :: Qubit -> CliffordCirc ()
gate_Z q = do
tab <- get
put (apply_unitary z q tab)
| Apply a Hadamard gate to the given qubit .
gate_H :: Qubit -> CliffordCirc ()
gate_H q = do
tab <- get
put (apply_unitary h q tab)
gate_S :: Qubit -> CliffordCirc ()
gate_S q = do
tab <- get
put (apply_unitary s q tab)
gate_Unitary :: Unitary -> Qubit -> CliffordCirc ()
gate_Unitary u q = do
tab <- get
put (apply_unitary u q tab)
controlled_X :: Qubit -> Qubit -> CliffordCirc ()
controlled_X q1 q2 = do
tab <- get
put (apply_unitary2 cnot (q1,q2) tab)
controlled_Z :: Qubit -> Qubit -> CliffordCirc ()
controlled_Z q1 q2 = do
tab <- get
put (apply_unitary2 cz (q1,q2) tab)
gate_Unitary2 :: Unitary2 -> Qubit -> Qubit -> CliffordCirc ()
gate_Unitary2 u q1 q2 = do
tab <- get
put (apply_unitary2 u (q1,q2) tab)
measure_qubit :: Qubit -> CliffordCirc Bool
measure_qubit q = do
tab <- get
(res,tab') <- lift $ measure q tab
put tab'
return res
measure_qubits :: [Qubit] -> CliffordCirc [Bool]
measure_qubits = mapM measure_qubit
show_tableau :: CliffordCirc ()
show_tableau = do
tab <- get
lift $ putStrLn (show tab)
| Return the evaluated ' ' for the given circuit .
eval :: CliffordCirc a -> IO Tableau
eval cc = execStateT cc empty_tableau
sim :: CliffordCirc a -> IO a
sim cc = evalStateT cc empty_tableau
| A swap gate can be defined in terms of three controlled - not gates .
swap :: Qubit -> Qubit -> CliffordCirc ()
swap q1 q2 = do
controlled_X q1 q2
controlled_X q2 q1
controlled_X q1 q2
Hadamard and controlled-/X/.
controlled_Z' :: Qubit -> Qubit -> CliffordCirc ()
controlled_Z' q1 q2 = do
gate_H q2
controlled_X q1 q2
gate_H q2
| Each of the four Bell states can be generated , indexed by a pair
bell :: (Bool,Bool) -> CliffordCirc (Qubit,Qubit)
bell (bx,by) = do
x <- init_qubit bx
y <- init_qubit by
gate_H x
controlled_X x y
return (x,y)
| Create a Bell state , and measure it .
measure_bell00 :: CliffordCirc (Bool,Bool)
measure_bell00 = do
(bx,by) <- bell (False,False)
mx <- measure_qubit bx
my <- measure_qubit by
return (mx,my)
controlled_if :: Bool -> (Qubit -> CliffordCirc ()) -> Qubit -> CliffordCirc ()
controlled_if b u q = if b then u q else return ()
teleport :: Qubit -> CliffordCirc Qubit
teleport q1 = do
(q2,q3) <- bell (False,False)
controlled_X q1 q2
gate_H q1
[b1,b2] <- measure_qubits [q1,q2]
controlled_if b2 gate_X q3
controlled_if b1 gate_Z q3
return q3
test_teleport :: Bool -> CliffordCirc Bool
test_teleport b = do
q <- init_qubit b
q' <- teleport q
measure_qubit q'
random_bool :: CliffordCirc Bool
random_bool = do
q <- init_qubit False
gate_H q
measure_qubit q
|
0648e104a19f5912533cf9042456840e6fe0d77543deed09dd291a26630ec21f | WorksHub/client | verticals.cljc | (ns wh.components.verticals
(:require
#?(:cljs [wh.components.forms.views :as views])
[re-frame.core :refer [dispatch]]
[wh.components.branding :as branding]
[wh.components.icons :refer [icon]]
[wh.util :as util]))
(defn vertical-line [status vertical toggle-event]
(when toggle-event
#?(:cljs (views/labelled-checkbox
status
(merge {:label [:div {:class "verticals-pod__vertical-toggle"}
[icon vertical] (branding/vertical-title vertical {:size :small})]
:label-class "verticals-pod__vertical-toggle-wrapper"}
(when toggle-event {:on-change (conj toggle-event vertical)}))))))
(defn verticals-pod
[{:keys [on-verticals off-verticals toggle-event]}]
[:div
{:class "verticals-pod-wrapper"}
[:div.wh-formx [:h2.is-hidden-desktop "Hubs"]]
[:div.pod
{:class "verticals-pod"}
[:span "Will be posted on: "]
[:div
{:class (util/merge-classes
"verticals-pod__verticals"
"verticals-pod__verticals--on")}
(doall (for [vertical on-verticals]
^{:key vertical}
[vertical-line true vertical toggle-event]))]
[:div
{:class (util/merge-classes
"verticals-pod__verticals"
"verticals-pod__verticals--off")}
(doall (for [vertical off-verticals]
^{:key vertical}
[vertical-line false vertical toggle-event]))]]])
| null | https://raw.githubusercontent.com/WorksHub/client/a51729585c2b9d7692e57b3edcd5217c228cf47c/common/src/wh/components/verticals.cljc | clojure | (ns wh.components.verticals
(:require
#?(:cljs [wh.components.forms.views :as views])
[re-frame.core :refer [dispatch]]
[wh.components.branding :as branding]
[wh.components.icons :refer [icon]]
[wh.util :as util]))
(defn vertical-line [status vertical toggle-event]
(when toggle-event
#?(:cljs (views/labelled-checkbox
status
(merge {:label [:div {:class "verticals-pod__vertical-toggle"}
[icon vertical] (branding/vertical-title vertical {:size :small})]
:label-class "verticals-pod__vertical-toggle-wrapper"}
(when toggle-event {:on-change (conj toggle-event vertical)}))))))
(defn verticals-pod
[{:keys [on-verticals off-verticals toggle-event]}]
[:div
{:class "verticals-pod-wrapper"}
[:div.wh-formx [:h2.is-hidden-desktop "Hubs"]]
[:div.pod
{:class "verticals-pod"}
[:span "Will be posted on: "]
[:div
{:class (util/merge-classes
"verticals-pod__verticals"
"verticals-pod__verticals--on")}
(doall (for [vertical on-verticals]
^{:key vertical}
[vertical-line true vertical toggle-event]))]
[:div
{:class (util/merge-classes
"verticals-pod__verticals"
"verticals-pod__verticals--off")}
(doall (for [vertical off-verticals]
^{:key vertical}
[vertical-line false vertical toggle-event]))]]])
| |
9e6591a46f4df7bd79d9661f870a9acde367c5ba59180b098afbe3e26be22835 | theodormoroianu/SecondYearCourses | LambdaChurch_20210415170921.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
------------
--BOOLEANS--
------------
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
--If is not really needed because we can use the booleans themselves, but...
cIf :: Term
cIf = undefined
--The boolean negation switches the alternatives
cNot :: Term
cNot = undefined
--The boolean conjunction can be built as a conditional
cAnd :: Term
cAnd = undefined
--The boolean disjunction can be built as a conditional
cOr :: Term
cOr = undefined
---------
PAIRS--
---------
-- a pair with components of type a and b is a way to compute something based
-- on the values contained within the pair (a -> b -> c) -> c
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
-------------------
--NATURAL NUMBERS--
-------------------
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z ( (t -> t) -> t -> t )
--0 will iterate the function s 0 times over z, producing z
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
--Addition of m and n can be done by composing n s with m s
cPlus :: Term
cPlus = undefined
--Multiplication of m and n can be done by composing n and m
cMul :: Term
cMul = undefined
--Exponentiation of m and n can be done by applying n to m
cPow :: Term
cPow = undefined
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
cSub :: Term
cSub = undefined
-- m is less than (or equal to) n if when substracting n from m we get 0
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
-- equality on naturals can be defined my means of comparisons
cEq :: Term
cEq = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and so far factorial
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
--Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
--hint iterate over a pair, initially (0, m),
incrementing the first and substracting n from the second if it is smaller than n
--for at most m times
cDivMod :: Term
cDivMod = undefined
---------
LISTS--
---------
-- a list with elements of type a is a way to aggregate a sequence of elements of type a
-- given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
-- The empty list is that which when aggregated it will always produce the initial value
cNil :: Term
cNil = undefined
-- Adding an element to a list means that, when aggregating the list, the newly added
-- element will be aggregated with the result obtained by aggregating the remainder of the list
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
-- builds a encoded list of encodings of natural numbers corresponding to a list of Integers
cNatList :: [Integer] -> Term
cNatList = undefined
-- sums the elements in the list
cSum :: Term
cSum = undefined
-- checks whether a list is nil (similar to cIs0)
cIsNil :: Term
cIsNil = undefined
-- gets the head of the list (or the default specified value if the list is empty)
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415170921.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
----------
BOOLEANS--
----------
If is not really needed because we can use the booleans themselves, but...
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
-------
-------
a pair with components of type a and b is a way to compute something based
on the values contained within the pair (a -> b -> c) -> c
a function to be applied on the values, it will apply it on them.
-----------------
NATURAL NUMBERS--
-----------------
A natural number is any way to iterate a function s a number of times
over an initial value z ( (t -> t) -> t -> t )
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n can be done by composing n s with m s
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and so far factorial
Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
hint iterate over a pair, initially (0, m),
for at most m times
-------
-------
a list with elements of type a is a way to aggregate a sequence of elements of type a
given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
The empty list is that which when aggregated it will always produce the initial value
Adding an element to a list means that, when aggregating the list, the newly added
element will be aggregated with the result obtained by aggregating the remainder of the list
builds a encoded list of encodings of natural numbers corresponding to a list of Integers
sums the elements in the list
checks whether a list is nil (similar to cIs0)
gets the head of the list (or the default specified value if the list is empty) | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
cIf :: Term
cIf = undefined
cNot :: Term
cNot = undefined
cAnd :: Term
cAnd = undefined
cOr :: Term
cOr = undefined
builds a pair out of two values as an object which , when given
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
- applies s one more time in addition to what n does
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
cPlus :: Term
cPlus = undefined
cMul :: Term
cMul = undefined
cPow :: Term
cPow = undefined
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
cSub :: Term
cSub = undefined
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
cEq :: Term
cEq = undefined
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
incrementing the first and substracting n from the second if it is smaller than n
cDivMod :: Term
cDivMod = undefined
cNil :: Term
cNil = undefined
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
cNatList :: [Integer] -> Term
cNatList = undefined
cSum :: Term
cSum = undefined
cIsNil :: Term
cIsNil = undefined
cHead :: Term
cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cTail :: Term
cTail = lam "l" (cFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t"))
$$ (cSnd $$ v "p"))
$$ (cPair $$ cNil $$ cNil)
))
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
|
24c5165d9e83c7e43f3f9bb138d1fa3fb0e5a999729ccf243c649b2eb5b0450c | arachne-framework/arachne-docs | config.clj | (ns ^:config myproj.config
(:require [arachne.core.dsl :as a]
[arachne.http.dsl :as h]
[arachne.pedestal.dsl :as p]))
(a/id :myproj/widget-1 (a/component 'myproj.core/make-widget))
(a/id :myproj/runtime (a/runtime [:myproj/server :myproj/widget-1]))
(a/id :myproj/hello (h/handler 'myproj.core/hello-handler))
(a/id :myproj/server
(p/server 8080
(h/endpoint :get "/" :myproj/hello)
(h/endpoint :get "/greet/:name" (h/handler 'myproj.core/greeter))
))
| null | https://raw.githubusercontent.com/arachne-framework/arachne-docs/5288932ea266639e41b139b19aaa109b1bf8b341/tutorial-code/http-requests/config/myproj/config.clj | clojure | (ns ^:config myproj.config
(:require [arachne.core.dsl :as a]
[arachne.http.dsl :as h]
[arachne.pedestal.dsl :as p]))
(a/id :myproj/widget-1 (a/component 'myproj.core/make-widget))
(a/id :myproj/runtime (a/runtime [:myproj/server :myproj/widget-1]))
(a/id :myproj/hello (h/handler 'myproj.core/hello-handler))
(a/id :myproj/server
(p/server 8080
(h/endpoint :get "/" :myproj/hello)
(h/endpoint :get "/greet/:name" (h/handler 'myproj.core/greeter))
))
| |
2eee5137c1473403b97755c0e99486291aca45df01e0284cedea0624ab7df666 | mirage/irmin-server | command_tree.ml | open Lwt.Syntax
module Make
(IO : Conn.IO)
(Codec : Conn.Codec.S)
(Store : Irmin.Generic_key.S)
(Tree : Tree.S
with type concrete = Store.Tree.concrete
and type kinded_key = Store.Tree.kinded_key)
(Commit : Commit.S with type hash = Store.hash and type tree = Tree.t) =
struct
include Context.Make (IO) (Codec) (Store) (Tree)
module Return = Conn.Return
type t = Tree.t
module Empty = struct
type req = unit [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.empty"
let run conn ctx _ () =
let empty = Store.Tree.empty in
let id = incr_id () in
Hashtbl.replace ctx.trees id (empty ());
Return.v conn res_t (ID id)
end
module Clear = struct
type req = Tree.t [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.clear"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
Store.Tree.clear tree;
Return.v conn res_t ()
end
module Of_path = struct
type req = Store.path [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_path"
let run conn ctx _ path =
let* tree = Store.find_tree ctx.store path in
match tree with
| None -> Return.v conn res_t None
| Some tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Of_hash = struct
type req = Store.hash [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_hash"
let run conn ctx _ hash =
let* tree = Store.Tree.of_hash ctx.repo (`Node hash) in
match tree with
| None -> Return.v conn res_t None
| Some tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Of_commit = struct
type req = Store.hash [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_commit"
let run conn ctx _ hash =
let* commit = Store.Commit.of_hash ctx.repo hash in
match commit with
| None -> Return.v conn res_t None
| Some commit ->
let tree = Store.Commit.tree commit in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Save = struct
type req = Tree.t [@@deriving irmin]
type res = [ `Contents of Store.contents_key | `Node of Store.node_key ]
[@@deriving irmin]
let name = "tree.save"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let* hash =
Store.Backend.Repo.batch ctx.repo (fun x y _ ->
Store.save_tree ctx.repo x y tree)
in
Return.v conn res_t hash
end
module Add = struct
type req = Tree.t * Store.path * Store.contents [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.add"
let run conn ctx _ (tree, path, value) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.add tree path value in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Batch_commit = struct
type req = (Store.commit_key list * Store.info) * Tree.t [@@deriving irmin]
type res = Store.commit_key [@@deriving irmin]
let name = "tree.batch.commit"
let run conn ctx _ ((parents, info), tree) =
let* _, tree = resolve_tree ctx tree in
let* commit = Store.Commit.v ctx.repo ~info ~parents tree in
let key = Store.Commit.key commit in
Return.v conn res_t key
end
module Batch_apply = struct
type req =
Store.path
* (Store.hash list option * Store.info)
* (Store.path
* [ `Contents of
[ `Hash of Store.Hash.t | `Value of Store.contents ]
* Store.metadata option
| `Tree of Tree.t ]
option)
list
[@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.batch.apply"
let mk_parents ctx parents =
match parents with
| None -> Lwt.return None
| Some parents ->
let* parents =
Lwt_list.filter_map_s
(fun hash -> Store.Commit.of_hash ctx.repo hash)
parents
in
Lwt.return_some parents
let run conn ctx _ (path, (parents, info), l) =
let* parents = mk_parents ctx parents in
let* () =
Store.with_tree_exn ctx.store path ?parents
~info:(fun () -> info)
(fun tree ->
let tree = Option.value ~default:(Store.Tree.empty ()) tree in
let* tree =
Lwt_list.fold_left_s
(fun tree (path, value) ->
match value with
| Some (`Contents (`Hash value, metadata)) ->
let* value = Store.Contents.of_hash ctx.repo value in
Store.Tree.add tree path ?metadata (Option.get value)
| Some (`Contents (`Value value, metadata)) ->
Store.Tree.add tree path ?metadata value
| Some (`Tree t) ->
let* _, tree' = resolve_tree ctx t in
Store.Tree.add_tree tree path tree'
| None -> Store.Tree.remove tree path)
tree l
in
Lwt.return (Some tree))
in
Return.v conn res_t ()
end
module Batch_tree = struct
type req =
Tree.t
* (Store.path
* [ `Contents of
[ `Hash of Store.Hash.t | `Value of Store.contents ]
* Store.metadata option
| `Tree of Tree.t ]
option)
list
[@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.batch.tree"
let run conn ctx _ (tree, l) =
let* _, tree = resolve_tree ctx tree in
let* tree =
Lwt_list.fold_left_s
(fun tree (path, value) ->
match value with
| Some (`Contents (`Hash value, metadata)) ->
let* value = Store.Contents.of_hash ctx.repo value in
Store.Tree.add tree path ?metadata (Option.get value)
| Some (`Contents (`Value value, metadata)) ->
Store.Tree.add tree path ?metadata value
| Some (`Tree t) ->
let* _, tree' = resolve_tree ctx t in
Store.Tree.add_tree tree path tree'
| None -> Store.Tree.remove tree path)
tree l
in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Add_tree = struct
type req = Tree.t * Store.path * Tree.t [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.add_tree"
let run conn ctx _ (tree, path, tr) =
let* _, tree = resolve_tree ctx tree in
let* _, tree' = resolve_tree ctx tr in
let* tree = Store.Tree.add_tree tree path tree' in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Merge = struct
type req = Tree.t * Tree.t * Tree.t [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.merge"
let run conn ctx _ (old, tree, tr) =
let* _, old = resolve_tree ctx old in
let* _, tree = resolve_tree ctx tree in
let* _, tree' = resolve_tree ctx tr in
let* tree =
Irmin.Merge.f Store.Tree.merge ~old:(Irmin.Merge.promise old) tree tree'
in
match tree with
| Ok tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
| Error e ->
Return.err conn (Irmin.Type.to_string Irmin.Merge.conflict_t e)
end
module Find = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Store.contents option [@@deriving irmin]
let name = "tree.find"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* contents = Store.Tree.find tree path in
Return.v conn res_t contents
end
module Find_tree = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.find_tree"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.find_tree tree path in
let tree =
Option.map
(fun tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Tree.ID id)
tree
in
Return.v conn res_t tree
end
module Remove = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.remove"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.remove tree path in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Cleanup = struct
type req = Tree.t [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.cleanup"
let run conn ctx _ tree =
let () =
match tree with Tree.ID id -> Hashtbl.remove ctx.trees id | _ -> ()
in
Return.ok conn
end
module To_local = struct
type req = Tree.t [@@deriving irmin]
type res = Tree.concrete [@@deriving irmin]
let name = "tree.to_local"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.to_concrete tree in
Return.v conn res_t tree
end
module Mem = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = bool [@@deriving irmin]
let name = "tree.mem"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* res = Store.Tree.mem tree path in
Return.v conn res_t res
end
module Mem_tree = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = bool [@@deriving irmin]
let name = "tree.mem_tree"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* res = Store.Tree.mem_tree tree path in
Return.v conn res_t res
end
module List = struct
type req = Tree.t * Store.path [@@deriving irmin]
type tree = [ `Contents | `Tree ] [@@deriving irmin]
type res = (Store.Path.step * [ `Contents | `Tree ]) list [@@deriving irmin]
let name = "tree.list"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* l = Store.Tree.list tree path in
let* x =
Lwt_list.map_s
(fun (k, _) ->
let+ exists = Store.Tree.mem_tree tree (Store.Path.rcons path k) in
if exists then (k, `Tree) else (k, `Contents))
l
in
Return.v conn res_t x
end
module Hash = struct
type req = Tree.t [@@deriving irmin]
type res = Store.Hash.t [@@deriving irmin]
let name = "tree.hash"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let hash = Store.Tree.hash tree in
Return.v conn res_t hash
end
module Key = struct
type req = Tree.t [@@deriving irmin]
type res = Store.Tree.kinded_key [@@deriving irmin]
let name = "tree.key"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let key = Store.Tree.key tree in
Return.v conn res_t (Option.get key)
end
module Cleanup_all = struct
type req = unit [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.cleanup_all"
let run conn ctx _ () =
reset_trees ctx;
Return.v conn res_t ()
end
let commands =
[
cmd (module Empty);
cmd (module Clear);
cmd (module Add);
cmd (module Batch_commit);
cmd (module Batch_apply);
cmd (module Batch_tree);
cmd (module Remove);
cmd (module Cleanup);
cmd (module Cleanup_all);
cmd (module Mem);
cmd (module Mem_tree);
cmd (module List);
cmd (module To_local);
cmd (module Find);
cmd (module Find_tree);
cmd (module Add_tree);
cmd (module Hash);
cmd (module Merge);
cmd (module Save);
cmd (module Of_path);
cmd (module Of_hash);
cmd (module Of_commit);
]
end
| null | https://raw.githubusercontent.com/mirage/irmin-server/41a0c6189614b12cf571e78bd0f4f31373b19ad2/src/irmin-server-internal/command_tree.ml | ocaml | open Lwt.Syntax
module Make
(IO : Conn.IO)
(Codec : Conn.Codec.S)
(Store : Irmin.Generic_key.S)
(Tree : Tree.S
with type concrete = Store.Tree.concrete
and type kinded_key = Store.Tree.kinded_key)
(Commit : Commit.S with type hash = Store.hash and type tree = Tree.t) =
struct
include Context.Make (IO) (Codec) (Store) (Tree)
module Return = Conn.Return
type t = Tree.t
module Empty = struct
type req = unit [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.empty"
let run conn ctx _ () =
let empty = Store.Tree.empty in
let id = incr_id () in
Hashtbl.replace ctx.trees id (empty ());
Return.v conn res_t (ID id)
end
module Clear = struct
type req = Tree.t [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.clear"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
Store.Tree.clear tree;
Return.v conn res_t ()
end
module Of_path = struct
type req = Store.path [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_path"
let run conn ctx _ path =
let* tree = Store.find_tree ctx.store path in
match tree with
| None -> Return.v conn res_t None
| Some tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Of_hash = struct
type req = Store.hash [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_hash"
let run conn ctx _ hash =
let* tree = Store.Tree.of_hash ctx.repo (`Node hash) in
match tree with
| None -> Return.v conn res_t None
| Some tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Of_commit = struct
type req = Store.hash [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.of_commit"
let run conn ctx _ hash =
let* commit = Store.Commit.of_hash ctx.repo hash in
match commit with
| None -> Return.v conn res_t None
| Some commit ->
let tree = Store.Commit.tree commit in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (Some (ID id))
end
module Save = struct
type req = Tree.t [@@deriving irmin]
type res = [ `Contents of Store.contents_key | `Node of Store.node_key ]
[@@deriving irmin]
let name = "tree.save"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let* hash =
Store.Backend.Repo.batch ctx.repo (fun x y _ ->
Store.save_tree ctx.repo x y tree)
in
Return.v conn res_t hash
end
module Add = struct
type req = Tree.t * Store.path * Store.contents [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.add"
let run conn ctx _ (tree, path, value) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.add tree path value in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Batch_commit = struct
type req = (Store.commit_key list * Store.info) * Tree.t [@@deriving irmin]
type res = Store.commit_key [@@deriving irmin]
let name = "tree.batch.commit"
let run conn ctx _ ((parents, info), tree) =
let* _, tree = resolve_tree ctx tree in
let* commit = Store.Commit.v ctx.repo ~info ~parents tree in
let key = Store.Commit.key commit in
Return.v conn res_t key
end
module Batch_apply = struct
type req =
Store.path
* (Store.hash list option * Store.info)
* (Store.path
* [ `Contents of
[ `Hash of Store.Hash.t | `Value of Store.contents ]
* Store.metadata option
| `Tree of Tree.t ]
option)
list
[@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.batch.apply"
let mk_parents ctx parents =
match parents with
| None -> Lwt.return None
| Some parents ->
let* parents =
Lwt_list.filter_map_s
(fun hash -> Store.Commit.of_hash ctx.repo hash)
parents
in
Lwt.return_some parents
let run conn ctx _ (path, (parents, info), l) =
let* parents = mk_parents ctx parents in
let* () =
Store.with_tree_exn ctx.store path ?parents
~info:(fun () -> info)
(fun tree ->
let tree = Option.value ~default:(Store.Tree.empty ()) tree in
let* tree =
Lwt_list.fold_left_s
(fun tree (path, value) ->
match value with
| Some (`Contents (`Hash value, metadata)) ->
let* value = Store.Contents.of_hash ctx.repo value in
Store.Tree.add tree path ?metadata (Option.get value)
| Some (`Contents (`Value value, metadata)) ->
Store.Tree.add tree path ?metadata value
| Some (`Tree t) ->
let* _, tree' = resolve_tree ctx t in
Store.Tree.add_tree tree path tree'
| None -> Store.Tree.remove tree path)
tree l
in
Lwt.return (Some tree))
in
Return.v conn res_t ()
end
module Batch_tree = struct
type req =
Tree.t
* (Store.path
* [ `Contents of
[ `Hash of Store.Hash.t | `Value of Store.contents ]
* Store.metadata option
| `Tree of Tree.t ]
option)
list
[@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.batch.tree"
let run conn ctx _ (tree, l) =
let* _, tree = resolve_tree ctx tree in
let* tree =
Lwt_list.fold_left_s
(fun tree (path, value) ->
match value with
| Some (`Contents (`Hash value, metadata)) ->
let* value = Store.Contents.of_hash ctx.repo value in
Store.Tree.add tree path ?metadata (Option.get value)
| Some (`Contents (`Value value, metadata)) ->
Store.Tree.add tree path ?metadata value
| Some (`Tree t) ->
let* _, tree' = resolve_tree ctx t in
Store.Tree.add_tree tree path tree'
| None -> Store.Tree.remove tree path)
tree l
in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Add_tree = struct
type req = Tree.t * Store.path * Tree.t [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.add_tree"
let run conn ctx _ (tree, path, tr) =
let* _, tree = resolve_tree ctx tree in
let* _, tree' = resolve_tree ctx tr in
let* tree = Store.Tree.add_tree tree path tree' in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Merge = struct
type req = Tree.t * Tree.t * Tree.t [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.merge"
let run conn ctx _ (old, tree, tr) =
let* _, old = resolve_tree ctx old in
let* _, tree = resolve_tree ctx tree in
let* _, tree' = resolve_tree ctx tr in
let* tree =
Irmin.Merge.f Store.Tree.merge ~old:(Irmin.Merge.promise old) tree tree'
in
match tree with
| Ok tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
| Error e ->
Return.err conn (Irmin.Type.to_string Irmin.Merge.conflict_t e)
end
module Find = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Store.contents option [@@deriving irmin]
let name = "tree.find"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* contents = Store.Tree.find tree path in
Return.v conn res_t contents
end
module Find_tree = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Tree.t option [@@deriving irmin]
let name = "tree.find_tree"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.find_tree tree path in
let tree =
Option.map
(fun tree ->
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Tree.ID id)
tree
in
Return.v conn res_t tree
end
module Remove = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = Tree.t [@@deriving irmin]
let name = "tree.remove"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.remove tree path in
let id = incr_id () in
Hashtbl.replace ctx.trees id tree;
Return.v conn res_t (ID id)
end
module Cleanup = struct
type req = Tree.t [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.cleanup"
let run conn ctx _ tree =
let () =
match tree with Tree.ID id -> Hashtbl.remove ctx.trees id | _ -> ()
in
Return.ok conn
end
module To_local = struct
type req = Tree.t [@@deriving irmin]
type res = Tree.concrete [@@deriving irmin]
let name = "tree.to_local"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let* tree = Store.Tree.to_concrete tree in
Return.v conn res_t tree
end
module Mem = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = bool [@@deriving irmin]
let name = "tree.mem"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* res = Store.Tree.mem tree path in
Return.v conn res_t res
end
module Mem_tree = struct
type req = Tree.t * Store.path [@@deriving irmin]
type res = bool [@@deriving irmin]
let name = "tree.mem_tree"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* res = Store.Tree.mem_tree tree path in
Return.v conn res_t res
end
module List = struct
type req = Tree.t * Store.path [@@deriving irmin]
type tree = [ `Contents | `Tree ] [@@deriving irmin]
type res = (Store.Path.step * [ `Contents | `Tree ]) list [@@deriving irmin]
let name = "tree.list"
let run conn ctx _ (tree, path) =
let* _, tree = resolve_tree ctx tree in
let* l = Store.Tree.list tree path in
let* x =
Lwt_list.map_s
(fun (k, _) ->
let+ exists = Store.Tree.mem_tree tree (Store.Path.rcons path k) in
if exists then (k, `Tree) else (k, `Contents))
l
in
Return.v conn res_t x
end
module Hash = struct
type req = Tree.t [@@deriving irmin]
type res = Store.Hash.t [@@deriving irmin]
let name = "tree.hash"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let hash = Store.Tree.hash tree in
Return.v conn res_t hash
end
module Key = struct
type req = Tree.t [@@deriving irmin]
type res = Store.Tree.kinded_key [@@deriving irmin]
let name = "tree.key"
let run conn ctx _ tree =
let* _, tree = resolve_tree ctx tree in
let key = Store.Tree.key tree in
Return.v conn res_t (Option.get key)
end
module Cleanup_all = struct
type req = unit [@@deriving irmin]
type res = unit [@@deriving irmin]
let name = "tree.cleanup_all"
let run conn ctx _ () =
reset_trees ctx;
Return.v conn res_t ()
end
let commands =
[
cmd (module Empty);
cmd (module Clear);
cmd (module Add);
cmd (module Batch_commit);
cmd (module Batch_apply);
cmd (module Batch_tree);
cmd (module Remove);
cmd (module Cleanup);
cmd (module Cleanup_all);
cmd (module Mem);
cmd (module Mem_tree);
cmd (module List);
cmd (module To_local);
cmd (module Find);
cmd (module Find_tree);
cmd (module Add_tree);
cmd (module Hash);
cmd (module Merge);
cmd (module Save);
cmd (module Of_path);
cmd (module Of_hash);
cmd (module Of_commit);
]
end
| |
5b63361aacaf393b9fcd8a4c10bce84d1dfad865e1dd046ee2dcb6176c19bb6c | spechub/Hets | ParseTHF.hs | |
Module : ./THF / ParseTHF.hs
Description : A Parser for the TPTP - THF Syntax
Copyright : ( c ) , DFKI Bremen 2012
( c ) , DFKI Bremen 2011
License : GPLv2 or higher , see LICENSE.txt
Maintainer : < >
Stability : provisional
Portability : portable
A Parser for the TPTP - THF Input Syntax v5.4.0.0 taken from
< /~tptp/TPTP/SyntaxBNF.html > and THF0
Syntax taken from < -sb.de/~chris/papers/C25.pdf > P. 15 - 16
Note : The parser prefers a THF0 parse tree over a THF parse tree
Note : We pretend as if tuples were still part of the syntax
Module : ./THF/ParseTHF.hs
Description : A Parser for the TPTP-THF Syntax
Copyright : (c) Jonathan von Schroeder, DFKI Bremen 2012
(c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Jonathan von Schroeder <>
Stability : provisional
Portability : portable
A Parser for the TPTP-THF Input Syntax v5.4.0.0 taken from
</~tptp/TPTP/SyntaxBNF.html> and THF0
Syntax taken from <-sb.de/~chris/papers/C25.pdf> P. 15-16
Note: The parser prefers a THF0 parse tree over a THF parse tree
Note: We pretend as if tuples were still part of the syntax
-}
module THF.ParseTHF (parseTHF) where
import THF.As
import Text.ParserCombinators.Parsec
import Common.Parsec
import Common.Id (Token (..))
import Common.Lexer (parseToken)
import qualified Control.Monad.Fail as Fail
import Data.Char
import Data.Maybe
-----------------------------------------------------------------------------
for the THF and THF0 Syntax
-----------------------------------------------------------------------------
Parser for the THF and THF0 Syntax
----------------------------------------------------------------------------- -}
THF & THF0 :
< TPTP_input > : : = < annotated_formula > | < include >
< thf_annotated > : : = thf(<name>,<formula_role>,<thf_formula><annotations > ) .
Data Type : TPTP_THF
<TPTP_input> ::= <annotated_formula> | <include>
<thf_annotated> ::= thf(<name>,<formula_role>,<thf_formula><annotations>).
Data Type: TPTP_THF -}
parseTHF :: CharParser st [TPTP_THF]
parseTHF = do
h <- optionMaybe header
thf <- many ((systemComment <|> definedComment <|> comment <|>
include <|> thfAnnotatedFormula) << skipSpaces)
return $ if isJust h then fromJust h : thf else thf
header :: CharParser st TPTP_THF
header = try (do
s <- headerSE
c <- myManyTill (try (commentLine << skipSpaces)) (try headerSE)
return $ TPTP_Header (s : c))
headerSE :: CharParser st Comment
headerSE = do
try (char '%' >> notFollowedBy (char '$'))
c <- parseToken $ many1 $ char '-' << notFollowedBy printableChar
skipSpaces
return $ Comment_Line c
THF & THF0 :
< comment > : : - < comment_line>|<comment_block >
< comment_line > : : - [ % ] < printable_char > *
< comment_block > : : : [ /][*]<not_star_slash>[*][*]*[/ ]
< not_star_slash > : : : ( [ ^*]*[*][*]*[^/*])*[^ * ] *
<comment> ::- <comment_line>|<comment_block>
<comment_line> ::- [%]<printable_char>*
<comment_block> ::: [/][*]<not_star_slash>[*][*]*[/]
<not_star_slash> ::: ([^*]*[*][*]*[^/*])*[^*]* -}
commentLine :: CharParser st Comment
commentLine = do
try (char '%' >> notFollowedBy (char '$'))
c <- parseToken $ many printableChar
return $ Comment_Line c
comment_ :: String -> CharParser st Token
comment_ start = do
try (string start >> notFollowedBy (char '$'))
c <- parseToken $ many (noneOf "*/")
skipMany1 (char '*')
char '/'
return c
comment :: CharParser st TPTP_THF
comment = fmap TPTP_Comment commentLine
<|> do
c <- comment_ "/*"
return $ TPTP_Comment (Comment_Block c)
THF & THF0 :
< defined_comment > : : - < def_comment_line>|<def_comment_block >
< def_comment_line > : : : [ % ] < dollar><printable_char > *
< def_comment_block > : : : [ /][*]<dollar><not_star_slash>[*][*]*[/ ]
Data Type : DefinedComment
<defined_comment> ::- <def_comment_line>|<def_comment_block>
<def_comment_line> ::: [%]<dollar><printable_char>*
<def_comment_block> ::: [/][*]<dollar><not_star_slash>[*][*]*[/]
Data Type: DefinedComment -}
definedComment :: CharParser st TPTP_THF
definedComment = do
try (string "%$" >> notFollowedBy (char '$'))
c <- parseToken $ many printableChar
return $ TPTP_Defined_Comment (Defined_Comment_Line c)
<|> do
c <- comment_ "/*$"
return $ TPTP_Defined_Comment (Defined_Comment_Block c)
THF & THF0 :
< system_comment > : : - < sys_comment_line>|<sys_comment_block >
< sys_comment_line > : : : [ % ] < dollar><dollar><printable_char > *
< sys_comment_block > : : : [ /][*]<dollar><dollar><not_star_slash>[*][*]*[/ ]
Data Type : SystemComment
<system_comment> ::- <sys_comment_line>|<sys_comment_block>
<sys_comment_line> ::: [%]<dollar><dollar><printable_char>*
<sys_comment_block> ::: [/][*]<dollar><dollar><not_star_slash>[*][*]*[/]
Data Type: SystemComment -}
systemComment :: CharParser st TPTP_THF
systemComment = do
tryString "%$$"
c <- parseToken $ many printableChar
return $ TPTP_System_Comment (System_Comment_Line c)
<|> do
c <- comment_ "/*$$"
return $ TPTP_System_Comment (System_Comment_Block c)
THF & THF0 :
< include > : : = include(<file_name><formula_selection > ) .
< formula_selection > : : = , [ < name_list > ] | < null >
Data Type : Include
<include> ::= include(<file_name><formula_selection>).
<formula_selection> ::= ,[<name_list>] | <null>
Data Type: Include -}
include :: CharParser st TPTP_THF
include = do
key $ tryString "include"
oParentheses
fn <- fileName
fs <- formulaSelection
cParentheses
char '.'
return $ TPTP_Include (I_Include fn fs)
thfAnnotatedFormula :: CharParser st TPTP_THF
thfAnnotatedFormula = do
key $ tryString "thf"
oParentheses
n <- name
comma
fr <- formulaRole
comma
tf <- thfFormula
a <- annotations
cParentheses
char '.'
return $ TPTP_THF_Annotated_Formula n fr tf a
THF & THF0 :
< annotations > : : = , < source><optional_info > | < null >
<annotations> ::= ,<source><optional_info> | <null> -}
annotations :: CharParser st Annotations
annotations = do
comma
s <- source
oi <- optionalInfo
return $ Annotations s oi
<|> do
notFollowedBy (char ',')
return Null
THF & THF0 :
< formula_role > : : = < lower_word >
< formula_role > : = = axiom | hypothesis | definition | assumption |
lemma | theorem | conjecture | negated_conjecture |
plain | fi_domain | fi_functors | fi_predicates |
type | unknown
<formula_role> ::= <lower_word>
<formula_role> :== axiom | hypothesis | definition | assumption |
lemma | theorem | conjecture | negated_conjecture |
plain | fi_domain | fi_functors | fi_predicates |
type | unknown -}
formulaRole :: CharParser st FormulaRole
formulaRole = do
r <- lowerWord
case show r of
"axiom" -> return Axiom
"hypothesis" -> return Hypothesis
"definition" -> return Definition
"assumption" -> return Assumption
"lemma" -> return Lemma
"theorem" -> return Theorem
"conjecture" -> return Conjecture
"negated_conjecture" -> return Negated_Conjecture
"plain" -> return Plain
"fi_domain" -> return Fi_Domain
"fi_functors" -> return Fi_Functors
"fi_predicates" -> return Fi_Predicates
"type" -> return Type
"unknown" -> return Unknown
s -> Fail.fail ("No such Role: " ++ s)
THF
< thf_formula > : : = < thf_logic_formula > | < thf_sequent >
THF0 :
< thf_formula > : : = < thf_logic_formula > | < thf_typed_const >
<thf_formula> ::= <thf_logic_formula> | <thf_sequent>
THF0:
<thf_formula> ::= <thf_logic_formula> | <thf_typed_const> -}
thfFormula :: CharParser st THFFormula
thfFormula = fmap T0F_THF_Typed_Const thfTypedConst
<|> fmap TF_THF_Logic_Formula thfLogicFormula
<|> fmap TF_THF_Sequent thfSequent
THF :
< thf_logic_formula > : : = < thf_binary_formula > | < thf_unitary_formula > |
< thf_type_formula > | < thf_subtype >
THF0 :
< thf_logic_formula > : : = < thf_binary_formula > | < thf_unitary_formula >
<thf_logic_formula> ::= <thf_binary_formula> | <thf_unitary_formula> |
<thf_type_formula> | <thf_subtype>
THF0:
<thf_logic_formula> ::= <thf_binary_formula> | <thf_unitary_formula> -}
thfLogicFormula :: CharParser st THFLogicFormula
thfLogicFormula = fmap TLF_THF_Binary_Formula thfBinaryFormula
<|> fmap TLF_THF_Unitary_Formula thfUnitaryFormula
-- different position for unitary formula to prefer thf0 parse
<|> fmap TLF_THF_Type_Formula thfTypeFormula
<|> fmap TLF_THF_Sub_Type thfSubType
THF :
< thf_binary_formula > : : = < thf_binary_pair > | < thf_binary_tuple > |
< thf_binary_type >
< thf_binary_pair > : : = < thf_unitary_formula > < thf_pair_connective >
< thf_unitary_formula >
THF0 :
< thf_binary_formula > : : = < thf_pair_binary > | < thf_tuple_binary >
< thf_pair_binary > : : = < thf_unitary_formula > < thf_pair_connective >
< thf_unitary_formula >
Note : For THF0
< thf_binary_pair > is used like < thf_pair_binary > and
< thf_binary_tuple > are used like < thf_tuple_binary >
<thf_binary_formula> ::= <thf_binary_pair> | <thf_binary_tuple> |
<thf_binary_type>
<thf_binary_pair> ::= <thf_unitary_formula> <thf_pair_connective>
<thf_unitary_formula>
THF0:
<thf_binary_formula> ::= <thf_pair_binary> | <thf_tuple_binary>
<thf_pair_binary> ::= <thf_unitary_formula> <thf_pair_connective>
<thf_unitary_formula>
Note: For THF0
<thf_binary_pair> is used like <thf_pair_binary> and
<thf_binary_tuple> are used like <thf_tuple_binary> -}
thfBinaryFormula :: CharParser st THFBinaryFormula
thfBinaryFormula = fmap TBF_THF_Binary_Tuple thfBinaryTuple
<|> do
(uff, pc) <- try $ do
uff1 <- thfUnitaryFormula
pc1 <- thfPairConnective
return (uff1, pc1)
ufb <- thfUnitaryFormula
return $ TBF_THF_Binary_Pair uff pc ufb
<|> fmap TBF_THF_Binary_Type thfBinaryType
-- different position for binary type to prefer thf0 parse
THF :
< thf_binary_tuple > : : = < thf_or_formula > | < thf_and_formula > |
< thf_apply_formula >
THF0 :
< thf_tuple_binary > : : = < thf_or_formula > | < thf_and_formula > |
< thf_apply_formula >
THF & THF0 :
< thf_or_formula > : : = < thf_unitary_formula > < vline > < thf_unitary_formula > |
< thf_or_formula > < vline > < thf_unitary_formula >
< thf_and_formula > : : = < thf_unitary_formula > & < thf_unitary_formula > |
thf_and_formula > & < thf_unitary_formula >
< thf_apply_formula > : : = < thf_unitary_formula > @ < thf_unitary_formula > |
< thf_apply_formula > @ < thf_unitary_formula >
< vline > : = = |
<thf_binary_tuple> ::= <thf_or_formula> | <thf_and_formula> |
<thf_apply_formula>
THF0:
<thf_tuple_binary> ::= <thf_or_formula> | <thf_and_formula> |
<thf_apply_formula>
THF & THF0:
<thf_or_formula> ::= <thf_unitary_formula> <vline> <thf_unitary_formula> |
<thf_or_formula> <vline> <thf_unitary_formula>
<thf_and_formula> ::= <thf_unitary_formula> & <thf_unitary_formula> |
thf_and_formula> & <thf_unitary_formula>
<thf_apply_formula> ::= <thf_unitary_formula> @ <thf_unitary_formula> |
<thf_apply_formula> @ <thf_unitary_formula>
<vline> :== | -}
thfBinaryTuple :: CharParser st THFBinaryTuple
thfBinaryTuple = do -- or
uff <- try (thfUnitaryFormula << vLine)
ufb <- sepBy1 thfUnitaryFormula vLine
return $ TBT_THF_Or_Formula (uff : ufb)
<|> do -- and
uff <- try (thfUnitaryFormula << ampersand)
ufb <- sepBy1 thfUnitaryFormula ampersand
return $ TBT_THF_And_Formula (uff : ufb)
<|> do -- apply
uff <- try (thfUnitaryFormula << at)
ufb <- sepBy1 thfUnitaryFormula at
return $ TBT_THF_Apply_Formula (uff : ufb)
formulaWithVariables :: CharParser st (THFVariableList, THFUnitaryFormula)
formulaWithVariables = do
vl <- brackets thfVariableList
colon
uf <- thfUnitaryFormula
return (vl, uf)
THF :
< thf_unitary_formula > : : = < thf_quantified_formula > | < thf_unary_formula > |
< thf_atom > | < thf_tuple > | < thf_let > |
< thf_conditional > | ( < thf_logic_formula > )
note : thf let is currently not well defined and thus ommited
< thf_conditional > : : = $ itef(<thf_logic_formula>,<thf_logic_formula > ,
< thf_logic_formula > )
THF0 :
< thf_unitary_formula > : : = < thf_quantified_formula > | < thf_abstraction > |
< thf_unary_formula > | < thf_atom > |
( < thf_logic_formula > )
< thf_abstraction > : : = < thf_lambda > [ < thf_variable_list > ] :
< thf_unitary_formula >
< thf_lambda > : : = ^
THF & THF0 :
< thf_unary_formula > : : = < thf_unary_connective > ( < thf_logic_formula > )
<thf_unitary_formula> ::= <thf_quantified_formula> | <thf_unary_formula> |
<thf_atom> | <thf_tuple> | <thf_let> |
<thf_conditional> | (<thf_logic_formula>)
note: thf let is currently not well defined and thus ommited
<thf_conditional> ::= $itef(<thf_logic_formula>,<thf_logic_formula>,
<thf_logic_formula>)
THF0:
<thf_unitary_formula> ::= <thf_quantified_formula> | <thf_abstraction> |
<thf_unary_formula> | <thf_atom> |
(<thf_logic_formula>)
<thf_abstraction> ::= <thf_lambda> [<thf_variable_list>] :
<thf_unitary_formula>
<thf_lambda> ::= ^
THF & THF0:
<thf_unary_formula> ::= <thf_unary_connective> (<thf_logic_formula>) -}
thfUnitaryFormula :: CharParser st THFUnitaryFormula
thfUnitaryFormula = fmap TUF_THF_Logic_Formula_Par (parentheses thfLogicFormula)
<|> fmap TUF_THF_Quantified_Formula (try thfQuantifiedFormula)
<|> do
keyChar '^'
(vl, uf) <- formulaWithVariables
added this for thf0
changed positions of parses below to prefer
changed positions of parses below to prefer th0 -}
<|> try thfUnaryFormula
<|> fmap TUF_THF_Atom thfAtom
<|> fmap TUF_THF_Tuple thfTuple
<|> do
key $ tryString "$itef"
oParentheses
lf1 <- thfLogicFormula
comma
lf2 <- thfLogicFormula
comma
lf3 <- thfLogicFormula
cParentheses
return $ TUF_THF_Conditional lf1 lf2 lf3
THF :
< thf_quantified_formula > : : = < thf_quantifier > [ < thf_variable_list > ] :
< thf_unitary_formula >
THF0 :
< thf_quantified_formula > : : = < thf_quantified_var > | < thf_quantified_novar >
< thf_quantified_var > : : = < quantifier > [ < thf_variable_list > ] :
< thf_unitary_formula >
< thf_quantified_novar > : : = < thf_quantifier > ( < thf_unitary_formula > )
<thf_quantified_formula> ::= <thf_quantifier> [<thf_variable_list>] :
<thf_unitary_formula>
THF0:
<thf_quantified_formula> ::= <thf_quantified_var> | <thf_quantified_novar>
<thf_quantified_var> ::= <quantifier> [<thf_variable_list>] :
<thf_unitary_formula>
<thf_quantified_novar> ::= <thf_quantifier> (<thf_unitary_formula>) -}
thfQuantifiedFormula :: CharParser st THFQuantifiedFormula
thfQuantifiedFormula = do
q <- quantifier
(vl, uf) <- formulaWithVariables
return $ T0QF_THF_Quantified_Var q vl uf -- added this for thf0
<|> do
q <- thfQuantifier
uf <- parentheses thfUnitaryFormula
return $ T0QF_THF_Quantified_Novar q uf -- added this for thf0
<|> do
q <- thfQuantifier
(vl, uf) <- formulaWithVariables
return $ TQF_THF_Quantified_Formula q vl uf
THF & THF0 :
< thf_variable_list > : : = < thf_variable > |
< thf_variable>,<thf_variable_list >
<thf_variable_list> ::= <thf_variable> |
<thf_variable>,<thf_variable_list> -}
thfVariableList :: CharParser st THFVariableList
thfVariableList = sepBy1 thfVariable comma
THF & THF0 :
< thf_variable > : : = < thf_typed_variable > | < variable >
< thf_typed_variable > : : = < variable > : < thf_top_level_type >
<thf_variable> ::= <thf_typed_variable> | <variable>
<thf_typed_variable> ::= <variable> : <thf_top_level_type> -}
thfVariable :: CharParser st THFVariable
thfVariable = do
v <- try (variable << colon)
tlt <- thfTopLevelType
return $ TV_THF_Typed_Variable v tlt
<|> fmap TV_Variable variable
{- THF0:
<thf_typed_const> ::= <constant> : <thf_top_level_type> |
(<thf_typed_const>) -}
thfTypedConst :: CharParser st THFTypedConst -- added this for thf0
thfTypedConst = fmap T0TC_THF_TypedConst_Par (parentheses thfTypedConst)
<|> do
c <- try (constant << colon)
tlt <- thfTopLevelType
return $ T0TC_Typed_Const c tlt
thfUnaryFormula :: CharParser st THFUnitaryFormula
thfUnaryFormula = do
uc <- thfUnaryConnective
lf <- parentheses thfLogicFormula
return $ TUF_THF_Unary_Formula uc lf
THF :
< thf_type_formula > : : = < thf_typeable_formula > : < thf_top_level_type >
< thf_type_formula > : = = < constant > : < thf_top_level_type >
<thf_type_formula> ::= <thf_typeable_formula> : <thf_top_level_type>
<thf_type_formula> :== <constant> : <thf_top_level_type> -}
thfTypeFormula :: CharParser st THFTypeFormula
thfTypeFormula = do
tp <- try (thfTypeableFormula << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Type_Formula tp tlt
<|> do
c <- try (constant << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Typed_Const c tlt
THF :
< thf_typeable_formula > : : = < thf_atom > | < thf_tuple > | ( < thf_logic_formula > )
<thf_typeable_formula> ::= <thf_atom> | <thf_tuple> | (<thf_logic_formula>) -}
thfTypeableFormula :: CharParser st THFTypeableFormula
thfTypeableFormula = fmap TTyF_THF_Atom thfAtom
<|> fmap TTyF_THF_Tuple thfTuple
<|> fmap TTyF_THF_Logic_Formula (parentheses thfLogicFormula)
THF :
< thf_subtype > : : = < constant > < subtype_sign > < constant >
< subtype_sign > = = < <
<thf_subtype> ::= <constant> <subtype_sign> <constant>
<subtype_sign> == << -}
thfSubType :: CharParser st THFSubType
thfSubType = do
cf <- try (constant << key (string "<<"))
cb <- constant
return $ TST_THF_Sub_Type cf cb
THF :
< thf_top_level_type > : : = < thf_logic_formula >
THF0 :
< thf_top_level_type > : : = < constant > | < variable > | < defined_type > |
< system_type > | < thf_binary_type >
<thf_top_level_type> ::= <thf_logic_formula>
THF0:
<thf_top_level_type> ::= <constant> | <variable> | <defined_type> |
<system_type> | <thf_binary_type> -}
thfTopLevelType :: CharParser st THFTopLevelType
thfTopLevelType = fmap T0TLT_THF_Binary_Type thfBinaryType
<|> fmap T0TLT_Constant constant
<|> fmap T0TLT_Variable variable
<|> fmap T0TLT_Defined_Type definedType
<|> fmap T0TLT_System_Type systemType
<|> fmap TTLT_THF_Logic_Formula thfLogicFormula
-- added all except for this for thf0
THF :
< thf_unitary_type > : : = < thf_unitary_formula >
THF0 :
< thf_unitary_type > : : = < constant > | < variable > | < defined_type > |
< system_type > | ( < thf_binary_type > )
<thf_unitary_type> ::= <thf_unitary_formula>
THF0:
<thf_unitary_type> ::= <constant> | <variable> | <defined_type> |
<system_type> | (<thf_binary_type>) -}
thfUnitaryType :: CharParser st THFUnitaryType
thfUnitaryType = fmap T0UT_Constant constant
<|> fmap T0UT_Variable variable
<|> fmap T0UT_Defined_Type definedType
<|> fmap T0UT_System_Type systemType
<|> fmap T0UT_THF_Binary_Type_Par (parentheses thfBinaryType)
<|> fmap TUT_THF_Unitary_Formula thfUnitaryFormula
added all except for this for
THF :
< thf_binary_type > : : = < thf_mapping_type > | < thf_xprod_type > |
< thf_union_type >
< thf_xprod_type > : : = < thf_unitary_type > < star > < thf_unitary_type > |
< thf_xprod_type > < star > < thf_unitary_type >
< star > : : - *
< thf_union_type > : : = < thf_unitary_type > < plus > < thf_unitary_type > |
< thf_union_type > < plus > < thf_unitary_type >
< plus > : : - +
THF0 :
< thf_binary_type > : : = < thf_mapping_type > | ( < thf_binary_type > )
THF & THF0 :
< thf_mapping_type > : : = < thf_unitary_type > < arrow > < thf_unitary_type > |
< thf_unitary_type > < arrow > < thf_mapping_type >
< arrow > : : - >
<thf_binary_type> ::= <thf_mapping_type> | <thf_xprod_type> |
<thf_union_type>
<thf_xprod_type> ::= <thf_unitary_type> <star> <thf_unitary_type> |
<thf_xprod_type> <star> <thf_unitary_type>
<star> ::- *
<thf_union_type> ::= <thf_unitary_type> <plus> <thf_unitary_type> |
<thf_union_type> <plus> <thf_unitary_type>
<plus> ::- +
THF0:
<thf_binary_type> ::= <thf_mapping_type> | (<thf_binary_type>)
THF & THF0:
<thf_mapping_type> ::= <thf_unitary_type> <arrow> <thf_unitary_type> |
<thf_unitary_type> <arrow> <thf_mapping_type>
<arrow> ::- > -}
thfBinaryType :: CharParser st THFBinaryType
thfBinaryType = do
utf <- try (thfUnitaryType << arrow)
utb <- sepBy1 thfUnitaryType arrow
return $ TBT_THF_Mapping_Type (utf : utb)
<|> fmap T0BT_THF_Binary_Type_Par (parentheses thfBinaryType)
-- added this for thf0
<|> do -- xprodType
utf <- try (thfUnitaryType << star)
utb <- sepBy1 thfUnitaryType star
return $ TBT_THF_Xprod_Type (utf : utb)
<|> do -- unionType
utf <- try (thfUnitaryType << plus)
utb <- sepBy1 thfUnitaryType plus
return $ TBT_THF_Union_Type (utf : utb)
THF :
< thf_atom > : : = < term > | < thf_conn_term >
% ----<thf_atom > can also be < defined_type > | < defined_plain_formula > |
% ----<system_type > | < system_atomic_formula > , but they are syntactically
% ----captured by < term > .
< system_atomic_formula > : : = < system_term >
THF0 :
< thf_atom > : : = < constant > | < defined_constant > |
< system_constant > | < variable > | < thf_conn_term >
< defined_constant > : : = < atomic_defined_word >
< system_constant > : : = < atomic_system_word >
<thf_atom> ::= <term> | <thf_conn_term>
%----<thf_atom> can also be <defined_type> | <defined_plain_formula> |
%----<system_type> | <system_atomic_formula>, but they are syntactically
%----captured by <term>.
<system_atomic_formula> ::= <system_term>
THF0:
<thf_atom> ::= <constant> | <defined_constant> |
<system_constant> | <variable> | <thf_conn_term>
<defined_constant> ::= <atomic_defined_word>
<system_constant> ::= <atomic_system_word> -}
thfAtom :: CharParser st THFAtom
thfAtom = fmap T0A_Constant constant
<|> fmap T0A_Defined_Constant atomicDefinedWord
<|> fmap T0A_System_Constant atomicSystemWord
<|> fmap T0A_Variable variable
-- added all above for thf0
<|> fmap TA_THF_Conn_Term thfConnTerm
-- changed position to prefer thf0
<|> fmap TA_Defined_Type definedType
<|> fmap TA_Defined_Plain_Formula definedPlainFormula
<|> fmap TA_System_Type systemType
<|> fmap TA_System_Atomic_Formula systemTerm
<|> fmap TA_Term term
THF :
< thf_tuple > : : = [ ] | [ < thf_tuple_list > ]
< thf_tuple_list > : : = < thf_logic_formula > |
< thf_logic_formula>,<thf_tuple_list >
THFTupleList must not be empty
<thf_tuple> ::= [] | [<thf_tuple_list>]
<thf_tuple_list> ::= <thf_logic_formula> |
<thf_logic_formula>,<thf_tuple_list>
THFTupleList must not be empty -}
thfTuple :: CharParser st THFTuple
thfTuple = try ((oBracket >> cBracket) >> return [])
<|> brackets (sepBy1 thfLogicFormula comma)
THF :
< thf_sequent > : : = < thf_tuple > < gentzen_arrow > < thf_tuple > |
( < thf_sequent > )
< gentzen_arrow > : : = -- >
<thf_sequent> ::= <thf_tuple> <gentzen_arrow> <thf_tuple> |
(<thf_sequent>)
<gentzen_arrow> ::= --> -}
thfSequent :: CharParser st THFSequent
thfSequent = fmap TS_THF_Sequent_Par (parentheses thfSequent)
<|> do
tf <- try (thfTuple << gentzenArrow)
tb <- thfTuple
return $ TS_THF_Sequent tf tb
THF :
< thf_conn_term > : : = < thf_pair_connective > | < assoc_connective > |
< thf_unary_connective >
THF0 :
< thf_conn_term > : : = < thf_quantifier > | < thf_pair_connective > |
< assoc_connective > | < thf_unary_connective >
<thf_conn_term> ::= <thf_pair_connective> | <assoc_connective> |
<thf_unary_connective>
THF0:
<thf_conn_term> ::= <thf_quantifier> | <thf_pair_connective> |
<assoc_connective> | <thf_unary_connective> -}
thfConnTerm :: CharParser st THFConnTerm
thfConnTerm = fmap TCT_THF_Pair_Connective thfPairConnective
<|> fmap TCT_Assoc_Connective assocConnective
<|> fmap TCT_THF_Unary_Connective thfUnaryConnective
<|> fmap T0CT_THF_Quantifier thfQuantifier
-- added for thf0
THF :
< thf_quantifier > : : = < fol_quantifier > | ^ | ! > | ? * | @+ | @-
< fol_quantifier > : : = ! | ?
THF0 :
< thf_quantifier > : : = ! ! | ? ?
<thf_quantifier> ::= <fol_quantifier> | ^ | !> | ?* | @+ | @-
<fol_quantifier> ::= ! | ?
THF0:
<thf_quantifier> ::= !! | ?? -}
thfQuantifier :: CharParser st THFQuantifier
thfQuantifier = (key (tryString "!!") >> return T0Q_PiForAll)
<|> (key (tryString "??") >> return T0Q_SigmaExists)
-- added all above for thf0
<|> (keyChar '!' >> return TQ_ForAll)
<|> (keyChar '?' >> return TQ_Exists)
<|> (keyChar '^' >> return TQ_Lambda_Binder)
<|> (key (tryString "!>") >> return TQ_Dependent_Product)
<|> (key (tryString "?*") >> return TQ_Dependent_Sum)
<|> (key (tryString "@+") >> return TQ_Indefinite_Description)
<|> (key (tryString "@-") >> return TQ_Definite_Description)
<?> "thfQuantifier"
{- THF0:
<quantifier> ::= ! | ? -}
quantifier :: CharParser st Quantifier
quantifier = (keyChar '!' >> return T0Q_ForAll)
<|> (keyChar '?' >> return T0Q_Exists)
<?> "quantifier"
THF :
< thf_pair_connective > : : = < infix_equality > | < infix_inequality > |
< binary_connective >
< infix_equality > : : = =
< infix_inequality > : : = ! =
THF0 :
< thf_pair_connective > : : = < defined_infix_pred > | < binary_connective >
< defined_infix_pred > : : = = | ! =
THF & THF0 :
< binary_connective > : : = < = > | = > | < = | < ~ > | ~<vline > | ~ &
<thf_pair_connective> ::= <infix_equality> | <infix_inequality> |
<binary_connective>
<infix_equality> ::= =
<infix_inequality> ::= !=
THF0:
<thf_pair_connective> ::= <defined_infix_pred> | <binary_connective>
<defined_infix_pred> ::= = | !=
THF & THF0:
<binary_connective> ::= <=> | => | <= | <~> | ~<vline> | ~& -}
thfPairConnective :: CharParser st THFPairConnective
thfPairConnective = (key (tryString "!=") >> return Infix_Inequality)
<|> (key (tryString "<=>") >> return Equivalent)
<|> (key (tryString "=>") >> return Implication)
<|> (key (tryString "<=") >> return IF)
<|> (key (tryString "<~>") >> return XOR)
<|> (key (tryString "~|") >> return NOR)
<|> (key (tryString "~&") >> return NAND)
<|> (keyChar '=' >> return Infix_Equality)
<?> "pairConnective"
THF :
< thf_unary_connective > : : = < unary_connective > | ! ! | ? ?
THF0 :
< thf_unary_connective > : : = < unary_connective >
THF & THF0 :
< unary_connective > : : = ~
<thf_unary_connective> ::= <unary_connective> | !! | ??
THF0:
<thf_unary_connective> ::= <unary_connective>
THF & THF0:
<unary_connective> ::= ~ -}
thfUnaryConnective :: CharParser st THFUnaryConnective
thfUnaryConnective = (keyChar '~' >> return Negation)
<|> (key (tryString "!!") >> return PiForAll)
<|> (key (tryString "??") >> return SigmaExists)
THF & THF0 :
< assoc_connective > : : = < vline > | &
<assoc_connective> ::= <vline> | & -}
assocConnective :: CharParser st AssocConnective
assocConnective = (keyChar '|' >> return OR)
<|> (keyChar '&' >> return AND)
THF :
< defined_type > : = = $ oType | $ o | $ iType | $ i | $ tType |
real | $ rat | $ int
THF0 :
< defined_type > : = = $ oType | $ o | $ iType | $ i | THF & THF0 :
< defined_type > : : = < atomic_defined_word >
<defined_type> :== $oType | $o | $iType | $i | $tType |
real | $rat | $int
THF0:
<defined_type> :== $oType | $o | $iType | $i | $tType
THF & THF0:
<defined_type> ::= <atomic_defined_word> -}
definedType :: CharParser st DefinedType
definedType = do
adw <- atomicDefinedWord
case show adw of
"oType" -> return DT_oType
"o" -> return DT_o
"iType" -> return DT_iType
"i" -> return DT_i
"tType" -> return DT_tType
"real" -> return DT_real
"rat" -> return DT_rat
"int" -> return DT_int
s -> Fail.fail ("No such definedType: " ++ s)
THF & THF0 :
< system_type > : : = < atomic_system_word >
<system_type> ::= <atomic_system_word> -}
systemType :: CharParser st Token
systemType = atomicSystemWord
THF :
< defined_plain_formula > : : = < defined_plain_term >
< defined_plain_formula > : = = < defined_prop > | < defined_pred>(<arguments > )
<defined_plain_formula> ::= <defined_plain_term>
<defined_plain_formula> :== <defined_prop> | <defined_pred>(<arguments>) -}
definedPlainFormula :: CharParser st DefinedPlainFormula
definedPlainFormula = fmap DPF_Defined_Prop definedProp
<|> do
dp <- definedPred
a <- parentheses arguments
return $ DPF_Defined_Formula dp a
THF & THF0 :
< defined_prop > : = = < atomic_defined_word >
< defined_prop > : = = $ true | $ false
<defined_prop> :== <atomic_defined_word>
<defined_prop> :== $true | $false -}
definedProp :: CharParser st DefinedProp
definedProp = do
adw <- atomicDefinedWord
case show adw of
"true" -> return DP_True
"false" -> return DP_False
s -> Fail.fail ("No such definedProp: " ++ s)
THF :
< defined_pred > : = = < atomic_defined_word >
< defined_pred > : = = $ distinct |
less | $ lesseq | $ greater | $ greatereq |
is_int | $ is_rat
<defined_pred> :== <atomic_defined_word>
<defined_pred> :== $distinct |
less | $lesseq | $greater | $greatereq |
is_int | $is_rat -}
definedPred :: CharParser st DefinedPred
definedPred = do
adw <- atomicDefinedWord
case show adw of
"distinct" -> return Disrinct
"less" -> return Less
"lesseq" -> return Lesseq
"greater" -> return Greater
"greatereq" -> return Greatereq
"is_int" -> return Is_int
"is_rat" -> return Is_rat
s -> Fail.fail ("No such definedPred: " ++ s)
THF :
< term > : : = < function_term > | < variable > | < conditional_term >
% ----Conditional terms should only be used by TFF and not by THF .
Thus tey are not implemented .
<term> ::= <function_term> | <variable> | <conditional_term>
%----Conditional terms should only be used by TFF and not by THF.
Thus tey are not implemented. -}
term :: CharParser st Term
term = fmap T_Function_Term functionTerm
<|> fmap T_Variable variable
THF :
< function_term > : : = < plain_term > | < defined_term > | < system_term >
<function_term> ::= <plain_term> | <defined_term> | <system_term> -}
functionTerm :: CharParser st FunctionTerm
functionTerm = fmap FT_System_Term systemTerm
<|> fmap FT_Defined_Term definedTerm
<|> fmap FT_Plain_Term plainTerm
THF :
< plain_term > : : = < constant > | < functor>(<arguments > )
<plain_term> ::= <constant> | <functor>(<arguments>) -}
plainTerm :: CharParser st PlainTerm
plainTerm = try (do
f <- tptpFunctor
a <- parentheses arguments
return $ PT_Plain_Term f a)
<|> fmap PT_Constant constant
THF & THF0 :
< constant > : : = < functor >
<constant> ::= <functor> -}
constant :: CharParser st Constant
constant = tptpFunctor
THF & THF0 :
< functor > : : = < atomic_word >
<functor> ::= <atomic_word> -}
tptpFunctor :: CharParser st AtomicWord
tptpFunctor = atomicWord
THF :
< defined_term > : : = < defined_atom > | < defined_atomic_term >
< defined_atomic_term > : : = < defined_plain_term >
<defined_term> ::= <defined_atom> | <defined_atomic_term>
<defined_atomic_term> ::= <defined_plain_term> -}
definedTerm :: CharParser st DefinedTerm
definedTerm = fmap DT_Defined_Atomic_Term definedPlainTerm
<|> fmap DT_Defined_Atom definedAtom
THF :
< defined_atom > : : = < number > | < distinct_object >
<defined_atom> ::= <number> | <distinct_object> -}
definedAtom :: CharParser st DefinedAtom
definedAtom = fmap DA_Number number
<|> fmap DA_Distinct_Object distinctObject
THF :
< defined_plain_term > : : = < defined_constant > | < defined_functor>(<arguments > )
< defined_constant > : : = < defined_functor >
<defined_plain_term> ::= <defined_constant> | <defined_functor>(<arguments>)
<defined_constant> ::= <defined_functor> -}
definedPlainTerm :: CharParser st DefinedPlainTerm
definedPlainTerm = try (do
df <- definedFunctor
a <- parentheses arguments
return $ DPT_Defined_Function df a)
<|> fmap DPT_Defined_Constant definedFunctor
THF :
< defined_functor > : : = < atomic_defined_word >
< defined_functor > : = = $ uminus | $ sum | $ difference | $ product |
quotient | $ quotient_e | $ quotient_t | $ quotient_f |
remainder_e | $ remainder_t | $ remainder_f |
floor | $ ceiling | $ truncate | $ round |
to_int | $ to_rat | $ to_real
<defined_functor> ::= <atomic_defined_word>
<defined_functor> :== $uminus | $sum | $difference | $product |
quotient | $quotient_e | $quotient_t | $quotient_f |
remainder_e | $remainder_t | $remainder_f |
floor | $ceiling | $truncate | $round |
to_int | $to_rat | $to_real -}
definedFunctor :: CharParser st DefinedFunctor
definedFunctor = do
adw <- atomicDefinedWord
case show adw of
"uminus" -> return UMinus
"sum" -> return Sum
"difference" -> return Difference
"product" -> return Product
"quotient" -> return Quotient
"quotient_e" -> return Quotient_e
"quotient_t" -> return Quotient_t
"quotient_f" -> return Quotient_f
"floor" -> return Floor
"ceiling" -> return Ceiling
"truncate" -> return Truncate
"round" -> return Round
"to_int" -> return To_int
"to_rat" -> return To_rat
"to_real" -> return To_real
s -> Fail.fail ("No such definedFunctor: " ++ s)
THF :
< system_term > : : = < system_constant > | < system_functor>(<arguments > )
< system_constant > : : = < system_functor >
<system_term> ::= <system_constant> | <system_functor>(<arguments>)
<system_constant> ::= <system_functor> -}
systemTerm :: CharParser st SystemTerm
systemTerm = try (do
sf <- systemFunctor
a <- parentheses arguments
return $ ST_System_Term sf a)
<|> fmap ST_System_Constant systemFunctor
THF :
< system_functor > : : = < atomic_system_word >
<system_functor> ::= <atomic_system_word> -}
systemFunctor :: CharParser st Token
systemFunctor = atomicSystemWord
THF & THF0 :
< variable > : : = < upper_word >
<variable> ::= <upper_word> -}
variable :: CharParser st Token
variable = parseToken
(do
u <- upper
an <- many (alphaNum <|> char '_')
skipAll
return (u : an)
<?> "Variable")
THF :
< arguments > : : = < term > | < term>,<arguments >
at least one term is neaded
<arguments> ::= <term> | <term>,<arguments>
at least one term is neaded -}
arguments :: CharParser st Arguments
arguments = sepBy1 term comma
THF & THF0 :
< principal_symbol > : = = < functor > | < variable >
<principal_symbol> :== <functor> | <variable> -}
principalSymbol :: CharParser st PrincipalSymbol
principalSymbol = fmap PS_Functor tptpFunctor
<|> fmap PS_Variable variable
THF & THF0 :
< source > : : = < general_term >
< source > : = = < dag_source > | < internal_source > | < external_source > |
unknown | [ < sources > ]
< internal_source > : = = introduced(<intro_type><optional_info > )
< sources > : = = < source > | < source>,<sources >
<source> ::= <general_term>
<source> :== <dag_source> | <internal_source> | <external_source> |
unknown | [<sources>]
<internal_source> :== introduced(<intro_type><optional_info>)
<sources> :== <source> | <source>,<sources> -}
source :: CharParser st Source
source = (key (tryString "unknown") >> return S_Unknown)
<|> fmap S_Dag_Source dagSource
<|> fmap S_External_Source externalSource
<|> fmap S_Sources (sepBy1 source comma)
internal_source
key $ tryString "introduced"
oParentheses
it <- introType
oi <- optionalInfo
cParentheses
return $ S_Internal_Source it oi
THF & THF0 :
< dag_source > : = = < name > | < inference_record >
< inference_record > : = = > ,
[ < parent_list > ] )
< inference_rule > : = = < atomic_word >
< parent_list > : = = < parent_info > | < parent_info>,<parent_list >
<dag_source> :== <name> | <inference_record>
<inference_record> :== inference(<inference_rule>,<useful_info>,
[<parent_list>])
<inference_rule> :== <atomic_word>
<parent_list> :== <parent_info> | <parent_info>,<parent_list> -}
dagSource :: CharParser st DagSource
dagSource = do
key (tryString "inference")
oParentheses
ir <- atomicWord
comma
ui <- usefulInfo
comma
pl <- brackets (sepBy1 parentInfo comma)
cParentheses
return (DS_Inference_Record ir ui pl)
<|> fmap DS_Name name
THF & THF0 :
< parent_info > : = = < source><parent_details >
< parent_details > : = = : < general_list > | < null >
<parent_info> :== <source><parent_details>
<parent_details> :== :<general_list> | <null> -}
parentInfo :: CharParser st ParentInfo
parentInfo = do
s <- source
pd <- parentDetails
return $ PI_Parent_Info s pd
parentDetails :: CharParser st (Maybe GeneralList)
parentDetails = fmap Just (colon >> generalList)
<|> (notFollowedBy (char ':') >> return Nothing)
THF & THF0 :
< intro_type > : = = definition | axiom_of_choice | tautology | assumption
<intro_type> :== definition | axiom_of_choice | tautology | assumption -}
introType :: CharParser st IntroType
introType = (key (tryString "definition") >> return IT_definition)
<|> (key (tryString "axiom_of_choice") >> return IT_axiom_of_choice)
<|> (key (tryString "tautology") >> return IT_tautology)
<|> (key (tryString "assumption") >> return IT_assumption)
THF & THF0 :
< external_source > : = = < file_source > | < theory > | < creator_source >
< theory > : = = theory(<theory_name><optional_info > )
< creator_source > : = = creator(<creator_name><optional_info > )
< creator_name > : = = < atomic_word >
<external_source> :== <file_source> | <theory> | <creator_source>
<theory> :== theory(<theory_name><optional_info>)
<creator_source> :== creator(<creator_name><optional_info>)
<creator_name> :== <atomic_word> -}
externalSource :: CharParser st ExternalSource
externalSource = fmap ES_File_Source fileSource
<|> do
key $ tryString "theory"
oParentheses
tn <- theoryName
oi <- optionalInfo
cParentheses
return $ ES_Theory tn oi
<|> do
key $ tryString "creator"
oParentheses
cn <- atomicWord
oi <- optionalInfo
cParentheses
return $ ES_Creator_Source cn oi
THF & THF0 :
< file_source > : = = > )
< file_info > : = = , < name > | < null >
<file_source> :== file(<file_name><file_info>)
<file_info> :== ,<name> | <null> -}
fileSource :: CharParser st FileSource
fileSource = do
key $ tryString "file"
oParentheses
fn <- fileName
fi <- fileInfo
cParentheses
return $ FS_File fn fi
fileInfo :: CharParser st (Maybe Name)
fileInfo = fmap Just (comma >> name)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< theory_name > : = = equality | ac
<theory_name> :== equality | ac -}
theoryName :: CharParser st TheoryName
theoryName = (key (tryString "equality") >> return Equality)
<|> (key (tryString "ac") >> return Ac)
THF & THF0 :
< optional_info > : : = , < useful_info > | < null >
<optional_info> ::= ,<useful_info> | <null> -}
optionalInfo :: CharParser st OptionalInfo
optionalInfo = fmap Just (comma >> usefulInfo)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< useful_info > : : = < general_list >
< useful_info > : = = [ ] | [ < info_items > ]
< info_items > : = = < info_item > | < info_item>,<info_items >
<useful_info> ::= <general_list>
<useful_info> :== [] | [<info_items>]
<info_items> :== <info_item> | <info_item>,<info_items> -}
usefulInfo :: CharParser st UsefulInfo
usefulInfo = (oBracket >> cBracket >> return [])
<|> brackets (sepBy1 infoItem comma)
THF & THF0 :
< info_item > : = = < formula_item > | < inference_item > |
< general_function >
<info_item> :== <formula_item> | <inference_item> |
<general_function> -}
infoItem :: CharParser st InfoItem
infoItem = fmap II_Formula_Item formulaItem
<|> fmap II_Inference_Item inferenceItem
<|> fmap II_General_Function generalFunction
THF & THF0 :
< formula_item > : = = < description_item > | < iquote_item >
< description_item > : = = description(<atomic_word > )
< iquote_item > : = = iquote(<atomic_word > )
<formula_item> :== <description_item> | <iquote_item>
<description_item> :== description(<atomic_word>)
<iquote_item> :== iquote(<atomic_word>) -}
formulaItem :: CharParser st FormulaItem
formulaItem = do
key $ tryString "description"
fmap FI_Description_Item (parentheses atomicWord)
<|> do
key $ tryString "iquote"
fmap FI_Iquote_Item (parentheses atomicWord)
THF & THF0 :
< inference_item > : = = < inference_status > | < assumptions_record > |
< new_symbol_record > | < refutation >
< assumptions_record > : = = assumptions([<name_list > ] )
< refutation > : = = refutation(<file_source > )
< new_symbol_record > : = = new_symbols(<atomic_word>,[<new_symbol_list > ] )
< new_symbol_list > : = = < principal_symbol > |
< principal_symbol>,<new_symbol_list >
<inference_item> :== <inference_status> | <assumptions_record> |
<new_symbol_record> | <refutation>
<assumptions_record> :== assumptions([<name_list>])
<refutation> :== refutation(<file_source>)
<new_symbol_record> :== new_symbols(<atomic_word>,[<new_symbol_list>])
<new_symbol_list> :== <principal_symbol> |
<principal_symbol>,<new_symbol_list> -}
inferenceItem :: CharParser st InferenceItem
inferenceItem = fmap II_Inference_Status inferenceStatus
<|> do
key $ tryString "assumptions"
fmap II_Assumptions_Record (parentheses (brackets nameList))
<|> do
key $ tryString "new_symbols"
oParentheses
aw <- atomicWord
comma
nsl <- brackets (sepBy1 principalSymbol comma)
cParentheses
return $ II_New_Symbol_Record aw nsl
<|> do
key $ tryString "refutation"
fmap II_Refutation (parentheses fileSource)
THF & THF0 :
< inference_status > : = = status(<status_value > ) | < inference_info >
< inference_info > : = = < inference_rule>(<atomic_word>,<general_list > )
< inference_rule > : = = < atomic_word >
<inference_status> :== status(<status_value>) | <inference_info>
<inference_info> :== <inference_rule>(<atomic_word>,<general_list>)
<inference_rule> :== <atomic_word> -}
inferenceStatus :: CharParser st InferenceStatus
inferenceStatus = do
key $ tryString "status"
fmap IS_Status (parentheses statusValue)
<|> do
ir <- try (atomicWord << oParentheses)
aw <- atomicWord
comma
gl <- generalList
cParentheses
return $ IS_Inference_Info ir aw gl
THF & THF0 :
< status_value > : = = suc | unp | sap | esa | sat | fsa | thm | eqv | tac |
wec | eth | tau | wtc | wth | cax | sca | tca | wca |
cup | csp | ecs | csa | cth | ceq | unc | wcc | ect |
fun | uns | wuc | wct | scc | uca | noc
<status_value> :== suc | unp | sap | esa | sat | fsa | thm | eqv | tac |
wec | eth | tau | wtc | wth | cax | sca | tca | wca |
cup | csp | ecs | csa | cth | ceq | unc | wcc | ect |
fun | uns | wuc | wct | scc | uca | noc -}
statusValue :: CharParser st StatusValue
statusValue = choice $ map (\ r -> key (tryString $ showStatusValue r)
>> return r) allStatusValues
allStatusValues :: [StatusValue]
allStatusValues =
[Suc, Unp, Sap, Esa, Sat, Fsa, Thm, Eqv, Tac,
Wec, Eth, Tau, Wtc, Wth, Cax, Sca, Tca, Wca,
Cup, Csp, Ecs, Csa, Cth, Ceq, Unc, Wcc, Ect,
Fun, Uns, Wuc, Wct, Scc, Uca, Noc]
showStatusValue :: StatusValue -> String
showStatusValue = map toLower . show
formulaSelection :: CharParser st (Maybe NameList)
formulaSelection = fmap Just (comma >> brackets nameList)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< name_list > : : = < name > | < name>,<name_list >
the list must mot be empty
<name_list> ::= <name> | <name>,<name_list>
the list must mot be empty -}
nameList :: CharParser st NameList
nameList = sepBy1 name comma
THF & THF0 :
< general_term > : : = < general_data > | < general_data>:<general_term > |
< general_list >
<general_term> ::= <general_data> | <general_data>:<general_term> |
<general_list> -}
generalTerm :: CharParser st GeneralTerm
generalTerm = do
gd <- try (generalData << notFollowedBy (char ':'))
return $ GT_General_Data gd
<|> do
gd <- try (generalData << colon)
gt <- generalTerm
return $ GT_General_Data_Term gd gt
<|> fmap GT_General_List generalList
THF & THF0 :
< general_data > : : = < atomic_word > | < general_function > |
< variable > | < number > | < distinct_object > |
< formula_data >
< general_data > : = = bind(<variable>,<formula_data > )
<general_data> ::= <atomic_word> | <general_function> |
<variable> | <number> | <distinct_object> |
<formula_data>
<general_data> :== bind(<variable>,<formula_data>) -}
generalData :: CharParser st GeneralData
generalData = fmap GD_Variable variable
<|> fmap GD_Number number
<|> fmap GD_Distinct_Object distinctObject
<|> do
key $ tryString "bind"
oParentheses
v <- variable
comma
fd <- formulaData
cParentheses
return (GD_Bind v fd)
<|> fmap GD_General_Function generalFunction
<|> fmap GD_Atomic_Word atomicWord
<|> fmap GD_Formula_Data formulaData
THF & THF0 :
< general_function > : : = < atomic_word>(<general_terms > )
general_terms must not be empty
<general_function> ::= <atomic_word>(<general_terms>)
general_terms must not be empty -}
generalFunction :: CharParser st GeneralFunction
generalFunction = do
aw <- atomicWord
gts <- parentheses generalTerms
return $ GF_General_Function aw gts
THF & THF0 :
< formula_data > : : = $ thf(<thf_formula > ) | $ tff(<tff_formula > ) |
fof(<fof_formula > ) | $ cnf(<cnf_formula > ) |
fot(<term > )
only thf is used here
<formula_data> ::= $thf(<thf_formula>) | $tff(<tff_formula>) |
fof(<fof_formula>) | $cnf(<cnf_formula>) |
fot(<term>)
only thf is used here -}
formulaData :: CharParser st FormulaData
formulaData = fmap THF_Formula thfFormula
THF & THF0 :
< general_list > : : = [ ] | [ < general_terms > ]
<general_list> ::= [] | [<general_terms>] -}
generalList :: CharParser st GeneralList
generalList = (try (oBracket >> cBracket) >> return [])
<|> brackets generalTerms
THF & THF0 :
< general_terms > : : = < general_term > | < general_term>,<general_terms >
<general_terms> ::= <general_term> | <general_term>,<general_terms> -}
generalTerms :: CharParser st [GeneralTerm]
generalTerms = sepBy1 generalTerm comma
THF :
< name > : : = < atomic_word > | < integer >
THF0 :
< name > : : = < atomic_word > | < unsigned_integer >
<name> ::= <atomic_word> | <integer>
THF0:
<name> ::= <atomic_word> | <unsigned_integer> -}
name :: CharParser st Name
name = fmap T0N_Unsigned_Integer (parseToken (unsignedInteger << skipAll))
-- added for thf0
<|> fmap N_Integer (integer << skipAll)
<|> fmap N_Atomic_Word atomicWord
THF & THF0 :
< atomic_word > : : = < lower_word > | < single_quoted >
<atomic_word> ::= <lower_word> | <single_quoted> -}
atomicWord :: CharParser st AtomicWord
atomicWord = fmap A_Lower_Word lowerWord
<|> fmap A_Single_Quoted singleQuoted
<?> "lowerWord or singleQuoted"
THF & THF0 :
< atomic_defined_word > : : = < dollar_word >
<atomic_defined_word> ::= <dollar_word> -}
atomicDefinedWord :: CharParser st Token
atomicDefinedWord = char '$' >> lowerWord
THF & THF0 :
< atomic_system_word > : : = < dollar_dollar_word >
< dollar_dollar_word > : : - < dollar><dollar><lower_word >
< dollar > : : : [ $ ]
<atomic_system_word> ::= <dollar_dollar_word>
<dollar_dollar_word> ::- <dollar><dollar><lower_word>
<dollar> ::: [$] -}
atomicSystemWord :: CharParser st Token
atomicSystemWord = tryString "$$" >> lowerWord
THF & THF0 :
< number > : : = < integer > | < rational > | < real >
< real > : : - ( < signed_real>|<unsigned_real > )
< signed_real > : : - < sign><unsigned_real >
< unsigned_real > : : - ( < decimal_fraction>|<decimal_exponent > )
< rational > : : - ( < signed_rational>|<unsigned_rational > )
< signed_rational > : : - < sign><unsigned_rational >
< unsigned_rational > : : - < decimal><slash><positive_decimal >
< integer > : : - ( < signed_integer>|<unsigned_integer > )
< signed_integer > : : - < sign><unsigned_integer >
< unsigned_integer > : : - < decimal >
< decimal > : : - ( < zero_numeric>|<positive_decimal > )
< positive_decimal > : : - < non_zero_numeric><numeric > *
< decimal_exponent > : : - ( < decimal>|<decimal_fraction>)<exponent><decimal >
< decimal_fraction > : : - < decimal><dot_decimal >
< dot_decimal > : : - < dot><numeric><numeric > *
< sign > : : : [ + - ]
< dot > : : : [ . ]
< exponent > : : : [ Ee ]
< slash > : : : [ / ]
< zero_numeric > : : : [ 0 ]
< : : : [ 1 - 9 ]
< numeric > : : : [ 0 - 9 ]
<number> ::= <integer> | <rational> | <real>
<real> ::- (<signed_real>|<unsigned_real>)
<signed_real> ::- <sign><unsigned_real>
<unsigned_real> ::- (<decimal_fraction>|<decimal_exponent>)
<rational> ::- (<signed_rational>|<unsigned_rational>)
<signed_rational> ::- <sign><unsigned_rational>
<unsigned_rational> ::- <decimal><slash><positive_decimal>
<integer> ::- (<signed_integer>|<unsigned_integer>)
<signed_integer> ::- <sign><unsigned_integer>
<unsigned_integer> ::- <decimal>
<decimal> ::- (<zero_numeric>|<positive_decimal>)
<positive_decimal> ::- <non_zero_numeric><numeric>*
<decimal_exponent> ::- (<decimal>|<decimal_fraction>)<exponent><decimal>
<decimal_fraction> ::- <decimal><dot_decimal>
<dot_decimal> ::- <dot><numeric><numeric>*
<sign> ::: [+-]
<dot> ::: [.]
<exponent> ::: [Ee]
<slash> ::: [/]
<zero_numeric> ::: [0]
<non_zero_numeric> ::: [1-9]
<numeric> ::: [0-9] -}
number :: CharParser st Number
number = fmap Num_Real (real << skipAll)
<|> fmap Num_Rational (rational << skipAll)
<|> fmap Num_Integer (integer << skipAll)
THF & THF0 :
< file_name > : : = < single_quoted >
<file_name> ::= <single_quoted> -}
fileName :: CharParser st Token
fileName = singleQuoted
THF & THF0 :
< single_quoted > : : - < single_quote><sq_char><sq_char>*<single_quote >
< single_quote > : : : [ ' ]
< sq_char > : : : ( [ \40-\46\50-\133\135-\176]|[\\]['\\ ] )
<single_quoted> ::- <single_quote><sq_char><sq_char>*<single_quote>
<single_quote> ::: [']
<sq_char> ::: ([\40-\46\50-\133\135-\176]|[\\]['\\]) -}
singleQuoted :: CharParser st Token
singleQuoted = parseToken $ do
char '\''
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\'"
<|> tryString "\\\'"
<|> single ( satisfy (\ c -> printable c && notElem c "'\\")))
keyChar '\''
return s
THF & THF0 :
< distinct_object > : : - < double_quote><do_char>*<double_quote >
< do_char > : : : ( [ \40-\41\43-\133\135-\176]|[\\]["\\ ] )
< double_quote > : : : [ " ]
<distinct_object> ::- <double_quote><do_char>*<double_quote>
<do_char> ::: ([\40-\41\43-\133\135-\176]|[\\]["\\])
<double_quote> ::: ["] -}
distinctObject :: CharParser st Token
distinctObject = parseToken $ do
char '\"'
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\\""
<|> single ( satisfy (\ c -> printable c && notElem c "\"\\")))
keyChar '\"'
return s
THF & THF0 :
< lower_word > : : - < lower_alpha><alpha_numeric > *
< alpha_numeric > : : : ( < lower_alpha>|<upper_alpha>|<numeric>| [ _ ] )
< lower_alpha > : : : [ a - z ]
< upper_alpha > : : : [ A - Z ]
< numeric > : : : [ 0 - 9 ]
<lower_word> ::- <lower_alpha><alpha_numeric>*
<alpha_numeric> ::: (<lower_alpha>|<upper_alpha>|<numeric>|[_])
<lower_alpha> ::: [a-z]
<upper_alpha> ::: [A-Z]
<numeric> ::: [0-9] -}
lowerWord :: CharParser st Token
lowerWord = parseToken (do
l <- lower
an <- many (alphaNum <|> char '_')
skipAll
return (l : an)
<?> "alphanumeric word with leading lowercase letter")
printableChar :: CharParser st Char
printableChar = satisfy printable
printable :: Char -> Bool
printable c = ord c >= 32 && ord c <= 126
-- Numbers
real :: CharParser st Token
real = parseToken (try (do
s <- oneOf "-+"
ur <- unsignedReal
return (s : ur))
<|> unsignedReal
<?> "(signed) real")
unsignedReal :: CharParser st String
unsignedReal = do
de <- try (do
d <- decimalFractional <|> decimal
e <- oneOf "Ee"
return (d ++ [e]))
ex <- integer
return (de ++ (show ex))
<|> decimalFractional
<?> "unsigned real"
rational :: CharParser st Token
rational = parseToken (try (do
s <- oneOf "-+"
ur <- unsignedRational
return (s : ur))
<|> unsignedRational
<?> "(signed) rational")
unsignedRational :: CharParser st String
unsignedRational = do
d1 <- try (decimal << char '/')
d2 <- positiveDecimal
return (d1 ++ "/" ++ d2)
integer :: CharParser st Token
integer = parseToken (try (do
s <- oneOf "-+"
ui <- unsignedInteger
return (s : ui))
<|> unsignedInteger
<?> "(signed) integer")
unsignedInteger :: CharParser st String
unsignedInteger = try (decimal << notFollowedBy (oneOf "eE/."))
decimal :: CharParser st String
decimal = do
char '0'
notFollowedBy digit
return "0"
<|> positiveDecimal
<?> "single zero or digits"
positiveDecimal :: CharParser st String
positiveDecimal = do
nz <- satisfy (\ c -> isDigit c && c /= '0')
d <- many digit
return (nz : d)
<?> "positiv decimal"
decimalFractional :: CharParser st String
decimalFractional = do
dec <- try (decimal << char '.')
n <- many1 digit
return (dec ++ "." ++ n)
<?> "decimal fractional"
{- -----------------------------------------------------------------------------
Some helper functions
----------------------------------------------------------------------------- -}
skipAll :: CharParser st ()
skipAll = skipMany (skipMany1 space <|>
forget (comment <|> definedComment <|> systemComment))
skipSpaces :: CharParser st ()
skipSpaces = skipMany space
key :: CharParser st a -> CharParser st ()
key = (>> skipAll)
keyChar :: Char -> CharParser st ()
keyChar = key . char
myManyTill :: CharParser st a -> CharParser st a -> CharParser st [a]
myManyTill p end = do
e <- end
return [e]
<|> do
x <- p
xs <- myManyTill p end
return (x : xs)
{- -----------------------------------------------------------------------------
Different simple symbols
----------------------------------------------------------------------------- -}
vLine :: CharParser st ()
vLine = keyChar '|'
star :: CharParser st ()
star = keyChar '*'
plus :: CharParser st ()
plus = keyChar '+'
arrow :: CharParser st ()
arrow = keyChar '>'
comma :: CharParser st ()
comma = keyChar ','
colon :: CharParser st ()
colon = keyChar ':'
oParentheses :: CharParser st ()
oParentheses = keyChar '('
cParentheses :: CharParser st ()
cParentheses = keyChar ')'
parentheses :: CharParser st a -> CharParser st a
parentheses p = do
r <- try (oParentheses >> p)
cParentheses
return r
oBracket :: CharParser st ()
oBracket = keyChar '['
cBracket :: CharParser st ()
cBracket = keyChar ']'
brackets :: CharParser st a -> CharParser st a
brackets p = do
r <- try (oBracket >> p)
cBracket
return r
ampersand :: CharParser st ()
ampersand = keyChar '&'
at :: CharParser st ()
at = keyChar '@'
gentzenArrow :: CharParser st ()
gentzenArrow = key $ string "-->"
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/THF/ParseTHF.hs | haskell | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
--------------------------------------------------------------------------- -}
different position for unitary formula to prefer thf0 parse
different position for binary type to prefer thf0 parse
or
and
apply
added this for thf0
added this for thf0
THF0:
<thf_typed_const> ::= <constant> : <thf_top_level_type> |
(<thf_typed_const>)
added this for thf0
added all except for this for thf0
added this for thf0
xprodType
unionType
--<thf_atom > can also be < defined_type > | < defined_plain_formula > |
--<system_type > | < system_atomic_formula > , but they are syntactically
--captured by < term > .
--<thf_atom> can also be <defined_type> | <defined_plain_formula> |
--<system_type> | <system_atomic_formula>, but they are syntactically
--captured by <term>.
added all above for thf0
changed position to prefer thf0
>
> -}
added for thf0
added all above for thf0
THF0:
<quantifier> ::= ! | ?
--Conditional terms should only be used by TFF and not by THF .
--Conditional terms should only be used by TFF and not by THF.
added for thf0
Numbers
-----------------------------------------------------------------------------
Some helper functions
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Different simple symbols
----------------------------------------------------------------------------- | |
Module : ./THF / ParseTHF.hs
Description : A Parser for the TPTP - THF Syntax
Copyright : ( c ) , DFKI Bremen 2012
( c ) , DFKI Bremen 2011
License : GPLv2 or higher , see LICENSE.txt
Maintainer : < >
Stability : provisional
Portability : portable
A Parser for the TPTP - THF Input Syntax v5.4.0.0 taken from
< /~tptp/TPTP/SyntaxBNF.html > and THF0
Syntax taken from < -sb.de/~chris/papers/C25.pdf > P. 15 - 16
Note : The parser prefers a THF0 parse tree over a THF parse tree
Note : We pretend as if tuples were still part of the syntax
Module : ./THF/ParseTHF.hs
Description : A Parser for the TPTP-THF Syntax
Copyright : (c) Jonathan von Schroeder, DFKI Bremen 2012
(c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Jonathan von Schroeder <>
Stability : provisional
Portability : portable
A Parser for the TPTP-THF Input Syntax v5.4.0.0 taken from
</~tptp/TPTP/SyntaxBNF.html> and THF0
Syntax taken from <-sb.de/~chris/papers/C25.pdf> P. 15-16
Note: The parser prefers a THF0 parse tree over a THF parse tree
Note: We pretend as if tuples were still part of the syntax
-}
module THF.ParseTHF (parseTHF) where
import THF.As
import Text.ParserCombinators.Parsec
import Common.Parsec
import Common.Id (Token (..))
import Common.Lexer (parseToken)
import qualified Control.Monad.Fail as Fail
import Data.Char
import Data.Maybe
for the THF and THF0 Syntax
Parser for the THF and THF0 Syntax
THF & THF0 :
< TPTP_input > : : = < annotated_formula > | < include >
< thf_annotated > : : = thf(<name>,<formula_role>,<thf_formula><annotations > ) .
Data Type : TPTP_THF
<TPTP_input> ::= <annotated_formula> | <include>
<thf_annotated> ::= thf(<name>,<formula_role>,<thf_formula><annotations>).
Data Type: TPTP_THF -}
parseTHF :: CharParser st [TPTP_THF]
parseTHF = do
h <- optionMaybe header
thf <- many ((systemComment <|> definedComment <|> comment <|>
include <|> thfAnnotatedFormula) << skipSpaces)
return $ if isJust h then fromJust h : thf else thf
header :: CharParser st TPTP_THF
header = try (do
s <- headerSE
c <- myManyTill (try (commentLine << skipSpaces)) (try headerSE)
return $ TPTP_Header (s : c))
headerSE :: CharParser st Comment
headerSE = do
try (char '%' >> notFollowedBy (char '$'))
c <- parseToken $ many1 $ char '-' << notFollowedBy printableChar
skipSpaces
return $ Comment_Line c
THF & THF0 :
< comment > : : - < comment_line>|<comment_block >
< comment_line > : : - [ % ] < printable_char > *
< comment_block > : : : [ /][*]<not_star_slash>[*][*]*[/ ]
< not_star_slash > : : : ( [ ^*]*[*][*]*[^/*])*[^ * ] *
<comment> ::- <comment_line>|<comment_block>
<comment_line> ::- [%]<printable_char>*
<comment_block> ::: [/][*]<not_star_slash>[*][*]*[/]
<not_star_slash> ::: ([^*]*[*][*]*[^/*])*[^*]* -}
commentLine :: CharParser st Comment
commentLine = do
try (char '%' >> notFollowedBy (char '$'))
c <- parseToken $ many printableChar
return $ Comment_Line c
comment_ :: String -> CharParser st Token
comment_ start = do
try (string start >> notFollowedBy (char '$'))
c <- parseToken $ many (noneOf "*/")
skipMany1 (char '*')
char '/'
return c
comment :: CharParser st TPTP_THF
comment = fmap TPTP_Comment commentLine
<|> do
c <- comment_ "/*"
return $ TPTP_Comment (Comment_Block c)
THF & THF0 :
< defined_comment > : : - < def_comment_line>|<def_comment_block >
< def_comment_line > : : : [ % ] < dollar><printable_char > *
< def_comment_block > : : : [ /][*]<dollar><not_star_slash>[*][*]*[/ ]
Data Type : DefinedComment
<defined_comment> ::- <def_comment_line>|<def_comment_block>
<def_comment_line> ::: [%]<dollar><printable_char>*
<def_comment_block> ::: [/][*]<dollar><not_star_slash>[*][*]*[/]
Data Type: DefinedComment -}
definedComment :: CharParser st TPTP_THF
definedComment = do
try (string "%$" >> notFollowedBy (char '$'))
c <- parseToken $ many printableChar
return $ TPTP_Defined_Comment (Defined_Comment_Line c)
<|> do
c <- comment_ "/*$"
return $ TPTP_Defined_Comment (Defined_Comment_Block c)
THF & THF0 :
< system_comment > : : - < sys_comment_line>|<sys_comment_block >
< sys_comment_line > : : : [ % ] < dollar><dollar><printable_char > *
< sys_comment_block > : : : [ /][*]<dollar><dollar><not_star_slash>[*][*]*[/ ]
Data Type : SystemComment
<system_comment> ::- <sys_comment_line>|<sys_comment_block>
<sys_comment_line> ::: [%]<dollar><dollar><printable_char>*
<sys_comment_block> ::: [/][*]<dollar><dollar><not_star_slash>[*][*]*[/]
Data Type: SystemComment -}
systemComment :: CharParser st TPTP_THF
systemComment = do
tryString "%$$"
c <- parseToken $ many printableChar
return $ TPTP_System_Comment (System_Comment_Line c)
<|> do
c <- comment_ "/*$$"
return $ TPTP_System_Comment (System_Comment_Block c)
THF & THF0 :
< include > : : = include(<file_name><formula_selection > ) .
< formula_selection > : : = , [ < name_list > ] | < null >
Data Type : Include
<include> ::= include(<file_name><formula_selection>).
<formula_selection> ::= ,[<name_list>] | <null>
Data Type: Include -}
include :: CharParser st TPTP_THF
include = do
key $ tryString "include"
oParentheses
fn <- fileName
fs <- formulaSelection
cParentheses
char '.'
return $ TPTP_Include (I_Include fn fs)
thfAnnotatedFormula :: CharParser st TPTP_THF
thfAnnotatedFormula = do
key $ tryString "thf"
oParentheses
n <- name
comma
fr <- formulaRole
comma
tf <- thfFormula
a <- annotations
cParentheses
char '.'
return $ TPTP_THF_Annotated_Formula n fr tf a
THF & THF0 :
< annotations > : : = , < source><optional_info > | < null >
<annotations> ::= ,<source><optional_info> | <null> -}
annotations :: CharParser st Annotations
annotations = do
comma
s <- source
oi <- optionalInfo
return $ Annotations s oi
<|> do
notFollowedBy (char ',')
return Null
THF & THF0 :
< formula_role > : : = < lower_word >
< formula_role > : = = axiom | hypothesis | definition | assumption |
lemma | theorem | conjecture | negated_conjecture |
plain | fi_domain | fi_functors | fi_predicates |
type | unknown
<formula_role> ::= <lower_word>
<formula_role> :== axiom | hypothesis | definition | assumption |
lemma | theorem | conjecture | negated_conjecture |
plain | fi_domain | fi_functors | fi_predicates |
type | unknown -}
formulaRole :: CharParser st FormulaRole
formulaRole = do
r <- lowerWord
case show r of
"axiom" -> return Axiom
"hypothesis" -> return Hypothesis
"definition" -> return Definition
"assumption" -> return Assumption
"lemma" -> return Lemma
"theorem" -> return Theorem
"conjecture" -> return Conjecture
"negated_conjecture" -> return Negated_Conjecture
"plain" -> return Plain
"fi_domain" -> return Fi_Domain
"fi_functors" -> return Fi_Functors
"fi_predicates" -> return Fi_Predicates
"type" -> return Type
"unknown" -> return Unknown
s -> Fail.fail ("No such Role: " ++ s)
THF
< thf_formula > : : = < thf_logic_formula > | < thf_sequent >
THF0 :
< thf_formula > : : = < thf_logic_formula > | < thf_typed_const >
<thf_formula> ::= <thf_logic_formula> | <thf_sequent>
THF0:
<thf_formula> ::= <thf_logic_formula> | <thf_typed_const> -}
thfFormula :: CharParser st THFFormula
thfFormula = fmap T0F_THF_Typed_Const thfTypedConst
<|> fmap TF_THF_Logic_Formula thfLogicFormula
<|> fmap TF_THF_Sequent thfSequent
THF :
< thf_logic_formula > : : = < thf_binary_formula > | < thf_unitary_formula > |
< thf_type_formula > | < thf_subtype >
THF0 :
< thf_logic_formula > : : = < thf_binary_formula > | < thf_unitary_formula >
<thf_logic_formula> ::= <thf_binary_formula> | <thf_unitary_formula> |
<thf_type_formula> | <thf_subtype>
THF0:
<thf_logic_formula> ::= <thf_binary_formula> | <thf_unitary_formula> -}
thfLogicFormula :: CharParser st THFLogicFormula
thfLogicFormula = fmap TLF_THF_Binary_Formula thfBinaryFormula
<|> fmap TLF_THF_Unitary_Formula thfUnitaryFormula
<|> fmap TLF_THF_Type_Formula thfTypeFormula
<|> fmap TLF_THF_Sub_Type thfSubType
THF :
< thf_binary_formula > : : = < thf_binary_pair > | < thf_binary_tuple > |
< thf_binary_type >
< thf_binary_pair > : : = < thf_unitary_formula > < thf_pair_connective >
< thf_unitary_formula >
THF0 :
< thf_binary_formula > : : = < thf_pair_binary > | < thf_tuple_binary >
< thf_pair_binary > : : = < thf_unitary_formula > < thf_pair_connective >
< thf_unitary_formula >
Note : For THF0
< thf_binary_pair > is used like < thf_pair_binary > and
< thf_binary_tuple > are used like < thf_tuple_binary >
<thf_binary_formula> ::= <thf_binary_pair> | <thf_binary_tuple> |
<thf_binary_type>
<thf_binary_pair> ::= <thf_unitary_formula> <thf_pair_connective>
<thf_unitary_formula>
THF0:
<thf_binary_formula> ::= <thf_pair_binary> | <thf_tuple_binary>
<thf_pair_binary> ::= <thf_unitary_formula> <thf_pair_connective>
<thf_unitary_formula>
Note: For THF0
<thf_binary_pair> is used like <thf_pair_binary> and
<thf_binary_tuple> are used like <thf_tuple_binary> -}
thfBinaryFormula :: CharParser st THFBinaryFormula
thfBinaryFormula = fmap TBF_THF_Binary_Tuple thfBinaryTuple
<|> do
(uff, pc) <- try $ do
uff1 <- thfUnitaryFormula
pc1 <- thfPairConnective
return (uff1, pc1)
ufb <- thfUnitaryFormula
return $ TBF_THF_Binary_Pair uff pc ufb
<|> fmap TBF_THF_Binary_Type thfBinaryType
THF :
< thf_binary_tuple > : : = < thf_or_formula > | < thf_and_formula > |
< thf_apply_formula >
THF0 :
< thf_tuple_binary > : : = < thf_or_formula > | < thf_and_formula > |
< thf_apply_formula >
THF & THF0 :
< thf_or_formula > : : = < thf_unitary_formula > < vline > < thf_unitary_formula > |
< thf_or_formula > < vline > < thf_unitary_formula >
< thf_and_formula > : : = < thf_unitary_formula > & < thf_unitary_formula > |
thf_and_formula > & < thf_unitary_formula >
< thf_apply_formula > : : = < thf_unitary_formula > @ < thf_unitary_formula > |
< thf_apply_formula > @ < thf_unitary_formula >
< vline > : = = |
<thf_binary_tuple> ::= <thf_or_formula> | <thf_and_formula> |
<thf_apply_formula>
THF0:
<thf_tuple_binary> ::= <thf_or_formula> | <thf_and_formula> |
<thf_apply_formula>
THF & THF0:
<thf_or_formula> ::= <thf_unitary_formula> <vline> <thf_unitary_formula> |
<thf_or_formula> <vline> <thf_unitary_formula>
<thf_and_formula> ::= <thf_unitary_formula> & <thf_unitary_formula> |
thf_and_formula> & <thf_unitary_formula>
<thf_apply_formula> ::= <thf_unitary_formula> @ <thf_unitary_formula> |
<thf_apply_formula> @ <thf_unitary_formula>
<vline> :== | -}
thfBinaryTuple :: CharParser st THFBinaryTuple
uff <- try (thfUnitaryFormula << vLine)
ufb <- sepBy1 thfUnitaryFormula vLine
return $ TBT_THF_Or_Formula (uff : ufb)
uff <- try (thfUnitaryFormula << ampersand)
ufb <- sepBy1 thfUnitaryFormula ampersand
return $ TBT_THF_And_Formula (uff : ufb)
uff <- try (thfUnitaryFormula << at)
ufb <- sepBy1 thfUnitaryFormula at
return $ TBT_THF_Apply_Formula (uff : ufb)
formulaWithVariables :: CharParser st (THFVariableList, THFUnitaryFormula)
formulaWithVariables = do
vl <- brackets thfVariableList
colon
uf <- thfUnitaryFormula
return (vl, uf)
THF :
< thf_unitary_formula > : : = < thf_quantified_formula > | < thf_unary_formula > |
< thf_atom > | < thf_tuple > | < thf_let > |
< thf_conditional > | ( < thf_logic_formula > )
note : thf let is currently not well defined and thus ommited
< thf_conditional > : : = $ itef(<thf_logic_formula>,<thf_logic_formula > ,
< thf_logic_formula > )
THF0 :
< thf_unitary_formula > : : = < thf_quantified_formula > | < thf_abstraction > |
< thf_unary_formula > | < thf_atom > |
( < thf_logic_formula > )
< thf_abstraction > : : = < thf_lambda > [ < thf_variable_list > ] :
< thf_unitary_formula >
< thf_lambda > : : = ^
THF & THF0 :
< thf_unary_formula > : : = < thf_unary_connective > ( < thf_logic_formula > )
<thf_unitary_formula> ::= <thf_quantified_formula> | <thf_unary_formula> |
<thf_atom> | <thf_tuple> | <thf_let> |
<thf_conditional> | (<thf_logic_formula>)
note: thf let is currently not well defined and thus ommited
<thf_conditional> ::= $itef(<thf_logic_formula>,<thf_logic_formula>,
<thf_logic_formula>)
THF0:
<thf_unitary_formula> ::= <thf_quantified_formula> | <thf_abstraction> |
<thf_unary_formula> | <thf_atom> |
(<thf_logic_formula>)
<thf_abstraction> ::= <thf_lambda> [<thf_variable_list>] :
<thf_unitary_formula>
<thf_lambda> ::= ^
THF & THF0:
<thf_unary_formula> ::= <thf_unary_connective> (<thf_logic_formula>) -}
thfUnitaryFormula :: CharParser st THFUnitaryFormula
thfUnitaryFormula = fmap TUF_THF_Logic_Formula_Par (parentheses thfLogicFormula)
<|> fmap TUF_THF_Quantified_Formula (try thfQuantifiedFormula)
<|> do
keyChar '^'
(vl, uf) <- formulaWithVariables
added this for thf0
changed positions of parses below to prefer
changed positions of parses below to prefer th0 -}
<|> try thfUnaryFormula
<|> fmap TUF_THF_Atom thfAtom
<|> fmap TUF_THF_Tuple thfTuple
<|> do
key $ tryString "$itef"
oParentheses
lf1 <- thfLogicFormula
comma
lf2 <- thfLogicFormula
comma
lf3 <- thfLogicFormula
cParentheses
return $ TUF_THF_Conditional lf1 lf2 lf3
THF :
< thf_quantified_formula > : : = < thf_quantifier > [ < thf_variable_list > ] :
< thf_unitary_formula >
THF0 :
< thf_quantified_formula > : : = < thf_quantified_var > | < thf_quantified_novar >
< thf_quantified_var > : : = < quantifier > [ < thf_variable_list > ] :
< thf_unitary_formula >
< thf_quantified_novar > : : = < thf_quantifier > ( < thf_unitary_formula > )
<thf_quantified_formula> ::= <thf_quantifier> [<thf_variable_list>] :
<thf_unitary_formula>
THF0:
<thf_quantified_formula> ::= <thf_quantified_var> | <thf_quantified_novar>
<thf_quantified_var> ::= <quantifier> [<thf_variable_list>] :
<thf_unitary_formula>
<thf_quantified_novar> ::= <thf_quantifier> (<thf_unitary_formula>) -}
thfQuantifiedFormula :: CharParser st THFQuantifiedFormula
thfQuantifiedFormula = do
q <- quantifier
(vl, uf) <- formulaWithVariables
<|> do
q <- thfQuantifier
uf <- parentheses thfUnitaryFormula
<|> do
q <- thfQuantifier
(vl, uf) <- formulaWithVariables
return $ TQF_THF_Quantified_Formula q vl uf
THF & THF0 :
< thf_variable_list > : : = < thf_variable > |
< thf_variable>,<thf_variable_list >
<thf_variable_list> ::= <thf_variable> |
<thf_variable>,<thf_variable_list> -}
thfVariableList :: CharParser st THFVariableList
thfVariableList = sepBy1 thfVariable comma
THF & THF0 :
< thf_variable > : : = < thf_typed_variable > | < variable >
< thf_typed_variable > : : = < variable > : < thf_top_level_type >
<thf_variable> ::= <thf_typed_variable> | <variable>
<thf_typed_variable> ::= <variable> : <thf_top_level_type> -}
thfVariable :: CharParser st THFVariable
thfVariable = do
v <- try (variable << colon)
tlt <- thfTopLevelType
return $ TV_THF_Typed_Variable v tlt
<|> fmap TV_Variable variable
thfTypedConst = fmap T0TC_THF_TypedConst_Par (parentheses thfTypedConst)
<|> do
c <- try (constant << colon)
tlt <- thfTopLevelType
return $ T0TC_Typed_Const c tlt
thfUnaryFormula :: CharParser st THFUnitaryFormula
thfUnaryFormula = do
uc <- thfUnaryConnective
lf <- parentheses thfLogicFormula
return $ TUF_THF_Unary_Formula uc lf
THF :
< thf_type_formula > : : = < thf_typeable_formula > : < thf_top_level_type >
< thf_type_formula > : = = < constant > : < thf_top_level_type >
<thf_type_formula> ::= <thf_typeable_formula> : <thf_top_level_type>
<thf_type_formula> :== <constant> : <thf_top_level_type> -}
thfTypeFormula :: CharParser st THFTypeFormula
thfTypeFormula = do
tp <- try (thfTypeableFormula << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Type_Formula tp tlt
<|> do
c <- try (constant << colon)
tlt <- thfTopLevelType
return $ TTF_THF_Typed_Const c tlt
THF :
< thf_typeable_formula > : : = < thf_atom > | < thf_tuple > | ( < thf_logic_formula > )
<thf_typeable_formula> ::= <thf_atom> | <thf_tuple> | (<thf_logic_formula>) -}
thfTypeableFormula :: CharParser st THFTypeableFormula
thfTypeableFormula = fmap TTyF_THF_Atom thfAtom
<|> fmap TTyF_THF_Tuple thfTuple
<|> fmap TTyF_THF_Logic_Formula (parentheses thfLogicFormula)
THF :
< thf_subtype > : : = < constant > < subtype_sign > < constant >
< subtype_sign > = = < <
<thf_subtype> ::= <constant> <subtype_sign> <constant>
<subtype_sign> == << -}
thfSubType :: CharParser st THFSubType
thfSubType = do
cf <- try (constant << key (string "<<"))
cb <- constant
return $ TST_THF_Sub_Type cf cb
THF :
< thf_top_level_type > : : = < thf_logic_formula >
THF0 :
< thf_top_level_type > : : = < constant > | < variable > | < defined_type > |
< system_type > | < thf_binary_type >
<thf_top_level_type> ::= <thf_logic_formula>
THF0:
<thf_top_level_type> ::= <constant> | <variable> | <defined_type> |
<system_type> | <thf_binary_type> -}
thfTopLevelType :: CharParser st THFTopLevelType
thfTopLevelType = fmap T0TLT_THF_Binary_Type thfBinaryType
<|> fmap T0TLT_Constant constant
<|> fmap T0TLT_Variable variable
<|> fmap T0TLT_Defined_Type definedType
<|> fmap T0TLT_System_Type systemType
<|> fmap TTLT_THF_Logic_Formula thfLogicFormula
THF :
< thf_unitary_type > : : = < thf_unitary_formula >
THF0 :
< thf_unitary_type > : : = < constant > | < variable > | < defined_type > |
< system_type > | ( < thf_binary_type > )
<thf_unitary_type> ::= <thf_unitary_formula>
THF0:
<thf_unitary_type> ::= <constant> | <variable> | <defined_type> |
<system_type> | (<thf_binary_type>) -}
thfUnitaryType :: CharParser st THFUnitaryType
thfUnitaryType = fmap T0UT_Constant constant
<|> fmap T0UT_Variable variable
<|> fmap T0UT_Defined_Type definedType
<|> fmap T0UT_System_Type systemType
<|> fmap T0UT_THF_Binary_Type_Par (parentheses thfBinaryType)
<|> fmap TUT_THF_Unitary_Formula thfUnitaryFormula
added all except for this for
THF :
< thf_binary_type > : : = < thf_mapping_type > | < thf_xprod_type > |
< thf_union_type >
< thf_xprod_type > : : = < thf_unitary_type > < star > < thf_unitary_type > |
< thf_xprod_type > < star > < thf_unitary_type >
< star > : : - *
< thf_union_type > : : = < thf_unitary_type > < plus > < thf_unitary_type > |
< thf_union_type > < plus > < thf_unitary_type >
< plus > : : - +
THF0 :
< thf_binary_type > : : = < thf_mapping_type > | ( < thf_binary_type > )
THF & THF0 :
< thf_mapping_type > : : = < thf_unitary_type > < arrow > < thf_unitary_type > |
< thf_unitary_type > < arrow > < thf_mapping_type >
< arrow > : : - >
<thf_binary_type> ::= <thf_mapping_type> | <thf_xprod_type> |
<thf_union_type>
<thf_xprod_type> ::= <thf_unitary_type> <star> <thf_unitary_type> |
<thf_xprod_type> <star> <thf_unitary_type>
<star> ::- *
<thf_union_type> ::= <thf_unitary_type> <plus> <thf_unitary_type> |
<thf_union_type> <plus> <thf_unitary_type>
<plus> ::- +
THF0:
<thf_binary_type> ::= <thf_mapping_type> | (<thf_binary_type>)
THF & THF0:
<thf_mapping_type> ::= <thf_unitary_type> <arrow> <thf_unitary_type> |
<thf_unitary_type> <arrow> <thf_mapping_type>
<arrow> ::- > -}
thfBinaryType :: CharParser st THFBinaryType
thfBinaryType = do
utf <- try (thfUnitaryType << arrow)
utb <- sepBy1 thfUnitaryType arrow
return $ TBT_THF_Mapping_Type (utf : utb)
<|> fmap T0BT_THF_Binary_Type_Par (parentheses thfBinaryType)
utf <- try (thfUnitaryType << star)
utb <- sepBy1 thfUnitaryType star
return $ TBT_THF_Xprod_Type (utf : utb)
utf <- try (thfUnitaryType << plus)
utb <- sepBy1 thfUnitaryType plus
return $ TBT_THF_Union_Type (utf : utb)
THF :
< thf_atom > : : = < term > | < thf_conn_term >
< system_atomic_formula > : : = < system_term >
THF0 :
< thf_atom > : : = < constant > | < defined_constant > |
< system_constant > | < variable > | < thf_conn_term >
< defined_constant > : : = < atomic_defined_word >
< system_constant > : : = < atomic_system_word >
<thf_atom> ::= <term> | <thf_conn_term>
<system_atomic_formula> ::= <system_term>
THF0:
<thf_atom> ::= <constant> | <defined_constant> |
<system_constant> | <variable> | <thf_conn_term>
<defined_constant> ::= <atomic_defined_word>
<system_constant> ::= <atomic_system_word> -}
thfAtom :: CharParser st THFAtom
thfAtom = fmap T0A_Constant constant
<|> fmap T0A_Defined_Constant atomicDefinedWord
<|> fmap T0A_System_Constant atomicSystemWord
<|> fmap T0A_Variable variable
<|> fmap TA_THF_Conn_Term thfConnTerm
<|> fmap TA_Defined_Type definedType
<|> fmap TA_Defined_Plain_Formula definedPlainFormula
<|> fmap TA_System_Type systemType
<|> fmap TA_System_Atomic_Formula systemTerm
<|> fmap TA_Term term
THF :
< thf_tuple > : : = [ ] | [ < thf_tuple_list > ]
< thf_tuple_list > : : = < thf_logic_formula > |
< thf_logic_formula>,<thf_tuple_list >
THFTupleList must not be empty
<thf_tuple> ::= [] | [<thf_tuple_list>]
<thf_tuple_list> ::= <thf_logic_formula> |
<thf_logic_formula>,<thf_tuple_list>
THFTupleList must not be empty -}
thfTuple :: CharParser st THFTuple
thfTuple = try ((oBracket >> cBracket) >> return [])
<|> brackets (sepBy1 thfLogicFormula comma)
THF :
< thf_sequent > : : = < thf_tuple > < gentzen_arrow > < thf_tuple > |
( < thf_sequent > )
<thf_sequent> ::= <thf_tuple> <gentzen_arrow> <thf_tuple> |
(<thf_sequent>)
thfSequent :: CharParser st THFSequent
thfSequent = fmap TS_THF_Sequent_Par (parentheses thfSequent)
<|> do
tf <- try (thfTuple << gentzenArrow)
tb <- thfTuple
return $ TS_THF_Sequent tf tb
THF :
< thf_conn_term > : : = < thf_pair_connective > | < assoc_connective > |
< thf_unary_connective >
THF0 :
< thf_conn_term > : : = < thf_quantifier > | < thf_pair_connective > |
< assoc_connective > | < thf_unary_connective >
<thf_conn_term> ::= <thf_pair_connective> | <assoc_connective> |
<thf_unary_connective>
THF0:
<thf_conn_term> ::= <thf_quantifier> | <thf_pair_connective> |
<assoc_connective> | <thf_unary_connective> -}
thfConnTerm :: CharParser st THFConnTerm
thfConnTerm = fmap TCT_THF_Pair_Connective thfPairConnective
<|> fmap TCT_Assoc_Connective assocConnective
<|> fmap TCT_THF_Unary_Connective thfUnaryConnective
<|> fmap T0CT_THF_Quantifier thfQuantifier
THF :
< thf_quantifier > : : = < fol_quantifier > | ^ | ! > | ? * | @+ | @-
< fol_quantifier > : : = ! | ?
THF0 :
< thf_quantifier > : : = ! ! | ? ?
<thf_quantifier> ::= <fol_quantifier> | ^ | !> | ?* | @+ | @-
<fol_quantifier> ::= ! | ?
THF0:
<thf_quantifier> ::= !! | ?? -}
thfQuantifier :: CharParser st THFQuantifier
thfQuantifier = (key (tryString "!!") >> return T0Q_PiForAll)
<|> (key (tryString "??") >> return T0Q_SigmaExists)
<|> (keyChar '!' >> return TQ_ForAll)
<|> (keyChar '?' >> return TQ_Exists)
<|> (keyChar '^' >> return TQ_Lambda_Binder)
<|> (key (tryString "!>") >> return TQ_Dependent_Product)
<|> (key (tryString "?*") >> return TQ_Dependent_Sum)
<|> (key (tryString "@+") >> return TQ_Indefinite_Description)
<|> (key (tryString "@-") >> return TQ_Definite_Description)
<?> "thfQuantifier"
quantifier :: CharParser st Quantifier
quantifier = (keyChar '!' >> return T0Q_ForAll)
<|> (keyChar '?' >> return T0Q_Exists)
<?> "quantifier"
THF :
< thf_pair_connective > : : = < infix_equality > | < infix_inequality > |
< binary_connective >
< infix_equality > : : = =
< infix_inequality > : : = ! =
THF0 :
< thf_pair_connective > : : = < defined_infix_pred > | < binary_connective >
< defined_infix_pred > : : = = | ! =
THF & THF0 :
< binary_connective > : : = < = > | = > | < = | < ~ > | ~<vline > | ~ &
<thf_pair_connective> ::= <infix_equality> | <infix_inequality> |
<binary_connective>
<infix_equality> ::= =
<infix_inequality> ::= !=
THF0:
<thf_pair_connective> ::= <defined_infix_pred> | <binary_connective>
<defined_infix_pred> ::= = | !=
THF & THF0:
<binary_connective> ::= <=> | => | <= | <~> | ~<vline> | ~& -}
thfPairConnective :: CharParser st THFPairConnective
thfPairConnective = (key (tryString "!=") >> return Infix_Inequality)
<|> (key (tryString "<=>") >> return Equivalent)
<|> (key (tryString "=>") >> return Implication)
<|> (key (tryString "<=") >> return IF)
<|> (key (tryString "<~>") >> return XOR)
<|> (key (tryString "~|") >> return NOR)
<|> (key (tryString "~&") >> return NAND)
<|> (keyChar '=' >> return Infix_Equality)
<?> "pairConnective"
THF :
< thf_unary_connective > : : = < unary_connective > | ! ! | ? ?
THF0 :
< thf_unary_connective > : : = < unary_connective >
THF & THF0 :
< unary_connective > : : = ~
<thf_unary_connective> ::= <unary_connective> | !! | ??
THF0:
<thf_unary_connective> ::= <unary_connective>
THF & THF0:
<unary_connective> ::= ~ -}
thfUnaryConnective :: CharParser st THFUnaryConnective
thfUnaryConnective = (keyChar '~' >> return Negation)
<|> (key (tryString "!!") >> return PiForAll)
<|> (key (tryString "??") >> return SigmaExists)
THF & THF0 :
< assoc_connective > : : = < vline > | &
<assoc_connective> ::= <vline> | & -}
assocConnective :: CharParser st AssocConnective
assocConnective = (keyChar '|' >> return OR)
<|> (keyChar '&' >> return AND)
THF :
< defined_type > : = = $ oType | $ o | $ iType | $ i | $ tType |
real | $ rat | $ int
THF0 :
< defined_type > : = = $ oType | $ o | $ iType | $ i | THF & THF0 :
< defined_type > : : = < atomic_defined_word >
<defined_type> :== $oType | $o | $iType | $i | $tType |
real | $rat | $int
THF0:
<defined_type> :== $oType | $o | $iType | $i | $tType
THF & THF0:
<defined_type> ::= <atomic_defined_word> -}
definedType :: CharParser st DefinedType
definedType = do
adw <- atomicDefinedWord
case show adw of
"oType" -> return DT_oType
"o" -> return DT_o
"iType" -> return DT_iType
"i" -> return DT_i
"tType" -> return DT_tType
"real" -> return DT_real
"rat" -> return DT_rat
"int" -> return DT_int
s -> Fail.fail ("No such definedType: " ++ s)
THF & THF0 :
< system_type > : : = < atomic_system_word >
<system_type> ::= <atomic_system_word> -}
systemType :: CharParser st Token
systemType = atomicSystemWord
THF :
< defined_plain_formula > : : = < defined_plain_term >
< defined_plain_formula > : = = < defined_prop > | < defined_pred>(<arguments > )
<defined_plain_formula> ::= <defined_plain_term>
<defined_plain_formula> :== <defined_prop> | <defined_pred>(<arguments>) -}
definedPlainFormula :: CharParser st DefinedPlainFormula
definedPlainFormula = fmap DPF_Defined_Prop definedProp
<|> do
dp <- definedPred
a <- parentheses arguments
return $ DPF_Defined_Formula dp a
THF & THF0 :
< defined_prop > : = = < atomic_defined_word >
< defined_prop > : = = $ true | $ false
<defined_prop> :== <atomic_defined_word>
<defined_prop> :== $true | $false -}
definedProp :: CharParser st DefinedProp
definedProp = do
adw <- atomicDefinedWord
case show adw of
"true" -> return DP_True
"false" -> return DP_False
s -> Fail.fail ("No such definedProp: " ++ s)
THF :
< defined_pred > : = = < atomic_defined_word >
< defined_pred > : = = $ distinct |
less | $ lesseq | $ greater | $ greatereq |
is_int | $ is_rat
<defined_pred> :== <atomic_defined_word>
<defined_pred> :== $distinct |
less | $lesseq | $greater | $greatereq |
is_int | $is_rat -}
definedPred :: CharParser st DefinedPred
definedPred = do
adw <- atomicDefinedWord
case show adw of
"distinct" -> return Disrinct
"less" -> return Less
"lesseq" -> return Lesseq
"greater" -> return Greater
"greatereq" -> return Greatereq
"is_int" -> return Is_int
"is_rat" -> return Is_rat
s -> Fail.fail ("No such definedPred: " ++ s)
THF :
< term > : : = < function_term > | < variable > | < conditional_term >
Thus tey are not implemented .
<term> ::= <function_term> | <variable> | <conditional_term>
Thus tey are not implemented. -}
term :: CharParser st Term
term = fmap T_Function_Term functionTerm
<|> fmap T_Variable variable
THF :
< function_term > : : = < plain_term > | < defined_term > | < system_term >
<function_term> ::= <plain_term> | <defined_term> | <system_term> -}
functionTerm :: CharParser st FunctionTerm
functionTerm = fmap FT_System_Term systemTerm
<|> fmap FT_Defined_Term definedTerm
<|> fmap FT_Plain_Term plainTerm
THF :
< plain_term > : : = < constant > | < functor>(<arguments > )
<plain_term> ::= <constant> | <functor>(<arguments>) -}
plainTerm :: CharParser st PlainTerm
plainTerm = try (do
f <- tptpFunctor
a <- parentheses arguments
return $ PT_Plain_Term f a)
<|> fmap PT_Constant constant
THF & THF0 :
< constant > : : = < functor >
<constant> ::= <functor> -}
constant :: CharParser st Constant
constant = tptpFunctor
THF & THF0 :
< functor > : : = < atomic_word >
<functor> ::= <atomic_word> -}
tptpFunctor :: CharParser st AtomicWord
tptpFunctor = atomicWord
THF :
< defined_term > : : = < defined_atom > | < defined_atomic_term >
< defined_atomic_term > : : = < defined_plain_term >
<defined_term> ::= <defined_atom> | <defined_atomic_term>
<defined_atomic_term> ::= <defined_plain_term> -}
definedTerm :: CharParser st DefinedTerm
definedTerm = fmap DT_Defined_Atomic_Term definedPlainTerm
<|> fmap DT_Defined_Atom definedAtom
THF :
< defined_atom > : : = < number > | < distinct_object >
<defined_atom> ::= <number> | <distinct_object> -}
definedAtom :: CharParser st DefinedAtom
definedAtom = fmap DA_Number number
<|> fmap DA_Distinct_Object distinctObject
THF :
< defined_plain_term > : : = < defined_constant > | < defined_functor>(<arguments > )
< defined_constant > : : = < defined_functor >
<defined_plain_term> ::= <defined_constant> | <defined_functor>(<arguments>)
<defined_constant> ::= <defined_functor> -}
definedPlainTerm :: CharParser st DefinedPlainTerm
definedPlainTerm = try (do
df <- definedFunctor
a <- parentheses arguments
return $ DPT_Defined_Function df a)
<|> fmap DPT_Defined_Constant definedFunctor
THF :
< defined_functor > : : = < atomic_defined_word >
< defined_functor > : = = $ uminus | $ sum | $ difference | $ product |
quotient | $ quotient_e | $ quotient_t | $ quotient_f |
remainder_e | $ remainder_t | $ remainder_f |
floor | $ ceiling | $ truncate | $ round |
to_int | $ to_rat | $ to_real
<defined_functor> ::= <atomic_defined_word>
<defined_functor> :== $uminus | $sum | $difference | $product |
quotient | $quotient_e | $quotient_t | $quotient_f |
remainder_e | $remainder_t | $remainder_f |
floor | $ceiling | $truncate | $round |
to_int | $to_rat | $to_real -}
definedFunctor :: CharParser st DefinedFunctor
definedFunctor = do
adw <- atomicDefinedWord
case show adw of
"uminus" -> return UMinus
"sum" -> return Sum
"difference" -> return Difference
"product" -> return Product
"quotient" -> return Quotient
"quotient_e" -> return Quotient_e
"quotient_t" -> return Quotient_t
"quotient_f" -> return Quotient_f
"floor" -> return Floor
"ceiling" -> return Ceiling
"truncate" -> return Truncate
"round" -> return Round
"to_int" -> return To_int
"to_rat" -> return To_rat
"to_real" -> return To_real
s -> Fail.fail ("No such definedFunctor: " ++ s)
THF :
< system_term > : : = < system_constant > | < system_functor>(<arguments > )
< system_constant > : : = < system_functor >
<system_term> ::= <system_constant> | <system_functor>(<arguments>)
<system_constant> ::= <system_functor> -}
systemTerm :: CharParser st SystemTerm
systemTerm = try (do
sf <- systemFunctor
a <- parentheses arguments
return $ ST_System_Term sf a)
<|> fmap ST_System_Constant systemFunctor
THF :
< system_functor > : : = < atomic_system_word >
<system_functor> ::= <atomic_system_word> -}
systemFunctor :: CharParser st Token
systemFunctor = atomicSystemWord
THF & THF0 :
< variable > : : = < upper_word >
<variable> ::= <upper_word> -}
variable :: CharParser st Token
variable = parseToken
(do
u <- upper
an <- many (alphaNum <|> char '_')
skipAll
return (u : an)
<?> "Variable")
THF :
< arguments > : : = < term > | < term>,<arguments >
at least one term is neaded
<arguments> ::= <term> | <term>,<arguments>
at least one term is neaded -}
arguments :: CharParser st Arguments
arguments = sepBy1 term comma
THF & THF0 :
< principal_symbol > : = = < functor > | < variable >
<principal_symbol> :== <functor> | <variable> -}
principalSymbol :: CharParser st PrincipalSymbol
principalSymbol = fmap PS_Functor tptpFunctor
<|> fmap PS_Variable variable
THF & THF0 :
< source > : : = < general_term >
< source > : = = < dag_source > | < internal_source > | < external_source > |
unknown | [ < sources > ]
< internal_source > : = = introduced(<intro_type><optional_info > )
< sources > : = = < source > | < source>,<sources >
<source> ::= <general_term>
<source> :== <dag_source> | <internal_source> | <external_source> |
unknown | [<sources>]
<internal_source> :== introduced(<intro_type><optional_info>)
<sources> :== <source> | <source>,<sources> -}
source :: CharParser st Source
source = (key (tryString "unknown") >> return S_Unknown)
<|> fmap S_Dag_Source dagSource
<|> fmap S_External_Source externalSource
<|> fmap S_Sources (sepBy1 source comma)
internal_source
key $ tryString "introduced"
oParentheses
it <- introType
oi <- optionalInfo
cParentheses
return $ S_Internal_Source it oi
THF & THF0 :
< dag_source > : = = < name > | < inference_record >
< inference_record > : = = > ,
[ < parent_list > ] )
< inference_rule > : = = < atomic_word >
< parent_list > : = = < parent_info > | < parent_info>,<parent_list >
<dag_source> :== <name> | <inference_record>
<inference_record> :== inference(<inference_rule>,<useful_info>,
[<parent_list>])
<inference_rule> :== <atomic_word>
<parent_list> :== <parent_info> | <parent_info>,<parent_list> -}
dagSource :: CharParser st DagSource
dagSource = do
key (tryString "inference")
oParentheses
ir <- atomicWord
comma
ui <- usefulInfo
comma
pl <- brackets (sepBy1 parentInfo comma)
cParentheses
return (DS_Inference_Record ir ui pl)
<|> fmap DS_Name name
THF & THF0 :
< parent_info > : = = < source><parent_details >
< parent_details > : = = : < general_list > | < null >
<parent_info> :== <source><parent_details>
<parent_details> :== :<general_list> | <null> -}
parentInfo :: CharParser st ParentInfo
parentInfo = do
s <- source
pd <- parentDetails
return $ PI_Parent_Info s pd
parentDetails :: CharParser st (Maybe GeneralList)
parentDetails = fmap Just (colon >> generalList)
<|> (notFollowedBy (char ':') >> return Nothing)
THF & THF0 :
< intro_type > : = = definition | axiom_of_choice | tautology | assumption
<intro_type> :== definition | axiom_of_choice | tautology | assumption -}
introType :: CharParser st IntroType
introType = (key (tryString "definition") >> return IT_definition)
<|> (key (tryString "axiom_of_choice") >> return IT_axiom_of_choice)
<|> (key (tryString "tautology") >> return IT_tautology)
<|> (key (tryString "assumption") >> return IT_assumption)
THF & THF0 :
< external_source > : = = < file_source > | < theory > | < creator_source >
< theory > : = = theory(<theory_name><optional_info > )
< creator_source > : = = creator(<creator_name><optional_info > )
< creator_name > : = = < atomic_word >
<external_source> :== <file_source> | <theory> | <creator_source>
<theory> :== theory(<theory_name><optional_info>)
<creator_source> :== creator(<creator_name><optional_info>)
<creator_name> :== <atomic_word> -}
externalSource :: CharParser st ExternalSource
externalSource = fmap ES_File_Source fileSource
<|> do
key $ tryString "theory"
oParentheses
tn <- theoryName
oi <- optionalInfo
cParentheses
return $ ES_Theory tn oi
<|> do
key $ tryString "creator"
oParentheses
cn <- atomicWord
oi <- optionalInfo
cParentheses
return $ ES_Creator_Source cn oi
THF & THF0 :
< file_source > : = = > )
< file_info > : = = , < name > | < null >
<file_source> :== file(<file_name><file_info>)
<file_info> :== ,<name> | <null> -}
fileSource :: CharParser st FileSource
fileSource = do
key $ tryString "file"
oParentheses
fn <- fileName
fi <- fileInfo
cParentheses
return $ FS_File fn fi
fileInfo :: CharParser st (Maybe Name)
fileInfo = fmap Just (comma >> name)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< theory_name > : = = equality | ac
<theory_name> :== equality | ac -}
theoryName :: CharParser st TheoryName
theoryName = (key (tryString "equality") >> return Equality)
<|> (key (tryString "ac") >> return Ac)
THF & THF0 :
< optional_info > : : = , < useful_info > | < null >
<optional_info> ::= ,<useful_info> | <null> -}
optionalInfo :: CharParser st OptionalInfo
optionalInfo = fmap Just (comma >> usefulInfo)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< useful_info > : : = < general_list >
< useful_info > : = = [ ] | [ < info_items > ]
< info_items > : = = < info_item > | < info_item>,<info_items >
<useful_info> ::= <general_list>
<useful_info> :== [] | [<info_items>]
<info_items> :== <info_item> | <info_item>,<info_items> -}
usefulInfo :: CharParser st UsefulInfo
usefulInfo = (oBracket >> cBracket >> return [])
<|> brackets (sepBy1 infoItem comma)
THF & THF0 :
< info_item > : = = < formula_item > | < inference_item > |
< general_function >
<info_item> :== <formula_item> | <inference_item> |
<general_function> -}
infoItem :: CharParser st InfoItem
infoItem = fmap II_Formula_Item formulaItem
<|> fmap II_Inference_Item inferenceItem
<|> fmap II_General_Function generalFunction
THF & THF0 :
< formula_item > : = = < description_item > | < iquote_item >
< description_item > : = = description(<atomic_word > )
< iquote_item > : = = iquote(<atomic_word > )
<formula_item> :== <description_item> | <iquote_item>
<description_item> :== description(<atomic_word>)
<iquote_item> :== iquote(<atomic_word>) -}
formulaItem :: CharParser st FormulaItem
formulaItem = do
key $ tryString "description"
fmap FI_Description_Item (parentheses atomicWord)
<|> do
key $ tryString "iquote"
fmap FI_Iquote_Item (parentheses atomicWord)
THF & THF0 :
< inference_item > : = = < inference_status > | < assumptions_record > |
< new_symbol_record > | < refutation >
< assumptions_record > : = = assumptions([<name_list > ] )
< refutation > : = = refutation(<file_source > )
< new_symbol_record > : = = new_symbols(<atomic_word>,[<new_symbol_list > ] )
< new_symbol_list > : = = < principal_symbol > |
< principal_symbol>,<new_symbol_list >
<inference_item> :== <inference_status> | <assumptions_record> |
<new_symbol_record> | <refutation>
<assumptions_record> :== assumptions([<name_list>])
<refutation> :== refutation(<file_source>)
<new_symbol_record> :== new_symbols(<atomic_word>,[<new_symbol_list>])
<new_symbol_list> :== <principal_symbol> |
<principal_symbol>,<new_symbol_list> -}
inferenceItem :: CharParser st InferenceItem
inferenceItem = fmap II_Inference_Status inferenceStatus
<|> do
key $ tryString "assumptions"
fmap II_Assumptions_Record (parentheses (brackets nameList))
<|> do
key $ tryString "new_symbols"
oParentheses
aw <- atomicWord
comma
nsl <- brackets (sepBy1 principalSymbol comma)
cParentheses
return $ II_New_Symbol_Record aw nsl
<|> do
key $ tryString "refutation"
fmap II_Refutation (parentheses fileSource)
THF & THF0 :
< inference_status > : = = status(<status_value > ) | < inference_info >
< inference_info > : = = < inference_rule>(<atomic_word>,<general_list > )
< inference_rule > : = = < atomic_word >
<inference_status> :== status(<status_value>) | <inference_info>
<inference_info> :== <inference_rule>(<atomic_word>,<general_list>)
<inference_rule> :== <atomic_word> -}
inferenceStatus :: CharParser st InferenceStatus
inferenceStatus = do
key $ tryString "status"
fmap IS_Status (parentheses statusValue)
<|> do
ir <- try (atomicWord << oParentheses)
aw <- atomicWord
comma
gl <- generalList
cParentheses
return $ IS_Inference_Info ir aw gl
THF & THF0 :
< status_value > : = = suc | unp | sap | esa | sat | fsa | thm | eqv | tac |
wec | eth | tau | wtc | wth | cax | sca | tca | wca |
cup | csp | ecs | csa | cth | ceq | unc | wcc | ect |
fun | uns | wuc | wct | scc | uca | noc
<status_value> :== suc | unp | sap | esa | sat | fsa | thm | eqv | tac |
wec | eth | tau | wtc | wth | cax | sca | tca | wca |
cup | csp | ecs | csa | cth | ceq | unc | wcc | ect |
fun | uns | wuc | wct | scc | uca | noc -}
statusValue :: CharParser st StatusValue
statusValue = choice $ map (\ r -> key (tryString $ showStatusValue r)
>> return r) allStatusValues
allStatusValues :: [StatusValue]
allStatusValues =
[Suc, Unp, Sap, Esa, Sat, Fsa, Thm, Eqv, Tac,
Wec, Eth, Tau, Wtc, Wth, Cax, Sca, Tca, Wca,
Cup, Csp, Ecs, Csa, Cth, Ceq, Unc, Wcc, Ect,
Fun, Uns, Wuc, Wct, Scc, Uca, Noc]
showStatusValue :: StatusValue -> String
showStatusValue = map toLower . show
formulaSelection :: CharParser st (Maybe NameList)
formulaSelection = fmap Just (comma >> brackets nameList)
<|> (notFollowedBy (char ',') >> return Nothing)
THF & THF0 :
< name_list > : : = < name > | < name>,<name_list >
the list must mot be empty
<name_list> ::= <name> | <name>,<name_list>
the list must mot be empty -}
nameList :: CharParser st NameList
nameList = sepBy1 name comma
THF & THF0 :
< general_term > : : = < general_data > | < general_data>:<general_term > |
< general_list >
<general_term> ::= <general_data> | <general_data>:<general_term> |
<general_list> -}
generalTerm :: CharParser st GeneralTerm
generalTerm = do
gd <- try (generalData << notFollowedBy (char ':'))
return $ GT_General_Data gd
<|> do
gd <- try (generalData << colon)
gt <- generalTerm
return $ GT_General_Data_Term gd gt
<|> fmap GT_General_List generalList
THF & THF0 :
< general_data > : : = < atomic_word > | < general_function > |
< variable > | < number > | < distinct_object > |
< formula_data >
< general_data > : = = bind(<variable>,<formula_data > )
<general_data> ::= <atomic_word> | <general_function> |
<variable> | <number> | <distinct_object> |
<formula_data>
<general_data> :== bind(<variable>,<formula_data>) -}
generalData :: CharParser st GeneralData
generalData = fmap GD_Variable variable
<|> fmap GD_Number number
<|> fmap GD_Distinct_Object distinctObject
<|> do
key $ tryString "bind"
oParentheses
v <- variable
comma
fd <- formulaData
cParentheses
return (GD_Bind v fd)
<|> fmap GD_General_Function generalFunction
<|> fmap GD_Atomic_Word atomicWord
<|> fmap GD_Formula_Data formulaData
THF & THF0 :
< general_function > : : = < atomic_word>(<general_terms > )
general_terms must not be empty
<general_function> ::= <atomic_word>(<general_terms>)
general_terms must not be empty -}
generalFunction :: CharParser st GeneralFunction
generalFunction = do
aw <- atomicWord
gts <- parentheses generalTerms
return $ GF_General_Function aw gts
THF & THF0 :
< formula_data > : : = $ thf(<thf_formula > ) | $ tff(<tff_formula > ) |
fof(<fof_formula > ) | $ cnf(<cnf_formula > ) |
fot(<term > )
only thf is used here
<formula_data> ::= $thf(<thf_formula>) | $tff(<tff_formula>) |
fof(<fof_formula>) | $cnf(<cnf_formula>) |
fot(<term>)
only thf is used here -}
formulaData :: CharParser st FormulaData
formulaData = fmap THF_Formula thfFormula
THF & THF0 :
< general_list > : : = [ ] | [ < general_terms > ]
<general_list> ::= [] | [<general_terms>] -}
generalList :: CharParser st GeneralList
generalList = (try (oBracket >> cBracket) >> return [])
<|> brackets generalTerms
THF & THF0 :
< general_terms > : : = < general_term > | < general_term>,<general_terms >
<general_terms> ::= <general_term> | <general_term>,<general_terms> -}
generalTerms :: CharParser st [GeneralTerm]
generalTerms = sepBy1 generalTerm comma
THF :
< name > : : = < atomic_word > | < integer >
THF0 :
< name > : : = < atomic_word > | < unsigned_integer >
<name> ::= <atomic_word> | <integer>
THF0:
<name> ::= <atomic_word> | <unsigned_integer> -}
name :: CharParser st Name
name = fmap T0N_Unsigned_Integer (parseToken (unsignedInteger << skipAll))
<|> fmap N_Integer (integer << skipAll)
<|> fmap N_Atomic_Word atomicWord
THF & THF0 :
< atomic_word > : : = < lower_word > | < single_quoted >
<atomic_word> ::= <lower_word> | <single_quoted> -}
atomicWord :: CharParser st AtomicWord
atomicWord = fmap A_Lower_Word lowerWord
<|> fmap A_Single_Quoted singleQuoted
<?> "lowerWord or singleQuoted"
THF & THF0 :
< atomic_defined_word > : : = < dollar_word >
<atomic_defined_word> ::= <dollar_word> -}
atomicDefinedWord :: CharParser st Token
atomicDefinedWord = char '$' >> lowerWord
THF & THF0 :
< atomic_system_word > : : = < dollar_dollar_word >
< dollar_dollar_word > : : - < dollar><dollar><lower_word >
< dollar > : : : [ $ ]
<atomic_system_word> ::= <dollar_dollar_word>
<dollar_dollar_word> ::- <dollar><dollar><lower_word>
<dollar> ::: [$] -}
atomicSystemWord :: CharParser st Token
atomicSystemWord = tryString "$$" >> lowerWord
THF & THF0 :
< number > : : = < integer > | < rational > | < real >
< real > : : - ( < signed_real>|<unsigned_real > )
< signed_real > : : - < sign><unsigned_real >
< unsigned_real > : : - ( < decimal_fraction>|<decimal_exponent > )
< rational > : : - ( < signed_rational>|<unsigned_rational > )
< signed_rational > : : - < sign><unsigned_rational >
< unsigned_rational > : : - < decimal><slash><positive_decimal >
< integer > : : - ( < signed_integer>|<unsigned_integer > )
< signed_integer > : : - < sign><unsigned_integer >
< unsigned_integer > : : - < decimal >
< decimal > : : - ( < zero_numeric>|<positive_decimal > )
< positive_decimal > : : - < non_zero_numeric><numeric > *
< decimal_exponent > : : - ( < decimal>|<decimal_fraction>)<exponent><decimal >
< decimal_fraction > : : - < decimal><dot_decimal >
< dot_decimal > : : - < dot><numeric><numeric > *
< sign > : : : [ + - ]
< dot > : : : [ . ]
< exponent > : : : [ Ee ]
< slash > : : : [ / ]
< zero_numeric > : : : [ 0 ]
< : : : [ 1 - 9 ]
< numeric > : : : [ 0 - 9 ]
<number> ::= <integer> | <rational> | <real>
<real> ::- (<signed_real>|<unsigned_real>)
<signed_real> ::- <sign><unsigned_real>
<unsigned_real> ::- (<decimal_fraction>|<decimal_exponent>)
<rational> ::- (<signed_rational>|<unsigned_rational>)
<signed_rational> ::- <sign><unsigned_rational>
<unsigned_rational> ::- <decimal><slash><positive_decimal>
<integer> ::- (<signed_integer>|<unsigned_integer>)
<signed_integer> ::- <sign><unsigned_integer>
<unsigned_integer> ::- <decimal>
<decimal> ::- (<zero_numeric>|<positive_decimal>)
<positive_decimal> ::- <non_zero_numeric><numeric>*
<decimal_exponent> ::- (<decimal>|<decimal_fraction>)<exponent><decimal>
<decimal_fraction> ::- <decimal><dot_decimal>
<dot_decimal> ::- <dot><numeric><numeric>*
<sign> ::: [+-]
<dot> ::: [.]
<exponent> ::: [Ee]
<slash> ::: [/]
<zero_numeric> ::: [0]
<non_zero_numeric> ::: [1-9]
<numeric> ::: [0-9] -}
number :: CharParser st Number
number = fmap Num_Real (real << skipAll)
<|> fmap Num_Rational (rational << skipAll)
<|> fmap Num_Integer (integer << skipAll)
THF & THF0 :
< file_name > : : = < single_quoted >
<file_name> ::= <single_quoted> -}
fileName :: CharParser st Token
fileName = singleQuoted
THF & THF0 :
< single_quoted > : : - < single_quote><sq_char><sq_char>*<single_quote >
< single_quote > : : : [ ' ]
< sq_char > : : : ( [ \40-\46\50-\133\135-\176]|[\\]['\\ ] )
<single_quoted> ::- <single_quote><sq_char><sq_char>*<single_quote>
<single_quote> ::: [']
<sq_char> ::: ([\40-\46\50-\133\135-\176]|[\\]['\\]) -}
singleQuoted :: CharParser st Token
singleQuoted = parseToken $ do
char '\''
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\'"
<|> tryString "\\\'"
<|> single ( satisfy (\ c -> printable c && notElem c "'\\")))
keyChar '\''
return s
THF & THF0 :
< distinct_object > : : - < double_quote><do_char>*<double_quote >
< do_char > : : : ( [ \40-\41\43-\133\135-\176]|[\\]["\\ ] )
< double_quote > : : : [ " ]
<distinct_object> ::- <double_quote><do_char>*<double_quote>
<do_char> ::: ([\40-\41\43-\133\135-\176]|[\\]["\\])
<double_quote> ::: ["] -}
distinctObject :: CharParser st Token
distinctObject = parseToken $ do
char '\"'
s <- fmap concat $ many1 (tryString "\\\\" <|> tryString "\\\""
<|> single ( satisfy (\ c -> printable c && notElem c "\"\\")))
keyChar '\"'
return s
THF & THF0 :
< lower_word > : : - < lower_alpha><alpha_numeric > *
< alpha_numeric > : : : ( < lower_alpha>|<upper_alpha>|<numeric>| [ _ ] )
< lower_alpha > : : : [ a - z ]
< upper_alpha > : : : [ A - Z ]
< numeric > : : : [ 0 - 9 ]
<lower_word> ::- <lower_alpha><alpha_numeric>*
<alpha_numeric> ::: (<lower_alpha>|<upper_alpha>|<numeric>|[_])
<lower_alpha> ::: [a-z]
<upper_alpha> ::: [A-Z]
<numeric> ::: [0-9] -}
lowerWord :: CharParser st Token
lowerWord = parseToken (do
l <- lower
an <- many (alphaNum <|> char '_')
skipAll
return (l : an)
<?> "alphanumeric word with leading lowercase letter")
printableChar :: CharParser st Char
printableChar = satisfy printable
printable :: Char -> Bool
printable c = ord c >= 32 && ord c <= 126
real :: CharParser st Token
real = parseToken (try (do
s <- oneOf "-+"
ur <- unsignedReal
return (s : ur))
<|> unsignedReal
<?> "(signed) real")
unsignedReal :: CharParser st String
unsignedReal = do
de <- try (do
d <- decimalFractional <|> decimal
e <- oneOf "Ee"
return (d ++ [e]))
ex <- integer
return (de ++ (show ex))
<|> decimalFractional
<?> "unsigned real"
rational :: CharParser st Token
rational = parseToken (try (do
s <- oneOf "-+"
ur <- unsignedRational
return (s : ur))
<|> unsignedRational
<?> "(signed) rational")
unsignedRational :: CharParser st String
unsignedRational = do
d1 <- try (decimal << char '/')
d2 <- positiveDecimal
return (d1 ++ "/" ++ d2)
integer :: CharParser st Token
integer = parseToken (try (do
s <- oneOf "-+"
ui <- unsignedInteger
return (s : ui))
<|> unsignedInteger
<?> "(signed) integer")
unsignedInteger :: CharParser st String
unsignedInteger = try (decimal << notFollowedBy (oneOf "eE/."))
decimal :: CharParser st String
decimal = do
char '0'
notFollowedBy digit
return "0"
<|> positiveDecimal
<?> "single zero or digits"
positiveDecimal :: CharParser st String
positiveDecimal = do
nz <- satisfy (\ c -> isDigit c && c /= '0')
d <- many digit
return (nz : d)
<?> "positiv decimal"
decimalFractional :: CharParser st String
decimalFractional = do
dec <- try (decimal << char '.')
n <- many1 digit
return (dec ++ "." ++ n)
<?> "decimal fractional"
skipAll :: CharParser st ()
skipAll = skipMany (skipMany1 space <|>
forget (comment <|> definedComment <|> systemComment))
skipSpaces :: CharParser st ()
skipSpaces = skipMany space
key :: CharParser st a -> CharParser st ()
key = (>> skipAll)
keyChar :: Char -> CharParser st ()
keyChar = key . char
myManyTill :: CharParser st a -> CharParser st a -> CharParser st [a]
myManyTill p end = do
e <- end
return [e]
<|> do
x <- p
xs <- myManyTill p end
return (x : xs)
vLine :: CharParser st ()
vLine = keyChar '|'
star :: CharParser st ()
star = keyChar '*'
plus :: CharParser st ()
plus = keyChar '+'
arrow :: CharParser st ()
arrow = keyChar '>'
comma :: CharParser st ()
comma = keyChar ','
colon :: CharParser st ()
colon = keyChar ':'
oParentheses :: CharParser st ()
oParentheses = keyChar '('
cParentheses :: CharParser st ()
cParentheses = keyChar ')'
parentheses :: CharParser st a -> CharParser st a
parentheses p = do
r <- try (oParentheses >> p)
cParentheses
return r
oBracket :: CharParser st ()
oBracket = keyChar '['
cBracket :: CharParser st ()
cBracket = keyChar ']'
brackets :: CharParser st a -> CharParser st a
brackets p = do
r <- try (oBracket >> p)
cBracket
return r
ampersand :: CharParser st ()
ampersand = keyChar '&'
at :: CharParser st ()
at = keyChar '@'
gentzenArrow :: CharParser st ()
gentzenArrow = key $ string "-->"
|
0acb7192cf0f0554683b90f17cba5037a7411f0d27c63467e938f7b9b7e9b418 | frizensami/singlang | ParserSpec.hs | module ParserSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import Lexer
import Parser
spec :: Spec
spec = do
describe "Parser" $ do
it "should parse simple let stmts" $
let
stmts = parseTokens [TLet, TVar "x", TEq, TInt 5]
in
stmts `shouldBe` [Let "x" (Int 5)] | null | https://raw.githubusercontent.com/frizensami/singlang/cecc7f34083d9ae4f748093285dd4b7463fe15a0/test/ParserSpec.hs | haskell | module ParserSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
import Lexer
import Parser
spec :: Spec
spec = do
describe "Parser" $ do
it "should parse simple let stmts" $
let
stmts = parseTokens [TLet, TVar "x", TEq, TInt 5]
in
stmts `shouldBe` [Let "x" (Int 5)] | |
2778cd6657f851a5840346c7743f654ae9739fc996541bd8971ea0f4bf6bc9d3 | ivankelly/gambit | m4.scm | (define (f1 x) (* 2 (f2 x)))
(display "hello from m4")
(newline)
(c-declare #<<c-declare-end
#include "x.h"
c-declare-end
)
(define x-initialize (c-lambda (char-string) bool "x_initialize"))
(define x-display-name (c-lambda () char-string "x_display_name"))
(define x-bell (c-lambda (int) void "x_bell"))
| null | https://raw.githubusercontent.com/ivankelly/gambit/7377246988d0982ceeb10f4249e96badf3ff9a8f/doc/m4.scm | scheme | (define (f1 x) (* 2 (f2 x)))
(display "hello from m4")
(newline)
(c-declare #<<c-declare-end
#include "x.h"
c-declare-end
)
(define x-initialize (c-lambda (char-string) bool "x_initialize"))
(define x-display-name (c-lambda () char-string "x_display_name"))
(define x-bell (c-lambda (int) void "x_bell"))
| |
1cd349acb253b74a53f7d65a17221c6ec329fa993e5dff6001744796923068cd | diagrams/geometry | Points.hs | -----------------------------------------------------------------------------
-- |
-- Module : Geometry.TwoD.Points
Copyright : ( c ) 2014 - 2017 diagrams team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
Special functions for points in R2 .
--
-----------------------------------------------------------------------------
# LANGUAGE TypeFamilies #
module Geometry.TwoD.Points where
import Data.List
import Linear.Affine
import Geometry.Space
import Geometry.TwoD.Types (P2)
import Geometry.TwoD.Vector
| Find the convex hull of a list of points using 's monotone chain
-- algorithm O(n log n).
--
-- Returns clockwise list of points starting from the left-most point.
convexHull2D :: OrderedField n => [P2 n] -> [P2 n]
convexHull2D ps = init upper ++ reverse (tail lower)
where
(upper, lower) = sortedConvexHull (sort ps)
-- | Find the convex hull of a set of points already sorted in the x direction.
The first list of the tuple is the upper hull going clockwise from
left - most to right - most point . The second is the lower hull from
-- right-most to left-most in the anti-clockwise direction.
sortedConvexHull :: OrderedField n => [P2 n] -> ([P2 n], [P2 n])
sortedConvexHull ps = (chain True ps, chain False ps)
where
chain upper (p1_:p2_:rest_) =
case go (p2_ .-. p1_) p2_ rest_ of
Right l -> p1_:l
Left l -> chain upper (p1_:l)
where
test = if upper then (>0) else (<0)
-- find the convex hull by comparing the angles of the vectors with
-- the cross product and backtracking if necessary
go d p1 l@(p2:rest)
-- backtrack if the direction is outward
| test $ d `crossZ` d' = Left l
| otherwise =
case go d' p2 rest of
Left m -> go d p1 m
Right m -> Right (p1:m)
where
d' = p2 .-. p1
go _ p1 p = Right (p1:p)
chain _ l = l
| null | https://raw.githubusercontent.com/diagrams/geometry/945c8c36b22e71d0c0e4427f23de6614f4e7594a/src/Geometry/TwoD/Points.hs | haskell | ---------------------------------------------------------------------------
|
Module : Geometry.TwoD.Points
License : BSD-style (see LICENSE)
Maintainer :
---------------------------------------------------------------------------
algorithm O(n log n).
Returns clockwise list of points starting from the left-most point.
| Find the convex hull of a set of points already sorted in the x direction.
right-most to left-most in the anti-clockwise direction.
find the convex hull by comparing the angles of the vectors with
the cross product and backtracking if necessary
backtrack if the direction is outward | Copyright : ( c ) 2014 - 2017 diagrams team ( see LICENSE )
Special functions for points in R2 .
# LANGUAGE TypeFamilies #
module Geometry.TwoD.Points where
import Data.List
import Linear.Affine
import Geometry.Space
import Geometry.TwoD.Types (P2)
import Geometry.TwoD.Vector
| Find the convex hull of a list of points using 's monotone chain
convexHull2D :: OrderedField n => [P2 n] -> [P2 n]
convexHull2D ps = init upper ++ reverse (tail lower)
where
(upper, lower) = sortedConvexHull (sort ps)
The first list of the tuple is the upper hull going clockwise from
left - most to right - most point . The second is the lower hull from
sortedConvexHull :: OrderedField n => [P2 n] -> ([P2 n], [P2 n])
sortedConvexHull ps = (chain True ps, chain False ps)
where
chain upper (p1_:p2_:rest_) =
case go (p2_ .-. p1_) p2_ rest_ of
Right l -> p1_:l
Left l -> chain upper (p1_:l)
where
test = if upper then (>0) else (<0)
go d p1 l@(p2:rest)
| test $ d `crossZ` d' = Left l
| otherwise =
case go d' p2 rest of
Left m -> go d p1 m
Right m -> Right (p1:m)
where
d' = p2 .-. p1
go _ p1 p = Right (p1:p)
chain _ l = l
|
25455ace23dc0d314089537db23699f72eecc74b2e438cf8b6dfaa288c3d6c9b | cyclone-scheme/winds | test.scm | (import (scheme base)
(cyclone test)
(libs semantic))
(define (run-tests)
(test-begin "Winds testing")
(test-group "Semantic versioning"
(test-group "Sanitizing improper dots"
(test "*.*.*" (sanitize-version "."))
(test "*.*.*" (sanitize-version ".1"))
(test "1.*.*" (sanitize-version "1."))
(test "*.*.*" (sanitize-version ".1.")))
(test-group "Sanitizing length"
(test "1.*.*" (sanitize-version "1"))
(test "1.1.*" (sanitize-version "1.1"))
(test "1.1.1" (sanitize-version "1.1.1"))
(test-error (sanitize-version "1.1.1."))
(test-error (sanitize-version "1.1.1.1"))
(test-error (sanitize-version "1.1.1.1.1")))
(test-group "Sanitizing placeholders (stars)"
(test "*.*.*" (sanitize-version "*"))
(test "*.*.*" (sanitize-version "*.1"))
(test "*.*.*" (sanitize-version "*.1.1"))
(test "1.*.*" (sanitize-version "1.*"))
(test "1.*.*" (sanitize-version "1.*.1"))
(test "1.1.*" (sanitize-version "1.1.*")))
(test-group "Evaluating greatest-version"
(test "0.0.2" (greatest-version "0.0.1" "0.0.2"))
(test "0.0.2" (greatest-version "0.0.2" "0.0.1")))
(test-group "Finding version on a list"
(test "0.10.2" (find-version "0.*.9" '("0.0.2" "0.10.2" "1.4.6")))
(test "9.3.21" (find-version "*" '("0.0.2" "0.10.2" "1.4.6" "9.3.21")))
(test "2.2.1" (find-version "2.2.1" '("0.0.2" "2.2.1" "1.4.6" "9.3.21"))))
(test-group "Latest version on a list"
(test "1.4.6" (latest-version '("0.0.2" "0.10.2" "1.4.6" "1.2.4")))))
(test-group "Winds commands"
(test-group "Remote work (read-only procedures)"
(test 0 (system "./winds -v index"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "./winds -v search srfi"))
(test 0 (system "./winds -v info iset")))
(test-group "Remote work (read and write procedures)"
(test 0 (system "sudo ./winds -v install iset"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "sudo ./winds -v reinstall iset"))
(test 0 (system "sudo ./winds -v upgrade string"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "sudo ./winds -v upgrade"))
(test 0 (system "sudo ./winds -v uninstall iset"))
(test 0 (system "sudo ./winds -v uninstall string")))
(test-group "Local work (write procedures)"
(test 0 (system "./winds -v retrieve array-list"))
(test 0 (system "cd array-list && ../winds -v build-local"))
(test 0 (system "./winds -v build-local array-list"))
(test 0 (system "cd array-list && .././winds -v test-local"))
(test 0 (system "./winds -v test-local array-list"))
(test 0 (system "cd array-list && ../winds -v package"))
(test 0 (system "./winds -v package array-list && rm -Rf array-list"))
(test 0 (system "./winds -v retrieve srfi-26"))
(test 0 (system "./winds -v package-srfi srfi-26 && rm -Rf srfi-26"))))
(test-end))
(run-tests)
| null | https://raw.githubusercontent.com/cyclone-scheme/winds/6921b2f444d9469c5cbd497c7b018de8c2a57d89/tests/test.scm | scheme | (import (scheme base)
(cyclone test)
(libs semantic))
(define (run-tests)
(test-begin "Winds testing")
(test-group "Semantic versioning"
(test-group "Sanitizing improper dots"
(test "*.*.*" (sanitize-version "."))
(test "*.*.*" (sanitize-version ".1"))
(test "1.*.*" (sanitize-version "1."))
(test "*.*.*" (sanitize-version ".1.")))
(test-group "Sanitizing length"
(test "1.*.*" (sanitize-version "1"))
(test "1.1.*" (sanitize-version "1.1"))
(test "1.1.1" (sanitize-version "1.1.1"))
(test-error (sanitize-version "1.1.1."))
(test-error (sanitize-version "1.1.1.1"))
(test-error (sanitize-version "1.1.1.1.1")))
(test-group "Sanitizing placeholders (stars)"
(test "*.*.*" (sanitize-version "*"))
(test "*.*.*" (sanitize-version "*.1"))
(test "*.*.*" (sanitize-version "*.1.1"))
(test "1.*.*" (sanitize-version "1.*"))
(test "1.*.*" (sanitize-version "1.*.1"))
(test "1.1.*" (sanitize-version "1.1.*")))
(test-group "Evaluating greatest-version"
(test "0.0.2" (greatest-version "0.0.1" "0.0.2"))
(test "0.0.2" (greatest-version "0.0.2" "0.0.1")))
(test-group "Finding version on a list"
(test "0.10.2" (find-version "0.*.9" '("0.0.2" "0.10.2" "1.4.6")))
(test "9.3.21" (find-version "*" '("0.0.2" "0.10.2" "1.4.6" "9.3.21")))
(test "2.2.1" (find-version "2.2.1" '("0.0.2" "2.2.1" "1.4.6" "9.3.21"))))
(test-group "Latest version on a list"
(test "1.4.6" (latest-version '("0.0.2" "0.10.2" "1.4.6" "1.2.4")))))
(test-group "Winds commands"
(test-group "Remote work (read-only procedures)"
(test 0 (system "./winds -v index"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "./winds -v search srfi"))
(test 0 (system "./winds -v info iset")))
(test-group "Remote work (read and write procedures)"
(test 0 (system "sudo ./winds -v install iset"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "sudo ./winds -v reinstall iset"))
(test 0 (system "sudo ./winds -v upgrade string"))
(test 0 (system "./winds -v local-status"))
(test 0 (system "sudo ./winds -v upgrade"))
(test 0 (system "sudo ./winds -v uninstall iset"))
(test 0 (system "sudo ./winds -v uninstall string")))
(test-group "Local work (write procedures)"
(test 0 (system "./winds -v retrieve array-list"))
(test 0 (system "cd array-list && ../winds -v build-local"))
(test 0 (system "./winds -v build-local array-list"))
(test 0 (system "cd array-list && .././winds -v test-local"))
(test 0 (system "./winds -v test-local array-list"))
(test 0 (system "cd array-list && ../winds -v package"))
(test 0 (system "./winds -v package array-list && rm -Rf array-list"))
(test 0 (system "./winds -v retrieve srfi-26"))
(test 0 (system "./winds -v package-srfi srfi-26 && rm -Rf srfi-26"))))
(test-end))
(run-tests)
| |
b33aa9f3dde56a1224c3700b40c2656450856edd1e1c196f967173cd58281ae6 | fhur/presto | core_test.clj | (ns presto.core-test
(:require [clojure.test :refer :all]
[presto.core :refer :all]))
(expected-when "test-inc" inc
:when [0] = 1
:when [1] = 2
:when [2] = 3
:when [3] = 4
:when [4] = 5
:when [5] = 6)
(expected-when "test-*" *
:when [1] = 1
:when [2123] = 2123
:when [7 2] = 14
:when [10 10 -2 -4] = 800
:when [] = 1)
(expected-when "test-=" =
:when [1] = true
:when [1 1] = true
:when ["a" "a" "a"] = true
:when [:foo :foo :foo :foo] = true
:when [1 2 3] = false
:when [1 "1"] = false)
;; You can also change the :when for a fail message
(expected-when "a test" *
when [1 1] = 1
when [2 3] = 6)
| null | https://raw.githubusercontent.com/fhur/presto/c03071c63412fe9ae689ba1ec7a9abeb13a91bfd/test/presto/core_test.clj | clojure | You can also change the :when for a fail message | (ns presto.core-test
(:require [clojure.test :refer :all]
[presto.core :refer :all]))
(expected-when "test-inc" inc
:when [0] = 1
:when [1] = 2
:when [2] = 3
:when [3] = 4
:when [4] = 5
:when [5] = 6)
(expected-when "test-*" *
:when [1] = 1
:when [2123] = 2123
:when [7 2] = 14
:when [10 10 -2 -4] = 800
:when [] = 1)
(expected-when "test-=" =
:when [1] = true
:when [1 1] = true
:when ["a" "a" "a"] = true
:when [:foo :foo :foo :foo] = true
:when [1 2 3] = false
:when [1 "1"] = false)
(expected-when "a test" *
when [1 1] = 1
when [2 3] = 6)
|
e3fe1995f333e01dde89763681438df920e0f93ead1577810c11c88813da280a | rmloveland/scheme48-0.53 | graph.scm | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
; Code to print out module dependencies in a format readable by the
graph layout program AT&T DOT Release 1.0 . ( for information on DOT call
the AT&T Software Technology Center Common Support Hotline ( 908 ) 582 - 7009 )
; Follow link script up to the actual linking
;(load-configuration "scheme/interfaces.scm")
;(load-configuration "scheme/packages.scm")
;(flatload initial-structures)
;(load "build/initial.scm")
;
; Load this and run it
;(load "scheme/debug/graph.scm")
;(dependency-graph (initial-packages)
; (map structure-package (list scheme-level-1 scheme-level-0))
; "graph.dot")
;
; Run the graph layout program
setenv SDE_LICENSE_FILE /pls / local / lib / DOT / LICENSE.dot
/pls / local / lib / DOT / dot -Tps graph.dot -o graph.ps
; Returns a list of the packages in the initial system.
(define (initial-packages)
(map (lambda (p)
(structure-package (cdr p)))
(append (struct-list scheme
environments
module-system
ensures-loaded
packages
packages-internal)
(desirable-structures))))
; Write the dependency graph found by rooting from PACKAGES to FILENAME.
Packages in the list IGNORE are ignored .
;
; Each configuration file's packages are done as a separate subgraph.
(define (dependency-graph packages ignore filename)
(call-with-output-file filename
(lambda (out)
(display prelude out)
(newline out)
(let ((subgraphs (do-next-package packages ignore '() ignore out)))
(for-each (lambda (sub)
(note-subgraph sub out))
subgraphs)
(display "}" out)
(newline out)))))
Do the first not - yet - done package , returning the subgraphs if there are
no packages left . TO - DO , DONE , and IGNORE are lists of packages .
SUBGRAPHS is an a - list indexed by source - file - name .
(define (do-next-package to-do done subgraphs ignore out)
(let loop ((to-do to-do))
(if (null? to-do)
subgraphs
(let ((package (car to-do)))
(if (memq package done)
(loop (cdr to-do))
(do-package package (cdr to-do) (cons package done)
subgraphs ignore out))))))
; Find the correct subgraph, add PACKAGE to it, note any edges, and continue
; with the rest of the graph.
(define (do-package package to-do done subgraphs ignore out)
(let* ((source-file (package-file-name package))
(opens (map structure-package
((package-opens-thunk package))))
(old-subgraph (assq source-file subgraphs))
(subgraph (or old-subgraph
(list source-file))))
(set-cdr! subgraph (cons package (cdr subgraph)))
(do-edges package opens source-file ignore out)
(do-next-package (append opens to-do)
done
(if old-subgraph
subgraphs
(cons subgraph subgraphs))
ignore
out)))
; Add an edge from each package in OPENS to PACKAGE, provided that the
two were defined in the same file .
(define (do-edges package opens source-file ignore out)
(let loop ((opens opens) (done ignore))
(if (not (null? opens))
(loop (cdr opens)
(let ((p (car opens)))
(if (or (memq p done)
(not (string=? source-file (package-file-name p))))
done
(begin
(note-edge p package out)
(cons p done))))))))
; Writing out the package name as a string (actually, its the name of
the first of the package 's clients ) .
(define (package-name package out)
(let ((clients (population->list (package-clients package))))
(write-char #\" out)
(display (structure-name (car clients)) out)
(write-char #\" out)))
Header for DOT files
(define prelude
"digraph G {
orientation=landscape;
size =\"10,7.5\";
page =\"8.5,11\";
ratio =fill;")
; Writing out edges and subgraphs
(define (note-edge from to out)
(display " " out)
(package-name from out)
(display " -> " out)
(package-name to out)
(write-char #\; out)
(newline out))
(define (note-subgraph subgraph out)
(display " subgraph \"cluster_" out)
(display (car subgraph) out)
(display "\" { label=\"" out)
(display (car subgraph) out)
(display "\"; " out)
(for-each (lambda (p)
(package-name p out)
(display "; " out))
(cdr subgraph))
(display "}" out)
(newline out))
| null | https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/debug/graph.scm | scheme | Code to print out module dependencies in a format readable by the
Follow link script up to the actual linking
(load-configuration "scheme/interfaces.scm")
(load-configuration "scheme/packages.scm")
(flatload initial-structures)
(load "build/initial.scm")
Load this and run it
(load "scheme/debug/graph.scm")
(dependency-graph (initial-packages)
(map structure-package (list scheme-level-1 scheme-level-0))
"graph.dot")
Run the graph layout program
Returns a list of the packages in the initial system.
Write the dependency graph found by rooting from PACKAGES to FILENAME.
Each configuration file's packages are done as a separate subgraph.
Find the correct subgraph, add PACKAGE to it, note any edges, and continue
with the rest of the graph.
Add an edge from each package in OPENS to PACKAGE, provided that the
Writing out the package name as a string (actually, its the name of
")
Writing out edges and subgraphs
out)
" out) | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
graph layout program AT&T DOT Release 1.0 . ( for information on DOT call
the AT&T Software Technology Center Common Support Hotline ( 908 ) 582 - 7009 )
setenv SDE_LICENSE_FILE /pls / local / lib / DOT / LICENSE.dot
/pls / local / lib / DOT / dot -Tps graph.dot -o graph.ps
(define (initial-packages)
(map (lambda (p)
(structure-package (cdr p)))
(append (struct-list scheme
environments
module-system
ensures-loaded
packages
packages-internal)
(desirable-structures))))
Packages in the list IGNORE are ignored .
(define (dependency-graph packages ignore filename)
(call-with-output-file filename
(lambda (out)
(display prelude out)
(newline out)
(let ((subgraphs (do-next-package packages ignore '() ignore out)))
(for-each (lambda (sub)
(note-subgraph sub out))
subgraphs)
(display "}" out)
(newline out)))))
Do the first not - yet - done package , returning the subgraphs if there are
no packages left . TO - DO , DONE , and IGNORE are lists of packages .
SUBGRAPHS is an a - list indexed by source - file - name .
(define (do-next-package to-do done subgraphs ignore out)
(let loop ((to-do to-do))
(if (null? to-do)
subgraphs
(let ((package (car to-do)))
(if (memq package done)
(loop (cdr to-do))
(do-package package (cdr to-do) (cons package done)
subgraphs ignore out))))))
(define (do-package package to-do done subgraphs ignore out)
(let* ((source-file (package-file-name package))
(opens (map structure-package
((package-opens-thunk package))))
(old-subgraph (assq source-file subgraphs))
(subgraph (or old-subgraph
(list source-file))))
(set-cdr! subgraph (cons package (cdr subgraph)))
(do-edges package opens source-file ignore out)
(do-next-package (append opens to-do)
done
(if old-subgraph
subgraphs
(cons subgraph subgraphs))
ignore
out)))
two were defined in the same file .
(define (do-edges package opens source-file ignore out)
(let loop ((opens opens) (done ignore))
(if (not (null? opens))
(loop (cdr opens)
(let ((p (car opens)))
(if (or (memq p done)
(not (string=? source-file (package-file-name p))))
done
(begin
(note-edge p package out)
(cons p done))))))))
the first of the package 's clients ) .
(define (package-name package out)
(let ((clients (population->list (package-clients package))))
(write-char #\" out)
(display (structure-name (car clients)) out)
(write-char #\" out)))
Header for DOT files
(define prelude
"digraph G {
(define (note-edge from to out)
(display " " out)
(package-name from out)
(display " -> " out)
(package-name to out)
(newline out))
(define (note-subgraph subgraph out)
(display " subgraph \"cluster_" out)
(display (car subgraph) out)
(display "\" { label=\"" out)
(display (car subgraph) out)
(for-each (lambda (p)
(package-name p out)
(display "; " out))
(cdr subgraph))
(display "}" out)
(newline out))
|
bb5000c26e0349f0592ac7866490b6482756befe58688fe583519297db6d9415 | LaurentRDC/pandoc-pyplot | Pyplot.hs | {-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
|
Module : $ header$
Description : Pandoc filter to create / Plotly figures from code blocks
Copyright : ( c ) , 2019
License : GNU GPL , version 2 or above
Maintainer :
Stability : stable
Portability : portable
This module defines a Pandoc filter @makePlot@ and related functions
that can be used to walk over a Pandoc document and generate figures from
Python code blocks .
The syntax for code blocks is simple , Code blocks with the @.pyplot@ or @.plotly@
attribute will trigger the filter . The code block will be reworked into a Python
script and the output figure will be captured , along with a high - resolution version
of the figure and the source code used to generate the figure .
To trigger pandoc - pyplot , one of the following is _ _ required _ _ :
* @.pyplot@ : Trigger pandoc - pyplot , rendering via the Matplotlib library
* @.plotly@ : Trigger pandoc - pyplot , rendering via the Plotly library
Here are the possible attributes what pandoc - pyplot understands :
* @directory= ... @ : Directory where to save the figure .
* @format= ... @ : Format of the generated figure . This can be an extension or an acronym , e.g. @format = png@.
* @caption=" ... "@ : Specify a plot caption ( or alternate text ) . Captions support Markdown formatting and LaTeX math ( @$ ... $@ ) .
* @dpi= ... @ : Specify a value for figure resolution , or dots - per - inch . Default is 80DPI . ( Matplotlib only , ignored otherwise )
* ... @ : Path to a Python script to include before the code block . Ideal to avoid repetition over many figures .
* = true|false@ : Add links to source code and high - resolution version of this figure .
This is @true@ by default , but you may wish to disable this for PDF output .
Custom configurations are possible via the @Configuration@ type and the filter
functions @plotTransformWithConfig@ and @makePlotWithConfig@.
Module : $header$
Description : Pandoc filter to create Matplotlib/Plotly figures from code blocks
Copyright : (c) Laurent P René de Cotret, 2019
License : GNU GPL, version 2 or above
Maintainer :
Stability : stable
Portability : portable
This module defines a Pandoc filter @makePlot@ and related functions
that can be used to walk over a Pandoc document and generate figures from
Python code blocks.
The syntax for code blocks is simple, Code blocks with the @.pyplot@ or @.plotly@
attribute will trigger the filter. The code block will be reworked into a Python
script and the output figure will be captured, along with a high-resolution version
of the figure and the source code used to generate the figure.
To trigger pandoc-pyplot, one of the following is __required__:
* @.pyplot@: Trigger pandoc-pyplot, rendering via the Matplotlib library
* @.plotly@: Trigger pandoc-pyplot, rendering via the Plotly library
Here are the possible attributes what pandoc-pyplot understands:
* @directory=...@ : Directory where to save the figure.
* @format=...@: Format of the generated figure. This can be an extension or an acronym, e.g. @format=png@.
* @caption="..."@: Specify a plot caption (or alternate text). Captions support Markdown formatting and LaTeX math (@$...$@).
* @dpi=...@: Specify a value for figure resolution, or dots-per-inch. Default is 80DPI. (Matplotlib only, ignored otherwise)
* @include=...@: Path to a Python script to include before the code block. Ideal to avoid repetition over many figures.
* @links=true|false@: Add links to source code and high-resolution version of this figure.
This is @true@ by default, but you may wish to disable this for PDF output.
Custom configurations are possible via the @Configuration@ type and the filter
functions @plotTransformWithConfig@ and @makePlotWithConfig@.
-}
module Text.Pandoc.Filter.Pyplot (
* Operating on single Pandoc blocks
makePlot
, makePlotWithConfig
* Operating on whole Pandoc documents
, plotTransform
, plotTransformWithConfig
-- * For configuration purposes
, configuration
, Configuration (..)
, PythonScript
, SaveFormat (..)
-- * For testing and internal purposes only
, PandocPyplotError(..)
, makePlot'
) where
import Control.Monad.Reader
import Data.Default.Class (def)
import Text.Pandoc.Definition
import Text.Pandoc.Walk (walkM)
import Text.Pandoc.Filter.Pyplot.Internal
-- | Main routine to include plots.
Code blocks containing the attributes @.pyplot@ or @.plotly@ are considered
-- Python plotting scripts. All other possible blocks are ignored.
makePlot' :: Block -> PyplotM (Either PandocPyplotError Block)
makePlot' block = do
parsed <- parseFigureSpec block
maybe
(return $ Right block)
(\s -> handleResult s <$> runScriptIfNecessary s)
parsed
where
handleResult _ (ScriptChecksFailed msg) = Left $ ScriptChecksFailedError msg
handleResult _ (ScriptFailure code) = Left $ ScriptError code
handleResult spec ScriptSuccess = Right $ toImage spec
| Highest - level function that can be walked over a Pandoc tree .
-- All code blocks that have the @.pyplot@ / @.plotly@ class will be considered
-- figures.
makePlot :: Block -> IO Block
makePlot = makePlotWithConfig def
| like @makePlot@ with with a custom default values .
--
-- @since 2.1.0.0
makePlotWithConfig :: Configuration -> Block -> IO Block
makePlotWithConfig config block =
runReaderT (makePlot' block >>= either (fail . show) return) config
| Walk over an entire Pandoc document , changing appropriate code blocks
-- into figures. Default configuration is used.
plotTransform :: Pandoc -> IO Pandoc
plotTransform = walkM makePlot
| Walk over an entire Pandoc document , changing appropriate code blocks
into figures . The default values are determined by a
--
-- @since 2.1.0.0
plotTransformWithConfig :: Configuration -> Pandoc -> IO Pandoc
plotTransformWithConfig = walkM . makePlotWithConfig
| null | https://raw.githubusercontent.com/LaurentRDC/pandoc-pyplot/c709ec46fc4977a5f6eb223375c15889214465fd/src/Text/Pandoc/Filter/Pyplot.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
* For configuration purposes
* For testing and internal purposes only
| Main routine to include plots.
Python plotting scripts. All other possible blocks are ignored.
All code blocks that have the @.pyplot@ / @.plotly@ class will be considered
figures.
@since 2.1.0.0
into figures. Default configuration is used.
@since 2.1.0.0 |
|
Module : $ header$
Description : Pandoc filter to create / Plotly figures from code blocks
Copyright : ( c ) , 2019
License : GNU GPL , version 2 or above
Maintainer :
Stability : stable
Portability : portable
This module defines a Pandoc filter @makePlot@ and related functions
that can be used to walk over a Pandoc document and generate figures from
Python code blocks .
The syntax for code blocks is simple , Code blocks with the @.pyplot@ or @.plotly@
attribute will trigger the filter . The code block will be reworked into a Python
script and the output figure will be captured , along with a high - resolution version
of the figure and the source code used to generate the figure .
To trigger pandoc - pyplot , one of the following is _ _ required _ _ :
* @.pyplot@ : Trigger pandoc - pyplot , rendering via the Matplotlib library
* @.plotly@ : Trigger pandoc - pyplot , rendering via the Plotly library
Here are the possible attributes what pandoc - pyplot understands :
* @directory= ... @ : Directory where to save the figure .
* @format= ... @ : Format of the generated figure . This can be an extension or an acronym , e.g. @format = png@.
* @caption=" ... "@ : Specify a plot caption ( or alternate text ) . Captions support Markdown formatting and LaTeX math ( @$ ... $@ ) .
* @dpi= ... @ : Specify a value for figure resolution , or dots - per - inch . Default is 80DPI . ( Matplotlib only , ignored otherwise )
* ... @ : Path to a Python script to include before the code block . Ideal to avoid repetition over many figures .
* = true|false@ : Add links to source code and high - resolution version of this figure .
This is @true@ by default , but you may wish to disable this for PDF output .
Custom configurations are possible via the @Configuration@ type and the filter
functions @plotTransformWithConfig@ and @makePlotWithConfig@.
Module : $header$
Description : Pandoc filter to create Matplotlib/Plotly figures from code blocks
Copyright : (c) Laurent P René de Cotret, 2019
License : GNU GPL, version 2 or above
Maintainer :
Stability : stable
Portability : portable
This module defines a Pandoc filter @makePlot@ and related functions
that can be used to walk over a Pandoc document and generate figures from
Python code blocks.
The syntax for code blocks is simple, Code blocks with the @.pyplot@ or @.plotly@
attribute will trigger the filter. The code block will be reworked into a Python
script and the output figure will be captured, along with a high-resolution version
of the figure and the source code used to generate the figure.
To trigger pandoc-pyplot, one of the following is __required__:
* @.pyplot@: Trigger pandoc-pyplot, rendering via the Matplotlib library
* @.plotly@: Trigger pandoc-pyplot, rendering via the Plotly library
Here are the possible attributes what pandoc-pyplot understands:
* @directory=...@ : Directory where to save the figure.
* @format=...@: Format of the generated figure. This can be an extension or an acronym, e.g. @format=png@.
* @caption="..."@: Specify a plot caption (or alternate text). Captions support Markdown formatting and LaTeX math (@$...$@).
* @dpi=...@: Specify a value for figure resolution, or dots-per-inch. Default is 80DPI. (Matplotlib only, ignored otherwise)
* @include=...@: Path to a Python script to include before the code block. Ideal to avoid repetition over many figures.
* @links=true|false@: Add links to source code and high-resolution version of this figure.
This is @true@ by default, but you may wish to disable this for PDF output.
Custom configurations are possible via the @Configuration@ type and the filter
functions @plotTransformWithConfig@ and @makePlotWithConfig@.
-}
module Text.Pandoc.Filter.Pyplot (
* Operating on single Pandoc blocks
makePlot
, makePlotWithConfig
* Operating on whole Pandoc documents
, plotTransform
, plotTransformWithConfig
, configuration
, Configuration (..)
, PythonScript
, SaveFormat (..)
, PandocPyplotError(..)
, makePlot'
) where
import Control.Monad.Reader
import Data.Default.Class (def)
import Text.Pandoc.Definition
import Text.Pandoc.Walk (walkM)
import Text.Pandoc.Filter.Pyplot.Internal
Code blocks containing the attributes @.pyplot@ or @.plotly@ are considered
makePlot' :: Block -> PyplotM (Either PandocPyplotError Block)
makePlot' block = do
parsed <- parseFigureSpec block
maybe
(return $ Right block)
(\s -> handleResult s <$> runScriptIfNecessary s)
parsed
where
handleResult _ (ScriptChecksFailed msg) = Left $ ScriptChecksFailedError msg
handleResult _ (ScriptFailure code) = Left $ ScriptError code
handleResult spec ScriptSuccess = Right $ toImage spec
| Highest - level function that can be walked over a Pandoc tree .
makePlot :: Block -> IO Block
makePlot = makePlotWithConfig def
| like @makePlot@ with with a custom default values .
makePlotWithConfig :: Configuration -> Block -> IO Block
makePlotWithConfig config block =
runReaderT (makePlot' block >>= either (fail . show) return) config
| Walk over an entire Pandoc document , changing appropriate code blocks
plotTransform :: Pandoc -> IO Pandoc
plotTransform = walkM makePlot
| Walk over an entire Pandoc document , changing appropriate code blocks
into figures . The default values are determined by a
plotTransformWithConfig :: Configuration -> Pandoc -> IO Pandoc
plotTransformWithConfig = walkM . makePlotWithConfig
|
db808f2d591315ef1efdbbe078949f6e8911285f16347dce62666f70a0cb66fa | tek/ribosome | BootError.hs | -- |The fatal error type
module Ribosome.Host.Data.BootError where
|This type represents the singular fatal error used by Ribosome .
--
-- Contrary to all other errors, this one is used with 'Error' instead of 'Stop'.
-- It is only thrown from intialization code of interpreters when operation of the plugin is impossible due to the error
-- condition.
newtype BootError =
BootError { unBootError :: Text }
deriving stock (Eq, Show)
deriving newtype (IsString, Ord)
| null | https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/host/lib/Ribosome/Host/Data/BootError.hs | haskell | |The fatal error type
Contrary to all other errors, this one is used with 'Error' instead of 'Stop'.
It is only thrown from intialization code of interpreters when operation of the plugin is impossible due to the error
condition. | module Ribosome.Host.Data.BootError where
|This type represents the singular fatal error used by Ribosome .
newtype BootError =
BootError { unBootError :: Text }
deriving stock (Eq, Show)
deriving newtype (IsString, Ord)
|
2ee92bb14c37c2bf8648d7c209ee3a2fc2a4d71ed16bd3b6c8958082af0ca96c | rowangithub/DOrder | 057_a-cppr.ml | let make_array n i = assert (0 <= i && i < n); 5
let update (i:int) (n:int) des (x:int) =
let a (j:int) = if i=j then x else des j in a
let print_int (n:int) = ()
let f (m:int) src des =
let rec bcopy (m:int) i (src: int->int) (des:int->int) =
if i >= m then
des
else
let des = update i m des (src i) in
bcopy m (i+1) src des
in
let rec print_array m i (array:int->int) =
if i >= m then
()
else
(print_int (array i);
print_array m (i + 1) array)
in
let array : int -> int = bcopy m 0 src des in
print_array m 0 array
let main n =
let array1 = make_array n in
let array2 = make_array n in
if (n > 0) then
f n array1 array2
else () | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/mochi2/benchs/057_a-cppr.ml | ocaml | let make_array n i = assert (0 <= i && i < n); 5
let update (i:int) (n:int) des (x:int) =
let a (j:int) = if i=j then x else des j in a
let print_int (n:int) = ()
let f (m:int) src des =
let rec bcopy (m:int) i (src: int->int) (des:int->int) =
if i >= m then
des
else
let des = update i m des (src i) in
bcopy m (i+1) src des
in
let rec print_array m i (array:int->int) =
if i >= m then
()
else
(print_int (array i);
print_array m (i + 1) array)
in
let array : int -> int = bcopy m 0 src des in
print_array m 0 array
let main n =
let array1 = make_array n in
let array2 = make_array n in
if (n > 0) then
f n array1 array2
else () | |
6aa5f1bc688894a1891e271a969b8634c3f100670fac93c977be957b70d6a8d4 | VisionsGlobalEmpowerment/webchange | icon_images.cljs | (ns webchange.ui.components.icon.system.icon-images)
(def data
[:svg {:xmlns ""
:width "14" :height "14" :viewBox "0 0 14 14"
:class-name "stroke-colored"
:fill "none" :stroke "#3453A1" :stroke-width "1" :stroke-miterlimit "10"}
[:path {:d "M10.1857 3.5H3.82209C3.64636 3.5 3.50391 3.64245 3.50391 3.81818V10.1818C3.50391 10.3575 3.64636 10.5 3.82209 10.5H10.1857C10.3615 10.5 10.5039 10.3575 10.5039 10.1818V3.81818C10.5039 3.64245 10.3615 3.5 10.1857 3.5Z"}]
[:path {:d "M10.5039 8.27338L8.8198 6.58929C8.76013 6.52962 8.6792 6.49609 8.59481 6.49609C8.51043 6.49609 8.4295 6.52962 8.36983 6.58929L6.59253 8.36658C6.53286 8.42625 6.45193 8.45978 6.36754 8.45978C6.28315 8.45978 6.20222 8.42625 6.14255 8.36658L5.3198 7.54383C5.26013 7.48416 5.1792 7.45064 5.09481 7.45064C5.01043 7.45064 4.9295 7.48416 4.86983 7.54383L3.50391 8.90975"}]
[:path {:d "M5.83333 5.83268C6.1555 5.83268 6.41667 5.57152 6.41667 5.24935C6.41667 4.92718 6.1555 4.66602 5.83333 4.66602C5.51117 4.66602 5.25 4.92718 5.25 5.24935C5.25 5.57152 5.51117 5.83268 5.83333 5.83268Z"}]])
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/acef27b5ce23ba1d34346eb07989ef639500b9b5/src/cljs/webchange/ui/components/icon/system/icon_images.cljs | clojure | (ns webchange.ui.components.icon.system.icon-images)
(def data
[:svg {:xmlns ""
:width "14" :height "14" :viewBox "0 0 14 14"
:class-name "stroke-colored"
:fill "none" :stroke "#3453A1" :stroke-width "1" :stroke-miterlimit "10"}
[:path {:d "M10.1857 3.5H3.82209C3.64636 3.5 3.50391 3.64245 3.50391 3.81818V10.1818C3.50391 10.3575 3.64636 10.5 3.82209 10.5H10.1857C10.3615 10.5 10.5039 10.3575 10.5039 10.1818V3.81818C10.5039 3.64245 10.3615 3.5 10.1857 3.5Z"}]
[:path {:d "M10.5039 8.27338L8.8198 6.58929C8.76013 6.52962 8.6792 6.49609 8.59481 6.49609C8.51043 6.49609 8.4295 6.52962 8.36983 6.58929L6.59253 8.36658C6.53286 8.42625 6.45193 8.45978 6.36754 8.45978C6.28315 8.45978 6.20222 8.42625 6.14255 8.36658L5.3198 7.54383C5.26013 7.48416 5.1792 7.45064 5.09481 7.45064C5.01043 7.45064 4.9295 7.48416 4.86983 7.54383L3.50391 8.90975"}]
[:path {:d "M5.83333 5.83268C6.1555 5.83268 6.41667 5.57152 6.41667 5.24935C6.41667 4.92718 6.1555 4.66602 5.83333 4.66602C5.51117 4.66602 5.25 4.92718 5.25 5.24935C5.25 5.57152 5.51117 5.83268 5.83333 5.83268Z"}]])
| |
0107c0197a2b2956e6744c27d409b543d189c74ec668abd165e07a5331664f80 | easyuc/EasyUC | ecHiGoal.ml | (* -------------------------------------------------------------------- *)
open EcUtils
open EcLocation
open EcSymbols
open EcParsetree
open EcTypes
open EcFol
open EcEnv
open EcMatching
open EcBaseLogic
open EcProofTerm
open EcCoreGoal
open EcCoreGoal.FApi
open EcLowGoal
module Sid = EcIdent.Sid
module Mid = EcIdent.Mid
module Sp = EcPath.Sp
module ER = EcReduction
module PT = EcProofTerm
module TT = EcTyping
module TTC = EcProofTyping
module LG = EcCoreLib.CI_Logic
(* -------------------------------------------------------------------- *)
type ttenv = {
tt_provers : EcParsetree.pprover_infos -> EcProvers.prover_infos;
tt_smtmode : [`Admit | `Strict | `Standard | `Report];
tt_implicits : bool;
tt_oldip : bool;
tt_redlogic : bool;
tt_und_delta : bool;
}
type engine = ptactic_core -> FApi.backward
(* -------------------------------------------------------------------- *)
let t_simplify_lg ?target ?delta (ttenv, logic) (tc : tcenv1) =
let logic =
match logic with
| `Default -> if ttenv.tt_redlogic then `Full else `ProductCompat
| `Variant -> if ttenv.tt_redlogic then `ProductCompat else `Full
in t_simplify ?target ?delta ~logic:(Some logic) tc
(* -------------------------------------------------------------------- *)
type focus_t = EcParsetree.tfocus
let process_tfocus tc (focus : focus_t) : tfocus =
let count = FApi.tc_count tc in
let check1 i =
let error () = tc_error !$tc "invalid focus index: %d" i in
if i >= 0
then if not (0 < i && i <= count) then error () else i-1
else if -i > count then error () else count+i
in
let checkfs fs =
List.fold_left
(fun rg (i1, i2) ->
let i1 = odfl min_int (omap check1 i1) in
let i2 = odfl max_int (omap check1 i2) in
if i1 <= i2 then ISet.add_range i1 i2 rg else rg)
ISet.empty fs
in
let posfs = omap checkfs (fst focus) in
let negfs = omap checkfs (snd focus) in
fun i ->
odfl true (posfs |> omap (ISet.mem i))
&& odfl true (negfs |> omap (fun fc -> not (ISet.mem i fc)))
(* -------------------------------------------------------------------- *)
let process_assumption (tc : tcenv1) =
EcLowGoal.t_assumption `Conv tc
(* -------------------------------------------------------------------- *)
let process_reflexivity (tc : tcenv1) =
try EcLowGoal.t_reflex tc
with InvalidGoalShape ->
tc_error !!tc "cannot prove goal by reflexivity"
(* -------------------------------------------------------------------- *)
let process_change fp (tc : tcenv1) =
let fp = TTC.tc1_process_formula tc fp in
t_change fp tc
(* -------------------------------------------------------------------- *)
let process_simplify_info ri (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let do1 (sop, sid) ps =
match ps.pl_desc with
| ([], s) when LDecl.has_name s hyps ->
let id = fst (LDecl.by_name s hyps) in
(sop, Sid.add id sid)
| qs ->
match EcEnv.Op.lookup_opt qs env with
| None -> tc_lookup_error !!tc ~loc:ps.pl_loc `Operator qs
| Some p -> (Sp.add (fst p) sop, sid)
in
let delta_p, delta_h =
ri.pdelta
|> omap (List.fold_left do1 (Sp.empty, Sid.empty))
|> omap (fun (x, y) -> (fun p -> if Sp.mem p x then `Force else `No), (Sid.mem^~ y))
|> odfl ((fun _ -> `Yes), predT)
in
{
EcReduction.beta = ri.pbeta;
EcReduction.delta_p = delta_p;
EcReduction.delta_h = delta_h;
EcReduction.zeta = ri.pzeta;
EcReduction.iota = ri.piota;
EcReduction.eta = ri.peta;
EcReduction.logic = if ri.plogic then Some `Full else None;
EcReduction.modpath = ri.pmodpath;
EcReduction.user = ri.puser;
EcReduction.cost = ri.pcost;
}
(*-------------------------------------------------------------------- *)
let process_simplify ri (tc : tcenv1) =
t_simplify_with_info (process_simplify_info ri tc) tc
(* -------------------------------------------------------------------- *)
let process_cbv ri (tc : tcenv1) =
t_cbv_with_info (process_simplify_info ri tc) tc
(* -------------------------------------------------------------------- *)
let process_smt ?loc (ttenv : ttenv) pi (tc : tcenv1) =
let pi = ttenv.tt_provers pi in
match ttenv.tt_smtmode with
| `Admit ->
t_admit tc
| (`Standard | `Strict) as mode ->
t_seq (t_simplify ~delta:false) (t_smt ~mode pi) tc
| `Report ->
t_seq (t_simplify ~delta:false) (t_smt ~mode:(`Report loc) pi) tc
(* -------------------------------------------------------------------- *)
let process_clear symbols tc =
let hyps = FApi.tc1_hyps tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps)
in
try t_clears (List.map toid symbols) tc
with (ClearError _) as err -> tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let process_algebra mode kind eqs (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcAlgTactic.is_module_loaded env) then
tacuerror "ring/field cannot be used when AlgTactic is not loaded";
let (ty, f1, f2) =
match sform_of_form concl with
| SFeq (f1, f2) -> (f1.f_ty, f1, f2)
| _ -> tacuerror "conclusion must be an equation"
in
let eqs =
let eq1 { pl_desc = x } =
match LDecl.hyp_exists x hyps with
| false -> tacuerror "cannot find equation referenced by `%s'" x
| true -> begin
match sform_of_form (snd (LDecl.hyp_by_name x hyps)) with
| SFeq (f1, f2) ->
if not (EcReduction.EqTest.for_type env ty f1.f_ty) then
tacuerror "assumption `%s' is not an equation over the right type" x;
(f1, f2)
| _ -> tacuerror "assumption `%s' is not an equation" x
end
in List.map eq1 eqs
in
let tparams = (LDecl.tohyps hyps).h_tvar in
let tactic =
match
match mode, kind with
| `Simpl, `Ring -> `Ring EcAlgTactic.t_ring_simplify
| `Simpl, `Field -> `Field EcAlgTactic.t_field_simplify
| `Solve, `Ring -> `Ring EcAlgTactic.t_ring
| `Solve, `Field -> `Field EcAlgTactic.t_field
with
| `Ring t ->
let r =
match TT.get_ring (tparams, ty) env with
| None -> tacuerror "cannot find a ring structure"
| Some r -> r
in t r eqs (f1, f2)
| `Field t ->
let r =
match TT.get_field (tparams, ty) env with
| None -> tacuerror "cannot find a field structure"
| Some r -> r
in t r eqs (f1, f2)
in
tactic tc
(* -------------------------------------------------------------------- *)
let t_apply_prept pt tc =
EcLowGoal.Apply.t_apply_bwd_r (pt_of_prept tc pt) tc
(* -------------------------------------------------------------------- *)
module LowRewrite = struct
type error =
| LRW_NotAnEquation
| LRW_NothingToRewrite
| LRW_InvalidOccurence
| LRW_CannotInfer
| LRW_IdRewriting
| LRW_RPatternNoMatch
| LRW_RPatternNoRuleMatch
exception RewriteError of error
let rec find_rewrite_patterns ~inpred (dir : rwside) pt =
let hyps = pt.PT.ptev_env.PT.pte_hy in
let env = LDecl.toenv hyps in
let pt = { pt with ptev_ax = snd (PT.concretize pt) } in
let ptc = { pt with ptev_env = EcProofTerm.copy pt.ptev_env } in
let ax = pt.ptev_ax in
let base ax =
match EcFol.sform_of_form ax with
| EcFol.SFeq (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFiff (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFnot f ->
let pt' = pt_of_global_r pt.ptev_env LG.p_negeqF [] in
let pt' = apply_pterm_to_arg_r pt' (PVAFormula f) in
let pt' = apply_pterm_to_arg_r pt' (PVASub pt) in
[(pt', `Eq, (f, f_false))]
| _ -> []
and split ax =
match EcFol.sform_of_form ax with
| EcFol.SFand (`Sym, (f1, f2)) ->
let pt1 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_l [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
let pt2 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_r [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
(find_rewrite_patterns ~inpred dir pt2)
@ (find_rewrite_patterns ~inpred dir pt1)
| _ -> []
in
match base ax with
| _::_ as rws -> rws
| [] -> begin
let ptb = Lazy.from_fun (fun () ->
let pt1 = split ax
and pt2 =
if dir = `LtoR then
if ER.EqTest.for_type env ax.f_ty tbool
then Some (ptc, `Bool, (ax, f_true))
else None
else None
and pt3 = omap base
(EcReduction.h_red_opt EcReduction.full_red hyps ax)
in pt1 @ (otolist pt2) @ (odfl [] pt3)) in
let rec doit reduce =
match TTC.destruct_product ~reduce hyps ax with
| None -> begin
if reduce then Lazy.force ptb else
let pts = doit true in
if inpred then pts else (Lazy.force ptb) @ pts
end
| Some _ ->
let pt = EcProofTerm.apply_pterm_to_hole pt in
find_rewrite_patterns ~inpred:(inpred || reduce) dir pt
in doit false
end
let find_rewrite_patterns = find_rewrite_patterns ~inpred:false
type rwinfos = rwside * EcFol.form option * EcMatching.occ option
let t_rewrite_r ?(mode = `Full) ?target ((s, prw, o) : rwinfos) pt tc =
let hyps, tgfp = FApi.tc1_flat ?target tc in
let modes =
match mode with
| `Full -> [{ k_keyed = true; k_conv = false };
{ k_keyed = true; k_conv = true };]
| `Light -> [{ k_keyed = true; k_conv = false }] in
let for1 (pt, mode, (f1, f2)) =
let fp, tp = match s with `LtoR -> f1, f2 | `RtoL -> f2, f1 in
let subf, occmode =
match prw with
| None -> begin
try
PT.pf_find_occurence_lazy pt.PT.ptev_env ~modes ~ptn:fp tgfp
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_NothingToRewrite)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end
| Some prw -> begin
let prw, _ =
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~full:false ~modes ~ptn:prw tgfp;
with PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoMatch) in
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~rooted:true ~modes ~ptn:fp prw
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoRuleMatch)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end in
if not occmode.k_keyed then begin
let tp = PT.concretize_form pt.PT.ptev_env tp in
if EcReduction.is_conv hyps fp tp then
raise (RewriteError LRW_IdRewriting);
end;
let pt = fst (PT.concretize pt) in
let cpos =
try FPosition.select_form
~xconv:`AlphaEq ~keyed:occmode.k_keyed
hyps o subf tgfp
with InvalidOccurence -> raise (RewriteError (LRW_InvalidOccurence))
in
EcLowGoal.t_rewrite
~keyed:occmode.k_keyed ?target ~mode pt (s, Some cpos) tc in
let rec do_first = function
| [] -> raise (RewriteError LRW_NothingToRewrite)
| (pt, mode, (f1, f2)) :: pts ->
try for1 (pt, mode, (f1, f2))
with RewriteError (LRW_NothingToRewrite | LRW_IdRewriting) ->
do_first pts
in
let pts = find_rewrite_patterns s pt in
if List.is_empty pts then
raise (RewriteError LRW_NotAnEquation);
do_first (List.rev pts)
let t_rewrite ?target (s, p, o) pt (tc : tcenv1) =
let hyps = FApi.tc1_hyps ?target tc in
let pt, ax = EcLowGoal.LowApply.check `Elim pt (`Hyps (hyps, !!tc)) in
let ptenv = ptenv_of_penv hyps !!tc in
t_rewrite_r ?target (s, p, o)
{ ptev_env = ptenv; ptev_pt = pt; ptev_ax = ax; }
tc
let t_autorewrite lemmas (tc : tcenv1) =
let pts =
let do1 lemma =
PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) lemma in
List.map do1 lemmas
in
let try1 pt tc =
let pt = { pt with PT.ptev_env = PT.copy pt.ptev_env } in
try t_rewrite_r (`LtoR, None, None) pt tc
with RewriteError _ -> raise InvalidGoalShape
in t_do_r ~focus:0 `Maybe None (t_ors (List.map try1 pts)) !@tc
end
let t_rewrite_prept info pt tc =
LowRewrite.t_rewrite_r info (pt_of_prept tc pt) tc
(* -------------------------------------------------------------------- *)
let process_solve ?bases ?depth (tc : tcenv1) =
match FApi.t_try_base (EcLowGoal.t_solve ~canfail:false ?bases ?depth) tc with
| `Failure _ ->
tc_error (FApi.tc1_penv tc) "[solve]: cannot close goal"
| `Success tc ->
tc
(* -------------------------------------------------------------------- *)
let process_trivial (tc : tcenv1) =
EcPhlAuto.t_pl_trivial ~conv:`Conv tc
(* -------------------------------------------------------------------- *)
let process_crushmode d =
d.cm_simplify, if d.cm_solve then Some process_trivial else None
(* -------------------------------------------------------------------- *)
let process_done tc =
let tc = process_trivial tc in
if not (FApi.tc_done tc) then
tc_error (FApi.tc_penv tc) "[by]: cannot close goals";
tc
(* -------------------------------------------------------------------- *)
let process_apply_bwd ~implicits mode (ff : ppterm) (tc : tcenv1) =
let pt = PT.tc1_process_full_pterm ~implicits tc ff in
try
match mode with
| `Alpha ->
begin try
PT.pf_form_match
pt.ptev_env
~mode:fmrigid
~ptn:pt.ptev_ax
(FApi.tc1_goal tc)
with EcMatching.MatchFailure ->
tc_error !!tc "proof-term is not alpha-convertible to conclusion" end;
EcLowGoal.t_apply (fst (PT.concretize pt)) tc
| `Apply ->
EcLowGoal.Apply.t_apply_bwd_r pt tc
| `Exact ->
let aout = EcLowGoal.Apply.t_apply_bwd_r pt tc in
let aout = FApi.t_onall process_trivial aout in
if not (FApi.tc_done aout) then
tc_error !!tc "cannot close goal";
aout
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let process_apply_fwd ~implicits (pe, hyp) tc =
let module E = struct exception NoInstance end in
let hyps = FApi.tc1_hyps tc in
if not (LDecl.hyp_exists (unloc hyp) hyps) then
tc_error !!tc "unknown hypothesis: %s" (unloc hyp);
let hyp, fp = LDecl.hyp_by_name (unloc hyp) hyps in
let pte = PT.tc1_process_full_pterm ~implicits tc pe in
try
let rec instantiate pte =
match TTC.destruct_product hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall _) ->
instantiate (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) ->
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, f2)
with MatchFailure -> raise E.NoInstance
in
let (pte, cutf) = instantiate pte in
if not (PT.can_concretize pte.ptev_env) then
tc_error !!tc "cannot infer all variables";
let pt = fst (PT.concretize pte) in
let pt = { pt with pt_args = pt.pt_args @ [palocal hyp]; } in
let cutf = PT.concretize_form pte.PT.ptev_env cutf in
FApi.t_last
(FApi.t_seq (t_clear hyp) (t_intros_i [hyp]))
(t_cutdef pt cutf tc)
with E.NoInstance ->
tc_error_lazy !!tc
(fun fmt ->
let ppe = EcPrinting.PPEnv.ofenv (FApi.tc1_env tc) in
Format.fprintf fmt
"cannot apply (in %a) the given proof-term for:\n\n%!"
(EcPrinting.pp_local ppe) hyp;
Format.fprintf fmt
" @[%a@]" (EcPrinting.pp_form ppe) pte.PT.ptev_ax)
(* -------------------------------------------------------------------- *)
let process_apply_top tc =
let hyps, concl = FApi.tc1_flat tc in
match TTC.destruct_product hyps concl with
| Some (`Imp _) -> begin
let h = LDecl.fresh_id hyps "h" in
try
EcLowGoal.t_intros_i_seq ~clear:true [h]
(EcLowGoal.Apply.t_apply_bwd { pt_head = PTLocal h; pt_args = []} )
tc
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
end
| _ -> tc_error !!tc "no top assumption"
(* -------------------------------------------------------------------- *)
let process_rewrite1_core ?mode ?(close = true) ?target (s, p, o) pt tc =
let o = norm_rwocc o in
try
let tc = LowRewrite.t_rewrite_r ?mode ?target (s, p, o) pt tc in
let cl = fun tc ->
if EcFol.f_equal f_true (FApi.tc1_goal tc) then
t_true tc
else t_id tc
in if close then FApi.t_last cl tc else tc
with
| LowRewrite.RewriteError e ->
match e with
| LowRewrite.LRW_NotAnEquation ->
tc_error !!tc "not an equation to rewrite"
| LowRewrite.LRW_NothingToRewrite ->
tc_error !!tc "nothing to rewrite"
| LowRewrite.LRW_InvalidOccurence ->
tc_error !!tc "invalid occurence selector"
| LowRewrite.LRW_CannotInfer ->
tc_error !!tc "cannot infer all placeholders"
| LowRewrite.LRW_IdRewriting ->
tc_error !!tc "refuse to perform an identity rewriting"
| LowRewrite.LRW_RPatternNoMatch ->
tc_error !!tc "r-pattern does not match the goal"
| LowRewrite.LRW_RPatternNoRuleMatch ->
tc_error !!tc "r-pattern does not match the rewriting rule"
(* -------------------------------------------------------------------- *)
let process_delta ~und_delta ?target (s, o, p) tc =
let env, hyps, concl = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let idtg, target =
match target with
| None -> (None, concl)
| Some h -> fst_map some (LDecl.hyp_by_name (unloc h) hyps)
in
match unloc p with
| PFident ({ pl_desc = ([], x) }, None)
when s = `LtoR && EcUtils.is_none o ->
let check_op = fun p -> if sym_equal (EcPath.basename p) x then `Force else `No in
let check_id = fun y -> sym_equal (EcIdent.name y) x in
let ri =
{ EcReduction.no_red with
EcReduction.delta_p = check_op;
EcReduction.delta_h = check_id; } in
let redform = EcReduction.simplify ri hyps target in
if und_delta then begin
if EcFol.f_equal target redform then
EcEnv.notify env `Warning "unused unfold: /%s" x
end;
t_change ~ri ?target:idtg redform tc
| _ ->
(* Continue with matching based unfolding *)
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
let (tvi, tparams, body, args, dp) =
match sform_of_form p with
| SFop (p, args) -> begin
let op = EcEnv.Op.by_path (fst p) env in
match op.EcDecl.op_kind with
| EcDecl.OB_oper (Some (EcDecl.OP_Plain (e, _))) ->
(snd p, op.EcDecl.op_tparams, form_of_expr EcFol.mhr e, args, Some (fst p))
| EcDecl.OB_pred (Some (EcDecl.PR_Plain f)) ->
(snd p, op.EcDecl.op_tparams, f, args, Some (fst p))
| _ ->
tc_error !!tc "the operator cannot be unfolded"
end
| SFlocal x when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, [], None)
| SFother { f_node = Fapp ({ f_node = Flocal x }, args) }
when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, args, None)
| _ -> tc_error !!tc "not headed by an operator/predicate"
in
let ri = { EcReduction.full_red with
delta_p = (fun p -> if Some p = dp then `Force else `Yes)} in
let na = List.length args in
match s with
| `LtoR -> begin
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:p target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let cpos =
let test = fun _ fp ->
let fp =
match fp.f_node with
| Fapp (h, hargs) when List.length hargs > na ->
let (a1, a2) = List.takedrop na hargs in
f_app h a1 (toarrow (List.map f_ty a2) fp.f_ty)
| _ -> fp
in
if EcReduction.is_alpha_eq hyps p fp
then `Accept (-1)
else `Continue
in
try FPosition.select ?o test target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target =
FPosition.map cpos
(fun topfp ->
let (fp, args) = EcFol.destr_app topfp in
match sform_of_form fp with
| SFop ((_, tvi), []) -> begin
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| SFlocal _ -> begin
assert (tparams = []);
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| _ -> assert false)
target
in
t_change ~ri ?target:idtg target tc
end else t_id tc
end
| `RtoL ->
let fp =
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let fp = f_app body args p.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps fp
with EcEnv.NotReducible -> fp
in
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:fp target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let fp = concretize_form ptenv fp in
let cpos =
try FPosition.select_form hyps o fp target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target = FPosition.map cpos (fun _ -> p) target in
t_change ~ri ?target:idtg target tc
end else t_id tc
(* -------------------------------------------------------------------- *)
let process_rewrite1_r ttenv ?target ri tc =
let implicits = ttenv.tt_implicits in
let und_delta = ttenv.tt_und_delta in
match unloc ri with
| RWDone simpl ->
let tt =
match simpl with
| Some logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic)
| None -> t_id
in FApi.t_seq tt process_trivial tc
| RWSimpl logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic) tc
| RWDelta ((s, r, o, px), p) -> begin
if Option.is_some px then
tc_error !!tc "cannot use pattern selection in delta-rewrite rules";
let do1 tc = process_delta ~und_delta ?target (s, o, p) tc in
match r with
| None -> do1 tc
| Some (b, n) -> t_do b n do1 tc
end
| RWRw (((s : rwside), r, o, p), pts) -> begin
let do1 (mode : [`Full | `Light]) ((subs : rwside), pt) tc =
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
let hyps = FApi.tc1_hyps ?target tc in
let ptenv, prw =
match p with
| None ->
PT.ptenv_of_penv hyps !!tc, None
| Some p ->
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(PT.ptenv !!tc hyps (ue, ev), Some p) in
let theside =
match s, subs with
| `LtoR, _ -> (subs :> rwside)
| _ , `LtoR -> (s :> rwside)
| `RtoL, `RtoL -> (`LtoR :> rwside) in
let is_baserw p =
EcEnv.BaseRw.is_base p.pl_desc (FApi.tc1_env tc) in
match pt with
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit && is_baserw p
->
let env = FApi.tc1_env tc in
let ls = snd (EcEnv.BaseRw.lookup p.pl_desc env) in
let ls = EcPath.Sp.elements ls in
let do1 lemma tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in t_ors (List.map do1 ls) tc
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit
->
let env = FApi.tc1_env tc in
let ptenv0 = PT.copy ptenv in
let pt = PT.process_full_pterm ~implicits ptenv pt
in
if is_ptglobal pt.PT.ptev_pt.pt_head
&& List.is_empty pt.PT.ptev_pt.pt_args
then begin
let ls = EcEnv.Ax.all ~name:(unloc p) env in
let do1 (lemma, _) tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv0) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc in
t_ors (List.map do1 ls) tc
end else
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
| _ ->
let pt = PT.process_full_pterm ~implicits ptenv pt in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in
let doall mode tc = t_ors (List.map (do1 mode) pts) tc in
match r with
| None ->
doall `Full tc
| Some (`Maybe, None) ->
t_seq
(t_do `Maybe (Some 1) (doall `Full))
(t_do `Maybe None (doall `Light))
tc
| Some (b, n) ->
t_do b n (doall `Full) tc
end
| RWPr (x, f) -> begin
if EcUtils.is_some target then
tc_error !!tc "cannot rewrite Pr[] in local assumptions";
EcPhlPrRw.t_pr_rewrite (unloc x, f) tc
end
| RWSmt (false, info) ->
process_smt ~loc:ri.pl_loc ttenv info tc
| RWSmt (true, info) ->
t_or process_done (process_smt ~loc:ri.pl_loc ttenv info) tc
| RWApp fp -> begin
let implicits = ttenv.tt_implicits in
match target with
| None -> process_apply_bwd ~implicits `Apply fp tc
| Some target -> process_apply_fwd ~implicits (fp, target) tc
end
| RWTactic `Ring ->
process_algebra `Solve `Ring [] tc
| RWTactic `Field ->
process_algebra `Solve `Field [] tc
(* -------------------------------------------------------------------- *)
let process_rewrite1 ttenv ?target ri tc =
EcCoreGoal.reloc (loc ri) (process_rewrite1_r ttenv ?target ri) tc
(* -------------------------------------------------------------------- *)
let process_rewrite ttenv ?target ri tc =
let do1 tc gi (fc, ri) =
let ngoals = FApi.tc_count tc in
let dorw = fun i tc ->
if gi = 0 || (i+1) = ngoals
then process_rewrite1 ttenv ?target ri tc
else process_rewrite1 ttenv ri tc
in
match fc |> omap ((process_tfocus tc) |- unloc) with
| None -> FApi.t_onalli dorw tc
| Some fc -> FApi.t_onselecti fc dorw tc
in
List.fold_lefti do1 (tcenv_of_tcenv1 tc) ri
(* -------------------------------------------------------------------- *)
let process_elimT qs tc =
let noelim () = tc_error !!tc "cannot recognize elimination principle" in
let (hyps, concl) = FApi.tc1_flat tc in
let (pf, pfty, _concl) =
match TTC.destruct_product hyps concl with
| Some (`Forall (x, GTty xty, concl)) -> (x, xty, concl)
| _ -> noelim ()
in
let pf = LDecl.fresh_id hyps (EcIdent.name pf) in
let tc = t_intros_i_1 [pf] tc in
let (hyps, concl) = FApi.tc1_flat tc in
let pt = PT.tc1_process_full_pterm tc qs in
let (_xp, xpty, ax) =
match TTC.destruct_product hyps pt.ptev_ax with
| Some (`Forall (xp, GTty xpty, f)) -> (xp, xpty, f)
| _ -> noelim ()
in
begin
let ue = pt.ptev_env.pte_ue in
try EcUnify.unify (LDecl.toenv hyps) ue (tfun pfty tbool) xpty
with EcUnify.UnificationFailure _ -> noelim ()
end;
if not (PT.can_concretize pt.ptev_env) then noelim ();
let ax = PT.concretize_form pt.ptev_env ax in
let rec skip ax =
match TTC.destruct_product hyps ax with
| Some (`Imp (_f1, f2)) -> skip f2
| Some (`Forall (x, GTty xty, f)) -> ((x, xty), f)
| _ -> noelim ()
in
let ((x, _xty), ax) = skip ax in
let fpf = f_local pf pfty in
let ptnpos = FPosition.select_form hyps None fpf concl in
let (_xabs, body) = FPosition.topattern ~x:x ptnpos concl in
let rec skipmatch ax body sk =
match TTC.destruct_product hyps ax, TTC.destruct_product hyps body with
| Some (`Imp (i1, f1)), Some (`Imp (i2, f2)) ->
if EcReduction.is_alpha_eq hyps i1 i2
then skipmatch f1 f2 (sk+1)
else sk
| _ -> sk
in
let sk = skipmatch ax body 0 in
t_seqs
[t_elimT_form (fst (PT.concretize pt)) ~sk fpf;
t_or
(t_clear pf)
(t_seq (t_generalize_hyp pf) (t_clear pf));
t_simplify_with_info EcReduction.beta_red]
tc
(* -------------------------------------------------------------------- *)
let process_view1 pe tc =
let module E = struct
exception NoInstance
exception NoTopAssumption
end in
let destruct hyps fp =
let doit fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, t), lazy f) -> `Forall (x, t, f)
| SFimp (f1, f2) -> `Imp (f1, f2)
| SFiff (f1, f2) -> `Iff (f1, f2)
| _ -> raise EcProofTyping.NoMatch
in
EcProofTyping.lazy_destruct hyps doit fp
in
let rec instantiate fp ids pte =
let hyps = pte.PT.ptev_env.PT.pte_hy in
match destruct hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall (x, xty, _)) ->
instantiate fp ((x, xty) :: ids) (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `None)
with MatchFailure -> raise E.NoInstance
end
| Some (`Iff (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `IffLR (f1, f2))
with MatchFailure -> try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f2 fp;
(pte, ids, f1, `IffRL (f1, f2))
with MatchFailure ->
raise E.NoInstance
end
in
try
match TTC.destruct_product (tc1_hyps tc) (FApi.tc1_goal tc) with
| None -> raise E.NoTopAssumption
| Some (`Forall _) ->
process_elimT pe tc
| Some (`Imp (f1, _)) when pe.fp_head = FPCut None ->
let hyps = FApi.tc1_hyps tc in
let hid = LDecl.fresh_id hyps "h" in
let hqs = mk_loc _dummy ([], EcIdent.name hid) in
let pe = { pe with fp_head = FPNamed (hqs, None) } in
t_intros_i_seq ~clear:true [hid]
(fun tc ->
let pe = PT.tc1_process_full_pterm tc pe in
let regen =
if PT.can_concretize pe.PT.ptev_env then [] else
snd (List.fold_left_map (fun f1 arg ->
let pre, f1 =
match oget (TTC.destruct_product (tc1_hyps tc) f1) with
| `Imp (_, f1) -> (None, f1)
| `Forall (x, xty, f1) ->
let aout =
match xty with GTty ty -> Some (x, ty) | _ -> None
in (aout, f1)
in
let module E = struct exception Bailout end in
try
let v =
match arg with
| PAFormula { f_node = Flocal x } ->
let meta =
let env = !(pe.PT.ptev_env.pte_ev) in
MEV.mem x `Form env && not (MEV.isset x `Form env) in
if not meta then raise E.Bailout;
let y, yty =
let CPTEnv subst = PT.concretize_env pe.PT.ptev_env in
snd_map subst.fs_ty (oget pre) in
let fy = EcIdent.fresh y in
pe.PT.ptev_env.pte_ev := MEV.set
x (`Form (f_local fy yty)) !(pe.PT.ptev_env.pte_ev);
(fy, yty)
| _ ->
raise E.Bailout
in (f1, Some v)
with E.Bailout -> (f1, None)
) f1 pe.PT.ptev_pt.pt_args)
in
let regen = List.pmap (fun x -> x) regen in
let bds = List.map (fun (x, ty) -> (x, GTty ty)) regen in
if not (PT.can_concretize pe.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = snd_map (f_forall bds) (PT.concretize pe) in
t_first (fun subtc ->
let regen = List.fst regen in
let ttcut tc =
t_onall
(EcLowGoal.t_generalize_hyps ~clear:`Yes regen)
(EcLowGoal.t_apply pt tc) in
t_intros_i_seq regen ttcut subtc
) (t_cut ax tc)
) tc
| Some (`Imp (f1, _)) ->
let top = LDecl.fresh_id (tc1_hyps tc) "h" in
let tc = t_intros_i_1 [top] tc in
let hyps = tc1_hyps tc in
let pte = PT.tc1_process_full_pterm tc pe in
let inargs = List.length pte.PT.ptev_pt.pt_args in
let (pte, ids, cutf, view) = instantiate f1 [] pte in
let evm = !(pte.PT.ptev_env.PT.pte_ev) in
let args = List.drop inargs pte.PT.ptev_pt.pt_args in
let args = List.combine (List.rev ids) args in
let ids =
let for1 ((_, ty) as idty, arg) =
match ty, arg with
| GTty _, PAFormula { f_node = Flocal x } when MEV.mem x `Form evm ->
if MEV.isset x `Form evm then None else Some (x, idty)
| GTmem _, PAMemory x when MEV.mem x `Mem evm ->
if MEV.isset x `Mem evm then None else Some (x, idty)
| _, _ -> assert false
in List.pmap for1 args
in
let cutf =
let ptenv = PT.copy pte.PT.ptev_env in
let for1 evm (x, idty) =
match idty with
| id, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| id, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _ , GTmodty _ -> assert false
in
List.iter (for1 ptenv.PT.pte_ev) ids;
if not (PT.can_concretize ptenv) then
tc_error !!tc "cannot infer all type variables";
PT.concretize_e_form
(PT.concretize_env ptenv)
(f_forall (List.map snd ids) cutf)
in
let discharge tc =
let intros = List.map (EcIdent.name |- fst |- snd) ids in
let intros = LDecl.fresh_ids hyps intros in
let for1 evm (x, idty) id =
match idty with
| _, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| _, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _, GTmodty _ -> assert false
in
let tc = EcLowGoal.t_intros_i_1 intros tc in
List.iter2 (for1 pte.PT.ptev_env.PT.pte_ev) ids intros;
let pte =
match view with
| `None -> pte
| `IffLR (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_lr [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
| `IffRL (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_rl [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
in
let pt = fst (PT.concretize (PT.apply_pterm_to_hole pte)) in
FApi.t_seq
(EcLowGoal.t_apply pt)
(EcLowGoal.t_apply_hyp top)
tc
in
FApi.t_internal
(FApi.t_seqsub (EcLowGoal.t_cut cutf)
[EcLowGoal.t_close ~who:"view" discharge;
EcLowGoal.t_clear top])
tc
with
| E.NoInstance ->
tc_error !!tc "cannot apply view"
| E.NoTopAssumption ->
tc_error !!tc "no top assumption"
(* -------------------------------------------------------------------- *)
let process_view pes tc =
let views = List.map (t_last |- process_view1) pes in
List.fold_left (fun tc tt -> tt tc) (FApi.tcenv_of_tcenv1 tc) views
(* -------------------------------------------------------------------- *)
module IntroState : sig
type state
type action = [ `Revert | `Dup | `Clear ]
val create : unit -> state
val push : ?name:symbol -> action -> EcIdent.t -> state -> unit
val listing : state -> ([`Gen of genclear | `Clear] * EcIdent.t) list
val naming : state -> (EcIdent.t -> symbol option)
end = struct
type state = {
mutable torev : ([`Gen of genclear | `Clear] * EcIdent.t) list;
mutable naming : symbol option Mid.t;
}
and action = [ `Revert | `Dup | `Clear ]
let create () =
{ torev = []; naming = Mid.empty; }
let push ?name action id st =
let map =
Mid.change (function
| None -> Some name
| Some _ -> assert false)
id st.naming
and action =
match action with
| `Revert -> `Gen `TryClear
| `Dup -> `Gen `NoClear
| `Clear -> `Clear
in
st.torev <- (action, id) :: st.torev;
st.naming <- map
let listing (st : state) =
List.rev st.torev
let naming (st : state) (x : EcIdent.t) =
Mid.find_opt x st.naming |> odfl None
end
(* -------------------------------------------------------------------- *)
exception IntroCollect of [
`InternalBreak
]
exception CollectBreak
exception CollectCore of ipcore located
let rec process_mintros_1 ?(cf = true) ttenv pis gs =
let module ST = IntroState in
let mk_intro ids (hyps, form) =
let (_, torev), ids =
let rec compile (((hyps, form), torev) as acc) newids ids =
match ids with [] -> (acc, newids) | s :: ids ->
let rec destruct fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, _) , lazy fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFlet (LSymbol (x, _), _, fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFimp (_, fp) ->
("H", None, `Hyp, fp)
| _ -> begin
match EcReduction.h_red_opt EcReduction.full_red hyps fp with
| None -> ("_", None, `None, f_true)
| Some f -> destruct f
end
in
let name, revname, kind, form = destruct form in
let revertid =
if ttenv.tt_oldip then
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (None , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
if (a = Some None && kind = `None) || a = Some (Some 0)
then None
else Some (None, LDecl.fresh_id hyps name)
else
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (Some true , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
match a, kind with
| Some None, `None ->
None
| (Some (Some 0), _) ->
None
| _, `Named ->
Some (None, LDecl.fresh_id hyps ("`" ^ name))
| _, _ ->
Some (None, LDecl.fresh_id hyps "_")
in
match revertid with
| Some (revert, id) ->
let id = mk_loc s.pl_loc id in
let hyps = LDecl.add_local id.pl_desc (LD_var (tbool, None)) hyps in
let revert = revert |> omap (fun b -> if b then `Clear else `Revert) in
let torev = revert
|> omap (fun b -> (b, unloc id, revname) :: torev)
|> odfl torev
in
let newids = Tagged (unloc id, Some id.pl_loc) :: newids in
let ((hyps, form), torev), newids =
match unloc s with
| `Anonymous (Some None) when kind <> `None ->
compile ((hyps, form), torev) newids [s]
| `Anonymous (Some (Some i)) when 1 < i ->
let s = mk_loc (loc s) (`Anonymous (Some (Some (i-1)))) in
compile ((hyps, form), torev) newids [s]
| _ -> ((hyps, form), torev), newids
in compile ((hyps, form), torev) newids ids
| None -> compile ((hyps, form), torev) newids ids
in snd_map List.rev (compile ((hyps, form), []) [] ids)
in (List.rev torev, ids)
in
let rec collect intl acc core pis =
let maybe_core () =
let loc = EcLocation.mergeall (List.map loc core) in
match core with
| [] -> acc
| _ -> mk_loc loc (`Core (List.rev core)) :: acc
in
match pis with
| [] -> (maybe_core (), [])
| { pl_loc = ploc } as pi :: pis ->
try
let ip =
match unloc pi with
| IPBreak ->
if intl then raise (IntroCollect `InternalBreak);
raise CollectBreak
| IPCore x -> raise (CollectCore (mk_loc (loc pi) x))
| IPDup -> `Dup
| IPDone x -> `Done x
| IPSmt x -> `Smt x
| IPClear x -> `Clear x
| IPRw x -> `Rw x
| IPDelta x -> `Delta x
| IPView x -> `View x
| IPSubst x -> `Subst x
| IPSimplify x -> `Simpl x
| IPCrush x -> `Crush x
| IPCase (mode, x) ->
let subcollect = List.rev -| fst -| collect true [] [] in
`Case (mode, List.map subcollect x)
| IPSubstTop x -> `SubstTop x
in collect intl (mk_loc ploc ip :: maybe_core ()) [] pis
with
| CollectBreak -> (maybe_core (), pis)
| CollectCore x -> collect intl acc (x :: core) pis
in
let collect pis = collect false [] [] pis in
let rec intro1_core (st : ST.state) ids (tc : tcenv1) =
let torev, ids = mk_intro ids (FApi.tc1_flat tc) in
List.iter (fun (act, id, name) -> ST.push ?name act id st) torev;
t_intros ids tc
and intro1_dup (_ : ST.state) (tc : tcenv1) =
try
let pt = PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) LG.p_ip_dup in
EcLowGoal.Apply.t_apply_bwd_r ~mode:fmrigid ~canview:false pt tc
with EcLowGoal.Apply.NoInstance _ ->
tc_error !!tc "no top-assumption to duplicate"
and intro1_done (_ : ST.state) simplify (tc : tcenv1) =
let t =
match simplify with
| Some x ->
t_seq (t_simplify_lg ~delta:false (ttenv, x)) process_trivial
| None -> process_trivial
in t tc
and intro1_smt (_ : ST.state) ((dn, pi) : _ * pprover_infos) (tc : tcenv1) =
if dn then
t_or process_done (process_smt ttenv pi) tc
else process_smt ttenv pi tc
and intro1_simplify (_ : ST.state) logic tc =
t_simplify_lg ~delta:false (ttenv, logic) tc
and intro1_clear (_ : ST.state) xs tc =
process_clear xs tc
and intro1_case (st : ST.state) nointro pis gs =
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let tc = t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case] in
let tc =
fun g ->
try tc g
with InvalidGoalShape ->
tc_error !!g "invalid intro-pattern: nothing to eliminate"
in
if nointro && not cf then onsub gs else begin
match pis with
| [] -> t_onall tc gs
| _ -> t_onall (fun gs -> onsub (tc gs)) gs
end
and intro1_full_case (st : ST.state)
((prind, delta), withor, (cnt : icasemode_full option)) pis tc
=
let cnt = cnt |> odfl (`AtMost 1) in
let red = if delta then `Full else `NoDelta in
let t_case =
let t_and, t_or =
if prind then
((fun tc -> fst_map List.singleton (t_elim_iso_and ~reduce:red tc)),
(fun tc -> t_elim_iso_or ~reduce:red tc))
else
((fun tc -> ([2] , t_elim_and ~reduce:red tc)),
(fun tc -> ([1; 1], t_elim_or ~reduce:red tc))) in
let ts = if withor then [t_and; t_or] else [t_and] in
fun tc -> FApi.t_or_map ts tc
in
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let doit tc =
let rec aux imax tc =
if imax = Some 0 then t_id tc else
try
let ntop, tc = t_case tc in
FApi.t_sublasts
(List.map (fun i tc -> aux (omap ((+) (i-1)) imax) tc) ntop)
tc
with InvalidGoalShape ->
try
tc |> EcLowGoal.t_intro_sx_seq
`Fresh
(fun id ->
t_seq
(aux (omap ((+) (-1)) imax))
(t_generalize_hyps ~clear:`Yes [id]))
with
| EcCoreGoal.TcError _ when EcUtils.is_some imax ->
tc_error !!tc "not enough top-assumptions"
| EcCoreGoal.TcError _ ->
t_id tc
in
match cnt with
| `AtMost cnt -> aux (Some (max 1 cnt)) tc
| `AsMuch -> aux None tc
in
if List.is_empty pis then doit tc else onsub (doit tc)
and intro1_rw (_ : ST.state) (o, s) tc =
let h = EcIdent.create "_" in
let rwt tc =
let pt = PT.pt_of_hyp !!tc (FApi.tc1_hyps tc) h in
process_rewrite1_core ~close:false (s, None, o) pt tc
in t_seqs [t_intros_i [h]; rwt; t_clear h] tc
and intro1_unfold (_ : ST.state) (s, o) p tc =
process_delta ~und_delta:ttenv.tt_und_delta (s, o, p) tc
and intro1_view (_ : ST.state) pe tc =
process_view1 pe tc
and intro1_subst (_ : ST.state) d (tc : tcenv1) =
try
t_intros_i_seq ~clear:true [EcIdent.create "_"]
(EcLowGoal.t_subst ~clear:true ~tside:(d :> tside))
tc
with InvalidGoalShape ->
tc_error !!tc "nothing to substitute"
and intro1_subst_top (_ : ST.state) (omax, osd) (tc : tcenv1) =
let t_subst eqid =
let sk1 = { empty_subst_kind with sk_local = true ; } in
let sk2 = { full_subst_kind with sk_local = false; } in
let side = `All osd in
FApi.t_or
(t_subst ~tside:side ~kind:sk1 ~eqid)
(t_subst ~tside:side ~kind:sk2 ~eqid)
in
let togen = ref [] in
let rec doit i tc =
match omax with Some max when i >= max -> tcenv_of_tcenv1 tc | _ ->
try
let id = EcIdent.create "_" in
let tc = EcLowGoal.t_intros_i_1 [id] tc in
FApi.t_switch (t_subst id) ~ifok:(doit (i+1))
~iffail:(fun tc -> togen := id :: !togen; doit (i+1) tc)
tc
with EcCoreGoal.TcError _ ->
if is_some omax then
tc_error !!tc "not enough top-assumptions";
tcenv_of_tcenv1 tc in
let tc = doit 0 tc in
t_generalize_hyps
~clear:`Yes ~missing:true
(List.rev !togen) (FApi.as_tcenv1 tc)
and intro1_crush (_st : ST.state) (d : crushmode) (gs : tcenv1) =
let delta, tsolve = process_crushmode d in
FApi.t_or
(EcPhlConseq.t_conseqauto ~delta ?tsolve)
(EcLowGoal.t_crush ~delta ?tsolve)
gs
and dointro (st : ST.state) nointro pis (gs : tcenv) =
match pis with [] -> gs | { pl_desc = pi; pl_loc = ploc } :: pis ->
let nointro, gs =
let rl x = EcCoreGoal.reloc ploc x in
match pi with
| `Core ids ->
(false, rl (t_onall (intro1_core st ids)) gs)
| `Dup ->
(false, rl (t_onall (intro1_dup st)) gs)
| `Done b ->
(nointro, rl (t_onall (intro1_done st b)) gs)
| `Smt pi ->
(nointro, rl (t_onall (intro1_smt st pi)) gs)
| `Simpl b ->
(nointro, rl (t_onall (intro1_simplify st b)) gs)
| `Clear xs ->
(nointro, rl (t_onall (intro1_clear st xs)) gs)
| `Case (`One, pis) ->
(false, rl (intro1_case st nointro pis) gs)
| `Case (`Full x, pis) ->
(false, rl (t_onall (intro1_full_case st x pis)) gs)
| `Rw (o, s, None) ->
(false, rl (t_onall (intro1_rw st (o, s))) gs)
| `Rw (o, s, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_rw st (o, s)))) gs)
| `Delta ((o, s), p) ->
(nointro, rl (t_onall (intro1_unfold st (o, s) p)) gs)
| `View pe ->
(false, rl (t_onall (intro1_view st pe)) gs)
| `Subst (d, None) ->
(false, rl (t_onall (intro1_subst st d)) gs)
| `Subst (d, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_subst st d))) gs)
| `SubstTop d ->
(false, rl (t_onall (intro1_subst_top st d)) gs)
| `Crush d ->
(false, rl (t_onall (intro1_crush st d)) gs)
in dointro st nointro pis gs
and dointro1 st nointro pis tc =
dointro st nointro pis (FApi.tcenv_of_tcenv1 tc) in
try
let st = ST.create () in
let ip, pis = collect pis in
let gs = dointro st true (List.rev ip) gs in
let gs =
let ls = ST.listing st in
let gn = List.pmap (function (`Gen x, y) -> Some (x, y) | _ -> None) ls in
let cl = List.pmap (function (`Clear, y) -> Some y | _ -> None) ls in
t_onall (fun tc ->
t_generalize_hyps_x
~missing:true ~naming:(ST.naming st)
gn tc)
(t_onall (t_clears cl) gs)
in
if List.is_empty pis then gs else
gs |> t_onall (fun tc ->
process_mintros_1 ~cf:true ttenv pis (FApi.tcenv_of_tcenv1 tc))
with IntroCollect e -> begin
match e with
| `InternalBreak ->
tc_error !$gs "cannot use internal break in intro-patterns"
end
(* -------------------------------------------------------------------- *)
let process_intros_1 ?cf ttenv pis tc =
process_mintros_1 ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let rec process_mintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc = process_mintros_1 ?cf ttenv pi tc in
process_mintros ~cf:false ttenv pis tc
(* -------------------------------------------------------------------- *)
let process_intros ?cf ttenv pis tc =
process_mintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let process_generalize1 ?(doeq = false) pattern (tc : tcenv1) =
let env, hyps, concl = FApi.tc1_eflat tc in
let onresolved ?(tryclear = true) pattern =
let clear = if tryclear then `Yes else `No in
match pattern with
| `Form (occ, pf) -> begin
match pf.pl_desc with
| PFident ({pl_desc = ([], s)}, None)
when not doeq && is_none occ && LDecl.has_name s hyps
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc pf in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
(try ignore (PT.pf_find_occurence ptenv ~ptn:p concl)
with PT.FindOccFailure _ -> tc_error !!tc "cannot find an occurence");
let p = PT.concretize_form ptenv p in
let occ = norm_rwocc occ in
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps occ p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
let name =
match EcParsetree.pf_ident pf with
| None ->
EcIdent.create "x"
| Some x when EcIo.is_sym_ident x ->
EcIdent.create x
| Some _ ->
EcIdent.create (EcTypes.symbol_of_ty p.f_ty)
in
let name, newconcl = FPosition.topattern ~x:name cpos concl in
let newconcl =
if doeq then
if EcReduction.EqTest.for_type env p.f_ty tbool then
f_imps [f_iff p (f_local name p.f_ty)] newconcl
else
f_imps [f_eq p (f_local name p.f_ty)] newconcl
else newconcl in
let newconcl = f_forall [(name, GTty p.f_ty)] newconcl in
let pt = { pt_head = PTCut newconcl; pt_args = [PAFormula p]; } in
EcLowGoal.t_apply pt tc
end
| `ProofTerm fp -> begin
match fp.fp_head with
| FPNamed ({ pl_desc = ([], s) }, None)
when LDecl.has_name s hyps && List.is_empty fp.fp_args
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let pt = PT.tc1_process_full_pterm tc fp in
if not (PT.can_concretize pt.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
t_cutdef pt ax tc
end
| `LetIn x ->
let id =
let binding =
try Some (LDecl.by_name (unloc x) hyps)
with EcEnv.LDecl.LdeclError _ -> None in
match binding with
| Some (id, LD_var (_, Some _)) -> id
| _ ->
let msg = "symbol must reference let-in" in
tc_error ~loc:(loc x) !!tc "%s" msg
in t_generalize_hyp ~clear ~letin:true id tc
in
match ffpattern_of_genpattern hyps pattern with
| Some ff ->
let tryclear =
match pattern with
| (`Form (None, { pl_desc = PFident _ })) -> true
| _ -> false
in onresolved ~tryclear (`ProofTerm ff)
| None -> onresolved pattern
(* -------------------------------------------------------------------- *)
let process_generalize ?(doeq = false) patterns (tc : tcenv1) =
try
let patterns = List.mapi (fun i p ->
process_generalize1 ~doeq:(doeq && i = 0) p) patterns in
FApi.t_seqs (List.rev patterns) tc
with (EcCoreGoal.ClearError _) as err ->
tc_error_exn !!tc err
(* -------------------------------------------------------------------- *)
let rec process_mgenintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc =
match pi with
| `Ip pi -> process_mintros_1 ?cf ttenv pi tc
| `Gen gn ->
t_onall (
t_seqs [
process_clear gn.pr_clear;
process_generalize gn.pr_genp
]) tc
in process_mgenintros ~cf:false ttenv pis tc
(* -------------------------------------------------------------------- *)
let process_genintros ?cf ttenv pis tc =
process_mgenintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
(* -------------------------------------------------------------------- *)
let process_move ?doeq views pr (tc : tcenv1) =
t_seqs
[process_clear pr.pr_clear;
process_generalize ?doeq pr.pr_genp;
process_view views]
tc
(* -------------------------------------------------------------------- *)
let process_pose xsym bds o p (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let (ptenv, p) =
let ps = ref Mid.empty in
let ue = TTC.unienv_of_hyps hyps in
let (senv, bds) = EcTyping.trans_binding env ue bds in
let p = EcTyping.trans_pattern senv ps ue p in
let ev = MEV.of_idents (Mid.keys !ps) `Form in
(ptenv !!tc hyps (ue, ev),
f_lambda (List.map (snd_map gtty) bds) p)
in
let dopat =
try
ignore (PT.pf_find_occurence ~occmode:PT.om_rigid ptenv ~ptn:p concl);
true
with PT.FindOccFailure _ ->
if not (PT.can_concretize ptenv) then
if not (EcMatching.MEV.filled !(ptenv.PT.pte_ev)) then
tc_error !!tc "cannot find an occurence"
else
tc_error !!tc "%s - %s"
"cannot find an occurence"
"instantiate type variables manually"
else
false
in
let p = PT.concretize_form ptenv p in
let (x, letin) =
match dopat with
| false -> (EcIdent.create (unloc xsym), concl)
| true -> begin
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps o p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
FPosition.topattern ~x:(EcIdent.create (unloc xsym)) cpos concl
end
in
let letin = EcFol.f_let1 x p letin in
FApi.t_seq
(t_change letin)
(t_intros [Tagged (x, Some xsym.pl_loc)]) tc
(* -------------------------------------------------------------------- *)
type apply_t = EcParsetree.apply_info
let process_apply ~implicits ((infos, orv) : apply_t * prevert option) tc =
let do_apply tc =
match infos with
| `ApplyIn (pe, tg) ->
process_apply_fwd ~implicits (pe, tg) tc
| `Apply (pe, mode) ->
let for1 tc pe =
t_last (process_apply_bwd ~implicits `Apply pe) tc in
let tc = List.fold_left for1 (tcenv_of_tcenv1 tc) pe in
if mode = `Exact then t_onall process_done tc else tc
| `Alpha pe ->
process_apply_bwd ~implicits `Alpha pe tc
| `Top mode ->
let tc = process_apply_top tc in
if mode = `Exact then t_onall process_done tc else tc
in
t_seq
(fun tc -> ofdfl
(fun () -> t_id tc)
(omap (fun rv -> process_move [] rv tc) orv))
do_apply tc
(* -------------------------------------------------------------------- *)
let process_subst syms (tc : tcenv1) =
let resolve symp =
let sym = TTC.tc1_process_form_opt tc None symp in
match sym.f_node with
| Flocal id -> `Local id
| Fglob (mp, mem) -> `Glob (mp, mem)
| Fpvar (pv, mem) -> `PVar (pv, mem)
| _ ->
tc_error !!tc ~loc:symp.pl_loc
"this formula is not subject to substitution"
in
match List.map resolve syms with
| [] -> t_repeat t_subst tc
| syms -> FApi.t_seqs (List.map (fun var tc -> t_subst ~var tc) syms) tc
(* -------------------------------------------------------------------- *)
type cut_t = intropattern * pformula * (ptactics located) option
type cutmode = [`Have | `Suff]
let process_cut ?(mode = `Have) engine ttenv ((ip, phi, t) : cut_t) tc =
let phi = TTC.tc1_process_formula tc phi in
let tc = EcLowGoal.t_cut phi tc in
let applytc tc =
t |> ofold (fun t tc ->
let t = mk_loc (loc t) (Pby (Some (unloc t))) in
t_onall (engine t) tc) (FApi.tcenv_of_tcenv1 tc)
in
match mode with
| `Have ->
FApi.t_first applytc
(FApi.t_last (process_intros_1 ttenv ip) tc)
| `Suff ->
FApi.t_rotate `Left 1
(FApi.t_on1 0 t_id ~ttout:applytc
(FApi.t_last (process_intros_1 ttenv ip) tc))
(* -------------------------------------------------------------------- *)
type cutdef_t = intropattern * pcutdef
let process_cutdef ttenv (ip, pt) (tc : tcenv1) =
let pt = {
fp_mode = `Implicit;
fp_head = FPNamed (pt.ptcd_name, pt.ptcd_tys);
fp_args = pt.ptcd_args;
} in
let pt = PT.tc1_process_full_pterm tc pt in
if not (PT.can_concretize pt.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut ax tc)
(* -------------------------------------------------------------------- *)
type cutdef_sc_t = intropattern * pcutdef_schema
let process_cutdef_sc ttenv (ip, inst) (tc : tcenv1) =
let pt,sc_i = PT.tc1_process_sc_instantiation tc inst in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut sc_i tc)
(* -------------------------------------------------------------------- *)
let process_left (tc : tcenv1) =
try
t_ors [EcLowGoal.t_left; EcLowGoal.t_or_intro_prind `Left] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `left` on that goal"
(* -------------------------------------------------------------------- *)
let process_right (tc : tcenv1) =
try
t_ors [EcLowGoal.t_right; EcLowGoal.t_or_intro_prind `Right] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `right` on that goal"
(* -------------------------------------------------------------------- *)
let process_split (tc : tcenv1) =
try t_ors [EcLowGoal.t_split; EcLowGoal.t_split_prind] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `split` on that goal"
(* -------------------------------------------------------------------- *)
let process_elim (pe, qs) tc =
let doelim tc =
match qs with
| None -> t_or (t_elimT_ind `Ind) t_elim tc
| Some qs ->
let qs = {
fp_mode = `Implicit;
fp_head = FPNamed (qs, None);
fp_args = [];
} in process_elimT qs tc
in
try
FApi.t_last doelim (process_move [] pe tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't know what to eliminate"
(* -------------------------------------------------------------------- *)
let process_case ?(doeq = false) gp tc =
let module E = struct exception LEMFailure end in
try
match gp.pr_rev with
| { pr_genp = [`Form (None, pf)] }
when List.is_empty gp.pr_view ->
let env = FApi.tc1_env tc in
let f =
try TTC.process_formula (FApi.tc1_hyps tc) pf
with TT.TyError _ | LocError (_, TT.TyError _) -> raise E.LEMFailure
in
if not (EcReduction.EqTest.for_type env f.f_ty tbool) then
raise E.LEMFailure;
begin
match (fst (destr_app f)).f_node with
| Fop (p, _) when EcEnv.Op.is_prind env p ->
raise E.LEMFailure
| _ -> ()
end;
t_seqs
[process_clear gp.pr_rev.pr_clear; t_case f;
t_simplify_with_info EcReduction.betaiota_red]
tc
| _ -> raise E.LEMFailure
with E.LEMFailure ->
try
FApi.t_last
(t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case])
(process_move ~doeq gp.pr_view gp.pr_rev tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't known what to eliminate"
(* -------------------------------------------------------------------- *)
let process_exists args (tc : tcenv1) =
let hyps = FApi.tc1_hyps tc in
let pte = (TTC.unienv_of_hyps hyps, EcMatching.MEV.empty) in
let pte = PT.ptenv !!tc (FApi.tc1_hyps tc) pte in
let for1 concl arg =
match TTC.destruct_exists hyps concl with
| None -> tc_error !!tc "not an existential"
| Some (`Exists (x, xty, f)) ->
let arg =
match xty with
| GTty _ -> trans_pterm_arg_value pte arg
| GTmem _ -> trans_pterm_arg_mem pte arg
| GTmodty _ -> trans_pterm_arg_mod pte arg
in
PT.check_pterm_arg pte (x, xty) f arg.ptea_arg
in
let _concl, args = List.map_fold for1 (FApi.tc1_goal tc) args in
if not (PT.can_concretize pte) then
tc_error !!tc "cannot infer all placeholders";
let pte = PT.concretize_env pte in
let args = List.map (PT.concretize_e_arg pte) args in
EcLowGoal.t_exists_intro_s args tc
(* -------------------------------------------------------------------- *)
let process_congr tc =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcFol.is_eq_or_iff concl) then
tc_error !!tc "goal must be an equality or an equivalence";
let ((f1, f2), iseq) =
if EcFol.is_eq concl
then (EcFol.destr_eq concl, true )
else (EcFol.destr_iff concl, false) in
let t_ensure_eq =
if iseq then t_id
else
(fun tc ->
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_uglobal !!tc hyps LG.p_eq_iff) tc) in
let t_subgoal = t_ors [t_reflex ~mode:`Alpha; t_assumption `Alpha; t_id] in
match f1.f_node, f2.f_node with
| _, _ when EcReduction.is_alpha_eq hyps f1 f2 ->
FApi.t_seq t_ensure_eq EcLowGoal.t_reflex tc
| Fapp (o1, a1), Fapp (o2, a2)
when EcReduction.is_alpha_eq hyps o1 o2
&& List.length a1 = List.length a2 ->
let tt1 = t_congr (o1, o2) ((List.combine a1 a2), f1.f_ty) in
FApi.t_seqs [t_ensure_eq; tt1; t_subgoal] tc
| Fif (_, { f_ty = cty }, _), Fif _ ->
let tt0 tc =
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_global !!tc hyps LG.p_if_congr [cty]) tc
in FApi.t_seqs [tt0; t_subgoal] tc
| Ftuple _, Ftuple _ when iseq ->
FApi.t_seqs [t_split; t_subgoal] tc
| Fproj (f1, i1), Fproj (f2, i2)
when i1 = i2 && EcReduction.EqTest.for_type env f1.f_ty f2.f_ty
-> EcCoreGoal.FApi.xmutate1 tc `CongrProj [f_eq f1 f2]
| _, _ -> tacuerror "not a congruence"
(* -------------------------------------------------------------------- *)
let process_wlog ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_rotate `Left 1 (EcLowGoal.t_cut wlog tc) in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc
in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut gen tc))
(* -------------------------------------------------------------------- *)
let process_wlog_suff ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let wlog =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) (t_cut wlog tc) in
FApi.tc_goal tc in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut wlog tc))
(* -------------------------------------------------------------------- *)
let process_wlog ~suff ids wlog tc =
if suff
then process_wlog_suff ids wlog tc
else process_wlog ids wlog tc
(* -------------------------------------------------------------------- *)
let process_genhave (ttenv : ttenv) ((name, ip, ids, gen) : pgenhave) tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let gen = TTC.tc1_process_formula tc gen in
let tc = EcLowGoal.t_cut gen tc in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc in
let doip tc =
let genid = EcIdent.create (unloc name) in
let tc = t_intros_i_1 [genid] tc in
match ip with
| None ->
t_id tc
| Some ip ->
let pt = EcProofTerm.pt_of_hyp !!tc (FApi.tc1_hyps tc) genid in
let pt = List.fold_left EcProofTerm.apply_pterm_to_local pt ids in
let tc = t_cutdef pt.ptev_pt pt.ptev_ax tc in
process_mintros ttenv [ip] tc in
t_sub [
t_seq (t_clears ids) (t_intros_i ids);
doip
] (t_cut gen tc)
| null | https://raw.githubusercontent.com/easyuc/EasyUC/67a983a7263ee8234452b9c157c4cb4f3d5f7b26/uc-dsl/ucdsl-proj/src/ECsrc/ecHiGoal.ml | ocaml | --------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Continue with matching based unfolding
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | open EcUtils
open EcLocation
open EcSymbols
open EcParsetree
open EcTypes
open EcFol
open EcEnv
open EcMatching
open EcBaseLogic
open EcProofTerm
open EcCoreGoal
open EcCoreGoal.FApi
open EcLowGoal
module Sid = EcIdent.Sid
module Mid = EcIdent.Mid
module Sp = EcPath.Sp
module ER = EcReduction
module PT = EcProofTerm
module TT = EcTyping
module TTC = EcProofTyping
module LG = EcCoreLib.CI_Logic
type ttenv = {
tt_provers : EcParsetree.pprover_infos -> EcProvers.prover_infos;
tt_smtmode : [`Admit | `Strict | `Standard | `Report];
tt_implicits : bool;
tt_oldip : bool;
tt_redlogic : bool;
tt_und_delta : bool;
}
type engine = ptactic_core -> FApi.backward
let t_simplify_lg ?target ?delta (ttenv, logic) (tc : tcenv1) =
let logic =
match logic with
| `Default -> if ttenv.tt_redlogic then `Full else `ProductCompat
| `Variant -> if ttenv.tt_redlogic then `ProductCompat else `Full
in t_simplify ?target ?delta ~logic:(Some logic) tc
type focus_t = EcParsetree.tfocus
let process_tfocus tc (focus : focus_t) : tfocus =
let count = FApi.tc_count tc in
let check1 i =
let error () = tc_error !$tc "invalid focus index: %d" i in
if i >= 0
then if not (0 < i && i <= count) then error () else i-1
else if -i > count then error () else count+i
in
let checkfs fs =
List.fold_left
(fun rg (i1, i2) ->
let i1 = odfl min_int (omap check1 i1) in
let i2 = odfl max_int (omap check1 i2) in
if i1 <= i2 then ISet.add_range i1 i2 rg else rg)
ISet.empty fs
in
let posfs = omap checkfs (fst focus) in
let negfs = omap checkfs (snd focus) in
fun i ->
odfl true (posfs |> omap (ISet.mem i))
&& odfl true (negfs |> omap (fun fc -> not (ISet.mem i fc)))
let process_assumption (tc : tcenv1) =
EcLowGoal.t_assumption `Conv tc
let process_reflexivity (tc : tcenv1) =
try EcLowGoal.t_reflex tc
with InvalidGoalShape ->
tc_error !!tc "cannot prove goal by reflexivity"
let process_change fp (tc : tcenv1) =
let fp = TTC.tc1_process_formula tc fp in
t_change fp tc
let process_simplify_info ri (tc : tcenv1) =
let env, hyps, _ = FApi.tc1_eflat tc in
let do1 (sop, sid) ps =
match ps.pl_desc with
| ([], s) when LDecl.has_name s hyps ->
let id = fst (LDecl.by_name s hyps) in
(sop, Sid.add id sid)
| qs ->
match EcEnv.Op.lookup_opt qs env with
| None -> tc_lookup_error !!tc ~loc:ps.pl_loc `Operator qs
| Some p -> (Sp.add (fst p) sop, sid)
in
let delta_p, delta_h =
ri.pdelta
|> omap (List.fold_left do1 (Sp.empty, Sid.empty))
|> omap (fun (x, y) -> (fun p -> if Sp.mem p x then `Force else `No), (Sid.mem^~ y))
|> odfl ((fun _ -> `Yes), predT)
in
{
EcReduction.beta = ri.pbeta;
EcReduction.delta_p = delta_p;
EcReduction.delta_h = delta_h;
EcReduction.zeta = ri.pzeta;
EcReduction.iota = ri.piota;
EcReduction.eta = ri.peta;
EcReduction.logic = if ri.plogic then Some `Full else None;
EcReduction.modpath = ri.pmodpath;
EcReduction.user = ri.puser;
EcReduction.cost = ri.pcost;
}
let process_simplify ri (tc : tcenv1) =
t_simplify_with_info (process_simplify_info ri tc) tc
let process_cbv ri (tc : tcenv1) =
t_cbv_with_info (process_simplify_info ri tc) tc
let process_smt ?loc (ttenv : ttenv) pi (tc : tcenv1) =
let pi = ttenv.tt_provers pi in
match ttenv.tt_smtmode with
| `Admit ->
t_admit tc
| (`Standard | `Strict) as mode ->
t_seq (t_simplify ~delta:false) (t_smt ~mode pi) tc
| `Report ->
t_seq (t_simplify ~delta:false) (t_smt ~mode:(`Report loc) pi) tc
let process_clear symbols tc =
let hyps = FApi.tc1_hyps tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps)
in
try t_clears (List.map toid symbols) tc
with (ClearError _) as err -> tc_error_exn !!tc err
let process_algebra mode kind eqs (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcAlgTactic.is_module_loaded env) then
tacuerror "ring/field cannot be used when AlgTactic is not loaded";
let (ty, f1, f2) =
match sform_of_form concl with
| SFeq (f1, f2) -> (f1.f_ty, f1, f2)
| _ -> tacuerror "conclusion must be an equation"
in
let eqs =
let eq1 { pl_desc = x } =
match LDecl.hyp_exists x hyps with
| false -> tacuerror "cannot find equation referenced by `%s'" x
| true -> begin
match sform_of_form (snd (LDecl.hyp_by_name x hyps)) with
| SFeq (f1, f2) ->
if not (EcReduction.EqTest.for_type env ty f1.f_ty) then
tacuerror "assumption `%s' is not an equation over the right type" x;
(f1, f2)
| _ -> tacuerror "assumption `%s' is not an equation" x
end
in List.map eq1 eqs
in
let tparams = (LDecl.tohyps hyps).h_tvar in
let tactic =
match
match mode, kind with
| `Simpl, `Ring -> `Ring EcAlgTactic.t_ring_simplify
| `Simpl, `Field -> `Field EcAlgTactic.t_field_simplify
| `Solve, `Ring -> `Ring EcAlgTactic.t_ring
| `Solve, `Field -> `Field EcAlgTactic.t_field
with
| `Ring t ->
let r =
match TT.get_ring (tparams, ty) env with
| None -> tacuerror "cannot find a ring structure"
| Some r -> r
in t r eqs (f1, f2)
| `Field t ->
let r =
match TT.get_field (tparams, ty) env with
| None -> tacuerror "cannot find a field structure"
| Some r -> r
in t r eqs (f1, f2)
in
tactic tc
let t_apply_prept pt tc =
EcLowGoal.Apply.t_apply_bwd_r (pt_of_prept tc pt) tc
module LowRewrite = struct
type error =
| LRW_NotAnEquation
| LRW_NothingToRewrite
| LRW_InvalidOccurence
| LRW_CannotInfer
| LRW_IdRewriting
| LRW_RPatternNoMatch
| LRW_RPatternNoRuleMatch
exception RewriteError of error
let rec find_rewrite_patterns ~inpred (dir : rwside) pt =
let hyps = pt.PT.ptev_env.PT.pte_hy in
let env = LDecl.toenv hyps in
let pt = { pt with ptev_ax = snd (PT.concretize pt) } in
let ptc = { pt with ptev_env = EcProofTerm.copy pt.ptev_env } in
let ax = pt.ptev_ax in
let base ax =
match EcFol.sform_of_form ax with
| EcFol.SFeq (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFiff (f1, f2) -> [(pt, `Eq, (f1, f2))]
| EcFol.SFnot f ->
let pt' = pt_of_global_r pt.ptev_env LG.p_negeqF [] in
let pt' = apply_pterm_to_arg_r pt' (PVAFormula f) in
let pt' = apply_pterm_to_arg_r pt' (PVASub pt) in
[(pt', `Eq, (f, f_false))]
| _ -> []
and split ax =
match EcFol.sform_of_form ax with
| EcFol.SFand (`Sym, (f1, f2)) ->
let pt1 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_l [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
let pt2 =
let pt'= pt_of_global_r pt.ptev_env LG.p_and_proj_r [] in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f1) in
let pt'= apply_pterm_to_arg_r pt' (PVAFormula f2) in
apply_pterm_to_arg_r pt' (PVASub pt) in
(find_rewrite_patterns ~inpred dir pt2)
@ (find_rewrite_patterns ~inpred dir pt1)
| _ -> []
in
match base ax with
| _::_ as rws -> rws
| [] -> begin
let ptb = Lazy.from_fun (fun () ->
let pt1 = split ax
and pt2 =
if dir = `LtoR then
if ER.EqTest.for_type env ax.f_ty tbool
then Some (ptc, `Bool, (ax, f_true))
else None
else None
and pt3 = omap base
(EcReduction.h_red_opt EcReduction.full_red hyps ax)
in pt1 @ (otolist pt2) @ (odfl [] pt3)) in
let rec doit reduce =
match TTC.destruct_product ~reduce hyps ax with
| None -> begin
if reduce then Lazy.force ptb else
let pts = doit true in
if inpred then pts else (Lazy.force ptb) @ pts
end
| Some _ ->
let pt = EcProofTerm.apply_pterm_to_hole pt in
find_rewrite_patterns ~inpred:(inpred || reduce) dir pt
in doit false
end
let find_rewrite_patterns = find_rewrite_patterns ~inpred:false
type rwinfos = rwside * EcFol.form option * EcMatching.occ option
let t_rewrite_r ?(mode = `Full) ?target ((s, prw, o) : rwinfos) pt tc =
let hyps, tgfp = FApi.tc1_flat ?target tc in
let modes =
match mode with
| `Full -> [{ k_keyed = true; k_conv = false };
{ k_keyed = true; k_conv = true };]
| `Light -> [{ k_keyed = true; k_conv = false }] in
let for1 (pt, mode, (f1, f2)) =
let fp, tp = match s with `LtoR -> f1, f2 | `RtoL -> f2, f1 in
let subf, occmode =
match prw with
| None -> begin
try
PT.pf_find_occurence_lazy pt.PT.ptev_env ~modes ~ptn:fp tgfp
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_NothingToRewrite)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end
| Some prw -> begin
let prw, _ =
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~full:false ~modes ~ptn:prw tgfp;
with PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoMatch) in
try
PT.pf_find_occurence_lazy
pt.PT.ptev_env ~rooted:true ~modes ~ptn:fp prw
with
| PT.FindOccFailure `MatchFailure ->
raise (RewriteError LRW_RPatternNoRuleMatch)
| PT.FindOccFailure `IncompleteMatch ->
raise (RewriteError LRW_CannotInfer)
end in
if not occmode.k_keyed then begin
let tp = PT.concretize_form pt.PT.ptev_env tp in
if EcReduction.is_conv hyps fp tp then
raise (RewriteError LRW_IdRewriting);
end;
let pt = fst (PT.concretize pt) in
let cpos =
try FPosition.select_form
~xconv:`AlphaEq ~keyed:occmode.k_keyed
hyps o subf tgfp
with InvalidOccurence -> raise (RewriteError (LRW_InvalidOccurence))
in
EcLowGoal.t_rewrite
~keyed:occmode.k_keyed ?target ~mode pt (s, Some cpos) tc in
let rec do_first = function
| [] -> raise (RewriteError LRW_NothingToRewrite)
| (pt, mode, (f1, f2)) :: pts ->
try for1 (pt, mode, (f1, f2))
with RewriteError (LRW_NothingToRewrite | LRW_IdRewriting) ->
do_first pts
in
let pts = find_rewrite_patterns s pt in
if List.is_empty pts then
raise (RewriteError LRW_NotAnEquation);
do_first (List.rev pts)
let t_rewrite ?target (s, p, o) pt (tc : tcenv1) =
let hyps = FApi.tc1_hyps ?target tc in
let pt, ax = EcLowGoal.LowApply.check `Elim pt (`Hyps (hyps, !!tc)) in
let ptenv = ptenv_of_penv hyps !!tc in
t_rewrite_r ?target (s, p, o)
{ ptev_env = ptenv; ptev_pt = pt; ptev_ax = ax; }
tc
let t_autorewrite lemmas (tc : tcenv1) =
let pts =
let do1 lemma =
PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) lemma in
List.map do1 lemmas
in
let try1 pt tc =
let pt = { pt with PT.ptev_env = PT.copy pt.ptev_env } in
try t_rewrite_r (`LtoR, None, None) pt tc
with RewriteError _ -> raise InvalidGoalShape
in t_do_r ~focus:0 `Maybe None (t_ors (List.map try1 pts)) !@tc
end
let t_rewrite_prept info pt tc =
LowRewrite.t_rewrite_r info (pt_of_prept tc pt) tc
let process_solve ?bases ?depth (tc : tcenv1) =
match FApi.t_try_base (EcLowGoal.t_solve ~canfail:false ?bases ?depth) tc with
| `Failure _ ->
tc_error (FApi.tc1_penv tc) "[solve]: cannot close goal"
| `Success tc ->
tc
let process_trivial (tc : tcenv1) =
EcPhlAuto.t_pl_trivial ~conv:`Conv tc
let process_crushmode d =
d.cm_simplify, if d.cm_solve then Some process_trivial else None
let process_done tc =
let tc = process_trivial tc in
if not (FApi.tc_done tc) then
tc_error (FApi.tc_penv tc) "[by]: cannot close goals";
tc
let process_apply_bwd ~implicits mode (ff : ppterm) (tc : tcenv1) =
let pt = PT.tc1_process_full_pterm ~implicits tc ff in
try
match mode with
| `Alpha ->
begin try
PT.pf_form_match
pt.ptev_env
~mode:fmrigid
~ptn:pt.ptev_ax
(FApi.tc1_goal tc)
with EcMatching.MatchFailure ->
tc_error !!tc "proof-term is not alpha-convertible to conclusion" end;
EcLowGoal.t_apply (fst (PT.concretize pt)) tc
| `Apply ->
EcLowGoal.Apply.t_apply_bwd_r pt tc
| `Exact ->
let aout = EcLowGoal.Apply.t_apply_bwd_r pt tc in
let aout = FApi.t_onall process_trivial aout in
if not (FApi.tc_done aout) then
tc_error !!tc "cannot close goal";
aout
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
let process_apply_fwd ~implicits (pe, hyp) tc =
let module E = struct exception NoInstance end in
let hyps = FApi.tc1_hyps tc in
if not (LDecl.hyp_exists (unloc hyp) hyps) then
tc_error !!tc "unknown hypothesis: %s" (unloc hyp);
let hyp, fp = LDecl.hyp_by_name (unloc hyp) hyps in
let pte = PT.tc1_process_full_pterm ~implicits tc pe in
try
let rec instantiate pte =
match TTC.destruct_product hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall _) ->
instantiate (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) ->
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, f2)
with MatchFailure -> raise E.NoInstance
in
let (pte, cutf) = instantiate pte in
if not (PT.can_concretize pte.ptev_env) then
tc_error !!tc "cannot infer all variables";
let pt = fst (PT.concretize pte) in
let pt = { pt with pt_args = pt.pt_args @ [palocal hyp]; } in
let cutf = PT.concretize_form pte.PT.ptev_env cutf in
FApi.t_last
(FApi.t_seq (t_clear hyp) (t_intros_i [hyp]))
(t_cutdef pt cutf tc)
with E.NoInstance ->
tc_error_lazy !!tc
(fun fmt ->
let ppe = EcPrinting.PPEnv.ofenv (FApi.tc1_env tc) in
Format.fprintf fmt
"cannot apply (in %a) the given proof-term for:\n\n%!"
(EcPrinting.pp_local ppe) hyp;
Format.fprintf fmt
" @[%a@]" (EcPrinting.pp_form ppe) pte.PT.ptev_ax)
let process_apply_top tc =
let hyps, concl = FApi.tc1_flat tc in
match TTC.destruct_product hyps concl with
| Some (`Imp _) -> begin
let h = LDecl.fresh_id hyps "h" in
try
EcLowGoal.t_intros_i_seq ~clear:true [h]
(EcLowGoal.Apply.t_apply_bwd { pt_head = PTLocal h; pt_args = []} )
tc
with (EcLowGoal.Apply.NoInstance _) as err ->
tc_error_exn !!tc err
end
| _ -> tc_error !!tc "no top assumption"
let process_rewrite1_core ?mode ?(close = true) ?target (s, p, o) pt tc =
let o = norm_rwocc o in
try
let tc = LowRewrite.t_rewrite_r ?mode ?target (s, p, o) pt tc in
let cl = fun tc ->
if EcFol.f_equal f_true (FApi.tc1_goal tc) then
t_true tc
else t_id tc
in if close then FApi.t_last cl tc else tc
with
| LowRewrite.RewriteError e ->
match e with
| LowRewrite.LRW_NotAnEquation ->
tc_error !!tc "not an equation to rewrite"
| LowRewrite.LRW_NothingToRewrite ->
tc_error !!tc "nothing to rewrite"
| LowRewrite.LRW_InvalidOccurence ->
tc_error !!tc "invalid occurence selector"
| LowRewrite.LRW_CannotInfer ->
tc_error !!tc "cannot infer all placeholders"
| LowRewrite.LRW_IdRewriting ->
tc_error !!tc "refuse to perform an identity rewriting"
| LowRewrite.LRW_RPatternNoMatch ->
tc_error !!tc "r-pattern does not match the goal"
| LowRewrite.LRW_RPatternNoRuleMatch ->
tc_error !!tc "r-pattern does not match the rewriting rule"
let process_delta ~und_delta ?target (s, o, p) tc =
let env, hyps, concl = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let idtg, target =
match target with
| None -> (None, concl)
| Some h -> fst_map some (LDecl.hyp_by_name (unloc h) hyps)
in
match unloc p with
| PFident ({ pl_desc = ([], x) }, None)
when s = `LtoR && EcUtils.is_none o ->
let check_op = fun p -> if sym_equal (EcPath.basename p) x then `Force else `No in
let check_id = fun y -> sym_equal (EcIdent.name y) x in
let ri =
{ EcReduction.no_red with
EcReduction.delta_p = check_op;
EcReduction.delta_h = check_id; } in
let redform = EcReduction.simplify ri hyps target in
if und_delta then begin
if EcFol.f_equal target redform then
EcEnv.notify env `Warning "unused unfold: /%s" x
end;
t_change ~ri ?target:idtg redform tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
let (tvi, tparams, body, args, dp) =
match sform_of_form p with
| SFop (p, args) -> begin
let op = EcEnv.Op.by_path (fst p) env in
match op.EcDecl.op_kind with
| EcDecl.OB_oper (Some (EcDecl.OP_Plain (e, _))) ->
(snd p, op.EcDecl.op_tparams, form_of_expr EcFol.mhr e, args, Some (fst p))
| EcDecl.OB_pred (Some (EcDecl.PR_Plain f)) ->
(snd p, op.EcDecl.op_tparams, f, args, Some (fst p))
| _ ->
tc_error !!tc "the operator cannot be unfolded"
end
| SFlocal x when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, [], None)
| SFother { f_node = Fapp ({ f_node = Flocal x }, args) }
when LDecl.can_unfold x hyps ->
([], [], LDecl.unfold x hyps, args, None)
| _ -> tc_error !!tc "not headed by an operator/predicate"
in
let ri = { EcReduction.full_red with
delta_p = (fun p -> if Some p = dp then `Force else `Yes)} in
let na = List.length args in
match s with
| `LtoR -> begin
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:p target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let cpos =
let test = fun _ fp ->
let fp =
match fp.f_node with
| Fapp (h, hargs) when List.length hargs > na ->
let (a1, a2) = List.takedrop na hargs in
f_app h a1 (toarrow (List.map f_ty a2) fp.f_ty)
| _ -> fp
in
if EcReduction.is_alpha_eq hyps p fp
then `Accept (-1)
else `Continue
in
try FPosition.select ?o test target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target =
FPosition.map cpos
(fun topfp ->
let (fp, args) = EcFol.destr_app topfp in
match sform_of_form fp with
| SFop ((_, tvi), []) -> begin
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| SFlocal _ -> begin
assert (tparams = []);
let body = f_app body args topfp.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps body
with EcEnv.NotReducible -> body
end
| _ -> assert false)
target
in
t_change ~ri ?target:idtg target tc
end else t_id tc
end
| `RtoL ->
let fp =
FIXME : TC HOOK
let subst = EcTypes.Tvar.init (List.map fst tparams) tvi in
let body = EcFol.Fsubst.subst_tvar subst body in
let fp = f_app body args p.f_ty in
try EcReduction.h_red EcReduction.beta_red hyps fp
with EcEnv.NotReducible -> fp
in
let matches =
try ignore (PT.pf_find_occurence ptenv ~ptn:fp target); true
with PT.FindOccFailure _ -> false
in
if matches then begin
let p = concretize_form ptenv p in
let fp = concretize_form ptenv fp in
let cpos =
try FPosition.select_form hyps o fp target
with InvalidOccurence ->
tc_error !!tc "invalid occurences selector"
in
let target = FPosition.map cpos (fun _ -> p) target in
t_change ~ri ?target:idtg target tc
end else t_id tc
let process_rewrite1_r ttenv ?target ri tc =
let implicits = ttenv.tt_implicits in
let und_delta = ttenv.tt_und_delta in
match unloc ri with
| RWDone simpl ->
let tt =
match simpl with
| Some logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic)
| None -> t_id
in FApi.t_seq tt process_trivial tc
| RWSimpl logic ->
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
t_simplify_lg ?target ~delta:false (ttenv, logic) tc
| RWDelta ((s, r, o, px), p) -> begin
if Option.is_some px then
tc_error !!tc "cannot use pattern selection in delta-rewrite rules";
let do1 tc = process_delta ~und_delta ?target (s, o, p) tc in
match r with
| None -> do1 tc
| Some (b, n) -> t_do b n do1 tc
end
| RWRw (((s : rwside), r, o, p), pts) -> begin
let do1 (mode : [`Full | `Light]) ((subs : rwside), pt) tc =
let hyps = FApi.tc1_hyps tc in
let target = target |> omap (fst |- LDecl.hyp_by_name^~ hyps |- unloc) in
let hyps = FApi.tc1_hyps ?target tc in
let ptenv, prw =
match p with
| None ->
PT.ptenv_of_penv hyps !!tc, None
| Some p ->
let (ps, ue), p = TTC.tc1_process_pattern tc p in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(PT.ptenv !!tc hyps (ue, ev), Some p) in
let theside =
match s, subs with
| `LtoR, _ -> (subs :> rwside)
| _ , `LtoR -> (s :> rwside)
| `RtoL, `RtoL -> (`LtoR :> rwside) in
let is_baserw p =
EcEnv.BaseRw.is_base p.pl_desc (FApi.tc1_env tc) in
match pt with
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit && is_baserw p
->
let env = FApi.tc1_env tc in
let ls = snd (EcEnv.BaseRw.lookup p.pl_desc env) in
let ls = EcPath.Sp.elements ls in
let do1 lemma tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in t_ors (List.map do1 ls) tc
| { fp_head = FPNamed (p, None); fp_args = []; }
when pt.fp_mode = `Implicit
->
let env = FApi.tc1_env tc in
let ptenv0 = PT.copy ptenv in
let pt = PT.process_full_pterm ~implicits ptenv pt
in
if is_ptglobal pt.PT.ptev_pt.pt_head
&& List.is_empty pt.PT.ptev_pt.pt_args
then begin
let ls = EcEnv.Ax.all ~name:(unloc p) env in
let do1 (lemma, _) tc =
let pt = PT.pt_of_uglobal_r (PT.copy ptenv0) lemma in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc in
t_ors (List.map do1 ls) tc
end else
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
| _ ->
let pt = PT.process_full_pterm ~implicits ptenv pt in
process_rewrite1_core ~mode ?target (theside, prw, o) pt tc
in
let doall mode tc = t_ors (List.map (do1 mode) pts) tc in
match r with
| None ->
doall `Full tc
| Some (`Maybe, None) ->
t_seq
(t_do `Maybe (Some 1) (doall `Full))
(t_do `Maybe None (doall `Light))
tc
| Some (b, n) ->
t_do b n (doall `Full) tc
end
| RWPr (x, f) -> begin
if EcUtils.is_some target then
tc_error !!tc "cannot rewrite Pr[] in local assumptions";
EcPhlPrRw.t_pr_rewrite (unloc x, f) tc
end
| RWSmt (false, info) ->
process_smt ~loc:ri.pl_loc ttenv info tc
| RWSmt (true, info) ->
t_or process_done (process_smt ~loc:ri.pl_loc ttenv info) tc
| RWApp fp -> begin
let implicits = ttenv.tt_implicits in
match target with
| None -> process_apply_bwd ~implicits `Apply fp tc
| Some target -> process_apply_fwd ~implicits (fp, target) tc
end
| RWTactic `Ring ->
process_algebra `Solve `Ring [] tc
| RWTactic `Field ->
process_algebra `Solve `Field [] tc
let process_rewrite1 ttenv ?target ri tc =
EcCoreGoal.reloc (loc ri) (process_rewrite1_r ttenv ?target ri) tc
let process_rewrite ttenv ?target ri tc =
let do1 tc gi (fc, ri) =
let ngoals = FApi.tc_count tc in
let dorw = fun i tc ->
if gi = 0 || (i+1) = ngoals
then process_rewrite1 ttenv ?target ri tc
else process_rewrite1 ttenv ri tc
in
match fc |> omap ((process_tfocus tc) |- unloc) with
| None -> FApi.t_onalli dorw tc
| Some fc -> FApi.t_onselecti fc dorw tc
in
List.fold_lefti do1 (tcenv_of_tcenv1 tc) ri
let process_elimT qs tc =
let noelim () = tc_error !!tc "cannot recognize elimination principle" in
let (hyps, concl) = FApi.tc1_flat tc in
let (pf, pfty, _concl) =
match TTC.destruct_product hyps concl with
| Some (`Forall (x, GTty xty, concl)) -> (x, xty, concl)
| _ -> noelim ()
in
let pf = LDecl.fresh_id hyps (EcIdent.name pf) in
let tc = t_intros_i_1 [pf] tc in
let (hyps, concl) = FApi.tc1_flat tc in
let pt = PT.tc1_process_full_pterm tc qs in
let (_xp, xpty, ax) =
match TTC.destruct_product hyps pt.ptev_ax with
| Some (`Forall (xp, GTty xpty, f)) -> (xp, xpty, f)
| _ -> noelim ()
in
begin
let ue = pt.ptev_env.pte_ue in
try EcUnify.unify (LDecl.toenv hyps) ue (tfun pfty tbool) xpty
with EcUnify.UnificationFailure _ -> noelim ()
end;
if not (PT.can_concretize pt.ptev_env) then noelim ();
let ax = PT.concretize_form pt.ptev_env ax in
let rec skip ax =
match TTC.destruct_product hyps ax with
| Some (`Imp (_f1, f2)) -> skip f2
| Some (`Forall (x, GTty xty, f)) -> ((x, xty), f)
| _ -> noelim ()
in
let ((x, _xty), ax) = skip ax in
let fpf = f_local pf pfty in
let ptnpos = FPosition.select_form hyps None fpf concl in
let (_xabs, body) = FPosition.topattern ~x:x ptnpos concl in
let rec skipmatch ax body sk =
match TTC.destruct_product hyps ax, TTC.destruct_product hyps body with
| Some (`Imp (i1, f1)), Some (`Imp (i2, f2)) ->
if EcReduction.is_alpha_eq hyps i1 i2
then skipmatch f1 f2 (sk+1)
else sk
| _ -> sk
in
let sk = skipmatch ax body 0 in
t_seqs
[t_elimT_form (fst (PT.concretize pt)) ~sk fpf;
t_or
(t_clear pf)
(t_seq (t_generalize_hyp pf) (t_clear pf));
t_simplify_with_info EcReduction.beta_red]
tc
let process_view1 pe tc =
let module E = struct
exception NoInstance
exception NoTopAssumption
end in
let destruct hyps fp =
let doit fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, t), lazy f) -> `Forall (x, t, f)
| SFimp (f1, f2) -> `Imp (f1, f2)
| SFiff (f1, f2) -> `Iff (f1, f2)
| _ -> raise EcProofTyping.NoMatch
in
EcProofTyping.lazy_destruct hyps doit fp
in
let rec instantiate fp ids pte =
let hyps = pte.PT.ptev_env.PT.pte_hy in
match destruct hyps pte.PT.ptev_ax with
| None -> raise E.NoInstance
| Some (`Forall (x, xty, _)) ->
instantiate fp ((x, xty) :: ids) (PT.apply_pterm_to_hole pte)
| Some (`Imp (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `None)
with MatchFailure -> raise E.NoInstance
end
| Some (`Iff (f1, f2)) -> begin
try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f1 fp;
(pte, ids, f2, `IffLR (f1, f2))
with MatchFailure -> try
PT.pf_form_match ~mode:fmdelta pte.PT.ptev_env ~ptn:f2 fp;
(pte, ids, f1, `IffRL (f1, f2))
with MatchFailure ->
raise E.NoInstance
end
in
try
match TTC.destruct_product (tc1_hyps tc) (FApi.tc1_goal tc) with
| None -> raise E.NoTopAssumption
| Some (`Forall _) ->
process_elimT pe tc
| Some (`Imp (f1, _)) when pe.fp_head = FPCut None ->
let hyps = FApi.tc1_hyps tc in
let hid = LDecl.fresh_id hyps "h" in
let hqs = mk_loc _dummy ([], EcIdent.name hid) in
let pe = { pe with fp_head = FPNamed (hqs, None) } in
t_intros_i_seq ~clear:true [hid]
(fun tc ->
let pe = PT.tc1_process_full_pterm tc pe in
let regen =
if PT.can_concretize pe.PT.ptev_env then [] else
snd (List.fold_left_map (fun f1 arg ->
let pre, f1 =
match oget (TTC.destruct_product (tc1_hyps tc) f1) with
| `Imp (_, f1) -> (None, f1)
| `Forall (x, xty, f1) ->
let aout =
match xty with GTty ty -> Some (x, ty) | _ -> None
in (aout, f1)
in
let module E = struct exception Bailout end in
try
let v =
match arg with
| PAFormula { f_node = Flocal x } ->
let meta =
let env = !(pe.PT.ptev_env.pte_ev) in
MEV.mem x `Form env && not (MEV.isset x `Form env) in
if not meta then raise E.Bailout;
let y, yty =
let CPTEnv subst = PT.concretize_env pe.PT.ptev_env in
snd_map subst.fs_ty (oget pre) in
let fy = EcIdent.fresh y in
pe.PT.ptev_env.pte_ev := MEV.set
x (`Form (f_local fy yty)) !(pe.PT.ptev_env.pte_ev);
(fy, yty)
| _ ->
raise E.Bailout
in (f1, Some v)
with E.Bailout -> (f1, None)
) f1 pe.PT.ptev_pt.pt_args)
in
let regen = List.pmap (fun x -> x) regen in
let bds = List.map (fun (x, ty) -> (x, GTty ty)) regen in
if not (PT.can_concretize pe.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = snd_map (f_forall bds) (PT.concretize pe) in
t_first (fun subtc ->
let regen = List.fst regen in
let ttcut tc =
t_onall
(EcLowGoal.t_generalize_hyps ~clear:`Yes regen)
(EcLowGoal.t_apply pt tc) in
t_intros_i_seq regen ttcut subtc
) (t_cut ax tc)
) tc
| Some (`Imp (f1, _)) ->
let top = LDecl.fresh_id (tc1_hyps tc) "h" in
let tc = t_intros_i_1 [top] tc in
let hyps = tc1_hyps tc in
let pte = PT.tc1_process_full_pterm tc pe in
let inargs = List.length pte.PT.ptev_pt.pt_args in
let (pte, ids, cutf, view) = instantiate f1 [] pte in
let evm = !(pte.PT.ptev_env.PT.pte_ev) in
let args = List.drop inargs pte.PT.ptev_pt.pt_args in
let args = List.combine (List.rev ids) args in
let ids =
let for1 ((_, ty) as idty, arg) =
match ty, arg with
| GTty _, PAFormula { f_node = Flocal x } when MEV.mem x `Form evm ->
if MEV.isset x `Form evm then None else Some (x, idty)
| GTmem _, PAMemory x when MEV.mem x `Mem evm ->
if MEV.isset x `Mem evm then None else Some (x, idty)
| _, _ -> assert false
in List.pmap for1 args
in
let cutf =
let ptenv = PT.copy pte.PT.ptev_env in
let for1 evm (x, idty) =
match idty with
| id, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| id, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _ , GTmodty _ -> assert false
in
List.iter (for1 ptenv.PT.pte_ev) ids;
if not (PT.can_concretize ptenv) then
tc_error !!tc "cannot infer all type variables";
PT.concretize_e_form
(PT.concretize_env ptenv)
(f_forall (List.map snd ids) cutf)
in
let discharge tc =
let intros = List.map (EcIdent.name |- fst |- snd) ids in
let intros = LDecl.fresh_ids hyps intros in
let for1 evm (x, idty) id =
match idty with
| _, GTty ty -> evm := MEV.set x (`Form (f_local id ty)) !evm
| _, GTmem _ -> evm := MEV.set x (`Mem id) !evm
| _, GTmodty _ -> assert false
in
let tc = EcLowGoal.t_intros_i_1 intros tc in
List.iter2 (for1 pte.PT.ptev_env.PT.pte_ev) ids intros;
let pte =
match view with
| `None -> pte
| `IffLR (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_lr [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
| `IffRL (f1, f2) ->
let vpte = PT.pt_of_global_r pte.PT.ptev_env LG.p_iff_rl [] in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f1) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVAFormula f2) in
let vpte = PT.apply_pterm_to_arg_r vpte (PVASub pte) in
vpte
in
let pt = fst (PT.concretize (PT.apply_pterm_to_hole pte)) in
FApi.t_seq
(EcLowGoal.t_apply pt)
(EcLowGoal.t_apply_hyp top)
tc
in
FApi.t_internal
(FApi.t_seqsub (EcLowGoal.t_cut cutf)
[EcLowGoal.t_close ~who:"view" discharge;
EcLowGoal.t_clear top])
tc
with
| E.NoInstance ->
tc_error !!tc "cannot apply view"
| E.NoTopAssumption ->
tc_error !!tc "no top assumption"
let process_view pes tc =
let views = List.map (t_last |- process_view1) pes in
List.fold_left (fun tc tt -> tt tc) (FApi.tcenv_of_tcenv1 tc) views
module IntroState : sig
type state
type action = [ `Revert | `Dup | `Clear ]
val create : unit -> state
val push : ?name:symbol -> action -> EcIdent.t -> state -> unit
val listing : state -> ([`Gen of genclear | `Clear] * EcIdent.t) list
val naming : state -> (EcIdent.t -> symbol option)
end = struct
type state = {
mutable torev : ([`Gen of genclear | `Clear] * EcIdent.t) list;
mutable naming : symbol option Mid.t;
}
and action = [ `Revert | `Dup | `Clear ]
let create () =
{ torev = []; naming = Mid.empty; }
let push ?name action id st =
let map =
Mid.change (function
| None -> Some name
| Some _ -> assert false)
id st.naming
and action =
match action with
| `Revert -> `Gen `TryClear
| `Dup -> `Gen `NoClear
| `Clear -> `Clear
in
st.torev <- (action, id) :: st.torev;
st.naming <- map
let listing (st : state) =
List.rev st.torev
let naming (st : state) (x : EcIdent.t) =
Mid.find_opt x st.naming |> odfl None
end
exception IntroCollect of [
`InternalBreak
]
exception CollectBreak
exception CollectCore of ipcore located
let rec process_mintros_1 ?(cf = true) ttenv pis gs =
let module ST = IntroState in
let mk_intro ids (hyps, form) =
let (_, torev), ids =
let rec compile (((hyps, form), torev) as acc) newids ids =
match ids with [] -> (acc, newids) | s :: ids ->
let rec destruct fp =
match EcFol.sform_of_form fp with
| SFquant (Lforall, (x, _) , lazy fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFlet (LSymbol (x, _), _, fp) ->
let name = EcIdent.name x in (name, Some name, `Named, fp)
| SFimp (_, fp) ->
("H", None, `Hyp, fp)
| _ -> begin
match EcReduction.h_red_opt EcReduction.full_red hyps fp with
| None -> ("_", None, `None, f_true)
| Some f -> destruct f
end
in
let name, revname, kind, form = destruct form in
let revertid =
if ttenv.tt_oldip then
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (None , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
if (a = Some None && kind = `None) || a = Some (Some 0)
then None
else Some (None, LDecl.fresh_id hyps name)
else
match unloc s with
| `Revert -> Some (Some false, EcIdent.create "_")
| `Clear -> Some (Some true , EcIdent.create "_")
| `Named s -> Some (None , EcIdent.create s)
| `Anonymous a ->
match a, kind with
| Some None, `None ->
None
| (Some (Some 0), _) ->
None
| _, `Named ->
Some (None, LDecl.fresh_id hyps ("`" ^ name))
| _, _ ->
Some (None, LDecl.fresh_id hyps "_")
in
match revertid with
| Some (revert, id) ->
let id = mk_loc s.pl_loc id in
let hyps = LDecl.add_local id.pl_desc (LD_var (tbool, None)) hyps in
let revert = revert |> omap (fun b -> if b then `Clear else `Revert) in
let torev = revert
|> omap (fun b -> (b, unloc id, revname) :: torev)
|> odfl torev
in
let newids = Tagged (unloc id, Some id.pl_loc) :: newids in
let ((hyps, form), torev), newids =
match unloc s with
| `Anonymous (Some None) when kind <> `None ->
compile ((hyps, form), torev) newids [s]
| `Anonymous (Some (Some i)) when 1 < i ->
let s = mk_loc (loc s) (`Anonymous (Some (Some (i-1)))) in
compile ((hyps, form), torev) newids [s]
| _ -> ((hyps, form), torev), newids
in compile ((hyps, form), torev) newids ids
| None -> compile ((hyps, form), torev) newids ids
in snd_map List.rev (compile ((hyps, form), []) [] ids)
in (List.rev torev, ids)
in
let rec collect intl acc core pis =
let maybe_core () =
let loc = EcLocation.mergeall (List.map loc core) in
match core with
| [] -> acc
| _ -> mk_loc loc (`Core (List.rev core)) :: acc
in
match pis with
| [] -> (maybe_core (), [])
| { pl_loc = ploc } as pi :: pis ->
try
let ip =
match unloc pi with
| IPBreak ->
if intl then raise (IntroCollect `InternalBreak);
raise CollectBreak
| IPCore x -> raise (CollectCore (mk_loc (loc pi) x))
| IPDup -> `Dup
| IPDone x -> `Done x
| IPSmt x -> `Smt x
| IPClear x -> `Clear x
| IPRw x -> `Rw x
| IPDelta x -> `Delta x
| IPView x -> `View x
| IPSubst x -> `Subst x
| IPSimplify x -> `Simpl x
| IPCrush x -> `Crush x
| IPCase (mode, x) ->
let subcollect = List.rev -| fst -| collect true [] [] in
`Case (mode, List.map subcollect x)
| IPSubstTop x -> `SubstTop x
in collect intl (mk_loc ploc ip :: maybe_core ()) [] pis
with
| CollectBreak -> (maybe_core (), pis)
| CollectCore x -> collect intl acc (x :: core) pis
in
let collect pis = collect false [] [] pis in
let rec intro1_core (st : ST.state) ids (tc : tcenv1) =
let torev, ids = mk_intro ids (FApi.tc1_flat tc) in
List.iter (fun (act, id, name) -> ST.push ?name act id st) torev;
t_intros ids tc
and intro1_dup (_ : ST.state) (tc : tcenv1) =
try
let pt = PT.pt_of_uglobal !!tc (FApi.tc1_hyps tc) LG.p_ip_dup in
EcLowGoal.Apply.t_apply_bwd_r ~mode:fmrigid ~canview:false pt tc
with EcLowGoal.Apply.NoInstance _ ->
tc_error !!tc "no top-assumption to duplicate"
and intro1_done (_ : ST.state) simplify (tc : tcenv1) =
let t =
match simplify with
| Some x ->
t_seq (t_simplify_lg ~delta:false (ttenv, x)) process_trivial
| None -> process_trivial
in t tc
and intro1_smt (_ : ST.state) ((dn, pi) : _ * pprover_infos) (tc : tcenv1) =
if dn then
t_or process_done (process_smt ttenv pi) tc
else process_smt ttenv pi tc
and intro1_simplify (_ : ST.state) logic tc =
t_simplify_lg ~delta:false (ttenv, logic) tc
and intro1_clear (_ : ST.state) xs tc =
process_clear xs tc
and intro1_case (st : ST.state) nointro pis gs =
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let tc = t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case] in
let tc =
fun g ->
try tc g
with InvalidGoalShape ->
tc_error !!g "invalid intro-pattern: nothing to eliminate"
in
if nointro && not cf then onsub gs else begin
match pis with
| [] -> t_onall tc gs
| _ -> t_onall (fun gs -> onsub (tc gs)) gs
end
and intro1_full_case (st : ST.state)
((prind, delta), withor, (cnt : icasemode_full option)) pis tc
=
let cnt = cnt |> odfl (`AtMost 1) in
let red = if delta then `Full else `NoDelta in
let t_case =
let t_and, t_or =
if prind then
((fun tc -> fst_map List.singleton (t_elim_iso_and ~reduce:red tc)),
(fun tc -> t_elim_iso_or ~reduce:red tc))
else
((fun tc -> ([2] , t_elim_and ~reduce:red tc)),
(fun tc -> ([1; 1], t_elim_or ~reduce:red tc))) in
let ts = if withor then [t_and; t_or] else [t_and] in
fun tc -> FApi.t_or_map ts tc
in
let onsub gs =
if List.is_empty pis then gs else begin
if FApi.tc_count gs <> List.length pis then
tc_error !$gs
"not the right number of intro-patterns (got %d, expecting %d)"
(List.length pis) (FApi.tc_count gs);
t_sub (List.map (dointro1 st false) pis) gs
end
in
let doit tc =
let rec aux imax tc =
if imax = Some 0 then t_id tc else
try
let ntop, tc = t_case tc in
FApi.t_sublasts
(List.map (fun i tc -> aux (omap ((+) (i-1)) imax) tc) ntop)
tc
with InvalidGoalShape ->
try
tc |> EcLowGoal.t_intro_sx_seq
`Fresh
(fun id ->
t_seq
(aux (omap ((+) (-1)) imax))
(t_generalize_hyps ~clear:`Yes [id]))
with
| EcCoreGoal.TcError _ when EcUtils.is_some imax ->
tc_error !!tc "not enough top-assumptions"
| EcCoreGoal.TcError _ ->
t_id tc
in
match cnt with
| `AtMost cnt -> aux (Some (max 1 cnt)) tc
| `AsMuch -> aux None tc
in
if List.is_empty pis then doit tc else onsub (doit tc)
and intro1_rw (_ : ST.state) (o, s) tc =
let h = EcIdent.create "_" in
let rwt tc =
let pt = PT.pt_of_hyp !!tc (FApi.tc1_hyps tc) h in
process_rewrite1_core ~close:false (s, None, o) pt tc
in t_seqs [t_intros_i [h]; rwt; t_clear h] tc
and intro1_unfold (_ : ST.state) (s, o) p tc =
process_delta ~und_delta:ttenv.tt_und_delta (s, o, p) tc
and intro1_view (_ : ST.state) pe tc =
process_view1 pe tc
and intro1_subst (_ : ST.state) d (tc : tcenv1) =
try
t_intros_i_seq ~clear:true [EcIdent.create "_"]
(EcLowGoal.t_subst ~clear:true ~tside:(d :> tside))
tc
with InvalidGoalShape ->
tc_error !!tc "nothing to substitute"
and intro1_subst_top (_ : ST.state) (omax, osd) (tc : tcenv1) =
let t_subst eqid =
let sk1 = { empty_subst_kind with sk_local = true ; } in
let sk2 = { full_subst_kind with sk_local = false; } in
let side = `All osd in
FApi.t_or
(t_subst ~tside:side ~kind:sk1 ~eqid)
(t_subst ~tside:side ~kind:sk2 ~eqid)
in
let togen = ref [] in
let rec doit i tc =
match omax with Some max when i >= max -> tcenv_of_tcenv1 tc | _ ->
try
let id = EcIdent.create "_" in
let tc = EcLowGoal.t_intros_i_1 [id] tc in
FApi.t_switch (t_subst id) ~ifok:(doit (i+1))
~iffail:(fun tc -> togen := id :: !togen; doit (i+1) tc)
tc
with EcCoreGoal.TcError _ ->
if is_some omax then
tc_error !!tc "not enough top-assumptions";
tcenv_of_tcenv1 tc in
let tc = doit 0 tc in
t_generalize_hyps
~clear:`Yes ~missing:true
(List.rev !togen) (FApi.as_tcenv1 tc)
and intro1_crush (_st : ST.state) (d : crushmode) (gs : tcenv1) =
let delta, tsolve = process_crushmode d in
FApi.t_or
(EcPhlConseq.t_conseqauto ~delta ?tsolve)
(EcLowGoal.t_crush ~delta ?tsolve)
gs
and dointro (st : ST.state) nointro pis (gs : tcenv) =
match pis with [] -> gs | { pl_desc = pi; pl_loc = ploc } :: pis ->
let nointro, gs =
let rl x = EcCoreGoal.reloc ploc x in
match pi with
| `Core ids ->
(false, rl (t_onall (intro1_core st ids)) gs)
| `Dup ->
(false, rl (t_onall (intro1_dup st)) gs)
| `Done b ->
(nointro, rl (t_onall (intro1_done st b)) gs)
| `Smt pi ->
(nointro, rl (t_onall (intro1_smt st pi)) gs)
| `Simpl b ->
(nointro, rl (t_onall (intro1_simplify st b)) gs)
| `Clear xs ->
(nointro, rl (t_onall (intro1_clear st xs)) gs)
| `Case (`One, pis) ->
(false, rl (intro1_case st nointro pis) gs)
| `Case (`Full x, pis) ->
(false, rl (t_onall (intro1_full_case st x pis)) gs)
| `Rw (o, s, None) ->
(false, rl (t_onall (intro1_rw st (o, s))) gs)
| `Rw (o, s, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_rw st (o, s)))) gs)
| `Delta ((o, s), p) ->
(nointro, rl (t_onall (intro1_unfold st (o, s) p)) gs)
| `View pe ->
(false, rl (t_onall (intro1_view st pe)) gs)
| `Subst (d, None) ->
(false, rl (t_onall (intro1_subst st d)) gs)
| `Subst (d, Some i) ->
(false, rl (t_onall (t_do `All i (intro1_subst st d))) gs)
| `SubstTop d ->
(false, rl (t_onall (intro1_subst_top st d)) gs)
| `Crush d ->
(false, rl (t_onall (intro1_crush st d)) gs)
in dointro st nointro pis gs
and dointro1 st nointro pis tc =
dointro st nointro pis (FApi.tcenv_of_tcenv1 tc) in
try
let st = ST.create () in
let ip, pis = collect pis in
let gs = dointro st true (List.rev ip) gs in
let gs =
let ls = ST.listing st in
let gn = List.pmap (function (`Gen x, y) -> Some (x, y) | _ -> None) ls in
let cl = List.pmap (function (`Clear, y) -> Some y | _ -> None) ls in
t_onall (fun tc ->
t_generalize_hyps_x
~missing:true ~naming:(ST.naming st)
gn tc)
(t_onall (t_clears cl) gs)
in
if List.is_empty pis then gs else
gs |> t_onall (fun tc ->
process_mintros_1 ~cf:true ttenv pis (FApi.tcenv_of_tcenv1 tc))
with IntroCollect e -> begin
match e with
| `InternalBreak ->
tc_error !$gs "cannot use internal break in intro-patterns"
end
let process_intros_1 ?cf ttenv pis tc =
process_mintros_1 ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let rec process_mintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc = process_mintros_1 ?cf ttenv pi tc in
process_mintros ~cf:false ttenv pis tc
let process_intros ?cf ttenv pis tc =
process_mintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let process_generalize1 ?(doeq = false) pattern (tc : tcenv1) =
let env, hyps, concl = FApi.tc1_eflat tc in
let onresolved ?(tryclear = true) pattern =
let clear = if tryclear then `Yes else `No in
match pattern with
| `Form (occ, pf) -> begin
match pf.pl_desc with
| PFident ({pl_desc = ([], s)}, None)
when not doeq && is_none occ && LDecl.has_name s hyps
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let (ptenv, p) =
let (ps, ue), p = TTC.tc1_process_pattern tc pf in
let ev = MEV.of_idents (Mid.keys ps) `Form in
(ptenv !!tc hyps (ue, ev), p)
in
(try ignore (PT.pf_find_occurence ptenv ~ptn:p concl)
with PT.FindOccFailure _ -> tc_error !!tc "cannot find an occurence");
let p = PT.concretize_form ptenv p in
let occ = norm_rwocc occ in
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps occ p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
let name =
match EcParsetree.pf_ident pf with
| None ->
EcIdent.create "x"
| Some x when EcIo.is_sym_ident x ->
EcIdent.create x
| Some _ ->
EcIdent.create (EcTypes.symbol_of_ty p.f_ty)
in
let name, newconcl = FPosition.topattern ~x:name cpos concl in
let newconcl =
if doeq then
if EcReduction.EqTest.for_type env p.f_ty tbool then
f_imps [f_iff p (f_local name p.f_ty)] newconcl
else
f_imps [f_eq p (f_local name p.f_ty)] newconcl
else newconcl in
let newconcl = f_forall [(name, GTty p.f_ty)] newconcl in
let pt = { pt_head = PTCut newconcl; pt_args = [PAFormula p]; } in
EcLowGoal.t_apply pt tc
end
| `ProofTerm fp -> begin
match fp.fp_head with
| FPNamed ({ pl_desc = ([], s) }, None)
when LDecl.has_name s hyps && List.is_empty fp.fp_args
->
let id = fst (LDecl.by_name s hyps) in
t_generalize_hyp ~clear id tc
| _ ->
let pt = PT.tc1_process_full_pterm tc fp in
if not (PT.can_concretize pt.PT.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
t_cutdef pt ax tc
end
| `LetIn x ->
let id =
let binding =
try Some (LDecl.by_name (unloc x) hyps)
with EcEnv.LDecl.LdeclError _ -> None in
match binding with
| Some (id, LD_var (_, Some _)) -> id
| _ ->
let msg = "symbol must reference let-in" in
tc_error ~loc:(loc x) !!tc "%s" msg
in t_generalize_hyp ~clear ~letin:true id tc
in
match ffpattern_of_genpattern hyps pattern with
| Some ff ->
let tryclear =
match pattern with
| (`Form (None, { pl_desc = PFident _ })) -> true
| _ -> false
in onresolved ~tryclear (`ProofTerm ff)
| None -> onresolved pattern
let process_generalize ?(doeq = false) patterns (tc : tcenv1) =
try
let patterns = List.mapi (fun i p ->
process_generalize1 ~doeq:(doeq && i = 0) p) patterns in
FApi.t_seqs (List.rev patterns) tc
with (EcCoreGoal.ClearError _) as err ->
tc_error_exn !!tc err
let rec process_mgenintros ?cf ttenv pis tc =
match pis with [] -> tc | pi :: pis ->
let tc =
match pi with
| `Ip pi -> process_mintros_1 ?cf ttenv pi tc
| `Gen gn ->
t_onall (
t_seqs [
process_clear gn.pr_clear;
process_generalize gn.pr_genp
]) tc
in process_mgenintros ~cf:false ttenv pis tc
let process_genintros ?cf ttenv pis tc =
process_mgenintros ?cf ttenv pis (FApi.tcenv_of_tcenv1 tc)
let process_move ?doeq views pr (tc : tcenv1) =
t_seqs
[process_clear pr.pr_clear;
process_generalize ?doeq pr.pr_genp;
process_view views]
tc
let process_pose xsym bds o p (tc : tcenv1) =
let (env, hyps, concl) = FApi.tc1_eflat tc in
let o = norm_rwocc o in
let (ptenv, p) =
let ps = ref Mid.empty in
let ue = TTC.unienv_of_hyps hyps in
let (senv, bds) = EcTyping.trans_binding env ue bds in
let p = EcTyping.trans_pattern senv ps ue p in
let ev = MEV.of_idents (Mid.keys !ps) `Form in
(ptenv !!tc hyps (ue, ev),
f_lambda (List.map (snd_map gtty) bds) p)
in
let dopat =
try
ignore (PT.pf_find_occurence ~occmode:PT.om_rigid ptenv ~ptn:p concl);
true
with PT.FindOccFailure _ ->
if not (PT.can_concretize ptenv) then
if not (EcMatching.MEV.filled !(ptenv.PT.pte_ev)) then
tc_error !!tc "cannot find an occurence"
else
tc_error !!tc "%s - %s"
"cannot find an occurence"
"instantiate type variables manually"
else
false
in
let p = PT.concretize_form ptenv p in
let (x, letin) =
match dopat with
| false -> (EcIdent.create (unloc xsym), concl)
| true -> begin
let cpos =
try FPosition.select_form ~xconv:`AlphaEq hyps o p concl
with InvalidOccurence -> tacuerror "invalid occurence selector"
in
FPosition.topattern ~x:(EcIdent.create (unloc xsym)) cpos concl
end
in
let letin = EcFol.f_let1 x p letin in
FApi.t_seq
(t_change letin)
(t_intros [Tagged (x, Some xsym.pl_loc)]) tc
type apply_t = EcParsetree.apply_info
let process_apply ~implicits ((infos, orv) : apply_t * prevert option) tc =
let do_apply tc =
match infos with
| `ApplyIn (pe, tg) ->
process_apply_fwd ~implicits (pe, tg) tc
| `Apply (pe, mode) ->
let for1 tc pe =
t_last (process_apply_bwd ~implicits `Apply pe) tc in
let tc = List.fold_left for1 (tcenv_of_tcenv1 tc) pe in
if mode = `Exact then t_onall process_done tc else tc
| `Alpha pe ->
process_apply_bwd ~implicits `Alpha pe tc
| `Top mode ->
let tc = process_apply_top tc in
if mode = `Exact then t_onall process_done tc else tc
in
t_seq
(fun tc -> ofdfl
(fun () -> t_id tc)
(omap (fun rv -> process_move [] rv tc) orv))
do_apply tc
let process_subst syms (tc : tcenv1) =
let resolve symp =
let sym = TTC.tc1_process_form_opt tc None symp in
match sym.f_node with
| Flocal id -> `Local id
| Fglob (mp, mem) -> `Glob (mp, mem)
| Fpvar (pv, mem) -> `PVar (pv, mem)
| _ ->
tc_error !!tc ~loc:symp.pl_loc
"this formula is not subject to substitution"
in
match List.map resolve syms with
| [] -> t_repeat t_subst tc
| syms -> FApi.t_seqs (List.map (fun var tc -> t_subst ~var tc) syms) tc
type cut_t = intropattern * pformula * (ptactics located) option
type cutmode = [`Have | `Suff]
let process_cut ?(mode = `Have) engine ttenv ((ip, phi, t) : cut_t) tc =
let phi = TTC.tc1_process_formula tc phi in
let tc = EcLowGoal.t_cut phi tc in
let applytc tc =
t |> ofold (fun t tc ->
let t = mk_loc (loc t) (Pby (Some (unloc t))) in
t_onall (engine t) tc) (FApi.tcenv_of_tcenv1 tc)
in
match mode with
| `Have ->
FApi.t_first applytc
(FApi.t_last (process_intros_1 ttenv ip) tc)
| `Suff ->
FApi.t_rotate `Left 1
(FApi.t_on1 0 t_id ~ttout:applytc
(FApi.t_last (process_intros_1 ttenv ip) tc))
type cutdef_t = intropattern * pcutdef
let process_cutdef ttenv (ip, pt) (tc : tcenv1) =
let pt = {
fp_mode = `Implicit;
fp_head = FPNamed (pt.ptcd_name, pt.ptcd_tys);
fp_args = pt.ptcd_args;
} in
let pt = PT.tc1_process_full_pterm tc pt in
if not (PT.can_concretize pt.ptev_env) then
tc_error !!tc "cannot infer all placeholders";
let pt, ax = PT.concretize pt in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut ax tc)
type cutdef_sc_t = intropattern * pcutdef_schema
let process_cutdef_sc ttenv (ip, inst) (tc : tcenv1) =
let pt,sc_i = PT.tc1_process_sc_instantiation tc inst in
FApi.t_sub
[EcLowGoal.t_apply pt; process_intros_1 ttenv ip]
(t_cut sc_i tc)
let process_left (tc : tcenv1) =
try
t_ors [EcLowGoal.t_left; EcLowGoal.t_or_intro_prind `Left] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `left` on that goal"
let process_right (tc : tcenv1) =
try
t_ors [EcLowGoal.t_right; EcLowGoal.t_or_intro_prind `Right] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `right` on that goal"
let process_split (tc : tcenv1) =
try t_ors [EcLowGoal.t_split; EcLowGoal.t_split_prind] tc
with InvalidGoalShape ->
tc_error !!tc "cannot apply `split` on that goal"
let process_elim (pe, qs) tc =
let doelim tc =
match qs with
| None -> t_or (t_elimT_ind `Ind) t_elim tc
| Some qs ->
let qs = {
fp_mode = `Implicit;
fp_head = FPNamed (qs, None);
fp_args = [];
} in process_elimT qs tc
in
try
FApi.t_last doelim (process_move [] pe tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't know what to eliminate"
let process_case ?(doeq = false) gp tc =
let module E = struct exception LEMFailure end in
try
match gp.pr_rev with
| { pr_genp = [`Form (None, pf)] }
when List.is_empty gp.pr_view ->
let env = FApi.tc1_env tc in
let f =
try TTC.process_formula (FApi.tc1_hyps tc) pf
with TT.TyError _ | LocError (_, TT.TyError _) -> raise E.LEMFailure
in
if not (EcReduction.EqTest.for_type env f.f_ty tbool) then
raise E.LEMFailure;
begin
match (fst (destr_app f)).f_node with
| Fop (p, _) when EcEnv.Op.is_prind env p ->
raise E.LEMFailure
| _ -> ()
end;
t_seqs
[process_clear gp.pr_rev.pr_clear; t_case f;
t_simplify_with_info EcReduction.betaiota_red]
tc
| _ -> raise E.LEMFailure
with E.LEMFailure ->
try
FApi.t_last
(t_ors [t_elimT_ind `Case; t_elim; t_elim_prind `Case])
(process_move ~doeq gp.pr_view gp.pr_rev tc)
with EcCoreGoal.InvalidGoalShape ->
tc_error !!tc "don't known what to eliminate"
let process_exists args (tc : tcenv1) =
let hyps = FApi.tc1_hyps tc in
let pte = (TTC.unienv_of_hyps hyps, EcMatching.MEV.empty) in
let pte = PT.ptenv !!tc (FApi.tc1_hyps tc) pte in
let for1 concl arg =
match TTC.destruct_exists hyps concl with
| None -> tc_error !!tc "not an existential"
| Some (`Exists (x, xty, f)) ->
let arg =
match xty with
| GTty _ -> trans_pterm_arg_value pte arg
| GTmem _ -> trans_pterm_arg_mem pte arg
| GTmodty _ -> trans_pterm_arg_mod pte arg
in
PT.check_pterm_arg pte (x, xty) f arg.ptea_arg
in
let _concl, args = List.map_fold for1 (FApi.tc1_goal tc) args in
if not (PT.can_concretize pte) then
tc_error !!tc "cannot infer all placeholders";
let pte = PT.concretize_env pte in
let args = List.map (PT.concretize_e_arg pte) args in
EcLowGoal.t_exists_intro_s args tc
let process_congr tc =
let (env, hyps, concl) = FApi.tc1_eflat tc in
if not (EcFol.is_eq_or_iff concl) then
tc_error !!tc "goal must be an equality or an equivalence";
let ((f1, f2), iseq) =
if EcFol.is_eq concl
then (EcFol.destr_eq concl, true )
else (EcFol.destr_iff concl, false) in
let t_ensure_eq =
if iseq then t_id
else
(fun tc ->
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_uglobal !!tc hyps LG.p_eq_iff) tc) in
let t_subgoal = t_ors [t_reflex ~mode:`Alpha; t_assumption `Alpha; t_id] in
match f1.f_node, f2.f_node with
| _, _ when EcReduction.is_alpha_eq hyps f1 f2 ->
FApi.t_seq t_ensure_eq EcLowGoal.t_reflex tc
| Fapp (o1, a1), Fapp (o2, a2)
when EcReduction.is_alpha_eq hyps o1 o2
&& List.length a1 = List.length a2 ->
let tt1 = t_congr (o1, o2) ((List.combine a1 a2), f1.f_ty) in
FApi.t_seqs [t_ensure_eq; tt1; t_subgoal] tc
| Fif (_, { f_ty = cty }, _), Fif _ ->
let tt0 tc =
let hyps = FApi.tc1_hyps tc in
EcLowGoal.Apply.t_apply_bwd_r
(PT.pt_of_global !!tc hyps LG.p_if_congr [cty]) tc
in FApi.t_seqs [tt0; t_subgoal] tc
| Ftuple _, Ftuple _ when iseq ->
FApi.t_seqs [t_split; t_subgoal] tc
| Fproj (f1, i1), Fproj (f2, i2)
when i1 = i2 && EcReduction.EqTest.for_type env f1.f_ty f2.f_ty
-> EcCoreGoal.FApi.xmutate1 tc `CongrProj [f_eq f1 f2]
| _, _ -> tacuerror "not a congruence"
let process_wlog ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_rotate `Left 1 (EcLowGoal.t_cut wlog tc) in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc
in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut gen tc))
let process_wlog_suff ids wlog tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let wlog =
let wlog = TTC.tc1_process_formula tc wlog in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) (t_cut wlog tc) in
FApi.tc_goal tc in
t_rotate `Left 1
(t_first
(t_seq (t_clears ids) (t_intros_i ids))
(t_cut wlog tc))
let process_wlog ~suff ids wlog tc =
if suff
then process_wlog_suff ids wlog tc
else process_wlog ids wlog tc
let process_genhave (ttenv : ttenv) ((name, ip, ids, gen) : pgenhave) tc =
let hyps, _ = FApi.tc1_flat tc in
let toid s =
if not (LDecl.has_name (unloc s) hyps) then
tc_lookup_error !!tc ~loc:s.pl_loc `Local ([], unloc s);
fst (LDecl.by_name (unloc s) hyps) in
let ids = List.map toid ids in
let gen =
let gen = TTC.tc1_process_formula tc gen in
let tc = EcLowGoal.t_cut gen tc in
let tc = t_first (t_generalize_hyps ~clear:`Yes ids) tc in
FApi.tc_goal tc in
let doip tc =
let genid = EcIdent.create (unloc name) in
let tc = t_intros_i_1 [genid] tc in
match ip with
| None ->
t_id tc
| Some ip ->
let pt = EcProofTerm.pt_of_hyp !!tc (FApi.tc1_hyps tc) genid in
let pt = List.fold_left EcProofTerm.apply_pterm_to_local pt ids in
let tc = t_cutdef pt.ptev_pt pt.ptev_ax tc in
process_mintros ttenv [ip] tc in
t_sub [
t_seq (t_clears ids) (t_intros_i ids);
doip
] (t_cut gen tc)
|
57b0a7ff1e99abecd9945eea11e0be0059f2217e1d3da63200fbe69b397e4261 | FranklinChen/hugs98-plus-Sep2006 | Types.hs | -----------------------------------------------------------------------------
-- |
-- Module : System.Win32.Types
Copyright : ( c ) , 1997 - 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer : Vuokko < >
-- Stability : provisional
-- Portability : portable
--
A collection of FFI declarations for interfacing with Win32 .
--
-----------------------------------------------------------------------------
module System.Win32.Types
( module System.Win32.Types
, nullPtr
) where
import Data.Maybe
import Foreign
import Foreign.C
import Numeric (showHex)
----------------------------------------------------------------
-- Platform specific definitions
--
-- Most typedefs and prototypes in Win32 are expressed in terms
-- of these types. Try to follow suit - it'll make it easier to
get things working on Win64 ( or whatever they call it on Alphas ) .
----------------------------------------------------------------
type BOOL = Bool
type BYTE = Word8
type USHORT = Word16
type UINT = Word32
type INT = Int32
type WORD = Word16
type DWORD = Word32
type LONG = Int32
type FLOAT = Float
type LARGE_INTEGER = Int64
-- Not really a basic type, but used in many places
type DDWORD = Word64
----------------------------------------------------------------
type MbString = Maybe String
type MbINT = Maybe INT
type ATOM = UINT
type WPARAM = UINT
type LPARAM = LONG
type LRESULT = LONG
type SIZE_T = DWORD
type MbATOM = Maybe ATOM
----------------------------------------------------------------
Pointers
----------------------------------------------------------------
type Addr = Ptr ()
type LPVOID = Ptr ()
type LPBYTE = Ptr BYTE
type LPSTR = Ptr CChar
type LPCSTR = LPSTR
type LPWSTR = Ptr CWchar
type LPCWSTR = LPWSTR
type LPTSTR = Ptr TCHAR
type LPCTSTR = LPTSTR
type LPCTSTR_ = LPCTSTR
-- Optional things with defaults
maybePtr :: Maybe (Ptr a) -> Ptr a
maybePtr = fromMaybe nullPtr
ptrToMaybe :: Ptr a -> Maybe (Ptr a)
ptrToMaybe p = if p == nullPtr then Nothing else Just p
maybeNum :: Num a => Maybe a -> a
maybeNum = fromMaybe 0
numToMaybe :: Num a => a -> Maybe a
numToMaybe n = if n == 0 then Nothing else Just n
type MbLPVOID = Maybe LPVOID
type MbLPCSTR = Maybe LPCSTR
type MbLPCTSTR = Maybe LPCTSTR
----------------------------------------------------------------
-- Chars and strings
----------------------------------------------------------------
withTString :: String -> (LPTSTR -> IO a) -> IO a
withTStringLen :: String -> ((LPTSTR, Int) -> IO a) -> IO a
peekTString :: LPCTSTR -> IO String
peekTStringLen :: (LPCTSTR, Int) -> IO String
newTString :: String -> IO LPCTSTR
-- UTF-16 version:
type TCHAR = CWchar
withTString = withCWString
withTStringLen = withCWStringLen
peekTString = peekCWString
peekTStringLen = peekCWStringLen
newTString = newCWString
ANSI version :
type TCHAR =
withTString = withCString
withTStringLen = withCStringLen
peekTString = peekCString
peekTStringLen = peekCStringLen
newTString = newCString
type TCHAR = CChar
withTString = withCString
withTStringLen = withCStringLen
peekTString = peekCString
peekTStringLen = peekCStringLen
newTString = newCString
-}
----------------------------------------------------------------
-- Handles
----------------------------------------------------------------
type HANDLE = Ptr ()
type ForeignHANDLE = ForeignPtr ()
newForeignHANDLE :: HANDLE -> IO ForeignHANDLE
newForeignHANDLE = newForeignPtr deleteObject_p
handleToWord :: HANDLE -> UINT
handleToWord = castPtrToUINT
type HKEY = ForeignHANDLE
type PKEY = HANDLE
nullHANDLE :: HANDLE
nullHANDLE = nullPtr
type MbHANDLE = Maybe HANDLE
type HINSTANCE = Ptr ()
type MbHINSTANCE = Maybe HINSTANCE
type HMODULE = Ptr ()
type MbHMODULE = Maybe HMODULE
nullFinalHANDLE :: ForeignPtr a
nullFinalHANDLE = unsafePerformIO (newForeignPtr_ nullPtr)
iNVALID_HANDLE_VALUE :: HANDLE
iNVALID_HANDLE_VALUE = castUINTToPtr 0xffffffff
----------------------------------------------------------------
-- Errors
----------------------------------------------------------------
type ErrCode = DWORD
failIf :: (a -> Bool) -> String -> IO a -> IO a
failIf p wh act = do
v <- act
if p v then errorWin wh else return v
failIf_ :: (a -> Bool) -> String -> IO a -> IO ()
failIf_ p wh act = do
v <- act
if p v then errorWin wh else return ()
failIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
failIfNull = failIf (== nullPtr)
failIfZero :: Num a => String -> IO a -> IO a
failIfZero = failIf (== 0)
failIfFalse_ :: String -> IO Bool -> IO ()
failIfFalse_ = failIf_ not
failUnlessSuccess :: String -> IO ErrCode -> IO ()
failUnlessSuccess fn_name act = do
r <- act
if r == 0 then return () else failWith fn_name r
failUnlessSuccessOr :: ErrCode -> String -> IO ErrCode -> IO Bool
failUnlessSuccessOr val fn_name act = do
r <- act
if r == 0 then return False
else if r == val then return True
else failWith fn_name r
errorWin :: String -> IO a
errorWin fn_name = do
err_code <- getLastError
failWith fn_name err_code
failWith :: String -> ErrCode -> IO a
failWith fn_name err_code = do
c_msg <- getErrorMessage err_code
msg <- peekTString c_msg
localFree c_msg
fail (fn_name ++ ": " ++ msg ++ " (error code: " ++ showHex err_code ")")
----------------------------------------------------------------
-- Misc helpers
----------------------------------------------------------------
ddwordToDwords :: DDWORD -> (DWORD,DWORD)
ddwordToDwords n =
(fromIntegral (n `shiftR` bitSize (undefined::DWORD))
,fromIntegral (n .&. fromIntegral (maxBound :: DWORD)))
dwordsToDdword:: (DWORD,DWORD) -> DDWORD
dwordsToDdword (hi,low) = (fromIntegral low) .|. (fromIntegral hi `shiftL`bitSize hi)
----------------------------------------------------------------
-- Primitives
----------------------------------------------------------------
foreign import stdcall unsafe "windows.h &DeleteObject"
deleteObject_p :: FunPtr (HANDLE -> IO ())
foreign import stdcall unsafe "windows.h LocalFree"
localFree :: Ptr a -> IO (Ptr a)
foreign import stdcall unsafe "windows.h GetLastError"
getLastError :: IO ErrCode
{-# CFILES cbits/errors.c #-}
foreign import ccall unsafe "errors.h"
getErrorMessage :: DWORD -> IO LPWSTR
{-# CFILES cbits/HsWin32.c #-}
foreign import ccall unsafe "HsWin32.h"
lOWORD :: DWORD -> WORD
foreign import ccall unsafe "HsWin32.h"
hIWORD :: DWORD -> WORD
foreign import ccall unsafe "HsWin32.h"
castUINTToPtr :: UINT -> Ptr a
foreign import ccall unsafe "HsWin32.h"
castPtrToUINT :: Ptr s -> UINT
foreign import ccall unsafe "HsWin32.h"
castFunPtrToLONG :: FunPtr a -> LONG
type LCID = DWORD
type LANGID = WORD
type SortID = WORD
foreign import ccall unsafe "HsWin32.h prim_MAKELCID"
mAKELCID :: LANGID -> SortID -> LCID
foreign import ccall unsafe "HsWin32.h prim_LANGIDFROMLCID"
lANGIDFROMLCID :: LCID -> LANGID
foreign import ccall unsafe "HsWin32.h prim_SORTIDFROMLCID"
sORTIDFROMLCID :: LCID -> SortID
type SubLANGID = WORD
type PrimaryLANGID = WORD
foreign import ccall unsafe "HsWin32.h prim_MAKELANGID"
mAKELANGID :: PrimaryLANGID -> SubLANGID -> LANGID
foreign import ccall unsafe "HsWin32.h prim_PRIMARYLANGID"
pRIMARYLANGID :: LANGID -> PrimaryLANGID
foreign import ccall unsafe "HsWin32.h prim_SUBLANGID"
sUBLANGID :: LANGID -> SubLANGID
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/Win32/System/Win32/Types.hs | haskell | ---------------------------------------------------------------------------
|
Module : System.Win32.Types
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
--------------------------------------------------------------
Platform specific definitions
Most typedefs and prototypes in Win32 are expressed in terms
of these types. Try to follow suit - it'll make it easier to
--------------------------------------------------------------
Not really a basic type, but used in many places
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
Optional things with defaults
--------------------------------------------------------------
Chars and strings
--------------------------------------------------------------
UTF-16 version:
--------------------------------------------------------------
Handles
--------------------------------------------------------------
--------------------------------------------------------------
Errors
--------------------------------------------------------------
--------------------------------------------------------------
Misc helpers
--------------------------------------------------------------
--------------------------------------------------------------
Primitives
--------------------------------------------------------------
# CFILES cbits/errors.c #
# CFILES cbits/HsWin32.c #
--------------------------------------------------------------
End
-------------------------------------------------------------- | Copyright : ( c ) , 1997 - 2003
Maintainer : Vuokko < >
A collection of FFI declarations for interfacing with Win32 .
module System.Win32.Types
( module System.Win32.Types
, nullPtr
) where
import Data.Maybe
import Foreign
import Foreign.C
import Numeric (showHex)
get things working on Win64 ( or whatever they call it on Alphas ) .
type BOOL = Bool
type BYTE = Word8
type USHORT = Word16
type UINT = Word32
type INT = Int32
type WORD = Word16
type DWORD = Word32
type LONG = Int32
type FLOAT = Float
type LARGE_INTEGER = Int64
type DDWORD = Word64
type MbString = Maybe String
type MbINT = Maybe INT
type ATOM = UINT
type WPARAM = UINT
type LPARAM = LONG
type LRESULT = LONG
type SIZE_T = DWORD
type MbATOM = Maybe ATOM
Pointers
type Addr = Ptr ()
type LPVOID = Ptr ()
type LPBYTE = Ptr BYTE
type LPSTR = Ptr CChar
type LPCSTR = LPSTR
type LPWSTR = Ptr CWchar
type LPCWSTR = LPWSTR
type LPTSTR = Ptr TCHAR
type LPCTSTR = LPTSTR
type LPCTSTR_ = LPCTSTR
maybePtr :: Maybe (Ptr a) -> Ptr a
maybePtr = fromMaybe nullPtr
ptrToMaybe :: Ptr a -> Maybe (Ptr a)
ptrToMaybe p = if p == nullPtr then Nothing else Just p
maybeNum :: Num a => Maybe a -> a
maybeNum = fromMaybe 0
numToMaybe :: Num a => a -> Maybe a
numToMaybe n = if n == 0 then Nothing else Just n
type MbLPVOID = Maybe LPVOID
type MbLPCSTR = Maybe LPCSTR
type MbLPCTSTR = Maybe LPCTSTR
withTString :: String -> (LPTSTR -> IO a) -> IO a
withTStringLen :: String -> ((LPTSTR, Int) -> IO a) -> IO a
peekTString :: LPCTSTR -> IO String
peekTStringLen :: (LPCTSTR, Int) -> IO String
newTString :: String -> IO LPCTSTR
type TCHAR = CWchar
withTString = withCWString
withTStringLen = withCWStringLen
peekTString = peekCWString
peekTStringLen = peekCWStringLen
newTString = newCWString
ANSI version :
type TCHAR =
withTString = withCString
withTStringLen = withCStringLen
peekTString = peekCString
peekTStringLen = peekCStringLen
newTString = newCString
type TCHAR = CChar
withTString = withCString
withTStringLen = withCStringLen
peekTString = peekCString
peekTStringLen = peekCStringLen
newTString = newCString
-}
type HANDLE = Ptr ()
type ForeignHANDLE = ForeignPtr ()
newForeignHANDLE :: HANDLE -> IO ForeignHANDLE
newForeignHANDLE = newForeignPtr deleteObject_p
handleToWord :: HANDLE -> UINT
handleToWord = castPtrToUINT
type HKEY = ForeignHANDLE
type PKEY = HANDLE
nullHANDLE :: HANDLE
nullHANDLE = nullPtr
type MbHANDLE = Maybe HANDLE
type HINSTANCE = Ptr ()
type MbHINSTANCE = Maybe HINSTANCE
type HMODULE = Ptr ()
type MbHMODULE = Maybe HMODULE
nullFinalHANDLE :: ForeignPtr a
nullFinalHANDLE = unsafePerformIO (newForeignPtr_ nullPtr)
iNVALID_HANDLE_VALUE :: HANDLE
iNVALID_HANDLE_VALUE = castUINTToPtr 0xffffffff
type ErrCode = DWORD
failIf :: (a -> Bool) -> String -> IO a -> IO a
failIf p wh act = do
v <- act
if p v then errorWin wh else return v
failIf_ :: (a -> Bool) -> String -> IO a -> IO ()
failIf_ p wh act = do
v <- act
if p v then errorWin wh else return ()
failIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
failIfNull = failIf (== nullPtr)
failIfZero :: Num a => String -> IO a -> IO a
failIfZero = failIf (== 0)
failIfFalse_ :: String -> IO Bool -> IO ()
failIfFalse_ = failIf_ not
failUnlessSuccess :: String -> IO ErrCode -> IO ()
failUnlessSuccess fn_name act = do
r <- act
if r == 0 then return () else failWith fn_name r
failUnlessSuccessOr :: ErrCode -> String -> IO ErrCode -> IO Bool
failUnlessSuccessOr val fn_name act = do
r <- act
if r == 0 then return False
else if r == val then return True
else failWith fn_name r
errorWin :: String -> IO a
errorWin fn_name = do
err_code <- getLastError
failWith fn_name err_code
failWith :: String -> ErrCode -> IO a
failWith fn_name err_code = do
c_msg <- getErrorMessage err_code
msg <- peekTString c_msg
localFree c_msg
fail (fn_name ++ ": " ++ msg ++ " (error code: " ++ showHex err_code ")")
ddwordToDwords :: DDWORD -> (DWORD,DWORD)
ddwordToDwords n =
(fromIntegral (n `shiftR` bitSize (undefined::DWORD))
,fromIntegral (n .&. fromIntegral (maxBound :: DWORD)))
dwordsToDdword:: (DWORD,DWORD) -> DDWORD
dwordsToDdword (hi,low) = (fromIntegral low) .|. (fromIntegral hi `shiftL`bitSize hi)
foreign import stdcall unsafe "windows.h &DeleteObject"
deleteObject_p :: FunPtr (HANDLE -> IO ())
foreign import stdcall unsafe "windows.h LocalFree"
localFree :: Ptr a -> IO (Ptr a)
foreign import stdcall unsafe "windows.h GetLastError"
getLastError :: IO ErrCode
foreign import ccall unsafe "errors.h"
getErrorMessage :: DWORD -> IO LPWSTR
foreign import ccall unsafe "HsWin32.h"
lOWORD :: DWORD -> WORD
foreign import ccall unsafe "HsWin32.h"
hIWORD :: DWORD -> WORD
foreign import ccall unsafe "HsWin32.h"
castUINTToPtr :: UINT -> Ptr a
foreign import ccall unsafe "HsWin32.h"
castPtrToUINT :: Ptr s -> UINT
foreign import ccall unsafe "HsWin32.h"
castFunPtrToLONG :: FunPtr a -> LONG
type LCID = DWORD
type LANGID = WORD
type SortID = WORD
foreign import ccall unsafe "HsWin32.h prim_MAKELCID"
mAKELCID :: LANGID -> SortID -> LCID
foreign import ccall unsafe "HsWin32.h prim_LANGIDFROMLCID"
lANGIDFROMLCID :: LCID -> LANGID
foreign import ccall unsafe "HsWin32.h prim_SORTIDFROMLCID"
sORTIDFROMLCID :: LCID -> SortID
type SubLANGID = WORD
type PrimaryLANGID = WORD
foreign import ccall unsafe "HsWin32.h prim_MAKELANGID"
mAKELANGID :: PrimaryLANGID -> SubLANGID -> LANGID
foreign import ccall unsafe "HsWin32.h prim_PRIMARYLANGID"
pRIMARYLANGID :: LANGID -> PrimaryLANGID
foreign import ccall unsafe "HsWin32.h prim_SUBLANGID"
sUBLANGID :: LANGID -> SubLANGID
|
9ea06aa040cd806f09d20ceeb064d816bcdd09652bd94d570fbb4522e25806dd | RedBrainLabs/system-graph | utils.clj | (ns com.redbrainlabs.system-graph.utils
"Utillity fns for working with Prismatic's Graph and fnk"
(:require [plumbing.graph :as graph]
[schema.core :as s]))
(defn topo-sort
"Returns the topological sort of a Prismatic graph"
[g]
(-> g graph/->graph keys vec))
TODO : see if plumbing already has a fn for this ... or helper fns that seem less intrusive ..
(defn fnk-deps [fnk]
(->> fnk
s/fn-schema
:input-schemas ;; [[#schema.core.One{:schema {Keyword Any, :funk Any, :x Any}, :optional? false, :name arg0}]]
ffirst
:schema
keys
(filter keyword?)))
TODO : see if plumbing 's ` comp - partial ` does what I need ( as suggested by )
(defn comp-fnk
"Composes the given given fnk with the provided fn. Only handles the binary case."
[f fnk]
;; TODO: handle other fnks (verifying input/output schemas) and the variadic case
(let [comped (-> (comp f fnk)
(with-meta (meta fnk)))]
;; compose the positional function as well if present
(if [(-> fnk meta :plumbing.fnk.impl/positional-info)]
(vary-meta comped update-in [:plumbing.fnk.impl/positional-info 0] (partial comp f))
comped)))
| null | https://raw.githubusercontent.com/RedBrainLabs/system-graph/928d5d7de34047e54b0f05d33cf5104d0d9be53a/src/com/redbrainlabs/system_graph/utils.clj | clojure | [[#schema.core.One{:schema {Keyword Any, :funk Any, :x Any}, :optional? false, :name arg0}]]
TODO: handle other fnks (verifying input/output schemas) and the variadic case
compose the positional function as well if present | (ns com.redbrainlabs.system-graph.utils
"Utillity fns for working with Prismatic's Graph and fnk"
(:require [plumbing.graph :as graph]
[schema.core :as s]))
(defn topo-sort
"Returns the topological sort of a Prismatic graph"
[g]
(-> g graph/->graph keys vec))
TODO : see if plumbing already has a fn for this ... or helper fns that seem less intrusive ..
(defn fnk-deps [fnk]
(->> fnk
s/fn-schema
ffirst
:schema
keys
(filter keyword?)))
TODO : see if plumbing 's ` comp - partial ` does what I need ( as suggested by )
(defn comp-fnk
"Composes the given given fnk with the provided fn. Only handles the binary case."
[f fnk]
(let [comped (-> (comp f fnk)
(with-meta (meta fnk)))]
(if [(-> fnk meta :plumbing.fnk.impl/positional-info)]
(vary-meta comped update-in [:plumbing.fnk.impl/positional-info 0] (partial comp f))
comped)))
|
7c7ddc753370f3957207ddcba34105fa114a745c9beef05a150ab8ef9994a471 | srid/ka | Listing.hs | # LANGUAGE RecursiveDo #
module Ka.Sidebar.Listing (render) where
import Control.Monad.Fix (MonadFix)
import Data.Tagged
import qualified Data.Text as T
import Ka.Graph (ThingName (..))
import qualified Ka.Plugin.Calendar as Calendar
import Ka.Route
import Reflex.Dom.Core
type SearchQuery = Tagged "SearchQuery" Text
mkSearchQuery :: Text -> Maybe SearchQuery
mkSearchQuery (T.strip -> s) =
if T.null s
then Nothing
else Just $ Tagged s
render ::
forall t m js.
( DomBuilder t m,
MonadHold t m,
PostBuild t m,
MonadFix m,
Prerender js t m
) =>
Dynamic t [ThingName] ->
m (Event t (R Route))
render xs = do
rec q <- searchInput $ () <$ routeChanged
let results = zipDynWith (filter . includeInListing) q xs
routeChanged <- renderListing results
pure routeChanged
searchInput ::
DomBuilder t m =>
-- | Clear the input field when this event fires
Event t () ->
m (Dynamic t (Maybe SearchQuery))
searchInput clearInput = do
divClass "item" $ do
divClass "ui input" $ do
fmap (fmap mkSearchQuery . value) $
inputElement $
def
& initialAttributes .~ ("placeholder" =: "Press / to search")
& inputElementConfig_setValue .~ ("" <$ clearInput)
renderListing ::
( DomBuilder t m,
MonadHold t m,
PostBuild t m,
MonadFix m,
Prerender js t m
) =>
Dynamic t [ThingName] ->
m (Event t (R Route))
renderListing res = do
fmap (switch . current . fmap leftmost) $
simpleList res $ \th -> do
let rDyn = (Route_Node :/) <$> th
dynRouteLink rDyn (constDyn $ "class" =: "gray active item") $ do
dyn_ $ renderRouteText <$> rDyn
-- | Include the given thing in the listing?
includeInListing :: Maybe SearchQuery -> ThingName -> Bool
includeInListing mq th =
case mq of
Nothing ->
-- If the user is not searching, we apply the default filters.
-- If they are currently searching, however, we don't apply them (allowing
-- them to search through the otherwise filtered out things.)
Calendar.includeInSidebar th
Just (untag -> q) ->
q `caseInsensitiveIsInfixOf` unThingName th
where
caseInsensitiveIsInfixOf p s =
T.toLower p `T.isInfixOf` T.toLower s | null | https://raw.githubusercontent.com/srid/ka/9d020738215a752d30674063384cdc6bf10c4067/src/Ka/Sidebar/Listing.hs | haskell | | Clear the input field when this event fires
| Include the given thing in the listing?
If the user is not searching, we apply the default filters.
If they are currently searching, however, we don't apply them (allowing
them to search through the otherwise filtered out things.) | # LANGUAGE RecursiveDo #
module Ka.Sidebar.Listing (render) where
import Control.Monad.Fix (MonadFix)
import Data.Tagged
import qualified Data.Text as T
import Ka.Graph (ThingName (..))
import qualified Ka.Plugin.Calendar as Calendar
import Ka.Route
import Reflex.Dom.Core
type SearchQuery = Tagged "SearchQuery" Text
mkSearchQuery :: Text -> Maybe SearchQuery
mkSearchQuery (T.strip -> s) =
if T.null s
then Nothing
else Just $ Tagged s
render ::
forall t m js.
( DomBuilder t m,
MonadHold t m,
PostBuild t m,
MonadFix m,
Prerender js t m
) =>
Dynamic t [ThingName] ->
m (Event t (R Route))
render xs = do
rec q <- searchInput $ () <$ routeChanged
let results = zipDynWith (filter . includeInListing) q xs
routeChanged <- renderListing results
pure routeChanged
searchInput ::
DomBuilder t m =>
Event t () ->
m (Dynamic t (Maybe SearchQuery))
searchInput clearInput = do
divClass "item" $ do
divClass "ui input" $ do
fmap (fmap mkSearchQuery . value) $
inputElement $
def
& initialAttributes .~ ("placeholder" =: "Press / to search")
& inputElementConfig_setValue .~ ("" <$ clearInput)
renderListing ::
( DomBuilder t m,
MonadHold t m,
PostBuild t m,
MonadFix m,
Prerender js t m
) =>
Dynamic t [ThingName] ->
m (Event t (R Route))
renderListing res = do
fmap (switch . current . fmap leftmost) $
simpleList res $ \th -> do
let rDyn = (Route_Node :/) <$> th
dynRouteLink rDyn (constDyn $ "class" =: "gray active item") $ do
dyn_ $ renderRouteText <$> rDyn
includeInListing :: Maybe SearchQuery -> ThingName -> Bool
includeInListing mq th =
case mq of
Nothing ->
Calendar.includeInSidebar th
Just (untag -> q) ->
q `caseInsensitiveIsInfixOf` unThingName th
where
caseInsensitiveIsInfixOf p s =
T.toLower p `T.isInfixOf` T.toLower s |
9b346fb383da8b75d171716a2dc2cefcba81aa3dac7d75f941d0a6346f651287 | W-Net-AI/LISP-CV | main.lisp | (defpackage "LISP-EXECUTABLE.EXAMPLE"
(:use "COMMON-LISP" "LISP-EXECUTABLE"))
(in-package "LISP-EXECUTABLE.EXAMPLE")
;;See <lisp-cv-src-dir>/macros.lisp for instructions
(define-program example-program (&options help)
(cv:with-captured-camera (cap 0 :width 640 :height 480)
help
(let* ((window-name "EXAMPLE-PROGRAM"))
(cv:with-named-window (window-name cv:+window-normal+)
(cv:move-window window-name 759 175)
(loop
(cv:with-mat ((frame (cv:mat)))
(cv:read cap frame)
(cv:imshow window-name frame)
(let ((c (cv:wait-key 33)))
(when (= c 27)
(return)))))))))
| null | https://raw.githubusercontent.com/W-Net-AI/LISP-CV/10d5c7c1a6fa026de488ca89a28e8a5c519ff8f2/extras/main.lisp | lisp | See <lisp-cv-src-dir>/macros.lisp for instructions | (defpackage "LISP-EXECUTABLE.EXAMPLE"
(:use "COMMON-LISP" "LISP-EXECUTABLE"))
(in-package "LISP-EXECUTABLE.EXAMPLE")
(define-program example-program (&options help)
(cv:with-captured-camera (cap 0 :width 640 :height 480)
help
(let* ((window-name "EXAMPLE-PROGRAM"))
(cv:with-named-window (window-name cv:+window-normal+)
(cv:move-window window-name 759 175)
(loop
(cv:with-mat ((frame (cv:mat)))
(cv:read cap frame)
(cv:imshow window-name frame)
(let ((c (cv:wait-key 33)))
(when (= c 27)
(return)))))))))
|
98945d2918d8dcb42b84f492609c9442e8d9598a3be6a58e62866604625616f1 | sheyll/b9-vm-image-builder | Actions.hs | | Convenient Shake ' Action 's for ' B9 ' rules .
module B9.Shake.Actions
( b9InvocationAction,
buildB9File,
)
where
import B9
import Control.Lens ((?~))
import Development.Shake
import GHC.Stack
-- | Convert a 'B9ConfigAction' action into a Shake 'Action'. This is just
-- an alias for 'runB9ConfigActionWithOverrides' since 'Action' is an instance of 'MonadIO'
-- and 'runB9ConfigActionWithOverrides' work on any .
b9InvocationAction :: HasCallStack => B9ConfigAction a -> B9ConfigOverride -> Action a
b9InvocationAction x y = liftIO (runB9ConfigActionWithOverrides x y)
-- | An action that does the equivalent of
@b9c build -f < b9file > -- ( args ! ! 0 ) ( args ! ! 1 ) ... ( args ! ! ( length args - 1))@
-- with the current working directory changed to @b9Root@.
-- The return value is the buildid, see 'getBuildId'
buildB9File :: HasCallStack => FilePath -> FilePath -> [String] -> Action String
buildB9File b9Root b9File args = do
let f = b9Root </> b9File
need [f]
liftIO
( runB9ConfigAction
( addLocalPositionalArguments
args
(localB9Config (projectRoot ?~ b9Root) (runBuildArtifacts [f]))
)
)
| null | https://raw.githubusercontent.com/sheyll/b9-vm-image-builder/4d2af80d3be4decfce6c137ee284c961e3f4a396/src/lib/B9/Shake/Actions.hs | haskell | | Convert a 'B9ConfigAction' action into a Shake 'Action'. This is just
an alias for 'runB9ConfigActionWithOverrides' since 'Action' is an instance of 'MonadIO'
and 'runB9ConfigActionWithOverrides' work on any .
| An action that does the equivalent of
( args ! ! 0 ) ( args ! ! 1 ) ... ( args ! ! ( length args - 1))@
with the current working directory changed to @b9Root@.
The return value is the buildid, see 'getBuildId' | | Convenient Shake ' Action 's for ' B9 ' rules .
module B9.Shake.Actions
( b9InvocationAction,
buildB9File,
)
where
import B9
import Control.Lens ((?~))
import Development.Shake
import GHC.Stack
b9InvocationAction :: HasCallStack => B9ConfigAction a -> B9ConfigOverride -> Action a
b9InvocationAction x y = liftIO (runB9ConfigActionWithOverrides x y)
buildB9File :: HasCallStack => FilePath -> FilePath -> [String] -> Action String
buildB9File b9Root b9File args = do
let f = b9Root </> b9File
need [f]
liftIO
( runB9ConfigAction
( addLocalPositionalArguments
args
(localB9Config (projectRoot ?~ b9Root) (runBuildArtifacts [f]))
)
)
|
e3cbf2b572c0584da5e20857cdc04c2fe875a66e51d2929c7e056e5481a942d3 | skeuchel/needle | WeakenRelation.hs | {-# LANGUAGE GADTs #-}
module KnotCore.Elaboration.Lemma.WeakenRelation where
import Coq.StdLib
import Coq.Syntax
import KnotCore.Syntax
import KnotCore.Elaboration.Core
import KnotCore.Elaboration.Eq
import Control.Applicative
import Control.Arrow
import Control.Monad ((>=>))
import Data.Maybe (catMaybes)
import Data.Traversable (for, traverse, sequenceA)
lemmas :: Elab m => [RelationGroupDecl] -> m [Sentence]
lemmas rgds = catMaybes <$> traverse eRelationDecl (concatMap rgRelations rgds)
eRelationDecl :: Elab m => RelationDecl -> m (Maybe Sentence)
eRelationDecl (RelationDecl Nothing _ _ _ _ _) = return Nothing
eRelationDecl (RelationDecl (Just ev) rtn fds _ _ _) = do
let etn = typeNameOf ev
evd <- freshEnvVariable etn
evg <- freshEnvVariable etn
fds' <- freshen fds
fs' <- eFieldDeclFields fds'
jmv <- freshJudgementVariable rtn
outFnEtns <- lookupRelationOutputs rtn
outFnEvs <- for outFnEtns $ \(fn,etn) -> (,) fn <$> freshEnvVariable etn
let jmt = Judgement rtn
(Just (SymEnvVar evg))
(map (fieldDeclToSymbolicField Nil) fds')
(map (second SymEnvVar) outFnEvs)
binders <-
sequenceA
(toBinder evg :
eFieldDeclBinders fds' ++
map (toBinder.snd) outFnEvs ++
[jvBinder jmv jmt]
)
nil <- getEnvCtorNil etn
conss <- getEnvCtorConss etn
nilEq <-
Equation
<$> (PatCtor <$> toQualId nil <*> pure [])
<*> (TermAbs binders <$> toRef jmv)
rec <-
TermApp
<$> (idLemmaWeakenRelation rtn >>= toRef)
<*> sequenceA
( toRef evd :
toRef evg :
eFieldDeclRefs fds' ++
map (toRef.snd) outFnEvs ++ [toRef jmv]
)
consEqs <- for conss $ \cons -> do
EnvCtorCons cn mv' fds'' _mbRtn <- freshen cons
fs'' <- eFieldDeclFields fds''
let ntn = typeNameOf mv'
Equation
<$> (PatCtor
<$> toQualId cn
<*> sequenceA (toId evd:eFieldDeclIdentifiers fds'')
)
<*> (TermAbs binders
<$> (TermApp
<$> (idLemmaShiftRelation etn (typeNameOf mv') rtn >>= toRef)
<*> sequenceA
( toTerm (EAppend (EVar evg) (EVar evd))
: map (\f ->
toTerm (weakenField
f
(HVDomainEnv (EVar evd)))) fs'
++ map (\(_fn,ev) -> toTerm (EWeaken (EVar ev) (HVDomainEnv (EVar evd)))) outFnEvs
++
[ pure rec
, toTerm (C0 (typeNameOf mv'))
, toTerm (ECons (EAppend (EVar evg) (EVar evd)) ntn fs'')
, idCtorInsertEnvHere cn >>= toRef
]
)
)
)
result <-
TermForall binders
<$> toTerm (PJudgement rtn
(JudgementEnvTerm (EAppend (EVar evg) (EVar evd)))
(map (\f -> weakenField f (HVDomainEnv (EVar evd))) fs')
(map (\(fn,ev) -> EWeaken (EVar ev) (HVDomainEnv (EVar evd))) outFnEvs)
)
body <- FixpointBody
<$> idLemmaWeakenRelation rtn
<*> sequenceA [toBinder evd]
<*> pure Nothing
<*> pure result
<*> (TermMatch
<$> (MatchItem
<$> toRef evd
<*> pure Nothing
<*> pure Nothing
)
<*> pure (Just result)
<*> pure (nilEq:consEqs)
)
return (Just (SentenceFixpoint (Fixpoint [body])))
| null | https://raw.githubusercontent.com/skeuchel/needle/25f46005d37571c1585805487a47950dcd588269/src/KnotCore/Elaboration/Lemma/WeakenRelation.hs | haskell | # LANGUAGE GADTs # |
module KnotCore.Elaboration.Lemma.WeakenRelation where
import Coq.StdLib
import Coq.Syntax
import KnotCore.Syntax
import KnotCore.Elaboration.Core
import KnotCore.Elaboration.Eq
import Control.Applicative
import Control.Arrow
import Control.Monad ((>=>))
import Data.Maybe (catMaybes)
import Data.Traversable (for, traverse, sequenceA)
lemmas :: Elab m => [RelationGroupDecl] -> m [Sentence]
lemmas rgds = catMaybes <$> traverse eRelationDecl (concatMap rgRelations rgds)
eRelationDecl :: Elab m => RelationDecl -> m (Maybe Sentence)
eRelationDecl (RelationDecl Nothing _ _ _ _ _) = return Nothing
eRelationDecl (RelationDecl (Just ev) rtn fds _ _ _) = do
let etn = typeNameOf ev
evd <- freshEnvVariable etn
evg <- freshEnvVariable etn
fds' <- freshen fds
fs' <- eFieldDeclFields fds'
jmv <- freshJudgementVariable rtn
outFnEtns <- lookupRelationOutputs rtn
outFnEvs <- for outFnEtns $ \(fn,etn) -> (,) fn <$> freshEnvVariable etn
let jmt = Judgement rtn
(Just (SymEnvVar evg))
(map (fieldDeclToSymbolicField Nil) fds')
(map (second SymEnvVar) outFnEvs)
binders <-
sequenceA
(toBinder evg :
eFieldDeclBinders fds' ++
map (toBinder.snd) outFnEvs ++
[jvBinder jmv jmt]
)
nil <- getEnvCtorNil etn
conss <- getEnvCtorConss etn
nilEq <-
Equation
<$> (PatCtor <$> toQualId nil <*> pure [])
<*> (TermAbs binders <$> toRef jmv)
rec <-
TermApp
<$> (idLemmaWeakenRelation rtn >>= toRef)
<*> sequenceA
( toRef evd :
toRef evg :
eFieldDeclRefs fds' ++
map (toRef.snd) outFnEvs ++ [toRef jmv]
)
consEqs <- for conss $ \cons -> do
EnvCtorCons cn mv' fds'' _mbRtn <- freshen cons
fs'' <- eFieldDeclFields fds''
let ntn = typeNameOf mv'
Equation
<$> (PatCtor
<$> toQualId cn
<*> sequenceA (toId evd:eFieldDeclIdentifiers fds'')
)
<*> (TermAbs binders
<$> (TermApp
<$> (idLemmaShiftRelation etn (typeNameOf mv') rtn >>= toRef)
<*> sequenceA
( toTerm (EAppend (EVar evg) (EVar evd))
: map (\f ->
toTerm (weakenField
f
(HVDomainEnv (EVar evd)))) fs'
++ map (\(_fn,ev) -> toTerm (EWeaken (EVar ev) (HVDomainEnv (EVar evd)))) outFnEvs
++
[ pure rec
, toTerm (C0 (typeNameOf mv'))
, toTerm (ECons (EAppend (EVar evg) (EVar evd)) ntn fs'')
, idCtorInsertEnvHere cn >>= toRef
]
)
)
)
result <-
TermForall binders
<$> toTerm (PJudgement rtn
(JudgementEnvTerm (EAppend (EVar evg) (EVar evd)))
(map (\f -> weakenField f (HVDomainEnv (EVar evd))) fs')
(map (\(fn,ev) -> EWeaken (EVar ev) (HVDomainEnv (EVar evd))) outFnEvs)
)
body <- FixpointBody
<$> idLemmaWeakenRelation rtn
<*> sequenceA [toBinder evd]
<*> pure Nothing
<*> pure result
<*> (TermMatch
<$> (MatchItem
<$> toRef evd
<*> pure Nothing
<*> pure Nothing
)
<*> pure (Just result)
<*> pure (nilEq:consEqs)
)
return (Just (SentenceFixpoint (Fixpoint [body])))
|
805bcb0a5d39c93c5eec5aedf2326820630511fc02579d2ae2c723f39c8f27e2 | froggey/Mezzano | dispatch.lisp | ;;;; libdispatch inspired concurrency API.
(defpackage :mezzano.sync.dispatch
(:use :cl)
(:local-nicknames (:sup :mezzano.supervisor)
(:pool :mezzano.sync.thread-pool)
(:sync :mezzano.sync)
(:clos :mezzano.clos))
(:export #:context
#:local-context
#:make-dispatch-context
#:dispatch-shutdown
Generic dispatch objects
#:dispatch-object
#:resume
#:suspend
#:cancel
#:canceled-p
#:wait
#:notify
Queues
#:queue
#:serial-queue
#:concurrent-queue
#:manager-queue
#:global-queue
#:standard-queue
#:standard-serial-queue
#:standard-concurrent-queue
#:make-queue
#:dispatch-async
#:dispatch-sync
#:dispatch-multiple
#:dispatch-after
#:dispatch-delayed
;; Sources
#:source
#:make-source
#:source-target
#:source-event
#:source-handler
#:source-cancellation-handler
Groups
#:group
#:make-group
#:group-enter
#:group-leave
))
(in-package :mezzano.sync.dispatch)
;;; A context owns a set of queues, sources, threads, etc.
(defclass context ()
((%name :reader context-name :initarg :name)
(%thread-pool :reader context-thread-pool)
(%manager-thread :reader context-manager-thread)
(%manager-mailbox :reader context-manager-mailbox)
(%manager-queue :reader context-manager-queue)
(%manager-events :initform '() :accessor context-manager-events)
(%global-queue :reader context-global-queue))
(:default-initargs :name nil))
(defmethod print-object ((instance context) stream)
(print-unreadable-object (instance stream :type t :identity t)
(format stream "~A" (context-name instance))))
(defvar *local-context* nil)
(defun local-context ()
*local-context*)
(defun manager ()
(let* ((context *local-context*)
(mailbox (context-manager-mailbox context)))
(with-simple-restart (abort "Terminate manager thread for context ~S" context)
(loop
(dolist (evt (apply #'sync:wait-for-objects mailbox (context-manager-events context)))
(cond ((eql evt mailbox)
;; Process pending functions.
(loop
(multiple-value-bind (value validp)
(sync:mailbox-receive mailbox :wait-p nil)
(when (not validp)
(return))
(with-simple-restart (continue "Ignore manager work ~S" value)
(funcall value)))))
(t
(with-simple-restart (continue "Ignore source event ~S" evt)
(process-source evt)))))))))
(defmethod initialize-instance :after ((instance context) &key initial-bindings)
(push (list '*local-context* instance) initial-bindings)
(setf (slot-value instance '%thread-pool)
(pool:make-thread-pool :name instance
:initial-bindings initial-bindings))
(setf (slot-value instance '%manager-mailbox)
(sync:make-mailbox :name `(manager-mailbox ,instance)))
(setf (slot-value instance '%manager-thread)
(sup:make-thread #'manager
:name `(manager ,instance)
:initial-bindings initial-bindings))
(setf (slot-value instance '%manager-queue)
(make-instance 'manager-queue :context instance))
(setf (slot-value instance '%global-queue)
(make-instance 'global-queue :context instance)))
(defun make-dispatch-context (&key initial-bindings initial-work name)
"Create a new dispatch context.
INITIAL-BINDINGS is a list of (symbol value) pairs which specifies the initial
values of the given symbols. Modifications to these bindings may or may not
persist between task invocations.
INITIAL-WORK will be submitted to the manager queue immediately on context
creation and can be used to perform initial setup."
(let ((ctx (make-instance 'context
:initial-bindings initial-bindings
:name name)))
(when initial-work
(dispatch-async initial-work (manager-queue :context ctx)))
ctx))
(defun dispatch-shutdown (&key (context *local-context*) abort)
"Shut down CONTEXT.
Shuts down the thread pool and terminates the manager thread.
If ABORT is true then threads will be terminated immediately, else it
will wait for the currently running tasks to complete."
(pool:thread-pool-shutdown (context-thread-pool context) :abort abort)
(cond (abort
(sup:terminate-thread (context-manager-thread context)))
(t
(dispatch-async (lambda () (throw 'sup:terminate-thread nil))
(manager-queue :context context))))
(values))
Generic dispatch - related objects .
(defgeneric context (object)
(:documentation "Return the dispatch context in which OBJECT exists."))
(defgeneric resume (object)
(:documentation "Resumes the invocation of blocks on a dispatch object."))
(defgeneric suspend (object)
(:documentation "Suspends the invocation of blocks on a dispatch object."))
(defgeneric cancel (object)
(:documentation "Asynchronously cancel the specifed object."))
(defgeneric canceled-p (object)
(:documentation "Test whether the specified object has been canceled."))
(defgeneric wait (object &key timeout)
(:documentation "Wait synchronously for an object or until the specified timeout has elapsed."))
(defgeneric notify (object function &key target)
(:documentation "Schedule a notification function to be submitted to a queue when the execution of a specified object has completed."))
(defclass dispatch-object ()
((%context :initarg :context :reader context))
(:documentation "Base class of all dispatch objects associated with a context."))
Queues
(defclass queue (dispatch-object)
()
(:documentation "Base class of all queues.
Queues must implement DISPATCH-ASYNC."))
(defclass serial-queue (queue) ()
(:documentation "An abstract queue type that dispatches tasks one by one."))
(defclass concurrent-queue (queue) ()
(:documentation "An abstract queue type that dispatches tasks in parallel."))
(defclass manager-queue (serial-queue) ()
(:documentation "A queue type that dispatches events serially on the context's manager thread."))
(defclass global-queue (concurrent-queue) ()
(:documentation "A queue type that dispatches events concurrently using the context's thread pool."))
(defclass standard-queue (queue)
((%name :initarg :name :reader standard-queue-name)
(%target :initarg :target :reader standard-queue-target)
(%active :initarg :active :accessor standard-queue-active-p)
(%lock :reader queue-lock)))
(defmethod initialize-instance :after ((instance standard-queue) &key)
(setf (slot-value instance '%lock) (sup:make-mutex instance)))
(defclass standard-serial-queue (standard-queue serial-queue)
((%queue-running :initform nil :accessor queue-running-p)
(%pending :initform '() :accessor queue-pending)))
(defclass standard-concurrent-queue (standard-queue concurrent-queue)
((%queue-work-count :initform 0 :accessor queue-work-count)
(%pending :initform '() :accessor queue-pending)
(%barriered :initform nil :accessor queue-barriered)))
(defun global-queue (&key context priority)
"Return the global queue for CONTEXT for the specified PRIORITY.
CONTEXT defaults to the local context."
(declare (ignore priority))
(context-global-queue (or context *local-context*)))
(defun manager-queue (&key context)
"Return the manager queue for CONTEXT
CONTEXT defaults to the local context."
(context-manager-queue (or context *local-context*)))
(defgeneric dispatch-async (function queue &key barrier group)
(:documentation "Submits a function for asynchronous execution on a dispatch queue.
If BARRIER is supplied, then all prior functions will be executed before the function
is executed and functions added after will be deferred until the barrier function completes.
GROUP specifies a group to associate this function with."))
(defmethod dispatch-async (function (queue manager-queue) &key barrier group)
(declare (ignore barrier))
(sync:mailbox-send (group-wrap function group)
(context-manager-mailbox (context queue)))
(values))
(defmethod dispatch-async (function (queue global-queue) &key barrier group)
(when barrier
(error "Barrier not supported on global queues."))
(pool:thread-pool-add (group-wrap function group)
(context-thread-pool (context queue)))
(values))
(defun make-queue (&key name target context concurrent priority suspended)
"Create a new standard queue.
The queue will dispatch tasks using the TARGET queue or CONTEXT's global
queue for supplied priority.
If SUSPENDED is true then the queue will initially be suspended and
RESUME must be called before tasks are executed."
(when (and target (not context))
(setf context (context target)))
(when target
(assert (not priority) (priority) "Can't specify priority and target queue"))
(when (not target)
(setf target (global-queue :context (or context *local-context*)
:priority priority)))
(when (and (typep target 'serial-queue)
concurrent)
(error "Cannot target a concurrent queue on to serial queue ~S" target))
(when context
(assert (eql context (context target))))
(make-instance (if concurrent
'standard-concurrent-queue
'standard-serial-queue)
:name name
:target target
:context (context target)
:active (not suspended)))
(defun serial-queue-runner (queue)
(loop
(let ((current (sup:with-mutex ((queue-lock queue))
(when (or (not (standard-queue-active-p queue))
(endp (queue-pending queue)))
(setf (queue-running-p queue) nil)
(return-from serial-queue-runner))
(pop (queue-pending queue)))))
(funcall current))))
(defmethod dispatch-async (function (queue standard-serial-queue) &key barrier group)
(declare (ignore barrier))
(sup:with-mutex ((queue-lock queue))
(when (and (standard-queue-active-p queue)
(not (queue-running-p queue)))
(setf (queue-running-p queue) t)
(dispatch-async (lambda () (serial-queue-runner queue))
(standard-queue-target queue)))
(setf (queue-pending queue) (append (queue-pending queue)
(list (group-wrap function group)))))
(values))
(defmethod resume ((queue standard-serial-queue))
(sup:with-mutex ((queue-lock queue))
(when (not (standard-queue-active-p queue))
(setf (standard-queue-active-p queue) t)
(when (and (not (queue-running-p queue))
(queue-pending queue))
;; There is work pending but no active runner. (Re)start it.
(setf (queue-running-p queue) t)
(dispatch-async (lambda () (serial-queue-runner queue))
(standard-queue-target queue)))))
(values))
(defmethod suspend ((queue standard-serial-queue))
(sup:with-mutex ((queue-lock queue))
(setf (standard-queue-active-p queue) nil))
(values))
(defclass barrier-work ()
((%function :initarg :function :reader barrier-work-function)))
(defun run-concurrent-fn (queue function)
(unwind-protect
(funcall function)
(sup:with-mutex ((queue-lock queue))
(decf (queue-work-count queue))
(when (and (standard-queue-active-p queue)
(zerop (queue-work-count queue))
(queue-pending queue))
;; There's pending work, this should be a barrier function.
(let ((fn (pop (queue-pending queue))))
(assert (typep fn 'barrier-work))
(setf fn (barrier-work-function fn))
(incf (queue-work-count queue))
(setf (queue-barriered queue) t)
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue)))))))
(defun run-concurrent-barrier-fn (queue function)
(unwind-protect
(funcall function)
(sup:with-mutex ((queue-lock queue))
(decf (queue-work-count queue))
(assert (queue-barriered queue))
(assert (zerop (queue-work-count queue)))
(setf (queue-barriered queue) nil)
(when (and (standard-queue-active-p queue)
(queue-pending queue))
(cond ((typep (first (queue-pending queue)) 'barrier-work)
If the first function is a barrier function , then just run that .
(let ((fn (barrier-work-function (pop (queue-pending queue)))))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue))))
(t
;; Otherwise, dispatch all pending work units until a
;; barrier or end-of-list is seen.
(loop
(when (or (endp (queue-pending queue))
(typep (first (queue-pending queue)) 'barrier-work))
(return))
(let ((fn (pop (queue-pending queue))))
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-fn queue fn))
(standard-queue-target queue))))))))))
(defmethod dispatch-async (function (queue standard-concurrent-queue) &key barrier group)
(setf function (group-wrap function group))
(sup:with-mutex ((queue-lock queue))
(cond ((identity barrier)
(cond ((and (standard-queue-active-p queue)
(zerop (queue-work-count queue)))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue function))
(standard-queue-target queue)))
(t
;; Outstanding work or inactive queue, just add to the
;; pending list. It'll be picked up when work finishes.
(let ((barrier-fn (make-instance 'barrier-work
:function function)))
(setf (queue-pending queue) (append (queue-pending queue)
(list barrier-fn)))))))
((or (not (standard-queue-active-p queue))
(queue-pending queue)
(queue-barriered queue))
(setf (queue-pending queue) (append (queue-pending queue)
(list function))))
(t
(incf (queue-work-count queue))
(dispatch-async (lambda () (run-concurrent-fn queue function))
(standard-queue-target queue)))))
(values))
(defmethod resume ((queue standard-concurrent-queue))
(sup:with-mutex ((queue-lock queue))
(when (not (standard-queue-active-p queue))
(setf (standard-queue-active-p queue) t)
(when (and (zerop (queue-work-count queue))
(queue-pending queue))
;; There is work pending but no active runners.
(cond ((typep (first (queue-pending queue)) 'barrier-work)
If the first function is a barrier function , then just run that .
(let ((fn (barrier-work-function (pop (queue-pending queue)))))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue))))
(t
;; Otherwise, dispatch all pending work units until a
;; barrier or end-of-list is seen.
(loop
(when (or (endp (queue-pending queue))
(typep (first (queue-pending queue)) 'barrier-work))
(return))
(let ((fn (pop (queue-pending queue))))
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-fn queue fn))
(standard-queue-target queue)))))))))
(values))
(defmethod suspend ((queue standard-concurrent-queue))
(sup:with-mutex ((queue-lock queue))
(setf (standard-queue-active-p queue) nil))
(values))
(defun dispatch-sync (function queue &key barrier)
"Dispatch FUNCTION on QUEUE and wait for completion."
(let ((group (make-group :context (context queue))))
(dispatch-async function queue :group group :barrier barrier)
(wait group))
(values))
(defun dispatch-multiple (function iterations queue &key group)
"Dispatch FUNCTION on QUEUE multiple times. The function is called with the iteration number."
(dotimes (i iterations)
(let ((n i))
(dispatch-async (lambda () (funcall function n))
queue
:group group)))
(values))
(defun dispatch-after (function run-time queue)
"Submits a function for asynchronous execution on a dispatch queue after the specified time."
(let* ((timer (mezzano.supervisor:make-timer :deadline run-time))
(source (make-source timer nil
:cancellation-handler (lambda ()
;; Return the timer to the pool after the source
;; is fully canceled.
(mezzano.supervisor::push-timer-pool timer))
:suspended t)))
(setf (source-handler source) (lambda ()
(dispatch-async function queue)
;; Disarm the timer to prevent the source
;; from immediately refiring (suspend is async).
(mezzano.supervisor:timer-disarm timer)
;; Cancel the source to stop it hanging around.
(cancel source)))
(resume source))
(values))
(defun delay-to-run-time (delay)
"Convert a delay (a non-negative real representing seconds) to an absolute run time."
(+ (get-internal-run-time)
(truncate (* delay internal-time-units-per-second))))
(defun dispatch-delayed (function delay queue)
"Submits a function for asynchronous execution on a dispatch queue after the specified delay."
(dispatch-at function (delay-to-run-time delay) queue)
(values))
;;; Sources
;; Implementation detail:
;; Sources are operated on entirely from the manager thread,
;; this avoids the need for any locking or other kinds of
;; synchronization.
(defclass source (dispatch-object)
((%target :initarg :target :reader source-target)
(%event :initarg :event :reader source-event)
(%handler :initarg :handler :reader source-handler)
(%cancellation-handler :initarg :cancellation-handler
:reader source-cancellation-handler)
(%state :initform :suspended :accessor source-state))
(:documentation "A source connects an event to a dispatch context."))
(defmethod print-object ((instance source) stream)
(print-unreadable-object (instance stream :type t :identity t)
(format stream "~A targeting ~S" (source-event instance) (source-target instance))))
(defmethod sync:get-object-event ((object source))
(sync:get-object-event (source-event object)))
(defun make-source (event handler &key target cancellation-handler suspended)
"Create a new source object connected to EVENT.
HANDLER is the function to be called when EVENT becomes active. It
can initially be NIL but must be set via (SETF SOURCE-HANDLER) before
the source is initially activated.
TARGET is the queue that the handlers are to be dispatched on. It defaults
to the global queue for the current context.
CANCELLATION-HANDLER is a function that will be dispatched when CANCEL completes
and the source has been fully unregistered.
SUSPENDED specifies if the source should start in a suspeneded state or
if it should immediately begin dispatching events."
(assert (or handler suspended) (handler suspended) "The queue must start in a suspended state if no handler is supplied.")
(let* ((target (or target (global-queue)))
(context (context target))
(source (make-instance 'source
:event event
:context context
:target target
:handler handler
:cancellation-handler cancellation-handler)))
(when (not suspended)
(resume source))
source))
(defun %set-source-handler (value source)
(assert (eql (source-state source) :suspended))
(setf (slot-value source '%handler) value))
(defun (setf source-handler) (value source)
(check-type value (or function null))
(dispatch-async (lambda () (%set-source-handler value source))
(manager-queue :context (context source)))
value)
(defun %resume-source (source)
(ecase (source-state source)
(:suspended
(assert (source-handler source))
(setf (source-state source) :active)
(push source (context-manager-events *local-context*)))
(:event-running-suspend-requested
(setf (source-state source) :event-running))
(:event-running)
(:active)
((:canceled :event-running-cancel-requested)
(error "Cannot resume a canceled source ~S" source))))
(defmethod resume ((source source))
(dispatch-async (lambda () (%resume-source source))
(manager-queue :context (context source)))
(values))
(defun %suspend-source (source)
(ecase (source-state source)
((:suspended :canceled))
((:event-running-suspend-requested :event-running-cancel-requested))
(:event-running
(setf (source-state source) :event-running-suspend-requested))
(:active
(setf (source-state source) :suspended)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*))))))
(defmethod suspend ((source source))
(dispatch-async (lambda () (%suspend-source source))
(manager-queue :context (context source)))
(values))
(defun process-source (source)
;; can't be in either of the event-running states.
(ecase (source-state source)
(:suspended :canceled) ; possible if the source was suspended at the same time that it was triggered
(:active
(setf (source-state source) :event-running)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*)))
(dispatch-async (lambda ()
(unwind-protect
(funcall (source-handler source))
(dispatch-async (lambda () (complete-source source))
(manager-queue :context (context source)))))
(source-target source)))))
(defun complete-source (source)
(ecase (source-state source)
(:event-running-cancel-requested
(setf (source-state source) :canceled)
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))
(:event-running-suspend-requested
(setf (source-state source) :suspended))
(:event-running
(setf (source-state source) :active)
(push source (context-manager-events *local-context*)))))
(defun %cancel-source (source)
(ecase (source-state source)
((:canceled :event-running-cancel-requested))
(:suspended
(setf (source-state source) :canceled)
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))
((:event-running-suspend-requested :event-running)
(setf (source-state source) :event-running-cancel-requested))
(:active
(setf (source-state source) :canceled)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*)))
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))))
(defmethod cancel ((source source))
(dispatch-async (lambda () (%cancel-source source))
(manager-queue :context (context source)))
(values))
(defmethod canceled-p ((source source))
(eql (source-state source) :canceled))
Groups
(defclass group (dispatch-object)
((%count :initform 0 :accessor group-count)
(%pending :initform '() :accessor group-notifiers)
(%lock :reader group-lock)
(%cvar :reader group-cvar)))
(defmethod initialize-instance :after ((instance group) &key)
(setf (slot-value instance '%lock) (sup:make-mutex instance)
(slot-value instance '%cvar) (sup:make-condition-variable instance)))
(defun make-group (&key (context *local-context*))
"Create a new group.
Groups can be used to determine when a collections of work items
have all been completed."
(make-instance 'group :context context))
(defmethod wait ((group group) &key timeout)
(sup:with-mutex ((group-lock group))
(sup:condition-wait-for ((group-cvar group) (group-lock group) timeout)
(zerop (group-count group)))))
(defmethod notify (function (group group) &key target)
(setf target (or target (global-queue :context (context group))))
(sup:with-mutex ((group-lock group))
(if (zerop (group-count group))
(dispatch-async function target)
(push (list function target) (group-notifiers group))))
(values))
(defun group-enter (group)
"Manually enter a group, incrementing the internal counter."
(sup:with-mutex ((group-lock group))
(incf (group-count group)))
(values))
(defun group-leave (group)
"Manually leave a group, decrementing the internal counter.
When the group's internal counter reaches zero all pending
notifications will be dispatched."
(sup:with-mutex ((group-lock group))
(decf (group-count group))
(when (zerop (group-count group))
(sup:condition-notify (group-cvar group) t)
(loop
for (function target) in (group-notifiers group)
do (dispatch-async function target))
(setf (group-notifiers group) '())))
(values))
(defun group-wrap (function group)
(cond (group
(group-enter group)
(lambda ()
(unwind-protect
(funcall function)
(group-leave group))))
(t
function)))
| null | https://raw.githubusercontent.com/froggey/Mezzano/e9c4e426ae9732daa45cd7fd0f812a627b79dea6/system/dispatch.lisp | lisp | libdispatch inspired concurrency API.
Sources
A context owns a set of queues, sources, threads, etc.
Process pending functions.
There is work pending but no active runner. (Re)start it.
There's pending work, this should be a barrier function.
Otherwise, dispatch all pending work units until a
barrier or end-of-list is seen.
Outstanding work or inactive queue, just add to the
pending list. It'll be picked up when work finishes.
There is work pending but no active runners.
Otherwise, dispatch all pending work units until a
barrier or end-of-list is seen.
Return the timer to the pool after the source
is fully canceled.
Disarm the timer to prevent the source
from immediately refiring (suspend is async).
Cancel the source to stop it hanging around.
Sources
Implementation detail:
Sources are operated on entirely from the manager thread,
this avoids the need for any locking or other kinds of
synchronization.
can't be in either of the event-running states.
possible if the source was suspended at the same time that it was triggered |
(defpackage :mezzano.sync.dispatch
(:use :cl)
(:local-nicknames (:sup :mezzano.supervisor)
(:pool :mezzano.sync.thread-pool)
(:sync :mezzano.sync)
(:clos :mezzano.clos))
(:export #:context
#:local-context
#:make-dispatch-context
#:dispatch-shutdown
Generic dispatch objects
#:dispatch-object
#:resume
#:suspend
#:cancel
#:canceled-p
#:wait
#:notify
Queues
#:queue
#:serial-queue
#:concurrent-queue
#:manager-queue
#:global-queue
#:standard-queue
#:standard-serial-queue
#:standard-concurrent-queue
#:make-queue
#:dispatch-async
#:dispatch-sync
#:dispatch-multiple
#:dispatch-after
#:dispatch-delayed
#:source
#:make-source
#:source-target
#:source-event
#:source-handler
#:source-cancellation-handler
Groups
#:group
#:make-group
#:group-enter
#:group-leave
))
(in-package :mezzano.sync.dispatch)
(defclass context ()
((%name :reader context-name :initarg :name)
(%thread-pool :reader context-thread-pool)
(%manager-thread :reader context-manager-thread)
(%manager-mailbox :reader context-manager-mailbox)
(%manager-queue :reader context-manager-queue)
(%manager-events :initform '() :accessor context-manager-events)
(%global-queue :reader context-global-queue))
(:default-initargs :name nil))
(defmethod print-object ((instance context) stream)
(print-unreadable-object (instance stream :type t :identity t)
(format stream "~A" (context-name instance))))
(defvar *local-context* nil)
(defun local-context ()
*local-context*)
(defun manager ()
(let* ((context *local-context*)
(mailbox (context-manager-mailbox context)))
(with-simple-restart (abort "Terminate manager thread for context ~S" context)
(loop
(dolist (evt (apply #'sync:wait-for-objects mailbox (context-manager-events context)))
(cond ((eql evt mailbox)
(loop
(multiple-value-bind (value validp)
(sync:mailbox-receive mailbox :wait-p nil)
(when (not validp)
(return))
(with-simple-restart (continue "Ignore manager work ~S" value)
(funcall value)))))
(t
(with-simple-restart (continue "Ignore source event ~S" evt)
(process-source evt)))))))))
(defmethod initialize-instance :after ((instance context) &key initial-bindings)
(push (list '*local-context* instance) initial-bindings)
(setf (slot-value instance '%thread-pool)
(pool:make-thread-pool :name instance
:initial-bindings initial-bindings))
(setf (slot-value instance '%manager-mailbox)
(sync:make-mailbox :name `(manager-mailbox ,instance)))
(setf (slot-value instance '%manager-thread)
(sup:make-thread #'manager
:name `(manager ,instance)
:initial-bindings initial-bindings))
(setf (slot-value instance '%manager-queue)
(make-instance 'manager-queue :context instance))
(setf (slot-value instance '%global-queue)
(make-instance 'global-queue :context instance)))
(defun make-dispatch-context (&key initial-bindings initial-work name)
"Create a new dispatch context.
INITIAL-BINDINGS is a list of (symbol value) pairs which specifies the initial
values of the given symbols. Modifications to these bindings may or may not
persist between task invocations.
INITIAL-WORK will be submitted to the manager queue immediately on context
creation and can be used to perform initial setup."
(let ((ctx (make-instance 'context
:initial-bindings initial-bindings
:name name)))
(when initial-work
(dispatch-async initial-work (manager-queue :context ctx)))
ctx))
(defun dispatch-shutdown (&key (context *local-context*) abort)
"Shut down CONTEXT.
Shuts down the thread pool and terminates the manager thread.
If ABORT is true then threads will be terminated immediately, else it
will wait for the currently running tasks to complete."
(pool:thread-pool-shutdown (context-thread-pool context) :abort abort)
(cond (abort
(sup:terminate-thread (context-manager-thread context)))
(t
(dispatch-async (lambda () (throw 'sup:terminate-thread nil))
(manager-queue :context context))))
(values))
Generic dispatch - related objects .
(defgeneric context (object)
(:documentation "Return the dispatch context in which OBJECT exists."))
(defgeneric resume (object)
(:documentation "Resumes the invocation of blocks on a dispatch object."))
(defgeneric suspend (object)
(:documentation "Suspends the invocation of blocks on a dispatch object."))
(defgeneric cancel (object)
(:documentation "Asynchronously cancel the specifed object."))
(defgeneric canceled-p (object)
(:documentation "Test whether the specified object has been canceled."))
(defgeneric wait (object &key timeout)
(:documentation "Wait synchronously for an object or until the specified timeout has elapsed."))
(defgeneric notify (object function &key target)
(:documentation "Schedule a notification function to be submitted to a queue when the execution of a specified object has completed."))
(defclass dispatch-object ()
((%context :initarg :context :reader context))
(:documentation "Base class of all dispatch objects associated with a context."))
Queues
(defclass queue (dispatch-object)
()
(:documentation "Base class of all queues.
Queues must implement DISPATCH-ASYNC."))
(defclass serial-queue (queue) ()
(:documentation "An abstract queue type that dispatches tasks one by one."))
(defclass concurrent-queue (queue) ()
(:documentation "An abstract queue type that dispatches tasks in parallel."))
(defclass manager-queue (serial-queue) ()
(:documentation "A queue type that dispatches events serially on the context's manager thread."))
(defclass global-queue (concurrent-queue) ()
(:documentation "A queue type that dispatches events concurrently using the context's thread pool."))
(defclass standard-queue (queue)
((%name :initarg :name :reader standard-queue-name)
(%target :initarg :target :reader standard-queue-target)
(%active :initarg :active :accessor standard-queue-active-p)
(%lock :reader queue-lock)))
(defmethod initialize-instance :after ((instance standard-queue) &key)
(setf (slot-value instance '%lock) (sup:make-mutex instance)))
(defclass standard-serial-queue (standard-queue serial-queue)
((%queue-running :initform nil :accessor queue-running-p)
(%pending :initform '() :accessor queue-pending)))
(defclass standard-concurrent-queue (standard-queue concurrent-queue)
((%queue-work-count :initform 0 :accessor queue-work-count)
(%pending :initform '() :accessor queue-pending)
(%barriered :initform nil :accessor queue-barriered)))
(defun global-queue (&key context priority)
"Return the global queue for CONTEXT for the specified PRIORITY.
CONTEXT defaults to the local context."
(declare (ignore priority))
(context-global-queue (or context *local-context*)))
(defun manager-queue (&key context)
"Return the manager queue for CONTEXT
CONTEXT defaults to the local context."
(context-manager-queue (or context *local-context*)))
(defgeneric dispatch-async (function queue &key barrier group)
(:documentation "Submits a function for asynchronous execution on a dispatch queue.
If BARRIER is supplied, then all prior functions will be executed before the function
is executed and functions added after will be deferred until the barrier function completes.
GROUP specifies a group to associate this function with."))
(defmethod dispatch-async (function (queue manager-queue) &key barrier group)
(declare (ignore barrier))
(sync:mailbox-send (group-wrap function group)
(context-manager-mailbox (context queue)))
(values))
(defmethod dispatch-async (function (queue global-queue) &key barrier group)
(when barrier
(error "Barrier not supported on global queues."))
(pool:thread-pool-add (group-wrap function group)
(context-thread-pool (context queue)))
(values))
(defun make-queue (&key name target context concurrent priority suspended)
"Create a new standard queue.
The queue will dispatch tasks using the TARGET queue or CONTEXT's global
queue for supplied priority.
If SUSPENDED is true then the queue will initially be suspended and
RESUME must be called before tasks are executed."
(when (and target (not context))
(setf context (context target)))
(when target
(assert (not priority) (priority) "Can't specify priority and target queue"))
(when (not target)
(setf target (global-queue :context (or context *local-context*)
:priority priority)))
(when (and (typep target 'serial-queue)
concurrent)
(error "Cannot target a concurrent queue on to serial queue ~S" target))
(when context
(assert (eql context (context target))))
(make-instance (if concurrent
'standard-concurrent-queue
'standard-serial-queue)
:name name
:target target
:context (context target)
:active (not suspended)))
(defun serial-queue-runner (queue)
(loop
(let ((current (sup:with-mutex ((queue-lock queue))
(when (or (not (standard-queue-active-p queue))
(endp (queue-pending queue)))
(setf (queue-running-p queue) nil)
(return-from serial-queue-runner))
(pop (queue-pending queue)))))
(funcall current))))
(defmethod dispatch-async (function (queue standard-serial-queue) &key barrier group)
(declare (ignore barrier))
(sup:with-mutex ((queue-lock queue))
(when (and (standard-queue-active-p queue)
(not (queue-running-p queue)))
(setf (queue-running-p queue) t)
(dispatch-async (lambda () (serial-queue-runner queue))
(standard-queue-target queue)))
(setf (queue-pending queue) (append (queue-pending queue)
(list (group-wrap function group)))))
(values))
(defmethod resume ((queue standard-serial-queue))
(sup:with-mutex ((queue-lock queue))
(when (not (standard-queue-active-p queue))
(setf (standard-queue-active-p queue) t)
(when (and (not (queue-running-p queue))
(queue-pending queue))
(setf (queue-running-p queue) t)
(dispatch-async (lambda () (serial-queue-runner queue))
(standard-queue-target queue)))))
(values))
(defmethod suspend ((queue standard-serial-queue))
(sup:with-mutex ((queue-lock queue))
(setf (standard-queue-active-p queue) nil))
(values))
(defclass barrier-work ()
((%function :initarg :function :reader barrier-work-function)))
(defun run-concurrent-fn (queue function)
(unwind-protect
(funcall function)
(sup:with-mutex ((queue-lock queue))
(decf (queue-work-count queue))
(when (and (standard-queue-active-p queue)
(zerop (queue-work-count queue))
(queue-pending queue))
(let ((fn (pop (queue-pending queue))))
(assert (typep fn 'barrier-work))
(setf fn (barrier-work-function fn))
(incf (queue-work-count queue))
(setf (queue-barriered queue) t)
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue)))))))
(defun run-concurrent-barrier-fn (queue function)
(unwind-protect
(funcall function)
(sup:with-mutex ((queue-lock queue))
(decf (queue-work-count queue))
(assert (queue-barriered queue))
(assert (zerop (queue-work-count queue)))
(setf (queue-barriered queue) nil)
(when (and (standard-queue-active-p queue)
(queue-pending queue))
(cond ((typep (first (queue-pending queue)) 'barrier-work)
If the first function is a barrier function , then just run that .
(let ((fn (barrier-work-function (pop (queue-pending queue)))))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue))))
(t
(loop
(when (or (endp (queue-pending queue))
(typep (first (queue-pending queue)) 'barrier-work))
(return))
(let ((fn (pop (queue-pending queue))))
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-fn queue fn))
(standard-queue-target queue))))))))))
(defmethod dispatch-async (function (queue standard-concurrent-queue) &key barrier group)
(setf function (group-wrap function group))
(sup:with-mutex ((queue-lock queue))
(cond ((identity barrier)
(cond ((and (standard-queue-active-p queue)
(zerop (queue-work-count queue)))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue function))
(standard-queue-target queue)))
(t
(let ((barrier-fn (make-instance 'barrier-work
:function function)))
(setf (queue-pending queue) (append (queue-pending queue)
(list barrier-fn)))))))
((or (not (standard-queue-active-p queue))
(queue-pending queue)
(queue-barriered queue))
(setf (queue-pending queue) (append (queue-pending queue)
(list function))))
(t
(incf (queue-work-count queue))
(dispatch-async (lambda () (run-concurrent-fn queue function))
(standard-queue-target queue)))))
(values))
(defmethod resume ((queue standard-concurrent-queue))
(sup:with-mutex ((queue-lock queue))
(when (not (standard-queue-active-p queue))
(setf (standard-queue-active-p queue) t)
(when (and (zerop (queue-work-count queue))
(queue-pending queue))
(cond ((typep (first (queue-pending queue)) 'barrier-work)
If the first function is a barrier function , then just run that .
(let ((fn (barrier-work-function (pop (queue-pending queue)))))
(setf (queue-barriered queue) t)
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-barrier-fn queue fn))
(standard-queue-target queue))))
(t
(loop
(when (or (endp (queue-pending queue))
(typep (first (queue-pending queue)) 'barrier-work))
(return))
(let ((fn (pop (queue-pending queue))))
(incf (queue-work-count queue))
(dispatch-async (lambda ()
(run-concurrent-fn queue fn))
(standard-queue-target queue)))))))))
(values))
(defmethod suspend ((queue standard-concurrent-queue))
(sup:with-mutex ((queue-lock queue))
(setf (standard-queue-active-p queue) nil))
(values))
(defun dispatch-sync (function queue &key barrier)
"Dispatch FUNCTION on QUEUE and wait for completion."
(let ((group (make-group :context (context queue))))
(dispatch-async function queue :group group :barrier barrier)
(wait group))
(values))
(defun dispatch-multiple (function iterations queue &key group)
"Dispatch FUNCTION on QUEUE multiple times. The function is called with the iteration number."
(dotimes (i iterations)
(let ((n i))
(dispatch-async (lambda () (funcall function n))
queue
:group group)))
(values))
(defun dispatch-after (function run-time queue)
"Submits a function for asynchronous execution on a dispatch queue after the specified time."
(let* ((timer (mezzano.supervisor:make-timer :deadline run-time))
(source (make-source timer nil
:cancellation-handler (lambda ()
(mezzano.supervisor::push-timer-pool timer))
:suspended t)))
(setf (source-handler source) (lambda ()
(dispatch-async function queue)
(mezzano.supervisor:timer-disarm timer)
(cancel source)))
(resume source))
(values))
(defun delay-to-run-time (delay)
"Convert a delay (a non-negative real representing seconds) to an absolute run time."
(+ (get-internal-run-time)
(truncate (* delay internal-time-units-per-second))))
(defun dispatch-delayed (function delay queue)
"Submits a function for asynchronous execution on a dispatch queue after the specified delay."
(dispatch-at function (delay-to-run-time delay) queue)
(values))
(defclass source (dispatch-object)
((%target :initarg :target :reader source-target)
(%event :initarg :event :reader source-event)
(%handler :initarg :handler :reader source-handler)
(%cancellation-handler :initarg :cancellation-handler
:reader source-cancellation-handler)
(%state :initform :suspended :accessor source-state))
(:documentation "A source connects an event to a dispatch context."))
(defmethod print-object ((instance source) stream)
(print-unreadable-object (instance stream :type t :identity t)
(format stream "~A targeting ~S" (source-event instance) (source-target instance))))
(defmethod sync:get-object-event ((object source))
(sync:get-object-event (source-event object)))
(defun make-source (event handler &key target cancellation-handler suspended)
"Create a new source object connected to EVENT.
HANDLER is the function to be called when EVENT becomes active. It
can initially be NIL but must be set via (SETF SOURCE-HANDLER) before
the source is initially activated.
TARGET is the queue that the handlers are to be dispatched on. It defaults
to the global queue for the current context.
CANCELLATION-HANDLER is a function that will be dispatched when CANCEL completes
and the source has been fully unregistered.
SUSPENDED specifies if the source should start in a suspeneded state or
if it should immediately begin dispatching events."
(assert (or handler suspended) (handler suspended) "The queue must start in a suspended state if no handler is supplied.")
(let* ((target (or target (global-queue)))
(context (context target))
(source (make-instance 'source
:event event
:context context
:target target
:handler handler
:cancellation-handler cancellation-handler)))
(when (not suspended)
(resume source))
source))
(defun %set-source-handler (value source)
(assert (eql (source-state source) :suspended))
(setf (slot-value source '%handler) value))
(defun (setf source-handler) (value source)
(check-type value (or function null))
(dispatch-async (lambda () (%set-source-handler value source))
(manager-queue :context (context source)))
value)
(defun %resume-source (source)
(ecase (source-state source)
(:suspended
(assert (source-handler source))
(setf (source-state source) :active)
(push source (context-manager-events *local-context*)))
(:event-running-suspend-requested
(setf (source-state source) :event-running))
(:event-running)
(:active)
((:canceled :event-running-cancel-requested)
(error "Cannot resume a canceled source ~S" source))))
(defmethod resume ((source source))
(dispatch-async (lambda () (%resume-source source))
(manager-queue :context (context source)))
(values))
(defun %suspend-source (source)
(ecase (source-state source)
((:suspended :canceled))
((:event-running-suspend-requested :event-running-cancel-requested))
(:event-running
(setf (source-state source) :event-running-suspend-requested))
(:active
(setf (source-state source) :suspended)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*))))))
(defmethod suspend ((source source))
(dispatch-async (lambda () (%suspend-source source))
(manager-queue :context (context source)))
(values))
(defun process-source (source)
(ecase (source-state source)
(:active
(setf (source-state source) :event-running)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*)))
(dispatch-async (lambda ()
(unwind-protect
(funcall (source-handler source))
(dispatch-async (lambda () (complete-source source))
(manager-queue :context (context source)))))
(source-target source)))))
(defun complete-source (source)
(ecase (source-state source)
(:event-running-cancel-requested
(setf (source-state source) :canceled)
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))
(:event-running-suspend-requested
(setf (source-state source) :suspended))
(:event-running
(setf (source-state source) :active)
(push source (context-manager-events *local-context*)))))
(defun %cancel-source (source)
(ecase (source-state source)
((:canceled :event-running-cancel-requested))
(:suspended
(setf (source-state source) :canceled)
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))
((:event-running-suspend-requested :event-running)
(setf (source-state source) :event-running-cancel-requested))
(:active
(setf (source-state source) :canceled)
(setf (context-manager-events *local-context*)
(remove source (context-manager-events *local-context*)))
(when (source-cancellation-handler source)
(dispatch-async (source-cancellation-handler source)
(source-target source))))))
(defmethod cancel ((source source))
(dispatch-async (lambda () (%cancel-source source))
(manager-queue :context (context source)))
(values))
(defmethod canceled-p ((source source))
(eql (source-state source) :canceled))
Groups
(defclass group (dispatch-object)
((%count :initform 0 :accessor group-count)
(%pending :initform '() :accessor group-notifiers)
(%lock :reader group-lock)
(%cvar :reader group-cvar)))
(defmethod initialize-instance :after ((instance group) &key)
(setf (slot-value instance '%lock) (sup:make-mutex instance)
(slot-value instance '%cvar) (sup:make-condition-variable instance)))
(defun make-group (&key (context *local-context*))
"Create a new group.
Groups can be used to determine when a collections of work items
have all been completed."
(make-instance 'group :context context))
(defmethod wait ((group group) &key timeout)
(sup:with-mutex ((group-lock group))
(sup:condition-wait-for ((group-cvar group) (group-lock group) timeout)
(zerop (group-count group)))))
(defmethod notify (function (group group) &key target)
(setf target (or target (global-queue :context (context group))))
(sup:with-mutex ((group-lock group))
(if (zerop (group-count group))
(dispatch-async function target)
(push (list function target) (group-notifiers group))))
(values))
(defun group-enter (group)
"Manually enter a group, incrementing the internal counter."
(sup:with-mutex ((group-lock group))
(incf (group-count group)))
(values))
(defun group-leave (group)
"Manually leave a group, decrementing the internal counter.
When the group's internal counter reaches zero all pending
notifications will be dispatched."
(sup:with-mutex ((group-lock group))
(decf (group-count group))
(when (zerop (group-count group))
(sup:condition-notify (group-cvar group) t)
(loop
for (function target) in (group-notifiers group)
do (dispatch-async function target))
(setf (group-notifiers group) '())))
(values))
(defun group-wrap (function group)
(cond (group
(group-enter group)
(lambda ()
(unwind-protect
(funcall function)
(group-leave group))))
(t
function)))
|
4be63037823c3435a24388c56cf098f758257d5474640731930febc02fd97e22 | polyfy/polylith | tap.clj | (ns polylith.clj.core.help.tap
(:require [polylith.clj.core.help.shared :as s]))
(defn help [cm]
(str " Opens (or closes/cleans) a portal window ()\n"
" where " (s/key "tap>" cm) " statements are sent to. This command is used from the shell and\n"
" is mainly used internally when developing the poly tool itself.\n"
"\n"
" tap [" (s/key "ARG" cm) "]\n"
" " (s/key "ARG" cm) " = " (s/key "(omitted)" cm) " Opens a portal window.\n"
" " (s/key "open" cm) " Opens a portal window.\n"
" " (s/key "close" cm) " Closes the portal window\n"
" " (s/key "clear" cm) " Clears the portal window\n"
"\n"
" Example:\n"
" tap\n"
" tap open\n"
" tap clean\n"
" tap close"))
(defn print-help [color-mode]
(println (help color-mode)))
(comment
(print-help "dark")
#__)
| null | https://raw.githubusercontent.com/polyfy/polylith/36b75565032dea88ee20cdc0bc5af18f6f4d4cf4/components/help/src/polylith/clj/core/help/tap.clj | clojure | (ns polylith.clj.core.help.tap
(:require [polylith.clj.core.help.shared :as s]))
(defn help [cm]
(str " Opens (or closes/cleans) a portal window ()\n"
" where " (s/key "tap>" cm) " statements are sent to. This command is used from the shell and\n"
" is mainly used internally when developing the poly tool itself.\n"
"\n"
" tap [" (s/key "ARG" cm) "]\n"
" " (s/key "ARG" cm) " = " (s/key "(omitted)" cm) " Opens a portal window.\n"
" " (s/key "open" cm) " Opens a portal window.\n"
" " (s/key "close" cm) " Closes the portal window\n"
" " (s/key "clear" cm) " Clears the portal window\n"
"\n"
" Example:\n"
" tap\n"
" tap open\n"
" tap clean\n"
" tap close"))
(defn print-help [color-mode]
(println (help color-mode)))
(comment
(print-help "dark")
#__)
| |
bd30d26fc30095a6d348382549a8671c6e05016bef1a1e02d07131b0aed9cfbf | vehicle-lang/vehicle | Normalised.hs | module Vehicle.Expr.Normalised where
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Vehicle.Compile.Prelude.Contexts (BoundCtx)
import Vehicle.Expr.DeBruijn
import Vehicle.Expr.Normalisable
import Vehicle.Syntax.AST
-----------------------------------------------------------------------------
-- Normalised expressions
-- | A normalised expression. Internal invariant is that it should always be
-- well-typed.
data NormExpr types
= VUniverse UniverseLevel
| VLam (NormBinder types) (Env types) (NormalisableExpr types)
| VPi (NormBinder types) (NormExpr types)
| VMeta MetaID (Spine types)
| VFreeVar Identifier (Spine types)
| VBoundVar DBLevel (Spine types)
| VBuiltin (NormalisableBuiltin types) (ExplicitSpine types)
deriving (Eq, Show, Generic)
instance Serialize types => Serialize (NormExpr types)
type NormArg types = GenericArg (NormExpr types)
type NormBinder types = GenericBinder DBBinding (NormType types)
type NormDecl types = GenericDecl (NormExpr types)
type NormProg types = GenericDecl types
-- | A normalised type
type NormType types = NormExpr types
-----------------------------------------------------------------------------
-- Spines and environments
-- | A list of arguments for an application that cannot be normalised.
type Spine types = [NormArg types]
-- | A spine type for builtins which enforces the invariant that they should
-- only ever depend computationally on their explicit arguments.
type ExplicitSpine types = [NormExpr types]
type Env types = BoundCtx (Maybe Name, NormExpr types)
extendEnv :: GenericBinder binder expr -> NormExpr types -> Env types -> Env types
extendEnv binder value = ((nameOf binder, value) :)
extendEnvOverBinder :: GenericBinder binder expr -> Env types -> Env types
extendEnvOverBinder binder env =
extendEnv binder (VBoundVar (DBLevel $ length env) []) env
-----------------------------------------------------------------------------
-- Patterns
pattern VTypeUniverse :: UniverseLevel -> NormType types
pattern VTypeUniverse l = VUniverse l
pattern VBuiltinFunction :: BuiltinFunction -> ExplicitSpine types -> NormExpr types
pattern VBuiltinFunction f spine = VBuiltin (CFunction f) spine
pattern VConstructor :: BuiltinConstructor -> ExplicitSpine types -> NormExpr types
pattern VConstructor c args = VBuiltin (CConstructor c) args
pattern VNullaryConstructor :: BuiltinConstructor -> NormExpr types
pattern VNullaryConstructor c <- VConstructor c []
where
VNullaryConstructor c = VConstructor c []
pattern VUnitLiteral :: NormExpr types
pattern VUnitLiteral = VNullaryConstructor LUnit
pattern VBoolLiteral :: Bool -> NormExpr types
pattern VBoolLiteral x = VNullaryConstructor (LBool x)
pattern VIndexLiteral :: Int -> NormExpr types
pattern VIndexLiteral x = VNullaryConstructor (LIndex x)
pattern VNatLiteral :: Int -> NormExpr types
pattern VNatLiteral x = VNullaryConstructor (LNat x)
pattern VIntLiteral :: Int -> NormExpr types
pattern VIntLiteral x = VNullaryConstructor (LInt x)
pattern VRatLiteral :: Rational -> NormExpr types
pattern VRatLiteral x = VNullaryConstructor (LRat x)
pattern VVecLiteral :: [NormExpr types] -> NormExpr types
pattern VVecLiteral xs <- VConstructor (LVec _) xs
where
VVecLiteral xs = VConstructor (LVec (length xs)) xs
pattern VNil :: NormExpr types
pattern VNil = VNullaryConstructor Nil
pattern VCons :: [NormExpr types] -> NormExpr types
pattern VCons xs = VConstructor Cons xs
mkVList :: [NormExpr types] -> NormExpr types
mkVList = foldr cons nil
where
nil = VConstructor Nil []
cons y ys = VConstructor Cons [y, ys]
mkVLVec :: [NormExpr types] -> NormExpr types
mkVLVec xs = VConstructor (LVec (length xs)) xs
isNTypeUniverse :: NormExpr types -> Bool
isNTypeUniverse VUniverse {} = True
isNTypeUniverse _ = False
isNMeta :: NormExpr types -> Bool
isNMeta VMeta {} = True
isNMeta _ = False
getNMeta :: NormExpr types -> Maybe MetaID
getNMeta (VMeta m _) = Just m
getNMeta _ = Nothing
-----------------------------------------------------------------------------
-- Glued expressions
-- | A pair of an unnormalised and normalised expression.
data GluedExpr types = Glued
{ unnormalised :: NormalisableExpr types,
normalised :: NormExpr types
}
deriving (Show, Generic)
instance Serialize types => Serialize (GluedExpr types)
instance HasProvenance (GluedExpr types) where
provenanceOf = provenanceOf . unnormalised
type GluedArg types = GenericArg (GluedExpr types)
type GluedType types = GluedExpr types
type GluedProg types = GenericProg (GluedExpr types)
type GluedDecl types = GenericDecl (GluedExpr types)
traverseNormalised :: Monad m => (NormExpr types -> m (NormExpr types)) -> GluedExpr types -> m (GluedExpr types)
traverseNormalised f (Glued u n) = Glued u <$> f n
traverseUnnormalised :: Monad m => (NormalisableExpr types -> m (NormalisableExpr types)) -> GluedExpr types -> m (GluedExpr types)
traverseUnnormalised f (Glued u n) = Glued <$> f u <*> pure n
| null | https://raw.githubusercontent.com/vehicle-lang/vehicle/3a3548f9b48c3969212ccb51e954d4d4556ea815/vehicle/src/Vehicle/Expr/Normalised.hs | haskell | ---------------------------------------------------------------------------
Normalised expressions
| A normalised expression. Internal invariant is that it should always be
well-typed.
| A normalised type
---------------------------------------------------------------------------
Spines and environments
| A list of arguments for an application that cannot be normalised.
| A spine type for builtins which enforces the invariant that they should
only ever depend computationally on their explicit arguments.
---------------------------------------------------------------------------
Patterns
---------------------------------------------------------------------------
Glued expressions
| A pair of an unnormalised and normalised expression. | module Vehicle.Expr.Normalised where
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Vehicle.Compile.Prelude.Contexts (BoundCtx)
import Vehicle.Expr.DeBruijn
import Vehicle.Expr.Normalisable
import Vehicle.Syntax.AST
data NormExpr types
= VUniverse UniverseLevel
| VLam (NormBinder types) (Env types) (NormalisableExpr types)
| VPi (NormBinder types) (NormExpr types)
| VMeta MetaID (Spine types)
| VFreeVar Identifier (Spine types)
| VBoundVar DBLevel (Spine types)
| VBuiltin (NormalisableBuiltin types) (ExplicitSpine types)
deriving (Eq, Show, Generic)
instance Serialize types => Serialize (NormExpr types)
type NormArg types = GenericArg (NormExpr types)
type NormBinder types = GenericBinder DBBinding (NormType types)
type NormDecl types = GenericDecl (NormExpr types)
type NormProg types = GenericDecl types
type NormType types = NormExpr types
type Spine types = [NormArg types]
type ExplicitSpine types = [NormExpr types]
type Env types = BoundCtx (Maybe Name, NormExpr types)
extendEnv :: GenericBinder binder expr -> NormExpr types -> Env types -> Env types
extendEnv binder value = ((nameOf binder, value) :)
extendEnvOverBinder :: GenericBinder binder expr -> Env types -> Env types
extendEnvOverBinder binder env =
extendEnv binder (VBoundVar (DBLevel $ length env) []) env
pattern VTypeUniverse :: UniverseLevel -> NormType types
pattern VTypeUniverse l = VUniverse l
pattern VBuiltinFunction :: BuiltinFunction -> ExplicitSpine types -> NormExpr types
pattern VBuiltinFunction f spine = VBuiltin (CFunction f) spine
pattern VConstructor :: BuiltinConstructor -> ExplicitSpine types -> NormExpr types
pattern VConstructor c args = VBuiltin (CConstructor c) args
pattern VNullaryConstructor :: BuiltinConstructor -> NormExpr types
pattern VNullaryConstructor c <- VConstructor c []
where
VNullaryConstructor c = VConstructor c []
pattern VUnitLiteral :: NormExpr types
pattern VUnitLiteral = VNullaryConstructor LUnit
pattern VBoolLiteral :: Bool -> NormExpr types
pattern VBoolLiteral x = VNullaryConstructor (LBool x)
pattern VIndexLiteral :: Int -> NormExpr types
pattern VIndexLiteral x = VNullaryConstructor (LIndex x)
pattern VNatLiteral :: Int -> NormExpr types
pattern VNatLiteral x = VNullaryConstructor (LNat x)
pattern VIntLiteral :: Int -> NormExpr types
pattern VIntLiteral x = VNullaryConstructor (LInt x)
pattern VRatLiteral :: Rational -> NormExpr types
pattern VRatLiteral x = VNullaryConstructor (LRat x)
pattern VVecLiteral :: [NormExpr types] -> NormExpr types
pattern VVecLiteral xs <- VConstructor (LVec _) xs
where
VVecLiteral xs = VConstructor (LVec (length xs)) xs
pattern VNil :: NormExpr types
pattern VNil = VNullaryConstructor Nil
pattern VCons :: [NormExpr types] -> NormExpr types
pattern VCons xs = VConstructor Cons xs
mkVList :: [NormExpr types] -> NormExpr types
mkVList = foldr cons nil
where
nil = VConstructor Nil []
cons y ys = VConstructor Cons [y, ys]
mkVLVec :: [NormExpr types] -> NormExpr types
mkVLVec xs = VConstructor (LVec (length xs)) xs
isNTypeUniverse :: NormExpr types -> Bool
isNTypeUniverse VUniverse {} = True
isNTypeUniverse _ = False
isNMeta :: NormExpr types -> Bool
isNMeta VMeta {} = True
isNMeta _ = False
getNMeta :: NormExpr types -> Maybe MetaID
getNMeta (VMeta m _) = Just m
getNMeta _ = Nothing
data GluedExpr types = Glued
{ unnormalised :: NormalisableExpr types,
normalised :: NormExpr types
}
deriving (Show, Generic)
instance Serialize types => Serialize (GluedExpr types)
instance HasProvenance (GluedExpr types) where
provenanceOf = provenanceOf . unnormalised
type GluedArg types = GenericArg (GluedExpr types)
type GluedType types = GluedExpr types
type GluedProg types = GenericProg (GluedExpr types)
type GluedDecl types = GenericDecl (GluedExpr types)
traverseNormalised :: Monad m => (NormExpr types -> m (NormExpr types)) -> GluedExpr types -> m (GluedExpr types)
traverseNormalised f (Glued u n) = Glued u <$> f n
traverseUnnormalised :: Monad m => (NormalisableExpr types -> m (NormalisableExpr types)) -> GluedExpr types -> m (GluedExpr types)
traverseUnnormalised f (Glued u n) = Glued <$> f u <*> pure n
|
ed52bed42623bf23f4a32cb57fc3df5f91bee82e965483eae4be4cdacba4de71 | zalky/reflet | workflow.cljs | (ns reflet.client.ui.workflow
(:require [goog.string :as gstr]
[goog.string.format]
[reflet.client.ui.workflow.impl :as impl]
[reflet.core :as f]
[reflet.debug.glyphs :as g]))
;;;; Utility
(def option-labels
["A" "B" "C" "D"])
(defn- stroke
[props]
(-> {:stroke-width "2px"}
(merge props)
(g/stroke)))
(defn- checked
[]
[:path (stroke {:d "M 8,10 L 10,12 17,5"})])
(defn- check
[{:keys [done on-click]
:as props}]
[:div {:class "workflow-check"
:on-click on-click}
[:svg {:view-box "0 0 20 20"}
[:circle (stroke {:cx 10
:cy 10
:r 6})]
(when done (checked))]])
(defn- step
[{:keys [done active on-click]
:as props}]
[:div {:class "workflow-step"
:on-click on-click}
[:svg {:view-box "0 0 20 20"}
(if done
(checked)
[:circle (stroke {:cx 10
:cy 10
:r (if active 6 3)
:fill "currentColor"})])]])
(defn- line
[]
[:div {:class "workflow-line"}
[:svg {:view-box "0 0 80 20"}
[:path (stroke {:d "M 5,10 L 75,10"})]]])
(defn- grid-template
[items]
(->> (count items)
(dec)
(gstr/format "repeat(%d, 20px 80px) 20px")
(hash-map :grid-template-columns)))
(defn- progress-step
[{:keys [active label]
:as item}]
[:div {:class "workflow-progress-step"}
[step item]
[:div {:class (when active "active")}
label]])
(defn- progress
[items]
[:div {:class "workflow-progress"
:style (grid-template items)}
(->> items
(map progress-step)
(interpose [line])
(map-indexed #(with-meta %2 {:key %1}))
(doall))])
;;;; Workflows
(defn- form-entry
[i self]
(let [attr (keyword "attr" i)
selected? (f/sub [::impl/selected? self attr])
on-click #(f/disp [::impl/select self attr])]
[:<> {:key i}
[:div {:class "workflow-label"}
(nth option-labels i)]
[check {:on-click on-click
:done @selected?}]]))
(defn- form
[{:keys [self required total]}]
{:pre [(number? total)]}
@(f/sub [::impl/form self required])
[:div {:class "workflow-form"}
[:div {:class "workflow-required"}
[:span "Choose"]
[:span required]
[:span "/"]
[:span total]]
(doall
(for [i (range total)]
(form-entry i self)))])
(defmulti workflow-b
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-b ::impl/step-1
[_ {:keys [::f1]}]
[form {:self f1
:required 2
:total 3}])
(defmethod workflow-b ::impl/step-2
[_ {:keys [::f2]}]
[form {:self f2
:required 2
:total 4}])
(defmethod workflow-b ::impl/step-3
[_ {:keys [::f3]}]
[form {:self f3
:required 1
:total 3}])
(defmethod workflow-b ::impl/step-4
[_ {:keys [::f4]}]
[form {:self f4
:required 1
:total 1}])
(defmethod workflow-b ::impl/done
[_ _]
[:div {:class "workflow-done"}
"Done!"])
(defmulti workflow-c
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-c ::impl/step-1
[_ {:keys [::f1]}]
[form {:self f1
:required 2
:total 2}])
(defmethod workflow-c ::impl/step-2
[_ {:keys [::f2]}]
[form {:self f2
:required 1
:total 4}])
(defmethod workflow-c ::impl/step-3
[_ {:keys [::f3]}]
[form {:self f3
:required 2
:total 3}])
(defmethod workflow-c ::impl/done
[_ _]
[:div {:class "workflow-done"}
"Done!"])
(defmulti workflow-a
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-a ::impl/step-1
[_ props]
(f/with-ref {:cmp/uuid [::b ::f1 ::f2 ::f3 ::f4]
:in props}
(let [state @(f/sub [::impl/workflow-b b f1 f2 f3 f4])]
[:<>
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? f1])
:label "Form 1"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? f2])
:label "Form 2"}
{:active (= state ::impl/step-3)
:done @(f/sub [::impl/done? f3])
:label "Form 3"}
{:active (= state ::impl/step-4)
:done @(f/sub [::impl/done? f4])
:label "Form 4"}]]
[workflow-b state props]])))
(defmethod workflow-a ::impl/step-2
[_ props]
(f/with-ref {:cmp/uuid [::c ::f1 ::f2 ::f3]
:in props}
(let [state @(f/sub [::impl/workflow-c c f1 f2 f3])]
[:<>
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? f1])
:label "Form 1"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? f2])
:label "Form 2"}
{:active (= state ::impl/step-3)
:done @(f/sub [::impl/done? f3])
:label "Form 3"}]]
[workflow-c state props]])))
(defmethod workflow-a ::impl/done
[_ props]
[:div {:class "workflow-done"}
"Done!"])
(defn workflow
[props]
(f/with-ref {:cmp/uuid [::a ::b ::c]
:in props}
(let [state @(f/sub [::impl/workflow-a a b c])]
[:div {:class "workflow"}
(when-not (= ::impl/done state)
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? b])
:label "Workflow B"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? c])
:label "Workflow C"}]])
[workflow-a state props]])))
| null | https://raw.githubusercontent.com/zalky/reflet/fe88f7fd7d761dfa40af0e8f83d7f390e5a914b6/client/clojure/reflet/client/ui/workflow.cljs | clojure | Utility
Workflows | (ns reflet.client.ui.workflow
(:require [goog.string :as gstr]
[goog.string.format]
[reflet.client.ui.workflow.impl :as impl]
[reflet.core :as f]
[reflet.debug.glyphs :as g]))
(def option-labels
["A" "B" "C" "D"])
(defn- stroke
[props]
(-> {:stroke-width "2px"}
(merge props)
(g/stroke)))
(defn- checked
[]
[:path (stroke {:d "M 8,10 L 10,12 17,5"})])
(defn- check
[{:keys [done on-click]
:as props}]
[:div {:class "workflow-check"
:on-click on-click}
[:svg {:view-box "0 0 20 20"}
[:circle (stroke {:cx 10
:cy 10
:r 6})]
(when done (checked))]])
(defn- step
[{:keys [done active on-click]
:as props}]
[:div {:class "workflow-step"
:on-click on-click}
[:svg {:view-box "0 0 20 20"}
(if done
(checked)
[:circle (stroke {:cx 10
:cy 10
:r (if active 6 3)
:fill "currentColor"})])]])
(defn- line
[]
[:div {:class "workflow-line"}
[:svg {:view-box "0 0 80 20"}
[:path (stroke {:d "M 5,10 L 75,10"})]]])
(defn- grid-template
[items]
(->> (count items)
(dec)
(gstr/format "repeat(%d, 20px 80px) 20px")
(hash-map :grid-template-columns)))
(defn- progress-step
[{:keys [active label]
:as item}]
[:div {:class "workflow-progress-step"}
[step item]
[:div {:class (when active "active")}
label]])
(defn- progress
[items]
[:div {:class "workflow-progress"
:style (grid-template items)}
(->> items
(map progress-step)
(interpose [line])
(map-indexed #(with-meta %2 {:key %1}))
(doall))])
(defn- form-entry
[i self]
(let [attr (keyword "attr" i)
selected? (f/sub [::impl/selected? self attr])
on-click #(f/disp [::impl/select self attr])]
[:<> {:key i}
[:div {:class "workflow-label"}
(nth option-labels i)]
[check {:on-click on-click
:done @selected?}]]))
(defn- form
[{:keys [self required total]}]
{:pre [(number? total)]}
@(f/sub [::impl/form self required])
[:div {:class "workflow-form"}
[:div {:class "workflow-required"}
[:span "Choose"]
[:span required]
[:span "/"]
[:span total]]
(doall
(for [i (range total)]
(form-entry i self)))])
(defmulti workflow-b
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-b ::impl/step-1
[_ {:keys [::f1]}]
[form {:self f1
:required 2
:total 3}])
(defmethod workflow-b ::impl/step-2
[_ {:keys [::f2]}]
[form {:self f2
:required 2
:total 4}])
(defmethod workflow-b ::impl/step-3
[_ {:keys [::f3]}]
[form {:self f3
:required 1
:total 3}])
(defmethod workflow-b ::impl/step-4
[_ {:keys [::f4]}]
[form {:self f4
:required 1
:total 1}])
(defmethod workflow-b ::impl/done
[_ _]
[:div {:class "workflow-done"}
"Done!"])
(defmulti workflow-c
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-c ::impl/step-1
[_ {:keys [::f1]}]
[form {:self f1
:required 2
:total 2}])
(defmethod workflow-c ::impl/step-2
[_ {:keys [::f2]}]
[form {:self f2
:required 1
:total 4}])
(defmethod workflow-c ::impl/step-3
[_ {:keys [::f3]}]
[form {:self f3
:required 2
:total 3}])
(defmethod workflow-c ::impl/done
[_ _]
[:div {:class "workflow-done"}
"Done!"])
(defmulti workflow-a
(fn [state _] state)
:default ::impl/step-1)
(defmethod workflow-a ::impl/step-1
[_ props]
(f/with-ref {:cmp/uuid [::b ::f1 ::f2 ::f3 ::f4]
:in props}
(let [state @(f/sub [::impl/workflow-b b f1 f2 f3 f4])]
[:<>
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? f1])
:label "Form 1"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? f2])
:label "Form 2"}
{:active (= state ::impl/step-3)
:done @(f/sub [::impl/done? f3])
:label "Form 3"}
{:active (= state ::impl/step-4)
:done @(f/sub [::impl/done? f4])
:label "Form 4"}]]
[workflow-b state props]])))
(defmethod workflow-a ::impl/step-2
[_ props]
(f/with-ref {:cmp/uuid [::c ::f1 ::f2 ::f3]
:in props}
(let [state @(f/sub [::impl/workflow-c c f1 f2 f3])]
[:<>
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? f1])
:label "Form 1"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? f2])
:label "Form 2"}
{:active (= state ::impl/step-3)
:done @(f/sub [::impl/done? f3])
:label "Form 3"}]]
[workflow-c state props]])))
(defmethod workflow-a ::impl/done
[_ props]
[:div {:class "workflow-done"}
"Done!"])
(defn workflow
[props]
(f/with-ref {:cmp/uuid [::a ::b ::c]
:in props}
(let [state @(f/sub [::impl/workflow-a a b c])]
[:div {:class "workflow"}
(when-not (= ::impl/done state)
[progress [{:active (= state ::impl/step-1)
:done @(f/sub [::impl/done? b])
:label "Workflow B"}
{:active (= state ::impl/step-2)
:done @(f/sub [::impl/done? c])
:label "Workflow C"}]])
[workflow-a state props]])))
|
9ed1378bbc710783cd89b88613698e29cfa1174c9af2dba7a818d9678f1fe825 | tokenmill/timewords | fuzzy.clj | (ns timewords.fuzzy.fuzzy
(:require [clj-time.core :refer [date-time]]
[timewords.fuzzy.en.en :as en]
[timewords.fuzzy.lt.lt :as lt])
(:import (org.joda.time DateTime)))
(defn to-date
"Parses string dates into components represented by numeric values:
1-12 for months
1-31 for days
19??-20?? for years.
Dispatches parsing by language. Default language is en."
^DateTime [^String fuzzy-date & [^String language ^DateTime document-time]]
(cond
(= language "en") (if-let [date-parts (en/parse-date fuzzy-date document-time)]
(apply date-time (map #(Integer/parseInt %) date-parts)))
(= language "lt") (if-let [date-parts (lt/parse-date fuzzy-date document-time)]
(apply date-time (map #(Integer/parseInt %) date-parts)))
:else nil))
| null | https://raw.githubusercontent.com/tokenmill/timewords/431ef3aa9eb899f2abd47cebc20a232f8c226b4a/src/timewords/fuzzy/fuzzy.clj | clojure | (ns timewords.fuzzy.fuzzy
(:require [clj-time.core :refer [date-time]]
[timewords.fuzzy.en.en :as en]
[timewords.fuzzy.lt.lt :as lt])
(:import (org.joda.time DateTime)))
(defn to-date
"Parses string dates into components represented by numeric values:
1-12 for months
1-31 for days
19??-20?? for years.
Dispatches parsing by language. Default language is en."
^DateTime [^String fuzzy-date & [^String language ^DateTime document-time]]
(cond
(= language "en") (if-let [date-parts (en/parse-date fuzzy-date document-time)]
(apply date-time (map #(Integer/parseInt %) date-parts)))
(= language "lt") (if-let [date-parts (lt/parse-date fuzzy-date document-time)]
(apply date-time (map #(Integer/parseInt %) date-parts)))
:else nil))
| |
37370f70365b5621bedf2200faed970a4049c452a3c6ab6127f3e1d5e75fd025 | msp-strath/feet | Parser.hs | # LANGUAGE TupleSections #
# LANGUAGE GeneralizedNewtypeDeriving #
module Feet.Parser where
import Control.Applicative
import Control.Monad hiding (fail)
import Control.Arrow ((***))
import Data.List
import Data.Char
import Text.Read (readMaybe)
import Feet.Syntax
import Feet.Frontend
newtype DBP x = DBP {dbp :: [String] -> String -> [(x, String)]}
deriving (Semigroup, Monoid)
instance Monad DBP where
return x = DBP $ \ is s -> return (x, s)
DBP a >>= k = DBP $ \ is s -> do
(a, s) <- a is s
dbp (k a) is s
instance Applicative DBP where
pure = return
f <*> a = f >>= \ f -> a >>= \ a -> return (f a)
instance Functor DBP where
fmap = (<*>) . pure
instance Alternative DBP where
empty = mempty
(<|>) = (<>)
push :: String -> DBP x -> DBP x
push i (DBP p) = DBP $ \ is s -> p (i : is) s
dbix :: String -> DBP Int
dbix j = DBP $ \ is s -> case findIndex (j ==) is of
Just i -> [(i, s)]
Nothing -> []
get :: (Char -> Bool) -> DBP Char
get p = DBP $ \ is s -> case s of
c : s | p c -> [(c, s)]
_ -> []
string :: String -> DBP String
string = traverse (get . (==))
punc :: String -> DBP ()
punc s = () <$ string s
spc :: DBP ()
spc = () <$ many (get isSpace)
spaced :: DBP x -> DBP x
spaced p = spc *> p <* spc
pId :: DBP String
pId = (:) <$> get isAlpha <*> many (get $ \ c -> isAlphaNum c || elem c "'_$")
pTel :: (Tel -> DBP x) -> DBP x
pTel k = do
xs <- pIds
spaced $ punc ":"
pChk 0 >>= bind k xs
where
pIds = (:) <$> pId <*> (id <$ get isSpace <* spc <*> pIds <|> pure [])
pMore k = (do
spaced $ punc ","
xs <- pIds
spaced $ punc ":"
pChk 0 >>= bind k xs)
<|> k T0
bind k [] s = pMore k
bind k (x : xs) s = push x (bind (k . ((x,s) :\:)) xs (s <^> Th (negate 2)))
pChk :: Int -> DBP ChkTm
pChk l =
id <$ guard (l == 0) <*>
( (do
punc "\\"
x <- spaced pId
t <- push x (pChk 0)
return $ Lam t)
<|> id <$ punc "(" <* spc <*> pTel pPiSg
)
<|> (pHead >>= pMore l) where
pHead =
(do
a <- pAdapter 0
spc
e <- pSyn l
return (e :-: a)
)
<|> Ty <$ punc "Ty"
<|> List <$ punc "List" <* spc <*> pChk 2
<|> Enum <$ punc "Enum" <* spc <*> pChk 2
-- TODO: [ _P' | (v : _X') <- xs ]"
<|> (do
punc "AllT"
spc
_X <- pChk 0
spaced $ punc "("
x <- spaced pId
_P <- push x (pChk 0)
spaced $ punc ")"
xs <- pChk 0
return (AllT _X _P xs))
<|> One <$ punc "One"
<|> Nat <$ punc "Nat"
<|> Atom <$ punc "Atom"
<|> pNat
<|> Void <$ punc "<>"
<|> Nil <$ punc "."
<|> Th1 <$ punc "1.."
<|> Th0 <$ punc "0.."
<|> (\ x -> Cons (A [x])) <$> get (\ x -> x == '0' || x == '1') <*> pChk 2
<|> A <$ punc "'" <*> pId
<|> FAb <$ punc "FAb" <* spc <*> pChk 2
<|> FOne <$ punc "@"
<|> Inv <$ punc "!" <* spc <*> pHead
<|> id <$ punc "[" <* spc <*> pList <* spc <* punc "]"
<|> tuple <$ punc "(" <* spc <*> pList <* spc <* punc ")"
pMore l s =
id <$ guard (l == 0) <* spc <*>
( Pi s <$ punc "->" <* spc <*> push "" (pChk 0)
<|> Sg s <$ punc "*" <* spc <*> push "" (pChk 0)
<|> (s :++:) <$ punc "++" <* spc <*> pChk 0
<|> (s :.:) <$ punc "." <* spc <*> (pChk 2 >>= noNil)
<|> (do
spaced $ punc "<["
_X <- pChk 0
spaced $ punc "]="
de <- pChk 0
return (Thinning _X s de))
<|> ((ThSemi s <$ punc "`;" <* spc <*> pHead) >>= pMore l)
)
<|> pure s
noNil :: ChkTm -> DBP ChkTm
noNil Nil = empty
noNil t = pure t
tuple (Single t) = t
tuple Nil = Void
tuple (s :++: t) = (tuple s) :& (tuple t)
tuple z = error "it has to be a list to be tupled"
pPiSg :: Tel -> DBP ChkTm
pPiSg t = go t <$ spc <* punc ")" <* spc
<*> (Pi <$ punc "->" <|> Sg <$ punc "*") <* spc <*> pChk 0
where
go :: Tel -> (ChkTm -> ChkTm -> ChkTm) -> ChkTm -> ChkTm
go T0 bi body = body
go ((x,s) :\: t) bi body = bi s $ go t bi body
pAdapter :: Int -> DBP Adapter
pAdapter l =
List <$ punc "List" <* spc <*> pChk l
<|> Hom <$ punc "Hom" <* spc <*> pChk l
<|> Enum <$ punc "Enum" <* spc <*> pChk l
<|> Thinning <$ punc "Th" <* spc <*> pChk l <* spc <*> pChk l <* spc <*> pChk l
<|> AllT <$ punc "All" <* spc <*> pChk l <* spc <*> pChk l <* spc <*> pChk l
<|> pure Idapter
pVar :: DBP SynTm
pVar = do
x <- pId
V <$> dbix x
pSyn :: Int -> DBP SynTm
pSyn l = pHead >>= pMore l where
pHead :: DBP SynTm
pHead = pVar
<|> do
punc "(" <* spc
s <- pChk 0 >>= novar
spaced $ punc ":"
ty <- pChk 0
spc *> punc ")"
return (s ::: ty)
-- We avoid ambiguity between telescopes and radicals by disallowing
-- radical variables (for there is never need to annotate a variable).
novar :: ChkTm -> DBP ChkTm
novar (E (V _)) = empty
novar t = pure t
pMore :: Int -> SynTm -> DBP SynTm
pMore l e =
((id <$ guard (l < 2) <* spc <*> (
(e :$) <$> pChk 2
<|>
(do
punc "{"
x <- spaced pId
t <- push x (pChk 0)
spaced $ punc ";"
punc "[" <* spc <* punc "]"
spaced $ punc "->"
b <- pChk 0
spaced $ punc ";"
punc "["
x <- spaced pId
punc "]" <* spc <* punc "++"
xs <- spaced pId
punc "->"
s <- spaced $ push x (push xs (push (xs ++ "$") (pChk 0)))
punc "}"
return (e :$ ListElim t b s)
)
<|> (e :$ Fst) <$ punc "-fst"
<|> (e :$ Snd) <$ punc "-snd"
)) >>= pMore l)
<|> pure e
pNat :: DBP ChkTm
pNat = do
t <- many (get isNumber)
case readMaybe t of
Just n -> return (fromInteger n)
Nothing -> empty
pList :: DBP ChkTm
pList = pSome <|> pure Nil where
pSome = ((Single <$> pChk 0) >>= pMore)
pMore xs = (xs :++:) <$ spc <* punc "," <* spc <*> pSome <|> pure xs
pTask :: DBP Task
pTask = (pTel $ \ ga -> (ga :|-) <$ spc <* punc "|-" <* spc <*> pTask)
<|> (pId >>= \ x ->
(:&&) <$ spc <* punc "=" <* spc <*> ((x,) <$> pSyn 0)
<* spc <* punc ";" <* spc
<*> push x pTask)
<|> pure Done
pGo :: DBP x -> String -> [x]
pGo p s = do
(x, "") <- dbp p mempty s
return x
| null | https://raw.githubusercontent.com/msp-strath/feet/ff503e4122a5cbaf433fcffe9582ba7c8408e852/src/Feet/Parser.hs | haskell | TODO: [ _P' | (v : _X') <- xs ]"
We avoid ambiguity between telescopes and radicals by disallowing
radical variables (for there is never need to annotate a variable). | # LANGUAGE TupleSections #
# LANGUAGE GeneralizedNewtypeDeriving #
module Feet.Parser where
import Control.Applicative
import Control.Monad hiding (fail)
import Control.Arrow ((***))
import Data.List
import Data.Char
import Text.Read (readMaybe)
import Feet.Syntax
import Feet.Frontend
newtype DBP x = DBP {dbp :: [String] -> String -> [(x, String)]}
deriving (Semigroup, Monoid)
instance Monad DBP where
return x = DBP $ \ is s -> return (x, s)
DBP a >>= k = DBP $ \ is s -> do
(a, s) <- a is s
dbp (k a) is s
instance Applicative DBP where
pure = return
f <*> a = f >>= \ f -> a >>= \ a -> return (f a)
instance Functor DBP where
fmap = (<*>) . pure
instance Alternative DBP where
empty = mempty
(<|>) = (<>)
push :: String -> DBP x -> DBP x
push i (DBP p) = DBP $ \ is s -> p (i : is) s
dbix :: String -> DBP Int
dbix j = DBP $ \ is s -> case findIndex (j ==) is of
Just i -> [(i, s)]
Nothing -> []
get :: (Char -> Bool) -> DBP Char
get p = DBP $ \ is s -> case s of
c : s | p c -> [(c, s)]
_ -> []
string :: String -> DBP String
string = traverse (get . (==))
punc :: String -> DBP ()
punc s = () <$ string s
spc :: DBP ()
spc = () <$ many (get isSpace)
spaced :: DBP x -> DBP x
spaced p = spc *> p <* spc
pId :: DBP String
pId = (:) <$> get isAlpha <*> many (get $ \ c -> isAlphaNum c || elem c "'_$")
pTel :: (Tel -> DBP x) -> DBP x
pTel k = do
xs <- pIds
spaced $ punc ":"
pChk 0 >>= bind k xs
where
pIds = (:) <$> pId <*> (id <$ get isSpace <* spc <*> pIds <|> pure [])
pMore k = (do
spaced $ punc ","
xs <- pIds
spaced $ punc ":"
pChk 0 >>= bind k xs)
<|> k T0
bind k [] s = pMore k
bind k (x : xs) s = push x (bind (k . ((x,s) :\:)) xs (s <^> Th (negate 2)))
pChk :: Int -> DBP ChkTm
pChk l =
id <$ guard (l == 0) <*>
( (do
punc "\\"
x <- spaced pId
t <- push x (pChk 0)
return $ Lam t)
<|> id <$ punc "(" <* spc <*> pTel pPiSg
)
<|> (pHead >>= pMore l) where
pHead =
(do
a <- pAdapter 0
spc
e <- pSyn l
return (e :-: a)
)
<|> Ty <$ punc "Ty"
<|> List <$ punc "List" <* spc <*> pChk 2
<|> Enum <$ punc "Enum" <* spc <*> pChk 2
<|> (do
punc "AllT"
spc
_X <- pChk 0
spaced $ punc "("
x <- spaced pId
_P <- push x (pChk 0)
spaced $ punc ")"
xs <- pChk 0
return (AllT _X _P xs))
<|> One <$ punc "One"
<|> Nat <$ punc "Nat"
<|> Atom <$ punc "Atom"
<|> pNat
<|> Void <$ punc "<>"
<|> Nil <$ punc "."
<|> Th1 <$ punc "1.."
<|> Th0 <$ punc "0.."
<|> (\ x -> Cons (A [x])) <$> get (\ x -> x == '0' || x == '1') <*> pChk 2
<|> A <$ punc "'" <*> pId
<|> FAb <$ punc "FAb" <* spc <*> pChk 2
<|> FOne <$ punc "@"
<|> Inv <$ punc "!" <* spc <*> pHead
<|> id <$ punc "[" <* spc <*> pList <* spc <* punc "]"
<|> tuple <$ punc "(" <* spc <*> pList <* spc <* punc ")"
pMore l s =
id <$ guard (l == 0) <* spc <*>
( Pi s <$ punc "->" <* spc <*> push "" (pChk 0)
<|> Sg s <$ punc "*" <* spc <*> push "" (pChk 0)
<|> (s :++:) <$ punc "++" <* spc <*> pChk 0
<|> (s :.:) <$ punc "." <* spc <*> (pChk 2 >>= noNil)
<|> (do
spaced $ punc "<["
_X <- pChk 0
spaced $ punc "]="
de <- pChk 0
return (Thinning _X s de))
<|> ((ThSemi s <$ punc "`;" <* spc <*> pHead) >>= pMore l)
)
<|> pure s
noNil :: ChkTm -> DBP ChkTm
noNil Nil = empty
noNil t = pure t
tuple (Single t) = t
tuple Nil = Void
tuple (s :++: t) = (tuple s) :& (tuple t)
tuple z = error "it has to be a list to be tupled"
pPiSg :: Tel -> DBP ChkTm
pPiSg t = go t <$ spc <* punc ")" <* spc
<*> (Pi <$ punc "->" <|> Sg <$ punc "*") <* spc <*> pChk 0
where
go :: Tel -> (ChkTm -> ChkTm -> ChkTm) -> ChkTm -> ChkTm
go T0 bi body = body
go ((x,s) :\: t) bi body = bi s $ go t bi body
pAdapter :: Int -> DBP Adapter
pAdapter l =
List <$ punc "List" <* spc <*> pChk l
<|> Hom <$ punc "Hom" <* spc <*> pChk l
<|> Enum <$ punc "Enum" <* spc <*> pChk l
<|> Thinning <$ punc "Th" <* spc <*> pChk l <* spc <*> pChk l <* spc <*> pChk l
<|> AllT <$ punc "All" <* spc <*> pChk l <* spc <*> pChk l <* spc <*> pChk l
<|> pure Idapter
pVar :: DBP SynTm
pVar = do
x <- pId
V <$> dbix x
pSyn :: Int -> DBP SynTm
pSyn l = pHead >>= pMore l where
pHead :: DBP SynTm
pHead = pVar
<|> do
punc "(" <* spc
s <- pChk 0 >>= novar
spaced $ punc ":"
ty <- pChk 0
spc *> punc ")"
return (s ::: ty)
novar :: ChkTm -> DBP ChkTm
novar (E (V _)) = empty
novar t = pure t
pMore :: Int -> SynTm -> DBP SynTm
pMore l e =
((id <$ guard (l < 2) <* spc <*> (
(e :$) <$> pChk 2
<|>
(do
punc "{"
x <- spaced pId
t <- push x (pChk 0)
spaced $ punc ";"
punc "[" <* spc <* punc "]"
spaced $ punc "->"
b <- pChk 0
spaced $ punc ";"
punc "["
x <- spaced pId
punc "]" <* spc <* punc "++"
xs <- spaced pId
punc "->"
s <- spaced $ push x (push xs (push (xs ++ "$") (pChk 0)))
punc "}"
return (e :$ ListElim t b s)
)
<|> (e :$ Fst) <$ punc "-fst"
<|> (e :$ Snd) <$ punc "-snd"
)) >>= pMore l)
<|> pure e
pNat :: DBP ChkTm
pNat = do
t <- many (get isNumber)
case readMaybe t of
Just n -> return (fromInteger n)
Nothing -> empty
pList :: DBP ChkTm
pList = pSome <|> pure Nil where
pSome = ((Single <$> pChk 0) >>= pMore)
pMore xs = (xs :++:) <$ spc <* punc "," <* spc <*> pSome <|> pure xs
pTask :: DBP Task
pTask = (pTel $ \ ga -> (ga :|-) <$ spc <* punc "|-" <* spc <*> pTask)
<|> (pId >>= \ x ->
(:&&) <$ spc <* punc "=" <* spc <*> ((x,) <$> pSyn 0)
<* spc <* punc ";" <* spc
<*> push x pTask)
<|> pure Done
pGo :: DBP x -> String -> [x]
pGo p s = do
(x, "") <- dbp p mempty s
return x
|
a00b2d3eb55dde92a69f0f96ab8b469873bd96bda5d1fedac2a248dc552912c4 | mflatt/sirmail | info.rkt | #lang setup/infotab
(define collection 'multi)
(define deps '("base"
"compatibility-lib"
"drracket" ; for browser/htmltext
"gui-lib"
"net-lib"
"parser-tools-lib"
"scheme-lib"
"syntax-color-lib"
"sandbox-lib"
"pict-lib"
"pict-snip-lib"))
| null | https://raw.githubusercontent.com/mflatt/sirmail/5a08636d126ea04b5c903ab42a6e7eb2b143d864/info.rkt | racket | for browser/htmltext | #lang setup/infotab
(define collection 'multi)
(define deps '("base"
"compatibility-lib"
"gui-lib"
"net-lib"
"parser-tools-lib"
"scheme-lib"
"syntax-color-lib"
"sandbox-lib"
"pict-lib"
"pict-snip-lib"))
|
9d45bac9ad845142afd0f4bbbcf81b1b15cb011963e4299c2fb1978dc356cb85 | drjdn/p5scm | pr_o.cppo.ml | #include "pr_o.orig.ml"
value pr_o e = Eprinter.apply pr_str_item Pprintf.empty_pc e;
| null | https://raw.githubusercontent.com/drjdn/p5scm/b12ccf2b5d34ae338c91ecd0ecc0d3ebd22009b3/src/lib/camlp5/pr_o.cppo.ml | ocaml | #include "pr_o.orig.ml"
value pr_o e = Eprinter.apply pr_str_item Pprintf.empty_pc e;
| |
5e6b34408ce5c071689e2dfd918c134b2dff6b078802cae9e410eee637415a27 | phoe/protest | variable.lisp | ;;;; src/protocol/elements/variable.lisp
(in-package #:protest/protocol)
(defclass protocol-variable (protocol-data-type)
((%name :reader name
:initarg :name
:initform (error "Must provide NAME."))
(%value-type :accessor value-type
:initarg :value-type
:initform t)
(%initial-value :accessor initial-value
:initarg :initial-value)
(%declaim-type-p :accessor declaim-type-p
:initform t))
(:documentation
"Describes a protocol variable that is a part of a protocol.
\
The form for a protocol variable consists of the following subforms:
* NAME - mandatory, must be a symbol. Denotes the name of the variable.
* VALUE-TYPE - optional, must be a valid type specifier. Denotes the type of
the value bound to the variable. If not passed, the variable type will not be
declaimed.
* INITIAL-VALUE - optional. Denotes the default value that the variable will be
bound to at the moment of executing the protocol. If not passed, the variable
will be unbound."))
(defmethod keyword-element-class ((keyword (eql :variable)))
(find-class 'protocol-variable))
(defmethod generate-element-using-class
((class (eql (find-class 'protocol-variable)))
details &optional (declaim-type-p t))
(destructuring-bind (name . rest) details
(declare (ignore rest))
(assert (and (not (null name)) (symbolp name)) ()
"Wrong thing to be a variable name: ~S" name)
(let ((element (make-instance class :name name)))
(setf (declaim-type-p element) declaim-type-p)
(when (<= 2 (length details))
(let ((type (second details)))
(setf (value-type element) type)))
(when (<= 3 (length details))
(let ((initial-value (third details)))
(unless (typep initial-value (second details))
(protocol-error "The provided initial value, ~S, is not of the ~
provided type ~S." (value-type element)) initial-value)
(setf (initial-value element) initial-value)))
element)))
(defmethod embed-documentation ((element protocol-variable) (string string))
(setf (documentation (name element) 'variable) string))
(defmethod generate-forms ((element protocol-variable))
(let* ((name (name element))
(type (value-type element))
(documentation (docstring element)))
`((:variable ,name ,@(unless (eq type 't) `(,type))
,@(when (slot-boundp element '%initial-value)
`(,(initial-value element))))
,@(when documentation `(,documentation)))))
(defmethod generate-code ((element protocol-variable))
(with-accessors
((name name) (value-type value-type)
(initial-value initial-value))
element
(let ((documentation (docstring element)))
`(,@(when (and (declaim-type-p element) (not (eq value-type 't)))
`((declaim (type ,value-type ,name))))
(defvar ,name ,@(when (slot-boundp element '%initial-value)
`(,(initial-value element))))
,@(when documentation
`((setf (documentation ',name 'variable) ,documentation)))))))
(defmethod protocol-element-boundp ((element protocol-variable))
(if (slot-boundp element '%initial-value)
(values t t)
(values nil t)))
(defmethod protocol-element-makunbound ((element protocol-variable))
(when (slot-boundp element '%initial-value)
(slot-makunbound element '%initial-value))
element)
(defmethod remove-protocol-element ((element protocol-variable))
(let ((name (name element)))
(setf (documentation name 'function) nil)
(makunbound name)))
| null | https://raw.githubusercontent.com/phoe/protest/be885130044d9950758a2d1726246c4c114692c1/src/protocol/elements/variable.lisp | lisp | src/protocol/elements/variable.lisp |
(in-package #:protest/protocol)
(defclass protocol-variable (protocol-data-type)
((%name :reader name
:initarg :name
:initform (error "Must provide NAME."))
(%value-type :accessor value-type
:initarg :value-type
:initform t)
(%initial-value :accessor initial-value
:initarg :initial-value)
(%declaim-type-p :accessor declaim-type-p
:initform t))
(:documentation
"Describes a protocol variable that is a part of a protocol.
\
The form for a protocol variable consists of the following subforms:
* NAME - mandatory, must be a symbol. Denotes the name of the variable.
* VALUE-TYPE - optional, must be a valid type specifier. Denotes the type of
the value bound to the variable. If not passed, the variable type will not be
declaimed.
* INITIAL-VALUE - optional. Denotes the default value that the variable will be
bound to at the moment of executing the protocol. If not passed, the variable
will be unbound."))
(defmethod keyword-element-class ((keyword (eql :variable)))
(find-class 'protocol-variable))
(defmethod generate-element-using-class
((class (eql (find-class 'protocol-variable)))
details &optional (declaim-type-p t))
(destructuring-bind (name . rest) details
(declare (ignore rest))
(assert (and (not (null name)) (symbolp name)) ()
"Wrong thing to be a variable name: ~S" name)
(let ((element (make-instance class :name name)))
(setf (declaim-type-p element) declaim-type-p)
(when (<= 2 (length details))
(let ((type (second details)))
(setf (value-type element) type)))
(when (<= 3 (length details))
(let ((initial-value (third details)))
(unless (typep initial-value (second details))
(protocol-error "The provided initial value, ~S, is not of the ~
provided type ~S." (value-type element)) initial-value)
(setf (initial-value element) initial-value)))
element)))
(defmethod embed-documentation ((element protocol-variable) (string string))
(setf (documentation (name element) 'variable) string))
(defmethod generate-forms ((element protocol-variable))
(let* ((name (name element))
(type (value-type element))
(documentation (docstring element)))
`((:variable ,name ,@(unless (eq type 't) `(,type))
,@(when (slot-boundp element '%initial-value)
`(,(initial-value element))))
,@(when documentation `(,documentation)))))
(defmethod generate-code ((element protocol-variable))
(with-accessors
((name name) (value-type value-type)
(initial-value initial-value))
element
(let ((documentation (docstring element)))
`(,@(when (and (declaim-type-p element) (not (eq value-type 't)))
`((declaim (type ,value-type ,name))))
(defvar ,name ,@(when (slot-boundp element '%initial-value)
`(,(initial-value element))))
,@(when documentation
`((setf (documentation ',name 'variable) ,documentation)))))))
(defmethod protocol-element-boundp ((element protocol-variable))
(if (slot-boundp element '%initial-value)
(values t t)
(values nil t)))
(defmethod protocol-element-makunbound ((element protocol-variable))
(when (slot-boundp element '%initial-value)
(slot-makunbound element '%initial-value))
element)
(defmethod remove-protocol-element ((element protocol-variable))
(let ((name (name element)))
(setf (documentation name 'function) nil)
(makunbound name)))
|
59c37379f89c8923b3d8c875986dfb4c293483fe8dfa47f863e787bfc91c079d | FranklinChen/hugs98-plus-Sep2006 | PixelTransfer.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer
Copyright : ( c ) 2002 - 2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
This module corresponds to a part of section 3.6.1 ( Pixel Storage Modes ) of
the OpenGL 1.5 specs .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer (
PixelTransferStage(..),
mapColor, mapStencil, indexShift, indexOffset, depthScale, depthBias,
rgbaScale, rgbaBias
) where
import Graphics.Rendering.OpenGL.GL.Capability (
marshalCapability, unmarshalCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes (
GLenum, GLint, GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetMapColor,GetMapStencil,GetIndexShift,GetIndexOffset,
GetRedScale,GetGreenScale,GetBlueScale,GetAlphaScale,GetDepthScale,
GetRedBias,GetGreenBias,GetBlueBias,GetAlphaBias,GetDepthBias,
GetPostConvolutionRedScale,GetPostConvolutionGreenScale,
GetPostConvolutionBlueScale,GetPostConvolutionAlphaScale,
GetPostConvolutionRedBias,GetPostConvolutionGreenBias,
GetPostConvolutionBlueBias,GetPostConvolutionAlphaBias,
GetPostColorMatrixRedScale,GetPostColorMatrixGreenScale,
GetPostColorMatrixBlueScale,GetPostColorMatrixAlphaScale,
GetPostColorMatrixRedBias,GetPostColorMatrixGreenBias,
GetPostColorMatrixBlueBias,GetPostColorMatrixAlphaBias),
getBoolean1, getInteger1, getFloat1 )
import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar )
import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) )
--------------------------------------------------------------------------------
data PixelTransfer =
MapColor
| MapStencil
| IndexShift
| IndexOffset
| RedScale
| RedBias
| GreenScale
| GreenBias
| BlueScale
| BlueBias
| AlphaScale
| AlphaBias
| DepthScale
| DepthBias
| PostConvolutionRedScale
| PostConvolutionGreenScale
| PostConvolutionBlueScale
| PostConvolutionAlphaScale
| PostConvolutionRedBias
| PostConvolutionGreenBias
| PostConvolutionBlueBias
| PostConvolutionAlphaBias
| PostColorMatrixRedScale
| PostColorMatrixGreenScale
| PostColorMatrixBlueScale
| PostColorMatrixAlphaScale
| PostColorMatrixRedBias
| PostColorMatrixGreenBias
| PostColorMatrixBlueBias
| PostColorMatrixAlphaBias
marshalPixelTransfer :: PixelTransfer -> GLenum
marshalPixelTransfer x = case x of
MapColor -> 0xd10
MapStencil -> 0xd11
IndexShift -> 0xd12
IndexOffset -> 0xd13
RedScale -> 0xd14
RedBias -> 0xd15
GreenScale -> 0xd18
GreenBias -> 0xd19
BlueScale -> 0xd1a
BlueBias -> 0xd1b
AlphaScale -> 0xd1c
AlphaBias -> 0xd1d
DepthScale -> 0xd1e
DepthBias -> 0xd1f
PostConvolutionRedScale -> 0x801c
PostConvolutionGreenScale -> 0x801d
PostConvolutionBlueScale -> 0x801e
PostConvolutionAlphaScale -> 0x801f
PostConvolutionRedBias -> 0x8020
PostConvolutionGreenBias -> 0x8021
PostConvolutionBlueBias -> 0x8022
PostConvolutionAlphaBias -> 0x8023
PostColorMatrixRedScale -> 0x80b4
PostColorMatrixGreenScale -> 0x80b5
PostColorMatrixBlueScale -> 0x80b6
PostColorMatrixAlphaScale -> 0x80b7
PostColorMatrixRedBias -> 0x80b8
PostColorMatrixGreenBias -> 0x80b9
PostColorMatrixBlueBias -> 0x80ba
PostColorMatrixAlphaBias -> 0x80bb
--------------------------------------------------------------------------------
data PixelTransferStage =
PreConvolution
| PostConvolution
| PostColorMatrix
deriving ( Eq, Ord, Show )
stageToGetScales ::
PixelTransferStage
-> (GetPName, GetPName, GetPName, GetPName)
stageToGetScales s = case s of
PreConvolution -> (GetRedScale,
GetGreenScale,
GetBlueScale,
GetAlphaScale)
PostConvolution -> (GetPostConvolutionRedScale,
GetPostConvolutionGreenScale,
GetPostConvolutionBlueScale,
GetPostConvolutionAlphaScale)
PostColorMatrix -> (GetPostColorMatrixRedScale,
GetPostColorMatrixGreenScale,
GetPostColorMatrixBlueScale,
GetPostColorMatrixAlphaScale)
stageToSetScales ::
PixelTransferStage
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
stageToSetScales s = case s of
PreConvolution -> (RedScale,
GreenScale,
BlueScale,
AlphaScale)
PostConvolution -> (PostConvolutionRedScale,
PostConvolutionGreenScale,
PostConvolutionBlueScale,
PostConvolutionAlphaScale)
PostColorMatrix -> (PostColorMatrixRedScale,
PostColorMatrixGreenScale,
PostColorMatrixBlueScale,
PostColorMatrixAlphaScale)
stageToGetBiases ::
PixelTransferStage
-> (GetPName, GetPName, GetPName, GetPName)
stageToGetBiases s = case s of
PreConvolution -> (GetRedBias,
GetGreenBias,
GetBlueBias,
GetAlphaBias)
PostConvolution -> (GetPostConvolutionRedBias,
GetPostConvolutionGreenBias,
GetPostConvolutionBlueBias,
GetPostConvolutionAlphaBias)
PostColorMatrix -> (GetPostColorMatrixRedBias,
GetPostColorMatrixGreenBias,
GetPostColorMatrixBlueBias,
GetPostColorMatrixAlphaBias)
stageToSetBiases ::
PixelTransferStage
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
stageToSetBiases s = case s of
PreConvolution -> (RedBias,
GreenBias,
BlueBias,
AlphaBias)
PostConvolution -> (PostConvolutionRedBias,
PostConvolutionGreenBias,
PostConvolutionBlueBias,
PostConvolutionAlphaBias)
PostColorMatrix -> (PostColorMatrixRedBias,
PostColorMatrixGreenBias,
PostColorMatrixBlueBias,
PostColorMatrixAlphaBias)
--------------------------------------------------------------------------------
mapColor :: StateVar Capability
mapColor = pixelTransferb GetMapColor MapColor
mapStencil :: StateVar Capability
mapStencil = pixelTransferb GetMapStencil MapStencil
indexShift :: StateVar GLint
indexShift = pixelTransferi GetIndexShift IndexShift
indexOffset :: StateVar GLint
indexOffset = pixelTransferi GetIndexOffset IndexOffset
depthScale :: StateVar GLfloat
depthScale = pixelTransferf GetDepthScale DepthScale
depthBias :: StateVar GLfloat
depthBias = pixelTransferf GetDepthBias DepthBias
rgbaScale :: PixelTransferStage -> StateVar (Color4 GLfloat)
rgbaScale s = pixelTransfer4f (stageToGetScales s) (stageToSetScales s)
rgbaBias :: PixelTransferStage -> StateVar (Color4 GLfloat)
rgbaBias s = pixelTransfer4f (stageToGetBiases s) (stageToSetBiases s)
--------------------------------------------------------------------------------
pixelTransferb :: GetPName -> PixelTransfer -> StateVar Capability
pixelTransferb pn pt =
makeStateVar
(getBoolean1 unmarshalCapability pn)
(glPixelTransferi (marshalPixelTransfer pt) .
fromIntegral . marshalCapability)
pixelTransferi :: GetPName -> PixelTransfer -> StateVar GLint
pixelTransferi pn pt =
makeStateVar
(getInteger1 id pn)
(glPixelTransferi (marshalPixelTransfer pt))
foreign import CALLCONV unsafe "glPixelTransferi" glPixelTransferi ::
GLenum -> GLint -> IO ()
pixelTransferf :: GetPName -> PixelTransfer -> StateVar GLfloat
pixelTransferf pn pt =
makeStateVar
(getFloat1 id pn)
(glPixelTransferf (marshalPixelTransfer pt))
pixelTransfer4f ::
(GetPName, GetPName, GetPName, GetPName)
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
-> StateVar (Color4 GLfloat)
pixelTransfer4f (pr, pg, pb, pa) (tr, tg, tb, ta) = makeStateVar get4f set4f
where get4f = do
r <- getFloat1 id pr
g <- getFloat1 id pg
b <- getFloat1 id pb
a <- getFloat1 id pa
return $ Color4 r g b a
set4f (Color4 r g b a) = do
glPixelTransferf (marshalPixelTransfer tr) r
glPixelTransferf (marshalPixelTransfer tg) g
glPixelTransferf (marshalPixelTransfer tb) b
glPixelTransferf (marshalPixelTransfer ta) a
foreign import CALLCONV unsafe "glPixelTransferf" glPixelTransferf ::
GLenum -> GLfloat -> IO ()
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/PixelTransfer.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright : ( c ) 2002 - 2005
This module corresponds to a part of section 3.6.1 ( Pixel Storage Modes ) of
the OpenGL 1.5 specs .
module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer (
PixelTransferStage(..),
mapColor, mapStencil, indexShift, indexOffset, depthScale, depthBias,
rgbaScale, rgbaBias
) where
import Graphics.Rendering.OpenGL.GL.Capability (
marshalCapability, unmarshalCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes (
GLenum, GLint, GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetMapColor,GetMapStencil,GetIndexShift,GetIndexOffset,
GetRedScale,GetGreenScale,GetBlueScale,GetAlphaScale,GetDepthScale,
GetRedBias,GetGreenBias,GetBlueBias,GetAlphaBias,GetDepthBias,
GetPostConvolutionRedScale,GetPostConvolutionGreenScale,
GetPostConvolutionBlueScale,GetPostConvolutionAlphaScale,
GetPostConvolutionRedBias,GetPostConvolutionGreenBias,
GetPostConvolutionBlueBias,GetPostConvolutionAlphaBias,
GetPostColorMatrixRedScale,GetPostColorMatrixGreenScale,
GetPostColorMatrixBlueScale,GetPostColorMatrixAlphaScale,
GetPostColorMatrixRedBias,GetPostColorMatrixGreenBias,
GetPostColorMatrixBlueBias,GetPostColorMatrixAlphaBias),
getBoolean1, getInteger1, getFloat1 )
import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar )
import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) )
data PixelTransfer =
MapColor
| MapStencil
| IndexShift
| IndexOffset
| RedScale
| RedBias
| GreenScale
| GreenBias
| BlueScale
| BlueBias
| AlphaScale
| AlphaBias
| DepthScale
| DepthBias
| PostConvolutionRedScale
| PostConvolutionGreenScale
| PostConvolutionBlueScale
| PostConvolutionAlphaScale
| PostConvolutionRedBias
| PostConvolutionGreenBias
| PostConvolutionBlueBias
| PostConvolutionAlphaBias
| PostColorMatrixRedScale
| PostColorMatrixGreenScale
| PostColorMatrixBlueScale
| PostColorMatrixAlphaScale
| PostColorMatrixRedBias
| PostColorMatrixGreenBias
| PostColorMatrixBlueBias
| PostColorMatrixAlphaBias
marshalPixelTransfer :: PixelTransfer -> GLenum
marshalPixelTransfer x = case x of
MapColor -> 0xd10
MapStencil -> 0xd11
IndexShift -> 0xd12
IndexOffset -> 0xd13
RedScale -> 0xd14
RedBias -> 0xd15
GreenScale -> 0xd18
GreenBias -> 0xd19
BlueScale -> 0xd1a
BlueBias -> 0xd1b
AlphaScale -> 0xd1c
AlphaBias -> 0xd1d
DepthScale -> 0xd1e
DepthBias -> 0xd1f
PostConvolutionRedScale -> 0x801c
PostConvolutionGreenScale -> 0x801d
PostConvolutionBlueScale -> 0x801e
PostConvolutionAlphaScale -> 0x801f
PostConvolutionRedBias -> 0x8020
PostConvolutionGreenBias -> 0x8021
PostConvolutionBlueBias -> 0x8022
PostConvolutionAlphaBias -> 0x8023
PostColorMatrixRedScale -> 0x80b4
PostColorMatrixGreenScale -> 0x80b5
PostColorMatrixBlueScale -> 0x80b6
PostColorMatrixAlphaScale -> 0x80b7
PostColorMatrixRedBias -> 0x80b8
PostColorMatrixGreenBias -> 0x80b9
PostColorMatrixBlueBias -> 0x80ba
PostColorMatrixAlphaBias -> 0x80bb
data PixelTransferStage =
PreConvolution
| PostConvolution
| PostColorMatrix
deriving ( Eq, Ord, Show )
stageToGetScales ::
PixelTransferStage
-> (GetPName, GetPName, GetPName, GetPName)
stageToGetScales s = case s of
PreConvolution -> (GetRedScale,
GetGreenScale,
GetBlueScale,
GetAlphaScale)
PostConvolution -> (GetPostConvolutionRedScale,
GetPostConvolutionGreenScale,
GetPostConvolutionBlueScale,
GetPostConvolutionAlphaScale)
PostColorMatrix -> (GetPostColorMatrixRedScale,
GetPostColorMatrixGreenScale,
GetPostColorMatrixBlueScale,
GetPostColorMatrixAlphaScale)
stageToSetScales ::
PixelTransferStage
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
stageToSetScales s = case s of
PreConvolution -> (RedScale,
GreenScale,
BlueScale,
AlphaScale)
PostConvolution -> (PostConvolutionRedScale,
PostConvolutionGreenScale,
PostConvolutionBlueScale,
PostConvolutionAlphaScale)
PostColorMatrix -> (PostColorMatrixRedScale,
PostColorMatrixGreenScale,
PostColorMatrixBlueScale,
PostColorMatrixAlphaScale)
stageToGetBiases ::
PixelTransferStage
-> (GetPName, GetPName, GetPName, GetPName)
stageToGetBiases s = case s of
PreConvolution -> (GetRedBias,
GetGreenBias,
GetBlueBias,
GetAlphaBias)
PostConvolution -> (GetPostConvolutionRedBias,
GetPostConvolutionGreenBias,
GetPostConvolutionBlueBias,
GetPostConvolutionAlphaBias)
PostColorMatrix -> (GetPostColorMatrixRedBias,
GetPostColorMatrixGreenBias,
GetPostColorMatrixBlueBias,
GetPostColorMatrixAlphaBias)
stageToSetBiases ::
PixelTransferStage
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
stageToSetBiases s = case s of
PreConvolution -> (RedBias,
GreenBias,
BlueBias,
AlphaBias)
PostConvolution -> (PostConvolutionRedBias,
PostConvolutionGreenBias,
PostConvolutionBlueBias,
PostConvolutionAlphaBias)
PostColorMatrix -> (PostColorMatrixRedBias,
PostColorMatrixGreenBias,
PostColorMatrixBlueBias,
PostColorMatrixAlphaBias)
mapColor :: StateVar Capability
mapColor = pixelTransferb GetMapColor MapColor
mapStencil :: StateVar Capability
mapStencil = pixelTransferb GetMapStencil MapStencil
indexShift :: StateVar GLint
indexShift = pixelTransferi GetIndexShift IndexShift
indexOffset :: StateVar GLint
indexOffset = pixelTransferi GetIndexOffset IndexOffset
depthScale :: StateVar GLfloat
depthScale = pixelTransferf GetDepthScale DepthScale
depthBias :: StateVar GLfloat
depthBias = pixelTransferf GetDepthBias DepthBias
rgbaScale :: PixelTransferStage -> StateVar (Color4 GLfloat)
rgbaScale s = pixelTransfer4f (stageToGetScales s) (stageToSetScales s)
rgbaBias :: PixelTransferStage -> StateVar (Color4 GLfloat)
rgbaBias s = pixelTransfer4f (stageToGetBiases s) (stageToSetBiases s)
pixelTransferb :: GetPName -> PixelTransfer -> StateVar Capability
pixelTransferb pn pt =
makeStateVar
(getBoolean1 unmarshalCapability pn)
(glPixelTransferi (marshalPixelTransfer pt) .
fromIntegral . marshalCapability)
pixelTransferi :: GetPName -> PixelTransfer -> StateVar GLint
pixelTransferi pn pt =
makeStateVar
(getInteger1 id pn)
(glPixelTransferi (marshalPixelTransfer pt))
foreign import CALLCONV unsafe "glPixelTransferi" glPixelTransferi ::
GLenum -> GLint -> IO ()
pixelTransferf :: GetPName -> PixelTransfer -> StateVar GLfloat
pixelTransferf pn pt =
makeStateVar
(getFloat1 id pn)
(glPixelTransferf (marshalPixelTransfer pt))
pixelTransfer4f ::
(GetPName, GetPName, GetPName, GetPName)
-> (PixelTransfer, PixelTransfer, PixelTransfer, PixelTransfer)
-> StateVar (Color4 GLfloat)
pixelTransfer4f (pr, pg, pb, pa) (tr, tg, tb, ta) = makeStateVar get4f set4f
where get4f = do
r <- getFloat1 id pr
g <- getFloat1 id pg
b <- getFloat1 id pb
a <- getFloat1 id pa
return $ Color4 r g b a
set4f (Color4 r g b a) = do
glPixelTransferf (marshalPixelTransfer tr) r
glPixelTransferf (marshalPixelTransfer tg) g
glPixelTransferf (marshalPixelTransfer tb) b
glPixelTransferf (marshalPixelTransfer ta) a
foreign import CALLCONV unsafe "glPixelTransferf" glPixelTransferf ::
GLenum -> GLfloat -> IO ()
|
914381394c975264ff57cf3a90b23ebeb494740936781009ad5a54b14b318c8b | ArulselvanMadhavan/haskell-first-principles | Mem.hs | module Mem where
import Data.Monoid
import Test.QuickCheck
newtype Mem s a =
Mem {
runMem :: s -> (a, s)
}
instance (Eq a, Monoid a) => Monoid (Mem s a) where
mempty = Mem (\s -> (mempty, s))
mappend f g = ( \s - > runMem f . snd . )
mappend f g =
Mem
(\s ->
let gs = runMem g s
fs = runMem f (snd gs)
emps = runMem mempty s
in case (fst fs == fst emps, fst gs == fst emps) of
(True, False) -> (fst gs, snd fs)
(_, _) -> fs)
f' = Mem $ \s -> ("hi", s + 1)
memAssoc :: (Eq a, Eq s, Monoid a) => Mem s a -> Mem s a -> Mem s a -> s -> Bool
memAssoc a b c val =
let x = runMem (a <> (b <> c)) $ val
y = runMem ((a <> b) <> c) $ val
in x == y
memLeftIdentity :: (Eq a, Eq s, Monoid a) => Mem s a -> s -> Bool
memLeftIdentity f val =
let x = runMem (f <> mempty) $ val
y = runMem f $ val
in x == y
memRightIdentity :: (Eq a, Eq s, Monoid a) => Mem s a -> s -> Bool
memRightIdentity f val =
let x = runMem f $ val
y = runMem (f <> mempty) $ val
in x == y
runTests :: IO ()
runTests = do
quickCheck ((memRightIdentity f') :: Int -> Bool)
quickCheck ((memLeftIdentity f') :: Int -> Bool)
visualTests :: IO ()
visualTests = do
let rmzero = runMem mempty 0
rmleft = runMem (f' <> mempty) 0
rmright = runMem (mempty <> f') 0
print $ rmleft
print $ rmright
print $ (rmzero :: (String, Int))
print $ rmleft == runMem f' 0
print $ rmright == runMem f' 0
| null | https://raw.githubusercontent.com/ArulselvanMadhavan/haskell-first-principles/06e0c71c502848c8e75c8109dd49c0954d815bba/chapter15/test/Mem.hs | haskell | module Mem where
import Data.Monoid
import Test.QuickCheck
newtype Mem s a =
Mem {
runMem :: s -> (a, s)
}
instance (Eq a, Monoid a) => Monoid (Mem s a) where
mempty = Mem (\s -> (mempty, s))
mappend f g = ( \s - > runMem f . snd . )
mappend f g =
Mem
(\s ->
let gs = runMem g s
fs = runMem f (snd gs)
emps = runMem mempty s
in case (fst fs == fst emps, fst gs == fst emps) of
(True, False) -> (fst gs, snd fs)
(_, _) -> fs)
f' = Mem $ \s -> ("hi", s + 1)
memAssoc :: (Eq a, Eq s, Monoid a) => Mem s a -> Mem s a -> Mem s a -> s -> Bool
memAssoc a b c val =
let x = runMem (a <> (b <> c)) $ val
y = runMem ((a <> b) <> c) $ val
in x == y
memLeftIdentity :: (Eq a, Eq s, Monoid a) => Mem s a -> s -> Bool
memLeftIdentity f val =
let x = runMem (f <> mempty) $ val
y = runMem f $ val
in x == y
memRightIdentity :: (Eq a, Eq s, Monoid a) => Mem s a -> s -> Bool
memRightIdentity f val =
let x = runMem f $ val
y = runMem (f <> mempty) $ val
in x == y
runTests :: IO ()
runTests = do
quickCheck ((memRightIdentity f') :: Int -> Bool)
quickCheck ((memLeftIdentity f') :: Int -> Bool)
visualTests :: IO ()
visualTests = do
let rmzero = runMem mempty 0
rmleft = runMem (f' <> mempty) 0
rmright = runMem (mempty <> f') 0
print $ rmleft
print $ rmright
print $ (rmzero :: (String, Int))
print $ rmleft == runMem f' 0
print $ rmright == runMem f' 0
| |
a2f6a6de299a36599fd05c47ced14f3c3d808aaea4691c5db6bbe43bd9c67ab5 | minio/minio-hs | RemoveBucket.hs | #!/usr/bin/env stack
-- stack --resolver lts-14.11 runghc --package minio-hs
--
MinIO Haskell SDK , ( C ) 2017 , 2018 MinIO , Inc.
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- -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.
--
{-# LANGUAGE OverloadedStrings #-}
import Network.Minio
import Prelude
| The following example uses 's play server at
. The endpoint and associated
credentials are provided via the libary constant ,
--
> minioPlayCI : : ConnectInfo
main :: IO ()
main = do
let bucket = "my-bucket"
res <- runMinio minioPlayCI $ removeBucket bucket
print res
| null | https://raw.githubusercontent.com/minio/minio-hs/c52f2811fe8eb2a657f1467d0798067a15deb395/examples/RemoveBucket.hs | haskell | stack --resolver lts-14.11 runghc --package minio-hs
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.
# LANGUAGE OverloadedStrings #
| #!/usr/bin/env stack
MinIO Haskell SDK , ( C ) 2017 , 2018 MinIO , Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
import Network.Minio
import Prelude
| The following example uses 's play server at
. The endpoint and associated
credentials are provided via the libary constant ,
> minioPlayCI : : ConnectInfo
main :: IO ()
main = do
let bucket = "my-bucket"
res <- runMinio minioPlayCI $ removeBucket bucket
print res
|
52fe5151ff10419518ba1a57efacf852c66e40ee3d9efb733a16803508492f18 | oscoin/oscoin | Ledger.hs | # LANGUAGE UndecidableInstances #
-- | Core ledger data types.
--
module Oscoin.Data.Ledger where
-- Since the handler functions implemented in this module may
-- eventually be turned into smart contracts, we keep track of
-- all imports and try to keep them to a minimum.
import Oscoin.Prelude
( Either(..)
, Eq(..)
, Generic
, Int
, IsString
, Map
, Maybe(..)
, Monoid(..)
, Ord(..)
, Set
, Show
, Text
, Word64
, Word8
, div
, fromIntegral
, liftA2
, map
, maxBound
, mod
, show
, sum
, ($)
, (++)
, (.)
, (<$>)
, (<*>)
, (<>)
)
import Oscoin.Crypto.Blockchain (Height)
import Oscoin.Crypto.Blockchain.Block (BlockHash)
import qualified Oscoin.Crypto.Hash as Crypto
import Oscoin.Crypto.PubKey (PublicKey, Signature, Signed)
import qualified Codec.CBOR.Decoding as CBOR
import qualified Codec.CBOR.Encoding as CBOR
import Codec.Serialise (Serialise)
import qualified Codec.Serialise as CBOR
import Control.Monad.Fail (fail)
import Crypto.Data.Auth.Tree (Tree)
import qualified Crypto.Data.Auth.Tree as WorldState
import Data.ByteArray (ByteArrayAccess(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import qualified Data.Set as Set
import Numeric.Natural
-------------------------------------------------------------------------------
World State
-------------------------------------------------------------------------------
-- | The state of the world, materialized from transactions.
type WorldState c = Tree StateKey (StateVal c)
-- | State lookup key.
type StateKey = ByteString
-- | State value.
data StateVal c =
AccountVal (Account c)
| ProjectVal (Project c)
| NatVal Natural
deriving instance (Eq (AccountId c), Eq (PublicKey c)) => Eq (StateVal c)
instance Serialise (StateVal c) => ByteArrayAccess (StateVal c) where
length = fromIntegral . LBS.length . CBOR.serialise
withByteArray sv f = withByteArray (LBS.toStrict (CBOR.serialise sv)) f
instance
( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
, Ord (AccountId c)
) => Serialise (StateVal c)
where
encode (AccountVal acc) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> CBOR.encode acc
encode (ProjectVal proj) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 1
<> CBOR.encode proj
encode (NatVal n) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 2
<> CBOR.encode n
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(2, 0) -> AccountVal <$> CBOR.decode
(2, 1) -> ProjectVal . mkProject <$> CBOR.decode
(2, 2) -> NatVal <$> CBOR.decode
e -> fail $ "Failed decoding StateVal from CBOR: " ++ show e
-- | Like 'Map.adjust', but for 'WorldState'.
adjust :: (StateVal c -> StateVal c) -> StateKey -> WorldState c -> WorldState c
adjust f k ws =
case WorldState.lookup k ws of
Just v -> WorldState.insert k (f v) ws
Nothing -> ws
-- | Like 'Map.alter', but for 'WorldState'.
alter
:: (Maybe (StateVal c) -> Maybe (StateVal c))
-> StateKey
-> WorldState c
-> WorldState c
alter f k ws =
case f (WorldState.lookup k ws) of
Just v -> WorldState.insert k v ws
Nothing -> WorldState.delete k ws
-- | /O(n)/. Returns the total supply of tokens in the ledger.
balanceTotal :: WorldState c -> Balance
balanceTotal ws = sum $ map f (WorldState.toList ws)
where
f (_, AccountVal acc) = accountBalance acc
f _ = 0
-------------------------------------------------------------------------------
Core types
-------------------------------------------------------------------------------
-- | A balance of oscoin in the smallest denomination.
type Balance = Word64
-- | An account nonce to prevent replay attacks.
type Nonce = Word64
-- | An account identifier.
type AccountId c = Crypto.ShortHash c
-- | An account which holds a balance.
data Account c = Account
{ accountId :: AccountId c
-- ^ The account identifier.
, accountBalance :: Balance
-- ^ The oscoin balance.
, accountNonce :: Nonce
-- ^ The nonce is equal to the number of transactions
-- made from this account.
}
deriving instance (Eq (AccountId c)) => Eq (Account c)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (Account c)
where
encode Account{..} =
CBOR.encodeListLen 4
<> CBOR.encodeWord 0
<> CBOR.encode accountId
<> CBOR.encode accountBalance
<> CBOR.encode accountNonce
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(4, 0) ->
Account
<$> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
e -> fail $ "Failed decoding Account from CBOR: " ++ show e
mkAccount :: AccountId c -> Account c
mkAccount acc = Account
{ accountId = acc
, accountBalance = 0
, accountNonce = 0
}
| Convert an ' AccountId ' into a StateKey
accountKey
:: CBOR.Serialise (AccountId c)
=> AccountId c
-> StateKey
accountKey = LBS.toStrict . CBOR.serialise
| Convert a ' PublicKey ' to an ' AccountId ' .
toAccountId :: Crypto.Hashable c (PublicKey c) => PublicKey c -> AccountId c
toAccountId = Crypto.fromShortHashed . Crypto.shortHash
-------------------------------------------------------------------------------
-- | A number of blocks representing a long period of time.
type Epoch = Natural
-- | A number of epochs.
type Epochs = Natural
-- | A contribution signed-off by a maintainer.
type Signoff c = Signed c (Contribution c)
-------------------------------------------------------------------------------
Checkpoints
-------------------------------------------------------------------------------
-- | A project checkpoint.
data Checkpoint c = Checkpoint
{ checkpointNumber :: Natural
^ The checkpoint number , starting from zero .
, checkpointStateHash :: Crypto.Hash c
-- ^ The hash of the project state at this checkpoint.
, checkpointContributions :: [Contribution c]
-- ^ The new contributions since the last checkpoint.
-- Contributions /must/ be hash-linked to maintain the integrity of the list.
-- See 'Contribution' for details.
, checkpointDependencies :: [DependencyUpdate c]
-- ^ Updates to the dependencies since the last checkpoint.
}
deriving instance
( Eq (AccountId c)
, Eq (PublicKey c)
, Eq (Crypto.Hash c)
, Eq (Signature c)
) => Eq (Checkpoint c)
instance
( Eq (AccountId c)
, Eq (PublicKey c)
, Eq (Crypto.Hash c)
, Eq (Signature c)
) => Ord (Checkpoint c)
where
a <= b = checkpointNumber a <= checkpointNumber b
-- | A contribution to a project.
data Contribution c = Contribution
{ contribHash :: Crypto.Hash c
-- ^ The hash of the off-chain contribution artefact.
, contribParentHash :: Maybe (Crypto.Hash c)
^ The parent contribution , or ' Nothing ' if it 's the first .
-- Matches with 'contribHash', forming a hash-linked list.
, contribAccount :: AccountId c
-- ^ The account id of the contributor.
, contribSignoff :: Maybe (Signoff c)
-- ^ An optional sign-off signature.
, contribLabels :: Set Label
-- ^ A set of labels used to categorize the contribution.
} deriving (Generic)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (Contribution c)
where
encode Contribution{..} =
CBOR.encodeListLen 6
<> CBOR.encodeWord 0
<> CBOR.encode contribHash
<> CBOR.encode contribParentHash
<> CBOR.encode contribAccount
<> CBOR.encode contribSignoff
<> CBOR.encode contribLabels
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(6, 0) ->
Contribution
<$> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
e -> fail $ "Failed decoding Contribution from CBOR: " ++ show e
-- | A label used to tag a contribution.
newtype Label = Label Word8
deriving (Show, Eq, Ord, Serialise)
-------------------------------------------------------------------------------
deriving instance
( Show (Signature c)
, Show (BlockHash c)
, Show (AccountId c)
, Crypto.HasHashing c
) => Show (Contribution c)
deriving instance
( Eq (Signature c)
, Eq (BlockHash c)
, Eq (AccountId c)
) => Eq (Contribution c)
deriving instance
( Ord (Signature c)
, Ord (BlockHash c)
, Ord (AccountId c)
) => Ord (Contribution c)
-------------------------------------------------------------------------------
-- | An update to a project dependency.
data DependencyUpdate c =
Depend (AccountId c) (Crypto.Hash c)
-- ^ Start depending on a project starting from the given state hash.
| Undepend (AccountId c)
-- ^ Stop depending on a project.
deriving (Generic)
deriving instance (Eq (Crypto.Hash c), Eq (AccountId c)) => Eq (DependencyUpdate c)
deriving instance (Ord (Crypto.Hash c), Ord (AccountId c)) => Ord (DependencyUpdate c)
deriving instance (Show (Crypto.Hash c), Show (AccountId c)) => Show (DependencyUpdate c)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (DependencyUpdate c)
where
encode (Depend proj hsh) =
CBOR.encodeListLen 3
<> CBOR.encodeWord 0
<> CBOR.encode proj
<> CBOR.encode hsh
encode (Undepend proj) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 1
<> CBOR.encode proj
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(3, 0) -> Depend <$> CBOR.decode <*> CBOR.decode
(2, 1) -> Undepend <$> CBOR.decode
e -> fail $ "Failed decoding DependencyUpdate from CBOR: " ++ show e
-- | Additional signatures used to authorize a transaction in a
-- /multi-sig/ scenario.
newtype Signatures c = Signatures [Signed () c]
-------------------------------------------------------------------------------
Project
-------------------------------------------------------------------------------
-- | A project.
data Project c = Project
{ pAccount :: Account c
-- ^ The project account or /fund/.
, pMaintainers :: Map (AccountId c) (Member c)
, pContributors :: Map (AccountId c) (Member c)
, pSupporters :: Map (AccountId c) (Member c)
, pDependencies :: Map (AccountId c) (Dependency c)
, pCheckpoints :: Set (Checkpoint c)
-- | Contract
, pSendTransfer :: SendTransfer' c
, pReceiveTransfer :: ReceiveTransfer' c
, pReceiveReward :: ReceiveReward' c
, pCheckpoint :: Checkpoint' c
, pUnregister :: Unregister' c
, pAuthorize :: Authorize' c
, pDeauthorize :: Deauthorize' c
, pUpdateContract :: UpdateContract' c
}
instance
( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
, Ord (AccountId c)
) => Serialise (Project c)
where
encode Project{..} =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> CBOR.encode pAccount
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(2, 0) -> mkProject <$> CBOR.decode
e -> fail $ "Failed decoding Project from CBOR: " ++ show e
instance (Eq (AccountId c)) => Eq (Project c) where
(==) a b = projectId a == projectId b
mkProject :: (Ord (AccountId c)) => Account c -> Project c
mkProject acc = Project
{ pAccount = acc
, pMaintainers = mempty
, pContributors = mempty
, pSupporters = mempty
, pDependencies = mempty
, pCheckpoints = Set.empty
, pSendTransfer = defaultSendTransfer
, pReceiveTransfer = defaultReceiveTransfer
, pReceiveReward = defaultReceiveReward
, pCheckpoint = defaultCheckpoint
, pUnregister = defaultUnregister
, pAuthorize = defaultAuthorize
, pDeauthorize = defaultDeauthorize
, pUpdateContract = defaultUpdateContract
}
-- | Get the account id of a project.
projectId :: Project c -> AccountId c
projectId = accountId . pAccount
| A delegation of oscoin between two accounts . Allows members to become
-- /supporters/ by delegating their voting rights to a project. Allows projects
-- to use the delegated tokens to vote.
data Delegation c = Delegation
{ delegDelegator :: AccountId c
-- ^ Account delegating.
, delegReceiver :: AccountId c
-- ^ Account receiving the delegation.
, delegBalance :: Balance
-- ^ Balance being delegated.
, delegCommitment :: Height
-- ^ Time commitment of the delegation.
, delegSince :: Height
-- ^ Starting time of the delegation.
}
-- | A member of a project. Includes maintainers, contributors and supporters.
data Member c = Member
{ memberAccount :: AccountId c
, memberDelegation :: Maybe (Delegation c)
, memberSince :: Epoch
, memberContributions :: Set (Contribution c)
}
instance (Eq (AccountId c)) => Eq (Member c) where
(==) a b = memberAccount a == memberAccount b
mkMember
:: AccountId c -> Epoch -> Member c
mkMember acc e = Member
{ memberAccount = acc
, memberDelegation = Nothing
, memberSince = e
, memberContributions = Set.empty
}
| A dependency between two projects .
data Dependency c = Dependency
{ depFrom :: AccountId c
, depTo :: AccountId c
, depHash :: Crypto.Hash c
-- ^ Hash of the checkpoint state being depended on.
} deriving (Generic)
-- | Identifies a contract handler.
data Handler =
SendTransferHandler
| ReceiveRewardHandler
| ReceiveTransferHandler
| CheckpointHandler
| AuthorizeHandler
| DeauthorizeHandler
| UnregisterHandler
| UpdateContractHandler
deriving (Show, Eq, Ord)
-- | Dictionary used to parametrize a handler.
type HandlerParams = Map ParamKey ParamVal
-- | Parameter key.
type ParamKey = Text
-- | Parameter value.
data ParamVal =
Integer Int
-- ^ Expresses positive or negative whole numbers.
| Rational Int Int
^ Expresses ratios , eg . 1/2 .
deriving (Show, Eq, Ord)
-------------------------------------------------------------------------------
newtype HandlerError = HandlerError Text
deriving (Show, Eq, Ord, IsString)
-------------------------------------------------------------------------------
SendTransfer
-------------------------------------------------------------------------------
type SendTransfer' c =
Account c -- ^ Transaction signer
-> AccountId c -- ^ Sender
-> AccountId c -- ^ Receiver
-> Balance -- ^ Balance to transfer
-> Signatures c -- ^ Sign-offs
-> Either HandlerError ()
defaultSendTransfer :: SendTransfer' c
defaultSendTransfer = mkSendTransfer maxBound
mkSendTransfer :: Balance -> SendTransfer' c
mkSendTransfer maxBalance = sendTransfer
where
sendTransfer _signer _from _to bal _sigs =
if bal <= maxBalance
then Right ()
else Left "Max balance exceeded for transfer"
-------------------------------------------------------------------------------
-- ReceiveTransfer
-------------------------------------------------------------------------------
type ReceiveTransfer' c =
Balance
-> AccountId c -- ^ Sender
-> Project c
-> [(AccountId c, Balance)]
defaultReceiveTransfer :: ReceiveTransfer' c
defaultReceiveTransfer = depositToFund
mkReceiveTransfer :: ReceiveTransfer' c
mkReceiveTransfer _ _ _ = []
depositToFund :: ReceiveTransfer' c
depositToFund bal _ p =
[(projectId p, bal)]
-------------------------------------------------------------------------------
-- ReceiveReward
-------------------------------------------------------------------------------
type ReceiveReward' c =
Balance -- ^ The balance being rewarded
-> Epoch -- ^ The current epoch
-> Project c -- ^ The project dictionary
-> [(AccountId c, Balance)] -- ^ A balance distribution
-- | By default, burn the reward.
defaultReceiveReward :: ReceiveReward' c
defaultReceiveReward = burnReward
-- | Burn the reward!
burnReward :: ReceiveReward' c
burnReward _ _ _ = []
-- | Distribute reward equally to all project members. Store any remainder in the project fund.
distributeRewardEqually :: Ord (AccountId c) => ReceiveReward' c
distributeRewardEqually bal _epoch p@Project{..} =
let members = Map.keysSet $ pContributors <> pMaintainers <> pSupporters
(dist, rem) = distribute bal members
in (projectId p, rem) : dist
-------------------------------------------------------------------------------
Checkpoint
-------------------------------------------------------------------------------
type Checkpoint' c =
Checkpoint c -- ^ Checkpoint data
-> Project c -- ^ Project data
-> Account c -- ^ Transaction signer
-> Either HandlerError ()
-- | By default, authorize any checkpoint signed by a maintainer.
defaultCheckpoint :: Ord (AccountId c) => Checkpoint' c
defaultCheckpoint _ = requireMaintainer
-------------------------------------------------------------------------------
Unregister
-------------------------------------------------------------------------------
type Unregister' c =
Project c -- ^ Project data
-> Account c -- ^ Transaction signer
-> Either HandlerError ()
defaultUnregister :: Ord (AccountId c) => Unregister' c
defaultUnregister = requireMaintainer
-------------------------------------------------------------------------------
Authorize
-------------------------------------------------------------------------------
type Authorize' c =
AccountId c -- ^ Key to be added
-> Project c -- ^ Project data
-> Account c -- ^ Transaction signer
-> Either HandlerError ()
defaultAuthorize :: Ord (AccountId c) => Authorize' c
defaultAuthorize _ = requireMaintainer
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
type Deauthorize' c =
AccountId c -- ^ Key to be removed
-> Project c -- ^ Project data
-> Account c -- ^ Transaction signer
-> Either HandlerError ()
defaultDeauthorize :: Ord (AccountId c) => Deauthorize' c
defaultDeauthorize _ = requireMaintainer
-------------------------------------------------------------------------------
UpdateContract
-------------------------------------------------------------------------------
type UpdateContract' c =
Handler -- ^ Handler to be updated
-> HandlerParams -- ^ New handler parameters
-> Project c -- ^ Project data
-> Account c -- ^ Transaction signer
-> Either HandlerError ()
defaultUpdateContract :: Ord (AccountId c) => UpdateContract' c
defaultUpdateContract _ _ = requireMaintainer
-------------------------------------------------------------------------------
-- Utility functions
-------------------------------------------------------------------------------
-- | Distribute a balance equally to a set of accounts, returning the remainder.
distribute :: Balance -> Set (AccountId c) -> ([(AccountId c, Balance)], Balance)
distribute bal accs =
([(acc, share) | acc <- Set.toList accs], remainder)
where
share = bal `div` fromIntegral (Set.size accs)
remainder = bal `mod` share
-- | Return 'Right ()' if the account is a project maintainer and 'Left' otherwise.
requireMaintainer
:: Ord (AccountId c)
=> Project c
-> Account c
-> Either HandlerError ()
requireMaintainer Project{..} Account{..} =
if Map.member accountId pMaintainers
then Right ()
else Left (HandlerError "Signer must be a project maintainer")
| null | https://raw.githubusercontent.com/oscoin/oscoin/2eb5652c9999dd0f30c70b3ba6b638156c74cdb1/src/Oscoin/Data/Ledger.hs | haskell | | Core ledger data types.
Since the handler functions implemented in this module may
eventually be turned into smart contracts, we keep track of
all imports and try to keep them to a minimum.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| The state of the world, materialized from transactions.
| State lookup key.
| State value.
| Like 'Map.adjust', but for 'WorldState'.
| Like 'Map.alter', but for 'WorldState'.
| /O(n)/. Returns the total supply of tokens in the ledger.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A balance of oscoin in the smallest denomination.
| An account nonce to prevent replay attacks.
| An account identifier.
| An account which holds a balance.
^ The account identifier.
^ The oscoin balance.
^ The nonce is equal to the number of transactions
made from this account.
-----------------------------------------------------------------------------
| A number of blocks representing a long period of time.
| A number of epochs.
| A contribution signed-off by a maintainer.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A project checkpoint.
^ The hash of the project state at this checkpoint.
^ The new contributions since the last checkpoint.
Contributions /must/ be hash-linked to maintain the integrity of the list.
See 'Contribution' for details.
^ Updates to the dependencies since the last checkpoint.
| A contribution to a project.
^ The hash of the off-chain contribution artefact.
Matches with 'contribHash', forming a hash-linked list.
^ The account id of the contributor.
^ An optional sign-off signature.
^ A set of labels used to categorize the contribution.
| A label used to tag a contribution.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| An update to a project dependency.
^ Start depending on a project starting from the given state hash.
^ Stop depending on a project.
| Additional signatures used to authorize a transaction in a
/multi-sig/ scenario.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A project.
^ The project account or /fund/.
| Contract
| Get the account id of a project.
/supporters/ by delegating their voting rights to a project. Allows projects
to use the delegated tokens to vote.
^ Account delegating.
^ Account receiving the delegation.
^ Balance being delegated.
^ Time commitment of the delegation.
^ Starting time of the delegation.
| A member of a project. Includes maintainers, contributors and supporters.
^ Hash of the checkpoint state being depended on.
| Identifies a contract handler.
| Dictionary used to parametrize a handler.
| Parameter key.
| Parameter value.
^ Expresses positive or negative whole numbers.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Transaction signer
^ Sender
^ Receiver
^ Balance to transfer
^ Sign-offs
-----------------------------------------------------------------------------
ReceiveTransfer
-----------------------------------------------------------------------------
^ Sender
-----------------------------------------------------------------------------
ReceiveReward
-----------------------------------------------------------------------------
^ The balance being rewarded
^ The current epoch
^ The project dictionary
^ A balance distribution
| By default, burn the reward.
| Burn the reward!
| Distribute reward equally to all project members. Store any remainder in the project fund.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Checkpoint data
^ Project data
^ Transaction signer
| By default, authorize any checkpoint signed by a maintainer.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Project data
^ Transaction signer
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Key to be added
^ Project data
^ Transaction signer
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Key to be removed
^ Project data
^ Transaction signer
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
^ Handler to be updated
^ New handler parameters
^ Project data
^ Transaction signer
-----------------------------------------------------------------------------
Utility functions
-----------------------------------------------------------------------------
| Distribute a balance equally to a set of accounts, returning the remainder.
| Return 'Right ()' if the account is a project maintainer and 'Left' otherwise. | # LANGUAGE UndecidableInstances #
module Oscoin.Data.Ledger where
import Oscoin.Prelude
( Either(..)
, Eq(..)
, Generic
, Int
, IsString
, Map
, Maybe(..)
, Monoid(..)
, Ord(..)
, Set
, Show
, Text
, Word64
, Word8
, div
, fromIntegral
, liftA2
, map
, maxBound
, mod
, show
, sum
, ($)
, (++)
, (.)
, (<$>)
, (<*>)
, (<>)
)
import Oscoin.Crypto.Blockchain (Height)
import Oscoin.Crypto.Blockchain.Block (BlockHash)
import qualified Oscoin.Crypto.Hash as Crypto
import Oscoin.Crypto.PubKey (PublicKey, Signature, Signed)
import qualified Codec.CBOR.Decoding as CBOR
import qualified Codec.CBOR.Encoding as CBOR
import Codec.Serialise (Serialise)
import qualified Codec.Serialise as CBOR
import Control.Monad.Fail (fail)
import Crypto.Data.Auth.Tree (Tree)
import qualified Crypto.Data.Auth.Tree as WorldState
import Data.ByteArray (ByteArrayAccess(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import qualified Data.Set as Set
import Numeric.Natural
World State
type WorldState c = Tree StateKey (StateVal c)
type StateKey = ByteString
data StateVal c =
AccountVal (Account c)
| ProjectVal (Project c)
| NatVal Natural
deriving instance (Eq (AccountId c), Eq (PublicKey c)) => Eq (StateVal c)
instance Serialise (StateVal c) => ByteArrayAccess (StateVal c) where
length = fromIntegral . LBS.length . CBOR.serialise
withByteArray sv f = withByteArray (LBS.toStrict (CBOR.serialise sv)) f
instance
( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
, Ord (AccountId c)
) => Serialise (StateVal c)
where
encode (AccountVal acc) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> CBOR.encode acc
encode (ProjectVal proj) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 1
<> CBOR.encode proj
encode (NatVal n) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 2
<> CBOR.encode n
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(2, 0) -> AccountVal <$> CBOR.decode
(2, 1) -> ProjectVal . mkProject <$> CBOR.decode
(2, 2) -> NatVal <$> CBOR.decode
e -> fail $ "Failed decoding StateVal from CBOR: " ++ show e
adjust :: (StateVal c -> StateVal c) -> StateKey -> WorldState c -> WorldState c
adjust f k ws =
case WorldState.lookup k ws of
Just v -> WorldState.insert k (f v) ws
Nothing -> ws
alter
:: (Maybe (StateVal c) -> Maybe (StateVal c))
-> StateKey
-> WorldState c
-> WorldState c
alter f k ws =
case f (WorldState.lookup k ws) of
Just v -> WorldState.insert k v ws
Nothing -> WorldState.delete k ws
balanceTotal :: WorldState c -> Balance
balanceTotal ws = sum $ map f (WorldState.toList ws)
where
f (_, AccountVal acc) = accountBalance acc
f _ = 0
Core types
type Balance = Word64
type Nonce = Word64
type AccountId c = Crypto.ShortHash c
data Account c = Account
{ accountId :: AccountId c
, accountBalance :: Balance
, accountNonce :: Nonce
}
deriving instance (Eq (AccountId c)) => Eq (Account c)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (Account c)
where
encode Account{..} =
CBOR.encodeListLen 4
<> CBOR.encodeWord 0
<> CBOR.encode accountId
<> CBOR.encode accountBalance
<> CBOR.encode accountNonce
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(4, 0) ->
Account
<$> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
e -> fail $ "Failed decoding Account from CBOR: " ++ show e
mkAccount :: AccountId c -> Account c
mkAccount acc = Account
{ accountId = acc
, accountBalance = 0
, accountNonce = 0
}
| Convert an ' AccountId ' into a StateKey
accountKey
:: CBOR.Serialise (AccountId c)
=> AccountId c
-> StateKey
accountKey = LBS.toStrict . CBOR.serialise
| Convert a ' PublicKey ' to an ' AccountId ' .
toAccountId :: Crypto.Hashable c (PublicKey c) => PublicKey c -> AccountId c
toAccountId = Crypto.fromShortHashed . Crypto.shortHash
type Epoch = Natural
type Epochs = Natural
type Signoff c = Signed c (Contribution c)
Checkpoints
data Checkpoint c = Checkpoint
{ checkpointNumber :: Natural
^ The checkpoint number , starting from zero .
, checkpointStateHash :: Crypto.Hash c
, checkpointContributions :: [Contribution c]
, checkpointDependencies :: [DependencyUpdate c]
}
deriving instance
( Eq (AccountId c)
, Eq (PublicKey c)
, Eq (Crypto.Hash c)
, Eq (Signature c)
) => Eq (Checkpoint c)
instance
( Eq (AccountId c)
, Eq (PublicKey c)
, Eq (Crypto.Hash c)
, Eq (Signature c)
) => Ord (Checkpoint c)
where
a <= b = checkpointNumber a <= checkpointNumber b
data Contribution c = Contribution
{ contribHash :: Crypto.Hash c
, contribParentHash :: Maybe (Crypto.Hash c)
^ The parent contribution , or ' Nothing ' if it 's the first .
, contribAccount :: AccountId c
, contribSignoff :: Maybe (Signoff c)
, contribLabels :: Set Label
} deriving (Generic)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (Contribution c)
where
encode Contribution{..} =
CBOR.encodeListLen 6
<> CBOR.encodeWord 0
<> CBOR.encode contribHash
<> CBOR.encode contribParentHash
<> CBOR.encode contribAccount
<> CBOR.encode contribSignoff
<> CBOR.encode contribLabels
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(6, 0) ->
Contribution
<$> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
<*> CBOR.decode
e -> fail $ "Failed decoding Contribution from CBOR: " ++ show e
newtype Label = Label Word8
deriving (Show, Eq, Ord, Serialise)
deriving instance
( Show (Signature c)
, Show (BlockHash c)
, Show (AccountId c)
, Crypto.HasHashing c
) => Show (Contribution c)
deriving instance
( Eq (Signature c)
, Eq (BlockHash c)
, Eq (AccountId c)
) => Eq (Contribution c)
deriving instance
( Ord (Signature c)
, Ord (BlockHash c)
, Ord (AccountId c)
) => Ord (Contribution c)
data DependencyUpdate c =
Depend (AccountId c) (Crypto.Hash c)
| Undepend (AccountId c)
deriving (Generic)
deriving instance (Eq (Crypto.Hash c), Eq (AccountId c)) => Eq (DependencyUpdate c)
deriving instance (Ord (Crypto.Hash c), Ord (AccountId c)) => Ord (DependencyUpdate c)
deriving instance (Show (Crypto.Hash c), Show (AccountId c)) => Show (DependencyUpdate c)
instance ( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
) => Serialise (DependencyUpdate c)
where
encode (Depend proj hsh) =
CBOR.encodeListLen 3
<> CBOR.encodeWord 0
<> CBOR.encode proj
<> CBOR.encode hsh
encode (Undepend proj) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 1
<> CBOR.encode proj
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(3, 0) -> Depend <$> CBOR.decode <*> CBOR.decode
(2, 1) -> Undepend <$> CBOR.decode
e -> fail $ "Failed decoding DependencyUpdate from CBOR: " ++ show e
newtype Signatures c = Signatures [Signed () c]
Project
data Project c = Project
{ pAccount :: Account c
, pMaintainers :: Map (AccountId c) (Member c)
, pContributors :: Map (AccountId c) (Member c)
, pSupporters :: Map (AccountId c) (Member c)
, pDependencies :: Map (AccountId c) (Dependency c)
, pCheckpoints :: Set (Checkpoint c)
, pSendTransfer :: SendTransfer' c
, pReceiveTransfer :: ReceiveTransfer' c
, pReceiveReward :: ReceiveReward' c
, pCheckpoint :: Checkpoint' c
, pUnregister :: Unregister' c
, pAuthorize :: Authorize' c
, pDeauthorize :: Deauthorize' c
, pUpdateContract :: UpdateContract' c
}
instance
( Serialise (Crypto.Hash c)
, Serialise (AccountId c)
, Serialise (Signature c)
, Ord (AccountId c)
) => Serialise (Project c)
where
encode Project{..} =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> CBOR.encode pAccount
decode = do
pre <- liftA2 (,) CBOR.decodeListLenCanonical CBOR.decodeWordCanonical
case pre of
(2, 0) -> mkProject <$> CBOR.decode
e -> fail $ "Failed decoding Project from CBOR: " ++ show e
instance (Eq (AccountId c)) => Eq (Project c) where
(==) a b = projectId a == projectId b
mkProject :: (Ord (AccountId c)) => Account c -> Project c
mkProject acc = Project
{ pAccount = acc
, pMaintainers = mempty
, pContributors = mempty
, pSupporters = mempty
, pDependencies = mempty
, pCheckpoints = Set.empty
, pSendTransfer = defaultSendTransfer
, pReceiveTransfer = defaultReceiveTransfer
, pReceiveReward = defaultReceiveReward
, pCheckpoint = defaultCheckpoint
, pUnregister = defaultUnregister
, pAuthorize = defaultAuthorize
, pDeauthorize = defaultDeauthorize
, pUpdateContract = defaultUpdateContract
}
projectId :: Project c -> AccountId c
projectId = accountId . pAccount
| A delegation of oscoin between two accounts . Allows members to become
data Delegation c = Delegation
{ delegDelegator :: AccountId c
, delegReceiver :: AccountId c
, delegBalance :: Balance
, delegCommitment :: Height
, delegSince :: Height
}
data Member c = Member
{ memberAccount :: AccountId c
, memberDelegation :: Maybe (Delegation c)
, memberSince :: Epoch
, memberContributions :: Set (Contribution c)
}
instance (Eq (AccountId c)) => Eq (Member c) where
(==) a b = memberAccount a == memberAccount b
mkMember
:: AccountId c -> Epoch -> Member c
mkMember acc e = Member
{ memberAccount = acc
, memberDelegation = Nothing
, memberSince = e
, memberContributions = Set.empty
}
| A dependency between two projects .
data Dependency c = Dependency
{ depFrom :: AccountId c
, depTo :: AccountId c
, depHash :: Crypto.Hash c
} deriving (Generic)
data Handler =
SendTransferHandler
| ReceiveRewardHandler
| ReceiveTransferHandler
| CheckpointHandler
| AuthorizeHandler
| DeauthorizeHandler
| UnregisterHandler
| UpdateContractHandler
deriving (Show, Eq, Ord)
type HandlerParams = Map ParamKey ParamVal
type ParamKey = Text
data ParamVal =
Integer Int
| Rational Int Int
^ Expresses ratios , eg . 1/2 .
deriving (Show, Eq, Ord)
newtype HandlerError = HandlerError Text
deriving (Show, Eq, Ord, IsString)
SendTransfer
type SendTransfer' c =
-> Either HandlerError ()
defaultSendTransfer :: SendTransfer' c
defaultSendTransfer = mkSendTransfer maxBound
mkSendTransfer :: Balance -> SendTransfer' c
mkSendTransfer maxBalance = sendTransfer
where
sendTransfer _signer _from _to bal _sigs =
if bal <= maxBalance
then Right ()
else Left "Max balance exceeded for transfer"
type ReceiveTransfer' c =
Balance
-> Project c
-> [(AccountId c, Balance)]
defaultReceiveTransfer :: ReceiveTransfer' c
defaultReceiveTransfer = depositToFund
mkReceiveTransfer :: ReceiveTransfer' c
mkReceiveTransfer _ _ _ = []
depositToFund :: ReceiveTransfer' c
depositToFund bal _ p =
[(projectId p, bal)]
type ReceiveReward' c =
defaultReceiveReward :: ReceiveReward' c
defaultReceiveReward = burnReward
burnReward :: ReceiveReward' c
burnReward _ _ _ = []
distributeRewardEqually :: Ord (AccountId c) => ReceiveReward' c
distributeRewardEqually bal _epoch p@Project{..} =
let members = Map.keysSet $ pContributors <> pMaintainers <> pSupporters
(dist, rem) = distribute bal members
in (projectId p, rem) : dist
Checkpoint
type Checkpoint' c =
-> Either HandlerError ()
defaultCheckpoint :: Ord (AccountId c) => Checkpoint' c
defaultCheckpoint _ = requireMaintainer
Unregister
type Unregister' c =
-> Either HandlerError ()
defaultUnregister :: Ord (AccountId c) => Unregister' c
defaultUnregister = requireMaintainer
Authorize
type Authorize' c =
-> Either HandlerError ()
defaultAuthorize :: Ord (AccountId c) => Authorize' c
defaultAuthorize _ = requireMaintainer
type Deauthorize' c =
-> Either HandlerError ()
defaultDeauthorize :: Ord (AccountId c) => Deauthorize' c
defaultDeauthorize _ = requireMaintainer
UpdateContract
type UpdateContract' c =
-> Either HandlerError ()
defaultUpdateContract :: Ord (AccountId c) => UpdateContract' c
defaultUpdateContract _ _ = requireMaintainer
distribute :: Balance -> Set (AccountId c) -> ([(AccountId c, Balance)], Balance)
distribute bal accs =
([(acc, share) | acc <- Set.toList accs], remainder)
where
share = bal `div` fromIntegral (Set.size accs)
remainder = bal `mod` share
requireMaintainer
:: Ord (AccountId c)
=> Project c
-> Account c
-> Either HandlerError ()
requireMaintainer Project{..} Account{..} =
if Map.member accountId pMaintainers
then Right ()
else Left (HandlerError "Signer must be a project maintainer")
|
2576801bae82bed9082aa0871911ad6325600cc66168c5d9162b21c390ab3e7b | Hexstream/definitions-systems | checking.lisp | (in-package #:definitions-systems)
(defclass defsys:check-definition-mixin (defsys:system) ())
(defgeneric defsys:base-definition-class (system))
(defclass defsys:base-definition-class-mixin (defsys:check-definition-mixin)
((%base-definition-class :initarg :base-definition-class
:reader defsys:base-definition-class
:type class
:canonicalize #'find-class
:initform (find-class 'defsys:definition))))
(define-condition defsys:unsuitable-definition-error (error)
((%system :initarg :system
:reader defsys:system
:type defsys:system
:initform (error "~S is required." :system))
(%definition :initarg :definition
:reader defsys:definition
:initform (error "~S is required." :definition))
(%details :initarg :details
:reader defsys:details
:initform nil))
(:report (lambda (error stream)
(format stream "~S is not a suitable definition for system ~S ~@
Details: ~S"
(defsys:definition error) (defsys:system error) (defsys:details error)))))
(defgeneric defsys:check-definition (system definition)
(:method ((system defsys:system) definition)
definition)
(:method ((system defsys:base-definition-class-mixin) definition)
(let ((base-definition-class (defsys:base-definition-class system)))
(if (typep definition base-definition-class)
definition
(error 'defsys:unsuitable-definition-error
:system system :definition definition
:details (make-condition 'type-error
:datum definition
:expected-type base-definition-class))))))
| null | https://raw.githubusercontent.com/Hexstream/definitions-systems/03ef8090479f65f96017319a65fb2d7afe031de5/checking.lisp | lisp | (in-package #:definitions-systems)
(defclass defsys:check-definition-mixin (defsys:system) ())
(defgeneric defsys:base-definition-class (system))
(defclass defsys:base-definition-class-mixin (defsys:check-definition-mixin)
((%base-definition-class :initarg :base-definition-class
:reader defsys:base-definition-class
:type class
:canonicalize #'find-class
:initform (find-class 'defsys:definition))))
(define-condition defsys:unsuitable-definition-error (error)
((%system :initarg :system
:reader defsys:system
:type defsys:system
:initform (error "~S is required." :system))
(%definition :initarg :definition
:reader defsys:definition
:initform (error "~S is required." :definition))
(%details :initarg :details
:reader defsys:details
:initform nil))
(:report (lambda (error stream)
(format stream "~S is not a suitable definition for system ~S ~@
Details: ~S"
(defsys:definition error) (defsys:system error) (defsys:details error)))))
(defgeneric defsys:check-definition (system definition)
(:method ((system defsys:system) definition)
definition)
(:method ((system defsys:base-definition-class-mixin) definition)
(let ((base-definition-class (defsys:base-definition-class system)))
(if (typep definition base-definition-class)
definition
(error 'defsys:unsuitable-definition-error
:system system :definition definition
:details (make-condition 'type-error
:datum definition
:expected-type base-definition-class))))))
| |
e4b5977ea7f020992419b06b246fa0dc32a502f0e19693b695514f06d4414953 | Jell/euroclojure-2016 | kioo_meta.cljs | (ns euroclojure.kioo-meta
(:require-macros [euroclojure.utils :refer [code-snippet]])
(:require [kioo.reagent :as kioo :refer-macros [deftemplate]]))
(deftemplate slide "templates/kioo_meta.html" []
{[:#kioo-says] (kioo/content "hello!")
[:#code-snippet]
(kioo/substitute
[:div
(code-snippet "html" "resources/private/templates/kioo_meta.html")
(code-snippet "clojure" "src/euroclojure/kioo_meta.cljs")])})
| null | https://raw.githubusercontent.com/Jell/euroclojure-2016/a8ca883e8480a4616ede19995aaacd4a495608af/src/euroclojure/kioo_meta.cljs | clojure | (ns euroclojure.kioo-meta
(:require-macros [euroclojure.utils :refer [code-snippet]])
(:require [kioo.reagent :as kioo :refer-macros [deftemplate]]))
(deftemplate slide "templates/kioo_meta.html" []
{[:#kioo-says] (kioo/content "hello!")
[:#code-snippet]
(kioo/substitute
[:div
(code-snippet "html" "resources/private/templates/kioo_meta.html")
(code-snippet "clojure" "src/euroclojure/kioo_meta.cljs")])})
| |
26141ced0ab8f0ff4fb728ff796c3a95223a593e3a6916e7cadafe44d9d54dcb | kunstmusik/pink | dynamics.clj | (ns pink.dynamics
"Functions for dealing with dynamics/amplitude of audio"
(:require [pink.util :refer [create-buffer getd generator gen-recur]]
[pink.config :refer [*buffer-size* *sr*]]))
;; Ensure unchecked math used for this namespace
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^:private ^{:tag 'double}
LOG10D20 (/ (Math/log 10) 20))
(defn db->amp
"Convert decibel to power ratio"
^double [^double d]
(Math/exp (* d LOG10D20)))
(defn balance
"Adjust one audio signal according to the values of another.
Based on Csound's balance opcode."
([asig acomp] (balance asig acomp 10))
([asig acomp ^double hp]
{:pre [(number? hp)]}
(let [TPIDSR (/ (* 2 Math/PI) (double *sr*))
b (- 2.0 (Math/cos (* hp TPIDSR)))
c2 (- b (Math/sqrt (- (* b b) 1.0)))
c1 (- 1.0 c2)
prvq (double-array 1 0.0)
prvr (double-array 1 0.0)
prva (double-array 1 0.0)
out ^doubles (create-buffer)]
; this one needs some thought...
;(generator
[ prvq 0.0
prvr 0.0
prva 0.0 ]
; [ain asig
cin acomp ]
; (yield out)
; )
(fn []
(let [abuf ^doubles (asig)
cbuf ^doubles (acomp)
buf-size (long *buffer-size*)]
(when (and abuf cbuf)
(loop [i (int 0)
q (getd prvq)
r (getd prvr)]
(if (< i buf-size)
(let [av (aget abuf i)
cv (aget cbuf i)]
(recur
(unchecked-inc i)
(+ (* c1 av av) (* c2 q))
(+ (* c1 cv cv) (* c2 r))))
(do
(aset prvq 0 q)
(aset prvr 0 r))))
(let [q (getd prvq)
r (getd prvr)
a (if (zero? q)
(Math/sqrt r)
(Math/sqrt (/ r q)))
pa (getd prva)
diff (- a pa)
]
(if (zero? diff)
(loop [i 0]
(when (< i buf-size)
(aset out i (* a (aget abuf i)))
(recur (unchecked-inc i))))
(let [incr (/ diff buf-size)]
(loop [i 0 m pa]
(if (< i buf-size)
(do
(aset out i (* m (aget abuf i)))
(recur (unchecked-inc i) (+ m incr)))
(aset prva 0 a))
)))
out)))))))
| null | https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/main/pink/dynamics.clj | clojure | Ensure unchecked math used for this namespace
this one needs some thought...
(generator
[ain asig
(yield out)
) | (ns pink.dynamics
"Functions for dealing with dynamics/amplitude of audio"
(:require [pink.util :refer [create-buffer getd generator gen-recur]]
[pink.config :refer [*buffer-size* *sr*]]))
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^:private ^{:tag 'double}
LOG10D20 (/ (Math/log 10) 20))
(defn db->amp
"Convert decibel to power ratio"
^double [^double d]
(Math/exp (* d LOG10D20)))
(defn balance
"Adjust one audio signal according to the values of another.
Based on Csound's balance opcode."
([asig acomp] (balance asig acomp 10))
([asig acomp ^double hp]
{:pre [(number? hp)]}
(let [TPIDSR (/ (* 2 Math/PI) (double *sr*))
b (- 2.0 (Math/cos (* hp TPIDSR)))
c2 (- b (Math/sqrt (- (* b b) 1.0)))
c1 (- 1.0 c2)
prvq (double-array 1 0.0)
prvr (double-array 1 0.0)
prva (double-array 1 0.0)
out ^doubles (create-buffer)]
[ prvq 0.0
prvr 0.0
prva 0.0 ]
cin acomp ]
(fn []
(let [abuf ^doubles (asig)
cbuf ^doubles (acomp)
buf-size (long *buffer-size*)]
(when (and abuf cbuf)
(loop [i (int 0)
q (getd prvq)
r (getd prvr)]
(if (< i buf-size)
(let [av (aget abuf i)
cv (aget cbuf i)]
(recur
(unchecked-inc i)
(+ (* c1 av av) (* c2 q))
(+ (* c1 cv cv) (* c2 r))))
(do
(aset prvq 0 q)
(aset prvr 0 r))))
(let [q (getd prvq)
r (getd prvr)
a (if (zero? q)
(Math/sqrt r)
(Math/sqrt (/ r q)))
pa (getd prva)
diff (- a pa)
]
(if (zero? diff)
(loop [i 0]
(when (< i buf-size)
(aset out i (* a (aget abuf i)))
(recur (unchecked-inc i))))
(let [incr (/ diff buf-size)]
(loop [i 0 m pa]
(if (< i buf-size)
(do
(aset out i (* m (aget abuf i)))
(recur (unchecked-inc i) (+ m incr)))
(aset prva 0 a))
)))
out)))))))
|
f372dbefd238851ff3392d71e1ff2f906df7d7210fda19a1c7b44d9c7377475c | fgalassi/cs61a-sp11 | 3.4.scm | (define (make-account balance secret-password)
(let ((unauthorized 0))
(define (reset-unauthorized) (set! unauthorized 0))
(define (incorrect-password . args)
(set! unauthorized (+ unauthorized 1))
(if (> unauthorized 7)
(begin (reset-unauthorized) (call-the-cops)))
"Incorrect password")
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch password method)
(if (eq? secret-password password)
(begin
(reset-unauthorized)
(cond ((eq? method 'withdraw) withdraw)
((eq? method 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m))))
incorrect-password))
dispatch))
(define (call-the-cops) (display " !!CALLING THE COPS!! "))
| null | https://raw.githubusercontent.com/fgalassi/cs61a-sp11/66df3b54b03ee27f368c716ae314fd7ed85c4dba/homework/3.4.scm | scheme | (define (make-account balance secret-password)
(let ((unauthorized 0))
(define (reset-unauthorized) (set! unauthorized 0))
(define (incorrect-password . args)
(set! unauthorized (+ unauthorized 1))
(if (> unauthorized 7)
(begin (reset-unauthorized) (call-the-cops)))
"Incorrect password")
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount)) balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount)) balance)
(define (dispatch password method)
(if (eq? secret-password password)
(begin
(reset-unauthorized)
(cond ((eq? method 'withdraw) withdraw)
((eq? method 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT" m))))
incorrect-password))
dispatch))
(define (call-the-cops) (display " !!CALLING THE COPS!! "))
| |
21eeabb07c0f1831203a83e1094e6bc0220b4915a33950e26ed59253d98ede8f | schemeorg-community/index.scheme.org | chibi.scm | (
;; r7rs small
((scheme base) . #t)
((scheme case-lambda) . #t)
((scheme complex) . #t)
((scheme char) . #t)
((scheme cxr) . #t)
((scheme eval) . #t)
((scheme file) . #t)
((scheme inexact) . #t)
((scheme lazy) . #t)
((scheme load) . #t)
((scheme process-context) . #t)
((scheme r5rs) . #t)
((scheme read) . #t)
((scheme repl) . #t)
((scheme time) . #t)
((scheme write) . #t)
; r7rs large red
((scheme box) . #t)
((scheme comparator) . #t)
((scheme charset) . #t)
((scheme ephemeron) . #t)
((scheme generator) . #t)
((scheme hash-table) . #t)
((scheme ideque) . #t)
((scheme ilist) . #t)
((scheme list) . #t)
((scheme list-queue) . #t)
((scheme lseq) . #t)
((scheme rlist) . #t)
((scheme set) . #t)
((scheme stream) . #t)
((scheme sort) . #t)
((scheme text) . #t)
((scheme vector) . #t)
; r7rs large tangerine
((scheme bitwise) . #t)
((scheme bytevector) . #t)
((scheme division) . #t)
((scheme fixnum) . #t)
((scheme flonum) . #t)
((scheme mapping) . #t)
((scheme mapping hash) . #t)
((scheme regex) . #t)
((scheme show) . #t)
((scheme vector base) . #t)
((scheme vector u8) . #t)
((scheme vector s8) . #t)
((scheme vector u16) . #t)
((scheme vector s16) . #t)
((scheme vector u32) . #t)
((scheme vector s32) . #t)
((scheme vector u64) . #t)
((scheme vector s64) . #t)
((scheme vector f32) . #t)
((scheme vector f64) . #t)
((scheme vector c64) . #t)
((scheme vector c128) . #t)
((srfi 0) . #t)
((srfi 1) . #t)
((srfi 2) . #t)
((srfi 6) . #t)
((srfi 8) . #t)
((srfi 9) . #t)
((srfi 11) . #t)
((srfi 14) . #t)
((srfi 16) . #t)
((srfi 18) . #t)
((srfi 23) . #t)
((srfi 26) . #t)
((srfi 27) . #t)
((srfi 38) . #t)
((srfi 39) . #t)
((srfi 41) . #t)
((srfi 46) . #t)
((srfi 69) . #t)
((srfi 95) . #t)
((srfi 98) . #t)
((srfi 99) . #t)
((srfi 99 records procedural) . #t)
((srfi 99 records inspection) . #t)
((srfi 99 records syntactic) . #t)
((srfi 101) . #t)
((srfi 111) . #t)
((srfi 113) . #t)
((srfi 115) . #t)
((srfi 116) . #t)
((srfi 117) . #t)
((srfi 124) . #t)
((srfi 125) . #t)
((srfi 127) . #t)
((srfi 128) . #t)
((srfi 129) . #t)
((srfi 130) . #t)
((srfi 132) . #t)
((srfi 133) . #t)
((srfi 134) . #t)
((srfi 135) . #t)
((srfi 141) . #t)
((srfi 143) . #t)
((srfi 144) . #t)
((srfi 145) . #t)
((srfi 146) . #t)
((srfi 146 hash) . #t)
((srfi 151) . #t)
((srfi 154) . #t)
((srfi 158) . #t)
((srfi 159) . #t)
((srfi 160 base) . #t)
((srfi 160 u8) . #t)
((srfi 160 s8) . #t)
((srfi 160 u16) . #t)
((srfi 160 s16) . #t)
((srfi 160 u32) . #t)
((srfi 160 s32) . #t)
((srfi 160 u64) . #t)
((srfi 160 s64) . #t)
((srfi 160 f32) . #t)
((srfi 160 f64) . #t)
((srfi 160 c64) . #t)
((srfi 160 c128) . #t)
((srfi 193) . #t)
((srfi 219) . #t)
)
| null | https://raw.githubusercontent.com/schemeorg-community/index.scheme.org/32e1afcfe423a158ac8ce014f5c0b8399d12a1ea/filters/chibi.scm | scheme | r7rs small
r7rs large red
r7rs large tangerine
| (
((scheme base) . #t)
((scheme case-lambda) . #t)
((scheme complex) . #t)
((scheme char) . #t)
((scheme cxr) . #t)
((scheme eval) . #t)
((scheme file) . #t)
((scheme inexact) . #t)
((scheme lazy) . #t)
((scheme load) . #t)
((scheme process-context) . #t)
((scheme r5rs) . #t)
((scheme read) . #t)
((scheme repl) . #t)
((scheme time) . #t)
((scheme write) . #t)
((scheme box) . #t)
((scheme comparator) . #t)
((scheme charset) . #t)
((scheme ephemeron) . #t)
((scheme generator) . #t)
((scheme hash-table) . #t)
((scheme ideque) . #t)
((scheme ilist) . #t)
((scheme list) . #t)
((scheme list-queue) . #t)
((scheme lseq) . #t)
((scheme rlist) . #t)
((scheme set) . #t)
((scheme stream) . #t)
((scheme sort) . #t)
((scheme text) . #t)
((scheme vector) . #t)
((scheme bitwise) . #t)
((scheme bytevector) . #t)
((scheme division) . #t)
((scheme fixnum) . #t)
((scheme flonum) . #t)
((scheme mapping) . #t)
((scheme mapping hash) . #t)
((scheme regex) . #t)
((scheme show) . #t)
((scheme vector base) . #t)
((scheme vector u8) . #t)
((scheme vector s8) . #t)
((scheme vector u16) . #t)
((scheme vector s16) . #t)
((scheme vector u32) . #t)
((scheme vector s32) . #t)
((scheme vector u64) . #t)
((scheme vector s64) . #t)
((scheme vector f32) . #t)
((scheme vector f64) . #t)
((scheme vector c64) . #t)
((scheme vector c128) . #t)
((srfi 0) . #t)
((srfi 1) . #t)
((srfi 2) . #t)
((srfi 6) . #t)
((srfi 8) . #t)
((srfi 9) . #t)
((srfi 11) . #t)
((srfi 14) . #t)
((srfi 16) . #t)
((srfi 18) . #t)
((srfi 23) . #t)
((srfi 26) . #t)
((srfi 27) . #t)
((srfi 38) . #t)
((srfi 39) . #t)
((srfi 41) . #t)
((srfi 46) . #t)
((srfi 69) . #t)
((srfi 95) . #t)
((srfi 98) . #t)
((srfi 99) . #t)
((srfi 99 records procedural) . #t)
((srfi 99 records inspection) . #t)
((srfi 99 records syntactic) . #t)
((srfi 101) . #t)
((srfi 111) . #t)
((srfi 113) . #t)
((srfi 115) . #t)
((srfi 116) . #t)
((srfi 117) . #t)
((srfi 124) . #t)
((srfi 125) . #t)
((srfi 127) . #t)
((srfi 128) . #t)
((srfi 129) . #t)
((srfi 130) . #t)
((srfi 132) . #t)
((srfi 133) . #t)
((srfi 134) . #t)
((srfi 135) . #t)
((srfi 141) . #t)
((srfi 143) . #t)
((srfi 144) . #t)
((srfi 145) . #t)
((srfi 146) . #t)
((srfi 146 hash) . #t)
((srfi 151) . #t)
((srfi 154) . #t)
((srfi 158) . #t)
((srfi 159) . #t)
((srfi 160 base) . #t)
((srfi 160 u8) . #t)
((srfi 160 s8) . #t)
((srfi 160 u16) . #t)
((srfi 160 s16) . #t)
((srfi 160 u32) . #t)
((srfi 160 s32) . #t)
((srfi 160 u64) . #t)
((srfi 160 s64) . #t)
((srfi 160 f32) . #t)
((srfi 160 f64) . #t)
((srfi 160 c64) . #t)
((srfi 160 c128) . #t)
((srfi 193) . #t)
((srfi 219) . #t)
)
|
3de95ab05951006e29d5420a421616f29cdb219eb2a2a7d5bf8f990373b23021 | tweag/ormolu | conlike-out.hs | foo :: Int
foo = 5
{-# INLINE CONLIKE foo #-}
bar :: Int
bar = 6
{-# INLINE CONLIKE bar #-}
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/signature/inline/conlike-out.hs | haskell | # INLINE CONLIKE foo #
# INLINE CONLIKE bar # | foo :: Int
foo = 5
bar :: Int
bar = 6
|
ed5dedfdb41916f778a13dc254f694d56ae94d4571121aa1bc35c6695f892e1d | OlivierSohn/hamazed | Interleave.hs | # LANGUAGE NoImplicitPrelude #
module Test.Imj.Interleave
( testInterleaveHalves
) where
import Imj.Prelude
import Data.List(elem,splitAt)
import Imj.Geo.Discrete.Interleave
import . Graphics . Text . Render
shouldBe :: (Show a, Eq a) => a -> a -> IO ()
shouldBe actual expected =
if actual == expected
then
return ()
else
error $ "expected\n" ++ show expected ++ " but got\n" ++ show actual
testInterleaveHalves :: IO ()
testInterleaveHalves = do
--------------------------------------------------------------------------
interleaveHalves [0,1::Int] `shouldBe` [0,1]
interleaveHalves [0,1,2::Int] `shouldBe` [2,0,1]
interleaveHalves [2,0,1::Int] `shouldBe` [1,2,0]
interleaveHalves [1,2,0::Int] `shouldBe` [0,1,2]
interleaveHalves [0,1,2,3::Int] `shouldBe` [2,0,3,1]
interleaveHalves [2,0,3,1::Int] `shouldBe` [3,2,1,0]
interleaveHalves [0,1,2,3,4::Int] `shouldBe` [4,2,0,3,1]
interleaveHalves [4,2,0,3,1::Int] `shouldBe` [1,0,4,3,2]
interleaveHalves [1,0,4,3,2::Int] `shouldBe` [2,4,1,3,0]
interleaveHalves [2,4,1,3,0::Int] `shouldBe` [0,1,2,3,4]
interleaveHalves [0,1,2,3,4,5::Int] `shouldBe` [4,2,0,5,3,1]
interleaveHalves [4,2,0,5,3,1::Int] `shouldBe` [3,0,4,1,5,2]
interleaveHalves [3,0,4,1,5,2::Int] `shouldBe` [5,4,3,2,1,0]
interleaveHalves [0,1,2,3,4,5,6::Int] `shouldBe` [6,4,2,0,5,3,1]
interleaveHalves [6,4,2,0,5,3,1::Int] `shouldBe` [1,5,2,6,3,0,4]
interleaveHalves [1,5,2,6,3,0,4::Int] `shouldBe` [4,3,2,1,0,6,5]
interleaveHalves [4,3,2,1,0,6,5::Int] `shouldBe` [5,0,2,4,6,1,3]
interleaveHalves [5,0,2,4,6,1,3::Int] `shouldBe` [3,6,2,5,1,4,0]
interleaveHalves [3,6,2,5,1,4,0::Int] `shouldBe` [0,1,2,3,4,5,6]
interleaveHalves [0,1,2,3,4,5,6,7::Int] `shouldBe` [6,4,2,0,7,5,3,1]
interleaveHalves [6,4,2,0,7,5,3,1::Int] `shouldBe` [3,7,2,6,1,5,0,4]
interleaveHalves [3,7,2,6,1,5,0,4::Int] `shouldBe` [0,1,2,3,4,5,6,7]
let f len final = do
let analyze i prevRes x =
bool (Left $ equivalents x ++ prevRes) (Right i) $ elem x prevRes
equivalents x =
it 's important to have x in first position
map (rotate $ reverse x) [0..pred len]
rotate xs n = bs ++ as where (as, bs) = splitAt n xs
foldM
(\res i -> return $ either
(\prevRes@(mostRecent:_) -> analyze i prevRes $ interleaveHalves mostRecent)
Right
res)
(Left $ equivalents [0..pred len])
[1.. 100] >>= either (error $ "not enough iterations " ++ show len) final
-- verify formula for countUsefulInterleavedVariations:
mapM_
(\len -> f len (`shouldBe` countUsefulInterleavedVariations len))
[1..20]
-- print values
putStrLn " "
mapM _
( \len - >
f len ( \value - >
countUsefulInterleavedVariations " + +
justifyR 3 ( show len ) + +
" = " + +
justifyR 3 ( show ( value::Int ) ) ) )
[ 1 .. 100 ]
putStrLn ""
mapM_
(\len ->
f len (\value ->
putStrLn $
"countUsefulInterleavedVariations " ++
justifyR 3 (show len) ++
" = " ++
justifyR 3 (show (value::Int))))
[1..100]
-}
--------------------------------------------------------------------------
verify that interleaveHalves and ' are the same
mapM_
(\i ->
let l = [0..i]
in interleaveHalves l `shouldBe` interleaveHalves' l)
[0..100::Int]
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/c0df1bb60a8538ac75e413d2f5bf0bf050e5bc37/imj-base/test/Test/Imj/Interleave.hs | haskell | ------------------------------------------------------------------------
verify formula for countUsefulInterleavedVariations:
print values
------------------------------------------------------------------------ | # LANGUAGE NoImplicitPrelude #
module Test.Imj.Interleave
( testInterleaveHalves
) where
import Imj.Prelude
import Data.List(elem,splitAt)
import Imj.Geo.Discrete.Interleave
import . Graphics . Text . Render
shouldBe :: (Show a, Eq a) => a -> a -> IO ()
shouldBe actual expected =
if actual == expected
then
return ()
else
error $ "expected\n" ++ show expected ++ " but got\n" ++ show actual
testInterleaveHalves :: IO ()
testInterleaveHalves = do
interleaveHalves [0,1::Int] `shouldBe` [0,1]
interleaveHalves [0,1,2::Int] `shouldBe` [2,0,1]
interleaveHalves [2,0,1::Int] `shouldBe` [1,2,0]
interleaveHalves [1,2,0::Int] `shouldBe` [0,1,2]
interleaveHalves [0,1,2,3::Int] `shouldBe` [2,0,3,1]
interleaveHalves [2,0,3,1::Int] `shouldBe` [3,2,1,0]
interleaveHalves [0,1,2,3,4::Int] `shouldBe` [4,2,0,3,1]
interleaveHalves [4,2,0,3,1::Int] `shouldBe` [1,0,4,3,2]
interleaveHalves [1,0,4,3,2::Int] `shouldBe` [2,4,1,3,0]
interleaveHalves [2,4,1,3,0::Int] `shouldBe` [0,1,2,3,4]
interleaveHalves [0,1,2,3,4,5::Int] `shouldBe` [4,2,0,5,3,1]
interleaveHalves [4,2,0,5,3,1::Int] `shouldBe` [3,0,4,1,5,2]
interleaveHalves [3,0,4,1,5,2::Int] `shouldBe` [5,4,3,2,1,0]
interleaveHalves [0,1,2,3,4,5,6::Int] `shouldBe` [6,4,2,0,5,3,1]
interleaveHalves [6,4,2,0,5,3,1::Int] `shouldBe` [1,5,2,6,3,0,4]
interleaveHalves [1,5,2,6,3,0,4::Int] `shouldBe` [4,3,2,1,0,6,5]
interleaveHalves [4,3,2,1,0,6,5::Int] `shouldBe` [5,0,2,4,6,1,3]
interleaveHalves [5,0,2,4,6,1,3::Int] `shouldBe` [3,6,2,5,1,4,0]
interleaveHalves [3,6,2,5,1,4,0::Int] `shouldBe` [0,1,2,3,4,5,6]
interleaveHalves [0,1,2,3,4,5,6,7::Int] `shouldBe` [6,4,2,0,7,5,3,1]
interleaveHalves [6,4,2,0,7,5,3,1::Int] `shouldBe` [3,7,2,6,1,5,0,4]
interleaveHalves [3,7,2,6,1,5,0,4::Int] `shouldBe` [0,1,2,3,4,5,6,7]
let f len final = do
let analyze i prevRes x =
bool (Left $ equivalents x ++ prevRes) (Right i) $ elem x prevRes
equivalents x =
it 's important to have x in first position
map (rotate $ reverse x) [0..pred len]
rotate xs n = bs ++ as where (as, bs) = splitAt n xs
foldM
(\res i -> return $ either
(\prevRes@(mostRecent:_) -> analyze i prevRes $ interleaveHalves mostRecent)
Right
res)
(Left $ equivalents [0..pred len])
[1.. 100] >>= either (error $ "not enough iterations " ++ show len) final
mapM_
(\len -> f len (`shouldBe` countUsefulInterleavedVariations len))
[1..20]
putStrLn " "
mapM _
( \len - >
f len ( \value - >
countUsefulInterleavedVariations " + +
justifyR 3 ( show len ) + +
" = " + +
justifyR 3 ( show ( value::Int ) ) ) )
[ 1 .. 100 ]
putStrLn ""
mapM_
(\len ->
f len (\value ->
putStrLn $
"countUsefulInterleavedVariations " ++
justifyR 3 (show len) ++
" = " ++
justifyR 3 (show (value::Int))))
[1..100]
-}
verify that interleaveHalves and ' are the same
mapM_
(\i ->
let l = [0..i]
in interleaveHalves l `shouldBe` interleaveHalves' l)
[0..100::Int]
|
c48ac47c849eb821c0c5ee4d7c6c16589ca0397a76711ea005dcd5678f7269c3 | typedclojure/typedclojure | load_test.clj | (ns ^:typed/skip-from-repo-root clojure.core.typed.test.load-test
(:require [clojure.core.typed.load :as load]
[clojure.test :refer :all]))
;; ensures evaluation occurs
(deftest evaluation-test
(is (try (some-> (find-ns 'clojure.core.typed.test.typed-load.eval)
ns-name
remove-ns)
(load/typed-load1 "clojure/core/typed/test/typed_load/eval")
nil
(catch clojure.lang.ExceptionInfo e
(-> e ex-data :blame :file #{"clojure/core/typed/test/typed_load/eval.clj"})))))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/a959d97f0e7e3d17c4f62fd8fc16e10bcc322c2d/typed/clj.checker/test/clojure/core/typed/test/load_test.clj | clojure | ensures evaluation occurs | (ns ^:typed/skip-from-repo-root clojure.core.typed.test.load-test
(:require [clojure.core.typed.load :as load]
[clojure.test :refer :all]))
(deftest evaluation-test
(is (try (some-> (find-ns 'clojure.core.typed.test.typed-load.eval)
ns-name
remove-ns)
(load/typed-load1 "clojure/core/typed/test/typed_load/eval")
nil
(catch clojure.lang.ExceptionInfo e
(-> e ex-data :blame :file #{"clojure/core/typed/test/typed_load/eval.clj"})))))
|
a1754c46a7e62dbd0e0644897a1e64594f15e7359eb3756955feff33a23162e0 | jayunit100/RudolF | vennnmr.clj | (ns BioClojure.test.vennnmr
(:use [BioClojure.vennnmr])
(:use [clojure.test]))
(def mseq (slurp "resources/venn_nmr/sequence.txt"))
(def mshift (slurp "resources/venn_nmr/assigned-shifts.prot"))
(def mstat (slurp "resources/venn_nmr/bmrbstats.txt"))
(deftest test-parse-bmrb-stats
(is (parse-sequence mseq))) ;; does this test actually do anything?
(deftest test-parse-assigned-shifts
(is (parse-shifts mshift)))
(deftest test-parse-bmrb-stats
(is (parse-bmrb-stats mstat)))
(deftest test-venn-nmr
(is (venn-nmr-help mseq mshift mstat))) ;; is this an effective test?
;;;; what follows is for informal testing
(def shifts (parse-shifts " 7 57.135 0.000 CA 1
1 4.155 0.000 HA 1
8 29.815 0.000 CB 1
2 1.908 0.000 HB2 1
3 2.003 0.000 HB3 1
9 36.326 0.000 CG 1
4 2.222 0.000 HG2 1
5 2.222 0.000 HG3 1
6 176.410 0.000 C 1
19 118.889 0.000 N 2
10 8.376 0.000 H 2
17 53.005 0.000 CA 2
11 4.752 0.000 HA 2
18 38.025 0.000 CB 2
12 2.675 0.000 HB2 2
13 2.932 0.000 HB3 2
20 110.708 0.000 ND2 2
14 6.792 0.000 HD21 2
15 7.423 0.000 HD22 2
16 175.445 0.000 C 2
123 116.209 0.000 N 12
116 8.466 0.000 H 12
121 56.000 0.000 CA 12
117 4.179 0.000 HA 12
122 40.455 0.000 CB 12
118 2.630 0.000 HB2 12
119 2.469 0.000 HB3 12
120 175.224 0.000 C 12"))
(def myseq (parse-sequence "MET
ASN
CYS
VAL
CYS
GLY
SER
GLY
LYS
THR
TYR
ASP
ASP
CYS
CYS
GLY
PRO
LEU"))
(def stats (parse-bmrb-stats "Res Name Atom Count Min. Max. Avg. StdDev
ALA H H 30843 3.53 11.48 8.20 0.60
ALA HA H 23429 0.87 6.51 4.26 0.44
ALA HB H 22202 -0.88 3.12 1.35 0.26
ALA C C 19475 164.48 187.20 177.72 2.14
ALA CA C 26260 44.22 65.52 53.13 1.98
ALA CB C 24766 0.00 38.70 19.01 1.84
ALA N N 28437 77.10 142.81 123.24 3.54
ARG H H 21153 3.57 12.69 8.24 0.61
ARG HA H 16560 1.34 6.52 4.30 0.46
ARG HB2 H 14978 -0.86 3.44 1.79 0.27
ARG HB3 H 14071 -0.86 3.32 1.76 0.28
ARG HG2 H 13472 -0.72 3.51 1.57 0.27
ARG HG3 H 12287 -0.74 3.51 1.54 0.29
ARG HD2 H 13185 0.96 4.69 3.12 0.24
ARG HD3 H 11833 0.73 4.56 3.10 0.26
ARG HE H 4149 2.99 11.88 7.39 0.64
ARG HH11 H 379 5.88 9.82 6.91 0.46
ARG HH12 H 274 6.01 8.76 6.81 0.32
ARG HH21 H 342 5.90 11.35 6.82 0.48
ARG HH22 H 268 5.97 10.18 6.76 0.36
ARG C C 12724 167.44 184.51 176.40 2.03
ARG CA C 17600 43.27 67.98 56.77 2.31
ARG CB C 16224 20.95 42.50 30.70 1.83
ARG CG C 10535 18.22 40.94 27.21 1.20
ARG CD C 10667 35.05 50.88 43.16 0.88
ARG CZ C 219 156.20 177.70 159.98 2.99
ARG N N 18883 102.78 137.60 120.80 3.68
ARG NE N 2261 67.00 99.81 84.64 1.70
ARG NH1 N 64 67.60 87.07 73.62 4.35
ARG NH2 N 55 70.10 85.28 73.26 3.32
ASP H H 24462 4.06 12.68 8.31 0.58
ASP HA H 18689 2.33 6.33 4.59 0.32
ASP HB2 H 17394 -0.39 4.58 2.72 0.26
ASP HB3 H 16624 -0.23 4.58 2.66 0.28
ASP HD2 H 4 4.65 6.03 5.25 0.58
ASP C C 15510 166.80 182.70 176.39 1.75
ASP CA C 21054 41.88 67.17 54.69 2.03
ASP CB C 19786 27.48 51.09 40.88 1.62
ASP CG C 290 170.72 186.50 179.16 1.81
ASP N N 22760 101.90 143.52 120.64 3.87
ASP OD1 O 20 177.59 180.97 179.66 0.91"))
(def trans-stats (transform-stats stats))
(def myprot (seq-to-protein myseq))
(def merged (merge-shifts myprot shifts)) | null | https://raw.githubusercontent.com/jayunit100/RudolF/8936bafbb30c65c78b820062dec550ceeea4b3a4/bioclojure/old/vennnmr.clj | clojure | does this test actually do anything?
is this an effective test?
what follows is for informal testing | (ns BioClojure.test.vennnmr
(:use [BioClojure.vennnmr])
(:use [clojure.test]))
(def mseq (slurp "resources/venn_nmr/sequence.txt"))
(def mshift (slurp "resources/venn_nmr/assigned-shifts.prot"))
(def mstat (slurp "resources/venn_nmr/bmrbstats.txt"))
(deftest test-parse-bmrb-stats
(deftest test-parse-assigned-shifts
(is (parse-shifts mshift)))
(deftest test-parse-bmrb-stats
(is (parse-bmrb-stats mstat)))
(deftest test-venn-nmr
(def shifts (parse-shifts " 7 57.135 0.000 CA 1
1 4.155 0.000 HA 1
8 29.815 0.000 CB 1
2 1.908 0.000 HB2 1
3 2.003 0.000 HB3 1
9 36.326 0.000 CG 1
4 2.222 0.000 HG2 1
5 2.222 0.000 HG3 1
6 176.410 0.000 C 1
19 118.889 0.000 N 2
10 8.376 0.000 H 2
17 53.005 0.000 CA 2
11 4.752 0.000 HA 2
18 38.025 0.000 CB 2
12 2.675 0.000 HB2 2
13 2.932 0.000 HB3 2
20 110.708 0.000 ND2 2
14 6.792 0.000 HD21 2
15 7.423 0.000 HD22 2
16 175.445 0.000 C 2
123 116.209 0.000 N 12
116 8.466 0.000 H 12
121 56.000 0.000 CA 12
117 4.179 0.000 HA 12
122 40.455 0.000 CB 12
118 2.630 0.000 HB2 12
119 2.469 0.000 HB3 12
120 175.224 0.000 C 12"))
(def myseq (parse-sequence "MET
ASN
CYS
VAL
CYS
GLY
SER
GLY
LYS
THR
TYR
ASP
ASP
CYS
CYS
GLY
PRO
LEU"))
(def stats (parse-bmrb-stats "Res Name Atom Count Min. Max. Avg. StdDev
ALA H H 30843 3.53 11.48 8.20 0.60
ALA HA H 23429 0.87 6.51 4.26 0.44
ALA HB H 22202 -0.88 3.12 1.35 0.26
ALA C C 19475 164.48 187.20 177.72 2.14
ALA CA C 26260 44.22 65.52 53.13 1.98
ALA CB C 24766 0.00 38.70 19.01 1.84
ALA N N 28437 77.10 142.81 123.24 3.54
ARG H H 21153 3.57 12.69 8.24 0.61
ARG HA H 16560 1.34 6.52 4.30 0.46
ARG HB2 H 14978 -0.86 3.44 1.79 0.27
ARG HB3 H 14071 -0.86 3.32 1.76 0.28
ARG HG2 H 13472 -0.72 3.51 1.57 0.27
ARG HG3 H 12287 -0.74 3.51 1.54 0.29
ARG HD2 H 13185 0.96 4.69 3.12 0.24
ARG HD3 H 11833 0.73 4.56 3.10 0.26
ARG HE H 4149 2.99 11.88 7.39 0.64
ARG HH11 H 379 5.88 9.82 6.91 0.46
ARG HH12 H 274 6.01 8.76 6.81 0.32
ARG HH21 H 342 5.90 11.35 6.82 0.48
ARG HH22 H 268 5.97 10.18 6.76 0.36
ARG C C 12724 167.44 184.51 176.40 2.03
ARG CA C 17600 43.27 67.98 56.77 2.31
ARG CB C 16224 20.95 42.50 30.70 1.83
ARG CG C 10535 18.22 40.94 27.21 1.20
ARG CD C 10667 35.05 50.88 43.16 0.88
ARG CZ C 219 156.20 177.70 159.98 2.99
ARG N N 18883 102.78 137.60 120.80 3.68
ARG NE N 2261 67.00 99.81 84.64 1.70
ARG NH1 N 64 67.60 87.07 73.62 4.35
ARG NH2 N 55 70.10 85.28 73.26 3.32
ASP H H 24462 4.06 12.68 8.31 0.58
ASP HA H 18689 2.33 6.33 4.59 0.32
ASP HB2 H 17394 -0.39 4.58 2.72 0.26
ASP HB3 H 16624 -0.23 4.58 2.66 0.28
ASP HD2 H 4 4.65 6.03 5.25 0.58
ASP C C 15510 166.80 182.70 176.39 1.75
ASP CA C 21054 41.88 67.17 54.69 2.03
ASP CB C 19786 27.48 51.09 40.88 1.62
ASP CG C 290 170.72 186.50 179.16 1.81
ASP N N 22760 101.90 143.52 120.64 3.87
ASP OD1 O 20 177.59 180.97 179.66 0.91"))
(def trans-stats (transform-stats stats))
(def myprot (seq-to-protein myseq))
(def merged (merge-shifts myprot shifts)) |
8a24b2d72871dfc3c59fa0e4e6e723147dea52147fdb5d68d2ea6a308c507c09 | AshleyYakeley/Truth | DynamicSupertype.hs | module Pinafore.Language.Type.DynamicSupertype where
import Data.Shim
import Language.Expression.Dolan
import Shapes
type PolyGreatestDynamicSupertype :: GroundTypeKind -> forall (dv :: DolanVariance) -> DolanVarianceKind dv -> Type
data PolyGreatestDynamicSupertype ground dv gt where
GeneralPolyGreatestDynamicSupertype
:: forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv).
(forall (t :: Type).
DolanArguments dv (DolanType ground) gt 'Negative t -> Maybe (DolanGroundedShimWit ground 'Negative (Maybe t)))
-> PolyGreatestDynamicSupertype ground dv gt
SimplePolyGreatestDynamicSupertype
:: forall (ground :: GroundTypeKind) (dt :: Type) (gt :: Type).
ground '[] dt
-> DolanPolyShim ground Type dt (Maybe gt)
-> DolanPolyShim ground Type gt dt
-> PolyGreatestDynamicSupertype ground '[] gt
nullPolyGreatestDynamicSupertype ::
forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv).
PolyGreatestDynamicSupertype ground dv gt
nullPolyGreatestDynamicSupertype = GeneralPolyGreatestDynamicSupertype $ \_ -> Nothing
getPolyGreatestDynamicSupertype ::
forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv) (t :: Type).
IsDolanGroundType ground
=> PolyGreatestDynamicSupertype ground dv gt
-> DolanArguments dv (DolanType ground) gt 'Negative t
-> Maybe (DolanGroundedShimWit ground 'Negative (Maybe t))
getPolyGreatestDynamicSupertype (GeneralPolyGreatestDynamicSupertype f) args = f args
getPolyGreatestDynamicSupertype (SimplePolyGreatestDynamicSupertype wt conv _) NilCCRArguments =
Just $ MkShimWit (MkDolanGroundedType wt NilCCRArguments) (MkPolarMap conv)
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/ac72ad5903f4ad329aad18733a5ea16e00efc0a8/Pinafore/pinafore-language/lib/Pinafore/Language/Type/DynamicSupertype.hs | haskell | module Pinafore.Language.Type.DynamicSupertype where
import Data.Shim
import Language.Expression.Dolan
import Shapes
type PolyGreatestDynamicSupertype :: GroundTypeKind -> forall (dv :: DolanVariance) -> DolanVarianceKind dv -> Type
data PolyGreatestDynamicSupertype ground dv gt where
GeneralPolyGreatestDynamicSupertype
:: forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv).
(forall (t :: Type).
DolanArguments dv (DolanType ground) gt 'Negative t -> Maybe (DolanGroundedShimWit ground 'Negative (Maybe t)))
-> PolyGreatestDynamicSupertype ground dv gt
SimplePolyGreatestDynamicSupertype
:: forall (ground :: GroundTypeKind) (dt :: Type) (gt :: Type).
ground '[] dt
-> DolanPolyShim ground Type dt (Maybe gt)
-> DolanPolyShim ground Type gt dt
-> PolyGreatestDynamicSupertype ground '[] gt
nullPolyGreatestDynamicSupertype ::
forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv).
PolyGreatestDynamicSupertype ground dv gt
nullPolyGreatestDynamicSupertype = GeneralPolyGreatestDynamicSupertype $ \_ -> Nothing
getPolyGreatestDynamicSupertype ::
forall (ground :: GroundTypeKind) (dv :: DolanVariance) (gt :: DolanVarianceKind dv) (t :: Type).
IsDolanGroundType ground
=> PolyGreatestDynamicSupertype ground dv gt
-> DolanArguments dv (DolanType ground) gt 'Negative t
-> Maybe (DolanGroundedShimWit ground 'Negative (Maybe t))
getPolyGreatestDynamicSupertype (GeneralPolyGreatestDynamicSupertype f) args = f args
getPolyGreatestDynamicSupertype (SimplePolyGreatestDynamicSupertype wt conv _) NilCCRArguments =
Just $ MkShimWit (MkDolanGroundedType wt NilCCRArguments) (MkPolarMap conv)
| |
5e84ac241a52abb6bf965743199f55c2e777e3bc736d5af743ba7e5a0087fa78 | tallaproject/talla | talla_dir_cowboy.erl | %%%
Copyright ( c ) 2016 The Talla Authors . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% -----------------------------------------------------------
@author < >
%%% @doc Cowboy Middleware.
%%% @end
%%% -----------------------------------------------------------
-module(talla_dir_cowboy).
%% API.
-export([on_request/1,
on_response/4]).
on_request(Request) ->
{Method, _} = cowboy_req:method(Request),
{Path, _} = cowboy_req:path(Request),
{Version, _} = cowboy_req:version(Request),
lager:info("~s ~s ~s", [Method, Path, Version]),
Request.
on_response(Status, _Headers, Body, Req) ->
{{IP, _Port}, Req} = cowboy_req:peer(Req),
Headers = [{<<"server">>, talla_core:platform()},
{<<"content-length">>, integer_to_binary(byte_size(Body))},
{<<"X-Your-Address-Is">>, inet:ntoa(IP)}],
{ok, Req2} = cowboy_req:reply(Status, Headers, Body, Req),
Req2.
| null | https://raw.githubusercontent.com/tallaproject/talla/72cfbd8f48705a7a390cac2b8310ab7550c21c15/apps/talla_dir/src/talla_dir_cowboy.erl | erlang |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-----------------------------------------------------------
@doc Cowboy Middleware.
@end
-----------------------------------------------------------
API. | Copyright ( c ) 2016 The Talla Authors . All rights reserved .
@author < >
-module(talla_dir_cowboy).
-export([on_request/1,
on_response/4]).
on_request(Request) ->
{Method, _} = cowboy_req:method(Request),
{Path, _} = cowboy_req:path(Request),
{Version, _} = cowboy_req:version(Request),
lager:info("~s ~s ~s", [Method, Path, Version]),
Request.
on_response(Status, _Headers, Body, Req) ->
{{IP, _Port}, Req} = cowboy_req:peer(Req),
Headers = [{<<"server">>, talla_core:platform()},
{<<"content-length">>, integer_to_binary(byte_size(Body))},
{<<"X-Your-Address-Is">>, inet:ntoa(IP)}],
{ok, Req2} = cowboy_req:reply(Status, Headers, Body, Req),
Req2.
|
f0486348fa1b206a5340ff2ccf415bb225406c995f28d983f7a631ac8e3d5c47 | Ericson2314/lighthouse | Fixed.hs | {-# OPTIONS -Wall -fno-warn-unused-binds #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Fixed
Copyright : ( c ) 2005 , 2006
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
-- This module defines a \"Fixed\" type for fixed-precision arithmetic.
The parameter to Fixed is any type that 's an instance of HasResolution .
HasResolution has a single method that gives the resolution of the Fixed type .
Parameter types E6 and E12 ( for 10 ^ 6 and 10 ^ 12 ) are defined , as well as
type synonyms for Fixed E6 and Fixed E12 .
--
This module also contains generalisations of div , mod , and divmod to work
-- with any Real instance.
--
-----------------------------------------------------------------------------
module Data.Fixed
(
div',mod',divMod',
Fixed,HasResolution(..),
showFixed,
E6,Micro,
E12,Pico
) where
import Prelude -- necessary to get dependencies right
-- | generalisation of 'div' to any instance of Real
div' :: (Real a,Integral b) => a -> a -> b
div' n d = floor ((toRational n) / (toRational d))
| generalisation of ' divMod ' to any instance of Real
divMod' :: (Real a,Integral b) => a -> a -> (b,a)
divMod' n d = (f,n - (fromIntegral f) * d) where
f = div' n d
-- | generalisation of 'mod' to any instance of Real
mod' :: (Real a) => a -> a -> a
mod' n d = n - (fromInteger f) * d where
f = div' n d
newtype Fixed a = MkFixed Integer deriving (Eq,Ord)
class HasResolution a where
resolution :: a -> Integer
fixedResolution :: (HasResolution a) => Fixed a -> Integer
fixedResolution fa = resolution (uf fa) where
uf :: Fixed a -> a
uf _ = undefined
withType :: (a -> f a) -> f a
withType foo = foo undefined
withResolution :: (HasResolution a) => (Integer -> f a) -> f a
withResolution foo = withType (foo . resolution)
instance Enum (Fixed a) where
succ (MkFixed a) = MkFixed (succ a)
pred (MkFixed a) = MkFixed (pred a)
toEnum = MkFixed . toEnum
fromEnum (MkFixed a) = fromEnum a
enumFrom (MkFixed a) = fmap MkFixed (enumFrom a)
enumFromThen (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromThen a b)
enumFromTo (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromTo a b)
enumFromThenTo (MkFixed a) (MkFixed b) (MkFixed c) = fmap MkFixed (enumFromThenTo a b c)
instance (HasResolution a) => Num (Fixed a) where
(MkFixed a) + (MkFixed b) = MkFixed (a + b)
(MkFixed a) - (MkFixed b) = MkFixed (a - b)
fa@(MkFixed a) * (MkFixed b) = MkFixed (div (a * b) (fixedResolution fa))
negate (MkFixed a) = MkFixed (negate a)
abs (MkFixed a) = MkFixed (abs a)
signum (MkFixed a) = fromInteger (signum a)
fromInteger i = withResolution (\res -> MkFixed (i * res))
instance (HasResolution a) => Real (Fixed a) where
toRational fa@(MkFixed a) = (toRational a) / (toRational (fixedResolution fa))
instance (HasResolution a) => Fractional (Fixed a) where
fa@(MkFixed a) / (MkFixed b) = MkFixed (div (a * (fixedResolution fa)) b)
recip fa@(MkFixed a) = MkFixed (div (res * res) a) where
res = fixedResolution fa
fromRational r = withResolution (\res -> MkFixed (floor (r * (toRational res))))
instance (HasResolution a) => RealFrac (Fixed a) where
properFraction a = (i,a - (fromIntegral i)) where
i = truncate a
truncate f = truncate (toRational f)
round f = round (toRational f)
ceiling f = ceiling (toRational f)
floor f = floor (toRational f)
chopZeros :: Integer -> String
chopZeros 0 = ""
chopZeros a | mod a 10 == 0 = chopZeros (div a 10)
chopZeros a = show a
-- only works for positive a
showIntegerZeros :: Bool -> Int -> Integer -> String
showIntegerZeros True _ 0 = ""
showIntegerZeros chopTrailingZeros digits a = replicate (digits - length s) '0' ++ s' where
s = show a
s' = if chopTrailingZeros then chopZeros a else s
withDot :: String -> String
withDot "" = ""
withDot s = '.':s
| First arg is whether to chop off trailing zeros
showFixed :: (HasResolution a) => Bool -> Fixed a -> String
showFixed chopTrailingZeros fa@(MkFixed a) | a < 0 = "-" ++ (showFixed chopTrailingZeros (asTypeOf (MkFixed (negate a)) fa))
showFixed chopTrailingZeros fa@(MkFixed a) = (show i) ++ (withDot (showIntegerZeros chopTrailingZeros digits fracNum)) where
res = fixedResolution fa
(i,d) = divMod a res
-- enough digits to be unambiguous
digits = ceiling (logBase 10 (fromInteger res) :: Double)
maxnum = 10 ^ digits
fracNum = div (d * maxnum) res
instance (HasResolution a) => Show (Fixed a) where
show = showFixed False
data E6 = E6
instance HasResolution E6 where
resolution _ = 1000000
type Micro = Fixed E6
data E12 = E12
instance HasResolution E12 where
resolution _ = 1000000000000
type Pico = Fixed E12
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/base/Data/Fixed.hs | haskell | # OPTIONS -Wall -fno-warn-unused-binds #
---------------------------------------------------------------------------
|
Module : Data.Fixed
License : BSD-style (see the file libraries/base/LICENSE)
Stability : experimental
Portability : portable
This module defines a \"Fixed\" type for fixed-precision arithmetic.
with any Real instance.
---------------------------------------------------------------------------
necessary to get dependencies right
| generalisation of 'div' to any instance of Real
| generalisation of 'mod' to any instance of Real
only works for positive a
enough digits to be unambiguous |
Copyright : ( c ) 2005 , 2006
Maintainer : < >
The parameter to Fixed is any type that 's an instance of HasResolution .
HasResolution has a single method that gives the resolution of the Fixed type .
Parameter types E6 and E12 ( for 10 ^ 6 and 10 ^ 12 ) are defined , as well as
type synonyms for Fixed E6 and Fixed E12 .
This module also contains generalisations of div , mod , and divmod to work
module Data.Fixed
(
div',mod',divMod',
Fixed,HasResolution(..),
showFixed,
E6,Micro,
E12,Pico
) where
div' :: (Real a,Integral b) => a -> a -> b
div' n d = floor ((toRational n) / (toRational d))
| generalisation of ' divMod ' to any instance of Real
divMod' :: (Real a,Integral b) => a -> a -> (b,a)
divMod' n d = (f,n - (fromIntegral f) * d) where
f = div' n d
mod' :: (Real a) => a -> a -> a
mod' n d = n - (fromInteger f) * d where
f = div' n d
newtype Fixed a = MkFixed Integer deriving (Eq,Ord)
class HasResolution a where
resolution :: a -> Integer
fixedResolution :: (HasResolution a) => Fixed a -> Integer
fixedResolution fa = resolution (uf fa) where
uf :: Fixed a -> a
uf _ = undefined
withType :: (a -> f a) -> f a
withType foo = foo undefined
withResolution :: (HasResolution a) => (Integer -> f a) -> f a
withResolution foo = withType (foo . resolution)
instance Enum (Fixed a) where
succ (MkFixed a) = MkFixed (succ a)
pred (MkFixed a) = MkFixed (pred a)
toEnum = MkFixed . toEnum
fromEnum (MkFixed a) = fromEnum a
enumFrom (MkFixed a) = fmap MkFixed (enumFrom a)
enumFromThen (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromThen a b)
enumFromTo (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromTo a b)
enumFromThenTo (MkFixed a) (MkFixed b) (MkFixed c) = fmap MkFixed (enumFromThenTo a b c)
instance (HasResolution a) => Num (Fixed a) where
(MkFixed a) + (MkFixed b) = MkFixed (a + b)
(MkFixed a) - (MkFixed b) = MkFixed (a - b)
fa@(MkFixed a) * (MkFixed b) = MkFixed (div (a * b) (fixedResolution fa))
negate (MkFixed a) = MkFixed (negate a)
abs (MkFixed a) = MkFixed (abs a)
signum (MkFixed a) = fromInteger (signum a)
fromInteger i = withResolution (\res -> MkFixed (i * res))
instance (HasResolution a) => Real (Fixed a) where
toRational fa@(MkFixed a) = (toRational a) / (toRational (fixedResolution fa))
instance (HasResolution a) => Fractional (Fixed a) where
fa@(MkFixed a) / (MkFixed b) = MkFixed (div (a * (fixedResolution fa)) b)
recip fa@(MkFixed a) = MkFixed (div (res * res) a) where
res = fixedResolution fa
fromRational r = withResolution (\res -> MkFixed (floor (r * (toRational res))))
instance (HasResolution a) => RealFrac (Fixed a) where
properFraction a = (i,a - (fromIntegral i)) where
i = truncate a
truncate f = truncate (toRational f)
round f = round (toRational f)
ceiling f = ceiling (toRational f)
floor f = floor (toRational f)
chopZeros :: Integer -> String
chopZeros 0 = ""
chopZeros a | mod a 10 == 0 = chopZeros (div a 10)
chopZeros a = show a
showIntegerZeros :: Bool -> Int -> Integer -> String
showIntegerZeros True _ 0 = ""
showIntegerZeros chopTrailingZeros digits a = replicate (digits - length s) '0' ++ s' where
s = show a
s' = if chopTrailingZeros then chopZeros a else s
withDot :: String -> String
withDot "" = ""
withDot s = '.':s
| First arg is whether to chop off trailing zeros
showFixed :: (HasResolution a) => Bool -> Fixed a -> String
showFixed chopTrailingZeros fa@(MkFixed a) | a < 0 = "-" ++ (showFixed chopTrailingZeros (asTypeOf (MkFixed (negate a)) fa))
showFixed chopTrailingZeros fa@(MkFixed a) = (show i) ++ (withDot (showIntegerZeros chopTrailingZeros digits fracNum)) where
res = fixedResolution fa
(i,d) = divMod a res
digits = ceiling (logBase 10 (fromInteger res) :: Double)
maxnum = 10 ^ digits
fracNum = div (d * maxnum) res
instance (HasResolution a) => Show (Fixed a) where
show = showFixed False
data E6 = E6
instance HasResolution E6 where
resolution _ = 1000000
type Micro = Fixed E6
data E12 = E12
instance HasResolution E12 where
resolution _ = 1000000000000
type Pico = Fixed E12
|
728de86dbeb8230c9f6ca7516b6e44a434fd29618806664f3751d574ea5a7a9d | stevenproctor/lumberjack | core.clj | (ns lumberjack.core
(require [clj-time.core :as ttime]
[clj-time.coerce :as coerce]
[clj-time.format :as tformat]))
(def ^:dynamic *timestamp-format* "dd/MMM/yyy:HH:mm:ss Z")
(defn parse-datetime [timestamp]
(tformat/parse (tformat/formatter *timestamp-format*) timestamp))
(defn timestamp-in-millis [record]
(coerce/to-long (parse-datetime (:timestamp record))))
(defn with-timestamp-in-millis [record]
(assoc record :timestamp-in-millis (timestamp-in-millis record)))
(def timestamp-resolutions
{:millis 1
:second 1000
:minute (* 1000 60)
:15-minutes (* 1000 60 15)
:hour (* 1000 60 60)})
(defn timestamp-to-resolution [record resolution]
(let [r (resolution timestamp-resolutions)]
(* r (quot (timestamp-in-millis record) r))))
(defn timestamp-millis [record]
(timestamp-to-resolution record :millis))
(defn timestamp-second [record]
(timestamp-to-resolution record :second))
(defn timestamp-minute [record]
(timestamp-to-resolution record :minute))
(defn timestamp-15-minutes [record]
(timestamp-to-resolution record :15-minutes))
(defn timestamp-hour [record]
(timestamp-to-resolution record :hour))
(defn count-entries [records & {:keys [by], :or {by identity}}]
(frequencies (map by records)))
| null | https://raw.githubusercontent.com/stevenproctor/lumberjack/0d43bef62e645c74b3d44bf88d3bc2f224a449d1/src/lumberjack/core.clj | clojure | (ns lumberjack.core
(require [clj-time.core :as ttime]
[clj-time.coerce :as coerce]
[clj-time.format :as tformat]))
(def ^:dynamic *timestamp-format* "dd/MMM/yyy:HH:mm:ss Z")
(defn parse-datetime [timestamp]
(tformat/parse (tformat/formatter *timestamp-format*) timestamp))
(defn timestamp-in-millis [record]
(coerce/to-long (parse-datetime (:timestamp record))))
(defn with-timestamp-in-millis [record]
(assoc record :timestamp-in-millis (timestamp-in-millis record)))
(def timestamp-resolutions
{:millis 1
:second 1000
:minute (* 1000 60)
:15-minutes (* 1000 60 15)
:hour (* 1000 60 60)})
(defn timestamp-to-resolution [record resolution]
(let [r (resolution timestamp-resolutions)]
(* r (quot (timestamp-in-millis record) r))))
(defn timestamp-millis [record]
(timestamp-to-resolution record :millis))
(defn timestamp-second [record]
(timestamp-to-resolution record :second))
(defn timestamp-minute [record]
(timestamp-to-resolution record :minute))
(defn timestamp-15-minutes [record]
(timestamp-to-resolution record :15-minutes))
(defn timestamp-hour [record]
(timestamp-to-resolution record :hour))
(defn count-entries [records & {:keys [by], :or {by identity}}]
(frequencies (map by records)))
| |
0a1f775d89e25d131aeb8ea3689e1878e7661239202cbc82432f92874e92a23f | emqx/emqx-stomp | emqx_stomp_connection.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_stomp_connection).
-behaviour(gen_server).
-include("emqx_stomp.hrl").
-export([ start_link/3
, info/1
]).
gen_server Function Exports
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, code_change/3
, terminate/2
]).
-record(stomp_client, {transport, socket, peername, conn_name, conn_state,
await_recv, rate_limit, parse_fun, proto_state,
proto_env, heartbeat}).
-define(INFO_KEYS, [peername, await_recv, conn_state]).
-define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt]).
-define(LOG(Level, Format, Args, State),
emqx_logger:Level("Stomp(~s): " ++ Format, [State#stomp_client.conn_name | Args])).
start_link(Transport, Sock, ProtoEnv) ->
{ok, proc_lib:spawn_link(?MODULE, init, [[Transport, Sock, ProtoEnv]])}.
info(CPid) ->
gen_server:call(CPid, info, infinity).
init([Transport, Sock, ProtoEnv]) ->
process_flag(trap_exit, true),
case Transport:wait(Sock) of
{ok, NewSock} ->
{ok, Peername} = Transport:ensure_ok_or_exit(peername, [NewSock]),
ConnName = esockd:format(Peername),
SendFun = send_fun(Transport, Sock),
ParseFun = emqx_stomp_frame:parser(ProtoEnv),
ProtoState = emqx_stomp_protocol:init(Peername, SendFun, ProtoEnv),
RateLimit = init_rate_limit(proplists:get_value(rate_limit, ProtoEnv)),
State = run_socket(#stomp_client{transport = Transport,
socket = NewSock,
peername = Peername,
conn_name = ConnName,
conn_state = running,
await_recv = false,
rate_limit = RateLimit,
parse_fun = ParseFun,
proto_env = ProtoEnv,
proto_state = ProtoState}),
gen_server:enter_loop(?MODULE, [{hibernate_after, 5000}], State, 20000);
{error, Reason} ->
{stop, Reason}
end.
init_rate_limit(undefined) ->
undefined;
init_rate_limit({Rate, Burst}) ->
esockd_rate_limit:new(Rate, Burst).
send_fun(Transport, Sock) ->
Self = self(),
fun(Data) ->
try Transport:async_send(Sock, Data) of
ok -> ok;
{error, Reason} -> Self ! {shutdown, Reason}
catch
error:Error -> Self ! {shutdown, Error}
end
end.
handle_call(info, _From, State = #stomp_client{transport = Transport,
socket = Sock,
peername = Peername,
await_recv = AwaitRecv,
conn_state = ConnState,
proto_state = ProtoState}) ->
ClientInfo = [{peername, Peername}, {await_recv, AwaitRecv},
{conn_state, ConnState}],
ProtoInfo = emqx_stomp_protocol:info(ProtoState),
case Transport:getstat(Sock, ?SOCK_STATS) of
{ok, SockStats} ->
{reply, lists:append([ClientInfo, ProtoInfo, SockStats]), State};
{error, Reason} ->
{stop, Reason, lists:append([ClientInfo, ProtoInfo]), State}
end;
handle_call(Req, _From, State) ->
?LOG(error, "unexpected request: ~p", [Req], State),
{reply, ignored, State}.
handle_cast(Msg, State) ->
?LOG(error, "unexpected msg: ~p", [Msg], State),
noreply(State).
handle_info(timeout, State) ->
shutdown(idle_timeout, State);
handle_info({shutdown, Reason}, State) ->
shutdown(Reason, State);
handle_info({transaction, {timeout, Id}}, State) ->
emqx_stomp_transaction:timeout(Id),
noreply(State);
handle_info({heartbeat, start, {Cx, Cy}},
State = #stomp_client{transport = Transport, socket = Sock}) ->
Self = self(),
Incomming = {Cx, statfun(recv_oct, State), fun() -> Self ! {heartbeat, timeout} end},
Outgoing = {Cy, statfun(send_oct, State), fun() -> Transport:send(Sock, <<$\n>>) end},
{ok, HbProc} = emqx_stomp_heartbeat:start_link(Incomming, Outgoing),
noreply(State#stomp_client{heartbeat = HbProc});
handle_info({heartbeat, timeout}, State) ->
stop({shutdown, heartbeat_timeout}, State);
handle_info({'EXIT', HbProc, Error}, State = #stomp_client{heartbeat = HbProc}) ->
stop(Error, State);
handle_info(activate_sock, State) ->
noreply(run_socket(State#stomp_client{conn_state = running}));
handle_info({inet_async, _Sock, _Ref, {ok, Bytes}}, State) ->
?LOG(debug, "RECV ~p", [Bytes], State),
received(Bytes, rate_limit(size(Bytes), State#stomp_client{await_recv = false}));
handle_info({inet_async, _Sock, _Ref, {error, Reason}}, State) ->
shutdown(Reason, State);
handle_info({inet_reply, _Ref, ok}, State) ->
noreply(State);
handle_info({inet_reply, _Sock, {error, Reason}}, State) ->
shutdown(Reason, State);
handle_info({deliver, _Topic, Msg}, State = #stomp_client{proto_state = ProtoState}) ->
noreply(State#stomp_client{proto_state = case emqx_stomp_protocol:send(Msg, ProtoState) of
{ok, ProtoState1} ->
ProtoState1;
{error, dropped, ProtoState1} ->
ProtoState1
end});
handle_info(Info, State) ->
?LOG(error, "Unexpected info: ~p", [Info], State),
noreply(State).
terminate(Reason, State = #stomp_client{transport = Transport,
socket = Sock,
proto_state = ProtoState}) ->
?LOG(info, "terminated for ~p", [Reason], State),
Transport:fast_close(Sock),
case {ProtoState, Reason} of
{undefined, _} -> ok;
{_, {shutdown, Error}} ->
emqx_stomp_protocol:shutdown(Error, ProtoState);
{_, Reason} ->
emqx_stomp_protocol:shutdown(Reason, ProtoState)
end.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Receive and Parse data
%%--------------------------------------------------------------------
received(<<>>, State) ->
noreply(State);
received(Bytes, State = #stomp_client{parse_fun = ParseFun,
proto_state = ProtoState}) ->
try ParseFun(Bytes) of
{more, NewParseFun} ->
noreply(State#stomp_client{parse_fun = NewParseFun});
{ok, Frame, Rest} ->
?LOG(info, "RECV Frame: ~s", [emqx_stomp_frame:format(Frame)], State),
case emqx_stomp_protocol:received(Frame, ProtoState) of
{ok, ProtoState1} ->
received(Rest, reset_parser(State#stomp_client{proto_state = ProtoState1}));
{error, Error, ProtoState1} ->
shutdown(Error, State#stomp_client{proto_state = ProtoState1});
{stop, Reason, ProtoState1} ->
stop(Reason, State#stomp_client{proto_state = ProtoState1})
end;
{error, Error} ->
?LOG(error, "Framing error - ~s", [Error], State),
?LOG(error, "Bytes: ~p", [Bytes], State),
shutdown(frame_error, State)
catch
_Error:Reason ->
?LOG(error, "Parser failed for ~p", [Reason], State),
?LOG(error, "Error data: ~p", [Bytes], State),
shutdown(parse_error, State)
end.
reset_parser(State = #stomp_client{proto_env = ProtoEnv}) ->
State#stomp_client{parse_fun = emqx_stomp_frame:parser(ProtoEnv)}.
rate_limit(_Size, State = #stomp_client{rate_limit = undefined}) ->
run_socket(State);
rate_limit(Size, State = #stomp_client{rate_limit = Rl}) ->
case esockd_rate_limit:check(Size, Rl) of
{0, Rl1} ->
run_socket(State#stomp_client{conn_state = running, rate_limit = Rl1});
{Pause, Rl1} ->
?LOG(error, "Rate limiter pause for ~p", [Pause], State),
erlang:send_after(Pause, self(), activate_sock),
State#stomp_client{conn_state = blocked, rate_limit = Rl1}
end.
run_socket(State = #stomp_client{conn_state = blocked}) ->
State;
run_socket(State = #stomp_client{await_recv = true}) ->
State;
run_socket(State = #stomp_client{transport = Transport, socket = Sock}) ->
Transport:async_recv(Sock, 0, infinity),
State#stomp_client{await_recv = true}.
statfun(Stat, #stomp_client{transport = Transport, socket = Sock}) ->
fun() ->
case Transport:getstat(Sock, [Stat]) of
{ok, [{Stat, Val}]} -> {ok, Val};
{error, Error} -> {error, Error}
end
end.
noreply(State) ->
{noreply, State}.
stop(Reason, State) ->
{stop, Reason, State}.
shutdown(Reason, State) ->
stop({shutdown, Reason}, State).
| null | https://raw.githubusercontent.com/emqx/emqx-stomp/07167183f3288abe555c4f73dafd1488216c1f11/src/emqx_stomp_connection.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_stomp_connection).
-behaviour(gen_server).
-include("emqx_stomp.hrl").
-export([ start_link/3
, info/1
]).
gen_server Function Exports
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, code_change/3
, terminate/2
]).
-record(stomp_client, {transport, socket, peername, conn_name, conn_state,
await_recv, rate_limit, parse_fun, proto_state,
proto_env, heartbeat}).
-define(INFO_KEYS, [peername, await_recv, conn_state]).
-define(SOCK_STATS, [recv_oct, recv_cnt, send_oct, send_cnt]).
-define(LOG(Level, Format, Args, State),
emqx_logger:Level("Stomp(~s): " ++ Format, [State#stomp_client.conn_name | Args])).
start_link(Transport, Sock, ProtoEnv) ->
{ok, proc_lib:spawn_link(?MODULE, init, [[Transport, Sock, ProtoEnv]])}.
info(CPid) ->
gen_server:call(CPid, info, infinity).
init([Transport, Sock, ProtoEnv]) ->
process_flag(trap_exit, true),
case Transport:wait(Sock) of
{ok, NewSock} ->
{ok, Peername} = Transport:ensure_ok_or_exit(peername, [NewSock]),
ConnName = esockd:format(Peername),
SendFun = send_fun(Transport, Sock),
ParseFun = emqx_stomp_frame:parser(ProtoEnv),
ProtoState = emqx_stomp_protocol:init(Peername, SendFun, ProtoEnv),
RateLimit = init_rate_limit(proplists:get_value(rate_limit, ProtoEnv)),
State = run_socket(#stomp_client{transport = Transport,
socket = NewSock,
peername = Peername,
conn_name = ConnName,
conn_state = running,
await_recv = false,
rate_limit = RateLimit,
parse_fun = ParseFun,
proto_env = ProtoEnv,
proto_state = ProtoState}),
gen_server:enter_loop(?MODULE, [{hibernate_after, 5000}], State, 20000);
{error, Reason} ->
{stop, Reason}
end.
init_rate_limit(undefined) ->
undefined;
init_rate_limit({Rate, Burst}) ->
esockd_rate_limit:new(Rate, Burst).
send_fun(Transport, Sock) ->
Self = self(),
fun(Data) ->
try Transport:async_send(Sock, Data) of
ok -> ok;
{error, Reason} -> Self ! {shutdown, Reason}
catch
error:Error -> Self ! {shutdown, Error}
end
end.
handle_call(info, _From, State = #stomp_client{transport = Transport,
socket = Sock,
peername = Peername,
await_recv = AwaitRecv,
conn_state = ConnState,
proto_state = ProtoState}) ->
ClientInfo = [{peername, Peername}, {await_recv, AwaitRecv},
{conn_state, ConnState}],
ProtoInfo = emqx_stomp_protocol:info(ProtoState),
case Transport:getstat(Sock, ?SOCK_STATS) of
{ok, SockStats} ->
{reply, lists:append([ClientInfo, ProtoInfo, SockStats]), State};
{error, Reason} ->
{stop, Reason, lists:append([ClientInfo, ProtoInfo]), State}
end;
handle_call(Req, _From, State) ->
?LOG(error, "unexpected request: ~p", [Req], State),
{reply, ignored, State}.
handle_cast(Msg, State) ->
?LOG(error, "unexpected msg: ~p", [Msg], State),
noreply(State).
handle_info(timeout, State) ->
shutdown(idle_timeout, State);
handle_info({shutdown, Reason}, State) ->
shutdown(Reason, State);
handle_info({transaction, {timeout, Id}}, State) ->
emqx_stomp_transaction:timeout(Id),
noreply(State);
handle_info({heartbeat, start, {Cx, Cy}},
State = #stomp_client{transport = Transport, socket = Sock}) ->
Self = self(),
Incomming = {Cx, statfun(recv_oct, State), fun() -> Self ! {heartbeat, timeout} end},
Outgoing = {Cy, statfun(send_oct, State), fun() -> Transport:send(Sock, <<$\n>>) end},
{ok, HbProc} = emqx_stomp_heartbeat:start_link(Incomming, Outgoing),
noreply(State#stomp_client{heartbeat = HbProc});
handle_info({heartbeat, timeout}, State) ->
stop({shutdown, heartbeat_timeout}, State);
handle_info({'EXIT', HbProc, Error}, State = #stomp_client{heartbeat = HbProc}) ->
stop(Error, State);
handle_info(activate_sock, State) ->
noreply(run_socket(State#stomp_client{conn_state = running}));
handle_info({inet_async, _Sock, _Ref, {ok, Bytes}}, State) ->
?LOG(debug, "RECV ~p", [Bytes], State),
received(Bytes, rate_limit(size(Bytes), State#stomp_client{await_recv = false}));
handle_info({inet_async, _Sock, _Ref, {error, Reason}}, State) ->
shutdown(Reason, State);
handle_info({inet_reply, _Ref, ok}, State) ->
noreply(State);
handle_info({inet_reply, _Sock, {error, Reason}}, State) ->
shutdown(Reason, State);
handle_info({deliver, _Topic, Msg}, State = #stomp_client{proto_state = ProtoState}) ->
noreply(State#stomp_client{proto_state = case emqx_stomp_protocol:send(Msg, ProtoState) of
{ok, ProtoState1} ->
ProtoState1;
{error, dropped, ProtoState1} ->
ProtoState1
end});
handle_info(Info, State) ->
?LOG(error, "Unexpected info: ~p", [Info], State),
noreply(State).
terminate(Reason, State = #stomp_client{transport = Transport,
socket = Sock,
proto_state = ProtoState}) ->
?LOG(info, "terminated for ~p", [Reason], State),
Transport:fast_close(Sock),
case {ProtoState, Reason} of
{undefined, _} -> ok;
{_, {shutdown, Error}} ->
emqx_stomp_protocol:shutdown(Error, ProtoState);
{_, Reason} ->
emqx_stomp_protocol:shutdown(Reason, ProtoState)
end.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Receive and Parse data
received(<<>>, State) ->
noreply(State);
received(Bytes, State = #stomp_client{parse_fun = ParseFun,
proto_state = ProtoState}) ->
try ParseFun(Bytes) of
{more, NewParseFun} ->
noreply(State#stomp_client{parse_fun = NewParseFun});
{ok, Frame, Rest} ->
?LOG(info, "RECV Frame: ~s", [emqx_stomp_frame:format(Frame)], State),
case emqx_stomp_protocol:received(Frame, ProtoState) of
{ok, ProtoState1} ->
received(Rest, reset_parser(State#stomp_client{proto_state = ProtoState1}));
{error, Error, ProtoState1} ->
shutdown(Error, State#stomp_client{proto_state = ProtoState1});
{stop, Reason, ProtoState1} ->
stop(Reason, State#stomp_client{proto_state = ProtoState1})
end;
{error, Error} ->
?LOG(error, "Framing error - ~s", [Error], State),
?LOG(error, "Bytes: ~p", [Bytes], State),
shutdown(frame_error, State)
catch
_Error:Reason ->
?LOG(error, "Parser failed for ~p", [Reason], State),
?LOG(error, "Error data: ~p", [Bytes], State),
shutdown(parse_error, State)
end.
reset_parser(State = #stomp_client{proto_env = ProtoEnv}) ->
State#stomp_client{parse_fun = emqx_stomp_frame:parser(ProtoEnv)}.
rate_limit(_Size, State = #stomp_client{rate_limit = undefined}) ->
run_socket(State);
rate_limit(Size, State = #stomp_client{rate_limit = Rl}) ->
case esockd_rate_limit:check(Size, Rl) of
{0, Rl1} ->
run_socket(State#stomp_client{conn_state = running, rate_limit = Rl1});
{Pause, Rl1} ->
?LOG(error, "Rate limiter pause for ~p", [Pause], State),
erlang:send_after(Pause, self(), activate_sock),
State#stomp_client{conn_state = blocked, rate_limit = Rl1}
end.
run_socket(State = #stomp_client{conn_state = blocked}) ->
State;
run_socket(State = #stomp_client{await_recv = true}) ->
State;
run_socket(State = #stomp_client{transport = Transport, socket = Sock}) ->
Transport:async_recv(Sock, 0, infinity),
State#stomp_client{await_recv = true}.
statfun(Stat, #stomp_client{transport = Transport, socket = Sock}) ->
fun() ->
case Transport:getstat(Sock, [Stat]) of
{ok, [{Stat, Val}]} -> {ok, Val};
{error, Error} -> {error, Error}
end
end.
noreply(State) ->
{noreply, State}.
stop(Reason, State) ->
{stop, Reason, State}.
shutdown(Reason, State) ->
stop({shutdown, Reason}, State).
|
6a69cc01ef76f920b70ffd9ec0a8a3025e60d5251b8354622255851e21193132 | brendanhay/gogol | UpdateOrganizationSettings.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . . Organizations . UpdateOrganizationSettings
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Updates an organization\'s settings.
--
-- /See:/ < Security Command Center API Reference> for @securitycenter.organizations.updateOrganizationSettings@.
module Gogol.SecurityCenter.Organizations.UpdateOrganizationSettings
( -- * Resource
SecurityCenterOrganizationsUpdateOrganizationSettingsResource,
-- ** Constructing a Request
SecurityCenterOrganizationsUpdateOrganizationSettings (..),
newSecurityCenterOrganizationsUpdateOrganizationSettings,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SecurityCenter.Types
| A resource alias for method which the
-- 'SecurityCenterOrganizationsUpdateOrganizationSettings' request conforms to.
type SecurityCenterOrganizationsUpdateOrganizationSettingsResource =
"v1p1beta1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] OrganizationSettings
Core.:> Core.Patch '[Core.JSON] OrganizationSettings
-- | Updates an organization\'s settings.
--
-- /See:/ 'newSecurityCenterOrganizationsUpdateOrganizationSettings' smart constructor.
data SecurityCenterOrganizationsUpdateOrganizationSettings = SecurityCenterOrganizationsUpdateOrganizationSettings
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | The relative resource name of the settings. See: https:\/\/cloud.google.com\/apis\/design\/resource/names#relative/resource/name Example: \"organizations\/{organization/id}\/organizationSettings\".
name :: Core.Text,
-- | Multipart request metadata.
payload :: OrganizationSettings,
-- | The FieldMask to use when updating the settings resource. If empty all mutable fields will be updated.
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'SecurityCenterOrganizationsUpdateOrganizationSettings' with the minimum fields required to make a request.
newSecurityCenterOrganizationsUpdateOrganizationSettings ::
-- | The relative resource name of the settings. See: https:\/\/cloud.google.com\/apis\/design\/resource/names#relative/resource/name Example: \"organizations\/{organization/id}\/organizationSettings\". See 'name'.
Core.Text ->
-- | Multipart request metadata. See 'payload'.
OrganizationSettings ->
SecurityCenterOrganizationsUpdateOrganizationSettings
newSecurityCenterOrganizationsUpdateOrganizationSettings name payload =
SecurityCenterOrganizationsUpdateOrganizationSettings
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SecurityCenterOrganizationsUpdateOrganizationSettings
where
type
Rs
SecurityCenterOrganizationsUpdateOrganizationSettings =
OrganizationSettings
type
Scopes
SecurityCenterOrganizationsUpdateOrganizationSettings =
'[CloudPlatform'FullControl]
requestClient
SecurityCenterOrganizationsUpdateOrganizationSettings {..} =
go
name
xgafv
accessToken
callback
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
securityCenterService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SecurityCenterOrganizationsUpdateOrganizationSettingsResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-securitycenter/gen/Gogol/SecurityCenter/Organizations/UpdateOrganizationSettings.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Updates an organization\'s settings.
/See:/ < Security Command Center API Reference> for @securitycenter.organizations.updateOrganizationSettings@.
* Resource
** Constructing a Request
'SecurityCenterOrganizationsUpdateOrganizationSettings' request conforms to.
| Updates an organization\'s settings.
/See:/ 'newSecurityCenterOrganizationsUpdateOrganizationSettings' smart constructor.
| V1 error format.
| OAuth access token.
| The relative resource name of the settings. See: https:\/\/cloud.google.com\/apis\/design\/resource/names#relative/resource/name Example: \"organizations\/{organization/id}\/organizationSettings\".
| Multipart request metadata.
| The FieldMask to use when updating the settings resource. If empty all mutable fields will be updated.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'SecurityCenterOrganizationsUpdateOrganizationSettings' with the minimum fields required to make a request.
| The relative resource name of the settings. See: https:\/\/cloud.google.com\/apis\/design\/resource/names#relative/resource/name Example: \"organizations\/{organization/id}\/organizationSettings\". See 'name'.
| Multipart request metadata. See 'payload'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . . Organizations . UpdateOrganizationSettings
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.SecurityCenter.Organizations.UpdateOrganizationSettings
SecurityCenterOrganizationsUpdateOrganizationSettingsResource,
SecurityCenterOrganizationsUpdateOrganizationSettings (..),
newSecurityCenterOrganizationsUpdateOrganizationSettings,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SecurityCenter.Types
| A resource alias for method which the
type SecurityCenterOrganizationsUpdateOrganizationSettingsResource =
"v1p1beta1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] OrganizationSettings
Core.:> Core.Patch '[Core.JSON] OrganizationSettings
data SecurityCenterOrganizationsUpdateOrganizationSettings = SecurityCenterOrganizationsUpdateOrganizationSettings
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
name :: Core.Text,
payload :: OrganizationSettings,
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSecurityCenterOrganizationsUpdateOrganizationSettings ::
Core.Text ->
OrganizationSettings ->
SecurityCenterOrganizationsUpdateOrganizationSettings
newSecurityCenterOrganizationsUpdateOrganizationSettings name payload =
SecurityCenterOrganizationsUpdateOrganizationSettings
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SecurityCenterOrganizationsUpdateOrganizationSettings
where
type
Rs
SecurityCenterOrganizationsUpdateOrganizationSettings =
OrganizationSettings
type
Scopes
SecurityCenterOrganizationsUpdateOrganizationSettings =
'[CloudPlatform'FullControl]
requestClient
SecurityCenterOrganizationsUpdateOrganizationSettings {..} =
go
name
xgafv
accessToken
callback
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
securityCenterService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
SecurityCenterOrganizationsUpdateOrganizationSettingsResource
)
Core.mempty
|
d4812dd4cbd4ee26dc94958f5e4a8ec6a6cc08a9ee0a9717d42d96efb8460e5f | fpco/unliftio | Memoize.hs | # LANGUAGE GeneralizedNewtypeDeriving #
-- | Memoize the results of actions. In other words: actions
-- will be run once, on demand, and their results saved.
--
-- Exceptions semantics: if a synchronous exception is thrown while performing
-- the computation, that result will be saved and rethrown each time
' runMemoized ' is called subsequently . '
--
-- @since 0.2.8.0
module UnliftIO.Memoize
( Memoized
, runMemoized
, memoizeRef
, memoizeMVar
) where
import Control.Applicative as A
import Control.Monad (join)
import Control.Monad.IO.Unlift
import UnliftIO.Exception
import UnliftIO.IORef
import UnliftIO.MVar
-- | A \"run once\" value, with results saved. Extract the value with
' runMemoized ' . For single - threaded usage , you can use ' memoizeRef ' to
create a value . If you need guarantees that only one thread will run the
action at a time , use ' memoizeMVar ' .
--
-- Note that this type provides a 'Show' instance for convenience, but not
-- useful information can be provided.
--
-- @since 0.2.8.0
newtype Memoized a = Memoized (IO a)
deriving (Functor, A.Applicative, Monad)
instance Show (Memoized a) where
show _ = "<<Memoized>>"
-- | Extract a value from a 'Memoized', running an action if no cached value is
-- available.
--
-- @since 0.2.8.0
runMemoized :: MonadIO m => Memoized a -> m a
runMemoized (Memoized m) = liftIO m
# INLINE runMemoized #
-- | Create a new 'Memoized' value using an 'IORef' under the surface. Note that
-- the action may be run in multiple threads simultaneously, so this may not be
-- thread safe (depending on the underlying action). Consider using
' memoizeMVar ' .
--
-- @since 0.2.8.0
memoizeRef :: MonadUnliftIO m => m a -> m (Memoized a)
memoizeRef action = withRunInIO $ \run -> do
ref <- newIORef Nothing
pure $ Memoized $ do
mres <- readIORef ref
res <-
case mres of
Just res -> pure res
Nothing -> do
res <- tryAny $ run action
writeIORef ref $ Just res
pure res
either throwIO pure res
| Same as ' memoizeRef ' , but uses an ' MVar ' to ensure that an action is
-- only run once, even in a multithreaded application.
--
-- @since 0.2.8.0
memoizeMVar :: MonadUnliftIO m => m a -> m (Memoized a)
memoizeMVar action = withRunInIO $ \run -> do
var <- newMVar Nothing
pure $ Memoized $ join $ modifyMVar var $ \mres -> do
res <- maybe (tryAny $ run action) pure mres
pure (Just res, either throwIO pure res)
| null | https://raw.githubusercontent.com/fpco/unliftio/d7ac43b9ae69efea0ca911aa556852e9f95af128/unliftio/src/UnliftIO/Memoize.hs | haskell | | Memoize the results of actions. In other words: actions
will be run once, on demand, and their results saved.
Exceptions semantics: if a synchronous exception is thrown while performing
the computation, that result will be saved and rethrown each time
@since 0.2.8.0
| A \"run once\" value, with results saved. Extract the value with
Note that this type provides a 'Show' instance for convenience, but not
useful information can be provided.
@since 0.2.8.0
| Extract a value from a 'Memoized', running an action if no cached value is
available.
@since 0.2.8.0
| Create a new 'Memoized' value using an 'IORef' under the surface. Note that
the action may be run in multiple threads simultaneously, so this may not be
thread safe (depending on the underlying action). Consider using
@since 0.2.8.0
only run once, even in a multithreaded application.
@since 0.2.8.0 | # LANGUAGE GeneralizedNewtypeDeriving #
' runMemoized ' is called subsequently . '
module UnliftIO.Memoize
( Memoized
, runMemoized
, memoizeRef
, memoizeMVar
) where
import Control.Applicative as A
import Control.Monad (join)
import Control.Monad.IO.Unlift
import UnliftIO.Exception
import UnliftIO.IORef
import UnliftIO.MVar
' runMemoized ' . For single - threaded usage , you can use ' memoizeRef ' to
create a value . If you need guarantees that only one thread will run the
action at a time , use ' memoizeMVar ' .
newtype Memoized a = Memoized (IO a)
deriving (Functor, A.Applicative, Monad)
instance Show (Memoized a) where
show _ = "<<Memoized>>"
runMemoized :: MonadIO m => Memoized a -> m a
runMemoized (Memoized m) = liftIO m
# INLINE runMemoized #
' memoizeMVar ' .
memoizeRef :: MonadUnliftIO m => m a -> m (Memoized a)
memoizeRef action = withRunInIO $ \run -> do
ref <- newIORef Nothing
pure $ Memoized $ do
mres <- readIORef ref
res <-
case mres of
Just res -> pure res
Nothing -> do
res <- tryAny $ run action
writeIORef ref $ Just res
pure res
either throwIO pure res
| Same as ' memoizeRef ' , but uses an ' MVar ' to ensure that an action is
memoizeMVar :: MonadUnliftIO m => m a -> m (Memoized a)
memoizeMVar action = withRunInIO $ \run -> do
var <- newMVar Nothing
pure $ Memoized $ join $ modifyMVar var $ \mres -> do
res <- maybe (tryAny $ run action) pure mres
pure (Just res, either throwIO pure res)
|
c7316a6b31d47560a37697673a76a0fe554a81d7847e404c41c4b16e71a21617 | jaspervdj/firefly | Internal.hs | --------------------------------------------------------------------------------
# LANGUAGE ForeignFunctionInterface #
module Firefly.Video.Texture.Internal
( CTexture
, Texture (..)
, textureFromImage
, textureFromPng
, textureSize
, textureSlice
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Foreign.C.String
import Foreign.C.Types
import Foreign.ForeignPtr
import Foreign.Ptr
import System.IO.Unsafe (unsafePerformIO)
--------------------------------------------------------------------------------
import Firefly.Video.Internal
--------------------------------------------------------------------------------
foreign import ccall unsafe "ff_textureFromImage" ff_textureFromImage
:: Ptr CImage -> IO (Ptr CTexture)
foreign import ccall unsafe "ff_textureFromPng" ff_textureFromPng
:: CString -> IO (Ptr CTexture)
foreign import ccall "&ff_textureFree" ff_textureFree
:: FunPtr (Ptr CTexture -> IO ())
foreign import ccall unsafe "ff_textureId" ff_textureId
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureWidth" ff_textureWidth
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureHeight" ff_textureHeight
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureSlice" ff_textureSlice
:: Ptr CTexture -> CInt -> CInt -> CInt -> CInt -> IO (Ptr CTexture)
--------------------------------------------------------------------------------
type CTexture = CChar
--------------------------------------------------------------------------------
newtype Texture = Texture (ForeignPtr CTexture)
--------------------------------------------------------------------------------
instance Eq Texture where
x == y = textureId x == textureId y
--------------------------------------------------------------------------------
instance Ord Texture where
compare x y = compare (textureId x) (textureId y)
--------------------------------------------------------------------------------
instance Show Texture where
show t = "(Texture " ++
"id=" ++ show (textureId t) ++ ", " ++
"size=" ++ show (textureSize t) ++ ")"
--------------------------------------------------------------------------------
textureFromImage :: Image -> IO Texture
textureFromImage (Image ifptr) = withForeignPtr ifptr $ \iptr -> do
tptr <- ff_textureFromImage iptr
Texture <$> newForeignPtr ff_textureFree tptr
--------------------------------------------------------------------------------
textureFromPng :: FilePath -> IO Texture
textureFromPng filePath = do
ptr <- withCString filePath ff_textureFromPng
if ptr /= nullPtr
then Texture <$> newForeignPtr ff_textureFree ptr
else error $
"Firefly.Video.Texture.textureFromPng: Can't load " ++ show filePath
--------------------------------------------------------------------------------
textureId :: Texture -> Int
textureId (Texture fptr) = unsafePerformIO $ withForeignPtr fptr $
fmap fromIntegral . ff_textureId
--------------------------------------------------------------------------------
textureSize :: Texture -> (Int, Int)
textureSize (Texture fptr) = unsafePerformIO $ withForeignPtr fptr $ \ptr -> do
w <- ff_textureWidth ptr
h <- ff_textureHeight ptr
return (fromIntegral w, fromIntegral h)
--------------------------------------------------------------------------------
textureSlice :: (Int, Int) -- ^ (X, Y)
^ ( Width , )
-> Texture -- ^ Original image
-> Texture -- ^ Sliced image
textureSlice (x, y) (w, h) (Texture fptr) = unsafePerformIO $
withForeignPtr fptr $ \ptr -> do
ptr' <- ff_textureSlice ptr
(fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h)
Texture <$> newForeignPtr ff_textureFree ptr'
| null | https://raw.githubusercontent.com/jaspervdj/firefly/71e1f5f11293272bedc26444446553a24ee318ad/src/Firefly/Video/Texture/Internal.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
^ (X, Y)
^ Original image
^ Sliced image | # LANGUAGE ForeignFunctionInterface #
module Firefly.Video.Texture.Internal
( CTexture
, Texture (..)
, textureFromImage
, textureFromPng
, textureSize
, textureSlice
) where
import Control.Applicative ((<$>))
import Foreign.C.String
import Foreign.C.Types
import Foreign.ForeignPtr
import Foreign.Ptr
import System.IO.Unsafe (unsafePerformIO)
import Firefly.Video.Internal
foreign import ccall unsafe "ff_textureFromImage" ff_textureFromImage
:: Ptr CImage -> IO (Ptr CTexture)
foreign import ccall unsafe "ff_textureFromPng" ff_textureFromPng
:: CString -> IO (Ptr CTexture)
foreign import ccall "&ff_textureFree" ff_textureFree
:: FunPtr (Ptr CTexture -> IO ())
foreign import ccall unsafe "ff_textureId" ff_textureId
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureWidth" ff_textureWidth
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureHeight" ff_textureHeight
:: Ptr CTexture -> IO CInt
foreign import ccall unsafe "ff_textureSlice" ff_textureSlice
:: Ptr CTexture -> CInt -> CInt -> CInt -> CInt -> IO (Ptr CTexture)
type CTexture = CChar
newtype Texture = Texture (ForeignPtr CTexture)
instance Eq Texture where
x == y = textureId x == textureId y
instance Ord Texture where
compare x y = compare (textureId x) (textureId y)
instance Show Texture where
show t = "(Texture " ++
"id=" ++ show (textureId t) ++ ", " ++
"size=" ++ show (textureSize t) ++ ")"
textureFromImage :: Image -> IO Texture
textureFromImage (Image ifptr) = withForeignPtr ifptr $ \iptr -> do
tptr <- ff_textureFromImage iptr
Texture <$> newForeignPtr ff_textureFree tptr
textureFromPng :: FilePath -> IO Texture
textureFromPng filePath = do
ptr <- withCString filePath ff_textureFromPng
if ptr /= nullPtr
then Texture <$> newForeignPtr ff_textureFree ptr
else error $
"Firefly.Video.Texture.textureFromPng: Can't load " ++ show filePath
textureId :: Texture -> Int
textureId (Texture fptr) = unsafePerformIO $ withForeignPtr fptr $
fmap fromIntegral . ff_textureId
textureSize :: Texture -> (Int, Int)
textureSize (Texture fptr) = unsafePerformIO $ withForeignPtr fptr $ \ptr -> do
w <- ff_textureWidth ptr
h <- ff_textureHeight ptr
return (fromIntegral w, fromIntegral h)
^ ( Width , )
textureSlice (x, y) (w, h) (Texture fptr) = unsafePerformIO $
withForeignPtr fptr $ \ptr -> do
ptr' <- ff_textureSlice ptr
(fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h)
Texture <$> newForeignPtr ff_textureFree ptr'
|
cdd1ad55be148b4b5ebfc552d3e893da7a856bd2ee54b79d1f3982e1d1443e7d | clojure-emacs/enrich-classpath | version.clj | (ns cider.enrich-classpath.version)
(def data-version 1)
(defn long-not= [^long x, ^long y] ;; coerces to primitive long at the edges
(not= x y))
(defn outdated-data-version? [m]
(-> m
:enrich-classpath/version ;; can be nil (handling maps before versioning was introduced)
(or 0)
(long-not= data-version)))
| null | https://raw.githubusercontent.com/clojure-emacs/enrich-classpath/9ca0daeeffab8f90445715227792394ccd6cb9ec/src/cider/enrich_classpath/version.clj | clojure | coerces to primitive long at the edges
can be nil (handling maps before versioning was introduced) | (ns cider.enrich-classpath.version)
(def data-version 1)
(not= x y))
(defn outdated-data-version? [m]
(-> m
(or 0)
(long-not= data-version)))
|
4e028975febe5a985ff4c192fccfe1d1c370e5c9aad50f71dfd1f188b6b4e8bb | patrickt/bracer | Expressions.hs | module Language.Bracer.Backends.C.Parser.Expressions where
import Prelude ()
import Overture hiding (try)
import Language.Bracer
import Language.Bracer.Backends.C.Syntax as C
import Language.Bracer.Backends.C.Parser.Internal
import Language.Bracer.Backends.C.Parser.Types ()
import qualified Text.Parser.Expression as E
import Text.Trifecta
reserved = reserve identifierStyle
instance ExpressionParsing CParser where
: expressions are either Literals , Idents , Exprs , or Operators
type ExpressionSig CParser = Expr :+: Operator :+: TypeSig CParser
parsePrefixOperator = choice
[ iDec <$ (symbol "--" <* notFollowedBy (symbol "-"))
, iInc <$ (symbol "++" <* notFollowedBy (symbol "+"))
, try $ iCast <$> parens (deepInject <$> parseTypeName)
, iRef <$ symbol "&"
, iDeref <$ symbol "*"
, iPos <$ symbol "+"
, iNeg <$ symbol "-"
, iBitwise Neg <$ symbol "~"
, iNot <$ symbol "!"
, iSizeOf <$ reserved "sizeof"
]
parsePostfixOperator = choice
[ iIndex <$$> brackets (deepInject <$> parseExpression)
, iCall <$$> parens (commaSep parseExpression)
, parseAccessor
, iUnary <$> (iPostInc <$ reserved "++")
, iUnary <$> (iPostDec <$ reserved "--")
] where
infixl 1 <$$>
a <$$> b = (flip a) <$> b
parseAccessor = do
operator <- choice [ iDot <$ dot, iArrow <$ symbol "->" ]
nam <- (deepInject <$> parseIdentifier)
return (\x -> iAccess x operator nam)
infixOperatorTable = []
type ExpressionT = Term (ExpressionSig CParser)
parsePrimaryExpression :: CParser ExpressionT
parsePrimaryExpression = choice
[ deepInject <$> parseIdentifier
, deepInject <$> parseLiteral
, iParen <$> parens parseExpression
]
parsePostfixExpression :: CParser ExpressionT
parsePostfixExpression = do
subject <- parsePrimaryExpression
postfixes <- many parsePostfixOperator
return $ foldl (>>>) id postfixes subject
parsePrefixExpression :: CParser ExpressionT
parsePrefixExpression = foldl (<<<) id <$> (many (iUnary <$> parsePrefixOperator)) <*> parsePostfixExpression
parseInfixExpression :: CParser ExpressionT
parseInfixExpression = E.buildExpressionParser infixOperatorTable parsePrefixExpression
parseExpression :: CParser ExpressionT
parseExpression = parseInfixExpression
| null | https://raw.githubusercontent.com/patrickt/bracer/ebad062d421f7678ddafc442245e361c0423cb1b/Language/Bracer/Backends/C/Parser/Expressions.hs | haskell | module Language.Bracer.Backends.C.Parser.Expressions where
import Prelude ()
import Overture hiding (try)
import Language.Bracer
import Language.Bracer.Backends.C.Syntax as C
import Language.Bracer.Backends.C.Parser.Internal
import Language.Bracer.Backends.C.Parser.Types ()
import qualified Text.Parser.Expression as E
import Text.Trifecta
reserved = reserve identifierStyle
instance ExpressionParsing CParser where
: expressions are either Literals , Idents , Exprs , or Operators
type ExpressionSig CParser = Expr :+: Operator :+: TypeSig CParser
parsePrefixOperator = choice
[ iDec <$ (symbol "--" <* notFollowedBy (symbol "-"))
, iInc <$ (symbol "++" <* notFollowedBy (symbol "+"))
, try $ iCast <$> parens (deepInject <$> parseTypeName)
, iRef <$ symbol "&"
, iDeref <$ symbol "*"
, iPos <$ symbol "+"
, iNeg <$ symbol "-"
, iBitwise Neg <$ symbol "~"
, iNot <$ symbol "!"
, iSizeOf <$ reserved "sizeof"
]
parsePostfixOperator = choice
[ iIndex <$$> brackets (deepInject <$> parseExpression)
, iCall <$$> parens (commaSep parseExpression)
, parseAccessor
, iUnary <$> (iPostInc <$ reserved "++")
, iUnary <$> (iPostDec <$ reserved "--")
] where
infixl 1 <$$>
a <$$> b = (flip a) <$> b
parseAccessor = do
operator <- choice [ iDot <$ dot, iArrow <$ symbol "->" ]
nam <- (deepInject <$> parseIdentifier)
return (\x -> iAccess x operator nam)
infixOperatorTable = []
type ExpressionT = Term (ExpressionSig CParser)
parsePrimaryExpression :: CParser ExpressionT
parsePrimaryExpression = choice
[ deepInject <$> parseIdentifier
, deepInject <$> parseLiteral
, iParen <$> parens parseExpression
]
parsePostfixExpression :: CParser ExpressionT
parsePostfixExpression = do
subject <- parsePrimaryExpression
postfixes <- many parsePostfixOperator
return $ foldl (>>>) id postfixes subject
parsePrefixExpression :: CParser ExpressionT
parsePrefixExpression = foldl (<<<) id <$> (many (iUnary <$> parsePrefixOperator)) <*> parsePostfixExpression
parseInfixExpression :: CParser ExpressionT
parseInfixExpression = E.buildExpressionParser infixOperatorTable parsePrefixExpression
parseExpression :: CParser ExpressionT
parseExpression = parseInfixExpression
| |
995febb7e658ccfca74518e2869737f9f82e68a53be0e5b823018a9f7b0fa124 | fulcro-legacy/semantic-ui-wrapper | ui_container.cljs | (ns fulcrologic.semantic-ui.elements.container.ui-container
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/elements/Container/Container" :default Container]))
(def ui-container
"A container limits content to a maximum width.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content.
- fluid (bool): Container has no maximum width.
- text (bool): Reduce maximum width to more naturally accommodate text.
- textAlign (enum): Align container text. (left, center, right, justified)"
(h/factory-apply Container))
| null | https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/elements/container/ui_container.cljs | clojure | (ns fulcrologic.semantic-ui.elements.container.ui-container
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/elements/Container/Container" :default Container]))
(def ui-container
"A container limits content to a maximum width.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content.
- fluid (bool): Container has no maximum width.
- text (bool): Reduce maximum width to more naturally accommodate text.
- textAlign (enum): Align container text. (left, center, right, justified)"
(h/factory-apply Container))
| |
2cb0f4892a2e59d7520e637059aa63171698b5c655605eb5ece0e81ec080f66a | fishcakez/acceptor_pool | acceptor_pool_test.erl | -module(acceptor_pool_test).
-behaviour(acceptor_pool).
-behaviour(acceptor).
-export([start_link/1]).
-export([init/1]).
-export([acceptor_init/3,
acceptor_continue/3,
acceptor_terminate/2]).
start_link(Spec) ->
acceptor_pool:start_link(?MODULE, Spec).
init(Spec) when is_map(Spec) ->
{ok, {#{}, [Spec]}};
init(ignore) ->
ignore;
init(Fun) when is_function(Fun, 0) ->
init(Fun()).
acceptor_init(_, _, {ok, trap_exit}) ->
_ = process_flag(trap_exit, true),
{ok, trap};
acceptor_init(_, _, Return) ->
Return.
acceptor_continue(_, Socket, _) ->
loop(Socket).
acceptor_terminate(_, _) ->
ok.
loop(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
_ = gen_tcp:send(Socket, Data),
loop(Socket);
{error, Reason} ->
error(Reason, [Socket])
end.
| null | https://raw.githubusercontent.com/fishcakez/acceptor_pool/3cbc455c103b8885401f161fd765a9b2f18203f2/test/acceptor_pool_test.erl | erlang | -module(acceptor_pool_test).
-behaviour(acceptor_pool).
-behaviour(acceptor).
-export([start_link/1]).
-export([init/1]).
-export([acceptor_init/3,
acceptor_continue/3,
acceptor_terminate/2]).
start_link(Spec) ->
acceptor_pool:start_link(?MODULE, Spec).
init(Spec) when is_map(Spec) ->
{ok, {#{}, [Spec]}};
init(ignore) ->
ignore;
init(Fun) when is_function(Fun, 0) ->
init(Fun()).
acceptor_init(_, _, {ok, trap_exit}) ->
_ = process_flag(trap_exit, true),
{ok, trap};
acceptor_init(_, _, Return) ->
Return.
acceptor_continue(_, Socket, _) ->
loop(Socket).
acceptor_terminate(_, _) ->
ok.
loop(Socket) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
_ = gen_tcp:send(Socket, Data),
loop(Socket);
{error, Reason} ->
error(Reason, [Socket])
end.
| |
3a00da49fcba79fba54b5ec91c08702aa5b20e261e9c75901314884ed5a2d0f6 | GaloisInc/semmc | Formula.hs | # LANGUAGE TypeApplications #
module Formula ( tests ) where
import qualified Data.Set as Set
import qualified Test.Tasty as T
import qualified Test.Tasty.HUnit as T
import qualified SemMC.Formula as F
import SemMC.Toy ( Toy )
tests :: T.TestTree
tests = T.testGroup "Formula" [ sanityChecks ]
sanityChecks :: T.TestTree
sanityChecks = T.testCase "sanityChecks" $ do
T.assertEqual "empty formula has no inputs" (F.formInputs @Toy @Int F.emptyFormula) Set.empty
T.assertEqual "empty formula has no outputs" (F.formOutputs @Toy @Int F.emptyFormula) Set.empty
| null | https://raw.githubusercontent.com/GaloisInc/semmc/4dc4439720b3b0de8812a68f8156dc89da76da57/semmc-toy/tests/Formula.hs | haskell | # LANGUAGE TypeApplications #
module Formula ( tests ) where
import qualified Data.Set as Set
import qualified Test.Tasty as T
import qualified Test.Tasty.HUnit as T
import qualified SemMC.Formula as F
import SemMC.Toy ( Toy )
tests :: T.TestTree
tests = T.testGroup "Formula" [ sanityChecks ]
sanityChecks :: T.TestTree
sanityChecks = T.testCase "sanityChecks" $ do
T.assertEqual "empty formula has no inputs" (F.formInputs @Toy @Int F.emptyFormula) Set.empty
T.assertEqual "empty formula has no outputs" (F.formOutputs @Toy @Int F.emptyFormula) Set.empty
| |
ebfcc9083d3454b25065e28e370daee2d3c47f5cb041a5590eba515bad50443b | jolby/arrayspace | multiarray_test.clj | (ns arrayspace.multiarray-test
(:require
[clojure.test :refer :all]
[arrayspace.multiarray :refer :all]
[arrayspace.core :refer [mget mset! make-distribution make-multi-array]]
[arrayspace.domain :refer [element-count-of-shape]]
[arrayspace.distributions.partitioned-buffer]))
;;
;; Utility functions
;;
(defn n-dim-progression
"Create a progression of dimensions from 1 to dim
with each dim having count-per-dim elements"
[dim count-per-dim]
(reductions conj [count-per-dim] (take (dec dim) (repeat count-per-dim))))
(defn n-dim-indx
"Create n-dim index with last dim of value idx"
[dim idx]
(map vec (reductions conj (list idx) (take (dec dim) (repeat 0)))))
(defn jarr [element-type shape]
(make-multi-array :default :element-type element-type :shape shape))
(defn buffarr [element-type shape]
(make-multi-array :local-byte-buffer :element-type element-type :shape shape))
(defn pbuffarr [element-type shape]
(let [element-count (element-count-of-shape shape)
pdist (make-distribution :partitioned-byte-buffer
:element-type element-type
:element-count element-count
:partition-count (count shape))]
(make-multi-array :partitioned-byte-buffer
:element-type element-type
:shape shape
:element-count element-count
:distribution pdist)))
(defn test-mget-for-type [element-type type-val shape shape-idx]
(let [a (jarr element-type shape)
buf (buffarr element-type shape)
pbuf (pbuffarr element-type shape)]
(mset! a shape-idx type-val)
(mset! buf shape-idx type-val)
(mset! pbuf shape-idx type-val)
(are [x y] (= x y)
type-val (mget a shape-idx)
type-val (mget buf shape-idx)
type-val (mget pbuf shape-idx))))
;;
;; Fixtures
;;
(def ^:dynamic *primitive-types* [byte char short int long float double])
(def ^:dynamic *type-vals* [(byte 2) (char \a) (short 2)
(int 2) (long 2) (float 2.2) (double 2.2)])
(def ^:dynamic *shapes* (n-dim-progression 5 5))
(def ^:dynamic *indexes* (n-dim-indx 5 1))
(deftest contiguous-array-creation
(testing "Contiguous Array Creation"
(is (not (nil? (jarr double [5 5 5]))))))
(deftest contiguous-buffer-array-creation
(testing "Contiguous Buffer Array Creation"
(is (not (nil? (buffarr double [5 5 5]))))))
(deftest partitioned-buffer-array-creation
(testing "Partitioned Buffer Array Creation"
(is (not (nil? (pbuffarr double [5 5 5]))))))
(deftest mget-test
(testing "mget implementation"
(let [a1 (jarr double [5])
buf1 (buffarr double [5])
a2 (jarr double [5 5])
buf2 (buffarr double [5 5])
a3 (jarr double [5 5 5])
buf3 (buffarr double [5 5 5])
a4 (jarr double [5 5 5 5])
buf4 (buffarr double [5 5 5 5])]
(are [x y] (= x y)
0.0 (mget a1 1)
0.0 (mget buf1 1)
0.0 (mget a2 0 1)
0.0 (mget buf2 0 1)
0.0 (mget a3 0 0 1)
0.0 (mget buf3 0 0 1)
0.0 (mget a4 0 0 0 1)
0.0 (mget buf4 0 0 0 1)))))
(deftest mset!-test
(testing "mset! implementation"
(let [a1 (jarr double [5])
buf1 (buffarr double [5])
a2 (jarr double [5 5])
buf2 (buffarr double [5 5])
a3 (jarr double [5 5 5])
buf3 (buffarr double [5 5 5])
a4 (jarr double [5 5 5 5])
buf4 (buffarr double [5 5 5 5])]
(mset! a1 1 2.2)
(mset! buf1 1 2.2)
(mset! a2 0 1 2.2)
(mset! buf2 0 1 2.2)
(mset! a3 0 0 1 2.2)
(mset! buf3 0 0 1 2.2)
(mset! a4 0 0 0 1 2.2)
(mset! buf4 0 0 0 1 2.2)
(are [x y] (= x y)
2.2 (mget a1 1)
2.2 (mget buf1 1)
2.2 (mget a2 0 1)
2.2 (mget buf2 0 1)
2.2 (mget a3 0 0 1)
2.2 (mget buf3 0 0 1)
2.2 (mget a4 0 0 0 1)
2.2 (mget buf4 0 0 0 1)))))
(deftest mget-types-test
"A more thourough version of above two tests"
(testing "mget over all primitive types"
(dorun (map (fn [type type-val]
(dorun (map (fn [shape shape-idx]
(test-mget-for-type type type-val
shape shape-idx))
*shapes* *indexes*)))
*primitive-types* *type-vals*))))
| null | https://raw.githubusercontent.com/jolby/arrayspace/400d32d486c544b6cc9a1b1e84be7062af7d7f97/test/arrayspace/multiarray_test.clj | clojure |
Utility functions
Fixtures
| (ns arrayspace.multiarray-test
(:require
[clojure.test :refer :all]
[arrayspace.multiarray :refer :all]
[arrayspace.core :refer [mget mset! make-distribution make-multi-array]]
[arrayspace.domain :refer [element-count-of-shape]]
[arrayspace.distributions.partitioned-buffer]))
(defn n-dim-progression
"Create a progression of dimensions from 1 to dim
with each dim having count-per-dim elements"
[dim count-per-dim]
(reductions conj [count-per-dim] (take (dec dim) (repeat count-per-dim))))
(defn n-dim-indx
"Create n-dim index with last dim of value idx"
[dim idx]
(map vec (reductions conj (list idx) (take (dec dim) (repeat 0)))))
(defn jarr [element-type shape]
(make-multi-array :default :element-type element-type :shape shape))
(defn buffarr [element-type shape]
(make-multi-array :local-byte-buffer :element-type element-type :shape shape))
(defn pbuffarr [element-type shape]
(let [element-count (element-count-of-shape shape)
pdist (make-distribution :partitioned-byte-buffer
:element-type element-type
:element-count element-count
:partition-count (count shape))]
(make-multi-array :partitioned-byte-buffer
:element-type element-type
:shape shape
:element-count element-count
:distribution pdist)))
(defn test-mget-for-type [element-type type-val shape shape-idx]
(let [a (jarr element-type shape)
buf (buffarr element-type shape)
pbuf (pbuffarr element-type shape)]
(mset! a shape-idx type-val)
(mset! buf shape-idx type-val)
(mset! pbuf shape-idx type-val)
(are [x y] (= x y)
type-val (mget a shape-idx)
type-val (mget buf shape-idx)
type-val (mget pbuf shape-idx))))
(def ^:dynamic *primitive-types* [byte char short int long float double])
(def ^:dynamic *type-vals* [(byte 2) (char \a) (short 2)
(int 2) (long 2) (float 2.2) (double 2.2)])
(def ^:dynamic *shapes* (n-dim-progression 5 5))
(def ^:dynamic *indexes* (n-dim-indx 5 1))
(deftest contiguous-array-creation
(testing "Contiguous Array Creation"
(is (not (nil? (jarr double [5 5 5]))))))
(deftest contiguous-buffer-array-creation
(testing "Contiguous Buffer Array Creation"
(is (not (nil? (buffarr double [5 5 5]))))))
(deftest partitioned-buffer-array-creation
(testing "Partitioned Buffer Array Creation"
(is (not (nil? (pbuffarr double [5 5 5]))))))
(deftest mget-test
(testing "mget implementation"
(let [a1 (jarr double [5])
buf1 (buffarr double [5])
a2 (jarr double [5 5])
buf2 (buffarr double [5 5])
a3 (jarr double [5 5 5])
buf3 (buffarr double [5 5 5])
a4 (jarr double [5 5 5 5])
buf4 (buffarr double [5 5 5 5])]
(are [x y] (= x y)
0.0 (mget a1 1)
0.0 (mget buf1 1)
0.0 (mget a2 0 1)
0.0 (mget buf2 0 1)
0.0 (mget a3 0 0 1)
0.0 (mget buf3 0 0 1)
0.0 (mget a4 0 0 0 1)
0.0 (mget buf4 0 0 0 1)))))
(deftest mset!-test
(testing "mset! implementation"
(let [a1 (jarr double [5])
buf1 (buffarr double [5])
a2 (jarr double [5 5])
buf2 (buffarr double [5 5])
a3 (jarr double [5 5 5])
buf3 (buffarr double [5 5 5])
a4 (jarr double [5 5 5 5])
buf4 (buffarr double [5 5 5 5])]
(mset! a1 1 2.2)
(mset! buf1 1 2.2)
(mset! a2 0 1 2.2)
(mset! buf2 0 1 2.2)
(mset! a3 0 0 1 2.2)
(mset! buf3 0 0 1 2.2)
(mset! a4 0 0 0 1 2.2)
(mset! buf4 0 0 0 1 2.2)
(are [x y] (= x y)
2.2 (mget a1 1)
2.2 (mget buf1 1)
2.2 (mget a2 0 1)
2.2 (mget buf2 0 1)
2.2 (mget a3 0 0 1)
2.2 (mget buf3 0 0 1)
2.2 (mget a4 0 0 0 1)
2.2 (mget buf4 0 0 0 1)))))
(deftest mget-types-test
"A more thourough version of above two tests"
(testing "mget over all primitive types"
(dorun (map (fn [type type-val]
(dorun (map (fn [shape shape-idx]
(test-mget-for-type type type-val
shape shape-idx))
*shapes* *indexes*)))
*primitive-types* *type-vals*))))
|
7de68314f9cd1f37bd9b0c1266afcebeb6320ccf57d57ca6edd8dd436922910b | dbuenzli/hyperbib | hyperbib_front.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2019 University of Bern . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2019 University of Bern. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open Brr
(* Removable *)
let hui_remover = Jstr.v "data-hui-remover"
let hui_remover_prop = El.Prop.bool hui_remover
let remover e =
if El.prop hui_remover_prop e then () else
let on_pointerdown ev =
Ev.prevent_default ev;
Ev.stop_propagation ev;
in
let on_click ev =
let rem = El.parent e |> Option.get |> El.parent |> Option.get in
Ev.prevent_default ev;
Ev.stop_propagation ev;
Fut.await (Hc_page.Effect.feedback_remove ~target:rem Element) @@ fun () ->
El.remove rem
in
ignore (Ev.listen Ev.click on_click (El.as_target e));
ignore (Ev.listen Ev.pointerdown on_pointerdown (El.as_target e));
El.set_prop hui_remover_prop true e
let remover_interactions () =
let hui_remover = Jstr.v "hui-remove" in
List.iter remover (El.find_by_class hui_remover)
Orderable
let hui_cleanup : unit Ev.type' = Ev.Type.create (Jstr.v "hui-cleanup")
let ordering_cl = Jstr.v "ordering"
let orderable_caret_cl = Jstr.v "orderable-caret"
let orderable_cl = Jstr.v "orderable"
let orderable_placeholder_cl = Jstr.v "orderable-placeholder"
let reordering_cl = Jstr.v "reordering"
let px x = Jstr.(of_float x + v "px")
let set_pos e x y =
El.set_inline_style El.Style.left (px x) e;
El.set_inline_style El.Style.top (px y) e
let set_size e w h =
El.set_inline_style El.Style.width (px w) e;
El.set_inline_style El.Style.height (px h) e
let orderable_peers e = match El.parent e with
| None -> []
| Some p ->
List.filter (fun o -> not (o == e)) @@
El.find_by_class ~root:p orderable_cl
let isect_vertical r o =
(* [true] iff [r]'s top-left or bottom-left or is within [o]'s vertical
bounds *)
let rtop = El.bound_y r in
let rbot = rtop +. El.bound_h r in
((El.bound_y o <= rtop && rtop <= El.bound_y o +. El.bound_h o) ||
(El.bound_y o <= rbot && rbot <= El.bound_y o +. El.bound_h o))
let h_limit_left = 15.
let h_limit_right = 30.
let isect r o = (* [true] iff top-left or bottom-left of [r] is in [o]. *)
let rleft = El.bound_x r in
(El.bound_x o -. h_limit_left <= rleft
&& rleft <= El.bound_x o +. min (El.bound_w o) h_limit_right) &&
isect_vertical r o
let isect_last r o =
(* [true iff top-left or bottom-left within [o] height and not too far. *)
let rleft = El.bound_x r in
let oright = El.bound_x o +. El.bound_w o in
(oright -. h_limit_left < rleft && rleft < oright +. h_limit_right) &&
isect_vertical r o
let rec find_caret_location r = function
| [] -> None
| o :: os ->
if isect r o then Some (`Before, o) else
if os = [] && isect_last r o then Some (`After, o) else
find_caret_location r os
let reordable reordering caret placeholder e =
let off_x = ref 0. and off_y = ref 0. in
let lpointerdown = ref None in
let lpointerup = ref None in
let lpointermove = ref None in
let lhuicleanup = ref None in
let unlisten r = match !r with
| None -> () | Some l -> Ev.unlisten l
in
let on_pointermove ev = match !reordering with
| None -> ()
| Some (r, peers) ->
let m = Ev.Pointer.as_mouse (Ev.as_type ev) in
set_pos r (Ev.Mouse.page_x m -. !off_x) (Ev.Mouse.page_y m -. !off_y);
El.remove caret;
match find_caret_location r peers with
| None -> ()
| Some (ins, o) -> El.insert_siblings ins o [caret]
in
let rec on_pointerup ev =
begin match !reordering with
| None -> ()
| Some (r, _) ->
reordering := None;
El.remove r;
El.set_class reordering_cl false r;
El.remove_inline_style El.Style.position r;
El.remove_inline_style El.Style.left r;
El.remove_inline_style El.Style.top r;
El.remove_inline_style El.Style.z_index r;
let after = match El.parent caret with
| None -> placeholder
| Some _ -> caret
in
El.insert_siblings `After after [r];
El.remove caret;
El.remove placeholder;
end;
unlisten lpointerup; unlisten lpointermove
in
let on_pointerdown ev = match !reordering with
| Some _ -> ()
| None ->
Ev.prevent_default ev;
let m = Ev.Pointer.as_mouse (Ev.as_type ev) in
off_x := Ev.Mouse.offset_x m;
off_y := Ev.Mouse.offset_y m;
reordering := Some (e, orderable_peers e);
El.set_class reordering_cl true e;
set_size placeholder (El.bound_w e) (El.bound_h e);
El.insert_siblings `Before e [placeholder];
El.set_inline_style El.Style.position (Jstr.v "absolute") e;
El.set_inline_style El.Style.z_index (Jstr.v "1000") e;
set_pos e (Ev.Mouse.page_x m -. !off_x) (Ev.Mouse.page_y m -. !off_y);
lpointerup :=
Some (Ev.listen Ev.pointerup on_pointerup
(Document.as_target G.document));
lpointermove := Some
(Ev.listen Ev.pointermove on_pointermove
(Document.as_target G.document));
in
let rec on_cleanup ev =
(* We need that to unregister the on_mousedown closure *)
unlisten lpointerdown; unlisten lhuicleanup;
in
(* Remove a potential previous listener *)
ignore (Ev.dispatch (Ev.create hui_cleanup) (El.as_target e));
lpointerdown :=
Some (Ev.listen Ev.pointerdown on_pointerdown (El.as_target e));
lhuicleanup :=
Some (Ev.listen hui_cleanup on_cleanup (El.as_target e))
let ordering_interactions () =
let setup_ordering e =
let reordering = ref None in
let caret =
let at = [At.class' orderable_caret_cl] in
El.span ~at [El.span [El.txt' "\u{2198}"]]
in
let placeholder = El.span ~at:[At.class' orderable_placeholder_cl] [] in
let os = El.find_by_class ~root:e orderable_cl in
List.iter (reordable reordering caret placeholder) os
in
List.iter setup_ordering (El.find_by_class ordering_cl)
(* Entity finders *)
let finder_input = Jstr.v "data-hui-finder-input"
let finder_input_prop = El.Prop.bool finder_input
let finder_input_clear i =
El.set_prop El.Prop.value Jstr.empty i;
ignore (Ev.dispatch (Ev.create Ev.input) (El.as_target i))
let finder_input_first_result i =
let (let*) = Option.bind in
let* root = El.parent i in
let* root = El.parent root in
El.find_first_by_selector ~root (Jstr.v ".finder-result")
let finder_result_input r =
let (let*) = Option.bind in
let* root = El.parent r in
let* root = El.parent root in
El.find_first_by_selector ~root (Jstr.v ".finder-input")
let key_escape = Jstr.v "Escape"
let key_arrow_down = Jstr.v "ArrowDown"
let key_arrow_up = Jstr.v "ArrowUp"
let key_space = Jstr.v "Space"
let key_enter = Jstr.v "Enter"
let finder_input i =
if El.prop finder_input_prop i then () else
let on_keydown ev = match Ev.Keyboard.code (Ev.as_type ev) with
| k when Jstr.equal k key_escape ->
Ev.prevent_default ev; finder_input_clear i
| k when Jstr.equal k key_arrow_down ->
begin match finder_input_first_result i with
| None -> ()
| Some fst -> Ev.prevent_default ev; El.set_has_focus true fst;
end
| _ -> ()
in
ignore (Ev.listen Ev.keydown on_keydown (El.as_target i));
El.set_prop finder_input_prop true i;
()
let finder_input_interactions () =
let finder_input_cl = Jstr.v "finder-input" in
List.iter finder_input (El.find_by_class finder_input_cl)
let finder_result = Jstr.v "data-hui-finder-result"
let finder_result_prop = El.Prop.bool finder_result
let finder_result r =
if El.prop finder_result_prop r then () else
let on_keydown ev = match Ev.Keyboard.code (Ev.as_type ev) with
| k when Jstr.equal k key_escape ->
begin match finder_result_input r with
| None -> ()
| Some i -> Ev.prevent_default ev; finder_input_clear i
end
| k when Jstr.equal k key_arrow_up ->
begin match El.previous_sibling r with
| Some el -> Ev.prevent_default ev; El.set_has_focus true el
| None ->
match finder_result_input r with
| None -> ()
| Some i -> Ev.prevent_default ev; El.set_has_focus true i
end
| k when Jstr.equal k key_arrow_down ->
begin match El.next_sibling r with
| Some el -> Ev.prevent_default ev; El.set_has_focus true el;
| None -> ()
end
| k when Jstr.equal k key_space || Jstr.equal k key_enter ->
Ev.prevent_default ev;
El.click r
| _ -> ()
in
ignore (Ev.listen Ev.keydown on_keydown (El.as_target r));
El.set_prop finder_result_prop true r;
()
let finder_result_interactions () =
let finder_result_cl = Jstr.v "finder-result" in
List.iter finder_result (El.find_by_class finder_result_cl)
let finder_interactions () =
finder_input_interactions ();
finder_result_interactions ()
(* Installing interactions. *)
FIXME nail down a strategy for applying stuff on hc
element insertions .
element insertions. *)
let install_interactions () =
remover_interactions ();
ordering_interactions ();
finder_interactions ();
()
let on_hc_cycle_end _ev =
The new data may have dois we need to replace .
Doi_relinker.relink_dois ();
install_interactions ();
()
let install_event_handlers () =
let document = Document.as_target G.document in
ignore (Ev.listen Hc_page.Ev.cycle_end on_hc_cycle_end document);
()
let main () =
Hc_page.init ();
Doi_relinker.install ();
install_interactions ();
install_event_handlers ();
()
let () = main ()
---------------------------------------------------------------------------
Copyright ( c ) 2019 University of Bern
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2019 University of Bern
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/hyperbib/a1def764f7f58b29bd732dacaa167e73497f6175/src/front/hyperbib_front.ml | ocaml | Removable
[true] iff [r]'s top-left or bottom-left or is within [o]'s vertical
bounds
[true] iff top-left or bottom-left of [r] is in [o].
[true iff top-left or bottom-left within [o] height and not too far.
We need that to unregister the on_mousedown closure
Remove a potential previous listener
Entity finders
Installing interactions. | ---------------------------------------------------------------------------
Copyright ( c ) 2019 University of Bern . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2019 University of Bern. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open Brr
let hui_remover = Jstr.v "data-hui-remover"
let hui_remover_prop = El.Prop.bool hui_remover
let remover e =
if El.prop hui_remover_prop e then () else
let on_pointerdown ev =
Ev.prevent_default ev;
Ev.stop_propagation ev;
in
let on_click ev =
let rem = El.parent e |> Option.get |> El.parent |> Option.get in
Ev.prevent_default ev;
Ev.stop_propagation ev;
Fut.await (Hc_page.Effect.feedback_remove ~target:rem Element) @@ fun () ->
El.remove rem
in
ignore (Ev.listen Ev.click on_click (El.as_target e));
ignore (Ev.listen Ev.pointerdown on_pointerdown (El.as_target e));
El.set_prop hui_remover_prop true e
let remover_interactions () =
let hui_remover = Jstr.v "hui-remove" in
List.iter remover (El.find_by_class hui_remover)
Orderable
let hui_cleanup : unit Ev.type' = Ev.Type.create (Jstr.v "hui-cleanup")
let ordering_cl = Jstr.v "ordering"
let orderable_caret_cl = Jstr.v "orderable-caret"
let orderable_cl = Jstr.v "orderable"
let orderable_placeholder_cl = Jstr.v "orderable-placeholder"
let reordering_cl = Jstr.v "reordering"
let px x = Jstr.(of_float x + v "px")
let set_pos e x y =
El.set_inline_style El.Style.left (px x) e;
El.set_inline_style El.Style.top (px y) e
let set_size e w h =
El.set_inline_style El.Style.width (px w) e;
El.set_inline_style El.Style.height (px h) e
let orderable_peers e = match El.parent e with
| None -> []
| Some p ->
List.filter (fun o -> not (o == e)) @@
El.find_by_class ~root:p orderable_cl
let isect_vertical r o =
let rtop = El.bound_y r in
let rbot = rtop +. El.bound_h r in
((El.bound_y o <= rtop && rtop <= El.bound_y o +. El.bound_h o) ||
(El.bound_y o <= rbot && rbot <= El.bound_y o +. El.bound_h o))
let h_limit_left = 15.
let h_limit_right = 30.
let rleft = El.bound_x r in
(El.bound_x o -. h_limit_left <= rleft
&& rleft <= El.bound_x o +. min (El.bound_w o) h_limit_right) &&
isect_vertical r o
let isect_last r o =
let rleft = El.bound_x r in
let oright = El.bound_x o +. El.bound_w o in
(oright -. h_limit_left < rleft && rleft < oright +. h_limit_right) &&
isect_vertical r o
let rec find_caret_location r = function
| [] -> None
| o :: os ->
if isect r o then Some (`Before, o) else
if os = [] && isect_last r o then Some (`After, o) else
find_caret_location r os
let reordable reordering caret placeholder e =
let off_x = ref 0. and off_y = ref 0. in
let lpointerdown = ref None in
let lpointerup = ref None in
let lpointermove = ref None in
let lhuicleanup = ref None in
let unlisten r = match !r with
| None -> () | Some l -> Ev.unlisten l
in
let on_pointermove ev = match !reordering with
| None -> ()
| Some (r, peers) ->
let m = Ev.Pointer.as_mouse (Ev.as_type ev) in
set_pos r (Ev.Mouse.page_x m -. !off_x) (Ev.Mouse.page_y m -. !off_y);
El.remove caret;
match find_caret_location r peers with
| None -> ()
| Some (ins, o) -> El.insert_siblings ins o [caret]
in
let rec on_pointerup ev =
begin match !reordering with
| None -> ()
| Some (r, _) ->
reordering := None;
El.remove r;
El.set_class reordering_cl false r;
El.remove_inline_style El.Style.position r;
El.remove_inline_style El.Style.left r;
El.remove_inline_style El.Style.top r;
El.remove_inline_style El.Style.z_index r;
let after = match El.parent caret with
| None -> placeholder
| Some _ -> caret
in
El.insert_siblings `After after [r];
El.remove caret;
El.remove placeholder;
end;
unlisten lpointerup; unlisten lpointermove
in
let on_pointerdown ev = match !reordering with
| Some _ -> ()
| None ->
Ev.prevent_default ev;
let m = Ev.Pointer.as_mouse (Ev.as_type ev) in
off_x := Ev.Mouse.offset_x m;
off_y := Ev.Mouse.offset_y m;
reordering := Some (e, orderable_peers e);
El.set_class reordering_cl true e;
set_size placeholder (El.bound_w e) (El.bound_h e);
El.insert_siblings `Before e [placeholder];
El.set_inline_style El.Style.position (Jstr.v "absolute") e;
El.set_inline_style El.Style.z_index (Jstr.v "1000") e;
set_pos e (Ev.Mouse.page_x m -. !off_x) (Ev.Mouse.page_y m -. !off_y);
lpointerup :=
Some (Ev.listen Ev.pointerup on_pointerup
(Document.as_target G.document));
lpointermove := Some
(Ev.listen Ev.pointermove on_pointermove
(Document.as_target G.document));
in
let rec on_cleanup ev =
unlisten lpointerdown; unlisten lhuicleanup;
in
ignore (Ev.dispatch (Ev.create hui_cleanup) (El.as_target e));
lpointerdown :=
Some (Ev.listen Ev.pointerdown on_pointerdown (El.as_target e));
lhuicleanup :=
Some (Ev.listen hui_cleanup on_cleanup (El.as_target e))
let ordering_interactions () =
let setup_ordering e =
let reordering = ref None in
let caret =
let at = [At.class' orderable_caret_cl] in
El.span ~at [El.span [El.txt' "\u{2198}"]]
in
let placeholder = El.span ~at:[At.class' orderable_placeholder_cl] [] in
let os = El.find_by_class ~root:e orderable_cl in
List.iter (reordable reordering caret placeholder) os
in
List.iter setup_ordering (El.find_by_class ordering_cl)
let finder_input = Jstr.v "data-hui-finder-input"
let finder_input_prop = El.Prop.bool finder_input
let finder_input_clear i =
El.set_prop El.Prop.value Jstr.empty i;
ignore (Ev.dispatch (Ev.create Ev.input) (El.as_target i))
let finder_input_first_result i =
let (let*) = Option.bind in
let* root = El.parent i in
let* root = El.parent root in
El.find_first_by_selector ~root (Jstr.v ".finder-result")
let finder_result_input r =
let (let*) = Option.bind in
let* root = El.parent r in
let* root = El.parent root in
El.find_first_by_selector ~root (Jstr.v ".finder-input")
let key_escape = Jstr.v "Escape"
let key_arrow_down = Jstr.v "ArrowDown"
let key_arrow_up = Jstr.v "ArrowUp"
let key_space = Jstr.v "Space"
let key_enter = Jstr.v "Enter"
let finder_input i =
if El.prop finder_input_prop i then () else
let on_keydown ev = match Ev.Keyboard.code (Ev.as_type ev) with
| k when Jstr.equal k key_escape ->
Ev.prevent_default ev; finder_input_clear i
| k when Jstr.equal k key_arrow_down ->
begin match finder_input_first_result i with
| None -> ()
| Some fst -> Ev.prevent_default ev; El.set_has_focus true fst;
end
| _ -> ()
in
ignore (Ev.listen Ev.keydown on_keydown (El.as_target i));
El.set_prop finder_input_prop true i;
()
let finder_input_interactions () =
let finder_input_cl = Jstr.v "finder-input" in
List.iter finder_input (El.find_by_class finder_input_cl)
let finder_result = Jstr.v "data-hui-finder-result"
let finder_result_prop = El.Prop.bool finder_result
let finder_result r =
if El.prop finder_result_prop r then () else
let on_keydown ev = match Ev.Keyboard.code (Ev.as_type ev) with
| k when Jstr.equal k key_escape ->
begin match finder_result_input r with
| None -> ()
| Some i -> Ev.prevent_default ev; finder_input_clear i
end
| k when Jstr.equal k key_arrow_up ->
begin match El.previous_sibling r with
| Some el -> Ev.prevent_default ev; El.set_has_focus true el
| None ->
match finder_result_input r with
| None -> ()
| Some i -> Ev.prevent_default ev; El.set_has_focus true i
end
| k when Jstr.equal k key_arrow_down ->
begin match El.next_sibling r with
| Some el -> Ev.prevent_default ev; El.set_has_focus true el;
| None -> ()
end
| k when Jstr.equal k key_space || Jstr.equal k key_enter ->
Ev.prevent_default ev;
El.click r
| _ -> ()
in
ignore (Ev.listen Ev.keydown on_keydown (El.as_target r));
El.set_prop finder_result_prop true r;
()
let finder_result_interactions () =
let finder_result_cl = Jstr.v "finder-result" in
List.iter finder_result (El.find_by_class finder_result_cl)
let finder_interactions () =
finder_input_interactions ();
finder_result_interactions ()
FIXME nail down a strategy for applying stuff on hc
element insertions .
element insertions. *)
let install_interactions () =
remover_interactions ();
ordering_interactions ();
finder_interactions ();
()
let on_hc_cycle_end _ev =
The new data may have dois we need to replace .
Doi_relinker.relink_dois ();
install_interactions ();
()
let install_event_handlers () =
let document = Document.as_target G.document in
ignore (Ev.listen Hc_page.Ev.cycle_end on_hc_cycle_end document);
()
let main () =
Hc_page.init ();
Doi_relinker.install ();
install_interactions ();
install_event_handlers ();
()
let () = main ()
---------------------------------------------------------------------------
Copyright ( c ) 2019 University of Bern
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2019 University of Bern
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
efb9b5dc60f310dbbeaa9038d40afdef767bcc3e6102e54a38080fe230bb3a65 | oakes/Lightmod | dynadoc.cljs | (ns lightmod.dynadoc
(:require [play-cljs.core]
[dynadoc.core]))
| null | https://raw.githubusercontent.com/oakes/Lightmod/141d1671d485326ef1f37b057c4116a2618dd948/src/cljs/lightmod/dynadoc.cljs | clojure | (ns lightmod.dynadoc
(:require [play-cljs.core]
[dynadoc.core]))
| |
7f1e6dbfedf45aa159a0d1e39218599e24075fffeb227d0b44cf720133149478 | argp/bap | test.ml |
Copyright 2009 , 2010 , 2011 , 2012 , 2013
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
open Piqirun
(* superposition operator *)
let ( ** ) f g x = f (g x)
let assert_eq a b = assert (a = b)
let test_key x =
let test_parse x =
(IBuf.of_string ** OBuf.to_string) x
in
assert (x = ((fun x -> let _, code = parse_field_header x in code) ** test_parse ** gen_key 0) x)
let test_gen_parse x =
(init_from_string ** to_string) x
* Names of the test _ * functions correspond to Piqi types : there are 12
* different integer types
* Names of the test_* functions correspond to Piqi types: there are 12
* different integer types
*)
let test_int x =
assert (x = (int_of_zigzag_varint ** test_gen_parse ** int_to_zigzag_varint (-1)) x)
let test_int32 x =
assert (x = (int32_of_zigzag_varint ** test_gen_parse ** int32_to_zigzag_varint (-1)) x)
let test_int64 x =
assert (x = (int64_of_zigzag_varint ** test_gen_parse ** int64_to_zigzag_varint (-1)) x)
let test_fixed_int32 x =
assert (x = (int32_of_signed_fixed32 ** test_gen_parse ** int32_to_signed_fixed32 (-1)) x)
let test_fixed_int64 x =
assert (x = (int64_of_signed_fixed64 ** test_gen_parse ** int64_to_signed_fixed64 (-1)) x)
NOTE : this type is not currently defined in Piqi
assert (x = (int_of_signed_varint ** test_gen_parse ** int_to_signed_varint (-1)) x)
let test_proto_int32 x =
assert (x = (int32_of_signed_varint ** test_gen_parse ** int32_to_signed_varint (-1)) x)
let test_proto_int64 x =
assert (x = (int64_of_signed_varint ** test_gen_parse ** int64_to_signed_varint (-1)) x)
let test_uint x =
assert (x = (int_of_varint ** test_gen_parse ** int_to_varint (-1)) x)
let test_uint32 x =
assert (x = (int32_of_varint ** test_gen_parse ** int32_to_varint (-1)) x)
let test_uint64 x =
assert (x = (int64_of_varint ** test_gen_parse ** int64_to_varint (-1)) x)
let test_fixed_uint32 x =
assert (x = (int32_of_fixed32 ** test_gen_parse ** int32_to_fixed32 (-1)) x)
let test_fixed_uint64 x =
assert (x = (int64_of_fixed64 ** test_gen_parse ** int64_to_fixed64 (-1)) x)
(*
* Testing packed
*)
let test_packed_gen_parse x =
(IBuf.of_string ** OBuf.to_string) x
* Names of the test _ * functions correspond to Piqi types : there are 12
* different integer types
* Names of the test_* functions correspond to Piqi types: there are 12
* different integer types
*)
let test_packed_int x =
assert (x = (int_of_packed_zigzag_varint ** test_packed_gen_parse ** int_to_packed_zigzag_varint) x)
let test_packed_int32 x =
assert (x = (int32_of_packed_zigzag_varint ** test_packed_gen_parse ** int32_to_packed_zigzag_varint) x)
let test_packed_int64 x =
assert (x = (int64_of_packed_zigzag_varint ** test_packed_gen_parse ** int64_to_packed_zigzag_varint) x)
let test_packed_fixed_int32 x =
assert (x = (int32_of_packed_signed_fixed32 ** test_packed_gen_parse ** int32_to_packed_signed_fixed32) x)
let test_packed_fixed_int64 x =
assert (x = (int64_of_packed_signed_fixed64 ** test_packed_gen_parse ** int64_to_packed_signed_fixed64) x)
NOTE : this type is not currently defined in Piqi
assert (x = (int_of_packed_signed_varint ** test_packed_gen_parse ** int_to_packed_signed_varint) x)
let test_packed_proto_int32 x =
assert (x = (int32_of_packed_signed_varint ** test_packed_gen_parse ** int32_to_packed_signed_varint) x)
let test_packed_proto_int64 x =
assert (x = (int64_of_packed_signed_varint ** test_packed_gen_parse ** int64_to_packed_signed_varint) x)
let test_packed_uint x =
assert (x = (int_of_packed_varint ** test_packed_gen_parse ** int_to_packed_varint) x)
let test_packed_uint32 x =
assert (x = (int32_of_packed_varint ** test_packed_gen_parse ** int32_to_packed_varint) x)
let test_packed_uint64 x =
assert (x = (int64_of_packed_varint ** test_packed_gen_parse ** int64_to_packed_varint) x)
let test_packed_fixed_uint32 x =
assert (x = (int32_of_packed_fixed32 ** test_packed_gen_parse ** int32_to_packed_fixed32) x)
let test_packed_fixed_uint64 x =
assert (x = (int64_of_packed_fixed64 ** test_packed_gen_parse ** int64_to_packed_fixed64) x)
let int_input =
[
0; 1; 2; 3; -1; -2; -3;
min_int; min_int + 1; min_int + 2; min_int + 3;
max_int; max_int - 1; max_int - 2; max_int - 3;
]
let uint_input =
let max_uint = lnot 0 in
[
0; 1; 2; 3;
max_uint;
]
open Int32
let int32_input =
let int_intput = List.map (fun x -> of_int x) int_input in
int_intput @
[
min_int; succ min_int; succ (succ min_int); succ (succ (succ min_int));
max_int; pred max_int; pred (pred max_int); pred (pred (pred max_int));
]
let uint32_input =
let max_uint = lognot 0l in
[
0l; 1l; 2l; 3l;
max_uint;
]
open Int64
let int64_input =
let int_intput = List.map (fun x -> of_int x) int_input in
let int32_intput = List.map (fun x -> of_int32 x) int32_input in
int_intput @
int32_intput @
[
min_int; succ min_int; succ (succ min_int); succ (succ (succ min_int));
max_int; pred max_int; pred (pred max_int); pred (pred (pred max_int));
]
let uint64_input =
let max_uint = lognot 0L in
let uint32_intput = List.map (fun x -> int64_of_uint32 x) uint32_input in
uint32_intput @
[
max_uint;
]
let max_key = (1 lsl 29) - 1
let key_input = [ 1; 2; 3; max_key - 1; max_key ]
TODO :
* tests for malformed / broken / unexpectedly terminated input
* tests for OCaml 's type overflows
* tests for cross - type reading , e.g. int64 - > int32 , varint - > int64 , etc .
* tests for bools , floats and other types
*
* tests for malformed/broken/unexpectedly terminated input
* tests for OCaml's type overflows
* tests for cross-type reading, e.g. int64 -> int32, varint -> int64, etc.
* tests for bools, floats and other types
*
*)
let test _ =
List.iter test_key key_input;
(* tests for integer fields *)
List.iter test_int int_input;
List.iter test_int32 int32_input;
List.iter test_int64 int64_input;
List.iter test_fixed_int32 int32_input;
List.iter test_fixed_int64 int64_input;
List.iter test_proto_int int_input;
List.iter test_proto_int32 int32_input;
List.iter test_proto_int64 int64_input;
List.iter test_uint uint_input;
List.iter test_uint32 uint32_input;
List.iter test_uint64 uint64_input;
List.iter test_fixed_uint32 uint32_input;
List.iter test_fixed_uint64 uint64_input;
(* tests for packed integers *)
List.iter test_packed_int int_input;
List.iter test_packed_int32 int32_input;
List.iter test_packed_int64 int64_input;
List.iter test_packed_fixed_int32 int32_input;
List.iter test_packed_fixed_int64 int64_input;
List.iter test_packed_proto_int int_input;
List.iter test_packed_proto_int32 int32_input;
List.iter test_packed_proto_int64 int64_input;
List.iter test_packed_uint uint_input;
List.iter test_packed_uint32 uint32_input;
List.iter test_packed_uint64 uint64_input;
List.iter test_packed_fixed_uint32 uint32_input;
List.iter test_packed_fixed_uint64 uint64_input;
()
let _ =
if !Sys.interactive
then ()
else test ()
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/libtracewrap/libtrace/piqi/piqi/piqirun-ocaml/test.ml | ocaml | superposition operator
* Testing packed
tests for integer fields
tests for packed integers |
Copyright 2009 , 2010 , 2011 , 2012 , 2013
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
open Piqirun
let ( ** ) f g x = f (g x)
let assert_eq a b = assert (a = b)
let test_key x =
let test_parse x =
(IBuf.of_string ** OBuf.to_string) x
in
assert (x = ((fun x -> let _, code = parse_field_header x in code) ** test_parse ** gen_key 0) x)
let test_gen_parse x =
(init_from_string ** to_string) x
* Names of the test _ * functions correspond to Piqi types : there are 12
* different integer types
* Names of the test_* functions correspond to Piqi types: there are 12
* different integer types
*)
let test_int x =
assert (x = (int_of_zigzag_varint ** test_gen_parse ** int_to_zigzag_varint (-1)) x)
let test_int32 x =
assert (x = (int32_of_zigzag_varint ** test_gen_parse ** int32_to_zigzag_varint (-1)) x)
let test_int64 x =
assert (x = (int64_of_zigzag_varint ** test_gen_parse ** int64_to_zigzag_varint (-1)) x)
let test_fixed_int32 x =
assert (x = (int32_of_signed_fixed32 ** test_gen_parse ** int32_to_signed_fixed32 (-1)) x)
let test_fixed_int64 x =
assert (x = (int64_of_signed_fixed64 ** test_gen_parse ** int64_to_signed_fixed64 (-1)) x)
NOTE : this type is not currently defined in Piqi
assert (x = (int_of_signed_varint ** test_gen_parse ** int_to_signed_varint (-1)) x)
let test_proto_int32 x =
assert (x = (int32_of_signed_varint ** test_gen_parse ** int32_to_signed_varint (-1)) x)
let test_proto_int64 x =
assert (x = (int64_of_signed_varint ** test_gen_parse ** int64_to_signed_varint (-1)) x)
let test_uint x =
assert (x = (int_of_varint ** test_gen_parse ** int_to_varint (-1)) x)
let test_uint32 x =
assert (x = (int32_of_varint ** test_gen_parse ** int32_to_varint (-1)) x)
let test_uint64 x =
assert (x = (int64_of_varint ** test_gen_parse ** int64_to_varint (-1)) x)
let test_fixed_uint32 x =
assert (x = (int32_of_fixed32 ** test_gen_parse ** int32_to_fixed32 (-1)) x)
let test_fixed_uint64 x =
assert (x = (int64_of_fixed64 ** test_gen_parse ** int64_to_fixed64 (-1)) x)
let test_packed_gen_parse x =
(IBuf.of_string ** OBuf.to_string) x
* Names of the test _ * functions correspond to Piqi types : there are 12
* different integer types
* Names of the test_* functions correspond to Piqi types: there are 12
* different integer types
*)
let test_packed_int x =
assert (x = (int_of_packed_zigzag_varint ** test_packed_gen_parse ** int_to_packed_zigzag_varint) x)
let test_packed_int32 x =
assert (x = (int32_of_packed_zigzag_varint ** test_packed_gen_parse ** int32_to_packed_zigzag_varint) x)
let test_packed_int64 x =
assert (x = (int64_of_packed_zigzag_varint ** test_packed_gen_parse ** int64_to_packed_zigzag_varint) x)
let test_packed_fixed_int32 x =
assert (x = (int32_of_packed_signed_fixed32 ** test_packed_gen_parse ** int32_to_packed_signed_fixed32) x)
let test_packed_fixed_int64 x =
assert (x = (int64_of_packed_signed_fixed64 ** test_packed_gen_parse ** int64_to_packed_signed_fixed64) x)
NOTE : this type is not currently defined in Piqi
assert (x = (int_of_packed_signed_varint ** test_packed_gen_parse ** int_to_packed_signed_varint) x)
let test_packed_proto_int32 x =
assert (x = (int32_of_packed_signed_varint ** test_packed_gen_parse ** int32_to_packed_signed_varint) x)
let test_packed_proto_int64 x =
assert (x = (int64_of_packed_signed_varint ** test_packed_gen_parse ** int64_to_packed_signed_varint) x)
let test_packed_uint x =
assert (x = (int_of_packed_varint ** test_packed_gen_parse ** int_to_packed_varint) x)
let test_packed_uint32 x =
assert (x = (int32_of_packed_varint ** test_packed_gen_parse ** int32_to_packed_varint) x)
let test_packed_uint64 x =
assert (x = (int64_of_packed_varint ** test_packed_gen_parse ** int64_to_packed_varint) x)
let test_packed_fixed_uint32 x =
assert (x = (int32_of_packed_fixed32 ** test_packed_gen_parse ** int32_to_packed_fixed32) x)
let test_packed_fixed_uint64 x =
assert (x = (int64_of_packed_fixed64 ** test_packed_gen_parse ** int64_to_packed_fixed64) x)
let int_input =
[
0; 1; 2; 3; -1; -2; -3;
min_int; min_int + 1; min_int + 2; min_int + 3;
max_int; max_int - 1; max_int - 2; max_int - 3;
]
let uint_input =
let max_uint = lnot 0 in
[
0; 1; 2; 3;
max_uint;
]
open Int32
let int32_input =
let int_intput = List.map (fun x -> of_int x) int_input in
int_intput @
[
min_int; succ min_int; succ (succ min_int); succ (succ (succ min_int));
max_int; pred max_int; pred (pred max_int); pred (pred (pred max_int));
]
let uint32_input =
let max_uint = lognot 0l in
[
0l; 1l; 2l; 3l;
max_uint;
]
open Int64
let int64_input =
let int_intput = List.map (fun x -> of_int x) int_input in
let int32_intput = List.map (fun x -> of_int32 x) int32_input in
int_intput @
int32_intput @
[
min_int; succ min_int; succ (succ min_int); succ (succ (succ min_int));
max_int; pred max_int; pred (pred max_int); pred (pred (pred max_int));
]
let uint64_input =
let max_uint = lognot 0L in
let uint32_intput = List.map (fun x -> int64_of_uint32 x) uint32_input in
uint32_intput @
[
max_uint;
]
let max_key = (1 lsl 29) - 1
let key_input = [ 1; 2; 3; max_key - 1; max_key ]
TODO :
* tests for malformed / broken / unexpectedly terminated input
* tests for OCaml 's type overflows
* tests for cross - type reading , e.g. int64 - > int32 , varint - > int64 , etc .
* tests for bools , floats and other types
*
* tests for malformed/broken/unexpectedly terminated input
* tests for OCaml's type overflows
* tests for cross-type reading, e.g. int64 -> int32, varint -> int64, etc.
* tests for bools, floats and other types
*
*)
let test _ =
List.iter test_key key_input;
List.iter test_int int_input;
List.iter test_int32 int32_input;
List.iter test_int64 int64_input;
List.iter test_fixed_int32 int32_input;
List.iter test_fixed_int64 int64_input;
List.iter test_proto_int int_input;
List.iter test_proto_int32 int32_input;
List.iter test_proto_int64 int64_input;
List.iter test_uint uint_input;
List.iter test_uint32 uint32_input;
List.iter test_uint64 uint64_input;
List.iter test_fixed_uint32 uint32_input;
List.iter test_fixed_uint64 uint64_input;
List.iter test_packed_int int_input;
List.iter test_packed_int32 int32_input;
List.iter test_packed_int64 int64_input;
List.iter test_packed_fixed_int32 int32_input;
List.iter test_packed_fixed_int64 int64_input;
List.iter test_packed_proto_int int_input;
List.iter test_packed_proto_int32 int32_input;
List.iter test_packed_proto_int64 int64_input;
List.iter test_packed_uint uint_input;
List.iter test_packed_uint32 uint32_input;
List.iter test_packed_uint64 uint64_input;
List.iter test_packed_fixed_uint32 uint32_input;
List.iter test_packed_fixed_uint64 uint64_input;
()
let _ =
if !Sys.interactive
then ()
else test ()
|
70f7fdf7803210a30ec61ff383f892c187e1a38085bd9ad7a99f7a9b65ad15d4 | input-output-hk/cardano-sl | GetTransactions.hs | # LANGUAGE TypeApplications #
# OPTIONS_GHC -fno - warn - orphans #
module Test.Spec.GetTransactions (spec) where
import Universum
import Control.Lens (to)
import Control.Monad.Except (runExceptT)
import Data.Acid (update)
import qualified Data.ByteString as B
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as M
import Formatting (build, sformat)
import Servant.Server
import Util.Buildable (ShowThroughBuild (..))
import Test.Hspec (Spec, describe, expectationFailure, shouldBe,
shouldMatchList, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (arbitrary, choose, withMaxSuccess)
import Test.QuickCheck.Monadic (PropertyM, monadicIO, pick)
import Pos.Chain.Txp (TxOut (..), TxOutAux (..))
import qualified Pos.Chain.Txp as Core
import Pos.Core as Core
import Pos.Core (Coin (..), IsBootstrapEraAddr (..),
deriveLvl2KeyPair, mkCoin)
import Pos.Core.NetworkMagic (NetworkMagic (..), makeNetworkMagic)
import Pos.Crypto (EncryptedSecretKey, ProtocolMagic,
ShouldCheckPassphrase (..), emptyPassphrase,
safeDeterministicKeyGen)
import Pos.Crypto.HD (firstHardened)
import Cardano.Wallet.API.Request
import Cardano.Wallet.API.Request.Pagination
import Cardano.Wallet.API.Response
import qualified Cardano.Wallet.API.V1.Handlers.Transactions as Handlers
import qualified Cardano.Wallet.API.V1.Types as V1
import qualified Cardano.Wallet.Kernel as Kernel
import Cardano.Wallet.Kernel.CoinSelection.FromGeneric
(CoinSelectionOptions (..), ExpenseRegulation (..),
InputGrouping (..), newOptions)
import Cardano.Wallet.Kernel.DB.AcidState
import Cardano.Wallet.Kernel.DB.HdWallet (AssuranceLevel (..),
HasSpendingPassword (..), HdAccountId (..),
HdAccountIx (..), HdAddressIx (..), HdRoot (..),
HdRootId (..), WalletName (..), eskToHdRootId,
hdAccountIdIx)
import Cardano.Wallet.Kernel.DB.HdWallet.Create (initHdRoot)
import Cardano.Wallet.Kernel.DB.HdWallet.Derivation
(HardeningMode (..), deriveIndex)
import Cardano.Wallet.Kernel.DB.InDb (InDb (..), fromDb)
import Cardano.Wallet.Kernel.DB.TxMeta
import qualified Cardano.Wallet.Kernel.DB.Util.IxSet as IxSet
import Cardano.Wallet.Kernel.Internal
import qualified Cardano.Wallet.Kernel.Keystore as Keystore
import qualified Cardano.Wallet.Kernel.PrefilterTx as Kernel
import qualified Cardano.Wallet.Kernel.Read as Kernel
import qualified Cardano.Wallet.Kernel.Transactions as Kernel
import Cardano.Wallet.Kernel.Types (AccountId (..), WalletId (..))
import qualified Cardano.Wallet.Kernel.Wallets as Kernel
import Cardano.Wallet.WalletLayer (ActiveWalletLayer (..),
walletPassiveLayer)
import qualified Cardano.Wallet.WalletLayer as WalletLayer
import qualified Cardano.Wallet.WalletLayer.Kernel.Accounts as Accounts
import qualified Cardano.Wallet.WalletLayer.Kernel.Conv as Kernel.Conv
import Cardano.Wallet.WalletLayer.Kernel.Transactions (toTransaction)
import qualified Test.Spec.Addresses as Addresses
import Test.Spec.CoinSelection.Generators (InitialBalance (..),
Pay (..), genUtxoWithAtLeast)
import qualified Test.Spec.Fixture as Fixture
import qualified Test.Spec.NewPayment as NewPayment
import Test.Spec.TxMetaStorage (Isomorphic (..), genMeta)
# ANN module ( " HLint : ignore Reduce duplication " : : Text ) #
data Fix = Fix {
fixtureHdRootId :: HdRootId
, fixtureHdRoot :: HdRoot
, fixtureESK :: EncryptedSecretKey
, fixtureAccountId :: AccountId
, fixtureUtxo :: Core.Utxo
}
data Fixture = Fixture {
fixture :: [Fix]
, fixturePw :: PassiveWallet
}
-- | Prepare some fixtures using the 'PropertyM' context to prepare the data,
and execute the ' acid - state ' update once the ' PassiveWallet ' gets into
-- scope (after the bracket initialisation).
prepareFixtures :: NetworkMagic
-> InitialBalance
-> Fixture.GenActiveWalletFixture Fixture
prepareFixtures nm initialBalance = do
fixt <- forM [0x11, 0x22] $ \b -> do
let (_, esk) = safeDeterministicKeyGen (B.pack $ replicate 32 b) mempty
let newRootId = eskToHdRootId nm esk
newRoot <- initHdRoot <$> pure newRootId
<*> pure (WalletName "A wallet")
<*> pure NoSpendingPassword
<*> pure AssuranceLevelNormal
<*> (InDb <$> pick arbitrary)
newAccountId <- HdAccountId newRootId <$> deriveIndex (pick . choose) HdAccountIx HardDerivation
utxo <- pick (genUtxoWithAtLeast initialBalance)
Override all the addresses of the random with something meaningful ,
-- i.e. with 'Address'(es) generated in a principled way, and not random.
utxo' <- foldlM (\acc (txIn, (TxOutAux (TxOut _ coin))) -> do
newIndex <- deriveIndex (pick . choose) HdAddressIx HardDerivation
let Just (addr, _) = deriveLvl2KeyPair nm
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase True)
mempty
esk
(newAccountId ^. hdAccountIdIx . to getHdAccountIx)
(getHdAddressIx newIndex)
return $ M.insert txIn (TxOutAux (TxOut addr coin)) acc
) M.empty (M.toList utxo)
return $ Fix {
fixtureHdRootId = newRootId
, fixtureHdRoot = newRoot
, fixtureAccountId = AccountIdHdRnd newAccountId
, fixtureESK = esk
, fixtureUtxo = utxo'
}
return $ \keystore aw -> do
let pw = Kernel.walletPassive aw
forM_ fixt $ \Fix{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let accounts = Kernel.prefilterUtxo nm fixtureHdRootId fixtureESK fixtureUtxo
hdAccountId = Kernel.defaultHdAccountId fixtureHdRootId
hdAddress = Kernel.defaultHdAddress nm fixtureESK emptyPassphrase fixtureHdRootId
void $ liftIO $ update (pw ^. wallets) (CreateHdWallet fixtureHdRoot hdAccountId hdAddress accounts)
return $ Fixture {
fixture = fixt
, fixturePw = pw
}
withFixture :: MonadIO m
=> ProtocolMagic
-> InitialBalance
-> ( Keystore.Keystore
-> WalletLayer.ActiveWalletLayer m
-> Kernel.ActiveWallet
-> Fixture
-> IO a
)
-> PropertyM IO a
withFixture pm initialBalance cc =
Fixture.withActiveWalletFixture pm (prepareFixtures nm initialBalance) cc
where
nm = makeNetworkMagic pm
-- | Returns the address that is automatically created with the wallet.
getFixedAddress :: WalletLayer.ActiveWalletLayer IO -> Fix -> IO Core.Address
getFixedAddress layer Fix{..} = do
let params = RequestParams (PaginationParams (Page 1) (PerPage 10))
let filters = NoFilters
Right wr <- WalletLayer.getAccountAddresses (walletPassiveLayer layer)
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex firstHardened)
params
filters
-- the defaut account of the wallet should have a unique address.
let [address] = wrData wr
return $ V1.unV1 . V1.addrId $ address
-- | Returns an address from the account we explicitely create.
getNonFixedAddress :: WalletLayer.ActiveWalletLayer IO -> Fix -> IO Core.Address
getNonFixedAddress layer Fix{..} = do
let params = RequestParams (PaginationParams (Page 1) (PerPage 10))
let filters = NoFilters
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let index = getHdAccountIx $ hdAccountId ^. hdAccountIdIx
Right wr <- WalletLayer.getAccountAddresses (walletPassiveLayer layer)
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex index)
params
filters
-- the account we create in the fixture should also have an address
let (address : _) = wrData wr
return $ V1.unV1 . V1.addrId $ address
getAccountBalanceNow :: Kernel.PassiveWallet -> Fix -> IO Word64
getAccountBalanceNow pw Fix{..} = do
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let index = getHdAccountIx $ hdAccountId ^. hdAccountIdIx
db <- Kernel.getWalletSnapshot pw
let res =
Accounts.getAccountBalance
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex index)
db
bimap STB STB res `shouldSatisfy` isRight
let Right (V1.AccountBalance (V1.V1 (Coin coins))) = res
return coins
-- | A constant fee calculation.
constantFee :: Word64 -> Int -> NonEmpty Coin -> Coin
constantFee c _ _ = mkCoin c
spec :: Spec
spec = do
describe "GetTransactions" $ do
prop "scenario: Layer.CreateAddress -> TxMeta.putTxMeta -> Layer.getTransactions works properly." $ withMaxSuccess 5 $
monadicIO $ do
testMetaSTB <- pick genMeta
pm <- pick arbitrary
Addresses.withFixture pm $ \keystore layer pwallet Addresses.Fixture{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let (HdRootId hdRoot) = fixtureHdRootId
(AccountIdHdRnd myAccountId) = fixtureAccountId
wId = sformat build (view fromDb hdRoot)
accIdx = myAccountId ^. hdAccountIdIx . to getHdAccountIx
hdl = (pwallet ^. Kernel.walletMeta)
testMeta = unSTB testMetaSTB
case decodeTextAddress wId of
Left _ -> expectationFailure "decodeTextAddress failed"
Right rootAddr -> do
let meta = testMeta {_txMetaWalletId = rootAddr, _txMetaAccountIx = accIdx}
_ <- liftIO $ WalletLayer.createAddress layer
(V1.NewAddress
Nothing
(V1.unsafeMkAccountIndex accIdx)
(V1.WalletId wId)
)
putTxMeta (pwallet ^. Kernel.walletMeta) meta
(result, mbCount) <- (getTxMetas hdl) (Offset 0) (Limit 10) Everything Nothing NoFilterOp NoFilterOp Nothing
map Isomorphic result `shouldMatchList` [Isomorphic meta]
let check APIResponse{..} = do
let PaginationMetadata{..} = metaPagination wrMeta
wrStatus `shouldBe` SuccessStatus
length wrData `shouldBe` 1
metaTotalPages `shouldBe` 1
metaTotalEntries `shouldBe` 1
metaPage `shouldBe` (Page 1)
metaPerPage `shouldBe` (PerPage 10)
case wrData of
[tx] -> V1.txStatus tx `shouldBe` V1.WontApply
ls -> expectationFailure $ "Tx list returned has wrong size "
<> show (length ls) <> "instead of 1: ls = " <> show ls
eiResp <- WalletLayer.getTransactions
layer
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
mbCount `shouldBe` (Just 1)
case eiResp of
Left l -> expectationFailure $ "returned " <> show l
Right resp -> check resp
prop "scenario: Layer.pay -> Layer.getTransactions works properly. Tx status should be Applying " $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
NewPayment.withFixture @IO pm (InitialADA 10000) (PayLovelace 25) $ \keystore activeLayer aw NewPayment.Fixture{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let (HdRootId (InDb rootAddress)) = fixtureHdRootId
let sourceWallet = V1.WalletId (sformat build rootAddress)
let accountIndex = Kernel.Conv.toAccountId hdAccountId
let destinations =
fmap (\(addr, coin) -> V1.PaymentDistribution (V1.V1 addr) (V1.V1 coin)
) fixturePayees
let newPayment = V1.Payment {
pmtSource = V1.PaymentSource sourceWallet accountIndex
, pmtDestinations = destinations
, pmtGroupingPolicy = Nothing
, pmtSpendingPassword = Nothing
}
res <- liftIO ((WalletLayer.pay activeLayer) mempty
IgnoreGrouping
SenderPaysFee
newPayment
)
case res of
Left _ -> expectationFailure "Kernel.newTransaction failed"
Right (_, meta) -> do
let txid = _txMetaId meta
pw = Kernel.walletPassive aw
layer = walletPassiveLayer activeLayer
(HdRootId hdRoot) = fixtureHdRootId
wId = sformat build (view fromDb hdRoot)
accIdx = Kernel.Conv.toAccountId hdAccountId
hdl = (pw ^. Kernel.walletMeta)
db <- Kernel.getWalletSnapshot pw
let isPending = Kernel.currentTxIsPending db txid hdAccountId
_ <- case isPending of
Left _err -> expectationFailure "hdAccountId not found in Acid State from Kernel"
Right False -> expectationFailure "txid not found in Acid State from Kernel"
Right True -> pure ()
_ <- liftIO (WalletLayer.createAddress layer (V1.NewAddress Nothing accIdx (V1.WalletId wId)))
(result, mbCount) <- (getTxMetas hdl) (Offset 0) (Limit 10) Everything Nothing NoFilterOp NoFilterOp Nothing
map Isomorphic result `shouldMatchList` [Isomorphic meta]
let check APIResponse{..} = do
let PaginationMetadata{..} = metaPagination wrMeta
wrStatus `shouldBe` SuccessStatus
length wrData `shouldBe` 1
metaTotalPages `shouldBe` 1
metaTotalEntries `shouldBe` 1
metaPage `shouldBe` (Page 1)
metaPerPage `shouldBe` (PerPage 10)
case wrData of
[tx1] -> do
V1.txStatus tx1 `shouldBe` V1.Applying
ls -> expectationFailure $ "Tx list returned has wrong size "
<> show (length ls) <> "instead of 1: ls = " <> show ls
eiResp <- WalletLayer.getTransactions
layer
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
mbCount `shouldBe` (Just 1)
case eiResp of
Left l -> expectationFailure $ "returned " <> show l
Right resp -> check resp
prop "newTransaction and getTransactions return the same result" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
NewPayment.withPayment pm (InitialADA 10000) (PayLovelace 100) $ \activeLayer newPayment -> do
payRes <- liftIO (runExceptT . runHandler' $ Handlers.newTransaction activeLayer newPayment)
getTxRes <- WalletLayer.getTransactions
(walletPassiveLayer activeLayer)
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
case (payRes, getTxRes) of
(Right txMetaPay, Right txMetaGet) ->
wrData txMetaGet `shouldBe` wrData ((\x -> [x]) <$> txMetaPay)
_ -> expectationFailure "WalletLayer.getTransactions or Handlers.newTransaction failed"
prop "TxMeta from pay has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
NewPayment.withFixture @IO pm (InitialADA 10000) (PayLovelace 100) $ \_ _ aw NewPayment.Fixture{..} -> do
we use constant fees here , to have predictable .
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
(_tx, txMeta) <- payAux aw hdAccountId fixturePayees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
describe "Transactions with multiple wallets" $ do
prop "test fixture has all the wanted properies" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
db <- Kernel.getWalletSnapshot (Kernel.walletPassive aw)
let Right accs1 = Accounts.getAccounts (Kernel.Conv.toRootId $ fixtureHdRootId w1) db
length (IxSet.toList accs1) `shouldBe` 2
let Right accs2 = Accounts.getAccounts (Kernel.Conv.toRootId $ fixtureHdRootId w2) db
length (IxSet.toList accs2) `shouldBe` 2
_ <- getFixedAddress layer w1
_ <- getFixedAddress layer w2
_ <- getNonFixedAddress layer w1
_ <- getNonFixedAddress layer w2
return ()
prop "TxMeta from pay between two wallets has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
address <- getFixedAddress layer w2
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
txMeta ^. txMetaIsOutgoing `shouldBe` True
txMeta ^. txMetaIsLocal `shouldBe` False
res <- toTransaction pw txMeta
bimap STB STB res `shouldSatisfy` isRight
let Right tx = res
V1.txStatus tx `shouldBe` V1.Applying
V1.txConfirmations tx `shouldBe` 0
prop "as above but now we pay to the explicitely created account" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
address <- getNonFixedAddress layer w2
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
prop "payment to different wallet changes the balance the same as txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
-- get the balance before the payment
coinsBefore <- getAccountBalanceNow pw w1
-- do the payment
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
address <- getFixedAddress layer w2
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
-- get the balance after the payment
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
prop "as above but now we pay to the explicitely created account" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
-- get the balance before the payment
coinsBefore <- getAccountBalanceNow pw w1
-- do the payment
address <- getNonFixedAddress layer w2
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
-- get the balance after the payment
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
prop "2 consecutive payments" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
-- get the balance before the payment
coinsBefore <- getAccountBalanceNow pw w1
-- do the payment
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
address1 <- getFixedAddress layer w2
address2 <- getNonFixedAddress layer w2
let payees1 = (NonEmpty.fromList [(address1, Coin 100)])
(_, txMeta1) <- payAux aw hdAccountId1 payees1 200
txMeta1 ^. txMetaAmount `shouldBe` Coin 300
do the second payment
let payees2 = (NonEmpty.fromList [(address2, Coin 400)])
(_, txMeta2) <- payAux aw hdAccountId1 payees2 800
txMeta2 ^. txMetaAmount `shouldBe` Coin 1200
-- get the balance after the payment
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 1500
describe "Transactions with multiple accounts" $ do
prop "TxMeta from pay between two accounts of the same wallet has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, _] _) -> do
let pw = Kernel.walletPassive aw
-- get the balance before the payment
coinsBefore <- getAccountBalanceNow pw w1
-- do the payment
address <- getFixedAddress layer w1
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_, txMeta) <- payAux aw hdAccountId1 payees 200
this is 200 because the outputs is at the same wallet .
txMeta ^. txMetaAmount `shouldBe` Coin 200
txMeta ^. txMetaIsOutgoing `shouldBe` True
txMeta ^. txMetaIsLocal `shouldBe` True
-- get the balance after the payment
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
payAux :: Kernel.ActiveWallet -> HdAccountId -> NonEmpty (Address, Coin) -> Word64 -> IO (Core.Tx, TxMeta)
payAux aw hdAccountId payees fees = do
let opts = (newOptions (constantFee fees)) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
payRes <- (Kernel.pay aw
mempty
opts
hdAccountId
payees
)
bimap STB STB payRes `shouldSatisfy` isRight
let Right t = payRes
return t
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/wallet/test/unit/Test/Spec/GetTransactions.hs | haskell | | Prepare some fixtures using the 'PropertyM' context to prepare the data,
scope (after the bracket initialisation).
i.e. with 'Address'(es) generated in a principled way, and not random.
| Returns the address that is automatically created with the wallet.
the defaut account of the wallet should have a unique address.
| Returns an address from the account we explicitely create.
the account we create in the fixture should also have an address
| A constant fee calculation.
get the balance before the payment
do the payment
get the balance after the payment
get the balance before the payment
do the payment
get the balance after the payment
get the balance before the payment
do the payment
get the balance after the payment
get the balance before the payment
do the payment
get the balance after the payment | # LANGUAGE TypeApplications #
# OPTIONS_GHC -fno - warn - orphans #
module Test.Spec.GetTransactions (spec) where
import Universum
import Control.Lens (to)
import Control.Monad.Except (runExceptT)
import Data.Acid (update)
import qualified Data.ByteString as B
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as M
import Formatting (build, sformat)
import Servant.Server
import Util.Buildable (ShowThroughBuild (..))
import Test.Hspec (Spec, describe, expectationFailure, shouldBe,
shouldMatchList, shouldSatisfy)
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck (arbitrary, choose, withMaxSuccess)
import Test.QuickCheck.Monadic (PropertyM, monadicIO, pick)
import Pos.Chain.Txp (TxOut (..), TxOutAux (..))
import qualified Pos.Chain.Txp as Core
import Pos.Core as Core
import Pos.Core (Coin (..), IsBootstrapEraAddr (..),
deriveLvl2KeyPair, mkCoin)
import Pos.Core.NetworkMagic (NetworkMagic (..), makeNetworkMagic)
import Pos.Crypto (EncryptedSecretKey, ProtocolMagic,
ShouldCheckPassphrase (..), emptyPassphrase,
safeDeterministicKeyGen)
import Pos.Crypto.HD (firstHardened)
import Cardano.Wallet.API.Request
import Cardano.Wallet.API.Request.Pagination
import Cardano.Wallet.API.Response
import qualified Cardano.Wallet.API.V1.Handlers.Transactions as Handlers
import qualified Cardano.Wallet.API.V1.Types as V1
import qualified Cardano.Wallet.Kernel as Kernel
import Cardano.Wallet.Kernel.CoinSelection.FromGeneric
(CoinSelectionOptions (..), ExpenseRegulation (..),
InputGrouping (..), newOptions)
import Cardano.Wallet.Kernel.DB.AcidState
import Cardano.Wallet.Kernel.DB.HdWallet (AssuranceLevel (..),
HasSpendingPassword (..), HdAccountId (..),
HdAccountIx (..), HdAddressIx (..), HdRoot (..),
HdRootId (..), WalletName (..), eskToHdRootId,
hdAccountIdIx)
import Cardano.Wallet.Kernel.DB.HdWallet.Create (initHdRoot)
import Cardano.Wallet.Kernel.DB.HdWallet.Derivation
(HardeningMode (..), deriveIndex)
import Cardano.Wallet.Kernel.DB.InDb (InDb (..), fromDb)
import Cardano.Wallet.Kernel.DB.TxMeta
import qualified Cardano.Wallet.Kernel.DB.Util.IxSet as IxSet
import Cardano.Wallet.Kernel.Internal
import qualified Cardano.Wallet.Kernel.Keystore as Keystore
import qualified Cardano.Wallet.Kernel.PrefilterTx as Kernel
import qualified Cardano.Wallet.Kernel.Read as Kernel
import qualified Cardano.Wallet.Kernel.Transactions as Kernel
import Cardano.Wallet.Kernel.Types (AccountId (..), WalletId (..))
import qualified Cardano.Wallet.Kernel.Wallets as Kernel
import Cardano.Wallet.WalletLayer (ActiveWalletLayer (..),
walletPassiveLayer)
import qualified Cardano.Wallet.WalletLayer as WalletLayer
import qualified Cardano.Wallet.WalletLayer.Kernel.Accounts as Accounts
import qualified Cardano.Wallet.WalletLayer.Kernel.Conv as Kernel.Conv
import Cardano.Wallet.WalletLayer.Kernel.Transactions (toTransaction)
import qualified Test.Spec.Addresses as Addresses
import Test.Spec.CoinSelection.Generators (InitialBalance (..),
Pay (..), genUtxoWithAtLeast)
import qualified Test.Spec.Fixture as Fixture
import qualified Test.Spec.NewPayment as NewPayment
import Test.Spec.TxMetaStorage (Isomorphic (..), genMeta)
# ANN module ( " HLint : ignore Reduce duplication " : : Text ) #
data Fix = Fix {
fixtureHdRootId :: HdRootId
, fixtureHdRoot :: HdRoot
, fixtureESK :: EncryptedSecretKey
, fixtureAccountId :: AccountId
, fixtureUtxo :: Core.Utxo
}
data Fixture = Fixture {
fixture :: [Fix]
, fixturePw :: PassiveWallet
}
and execute the ' acid - state ' update once the ' PassiveWallet ' gets into
prepareFixtures :: NetworkMagic
-> InitialBalance
-> Fixture.GenActiveWalletFixture Fixture
prepareFixtures nm initialBalance = do
fixt <- forM [0x11, 0x22] $ \b -> do
let (_, esk) = safeDeterministicKeyGen (B.pack $ replicate 32 b) mempty
let newRootId = eskToHdRootId nm esk
newRoot <- initHdRoot <$> pure newRootId
<*> pure (WalletName "A wallet")
<*> pure NoSpendingPassword
<*> pure AssuranceLevelNormal
<*> (InDb <$> pick arbitrary)
newAccountId <- HdAccountId newRootId <$> deriveIndex (pick . choose) HdAccountIx HardDerivation
utxo <- pick (genUtxoWithAtLeast initialBalance)
Override all the addresses of the random with something meaningful ,
utxo' <- foldlM (\acc (txIn, (TxOutAux (TxOut _ coin))) -> do
newIndex <- deriveIndex (pick . choose) HdAddressIx HardDerivation
let Just (addr, _) = deriveLvl2KeyPair nm
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase True)
mempty
esk
(newAccountId ^. hdAccountIdIx . to getHdAccountIx)
(getHdAddressIx newIndex)
return $ M.insert txIn (TxOutAux (TxOut addr coin)) acc
) M.empty (M.toList utxo)
return $ Fix {
fixtureHdRootId = newRootId
, fixtureHdRoot = newRoot
, fixtureAccountId = AccountIdHdRnd newAccountId
, fixtureESK = esk
, fixtureUtxo = utxo'
}
return $ \keystore aw -> do
let pw = Kernel.walletPassive aw
forM_ fixt $ \Fix{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let accounts = Kernel.prefilterUtxo nm fixtureHdRootId fixtureESK fixtureUtxo
hdAccountId = Kernel.defaultHdAccountId fixtureHdRootId
hdAddress = Kernel.defaultHdAddress nm fixtureESK emptyPassphrase fixtureHdRootId
void $ liftIO $ update (pw ^. wallets) (CreateHdWallet fixtureHdRoot hdAccountId hdAddress accounts)
return $ Fixture {
fixture = fixt
, fixturePw = pw
}
withFixture :: MonadIO m
=> ProtocolMagic
-> InitialBalance
-> ( Keystore.Keystore
-> WalletLayer.ActiveWalletLayer m
-> Kernel.ActiveWallet
-> Fixture
-> IO a
)
-> PropertyM IO a
withFixture pm initialBalance cc =
Fixture.withActiveWalletFixture pm (prepareFixtures nm initialBalance) cc
where
nm = makeNetworkMagic pm
getFixedAddress :: WalletLayer.ActiveWalletLayer IO -> Fix -> IO Core.Address
getFixedAddress layer Fix{..} = do
let params = RequestParams (PaginationParams (Page 1) (PerPage 10))
let filters = NoFilters
Right wr <- WalletLayer.getAccountAddresses (walletPassiveLayer layer)
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex firstHardened)
params
filters
let [address] = wrData wr
return $ V1.unV1 . V1.addrId $ address
getNonFixedAddress :: WalletLayer.ActiveWalletLayer IO -> Fix -> IO Core.Address
getNonFixedAddress layer Fix{..} = do
let params = RequestParams (PaginationParams (Page 1) (PerPage 10))
let filters = NoFilters
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let index = getHdAccountIx $ hdAccountId ^. hdAccountIdIx
Right wr <- WalletLayer.getAccountAddresses (walletPassiveLayer layer)
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex index)
params
filters
let (address : _) = wrData wr
return $ V1.unV1 . V1.addrId $ address
getAccountBalanceNow :: Kernel.PassiveWallet -> Fix -> IO Word64
getAccountBalanceNow pw Fix{..} = do
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let index = getHdAccountIx $ hdAccountId ^. hdAccountIdIx
db <- Kernel.getWalletSnapshot pw
let res =
Accounts.getAccountBalance
(Kernel.Conv.toRootId fixtureHdRootId)
(V1.unsafeMkAccountIndex index)
db
bimap STB STB res `shouldSatisfy` isRight
let Right (V1.AccountBalance (V1.V1 (Coin coins))) = res
return coins
constantFee :: Word64 -> Int -> NonEmpty Coin -> Coin
constantFee c _ _ = mkCoin c
spec :: Spec
spec = do
describe "GetTransactions" $ do
prop "scenario: Layer.CreateAddress -> TxMeta.putTxMeta -> Layer.getTransactions works properly." $ withMaxSuccess 5 $
monadicIO $ do
testMetaSTB <- pick genMeta
pm <- pick arbitrary
Addresses.withFixture pm $ \keystore layer pwallet Addresses.Fixture{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let (HdRootId hdRoot) = fixtureHdRootId
(AccountIdHdRnd myAccountId) = fixtureAccountId
wId = sformat build (view fromDb hdRoot)
accIdx = myAccountId ^. hdAccountIdIx . to getHdAccountIx
hdl = (pwallet ^. Kernel.walletMeta)
testMeta = unSTB testMetaSTB
case decodeTextAddress wId of
Left _ -> expectationFailure "decodeTextAddress failed"
Right rootAddr -> do
let meta = testMeta {_txMetaWalletId = rootAddr, _txMetaAccountIx = accIdx}
_ <- liftIO $ WalletLayer.createAddress layer
(V1.NewAddress
Nothing
(V1.unsafeMkAccountIndex accIdx)
(V1.WalletId wId)
)
putTxMeta (pwallet ^. Kernel.walletMeta) meta
(result, mbCount) <- (getTxMetas hdl) (Offset 0) (Limit 10) Everything Nothing NoFilterOp NoFilterOp Nothing
map Isomorphic result `shouldMatchList` [Isomorphic meta]
let check APIResponse{..} = do
let PaginationMetadata{..} = metaPagination wrMeta
wrStatus `shouldBe` SuccessStatus
length wrData `shouldBe` 1
metaTotalPages `shouldBe` 1
metaTotalEntries `shouldBe` 1
metaPage `shouldBe` (Page 1)
metaPerPage `shouldBe` (PerPage 10)
case wrData of
[tx] -> V1.txStatus tx `shouldBe` V1.WontApply
ls -> expectationFailure $ "Tx list returned has wrong size "
<> show (length ls) <> "instead of 1: ls = " <> show ls
eiResp <- WalletLayer.getTransactions
layer
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
mbCount `shouldBe` (Just 1)
case eiResp of
Left l -> expectationFailure $ "returned " <> show l
Right resp -> check resp
prop "scenario: Layer.pay -> Layer.getTransactions works properly. Tx status should be Applying " $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
NewPayment.withFixture @IO pm (InitialADA 10000) (PayLovelace 25) $ \keystore activeLayer aw NewPayment.Fixture{..} -> do
liftIO $ Keystore.insert (WalletIdHdRnd fixtureHdRootId) fixtureESK keystore
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
let (HdRootId (InDb rootAddress)) = fixtureHdRootId
let sourceWallet = V1.WalletId (sformat build rootAddress)
let accountIndex = Kernel.Conv.toAccountId hdAccountId
let destinations =
fmap (\(addr, coin) -> V1.PaymentDistribution (V1.V1 addr) (V1.V1 coin)
) fixturePayees
let newPayment = V1.Payment {
pmtSource = V1.PaymentSource sourceWallet accountIndex
, pmtDestinations = destinations
, pmtGroupingPolicy = Nothing
, pmtSpendingPassword = Nothing
}
res <- liftIO ((WalletLayer.pay activeLayer) mempty
IgnoreGrouping
SenderPaysFee
newPayment
)
case res of
Left _ -> expectationFailure "Kernel.newTransaction failed"
Right (_, meta) -> do
let txid = _txMetaId meta
pw = Kernel.walletPassive aw
layer = walletPassiveLayer activeLayer
(HdRootId hdRoot) = fixtureHdRootId
wId = sformat build (view fromDb hdRoot)
accIdx = Kernel.Conv.toAccountId hdAccountId
hdl = (pw ^. Kernel.walletMeta)
db <- Kernel.getWalletSnapshot pw
let isPending = Kernel.currentTxIsPending db txid hdAccountId
_ <- case isPending of
Left _err -> expectationFailure "hdAccountId not found in Acid State from Kernel"
Right False -> expectationFailure "txid not found in Acid State from Kernel"
Right True -> pure ()
_ <- liftIO (WalletLayer.createAddress layer (V1.NewAddress Nothing accIdx (V1.WalletId wId)))
(result, mbCount) <- (getTxMetas hdl) (Offset 0) (Limit 10) Everything Nothing NoFilterOp NoFilterOp Nothing
map Isomorphic result `shouldMatchList` [Isomorphic meta]
let check APIResponse{..} = do
let PaginationMetadata{..} = metaPagination wrMeta
wrStatus `shouldBe` SuccessStatus
length wrData `shouldBe` 1
metaTotalPages `shouldBe` 1
metaTotalEntries `shouldBe` 1
metaPage `shouldBe` (Page 1)
metaPerPage `shouldBe` (PerPage 10)
case wrData of
[tx1] -> do
V1.txStatus tx1 `shouldBe` V1.Applying
ls -> expectationFailure $ "Tx list returned has wrong size "
<> show (length ls) <> "instead of 1: ls = " <> show ls
eiResp <- WalletLayer.getTransactions
layer
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
mbCount `shouldBe` (Just 1)
case eiResp of
Left l -> expectationFailure $ "returned " <> show l
Right resp -> check resp
prop "newTransaction and getTransactions return the same result" $ withMaxSuccess 5 $ do
monadicIO $ do
pm <- pick arbitrary
NewPayment.withPayment pm (InitialADA 10000) (PayLovelace 100) $ \activeLayer newPayment -> do
payRes <- liftIO (runExceptT . runHandler' $ Handlers.newTransaction activeLayer newPayment)
getTxRes <- WalletLayer.getTransactions
(walletPassiveLayer activeLayer)
Nothing
Nothing
Nothing
(RequestParams $ PaginationParams (Page 1) (PerPage 10))
NoFilters
NoSorts
case (payRes, getTxRes) of
(Right txMetaPay, Right txMetaGet) ->
wrData txMetaGet `shouldBe` wrData ((\x -> [x]) <$> txMetaPay)
_ -> expectationFailure "WalletLayer.getTransactions or Handlers.newTransaction failed"
prop "TxMeta from pay has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
NewPayment.withFixture @IO pm (InitialADA 10000) (PayLovelace 100) $ \_ _ aw NewPayment.Fixture{..} -> do
we use constant fees here , to have predictable .
let (AccountIdHdRnd hdAccountId) = fixtureAccountId
(_tx, txMeta) <- payAux aw hdAccountId fixturePayees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
describe "Transactions with multiple wallets" $ do
prop "test fixture has all the wanted properies" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
db <- Kernel.getWalletSnapshot (Kernel.walletPassive aw)
let Right accs1 = Accounts.getAccounts (Kernel.Conv.toRootId $ fixtureHdRootId w1) db
length (IxSet.toList accs1) `shouldBe` 2
let Right accs2 = Accounts.getAccounts (Kernel.Conv.toRootId $ fixtureHdRootId w2) db
length (IxSet.toList accs2) `shouldBe` 2
_ <- getFixedAddress layer w1
_ <- getFixedAddress layer w2
_ <- getNonFixedAddress layer w1
_ <- getNonFixedAddress layer w2
return ()
prop "TxMeta from pay between two wallets has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
address <- getFixedAddress layer w2
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
txMeta ^. txMetaIsOutgoing `shouldBe` True
txMeta ^. txMetaIsLocal `shouldBe` False
res <- toTransaction pw txMeta
bimap STB STB res `shouldSatisfy` isRight
let Right tx = res
V1.txStatus tx `shouldBe` V1.Applying
V1.txConfirmations tx `shouldBe` 0
prop "as above but now we pay to the explicitely created account" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
address <- getNonFixedAddress layer w2
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
prop "payment to different wallet changes the balance the same as txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
coinsBefore <- getAccountBalanceNow pw w1
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
address <- getFixedAddress layer w2
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
prop "as above but now we pay to the explicitely created account" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
coinsBefore <- getAccountBalanceNow pw w1
address <- getNonFixedAddress layer w2
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_tx, txMeta) <- payAux aw hdAccountId1 payees 200
txMeta ^. txMetaAmount `shouldBe` Coin 300
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
prop "2 consecutive payments" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, w2] _) -> do
let pw = Kernel.walletPassive aw
coinsBefore <- getAccountBalanceNow pw w1
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
address1 <- getFixedAddress layer w2
address2 <- getNonFixedAddress layer w2
let payees1 = (NonEmpty.fromList [(address1, Coin 100)])
(_, txMeta1) <- payAux aw hdAccountId1 payees1 200
txMeta1 ^. txMetaAmount `shouldBe` Coin 300
do the second payment
let payees2 = (NonEmpty.fromList [(address2, Coin 400)])
(_, txMeta2) <- payAux aw hdAccountId1 payees2 800
txMeta2 ^. txMetaAmount `shouldBe` Coin 1200
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 1500
describe "Transactions with multiple accounts" $ do
prop "TxMeta from pay between two accounts of the same wallet has the correct txAmount" $ withMaxSuccess 5 $
monadicIO $ do
pm <- pick arbitrary
withFixture @IO pm (InitialADA 10000) $ \_ layer aw (Fixture [w1, _] _) -> do
let pw = Kernel.walletPassive aw
coinsBefore <- getAccountBalanceNow pw w1
address <- getFixedAddress layer w1
let (AccountIdHdRnd hdAccountId1) = fixtureAccountId w1
let payees = (NonEmpty.fromList [(address, Coin 100)])
(_, txMeta) <- payAux aw hdAccountId1 payees 200
this is 200 because the outputs is at the same wallet .
txMeta ^. txMetaAmount `shouldBe` Coin 200
txMeta ^. txMetaIsOutgoing `shouldBe` True
txMeta ^. txMetaIsLocal `shouldBe` True
coinsAfter <- getAccountBalanceNow pw w1
coinsBefore - coinsAfter `shouldBe` 300
payAux :: Kernel.ActiveWallet -> HdAccountId -> NonEmpty (Address, Coin) -> Word64 -> IO (Core.Tx, TxMeta)
payAux aw hdAccountId payees fees = do
let opts = (newOptions (constantFee fees)) {
csoExpenseRegulation = SenderPaysFee
, csoInputGrouping = IgnoreGrouping
}
payRes <- (Kernel.pay aw
mempty
opts
hdAccountId
payees
)
bimap STB STB payRes `shouldSatisfy` isRight
let Right t = payRes
return t
|
2b6437c33e5440f9ff985053af49cf74607f7b5758943029434062577838d494 | avsm/mirage-duniverse | type_abstract.mli | (**
Abstract types helpers.
An abstract type in the sense of the typerep library is a type whose representation is
unknown. Such a type has only a name that can be used to provide and register custom
implementation of generics. This is typically a type obtained with the following syntax
extension:
{[
type t with typerep(abstract)
]}
The following functors are meant to be used by the code generator, however they could
also be useful while writing low level typerep code manually.
*)
module Make0 (X : Named_intf.S0) : Typerepable.S0
with type t := X.t
module Make1 (X : Named_intf.S1) : Typerepable.S1
with type 'a t := 'a X.t
module Make2 (X : Named_intf.S2) : Typerepable.S2
with type ('a, 'b) t := ('a, 'b) X.t
module Make3 (X : Named_intf.S3) : Typerepable.S3
with type ('a, 'b, 'c) t := ('a, 'b, 'c) X.t
module Make4 (X : Named_intf.S4) : Typerepable.S4
with type ('a, 'b, 'c, 'd) t := ('a, 'b, 'c, 'd) X.t
module Make5 (X : Named_intf.S5) : Typerepable.S5
with type ('a, 'b, 'c, 'd, 'e) t := ('a, 'b, 'c, 'd, 'e) X.t
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/typerep/lib/type_abstract.mli | ocaml | *
Abstract types helpers.
An abstract type in the sense of the typerep library is a type whose representation is
unknown. Such a type has only a name that can be used to provide and register custom
implementation of generics. This is typically a type obtained with the following syntax
extension:
{[
type t with typerep(abstract)
]}
The following functors are meant to be used by the code generator, however they could
also be useful while writing low level typerep code manually.
|
module Make0 (X : Named_intf.S0) : Typerepable.S0
with type t := X.t
module Make1 (X : Named_intf.S1) : Typerepable.S1
with type 'a t := 'a X.t
module Make2 (X : Named_intf.S2) : Typerepable.S2
with type ('a, 'b) t := ('a, 'b) X.t
module Make3 (X : Named_intf.S3) : Typerepable.S3
with type ('a, 'b, 'c) t := ('a, 'b, 'c) X.t
module Make4 (X : Named_intf.S4) : Typerepable.S4
with type ('a, 'b, 'c, 'd) t := ('a, 'b, 'c, 'd) X.t
module Make5 (X : Named_intf.S5) : Typerepable.S5
with type ('a, 'b, 'c, 'd, 'e) t := ('a, 'b, 'c, 'd, 'e) X.t
|
bc7e9557d492bc25310002e2a2b069cf8507bad44761659e71a238b7cbad384a | eeng/shevek | repository_test.clj | (ns shevek.dashboards.repository-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.test-helper :refer [it wrap-unit-tests]]
[shevek.asserts :refer [submaps? submap? without?]]
[shevek.dashboards.repository :as r]
[shevek.db :refer [db]]
[shevek.lib.mongodb :as m]))
(use-fixtures :once wrap-unit-tests)
(deftest save-tests
(it "should save each report in their collection and store only the ids in the dashboard"
(r/save-dashboard db {:name "D" :panels [{:report {:name "R1"}} {:report {:name "R2"}}]})
(let [reports (m/find-all db "reports")]
(is (submaps? [{:name "R1"} {:name "R2"}]
reports))
(is (submaps? [{:name "D" :panels [{:report-id (-> reports first :id)}
{:report-id (-> reports second :id)}]}]
(m/find-all db "dashboards")))))
(it "if the report is not present should not try to save it"
(->> {:name "D" :panels [{:report {:name "R"}}]}
(r/save-dashboard db)
(r/save-dashboard db)) ; Here we have only the report-id
(is (= 1 (m/count db "reports"))))
; So the dashboards reports don't appear independently in the reports page
(it "should not set the owner-id of the reports"
(r/save-dashboard db {:name "D" :panels [{:report {:name "R"}}]})
(is (without? :owner-id (m/find-last db "reports")))))
(deftest delete-dashboard-tests
(it "should remove the dashboard and its reports"
(let [d1 (r/save-dashboard db {:name "D1" :panels [{:report {:name "R1"}}]})]
(r/save-dashboard db {:name "D2" :panels [{:report {:name "R2"}}]})
(r/delete-dashboard db (:id d1))
(is (submaps? [{:name "D2"}] (m/find-all db "dashboards")))
(is (submaps? [{:name "R2"}] (m/find-all db "reports")))))
(it "if there are slaves of the report to delete, they should became masters"
(let [master (r/save-dashboard db {:name "M" :panels [{:report {:name "R"}}]})
slave1 (r/save-dashboard db {:name "S1" :master-id (:id master)})
slave2 (r/save-dashboard db {:name "S2" :master-id (:id master)})]
(r/delete-dashboard db (:id master))
(let [slave1 (r/find-by-id! db (:id slave1))
slave2 (r/find-by-id! db (:id slave2))
idrs1 (get-in slave1 [:panels 0 :report-id])
idrs2 (get-in slave2 [:panels 0 :report-id])
r1 (m/find-by-id db "reports" idrs1)
r2 (m/find-by-id db "reports" idrs2)]
(is (= 2 (m/count db "reports")))
(is (= 2 (m/count db "dashboards")))
(is (without? :master-id slave1))
(is (without? :master-id slave2))
(is (not= idrs1 idrs2))
(is (submap? {:name "R" :dashboard-id (:id slave1)} r1))
(is (submap? {:name "R" :dashboard-id (:id slave2)} r2))))))
| null | https://raw.githubusercontent.com/eeng/shevek/7783b8037303b8dd5f320f35edee3bfbb2b41c02/test/clj/shevek/dashboards/repository_test.clj | clojure | Here we have only the report-id
So the dashboards reports don't appear independently in the reports page | (ns shevek.dashboards.repository-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.test-helper :refer [it wrap-unit-tests]]
[shevek.asserts :refer [submaps? submap? without?]]
[shevek.dashboards.repository :as r]
[shevek.db :refer [db]]
[shevek.lib.mongodb :as m]))
(use-fixtures :once wrap-unit-tests)
(deftest save-tests
(it "should save each report in their collection and store only the ids in the dashboard"
(r/save-dashboard db {:name "D" :panels [{:report {:name "R1"}} {:report {:name "R2"}}]})
(let [reports (m/find-all db "reports")]
(is (submaps? [{:name "R1"} {:name "R2"}]
reports))
(is (submaps? [{:name "D" :panels [{:report-id (-> reports first :id)}
{:report-id (-> reports second :id)}]}]
(m/find-all db "dashboards")))))
(it "if the report is not present should not try to save it"
(->> {:name "D" :panels [{:report {:name "R"}}]}
(r/save-dashboard db)
(is (= 1 (m/count db "reports"))))
(it "should not set the owner-id of the reports"
(r/save-dashboard db {:name "D" :panels [{:report {:name "R"}}]})
(is (without? :owner-id (m/find-last db "reports")))))
(deftest delete-dashboard-tests
(it "should remove the dashboard and its reports"
(let [d1 (r/save-dashboard db {:name "D1" :panels [{:report {:name "R1"}}]})]
(r/save-dashboard db {:name "D2" :panels [{:report {:name "R2"}}]})
(r/delete-dashboard db (:id d1))
(is (submaps? [{:name "D2"}] (m/find-all db "dashboards")))
(is (submaps? [{:name "R2"}] (m/find-all db "reports")))))
(it "if there are slaves of the report to delete, they should became masters"
(let [master (r/save-dashboard db {:name "M" :panels [{:report {:name "R"}}]})
slave1 (r/save-dashboard db {:name "S1" :master-id (:id master)})
slave2 (r/save-dashboard db {:name "S2" :master-id (:id master)})]
(r/delete-dashboard db (:id master))
(let [slave1 (r/find-by-id! db (:id slave1))
slave2 (r/find-by-id! db (:id slave2))
idrs1 (get-in slave1 [:panels 0 :report-id])
idrs2 (get-in slave2 [:panels 0 :report-id])
r1 (m/find-by-id db "reports" idrs1)
r2 (m/find-by-id db "reports" idrs2)]
(is (= 2 (m/count db "reports")))
(is (= 2 (m/count db "dashboards")))
(is (without? :master-id slave1))
(is (without? :master-id slave2))
(is (not= idrs1 idrs2))
(is (submap? {:name "R" :dashboard-id (:id slave1)} r1))
(is (submap? {:name "R" :dashboard-id (:id slave2)} r2))))))
|
0b303dba3e33f49ad073600b6e3d78a45b3a0232e0f0a31ca42a1921805ed2ce | funcatron/tron | tron_mode.clj | (ns funcatron.tron.modes.tron-mode
(:gen-class)
(:require [funcatron.tron.util :as fu]
[clojure.java.io :as cio]
[taoensso.timbre
:refer [log trace debug info warn error fatal report
logf tracef debugf infof warnf errorf fatalf reportf
spy get-env]]
[ring.middleware.json :as rm-json :refer [wrap-json-response]]
[compojure.core :refer [GET defroutes POST routes]]
[compojure.route :refer [not-found resources]]
[funcatron.tron.modes.common :as common]
[funcatron.tron.brokers.shared :as shared-b]
[funcatron.tron.routers.jar-router :as jarjar]
[funcatron.tron.options :as opts])
(:import (java.io File)
(funcatron.abstractions MessageBroker MessageBroker$ReceivedMessage Lifecycle)
(java.net URLEncoder)))
(set! *warn-on-reflection* true)
(def ^:private file-version (fu/random-uuid))
(defn- clean-network
"Remove everything from the network that's old"
[state]
if we have n't seen a node in 3 minutes , clean it
(swap!
(::network state)
(fn [cur]
(into
{}
(remove #(> too-old (:last-seen (second %))) cur))))))
(defn- send-host-info
"Sends a message about host information... how to HTTP to Tron"
[dest {:keys [::queue ::opts] :as state}]
(.sendMessage
^MessageBroker queue
dest
{:content-type "application/json"}
{:action "tron-info"
:msg-id (fu/random-uuid)
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:at (System/currentTimeMillis)
})
)
(defn- try-to-load-route-map
"Try to load the route map"
[opts bundles]
(let [file (fu/new-file (common/calc-storage-directory opts) "route_map.data")]
(try
(if (.exists file)
(let [data (slurp file)
data (read-string data)]
(if (map? data)
(let [data (into {} (filter #(contains? bundles (-> % second :sha)) data))]
data))))
(catch Exception e
(do
(error e "Failed to load route map")
[])))))
(defn- alter-listening
"Tell the runner to either listen to the bundle or sto stop listening"
[host path sha properties from {:keys [::queue ::opts]} action]
(let [message-queue queue]
(.sendMessage
^MessageBroker message-queue
from
{:content-type "application/json"}
{:action action
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:version (:version fu/version-info)
:at (System/currentTimeMillis)
:host host
:basePath path
:props properties
:sha sha})))
(defn- tell-runners-to-alter-listening
"Tell all the runners to alter their listening"
[host path sha properties {:keys [::network] :as state} action]
(clean-network state)
(doseq [[k {:keys [type]}] @network]
(cond
(= type "runner")
(do
(info (str "Alter " k " action " action))
(fu/run-in-pool (fn [] (alter-listening host path sha properties k state action))))
))
)
(defn- add-to-route-map
"Adds a route to the route table"
[host path bundle-sha properties route-map-atom state]
(let [sha (fu/route-to-sha host path)
data {:host host :path path :queue sha :sha bundle-sha :props properties}]
(tell-runners-to-alter-listening host path bundle-sha properties state "enable")
(swap!
route-map-atom
(fn [rm]
(let [rm (remove #(= (:queue %) sha) rm)
rm (conj rm data)
rm (sort
(fn [{:keys [path]} y]
(let [py (:path y)]
(- (count py) (count path)))
)
rm)]
(into [] rm))
))))
(defn- remove-from-route-map
"Removes a func bundle from the route map"
[host path bundle-sha route-map-atom state]
(tell-runners-to-alter-listening host path bundle-sha {} state "disable")
(swap!
route-map-atom
(fn [rm]
(let [rm (remove #(= (:sha %) bundle-sha) rm)]
(into [] rm))
)))
(defn- remove-other-instances-of-this-frontend
"Finds other front-end instances with the same `instance-id` and tell them to die"
[{:keys [from instance-id]} {:keys [::network ::queue]}]
(let [to-kill (filter (fn [[k v]]
(and (not= k from)
(= instance-id (:instance-id v))))
@network
)
kill-keys (into #{} (map first to-kill))
]
;; no more messages to the instances we're removing
(swap! network
(fn [m]
(into {} (remove #(kill-keys (first %)) m))))
(doseq [[k {:keys [instance-id]}] to-kill]
(info (str "Killing old id " k " with instance-id " instance-id))
(.sendMessage
^MessageBroker queue
k
{:content-type "application/json"}
{:action "die"
:version (:version fu/version-info)
:msg-id (fu/random-uuid)
:instance-id instance-id
:at (System/currentTimeMillis)
}))))
(defn- send-route-map
"Sends the route map to a destination"
([where {:keys [::queue ::route-map]}]
(.sendMessage
^MessageBroker queue where
{:content-type "application/json"}
{:action "route"
:version (:version fu/version-info)
:msg-id (fu/random-uuid)
:routes (or @route-map [])
:at (System/currentTimeMillis)
})))
(defn- routes-changed
"The routes changed, let all the front end instances know"
[{:keys [::network ::opts] :as state} _ _ new-routes]
(fu/run-in-pool
(fn []
;; write the file
(let [file (fu/new-file (common/calc-storage-directory opts) "route_map.data")]
(try
(spit file (pr-str new-routes))
(catch Exception e (error e "Failed to write route map"))
))
(clean-network state)
(doseq [[k {:keys [type]}] @network]
(cond
(= type "frontend")
(send-route-map k state)
)))))
#_(defn ^StableStore backing-store
"Returns the backing store object"
[]
@-backing-store)
(defn- no-file-with-same-sha
"Make sure there are no files in the storage-directory that have the same sha"
[sha-to-test {:keys [::opts]}]
(let [sha (URLEncoder/encode sha-to-test)
files (filter #(.contains ^String % sha) (.list ^File (common/calc-storage-directory opts)))]
(empty? files)))
(defn- upload-func-bundle
"Get a func bundle"
[{:keys [body]} {:keys [::opts ::bundles] :as state}]
(if body
(let [file (File/createTempFile "func-a-" ".tron")]
(cio/copy body file)
(try
;; load the file and make sure it's a valid func bundle
(let [{:keys [sha type ]} (common/sha-for-file file)
thing (jarjar/build-router file {})
swagger (fu/keywordize-keys (.swagger thing))
host (.host thing)
basePath (.basePath thing)
]
(.endLife thing)
(if (and type sha)
(let [dest-file (fu/new-file
(common/calc-storage-directory opts)
(str (System/currentTimeMillis)
"-"
(fu/clean-sha (URLEncoder/encode sha)) ".funcbundle"))]
(when (no-file-with-same-sha sha state)
(cio/copy file dest-file))
(.delete file)
(swap! bundles assoc sha {:file dest-file :swagger swagger})
{:status 200
:body {:accepted true
:type type
:host host
:route basePath
:swagger swagger
:sha sha}})
(do
(info (str "Failed to upload Func Bundle... failed the type and file-info test. Type "
type))
(info (str "The most likely reason is a missing or malformed funcatron.yaml file"))
{:status 400
:body {:accepted false
:error "Could not determine the file type"}})))
(catch Exception e (do
(error e "Failed up upload JAR")
{:status 400
:body {:accepted false
:error (.toString e)}})))
)
{:status 400
:body {:accepted false
:error "Must post a Func bundle file"}}
)
)
(defn- enable-func
"Enable a Func bundle"
[{:keys [json-params]} {:keys [::bundles ::route-map] :as state}]
(let [json-params (fu/keywordize-keys json-params)
{:keys [sha props]} json-params]
(if (not (and json-params sha))
;; failed
{:status 400
:body {:success false :error "Request must be JSON and include the 'sha' of the Func bundle to enable"}}
;; find the Func bundle and enable it
(let [{{:keys [host basePath]} :swagger :as bundle} (get @bundles sha)]
(if (not bundle)
;; couldn't find the bundle
{:status 404
:body {:success false :error (str "Could not find Func bundle with SHA: " sha)}}
(do
(add-to-route-map host basePath sha props route-map state)
{:status 200
:body {:success true :msg (str "Deployed Func bundle host: " host " basePath " basePath " sha " sha)}})
))
))
)
(defn- disable-func
"Disable a Func bundle"
[{:keys [json-params]} {:keys [::bundles ::route-map] :as state}]
(let [json-params (fu/keywordize-keys json-params)
{:keys [sha]} json-params]
(if (not (and json-params sha))
;; failed
{:status 400
:body {:success false :error "Request must be JSON and include the 'sha' of the Func bundle to disable"}}
;; find the Func bundle and enable it
(let [{{:keys [host basePath]} :swagger :as bundle} (get @bundles sha)]
(if (not bundle)
;; couldn't find the bundle
{:status 404
:body {:success false :error (str "Could not find Func bundle with SHA: " sha)}}
(do
(remove-from-route-map host basePath sha route-map state)
{:status 200
:body {:success true :msg (str "Deployed Func bundle host: " host " basePath " basePath " sha " sha)}})
)))))
(defn- bundles-from-state
"Pass in the state object and get a list of func bundles"
[{:keys [::bundles]}]
(map (fn [[k {{:keys [host basePath]} :swagger}]]
{:sha k
:host host
:path basePath})
@bundles))
(defn- get-known-funcs
"Return all the known func bundles"
[_ state]
{:status 200
:body {:func-bundles (bundles-from-state state)}})
(defn- get-stats
"Return statistics on activity"
[_ {:keys [::network ::route-map]}]
{:status 200
:body {:network @network
:route-map @route-map}
})
(defn- get-routes
"Return current routes"
[_ {:keys [ ::route-map]}]
{:status 200
:body @route-map
})
(defn- return-sha
"Get the Func bundle with the sha"
[req {:keys [::bundles]}]
(let [sha (-> req :params vals first)]
(if-let [{:keys [file]} (get @bundles sha)]
{:status 200
:body (clojure.java.io/input-stream file)}
{:status 404
:body (str "No func bundle with sha " sha " found")}
)
)
)
(defn tron-routes
"Routes for Tron"
[state]
(-> (routes
(POST "/api/v1/enable" req (enable-func req state))
(POST "/api/v1/disable" req (disable-func req state))
(GET "/api/v1/stats" req (get-stats req state))
(GET "/api/v1/routes" req (get-routes req state))
(GET "/api/v1/known_funcs" req (get-known-funcs req state))
(GET "/api/v1/bundle/:sha" req (return-sha req state))
(POST "/api/v1/add_func"
req (upload-func-bundle req state)))
(wrap-json-response :pretty true :escape-non-ascii true)
rm-json/wrap-json-params
))
(defmulti dispatch-tron-message
"Dispatch the incoming message"
(fn [msg & _] (-> msg :action))
)
(defmethod dispatch-tron-message "heartbeat"
[{:keys [from] :as dog} _ {:keys [::network ::queue ::opts] :as state}]
(trace (str "Heartbeat from " from))
(clean-network state)
(let [rn @network]
(when (not (get-in rn [from :type]))
(.sendMessage
^MessageBroker queue
from
{:content-type "application/json"}
{:action "resend-awake"
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:at (System/currentTimeMillis)
})
))
(swap! network assoc-in [from :last-seen] (System/currentTimeMillis))
(send-host-info from state))
(defn- send-func-bundles
"Send a list of the Func bundles to the Runner as well
as the host and port for this instance"
[destination {:keys [::queue ::opts] :as state}]
(.sendMessage
^MessageBroker queue
destination
{:content-type "application/json"}
{:action "all-bundles"
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:at (System/currentTimeMillis)
:bundles (bundles-from-state state)
}))
(defmethod dispatch-tron-message "awake"
[{:keys [from type host_info] :as msg} _ {:keys [::network ::route-map] :as state}]
(info (str "awake from " msg))
(clean-network state)
(swap! network assoc from
(merge
msg
{:last-seen (System/currentTimeMillis)}))
(send-host-info from state)
(cond
(= "frontend" type)
(do
(send-route-map from state)
(remove-other-instances-of-this-frontend msg state)
(when-let [{:keys [host port]} host_info]
(when (and (not-empty host) (not-empty port))
(info (str "Frontend at http://" host ":" port))))
)
(= "runner" type)
(do
(send-func-bundles from state)
(let [routes @route-map]
(doseq [{:keys [host path sha props]} routes]
(alter-listening host path sha props from state "enable")))
)))
(defmethod dispatch-tron-message "died"
[{:keys [from]} _ {:keys [::network]}]
(info (str "Got 'died' message from " from))
(swap! network dissoc from)
)
(defn- handle-tron-messages
"Handle messages sent to the tron queue"
[state ^MessageBroker$ReceivedMessage msg]
(fu/run-in-pool
(fn []
(let [body (.body msg)
body (fu/keywordize-keys body)
at (:at body)]
deal with messages less than 30 minutes old
(when (> at (- (System/currentTimeMillis) (* 1000 15 30)))
(try
(trace (str "Got message. Action " (:action body) " from " (:from body)))
(dispatch-tron-message body msg state)
(catch Exception e (error e (str "Failed to dispatch message: " body)))))))))
(defn- build-handler-func
[state]
(let [ver (atom file-version)
_ (atom (tron-routes state)) ;; do this twice
the-func (atom (tron-routes state))]
(fn [req]
(when (not= @ver file-version)
(reset! ver file-version)
(reset! the-func (tron-routes state)))
(try
(@the-func req)
(catch Exception e
(do
(error e "Why did this fail?")
(throw e))))
)))
(defn ^Lifecycle build-tron
"Builds a Tron instance as a Lifecycle"
[^MessageBroker queue opts]
(let [bundles (atom {})
route-map (atom [])
network (atom {})
shutdown-http-server (atom nil)
this (atom nil)
state {::queue queue
::bundles bundles
::network network
::opts opts
::this this
::shutdown-http-server shutdown-http-server
::route-map route-map}
]
(add-watch route-map state routes-changed)
(let [ret (reify Lifecycle
(startLife [_]
(info (str "Starting Tron lifecycle"))
(reset! bundles (common/load-func-bundles (common/calc-storage-directory opts))) ;; load the bundles
(info (str "Loaded bundles... " (count @bundles)))
(reset! route-map (try-to-load-route-map opts @bundles))
(let [{:keys [host port]} (fu/compute-host-and-port opts)]
(info (str "Tron running at host " host " and port " port))
(info (str "Upload a Func Bundle: wget -q -O - --post-file=THE_UBERJAR http://" host ":" port "/api/v1/add_func\n"))
(info (str "List known Func Bundles: curl -v http://"
host
":"
port
"/api/v1/known_funcs"))
(info (str "Enable a Func Bundle: curl -v -H \"Content-Type: application/json\" -d '{\"sha\":\"THE-SHA-HERE\", \"props\": {\"key\": \"value\"}}' -X POST http://"
host
":"
port
"/api/v1/enable"))
)
(reset! shutdown-http-server (fu/start-http-server opts (build-handler-func state)))
(shared-b/listen-to-queue
queue
(common/tron-queue)
(partial handle-tron-messages state))
)
(endLife [_]
(info (str "Ending Tron Lifecycle"))
(shared-b/close-all-listeners queue)
(.close queue)
(@shutdown-http-server))
(allInfo [_] {::message-queue queue
::func-bundles @bundles
::routes @route-map
::this @this
::network @network})
)]
(reset! this ret)
ret
)))
(defn ^Lifecycle build-tron-from-opts
"Builds the runner from options... and if none are passed in, use global options"
([] (build-tron-from-opts @opts/command-line-options))
([opts]
(require ;; load a bunch of the namespaces to register wiring
'[funcatron.tron.brokers.rabbitmq]
'[funcatron.tron.brokers.inmemory]
'[funcatron.tron.store.zookeeper]
'[funcatron.tron.substrate.mesos-substrate])
(let [queue (shared-b/wire-up-queue opts)]
(build-tron queue opts)))) | null | https://raw.githubusercontent.com/funcatron/tron/cfe0c227f9c3ad88b3d072b0319954786afb5f15/src/clojure/funcatron/tron/modes/tron_mode.clj | clojure | no more messages to the instances we're removing
write the file
load the file and make sure it's a valid func bundle
failed
find the Func bundle and enable it
couldn't find the bundle
failed
find the Func bundle and enable it
couldn't find the bundle
do this twice
load the bundles
load a bunch of the namespaces to register wiring | (ns funcatron.tron.modes.tron-mode
(:gen-class)
(:require [funcatron.tron.util :as fu]
[clojure.java.io :as cio]
[taoensso.timbre
:refer [log trace debug info warn error fatal report
logf tracef debugf infof warnf errorf fatalf reportf
spy get-env]]
[ring.middleware.json :as rm-json :refer [wrap-json-response]]
[compojure.core :refer [GET defroutes POST routes]]
[compojure.route :refer [not-found resources]]
[funcatron.tron.modes.common :as common]
[funcatron.tron.brokers.shared :as shared-b]
[funcatron.tron.routers.jar-router :as jarjar]
[funcatron.tron.options :as opts])
(:import (java.io File)
(funcatron.abstractions MessageBroker MessageBroker$ReceivedMessage Lifecycle)
(java.net URLEncoder)))
(set! *warn-on-reflection* true)
(def ^:private file-version (fu/random-uuid))
(defn- clean-network
"Remove everything from the network that's old"
[state]
if we have n't seen a node in 3 minutes , clean it
(swap!
(::network state)
(fn [cur]
(into
{}
(remove #(> too-old (:last-seen (second %))) cur))))))
(defn- send-host-info
"Sends a message about host information... how to HTTP to Tron"
[dest {:keys [::queue ::opts] :as state}]
(.sendMessage
^MessageBroker queue
dest
{:content-type "application/json"}
{:action "tron-info"
:msg-id (fu/random-uuid)
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:at (System/currentTimeMillis)
})
)
(defn- try-to-load-route-map
"Try to load the route map"
[opts bundles]
(let [file (fu/new-file (common/calc-storage-directory opts) "route_map.data")]
(try
(if (.exists file)
(let [data (slurp file)
data (read-string data)]
(if (map? data)
(let [data (into {} (filter #(contains? bundles (-> % second :sha)) data))]
data))))
(catch Exception e
(do
(error e "Failed to load route map")
[])))))
(defn- alter-listening
"Tell the runner to either listen to the bundle or sto stop listening"
[host path sha properties from {:keys [::queue ::opts]} action]
(let [message-queue queue]
(.sendMessage
^MessageBroker message-queue
from
{:content-type "application/json"}
{:action action
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:version (:version fu/version-info)
:at (System/currentTimeMillis)
:host host
:basePath path
:props properties
:sha sha})))
(defn- tell-runners-to-alter-listening
"Tell all the runners to alter their listening"
[host path sha properties {:keys [::network] :as state} action]
(clean-network state)
(doseq [[k {:keys [type]}] @network]
(cond
(= type "runner")
(do
(info (str "Alter " k " action " action))
(fu/run-in-pool (fn [] (alter-listening host path sha properties k state action))))
))
)
(defn- add-to-route-map
"Adds a route to the route table"
[host path bundle-sha properties route-map-atom state]
(let [sha (fu/route-to-sha host path)
data {:host host :path path :queue sha :sha bundle-sha :props properties}]
(tell-runners-to-alter-listening host path bundle-sha properties state "enable")
(swap!
route-map-atom
(fn [rm]
(let [rm (remove #(= (:queue %) sha) rm)
rm (conj rm data)
rm (sort
(fn [{:keys [path]} y]
(let [py (:path y)]
(- (count py) (count path)))
)
rm)]
(into [] rm))
))))
(defn- remove-from-route-map
"Removes a func bundle from the route map"
[host path bundle-sha route-map-atom state]
(tell-runners-to-alter-listening host path bundle-sha {} state "disable")
(swap!
route-map-atom
(fn [rm]
(let [rm (remove #(= (:sha %) bundle-sha) rm)]
(into [] rm))
)))
(defn- remove-other-instances-of-this-frontend
"Finds other front-end instances with the same `instance-id` and tell them to die"
[{:keys [from instance-id]} {:keys [::network ::queue]}]
(let [to-kill (filter (fn [[k v]]
(and (not= k from)
(= instance-id (:instance-id v))))
@network
)
kill-keys (into #{} (map first to-kill))
]
(swap! network
(fn [m]
(into {} (remove #(kill-keys (first %)) m))))
(doseq [[k {:keys [instance-id]}] to-kill]
(info (str "Killing old id " k " with instance-id " instance-id))
(.sendMessage
^MessageBroker queue
k
{:content-type "application/json"}
{:action "die"
:version (:version fu/version-info)
:msg-id (fu/random-uuid)
:instance-id instance-id
:at (System/currentTimeMillis)
}))))
(defn- send-route-map
"Sends the route map to a destination"
([where {:keys [::queue ::route-map]}]
(.sendMessage
^MessageBroker queue where
{:content-type "application/json"}
{:action "route"
:version (:version fu/version-info)
:msg-id (fu/random-uuid)
:routes (or @route-map [])
:at (System/currentTimeMillis)
})))
(defn- routes-changed
"The routes changed, let all the front end instances know"
[{:keys [::network ::opts] :as state} _ _ new-routes]
(fu/run-in-pool
(fn []
(let [file (fu/new-file (common/calc-storage-directory opts) "route_map.data")]
(try
(spit file (pr-str new-routes))
(catch Exception e (error e "Failed to write route map"))
))
(clean-network state)
(doseq [[k {:keys [type]}] @network]
(cond
(= type "frontend")
(send-route-map k state)
)))))
#_(defn ^StableStore backing-store
"Returns the backing store object"
[]
@-backing-store)
(defn- no-file-with-same-sha
"Make sure there are no files in the storage-directory that have the same sha"
[sha-to-test {:keys [::opts]}]
(let [sha (URLEncoder/encode sha-to-test)
files (filter #(.contains ^String % sha) (.list ^File (common/calc-storage-directory opts)))]
(empty? files)))
(defn- upload-func-bundle
"Get a func bundle"
[{:keys [body]} {:keys [::opts ::bundles] :as state}]
(if body
(let [file (File/createTempFile "func-a-" ".tron")]
(cio/copy body file)
(try
(let [{:keys [sha type ]} (common/sha-for-file file)
thing (jarjar/build-router file {})
swagger (fu/keywordize-keys (.swagger thing))
host (.host thing)
basePath (.basePath thing)
]
(.endLife thing)
(if (and type sha)
(let [dest-file (fu/new-file
(common/calc-storage-directory opts)
(str (System/currentTimeMillis)
"-"
(fu/clean-sha (URLEncoder/encode sha)) ".funcbundle"))]
(when (no-file-with-same-sha sha state)
(cio/copy file dest-file))
(.delete file)
(swap! bundles assoc sha {:file dest-file :swagger swagger})
{:status 200
:body {:accepted true
:type type
:host host
:route basePath
:swagger swagger
:sha sha}})
(do
(info (str "Failed to upload Func Bundle... failed the type and file-info test. Type "
type))
(info (str "The most likely reason is a missing or malformed funcatron.yaml file"))
{:status 400
:body {:accepted false
:error "Could not determine the file type"}})))
(catch Exception e (do
(error e "Failed up upload JAR")
{:status 400
:body {:accepted false
:error (.toString e)}})))
)
{:status 400
:body {:accepted false
:error "Must post a Func bundle file"}}
)
)
(defn- enable-func
"Enable a Func bundle"
[{:keys [json-params]} {:keys [::bundles ::route-map] :as state}]
(let [json-params (fu/keywordize-keys json-params)
{:keys [sha props]} json-params]
(if (not (and json-params sha))
{:status 400
:body {:success false :error "Request must be JSON and include the 'sha' of the Func bundle to enable"}}
(let [{{:keys [host basePath]} :swagger :as bundle} (get @bundles sha)]
(if (not bundle)
{:status 404
:body {:success false :error (str "Could not find Func bundle with SHA: " sha)}}
(do
(add-to-route-map host basePath sha props route-map state)
{:status 200
:body {:success true :msg (str "Deployed Func bundle host: " host " basePath " basePath " sha " sha)}})
))
))
)
(defn- disable-func
"Disable a Func bundle"
[{:keys [json-params]} {:keys [::bundles ::route-map] :as state}]
(let [json-params (fu/keywordize-keys json-params)
{:keys [sha]} json-params]
(if (not (and json-params sha))
{:status 400
:body {:success false :error "Request must be JSON and include the 'sha' of the Func bundle to disable"}}
(let [{{:keys [host basePath]} :swagger :as bundle} (get @bundles sha)]
(if (not bundle)
{:status 404
:body {:success false :error (str "Could not find Func bundle with SHA: " sha)}}
(do
(remove-from-route-map host basePath sha route-map state)
{:status 200
:body {:success true :msg (str "Deployed Func bundle host: " host " basePath " basePath " sha " sha)}})
)))))
(defn- bundles-from-state
"Pass in the state object and get a list of func bundles"
[{:keys [::bundles]}]
(map (fn [[k {{:keys [host basePath]} :swagger}]]
{:sha k
:host host
:path basePath})
@bundles))
(defn- get-known-funcs
"Return all the known func bundles"
[_ state]
{:status 200
:body {:func-bundles (bundles-from-state state)}})
(defn- get-stats
"Return statistics on activity"
[_ {:keys [::network ::route-map]}]
{:status 200
:body {:network @network
:route-map @route-map}
})
(defn- get-routes
"Return current routes"
[_ {:keys [ ::route-map]}]
{:status 200
:body @route-map
})
(defn- return-sha
"Get the Func bundle with the sha"
[req {:keys [::bundles]}]
(let [sha (-> req :params vals first)]
(if-let [{:keys [file]} (get @bundles sha)]
{:status 200
:body (clojure.java.io/input-stream file)}
{:status 404
:body (str "No func bundle with sha " sha " found")}
)
)
)
(defn tron-routes
"Routes for Tron"
[state]
(-> (routes
(POST "/api/v1/enable" req (enable-func req state))
(POST "/api/v1/disable" req (disable-func req state))
(GET "/api/v1/stats" req (get-stats req state))
(GET "/api/v1/routes" req (get-routes req state))
(GET "/api/v1/known_funcs" req (get-known-funcs req state))
(GET "/api/v1/bundle/:sha" req (return-sha req state))
(POST "/api/v1/add_func"
req (upload-func-bundle req state)))
(wrap-json-response :pretty true :escape-non-ascii true)
rm-json/wrap-json-params
))
(defmulti dispatch-tron-message
"Dispatch the incoming message"
(fn [msg & _] (-> msg :action))
)
(defmethod dispatch-tron-message "heartbeat"
[{:keys [from] :as dog} _ {:keys [::network ::queue ::opts] :as state}]
(trace (str "Heartbeat from " from))
(clean-network state)
(let [rn @network]
(when (not (get-in rn [from :type]))
(.sendMessage
^MessageBroker queue
from
{:content-type "application/json"}
{:action "resend-awake"
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:at (System/currentTimeMillis)
})
))
(swap! network assoc-in [from :last-seen] (System/currentTimeMillis))
(send-host-info from state))
(defn- send-func-bundles
"Send a list of the Func bundles to the Runner as well
as the host and port for this instance"
[destination {:keys [::queue ::opts] :as state}]
(.sendMessage
^MessageBroker queue
destination
{:content-type "application/json"}
{:action "all-bundles"
:version (:version fu/version-info)
:tron-host (fu/compute-host-and-port opts)
:msg-id (fu/random-uuid)
:at (System/currentTimeMillis)
:bundles (bundles-from-state state)
}))
(defmethod dispatch-tron-message "awake"
[{:keys [from type host_info] :as msg} _ {:keys [::network ::route-map] :as state}]
(info (str "awake from " msg))
(clean-network state)
(swap! network assoc from
(merge
msg
{:last-seen (System/currentTimeMillis)}))
(send-host-info from state)
(cond
(= "frontend" type)
(do
(send-route-map from state)
(remove-other-instances-of-this-frontend msg state)
(when-let [{:keys [host port]} host_info]
(when (and (not-empty host) (not-empty port))
(info (str "Frontend at http://" host ":" port))))
)
(= "runner" type)
(do
(send-func-bundles from state)
(let [routes @route-map]
(doseq [{:keys [host path sha props]} routes]
(alter-listening host path sha props from state "enable")))
)))
(defmethod dispatch-tron-message "died"
[{:keys [from]} _ {:keys [::network]}]
(info (str "Got 'died' message from " from))
(swap! network dissoc from)
)
(defn- handle-tron-messages
"Handle messages sent to the tron queue"
[state ^MessageBroker$ReceivedMessage msg]
(fu/run-in-pool
(fn []
(let [body (.body msg)
body (fu/keywordize-keys body)
at (:at body)]
deal with messages less than 30 minutes old
(when (> at (- (System/currentTimeMillis) (* 1000 15 30)))
(try
(trace (str "Got message. Action " (:action body) " from " (:from body)))
(dispatch-tron-message body msg state)
(catch Exception e (error e (str "Failed to dispatch message: " body)))))))))
(defn- build-handler-func
[state]
(let [ver (atom file-version)
the-func (atom (tron-routes state))]
(fn [req]
(when (not= @ver file-version)
(reset! ver file-version)
(reset! the-func (tron-routes state)))
(try
(@the-func req)
(catch Exception e
(do
(error e "Why did this fail?")
(throw e))))
)))
(defn ^Lifecycle build-tron
"Builds a Tron instance as a Lifecycle"
[^MessageBroker queue opts]
(let [bundles (atom {})
route-map (atom [])
network (atom {})
shutdown-http-server (atom nil)
this (atom nil)
state {::queue queue
::bundles bundles
::network network
::opts opts
::this this
::shutdown-http-server shutdown-http-server
::route-map route-map}
]
(add-watch route-map state routes-changed)
(let [ret (reify Lifecycle
(startLife [_]
(info (str "Starting Tron lifecycle"))
(info (str "Loaded bundles... " (count @bundles)))
(reset! route-map (try-to-load-route-map opts @bundles))
(let [{:keys [host port]} (fu/compute-host-and-port opts)]
(info (str "Tron running at host " host " and port " port))
(info (str "Upload a Func Bundle: wget -q -O - --post-file=THE_UBERJAR http://" host ":" port "/api/v1/add_func\n"))
(info (str "List known Func Bundles: curl -v http://"
host
":"
port
"/api/v1/known_funcs"))
(info (str "Enable a Func Bundle: curl -v -H \"Content-Type: application/json\" -d '{\"sha\":\"THE-SHA-HERE\", \"props\": {\"key\": \"value\"}}' -X POST http://"
host
":"
port
"/api/v1/enable"))
)
(reset! shutdown-http-server (fu/start-http-server opts (build-handler-func state)))
(shared-b/listen-to-queue
queue
(common/tron-queue)
(partial handle-tron-messages state))
)
(endLife [_]
(info (str "Ending Tron Lifecycle"))
(shared-b/close-all-listeners queue)
(.close queue)
(@shutdown-http-server))
(allInfo [_] {::message-queue queue
::func-bundles @bundles
::routes @route-map
::this @this
::network @network})
)]
(reset! this ret)
ret
)))
(defn ^Lifecycle build-tron-from-opts
"Builds the runner from options... and if none are passed in, use global options"
([] (build-tron-from-opts @opts/command-line-options))
([opts]
'[funcatron.tron.brokers.rabbitmq]
'[funcatron.tron.brokers.inmemory]
'[funcatron.tron.store.zookeeper]
'[funcatron.tron.substrate.mesos-substrate])
(let [queue (shared-b/wire-up-queue opts)]
(build-tron queue opts)))) |
5eec963c8f1d53fe580ce319cffb950312938a3f55bb2a0476aee5df1b815d9e | arcadia-unity/catcon | pprint_base.clj | pprint_base.clj -- part of the pretty printer for Clojure
Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
Author :
April 3 , 2009
;; This module implements the generic pretty print functions and special variables
(in-ns 'clojure.pprint)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variables that control the pretty printer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; *print-length*, *print-level* and *print-dup* are defined in clojure.core
;;; TODO: use *print-dup* here (or is it supplanted by other variables?)
;;; TODO: make dispatch items like "(let..." get counted in *print-length*
;;; constructs
(def ^:dynamic
^{:doc "Bind to true if you want write to use pretty printing", :added "1.2"}
*print-pretty* true)
(defonce ^:dynamic ; If folks have added stuff here, don't overwrite
^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch
to modify.",
:added "1.2"}
*print-pprint-dispatch* nil)
(def ^:dynamic
^{:doc "Pretty printing will try to avoid anything going beyond this column.
Set it to nil to have pprint let the line be arbitrarily long. This will ignore all
non-mandatory newlines.",
:added "1.2"}
*print-right-margin* 72)
(def ^:dynamic
^{:doc "The column at which to enter miser style. Depending on the dispatch table,
miser style add newlines in more places to try to keep lines short allowing for further
levels of nesting.",
:added "1.2"}
*print-miser-width* 40)
TODO implement output limiting
(def ^:dynamic
^{:private true,
:doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"}
*print-lines* nil)
;;; TODO: implement circle and shared
(def ^:dynamic
^{:private true,
:doc "Mark circular structures (N.B. This is not yet used)"}
*print-circle* nil)
;;; TODO: should we just use *print-dup* here?
(def ^:dynamic
^{:private true,
:doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"}
*print-shared* nil)
(def ^:dynamic
^{:doc "Don't print namespaces with symbols. This is particularly useful when
pretty printing the results of macro expansions"
:added "1.2"}
*print-suppress-namespaces* nil)
;;; TODO: support print-base and print-radix in cl-format
;;; TODO: support print-base and print-radix in rationals
(def ^:dynamic
^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8,
or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the
radix specifier is in the form #XXr where XX is the decimal value of *print-base* "
:added "1.2"}
*print-radix* nil)
(def ^:dynamic
^{:doc "The base to use for printing integers and rationals."
:added "1.2"}
*print-base* 10)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Internal variables that keep track of where we are in the
;; structure
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:dynamic ^{ :private true } *current-level* 0)
(def ^:dynamic ^{ :private true } *current-length* nil)
;; TODO: add variables for length, lines.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support for the write function
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare format-simple-number)
(def ^{:private true} orig-pr pr)
(defn- pr-with-base [x]
(if-let [s (format-simple-number x)]
(print s)
(orig-pr x)))
(def ^{:private true} write-option-table
{;:array *print-array*
:base 'clojure.pprint/*print-base*,
;;:case *print-case*,
:circle 'clojure.pprint/*print-circle*,
;;:escape *print-escape*,
: * print - gensym * ,
:length 'clojure.core/*print-length*,
:level 'clojure.core/*print-level*,
:lines 'clojure.pprint/*print-lines*,
:miser-width 'clojure.pprint/*print-miser-width*,
:dispatch 'clojure.pprint/*print-pprint-dispatch*,
:pretty 'clojure.pprint/*print-pretty*,
:radix 'clojure.pprint/*print-radix*,
:readably 'clojure.core/*print-readably*,
:right-margin 'clojure.pprint/*print-right-margin*,
:suppress-namespaces 'clojure.pprint/*print-suppress-namespaces*})
(defmacro ^{:private true} binding-map [amap & body]
(let []
`(do
(. clojure.lang.Var (pushThreadBindings ~amap))
(try
~@body
(finally
(. clojure.lang.Var (popThreadBindings)))))))
(defn- table-ize [t m]
(apply hash-map (mapcat
#(when-let [v (get t (key %))] [(find-var v) (val %)])
m)))
(defn- pretty-writer?
"Return true iff x is a PrettyWriter"
[x] (and (instance? clojure.lang.IDeref x) (:pretty-writer @@x)))
(defn- make-pretty-writer
"Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width"
[base-writer right-margin miser-width]
(pretty-writer base-writer right-margin miser-width))
(defmacro ^{:private true} with-pretty-writer [base-writer & body]
`(let [base-writer# ~base-writer
new-writer# (not (pretty-writer? base-writer#))]
(binding [*out* (if new-writer#
(make-pretty-writer base-writer# *print-right-margin* *print-miser-width*)
base-writer#)]
~@body
(.ppflush *out*))))
;;;TODO: if pretty print is not set, don't use pr but rather something that respects *print-base*, etc.
(defn write-out
"Write an object to *out* subject to the current bindings of the printer control
variables. Use the kw-args argument to override individual variables for this call (and
any recursive calls).
*out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility
of the caller.
This method is primarily intended for use by pretty print dispatch functions that
already know that the pretty printer will have set up their environment appropriately.
Normal library clients should use the standard \"write\" interface. "
{:added "1.2"}
[object]
(let [length-reached (and
*current-length*
*print-length*
(>= *current-length* *print-length*))]
(if-not *print-pretty*
(pr object)
(if length-reached
(print "...")
(do
(if *current-length* (set! *current-length* (inc *current-length*)))
(*print-pprint-dispatch* object))))
length-reached))
(defn write
"Write an object subject to the current bindings of the printer control variables.
Use the kw-args argument to override individual variables for this call (and any
recursive calls). Returns the string result if :stream is nil or nil otherwise.
The following keyword arguments can be passed with values:
Keyword Meaning Default value
:stream Writer for output or nil true (indicates *out*)
:base Base to use for writing rationals Current value of *print-base*
:circle* If true, mark circular structures Current value of *print-circle*
:length Maximum elements to show in sublists Current value of *print-length*
:level Maximum depth Current value of *print-level*
:lines* Maximum lines of output Current value of *print-lines*
:miser-width Width to enter miser mode Current value of *print-miser-width*
:dispatch The pretty print dispatch function Current value of *print-pprint-dispatch*
:pretty If true, do pretty printing Current value of *print-pretty*
:radix If true, prepend a radix specifier Current value of *print-radix*
:readably* If true, print readably Current value of *print-readably*
:right-margin The column for the right margin Current value of *print-right-margin*
:suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces*
* = not yet supported
"
{:added "1.2"}
[object & kw-args]
(let [options (merge {:stream true} (apply hash-map kw-args))]
(binding-map (table-ize write-option-table options)
(binding-map (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})
(let [optval (if (contains? options :stream)
(:stream options)
true)
base-writer (condp = optval
java.io . .
true *out*
optval)]
(if *print-pretty*
(with-pretty-writer base-writer
(write-out object))
(binding [*out* base-writer]
(pr object)))
(if (nil? optval)
toString java.io .
(defn pprint
"Pretty print object to the optional output writer. If the writer is not provided,
print the object to the currently bound value of *out*."
{:added "1.2"}
([object] (pprint object *out*))
([object writer]
(with-pretty-writer writer
(binding [*print-pretty* true]
(binding-map (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})
(write-out object)))
(if (not (= 0 (get-column *out*)))
(prn)))))
(defmacro pp
"A convenience macro that pretty prints the last thing output. This is
exactly equivalent to (pprint *1)."
{:added "1.2"}
[] `(pprint *1))
(defn set-pprint-dispatch
"Set the pretty print dispatch function to a function matching (fn [obj] ...)
where obj is the object to pretty print. That function will be called with *out* set
to a pretty printing writer to which it should do its printing.
For example functions, see simple-dispatch and code-dispatch in
clojure.pprint.dispatch.clj."
{:added "1.2"}
[function]
(let [old-meta (meta #'*print-pprint-dispatch*)]
(alter-var-root #'*print-pprint-dispatch* (constantly function))
(alter-meta! #'*print-pprint-dispatch* (constantly old-meta)))
nil)
(defmacro with-pprint-dispatch
"Execute body with the pretty print dispatch function bound to function."
{:added "1.2"}
[function & body]
`(binding [*print-pprint-dispatch* ~function]
~@body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support for the functional interface to the pretty printer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- parse-lb-options [opts body]
(loop [body body
acc []]
(if (opts (first body))
(recur (drop 2 body) (concat acc (take 2 body)))
[(apply hash-map acc) body])))
(defn- check-enumerated-arg [arg choices]
(if-not (choices arg)
(throw
IllegalArgumentException
TODO clean up choices string
(str "Bad argument: " arg ". It must be one of " choices)))))
(defn- level-exceeded []
(and *print-level* (>= *current-level* *print-level*)))
(defmacro pprint-logical-block
"Execute the body as a pretty printing logical block with output to *out* which
must be a pretty printing writer. When used from pprint or cl-format, this can be
assumed.
This function is intended for use when writing custom dispatch functions.
Before the body, the caller can optionally specify options: :prefix, :per-line-prefix,
and :suffix."
{:added "1.2", :arglists '[[options* body]]}
[& args]
(let [[options body] (parse-lb-options #{:prefix :per-line-prefix :suffix} args)]
`(do (if (#'clojure.pprint/level-exceeded)
(.Write ^System.IO.TextWriter *out* "#")
(do
(push-thread-bindings {#'clojure.pprint/*current-level*
(inc (var-get #'clojure.pprint/*current-level*))
#'clojure.pprint/*current-length* 0})
(try
(#'clojure.pprint/start-block *out*
~(:prefix options) ~(:per-line-prefix options) ~(:suffix options))
~@body
(#'clojure.pprint/end-block *out*)
(finally
(pop-thread-bindings)))))
nil)))
(defn pprint-newline
"Print a conditional newline to a pretty printing stream. kind specifies if the
newline is :linear, :miser, :fill, or :mandatory.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer."
{:added "1.2"}
[kind]
(check-enumerated-arg kind #{:linear :miser :fill :mandatory})
(nl *out* kind))
(defn pprint-indent
"Create an indent at this point in the pretty printing stream. This defines how
following lines are indented. relative-to can be either :block or :current depending
whether the indent should be computed relative to the start of the logical block or
the current column position. n is an offset.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer."
{:added "1.2"}
[relative-to n]
(check-enumerated-arg relative-to #{:block :current})
(indent *out* relative-to n))
TODO a real implementation for pprint - tab
(defn pprint-tab
"Tab at this point in the pretty printing stream. kind specifies whether the tab
is :line, :section, :line-relative, or :section-relative.
Colnum and colinc specify the target column and the increment to move the target
forward if the output is already past the original target.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer.
THIS FUNCTION IS NOT YET IMPLEMENTED."
{:added "1.2"}
[kind colnum colinc]
(check-enumerated-arg kind #{:line :section :line-relative :section-relative})
(throw (NotImplementedException. "pprint-tab is not yet implemented"))) ;;; UnsupportedOperationException
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Helpers for dispatch function writing
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pll-mod-body [var-sym body]
(letfn [(inner [form]
(if (seq? form)
(let [form (macroexpand form)]
(condp = (first form)
'loop* form
'recur (concat `(recur (inc ~var-sym)) (rest form))
(walk inner identity form)))
form))]
(walk inner identity body)))
(defmacro print-length-loop
"A version of loop that iterates at most *print-length* times. This is designed
for use in pretty-printer dispatch functions."
{:added "1.3"}
[bindings & body]
(let [count-var (gensym "length-count")
mod-body (pll-mod-body count-var body)]
`(loop ~(apply vector count-var 0 bindings)
(if (or (not *print-length*) (< ~count-var *print-length*))
(do ~@mod-body)
.write ^java.io . Writer
nil
| null | https://raw.githubusercontent.com/arcadia-unity/catcon/6c69f424d3c14639ff11a3ea7d9da6aa81328f8a/Arcadia/Internal/clojure/pprint/pprint_base.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.
This module implements the generic pretty print functions and special variables
Variables that control the pretty printer
*print-length*, *print-level* and *print-dup* are defined in clojure.core
TODO: use *print-dup* here (or is it supplanted by other variables?)
TODO: make dispatch items like "(let..." get counted in *print-length*
constructs
If folks have added stuff here, don't overwrite
TODO: implement circle and shared
TODO: should we just use *print-dup* here?
TODO: support print-base and print-radix in cl-format
TODO: support print-base and print-radix in rationals
Internal variables that keep track of where we are in the
structure
TODO: add variables for length, lines.
Support for the write function
:array *print-array*
:case *print-case*,
:escape *print-escape*,
TODO: if pretty print is not set, don't use pr but rather something that respects *print-base*, etc.
Support for the functional interface to the pretty printer
UnsupportedOperationException
Helpers for dispatch function writing
| pprint_base.clj -- part of the pretty printer for Clojure
Copyright ( c ) . All rights reserved .
Author :
April 3 , 2009
(in-ns 'clojure.pprint)
(def ^:dynamic
^{:doc "Bind to true if you want write to use pretty printing", :added "1.2"}
*print-pretty* true)
^{:doc "The pretty print dispatch function. Use with-pprint-dispatch or set-pprint-dispatch
to modify.",
:added "1.2"}
*print-pprint-dispatch* nil)
(def ^:dynamic
^{:doc "Pretty printing will try to avoid anything going beyond this column.
Set it to nil to have pprint let the line be arbitrarily long. This will ignore all
non-mandatory newlines.",
:added "1.2"}
*print-right-margin* 72)
(def ^:dynamic
^{:doc "The column at which to enter miser style. Depending on the dispatch table,
miser style add newlines in more places to try to keep lines short allowing for further
levels of nesting.",
:added "1.2"}
*print-miser-width* 40)
TODO implement output limiting
(def ^:dynamic
^{:private true,
:doc "Maximum number of lines to print in a pretty print instance (N.B. This is not yet used)"}
*print-lines* nil)
(def ^:dynamic
^{:private true,
:doc "Mark circular structures (N.B. This is not yet used)"}
*print-circle* nil)
(def ^:dynamic
^{:private true,
:doc "Mark repeated structures rather than repeat them (N.B. This is not yet used)"}
*print-shared* nil)
(def ^:dynamic
^{:doc "Don't print namespaces with symbols. This is particularly useful when
pretty printing the results of macro expansions"
:added "1.2"}
*print-suppress-namespaces* nil)
(def ^:dynamic
^{:doc "Print a radix specifier in front of integers and rationals. If *print-base* is 2, 8,
or 16, then the radix specifier used is #b, #o, or #x, respectively. Otherwise the
radix specifier is in the form #XXr where XX is the decimal value of *print-base* "
:added "1.2"}
*print-radix* nil)
(def ^:dynamic
^{:doc "The base to use for printing integers and rationals."
:added "1.2"}
*print-base* 10)
(def ^:dynamic ^{ :private true } *current-level* 0)
(def ^:dynamic ^{ :private true } *current-length* nil)
(declare format-simple-number)
(def ^{:private true} orig-pr pr)
(defn- pr-with-base [x]
(if-let [s (format-simple-number x)]
(print s)
(orig-pr x)))
(def ^{:private true} write-option-table
:base 'clojure.pprint/*print-base*,
:circle 'clojure.pprint/*print-circle*,
: * print - gensym * ,
:length 'clojure.core/*print-length*,
:level 'clojure.core/*print-level*,
:lines 'clojure.pprint/*print-lines*,
:miser-width 'clojure.pprint/*print-miser-width*,
:dispatch 'clojure.pprint/*print-pprint-dispatch*,
:pretty 'clojure.pprint/*print-pretty*,
:radix 'clojure.pprint/*print-radix*,
:readably 'clojure.core/*print-readably*,
:right-margin 'clojure.pprint/*print-right-margin*,
:suppress-namespaces 'clojure.pprint/*print-suppress-namespaces*})
(defmacro ^{:private true} binding-map [amap & body]
(let []
`(do
(. clojure.lang.Var (pushThreadBindings ~amap))
(try
~@body
(finally
(. clojure.lang.Var (popThreadBindings)))))))
(defn- table-ize [t m]
(apply hash-map (mapcat
#(when-let [v (get t (key %))] [(find-var v) (val %)])
m)))
(defn- pretty-writer?
"Return true iff x is a PrettyWriter"
[x] (and (instance? clojure.lang.IDeref x) (:pretty-writer @@x)))
(defn- make-pretty-writer
"Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width"
[base-writer right-margin miser-width]
(pretty-writer base-writer right-margin miser-width))
(defmacro ^{:private true} with-pretty-writer [base-writer & body]
`(let [base-writer# ~base-writer
new-writer# (not (pretty-writer? base-writer#))]
(binding [*out* (if new-writer#
(make-pretty-writer base-writer# *print-right-margin* *print-miser-width*)
base-writer#)]
~@body
(.ppflush *out*))))
(defn write-out
"Write an object to *out* subject to the current bindings of the printer control
variables. Use the kw-args argument to override individual variables for this call (and
any recursive calls).
*out* must be a PrettyWriter if pretty printing is enabled. This is the responsibility
of the caller.
This method is primarily intended for use by pretty print dispatch functions that
already know that the pretty printer will have set up their environment appropriately.
Normal library clients should use the standard \"write\" interface. "
{:added "1.2"}
[object]
(let [length-reached (and
*current-length*
*print-length*
(>= *current-length* *print-length*))]
(if-not *print-pretty*
(pr object)
(if length-reached
(print "...")
(do
(if *current-length* (set! *current-length* (inc *current-length*)))
(*print-pprint-dispatch* object))))
length-reached))
(defn write
"Write an object subject to the current bindings of the printer control variables.
Use the kw-args argument to override individual variables for this call (and any
recursive calls). Returns the string result if :stream is nil or nil otherwise.
The following keyword arguments can be passed with values:
Keyword Meaning Default value
:stream Writer for output or nil true (indicates *out*)
:base Base to use for writing rationals Current value of *print-base*
:circle* If true, mark circular structures Current value of *print-circle*
:length Maximum elements to show in sublists Current value of *print-length*
:level Maximum depth Current value of *print-level*
:lines* Maximum lines of output Current value of *print-lines*
:miser-width Width to enter miser mode Current value of *print-miser-width*
:dispatch The pretty print dispatch function Current value of *print-pprint-dispatch*
:pretty If true, do pretty printing Current value of *print-pretty*
:radix If true, prepend a radix specifier Current value of *print-radix*
:readably* If true, print readably Current value of *print-readably*
:right-margin The column for the right margin Current value of *print-right-margin*
:suppress-namespaces If true, no namespaces in symbols Current value of *print-suppress-namespaces*
* = not yet supported
"
{:added "1.2"}
[object & kw-args]
(let [options (merge {:stream true} (apply hash-map kw-args))]
(binding-map (table-ize write-option-table options)
(binding-map (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})
(let [optval (if (contains? options :stream)
(:stream options)
true)
base-writer (condp = optval
java.io . .
true *out*
optval)]
(if *print-pretty*
(with-pretty-writer base-writer
(write-out object))
(binding [*out* base-writer]
(pr object)))
(if (nil? optval)
toString java.io .
(defn pprint
"Pretty print object to the optional output writer. If the writer is not provided,
print the object to the currently bound value of *out*."
{:added "1.2"}
([object] (pprint object *out*))
([object writer]
(with-pretty-writer writer
(binding [*print-pretty* true]
(binding-map (if (or (not (= *print-base* 10)) *print-radix*) {#'pr pr-with-base} {})
(write-out object)))
(if (not (= 0 (get-column *out*)))
(prn)))))
(defmacro pp
"A convenience macro that pretty prints the last thing output. This is
exactly equivalent to (pprint *1)."
{:added "1.2"}
[] `(pprint *1))
(defn set-pprint-dispatch
"Set the pretty print dispatch function to a function matching (fn [obj] ...)
where obj is the object to pretty print. That function will be called with *out* set
to a pretty printing writer to which it should do its printing.
For example functions, see simple-dispatch and code-dispatch in
clojure.pprint.dispatch.clj."
{:added "1.2"}
[function]
(let [old-meta (meta #'*print-pprint-dispatch*)]
(alter-var-root #'*print-pprint-dispatch* (constantly function))
(alter-meta! #'*print-pprint-dispatch* (constantly old-meta)))
nil)
(defmacro with-pprint-dispatch
"Execute body with the pretty print dispatch function bound to function."
{:added "1.2"}
[function & body]
`(binding [*print-pprint-dispatch* ~function]
~@body))
(defn- parse-lb-options [opts body]
(loop [body body
acc []]
(if (opts (first body))
(recur (drop 2 body) (concat acc (take 2 body)))
[(apply hash-map acc) body])))
(defn- check-enumerated-arg [arg choices]
(if-not (choices arg)
(throw
IllegalArgumentException
TODO clean up choices string
(str "Bad argument: " arg ". It must be one of " choices)))))
(defn- level-exceeded []
(and *print-level* (>= *current-level* *print-level*)))
(defmacro pprint-logical-block
"Execute the body as a pretty printing logical block with output to *out* which
must be a pretty printing writer. When used from pprint or cl-format, this can be
assumed.
This function is intended for use when writing custom dispatch functions.
Before the body, the caller can optionally specify options: :prefix, :per-line-prefix,
and :suffix."
{:added "1.2", :arglists '[[options* body]]}
[& args]
(let [[options body] (parse-lb-options #{:prefix :per-line-prefix :suffix} args)]
`(do (if (#'clojure.pprint/level-exceeded)
(.Write ^System.IO.TextWriter *out* "#")
(do
(push-thread-bindings {#'clojure.pprint/*current-level*
(inc (var-get #'clojure.pprint/*current-level*))
#'clojure.pprint/*current-length* 0})
(try
(#'clojure.pprint/start-block *out*
~(:prefix options) ~(:per-line-prefix options) ~(:suffix options))
~@body
(#'clojure.pprint/end-block *out*)
(finally
(pop-thread-bindings)))))
nil)))
(defn pprint-newline
"Print a conditional newline to a pretty printing stream. kind specifies if the
newline is :linear, :miser, :fill, or :mandatory.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer."
{:added "1.2"}
[kind]
(check-enumerated-arg kind #{:linear :miser :fill :mandatory})
(nl *out* kind))
(defn pprint-indent
"Create an indent at this point in the pretty printing stream. This defines how
following lines are indented. relative-to can be either :block or :current depending
whether the indent should be computed relative to the start of the logical block or
the current column position. n is an offset.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer."
{:added "1.2"}
[relative-to n]
(check-enumerated-arg relative-to #{:block :current})
(indent *out* relative-to n))
TODO a real implementation for pprint - tab
(defn pprint-tab
"Tab at this point in the pretty printing stream. kind specifies whether the tab
is :line, :section, :line-relative, or :section-relative.
Colnum and colinc specify the target column and the increment to move the target
forward if the output is already past the original target.
This function is intended for use when writing custom dispatch functions.
Output is sent to *out* which must be a pretty printing writer.
THIS FUNCTION IS NOT YET IMPLEMENTED."
{:added "1.2"}
[kind colnum colinc]
(check-enumerated-arg kind #{:line :section :line-relative :section-relative})
(defn- pll-mod-body [var-sym body]
(letfn [(inner [form]
(if (seq? form)
(let [form (macroexpand form)]
(condp = (first form)
'loop* form
'recur (concat `(recur (inc ~var-sym)) (rest form))
(walk inner identity form)))
form))]
(walk inner identity body)))
(defmacro print-length-loop
"A version of loop that iterates at most *print-length* times. This is designed
for use in pretty-printer dispatch functions."
{:added "1.3"}
[bindings & body]
(let [count-var (gensym "length-count")
mod-body (pll-mod-body count-var body)]
`(loop ~(apply vector count-var 0 bindings)
(if (or (not *print-length*) (< ~count-var *print-length*))
(do ~@mod-body)
.write ^java.io . Writer
nil
|
8851d78e54564982051abf82aea728b47e4cb14335068a4976e928d6b39729c0 | mbj/stratosphere | Group.hs | module Stratosphere.Synthetics.Group (
Group(..), mkGroup
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Group
= Group {name :: (Value Prelude.Text),
resourceArns :: (Prelude.Maybe (ValueList Prelude.Text)),
tags :: (Prelude.Maybe [Tag])}
mkGroup :: Value Prelude.Text -> Group
mkGroup name
= Group
{name = name, resourceArns = Prelude.Nothing,
tags = Prelude.Nothing}
instance ToResourceProperties Group where
toResourceProperties Group {..}
= ResourceProperties
{awsType = "AWS::Synthetics::Group", supportsTags = Prelude.True,
properties = Prelude.fromList
((Prelude.<>)
["Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "ResourceArns" Prelude.<$> resourceArns,
(JSON..=) "Tags" Prelude.<$> tags]))}
instance JSON.ToJSON Group where
toJSON Group {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "ResourceArns" Prelude.<$> resourceArns,
(JSON..=) "Tags" Prelude.<$> tags])))
instance Property "Name" Group where
type PropertyType "Name" Group = Value Prelude.Text
set newValue Group {..} = Group {name = newValue, ..}
instance Property "ResourceArns" Group where
type PropertyType "ResourceArns" Group = ValueList Prelude.Text
set newValue Group {..}
= Group {resourceArns = Prelude.pure newValue, ..}
instance Property "Tags" Group where
type PropertyType "Tags" Group = [Tag]
set newValue Group {..} = Group {tags = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/synthetics/gen/Stratosphere/Synthetics/Group.hs | haskell | module Stratosphere.Synthetics.Group (
Group(..), mkGroup
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Group
= Group {name :: (Value Prelude.Text),
resourceArns :: (Prelude.Maybe (ValueList Prelude.Text)),
tags :: (Prelude.Maybe [Tag])}
mkGroup :: Value Prelude.Text -> Group
mkGroup name
= Group
{name = name, resourceArns = Prelude.Nothing,
tags = Prelude.Nothing}
instance ToResourceProperties Group where
toResourceProperties Group {..}
= ResourceProperties
{awsType = "AWS::Synthetics::Group", supportsTags = Prelude.True,
properties = Prelude.fromList
((Prelude.<>)
["Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "ResourceArns" Prelude.<$> resourceArns,
(JSON..=) "Tags" Prelude.<$> tags]))}
instance JSON.ToJSON Group where
toJSON Group {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "ResourceArns" Prelude.<$> resourceArns,
(JSON..=) "Tags" Prelude.<$> tags])))
instance Property "Name" Group where
type PropertyType "Name" Group = Value Prelude.Text
set newValue Group {..} = Group {name = newValue, ..}
instance Property "ResourceArns" Group where
type PropertyType "ResourceArns" Group = ValueList Prelude.Text
set newValue Group {..}
= Group {resourceArns = Prelude.pure newValue, ..}
instance Property "Tags" Group where
type PropertyType "Tags" Group = [Tag]
set newValue Group {..} = Group {tags = Prelude.pure newValue, ..} | |
852e9fbaf006afea11d262ee80cff0459b1322d0713a58e6265af9ade1014b13 | zadean/xqerl | prod_UnaryLookup_SUITE.erl | -module('prod_UnaryLookup_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['UnaryLookup-001'/1]).
-export(['UnaryLookup-002'/1]).
-export(['UnaryLookup-003'/1]).
-export(['UnaryLookup-004'/1]).
-export(['UnaryLookup-005'/1]).
-export(['UnaryLookup-006'/1]).
-export(['UnaryLookup-007'/1]).
-export(['UnaryLookup-008'/1]).
-export(['UnaryLookup-009'/1]).
-export(['UnaryLookup-010'/1]).
-export(['UnaryLookup-011'/1]).
-export(['UnaryLookup-012'/1]).
-export(['UnaryLookup-013'/1]).
-export(['UnaryLookup-014'/1]).
-export(['UnaryLookup-015'/1]).
-export(['UnaryLookup-016'/1]).
-export(['UnaryLookup-017'/1]).
-export(['UnaryLookup-018'/1]).
-export(['UnaryLookup-019'/1]).
-export(['UnaryLookup-020'/1]).
-export(['UnaryLookup-021'/1]).
-export(['UnaryLookup-022'/1]).
-export(['UnaryLookup-023'/1]).
-export(['UnaryLookup-024'/1]).
-export(['UnaryLookup-025'/1]).
-export(['UnaryLookup-040'/1]).
-export(['UnaryLookup-041'/1]).
-export(['UnaryLookup-042'/1]).
-export(['UnaryLookup-043'/1]).
-export(['UnaryLookup-044'/1]).
-export(['UnaryLookup-045'/1]).
-export(['UnaryLookup-046'/1]).
-export(['UnaryLookup-047'/1]).
-export(['UnaryLookup-048'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1}
].
groups() ->
[
{group_0, [parallel], [
'UnaryLookup-001',
'UnaryLookup-002',
'UnaryLookup-003',
'UnaryLookup-004',
'UnaryLookup-005',
'UnaryLookup-006',
'UnaryLookup-007',
'UnaryLookup-008',
'UnaryLookup-009',
'UnaryLookup-010',
'UnaryLookup-011',
'UnaryLookup-012',
'UnaryLookup-013',
'UnaryLookup-014',
'UnaryLookup-015',
'UnaryLookup-016',
'UnaryLookup-017',
'UnaryLookup-018',
'UnaryLookup-019',
'UnaryLookup-020',
'UnaryLookup-021',
'UnaryLookup-022',
'UnaryLookup-023'
]},
{group_1, [parallel], [
'UnaryLookup-024',
'UnaryLookup-025',
'UnaryLookup-040',
'UnaryLookup-041',
'UnaryLookup-042',
'UnaryLookup-043',
'UnaryLookup-044',
'UnaryLookup-045',
'UnaryLookup-046',
'UnaryLookup-047',
'UnaryLookup-048'
]}
].
'UnaryLookup-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[?1 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-001.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "let $i := 1 return (['a', 'b'], ['c', 'd'])[?($i) eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-002.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ? 001 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-003.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ? -1 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-004.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ?0 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-005.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOAY0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOAY0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'], ['e'])[ ?2 eq 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-006.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOAY0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOAY0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?(1 to 2) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-007.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c'], ['b', 'c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $i := (1, 3) return (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?($i) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-008.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['b', 'c', 'd'], ['e', 'f', 'b']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?first = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-009.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $d := current-date() return (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?($d) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-010.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "let $d := function($x) {$x + ?2} return $d(12)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-011.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(1 to 10)[?1 = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-012.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(floor#1, ceiling#1, round#1, abs#1)[?1 = 1]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-013.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?* = 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-014.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c'], ['b', 'c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "([1, [2], [3]], [[2], 2, [4]])[ ?1 = ?2 ]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-015.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "[[2], 2, [4]]") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[contains(?1, ?, '-functions/collation/codepoint')('a')]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-016.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[contains(?1, ?)('a')]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-017.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?1.0 = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-018.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?(1.0) = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-019.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaValidation"}.
'UnaryLookup-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" let $x := (<x>1</x>, <y>2</y>) return\n"
" (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?($x) = 'b']\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-021.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "(['a', 'b', 'c'], ['b', 'c', 'd'])") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "[['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b']]?*[?1 = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-022.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "[['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b']]!?*!?1",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-023.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "'a', 'b', 'e'") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-024'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" let $x := (<x>1</x>, <y>2</y>) return $x / ?1\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-024.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-025'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[exists(?())]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-025.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-040'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{'a':1, 'b':2, 'c':3}, map{'a':2, 'b':3, 'c':4})[?b eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-040.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a':2, 'b':3, 'c':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-041'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?2 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-041.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-042'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?(1 to 2) = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-042.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-043'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{'a-1':1, 'b-1':2, 'c-1':3}, map{'a-1':2, 'b-1':3, 'c-1':4})[?b-1 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-043.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a-1':2, 'b-1':3, 'c-1':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-044'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"(map{'a-1':1, 'b-1':2, 'c-1':3}, map{'a-1':2, 'b-1':3, 'c-1':4})[? (:confusing?:) b-1 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-044.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a-1':2, 'b-1':3, 'c-1':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-045'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?* = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-045.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-046'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[exists(?())]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-046.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-047'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1.1:1, 2.2:2, 3.3:3}, map{1.1:2, 2.2:3, 3.3:4})[?2.2 = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-047.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-048'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1.1:1, 2.2:2, 3.3:3}, map{1.1:2, 2.2:3, 3.3:4})[?(2.2) = 3]?(3.3)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-048.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "4") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null | https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/prod/prod_UnaryLookup_SUITE.erl | erlang | -module('prod_UnaryLookup_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['UnaryLookup-001'/1]).
-export(['UnaryLookup-002'/1]).
-export(['UnaryLookup-003'/1]).
-export(['UnaryLookup-004'/1]).
-export(['UnaryLookup-005'/1]).
-export(['UnaryLookup-006'/1]).
-export(['UnaryLookup-007'/1]).
-export(['UnaryLookup-008'/1]).
-export(['UnaryLookup-009'/1]).
-export(['UnaryLookup-010'/1]).
-export(['UnaryLookup-011'/1]).
-export(['UnaryLookup-012'/1]).
-export(['UnaryLookup-013'/1]).
-export(['UnaryLookup-014'/1]).
-export(['UnaryLookup-015'/1]).
-export(['UnaryLookup-016'/1]).
-export(['UnaryLookup-017'/1]).
-export(['UnaryLookup-018'/1]).
-export(['UnaryLookup-019'/1]).
-export(['UnaryLookup-020'/1]).
-export(['UnaryLookup-021'/1]).
-export(['UnaryLookup-022'/1]).
-export(['UnaryLookup-023'/1]).
-export(['UnaryLookup-024'/1]).
-export(['UnaryLookup-025'/1]).
-export(['UnaryLookup-040'/1]).
-export(['UnaryLookup-041'/1]).
-export(['UnaryLookup-042'/1]).
-export(['UnaryLookup-043'/1]).
-export(['UnaryLookup-044'/1]).
-export(['UnaryLookup-045'/1]).
-export(['UnaryLookup-046'/1]).
-export(['UnaryLookup-047'/1]).
-export(['UnaryLookup-048'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1}
].
groups() ->
[
{group_0, [parallel], [
'UnaryLookup-001',
'UnaryLookup-002',
'UnaryLookup-003',
'UnaryLookup-004',
'UnaryLookup-005',
'UnaryLookup-006',
'UnaryLookup-007',
'UnaryLookup-008',
'UnaryLookup-009',
'UnaryLookup-010',
'UnaryLookup-011',
'UnaryLookup-012',
'UnaryLookup-013',
'UnaryLookup-014',
'UnaryLookup-015',
'UnaryLookup-016',
'UnaryLookup-017',
'UnaryLookup-018',
'UnaryLookup-019',
'UnaryLookup-020',
'UnaryLookup-021',
'UnaryLookup-022',
'UnaryLookup-023'
]},
{group_1, [parallel], [
'UnaryLookup-024',
'UnaryLookup-025',
'UnaryLookup-040',
'UnaryLookup-041',
'UnaryLookup-042',
'UnaryLookup-043',
'UnaryLookup-044',
'UnaryLookup-045',
'UnaryLookup-046',
'UnaryLookup-047',
'UnaryLookup-048'
]}
].
'UnaryLookup-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[?1 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-001.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "let $i := 1 return (['a', 'b'], ['c', 'd'])[?($i) eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-002.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ? 001 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-003.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ? -1 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-004.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'])[ ?0 eq 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-005.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOAY0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOAY0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b'], ['c', 'd'], ['e'])[ ?2 eq 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-006.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOAY0001") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOAY0001 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?(1 to 2) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-007.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c'], ['b', 'c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $i := (1, 3) return (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?($i) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-008.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['b', 'c', 'd'], ['e', 'f', 'b']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?first = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-009.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"let $d := current-date() return (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?($d) = 'b']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-010.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "let $d := function($x) {$x + ?2} return $d(12)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-011.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(1 to 10)[?1 = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-012.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(floor#1, ceiling#1, round#1, abs#1)[?1 = 1]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-013.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[ ?* = 'c']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-014.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c'], ['b', 'c', 'd']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "([1, [2], [3]], [[2], 2, [4]])[ ?1 = ?2 ]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-015.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "[[2], 2, [4]]") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[contains(?1, ?, '-functions/collation/codepoint')('a')]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-016.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[contains(?1, ?)('a')]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-017.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?1.0 = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-018.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?(1.0) = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-019.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaValidation"}.
'UnaryLookup-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" let $x := (<x>1</x>, <y>2</y>) return\n"
" (['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[?($x) = 'b']\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-021.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "(['a', 'b', 'c'], ['b', 'c', 'd'])") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "[['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b']]?*[?1 = 'a']",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-022.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "['a', 'b', 'c']") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "[['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b']]!?*!?1",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-023.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "'a', 'b', 'e'") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-024'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" let $x := (<x>1</x>, <y>2</y>) return $x / ?1\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-024.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-025'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(['a', 'b', 'c'], ['b', 'c', 'd'], ['e', 'f', 'b'])[exists(?())]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-025.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-040'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{'a':1, 'b':2, 'c':3}, map{'a':2, 'b':3, 'c':4})[?b eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-040.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a':2, 'b':3, 'c':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-041'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?2 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-041.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-042'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?(1 to 2) = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-042.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-043'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{'a-1':1, 'b-1':2, 'c-1':3}, map{'a-1':2, 'b-1':3, 'c-1':4})[?b-1 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-043.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a-1':2, 'b-1':3, 'c-1':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-044'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"(map{'a-1':1, 'b-1':2, 'c-1':3}, map{'a-1':2, 'b-1':3, 'c-1':4})[? (:confusing?:) b-1 eq 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-044.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{'a-1':2, 'b-1':3, 'c-1':4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-045'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[?* = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-045.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_deep_eq(Res, "map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4}") of
true -> {comment, "Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-046'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1:1, 2:2, 3:3}, map{1:2, 2:3, 3:4})[exists(?())]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-046.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-047'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1.1:1, 2.2:2, 3.3:3}, map{1.1:2, 2.2:3, 3.3:4})[?2.2 = 3]",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-047.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'UnaryLookup-048'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "(map{1.1:1, 2.2:2, 3.3:3}, map{1.1:2, 2.2:3, 3.3:4})[?(2.2) = 3]?(3.3)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "UnaryLookup-048.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "4") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| |
74c11fdc2383fe693a79b8850c5cd8b3528db90bae16de7f1715799f7b22a12d | janestreet/merlin-jst | parser_raw.mli |
(* The type of tokens. *)
type token =
| WITH
| WHILE_LWT
| WHILE
| WHEN
| VIRTUAL
| VAL
| UNDERSCORE
| UIDENT of (string)
| TYPE
| TRY_LWT
| TRY
| TRUE
| TO
| TILDE
| THEN
| STRUCT
| STRING of (string * Location.t * string option)
| STAR
| SIG
| SEMISEMI
| SEMI
| RPAREN
| REC
| RBRACKET
| RBRACE
| QUOTED_STRING_ITEM of (string * Location.t * string * Location.t * string option)
| QUOTED_STRING_EXPR of (string * Location.t * string * Location.t * string option)
| QUOTE
| QUESTION
| PRIVATE
| PREFIXOP of (string)
| PLUSEQ
| PLUSDOT
| PLUS
| PERCENT
| OR
| OPTLABEL of (string)
| OPEN
| OF
| OBJECT
| NONREC
| NONLOCAL
| NEW
| MUTABLE
| MODULE
| MINUSGREATER
| MINUSDOT
| MINUS
| METHOD
| MATCH_LWT
| MATCH
| LPAREN
| LOCAL
| LIDENT of (string)
| LET_LWT
| LETOP of (string)
| LET
| LESSMINUS
| LESS
| LBRACKETPERCENTPERCENT
| LBRACKETPERCENT
| LBRACKETLESS
| LBRACKETGREATER
| LBRACKETBAR
| LBRACKETATATAT
| LBRACKETATAT
| LBRACKETAT
| LBRACKET
| LBRACELESS
| LBRACE
| LAZY
| LABEL of (string)
| INT of (string * char option)
| INITIALIZER
| INHERIT
| INFIXOP4 of (string)
| INFIXOP3 of (string)
| INFIXOP2 of (string)
| INFIXOP1 of (string)
| INFIXOP0 of (string)
| INCLUDE
| IN
| IF
| HASHOP of (string)
| HASH
| GREATERRBRACKET
| GREATERRBRACE
| GREATERDOT
| GREATER
| GLOBAL
| FUNCTOR
| FUNCTION
| FUN
| FOR_LWT
| FOR
| FLOAT of (string * char option)
| FINALLY_LWT
| FALSE
| EXTERNAL
| EXCEPTION
| EQUAL
| EOL
| EOF
| END
| ELSE
| DOWNTO
| DOTTILDE
| DOTOP of (string)
| DOTLESS
| DOTDOT
| DOT
| DONE
| DOCSTRING of (Docstrings.docstring)
| DO
| CONSTRAINT
| COMMENT of (string * Location.t)
| COMMA
| COLONGREATER
| COLONEQUAL
| COLONCOLON
| COLON
| CLASS
| CHAR of (char)
| BEGIN
| BARRBRACKET
| BARBAR
| BAR
| BANG
| BACKQUOTE
| ASSERT
| AS
| ANDOP of (string)
| AND
| AMPERSAND
| AMPERAMPER
(* This exception is raised by the monolithic API functions. *)
exception Error
(* The monolithic API. *)
val use_file: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.toplevel_phrase list)
val toplevel_phrase: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.toplevel_phrase)
val parse_val_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_pattern: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.pattern)
val parse_mty_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_module_type: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.module_type)
val parse_module_expr: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.module_expr)
val parse_mod_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_mod_ext_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_expression: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.expression)
val parse_core_type: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.core_type)
val parse_constr_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_any_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val interface: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.signature)
val implementation: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.structure)
module MenhirInterpreter : sig
(* The incremental API. *)
include MenhirLib.IncrementalEngine.INCREMENTAL_ENGINE
with type token = token
(* The indexed type of terminal symbols. *)
type _ terminal =
| T_error : unit terminal
| T_WITH : unit terminal
| T_WHILE_LWT : unit terminal
| T_WHILE : unit terminal
| T_WHEN : unit terminal
| T_VIRTUAL : unit terminal
| T_VAL : unit terminal
| T_UNDERSCORE : unit terminal
| T_UIDENT : (string) terminal
| T_TYPE : unit terminal
| T_TRY_LWT : unit terminal
| T_TRY : unit terminal
| T_TRUE : unit terminal
| T_TO : unit terminal
| T_TILDE : unit terminal
| T_THEN : unit terminal
| T_STRUCT : unit terminal
| T_STRING : (string * Location.t * string option) terminal
| T_STAR : unit terminal
| T_SIG : unit terminal
| T_SEMISEMI : unit terminal
| T_SEMI : unit terminal
| T_RPAREN : unit terminal
| T_REC : unit terminal
| T_RBRACKET : unit terminal
| T_RBRACE : unit terminal
| T_QUOTED_STRING_ITEM : (string * Location.t * string * Location.t * string option) terminal
| T_QUOTED_STRING_EXPR : (string * Location.t * string * Location.t * string option) terminal
| T_QUOTE : unit terminal
| T_QUESTION : unit terminal
| T_PRIVATE : unit terminal
| T_PREFIXOP : (string) terminal
| T_PLUSEQ : unit terminal
| T_PLUSDOT : unit terminal
| T_PLUS : unit terminal
| T_PERCENT : unit terminal
| T_OR : unit terminal
| T_OPTLABEL : (string) terminal
| T_OPEN : unit terminal
| T_OF : unit terminal
| T_OBJECT : unit terminal
| T_NONREC : unit terminal
| T_NONLOCAL : unit terminal
| T_NEW : unit terminal
| T_MUTABLE : unit terminal
| T_MODULE : unit terminal
| T_MINUSGREATER : unit terminal
| T_MINUSDOT : unit terminal
| T_MINUS : unit terminal
| T_METHOD : unit terminal
| T_MATCH_LWT : unit terminal
| T_MATCH : unit terminal
| T_LPAREN : unit terminal
| T_LOCAL : unit terminal
| T_LIDENT : (string) terminal
| T_LET_LWT : unit terminal
| T_LETOP : (string) terminal
| T_LET : unit terminal
| T_LESSMINUS : unit terminal
| T_LESS : unit terminal
| T_LBRACKETPERCENTPERCENT : unit terminal
| T_LBRACKETPERCENT : unit terminal
| T_LBRACKETLESS : unit terminal
| T_LBRACKETGREATER : unit terminal
| T_LBRACKETBAR : unit terminal
| T_LBRACKETATATAT : unit terminal
| T_LBRACKETATAT : unit terminal
| T_LBRACKETAT : unit terminal
| T_LBRACKET : unit terminal
| T_LBRACELESS : unit terminal
| T_LBRACE : unit terminal
| T_LAZY : unit terminal
| T_LABEL : (string) terminal
| T_INT : (string * char option) terminal
| T_INITIALIZER : unit terminal
| T_INHERIT : unit terminal
| T_INFIXOP4 : (string) terminal
| T_INFIXOP3 : (string) terminal
| T_INFIXOP2 : (string) terminal
| T_INFIXOP1 : (string) terminal
| T_INFIXOP0 : (string) terminal
| T_INCLUDE : unit terminal
| T_IN : unit terminal
| T_IF : unit terminal
| T_HASHOP : (string) terminal
| T_HASH : unit terminal
| T_GREATERRBRACKET : unit terminal
| T_GREATERRBRACE : unit terminal
| T_GREATERDOT : unit terminal
| T_GREATER : unit terminal
| T_GLOBAL : unit terminal
| T_FUNCTOR : unit terminal
| T_FUNCTION : unit terminal
| T_FUN : unit terminal
| T_FOR_LWT : unit terminal
| T_FOR : unit terminal
| T_FLOAT : (string * char option) terminal
| T_FINALLY_LWT : unit terminal
| T_FALSE : unit terminal
| T_EXTERNAL : unit terminal
| T_EXCEPTION : unit terminal
| T_EQUAL : unit terminal
| T_EOL : unit terminal
| T_EOF : unit terminal
| T_END : unit terminal
| T_ELSE : unit terminal
| T_DOWNTO : unit terminal
| T_DOTTILDE : unit terminal
| T_DOTOP : (string) terminal
| T_DOTLESS : unit terminal
| T_DOTDOT : unit terminal
| T_DOT : unit terminal
| T_DONE : unit terminal
| T_DOCSTRING : (Docstrings.docstring) terminal
| T_DO : unit terminal
| T_CONSTRAINT : unit terminal
| T_COMMENT : (string * Location.t) terminal
| T_COMMA : unit terminal
| T_COLONGREATER : unit terminal
| T_COLONEQUAL : unit terminal
| T_COLONCOLON : unit terminal
| T_COLON : unit terminal
| T_CLASS : unit terminal
| T_CHAR : (char) terminal
| T_BEGIN : unit terminal
| T_BARRBRACKET : unit terminal
| T_BARBAR : unit terminal
| T_BAR : unit terminal
| T_BANG : unit terminal
| T_BACKQUOTE : unit terminal
| T_ASSERT : unit terminal
| T_AS : unit terminal
| T_ANDOP : (string) terminal
| T_AND : unit terminal
| T_AMPERSAND : unit terminal
| T_AMPERAMPER : unit terminal
(* The indexed type of nonterminal symbols. *)
type _ nonterminal =
| N_with_type_binder : (Asttypes.private_flag) nonterminal
| N_with_constraint : (Parsetree.with_constraint) nonterminal
| N_virtual_with_private_flag : (Asttypes.private_flag) nonterminal
| N_virtual_with_mutable_flag : (Asttypes.mutable_flag) nonterminal
| N_virtual_flag : (Asttypes.virtual_flag) nonterminal
| N_value_description : (Parsetree.value_description * string Location.loc option) nonterminal
| N_value : ((string Location.loc * Asttypes.mutable_flag * Parsetree.class_field_kind) *
Parsetree.attributes) nonterminal
| N_val_longident : (Longident.t) nonterminal
| N_val_ident : (string) nonterminal
| N_val_extra_ident : (string) nonterminal
| N_use_file : (Parsetree.toplevel_phrase list) nonterminal
| N_type_variance : (Asttypes.variance * Asttypes.injectivity) nonterminal
| N_type_variable : (Parsetree.core_type) nonterminal
| N_type_parameters : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_type_parameter : (Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) nonterminal
| N_type_longident : (Longident.t) nonterminal
| N_type_kind : (Parsetree.type_kind * Asttypes.private_flag * Parsetree.core_type option) nonterminal
| N_type_constraint : (Parsetree.core_type option * Parsetree.core_type option) nonterminal
| N_tuple_type : (Parsetree.core_type) nonterminal
| N_toplevel_phrase : (Parsetree.toplevel_phrase) nonterminal
| N_toplevel_directive : (Parsetree.toplevel_phrase) nonterminal
| N_tag_field : (Parsetree.row_field) nonterminal
| N_subtractive : (string) nonterminal
| N_structure_item : (Parsetree.structure_item) nonterminal
| N_structure : (Parsetree.structure) nonterminal
| N_strict_function_type : (Parsetree.core_type) nonterminal
| N_strict_binding : (Parsetree.expression) nonterminal
| N_str_exception_declaration : (Parsetree.type_exception * string Location.loc option) nonterminal
| N_single_attr_id : (string) nonterminal
| N_simple_pattern_not_ident : (Parsetree.pattern) nonterminal
| N_simple_pattern : (Parsetree.pattern) nonterminal
| N_simple_expr : (Parsetree.expression) nonterminal
| N_simple_delimited_pattern : (Parsetree.pattern) nonterminal
| N_signed_constant : (Parsetree.constant) nonterminal
| N_signature_item : (Parsetree.signature_item) nonterminal
| N_signature : (Parsetree.signature) nonterminal
| N_sig_exception_declaration : (Parsetree.type_exception * string Location.loc option) nonterminal
| N_seq_expr : (Parsetree.expression) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_record_expr_field_ : ((Longident.t Location.loc * Parsetree.expression) list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_pattern_ : (Parsetree.pattern list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_object_expr_field_ : ((string Location.loc * Parsetree.expression) list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_expr_ : (Parsetree.expression list) nonterminal
| N_row_field : (Parsetree.row_field) nonterminal
| N_reversed_separated_nontrivial_llist_STAR_atomic_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nontrivial_llist_COMMA_expr_ : (Parsetree.expression list) nonterminal
| N_reversed_separated_nontrivial_llist_COMMA_core_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_STAR_atomic_type_gbl_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_COMMA_type_parameter_ : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_reversed_separated_nonempty_llist_COMMA_core_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_BAR_row_field_ : (Parsetree.row_field list) nonterminal
| N_reversed_separated_nonempty_llist_AND_with_constraint_ : (Parsetree.with_constraint list) nonterminal
| N_reversed_separated_nonempty_llist_AND_comprehension_clause_ : (Extensions.comprehension_clause list) nonterminal
| N_reversed_separated_nonempty_llist_AMPERSAND_core_type_no_attr_ : (Parsetree.core_type list) nonterminal
| N_reversed_preceded_or_separated_nonempty_llist_BAR_match_case_ : (Parsetree.case list) nonterminal
| N_reversed_nonempty_llist_typevar_ : (string Location.loc list) nonterminal
| N_reversed_nonempty_llist_name_tag_ : (string list) nonterminal
| N_reversed_nonempty_llist_labeled_simple_expr_ : ((Asttypes.arg_label * Parsetree.expression) list) nonterminal
| N_reversed_nonempty_llist_functor_arg_ : ((Lexing.position * Parsetree.functor_parameter) list) nonterminal
| N_reversed_llist_preceded_CONSTRAINT_constrain__ : ((Parsetree.core_type * Parsetree.core_type * Location.t) list) nonterminal
| N_reversed_bar_llist_extension_constructor_declaration_ : (Parsetree.extension_constructor list) nonterminal
| N_reversed_bar_llist_extension_constructor_ : (Parsetree.extension_constructor list) nonterminal
| N_reversed_bar_llist_constructor_declaration_ : (Parsetree.constructor_declaration list) nonterminal
| N_record_expr_content : (Parsetree.expression option *
(Longident.t Location.loc * Parsetree.expression) list) nonterminal
| N_rec_flag : (Asttypes.rec_flag) nonterminal
| N_private_virtual_flags : (Asttypes.private_flag * Asttypes.virtual_flag) nonterminal
| N_private_flag : (Asttypes.private_flag) nonterminal
| N_primitive_declaration : (Parsetree.value_description * string Location.loc option) nonterminal
| N_post_item_attribute : (Parsetree.attribute) nonterminal
| N_possibly_poly_core_type_no_attr_ : (Parsetree.core_type) nonterminal
| N_possibly_poly_core_type_ : (Parsetree.core_type) nonterminal
| N_payload : (Parsetree.payload) nonterminal
| N_pattern_var : (Parsetree.pattern) nonterminal
| N_pattern_no_exn : (Parsetree.pattern) nonterminal
| N_pattern_gen : (Parsetree.pattern) nonterminal
| N_pattern_comma_list_pattern_no_exn_ : (Parsetree.pattern list) nonterminal
| N_pattern_comma_list_pattern_ : (Parsetree.pattern list) nonterminal
| N_pattern : (Parsetree.pattern) nonterminal
| N_parse_val_longident : (Longident.t) nonterminal
| N_parse_pattern : (Parsetree.pattern) nonterminal
| N_parse_mty_longident : (Longident.t) nonterminal
| N_parse_module_type : (Parsetree.module_type) nonterminal
| N_parse_module_expr : (Parsetree.module_expr) nonterminal
| N_parse_mod_longident : (Longident.t) nonterminal
| N_parse_mod_ext_longident : (Longident.t) nonterminal
| N_parse_expression : (Parsetree.expression) nonterminal
| N_parse_core_type : (Parsetree.core_type) nonterminal
| N_parse_constr_longident : (Longident.t) nonterminal
| N_parse_any_longident : (Longident.t) nonterminal
| N_paren_module_expr : (Parsetree.module_expr) nonterminal
| N_optlabel : (string) nonterminal
| N_option_type_constraint_ : ((Parsetree.core_type option * Parsetree.core_type option) option) nonterminal
| N_option_preceded_EQUAL_seq_expr__ : (Parsetree.expression option) nonterminal
| N_option_preceded_EQUAL_pattern__ : (Parsetree.pattern option) nonterminal
| N_option_preceded_EQUAL_module_type__ : (Parsetree.module_type option) nonterminal
| N_option_preceded_EQUAL_expr__ : (Parsetree.expression option) nonterminal
| N_option_preceded_COLON_core_type__ : (Parsetree.core_type option) nonterminal
| N_option_preceded_AS_mkrhs_LIDENT___ : (string Location.loc option) nonterminal
| N_option_SEMI_ : (unit option) nonterminal
| N_option_BAR_ : (unit option) nonterminal
| N_opt_ampersand : (bool) nonterminal
| N_operator : (string) nonterminal
| N_open_description : (Longident.t Location.loc Parsetree.open_infos * string Location.loc option) nonterminal
| N_open_declaration : (Parsetree.module_expr Parsetree.open_infos * string Location.loc option) nonterminal
| N_nonempty_type_kind : (Parsetree.type_kind * Asttypes.private_flag * Parsetree.core_type option) nonterminal
| N_nonempty_list_raw_string_ : (string list) nonterminal
| N_nonempty_list_mkrhs_LIDENT__ : (string Location.loc list) nonterminal
| N_name_tag : (string) nonterminal
| N_mutable_virtual_flags : (Asttypes.mutable_flag * Asttypes.virtual_flag) nonterminal
| N_mutable_or_global_flag : (Asttypes.mutable_flag * Asttypes.global_flag) nonterminal
| N_mutable_flag : (Asttypes.mutable_flag) nonterminal
| N_mty_longident : (Longident.t) nonterminal
| N_module_type_subst : (Parsetree.module_type_declaration * string Location.loc option) nonterminal
| N_module_type_declaration : (Parsetree.module_type_declaration * string Location.loc option) nonterminal
| N_module_type : (Parsetree.module_type) nonterminal
| N_module_subst : (Parsetree.module_substitution * string Location.loc option) nonterminal
| N_module_name : (string option) nonterminal
| N_module_expr : (Parsetree.module_expr) nonterminal
| N_module_declaration_body : (Parsetree.module_type) nonterminal
| N_module_binding_body : (Parsetree.module_expr) nonterminal
| N_mod_longident : (Longident.t) nonterminal
| N_mod_ext_longident : (Longident.t) nonterminal
| N_mk_longident_mod_longident_val_ident_ : (Longident.t) nonterminal
| N_mk_longident_mod_longident_UIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_longident_LIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_ident_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident___anonymous_46_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_UIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_LIDENT_ : (Longident.t) nonterminal
| N_method_ : ((string Location.loc * Asttypes.private_flag * Parsetree.class_field_kind) *
Parsetree.attributes) nonterminal
| N_meth_list : (Parsetree.object_field list * Asttypes.closed_flag) nonterminal
| N_match_case : (Parsetree.case) nonterminal
| N_lwt_bindings : (Ast_helper.let_bindings) nonterminal
| N_lwt_binding : (Ast_helper.let_bindings) nonterminal
| N_local_strict_binding : (Parsetree.expression) nonterminal
| N_local_fun_binding : (Parsetree.expression) nonterminal
| N_listx_SEMI_record_pat_field_UNDERSCORE_ : ((Longident.t Location.loc * Parsetree.pattern) list * unit option) nonterminal
| N_list_use_file_element_ : (Parsetree.toplevel_phrase list list) nonterminal
| N_list_text_str_structure_item__ : (Parsetree.structure_item list list) nonterminal
| N_list_text_cstr_class_field__ : (Parsetree.class_field list list) nonterminal
| N_list_text_csig_class_sig_field__ : (Parsetree.class_type_field list list) nonterminal
| N_list_structure_element_ : (Parsetree.structure_item list list) nonterminal
| N_list_signature_element_ : (Parsetree.signature_item list list) nonterminal
| N_list_post_item_attribute_ : (Parsetree.attributes) nonterminal
| N_list_generic_and_type_declaration_type_subst_kind__ : (Parsetree.type_declaration list) nonterminal
| N_list_generic_and_type_declaration_type_kind__ : (Parsetree.type_declaration list) nonterminal
| N_list_attribute_ : (Parsetree.attributes) nonterminal
| N_list_and_module_declaration_ : (Parsetree.module_declaration list) nonterminal
| N_list_and_module_binding_ : (Parsetree.module_binding list) nonterminal
| N_list_and_class_type_declaration_ : (Parsetree.class_type Parsetree.class_infos list) nonterminal
| N_list_and_class_description_ : (Parsetree.class_type Parsetree.class_infos list) nonterminal
| N_list_and_class_declaration_ : (Parsetree.class_expr Parsetree.class_infos list) nonterminal
| N_letop_bindings : (Parsetree.pattern * Parsetree.expression * Parsetree.binding_op list) nonterminal
| N_letop_binding_body : (Parsetree.pattern * Parsetree.expression) nonterminal
| N_let_pattern : (Parsetree.pattern) nonterminal
| N_let_bindings_no_ext_ : (Ast_helper.let_bindings) nonterminal
| N_let_bindings_ext_ : (Ast_helper.let_bindings) nonterminal
| N_let_binding_body_no_punning : (Parsetree.pattern * Parsetree.expression) nonterminal
| N_let_binding_body : (Parsetree.pattern * Parsetree.expression * bool) nonterminal
| N_labeled_simple_pattern : (Asttypes.arg_label * Parsetree.expression option * Parsetree.pattern) nonterminal
| N_labeled_simple_expr : (Asttypes.arg_label * Parsetree.expression) nonterminal
| N_label_longident : (Longident.t) nonterminal
| N_label_let_pattern : (string * Parsetree.pattern) nonterminal
| N_label_declarations : (Parsetree.label_declaration list) nonterminal
| N_label_declaration_semi : (Parsetree.label_declaration) nonterminal
| N_label_declaration : (Parsetree.label_declaration) nonterminal
| N_item_extension : (Parsetree.extension) nonterminal
| N_interface : (Parsetree.signature) nonterminal
| N_index_mod : (string) nonterminal
| N_include_and_functor_attr : (Parsetree.attribute list) nonterminal
| N_implementation : (Parsetree.structure) nonterminal
| N_ident : (string) nonterminal
| N_generic_type_declaration_nonrec_flag_type_kind_ : ((Asttypes.rec_flag * string Location.loc option) *
Parsetree.type_declaration) nonterminal
| N_generic_type_declaration_no_nonrec_flag_type_subst_kind_ : ((Asttypes.rec_flag * string Location.loc option) *
Parsetree.type_declaration) nonterminal
| N_generic_constructor_declaration_epsilon_ : (Ocaml_parsing.Ast_helper.str * string Location.loc list *
Parsetree.constructor_arguments * Parsetree.core_type option *
Parsetree.attributes * Location.t * Ocaml_parsing.Docstrings.info) nonterminal
| N_generic_constructor_declaration_BAR_ : (Ocaml_parsing.Ast_helper.str * string Location.loc list *
Parsetree.constructor_arguments * Parsetree.core_type option *
Parsetree.attributes * Location.t * Ocaml_parsing.Docstrings.info) nonterminal
| N_generalized_constructor_arguments : (string Location.loc list * Parsetree.constructor_arguments *
Parsetree.core_type option) nonterminal
| N_functor_args : ((Lexing.position * Parsetree.functor_parameter) list) nonterminal
| N_functor_arg : (Lexing.position * Parsetree.functor_parameter) nonterminal
| N_function_type : (Parsetree.core_type) nonterminal
| N_fun_def : (Parsetree.expression) nonterminal
| N_fun_binding : (Parsetree.expression) nonterminal
| N_formal_class_parameters : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_floating_attribute : (Parsetree.attribute) nonterminal
| N_extension_constructor_rebind_epsilon_ : (Parsetree.extension_constructor) nonterminal
| N_extension_constructor_rebind_BAR_ : (Parsetree.extension_constructor) nonterminal
| N_extension : (Parsetree.extension) nonterminal
| N_ext : (string Location.loc option) nonterminal
| N_expr : (Parsetree.expression) nonterminal
| N_direction_flag : (Asttypes.direction_flag) nonterminal
| N_core_type : (Parsetree.core_type) nonterminal
| N_constructor_declarations : (Parsetree.constructor_declaration list) nonterminal
| N_constructor_arguments : (Parsetree.constructor_arguments) nonterminal
| N_constrain_field : (Parsetree.core_type * Parsetree.core_type) nonterminal
| N_constr_longident : (Longident.t) nonterminal
| N_constr_ident : (string) nonterminal
| N_constr_extra_nonprefix_ident : (string) nonterminal
| N_constant : (Parsetree.constant) nonterminal
| N_comprehension_tail_RBRACKET_ : (Extensions.comprehension list) nonterminal
| N_comprehension_tail_BARRBRACKET_ : (Extensions.comprehension list) nonterminal
| N_comprehension_clause : (Extensions.comprehension_clause) nonterminal
| N_clty_longident : (Longident.t) nonterminal
| N_class_type_declarations : (string Location.loc option * Parsetree.class_type_declaration list) nonterminal
| N_class_type : (Parsetree.class_type) nonterminal
| N_class_simple_expr : (Parsetree.class_expr) nonterminal
| N_class_signature : (Parsetree.class_type) nonterminal
| N_class_sig_field : (Parsetree.class_type_field) nonterminal
| N_class_self_type : (Parsetree.core_type) nonterminal
| N_class_self_pattern : (Parsetree.pattern) nonterminal
| N_class_longident : (Longident.t) nonterminal
| N_class_fun_def : (Parsetree.class_expr) nonterminal
| N_class_fun_binding : (Parsetree.class_expr) nonterminal
| N_class_field : (Parsetree.class_field) nonterminal
| N_class_expr : (Parsetree.class_expr) nonterminal
| N_attribute : (Parsetree.attribute) nonterminal
| N_attr_id : (string Location.loc) nonterminal
| N_atomic_type : (Parsetree.core_type) nonterminal
| N_any_longident : (Longident.t) nonterminal
| N_and_let_binding : (Ast_helper.let_binding) nonterminal
| N_alias_type : (Parsetree.core_type) nonterminal
| N_additive : (string) nonterminal
(* The inspection API. *)
include MenhirLib.IncrementalEngine.INSPECTION
with type 'a lr1state := 'a lr1state
with type production := production
with type 'a terminal := 'a terminal
with type 'a nonterminal := 'a nonterminal
with type 'a env := 'a env
end
(* The entry point(s) to the incremental API. *)
module Incremental : sig
val use_file: Lexing.position -> (Parsetree.toplevel_phrase list) MenhirInterpreter.checkpoint
val toplevel_phrase: Lexing.position -> (Parsetree.toplevel_phrase) MenhirInterpreter.checkpoint
val parse_val_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_pattern: Lexing.position -> (Parsetree.pattern) MenhirInterpreter.checkpoint
val parse_mty_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_module_type: Lexing.position -> (Parsetree.module_type) MenhirInterpreter.checkpoint
val parse_module_expr: Lexing.position -> (Parsetree.module_expr) MenhirInterpreter.checkpoint
val parse_mod_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_mod_ext_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_expression: Lexing.position -> (Parsetree.expression) MenhirInterpreter.checkpoint
val parse_core_type: Lexing.position -> (Parsetree.core_type) MenhirInterpreter.checkpoint
val parse_constr_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_any_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val interface: Lexing.position -> (Parsetree.signature) MenhirInterpreter.checkpoint
val implementation: Lexing.position -> (Parsetree.structure) MenhirInterpreter.checkpoint
end
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/9c3b60c98d80b56af18ea95c27a0902f0244659a/src/ocaml/preprocess/parser_raw.mli | ocaml | The type of tokens.
This exception is raised by the monolithic API functions.
The monolithic API.
The incremental API.
The indexed type of terminal symbols.
The indexed type of nonterminal symbols.
The inspection API.
The entry point(s) to the incremental API. |
type token =
| WITH
| WHILE_LWT
| WHILE
| WHEN
| VIRTUAL
| VAL
| UNDERSCORE
| UIDENT of (string)
| TYPE
| TRY_LWT
| TRY
| TRUE
| TO
| TILDE
| THEN
| STRUCT
| STRING of (string * Location.t * string option)
| STAR
| SIG
| SEMISEMI
| SEMI
| RPAREN
| REC
| RBRACKET
| RBRACE
| QUOTED_STRING_ITEM of (string * Location.t * string * Location.t * string option)
| QUOTED_STRING_EXPR of (string * Location.t * string * Location.t * string option)
| QUOTE
| QUESTION
| PRIVATE
| PREFIXOP of (string)
| PLUSEQ
| PLUSDOT
| PLUS
| PERCENT
| OR
| OPTLABEL of (string)
| OPEN
| OF
| OBJECT
| NONREC
| NONLOCAL
| NEW
| MUTABLE
| MODULE
| MINUSGREATER
| MINUSDOT
| MINUS
| METHOD
| MATCH_LWT
| MATCH
| LPAREN
| LOCAL
| LIDENT of (string)
| LET_LWT
| LETOP of (string)
| LET
| LESSMINUS
| LESS
| LBRACKETPERCENTPERCENT
| LBRACKETPERCENT
| LBRACKETLESS
| LBRACKETGREATER
| LBRACKETBAR
| LBRACKETATATAT
| LBRACKETATAT
| LBRACKETAT
| LBRACKET
| LBRACELESS
| LBRACE
| LAZY
| LABEL of (string)
| INT of (string * char option)
| INITIALIZER
| INHERIT
| INFIXOP4 of (string)
| INFIXOP3 of (string)
| INFIXOP2 of (string)
| INFIXOP1 of (string)
| INFIXOP0 of (string)
| INCLUDE
| IN
| IF
| HASHOP of (string)
| HASH
| GREATERRBRACKET
| GREATERRBRACE
| GREATERDOT
| GREATER
| GLOBAL
| FUNCTOR
| FUNCTION
| FUN
| FOR_LWT
| FOR
| FLOAT of (string * char option)
| FINALLY_LWT
| FALSE
| EXTERNAL
| EXCEPTION
| EQUAL
| EOL
| EOF
| END
| ELSE
| DOWNTO
| DOTTILDE
| DOTOP of (string)
| DOTLESS
| DOTDOT
| DOT
| DONE
| DOCSTRING of (Docstrings.docstring)
| DO
| CONSTRAINT
| COMMENT of (string * Location.t)
| COMMA
| COLONGREATER
| COLONEQUAL
| COLONCOLON
| COLON
| CLASS
| CHAR of (char)
| BEGIN
| BARRBRACKET
| BARBAR
| BAR
| BANG
| BACKQUOTE
| ASSERT
| AS
| ANDOP of (string)
| AND
| AMPERSAND
| AMPERAMPER
exception Error
val use_file: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.toplevel_phrase list)
val toplevel_phrase: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.toplevel_phrase)
val parse_val_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_pattern: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.pattern)
val parse_mty_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_module_type: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.module_type)
val parse_module_expr: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.module_expr)
val parse_mod_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_mod_ext_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_expression: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.expression)
val parse_core_type: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.core_type)
val parse_constr_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val parse_any_longident: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Longident.t)
val interface: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.signature)
val implementation: (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (Parsetree.structure)
module MenhirInterpreter : sig
include MenhirLib.IncrementalEngine.INCREMENTAL_ENGINE
with type token = token
type _ terminal =
| T_error : unit terminal
| T_WITH : unit terminal
| T_WHILE_LWT : unit terminal
| T_WHILE : unit terminal
| T_WHEN : unit terminal
| T_VIRTUAL : unit terminal
| T_VAL : unit terminal
| T_UNDERSCORE : unit terminal
| T_UIDENT : (string) terminal
| T_TYPE : unit terminal
| T_TRY_LWT : unit terminal
| T_TRY : unit terminal
| T_TRUE : unit terminal
| T_TO : unit terminal
| T_TILDE : unit terminal
| T_THEN : unit terminal
| T_STRUCT : unit terminal
| T_STRING : (string * Location.t * string option) terminal
| T_STAR : unit terminal
| T_SIG : unit terminal
| T_SEMISEMI : unit terminal
| T_SEMI : unit terminal
| T_RPAREN : unit terminal
| T_REC : unit terminal
| T_RBRACKET : unit terminal
| T_RBRACE : unit terminal
| T_QUOTED_STRING_ITEM : (string * Location.t * string * Location.t * string option) terminal
| T_QUOTED_STRING_EXPR : (string * Location.t * string * Location.t * string option) terminal
| T_QUOTE : unit terminal
| T_QUESTION : unit terminal
| T_PRIVATE : unit terminal
| T_PREFIXOP : (string) terminal
| T_PLUSEQ : unit terminal
| T_PLUSDOT : unit terminal
| T_PLUS : unit terminal
| T_PERCENT : unit terminal
| T_OR : unit terminal
| T_OPTLABEL : (string) terminal
| T_OPEN : unit terminal
| T_OF : unit terminal
| T_OBJECT : unit terminal
| T_NONREC : unit terminal
| T_NONLOCAL : unit terminal
| T_NEW : unit terminal
| T_MUTABLE : unit terminal
| T_MODULE : unit terminal
| T_MINUSGREATER : unit terminal
| T_MINUSDOT : unit terminal
| T_MINUS : unit terminal
| T_METHOD : unit terminal
| T_MATCH_LWT : unit terminal
| T_MATCH : unit terminal
| T_LPAREN : unit terminal
| T_LOCAL : unit terminal
| T_LIDENT : (string) terminal
| T_LET_LWT : unit terminal
| T_LETOP : (string) terminal
| T_LET : unit terminal
| T_LESSMINUS : unit terminal
| T_LESS : unit terminal
| T_LBRACKETPERCENTPERCENT : unit terminal
| T_LBRACKETPERCENT : unit terminal
| T_LBRACKETLESS : unit terminal
| T_LBRACKETGREATER : unit terminal
| T_LBRACKETBAR : unit terminal
| T_LBRACKETATATAT : unit terminal
| T_LBRACKETATAT : unit terminal
| T_LBRACKETAT : unit terminal
| T_LBRACKET : unit terminal
| T_LBRACELESS : unit terminal
| T_LBRACE : unit terminal
| T_LAZY : unit terminal
| T_LABEL : (string) terminal
| T_INT : (string * char option) terminal
| T_INITIALIZER : unit terminal
| T_INHERIT : unit terminal
| T_INFIXOP4 : (string) terminal
| T_INFIXOP3 : (string) terminal
| T_INFIXOP2 : (string) terminal
| T_INFIXOP1 : (string) terminal
| T_INFIXOP0 : (string) terminal
| T_INCLUDE : unit terminal
| T_IN : unit terminal
| T_IF : unit terminal
| T_HASHOP : (string) terminal
| T_HASH : unit terminal
| T_GREATERRBRACKET : unit terminal
| T_GREATERRBRACE : unit terminal
| T_GREATERDOT : unit terminal
| T_GREATER : unit terminal
| T_GLOBAL : unit terminal
| T_FUNCTOR : unit terminal
| T_FUNCTION : unit terminal
| T_FUN : unit terminal
| T_FOR_LWT : unit terminal
| T_FOR : unit terminal
| T_FLOAT : (string * char option) terminal
| T_FINALLY_LWT : unit terminal
| T_FALSE : unit terminal
| T_EXTERNAL : unit terminal
| T_EXCEPTION : unit terminal
| T_EQUAL : unit terminal
| T_EOL : unit terminal
| T_EOF : unit terminal
| T_END : unit terminal
| T_ELSE : unit terminal
| T_DOWNTO : unit terminal
| T_DOTTILDE : unit terminal
| T_DOTOP : (string) terminal
| T_DOTLESS : unit terminal
| T_DOTDOT : unit terminal
| T_DOT : unit terminal
| T_DONE : unit terminal
| T_DOCSTRING : (Docstrings.docstring) terminal
| T_DO : unit terminal
| T_CONSTRAINT : unit terminal
| T_COMMENT : (string * Location.t) terminal
| T_COMMA : unit terminal
| T_COLONGREATER : unit terminal
| T_COLONEQUAL : unit terminal
| T_COLONCOLON : unit terminal
| T_COLON : unit terminal
| T_CLASS : unit terminal
| T_CHAR : (char) terminal
| T_BEGIN : unit terminal
| T_BARRBRACKET : unit terminal
| T_BARBAR : unit terminal
| T_BAR : unit terminal
| T_BANG : unit terminal
| T_BACKQUOTE : unit terminal
| T_ASSERT : unit terminal
| T_AS : unit terminal
| T_ANDOP : (string) terminal
| T_AND : unit terminal
| T_AMPERSAND : unit terminal
| T_AMPERAMPER : unit terminal
type _ nonterminal =
| N_with_type_binder : (Asttypes.private_flag) nonterminal
| N_with_constraint : (Parsetree.with_constraint) nonterminal
| N_virtual_with_private_flag : (Asttypes.private_flag) nonterminal
| N_virtual_with_mutable_flag : (Asttypes.mutable_flag) nonterminal
| N_virtual_flag : (Asttypes.virtual_flag) nonterminal
| N_value_description : (Parsetree.value_description * string Location.loc option) nonterminal
| N_value : ((string Location.loc * Asttypes.mutable_flag * Parsetree.class_field_kind) *
Parsetree.attributes) nonterminal
| N_val_longident : (Longident.t) nonterminal
| N_val_ident : (string) nonterminal
| N_val_extra_ident : (string) nonterminal
| N_use_file : (Parsetree.toplevel_phrase list) nonterminal
| N_type_variance : (Asttypes.variance * Asttypes.injectivity) nonterminal
| N_type_variable : (Parsetree.core_type) nonterminal
| N_type_parameters : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_type_parameter : (Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) nonterminal
| N_type_longident : (Longident.t) nonterminal
| N_type_kind : (Parsetree.type_kind * Asttypes.private_flag * Parsetree.core_type option) nonterminal
| N_type_constraint : (Parsetree.core_type option * Parsetree.core_type option) nonterminal
| N_tuple_type : (Parsetree.core_type) nonterminal
| N_toplevel_phrase : (Parsetree.toplevel_phrase) nonterminal
| N_toplevel_directive : (Parsetree.toplevel_phrase) nonterminal
| N_tag_field : (Parsetree.row_field) nonterminal
| N_subtractive : (string) nonterminal
| N_structure_item : (Parsetree.structure_item) nonterminal
| N_structure : (Parsetree.structure) nonterminal
| N_strict_function_type : (Parsetree.core_type) nonterminal
| N_strict_binding : (Parsetree.expression) nonterminal
| N_str_exception_declaration : (Parsetree.type_exception * string Location.loc option) nonterminal
| N_single_attr_id : (string) nonterminal
| N_simple_pattern_not_ident : (Parsetree.pattern) nonterminal
| N_simple_pattern : (Parsetree.pattern) nonterminal
| N_simple_expr : (Parsetree.expression) nonterminal
| N_simple_delimited_pattern : (Parsetree.pattern) nonterminal
| N_signed_constant : (Parsetree.constant) nonterminal
| N_signature_item : (Parsetree.signature_item) nonterminal
| N_signature : (Parsetree.signature) nonterminal
| N_sig_exception_declaration : (Parsetree.type_exception * string Location.loc option) nonterminal
| N_seq_expr : (Parsetree.expression) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_record_expr_field_ : ((Longident.t Location.loc * Parsetree.expression) list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_pattern_ : (Parsetree.pattern list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_object_expr_field_ : ((string Location.loc * Parsetree.expression) list) nonterminal
| N_separated_or_terminated_nonempty_list_SEMI_expr_ : (Parsetree.expression list) nonterminal
| N_row_field : (Parsetree.row_field) nonterminal
| N_reversed_separated_nontrivial_llist_STAR_atomic_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nontrivial_llist_COMMA_expr_ : (Parsetree.expression list) nonterminal
| N_reversed_separated_nontrivial_llist_COMMA_core_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_STAR_atomic_type_gbl_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_COMMA_type_parameter_ : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_reversed_separated_nonempty_llist_COMMA_core_type_ : (Parsetree.core_type list) nonterminal
| N_reversed_separated_nonempty_llist_BAR_row_field_ : (Parsetree.row_field list) nonterminal
| N_reversed_separated_nonempty_llist_AND_with_constraint_ : (Parsetree.with_constraint list) nonterminal
| N_reversed_separated_nonempty_llist_AND_comprehension_clause_ : (Extensions.comprehension_clause list) nonterminal
| N_reversed_separated_nonempty_llist_AMPERSAND_core_type_no_attr_ : (Parsetree.core_type list) nonterminal
| N_reversed_preceded_or_separated_nonempty_llist_BAR_match_case_ : (Parsetree.case list) nonterminal
| N_reversed_nonempty_llist_typevar_ : (string Location.loc list) nonterminal
| N_reversed_nonempty_llist_name_tag_ : (string list) nonterminal
| N_reversed_nonempty_llist_labeled_simple_expr_ : ((Asttypes.arg_label * Parsetree.expression) list) nonterminal
| N_reversed_nonempty_llist_functor_arg_ : ((Lexing.position * Parsetree.functor_parameter) list) nonterminal
| N_reversed_llist_preceded_CONSTRAINT_constrain__ : ((Parsetree.core_type * Parsetree.core_type * Location.t) list) nonterminal
| N_reversed_bar_llist_extension_constructor_declaration_ : (Parsetree.extension_constructor list) nonterminal
| N_reversed_bar_llist_extension_constructor_ : (Parsetree.extension_constructor list) nonterminal
| N_reversed_bar_llist_constructor_declaration_ : (Parsetree.constructor_declaration list) nonterminal
| N_record_expr_content : (Parsetree.expression option *
(Longident.t Location.loc * Parsetree.expression) list) nonterminal
| N_rec_flag : (Asttypes.rec_flag) nonterminal
| N_private_virtual_flags : (Asttypes.private_flag * Asttypes.virtual_flag) nonterminal
| N_private_flag : (Asttypes.private_flag) nonterminal
| N_primitive_declaration : (Parsetree.value_description * string Location.loc option) nonterminal
| N_post_item_attribute : (Parsetree.attribute) nonterminal
| N_possibly_poly_core_type_no_attr_ : (Parsetree.core_type) nonterminal
| N_possibly_poly_core_type_ : (Parsetree.core_type) nonterminal
| N_payload : (Parsetree.payload) nonterminal
| N_pattern_var : (Parsetree.pattern) nonterminal
| N_pattern_no_exn : (Parsetree.pattern) nonterminal
| N_pattern_gen : (Parsetree.pattern) nonterminal
| N_pattern_comma_list_pattern_no_exn_ : (Parsetree.pattern list) nonterminal
| N_pattern_comma_list_pattern_ : (Parsetree.pattern list) nonterminal
| N_pattern : (Parsetree.pattern) nonterminal
| N_parse_val_longident : (Longident.t) nonterminal
| N_parse_pattern : (Parsetree.pattern) nonterminal
| N_parse_mty_longident : (Longident.t) nonterminal
| N_parse_module_type : (Parsetree.module_type) nonterminal
| N_parse_module_expr : (Parsetree.module_expr) nonterminal
| N_parse_mod_longident : (Longident.t) nonterminal
| N_parse_mod_ext_longident : (Longident.t) nonterminal
| N_parse_expression : (Parsetree.expression) nonterminal
| N_parse_core_type : (Parsetree.core_type) nonterminal
| N_parse_constr_longident : (Longident.t) nonterminal
| N_parse_any_longident : (Longident.t) nonterminal
| N_paren_module_expr : (Parsetree.module_expr) nonterminal
| N_optlabel : (string) nonterminal
| N_option_type_constraint_ : ((Parsetree.core_type option * Parsetree.core_type option) option) nonterminal
| N_option_preceded_EQUAL_seq_expr__ : (Parsetree.expression option) nonterminal
| N_option_preceded_EQUAL_pattern__ : (Parsetree.pattern option) nonterminal
| N_option_preceded_EQUAL_module_type__ : (Parsetree.module_type option) nonterminal
| N_option_preceded_EQUAL_expr__ : (Parsetree.expression option) nonterminal
| N_option_preceded_COLON_core_type__ : (Parsetree.core_type option) nonterminal
| N_option_preceded_AS_mkrhs_LIDENT___ : (string Location.loc option) nonterminal
| N_option_SEMI_ : (unit option) nonterminal
| N_option_BAR_ : (unit option) nonterminal
| N_opt_ampersand : (bool) nonterminal
| N_operator : (string) nonterminal
| N_open_description : (Longident.t Location.loc Parsetree.open_infos * string Location.loc option) nonterminal
| N_open_declaration : (Parsetree.module_expr Parsetree.open_infos * string Location.loc option) nonterminal
| N_nonempty_type_kind : (Parsetree.type_kind * Asttypes.private_flag * Parsetree.core_type option) nonterminal
| N_nonempty_list_raw_string_ : (string list) nonterminal
| N_nonempty_list_mkrhs_LIDENT__ : (string Location.loc list) nonterminal
| N_name_tag : (string) nonterminal
| N_mutable_virtual_flags : (Asttypes.mutable_flag * Asttypes.virtual_flag) nonterminal
| N_mutable_or_global_flag : (Asttypes.mutable_flag * Asttypes.global_flag) nonterminal
| N_mutable_flag : (Asttypes.mutable_flag) nonterminal
| N_mty_longident : (Longident.t) nonterminal
| N_module_type_subst : (Parsetree.module_type_declaration * string Location.loc option) nonterminal
| N_module_type_declaration : (Parsetree.module_type_declaration * string Location.loc option) nonterminal
| N_module_type : (Parsetree.module_type) nonterminal
| N_module_subst : (Parsetree.module_substitution * string Location.loc option) nonterminal
| N_module_name : (string option) nonterminal
| N_module_expr : (Parsetree.module_expr) nonterminal
| N_module_declaration_body : (Parsetree.module_type) nonterminal
| N_module_binding_body : (Parsetree.module_expr) nonterminal
| N_mod_longident : (Longident.t) nonterminal
| N_mod_ext_longident : (Longident.t) nonterminal
| N_mk_longident_mod_longident_val_ident_ : (Longident.t) nonterminal
| N_mk_longident_mod_longident_UIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_longident_LIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_ident_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident___anonymous_46_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_UIDENT_ : (Longident.t) nonterminal
| N_mk_longident_mod_ext_longident_LIDENT_ : (Longident.t) nonterminal
| N_method_ : ((string Location.loc * Asttypes.private_flag * Parsetree.class_field_kind) *
Parsetree.attributes) nonterminal
| N_meth_list : (Parsetree.object_field list * Asttypes.closed_flag) nonterminal
| N_match_case : (Parsetree.case) nonterminal
| N_lwt_bindings : (Ast_helper.let_bindings) nonterminal
| N_lwt_binding : (Ast_helper.let_bindings) nonterminal
| N_local_strict_binding : (Parsetree.expression) nonterminal
| N_local_fun_binding : (Parsetree.expression) nonterminal
| N_listx_SEMI_record_pat_field_UNDERSCORE_ : ((Longident.t Location.loc * Parsetree.pattern) list * unit option) nonterminal
| N_list_use_file_element_ : (Parsetree.toplevel_phrase list list) nonterminal
| N_list_text_str_structure_item__ : (Parsetree.structure_item list list) nonterminal
| N_list_text_cstr_class_field__ : (Parsetree.class_field list list) nonterminal
| N_list_text_csig_class_sig_field__ : (Parsetree.class_type_field list list) nonterminal
| N_list_structure_element_ : (Parsetree.structure_item list list) nonterminal
| N_list_signature_element_ : (Parsetree.signature_item list list) nonterminal
| N_list_post_item_attribute_ : (Parsetree.attributes) nonterminal
| N_list_generic_and_type_declaration_type_subst_kind__ : (Parsetree.type_declaration list) nonterminal
| N_list_generic_and_type_declaration_type_kind__ : (Parsetree.type_declaration list) nonterminal
| N_list_attribute_ : (Parsetree.attributes) nonterminal
| N_list_and_module_declaration_ : (Parsetree.module_declaration list) nonterminal
| N_list_and_module_binding_ : (Parsetree.module_binding list) nonterminal
| N_list_and_class_type_declaration_ : (Parsetree.class_type Parsetree.class_infos list) nonterminal
| N_list_and_class_description_ : (Parsetree.class_type Parsetree.class_infos list) nonterminal
| N_list_and_class_declaration_ : (Parsetree.class_expr Parsetree.class_infos list) nonterminal
| N_letop_bindings : (Parsetree.pattern * Parsetree.expression * Parsetree.binding_op list) nonterminal
| N_letop_binding_body : (Parsetree.pattern * Parsetree.expression) nonterminal
| N_let_pattern : (Parsetree.pattern) nonterminal
| N_let_bindings_no_ext_ : (Ast_helper.let_bindings) nonterminal
| N_let_bindings_ext_ : (Ast_helper.let_bindings) nonterminal
| N_let_binding_body_no_punning : (Parsetree.pattern * Parsetree.expression) nonterminal
| N_let_binding_body : (Parsetree.pattern * Parsetree.expression * bool) nonterminal
| N_labeled_simple_pattern : (Asttypes.arg_label * Parsetree.expression option * Parsetree.pattern) nonterminal
| N_labeled_simple_expr : (Asttypes.arg_label * Parsetree.expression) nonterminal
| N_label_longident : (Longident.t) nonterminal
| N_label_let_pattern : (string * Parsetree.pattern) nonterminal
| N_label_declarations : (Parsetree.label_declaration list) nonterminal
| N_label_declaration_semi : (Parsetree.label_declaration) nonterminal
| N_label_declaration : (Parsetree.label_declaration) nonterminal
| N_item_extension : (Parsetree.extension) nonterminal
| N_interface : (Parsetree.signature) nonterminal
| N_index_mod : (string) nonterminal
| N_include_and_functor_attr : (Parsetree.attribute list) nonterminal
| N_implementation : (Parsetree.structure) nonterminal
| N_ident : (string) nonterminal
| N_generic_type_declaration_nonrec_flag_type_kind_ : ((Asttypes.rec_flag * string Location.loc option) *
Parsetree.type_declaration) nonterminal
| N_generic_type_declaration_no_nonrec_flag_type_subst_kind_ : ((Asttypes.rec_flag * string Location.loc option) *
Parsetree.type_declaration) nonterminal
| N_generic_constructor_declaration_epsilon_ : (Ocaml_parsing.Ast_helper.str * string Location.loc list *
Parsetree.constructor_arguments * Parsetree.core_type option *
Parsetree.attributes * Location.t * Ocaml_parsing.Docstrings.info) nonterminal
| N_generic_constructor_declaration_BAR_ : (Ocaml_parsing.Ast_helper.str * string Location.loc list *
Parsetree.constructor_arguments * Parsetree.core_type option *
Parsetree.attributes * Location.t * Ocaml_parsing.Docstrings.info) nonterminal
| N_generalized_constructor_arguments : (string Location.loc list * Parsetree.constructor_arguments *
Parsetree.core_type option) nonterminal
| N_functor_args : ((Lexing.position * Parsetree.functor_parameter) list) nonterminal
| N_functor_arg : (Lexing.position * Parsetree.functor_parameter) nonterminal
| N_function_type : (Parsetree.core_type) nonterminal
| N_fun_def : (Parsetree.expression) nonterminal
| N_fun_binding : (Parsetree.expression) nonterminal
| N_formal_class_parameters : ((Parsetree.core_type * (Asttypes.variance * Asttypes.injectivity)) list) nonterminal
| N_floating_attribute : (Parsetree.attribute) nonterminal
| N_extension_constructor_rebind_epsilon_ : (Parsetree.extension_constructor) nonterminal
| N_extension_constructor_rebind_BAR_ : (Parsetree.extension_constructor) nonterminal
| N_extension : (Parsetree.extension) nonterminal
| N_ext : (string Location.loc option) nonterminal
| N_expr : (Parsetree.expression) nonterminal
| N_direction_flag : (Asttypes.direction_flag) nonterminal
| N_core_type : (Parsetree.core_type) nonterminal
| N_constructor_declarations : (Parsetree.constructor_declaration list) nonterminal
| N_constructor_arguments : (Parsetree.constructor_arguments) nonterminal
| N_constrain_field : (Parsetree.core_type * Parsetree.core_type) nonterminal
| N_constr_longident : (Longident.t) nonterminal
| N_constr_ident : (string) nonterminal
| N_constr_extra_nonprefix_ident : (string) nonterminal
| N_constant : (Parsetree.constant) nonterminal
| N_comprehension_tail_RBRACKET_ : (Extensions.comprehension list) nonterminal
| N_comprehension_tail_BARRBRACKET_ : (Extensions.comprehension list) nonterminal
| N_comprehension_clause : (Extensions.comprehension_clause) nonterminal
| N_clty_longident : (Longident.t) nonterminal
| N_class_type_declarations : (string Location.loc option * Parsetree.class_type_declaration list) nonterminal
| N_class_type : (Parsetree.class_type) nonterminal
| N_class_simple_expr : (Parsetree.class_expr) nonterminal
| N_class_signature : (Parsetree.class_type) nonterminal
| N_class_sig_field : (Parsetree.class_type_field) nonterminal
| N_class_self_type : (Parsetree.core_type) nonterminal
| N_class_self_pattern : (Parsetree.pattern) nonterminal
| N_class_longident : (Longident.t) nonterminal
| N_class_fun_def : (Parsetree.class_expr) nonterminal
| N_class_fun_binding : (Parsetree.class_expr) nonterminal
| N_class_field : (Parsetree.class_field) nonterminal
| N_class_expr : (Parsetree.class_expr) nonterminal
| N_attribute : (Parsetree.attribute) nonterminal
| N_attr_id : (string Location.loc) nonterminal
| N_atomic_type : (Parsetree.core_type) nonterminal
| N_any_longident : (Longident.t) nonterminal
| N_and_let_binding : (Ast_helper.let_binding) nonterminal
| N_alias_type : (Parsetree.core_type) nonterminal
| N_additive : (string) nonterminal
include MenhirLib.IncrementalEngine.INSPECTION
with type 'a lr1state := 'a lr1state
with type production := production
with type 'a terminal := 'a terminal
with type 'a nonterminal := 'a nonterminal
with type 'a env := 'a env
end
module Incremental : sig
val use_file: Lexing.position -> (Parsetree.toplevel_phrase list) MenhirInterpreter.checkpoint
val toplevel_phrase: Lexing.position -> (Parsetree.toplevel_phrase) MenhirInterpreter.checkpoint
val parse_val_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_pattern: Lexing.position -> (Parsetree.pattern) MenhirInterpreter.checkpoint
val parse_mty_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_module_type: Lexing.position -> (Parsetree.module_type) MenhirInterpreter.checkpoint
val parse_module_expr: Lexing.position -> (Parsetree.module_expr) MenhirInterpreter.checkpoint
val parse_mod_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_mod_ext_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_expression: Lexing.position -> (Parsetree.expression) MenhirInterpreter.checkpoint
val parse_core_type: Lexing.position -> (Parsetree.core_type) MenhirInterpreter.checkpoint
val parse_constr_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val parse_any_longident: Lexing.position -> (Longident.t) MenhirInterpreter.checkpoint
val interface: Lexing.position -> (Parsetree.signature) MenhirInterpreter.checkpoint
val implementation: Lexing.position -> (Parsetree.structure) MenhirInterpreter.checkpoint
end
|
e61b2962c68547dc2b3a45e319043495dcdfaf591b6fa29c610949f1d28992b4 | korya/efuns | manyargs.ml | let manyargs a b c d e f g h i j k =
print_string "a = "; print_int a; print_newline();
print_string "b = "; print_int b; print_newline();
print_string "c = "; print_int c; print_newline();
print_string "d = "; print_int d; print_newline();
print_string "e = "; print_int e; print_newline();
print_string "f = "; print_int f; print_newline();
print_string "g = "; print_int g; print_newline();
print_string "h = "; print_int h; print_newline();
print_string "i = "; print_int i; print_newline();
print_string "j = "; print_int j; print_newline();
print_string "k = "; print_int k; print_newline()
let _ = manyargs 1 2 3 4 5 6 7 8 9 10 11
external manyargs_ext: int -> int -> int -> int -> int -> int -> int -> int -> int -> int -> int -> int = "manyargs_argv" "manyargs"
let _ = manyargs_ext 1 2 3 4 5 6 7 8 9 10 11
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/inliner/perf/Moretest/manyargs.ml | ocaml | let manyargs a b c d e f g h i j k =
print_string "a = "; print_int a; print_newline();
print_string "b = "; print_int b; print_newline();
print_string "c = "; print_int c; print_newline();
print_string "d = "; print_int d; print_newline();
print_string "e = "; print_int e; print_newline();
print_string "f = "; print_int f; print_newline();
print_string "g = "; print_int g; print_newline();
print_string "h = "; print_int h; print_newline();
print_string "i = "; print_int i; print_newline();
print_string "j = "; print_int j; print_newline();
print_string "k = "; print_int k; print_newline()
let _ = manyargs 1 2 3 4 5 6 7 8 9 10 11
external manyargs_ext: int -> int -> int -> int -> int -> int -> int -> int -> int -> int -> int -> int = "manyargs_argv" "manyargs"
let _ = manyargs_ext 1 2 3 4 5 6 7 8 9 10 11
| |
ed6fd30f7bf46b29ad7ef0c327f49be2eeb3983891f89f376cdb466e829319ed | carld/compiler-tutorial | compiler.scm | Scheme compiler for x86_64
(load "tests-driver.scm")
(load "tests-1.1-req.scm")
(load "tests-1.2-req.scm")
(load "tests-1.3-req.scm")
(load "tests-1.4-req.scm")
(load "tests-1.5-req.scm")
(load "tests-1.6-req.scm")
(load "tests-1.7-req.scm")
(load "tests-1.8-req.scm")
(load "tests-1.9-req.scm")
The lower bits of a 64 bit machine word contains a Scheme type tag
(define fxshift 2)
(define fxmask #x03)
(define fxtag #x00)
(define wordsize 8)
(define boolmask #b10111111)
(define booltag #b101111)
(define bool-f #x2F) ; #b00101111
# b01101111
(define bool-bit 6)
(define charmask #xFF)
0x0F
(define charshift 8)
(define niltag #b00111111)
(define objshift 3)
(define objmask #b00000111)
(define pairtag #b00000001)
(define clotag #b00000010)
(define symtag #b00000011)
(define vectag #b00000101)
(define strtag #b00000110)
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (sub1 (expt 2 (- fixnum-bits 1))))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
(define (variable? x)
(symbol? x))
; Encode an immediate value in a machine word with a type tag
(define (immediate-rep x)
(cond
[(fixnum? x) (ash x fxshift)]
[(boolean? x) (if (equal? x #t) bool-t bool-f)]
[(char? x) (logor (ash (char->integer x) charshift) chartag)]
[(null? x) niltag]
[else (errorf 'immediate-rep "no immediate representation for ~s" x)]))
; Declare a global symbol with properties describing it as a code generator
; for a primitive operation.
(define-syntax define-primitive
(syntax-rules ()
[(_ (prim-name si env arg* ...) b b* ...)
(begin
(putprop 'prim-name '*is-prim* #t)
(putprop 'prim-name '*arg-count*
(length '(arg* ...)))
(putprop 'prim-name '*emitter*
(lambda (si env arg* ...) b b* ...)))]
; The *emitter* has no (lambda (si env arg* ...) )
; to allow a case-lambda *emitter* enabling variadic emitters
[(_ (prim-name) b b* ...)
(begin
(putprop 'prim-name '*is-prim* #t)
(putprop 'prim-name '*arg-count* #f)
(putprop 'prim-name '*emitter*
b b* ...))]))
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prim*)))
(define (list-starts-with-any? expr val)
(and (list? expr) (< 0 (length expr)) (memq (car expr) val)))
; Defines procedures that check for a specific symbol at the head of the list.
(define-syntax define-list-head-predicate
(syntax-rules ()
[(_ (predicate sym* ...))
(define (predicate expr)
(list-starts-with-any? expr (list sym* ...)))]))
(define-list-head-predicate (if? 'if))
(define-list-head-predicate (and? 'and))
(define-list-head-predicate (or? 'or))
(define-list-head-predicate (or? 'or))
(define-list-head-predicate (let? 'let 'let*))
(define-list-head-predicate (letrec? 'letrec ))
(define-list-head-predicate (begin? 'begin))
(define (primitive-emitter x)
(or (getprop x '*emitter*) (error 'primitive-emitter "missing emitter for" x)))
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (check-primcall-args prim args)
(equal? (length args) (getprop prim '*arg-count*)))
; Emits assembly for a primitive.
(define (emit-primcall si env expr tail?)
(let ([prim (car expr)] [args (cdr expr)])
(check-primcall-args prim args) ; TODO: this should error when arg count does not match, what about variadic though?
(apply (primitive-emitter prim) si env args)
(if tail? (emit " ret"))))
; Generate assembly that places an immediate value in the return register, rax.
; If this code is in tail position, return to the caller.
(define (emit-immediate expr tail?)
(emit " mov rax, ~s; immediate" (immediate-rep expr))
(if tail? (emit " ret")))
(define let-bindings cadr)
(define let-body cddr)
(define (empty? x)
(and (list? x) (= 0 (length x))))
(define first car)
(define rest cdr)
(define rhs cadr)
(define lhs car)
; Store the current expression held in rax, on the stack at the given index.
(define (emit-stack-save si)
(emit " mov [rsp + ~s], rax; emit-stack-save" si))
Get the next stack index , a machine word ( 8 bytes ) below the stack index argument .
(define (next-stack-index si)
(- si wordsize))
; Push the variable name and it's stack index onto the environment.
(define (extend-env var si env)
(cons (cons var si) env))
; Emit a let or let* expression.
This emits all of the bindings first , storing them on the stack before
; emitting the let body.
(define (emit-let si env expr tail?)
(define (process-let bindings si new-env)
(cond
[(empty? bindings)
; If a let expression is in tail position, then the body of the let is in
; tail position.
(emit-expr si new-env (cons 'begin (let-body expr)) tail?)]
[else
; Emit assembly for evaluating the next let binding
(let ([b (first bindings)])
(emit-expr si (if (equal? (car expr) 'let*) new-env env) (rhs b) #f)
(emit-stack-save si)
(process-let (rest bindings)
(next-stack-index si)
(extend-env (lhs b) si new-env)))]))
(process-let (let-bindings expr) si env))
; Returns the value from an association list, or false.
(define (lookup var alist)
(let ((val (assoc var alist)))
(if (pair? val) (cdr val) #f)))
; Emit assembly for loading value from stack into rax register.
(define (emit-stack-load si tail?)
(emit " mov rax, [rsp + ~s]; load from stack" si)
(if tail? (emit " ret")))
; Look up the expression in the environment and emit code that loads the
; value from the stack using the index.
(define (emit-variable-ref env expr tail?)
(let ([si (lookup expr env)])
(cond
[si (emit-stack-load si tail?)]
[else (error 'emit-variable-ref "could not find variable" var)])))
(define if-test cadr)
(define if-conseq caddr)
(define if-altern cadddr)
; Generate the assembly code for an if expression.
(define (emit-if si env expr tail?)
(let ([alt-label (unique-label)]
[end-label (unique-label)])
(emit-expr si env (if-test expr) #f) ; never in tail position
(emit " cmp al, ~s; false?" bool-f)
(emit " je ~a; jump to else" alt-label)
(emit-expr si env (if-conseq expr) tail?)
(unless tail? (emit " jmp ~a; jump to end" end-label))
(emit "~a:" alt-label)
(emit-expr si env (if-altern expr) tail?)
(unless tail? (emit "~a:" end-label))))
; Transform a cond expression into a nested if expression.
(define (transform-cond expr)
(let next-cond ([rem (cdr expr)])
(unless (null? rem)
`(if ,(caar rem) ,(cadar rem)
,(next-cond (cdr rem))))))
; Transform an and expression into a nested if expression.
; (and a b ...)
; (if a (if b #t #f) #f)
(define (transform-and expr)
(let conseq ([i (cdr expr)])
(if (null? i)
#t
`(if ,(car i) ,(conseq (cdr i)) #f))))
; Transform an or expression into a nested if expression.
; (or a b ...)
; (if a #t (if b #t #f) #f)
(define (transform-or expr)
(let altern ([i (cdr expr)])
(if (null? i)
#f
`(if ,(car i) #t ,(altern (cdr i))))))
; Generate a unique label for each var in the list
(define (unique-labels lvars)
(map (lambda (lvar)
(format "~a_~a" (unique-label) lvar)) lvars))
(define letrec-bindings let-bindings)
(define letrec-body let-body)
; Create an initial association list
(define (make-initial-env lvars labels)
(map cons lvars labels))
; Generate the assembly code prelude for the compiled scheme expression.
(define (emit-scheme-entry expr env)
(emit-function-header "L_scheme_entry" )
(emit-expr (- wordsize) env expr #f)
(emit " ret"))
; Emit a letrec expression
for now is only at the top of the stack ?
(define (emit-letrec expr)
(let* ([bindings (letrec-bindings expr)]
[lvars (map lhs bindings)]
[lambdas (map rhs bindings)]
[labels (unique-labels lvars)]
[env (make-initial-env lvars labels)])
(for-each (emit-lambda env) lambdas labels)
(emit-scheme-entry (cons 'begin (letrec-body expr)) env)))
(define lambda-formals cadr)
(define lambda-body caddr)
; Emit code that evaluates arguments passed to a lambda and then emits code
; that evaluates the lambda body.
(define (emit-lambda env)
(lambda (expr label)
(emit-function-header label)
(let ([fmls (lambda-formals expr)]
[body (lambda-body expr)]) ; The body of a procedure is in tail position.
(let f ([fmls fmls] [si (- wordsize)] [env env])
(cond
[(empty? fmls) ; emit expression
(emit-expr si env body 'tail-position)]
[else ; move stack index downwards to accomodate argument,
; and add stack index to environment
(f (rest fmls)
(next-stack-index si)
(extend-env (first fmls) si env))])))))
; Emit code that adds (or subtracts) the size of a machine word to or from the
; stack index.
(define (emit-adjust-base si)
(cond
[(> 0 si) (emit " sub rsp, ~s; adjust base" (- si))]
[(< 0 si) (emit " add rsp, ~s; adjust base" si)]))
(define call-target car)
(define call-args cdr)
; Emit assembly for a procedure call
(define (emit-call label tail?)
(if tail?
(emit " jmp ~a; tail call" label)
(emit " call ~a" label)))
; Emit evaluation of arguments and call a procedure
(define (emit-app si env expr tail?)
(define (emit-arguments si args)
(unless (empty? args)
(emit-expr si env (first args) #f)
(emit-stack-save si)
(emit-arguments (next-stack-index si) (rest args))))
; moves arguments on stack adjacent to rsp, overwriting any local variables.
(define (emit-move offset si args)
(unless (empty? args)
(emit " mov rax, [rsp + ~s]" si)
(emit " mov [rsp + ~s], rax; move arg ~s" (- si offset) (car args))
(emit-move offset (next-stack-index si) (rest args))))
(if tail?
(begin
(emit-arguments si (call-args expr)) ; evaluates args
(if (< si (- wordsize)) ; if the stack index is below the return address
(emit-move (- si (- wordsize)) si (call-args expr))) ;collapse frame
(emit-call (lookup (call-target expr) env) 'tail-position))
(begin
(emit-arguments (- si wordsize) (call-args expr))
(emit-adjust-base (+ si wordsize))
(emit-call (lookup (call-target expr) env) #f)
(emit-adjust-base (- (+ si wordsize))))))
; Determine apply, either when the expression starts with app, or the
; expression starts with a symbol that is in the environment.
; Note :- revisit this when implementing closures?
(define (app? expr env)
(cond
[(list-starts-with-any? expr '(app)) #t]
[(lookup (car expr) env) #t]
[else #f]))
; Remove the app symbol from the head of a list.
(define (chomp-app expr)
(cond
[(list-starts-with-any? expr '(app)) (cdr expr)]
[else expr]))
; Loop through each expression following begin and emit the code for each.
(define (emit-begin si env expr tail?)
(for-each (lambda(e)
(emit-expr si env e tail?)) (cdr expr)))
; Emit assembly code based on the form of the given expression.
(define (emit-expr si env expr tail?)
(cond
[(immediate? expr) (emit-immediate expr tail?)]
[(variable? expr) (emit-variable-ref env expr tail?)] ; gets si from env
[(if? expr) (emit-if si env expr tail?)]
[(and? expr) (emit-if si env (transform-and expr) tail?)]
[(or? expr) (emit-if si env (transform-or expr) tail?)]
[(let? expr) (emit-let si env expr tail?)]
[(begin? expr) (emit-begin si env expr tail?)]
[(primcall? expr) (emit-primcall si env expr tail?)]
[(app? expr env) (emit-app si env (chomp-app expr) tail?)] ; primitives shadow environment?
[else (error 'emit-expr "error in expression" expr)]))
; Emit the entry point for the compiled scheme code.
The emitted code preserves registers according to the System V ABI .
(define (emit-program expr)
(if (letrec? expr)
(emit-letrec expr)
(emit-scheme-entry expr '()))
(emit-function-header (or (getenv "ENTRY") "_scheme_entry")) ;"scheme_entry")
parameters in rdi , rsi , rdx , rcx , r8 , r9 , then stack right to left
; preserve registers rbx, rsp, rbp, r12, r13, r14, r15
(emit " mov rcx, rdi; store context pointer in rdx") ; allocated context argument
(emit " mov [rcx + 8], rbx")
(emit " mov [rcx + 48], rsp")
(emit " mov [rcx + 56], rbp")
(emit " mov [rcx + 96], r12")
(emit " mov [rcx + 104], r13")
(emit " mov [rcx + 112], r14")
(emit " mov [rcx + 120], r15")
(emit " mov rsp, rsi") ; allocated stack base argument, calling convention puts it in rdi ...
(emit " mov rbp, rdx") ; allocated heap base argument,
push rip to rsp and
(emit " mov rbx, [rcx + 8]")
(emit " mov rsp, [rcx + 48]")
(emit " mov rbp, [rcx + 56]")
(emit " mov r12, [rcx + 96]")
(emit " mov r13, [rcx + 104]")
(emit " mov r14, [rcx + 112]")
(emit " mov r15, [rcx + 120]")
(emit " ret")) ; pop rsp and jump
; Export and declare a label in the emitted assembly code.
(define (emit-function-header name)
(emit "global ~a" name)
(emit "~a:" name))
Defines procedures that emit primitives of one argument .
(define-syntax define-primitive-unary
(syntax-rules ()
[(_ (name) b ...)
(define-primitive (name si env arg)
(emit-expr si env arg #f)
b ... )]))
; Add one to the fixnum value held in the rax register.
(define-primitive-unary (fxadd1)
(emit " add rax, ~s" (immediate-rep 1))) ; add x, y x ← x + y
Subtract one from the fixnum value held in the rax register .
(define-primitive-unary (fxsub1)
(emit " sub rax, ~s" (immediate-rep 1)))
; Convert the fixnum to a tagged character.
(define-primitive-unary (fixnum->char)
shift left 8 - 2 = 6 bits
or 00001111
; Convert the character to a tagged fixnum.
(define-primitive-unary (char->fixnum)
(emit " shr rax, ~s" (- charshift fxshift))
(emit " and rax, ~s" (lognot fxmask)))
Pairs are tagged using the first bit , 0x01 ,
; subtracting one, results in a pointer to the car, implicitly untagging.
(define-primitive (car si env arg)
(emit " mov rax, [ rax - 1 ]; car"))
Pairs are tagged using the first bit , 0x01 ,
adding 7 results in a pointer to the cdr , implicity untagging .
(define-primitive (cdr si env arg)
(emit " mov rax, [ rax + 7 ]; cdr"))
; Sets the car of a pair.
(define-primitive (set-car! si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " mov [ rax - 1 ], rbx")) ; untag (pairtag is 1), and set car
; Sets the cdr of a pair.
(define-primitive (set-cdr! si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
untag and offset , and set cdr
; Emits code that will allocate a new pair on the heap,
; and move the heap pointer, stored in register rbp.
(define-primitive (cons si env arg1 arg2)
(emit-expr si env arg1 #f)
(emit " mov [ rbp + 0 ], rax")
(emit-expr si env arg2 #f)
(emit " mov [ rbp + 8 ], rax")
(emit " mov rax, rbp")
(emit " or rax, ~s" pairtag)
(emit " add rbp, 16"))
Emits code that will set the al ( low 8 bits of rax ) register to 1 based on
; the given operator argument and the flags state after a cmp
(define (emit-true-using set-byte-on-condition)
set equal : set to 1 otherwise 0 on condition ( ZF=0 )
(emit " movsx rax, al")
(emit " sal al, ~s" bool-bit)
(emit " or al, ~s" bool-f))
; Defines a procedure that determines whether it's argument is of a specific type
; and leaves true in the rax register if so.
(define-syntax define-primitive-predicate
(syntax-rules ()
[(_ (name tag-or-value) b ...)
(define-primitive (name si env arg)
(emit-expr si env arg #f)
b ...
(emit " cmp rax, ~s" tag-or-value)
(emit-true-using 'sete))]
[(_ (name tag-or-value mask))
(define-primitive-predicate (name tag-or-value)
(emit " and rax, ~s" mask))]))
(define-primitive-predicate (fxzero? 0))
(define-primitive-predicate (fixnum? fxtag fxmask))
(define-primitive-predicate (pair? pairtag objmask))
(define-primitive-predicate (null? niltag))
(define-primitive-predicate (boolean? bool-f boolmask))
(define-primitive-predicate (char? chartag charmask))
(define-primitive-predicate (vector? vectag objmask))
(define-primitive-predicate (string? strtag objmask))
The primitive not takes any kind of value and returns # t if the object is # f ,
otherwise it returns # f.
(define-primitive (not si env arg)
(emit-expr si env arg #f)
(emit " cmp rax, ~s" bool-f)
(emit-true-using 'sete))
; Returns a string containing a unique label and increments an internal counter.
(define unique-label
(let ([count 0])
(lambda ()
(let ([L (format "L_~s" count)])
(set! count (add1 count))
L))))
Emits code that adds it 's two fixnum expressions and leaves the result in
; the rax register.
(define-primitive (fx+ si env arg1 arg2)
(emit-expr si env arg1 #f)
(emit " mov [rsp + ~s], rax; put on stack" si)
(emit-expr (next-stack-index si) env arg2 #f)
(emit " add rax, [rsp + ~s]; add stack and rax" si))
Emits code that adds two fixnums and puts the result in the rax register .
(define-primitive (fx- si env arg1 arg2)
(emit-expr si env arg2 #f) ; rax <- arg1
(emit " mov [rsp + ~s], rax" si)
(emit-expr (next-stack-index si) env arg1 #f)
(emit " sub rax, [rsp + ~s]" si))
Emits code that multiplies two fixnums and puts the result in the rax
; register.
(define-primitive (fx* si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " imul ebx") ; eax * ebx
(emit " mov ebx, 4")
(emit " idiv ebx")) ; eax / ebx
Emits code that evaluates two expressions , saves them to the stack from the
given stack index , and also stores the results in the two register arguments .
(define (emit-exprs-load si env arg1 arg2 register1 register2)
(emit-expr si env arg1 #f)
(emit-stack-save si)
(emit-expr (next-stack-index si) env arg2 #f)
(emit-stack-save (next-stack-index si))
(emit " mov ~s, [rsp + ~s]" register1 si) ; (emit-stack-load si)
(emit " mov ~s, [rsp + ~s]" register2 (next-stack-index si))) ; (emit-stack-load (- si wordsize))
Emits code that performs a logical or on it 's two arguments .
(define-primitive (fxlogor si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " or rax, rbx"))
; Emits code that performs a logical not on it's fixnum argument and leaves
; the result in the rax register.
(define-primitive-unary (fxlognot)
(emit " shr rax, ~s" fxshift)
(emit " not rax")
(emit " shl rax, ~s" fxshift))
; Emits code that does a logical and on it's fixnum arguments and leaves the
; result in the rax register.
(define-primitive (fxlogand si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " and rax, rbx"))
Defines a procedure that will evaluate it 's two arguments using the provided
; comparison operator.
(define-syntax define-primitive-compare
(syntax-rules ()
[(_ (prim-name operator-instruction))
(define-primitive (prim-name si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " cmp rax, rbx" )
(emit-true-using operator-instruction))]))
(define-primitive-compare (fx= 'sete))
(define-primitive-compare (fx< 'setl))
(define-primitive-compare (fx<= 'setle))
(define-primitive-compare (fx> 'setg))
(define-primitive-compare (fx>= 'setge))
(define-primitive-compare (eq? 'sete))
(define-primitive-compare (char= 'sete))
(define-syntax define-make-vector-of-type
(syntax-rules ()
[(_ (emitter-name type))
(define-primitive (emitter-name)
(case-lambda
[(si env len)
(apply (primitive-emitter 'emitter-name) si env (list len #f))]
[(si env len val)
(let ([label (unique-label)])
(emit-expr si env len #f)
untag length
multiply by 8
(emit " mov [ rbp ], rax") ; set vector length
(emit-expr si env val #f)
(emit " mov rbx, rax") ;
(emit " mov rdi, 8; offset")
(emit "~a:" label)
(emit " mov [ rbp + rdi ], rbx")
(emit " add rdi, 8")
(emit " cmp rdi, [ rbp ]")
(emit " jle ~a" label)
(emit " mov rax, rbp")
(emit " or rax, ~s" type )
(emit " add rbp, rdi"))])) ]))
(define-make-vector-of-type (make-vector vectag))
(define-make-vector-of-type (make-string strtag))
(define-primitive (vector-length si env arg)
(emit-expr si env arg #f)
; assuming rax is actually a vector
untag
untag
(emit " mov rax, [rax]")
divide by 8
(emit " sal rax, ~s" fxshift)
(emit " or rax, ~s" fxtag))
(define-primitive (string-length)
(getprop 'vector-length '*emitter*))
(define-primitive (vector-set! si env v index value)
(emit-expr si env value #f)
(emit " mov rdx, rax")
(emit-expr si env index #f)
(emit " mov rbx, rax")
untag index
multiply index by 8
(emit " add rbx, 8"); offset index past length
(emit-expr si env v #f)
untag vector
untag vector
(emit " mov [ rax + rbx ], rdx"))
(define-primitive (string-set!)
(getprop 'vector-set! '*emitter*))
(define-primitive (vector-ref si env v index)
(emit-exprs-load si env v index 'rbx 'rdx)
untag vector
untag vector
untag index
multiply index by 8
(emit " add rdx, 8"); offset index past length
(emit " mov rax, [ rbx + rdx ]"))
(define-primitive (string-ref)
(getprop 'vector-ref '*emitter*))
| null | https://raw.githubusercontent.com/carld/compiler-tutorial/4b5d275336cadcccd8e4d4752c0646d655402b1f/compiler.scm | scheme | #b00101111
Encode an immediate value in a machine word with a type tag
Declare a global symbol with properties describing it as a code generator
for a primitive operation.
The *emitter* has no (lambda (si env arg* ...) )
to allow a case-lambda *emitter* enabling variadic emitters
Defines procedures that check for a specific symbol at the head of the list.
Emits assembly for a primitive.
TODO: this should error when arg count does not match, what about variadic though?
Generate assembly that places an immediate value in the return register, rax.
If this code is in tail position, return to the caller.
Store the current expression held in rax, on the stack at the given index.
Push the variable name and it's stack index onto the environment.
Emit a let or let* expression.
emitting the let body.
If a let expression is in tail position, then the body of the let is in
tail position.
Emit assembly for evaluating the next let binding
Returns the value from an association list, or false.
Emit assembly for loading value from stack into rax register.
Look up the expression in the environment and emit code that loads the
value from the stack using the index.
Generate the assembly code for an if expression.
never in tail position
Transform a cond expression into a nested if expression.
Transform an and expression into a nested if expression.
(and a b ...)
(if a (if b #t #f) #f)
Transform an or expression into a nested if expression.
(or a b ...)
(if a #t (if b #t #f) #f)
Generate a unique label for each var in the list
Create an initial association list
Generate the assembly code prelude for the compiled scheme expression.
Emit a letrec expression
Emit code that evaluates arguments passed to a lambda and then emits code
that evaluates the lambda body.
The body of a procedure is in tail position.
emit expression
move stack index downwards to accomodate argument,
and add stack index to environment
Emit code that adds (or subtracts) the size of a machine word to or from the
stack index.
Emit assembly for a procedure call
Emit evaluation of arguments and call a procedure
moves arguments on stack adjacent to rsp, overwriting any local variables.
evaluates args
if the stack index is below the return address
collapse frame
Determine apply, either when the expression starts with app, or the
expression starts with a symbol that is in the environment.
Note :- revisit this when implementing closures?
Remove the app symbol from the head of a list.
Loop through each expression following begin and emit the code for each.
Emit assembly code based on the form of the given expression.
gets si from env
primitives shadow environment?
Emit the entry point for the compiled scheme code.
"scheme_entry")
preserve registers rbx, rsp, rbp, r12, r13, r14, r15
allocated context argument
allocated stack base argument, calling convention puts it in rdi ...
allocated heap base argument,
pop rsp and jump
Export and declare a label in the emitted assembly code.
Add one to the fixnum value held in the rax register.
add x, y x ← x + y
Convert the fixnum to a tagged character.
Convert the character to a tagged fixnum.
subtracting one, results in a pointer to the car, implicitly untagging.
Sets the car of a pair.
untag (pairtag is 1), and set car
Sets the cdr of a pair.
Emits code that will allocate a new pair on the heap,
and move the heap pointer, stored in register rbp.
the given operator argument and the flags state after a cmp
Defines a procedure that determines whether it's argument is of a specific type
and leaves true in the rax register if so.
Returns a string containing a unique label and increments an internal counter.
the rax register.
rax <- arg1
register.
eax * ebx
eax / ebx
(emit-stack-load si)
(emit-stack-load (- si wordsize))
Emits code that performs a logical not on it's fixnum argument and leaves
the result in the rax register.
Emits code that does a logical and on it's fixnum arguments and leaves the
result in the rax register.
comparison operator.
set vector length
assuming rax is actually a vector
offset index past length
offset index past length | Scheme compiler for x86_64
(load "tests-driver.scm")
(load "tests-1.1-req.scm")
(load "tests-1.2-req.scm")
(load "tests-1.3-req.scm")
(load "tests-1.4-req.scm")
(load "tests-1.5-req.scm")
(load "tests-1.6-req.scm")
(load "tests-1.7-req.scm")
(load "tests-1.8-req.scm")
(load "tests-1.9-req.scm")
The lower bits of a 64 bit machine word contains a Scheme type tag
(define fxshift 2)
(define fxmask #x03)
(define fxtag #x00)
(define wordsize 8)
(define boolmask #b10111111)
(define booltag #b101111)
# b01101111
(define bool-bit 6)
(define charmask #xFF)
0x0F
(define charshift 8)
(define niltag #b00111111)
(define objshift 3)
(define objmask #b00000111)
(define pairtag #b00000001)
(define clotag #b00000010)
(define symtag #b00000011)
(define vectag #b00000101)
(define strtag #b00000110)
(define fixnum-bits (- (* wordsize 8) fxshift))
(define fxlower (- (expt 2 (- fixnum-bits 1))))
(define fxupper (sub1 (expt 2 (- fixnum-bits 1))))
(define (fixnum? x)
(and (integer? x) (exact? x) (<= fxlower x fxupper)))
(define (immediate? x)
(or (fixnum? x) (boolean? x) (char? x) (null? x)))
(define (variable? x)
(symbol? x))
(define (immediate-rep x)
(cond
[(fixnum? x) (ash x fxshift)]
[(boolean? x) (if (equal? x #t) bool-t bool-f)]
[(char? x) (logor (ash (char->integer x) charshift) chartag)]
[(null? x) niltag]
[else (errorf 'immediate-rep "no immediate representation for ~s" x)]))
(define-syntax define-primitive
(syntax-rules ()
[(_ (prim-name si env arg* ...) b b* ...)
(begin
(putprop 'prim-name '*is-prim* #t)
(putprop 'prim-name '*arg-count*
(length '(arg* ...)))
(putprop 'prim-name '*emitter*
(lambda (si env arg* ...) b b* ...)))]
[(_ (prim-name) b b* ...)
(begin
(putprop 'prim-name '*is-prim* #t)
(putprop 'prim-name '*arg-count* #f)
(putprop 'prim-name '*emitter*
b b* ...))]))
(define (primitive? x)
(and (symbol? x) (getprop x '*is-prim*)))
(define (list-starts-with-any? expr val)
(and (list? expr) (< 0 (length expr)) (memq (car expr) val)))
(define-syntax define-list-head-predicate
(syntax-rules ()
[(_ (predicate sym* ...))
(define (predicate expr)
(list-starts-with-any? expr (list sym* ...)))]))
(define-list-head-predicate (if? 'if))
(define-list-head-predicate (and? 'and))
(define-list-head-predicate (or? 'or))
(define-list-head-predicate (or? 'or))
(define-list-head-predicate (let? 'let 'let*))
(define-list-head-predicate (letrec? 'letrec ))
(define-list-head-predicate (begin? 'begin))
(define (primitive-emitter x)
(or (getprop x '*emitter*) (error 'primitive-emitter "missing emitter for" x)))
(define (primcall? expr)
(and (pair? expr) (primitive? (car expr))))
(define (check-primcall-args prim args)
(equal? (length args) (getprop prim '*arg-count*)))
(define (emit-primcall si env expr tail?)
(let ([prim (car expr)] [args (cdr expr)])
(apply (primitive-emitter prim) si env args)
(if tail? (emit " ret"))))
(define (emit-immediate expr tail?)
(emit " mov rax, ~s; immediate" (immediate-rep expr))
(if tail? (emit " ret")))
(define let-bindings cadr)
(define let-body cddr)
(define (empty? x)
(and (list? x) (= 0 (length x))))
(define first car)
(define rest cdr)
(define rhs cadr)
(define lhs car)
(define (emit-stack-save si)
(emit " mov [rsp + ~s], rax; emit-stack-save" si))
Get the next stack index , a machine word ( 8 bytes ) below the stack index argument .
(define (next-stack-index si)
(- si wordsize))
(define (extend-env var si env)
(cons (cons var si) env))
This emits all of the bindings first , storing them on the stack before
(define (emit-let si env expr tail?)
(define (process-let bindings si new-env)
(cond
[(empty? bindings)
(emit-expr si new-env (cons 'begin (let-body expr)) tail?)]
[else
(let ([b (first bindings)])
(emit-expr si (if (equal? (car expr) 'let*) new-env env) (rhs b) #f)
(emit-stack-save si)
(process-let (rest bindings)
(next-stack-index si)
(extend-env (lhs b) si new-env)))]))
(process-let (let-bindings expr) si env))
(define (lookup var alist)
(let ((val (assoc var alist)))
(if (pair? val) (cdr val) #f)))
(define (emit-stack-load si tail?)
(emit " mov rax, [rsp + ~s]; load from stack" si)
(if tail? (emit " ret")))
(define (emit-variable-ref env expr tail?)
(let ([si (lookup expr env)])
(cond
[si (emit-stack-load si tail?)]
[else (error 'emit-variable-ref "could not find variable" var)])))
(define if-test cadr)
(define if-conseq caddr)
(define if-altern cadddr)
(define (emit-if si env expr tail?)
(let ([alt-label (unique-label)]
[end-label (unique-label)])
(emit " cmp al, ~s; false?" bool-f)
(emit " je ~a; jump to else" alt-label)
(emit-expr si env (if-conseq expr) tail?)
(unless tail? (emit " jmp ~a; jump to end" end-label))
(emit "~a:" alt-label)
(emit-expr si env (if-altern expr) tail?)
(unless tail? (emit "~a:" end-label))))
(define (transform-cond expr)
(let next-cond ([rem (cdr expr)])
(unless (null? rem)
`(if ,(caar rem) ,(cadar rem)
,(next-cond (cdr rem))))))
(define (transform-and expr)
(let conseq ([i (cdr expr)])
(if (null? i)
#t
`(if ,(car i) ,(conseq (cdr i)) #f))))
(define (transform-or expr)
(let altern ([i (cdr expr)])
(if (null? i)
#f
`(if ,(car i) #t ,(altern (cdr i))))))
(define (unique-labels lvars)
(map (lambda (lvar)
(format "~a_~a" (unique-label) lvar)) lvars))
(define letrec-bindings let-bindings)
(define letrec-body let-body)
(define (make-initial-env lvars labels)
(map cons lvars labels))
(define (emit-scheme-entry expr env)
(emit-function-header "L_scheme_entry" )
(emit-expr (- wordsize) env expr #f)
(emit " ret"))
for now is only at the top of the stack ?
(define (emit-letrec expr)
(let* ([bindings (letrec-bindings expr)]
[lvars (map lhs bindings)]
[lambdas (map rhs bindings)]
[labels (unique-labels lvars)]
[env (make-initial-env lvars labels)])
(for-each (emit-lambda env) lambdas labels)
(emit-scheme-entry (cons 'begin (letrec-body expr)) env)))
(define lambda-formals cadr)
(define lambda-body caddr)
(define (emit-lambda env)
(lambda (expr label)
(emit-function-header label)
(let ([fmls (lambda-formals expr)]
(let f ([fmls fmls] [si (- wordsize)] [env env])
(cond
(emit-expr si env body 'tail-position)]
(f (rest fmls)
(next-stack-index si)
(extend-env (first fmls) si env))])))))
(define (emit-adjust-base si)
(cond
[(> 0 si) (emit " sub rsp, ~s; adjust base" (- si))]
[(< 0 si) (emit " add rsp, ~s; adjust base" si)]))
(define call-target car)
(define call-args cdr)
(define (emit-call label tail?)
(if tail?
(emit " jmp ~a; tail call" label)
(emit " call ~a" label)))
(define (emit-app si env expr tail?)
(define (emit-arguments si args)
(unless (empty? args)
(emit-expr si env (first args) #f)
(emit-stack-save si)
(emit-arguments (next-stack-index si) (rest args))))
(define (emit-move offset si args)
(unless (empty? args)
(emit " mov rax, [rsp + ~s]" si)
(emit " mov [rsp + ~s], rax; move arg ~s" (- si offset) (car args))
(emit-move offset (next-stack-index si) (rest args))))
(if tail?
(begin
(emit-call (lookup (call-target expr) env) 'tail-position))
(begin
(emit-arguments (- si wordsize) (call-args expr))
(emit-adjust-base (+ si wordsize))
(emit-call (lookup (call-target expr) env) #f)
(emit-adjust-base (- (+ si wordsize))))))
(define (app? expr env)
(cond
[(list-starts-with-any? expr '(app)) #t]
[(lookup (car expr) env) #t]
[else #f]))
(define (chomp-app expr)
(cond
[(list-starts-with-any? expr '(app)) (cdr expr)]
[else expr]))
(define (emit-begin si env expr tail?)
(for-each (lambda(e)
(emit-expr si env e tail?)) (cdr expr)))
(define (emit-expr si env expr tail?)
(cond
[(immediate? expr) (emit-immediate expr tail?)]
[(if? expr) (emit-if si env expr tail?)]
[(and? expr) (emit-if si env (transform-and expr) tail?)]
[(or? expr) (emit-if si env (transform-or expr) tail?)]
[(let? expr) (emit-let si env expr tail?)]
[(begin? expr) (emit-begin si env expr tail?)]
[(primcall? expr) (emit-primcall si env expr tail?)]
[else (error 'emit-expr "error in expression" expr)]))
The emitted code preserves registers according to the System V ABI .
(define (emit-program expr)
(if (letrec? expr)
(emit-letrec expr)
(emit-scheme-entry expr '()))
parameters in rdi , rsi , rdx , rcx , r8 , r9 , then stack right to left
(emit " mov [rcx + 8], rbx")
(emit " mov [rcx + 48], rsp")
(emit " mov [rcx + 56], rbp")
(emit " mov [rcx + 96], r12")
(emit " mov [rcx + 104], r13")
(emit " mov [rcx + 112], r14")
(emit " mov [rcx + 120], r15")
push rip to rsp and
(emit " mov rbx, [rcx + 8]")
(emit " mov rsp, [rcx + 48]")
(emit " mov rbp, [rcx + 56]")
(emit " mov r12, [rcx + 96]")
(emit " mov r13, [rcx + 104]")
(emit " mov r14, [rcx + 112]")
(emit " mov r15, [rcx + 120]")
(define (emit-function-header name)
(emit "global ~a" name)
(emit "~a:" name))
Defines procedures that emit primitives of one argument .
(define-syntax define-primitive-unary
(syntax-rules ()
[(_ (name) b ...)
(define-primitive (name si env arg)
(emit-expr si env arg #f)
b ... )]))
(define-primitive-unary (fxadd1)
Subtract one from the fixnum value held in the rax register .
(define-primitive-unary (fxsub1)
(emit " sub rax, ~s" (immediate-rep 1)))
(define-primitive-unary (fixnum->char)
shift left 8 - 2 = 6 bits
or 00001111
(define-primitive-unary (char->fixnum)
(emit " shr rax, ~s" (- charshift fxshift))
(emit " and rax, ~s" (lognot fxmask)))
Pairs are tagged using the first bit , 0x01 ,
(define-primitive (car si env arg)
(emit " mov rax, [ rax - 1 ]; car"))
Pairs are tagged using the first bit , 0x01 ,
adding 7 results in a pointer to the cdr , implicity untagging .
(define-primitive (cdr si env arg)
(emit " mov rax, [ rax + 7 ]; cdr"))
(define-primitive (set-car! si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(define-primitive (set-cdr! si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
untag and offset , and set cdr
(define-primitive (cons si env arg1 arg2)
(emit-expr si env arg1 #f)
(emit " mov [ rbp + 0 ], rax")
(emit-expr si env arg2 #f)
(emit " mov [ rbp + 8 ], rax")
(emit " mov rax, rbp")
(emit " or rax, ~s" pairtag)
(emit " add rbp, 16"))
Emits code that will set the al ( low 8 bits of rax ) register to 1 based on
(define (emit-true-using set-byte-on-condition)
set equal : set to 1 otherwise 0 on condition ( ZF=0 )
(emit " movsx rax, al")
(emit " sal al, ~s" bool-bit)
(emit " or al, ~s" bool-f))
(define-syntax define-primitive-predicate
(syntax-rules ()
[(_ (name tag-or-value) b ...)
(define-primitive (name si env arg)
(emit-expr si env arg #f)
b ...
(emit " cmp rax, ~s" tag-or-value)
(emit-true-using 'sete))]
[(_ (name tag-or-value mask))
(define-primitive-predicate (name tag-or-value)
(emit " and rax, ~s" mask))]))
(define-primitive-predicate (fxzero? 0))
(define-primitive-predicate (fixnum? fxtag fxmask))
(define-primitive-predicate (pair? pairtag objmask))
(define-primitive-predicate (null? niltag))
(define-primitive-predicate (boolean? bool-f boolmask))
(define-primitive-predicate (char? chartag charmask))
(define-primitive-predicate (vector? vectag objmask))
(define-primitive-predicate (string? strtag objmask))
The primitive not takes any kind of value and returns # t if the object is # f ,
otherwise it returns # f.
(define-primitive (not si env arg)
(emit-expr si env arg #f)
(emit " cmp rax, ~s" bool-f)
(emit-true-using 'sete))
(define unique-label
(let ([count 0])
(lambda ()
(let ([L (format "L_~s" count)])
(set! count (add1 count))
L))))
Emits code that adds it 's two fixnum expressions and leaves the result in
(define-primitive (fx+ si env arg1 arg2)
(emit-expr si env arg1 #f)
(emit " mov [rsp + ~s], rax; put on stack" si)
(emit-expr (next-stack-index si) env arg2 #f)
(emit " add rax, [rsp + ~s]; add stack and rax" si))
Emits code that adds two fixnums and puts the result in the rax register .
(define-primitive (fx- si env arg1 arg2)
(emit " mov [rsp + ~s], rax" si)
(emit-expr (next-stack-index si) env arg1 #f)
(emit " sub rax, [rsp + ~s]" si))
Emits code that multiplies two fixnums and puts the result in the rax
(define-primitive (fx* si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " mov ebx, 4")
Emits code that evaluates two expressions , saves them to the stack from the
given stack index , and also stores the results in the two register arguments .
(define (emit-exprs-load si env arg1 arg2 register1 register2)
(emit-expr si env arg1 #f)
(emit-stack-save si)
(emit-expr (next-stack-index si) env arg2 #f)
(emit-stack-save (next-stack-index si))
Emits code that performs a logical or on it 's two arguments .
(define-primitive (fxlogor si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " or rax, rbx"))
(define-primitive-unary (fxlognot)
(emit " shr rax, ~s" fxshift)
(emit " not rax")
(emit " shl rax, ~s" fxshift))
(define-primitive (fxlogand si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " and rax, rbx"))
Defines a procedure that will evaluate it 's two arguments using the provided
(define-syntax define-primitive-compare
(syntax-rules ()
[(_ (prim-name operator-instruction))
(define-primitive (prim-name si env arg1 arg2)
(emit-exprs-load si env arg1 arg2 'rax 'rbx)
(emit " cmp rax, rbx" )
(emit-true-using operator-instruction))]))
(define-primitive-compare (fx= 'sete))
(define-primitive-compare (fx< 'setl))
(define-primitive-compare (fx<= 'setle))
(define-primitive-compare (fx> 'setg))
(define-primitive-compare (fx>= 'setge))
(define-primitive-compare (eq? 'sete))
(define-primitive-compare (char= 'sete))
(define-syntax define-make-vector-of-type
(syntax-rules ()
[(_ (emitter-name type))
(define-primitive (emitter-name)
(case-lambda
[(si env len)
(apply (primitive-emitter 'emitter-name) si env (list len #f))]
[(si env len val)
(let ([label (unique-label)])
(emit-expr si env len #f)
untag length
multiply by 8
(emit-expr si env val #f)
(emit " mov rdi, 8; offset")
(emit "~a:" label)
(emit " mov [ rbp + rdi ], rbx")
(emit " add rdi, 8")
(emit " cmp rdi, [ rbp ]")
(emit " jle ~a" label)
(emit " mov rax, rbp")
(emit " or rax, ~s" type )
(emit " add rbp, rdi"))])) ]))
(define-make-vector-of-type (make-vector vectag))
(define-make-vector-of-type (make-string strtag))
(define-primitive (vector-length si env arg)
(emit-expr si env arg #f)
untag
untag
(emit " mov rax, [rax]")
divide by 8
(emit " sal rax, ~s" fxshift)
(emit " or rax, ~s" fxtag))
(define-primitive (string-length)
(getprop 'vector-length '*emitter*))
(define-primitive (vector-set! si env v index value)
(emit-expr si env value #f)
(emit " mov rdx, rax")
(emit-expr si env index #f)
(emit " mov rbx, rax")
untag index
multiply index by 8
(emit-expr si env v #f)
untag vector
untag vector
(emit " mov [ rax + rbx ], rdx"))
(define-primitive (string-set!)
(getprop 'vector-set! '*emitter*))
(define-primitive (vector-ref si env v index)
(emit-exprs-load si env v index 'rbx 'rdx)
untag vector
untag vector
untag index
multiply index by 8
(emit " mov rax, [ rbx + rdx ]"))
(define-primitive (string-ref)
(getprop 'vector-ref '*emitter*))
|
878e3f5e3173e902c075ae2defd2938621ffc855db7f2d51379f6eefdfd40f97 | Simre1/yampa-sdl2 | Colour.hs |
Copyright ( c ) 2008 , 2009
is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE .
Copyright (c) 2008, 2009
Russell O'Connor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-}
-- |Datatypes for representing the human perception of colour.
-- Includes common operations for blending and compositing colours.
-- The most common way of creating colours is either by name
( see " Data . Colour . Names " ) or by giving an sRGB triple
( see " Data . Colour . SRGB " ) .
--
-- Methods of specifying Colours can be found in
--
- " Data . Colour . SRGB "
--
- " Data . Colour . SRGB.Linear "
--
- " Data . Colour . CIE "
--
Colours can be specified in a generic ' Data . Colour . RGBSpace . RGBSpace '
-- by using
--
- " Data . Colour . RGBSpace "
TODO
- " Data . Colour . HDTV "
--
- " Data . Colour . SDTV "
module Data.Colour
(
* Interfacing with Other ' Colour Spaces
--
|Executive summary : Always use " Data . Colour . SRGB " when interfacing with
-- other libraries.
Use ' Data . Colour . SRGB.toSRGB24 ' \/ ' Data . Colour . SRGB.sRGB24 ' when
-- interfacing with libraries wanting 'Data.Word.Word8' per channel.
Use ' Data . Colour . SRGB.toSRGB ' \/ ' Data . Colour . SRGB.sRGB ' when
-- interfacing with libraries wanting 'Double' or 'Float' per channel.
--
Interfacing with the colour for other libraries , such as cairo
-- (</>) and OpenGL
-- (<-bin/hackage-scripts/package/OpenGL>),
-- can be a challenge because these libraries often do not use colour spaces
-- in a consistent way.
-- The problem is that these libraries work in a device dependent colour
-- space and give no indication what the colour space is.
-- For most devices this colours space is implicitly the non-linear sRGB
-- space.
-- However, to make matters worse, these libraries also do their
-- compositing and blending in the device colour space.
-- Blending and compositing ought to be done in a linear colour space,
-- but since the device space is typically non-linear sRGB, these libraries
-- typically produce colour blends that are too dark.
--
( Note that " Data . Colour " is a device /independent/ colour space , and
-- produces correct blends.
e.g. compare @toSRGB ( blend 0.5 lime red)@ with @RGB 0.5 0.5 0@ )
--
-- Because these other colour libraries can only blend in device colour
-- spaces, they are fundamentally broken and there is no \"right\" way
-- to interface with them.
-- For most libraries, the best one can do is assume they are working
-- with an sRGB colour space and doing incorrect blends.
In these cases use " Data . Colour . SRGB " to convert to and from the
colour coordinates . This is the best advice for interfacing with cairo .
--
-- When using OpenGL, the choice is less clear.
-- Again, OpenGL usually does blending in the device colour space.
However , because blending is an important part of proper shading , one
may want to consider that OpenGL is working in a linear colour space ,
-- and the resulting rasters are improperly displayed.
-- This is born out by the fact that OpenGL extensions that support
-- sRGB do so by converting sRGB input\/output to linear colour coordinates
-- for processing by OpenGL.
--
-- The best way to use OpenGL, is to use proper sRGB surfaces for textures
-- and rendering.
These surfaces will automatically convert to and from OpenGL 's linear
-- colour space.
In this case , use " Data . Colour . " to interface OpenGL 's linear
-- colour space.
--
-- If not using proper surfaces with OpenGL, then you have a choice between
-- having OpenGL do improper blending or improper display
-- If you are using OpenGL for 3D shading, I recommend using
" Data . Colour . " ( thus choosing improper OpenGL display ) .
-- If you are not using OpenGL for 3D shading, I recommend using
" Data . Colour . SRGB " ( thus choosing improper OpenGL blending ) .
-- *Colour type
Colour
,colourConvert
,black
,AlphaColour
,opaque, withOpacity
,transparent
,alphaColourConvert
,alphaChannel
,colourChannel
-- *Colour operations
-- |These operations allow combine and modify existing colours
,AffineSpace(..), blend
,ColourOps(..)
,dissolve, atop
)
where
import Data.Char
import Data.Colour.Internal
import qualified Data.Colour.SRGB.Linear
import Data.Colour.CIE.Chromaticity (app_prec, infix_prec)
instance (Fractional a, Show a) => Show (Colour a) where
showsPrec d c = showParen (d > app_prec) showStr
where
showStr = showString linearConstructorQualifiedName
. showString " " . (showsPrec (app_prec+1) r)
. showString " " . (showsPrec (app_prec+1) g)
. showString " " . (showsPrec (app_prec+1) b)
Data.Colour.SRGB.Linear.RGB r g b = Data.Colour.SRGB.Linear.toRGB c
instance (Fractional a, Read a) => Read (Colour a) where
readsPrec d r = readParen (d > app_prec)
(\r -> [(Data.Colour.SRGB.Linear.rgb r0 g0 b0,t)
|(name,s) <- mylex r
,name `elem` [linearConstructorName
,linearConstructorQualifiedName]
,(r0,s0) <- readsPrec (app_prec+1) s
,(g0,s1) <- readsPrec (app_prec+1) s0
,(b0,t) <- readsPrec (app_prec+1) s1]) r
where
mylex = return
. span (\c -> isAlphaNum c || c `elem` "._'")
. dropWhile isSpace
linearConstructorQualifiedName = "Data.Colour.SRGB.Linear.rgb"
linearConstructorName = "rgb"
instance (Fractional a, Show a, Eq a) => Show (AlphaColour a) where
showsPrec d ac | a == 0 = showString "transparent"
| otherwise = showParen (d > infix_prec) showStr
where
showStr = showsPrec (infix_prec+1) c
. showString " `withOpacity` "
. showsPrec (infix_prec+1) a
a = alphaChannel ac
c = colourChannel ac
instance (Fractional a, Read a) => Read (AlphaColour a) where
readsPrec d r = [(transparent,s)|("transparent",s) <- lex r]
++ readParen (d > infix_prec)
(\r -> [(c `withOpacity` o,s)
|(c,r0) <- readsPrec (infix_prec+1) r
,("`",r1) <- lex r0
,("withOpacity",r2) <- lex r1
,("`",r3) <- lex r2
,(o,s) <- readsPrec (infix_prec+1) r3]) r
| null | https://raw.githubusercontent.com/Simre1/yampa-sdl2/c0ad94b9ba50d545f842eaf0916c1acf093514c3/src/Data/Colour.hs | haskell | |Datatypes for representing the human perception of colour.
Includes common operations for blending and compositing colours.
The most common way of creating colours is either by name
Methods of specifying Colours can be found in
by using
other libraries.
interfacing with libraries wanting 'Data.Word.Word8' per channel.
interfacing with libraries wanting 'Double' or 'Float' per channel.
(</>) and OpenGL
(<-bin/hackage-scripts/package/OpenGL>),
can be a challenge because these libraries often do not use colour spaces
in a consistent way.
The problem is that these libraries work in a device dependent colour
space and give no indication what the colour space is.
For most devices this colours space is implicitly the non-linear sRGB
space.
However, to make matters worse, these libraries also do their
compositing and blending in the device colour space.
Blending and compositing ought to be done in a linear colour space,
but since the device space is typically non-linear sRGB, these libraries
typically produce colour blends that are too dark.
produces correct blends.
Because these other colour libraries can only blend in device colour
spaces, they are fundamentally broken and there is no \"right\" way
to interface with them.
For most libraries, the best one can do is assume they are working
with an sRGB colour space and doing incorrect blends.
When using OpenGL, the choice is less clear.
Again, OpenGL usually does blending in the device colour space.
and the resulting rasters are improperly displayed.
This is born out by the fact that OpenGL extensions that support
sRGB do so by converting sRGB input\/output to linear colour coordinates
for processing by OpenGL.
The best way to use OpenGL, is to use proper sRGB surfaces for textures
and rendering.
colour space.
colour space.
If not using proper surfaces with OpenGL, then you have a choice between
having OpenGL do improper blending or improper display
If you are using OpenGL for 3D shading, I recommend using
If you are not using OpenGL for 3D shading, I recommend using
*Colour type
*Colour operations
|These operations allow combine and modify existing colours |
Copyright ( c ) 2008 , 2009
is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE .
Copyright (c) 2008, 2009
Russell O'Connor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-}
( see " Data . Colour . Names " ) or by giving an sRGB triple
( see " Data . Colour . SRGB " ) .
- " Data . Colour . SRGB "
- " Data . Colour . SRGB.Linear "
- " Data . Colour . CIE "
Colours can be specified in a generic ' Data . Colour . RGBSpace . RGBSpace '
- " Data . Colour . RGBSpace "
TODO
- " Data . Colour . HDTV "
- " Data . Colour . SDTV "
module Data.Colour
(
* Interfacing with Other ' Colour Spaces
|Executive summary : Always use " Data . Colour . SRGB " when interfacing with
Use ' Data . Colour . SRGB.toSRGB24 ' \/ ' Data . Colour . SRGB.sRGB24 ' when
Use ' Data . Colour . SRGB.toSRGB ' \/ ' Data . Colour . SRGB.sRGB ' when
Interfacing with the colour for other libraries , such as cairo
( Note that " Data . Colour " is a device /independent/ colour space , and
e.g. compare @toSRGB ( blend 0.5 lime red)@ with @RGB 0.5 0.5 0@ )
In these cases use " Data . Colour . SRGB " to convert to and from the
colour coordinates . This is the best advice for interfacing with cairo .
However , because blending is an important part of proper shading , one
may want to consider that OpenGL is working in a linear colour space ,
These surfaces will automatically convert to and from OpenGL 's linear
In this case , use " Data . Colour . " to interface OpenGL 's linear
" Data . Colour . " ( thus choosing improper OpenGL display ) .
" Data . Colour . SRGB " ( thus choosing improper OpenGL blending ) .
Colour
,colourConvert
,black
,AlphaColour
,opaque, withOpacity
,transparent
,alphaColourConvert
,alphaChannel
,colourChannel
,AffineSpace(..), blend
,ColourOps(..)
,dissolve, atop
)
where
import Data.Char
import Data.Colour.Internal
import qualified Data.Colour.SRGB.Linear
import Data.Colour.CIE.Chromaticity (app_prec, infix_prec)
instance (Fractional a, Show a) => Show (Colour a) where
showsPrec d c = showParen (d > app_prec) showStr
where
showStr = showString linearConstructorQualifiedName
. showString " " . (showsPrec (app_prec+1) r)
. showString " " . (showsPrec (app_prec+1) g)
. showString " " . (showsPrec (app_prec+1) b)
Data.Colour.SRGB.Linear.RGB r g b = Data.Colour.SRGB.Linear.toRGB c
instance (Fractional a, Read a) => Read (Colour a) where
readsPrec d r = readParen (d > app_prec)
(\r -> [(Data.Colour.SRGB.Linear.rgb r0 g0 b0,t)
|(name,s) <- mylex r
,name `elem` [linearConstructorName
,linearConstructorQualifiedName]
,(r0,s0) <- readsPrec (app_prec+1) s
,(g0,s1) <- readsPrec (app_prec+1) s0
,(b0,t) <- readsPrec (app_prec+1) s1]) r
where
mylex = return
. span (\c -> isAlphaNum c || c `elem` "._'")
. dropWhile isSpace
linearConstructorQualifiedName = "Data.Colour.SRGB.Linear.rgb"
linearConstructorName = "rgb"
instance (Fractional a, Show a, Eq a) => Show (AlphaColour a) where
showsPrec d ac | a == 0 = showString "transparent"
| otherwise = showParen (d > infix_prec) showStr
where
showStr = showsPrec (infix_prec+1) c
. showString " `withOpacity` "
. showsPrec (infix_prec+1) a
a = alphaChannel ac
c = colourChannel ac
instance (Fractional a, Read a) => Read (AlphaColour a) where
readsPrec d r = [(transparent,s)|("transparent",s) <- lex r]
++ readParen (d > infix_prec)
(\r -> [(c `withOpacity` o,s)
|(c,r0) <- readsPrec (infix_prec+1) r
,("`",r1) <- lex r0
,("withOpacity",r2) <- lex r1
,("`",r3) <- lex r2
,(o,s) <- readsPrec (infix_prec+1) r3]) r
|
f4ff1a1f908bf69036befcc7cd26f15b7f0c09e07d6618677b7dd2966cadd675 | unisonweb/unison | Pretty.hs | module Unison.Test.Util.Pretty
( test,
)
where
import Control.Monad
import Data.String (fromString)
import EasyTest
import qualified Unison.Util.Pretty as Pretty
test :: Test ()
test =
scope "util.pretty" . tests $
[ scope "Delta.Semigroup.<>.associative" $ do
replicateM_ 100 $ do
d1 <- randomDelta
d2 <- randomDelta
d3 <- randomDelta
expect' $ (d1 <> d2) <> d3 == d1 <> (d2 <> d3)
ok
]
randomDelta :: Test Pretty.Delta
randomDelta =
Pretty.delta <$> randomPretty
where
randomPretty :: Test (Pretty.Pretty String)
randomPretty =
fromString <$> randomString
randomString :: Test String
randomString =
replicateM 3 (pick ['x', 'y', 'z', '\n'])
| null | https://raw.githubusercontent.com/unisonweb/unison/54e96e1e898e7e25f5b0e75e24fd35f9365f6c99/lib/unison-pretty-printer/tests/Unison/Test/Util/Pretty.hs | haskell | module Unison.Test.Util.Pretty
( test,
)
where
import Control.Monad
import Data.String (fromString)
import EasyTest
import qualified Unison.Util.Pretty as Pretty
test :: Test ()
test =
scope "util.pretty" . tests $
[ scope "Delta.Semigroup.<>.associative" $ do
replicateM_ 100 $ do
d1 <- randomDelta
d2 <- randomDelta
d3 <- randomDelta
expect' $ (d1 <> d2) <> d3 == d1 <> (d2 <> d3)
ok
]
randomDelta :: Test Pretty.Delta
randomDelta =
Pretty.delta <$> randomPretty
where
randomPretty :: Test (Pretty.Pretty String)
randomPretty =
fromString <$> randomString
randomString :: Test String
randomString =
replicateM 3 (pick ['x', 'y', 'z', '\n'])
| |
c0b86717bcbd24bf9bb7dc86bb0998cd7e00c3391208ba0de5e3baa8faee526d | tek/ribosome | WindowTest.hs | module Ribosome.Test.WindowTest where
import Polysemy.Test (UnitTest, assertEq, unitTest, (===))
import Test.Tasty (TestTree, testGroup)
import Ribosome.Api.Window (ensureMainWindow)
import Ribosome.Host.Api.Data (Window)
import Ribosome.Host.Api.Data (bufferSetOption, nvimCommand, vimGetCurrentBuffer, vimGetCurrentWindow, vimGetWindows)
import Ribosome.Host.Class.Msgpack.Encode (toMsgpack)
import Ribosome.Host.Effect.Rpc (Rpc)
import Ribosome.Host.Test.Run (embedTest_)
setCurrentNofile ::
Member Rpc r =>
Sem r ()
setCurrentNofile = do
buf <- vimGetCurrentBuffer
bufferSetOption buf "buftype" (toMsgpack ("nofile" :: Text))
createNofile ::
Member Rpc r =>
Sem r Window
createNofile = do
initialWindow <- vimGetCurrentWindow
nvimCommand "new"
setCurrentNofile
pure initialWindow
test_findMainWindowExisting :: UnitTest
test_findMainWindowExisting =
embedTest_ do
initialWindow <- createNofile
(initialWindow ===) =<< ensureMainWindow
test_findMainWindowCreate :: UnitTest
test_findMainWindowCreate =
embedTest_ do
setCurrentNofile
void createNofile
void ensureMainWindow
assertEq 3 . length =<< vimGetWindows
test_window :: TestTree
test_window =
testGroup "window" [
unitTest "find existing" test_findMainWindowExisting,
unitTest "find create" test_findMainWindowCreate
]
| null | https://raw.githubusercontent.com/tek/ribosome/800642404ee8bf6e1d563ad3440d3e191e5be62d/packages/ribosome/test/Ribosome/Test/WindowTest.hs | haskell | module Ribosome.Test.WindowTest where
import Polysemy.Test (UnitTest, assertEq, unitTest, (===))
import Test.Tasty (TestTree, testGroup)
import Ribosome.Api.Window (ensureMainWindow)
import Ribosome.Host.Api.Data (Window)
import Ribosome.Host.Api.Data (bufferSetOption, nvimCommand, vimGetCurrentBuffer, vimGetCurrentWindow, vimGetWindows)
import Ribosome.Host.Class.Msgpack.Encode (toMsgpack)
import Ribosome.Host.Effect.Rpc (Rpc)
import Ribosome.Host.Test.Run (embedTest_)
setCurrentNofile ::
Member Rpc r =>
Sem r ()
setCurrentNofile = do
buf <- vimGetCurrentBuffer
bufferSetOption buf "buftype" (toMsgpack ("nofile" :: Text))
createNofile ::
Member Rpc r =>
Sem r Window
createNofile = do
initialWindow <- vimGetCurrentWindow
nvimCommand "new"
setCurrentNofile
pure initialWindow
test_findMainWindowExisting :: UnitTest
test_findMainWindowExisting =
embedTest_ do
initialWindow <- createNofile
(initialWindow ===) =<< ensureMainWindow
test_findMainWindowCreate :: UnitTest
test_findMainWindowCreate =
embedTest_ do
setCurrentNofile
void createNofile
void ensureMainWindow
assertEq 3 . length =<< vimGetWindows
test_window :: TestTree
test_window =
testGroup "window" [
unitTest "find existing" test_findMainWindowExisting,
unitTest "find create" test_findMainWindowCreate
]
| |
efa5f546c588e85e63f11046c69c6e26364423b348488306c172229ae1947ad0 | discus-lang/ddc | PrimStore.hs |
-- | Construct applications of primitive store operators.
module DDC.Core.Salt.Compounds.PrimStore
( rTop
, ukTop
, xStoreSize, xStoreSize2
, xRead, xWrite
, xPeek, xPoke
, xPeekBounded, xPokeBounded
, xPlusPtr
, xCastPtr
, xGlobal, xGlobali
, typeOfPrimStore)
where
import DDC.Core.Salt.Compounds.Lit
import DDC.Core.Salt.Compounds.PrimTyCon
import DDC.Core.Salt.Name
import DDC.Core.Exp.Annot
import Data.Text (Text)
-- Regions --------------------------------------------------------------------
-- | The top-level region.
-- This region lives for the whole program, and is used to store objects whose
-- types don't have region annotations (like function closures and Unit values).
rTop :: Type Name
rTop = TVar (fst ukTop)
ukTop :: (Bound Name, Kind Name)
ukTop
= ( UName (NameVar "rT")
, kRegion)
| All the Prim Store vars have this form .
xPrimStore a p
= XVar a (UName (NamePrimOp $ PrimStore p))
-- | Take the number of bytes needed to store a value of a primitive type.
xStoreSize :: a -> Type Name -> Exp a Name
xStoreSize a tElem
= xApps a (xPrimStore a PrimStoreSize)
[RType tElem]
-- | Log2 of the number of bytes needed to store a value of primitive type.
xStoreSize2 :: a -> Type Name -> Exp a Name
xStoreSize2 a tElem
= xApps a (xPrimStore a PrimStoreSize2)
[RType tElem]
-- | Read a value from an address plus offset.
xRead :: a -> Type Name -> Exp a Name -> Exp a Name -> Exp a Name
xRead a tField xAddr xOffset
= xApps a (xPrimStore a PrimStoreRead)
[ RType tField, RTerm xAddr, RTerm xOffset ]
-- | Write a value to an address plus offset.
xWrite :: a -> Type Name -> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xWrite a tField xAddr xOffset xVal
= xApps a (xPrimStore a PrimStoreWrite)
[ RType tField, RTerm xAddr, RTerm xOffset, RTerm xVal ]
-- | Peek a value from a buffer pointer plus offset.
xPeek :: a -> Type Name -> Type Name -> Exp a Name -> Exp a Name
xPeek a r t xPtr
= xApps a (xPrimStore a PrimStorePeek)
[ RType r, RType t, RTerm xPtr ]
-- | Poke a value from a buffer pointer plus offset.
xPoke :: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name
xPoke a r t xPtr xVal
= xApps a (xPrimStore a PrimStorePoke)
[ RType r, RType t, RTerm xPtr, RTerm xVal]
-- | Peek a value from a buffer pointer plus offset.
xPeekBounded
:: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xPeekBounded a r t xPtr xOffset xLimit
= xApps a (xPrimStore a PrimStorePeekBounded)
[ RType r, RType t, RTerm xPtr, RTerm xOffset, RTerm xLimit ]
-- | Poke a value from a buffer pointer plus offset.
xPokeBounded
:: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xPokeBounded a r t xPtr xOffset xLimit xVal
= xApps a (xPrimStore a PrimStorePokeBounded)
[ RType r, RType t, RTerm xPtr, RTerm xOffset, RTerm xLimit, RTerm xVal]
-- | Add a byte offset to a pointer.
xPlusPtr :: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name
xPlusPtr a r t xPtr xOffset
= xApps a (xPrimStore a PrimStorePlusPtr)
[ RType r, RType t, RTerm xPtr, RTerm xOffset ]
| Cast a pointer to a different element ype .
xCastPtr :: a -> Type Name -> Type Name -> Type Name -> Exp a Name -> Exp a Name
xCastPtr a r toType fromType xPtr
= xApps a (xPrimStore a PrimStoreCastPtr)
[ RType r, RType toType, RType fromType, RTerm xPtr ]
-- | Reference to a global variable.
xGlobal :: a -> Type Name -> Text -> Exp a Name
xGlobal a t name
= xApps a (xPrimStore a (PrimStoreGlobal False))
[ RType t, RTerm $ xTextLit a name ]
-- | Reference to a global variable,
-- and also define it in the current module.
xGlobali :: a -> Type Name -> Text -> Exp a Name
xGlobali a t name
= xApps a (xPrimStore a (PrimStoreGlobal True))
[ RType t, RTerm $ xTextLit a name ]
---------------------------------------------------------------------------------------------------
-- | Take the type of a primitive projection.
typeOfPrimStore :: PrimStore -> Type Name
typeOfPrimStore jj
= case jj of
PrimStoreSize
-> tForall kData $ \_ -> tNat
PrimStoreSize2
-> tForall kData $ \_ -> tNat
PrimStoreCheck
-> tNat `tFun` tBool
PrimStoreAlloc
-> tNat `tFun` tAddr
PrimStoreAllocSlot
-> tForall kRegion
$ \r -> tPtr rTop (tPtr r tObj)
PrimStoreAllocSlotVal
-> tForall kRegion
$ \r -> tPtr r tObj `tFun` tPtr rTop (tPtr r tObj)
PrimStoreRead
-> tForall kData
$ \t -> tAddr `tFun` tNat `tFun` t
PrimStoreWrite
-> tForall kData
$ \t -> tAddr `tFun` tNat `tFun` t `tFun` tVoid
PrimStoreCopy
-> tAddr `tFun` tAddr `tFun` tNat `tFun` tVoid
PrimStoreSet
-> tAddr `tFun` tWord 8 `tFun` tNat `tFun` tVoid
PrimStorePlusAddr
-> tAddr `tFun` tNat `tFun` tAddr
PrimStoreMinusAddr
-> tAddr `tFun` tNat `tFun` tAddr
PrimStorePeek
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` t
PrimStorePoke
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` t `tFun` tVoid
PrimStorePeekBounded
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tNat `tFun` t
PrimStorePokeBounded
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tNat `tFun` t `tFun` tVoid
PrimStorePlusPtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tPtr r t
PrimStoreMinusPtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tPtr r t
PrimStoreMakePtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tAddr `tFun` tPtr r t
PrimStoreTakePtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tAddr
PrimStoreCastPtr
-> tForalls [kRegion, kData, kData]
$ \[r,t1,t2] -> tPtr r t2 `tFun` tPtr r t1
PrimStoreGlobal _
-> tForall kData
$ \_t -> tTextLit `tFun` tAddr
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-core-salt/DDC/Core/Salt/Compounds/PrimStore.hs | haskell | | Construct applications of primitive store operators.
Regions --------------------------------------------------------------------
| The top-level region.
This region lives for the whole program, and is used to store objects whose
types don't have region annotations (like function closures and Unit values).
| Take the number of bytes needed to store a value of a primitive type.
| Log2 of the number of bytes needed to store a value of primitive type.
| Read a value from an address plus offset.
| Write a value to an address plus offset.
| Peek a value from a buffer pointer plus offset.
| Poke a value from a buffer pointer plus offset.
| Peek a value from a buffer pointer plus offset.
| Poke a value from a buffer pointer plus offset.
| Add a byte offset to a pointer.
| Reference to a global variable.
| Reference to a global variable,
and also define it in the current module.
-------------------------------------------------------------------------------------------------
| Take the type of a primitive projection. |
module DDC.Core.Salt.Compounds.PrimStore
( rTop
, ukTop
, xStoreSize, xStoreSize2
, xRead, xWrite
, xPeek, xPoke
, xPeekBounded, xPokeBounded
, xPlusPtr
, xCastPtr
, xGlobal, xGlobali
, typeOfPrimStore)
where
import DDC.Core.Salt.Compounds.Lit
import DDC.Core.Salt.Compounds.PrimTyCon
import DDC.Core.Salt.Name
import DDC.Core.Exp.Annot
import Data.Text (Text)
rTop :: Type Name
rTop = TVar (fst ukTop)
ukTop :: (Bound Name, Kind Name)
ukTop
= ( UName (NameVar "rT")
, kRegion)
| All the Prim Store vars have this form .
xPrimStore a p
= XVar a (UName (NamePrimOp $ PrimStore p))
xStoreSize :: a -> Type Name -> Exp a Name
xStoreSize a tElem
= xApps a (xPrimStore a PrimStoreSize)
[RType tElem]
xStoreSize2 :: a -> Type Name -> Exp a Name
xStoreSize2 a tElem
= xApps a (xPrimStore a PrimStoreSize2)
[RType tElem]
xRead :: a -> Type Name -> Exp a Name -> Exp a Name -> Exp a Name
xRead a tField xAddr xOffset
= xApps a (xPrimStore a PrimStoreRead)
[ RType tField, RTerm xAddr, RTerm xOffset ]
xWrite :: a -> Type Name -> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xWrite a tField xAddr xOffset xVal
= xApps a (xPrimStore a PrimStoreWrite)
[ RType tField, RTerm xAddr, RTerm xOffset, RTerm xVal ]
xPeek :: a -> Type Name -> Type Name -> Exp a Name -> Exp a Name
xPeek a r t xPtr
= xApps a (xPrimStore a PrimStorePeek)
[ RType r, RType t, RTerm xPtr ]
xPoke :: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name
xPoke a r t xPtr xVal
= xApps a (xPrimStore a PrimStorePoke)
[ RType r, RType t, RTerm xPtr, RTerm xVal]
xPeekBounded
:: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xPeekBounded a r t xPtr xOffset xLimit
= xApps a (xPrimStore a PrimStorePeekBounded)
[ RType r, RType t, RTerm xPtr, RTerm xOffset, RTerm xLimit ]
xPokeBounded
:: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name -> Exp a Name
xPokeBounded a r t xPtr xOffset xLimit xVal
= xApps a (xPrimStore a PrimStorePokeBounded)
[ RType r, RType t, RTerm xPtr, RTerm xOffset, RTerm xLimit, RTerm xVal]
xPlusPtr :: a -> Type Name -> Type Name
-> Exp a Name -> Exp a Name -> Exp a Name
xPlusPtr a r t xPtr xOffset
= xApps a (xPrimStore a PrimStorePlusPtr)
[ RType r, RType t, RTerm xPtr, RTerm xOffset ]
| Cast a pointer to a different element ype .
xCastPtr :: a -> Type Name -> Type Name -> Type Name -> Exp a Name -> Exp a Name
xCastPtr a r toType fromType xPtr
= xApps a (xPrimStore a PrimStoreCastPtr)
[ RType r, RType toType, RType fromType, RTerm xPtr ]
xGlobal :: a -> Type Name -> Text -> Exp a Name
xGlobal a t name
= xApps a (xPrimStore a (PrimStoreGlobal False))
[ RType t, RTerm $ xTextLit a name ]
xGlobali :: a -> Type Name -> Text -> Exp a Name
xGlobali a t name
= xApps a (xPrimStore a (PrimStoreGlobal True))
[ RType t, RTerm $ xTextLit a name ]
typeOfPrimStore :: PrimStore -> Type Name
typeOfPrimStore jj
= case jj of
PrimStoreSize
-> tForall kData $ \_ -> tNat
PrimStoreSize2
-> tForall kData $ \_ -> tNat
PrimStoreCheck
-> tNat `tFun` tBool
PrimStoreAlloc
-> tNat `tFun` tAddr
PrimStoreAllocSlot
-> tForall kRegion
$ \r -> tPtr rTop (tPtr r tObj)
PrimStoreAllocSlotVal
-> tForall kRegion
$ \r -> tPtr r tObj `tFun` tPtr rTop (tPtr r tObj)
PrimStoreRead
-> tForall kData
$ \t -> tAddr `tFun` tNat `tFun` t
PrimStoreWrite
-> tForall kData
$ \t -> tAddr `tFun` tNat `tFun` t `tFun` tVoid
PrimStoreCopy
-> tAddr `tFun` tAddr `tFun` tNat `tFun` tVoid
PrimStoreSet
-> tAddr `tFun` tWord 8 `tFun` tNat `tFun` tVoid
PrimStorePlusAddr
-> tAddr `tFun` tNat `tFun` tAddr
PrimStoreMinusAddr
-> tAddr `tFun` tNat `tFun` tAddr
PrimStorePeek
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` t
PrimStorePoke
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` t `tFun` tVoid
PrimStorePeekBounded
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tNat `tFun` t
PrimStorePokeBounded
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tNat `tFun` t `tFun` tVoid
PrimStorePlusPtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tPtr r t
PrimStoreMinusPtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tNat `tFun` tPtr r t
PrimStoreMakePtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tAddr `tFun` tPtr r t
PrimStoreTakePtr
-> tForalls [kRegion, kData]
$ \[r,t] -> tPtr r t `tFun` tAddr
PrimStoreCastPtr
-> tForalls [kRegion, kData, kData]
$ \[r,t1,t2] -> tPtr r t2 `tFun` tPtr r t1
PrimStoreGlobal _
-> tForall kData
$ \_t -> tTextLit `tFun` tAddr
|
61112103205f8b8daf9d497f6e0fb87695d31cce1e1ae75c0c51c4a9992eb76b | haskell-numerics/hmatrix | TestGSL.hs | import Numeric.GSL.Tests
main :: IO ()
main = runTests 20
| null | https://raw.githubusercontent.com/haskell-numerics/hmatrix/2694f776c7b5034d239acb5d984c489417739225/packages/tests/src/TestGSL.hs | haskell | import Numeric.GSL.Tests
main :: IO ()
main = runTests 20
| |
f1a8702c1396d6792b9f67dfd49fd8209482bf68de024f19453d2c5a8f1b72d5 | Helium4Haskell/helium | Ex8.hs | module Ex8 where
f y (h:t) = t y
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Edinburgh/Ex8.hs | haskell | module Ex8 where
f y (h:t) = t y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.