_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
|
---|---|---|---|---|---|---|---|---|
7c029f254848614c7daa43ee08e840c9f8b4e95dfb233628778dc3a36299d802 | ekmett/reactor | Observer.hs | {-# LANGUAGE DeriveDataTypeable #-}
module Reactor.Observer
( Observer(..)
, (?!)
) where
import Prelude hiding (filter)
import Control.Monad
import Control.Exception hiding (handle)
import Control.Monad.Error
import Data.Monoid
import Data.Functor.Contravariant
import Data.Data
import Reactor.Filtered
import Reactor.Task
data Observer a = Observer
{ (!) :: a -> Task ()
, handle :: SomeException -> Task ()
, complete :: Task ()
} deriving Typeable
instance Contravariant Observer where
contramap g (Observer f h c) = Observer (f . g) h c
instance Filtered Observer where
filter p (Observer f h c) = Observer (\a -> when (p a) (f a)) h c
instance Monoid (Observer a) where
mempty = Observer (\_ -> return ()) throwError (return ())
p `mappend` q = Observer
(\a -> do p ! a; q ! a)
(\e -> do handle p e; handle q e)
(do complete p; complete q)
filter and map in one operation
(?!) :: Observer b -> (a -> Maybe b) -> Observer a
Observer f h c ?! p = Observer (maybe (return ()) f . p) h c
| null | https://raw.githubusercontent.com/ekmett/reactor/c071e639eb6070e6923cfc131d640161fdf6a1a9/Reactor/Observer.hs | haskell | # LANGUAGE DeriveDataTypeable # | module Reactor.Observer
( Observer(..)
, (?!)
) where
import Prelude hiding (filter)
import Control.Monad
import Control.Exception hiding (handle)
import Control.Monad.Error
import Data.Monoid
import Data.Functor.Contravariant
import Data.Data
import Reactor.Filtered
import Reactor.Task
data Observer a = Observer
{ (!) :: a -> Task ()
, handle :: SomeException -> Task ()
, complete :: Task ()
} deriving Typeable
instance Contravariant Observer where
contramap g (Observer f h c) = Observer (f . g) h c
instance Filtered Observer where
filter p (Observer f h c) = Observer (\a -> when (p a) (f a)) h c
instance Monoid (Observer a) where
mempty = Observer (\_ -> return ()) throwError (return ())
p `mappend` q = Observer
(\a -> do p ! a; q ! a)
(\e -> do handle p e; handle q e)
(do complete p; complete q)
filter and map in one operation
(?!) :: Observer b -> (a -> Maybe b) -> Observer a
Observer f h c ?! p = Observer (maybe (return ()) f . p) h c
|
50bb2cf3efa232b472384fb301da8ab829ef7e5b6707f667189e1394e91925c4 | JAremko/spacetools | fetch_test.clj | (ns spacetools.contributors.fetch-test
(:require [cats.monad.exception :as exc :refer [failure? success?]]
[clojure.test :refer :all]
[orchestra.spec.test :as st]
[org.httpkit.fake :refer :all]
[spacetools.contributors.fetch :as f]))
(st/instrument)
(deftest *first->l-p-url-fn
(let [b-url "/"
link-h-f "Link: <%sfoo?page=42>; rel=\"last\""
f-p-url (str b-url "foo?page=1")
l-p-url (str b-url "foo?page=42")]
(testing "Testing last page URL retrieval with proper URL."
(with-fake-http [{:url f-p-url} {:status 200
:headers {:link (format link-h-f b-url)}
:body "baz"}]
(is (success? (f/*first->last-page-url f-p-url)))
(is (= l-p-url @(f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval with 404 response."
(with-fake-http [{:url f-p-url} {:status 404
:headers {:link (format link-h-f b-url)}
:body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval with broken link headder reps"
(with-fake-http
[{:url f-p-url} {:status 200 :headers {:link "foo"} :body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval without link headder resp"
(with-fake-http
[{:url f-p-url} {:status 200 :body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))))
| null | https://raw.githubusercontent.com/JAremko/spacetools/d047e99689918b5a4ad483022f35802b2015af5f/components/contributors/test/spacetools/contributors/fetch_test.clj | clojure | (ns spacetools.contributors.fetch-test
(:require [cats.monad.exception :as exc :refer [failure? success?]]
[clojure.test :refer :all]
[orchestra.spec.test :as st]
[org.httpkit.fake :refer :all]
[spacetools.contributors.fetch :as f]))
(st/instrument)
(deftest *first->l-p-url-fn
(let [b-url "/"
link-h-f "Link: <%sfoo?page=42>; rel=\"last\""
f-p-url (str b-url "foo?page=1")
l-p-url (str b-url "foo?page=42")]
(testing "Testing last page URL retrieval with proper URL."
(with-fake-http [{:url f-p-url} {:status 200
:headers {:link (format link-h-f b-url)}
:body "baz"}]
(is (success? (f/*first->last-page-url f-p-url)))
(is (= l-p-url @(f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval with 404 response."
(with-fake-http [{:url f-p-url} {:status 404
:headers {:link (format link-h-f b-url)}
:body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval with broken link headder reps"
(with-fake-http
[{:url f-p-url} {:status 200 :headers {:link "foo"} :body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))
(testing "Testing last page URL retrieval without link headder resp"
(with-fake-http
[{:url f-p-url} {:status 200 :body "baz"}]
(is (failure? (f/*first->last-page-url f-p-url)))))))
|
|
917778434856511b89e5e1214ba938a59a9ec1bce208e4981ab75b2dcc8c9da0 | xoken/xoken-node | Chain.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE BangPatterns #-}
module Network.Xoken.Node.Service.Chain where
import Arivi.P2P.MessageHandler.HandlerTypes (HasNetworkConfig, networkConfig)
import Arivi.P2P.P2PEnv
import Arivi.P2P.PubSub.Class
import Arivi.P2P.PubSub.Env
import Arivi.P2P.PubSub.Publish as Pub
import Arivi.P2P.PubSub.Types
import Arivi.P2P.RPC.Env
import Arivi.P2P.RPC.Fetch
import Arivi.P2P.Types hiding (msgType)
import Codec.Serialise
import Conduit hiding (runResourceT)
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (AsyncCancelled, mapConcurrently, mapConcurrently_, race_)
import qualified Control.Concurrent.Async.Lifted as LA (async, concurrently, mapConcurrently, wait)
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import qualified Control.Error.Util as Extra
import Control.Exception
import Control.Exception
import qualified Control.Exception.Lifted as LE (try)
import Control.Monad
import Control.Monad.Extra
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Loops
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16 (decode, encode)
import Data.ByteString.Base64 as B64
import Data.ByteString.Base64.Lazy as B64L
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString.Short as BSS
import qualified Data.ByteString.UTF8 as BSU (toString)
import Data.Char
import Data.Default
import qualified Data.HashTable.IO as H
import Data.Hashable
import Data.IORef
import Data.Int
import Data.List
import qualified Data.List as L
import Data.Map.Strict as M
import Data.Maybe
import Data.Pool
import qualified Data.Serialize as S
import Data.Serialize
import qualified Data.Serialize as DS (decode, encode)
import qualified Data.Set as S
import Data.String (IsString, fromString)
import qualified Data.Text as DT
import qualified Data.Text.Encoding as DTE
import qualified Data.Text.Encoding as E
import Data.Time.Calendar
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Data.Word
import Data.Yaml
import qualified Database.Bolt as BT
import Database.XCQL.Protocol as Q
import qualified Network.Simple.TCP.TLS as TLS
import Network.Xoken.Address.Base58
import Network.Xoken.Block.Common
import Network.Xoken.Crypto.Hash
import Network.Xoken.Node.Data
import Network.Xoken.Node.Data.Allegory
import Network.Xoken.Node.Env
import Network.Xoken.Node.GraphDB
import Network . . Node . P2P.BlockSync
import Network.Xoken.Node.P2P.Common
import Network.Xoken.Node.P2P.Types
import Network.Xoken.Util (bsToInteger, integerToBS)
import Numeric (showHex)
import System.Logger as LG
import System.Logger.Message
import System.Random
import Text.Read
import Xoken
import qualified Xoken.NodeConfig as NC
xGetChainInfo :: (HasXokenNodeEnv env m, HasLogger m, MonadIO m) => m (Maybe ChainInfo)
xGetChainInfo = do
dbe <- getDB
lg <- getLogger
net <- (NC.bitcoinNetwork . nodeConfig) <$> getBitcoinP2P
let conn = xCqlClientState $ dbe
let conn = xCqlClientState dbe
str = "SELECT key,value from xoken.misc_store"
qstr = str :: Q.QueryString Q.R () (DT.Text, (Maybe Bool, Int32, Maybe Int64, DT.Text))
p = getSimpleQueryParam ()
res <- liftIO $ LE.try $ query conn (Q.RqQuery $ Q.Query qstr p)
case res of
Right iop -> do
if L.length iop < 3
then do
return Nothing
else do
let (_, blocks, _, bestSyncedHash) = snd . head $ (L.filter (\x -> fst x == "best-synced") iop)
(_, headers, _, bestBlockHash) = snd . head $ (L.filter (\x -> fst x == "best_chain_tip") iop)
(_, lagHeight, _, chainwork) = snd . head $ (L.filter (\x -> fst x == "chain-work") iop)
lagCW <- calculateChainWork [(lagHeight + 1) .. (headers)] conn
return $
Just $
ChainInfo
(getNetworkName net)
(showHex (lagCW + (read . DT.unpack $ chainwork)) "")
(headers)
(blocks)
(DT.unpack bestBlockHash)
(DT.unpack bestSyncedHash)
Left (e :: SomeException) -> do
err lg $ LG.msg $ "Error: xGetChainInfo: " ++ show e
throw KeyValueDBLookupException
xGetChainHeaders :: (HasXokenNodeEnv env m, HasLogger m, MonadIO m) => Int32 -> Int -> m [ChainHeader]
xGetChainHeaders sblk pgsize = do
dbe <- getDB
lg <- getLogger
let conn = xCqlClientState dbe
str = "SELECT block_hash,block_height,tx_count,block_header from xoken.blocks_by_height where block_height in ?"
qstr = str :: Q.QueryString Q.R (Identity [Int32]) (DT.Text, Int32, Maybe Int32, DT.Text)
p = getSimpleQueryParam $ Identity (L.take pgsize [sblk ..])
res <- liftIO $ LE.try $ query conn (Q.RqQuery $ Q.Query qstr p)
case res of
Right iop -> do
if length iop == 0
then return []
else do
case traverse
(\(hash, ht, txc, hdr) ->
case (eitherDecode $ BSL.fromStrict $ DTE.encodeUtf8 hdr) of
(Right bh) ->
Right $ ChainHeader ht (DT.unpack hash) bh (maybe (-1) fromIntegral txc)
Left e -> Left e)
(iop) of
Right x -> return x
Left e -> do
err lg $ LG.msg $ "Error: xGetChainHeaders: decode failed for blockrecord: " <> show e
return []
Left (e :: SomeException) -> do
err lg $ LG.msg $ "Error: xGetChainHeaders: " ++ show e
throw KeyValueDBLookupException
| null | https://raw.githubusercontent.com/xoken/xoken-node/99124fbe1b1cb9c2fc442c788c7c2bac06f5e900/node/src/Network/Xoken/Node/Service/Chain.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
# LANGUAGE BangPatterns # | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MonoLocalBinds #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
module Network.Xoken.Node.Service.Chain where
import Arivi.P2P.MessageHandler.HandlerTypes (HasNetworkConfig, networkConfig)
import Arivi.P2P.P2PEnv
import Arivi.P2P.PubSub.Class
import Arivi.P2P.PubSub.Env
import Arivi.P2P.PubSub.Publish as Pub
import Arivi.P2P.PubSub.Types
import Arivi.P2P.RPC.Env
import Arivi.P2P.RPC.Fetch
import Arivi.P2P.Types hiding (msgType)
import Codec.Serialise
import Conduit hiding (runResourceT)
import Control.Applicative
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (AsyncCancelled, mapConcurrently, mapConcurrently_, race_)
import qualified Control.Concurrent.Async.Lifted as LA (async, concurrently, mapConcurrently, wait)
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import qualified Control.Error.Util as Extra
import Control.Exception
import Control.Exception
import qualified Control.Exception.Lifted as LE (try)
import Control.Monad
import Control.Monad.Extra
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Loops
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Aeson as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as B16 (decode, encode)
import Data.ByteString.Base64 as B64
import Data.ByteString.Base64.Lazy as B64L
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString.Short as BSS
import qualified Data.ByteString.UTF8 as BSU (toString)
import Data.Char
import Data.Default
import qualified Data.HashTable.IO as H
import Data.Hashable
import Data.IORef
import Data.Int
import Data.List
import qualified Data.List as L
import Data.Map.Strict as M
import Data.Maybe
import Data.Pool
import qualified Data.Serialize as S
import Data.Serialize
import qualified Data.Serialize as DS (decode, encode)
import qualified Data.Set as S
import Data.String (IsString, fromString)
import qualified Data.Text as DT
import qualified Data.Text.Encoding as DTE
import qualified Data.Text.Encoding as E
import Data.Time.Calendar
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Data.Word
import Data.Yaml
import qualified Database.Bolt as BT
import Database.XCQL.Protocol as Q
import qualified Network.Simple.TCP.TLS as TLS
import Network.Xoken.Address.Base58
import Network.Xoken.Block.Common
import Network.Xoken.Crypto.Hash
import Network.Xoken.Node.Data
import Network.Xoken.Node.Data.Allegory
import Network.Xoken.Node.Env
import Network.Xoken.Node.GraphDB
import Network . . Node . P2P.BlockSync
import Network.Xoken.Node.P2P.Common
import Network.Xoken.Node.P2P.Types
import Network.Xoken.Util (bsToInteger, integerToBS)
import Numeric (showHex)
import System.Logger as LG
import System.Logger.Message
import System.Random
import Text.Read
import Xoken
import qualified Xoken.NodeConfig as NC
xGetChainInfo :: (HasXokenNodeEnv env m, HasLogger m, MonadIO m) => m (Maybe ChainInfo)
xGetChainInfo = do
dbe <- getDB
lg <- getLogger
net <- (NC.bitcoinNetwork . nodeConfig) <$> getBitcoinP2P
let conn = xCqlClientState $ dbe
let conn = xCqlClientState dbe
str = "SELECT key,value from xoken.misc_store"
qstr = str :: Q.QueryString Q.R () (DT.Text, (Maybe Bool, Int32, Maybe Int64, DT.Text))
p = getSimpleQueryParam ()
res <- liftIO $ LE.try $ query conn (Q.RqQuery $ Q.Query qstr p)
case res of
Right iop -> do
if L.length iop < 3
then do
return Nothing
else do
let (_, blocks, _, bestSyncedHash) = snd . head $ (L.filter (\x -> fst x == "best-synced") iop)
(_, headers, _, bestBlockHash) = snd . head $ (L.filter (\x -> fst x == "best_chain_tip") iop)
(_, lagHeight, _, chainwork) = snd . head $ (L.filter (\x -> fst x == "chain-work") iop)
lagCW <- calculateChainWork [(lagHeight + 1) .. (headers)] conn
return $
Just $
ChainInfo
(getNetworkName net)
(showHex (lagCW + (read . DT.unpack $ chainwork)) "")
(headers)
(blocks)
(DT.unpack bestBlockHash)
(DT.unpack bestSyncedHash)
Left (e :: SomeException) -> do
err lg $ LG.msg $ "Error: xGetChainInfo: " ++ show e
throw KeyValueDBLookupException
xGetChainHeaders :: (HasXokenNodeEnv env m, HasLogger m, MonadIO m) => Int32 -> Int -> m [ChainHeader]
xGetChainHeaders sblk pgsize = do
dbe <- getDB
lg <- getLogger
let conn = xCqlClientState dbe
str = "SELECT block_hash,block_height,tx_count,block_header from xoken.blocks_by_height where block_height in ?"
qstr = str :: Q.QueryString Q.R (Identity [Int32]) (DT.Text, Int32, Maybe Int32, DT.Text)
p = getSimpleQueryParam $ Identity (L.take pgsize [sblk ..])
res <- liftIO $ LE.try $ query conn (Q.RqQuery $ Q.Query qstr p)
case res of
Right iop -> do
if length iop == 0
then return []
else do
case traverse
(\(hash, ht, txc, hdr) ->
case (eitherDecode $ BSL.fromStrict $ DTE.encodeUtf8 hdr) of
(Right bh) ->
Right $ ChainHeader ht (DT.unpack hash) bh (maybe (-1) fromIntegral txc)
Left e -> Left e)
(iop) of
Right x -> return x
Left e -> do
err lg $ LG.msg $ "Error: xGetChainHeaders: decode failed for blockrecord: " <> show e
return []
Left (e :: SomeException) -> do
err lg $ LG.msg $ "Error: xGetChainHeaders: " ++ show e
throw KeyValueDBLookupException
|
09dc1f4e733d23c82bff54a6f677783ddef48b05b7a3158d95cfffb2d226b0bd | jserot/lascar | fsm_action.mli | (**********************************************************************)
(* *)
LASCAr
(* *)
Copyright ( c ) 2017 - present , . All rights reserved .
(* *)
(* This source code is licensed under the license found in the *)
(* LICENSE file in the root directory of this source tree. *)
(* *)
(**********************************************************************)
* { 2 Actions for FSM transitions }
module type T = sig
module Expr : Fsm_expr.T
type t =
| Assign of Expr.ident * Expr.t (* var, value *)
[@@deriving show {with_path=false}]
val to_string: t -> string
val of_string: ?lexer:(string->Genlex.token Stream.t) -> string -> t
val lexer: string -> Genlex.token Stream.t
val keywords: string list
val parse: Genlex.token Stream.t -> t
end
module Make (Expr: Fsm_expr.T) : T with module Expr = Expr
* Functor for converting a FSM action , with a given implementation of values
into another one with a different implementations
into another one with a different implementations *)
module Trans (A1: T) (A2: T) :
sig
val map: (A1.Expr.value -> A2.Expr.value) -> A1.t -> A2.t
end
(** Some predefined instances *)
module Int : T with module Expr = Fsm_expr.Int
module Bool : T with module Expr = Fsm_expr.Bool
| null | https://raw.githubusercontent.com/jserot/lascar/79bd11cd0d47545bccfc3a3571f37af065915c83/src/lib/fsm_action.mli | ocaml | ********************************************************************
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
********************************************************************
var, value
* Some predefined instances | LASCAr
Copyright ( c ) 2017 - present , . All rights reserved .
* { 2 Actions for FSM transitions }
module type T = sig
module Expr : Fsm_expr.T
type t =
[@@deriving show {with_path=false}]
val to_string: t -> string
val of_string: ?lexer:(string->Genlex.token Stream.t) -> string -> t
val lexer: string -> Genlex.token Stream.t
val keywords: string list
val parse: Genlex.token Stream.t -> t
end
module Make (Expr: Fsm_expr.T) : T with module Expr = Expr
* Functor for converting a FSM action , with a given implementation of values
into another one with a different implementations
into another one with a different implementations *)
module Trans (A1: T) (A2: T) :
sig
val map: (A1.Expr.value -> A2.Expr.value) -> A1.t -> A2.t
end
module Int : T with module Expr = Fsm_expr.Int
module Bool : T with module Expr = Fsm_expr.Bool
|
81bb74ab4d4f21fb96dbb47d082bb2b7f2b1d6e2eb7da91c13756fd0d2e4dda4 | clj-easy/graalvm-clojure | main.clj | (ns simple.main
(:require [cheshire.core :as json])
(:gen-class))
(defn -main []
(prn (json/generate-string {:foo "bar" :baz 5}))
(prn (json/parse-string "{\"foo\":\"bar\"}")))
| null | https://raw.githubusercontent.com/clj-easy/graalvm-clojure/5de155ad4f95d5dac97aac1ab3d118400e7d186f/cheshire/src/simple/main.clj | clojure | (ns simple.main
(:require [cheshire.core :as json])
(:gen-class))
(defn -main []
(prn (json/generate-string {:foo "bar" :baz 5}))
(prn (json/parse-string "{\"foo\":\"bar\"}")))
|
|
e26d61344a3486d9480931133e5b31cc624b516eef19d3e667136d4a084a9461 | darrenldl/ProVerif-ATP | rules.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
[ implies ] returns true when [ clause1 ] subsumes [ clause2 ]
val implies : reduction -> reduction -> bool
(* [reorder hyp] reorders the elements of the hypothesis [hyp]
to speed up the subsumption test. *)
val reorder : fact list -> fact list
[ corresp_initialize horn_state ] initializes the state of the solver and
saturates the set of clauses given in [ horn_state ] .
It allows subsequent calls to resolve_hyp , query_goal_std ,
and sound_bad_derivable .
saturates the set of clauses given in [horn_state].
It allows subsequent calls to resolve_hyp, query_goal_std,
and sound_bad_derivable. *)
val corresp_initialize : t_horn_state -> unit
[ resolve_hyp clause ] performs resolution on the hypothesis of the
clause [ clause ] , and returns the set of obtained clauses with no
selected hypothesis . In particular , when it returns no clause ,
the hypothesis of [ clause ] is not derivable .
It is called from piauth.ml and from reduction.ml , function
check_query_falsified , so it comes indirectly from piauth.ml
clause [clause], and returns the set of obtained clauses with no
selected hypothesis. In particular, when it returns no clause,
the hypothesis of [clause] is not derivable.
It is called from piauth.ml and from reduction.ml, function
check_query_falsified, so it comes indirectly from piauth.ml *)
val resolve_hyp : reduction -> reduction list
[ query_goal_std fact ] performs resolution on [ fact ] , and returns
the set of obtained clauses with no selected hypothesis that may
derive [ fact ] . In particular , when it returns no clause ,
[ fact ] is not derivable .
It is called only from reduction.ml , in case LetFilter
- so it comes indirectly from piauth.ml
the set of obtained clauses with no selected hypothesis that may
derive [fact]. In particular, when it returns no clause,
[fact] is not derivable.
It is called only from reduction.ml, in case LetFilter
- so it comes indirectly from piauth.ml *)
val query_goal_std : fact -> reduction list
(* [sound_bad_derivable clauses] returns the set of clauses that
derive bad from the initial clauses [clauses].
It is sound, that is, if it returns a clause, then bad is derivable
from this clause.
It restores the previous clauses after the call, so that
calls to [resolve_hyp] or [query_goal_std] can still be made
on the initial clauses passed to [corresp_initialize] after calling
[sound_bad_derivable].
It is called only from piauth.ml *)
val sound_bad_derivable : reduction list -> reduction list
(* [reset()] resets the whole state *)
val reset : unit -> unit
[ main_analysis horn_state queries ] determines whether the [ queries ]
are derivable from the clauses in [ horn_state ] . It displays the
results directly on the standard output or in an html file .
It is called only for the Horn and typed Horn front - ends
are derivable from the clauses in [horn_state]. It displays the
results directly on the standard output or in an html file.
It is called only for the Horn and typed Horn front-ends *)
val main_analysis : t_horn_state -> fact list -> unit
(* [bad_derivable horn_state] determines whether [bad] is derivable
from the clauses in [horn_state]. It returns the clauses with
no selected hypothesis that may derive bad.
It is called from [Main.interference_analysis] *)
val bad_derivable : t_horn_state -> reduction list
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/proverif2.00/src/rules.mli | ocaml | [reorder hyp] reorders the elements of the hypothesis [hyp]
to speed up the subsumption test.
[sound_bad_derivable clauses] returns the set of clauses that
derive bad from the initial clauses [clauses].
It is sound, that is, if it returns a clause, then bad is derivable
from this clause.
It restores the previous clauses after the call, so that
calls to [resolve_hyp] or [query_goal_std] can still be made
on the initial clauses passed to [corresp_initialize] after calling
[sound_bad_derivable].
It is called only from piauth.ml
[reset()] resets the whole state
[bad_derivable horn_state] determines whether [bad] is derivable
from the clauses in [horn_state]. It returns the clauses with
no selected hypothesis that may derive bad.
It is called from [Main.interference_analysis] | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
[ implies ] returns true when [ clause1 ] subsumes [ clause2 ]
val implies : reduction -> reduction -> bool
val reorder : fact list -> fact list
[ corresp_initialize horn_state ] initializes the state of the solver and
saturates the set of clauses given in [ horn_state ] .
It allows subsequent calls to resolve_hyp , query_goal_std ,
and sound_bad_derivable .
saturates the set of clauses given in [horn_state].
It allows subsequent calls to resolve_hyp, query_goal_std,
and sound_bad_derivable. *)
val corresp_initialize : t_horn_state -> unit
[ resolve_hyp clause ] performs resolution on the hypothesis of the
clause [ clause ] , and returns the set of obtained clauses with no
selected hypothesis . In particular , when it returns no clause ,
the hypothesis of [ clause ] is not derivable .
It is called from piauth.ml and from reduction.ml , function
check_query_falsified , so it comes indirectly from piauth.ml
clause [clause], and returns the set of obtained clauses with no
selected hypothesis. In particular, when it returns no clause,
the hypothesis of [clause] is not derivable.
It is called from piauth.ml and from reduction.ml, function
check_query_falsified, so it comes indirectly from piauth.ml *)
val resolve_hyp : reduction -> reduction list
[ query_goal_std fact ] performs resolution on [ fact ] , and returns
the set of obtained clauses with no selected hypothesis that may
derive [ fact ] . In particular , when it returns no clause ,
[ fact ] is not derivable .
It is called only from reduction.ml , in case LetFilter
- so it comes indirectly from piauth.ml
the set of obtained clauses with no selected hypothesis that may
derive [fact]. In particular, when it returns no clause,
[fact] is not derivable.
It is called only from reduction.ml, in case LetFilter
- so it comes indirectly from piauth.ml *)
val query_goal_std : fact -> reduction list
val sound_bad_derivable : reduction list -> reduction list
val reset : unit -> unit
[ main_analysis horn_state queries ] determines whether the [ queries ]
are derivable from the clauses in [ horn_state ] . It displays the
results directly on the standard output or in an html file .
It is called only for the Horn and typed Horn front - ends
are derivable from the clauses in [horn_state]. It displays the
results directly on the standard output or in an html file.
It is called only for the Horn and typed Horn front-ends *)
val main_analysis : t_horn_state -> fact list -> unit
val bad_derivable : t_horn_state -> reduction list
|
68d113bfff78c2748afe413a48a994b918b618a907bb6df4168bcc09d3baa1c1 | juspay/atlas | DriverTrackingHealthcheckMain.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App.DriverTrackingHealthcheck
import Prelude
main :: IO ()
main = runDriverHealthcheck id
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/server/DriverTrackingHealthcheckMain.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App.DriverTrackingHealthcheck
import Prelude
main :: IO ()
main = runDriverHealthcheck id
|
|
f6b081873664db15519671a6b743ac8f954ea39ed07569a8b4abc554aa2e39e8 | ds-wizard/engine-backend | LocaleMigration.hs | module Registry.Database.Migration.Development.Locale.LocaleMigration where
import Registry.Model.Context.AppContext
import Registry.Model.Context.ContextLenses ()
import Registry.S3.Locale.LocaleS3
import Registry.Util.Logger
import Shared.Database.DAO.Locale.LocaleDAO
import Shared.Database.Migration.Development.Locale.Data.Locales
import Shared.Model.Locale.Locale
runMigration :: AppContextM ()
runMigration = do
logInfo _CMP_MIGRATION "(App/Locale) started"
deleteLocales
insertLocale localeNl
logInfo _CMP_MIGRATION "(App/Locale) ended"
runS3Migration :: AppContextM ()
runS3Migration = do
_ <- putLocale localeNl.lId localeNlContent
return ()
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-registry/src/Registry/Database/Migration/Development/Locale/LocaleMigration.hs | haskell | module Registry.Database.Migration.Development.Locale.LocaleMigration where
import Registry.Model.Context.AppContext
import Registry.Model.Context.ContextLenses ()
import Registry.S3.Locale.LocaleS3
import Registry.Util.Logger
import Shared.Database.DAO.Locale.LocaleDAO
import Shared.Database.Migration.Development.Locale.Data.Locales
import Shared.Model.Locale.Locale
runMigration :: AppContextM ()
runMigration = do
logInfo _CMP_MIGRATION "(App/Locale) started"
deleteLocales
insertLocale localeNl
logInfo _CMP_MIGRATION "(App/Locale) ended"
runS3Migration :: AppContextM ()
runS3Migration = do
_ <- putLocale localeNl.lId localeNlContent
return ()
|
|
d841b5ea9cb35de31a6f6c613b1c4a18bbde9de93d30ab5cd2a0e6a8f4a0f84a | emina/rosette | reporter.rkt | #lang racket
(require rosette/base/core/reporter "data.rkt")
(provide (struct-out profiler-reporter) make-profiler-reporter
get-current-metrics/call get-call-time
get-sample-event
metrics-ref diff-metrics metrics->hash)
; The profiler reporter keeps a cumulative count of several metrics,
; as an association list, and reports
; them when requested to insert into a profile node.
; (Performance note: an association list is slightly faster than a hash table
for workloads that clone the current metrics state a lot , such as MemSynth ) .
(define (make-profiler-reporter profile)
(profiler-reporter
profile
(map (curryr cons 0) '(term-count merge-count merge-cases union-count union-size))
#f))
(struct profiler-reporter (profile [metrics #:mutable] [finitizing #:mutable])
#:transparent
#:property prop:procedure
(lambda (self . rest)
(match rest
[(list 'new-term the-term)
(unless (profiler-reporter-finitizing self)
(inc! self 'term-count 1))
(let* ([new (profile-event-term-new (get-current-metrics/none) the-term)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'merge merge-cases)
(unless (profiler-reporter-finitizing self)
(inc! self 'merge-count 1)
(inc! self 'merge-cases merge-cases))]
[(list 'new-union union-size)
(unless (profiler-reporter-finitizing self)
(inc! self 'union-count 1)
(inc! self 'union-size union-size))]
[(list 'solve-start)
(let* ([new (profile-event-solve-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'solve-finish sat?)
(let* ([new (profile-event-solve-finish (get-current-metrics/event) sat?)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'to-solver lists ...)
(let* ([new (profile-event-solve-encode (get-current-metrics/none) lists)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'finitize-start)
(set-profiler-reporter-finitizing! self #t)
(let* ([new (profile-event-finitize-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'finitize-finish)
(set-profiler-reporter-finitizing! self #f)
(let* ([new (profile-event-finitize-finish (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'encode-start)
(let* ([new (profile-event-encode-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'encode-finish)
(let* ([new (profile-event-encode-finish (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[_ (void)])))
(define (assoc-inc xs x v)
(let loop ([xs xs])
(cond [(null? xs) (cons x v)]
[(eq? (caar xs) x) (cons (cons x (+ v (cdar xs))) (cdr xs))]
[else (cons (car xs) (loop (cdr xs)))])))
(define (assoc-dec xs x v)
(let loop ([xs xs])
(cond [(null? xs) (cons x v)]
[(eq? (caar xs) x) (cons (cons x (- (cdar xs) v)) (cdr xs))]
[else (cons (car xs) (loop (cdr xs)))])))
(define-syntax-rule (inc! reporter key val)
(let ([ht (profiler-reporter-metrics reporter)])
(set-profiler-reporter-metrics! reporter (assoc-inc ht key val))))
(define-syntax-rule (dec! reporter key val)
(let ([ht (profiler-reporter-metrics reporter)])
(set-profiler-reporter-metrics! reporter (assoc-dec ht key val))))
(define (get-current-metrics/event)
(list (cons 'time (current-inexact-milliseconds))))
(define (get-current-metrics/none)
'())
(define (get-current-metrics/call reporter)
(cons (cons 'time (current-inexact-milliseconds))
(profiler-reporter-metrics reporter)))
; shortcut to get time from a get-current-metrics/call instance;
; make sure to update if get-current-metrics/call changes
(define (get-call-time evt)
(cdar (profile-event-metrics evt)))
(define (get-sample-event)
(profile-event-sample (get-current-metrics/call (current-reporter))))
;; Abstract out references to metrics in case we decide we need a better data
;; structure at some point.
(define (metrics-ref mets key)
(let ([a (assq key mets)])
(if a (cdr a) #f)))
;; Helper to compute the difference between entry and exit metrics
(define (diff-metrics old new)
(for/list ([k/v new])
(let ([k (car k/v)][v (cdr k/v)])
(let ([o (assq k old)])
(cons k (- v (if o (cdr o) 0)))))))
Convert metrics to a hash for output
(define (metrics->hash m)
(for/hash ([k/v m]) (values (car k/v) (cdr k/v))))
| null | https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/rosette/lib/profile/reporter.rkt | racket | The profiler reporter keeps a cumulative count of several metrics,
as an association list, and reports
them when requested to insert into a profile node.
(Performance note: an association list is slightly faster than a hash table
shortcut to get time from a get-current-metrics/call instance;
make sure to update if get-current-metrics/call changes
Abstract out references to metrics in case we decide we need a better data
structure at some point.
Helper to compute the difference between entry and exit metrics | #lang racket
(require rosette/base/core/reporter "data.rkt")
(provide (struct-out profiler-reporter) make-profiler-reporter
get-current-metrics/call get-call-time
get-sample-event
metrics-ref diff-metrics metrics->hash)
for workloads that clone the current metrics state a lot , such as MemSynth ) .
(define (make-profiler-reporter profile)
(profiler-reporter
profile
(map (curryr cons 0) '(term-count merge-count merge-cases union-count union-size))
#f))
(struct profiler-reporter (profile [metrics #:mutable] [finitizing #:mutable])
#:transparent
#:property prop:procedure
(lambda (self . rest)
(match rest
[(list 'new-term the-term)
(unless (profiler-reporter-finitizing self)
(inc! self 'term-count 1))
(let* ([new (profile-event-term-new (get-current-metrics/none) the-term)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'merge merge-cases)
(unless (profiler-reporter-finitizing self)
(inc! self 'merge-count 1)
(inc! self 'merge-cases merge-cases))]
[(list 'new-union union-size)
(unless (profiler-reporter-finitizing self)
(inc! self 'union-count 1)
(inc! self 'union-size union-size))]
[(list 'solve-start)
(let* ([new (profile-event-solve-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'solve-finish sat?)
(let* ([new (profile-event-solve-finish (get-current-metrics/event) sat?)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'to-solver lists ...)
(let* ([new (profile-event-solve-encode (get-current-metrics/none) lists)])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'finitize-start)
(set-profiler-reporter-finitizing! self #t)
(let* ([new (profile-event-finitize-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'finitize-finish)
(set-profiler-reporter-finitizing! self #f)
(let* ([new (profile-event-finitize-finish (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'encode-start)
(let* ([new (profile-event-encode-start (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[(list 'encode-finish)
(let* ([new (profile-event-encode-finish (get-current-metrics/event))])
(profile-state-append! (profiler-reporter-profile self) new))]
[_ (void)])))
(define (assoc-inc xs x v)
(let loop ([xs xs])
(cond [(null? xs) (cons x v)]
[(eq? (caar xs) x) (cons (cons x (+ v (cdar xs))) (cdr xs))]
[else (cons (car xs) (loop (cdr xs)))])))
(define (assoc-dec xs x v)
(let loop ([xs xs])
(cond [(null? xs) (cons x v)]
[(eq? (caar xs) x) (cons (cons x (- (cdar xs) v)) (cdr xs))]
[else (cons (car xs) (loop (cdr xs)))])))
(define-syntax-rule (inc! reporter key val)
(let ([ht (profiler-reporter-metrics reporter)])
(set-profiler-reporter-metrics! reporter (assoc-inc ht key val))))
(define-syntax-rule (dec! reporter key val)
(let ([ht (profiler-reporter-metrics reporter)])
(set-profiler-reporter-metrics! reporter (assoc-dec ht key val))))
(define (get-current-metrics/event)
(list (cons 'time (current-inexact-milliseconds))))
(define (get-current-metrics/none)
'())
(define (get-current-metrics/call reporter)
(cons (cons 'time (current-inexact-milliseconds))
(profiler-reporter-metrics reporter)))
(define (get-call-time evt)
(cdar (profile-event-metrics evt)))
(define (get-sample-event)
(profile-event-sample (get-current-metrics/call (current-reporter))))
(define (metrics-ref mets key)
(let ([a (assq key mets)])
(if a (cdr a) #f)))
(define (diff-metrics old new)
(for/list ([k/v new])
(let ([k (car k/v)][v (cdr k/v)])
(let ([o (assq k old)])
(cons k (- v (if o (cdr o) 0)))))))
Convert metrics to a hash for output
(define (metrics->hash m)
(for/hash ([k/v m]) (values (car k/v) (cdr k/v))))
|
ca2958b489e841d388cea1e1ab95561e6c36aa63de36fafceace527d1d5466c1 | processone/xmpp | xep0260.erl | Created automatically by XML generator ( fxml_gen.erl )
%% Source: xmpp_codec.spec
-module(xep0260).
-compile(export_all).
do_decode(<<"transport">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_transport(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"proxy-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_proxy_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"activated">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_activated(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate-used">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate_used(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() ->
[{<<"transport">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"proxy-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"activated">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate-used">>,
<<"urn:xmpp:jingle:transports:s5b:1">>}].
do_encode({jingle_s5b_candidate, _, _, _, _, _, _} =
Candidate,
TopXMLNS) ->
encode_jingle_s5b_candidate(Candidate, TopXMLNS);
do_encode({jingle_s5b_transport, _, _, _, _, _, _, _} =
Transport,
TopXMLNS) ->
encode_jingle_s5b_transport(Transport, TopXMLNS).
do_get_name({jingle_s5b_candidate, _, _, _, _, _, _}) ->
<<"candidate">>;
do_get_name({jingle_s5b_transport,
_,
_,
_,
_,
_,
_,
_}) ->
<<"transport">>.
do_get_ns({jingle_s5b_candidate, _, _, _, _, _, _}) ->
<<"urn:xmpp:jingle:transports:s5b:1">>;
do_get_ns({jingle_s5b_transport,
_,
_,
_,
_,
_,
_,
_}) ->
<<"urn:xmpp:jingle:transports:s5b:1">>.
pp(jingle_s5b_candidate, 6) ->
[cid, host, port, jid, type, priority];
pp(jingle_s5b_transport, 7) ->
[sid,
dstaddr,
mode,
candidates,
'candidate-used',
activated,
error];
pp(_, _) -> no.
records() ->
[{jingle_s5b_candidate, 6}, {jingle_s5b_transport, 7}].
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
dec_int(Val, Min, Max) ->
case erlang:binary_to_integer(Val) of
Int when Int =< Max, Min == infinity -> Int;
Int when Int =< Max, Int >= Min -> Int
end.
dec_ip(S) ->
{ok, Addr} = inet_parse:address(binary_to_list(S)),
Addr.
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
enc_int(Int) -> erlang:integer_to_binary(Int).
enc_ip({0, 0, 0, 0, 0, 65535, A, B}) ->
enc_ip({(A bsr 8) band 255,
A band 255,
(B bsr 8) band 255,
B band 255});
enc_ip(Addr) -> list_to_binary(inet_parse:ntoa(Addr)).
decode_jingle_s5b_transport(__TopXMLNS, __Opts,
{xmlel, <<"transport">>, _attrs, _els}) ->
{Error, Candidates, Activated, Candidate_used} =
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
undefined,
[],
undefined,
undefined),
{Sid, Dstaddr, Mode} =
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined),
{jingle_s5b_transport,
Sid,
Dstaddr,
Mode,
Candidates,
Candidate_used,
Activated,
Error}.
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts, [],
Error, Candidates, Activated, Candidate_used) ->
{Error,
lists:reverse(Candidates),
Activated,
Candidate_used};
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
[decode_jingle_s5b_candidate(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el)
| Candidates],
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate-used">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
decode_jingle_s5b_candidate_used(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el));
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"activated">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
decode_jingle_s5b_activated(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate-error">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
decode_jingle_s5b_candidate_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidates,
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"proxy-error">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
decode_jingle_s5b_proxy_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidates,
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[_ | _els], Error, Candidates, Activated,
Candidate_used) ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used).
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"sid">>, _val} | _attrs], _Sid, Dstaddr,
Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
_val,
Dstaddr,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"dstaddr">>, _val} | _attrs], Sid,
_Dstaddr, Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
_val,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"mode">>, _val} | _attrs], Sid, Dstaddr,
_Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
Dstaddr,
_val);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[_ | _attrs], Sid, Dstaddr, Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
Dstaddr,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS, [], Sid,
Dstaddr, Mode) ->
{decode_jingle_s5b_transport_attr_sid(__TopXMLNS, Sid),
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
Dstaddr),
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
Mode)}.
encode_jingle_s5b_transport({jingle_s5b_transport,
Sid,
Dstaddr,
Mode,
Candidates,
Candidate_used,
Activated,
Error},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_jingle_s5b_transport_$error'(Error,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$candidates'(Candidates,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$activated'(Activated,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$candidate-used'(Candidate_used,
__NewTopXMLNS,
[]))))),
_attrs = encode_jingle_s5b_transport_attr_mode(Mode,
encode_jingle_s5b_transport_attr_dstaddr(Dstaddr,
encode_jingle_s5b_transport_attr_sid(Sid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)))),
{xmlel, <<"transport">>, _attrs, _els}.
'encode_jingle_s5b_transport_$error'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$error'('candidate-error' =
Error,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_candidate_error(Error, __TopXMLNS)
| _acc];
'encode_jingle_s5b_transport_$error'('proxy-error' =
Error,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_proxy_error(Error, __TopXMLNS)
| _acc].
'encode_jingle_s5b_transport_$candidates'([],
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$candidates'([Candidates
| _els],
__TopXMLNS, _acc) ->
'encode_jingle_s5b_transport_$candidates'(_els,
__TopXMLNS,
[encode_jingle_s5b_candidate(Candidates,
__TopXMLNS)
| _acc]).
'encode_jingle_s5b_transport_$activated'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$activated'(Activated,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_activated(Activated, __TopXMLNS)
| _acc].
'encode_jingle_s5b_transport_$candidate-used'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$candidate-used'(Candidate_used,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_candidate_used(Candidate_used,
__TopXMLNS)
| _acc].
decode_jingle_s5b_transport_attr_sid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"sid">>,
<<"transport">>,
__TopXMLNS}});
decode_jingle_s5b_transport_attr_sid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_transport_attr_sid(_val, _acc) ->
[{<<"sid">>, _val} | _acc].
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
undefined) ->
<<>>;
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_transport_attr_dstaddr(<<>>, _acc) ->
_acc;
encode_jingle_s5b_transport_attr_dstaddr(_val, _acc) ->
[{<<"dstaddr">>, _val} | _acc].
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
undefined) ->
tcp;
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
_val) ->
case catch dec_enum(_val, [tcp, udp]) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"mode">>,
<<"transport">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_transport_attr_mode(tcp, _acc) ->
_acc;
encode_jingle_s5b_transport_attr_mode(_val, _acc) ->
[{<<"mode">>, enc_enum(_val)} | _acc].
decode_jingle_s5b_proxy_error(__TopXMLNS, __Opts,
{xmlel, <<"proxy-error">>, _attrs, _els}) ->
'proxy-error'.
encode_jingle_s5b_proxy_error('proxy-error',
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"proxy-error">>, _attrs, _els}.
decode_jingle_s5b_candidate_error(__TopXMLNS, __Opts,
{xmlel,
<<"candidate-error">>,
_attrs,
_els}) ->
'candidate-error'.
encode_jingle_s5b_candidate_error('candidate-error',
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"candidate-error">>, _attrs, _els}.
decode_jingle_s5b_activated(__TopXMLNS, __Opts,
{xmlel, <<"activated">>, _attrs, _els}) ->
Cid = decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
undefined),
Cid.
decode_jingle_s5b_activated_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid) ->
decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
_val);
decode_jingle_s5b_activated_attrs(__TopXMLNS,
[_ | _attrs], Cid) ->
decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
Cid);
decode_jingle_s5b_activated_attrs(__TopXMLNS, [],
Cid) ->
decode_jingle_s5b_activated_attr_cid(__TopXMLNS, Cid).
encode_jingle_s5b_activated(Cid, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_activated_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"activated">>, _attrs, _els}.
decode_jingle_s5b_activated_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"activated">>,
__TopXMLNS}});
decode_jingle_s5b_activated_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_activated_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
decode_jingle_s5b_candidate(__TopXMLNS, __Opts,
{xmlel, <<"candidate">>, _attrs, _els}) ->
{Cid, Host, Jid, Port, Priority, Type} =
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined),
{jingle_s5b_candidate,
Cid,
Host,
Port,
Jid,
Type,
Priority}.
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid, Host, Jid,
Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
_val,
Host,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"host">>, _val} | _attrs], Cid, _Host,
Jid, Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
_val,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Cid, Host, _Jid,
Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
_val,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"port">>, _val} | _attrs], Cid, Host, Jid,
_Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
_val,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"priority">>, _val} | _attrs], Cid, Host,
Jid, Port, _Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
_val,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"type">>, _val} | _attrs], Cid, Host, Jid,
Port, Priority, _Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
Priority,
_val);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[_ | _attrs], Cid, Host, Jid, Port, Priority,
Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS, [], Cid,
Host, Jid, Port, Priority, Type) ->
{decode_jingle_s5b_candidate_attr_cid(__TopXMLNS, Cid),
decode_jingle_s5b_candidate_attr_host(__TopXMLNS, Host),
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS, Jid),
decode_jingle_s5b_candidate_attr_port(__TopXMLNS, Port),
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
Priority),
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
Type)}.
encode_jingle_s5b_candidate({jingle_s5b_candidate,
Cid,
Host,
Port,
Jid,
Type,
Priority},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_candidate_attr_type(Type,
encode_jingle_s5b_candidate_attr_priority(Priority,
encode_jingle_s5b_candidate_attr_port(Port,
encode_jingle_s5b_candidate_attr_jid(Jid,
encode_jingle_s5b_candidate_attr_host(Host,
encode_jingle_s5b_candidate_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))))),
{xmlel, <<"candidate">>, _attrs, _els}.
decode_jingle_s5b_candidate_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_candidate_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
decode_jingle_s5b_candidate_attr_host(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"host">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_host(__TopXMLNS,
_val) ->
case catch dec_ip(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"host">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_host(_val, _acc) ->
[{<<"host">>, enc_ip(_val)} | _acc].
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"jid">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS,
_val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_jingle_s5b_candidate_attr_port(__TopXMLNS,
undefined) ->
undefined;
decode_jingle_s5b_candidate_attr_port(__TopXMLNS,
_val) ->
case catch dec_int(_val, 0, 65535) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"port">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_port(undefined,
_acc) ->
_acc;
encode_jingle_s5b_candidate_attr_port(_val, _acc) ->
[{<<"port">>, enc_int(_val)} | _acc].
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"priority">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
_val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"priority">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_priority(_val, _acc) ->
[{<<"priority">>, enc_int(_val)} | _acc].
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
undefined) ->
direct;
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[assisted, direct, proxy, tunnel])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"type">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_type(direct, _acc) ->
_acc;
encode_jingle_s5b_candidate_attr_type(_val, _acc) ->
[{<<"type">>, enc_enum(_val)} | _acc].
decode_jingle_s5b_candidate_used(__TopXMLNS, __Opts,
{xmlel, <<"candidate-used">>, _attrs, _els}) ->
Cid = decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
undefined),
Cid.
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid) ->
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
_val);
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
[_ | _attrs], Cid) ->
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
Cid);
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS, [],
Cid) ->
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
Cid).
encode_jingle_s5b_candidate_used(Cid, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_candidate_used_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"candidate-used">>, _attrs, _els}.
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"candidate-used">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_candidate_used_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
| null | https://raw.githubusercontent.com/processone/xmpp/88c43c3cf5843a8a0f76eac390980a3a39c972dd/src/xep0260.erl | erlang | Source: xmpp_codec.spec | Created automatically by XML generator ( fxml_gen.erl )
-module(xep0260).
-compile(export_all).
do_decode(<<"transport">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_transport(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"proxy-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_proxy_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"activated">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_activated(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(<<"candidate-used">>,
<<"urn:xmpp:jingle:transports:s5b:1">>, El, Opts) ->
decode_jingle_s5b_candidate_used(<<"urn:xmpp:jingle:transports:s5b:1">>,
Opts,
El);
do_decode(Name, <<>>, _, _) ->
erlang:error({xmpp_codec, {missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({xmpp_codec, {unknown_tag, Name, XMLNS}}).
tags() ->
[{<<"transport">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"proxy-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate-error">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"activated">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate">>,
<<"urn:xmpp:jingle:transports:s5b:1">>},
{<<"candidate-used">>,
<<"urn:xmpp:jingle:transports:s5b:1">>}].
do_encode({jingle_s5b_candidate, _, _, _, _, _, _} =
Candidate,
TopXMLNS) ->
encode_jingle_s5b_candidate(Candidate, TopXMLNS);
do_encode({jingle_s5b_transport, _, _, _, _, _, _, _} =
Transport,
TopXMLNS) ->
encode_jingle_s5b_transport(Transport, TopXMLNS).
do_get_name({jingle_s5b_candidate, _, _, _, _, _, _}) ->
<<"candidate">>;
do_get_name({jingle_s5b_transport,
_,
_,
_,
_,
_,
_,
_}) ->
<<"transport">>.
do_get_ns({jingle_s5b_candidate, _, _, _, _, _, _}) ->
<<"urn:xmpp:jingle:transports:s5b:1">>;
do_get_ns({jingle_s5b_transport,
_,
_,
_,
_,
_,
_,
_}) ->
<<"urn:xmpp:jingle:transports:s5b:1">>.
pp(jingle_s5b_candidate, 6) ->
[cid, host, port, jid, type, priority];
pp(jingle_s5b_transport, 7) ->
[sid,
dstaddr,
mode,
candidates,
'candidate-used',
activated,
error];
pp(_, _) -> no.
records() ->
[{jingle_s5b_candidate, 6}, {jingle_s5b_transport, 7}].
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
dec_int(Val, Min, Max) ->
case erlang:binary_to_integer(Val) of
Int when Int =< Max, Min == infinity -> Int;
Int when Int =< Max, Int >= Min -> Int
end.
dec_ip(S) ->
{ok, Addr} = inet_parse:address(binary_to_list(S)),
Addr.
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
enc_int(Int) -> erlang:integer_to_binary(Int).
enc_ip({0, 0, 0, 0, 0, 65535, A, B}) ->
enc_ip({(A bsr 8) band 255,
A band 255,
(B bsr 8) band 255,
B band 255});
enc_ip(Addr) -> list_to_binary(inet_parse:ntoa(Addr)).
decode_jingle_s5b_transport(__TopXMLNS, __Opts,
{xmlel, <<"transport">>, _attrs, _els}) ->
{Error, Candidates, Activated, Candidate_used} =
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
undefined,
[],
undefined,
undefined),
{Sid, Dstaddr, Mode} =
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined),
{jingle_s5b_transport,
Sid,
Dstaddr,
Mode,
Candidates,
Candidate_used,
Activated,
Error}.
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts, [],
Error, Candidates, Activated, Candidate_used) ->
{Error,
lists:reverse(Candidates),
Activated,
Candidate_used};
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
[decode_jingle_s5b_candidate(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el)
| Candidates],
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate-used">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
decode_jingle_s5b_candidate_used(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el));
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"activated">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
decode_jingle_s5b_activated(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"candidate-error">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
decode_jingle_s5b_candidate_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidates,
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[{xmlel, <<"proxy-error">>, _attrs, _} = _el
| _els],
Error, Candidates, Activated, Candidate_used) ->
case xmpp_codec:get_attr(<<"xmlns">>,
_attrs,
__TopXMLNS)
of
<<"urn:xmpp:jingle:transports:s5b:1">> ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
decode_jingle_s5b_proxy_error(<<"urn:xmpp:jingle:transports:s5b:1">>,
__Opts,
_el),
Candidates,
Activated,
Candidate_used);
_ ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used)
end;
decode_jingle_s5b_transport_els(__TopXMLNS, __Opts,
[_ | _els], Error, Candidates, Activated,
Candidate_used) ->
decode_jingle_s5b_transport_els(__TopXMLNS,
__Opts,
_els,
Error,
Candidates,
Activated,
Candidate_used).
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"sid">>, _val} | _attrs], _Sid, Dstaddr,
Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
_val,
Dstaddr,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"dstaddr">>, _val} | _attrs], Sid,
_Dstaddr, Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
_val,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[{<<"mode">>, _val} | _attrs], Sid, Dstaddr,
_Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
Dstaddr,
_val);
decode_jingle_s5b_transport_attrs(__TopXMLNS,
[_ | _attrs], Sid, Dstaddr, Mode) ->
decode_jingle_s5b_transport_attrs(__TopXMLNS,
_attrs,
Sid,
Dstaddr,
Mode);
decode_jingle_s5b_transport_attrs(__TopXMLNS, [], Sid,
Dstaddr, Mode) ->
{decode_jingle_s5b_transport_attr_sid(__TopXMLNS, Sid),
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
Dstaddr),
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
Mode)}.
encode_jingle_s5b_transport({jingle_s5b_transport,
Sid,
Dstaddr,
Mode,
Candidates,
Candidate_used,
Activated,
Error},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els =
lists:reverse('encode_jingle_s5b_transport_$error'(Error,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$candidates'(Candidates,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$activated'(Activated,
__NewTopXMLNS,
'encode_jingle_s5b_transport_$candidate-used'(Candidate_used,
__NewTopXMLNS,
[]))))),
_attrs = encode_jingle_s5b_transport_attr_mode(Mode,
encode_jingle_s5b_transport_attr_dstaddr(Dstaddr,
encode_jingle_s5b_transport_attr_sid(Sid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)))),
{xmlel, <<"transport">>, _attrs, _els}.
'encode_jingle_s5b_transport_$error'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$error'('candidate-error' =
Error,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_candidate_error(Error, __TopXMLNS)
| _acc];
'encode_jingle_s5b_transport_$error'('proxy-error' =
Error,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_proxy_error(Error, __TopXMLNS)
| _acc].
'encode_jingle_s5b_transport_$candidates'([],
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$candidates'([Candidates
| _els],
__TopXMLNS, _acc) ->
'encode_jingle_s5b_transport_$candidates'(_els,
__TopXMLNS,
[encode_jingle_s5b_candidate(Candidates,
__TopXMLNS)
| _acc]).
'encode_jingle_s5b_transport_$activated'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$activated'(Activated,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_activated(Activated, __TopXMLNS)
| _acc].
'encode_jingle_s5b_transport_$candidate-used'(undefined,
__TopXMLNS, _acc) ->
_acc;
'encode_jingle_s5b_transport_$candidate-used'(Candidate_used,
__TopXMLNS, _acc) ->
[encode_jingle_s5b_candidate_used(Candidate_used,
__TopXMLNS)
| _acc].
decode_jingle_s5b_transport_attr_sid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"sid">>,
<<"transport">>,
__TopXMLNS}});
decode_jingle_s5b_transport_attr_sid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_transport_attr_sid(_val, _acc) ->
[{<<"sid">>, _val} | _acc].
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
undefined) ->
<<>>;
decode_jingle_s5b_transport_attr_dstaddr(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_transport_attr_dstaddr(<<>>, _acc) ->
_acc;
encode_jingle_s5b_transport_attr_dstaddr(_val, _acc) ->
[{<<"dstaddr">>, _val} | _acc].
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
undefined) ->
tcp;
decode_jingle_s5b_transport_attr_mode(__TopXMLNS,
_val) ->
case catch dec_enum(_val, [tcp, udp]) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"mode">>,
<<"transport">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_transport_attr_mode(tcp, _acc) ->
_acc;
encode_jingle_s5b_transport_attr_mode(_val, _acc) ->
[{<<"mode">>, enc_enum(_val)} | _acc].
decode_jingle_s5b_proxy_error(__TopXMLNS, __Opts,
{xmlel, <<"proxy-error">>, _attrs, _els}) ->
'proxy-error'.
encode_jingle_s5b_proxy_error('proxy-error',
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"proxy-error">>, _attrs, _els}.
decode_jingle_s5b_candidate_error(__TopXMLNS, __Opts,
{xmlel,
<<"candidate-error">>,
_attrs,
_els}) ->
'candidate-error'.
encode_jingle_s5b_candidate_error('candidate-error',
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"candidate-error">>, _attrs, _els}.
decode_jingle_s5b_activated(__TopXMLNS, __Opts,
{xmlel, <<"activated">>, _attrs, _els}) ->
Cid = decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
undefined),
Cid.
decode_jingle_s5b_activated_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid) ->
decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
_val);
decode_jingle_s5b_activated_attrs(__TopXMLNS,
[_ | _attrs], Cid) ->
decode_jingle_s5b_activated_attrs(__TopXMLNS,
_attrs,
Cid);
decode_jingle_s5b_activated_attrs(__TopXMLNS, [],
Cid) ->
decode_jingle_s5b_activated_attr_cid(__TopXMLNS, Cid).
encode_jingle_s5b_activated(Cid, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_activated_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"activated">>, _attrs, _els}.
decode_jingle_s5b_activated_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"activated">>,
__TopXMLNS}});
decode_jingle_s5b_activated_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_activated_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
decode_jingle_s5b_candidate(__TopXMLNS, __Opts,
{xmlel, <<"candidate">>, _attrs, _els}) ->
{Cid, Host, Jid, Port, Priority, Type} =
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined),
{jingle_s5b_candidate,
Cid,
Host,
Port,
Jid,
Type,
Priority}.
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid, Host, Jid,
Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
_val,
Host,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"host">>, _val} | _attrs], Cid, _Host,
Jid, Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
_val,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"jid">>, _val} | _attrs], Cid, Host, _Jid,
Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
_val,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"port">>, _val} | _attrs], Cid, Host, Jid,
_Port, Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
_val,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"priority">>, _val} | _attrs], Cid, Host,
Jid, Port, _Priority, Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
_val,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[{<<"type">>, _val} | _attrs], Cid, Host, Jid,
Port, Priority, _Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
Priority,
_val);
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
[_ | _attrs], Cid, Host, Jid, Port, Priority,
Type) ->
decode_jingle_s5b_candidate_attrs(__TopXMLNS,
_attrs,
Cid,
Host,
Jid,
Port,
Priority,
Type);
decode_jingle_s5b_candidate_attrs(__TopXMLNS, [], Cid,
Host, Jid, Port, Priority, Type) ->
{decode_jingle_s5b_candidate_attr_cid(__TopXMLNS, Cid),
decode_jingle_s5b_candidate_attr_host(__TopXMLNS, Host),
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS, Jid),
decode_jingle_s5b_candidate_attr_port(__TopXMLNS, Port),
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
Priority),
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
Type)}.
encode_jingle_s5b_candidate({jingle_s5b_candidate,
Cid,
Host,
Port,
Jid,
Type,
Priority},
__TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_candidate_attr_type(Type,
encode_jingle_s5b_candidate_attr_priority(Priority,
encode_jingle_s5b_candidate_attr_port(Port,
encode_jingle_s5b_candidate_attr_jid(Jid,
encode_jingle_s5b_candidate_attr_host(Host,
encode_jingle_s5b_candidate_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS))))))),
{xmlel, <<"candidate">>, _attrs, _els}.
decode_jingle_s5b_candidate_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_candidate_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
decode_jingle_s5b_candidate_attr_host(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"host">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_host(__TopXMLNS,
_val) ->
case catch dec_ip(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"host">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_host(_val, _acc) ->
[{<<"host">>, enc_ip(_val)} | _acc].
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"jid">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_jid(__TopXMLNS,
_val) ->
case catch jid:decode(_val) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"jid">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_jid(_val, _acc) ->
[{<<"jid">>, jid:encode(_val)} | _acc].
decode_jingle_s5b_candidate_attr_port(__TopXMLNS,
undefined) ->
undefined;
decode_jingle_s5b_candidate_attr_port(__TopXMLNS,
_val) ->
case catch dec_int(_val, 0, 65535) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"port">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_port(undefined,
_acc) ->
_acc;
encode_jingle_s5b_candidate_attr_port(_val, _acc) ->
[{<<"port">>, enc_int(_val)} | _acc].
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"priority">>,
<<"candidate">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_attr_priority(__TopXMLNS,
_val) ->
case catch dec_int(_val, 0, infinity) of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"priority">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_priority(_val, _acc) ->
[{<<"priority">>, enc_int(_val)} | _acc].
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
undefined) ->
direct;
decode_jingle_s5b_candidate_attr_type(__TopXMLNS,
_val) ->
case catch dec_enum(_val,
[assisted, direct, proxy, tunnel])
of
{'EXIT', _} ->
erlang:error({xmpp_codec,
{bad_attr_value,
<<"type">>,
<<"candidate">>,
__TopXMLNS}});
_res -> _res
end.
encode_jingle_s5b_candidate_attr_type(direct, _acc) ->
_acc;
encode_jingle_s5b_candidate_attr_type(_val, _acc) ->
[{<<"type">>, enc_enum(_val)} | _acc].
decode_jingle_s5b_candidate_used(__TopXMLNS, __Opts,
{xmlel, <<"candidate-used">>, _attrs, _els}) ->
Cid = decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
undefined),
Cid.
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
[{<<"cid">>, _val} | _attrs], _Cid) ->
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
_val);
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
[_ | _attrs], Cid) ->
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS,
_attrs,
Cid);
decode_jingle_s5b_candidate_used_attrs(__TopXMLNS, [],
Cid) ->
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
Cid).
encode_jingle_s5b_candidate_used(Cid, __TopXMLNS) ->
__NewTopXMLNS =
xmpp_codec:choose_top_xmlns(<<"urn:xmpp:jingle:transports:s5b:1">>,
[],
__TopXMLNS),
_els = [],
_attrs = encode_jingle_s5b_candidate_used_attr_cid(Cid,
xmpp_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS)),
{xmlel, <<"candidate-used">>, _attrs, _els}.
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
undefined) ->
erlang:error({xmpp_codec,
{missing_attr,
<<"cid">>,
<<"candidate-used">>,
__TopXMLNS}});
decode_jingle_s5b_candidate_used_attr_cid(__TopXMLNS,
_val) ->
_val.
encode_jingle_s5b_candidate_used_attr_cid(_val, _acc) ->
[{<<"cid">>, _val} | _acc].
|
da7a4d2ac15207580aba91d90a280519f66f3149992af10ea053bee349ca5929 | mcgizzle/haxchange | Api.hs | {-# LANGUAGE OverloadedStrings #-}
module <newmodule>.Api where
import Types
( Api
, Ticker(..)
, Currency(..)
, Currency'(..)
, Markets(..)
, Balance(..)
, Order(..))
import qualified Types as T
import <newmodule>.Types
import <newmodule>.Internal
defaultOpts = Opts mempty mempty "public" mempty mempty mempty mempty
ping :: IO (Either Error String)
ping = return $ Left "Implement Me!"
getMarkets :: IO (Either Error Markets)
getTicker :: Markets -> IO (Either Error Tickers)
getTicker mrkt = return $ Left "Implement Me!"
getBalance :: IO (Either Error Balance)
getBalance = withKeys "keys/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
buyLimit :: Order -> IO (Either Error Order)
buyLimit Order{..} = withKeys "key/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
sellLimit :: Order -> IO (Either Error Order)
sellLimit Order{..} = withKeys "keys/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
| null | https://raw.githubusercontent.com/mcgizzle/haxchange/620a4c93ae28abdd637b7c1fd8b018628b3bd0e9/templates/Api.hs | haskell | # LANGUAGE OverloadedStrings # | module <newmodule>.Api where
import Types
( Api
, Ticker(..)
, Currency(..)
, Currency'(..)
, Markets(..)
, Balance(..)
, Order(..))
import qualified Types as T
import <newmodule>.Types
import <newmodule>.Internal
defaultOpts = Opts mempty mempty "public" mempty mempty mempty mempty
ping :: IO (Either Error String)
ping = return $ Left "Implement Me!"
getMarkets :: IO (Either Error Markets)
getTicker :: Markets -> IO (Either Error Tickers)
getTicker mrkt = return $ Left "Implement Me!"
getBalance :: IO (Either Error Balance)
getBalance = withKeys "keys/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
buyLimit :: Order -> IO (Either Error Order)
buyLimit Order{..} = withKeys "key/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
sellLimit :: Order -> IO (Either Error Order)
sellLimit Order{..} = withKeys "keys/<newmodule>" $ \ pubKey privKey -> return $ Left "Implement Me!"
|
97b8a74c3297dddbb9715e0eab49b2603df699ebf2a64c44518bcc532b3d4155 | clojure-interop/java-jdk | core.clj | (ns javax.xml.stream.events.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[javax.xml.stream.events.Attribute])
(require '[javax.xml.stream.events.Characters])
(require '[javax.xml.stream.events.Comment])
(require '[javax.xml.stream.events.DTD])
(require '[javax.xml.stream.events.EndDocument])
(require '[javax.xml.stream.events.EndElement])
(require '[javax.xml.stream.events.EntityDeclaration])
(require '[javax.xml.stream.events.EntityReference])
(require '[javax.xml.stream.events.Namespace])
(require '[javax.xml.stream.events.NotationDeclaration])
(require '[javax.xml.stream.events.ProcessingInstruction])
(require '[javax.xml.stream.events.StartDocument])
(require '[javax.xml.stream.events.StartElement])
(require '[javax.xml.stream.events.XMLEvent])
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/stream/events/core.clj | clojure | (ns javax.xml.stream.events.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[javax.xml.stream.events.Attribute])
(require '[javax.xml.stream.events.Characters])
(require '[javax.xml.stream.events.Comment])
(require '[javax.xml.stream.events.DTD])
(require '[javax.xml.stream.events.EndDocument])
(require '[javax.xml.stream.events.EndElement])
(require '[javax.xml.stream.events.EntityDeclaration])
(require '[javax.xml.stream.events.EntityReference])
(require '[javax.xml.stream.events.Namespace])
(require '[javax.xml.stream.events.NotationDeclaration])
(require '[javax.xml.stream.events.ProcessingInstruction])
(require '[javax.xml.stream.events.StartDocument])
(require '[javax.xml.stream.events.StartElement])
(require '[javax.xml.stream.events.XMLEvent])
|
|
5aa89ae0a8d8750c03abf245d0cf4cbe25460e0ffc59b04ec38e4ad7b714a361 | schell/gelatin | Shader.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
# OPTIONS_GHC -fno - warn - orphans #
{-# OPTIONS_GHC -fprint-explicit-kinds #-}
module Gelatin.GL.Shader (
-- * Compiling and loading shaders
Simple2DShader
, compileOGLShader
, compileOGLProgram
, loadSourcePaths
, compileSources
, compileProgram
, loadSimple2DShader
) where
import Control.Exception (assert)
import Control.Monad
import Control.Monad.Except (MonadError, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.ByteString.Char8 as B
import qualified Data.Foldable as F
import Data.Proxy (Proxy (..))
import qualified Data.Vector.Storable as S
import Data.Vector.Unboxed (Unbox, Vector)
import qualified Data.Vector.Unboxed as V
import Foreign.C.String
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import GHC.TypeLits (KnownNat, KnownSymbol, natVal)
import Graphics.GL.Core33
import Graphics.GL.Types
import Prelude hiding (init)
import Prelude as P
import Gelatin
import Gelatin.GL.TH
import Gelatin.Shaders
type Simple2DShader = GLuint
--------------------------------------------------------------------------------
IsShaderType instances
--------------------------------------------------------------------------------
instance IsShaderType VertexShader GLenum where
getShaderType _ = GL_VERTEX_SHADER
instance IsShaderType FragmentShader GLenum where
getShaderType _ = GL_FRAGMENT_SHADER
--------------------------------------------------------------------------------
-- Uniform marshaling functions
--------------------------------------------------------------------------------
$(genUniform [t|Bool|] [| \loc bool ->
glUniform1i loc $ if bool then 1 else 0 |])
$(genUniform [t|Int|] [| \loc enum ->
glUniform1i loc $ fromIntegral $ fromEnum enum |])
$(genUniform [t|PrimType|] [| \loc enum ->
glUniform1i loc $ fromIntegral $ fromEnum enum |])
$(genUniform [t|Float|] [| \loc float ->
glUniform1f loc $ realToFrac float |])
$(genUniform [t|V2 Float|] [| \loc v ->
let V2 x y = fmap realToFrac v
in glUniform2f loc x y |])
$(genUniform [t|V3 Float|] [| \loc v ->
let V3 x y z = fmap realToFrac v
in glUniform3f loc x y z|])
$(genUniform [t|V4 Float|] [| \loc v ->
let (V4 r g b a) = realToFrac <$> v
in glUniform4f loc r g b a |])
$(genUniform [t|M44 Float|] [| \loc val ->
with val $ glUniformMatrix4fv loc 1 GL_TRUE . castPtr |])
$(genUniform [t|(Int,Int)|] [| \loc (a, b) ->
let [x,y] = P.map fromIntegral [a, b]
in glUniform2i loc x y |])
$(genUniform [t|(LineCap,LineCap)|] [| \loc (a, b) ->
let [x,y] = P.map (fromIntegral . fromEnum) [a, b]
in glUniform2f loc x y |])
$(genUniform [t|V2 Int|] [| \loc v ->
let V2 x y = fmap fromIntegral v
in glUniform2i loc x y |])
--------------------------------------------------------------------------------
-- Attribute buffering and toggling
--------------------------------------------------------------------------------
convertVec
:: (Unbox (f Float), Foldable f) => Vector (f Float) -> S.Vector GLfloat
convertVec =
S.convert . V.map realToFrac . V.concatMap (V.fromList . F.toList)
instance
( KnownNat loc, KnownSymbol name
, Foldable f
, Unbox (f Float), Storable (f Float)
) => HasGenFunc (AttributeBuffering (Attribute name (f Float) loc)) where
type GenFunc (AttributeBuffering (Attribute name (f Float) loc)) =
GLint -> GLuint -> Vector (f Float) -> IO ()
genFunction _ n buf as = do
let loc = fromIntegral $ natVal (Proxy :: Proxy loc)
asize = V.length as * sizeOf (V.head as)
glBindBuffer GL_ARRAY_BUFFER buf
S.unsafeWith (convertVec as) $ \ptr ->
glBufferData GL_ARRAY_BUFFER (fromIntegral asize) (castPtr ptr) GL_STATIC_DRAW
glEnableVertexAttribArray loc
glVertexAttribPointer loc n GL_FLOAT GL_FALSE 0 nullPtr
err <- glGetError
when (err /= 0) $ do
print err
assert False $ return ()
instance (KnownNat loc, KnownSymbol name)
=> HasGenFunc (AttributeToggling (Attribute name val loc)) where
type GenFunc (AttributeToggling (Attribute name val loc)) = (IO (), IO ())
genFunction _ =
let aloc = fromIntegral $ natVal (Proxy :: Proxy loc)
in (glEnableVertexAttribArray aloc, glDisableVertexAttribArray aloc)
--------------------------------------------------------------------------------
-- OpenGL shader only stuff
--------------------------------------------------------------------------------
compileOGLShader :: (MonadIO m, MonadError String m)
=> ByteString
-- ^ The shader source
-> GLenum
-- ^ The shader type (vertex, frag, etc)
-> m GLuint
-- ^ Either an error message or the generated shader handle.
compileOGLShader src shType = do
shader <- liftIO $ glCreateShader shType
if shader == 0
then throwError "Could not create shader"
else do
success <- liftIO $ do
withCString (B.unpack src) $ \ptr ->
with ptr $ \ptrptr -> glShaderSource shader 1 ptrptr nullPtr
glCompileShader shader
with (0 :: GLint) $ \ptr -> do
glGetShaderiv shader GL_COMPILE_STATUS ptr
peek ptr
if success == GL_FALSE
then do
err <- liftIO $ do
infoLog <- with (0 :: GLint) $ \ptr -> do
glGetShaderiv shader GL_INFO_LOG_LENGTH ptr
logsize <- peek ptr
allocaArray (fromIntegral logsize) $ \logptr -> do
glGetShaderInfoLog shader logsize nullPtr logptr
peekArray (fromIntegral logsize) logptr
return $ P.unlines [ "Could not compile shader:"
, B.unpack src
, P.map (toEnum . fromEnum) infoLog
]
throwError err
else return shader
compileOGLProgram :: (MonadIO m, MonadError String m)
=> [(String, Integer)] -> [GLuint] -> m GLuint
compileOGLProgram attribs shaders = do
(program, success) <- liftIO $ do
program <- glCreateProgram
forM_ shaders (glAttachShader program)
forM_ attribs $ \(name, loc) ->
withCString name $ glBindAttribLocation program $ fromIntegral loc
glLinkProgram program
success <- with (0 :: GLint) $ \ptr -> do
glGetProgramiv program GL_LINK_STATUS ptr
peek ptr
return (program, success)
if success == GL_FALSE
then do
err <- liftIO $ with (0 :: GLint) $ \ptr -> do
glGetProgramiv program GL_INFO_LOG_LENGTH ptr
logsize <- peek ptr
infoLog <- allocaArray (fromIntegral logsize) $ \logptr -> do
glGetProgramInfoLog program logsize nullPtr logptr
peekArray (fromIntegral logsize) logptr
return $ P.unlines [ "Could not link program"
, P.map (toEnum . fromEnum) infoLog
]
throwError err
else do
liftIO $ forM_ shaders glDeleteShader
return program
--------------------------------------------------------------------------------
-- Loading shaders and compiling a program.
--------------------------------------------------------------------------------
loadSourcePaths :: MonadIO m
=> ShaderSteps (ts :: [*]) FilePath
-> m (ShaderSteps ts ByteString)
loadSourcePaths = (ShaderSteps <$>) . mapM (liftIO . B.readFile) . unShaderSteps
compileSources
:: forall m ts. (MonadIO m, MonadError String m, IsShaderType ts [GLenum])
=> ShaderSteps (ts :: [*]) ByteString
-> m (ShaderSteps ts GLuint)
compileSources =
(ShaderSteps <$>) . zipWithM (flip compileOGLShader) types . unShaderSteps
where types = getShaderType (Proxy :: Proxy ts)
compileProgram
:: (MonadIO m, MonadError String m, GetLits as [(String, Integer)])
=> Proxy (as :: [*])
-> ShaderSteps (ts :: [*]) GLuint
-> m GLuint
compileProgram p = compileOGLProgram (getSymbols p) . unShaderSteps
-- | Compile all shader programs and return a "sum renderer".
loadSimple2DShader :: (MonadIO m, MonadError String m) => m Simple2DShader
loadSimple2DShader = do
vertName <- liftIO simple2dVertFilePath
fragName <- liftIO simple2dFragFilePath
let paths :: ShaderSteps '[VertexShader, FragmentShader] FilePath
paths = ShaderSteps [vertName, fragName]
sources <- loadSourcePaths paths
shaders <- compileSources sources
compileProgram (Proxy :: Proxy Simple2DAttribs) shaders
| null | https://raw.githubusercontent.com/schell/gelatin/04c1c83d4297eac4f4cc5e8e5c805b1600b3ee98/gelatin-gl/src/Gelatin/GL/Shader.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
# LANGUAGE TypeSynonymInstances #
# OPTIONS_GHC -fprint-explicit-kinds #
* Compiling and loading shaders
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Uniform marshaling functions
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Attribute buffering and toggling
------------------------------------------------------------------------------
------------------------------------------------------------------------------
OpenGL shader only stuff
------------------------------------------------------------------------------
^ The shader source
^ The shader type (vertex, frag, etc)
^ Either an error message or the generated shader handle.
------------------------------------------------------------------------------
Loading shaders and compiling a program.
------------------------------------------------------------------------------
| Compile all shader programs and return a "sum renderer". | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
module Gelatin.GL.Shader (
Simple2DShader
, compileOGLShader
, compileOGLProgram
, loadSourcePaths
, compileSources
, compileProgram
, loadSimple2DShader
) where
import Control.Exception (assert)
import Control.Monad
import Control.Monad.Except (MonadError, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.ByteString.Char8 as B
import qualified Data.Foldable as F
import Data.Proxy (Proxy (..))
import qualified Data.Vector.Storable as S
import Data.Vector.Unboxed (Unbox, Vector)
import qualified Data.Vector.Unboxed as V
import Foreign.C.String
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import GHC.TypeLits (KnownNat, KnownSymbol, natVal)
import Graphics.GL.Core33
import Graphics.GL.Types
import Prelude hiding (init)
import Prelude as P
import Gelatin
import Gelatin.GL.TH
import Gelatin.Shaders
type Simple2DShader = GLuint
IsShaderType instances
instance IsShaderType VertexShader GLenum where
getShaderType _ = GL_VERTEX_SHADER
instance IsShaderType FragmentShader GLenum where
getShaderType _ = GL_FRAGMENT_SHADER
$(genUniform [t|Bool|] [| \loc bool ->
glUniform1i loc $ if bool then 1 else 0 |])
$(genUniform [t|Int|] [| \loc enum ->
glUniform1i loc $ fromIntegral $ fromEnum enum |])
$(genUniform [t|PrimType|] [| \loc enum ->
glUniform1i loc $ fromIntegral $ fromEnum enum |])
$(genUniform [t|Float|] [| \loc float ->
glUniform1f loc $ realToFrac float |])
$(genUniform [t|V2 Float|] [| \loc v ->
let V2 x y = fmap realToFrac v
in glUniform2f loc x y |])
$(genUniform [t|V3 Float|] [| \loc v ->
let V3 x y z = fmap realToFrac v
in glUniform3f loc x y z|])
$(genUniform [t|V4 Float|] [| \loc v ->
let (V4 r g b a) = realToFrac <$> v
in glUniform4f loc r g b a |])
$(genUniform [t|M44 Float|] [| \loc val ->
with val $ glUniformMatrix4fv loc 1 GL_TRUE . castPtr |])
$(genUniform [t|(Int,Int)|] [| \loc (a, b) ->
let [x,y] = P.map fromIntegral [a, b]
in glUniform2i loc x y |])
$(genUniform [t|(LineCap,LineCap)|] [| \loc (a, b) ->
let [x,y] = P.map (fromIntegral . fromEnum) [a, b]
in glUniform2f loc x y |])
$(genUniform [t|V2 Int|] [| \loc v ->
let V2 x y = fmap fromIntegral v
in glUniform2i loc x y |])
convertVec
:: (Unbox (f Float), Foldable f) => Vector (f Float) -> S.Vector GLfloat
convertVec =
S.convert . V.map realToFrac . V.concatMap (V.fromList . F.toList)
instance
( KnownNat loc, KnownSymbol name
, Foldable f
, Unbox (f Float), Storable (f Float)
) => HasGenFunc (AttributeBuffering (Attribute name (f Float) loc)) where
type GenFunc (AttributeBuffering (Attribute name (f Float) loc)) =
GLint -> GLuint -> Vector (f Float) -> IO ()
genFunction _ n buf as = do
let loc = fromIntegral $ natVal (Proxy :: Proxy loc)
asize = V.length as * sizeOf (V.head as)
glBindBuffer GL_ARRAY_BUFFER buf
S.unsafeWith (convertVec as) $ \ptr ->
glBufferData GL_ARRAY_BUFFER (fromIntegral asize) (castPtr ptr) GL_STATIC_DRAW
glEnableVertexAttribArray loc
glVertexAttribPointer loc n GL_FLOAT GL_FALSE 0 nullPtr
err <- glGetError
when (err /= 0) $ do
print err
assert False $ return ()
instance (KnownNat loc, KnownSymbol name)
=> HasGenFunc (AttributeToggling (Attribute name val loc)) where
type GenFunc (AttributeToggling (Attribute name val loc)) = (IO (), IO ())
genFunction _ =
let aloc = fromIntegral $ natVal (Proxy :: Proxy loc)
in (glEnableVertexAttribArray aloc, glDisableVertexAttribArray aloc)
compileOGLShader :: (MonadIO m, MonadError String m)
=> ByteString
-> GLenum
-> m GLuint
compileOGLShader src shType = do
shader <- liftIO $ glCreateShader shType
if shader == 0
then throwError "Could not create shader"
else do
success <- liftIO $ do
withCString (B.unpack src) $ \ptr ->
with ptr $ \ptrptr -> glShaderSource shader 1 ptrptr nullPtr
glCompileShader shader
with (0 :: GLint) $ \ptr -> do
glGetShaderiv shader GL_COMPILE_STATUS ptr
peek ptr
if success == GL_FALSE
then do
err <- liftIO $ do
infoLog <- with (0 :: GLint) $ \ptr -> do
glGetShaderiv shader GL_INFO_LOG_LENGTH ptr
logsize <- peek ptr
allocaArray (fromIntegral logsize) $ \logptr -> do
glGetShaderInfoLog shader logsize nullPtr logptr
peekArray (fromIntegral logsize) logptr
return $ P.unlines [ "Could not compile shader:"
, B.unpack src
, P.map (toEnum . fromEnum) infoLog
]
throwError err
else return shader
compileOGLProgram :: (MonadIO m, MonadError String m)
=> [(String, Integer)] -> [GLuint] -> m GLuint
compileOGLProgram attribs shaders = do
(program, success) <- liftIO $ do
program <- glCreateProgram
forM_ shaders (glAttachShader program)
forM_ attribs $ \(name, loc) ->
withCString name $ glBindAttribLocation program $ fromIntegral loc
glLinkProgram program
success <- with (0 :: GLint) $ \ptr -> do
glGetProgramiv program GL_LINK_STATUS ptr
peek ptr
return (program, success)
if success == GL_FALSE
then do
err <- liftIO $ with (0 :: GLint) $ \ptr -> do
glGetProgramiv program GL_INFO_LOG_LENGTH ptr
logsize <- peek ptr
infoLog <- allocaArray (fromIntegral logsize) $ \logptr -> do
glGetProgramInfoLog program logsize nullPtr logptr
peekArray (fromIntegral logsize) logptr
return $ P.unlines [ "Could not link program"
, P.map (toEnum . fromEnum) infoLog
]
throwError err
else do
liftIO $ forM_ shaders glDeleteShader
return program
loadSourcePaths :: MonadIO m
=> ShaderSteps (ts :: [*]) FilePath
-> m (ShaderSteps ts ByteString)
loadSourcePaths = (ShaderSteps <$>) . mapM (liftIO . B.readFile) . unShaderSteps
compileSources
:: forall m ts. (MonadIO m, MonadError String m, IsShaderType ts [GLenum])
=> ShaderSteps (ts :: [*]) ByteString
-> m (ShaderSteps ts GLuint)
compileSources =
(ShaderSteps <$>) . zipWithM (flip compileOGLShader) types . unShaderSteps
where types = getShaderType (Proxy :: Proxy ts)
compileProgram
:: (MonadIO m, MonadError String m, GetLits as [(String, Integer)])
=> Proxy (as :: [*])
-> ShaderSteps (ts :: [*]) GLuint
-> m GLuint
compileProgram p = compileOGLProgram (getSymbols p) . unShaderSteps
loadSimple2DShader :: (MonadIO m, MonadError String m) => m Simple2DShader
loadSimple2DShader = do
vertName <- liftIO simple2dVertFilePath
fragName <- liftIO simple2dFragFilePath
let paths :: ShaderSteps '[VertexShader, FragmentShader] FilePath
paths = ShaderSteps [vertName, fragName]
sources <- loadSourcePaths paths
shaders <- compileSources sources
compileProgram (Proxy :: Proxy Simple2DAttribs) shaders
|
e31fdc6b4dfe687578f50dd7f3093c963bfec9e1cd456d105a1846e0366e3cc3 | arichiardi/replumb | runner.cljs | (ns launcher.runner
(:require [doo.runner :as doo :refer-macros [doo-tests]]
replumb.core-test
replumb.repl-test
replumb.common-test
replumb.load-test
replumb.options-test
replumb.macro-test
TODO browser test
TODO browser test
TODO port it to the new test way
(enable-console-print!)
;; Or doo will exit with an error, see:
;; #issuecomment-165498172
(set! (.-error js/console) (fn [x] (.log js/console x)))
(set! goog.DEBUG false)
(doo-tests 'replumb.core-test
'replumb.repl-test
'replumb.common-test
'replumb.load-test
'replumb.options-test
'replumb.macro-test
#_'replumb.require-test
#_'replumb.source-test
#_'replumb.cache-node-test)
| null | https://raw.githubusercontent.com/arichiardi/replumb/dde2228f2e364c3bafdf6585bb1bc1c27a3e336c/test/browser/launcher/runner.cljs | clojure | Or doo will exit with an error, see:
#issuecomment-165498172 | (ns launcher.runner
(:require [doo.runner :as doo :refer-macros [doo-tests]]
replumb.core-test
replumb.repl-test
replumb.common-test
replumb.load-test
replumb.options-test
replumb.macro-test
TODO browser test
TODO browser test
TODO port it to the new test way
(enable-console-print!)
(set! (.-error js/console) (fn [x] (.log js/console x)))
(set! goog.DEBUG false)
(doo-tests 'replumb.core-test
'replumb.repl-test
'replumb.common-test
'replumb.load-test
'replumb.options-test
'replumb.macro-test
#_'replumb.require-test
#_'replumb.source-test
#_'replumb.cache-node-test)
|
d310d010802cd9328fc4c1351376d09f9944b5d117f0207e512601bb31a8a3aa | ankushdas/Nomos | typecheck.ml | module P = Print
type context = (string * Ast.ocamlTP) list
exception TypeError of string
let format_err (e : Ast.ocamlTP Ast.aug_expr) =
let a : string = P.print_ast(e.structure) in
let b : string = P.print_type(e.data) in
Printf.sprintf "expression %s did not have type %s" a b
let rec get_result_type (t : Ast.ocamlTP) =
match t with
Ast.Arrow(t1, t2) -> get_result_type(t2)
| _ -> t
let rec type_equals (t1 : Ast.ocamlTP) (t2 : Ast.ocamlTP) =
match (t1, t2) with
(Ast.Integer, Ast.Integer) -> true
| (Ast.Boolean, Ast.Boolean) -> true
| (Ast.Arrow(x, y), Ast.Arrow(a, b)) -> (type_equals x a) && (type_equals y b)
| (Ast.ListTP(a), Ast.ListTP(b)) -> type_equals a b
| _ -> false
let rec getType (ctx : context) (x : string) =
match ctx with
[] -> raise (TypeError (Printf.sprintf "Unbound variable %s" x))
| (y, tp)::xs -> if x = y then tp else getType xs x
let rec typecheck ( ctx : context ) ( e : Ast.expr ) ( t : Ast.ocamlTP ) : bool =
match e with
, e2 , e3 ) - > let t1 = Ast . Boolean in
let t2 = e2 t in
let t3 = e3 t in
if t1 & & t2 & & t3 then true else raise ( TypeError ( format_err e t ) )
| LetIn ( Ast . Binding(var , expr , ) , e ) - > if ( expr typ ) & &
( ( ( var , typ)::ctx ) e t )
then true
else raise ( TypeError ( format_err e t ) )
| Bool _ - > if t = Ast . Boolean then true else raise ( TypeError ( format_err e t ) )
| Int _ - > if t = Ast . Integer then true else raise ( TypeError ( format_err e t ) )
| Var(x ) - > if t = ( ) then true else raise ( TypeError ( format_err e t ) )
| List ( l ) - > ( match ( t , l ) with
( ListTP(t1 ) , [ ] ) - > true
| ( ListTP(t1 ) , e::es ) - > if ( t1 ) & & ( ( List(es ) ) t )
then true else raise ( TypeError ( format_err e t ) )
| _ - > raise ( TypeError ( format_err e t ) ) )
| App ( l ) - > ( match l with
[ ] - > raise ( TypeError " Impossible " )
| [ x ] - > raise ( TypeError " Impossible " )
| ( e1 , t1)::es - > let t2 = get_peeled_type es t1 in type_equals t2 t )
| Cons ( x , xs ) - > ( match t with
ListTP(t1 ) - > if ( t1 ) & & ( t )
then true else raise ( TypeError ( format_err e t ) )
| _ - > raise ( TypeError ( format_err e t ) ) )
| Match ( ( e1,t1 ) , e2 , id1 , id2 , e3 ) - > ( * Should add check for duplicate variables
match e with
If(e1, e2, e3) -> let t1 = typecheck ctx e1 Ast.Boolean in
let t2 = typecheck ctx e2 t in
let t3 = typecheck ctx e3 t in
if t1 && t2 && t3 then true else raise (TypeError (format_err e t))
| LetIn (Ast.Binding(var, expr, typ), e) -> if (typecheck ctx expr typ) &&
(typecheck ((var, typ)::ctx) e t)
then true
else raise (TypeError (format_err e t))
| Bool _ -> if t = Ast.Boolean then true else raise (TypeError (format_err e t))
| Int _ -> if t = Ast.Integer then true else raise (TypeError (format_err e t))
| Var(x) -> if t = (getType ctx x) then true else raise (TypeError (format_err e t))
| List (l) -> (match (t, l) with
(ListTP(t1), []) -> true
| (ListTP(t1), e::es) -> if (typecheck ctx e t1) && (typecheck ctx (List(es)) t)
then true else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| App (l) -> (match l with
[] -> raise (TypeError "Impossible")
| [x] -> raise (TypeError "Impossible")
| (e1, t1)::es -> let t2 = get_peeled_type es t1 in type_equals t2 t)
| Cons (x, xs) -> (match t with
ListTP(t1) -> if (typecheck ctx x t1) && (typecheck ctx xs t)
then true else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| Match ((e1,t1), e2, id1, id2, e3) -> (* Should add check for duplicate variables *)
(match t1 with
ListTP(t2) -> if (typecheck ctx e1 t1)
&&
(typecheck ctx e2 t)
&& (typecheck ((id1, t2)::(id2, t1)::ctx)
e3 t)
then true
else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| Lambda(l, e) -> (match t with
Arrow(t1, t2) ->
let (len, ctx') = addArglist l ctx in
if (typecheck ctx' e (get_result_type t))
then true
else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| Op (e1, op, e2) -> let a : bool = typecheck ctx e1 t in
let b : bool = typecheck ctx e2 t in
if a && b && (type_equals t Ast.Integer)
then true
else raise (TypeError (format_err e t))
| Ast.CompOp (e1, op, e2) ->
let a : bool = typecheck ctx e1 (Ast.Integer) in
let b : bool = typecheck ctx e2 (Ast.Integer) in
if a && b && (type_equals t Ast.Boolean)
then true
else raise (TypeError (format_err e t))
| Ast.RelOp (e1, op, e2) -> let a : bool = typecheck ctx e1 (Ast.Boolean) in
let b : bool = typecheck ctx e2 (Ast.Boolean) in
if a && b && (type_equals t Ast.Boolean)
then true
else raise (TypeError (format_err e t))
and checkArglist (l : Ast.arglist) (t : Ast.ocamlTP) =
match l with
Ast.Single(_, t1) -> t1 = t
| Ast.Curry ((_, t1), rest) -> match t with
Arrow(t2, t3) -> if (type_equals t1 t2) && (checkArglist rest t3)
then true
else false
| _ -> false
and addArglist l ctx = match l with
Ast.Single(x, t1) -> (1, (x,t1)::ctx)
| Ast.Curry((x,t1), rest) ->
let
(len, ctx') = addArglist rest ctx
in
(len + 1, (x,t1)::ctx')
and get_peeled_type l t = match (l, t) with
([], _) -> raise (TypeError "Impossible")
| ([(e1, t1)], Arrow(t2, t3)) -> if (type_equals t1 t2) then t3 else raise (TypeError "app rule failed")
| ((e1, t1)::es, Arrow(t2, t3)) -> if (type_equals t1 t2) then get_peeled_type es t3 else raise (TypeError "app rule failed")
| _ -> raise (TypeError "Impossible")
*)
| null | https://raw.githubusercontent.com/ankushdas/Nomos/db678f3981e75a1b3310bb55f66009bb23430cb1/redundant/functional/typecheck.ml | ocaml | Should add check for duplicate variables | module P = Print
type context = (string * Ast.ocamlTP) list
exception TypeError of string
let format_err (e : Ast.ocamlTP Ast.aug_expr) =
let a : string = P.print_ast(e.structure) in
let b : string = P.print_type(e.data) in
Printf.sprintf "expression %s did not have type %s" a b
let rec get_result_type (t : Ast.ocamlTP) =
match t with
Ast.Arrow(t1, t2) -> get_result_type(t2)
| _ -> t
let rec type_equals (t1 : Ast.ocamlTP) (t2 : Ast.ocamlTP) =
match (t1, t2) with
(Ast.Integer, Ast.Integer) -> true
| (Ast.Boolean, Ast.Boolean) -> true
| (Ast.Arrow(x, y), Ast.Arrow(a, b)) -> (type_equals x a) && (type_equals y b)
| (Ast.ListTP(a), Ast.ListTP(b)) -> type_equals a b
| _ -> false
let rec getType (ctx : context) (x : string) =
match ctx with
[] -> raise (TypeError (Printf.sprintf "Unbound variable %s" x))
| (y, tp)::xs -> if x = y then tp else getType xs x
let rec typecheck ( ctx : context ) ( e : Ast.expr ) ( t : Ast.ocamlTP ) : bool =
match e with
, e2 , e3 ) - > let t1 = Ast . Boolean in
let t2 = e2 t in
let t3 = e3 t in
if t1 & & t2 & & t3 then true else raise ( TypeError ( format_err e t ) )
| LetIn ( Ast . Binding(var , expr , ) , e ) - > if ( expr typ ) & &
( ( ( var , typ)::ctx ) e t )
then true
else raise ( TypeError ( format_err e t ) )
| Bool _ - > if t = Ast . Boolean then true else raise ( TypeError ( format_err e t ) )
| Int _ - > if t = Ast . Integer then true else raise ( TypeError ( format_err e t ) )
| Var(x ) - > if t = ( ) then true else raise ( TypeError ( format_err e t ) )
| List ( l ) - > ( match ( t , l ) with
( ListTP(t1 ) , [ ] ) - > true
| ( ListTP(t1 ) , e::es ) - > if ( t1 ) & & ( ( List(es ) ) t )
then true else raise ( TypeError ( format_err e t ) )
| _ - > raise ( TypeError ( format_err e t ) ) )
| App ( l ) - > ( match l with
[ ] - > raise ( TypeError " Impossible " )
| [ x ] - > raise ( TypeError " Impossible " )
| ( e1 , t1)::es - > let t2 = get_peeled_type es t1 in type_equals t2 t )
| Cons ( x , xs ) - > ( match t with
ListTP(t1 ) - > if ( t1 ) & & ( t )
then true else raise ( TypeError ( format_err e t ) )
| _ - > raise ( TypeError ( format_err e t ) ) )
| Match ( ( e1,t1 ) , e2 , id1 , id2 , e3 ) - > ( * Should add check for duplicate variables
match e with
If(e1, e2, e3) -> let t1 = typecheck ctx e1 Ast.Boolean in
let t2 = typecheck ctx e2 t in
let t3 = typecheck ctx e3 t in
if t1 && t2 && t3 then true else raise (TypeError (format_err e t))
| LetIn (Ast.Binding(var, expr, typ), e) -> if (typecheck ctx expr typ) &&
(typecheck ((var, typ)::ctx) e t)
then true
else raise (TypeError (format_err e t))
| Bool _ -> if t = Ast.Boolean then true else raise (TypeError (format_err e t))
| Int _ -> if t = Ast.Integer then true else raise (TypeError (format_err e t))
| Var(x) -> if t = (getType ctx x) then true else raise (TypeError (format_err e t))
| List (l) -> (match (t, l) with
(ListTP(t1), []) -> true
| (ListTP(t1), e::es) -> if (typecheck ctx e t1) && (typecheck ctx (List(es)) t)
then true else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| App (l) -> (match l with
[] -> raise (TypeError "Impossible")
| [x] -> raise (TypeError "Impossible")
| (e1, t1)::es -> let t2 = get_peeled_type es t1 in type_equals t2 t)
| Cons (x, xs) -> (match t with
ListTP(t1) -> if (typecheck ctx x t1) && (typecheck ctx xs t)
then true else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
(match t1 with
ListTP(t2) -> if (typecheck ctx e1 t1)
&&
(typecheck ctx e2 t)
&& (typecheck ((id1, t2)::(id2, t1)::ctx)
e3 t)
then true
else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| Lambda(l, e) -> (match t with
Arrow(t1, t2) ->
let (len, ctx') = addArglist l ctx in
if (typecheck ctx' e (get_result_type t))
then true
else raise (TypeError (format_err e t))
| _ -> raise (TypeError (format_err e t)))
| Op (e1, op, e2) -> let a : bool = typecheck ctx e1 t in
let b : bool = typecheck ctx e2 t in
if a && b && (type_equals t Ast.Integer)
then true
else raise (TypeError (format_err e t))
| Ast.CompOp (e1, op, e2) ->
let a : bool = typecheck ctx e1 (Ast.Integer) in
let b : bool = typecheck ctx e2 (Ast.Integer) in
if a && b && (type_equals t Ast.Boolean)
then true
else raise (TypeError (format_err e t))
| Ast.RelOp (e1, op, e2) -> let a : bool = typecheck ctx e1 (Ast.Boolean) in
let b : bool = typecheck ctx e2 (Ast.Boolean) in
if a && b && (type_equals t Ast.Boolean)
then true
else raise (TypeError (format_err e t))
and checkArglist (l : Ast.arglist) (t : Ast.ocamlTP) =
match l with
Ast.Single(_, t1) -> t1 = t
| Ast.Curry ((_, t1), rest) -> match t with
Arrow(t2, t3) -> if (type_equals t1 t2) && (checkArglist rest t3)
then true
else false
| _ -> false
and addArglist l ctx = match l with
Ast.Single(x, t1) -> (1, (x,t1)::ctx)
| Ast.Curry((x,t1), rest) ->
let
(len, ctx') = addArglist rest ctx
in
(len + 1, (x,t1)::ctx')
and get_peeled_type l t = match (l, t) with
([], _) -> raise (TypeError "Impossible")
| ([(e1, t1)], Arrow(t2, t3)) -> if (type_equals t1 t2) then t3 else raise (TypeError "app rule failed")
| ((e1, t1)::es, Arrow(t2, t3)) -> if (type_equals t1 t2) then get_peeled_type es t3 else raise (TypeError "app rule failed")
| _ -> raise (TypeError "Impossible")
*)
|
cce526a1d88eac768ff408c7caadf3c24e788cbdbefe56d0ed741a84ea312cb1 | tisnik/clojure-examples | core_test.clj | ;
( C ) Copyright 2018 , 2020
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(ns cucumber+expect2.core-test
(:require [clojure.test :refer :all]
[cucumber+expect2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/cucumber%2Bexpect2/test/cucumber%2Bexpect2/core_test.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2018 , 2020
-v10.html
(ns cucumber+expect2.core-test
(:require [clojure.test :refer :all]
[cucumber+expect2.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
013f968cc7e30375931f53d535e42297b4b33e35b07925ad8755ec03496f5674 | zenspider/schemers | exercise.2.13.scm | #lang racket/base
Exercise 2.13 :
;; Show that under the assumption of small percentage tolerances there
;; is a simple formula for the approximate percentage tolerance of the
product of two intervals in terms of the tolerances of the factors .
;; You may simplify the problem by assuming that all numbers are
;; positive.
;; no
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_2/exercise.2.13.scm | scheme | Show that under the assumption of small percentage tolerances there
is a simple formula for the approximate percentage tolerance of the
You may simplify the problem by assuming that all numbers are
positive.
no | #lang racket/base
Exercise 2.13 :
product of two intervals in terms of the tolerances of the factors .
|
4a70ccb8a85d596a24aa468aa5de57de2e47a511090a0d6ecc7e4fdb05350aa6 | mattboehm/dottask | project.clj | (defproject dottask "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[binaryage/devtools "0.5.2"]
[funcool/tubax "0.2.0"]
[historian "1.1.1"]
[reagent "0.5.1"]
[sablono "0.3.6"]]
:plugins [[lein-figwheel "0.5.0-1"]
[lein-cljsbuild "1.1.3"]
[lein-gossip "0.1.0-SNAPSHOT"]]
:clean-targets [:target-path "out"]
:cljsbuild {
:builds [{:id "dev"
:source-paths ["src"]
:figwheel {:on-jsload "dottask.graph/render!"}
:compiler {:main "dottask.graph"}
}
{:id "help"
:source-paths ["src"]
:figwheel {:on-jsload "dottask.help/render!"}
:compiler {:main "dottask.help"
:pretty-print false
:output-to "help.js"}
}
{:id "release"
:source-paths ["src"]
:compiler {
:main "dottask.graph"
:output-to "out/main.js"
:output-dir "out"
:optimizations :advanced
:pretty-print false
:source-map "out/main.js.map"}
}
{:id "help-release"
:source-paths ["src"]
:compiler {
:main "dottask.help"
:output-to "out/help.js"
:output-dir "out"
:optimizations :advanced
:pretty-print false
:source-map "out/help.js.map"}
}
]
}
:figwheel {
:css-dirs ["css"]
}
)
| null | https://raw.githubusercontent.com/mattboehm/dottask/0e481424a6a1f2fa60620af99e73e2efe218ca88/project.clj | clojure | (defproject dottask "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.7.0"]
[org.clojure/clojurescript "1.7.170"]
[binaryage/devtools "0.5.2"]
[funcool/tubax "0.2.0"]
[historian "1.1.1"]
[reagent "0.5.1"]
[sablono "0.3.6"]]
:plugins [[lein-figwheel "0.5.0-1"]
[lein-cljsbuild "1.1.3"]
[lein-gossip "0.1.0-SNAPSHOT"]]
:clean-targets [:target-path "out"]
:cljsbuild {
:builds [{:id "dev"
:source-paths ["src"]
:figwheel {:on-jsload "dottask.graph/render!"}
:compiler {:main "dottask.graph"}
}
{:id "help"
:source-paths ["src"]
:figwheel {:on-jsload "dottask.help/render!"}
:compiler {:main "dottask.help"
:pretty-print false
:output-to "help.js"}
}
{:id "release"
:source-paths ["src"]
:compiler {
:main "dottask.graph"
:output-to "out/main.js"
:output-dir "out"
:optimizations :advanced
:pretty-print false
:source-map "out/main.js.map"}
}
{:id "help-release"
:source-paths ["src"]
:compiler {
:main "dottask.help"
:output-to "out/help.js"
:output-dir "out"
:optimizations :advanced
:pretty-print false
:source-map "out/help.js.map"}
}
]
}
:figwheel {
:css-dirs ["css"]
}
)
|
|
e6547c36664b1f3d309485ddbcedfbcc354b605029189a63909a73f7c2028b3e | Helium4Haskell/helium | ClassInstaneError16.hs | class X a where
f :: a -> Int
instance Y a => X (Maybe a) where
f _ = 3 | null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeClasses/ClassInstaneError16.hs | haskell | class X a where
f :: a -> Int
instance Y a => X (Maybe a) where
f _ = 3 |
|
fb7ddb3df90b157944198b525772d4048ad3b6f7216b07bf80a89dac793ddbea | ocaml-multicore/tezos | script_cache.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
Testing
-------
Component : cache
Invocation : dune exec / long_tests / main.exe -- cache
Subject : Testing the script cache
Most of the tests need to fill the cache , which takes ~2 minutes on a
fast machine . This is why this test is in the " long test " category .
If at some point the cache layout can be set through protocol parameters ,
then we may consider duplicating these tests in the too .
-------
Component: cache
Invocation: dune exec tezt/long_tests/main.exe -- cache
Subject: Testing the script cache
Most of the tests need to fill the cache, which takes ~2 minutes on a
fast machine. This is why this test is in the "long test" category.
If at some point the cache layout can be set through protocol parameters,
then we may consider duplicating these tests in the CI too.
*)
(*
Helpers
=======
*)
RPC helpers
-----------
RPC helpers
-----------
*)
let get_operations client =
let* operations = RPC.get_operations client in
return JSON.(operations |> geti 3 |> geti 0 |> get "contents")
let read_consumed_gas operation =
JSON.(
operation |> get "metadata" |> get "operation_result" |> get "consumed_gas"
|> as_int)
let get_consumed_gas client =
JSON.(
let* operations = get_operations client in
return @@ read_consumed_gas (operations |> geti 0))
let get_consumed_gas_for_block client =
JSON.(
let* operations = get_operations client in
let gas =
List.fold_left
(fun gas op -> gas + read_consumed_gas op)
0
(operations |> as_list)
in
return gas)
let current_head = ["chains"; "main"; "blocks"; "head"]
let get_counter client =
let* counter =
RPC.Contracts.get_counter
~contract_id:Constant.bootstrap1.public_key_hash
client
in
return @@ JSON.as_int counter
let get_size client =
let* size =
Client.(
rpc GET (current_head @ ["context"; "cache"; "contracts"; "size"]) client)
in
return (JSON.as_int size)
let get_storage ~contract_id client =
let* storage = RPC.Contracts.get_storage ~contract_id client in
return
@@ JSON.(
List.assoc "args" (as_object storage) |> geti 0 |> fun x ->
List.assoc "string" (as_object x) |> as_string)
(*
Setup helpers
-------------
*)
* [ ~protocol ] runs a single node running [ protocol ] , returns
an associated client .
an associated client. *)
let init1 ~protocol =
let* node = Node.init [Synchronisation_threshold 0; Connections 0] in
let* client = Client.init ~endpoint:(Node node) () in
let* () = Client.activate_protocol ~protocol client in
let* _ = Node.wait_for_level node 1 in
Log.info "Activated protocol." ;
return (node, client)
(** [originate_contract prefix contract] returns a function [originate]
such that [originate client storage] deploys a new instance of
[contract] initialized with [storage]. The instance name starts with
[prefix]. *)
let originate_contract prefix contract =
let id = ref 0 in
let fresh () =
incr id ;
prefix ^ string_of_int !id
in
fun client storage ->
let* contract_id =
Client.originate_contract
~alias:(fresh ())
~amount:Tez.zero
~src:"bootstrap1"
~prg:contract
~init:storage
~burn_cap:Tez.(of_int 99999999999999)
client
in
let* () = Client.bake_for client in
Lwt.return contract_id
(** [originate_str_id_contract client str] bakes a block to originate the
[str_id] contract with storage [str], and returns its address. *)
let originate_str_id_contract =
let filename = "file:./tezt/tests/contracts/proto_alpha/large_str_id.tz" in
let originate = originate_contract "str" filename in
fun client str ->
originate client (Printf.sprintf "Pair \"%s\" \"%s\"" str str)
(** [originate_str_id_contracts client n] creates [n] instances of
[str_id] where the [k-th] instance starts with a storage
containing [k] "x". *)
let originate_str_id_contracts client n =
fold n [] @@ fun k contracts ->
let s = String.make k 'x' in
let* contract_id = originate_str_id_contract client s in
return (contract_id :: contracts)
(** [originate_very_small_contract client] bakes a block to originate the
[very_small] contract with storage [unit], and returns its address. *)
let originate_very_small_contract =
let filename = "file:./tezt/tests/contracts/proto_alpha/very_small.tz" in
let originate = originate_contract "very_small" filename in
fun client -> originate client "Unit"
(** [originate_very_small_contracts client n] creates [n] instances
of [large_types]. *)
let originate_very_small_contracts client n =
fold n [] @@ fun _ contracts ->
let* contract_id = originate_very_small_contract client in
return (contract_id :: contracts)
(** [call_contract contract_id k client] bakes a block with a
contract call to [contract_id], with [k] as an integer
parameter, using [client]. It returns the amount of consumed
gas. *)
let call_contract contract_id k client =
let* () =
Client.transfer
~amount:Tez.(of_int 100)
~burn_cap:Tez.(of_int 999999999)
~storage_limit:100000
~giver:"bootstrap1"
~receiver:contract_id
~arg:k
client
in
let* () = Client.bake_for client in
let* gas = get_consumed_gas client in
Lwt.return gas
(** [call_contracts calls client] bakes a block with multiple contract
[calls] using [client]. It returns the amount of consumed gas. *)
let call_contracts calls client =
let* () =
Client.multiple_transfers
~fee_cap:Tez.(of_int 9999999)
~burn_cap:Tez.(of_int 9999999)
~giver:"bootstrap1"
~json_batch:calls
client
in
let* () = Client.bake_for client in
let* gas = get_consumed_gas_for_block client in
Lwt.return gas
(** [make_calls f contracts] *)
let make_calls f contracts =
"[" ^ String.concat "," (List.map f contracts) ^ "]"
* [ str_id_calls contracts ] is a list of calls to [ contracts ] that
all are instances of [ str_id.tz ] .
all are instances of [str_id.tz]. *)
let str_id_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Left 4", "gas-limit" : "20000" } |}
contract)
(** [large_types_calls contracts] is a list of calls to [contracts] that
all are instances of [large_types.tz]. *)
let large_types_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Unit", "gas-limit" : "1040000" } |}
contract)
(** [very_small_calls contracts] is a list of calls to [contracts] that
all are instances of [very_small.tz]. *)
let very_small_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Unit", "gas-limit" : "1040000" } |}
contract)
let liquidity_baking_address = "KT1TxqZ8QtKvLu3V3JH7Gx58n7Co8pgtpQU5"
* [ get_cached_contracts client ] retrieves the cached scripts , except
the liquidity baking CPMM script .
the liquidity baking CPMM script. *)
let get_cached_contracts client =
let* contracts = RPC.Script_cache.get_cached_contracts client in
let all =
JSON.(
as_list contracts
|> List.map @@ fun t ->
as_list t |> function [s; _] -> as_string s | _ -> assert false)
in
let all = List.filter (fun c -> c <> liquidity_baking_address) all in
return all
* [ check label test ~protocol ] registers a script cache test in
.
These tests are long because it takes ~2 minutes to fill the
cache . Following recommendations , we set the timeout to ten
times the actual excepted time .
Tezt.
These tests are long because it takes ~2 minutes to fill the
cache. Following Tezt recommendations, we set the timeout to ten
times the actual excepted time.
*)
let check ?(tags = []) label test ~protocol ~executors =
Long_test.register
~__FILE__
~title:(sf "(%s) Cache: %s" (Protocol.name protocol) label)
~tags:(["cache"] @ tags)
~timeout:(Minutes 2000)
~executors
@@ test
(*
Testsuite
=========
*)
(*
Testing basic script caching functionality
------------------------------------------
We check that calling the same contract twice results in lower gas
consumption thanks to the cache.
*)
let check_contract_cache_lowers_gas_consumption ~protocol =
check "contract cache lowers gas consumption" ~protocol @@ fun () ->
let* (_, client) = init1 ~protocol in
let* contract_id = originate_str_id_contract client "" in
let* gas1 = call_contract contract_id "Left 1" client in
let* gas2 = call_contract contract_id "Left 1" client in
return
@@ Check.((gas2 < gas1) int)
~error_msg:"Contract cache should lower the gas consumption"
Testing LRU and size limit enforcement
--------------------------------------
The next test fills the cache with many instances of the contract
[ str_id.tz ] in a sequence of blocks .
Then , we can observe that :
- the cache does not grow beyond its limit ;
- the cache follows an LRU strategy .
Testing LRU and size limit enforcement
--------------------------------------
The next test fills the cache with many instances of the contract
[str_id.tz] in a sequence of blocks.
Then, we can observe that:
- the cache does not grow beyond its limit ;
- the cache follows an LRU strategy.
*)
let check_full_cache ~protocol =
check "contract cache does not go beyond its size limit" ~protocol
@@ fun () ->
let* (_, client) = init1 ~protocol in
let s = String.make 1024 'x' in
let* counter = get_counter client in
let rec aux contracts previous_size nremoved k counter =
if k = 0 then Lwt.return_unit
else
let* contract_id = originate_str_id_contract client s in
let contracts = contract_id :: contracts in
let* _ = call_contract contract_id "Left 4" client in
let* size = get_size client in
Log.info "%02d script(s) to be originated, cache size = %08d" k size ;
let cache_is_full = previous_size = size in
let nremoved = if cache_is_full then nremoved + 1 else nremoved in
if k <= 3 && not cache_is_full then Test.fail "Cache should be full now." ;
let* _ =
if cache_is_full then (
Log.info "The cache is full (size = %d | removed = %d)." size nremoved ;
let* cached_contracts = get_cached_contracts client in
if drop nremoved (List.rev contracts) <> cached_contracts then
Test.fail "LRU strategy is not correctly implemented." ;
return ())
else return ()
in
aux contracts size nremoved (k - 1) (counter + 1)
in
aux [] 0 0 80 counter
(*
Testing size limit enforcement within a block
---------------------------------------------
We check that within a block, it is impossible to violate the cache
size limit.
This test is also a stress tests for the cache as we evaluate that
the actual heap memory consumption of the node stays reasonable (<
1GB) while the cache is filled with contracts.
*)
let check_block_impact_on_cache ~protocol =
check "one cannot violate the cache size limit" ~protocol ~tags:["memory"]
@@ fun () ->
let* (node, client) = init1 ~protocol in
let* (Node.Observe memory_consumption) = Node.memory_consumption node in
(* The following number has been obtained by dichotomy and
corresponds to the minimal number of instances of the str_id
contract required to fill the cache. *)
let ncontracts = 260 in
let* green_contracts = originate_str_id_contracts client ncontracts in
Log.info "Green contracts are originated" ;
let* red_contracts = originate_str_id_contracts client ncontracts in
Log.info "Red contracts are originated" ;
let* _ = call_contracts (str_id_calls green_contracts) client in
let* cached_contracts = get_cached_contracts client in
let reds =
List.filter (fun c -> not @@ List.mem c green_contracts) cached_contracts
in
if not List.(reds = []) then
Test.fail "The cache should be full of green contracts." ;
Log.info "The cache is full with green contracts." ;
let* () = Client.bake_for client in
let* gas = call_contracts (str_id_calls red_contracts) client in
let* cached_contracts = get_cached_contracts client in
let (greens, reds) =
List.partition (fun c -> List.mem c green_contracts) cached_contracts
in
if List.(exists (fun c -> mem c green_contracts) cached_contracts) then (
Log.info "Green contracts:\n%s\n" (String.concat "\n " greens) ;
Log.info "Red contracts:\n%s\n" (String.concat "\n " reds) ;
Test.fail "The green contracts should have been removed from the cache.") ;
Log.info "It took %d unit of gas to replace the cache entirely." gas ;
let* () = Client.bake_for client in
let* size = get_size client in
Log.info "Cache size after baking: %d\n" size ;
let* ram_consumption_peak = memory_consumption () in
match ram_consumption_peak with
| Some ram_consumption_peak ->
Log.info "The node had a peak of %d bytes in RAM" ram_consumption_peak ;
if ram_consumption_peak >= 1024 * 1024 * 1024 then
Test.fail "The node is consuming too much RAM."
else return ()
| None -> return ()
Testing proper handling of chain reorganizations
------------------------------------------------
When a reorganization of the chain occurs , the cache must be
backtracked to match the cache of the chosen head .
Our testing strategy consists in looking at the evolution of a
contract storage during a reorganization . Since contract storage is
in the cache , this is an indirect way to check that the cache is
consistent with the context .
The test proceeds as follows :
1 . [ divergence ] creates two nodes [ A ] and [ B ] . One has a cache with
a contract containing a string [ s ] while the other has a another
head with a contract containing a string [ u ] . Node [ B ] has the
longest chain , and thus its head will be chosen .
2 . [ reorganize ] triggers the resolution of the fork . Node [ A ] must
backtrack on its cache .
3 . [ check ] validates that the contract now contains string [ u ] .
Testing proper handling of chain reorganizations
------------------------------------------------
When a reorganization of the chain occurs, the cache must be
backtracked to match the cache of the chosen head.
Our testing strategy consists in looking at the evolution of a
contract storage during a reorganization. Since contract storage is
in the cache, this is an indirect way to check that the cache is
consistent with the context.
The test proceeds as follows:
1. [divergence] creates two nodes [A] and [B]. One has a cache with
a contract containing a string [s] while the other has a another
head with a contract containing a string [u]. Node [B] has the
longest chain, and thus its head will be chosen.
2. [reorganize] triggers the resolution of the fork. Node [A] must
backtrack on its cache.
3. [check] validates that the contract now contains string [u].
*)
let check_cache_backtracking_during_chain_reorganization ~protocol =
check "the cache handles chain reorganizations" ~protocol @@ fun () ->
let* nodeA = Node.init [Synchronisation_threshold 0] in
let* clientA = Client.init ~endpoint:(Node nodeA) () in
let* nodeB = Node.init [Synchronisation_threshold 0] in
let* nodeB_identity = Node.wait_for_identity nodeB in
let* clientB = Client.init ~endpoint:(Node nodeB) () in
let* () = Client.Admin.trust_address clientA ~peer:nodeB
and* () = Client.Admin.trust_address clientB ~peer:nodeA in
let* () = Client.Admin.connect_address clientA ~peer:nodeB in
let* () = Client.activate_protocol ~protocol clientA in
Log.info "Activated protocol" ;
let* _ = Node.wait_for_level nodeA 1 and* _ = Node.wait_for_level nodeB 1 in
Log.info "Both nodes are at level 1" ;
let s = "x" in
let* contract_id = originate_str_id_contract clientA s in
let* _ = Node.wait_for_level nodeA 2 and* _ = Node.wait_for_level nodeB 2 in
let expected_storage client expected_storage =
let* storage = get_storage ~contract_id client in
Log.info "storage = %s" storage ;
if storage <> expected_storage then
Test.fail "Invalid storage, got %s, expecting %s" storage expected_storage
else return ()
in
let* () = expected_storage clientA "x" in
Log.info "Both nodes are at level 2" ;
let divergence () =
let* () = Client.Admin.kick_peer clientA ~peer:nodeB_identity in
let* _ = call_contract contract_id "Left 1" clientA in
let* _ = Node.wait_for_level nodeA 3 in
Log.info "Node A is at level 3" ;
At this point , [ nodeA ] has a chain of length 3 with storage xx .
let* () = expected_storage clientA "xx" in
let* () = Node.wait_for_ready nodeB in
let* _ = call_contract contract_id "Left 2" clientB in
let* _ = Node.wait_for_level nodeB 3 in
Log.info "Node B is at level 3" ;
let* () = Client.bake_for clientB in
let* _ = Node.wait_for_level nodeB 4 in
Log.info "Node B is at level 4" ;
At this point , [ nodeB ] has a chain of length 4 with storage xxxx .
let* () = expected_storage clientB "xxxx" in
return ()
in
let trigger_reorganization () =
let* () = Client.Admin.connect_address clientA ~peer:nodeB in
let* _ = Node.wait_for_level nodeA 4 in
return ()
in
let check () =
let* () = expected_storage clientA "xxxx" in
let* _ = call_contract contract_id "Left 1" clientA in
let* () = Client.bake_for clientA in
let* () = expected_storage clientA "xxxxxxxx" in
return ()
in
let* () = divergence () in
let* () = trigger_reorganization () in
let* () = check () in
return ()
(*
Testing efficiency of cache loading
-----------------------------------
We check that a node that has a full cache to reload is performing
reasonably fast. This is important because the baker must be awaken
sufficiently earlier before it bakes to preheat its cache.
To that end, we create a node [A] and populate it with a full
cache. We reboot [A] and measure the time it takes to reload the
cache.
*)
let check_reloading_efficiency ~protocol body =
let* (nodeA, clientA) = init1 ~protocol in
let* _ = body clientA in
let* () = Client.bake_for clientA in
Log.info "Contracts are in the cache" ;
let* size = get_size clientA in
Log.info "Cache size after baking: %d\n" size ;
let* cached_contracts = get_cached_contracts clientA in
let* () = Node.terminate nodeA in
let start = Unix.gettimeofday () in
let* () = Node.run nodeA [Synchronisation_threshold 0] in
let* () = Node.wait_for_ready nodeA in
let* _ = RPC.is_bootstrapped clientA in
let* _ = Client.bake_for clientA in
let stop = Unix.gettimeofday () in
let* cached_contracts' = get_cached_contracts clientA in
let duration = stop -. start in
Log.info "It took %f seconds to load a full cache" duration ;
if cached_contracts <> cached_contracts' then
Test.fail "Node A did not reload the cache correctly"
A delay of 15 seconds at node starting time seems unacceptable ,
even on a runner . Hence , the following condition .
In practice , we have observed a delay of 6 seconds on low
performance machines .
A delay of 15 seconds at node starting time seems unacceptable,
even on a CI runner. Hence, the following condition.
In practice, we have observed a delay of 6 seconds on low
performance machines.
*)
else if duration > 15. then
Test.fail "Node A did not reload the cache sufficiently fast"
else return ()
(*
Fill the cache with as many entries as possible to check the
efficiency of domain loading.
*)
let check_cache_reloading_is_not_too_slow ~protocol =
let tags = ["reload"; "performance"] in
check "a node reloads a full cache sufficiently fast" ~protocol ~tags
@@ fun () ->
check_reloading_efficiency ~protocol @@ fun client ->
repeat 1000 @@ fun () ->
let ncontracts = 5 in
let* contracts = originate_very_small_contracts client ncontracts in
let* () = Client.bake_for client in
let* _ = call_contracts (very_small_calls contracts) client in
return ()
(*
The simulation correctly takes the cache into account.
*)
let check_simulation_takes_cache_into_account ~protocol =
check "operation simulation takes cache into account" ~protocol @@ fun () ->
let* (_, client) = init1 ~protocol in
let* contract_id = originate_very_small_contract client in
let* chain_id = RPC.get_chain_id client in
let data block counter =
Ezjsonm.value_from_string
@@ Printf.sprintf
{| { "operation" :
{ "branch": "%s",
"contents": [
{ "kind": "transaction",
"source": "%s",
"fee": "1",
"counter": "%d",
"gas_limit": "800000",
"storage_limit": "60000",
"amount": "1",
"destination": "%s",
"parameters": {
"entrypoint": "default",
"value": { "prim" : "Unit" }
}
} ],
"signature": "edsigtXomBKi5CTRf5cjATJWSyaRvhfYNHqSUGrn4SdbYRcGwQrUGjzEfQDTuqHhuA8b2d8NarZjz8TRf65WkpQmo423BtomS8Q"
}, "chain_id" : "%s" } |}
(JSON.as_string block)
Constant.bootstrap1.public_key_hash
counter
contract_id
(JSON.as_string chain_id)
in
let* () = Client.bake_for client in
let gas_from_simulation counter =
let* block = RPC.get_branch ~offset:0 client in
let data = data block counter in
let* result = RPC.post_run_operation client ~data in
return (read_consumed_gas JSON.(get "contents" result |> geti 0))
in
let check simulation_gas real_gas =
if simulation_gas <> real_gas then
Test.fail
"The simulation has a wrong gas consumption. Predicted %d, got %d."
simulation_gas
real_gas
in
let* gas_no_cache = gas_from_simulation 2 in
Log.info "no cache: %d" gas_no_cache ;
let* real_gas_consumption = call_contract contract_id "Unit" client in
Log.info "real gas consumption with no cache: %d" real_gas_consumption ;
check gas_no_cache real_gas_consumption ;
let* () = Client.bake_for client in
let* gas_with_cache = gas_from_simulation 3 in
Log.info "with cache: %d" gas_with_cache ;
let* real_gas_consumption = call_contract contract_id "Unit" client in
Log.info "real gas consumption with cache: %d" real_gas_consumption ;
check gas_with_cache real_gas_consumption ;
return ()
(*
Main entrypoints
----------------
*)
let register ~executors () =
let protocol = Protocol.Alpha in
check_contract_cache_lowers_gas_consumption ~protocol ~executors ;
check_full_cache ~protocol ~executors ;
check_block_impact_on_cache ~protocol ~executors ;
check_cache_backtracking_during_chain_reorganization ~protocol ~executors ;
check_cache_reloading_is_not_too_slow ~protocol ~executors ;
check_simulation_takes_cache_into_account ~protocol ~executors
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/tezt/long_tests/script_cache.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
Helpers
=======
Setup helpers
-------------
* [originate_contract prefix contract] returns a function [originate]
such that [originate client storage] deploys a new instance of
[contract] initialized with [storage]. The instance name starts with
[prefix].
* [originate_str_id_contract client str] bakes a block to originate the
[str_id] contract with storage [str], and returns its address.
* [originate_str_id_contracts client n] creates [n] instances of
[str_id] where the [k-th] instance starts with a storage
containing [k] "x".
* [originate_very_small_contract client] bakes a block to originate the
[very_small] contract with storage [unit], and returns its address.
* [originate_very_small_contracts client n] creates [n] instances
of [large_types].
* [call_contract contract_id k client] bakes a block with a
contract call to [contract_id], with [k] as an integer
parameter, using [client]. It returns the amount of consumed
gas.
* [call_contracts calls client] bakes a block with multiple contract
[calls] using [client]. It returns the amount of consumed gas.
* [make_calls f contracts]
* [large_types_calls contracts] is a list of calls to [contracts] that
all are instances of [large_types.tz].
* [very_small_calls contracts] is a list of calls to [contracts] that
all are instances of [very_small.tz].
Testsuite
=========
Testing basic script caching functionality
------------------------------------------
We check that calling the same contract twice results in lower gas
consumption thanks to the cache.
Testing size limit enforcement within a block
---------------------------------------------
We check that within a block, it is impossible to violate the cache
size limit.
This test is also a stress tests for the cache as we evaluate that
the actual heap memory consumption of the node stays reasonable (<
1GB) while the cache is filled with contracts.
The following number has been obtained by dichotomy and
corresponds to the minimal number of instances of the str_id
contract required to fill the cache.
Testing efficiency of cache loading
-----------------------------------
We check that a node that has a full cache to reload is performing
reasonably fast. This is important because the baker must be awaken
sufficiently earlier before it bakes to preheat its cache.
To that end, we create a node [A] and populate it with a full
cache. We reboot [A] and measure the time it takes to reload the
cache.
Fill the cache with as many entries as possible to check the
efficiency of domain loading.
The simulation correctly takes the cache into account.
Main entrypoints
----------------
| Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
Testing
-------
Component : cache
Invocation : dune exec / long_tests / main.exe -- cache
Subject : Testing the script cache
Most of the tests need to fill the cache , which takes ~2 minutes on a
fast machine . This is why this test is in the " long test " category .
If at some point the cache layout can be set through protocol parameters ,
then we may consider duplicating these tests in the too .
-------
Component: cache
Invocation: dune exec tezt/long_tests/main.exe -- cache
Subject: Testing the script cache
Most of the tests need to fill the cache, which takes ~2 minutes on a
fast machine. This is why this test is in the "long test" category.
If at some point the cache layout can be set through protocol parameters,
then we may consider duplicating these tests in the CI too.
*)
RPC helpers
-----------
RPC helpers
-----------
*)
let get_operations client =
let* operations = RPC.get_operations client in
return JSON.(operations |> geti 3 |> geti 0 |> get "contents")
let read_consumed_gas operation =
JSON.(
operation |> get "metadata" |> get "operation_result" |> get "consumed_gas"
|> as_int)
let get_consumed_gas client =
JSON.(
let* operations = get_operations client in
return @@ read_consumed_gas (operations |> geti 0))
let get_consumed_gas_for_block client =
JSON.(
let* operations = get_operations client in
let gas =
List.fold_left
(fun gas op -> gas + read_consumed_gas op)
0
(operations |> as_list)
in
return gas)
let current_head = ["chains"; "main"; "blocks"; "head"]
let get_counter client =
let* counter =
RPC.Contracts.get_counter
~contract_id:Constant.bootstrap1.public_key_hash
client
in
return @@ JSON.as_int counter
let get_size client =
let* size =
Client.(
rpc GET (current_head @ ["context"; "cache"; "contracts"; "size"]) client)
in
return (JSON.as_int size)
let get_storage ~contract_id client =
let* storage = RPC.Contracts.get_storage ~contract_id client in
return
@@ JSON.(
List.assoc "args" (as_object storage) |> geti 0 |> fun x ->
List.assoc "string" (as_object x) |> as_string)
* [ ~protocol ] runs a single node running [ protocol ] , returns
an associated client .
an associated client. *)
let init1 ~protocol =
let* node = Node.init [Synchronisation_threshold 0; Connections 0] in
let* client = Client.init ~endpoint:(Node node) () in
let* () = Client.activate_protocol ~protocol client in
let* _ = Node.wait_for_level node 1 in
Log.info "Activated protocol." ;
return (node, client)
let originate_contract prefix contract =
let id = ref 0 in
let fresh () =
incr id ;
prefix ^ string_of_int !id
in
fun client storage ->
let* contract_id =
Client.originate_contract
~alias:(fresh ())
~amount:Tez.zero
~src:"bootstrap1"
~prg:contract
~init:storage
~burn_cap:Tez.(of_int 99999999999999)
client
in
let* () = Client.bake_for client in
Lwt.return contract_id
let originate_str_id_contract =
let filename = "file:./tezt/tests/contracts/proto_alpha/large_str_id.tz" in
let originate = originate_contract "str" filename in
fun client str ->
originate client (Printf.sprintf "Pair \"%s\" \"%s\"" str str)
let originate_str_id_contracts client n =
fold n [] @@ fun k contracts ->
let s = String.make k 'x' in
let* contract_id = originate_str_id_contract client s in
return (contract_id :: contracts)
let originate_very_small_contract =
let filename = "file:./tezt/tests/contracts/proto_alpha/very_small.tz" in
let originate = originate_contract "very_small" filename in
fun client -> originate client "Unit"
let originate_very_small_contracts client n =
fold n [] @@ fun _ contracts ->
let* contract_id = originate_very_small_contract client in
return (contract_id :: contracts)
let call_contract contract_id k client =
let* () =
Client.transfer
~amount:Tez.(of_int 100)
~burn_cap:Tez.(of_int 999999999)
~storage_limit:100000
~giver:"bootstrap1"
~receiver:contract_id
~arg:k
client
in
let* () = Client.bake_for client in
let* gas = get_consumed_gas client in
Lwt.return gas
let call_contracts calls client =
let* () =
Client.multiple_transfers
~fee_cap:Tez.(of_int 9999999)
~burn_cap:Tez.(of_int 9999999)
~giver:"bootstrap1"
~json_batch:calls
client
in
let* () = Client.bake_for client in
let* gas = get_consumed_gas_for_block client in
Lwt.return gas
let make_calls f contracts =
"[" ^ String.concat "," (List.map f contracts) ^ "]"
* [ str_id_calls contracts ] is a list of calls to [ contracts ] that
all are instances of [ str_id.tz ] .
all are instances of [str_id.tz]. *)
let str_id_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Left 4", "gas-limit" : "20000" } |}
contract)
let large_types_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Unit", "gas-limit" : "1040000" } |}
contract)
let very_small_calls =
make_calls (fun contract ->
Printf.sprintf
{| { "destination" : "%s", "amount" : "0",
"arg" : "Unit", "gas-limit" : "1040000" } |}
contract)
let liquidity_baking_address = "KT1TxqZ8QtKvLu3V3JH7Gx58n7Co8pgtpQU5"
* [ get_cached_contracts client ] retrieves the cached scripts , except
the liquidity baking CPMM script .
the liquidity baking CPMM script. *)
let get_cached_contracts client =
let* contracts = RPC.Script_cache.get_cached_contracts client in
let all =
JSON.(
as_list contracts
|> List.map @@ fun t ->
as_list t |> function [s; _] -> as_string s | _ -> assert false)
in
let all = List.filter (fun c -> c <> liquidity_baking_address) all in
return all
* [ check label test ~protocol ] registers a script cache test in
.
These tests are long because it takes ~2 minutes to fill the
cache . Following recommendations , we set the timeout to ten
times the actual excepted time .
Tezt.
These tests are long because it takes ~2 minutes to fill the
cache. Following Tezt recommendations, we set the timeout to ten
times the actual excepted time.
*)
let check ?(tags = []) label test ~protocol ~executors =
Long_test.register
~__FILE__
~title:(sf "(%s) Cache: %s" (Protocol.name protocol) label)
~tags:(["cache"] @ tags)
~timeout:(Minutes 2000)
~executors
@@ test
let check_contract_cache_lowers_gas_consumption ~protocol =
check "contract cache lowers gas consumption" ~protocol @@ fun () ->
let* (_, client) = init1 ~protocol in
let* contract_id = originate_str_id_contract client "" in
let* gas1 = call_contract contract_id "Left 1" client in
let* gas2 = call_contract contract_id "Left 1" client in
return
@@ Check.((gas2 < gas1) int)
~error_msg:"Contract cache should lower the gas consumption"
Testing LRU and size limit enforcement
--------------------------------------
The next test fills the cache with many instances of the contract
[ str_id.tz ] in a sequence of blocks .
Then , we can observe that :
- the cache does not grow beyond its limit ;
- the cache follows an LRU strategy .
Testing LRU and size limit enforcement
--------------------------------------
The next test fills the cache with many instances of the contract
[str_id.tz] in a sequence of blocks.
Then, we can observe that:
- the cache does not grow beyond its limit ;
- the cache follows an LRU strategy.
*)
let check_full_cache ~protocol =
check "contract cache does not go beyond its size limit" ~protocol
@@ fun () ->
let* (_, client) = init1 ~protocol in
let s = String.make 1024 'x' in
let* counter = get_counter client in
let rec aux contracts previous_size nremoved k counter =
if k = 0 then Lwt.return_unit
else
let* contract_id = originate_str_id_contract client s in
let contracts = contract_id :: contracts in
let* _ = call_contract contract_id "Left 4" client in
let* size = get_size client in
Log.info "%02d script(s) to be originated, cache size = %08d" k size ;
let cache_is_full = previous_size = size in
let nremoved = if cache_is_full then nremoved + 1 else nremoved in
if k <= 3 && not cache_is_full then Test.fail "Cache should be full now." ;
let* _ =
if cache_is_full then (
Log.info "The cache is full (size = %d | removed = %d)." size nremoved ;
let* cached_contracts = get_cached_contracts client in
if drop nremoved (List.rev contracts) <> cached_contracts then
Test.fail "LRU strategy is not correctly implemented." ;
return ())
else return ()
in
aux contracts size nremoved (k - 1) (counter + 1)
in
aux [] 0 0 80 counter
let check_block_impact_on_cache ~protocol =
check "one cannot violate the cache size limit" ~protocol ~tags:["memory"]
@@ fun () ->
let* (node, client) = init1 ~protocol in
let* (Node.Observe memory_consumption) = Node.memory_consumption node in
let ncontracts = 260 in
let* green_contracts = originate_str_id_contracts client ncontracts in
Log.info "Green contracts are originated" ;
let* red_contracts = originate_str_id_contracts client ncontracts in
Log.info "Red contracts are originated" ;
let* _ = call_contracts (str_id_calls green_contracts) client in
let* cached_contracts = get_cached_contracts client in
let reds =
List.filter (fun c -> not @@ List.mem c green_contracts) cached_contracts
in
if not List.(reds = []) then
Test.fail "The cache should be full of green contracts." ;
Log.info "The cache is full with green contracts." ;
let* () = Client.bake_for client in
let* gas = call_contracts (str_id_calls red_contracts) client in
let* cached_contracts = get_cached_contracts client in
let (greens, reds) =
List.partition (fun c -> List.mem c green_contracts) cached_contracts
in
if List.(exists (fun c -> mem c green_contracts) cached_contracts) then (
Log.info "Green contracts:\n%s\n" (String.concat "\n " greens) ;
Log.info "Red contracts:\n%s\n" (String.concat "\n " reds) ;
Test.fail "The green contracts should have been removed from the cache.") ;
Log.info "It took %d unit of gas to replace the cache entirely." gas ;
let* () = Client.bake_for client in
let* size = get_size client in
Log.info "Cache size after baking: %d\n" size ;
let* ram_consumption_peak = memory_consumption () in
match ram_consumption_peak with
| Some ram_consumption_peak ->
Log.info "The node had a peak of %d bytes in RAM" ram_consumption_peak ;
if ram_consumption_peak >= 1024 * 1024 * 1024 then
Test.fail "The node is consuming too much RAM."
else return ()
| None -> return ()
Testing proper handling of chain reorganizations
------------------------------------------------
When a reorganization of the chain occurs , the cache must be
backtracked to match the cache of the chosen head .
Our testing strategy consists in looking at the evolution of a
contract storage during a reorganization . Since contract storage is
in the cache , this is an indirect way to check that the cache is
consistent with the context .
The test proceeds as follows :
1 . [ divergence ] creates two nodes [ A ] and [ B ] . One has a cache with
a contract containing a string [ s ] while the other has a another
head with a contract containing a string [ u ] . Node [ B ] has the
longest chain , and thus its head will be chosen .
2 . [ reorganize ] triggers the resolution of the fork . Node [ A ] must
backtrack on its cache .
3 . [ check ] validates that the contract now contains string [ u ] .
Testing proper handling of chain reorganizations
------------------------------------------------
When a reorganization of the chain occurs, the cache must be
backtracked to match the cache of the chosen head.
Our testing strategy consists in looking at the evolution of a
contract storage during a reorganization. Since contract storage is
in the cache, this is an indirect way to check that the cache is
consistent with the context.
The test proceeds as follows:
1. [divergence] creates two nodes [A] and [B]. One has a cache with
a contract containing a string [s] while the other has a another
head with a contract containing a string [u]. Node [B] has the
longest chain, and thus its head will be chosen.
2. [reorganize] triggers the resolution of the fork. Node [A] must
backtrack on its cache.
3. [check] validates that the contract now contains string [u].
*)
let check_cache_backtracking_during_chain_reorganization ~protocol =
check "the cache handles chain reorganizations" ~protocol @@ fun () ->
let* nodeA = Node.init [Synchronisation_threshold 0] in
let* clientA = Client.init ~endpoint:(Node nodeA) () in
let* nodeB = Node.init [Synchronisation_threshold 0] in
let* nodeB_identity = Node.wait_for_identity nodeB in
let* clientB = Client.init ~endpoint:(Node nodeB) () in
let* () = Client.Admin.trust_address clientA ~peer:nodeB
and* () = Client.Admin.trust_address clientB ~peer:nodeA in
let* () = Client.Admin.connect_address clientA ~peer:nodeB in
let* () = Client.activate_protocol ~protocol clientA in
Log.info "Activated protocol" ;
let* _ = Node.wait_for_level nodeA 1 and* _ = Node.wait_for_level nodeB 1 in
Log.info "Both nodes are at level 1" ;
let s = "x" in
let* contract_id = originate_str_id_contract clientA s in
let* _ = Node.wait_for_level nodeA 2 and* _ = Node.wait_for_level nodeB 2 in
let expected_storage client expected_storage =
let* storage = get_storage ~contract_id client in
Log.info "storage = %s" storage ;
if storage <> expected_storage then
Test.fail "Invalid storage, got %s, expecting %s" storage expected_storage
else return ()
in
let* () = expected_storage clientA "x" in
Log.info "Both nodes are at level 2" ;
let divergence () =
let* () = Client.Admin.kick_peer clientA ~peer:nodeB_identity in
let* _ = call_contract contract_id "Left 1" clientA in
let* _ = Node.wait_for_level nodeA 3 in
Log.info "Node A is at level 3" ;
At this point , [ nodeA ] has a chain of length 3 with storage xx .
let* () = expected_storage clientA "xx" in
let* () = Node.wait_for_ready nodeB in
let* _ = call_contract contract_id "Left 2" clientB in
let* _ = Node.wait_for_level nodeB 3 in
Log.info "Node B is at level 3" ;
let* () = Client.bake_for clientB in
let* _ = Node.wait_for_level nodeB 4 in
Log.info "Node B is at level 4" ;
At this point , [ nodeB ] has a chain of length 4 with storage xxxx .
let* () = expected_storage clientB "xxxx" in
return ()
in
let trigger_reorganization () =
let* () = Client.Admin.connect_address clientA ~peer:nodeB in
let* _ = Node.wait_for_level nodeA 4 in
return ()
in
let check () =
let* () = expected_storage clientA "xxxx" in
let* _ = call_contract contract_id "Left 1" clientA in
let* () = Client.bake_for clientA in
let* () = expected_storage clientA "xxxxxxxx" in
return ()
in
let* () = divergence () in
let* () = trigger_reorganization () in
let* () = check () in
return ()
let check_reloading_efficiency ~protocol body =
let* (nodeA, clientA) = init1 ~protocol in
let* _ = body clientA in
let* () = Client.bake_for clientA in
Log.info "Contracts are in the cache" ;
let* size = get_size clientA in
Log.info "Cache size after baking: %d\n" size ;
let* cached_contracts = get_cached_contracts clientA in
let* () = Node.terminate nodeA in
let start = Unix.gettimeofday () in
let* () = Node.run nodeA [Synchronisation_threshold 0] in
let* () = Node.wait_for_ready nodeA in
let* _ = RPC.is_bootstrapped clientA in
let* _ = Client.bake_for clientA in
let stop = Unix.gettimeofday () in
let* cached_contracts' = get_cached_contracts clientA in
let duration = stop -. start in
Log.info "It took %f seconds to load a full cache" duration ;
if cached_contracts <> cached_contracts' then
Test.fail "Node A did not reload the cache correctly"
A delay of 15 seconds at node starting time seems unacceptable ,
even on a runner . Hence , the following condition .
In practice , we have observed a delay of 6 seconds on low
performance machines .
A delay of 15 seconds at node starting time seems unacceptable,
even on a CI runner. Hence, the following condition.
In practice, we have observed a delay of 6 seconds on low
performance machines.
*)
else if duration > 15. then
Test.fail "Node A did not reload the cache sufficiently fast"
else return ()
let check_cache_reloading_is_not_too_slow ~protocol =
let tags = ["reload"; "performance"] in
check "a node reloads a full cache sufficiently fast" ~protocol ~tags
@@ fun () ->
check_reloading_efficiency ~protocol @@ fun client ->
repeat 1000 @@ fun () ->
let ncontracts = 5 in
let* contracts = originate_very_small_contracts client ncontracts in
let* () = Client.bake_for client in
let* _ = call_contracts (very_small_calls contracts) client in
return ()
let check_simulation_takes_cache_into_account ~protocol =
check "operation simulation takes cache into account" ~protocol @@ fun () ->
let* (_, client) = init1 ~protocol in
let* contract_id = originate_very_small_contract client in
let* chain_id = RPC.get_chain_id client in
let data block counter =
Ezjsonm.value_from_string
@@ Printf.sprintf
{| { "operation" :
{ "branch": "%s",
"contents": [
{ "kind": "transaction",
"source": "%s",
"fee": "1",
"counter": "%d",
"gas_limit": "800000",
"storage_limit": "60000",
"amount": "1",
"destination": "%s",
"parameters": {
"entrypoint": "default",
"value": { "prim" : "Unit" }
}
} ],
"signature": "edsigtXomBKi5CTRf5cjATJWSyaRvhfYNHqSUGrn4SdbYRcGwQrUGjzEfQDTuqHhuA8b2d8NarZjz8TRf65WkpQmo423BtomS8Q"
}, "chain_id" : "%s" } |}
(JSON.as_string block)
Constant.bootstrap1.public_key_hash
counter
contract_id
(JSON.as_string chain_id)
in
let* () = Client.bake_for client in
let gas_from_simulation counter =
let* block = RPC.get_branch ~offset:0 client in
let data = data block counter in
let* result = RPC.post_run_operation client ~data in
return (read_consumed_gas JSON.(get "contents" result |> geti 0))
in
let check simulation_gas real_gas =
if simulation_gas <> real_gas then
Test.fail
"The simulation has a wrong gas consumption. Predicted %d, got %d."
simulation_gas
real_gas
in
let* gas_no_cache = gas_from_simulation 2 in
Log.info "no cache: %d" gas_no_cache ;
let* real_gas_consumption = call_contract contract_id "Unit" client in
Log.info "real gas consumption with no cache: %d" real_gas_consumption ;
check gas_no_cache real_gas_consumption ;
let* () = Client.bake_for client in
let* gas_with_cache = gas_from_simulation 3 in
Log.info "with cache: %d" gas_with_cache ;
let* real_gas_consumption = call_contract contract_id "Unit" client in
Log.info "real gas consumption with cache: %d" real_gas_consumption ;
check gas_with_cache real_gas_consumption ;
return ()
let register ~executors () =
let protocol = Protocol.Alpha in
check_contract_cache_lowers_gas_consumption ~protocol ~executors ;
check_full_cache ~protocol ~executors ;
check_block_impact_on_cache ~protocol ~executors ;
check_cache_backtracking_during_chain_reorganization ~protocol ~executors ;
check_cache_reloading_is_not_too_slow ~protocol ~executors ;
check_simulation_takes_cache_into_account ~protocol ~executors
|
53f911f05be8ddcd2928fd44baf1ccfe456f0bb24f177ffb75e6055c5e72e926 | jwiegley/notes | Folds.hs | foldr' :: (b -> a -> a) -> a -> [b] -> a
foldr' c n xs = run (fold xs c n)
data Fold a b = forall x. Fold (x -> a -> x) x (x -> b)
instance Functor (Fold a) where
fmap f (Fold step begin done) = Fold step begin (f . done)
instance Applicative (Fold a) where
pure b = Fold (\() _ -> ()) () (\() -> b)
(Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =
let step (xL, xR) a = (stepL xL a, stepR xR a)
begin = (beginL, beginR)
done (xL, xR) = (doneL xL) (doneR xR)
in Fold step begin done
data Fold' a b = forall x. Fold' (x -> Either b (a -> x)) x
instance Functor (Fold' a) where
fmap f (Fold' step begin) =
Fold' (\x -> case step x of
Left b -> Left (f b)
Right k -> Right k) begin
instance Applicative (Fold' a) where
pure b = Fold' (\() -> Left b) ()
(Fold' stepL beginL) <*> (Fold' stepR beginR) =
let step (xL, xR) =
case (stepL xL, stepR xR) of
(Left f, Left x) -> Left (f x)
(Left _, Right h) -> Right (\a -> (undefined, h a))
(Right k, Left _) -> Right (\a -> (k a, undefined))
(Right k, Right h) -> Right (k &&& h)
begin = (beginL, beginR)
in Fold' step begin
data HMachine a b = forall x. Hide (x -> Either b (a -> b, x)) x
instance Functor (HMachine a) where
fmap f (Hide step begin) =
Hide (\x -> case step x of
Left b -> Left (f b)
Right (k, x') -> Right (f . k, x')) begin
instance Applicative (HMachine a) where
pure b = Hide (\() -> Left b) ()
(Hide stepL beginL) <*> (Hide stepR beginR) =
let step (xL, xR) =
case (stepL xL, stepR xR) of
(Left f, Left x) -> Left (f x)
(Left f, Right (h, x')) -> Right (f . h, (undefined, x'))
(Right (_, x'), Left _) -> Right (undefined, (x', undefined))
(Right (_, x), Right (_, x')) -> Right (undefined, (x, x'))
begin = (beginL, beginR)
in Hide step begin
main :: IO ()
main = do
let x = fold ([1..10] :: [Int]) (+) 0
print (run (lmap (+100) x))
print (run (rmap (+100) x))
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Folds.hs | haskell | foldr' :: (b -> a -> a) -> a -> [b] -> a
foldr' c n xs = run (fold xs c n)
data Fold a b = forall x. Fold (x -> a -> x) x (x -> b)
instance Functor (Fold a) where
fmap f (Fold step begin done) = Fold step begin (f . done)
instance Applicative (Fold a) where
pure b = Fold (\() _ -> ()) () (\() -> b)
(Fold stepL beginL doneL) <*> (Fold stepR beginR doneR) =
let step (xL, xR) a = (stepL xL a, stepR xR a)
begin = (beginL, beginR)
done (xL, xR) = (doneL xL) (doneR xR)
in Fold step begin done
data Fold' a b = forall x. Fold' (x -> Either b (a -> x)) x
instance Functor (Fold' a) where
fmap f (Fold' step begin) =
Fold' (\x -> case step x of
Left b -> Left (f b)
Right k -> Right k) begin
instance Applicative (Fold' a) where
pure b = Fold' (\() -> Left b) ()
(Fold' stepL beginL) <*> (Fold' stepR beginR) =
let step (xL, xR) =
case (stepL xL, stepR xR) of
(Left f, Left x) -> Left (f x)
(Left _, Right h) -> Right (\a -> (undefined, h a))
(Right k, Left _) -> Right (\a -> (k a, undefined))
(Right k, Right h) -> Right (k &&& h)
begin = (beginL, beginR)
in Fold' step begin
data HMachine a b = forall x. Hide (x -> Either b (a -> b, x)) x
instance Functor (HMachine a) where
fmap f (Hide step begin) =
Hide (\x -> case step x of
Left b -> Left (f b)
Right (k, x') -> Right (f . k, x')) begin
instance Applicative (HMachine a) where
pure b = Hide (\() -> Left b) ()
(Hide stepL beginL) <*> (Hide stepR beginR) =
let step (xL, xR) =
case (stepL xL, stepR xR) of
(Left f, Left x) -> Left (f x)
(Left f, Right (h, x')) -> Right (f . h, (undefined, x'))
(Right (_, x'), Left _) -> Right (undefined, (x', undefined))
(Right (_, x), Right (_, x')) -> Right (undefined, (x, x'))
begin = (beginL, beginR)
in Hide step begin
main :: IO ()
main = do
let x = fold ([1..10] :: [Int]) (+) 0
print (run (lmap (+100) x))
print (run (rmap (+100) x))
|
|
8b4e8b44d7e4f7aaeea86742903b7ba80e9ea3e20cf5f8810c2232c47a6a388b | spacegangster/space-ui | video.cljc | (ns space-ui.video)
(defn face
[{:media/keys [alt title lazy? eager? loop? srcset src sources sizes css-class]}]
; -tricks.com/a-native-lazy-load-for-the-web-platform/
(let [loading (cond lazy? "lazy" eager? "eager" :else "auto")]
(cond
src
[:video {:title title :class css-class
:loop loop?
:playsinline true
:autoplay true
:src src
:loading loading}]
sources
[:video {:title title :class css-class
:loop loop?
:playsinline true
:autoplay true
:muted true
:loading loading}
;:controls true}
(for [{:media/keys [src src-type media] :as source} sources]
[:source {:type src-type :src src :media media}])])))
| null | https://raw.githubusercontent.com/spacegangster/space-ui/74825c904b6b456d845c3b3d669ce795b33f5ba9/src/space_ui/video.cljc | clojure | -tricks.com/a-native-lazy-load-for-the-web-platform/
:controls true} | (ns space-ui.video)
(defn face
[{:media/keys [alt title lazy? eager? loop? srcset src sources sizes css-class]}]
(let [loading (cond lazy? "lazy" eager? "eager" :else "auto")]
(cond
src
[:video {:title title :class css-class
:loop loop?
:playsinline true
:autoplay true
:src src
:loading loading}]
sources
[:video {:title title :class css-class
:loop loop?
:playsinline true
:autoplay true
:muted true
:loading loading}
(for [{:media/keys [src src-type media] :as source} sources]
[:source {:type src-type :src src :media media}])])))
|
59fd3985142544c85dcb2e578207d37ca3d1f58738b535c9782d3f0e4e4bff14 | laurencer/confluence-sync | PipeliningSnippet.hs | --
-- HTTP client for use with io-streams
--
Copyright © 2012 - 2014 Operational Dynamics Consulting , Pty Ltd
--
-- The code in this file, and the program it is a part of, is made
-- available to you by its authors as open source software: you can
redistribute it and/or modify it under a BSD licence .
--
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-unused-imports #-}
module Snippet where
import Control.Concurrent (threadDelay)
import Control.Exception (bracket)
import Network.Http.Client
--
-- Otherwise redundent imports, but useful for testing in GHCi.
--
import Blaze.ByteString.Builder (Builder)
import qualified Blaze.ByteString.Builder as Builder
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S
import Debug.Trace
import System.Exit (exitSuccess)
import System.IO.Streams (InputStream, OutputStream, stdout)
import qualified System.IO.Streams as Streams
main :: IO ()
main = do
c <- openConnection "kernel.operationaldynamics.com" 58080
let q1 = buildRequest1 $ do
http GET "/time?id=1"
setAccept "text/plain"
let q2 = buildRequest1 $ do
http GET "/time?id=2"
setAccept "text/plain"
let q3 = buildRequest1 $ do
http GET "/time?id=3"
setAccept "text/plain"
sendRequest c q1 emptyBody
threadDelay 1000000
sendRequest c q2 emptyBody
threadDelay 1000000
sendRequest c q3 emptyBody
receiveResponse c debugHandler
receiveResponse c debugHandler
receiveResponse c debugHandler
closeConnection c
| null | https://raw.githubusercontent.com/laurencer/confluence-sync/442fdbc84fe07471f323af80d2d4580026f8d9e8/vendor/http-streams/tests/PipeliningSnippet.hs | haskell |
HTTP client for use with io-streams
The code in this file, and the program it is a part of, is made
available to you by its authors as open source software: you can
# LANGUAGE OverloadedStrings #
# OPTIONS -fno-warn-unused-imports #
Otherwise redundent imports, but useful for testing in GHCi.
| Copyright © 2012 - 2014 Operational Dynamics Consulting , Pty Ltd
redistribute it and/or modify it under a BSD licence .
module Snippet where
import Control.Concurrent (threadDelay)
import Control.Exception (bracket)
import Network.Http.Client
import Blaze.ByteString.Builder (Builder)
import qualified Blaze.ByteString.Builder as Builder
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S
import Debug.Trace
import System.Exit (exitSuccess)
import System.IO.Streams (InputStream, OutputStream, stdout)
import qualified System.IO.Streams as Streams
main :: IO ()
main = do
c <- openConnection "kernel.operationaldynamics.com" 58080
let q1 = buildRequest1 $ do
http GET "/time?id=1"
setAccept "text/plain"
let q2 = buildRequest1 $ do
http GET "/time?id=2"
setAccept "text/plain"
let q3 = buildRequest1 $ do
http GET "/time?id=3"
setAccept "text/plain"
sendRequest c q1 emptyBody
threadDelay 1000000
sendRequest c q2 emptyBody
threadDelay 1000000
sendRequest c q3 emptyBody
receiveResponse c debugHandler
receiveResponse c debugHandler
receiveResponse c debugHandler
closeConnection c
|
3010588cb439193e25562a34a348c5d9980b88e63b59db8af07154f3f2a4798b | informatimago/commands | script-test.lisp | -*- mode : lisp ; coding : utf-8 -*-
(command :use-systems (:cffi))
(cffi:defcvar (environ "environ") :pointer)
(defun environment ()
(loop
:for i :from 0
:for s := (print (cffi:mem-aref environ :pointer i))
:until (cffi:null-pointer-p s)
:collect (cffi:foreign-string-to-lisp s)))
;;;;--------------------------------------------------------------------
(defun main (arguments)
(declare (ignore arguments))
;; (apropos "*" "UIOP")
;; (print uiop:*COMMAND-LINE-ARGUMENTS*)
(write-line "Environment:") (finish-output)
(dolist (e (environment))
(write-line e))
(write-line "Done.") (finish-output)
( apropos " * " " CL - LAUNCH " )
(dolist (v '("CL_LAUNCH_FILE" "PROG" "PROGBASE"))
(format t "~20A = ~S~%" v (uiop:getenv v)))
(let ((*package* (make-package "foo" :use '())))
(dolist (f (sort (copy-list *features*) (function string<)))
(print f)))
ex-ok)
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/commands/65d0d6385269f3e210aed4943aefdbb5372706b9/sources/commands/script-test.lisp | lisp | coding : utf-8 -*-
--------------------------------------------------------------------
(apropos "*" "UIOP")
(print uiop:*COMMAND-LINE-ARGUMENTS*)
THE END ;;;; |
(command :use-systems (:cffi))
(cffi:defcvar (environ "environ") :pointer)
(defun environment ()
(loop
:for i :from 0
:for s := (print (cffi:mem-aref environ :pointer i))
:until (cffi:null-pointer-p s)
:collect (cffi:foreign-string-to-lisp s)))
(defun main (arguments)
(declare (ignore arguments))
(write-line "Environment:") (finish-output)
(dolist (e (environment))
(write-line e))
(write-line "Done.") (finish-output)
( apropos " * " " CL - LAUNCH " )
(dolist (v '("CL_LAUNCH_FILE" "PROG" "PROGBASE"))
(format t "~20A = ~S~%" v (uiop:getenv v)))
(let ((*package* (make-package "foo" :use '())))
(dolist (f (sort (copy-list *features*) (function string<)))
(print f)))
ex-ok)
|
fc72b44333e36cb6fbb44f2b3f0828c9d3822d5fd6bb5f43a0fcfe8b8397493f | elastic/eui-cljs | field_text.cljs | (ns eui.field-text
(:require ["classnames" :default classNames]
[eui.form-control-layout :refer [EuiFormControlLayout]]
[eui.validatable-control :refer [EuiValidatableControl]]
[reagent.core :as r]))
(def custom-props
[:id
:name
:placeholder
:value
:className
:icon
:isInvalid
:inputRef
:fullWidth
:isLoading
:compressed
:prepend
:append
:readOnly
:controlOnly])
(defn EuiFieldText* []
(let [{:keys [id
name
placeholder
value
className
icon
isInvalid
inputRef
fullWidth
isLoading
compressed
prepend
append
readOnly
controlOnly]
:or {isInvalid false}
:as props} (r/props (r/current-component))
rest (apply dissoc props custom-props)
classes (classNames className
"euiFieldText"
#js{"euiFieldText--withIcon" icon
"euiFieldText--fullWidth" fullWidth
"euiFieldText--compressed" compressed
"euiFieldText--inGroup" (or prepend append)
"euiFieldText-isLoading" isLoading})
control [(r/adapt-react-class EuiValidatableControl)
{:isInvalid isInvalid}
[:input (merge {:type "text"
:id id
:name name
:placeholder placeholder
:class classes
:value value
:ref inputRef
:readOnly readOnly} rest)]]]
(if controlOnly
control
[:> EuiFormControlLayout {:icon icon
:fullWidth fullWidth
:isLoading isLoading
:compressed compressed
:readOnly readOnly
:prepend prepend
:append append
:inputId id}
control])))
(def EuiFieldText (r/reactify-component EuiFieldText*))
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/field_text.cljs | clojure | (ns eui.field-text
(:require ["classnames" :default classNames]
[eui.form-control-layout :refer [EuiFormControlLayout]]
[eui.validatable-control :refer [EuiValidatableControl]]
[reagent.core :as r]))
(def custom-props
[:id
:name
:placeholder
:value
:className
:icon
:isInvalid
:inputRef
:fullWidth
:isLoading
:compressed
:prepend
:append
:readOnly
:controlOnly])
(defn EuiFieldText* []
(let [{:keys [id
name
placeholder
value
className
icon
isInvalid
inputRef
fullWidth
isLoading
compressed
prepend
append
readOnly
controlOnly]
:or {isInvalid false}
:as props} (r/props (r/current-component))
rest (apply dissoc props custom-props)
classes (classNames className
"euiFieldText"
#js{"euiFieldText--withIcon" icon
"euiFieldText--fullWidth" fullWidth
"euiFieldText--compressed" compressed
"euiFieldText--inGroup" (or prepend append)
"euiFieldText-isLoading" isLoading})
control [(r/adapt-react-class EuiValidatableControl)
{:isInvalid isInvalid}
[:input (merge {:type "text"
:id id
:name name
:placeholder placeholder
:class classes
:value value
:ref inputRef
:readOnly readOnly} rest)]]]
(if controlOnly
control
[:> EuiFormControlLayout {:icon icon
:fullWidth fullWidth
:isLoading isLoading
:compressed compressed
:readOnly readOnly
:prepend prepend
:append append
:inputId id}
control])))
(def EuiFieldText (r/reactify-component EuiFieldText*))
|
|
064fad8d0557d37093771e9020c6c10eabf7f36178a29f689991120fd61de68e | Palmik/wai-sockjs | EventSource.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE FlexibleContexts #
module Network.Sock.Handler.EventSource
( EventSource
) where
------------------------------------------------------------------------------
import Data.Monoid ((<>))
------------------------------------------------------------------------------
import qualified Network.HTTP.Types as H (status200)
import qualified Network.HTTP.Types.Extra as H
------------------------------------------------------------------------------
import Network.Sock.Types.Handler
import Network.Sock.Frame
import Network.Sock.Session
import Network.Sock.Request
import Network.Sock.Handler.Common
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- |
data EventSource = EventSource
-- | EventSource Handler represents the /eventsource route.
-- The /eventsource route serves only to open sessions and to receive stream of incoming messages.
instance Handler EventSource where
handleReuqest tag req =
case requestMethod req of
"GET" -> do
let prelude = yieldAndFlush "\r\n"
session <- getSession $ requestSessionID req
return $ respondSource tag req H.status200 $ streamingSource tag req 4096 prelude session
"OPTIONS" -> return $! responseOptions ["OPTIONS", "GET"] req
_ -> return H.response404
format _ _ fr = "data: " <> encodeFrame fr <> "\r\n\r\n"
headers _ req = H.headerEventStream
<> H.headerNotCached
<> H.headerCORS "*" req
<> H.headerJSESSIONID req | null | https://raw.githubusercontent.com/Palmik/wai-sockjs/d1037cb00450a362b7e593a76d6257d06ecb2405/src/Network/Sock/Handler/EventSource.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
|
| EventSource Handler represents the /eventsource route.
The /eventsource route serves only to open sessions and to receive stream of incoming messages. | # LANGUAGE FlexibleContexts #
module Network.Sock.Handler.EventSource
( EventSource
) where
import Data.Monoid ((<>))
import qualified Network.HTTP.Types as H (status200)
import qualified Network.HTTP.Types.Extra as H
import Network.Sock.Types.Handler
import Network.Sock.Frame
import Network.Sock.Session
import Network.Sock.Request
import Network.Sock.Handler.Common
data EventSource = EventSource
instance Handler EventSource where
handleReuqest tag req =
case requestMethod req of
"GET" -> do
let prelude = yieldAndFlush "\r\n"
session <- getSession $ requestSessionID req
return $ respondSource tag req H.status200 $ streamingSource tag req 4096 prelude session
"OPTIONS" -> return $! responseOptions ["OPTIONS", "GET"] req
_ -> return H.response404
format _ _ fr = "data: " <> encodeFrame fr <> "\r\n\r\n"
headers _ req = H.headerEventStream
<> H.headerNotCached
<> H.headerCORS "*" req
<> H.headerJSESSIONID req |
090cce3576844e080455d31092c1e7aafd68e298dbe44e2b9a536e0cc6656813 | ninjudd/cake | test.clj | (ns cake.tasks.test
(:use cake cake.core
[cake.file :only [file]]
[cake.classloader :only [reload-test-classes with-test-classloader]]
[bake.core :only [with-timing]]
[bake.find-namespaces :only [find-namespaces-in-dir]]
[useful.utils :only [adjoin]]
[useful.map :only [map-vals]]
[clojure.pprint :only [pprint]]
[clojure.string :only [trim-newline]]
[clj-stacktrace.repl :as st]
[clj-stacktrace.utils :as st-utils])
(:refer-clojure :exclude [+])
(:require [com.georgejahad.difform :as difform]
[clansi.core :as ansi])
(:import [java.io File]))
(def ^:dynamic *difform* (not (read-string (*config* "disable.difform" "false"))))
(def + (fnil clojure.core/+ 0 0))
written by ( -difftest )
(defn difform-str
"Create a string that is the diff of the forms x and y."
[x y]
(subs
(with-out-str
(difform/clean-difform x y)) 1))
(defmulti diff? (fn [form] (when (coll? form) (first form))))
(defmethod diff? :default [form]
false)
(defmethod diff? 'not [form]
(diff? (last form)))
(defmethod diff? '= [form]
(let [a (second form)
b (last form)]
(or (and (coll? a) (coll? b))
(and (string? a) (string? b)))))
(defn actual-diff
"Transform the actual form that comes from clojure.test into a diff
string. This will diff forms like (not (= ...)) and will return the string
representation of anything else."
[form]
(if (diff? form)
(let [[_ [_ actual expected]] form]
(.trim (difform-str expected
actual)))
form)))
(defn test-opts
"Parse the test command line args."
[args]
(adjoin {:tags #{} :functions #{} :namespaces #{}}
(group-by #(cond (keyword? %) :tags
(namespace %) :functions
:else :namespaces)
(map read-string args))))
(defn printfs [style formatter & args]
(println (apply ansi/style (apply format formatter args) style)))
(defn clear-screen []
(print (str \u001b "[2J")
(str \u001b "[0;0H"))
(flush))
(defn all-pass? [count]
(= 0 (+ (:fail count) (:error count))))
(defn colorize [count]
(vector (if (all-pass? count)
:green
:red)))
(defmulti report :type)
(defmethod report :default [object]
(println object "\n"))
(defmethod report :fail [{:keys [file line message expected actual testing-contexts] :as m}]
(printfs [:red] "FAIL! in %s:%d" file line)
(println (str (when (seq testing-contexts) (str testing-contexts "\n"))
(when message (str message "\n"))
" expected:\n" expected
"\n actual:\n" (if *difform*
(actual-diff actual)
actual)
"\n")))
(defmethod report :error [m] ;; this is a hack of clj-stacktrace.repl/pst-on
(letfn [(find-source-width [excp]
(let [this-source-width (st-utils/fence
(sort
(map (comp #(.length %) source-str)
(:trace-elems excp))))]
(if-let [cause (:cause excp)]
(max this-source-width (find-source-width cause))
this-source-width)))]
(let [exec (:actual m)
source-width (find-source-width exec)]
(st/pst-class-on *out* true (:class exec))
(st/pst-message-on *out* true (:message exec))
(st/pst-elems-on *out* true (:trace-elems exec) source-width)
(if-let [cause (:cause exec)]
(#'st/pst-cause-on *out* true cause source-width))))
(println))
(defmethod report :ns [{:keys [ns count tests]}]
(printfs [:cyan] (str "cake test " ns "\n"))
(doseq [{:keys [name output] :as test} tests :when output]
(printfs [:yellow] (str "cake test " ns "/" name))
(dorun (map report output)))
(printfs [] "Ran %s tests containing %s assertions in %.2fs"
(:test count 0)
(:assertion count 0)
(/ (:time count) 1000.0))
(printfs (colorize count)
"%s failures, %s errors"
(:fail count 0)
(:error count 0))
(printfs [:underline] (apply str (repeat 40 " ")))
(println))
(defn accumulate-assertions [acc [name assertions]]
(let [counts (map-vals (group-by :type assertions) count)]
(merge-with + acc
(assoc counts
:test 1
:assertion (reduce + (vals counts))))))
(defn parse-results
"Generate a summary datastructure for the namespace with results."
[ns [results time]]
{:ns ns
:type :ns
:count (assoc (reduce accumulate-assertions {} results)
:time time
:ns 1)
:tests (for [[test result] results]
{:name test
:output (seq (remove (comp #{:pass} :type)
result))})})
(defn report-and-aggregate
[acc {:keys [count opts] :as results}]
(when-not (and (:auto opts) (all-pass? count))
(report results))
(merge-with + acc count))
(defn test-vars
"Determine which tests to run in the project JVM."
[opts]
(let [test-files (mapcat (comp find-namespaces-in-dir file) (:test-path *project*))]
(bake-invoke test-vars test-files opts)))
(defn run-project-tests
"Run the tests based on the command line options."
[opts]
(println)
(with-test-classloader
(bake-ns (:use bake.test)
(let [[count real-time] (with-timing
(reduce report-and-aggregate {}
(for [[ns tests] (test-vars opts) :when (seq tests)]
(assoc (parse-results ns (bake-invoke run-ns-tests ns tests))
:opts opts))))]
(if (< 0 (:test count 0))
(do (when (and (:auto opts) (all-pass? count))
(clear-screen)
(println))
(printfs [] "Ran %d tests in %d namespaces, containing %d assertions, in %.2fs (%.2fs real)"
(:test count 0)
(:ns count 0)
(:assertion count 0)
(/ (:time count) 1000.0)
(/ real-time 1000.0))
(printfs (colorize count)
"%d OK, %d failures, %d errors"
(:pass count 0)
(:fail count 0)
(:error count 0)))
(printfs [:red] "No tests matched arguments"))))))
(deftask test #{compile-java}
"Run project tests."
"Specify which tests to run as arguments like: namespace, namespace/function, or :tag"
"Use --auto to automatically run tests whenever your project code changes."
{[difform?] :difform args :test}
(binding [*difform* (if difform? (read-string difform?) *difform*)]
(let [opts (test-opts args)]
(if (:auto *opts*)
(do (clear-screen)
(loop [test? true]
(when test?
(run-project-tests (assoc opts :auto true)))
(Thread/sleep 5000)
(recur (reload-test-classes))))
(run-project-tests opts))))) | null | https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/src/cake/tasks/test.clj | clojure | this is a hack of clj-stacktrace.repl/pst-on | (ns cake.tasks.test
(:use cake cake.core
[cake.file :only [file]]
[cake.classloader :only [reload-test-classes with-test-classloader]]
[bake.core :only [with-timing]]
[bake.find-namespaces :only [find-namespaces-in-dir]]
[useful.utils :only [adjoin]]
[useful.map :only [map-vals]]
[clojure.pprint :only [pprint]]
[clojure.string :only [trim-newline]]
[clj-stacktrace.repl :as st]
[clj-stacktrace.utils :as st-utils])
(:refer-clojure :exclude [+])
(:require [com.georgejahad.difform :as difform]
[clansi.core :as ansi])
(:import [java.io File]))
(def ^:dynamic *difform* (not (read-string (*config* "disable.difform" "false"))))
(def + (fnil clojure.core/+ 0 0))
written by ( -difftest )
(defn difform-str
"Create a string that is the diff of the forms x and y."
[x y]
(subs
(with-out-str
(difform/clean-difform x y)) 1))
(defmulti diff? (fn [form] (when (coll? form) (first form))))
(defmethod diff? :default [form]
false)
(defmethod diff? 'not [form]
(diff? (last form)))
(defmethod diff? '= [form]
(let [a (second form)
b (last form)]
(or (and (coll? a) (coll? b))
(and (string? a) (string? b)))))
(defn actual-diff
"Transform the actual form that comes from clojure.test into a diff
string. This will diff forms like (not (= ...)) and will return the string
representation of anything else."
[form]
(if (diff? form)
(let [[_ [_ actual expected]] form]
(.trim (difform-str expected
actual)))
form)))
(defn test-opts
"Parse the test command line args."
[args]
(adjoin {:tags #{} :functions #{} :namespaces #{}}
(group-by #(cond (keyword? %) :tags
(namespace %) :functions
:else :namespaces)
(map read-string args))))
(defn printfs [style formatter & args]
(println (apply ansi/style (apply format formatter args) style)))
(defn clear-screen []
(print (str \u001b "[2J")
(str \u001b "[0;0H"))
(flush))
(defn all-pass? [count]
(= 0 (+ (:fail count) (:error count))))
(defn colorize [count]
(vector (if (all-pass? count)
:green
:red)))
(defmulti report :type)
(defmethod report :default [object]
(println object "\n"))
(defmethod report :fail [{:keys [file line message expected actual testing-contexts] :as m}]
(printfs [:red] "FAIL! in %s:%d" file line)
(println (str (when (seq testing-contexts) (str testing-contexts "\n"))
(when message (str message "\n"))
" expected:\n" expected
"\n actual:\n" (if *difform*
(actual-diff actual)
actual)
"\n")))
(letfn [(find-source-width [excp]
(let [this-source-width (st-utils/fence
(sort
(map (comp #(.length %) source-str)
(:trace-elems excp))))]
(if-let [cause (:cause excp)]
(max this-source-width (find-source-width cause))
this-source-width)))]
(let [exec (:actual m)
source-width (find-source-width exec)]
(st/pst-class-on *out* true (:class exec))
(st/pst-message-on *out* true (:message exec))
(st/pst-elems-on *out* true (:trace-elems exec) source-width)
(if-let [cause (:cause exec)]
(#'st/pst-cause-on *out* true cause source-width))))
(println))
(defmethod report :ns [{:keys [ns count tests]}]
(printfs [:cyan] (str "cake test " ns "\n"))
(doseq [{:keys [name output] :as test} tests :when output]
(printfs [:yellow] (str "cake test " ns "/" name))
(dorun (map report output)))
(printfs [] "Ran %s tests containing %s assertions in %.2fs"
(:test count 0)
(:assertion count 0)
(/ (:time count) 1000.0))
(printfs (colorize count)
"%s failures, %s errors"
(:fail count 0)
(:error count 0))
(printfs [:underline] (apply str (repeat 40 " ")))
(println))
(defn accumulate-assertions [acc [name assertions]]
(let [counts (map-vals (group-by :type assertions) count)]
(merge-with + acc
(assoc counts
:test 1
:assertion (reduce + (vals counts))))))
(defn parse-results
"Generate a summary datastructure for the namespace with results."
[ns [results time]]
{:ns ns
:type :ns
:count (assoc (reduce accumulate-assertions {} results)
:time time
:ns 1)
:tests (for [[test result] results]
{:name test
:output (seq (remove (comp #{:pass} :type)
result))})})
(defn report-and-aggregate
[acc {:keys [count opts] :as results}]
(when-not (and (:auto opts) (all-pass? count))
(report results))
(merge-with + acc count))
(defn test-vars
"Determine which tests to run in the project JVM."
[opts]
(let [test-files (mapcat (comp find-namespaces-in-dir file) (:test-path *project*))]
(bake-invoke test-vars test-files opts)))
(defn run-project-tests
"Run the tests based on the command line options."
[opts]
(println)
(with-test-classloader
(bake-ns (:use bake.test)
(let [[count real-time] (with-timing
(reduce report-and-aggregate {}
(for [[ns tests] (test-vars opts) :when (seq tests)]
(assoc (parse-results ns (bake-invoke run-ns-tests ns tests))
:opts opts))))]
(if (< 0 (:test count 0))
(do (when (and (:auto opts) (all-pass? count))
(clear-screen)
(println))
(printfs [] "Ran %d tests in %d namespaces, containing %d assertions, in %.2fs (%.2fs real)"
(:test count 0)
(:ns count 0)
(:assertion count 0)
(/ (:time count) 1000.0)
(/ real-time 1000.0))
(printfs (colorize count)
"%d OK, %d failures, %d errors"
(:pass count 0)
(:fail count 0)
(:error count 0)))
(printfs [:red] "No tests matched arguments"))))))
(deftask test #{compile-java}
"Run project tests."
"Specify which tests to run as arguments like: namespace, namespace/function, or :tag"
"Use --auto to automatically run tests whenever your project code changes."
{[difform?] :difform args :test}
(binding [*difform* (if difform? (read-string difform?) *difform*)]
(let [opts (test-opts args)]
(if (:auto *opts*)
(do (clear-screen)
(loop [test? true]
(when test?
(run-project-tests (assoc opts :auto true)))
(Thread/sleep 5000)
(recur (reload-test-classes))))
(run-project-tests opts))))) |
ac532a975e98767a03945b65d733297b0a1f77080acc8030ecfe4cf1b9a63d44 | kingcons/advent-of-code | day06.lisp | (mgl-pax:define-package :aoc.2020.06
(:nicknames :2020.06)
(:use :cl :aoc.util :mgl-pax)
(:import-from :serapeum :~>>))
(in-package :2020.06)
(defsummary (:title "Custom Customs")
"**Part 1** - Count any yes answers"
(parse-group function)
"**Part 2** - Count all yes answers"
(count-groups function))
(defun parse-group (group)
(~>> group
(cl-ppcre:split "\\n")
(mapcar (lambda (e) (coerce e 'list)))))
(defun count-groups (groups combine-rows)
(~>> groups
(mapcar (lambda (x) (reduce combine-rows x)))
(reduce #'+ _ :key #'length)))
(defun build-data (&optional input)
(read-day-input #'parse-group :separator "\\n\\n" :input input))
(defun part-1 (&optional (data (build-data)))
(count-groups data #'union))
(defun part-2 (&optional (data (build-data)))
(count-groups data #'intersection))
| null | https://raw.githubusercontent.com/kingcons/advent-of-code/ef8dfb86dda085f5f733c9909aedde476ea498e2/src/2020/day06.lisp | lisp | (mgl-pax:define-package :aoc.2020.06
(:nicknames :2020.06)
(:use :cl :aoc.util :mgl-pax)
(:import-from :serapeum :~>>))
(in-package :2020.06)
(defsummary (:title "Custom Customs")
"**Part 1** - Count any yes answers"
(parse-group function)
"**Part 2** - Count all yes answers"
(count-groups function))
(defun parse-group (group)
(~>> group
(cl-ppcre:split "\\n")
(mapcar (lambda (e) (coerce e 'list)))))
(defun count-groups (groups combine-rows)
(~>> groups
(mapcar (lambda (x) (reduce combine-rows x)))
(reduce #'+ _ :key #'length)))
(defun build-data (&optional input)
(read-day-input #'parse-group :separator "\\n\\n" :input input))
(defun part-1 (&optional (data (build-data)))
(count-groups data #'union))
(defun part-2 (&optional (data (build-data)))
(count-groups data #'intersection))
|
|
348dc7edb09d42c2257229d30c30b263d103a52dad5766c3cce8fc087cc63a58 | TrustInSoft/tis-interpreter | exn_flow.ml | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Cil
open Cil_types
let dkey = Kernel.register_category "exn_flow"
(* all exceptions that can be raised somewhere in the AST.
Used to handle function pointers without exn specification
*)
module All_exn =
State_builder.Option_ref(Cil_datatype.Typ.Set)
(struct let name = "Exn_flow.All_exn" let dependencies = [Ast.self] end)
module Exns =
State_builder.Hashtbl(Kernel_function.Hashtbl)(Cil_datatype.Typ.Set)
(struct
let name = "Exn_flow.Exns"
let dependencies = [Ast.self; All_exn.self]
let size = 47
end)
module ExnsStmt =
State_builder.Hashtbl(Cil_datatype.Stmt.Hashtbl)(Cil_datatype.Typ.Set)
(struct
let name = "Exn_flow.ExnsStmt"
let dependencies = [Ast.self; All_exn.self]
let size = 53
end)
let self_fun = Exns.self
let self_stmt = ExnsStmt.self
let purify t =
let t = Cil.unrollTypeDeep t in
Cil.type_remove_qualifier_attributes_deep t
class all_exn =
object
inherit Visitor.frama_c_inplace
val mutable all_exn = Cil_datatype.Typ.Set.empty
method get_exn = all_exn
method! vstmt_aux s =
match s.skind with
| Throw (Some (_,t),_) ->
all_exn <- Cil_datatype.Typ.Set.add (purify t) all_exn;
SkipChildren
| _ -> DoChildren
end
let compute_all_exn () =
let vis = new all_exn in
Visitor.visitFramacFileSameGlobals (vis:>Visitor.frama_c_visitor) (Ast.get());
vis#get_exn
let all_exn () = All_exn.memo compute_all_exn
let add_exn_var exns v =
let t = Cil.unrollTypeDeep v.vtype in
let t = Cil.type_remove_qualifier_attributes t in
Cil_datatype.Typ.Set.add t exns
let add_exn_clause exns (v,_) = add_exn_var exns v
We 're not really interested by intra - procedural Dataflow here : all the
interesting stuff happens at inter - procedural level ( except for Throw
encapsulated directly in a TryCatch , but even then it is easily captured
at syntactical level ) . Therefore , we can as well use a syntactic pass
at intra - procedural level
interesting stuff happens at inter-procedural level (except for Throw
encapsulated directly in a TryCatch, but even then it is easily captured
at syntactical level). Therefore, we can as well use a syntactic pass
at intra-procedural level
*)
class exn_visit =
object (self)
inherit Visitor.frama_c_inplace
val stack = Stack.create ()
val possible_exn = Stack.create ()
(* current set of exn included in a catch-all clause. Used to
handle Throw None;
*)
val current_exn = Stack.create ()
method private recursive_call kf =
try
Stack.iter
(fun (kf',_) -> if Kernel_function.equal kf kf' then raise Exit) stack;
false
with Exit -> true
method private add_exn t =
let current_uncaught = Stack.top possible_exn in
current_uncaught:= Cil_datatype.Typ.Set.add t !current_uncaught
method private union_exn s =
let current_uncaught = Stack.top possible_exn in
current_uncaught := Cil_datatype.Typ.Set.union s !current_uncaught
method! vstmt_aux s =
match s.skind with
| Throw (None,_) ->
let my_exn = Stack.top current_exn in
self#union_exn my_exn; ExnsStmt.replace s my_exn; SkipChildren
| Throw(Some (_,t),_) ->
let t = Cil.unrollTypeDeep t in
let t = Cil.type_remove_qualifier_attributes t in
self#add_exn t;
ExnsStmt.replace s (Cil_datatype.Typ.Set.singleton t);
SkipChildren
| TryCatch (t,c,_) ->
let catch, catch_all =
List.fold_left
(fun (catch, catch_all) ->
function
| (Catch_all,_) -> catch, true
| (Catch_exn(v,[]),_) ->
let catch = add_exn_var catch v in
catch, catch_all
| (Catch_exn(_,aux), _) ->
let catch = List.fold_left add_exn_clause catch aux in
catch, catch_all)
(Cil_datatype.Typ.Set.empty,false) c
in
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
ignore (Visitor.visitFramacBlock (self:>Visitor.frama_c_inplace) t);
let my_exn = Stack.pop possible_exn in
let uncaught = Cil_datatype.Typ.Set.diff !my_exn catch in
(* uncaught exceptions are lift to previous set of exn, but
only if there's no catch-all clause. *)
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
if not catch_all then self#union_exn uncaught;
List.iter
(fun (v,b) ->
let catch_all =
match v with
Catch_all -> true
| Catch_exn (v,[]) ->
let catch = add_exn_var Cil_datatype.Typ.Set.empty v in
Stack.push catch current_exn; false
| Catch_exn (_,aux) ->
let catch =
List.fold_left
add_exn_clause Cil_datatype.Typ.Set.empty aux
in
Stack.push catch current_exn; false
in
ignore
(Visitor.visitFramacBlock (self:>Visitor.frama_c_inplace) b);
if not catch_all then ignore (Stack.pop current_exn))
c;
let my_exn = !(Stack.pop possible_exn) in
ExnsStmt.replace s my_exn;
self#union_exn my_exn;
SkipChildren
| If _ | Switch _ | Loop _ | Block _ | UnspecifiedSequence _
| TryFinally _ | TryExcept _
| Instr _ -> (* must take into account exceptions thrown by a fun call*)
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
DoChildrenPost
(fun s ->
let my_exn = !(Stack.pop possible_exn) in
ExnsStmt.replace s my_exn;
self#union_exn my_exn;
s)
(* No exception can be thrown here. *)
| Return _ | Goto _ | Break _ | Continue _ ->
ExnsStmt.replace s Cil_datatype.Typ.Set.empty;
SkipChildren
method! vinst =
function
| Call(_,{ enode = Lval(Var f,NoOffset) },_,_) ->
let kf = Globals.Functions.get f in
if self#recursive_call kf then begin
let module Found =
struct
exception F of Cil_datatype.Typ.Set.t
end
in
let computed_exn =
try
Stack.iter
(fun (kf', exns) ->
if Kernel_function.equal kf kf' then raise (Found.F !exns))
stack;
Kernel.fatal "No cycle found!"
with Found.F exns -> exns
in
let known_exn =
try Exns.find kf with Not_found -> Cil_datatype.Typ.Set.empty
in
if Cil_datatype.Typ.Set.subset computed_exn known_exn then begin
Fixpoint found , no need to recurse .
self#union_exn known_exn
end else begin
(* add known exns in table and recurse. Termination is ensured
by the fact that only a finite number of exceptions
can be thrown. *)
let kf_exn = Cil_datatype.Typ.Set.union computed_exn known_exn in
Exns.replace kf kf_exn;
ignore
(Visitor.visitFramacFunction
(self:>Visitor.frama_c_visitor)
(Kernel_function.get_definition kf));
let callee_exn = Exns.find kf in
self#union_exn callee_exn
end
end else if Exns.mem kf then begin
self#union_exn (Exns.find kf)
end else if Kernel_function.is_definition kf then begin
let def = Kernel_function.get_definition kf in
ignore
(Visitor.visitFramacFunction (self:>Visitor.frama_c_visitor) def);
let callee_exn = Exns.find kf in
self#union_exn callee_exn
end else begin (* TODO: introduce extension to declare
exceptions that can be thrown by prototypes. *)
Kernel.warning
"Assuming declared function %a can't throw any exception"
Kernel_function.pretty kf
end;
SkipChildren
| Call _ ->
(* Function pointer: we consider that it can throw any possible
exception. *)
self#union_exn (all_exn()); SkipChildren
| _ -> SkipChildren
method! vfunc f =
let my_exns = ref Cil_datatype.Typ.Set.empty in
let kf = Globals.Functions.get f.svar in
Stack.push (kf,my_exns) stack;
Stack.push my_exns possible_exn;
let after_visit f =
let callee_exn = Stack.pop possible_exn in
Exns.add kf !callee_exn;
ignore (Stack.pop stack); f
in
DoChildrenPost after_visit
end
let compute_kf kf =
if Kernel_function.is_definition kf then
ignore
(Visitor.visitFramacFunction (new exn_visit)
(Kernel_function.get_definition kf))
(* just ignore prototypes. *)
let compute () = Globals.Functions.iter compute_kf
let get_type_tag t =
let rec aux t =
match t with
| TVoid _ -> "v"
| TInt (IBool,_) -> "B"
| TInt (IChar,_) -> "c"
| TInt (ISChar,_) -> "sc"
| TInt (IUChar,_) -> "uc"
| TInt (IInt,_) -> "i"
| TInt (IUInt,_) -> "ui"
| TInt (IShort,_) -> "s"
| TInt (IUShort,_) -> "us"
| TInt (ILong,_) -> "l"
| TInt (IULong,_) -> "ul"
| TInt (ILongLong,_) -> "ll"
| TInt (IULongLong,_) -> "ull"
| TFloat(FFloat,_) -> "f"
| TFloat(FDouble,_) -> "d"
| TFloat (FLongDouble,_) -> "ld"
| TPtr(t,_) -> "p" ^ aux t
| TArray(t,_,_,_) -> "a" ^ aux t
| TFun(rt,l,_,_) ->
let base = "fun" ^ aux rt in
(match l with
| None -> base
| Some l ->
List.fold_left (fun acc (_,t,_) -> acc ^ aux t) base l)
| TNamed _ -> Kernel.fatal "named type not correctly unrolled"
| TComp (s,_,_) -> (if s.cstruct then "S" else "U") ^ s.cname
| TEnum (e,_) -> "E" ^ e.ename
| TBuiltin_va_list _ -> "va"
in "__fc_" ^ aux t
let get_type_enum t = "__fc_exn_kind_" ^ (get_type_tag t)
let get_kf_exn kf =
if not (Exns.is_computed()) then compute();
Exns.find kf
let exn_uncaught_name = "exn_uncaught"
let exn_kind_name = "exn_kind"
let exn_obj_name = "exn_obj"
(* enumeration for all possible exceptions *)
let generate_exn_enum exns =
let loc = Cil_datatype.Location.unknown in
let v = ref 0 in
let info =
{ eorig_name = "__fc_exn_enum";
ename = "__fc_exn_enum";
eitems = [];
eattr = [];
ereferenced = true; (* not generated if no exn can be thrown *)
ekind = IInt; (* Take into account -enum option? *)
}
in
let create_enum_item t acc =
let ve = Cil.kinteger ~loc IInt !v in
let name = get_type_enum t in
incr v;
{ eiorig_name = name;
einame = name;
eival = ve;
eihost = info;
eiloc = loc;
} :: acc
in
let enums = Cil_datatype.Typ.Set.fold create_enum_item exns [] in
info.eitems <- enums;
info
(* discriminated union (i.e. struct + union) for all possible exceptions. *)
let generate_exn_union e exns =
let loc = Cil_datatype.Location.unknown in
let create_union_fields _ =
let add_one_field t acc = (get_type_tag t, t, None, [], loc) :: acc in
Cil_datatype.Typ.Set.fold add_one_field exns []
in
let union_name = "__fc_exn_union" in
let exn_kind_union =
Cil.mkCompInfo false union_name ~norig:union_name create_union_fields []
in
let create_struct_fields _ =
let uncaught = (exn_uncaught_name, Cil.intType, None, [], loc) in
let kind = (exn_kind_name, TEnum (e,[]), None, [], loc) in
let obj =
(exn_obj_name,
TComp(exn_kind_union, { scache = Not_Computed } , []), None, [], loc)
in
[uncaught; kind; obj]
in
let struct_name = "__fc_exn_struct" in
let exn_struct =
Cil.mkCompInfo true struct_name ~norig:struct_name create_struct_fields []
in
exn_kind_union, exn_struct
let add_types_and_globals typs globs f =
let iter_globs (acc,added) g =
match g with
| GVarDecl _ | GVar _ | GFun _ as g when not added ->
(g :: List.rev_append globs (List.rev_append typs acc), true)
| _ -> g :: acc, added
in
let globs, added = List.fold_left iter_globs ([],false) f.globals in
let globs =
if added then List.rev globs
else List.rev_append globs (List.rev_append typs globs)
in
f.globals <- globs;
f
let make_init_assign loc v init =
let rec aux lv acc = function
| SingleInit e -> Cil.mkStmtOneInstr (Set(lv,e,loc)) :: acc
| CompoundInit(_,l) ->
let treat_one_offset acc (o,i) = aux (Cil.addOffsetLval o lv) acc i in
List.fold_left treat_one_offset acc l
in
List.rev (aux (Var v, NoOffset) [] init)
let find_exns e =
match e.enode with
| Lval(Var v, NoOffset) ->
(try Exns.find (Globals.Functions.get v)
with Not_found -> Cil_datatype.Typ.Set.empty)
| _ -> all_exn ()
class erase_exn =
object(self)
inherit Visitor.frama_c_inplace
(* reverse before filling. *)
val mutable new_types = []
val exn_enum = Cil_datatype.Typ.Hashtbl.create 7
val exn_union = Cil_datatype.Typ.Hashtbl.create 7
val mutable modified_funcs = Cil_datatype.Fundec.Set.empty
val mutable exn_struct = None
val mutable exn_var = None
val mutable can_throw = false
val mutable catched_var = None
val mutable label_counter = 0
val exn_labels = Cil_datatype.Typ.Hashtbl.create 7
val catch_all_label = Stack.create ()
method modified_funcs = modified_funcs
method private update_enum_bindings enum exns =
let update_one_binding t =
let s = get_type_enum t in
let ei = List.find (fun ei -> ei.einame = s) enum.eitems in
Cil_datatype.Typ.Hashtbl.add exn_enum t ei
in
Cil_datatype.Typ.Set.iter update_one_binding exns
method private update_union_bindings union exns =
let update_one_binding t =
let s = get_type_tag t in
Kernel.debug ~dkey
"Registering %a as possible exn type" Cil_datatype.Typ.pretty t;
let fi = List.find (fun fi -> fi.fname = s) union.cfields in
Cil_datatype.Typ.Hashtbl.add exn_union t fi
in
Cil_datatype.Typ.Set.iter update_one_binding exns
method private exn_kind t = Cil_datatype.Typ.Hashtbl.find exn_enum t
method private exn_field_off name =
List.find (fun fi -> fi.fname = name) (Extlib.the exn_struct).cfields
method private exn_field name =
Var (Extlib.the exn_var), Field(self#exn_field_off name, NoOffset)
method private exn_field_term name =
TVar(Cil.cvar_to_lvar (Extlib.the exn_var)),
TField(self#exn_field_off name, TNoOffset)
method private exn_obj_field = self#exn_field exn_obj_name
method private exn_obj_field_term = self#exn_field_term exn_obj_name
method private exn_kind_field = self#exn_field exn_kind_name
method private exn_kind_field_term = self#exn_field_term exn_kind_name
method private uncaught_flag_field = self#exn_field exn_uncaught_name
method private uncaught_flag_field_term =
self#exn_field_term exn_uncaught_name
method private exn_obj_kind_field t =
Kernel.debug ~dkey
"Searching for %a as possible exn type" Cil_datatype.Typ.pretty t;
Cil_datatype.Typ.Hashtbl.find exn_union t
method private test_uncaught_flag loc b =
let e1 = Cil.new_exp ~loc (Lval self#uncaught_flag_field) in
let e2 = if b then Cil.one ~loc else Cil.zero ~loc in
Cil.new_exp ~loc (BinOp(Eq,e1,e2,Cil.intType))
method private pred_uncaught_flag loc b =
let e1 =
Logic_const.term
~loc (TLval self#uncaught_flag_field_term) Linteger
in
let e2 =
if b then Logic_const.tinteger ~loc 1
else Logic_const.tinteger ~loc 0
in
Logic_const.prel ~loc (Req,e1,e2)
method private set_uncaught_flag loc b =
let e = if b then Cil.one ~loc else Cil.zero ~loc in
Cil.mkStmtOneInstr (Set(self#uncaught_flag_field,e,loc))
method private set_exn_kind loc t =
let e = self#exn_kind (purify t) in
let e = Cil.new_exp ~loc (Const (CEnum e)) in
Cil.mkStmtOneInstr(Set(self#exn_kind_field,e,loc))
method private set_exn_value loc t e =
let lv = self#exn_obj_field in
let union_field = self#exn_obj_kind_field (purify t) in
let lv = Cil.addOffsetLval (Field (union_field, NoOffset)) lv in
Cil.mkStmtOneInstr (Set(lv,e,loc))
method private jumps_to_default_handler loc =
if Stack.is_empty catch_all_label then begin
(* no catch-all clause in the function: just go up in the stack. *)
let kf = Extlib.the self#current_kf in
let ret = Kernel_function.find_return kf in
let rtyp = Kernel_function.get_return_type kf in
if ret.labels = [] then
ret.labels <- [Label("__ret_label",Cil_datatype.Stmt.loc ret,false)];
let goto = mkStmt (Goto (ref ret,loc)) in
match ret.skind with
| Return (None,_) -> [goto]
(* rt is void: do not need to create a dummy return value *)
| Return (Some { enode = Lval(Var rv, NoOffset) },_) ->
let init = Cil.makeZeroInit ~loc rtyp in
make_init_assign loc rv init @ [goto]
| Return _ ->
Kernel.fatal "exception removal should be used after oneRet"
| _ ->
Kernel.fatal "find_return did not give a Return statement"
end else begin
let stmt = Stack.top catch_all_label in
[mkStmt (Goto (ref stmt, loc))]
end
method private jumps_to_handler loc t =
let t = purify t in
try
let stmt = Cil_datatype.Typ.Hashtbl.find exn_labels t in
[mkStmt (Goto (ref stmt, loc))]
with
| Not_found -> self#jumps_to_default_handler loc
method! vfile f =
let exns = all_exn () in
if not (Cil_datatype.Typ.Set.is_empty exns) then begin
let loc = Cil_datatype.Location.unknown in
let e = generate_exn_enum exns in
let u,s = generate_exn_union e exns in
let exn =
Cil.makeGlobalVar "__fc_exn" (TComp (s,{scache = Not_Computed},[]))
in
self#update_enum_bindings e exns;
self#update_union_bindings u exns;
exn_struct <- Some s;
can_throw <- true;
new_types <-
GCompTag (s,loc) ::
GCompTag (u,loc) ::
GEnumTag (e,loc) :: new_types;
exn_var <- Some exn;
let exn_init = Cil.makeZeroInit ~loc (TComp(s,{scache=Not_Computed},[]))
in
let gexn_var = GVar(exn, { init = Some exn_init }, loc) in
ChangeDoChildrenPost(
f,add_types_and_globals (List.rev new_types) [gexn_var])
nothing can be thrown in the first place , but we still have
to get rid of ( useless ) try / catch blocks if any .
to get rid of (useless) try/catch blocks if any. *)
DoChildren
method private visit_catch_clause loc (v,b) =
let loc =
match b.bstmts with
| [] -> loc
| [x] -> Cil_datatype.Stmt.loc x
| x::tl ->
fst (Cil_datatype.Stmt.loc x),
snd (Cil_datatype.Stmt.loc (Extlib.last tl))
in
let add_unreachable_block b =
Cil.mkStmt (If(Cil.zero ~loc, b, Cil.mkBlock [], loc))
in
let assign_catched_obj v b =
let exn_obj = self#exn_obj_field in
let kind_field = self#exn_obj_kind_field (purify v.vtype) in
let lv = Cil.addOffsetLval (Field (kind_field,NoOffset)) exn_obj in
let s =
Cil.mkStmtOneInstr
(Set ((Var v, NoOffset), Cil.new_exp ~loc (Lval lv), loc))
in
b.bstmts <- s :: b.bstmts
in
let f = Extlib.the self#current_func in
let update_locals v b =
if not (List.memq v b.blocals) then b.blocals <- v::b.blocals;
if not (List.memq v f.slocals) then f.slocals <- v::f.slocals
in
let b =
(match v with
| Catch_all -> b
| Catch_exn (v,[]) ->
v.vtype <- purify v.vtype; update_locals v b;assign_catched_obj v b; b
| Catch_exn(v,aux) ->
let add_one_aux stmts (v,b) =
v.vtype <- purify v.vtype; update_locals v b;
assign_catched_obj v b;
add_unreachable_block b :: stmts
in
b.blocals <- List.filter (fun v' -> v!=v') b.blocals;
let aux_blocks =
List.fold_left add_one_aux [Cil.mkStmt (Block b)] aux
in
let main_block = Cil.mkBlock aux_blocks in
v.vtype <- purify v.vtype;
update_locals v main_block;
main_block)
in
ignore (Visitor.visitFramacBlock (self :> Visitor.frama_c_visitor) b);
add_unreachable_block b
method! vfunc _ = label_counter <- 0; DoChildren
method private modify_current () =
modified_funcs <-
Cil_datatype.Fundec.Set.add (Extlib.the self#current_func) modified_funcs;
method private aux_handler_goto target (v,b) =
let loc = v.vdecl in
let goto_main_handler = Cil.mkStmt (Goto (ref target,loc)) in
let suf =
if label_counter = 0 then "" else "_" ^ (string_of_int label_counter)
in
let lab = (get_type_tag (purify v.vtype)) ^ suf in
label_counter <- label_counter + 1;
b.bstmts <- b.bstmts @ [goto_main_handler];
we have at least the statement in the block
let s = List.hd b.bstmts in
s.labels <- (Label(lab,loc,false)::s.labels);
Cil_datatype.Typ.Hashtbl.add exn_labels (purify v.vtype) s
method private guard_post_cond (kind,pred as orig) =
match kind with
(* If we exit explicitely with exit,
we haven't seen an uncaught exception anyway. *)
| Exits | Breaks | Continues -> orig
| Returns | Normal ->
let loc = pred.ip_loc in
let p = self#pred_uncaught_flag loc false in
let pred' = Logic_const.pred_of_id_pred pred in
(kind,
(Logic_const.new_predicate
(Logic_const.pimplies ~loc (p,pred'))))
method! vbehavior b =
match self#current_kf, self#current_stmt with
| None, None -> SkipChildren
Prototype is assumed to not throw any exception .
| None, Some _ ->
Kernel.fatal
"Inconsistent visitor state: visiting a statement \
outside of any function."
| Some f, None when not (Kernel_function.is_definition f) ->
(* By hypothesis, prototypes do not throw anything. *)
SkipChildren
| Some f, None -> (* function contract *)
let exns = Exns.find f in
if Cil_datatype.Typ.Set.is_empty exns then SkipChildren
else begin
b.b_post_cond <- List.map self#guard_post_cond b.b_post_cond;
ChangeTo b (* need to register the new clauses. *)
end
| Some _, Some s -> (* statement contract *)
let exns = ExnsStmt.find s in
if Cil_datatype.Typ.Set.is_empty exns then SkipChildren
else begin
b.b_post_cond <- List.map self#guard_post_cond b.b_post_cond;
ChangeTo b
end
method! vstmt_aux s =
match s.skind with
| Instr (Call (_,f,_,loc) as instr) ->
let my_exns = find_exns f in
if Cil_datatype.Typ.Set.is_empty my_exns then SkipChildren
else begin
self#modify_current ();
let make_jump t (stmts, uncaught) =
let t = purify t in
if Cil_datatype.Typ.Hashtbl.mem exn_labels t then begin
let e = self#exn_kind t in
let e = Cil.new_exp ~loc (Const (CEnum e)) in
let b = self#jumps_to_handler loc t in
let s = Cil.mkStmt (Block (Cil.mkBlock b)) in
s.labels <- [Case (Simple e,loc)];
s::stmts, uncaught
end else stmts, true
in
let stmts, uncaught =
Cil_datatype.Typ.Set.fold make_jump my_exns ([],false)
in
let stmts =
if uncaught then begin
let default =
Cil.mkStmt (
Block (Cil.mkBlock (self#jumps_to_default_handler loc)))
in
default.labels <- [Default loc];
List.rev_append stmts [default]
end else List.rev stmts
in
let test = self#test_uncaught_flag loc true in
let cases = Cil.new_exp ~loc (Lval self#exn_kind_field) in
let switch = Cil.mkStmt (Switch(cases,Cil.mkBlock stmts,stmts,loc)) in
let handler =
Cil.mkStmt (If(test,Cil.mkBlock [switch],Cil.mkBlock [],loc))
in
let instr =
Visitor.visitFramacInstr (self:>Visitor.frama_c_visitor) instr
in
let call = Cil.mkStmtOneInstr (List.hd instr) in
s.skind <- Block (Cil.mkBlock [call;handler]);
SkipChildren
end
| Throw _ when not can_throw ->
Kernel.fatal "Unexpected Throw statement"
| Throw(Some(e,t),loc) ->
self#modify_current();
let s1 = self#set_uncaught_flag loc true in
let s2 = self#set_exn_kind loc t in
let s3 = self#set_exn_value loc t e in
let rv = self#jumps_to_handler loc t in
let b = mkBlock (s1 :: s2 :: s3 :: rv) in
s.skind <- Block b;
SkipChildren
| Throw (None,loc) ->
self#modify_current ();
let s1 = self#set_uncaught_flag loc true in
let t = purify (Extlib.the exn_var).vtype in
let rv = self#jumps_to_handler loc t in
let b = mkBlock (s1 :: rv) in
s.skind <- Block b;
SkipChildren
| TryCatch (t,_,_) when not can_throw ->
self#modify_current();
(* no exception can be thrown:
we can simply remove the catch clauses. *)
s.skind <- (Block t);
DoChildren (* visit the block for nested try catch. *)
| TryCatch (t,c,loc) ->
self#modify_current();
Visit the catch clauses first , as they are in the same catch scope
than the current block . As we are adding statements in the
auxiliary blocks , we need to do that before adding labels to the
entry points of these blocks .
than the current block. As we are adding statements in the
auxiliary blocks, we need to do that before adding labels to the
entry points of these blocks.
*)
let stmts = List.map (self#visit_catch_clause loc) c in
let suf =
if label_counter = 0 then "" else "_" ^ (string_of_int label_counter)
in
label_counter <- label_counter + 1;
(* now generate the labels for jumping to the appropriate block when
catching an exception. *)
List.iter
(function
| (Catch_exn (v,aux),b) ->
(* first thing that we do is to flag the exn as caught *)
let stmt = self#set_uncaught_flag v.vdecl false in
let label = (get_type_tag (purify v.vtype)) ^ suf in
stmt.labels <- [Label (label,v.vdecl,false)];
b.bstmts <- stmt :: b.bstmts;
(match aux with
| [] ->
Cil_datatype.Typ.Hashtbl.add exn_labels (purify v.vtype) stmt
| _ :: _ ->
List.iter (self#aux_handler_goto stmt) aux)
| (Catch_all, b) ->
let loc =
match b.bstmts with [] -> loc | s::_ -> Cil_datatype.Stmt.loc s
in
let stmt = self#set_uncaught_flag loc false in
stmt.labels <- [Label ("catch_all" ^ suf,loc,false)];
b.bstmts <- stmt :: b.bstmts;
Stack.push stmt catch_all_label)
We generate the bindings in reverse order , as if two clauses
match the same type , the first one ( which is the one that has
to be taken ) , will be visited last , hiding the binding of the
second in the .
match the same type, the first one (which is the one that has
to be taken), will be visited last, hiding the binding of the
second in the Hashtbl. *)
(List.rev c);
ignore (Visitor.visitFramacBlock (self:>Visitor.frama_c_visitor) t);
List.iter
(function
| (Catch_exn (v,[]), _) ->
Cil_datatype.Typ.Hashtbl.remove exn_labels (purify v.vtype)
| Catch_exn(_,l), _ ->
List.iter
(fun (v,_) ->
Cil_datatype.Typ.Hashtbl.remove exn_labels (purify v.vtype))
l
| Catch_all,_ -> ignore (Stack.pop catch_all_label))
c; (* we remove bindings in the reverse order as we added them,
though order does not really matter here. *)
t.bstmts <- t.bstmts @ stmts;
s.skind <- Block t;
SkipChildren
| _ -> DoChildren
end
let prepare_file f =
if Kernel.SimplifyCfg.get () then begin
Cfg.prepareCFG ~keepSwitch:false f;
end;
File.must_recompute_cfg f
let remove_exn f =
if Kernel.RemoveExn.get() then begin
Visitor.visitFramacFileSameGlobals (new exn_visit) f;
let vis = new erase_exn in
Visitor.visitFramacFile (vis :> Visitor.frama_c_visitor) f;
Cil_datatype.Fundec.Set.iter prepare_file vis#modified_funcs
end
let transform_category = File.register_code_transformation_category "remove_exn"
let () =
let deps = [ (module Kernel.RemoveExn: Parameter_sig.S) ] in
File.add_code_transformation_after_cleanup ~deps transform_category remove_exn
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/kernel_services/analysis/exn_flow.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
all exceptions that can be raised somewhere in the AST.
Used to handle function pointers without exn specification
current set of exn included in a catch-all clause. Used to
handle Throw None;
uncaught exceptions are lift to previous set of exn, but
only if there's no catch-all clause.
must take into account exceptions thrown by a fun call
No exception can be thrown here.
add known exns in table and recurse. Termination is ensured
by the fact that only a finite number of exceptions
can be thrown.
TODO: introduce extension to declare
exceptions that can be thrown by prototypes.
Function pointer: we consider that it can throw any possible
exception.
just ignore prototypes.
enumeration for all possible exceptions
not generated if no exn can be thrown
Take into account -enum option?
discriminated union (i.e. struct + union) for all possible exceptions.
reverse before filling.
no catch-all clause in the function: just go up in the stack.
rt is void: do not need to create a dummy return value
If we exit explicitely with exit,
we haven't seen an uncaught exception anyway.
By hypothesis, prototypes do not throw anything.
function contract
need to register the new clauses.
statement contract
no exception can be thrown:
we can simply remove the catch clauses.
visit the block for nested try catch.
now generate the labels for jumping to the appropriate block when
catching an exception.
first thing that we do is to flag the exn as caught
we remove bindings in the reverse order as we added them,
though order does not really matter here. | Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil
open Cil_types
let dkey = Kernel.register_category "exn_flow"
module All_exn =
State_builder.Option_ref(Cil_datatype.Typ.Set)
(struct let name = "Exn_flow.All_exn" let dependencies = [Ast.self] end)
module Exns =
State_builder.Hashtbl(Kernel_function.Hashtbl)(Cil_datatype.Typ.Set)
(struct
let name = "Exn_flow.Exns"
let dependencies = [Ast.self; All_exn.self]
let size = 47
end)
module ExnsStmt =
State_builder.Hashtbl(Cil_datatype.Stmt.Hashtbl)(Cil_datatype.Typ.Set)
(struct
let name = "Exn_flow.ExnsStmt"
let dependencies = [Ast.self; All_exn.self]
let size = 53
end)
let self_fun = Exns.self
let self_stmt = ExnsStmt.self
let purify t =
let t = Cil.unrollTypeDeep t in
Cil.type_remove_qualifier_attributes_deep t
class all_exn =
object
inherit Visitor.frama_c_inplace
val mutable all_exn = Cil_datatype.Typ.Set.empty
method get_exn = all_exn
method! vstmt_aux s =
match s.skind with
| Throw (Some (_,t),_) ->
all_exn <- Cil_datatype.Typ.Set.add (purify t) all_exn;
SkipChildren
| _ -> DoChildren
end
let compute_all_exn () =
let vis = new all_exn in
Visitor.visitFramacFileSameGlobals (vis:>Visitor.frama_c_visitor) (Ast.get());
vis#get_exn
let all_exn () = All_exn.memo compute_all_exn
let add_exn_var exns v =
let t = Cil.unrollTypeDeep v.vtype in
let t = Cil.type_remove_qualifier_attributes t in
Cil_datatype.Typ.Set.add t exns
let add_exn_clause exns (v,_) = add_exn_var exns v
We 're not really interested by intra - procedural Dataflow here : all the
interesting stuff happens at inter - procedural level ( except for Throw
encapsulated directly in a TryCatch , but even then it is easily captured
at syntactical level ) . Therefore , we can as well use a syntactic pass
at intra - procedural level
interesting stuff happens at inter-procedural level (except for Throw
encapsulated directly in a TryCatch, but even then it is easily captured
at syntactical level). Therefore, we can as well use a syntactic pass
at intra-procedural level
*)
class exn_visit =
object (self)
inherit Visitor.frama_c_inplace
val stack = Stack.create ()
val possible_exn = Stack.create ()
val current_exn = Stack.create ()
method private recursive_call kf =
try
Stack.iter
(fun (kf',_) -> if Kernel_function.equal kf kf' then raise Exit) stack;
false
with Exit -> true
method private add_exn t =
let current_uncaught = Stack.top possible_exn in
current_uncaught:= Cil_datatype.Typ.Set.add t !current_uncaught
method private union_exn s =
let current_uncaught = Stack.top possible_exn in
current_uncaught := Cil_datatype.Typ.Set.union s !current_uncaught
method! vstmt_aux s =
match s.skind with
| Throw (None,_) ->
let my_exn = Stack.top current_exn in
self#union_exn my_exn; ExnsStmt.replace s my_exn; SkipChildren
| Throw(Some (_,t),_) ->
let t = Cil.unrollTypeDeep t in
let t = Cil.type_remove_qualifier_attributes t in
self#add_exn t;
ExnsStmt.replace s (Cil_datatype.Typ.Set.singleton t);
SkipChildren
| TryCatch (t,c,_) ->
let catch, catch_all =
List.fold_left
(fun (catch, catch_all) ->
function
| (Catch_all,_) -> catch, true
| (Catch_exn(v,[]),_) ->
let catch = add_exn_var catch v in
catch, catch_all
| (Catch_exn(_,aux), _) ->
let catch = List.fold_left add_exn_clause catch aux in
catch, catch_all)
(Cil_datatype.Typ.Set.empty,false) c
in
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
ignore (Visitor.visitFramacBlock (self:>Visitor.frama_c_inplace) t);
let my_exn = Stack.pop possible_exn in
let uncaught = Cil_datatype.Typ.Set.diff !my_exn catch in
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
if not catch_all then self#union_exn uncaught;
List.iter
(fun (v,b) ->
let catch_all =
match v with
Catch_all -> true
| Catch_exn (v,[]) ->
let catch = add_exn_var Cil_datatype.Typ.Set.empty v in
Stack.push catch current_exn; false
| Catch_exn (_,aux) ->
let catch =
List.fold_left
add_exn_clause Cil_datatype.Typ.Set.empty aux
in
Stack.push catch current_exn; false
in
ignore
(Visitor.visitFramacBlock (self:>Visitor.frama_c_inplace) b);
if not catch_all then ignore (Stack.pop current_exn))
c;
let my_exn = !(Stack.pop possible_exn) in
ExnsStmt.replace s my_exn;
self#union_exn my_exn;
SkipChildren
| If _ | Switch _ | Loop _ | Block _ | UnspecifiedSequence _
| TryFinally _ | TryExcept _
Stack.push (ref Cil_datatype.Typ.Set.empty) possible_exn;
DoChildrenPost
(fun s ->
let my_exn = !(Stack.pop possible_exn) in
ExnsStmt.replace s my_exn;
self#union_exn my_exn;
s)
| Return _ | Goto _ | Break _ | Continue _ ->
ExnsStmt.replace s Cil_datatype.Typ.Set.empty;
SkipChildren
method! vinst =
function
| Call(_,{ enode = Lval(Var f,NoOffset) },_,_) ->
let kf = Globals.Functions.get f in
if self#recursive_call kf then begin
let module Found =
struct
exception F of Cil_datatype.Typ.Set.t
end
in
let computed_exn =
try
Stack.iter
(fun (kf', exns) ->
if Kernel_function.equal kf kf' then raise (Found.F !exns))
stack;
Kernel.fatal "No cycle found!"
with Found.F exns -> exns
in
let known_exn =
try Exns.find kf with Not_found -> Cil_datatype.Typ.Set.empty
in
if Cil_datatype.Typ.Set.subset computed_exn known_exn then begin
Fixpoint found , no need to recurse .
self#union_exn known_exn
end else begin
let kf_exn = Cil_datatype.Typ.Set.union computed_exn known_exn in
Exns.replace kf kf_exn;
ignore
(Visitor.visitFramacFunction
(self:>Visitor.frama_c_visitor)
(Kernel_function.get_definition kf));
let callee_exn = Exns.find kf in
self#union_exn callee_exn
end
end else if Exns.mem kf then begin
self#union_exn (Exns.find kf)
end else if Kernel_function.is_definition kf then begin
let def = Kernel_function.get_definition kf in
ignore
(Visitor.visitFramacFunction (self:>Visitor.frama_c_visitor) def);
let callee_exn = Exns.find kf in
self#union_exn callee_exn
Kernel.warning
"Assuming declared function %a can't throw any exception"
Kernel_function.pretty kf
end;
SkipChildren
| Call _ ->
self#union_exn (all_exn()); SkipChildren
| _ -> SkipChildren
method! vfunc f =
let my_exns = ref Cil_datatype.Typ.Set.empty in
let kf = Globals.Functions.get f.svar in
Stack.push (kf,my_exns) stack;
Stack.push my_exns possible_exn;
let after_visit f =
let callee_exn = Stack.pop possible_exn in
Exns.add kf !callee_exn;
ignore (Stack.pop stack); f
in
DoChildrenPost after_visit
end
let compute_kf kf =
if Kernel_function.is_definition kf then
ignore
(Visitor.visitFramacFunction (new exn_visit)
(Kernel_function.get_definition kf))
let compute () = Globals.Functions.iter compute_kf
let get_type_tag t =
let rec aux t =
match t with
| TVoid _ -> "v"
| TInt (IBool,_) -> "B"
| TInt (IChar,_) -> "c"
| TInt (ISChar,_) -> "sc"
| TInt (IUChar,_) -> "uc"
| TInt (IInt,_) -> "i"
| TInt (IUInt,_) -> "ui"
| TInt (IShort,_) -> "s"
| TInt (IUShort,_) -> "us"
| TInt (ILong,_) -> "l"
| TInt (IULong,_) -> "ul"
| TInt (ILongLong,_) -> "ll"
| TInt (IULongLong,_) -> "ull"
| TFloat(FFloat,_) -> "f"
| TFloat(FDouble,_) -> "d"
| TFloat (FLongDouble,_) -> "ld"
| TPtr(t,_) -> "p" ^ aux t
| TArray(t,_,_,_) -> "a" ^ aux t
| TFun(rt,l,_,_) ->
let base = "fun" ^ aux rt in
(match l with
| None -> base
| Some l ->
List.fold_left (fun acc (_,t,_) -> acc ^ aux t) base l)
| TNamed _ -> Kernel.fatal "named type not correctly unrolled"
| TComp (s,_,_) -> (if s.cstruct then "S" else "U") ^ s.cname
| TEnum (e,_) -> "E" ^ e.ename
| TBuiltin_va_list _ -> "va"
in "__fc_" ^ aux t
let get_type_enum t = "__fc_exn_kind_" ^ (get_type_tag t)
let get_kf_exn kf =
if not (Exns.is_computed()) then compute();
Exns.find kf
let exn_uncaught_name = "exn_uncaught"
let exn_kind_name = "exn_kind"
let exn_obj_name = "exn_obj"
let generate_exn_enum exns =
let loc = Cil_datatype.Location.unknown in
let v = ref 0 in
let info =
{ eorig_name = "__fc_exn_enum";
ename = "__fc_exn_enum";
eitems = [];
eattr = [];
}
in
let create_enum_item t acc =
let ve = Cil.kinteger ~loc IInt !v in
let name = get_type_enum t in
incr v;
{ eiorig_name = name;
einame = name;
eival = ve;
eihost = info;
eiloc = loc;
} :: acc
in
let enums = Cil_datatype.Typ.Set.fold create_enum_item exns [] in
info.eitems <- enums;
info
let generate_exn_union e exns =
let loc = Cil_datatype.Location.unknown in
let create_union_fields _ =
let add_one_field t acc = (get_type_tag t, t, None, [], loc) :: acc in
Cil_datatype.Typ.Set.fold add_one_field exns []
in
let union_name = "__fc_exn_union" in
let exn_kind_union =
Cil.mkCompInfo false union_name ~norig:union_name create_union_fields []
in
let create_struct_fields _ =
let uncaught = (exn_uncaught_name, Cil.intType, None, [], loc) in
let kind = (exn_kind_name, TEnum (e,[]), None, [], loc) in
let obj =
(exn_obj_name,
TComp(exn_kind_union, { scache = Not_Computed } , []), None, [], loc)
in
[uncaught; kind; obj]
in
let struct_name = "__fc_exn_struct" in
let exn_struct =
Cil.mkCompInfo true struct_name ~norig:struct_name create_struct_fields []
in
exn_kind_union, exn_struct
let add_types_and_globals typs globs f =
let iter_globs (acc,added) g =
match g with
| GVarDecl _ | GVar _ | GFun _ as g when not added ->
(g :: List.rev_append globs (List.rev_append typs acc), true)
| _ -> g :: acc, added
in
let globs, added = List.fold_left iter_globs ([],false) f.globals in
let globs =
if added then List.rev globs
else List.rev_append globs (List.rev_append typs globs)
in
f.globals <- globs;
f
let make_init_assign loc v init =
let rec aux lv acc = function
| SingleInit e -> Cil.mkStmtOneInstr (Set(lv,e,loc)) :: acc
| CompoundInit(_,l) ->
let treat_one_offset acc (o,i) = aux (Cil.addOffsetLval o lv) acc i in
List.fold_left treat_one_offset acc l
in
List.rev (aux (Var v, NoOffset) [] init)
let find_exns e =
match e.enode with
| Lval(Var v, NoOffset) ->
(try Exns.find (Globals.Functions.get v)
with Not_found -> Cil_datatype.Typ.Set.empty)
| _ -> all_exn ()
class erase_exn =
object(self)
inherit Visitor.frama_c_inplace
val mutable new_types = []
val exn_enum = Cil_datatype.Typ.Hashtbl.create 7
val exn_union = Cil_datatype.Typ.Hashtbl.create 7
val mutable modified_funcs = Cil_datatype.Fundec.Set.empty
val mutable exn_struct = None
val mutable exn_var = None
val mutable can_throw = false
val mutable catched_var = None
val mutable label_counter = 0
val exn_labels = Cil_datatype.Typ.Hashtbl.create 7
val catch_all_label = Stack.create ()
method modified_funcs = modified_funcs
method private update_enum_bindings enum exns =
let update_one_binding t =
let s = get_type_enum t in
let ei = List.find (fun ei -> ei.einame = s) enum.eitems in
Cil_datatype.Typ.Hashtbl.add exn_enum t ei
in
Cil_datatype.Typ.Set.iter update_one_binding exns
method private update_union_bindings union exns =
let update_one_binding t =
let s = get_type_tag t in
Kernel.debug ~dkey
"Registering %a as possible exn type" Cil_datatype.Typ.pretty t;
let fi = List.find (fun fi -> fi.fname = s) union.cfields in
Cil_datatype.Typ.Hashtbl.add exn_union t fi
in
Cil_datatype.Typ.Set.iter update_one_binding exns
method private exn_kind t = Cil_datatype.Typ.Hashtbl.find exn_enum t
method private exn_field_off name =
List.find (fun fi -> fi.fname = name) (Extlib.the exn_struct).cfields
method private exn_field name =
Var (Extlib.the exn_var), Field(self#exn_field_off name, NoOffset)
method private exn_field_term name =
TVar(Cil.cvar_to_lvar (Extlib.the exn_var)),
TField(self#exn_field_off name, TNoOffset)
method private exn_obj_field = self#exn_field exn_obj_name
method private exn_obj_field_term = self#exn_field_term exn_obj_name
method private exn_kind_field = self#exn_field exn_kind_name
method private exn_kind_field_term = self#exn_field_term exn_kind_name
method private uncaught_flag_field = self#exn_field exn_uncaught_name
method private uncaught_flag_field_term =
self#exn_field_term exn_uncaught_name
method private exn_obj_kind_field t =
Kernel.debug ~dkey
"Searching for %a as possible exn type" Cil_datatype.Typ.pretty t;
Cil_datatype.Typ.Hashtbl.find exn_union t
method private test_uncaught_flag loc b =
let e1 = Cil.new_exp ~loc (Lval self#uncaught_flag_field) in
let e2 = if b then Cil.one ~loc else Cil.zero ~loc in
Cil.new_exp ~loc (BinOp(Eq,e1,e2,Cil.intType))
method private pred_uncaught_flag loc b =
let e1 =
Logic_const.term
~loc (TLval self#uncaught_flag_field_term) Linteger
in
let e2 =
if b then Logic_const.tinteger ~loc 1
else Logic_const.tinteger ~loc 0
in
Logic_const.prel ~loc (Req,e1,e2)
method private set_uncaught_flag loc b =
let e = if b then Cil.one ~loc else Cil.zero ~loc in
Cil.mkStmtOneInstr (Set(self#uncaught_flag_field,e,loc))
method private set_exn_kind loc t =
let e = self#exn_kind (purify t) in
let e = Cil.new_exp ~loc (Const (CEnum e)) in
Cil.mkStmtOneInstr(Set(self#exn_kind_field,e,loc))
method private set_exn_value loc t e =
let lv = self#exn_obj_field in
let union_field = self#exn_obj_kind_field (purify t) in
let lv = Cil.addOffsetLval (Field (union_field, NoOffset)) lv in
Cil.mkStmtOneInstr (Set(lv,e,loc))
method private jumps_to_default_handler loc =
if Stack.is_empty catch_all_label then begin
let kf = Extlib.the self#current_kf in
let ret = Kernel_function.find_return kf in
let rtyp = Kernel_function.get_return_type kf in
if ret.labels = [] then
ret.labels <- [Label("__ret_label",Cil_datatype.Stmt.loc ret,false)];
let goto = mkStmt (Goto (ref ret,loc)) in
match ret.skind with
| Return (None,_) -> [goto]
| Return (Some { enode = Lval(Var rv, NoOffset) },_) ->
let init = Cil.makeZeroInit ~loc rtyp in
make_init_assign loc rv init @ [goto]
| Return _ ->
Kernel.fatal "exception removal should be used after oneRet"
| _ ->
Kernel.fatal "find_return did not give a Return statement"
end else begin
let stmt = Stack.top catch_all_label in
[mkStmt (Goto (ref stmt, loc))]
end
method private jumps_to_handler loc t =
let t = purify t in
try
let stmt = Cil_datatype.Typ.Hashtbl.find exn_labels t in
[mkStmt (Goto (ref stmt, loc))]
with
| Not_found -> self#jumps_to_default_handler loc
method! vfile f =
let exns = all_exn () in
if not (Cil_datatype.Typ.Set.is_empty exns) then begin
let loc = Cil_datatype.Location.unknown in
let e = generate_exn_enum exns in
let u,s = generate_exn_union e exns in
let exn =
Cil.makeGlobalVar "__fc_exn" (TComp (s,{scache = Not_Computed},[]))
in
self#update_enum_bindings e exns;
self#update_union_bindings u exns;
exn_struct <- Some s;
can_throw <- true;
new_types <-
GCompTag (s,loc) ::
GCompTag (u,loc) ::
GEnumTag (e,loc) :: new_types;
exn_var <- Some exn;
let exn_init = Cil.makeZeroInit ~loc (TComp(s,{scache=Not_Computed},[]))
in
let gexn_var = GVar(exn, { init = Some exn_init }, loc) in
ChangeDoChildrenPost(
f,add_types_and_globals (List.rev new_types) [gexn_var])
nothing can be thrown in the first place , but we still have
to get rid of ( useless ) try / catch blocks if any .
to get rid of (useless) try/catch blocks if any. *)
DoChildren
method private visit_catch_clause loc (v,b) =
let loc =
match b.bstmts with
| [] -> loc
| [x] -> Cil_datatype.Stmt.loc x
| x::tl ->
fst (Cil_datatype.Stmt.loc x),
snd (Cil_datatype.Stmt.loc (Extlib.last tl))
in
let add_unreachable_block b =
Cil.mkStmt (If(Cil.zero ~loc, b, Cil.mkBlock [], loc))
in
let assign_catched_obj v b =
let exn_obj = self#exn_obj_field in
let kind_field = self#exn_obj_kind_field (purify v.vtype) in
let lv = Cil.addOffsetLval (Field (kind_field,NoOffset)) exn_obj in
let s =
Cil.mkStmtOneInstr
(Set ((Var v, NoOffset), Cil.new_exp ~loc (Lval lv), loc))
in
b.bstmts <- s :: b.bstmts
in
let f = Extlib.the self#current_func in
let update_locals v b =
if not (List.memq v b.blocals) then b.blocals <- v::b.blocals;
if not (List.memq v f.slocals) then f.slocals <- v::f.slocals
in
let b =
(match v with
| Catch_all -> b
| Catch_exn (v,[]) ->
v.vtype <- purify v.vtype; update_locals v b;assign_catched_obj v b; b
| Catch_exn(v,aux) ->
let add_one_aux stmts (v,b) =
v.vtype <- purify v.vtype; update_locals v b;
assign_catched_obj v b;
add_unreachable_block b :: stmts
in
b.blocals <- List.filter (fun v' -> v!=v') b.blocals;
let aux_blocks =
List.fold_left add_one_aux [Cil.mkStmt (Block b)] aux
in
let main_block = Cil.mkBlock aux_blocks in
v.vtype <- purify v.vtype;
update_locals v main_block;
main_block)
in
ignore (Visitor.visitFramacBlock (self :> Visitor.frama_c_visitor) b);
add_unreachable_block b
method! vfunc _ = label_counter <- 0; DoChildren
method private modify_current () =
modified_funcs <-
Cil_datatype.Fundec.Set.add (Extlib.the self#current_func) modified_funcs;
method private aux_handler_goto target (v,b) =
let loc = v.vdecl in
let goto_main_handler = Cil.mkStmt (Goto (ref target,loc)) in
let suf =
if label_counter = 0 then "" else "_" ^ (string_of_int label_counter)
in
let lab = (get_type_tag (purify v.vtype)) ^ suf in
label_counter <- label_counter + 1;
b.bstmts <- b.bstmts @ [goto_main_handler];
we have at least the statement in the block
let s = List.hd b.bstmts in
s.labels <- (Label(lab,loc,false)::s.labels);
Cil_datatype.Typ.Hashtbl.add exn_labels (purify v.vtype) s
method private guard_post_cond (kind,pred as orig) =
match kind with
| Exits | Breaks | Continues -> orig
| Returns | Normal ->
let loc = pred.ip_loc in
let p = self#pred_uncaught_flag loc false in
let pred' = Logic_const.pred_of_id_pred pred in
(kind,
(Logic_const.new_predicate
(Logic_const.pimplies ~loc (p,pred'))))
method! vbehavior b =
match self#current_kf, self#current_stmt with
| None, None -> SkipChildren
Prototype is assumed to not throw any exception .
| None, Some _ ->
Kernel.fatal
"Inconsistent visitor state: visiting a statement \
outside of any function."
| Some f, None when not (Kernel_function.is_definition f) ->
SkipChildren
let exns = Exns.find f in
if Cil_datatype.Typ.Set.is_empty exns then SkipChildren
else begin
b.b_post_cond <- List.map self#guard_post_cond b.b_post_cond;
end
let exns = ExnsStmt.find s in
if Cil_datatype.Typ.Set.is_empty exns then SkipChildren
else begin
b.b_post_cond <- List.map self#guard_post_cond b.b_post_cond;
ChangeTo b
end
method! vstmt_aux s =
match s.skind with
| Instr (Call (_,f,_,loc) as instr) ->
let my_exns = find_exns f in
if Cil_datatype.Typ.Set.is_empty my_exns then SkipChildren
else begin
self#modify_current ();
let make_jump t (stmts, uncaught) =
let t = purify t in
if Cil_datatype.Typ.Hashtbl.mem exn_labels t then begin
let e = self#exn_kind t in
let e = Cil.new_exp ~loc (Const (CEnum e)) in
let b = self#jumps_to_handler loc t in
let s = Cil.mkStmt (Block (Cil.mkBlock b)) in
s.labels <- [Case (Simple e,loc)];
s::stmts, uncaught
end else stmts, true
in
let stmts, uncaught =
Cil_datatype.Typ.Set.fold make_jump my_exns ([],false)
in
let stmts =
if uncaught then begin
let default =
Cil.mkStmt (
Block (Cil.mkBlock (self#jumps_to_default_handler loc)))
in
default.labels <- [Default loc];
List.rev_append stmts [default]
end else List.rev stmts
in
let test = self#test_uncaught_flag loc true in
let cases = Cil.new_exp ~loc (Lval self#exn_kind_field) in
let switch = Cil.mkStmt (Switch(cases,Cil.mkBlock stmts,stmts,loc)) in
let handler =
Cil.mkStmt (If(test,Cil.mkBlock [switch],Cil.mkBlock [],loc))
in
let instr =
Visitor.visitFramacInstr (self:>Visitor.frama_c_visitor) instr
in
let call = Cil.mkStmtOneInstr (List.hd instr) in
s.skind <- Block (Cil.mkBlock [call;handler]);
SkipChildren
end
| Throw _ when not can_throw ->
Kernel.fatal "Unexpected Throw statement"
| Throw(Some(e,t),loc) ->
self#modify_current();
let s1 = self#set_uncaught_flag loc true in
let s2 = self#set_exn_kind loc t in
let s3 = self#set_exn_value loc t e in
let rv = self#jumps_to_handler loc t in
let b = mkBlock (s1 :: s2 :: s3 :: rv) in
s.skind <- Block b;
SkipChildren
| Throw (None,loc) ->
self#modify_current ();
let s1 = self#set_uncaught_flag loc true in
let t = purify (Extlib.the exn_var).vtype in
let rv = self#jumps_to_handler loc t in
let b = mkBlock (s1 :: rv) in
s.skind <- Block b;
SkipChildren
| TryCatch (t,_,_) when not can_throw ->
self#modify_current();
s.skind <- (Block t);
| TryCatch (t,c,loc) ->
self#modify_current();
Visit the catch clauses first , as they are in the same catch scope
than the current block . As we are adding statements in the
auxiliary blocks , we need to do that before adding labels to the
entry points of these blocks .
than the current block. As we are adding statements in the
auxiliary blocks, we need to do that before adding labels to the
entry points of these blocks.
*)
let stmts = List.map (self#visit_catch_clause loc) c in
let suf =
if label_counter = 0 then "" else "_" ^ (string_of_int label_counter)
in
label_counter <- label_counter + 1;
List.iter
(function
| (Catch_exn (v,aux),b) ->
let stmt = self#set_uncaught_flag v.vdecl false in
let label = (get_type_tag (purify v.vtype)) ^ suf in
stmt.labels <- [Label (label,v.vdecl,false)];
b.bstmts <- stmt :: b.bstmts;
(match aux with
| [] ->
Cil_datatype.Typ.Hashtbl.add exn_labels (purify v.vtype) stmt
| _ :: _ ->
List.iter (self#aux_handler_goto stmt) aux)
| (Catch_all, b) ->
let loc =
match b.bstmts with [] -> loc | s::_ -> Cil_datatype.Stmt.loc s
in
let stmt = self#set_uncaught_flag loc false in
stmt.labels <- [Label ("catch_all" ^ suf,loc,false)];
b.bstmts <- stmt :: b.bstmts;
Stack.push stmt catch_all_label)
We generate the bindings in reverse order , as if two clauses
match the same type , the first one ( which is the one that has
to be taken ) , will be visited last , hiding the binding of the
second in the .
match the same type, the first one (which is the one that has
to be taken), will be visited last, hiding the binding of the
second in the Hashtbl. *)
(List.rev c);
ignore (Visitor.visitFramacBlock (self:>Visitor.frama_c_visitor) t);
List.iter
(function
| (Catch_exn (v,[]), _) ->
Cil_datatype.Typ.Hashtbl.remove exn_labels (purify v.vtype)
| Catch_exn(_,l), _ ->
List.iter
(fun (v,_) ->
Cil_datatype.Typ.Hashtbl.remove exn_labels (purify v.vtype))
l
| Catch_all,_ -> ignore (Stack.pop catch_all_label))
t.bstmts <- t.bstmts @ stmts;
s.skind <- Block t;
SkipChildren
| _ -> DoChildren
end
let prepare_file f =
if Kernel.SimplifyCfg.get () then begin
Cfg.prepareCFG ~keepSwitch:false f;
end;
File.must_recompute_cfg f
let remove_exn f =
if Kernel.RemoveExn.get() then begin
Visitor.visitFramacFileSameGlobals (new exn_visit) f;
let vis = new erase_exn in
Visitor.visitFramacFile (vis :> Visitor.frama_c_visitor) f;
Cil_datatype.Fundec.Set.iter prepare_file vis#modified_funcs
end
let transform_category = File.register_code_transformation_category "remove_exn"
let () =
let deps = [ (module Kernel.RemoveExn: Parameter_sig.S) ] in
File.add_code_transformation_after_cleanup ~deps transform_category remove_exn
|
a63ca0c5c2bd2e043cdd9ae70dbb84d75581fcb45f8ba960fe5e077e40f09e85 | synduce/Synduce | from_list_max.ml |
let xi_0 x6 = x6
let xi_1 x7 x8 = x8
let rec target =
function Leaf(a) -> xi_0 a | Node(a, l, r) -> xi_1 a (target r)
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/extras/solutions/constraints/bst/from_list_max.ml | ocaml |
let xi_0 x6 = x6
let xi_1 x7 x8 = x8
let rec target =
function Leaf(a) -> xi_0 a | Node(a, l, r) -> xi_1 a (target r)
|
|
0e469847a2dbabd37a97542356644ea5a6c68f7dc238747cd2a813621571a51f | generateme/fastmath | s.clj | (ns fastmath.fields.s
(:require [fastmath.core :as m]
[fastmath.random :as r]
[fastmath.vector :as v]
[fastmath.fields.utils :as u]
[fastmath.complex :as c])
(:import [fastmath.vector Vec2]))
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defn stwin-jw
"STwin JWildfire version"
([] {:type :regular
:config (fn [] {:distort (r/drand -6.0 6.0)
:multiplier (u/sdrand 0.0001 3.0)
:offset-xy (r/drand -1.0 1.0)
:offset-x2 (r/drand -1.0 1.0)
:offset-y2 (r/drand -1.0 1.0)
:multiplier2 (u/sdrand 0.0001 2.0)
:multiplier3 (u/sdrand 0.0001 2.0)})})
([^double amount {:keys [^double distort ^double multiplier
^double offset-xy ^double offset-x2 ^double offset-y2
^double multiplier2 ^double multiplier3]}]
(let [amultiplier (* amount multiplier)
om-x2 (* offset-x2 multiplier2)
om-y2 (* offset-y2 multiplier2)
om-xy (* offset-xy multiplier3)]
(fn [^Vec2 v]
(let [x (* (.x v) amultiplier)
y (* (.y v) amultiplier)
x2 (+ (* x x) om-x2)
y2 (+ (* y y) om-y2)
x2+y2 (+ x2 y2)
x2-y2 (- x2 y2)
div (if (zero? x2+y2) 1.0 x2+y2)
result (/ (* x2-y2 (m/sin (* m/TWO_PI distort (+ x y om-xy)))) div)]
(Vec2. (+ (* amount (.x v)) result)
(+ (* amount (.y v)) result)))))))
(defn stwin
"STwin by Xyrus-02, -vincent.deviantart.com/art/STwin-Plugin-136504836"
([] {:type :regular
:config (fn [] {:distort (r/drand -6.0 6.0)
:multiplier (u/sdrand 0.001 3.0)})})
([^double amount {:keys [^double distort ^double multiplier]}]
(let [amultiplier (* amount multiplier)]
(fn [^Vec2 v]
(let [x (* (.x v) amultiplier)
y (* (.y v) amultiplier)
x2 (* x x)
y2 (* y y)
x2+y2 (+ x2 y2)
x2-y2 (- x2 y2)
div (if (zero? x2+y2) 1.0 x2+y2)
result (/ (* x2-y2 (m/sin (* m/TWO_PI distort (+ x y)))) div)]
(Vec2. (+ (* amount (.x v)) result)
(+ (* amount (.y v)) result)))))))
(defn sattractor
([] {:type :random
:config (fn [] {:m (r/randval (r/irand 2 15) (r/drand 2.0 15.0))})})
([^double amount {:keys [^double m]}]
(let [m (max 2.0 m)
im (int m)
a (mapv #(m/cos (* m/TWO_PI (/ ^long % m))) (range im))
b (mapv #(m/sin (* m/TWO_PI (/ ^long % m))) (range im))
hamount (* 0.5 amount)]
(fn [^Vec2 v]
(let [l (r/irand im)
^double al (a l)
^double bl (b l)]
(-> (r/randval
(Vec2. (+ (* 0.5 (.x v)) al)
(+ (* 0.5 (.y v)) bl))
(let [xx (* (.x v) (.x v))]
(Vec2. (+ (* (.x v) al)
(* (.y v) bl)
(* xx bl))
(+ (* (.y v) al)
(* (.x v) bl -1.0)
(* xx al)))))
(v/mult hamount)))))))
(defn- scrambly-mx-randflip
[^long idxmin ^long idxmax ^long seed v]
(reduce (fn [v [^long j ^long prn]]
(let [ridx (inc j)]
(if (> idxmax ridx)
(let [ridx (+ ridx (mod prn (- idxmax ridx)))]
(-> v
(assoc ridx (v j))
(assoc j (v ridx))))
(reduced v)))) v (map vector
(range idxmin Integer/MAX_VALUE)
(next (iterate (fn [^long prn]
(let [prn (+ (* prn 1103515245) 12345)
prn (bit-or (bit-and prn 0xffff0000)
(bit-and 0xff00
(bit-shift-left prn 8))
(bit-and 0xff
(bit-shift-right prn 8)))
prn (if-not (zero? (bit-and prn 4))
(- prn seed)
(bit-xor prn seed))]
(if (neg? prn) (- prn) prn))) 1)))))
(defn scrambly
([] {:type :regular
:config (fn [] {:l (r/irand 3 26)
:seed (r/randval (r/irand 51) (r/irand))
:byrows (r/brand)
:cellsize (u/sdrand 1.0 5.0)})})
([^double amount {:keys [^long l ^long seed byrows ^double cellsize]}]
(let [LL (m/constrain (long (m/abs l)) 3 25)
LL2 (* LL LL)
mx-rd (int-array (if (< seed 50)
(map (fn [^long j] (mod (+ seed j 1) LL2)) (range LL2))
(let [tmp (vec (range LL2))]
(if byrows
(scrambly-mx-randflip 0 LL2 seed tmp)
(reduce (fn [t ^long j]
(scrambly-mx-randflip (* j LL)
(* (inc j) LL)
(+ seed j)
t)) tmp (range LL))))))
cella (/ cellsize LL)
mzcella (* 0.5 cellsize)
cellainv (/ cella)]
(fn [^Vec2 v]
(let [^Vec2 V (-> (v/shift v mzcella)
(v/mult cellainv))
^Vec2 I (v/floor V)]
(if (or (neg? (.x I))
(neg? (.y I))
(>= (.x I) LL)
(>= (.y I) LL))
(v/mult v amount)
(let [V (v/sub V I)
swp (aget mx-rd (+ (.x I) (* LL (.y I))))
I (Vec2. (quot swp LL) (mod swp LL))]
(-> (v/add V I)
(v/mult cella)
(v/shift (- mzcella))
(v/mult amount)))))))))
(defn scry2
([] {:type :regular
:config (fn [] {:sides (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))
:star (u/sdrand 0.01 1.2)
:circle (u/sdrand 0.01 1.2)})})
([^double amount {:keys [^double sides ^double star ^double circle]}]
(let [a (/ m/TWO_PI sides)
sina (m/sin a)
cosa (m/cos a)
a (* m/M_PI_2 -1.0 star)
sins (m/sin a)
coss (m/cos a)
a (* m/M_PI_2 circle)
sinc (m/sin a)
cosc (m/cos a)
sides- (m/abs (dec sides))
ramount (/ amount)]
(fn [^Vec2 v]
(let [xrt (.x v)
yrt (.y v)
r2 (+ (* xrt coss) (* (m/abs yrt) sins))
circle (v/mag v)
^double r2 (loop [r2 r2 xrt xrt yrt yrt i (long 0)]
(if (< i sides-)
(let [nxrt (- (* xrt cosa) (* yrt sina))
nyrt (+ (* xrt sina) (* yrt cosa))]
(recur (max r2 (+ (* nxrt coss) (* (m/abs nyrt) sins))) nxrt nyrt (inc i)))
(+ (* r2 cosc) (* circle sinc))))
r1 r2
r2 (if (> sides- 1) (* r2 r2) (* (m/abs r2) r2))]
(v/mult v (/ (* r1 (+ r2 ramount)))))))))
(defn scry
"Scry"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [t (v/magsq v)
d (-> 1.0
(/ amount)
(+ t)
(* (m/sqrt t))
(+ m/EPSILON))
r (/ 1.0 d)]
(v/mult v r)))))
(defn sec2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [secsin (m/sin (* (.x v) x1))
seccos (m/cos (* (.x v) x2))
secsinh (m/sinh (* (.y v) y1))
seccosh (m/cosh (* (.y v) y2))
secden (/ (* amount 2.0) (+ (m/cos (* 2.0 (.x v)))
(m/cosh (* 2.0 (.y v)))))]
(Vec2. (* secden seccos seccosh)
(* secden secsin secsinh))))))
(defn sec
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [secsin (m/sin (.x v))
seccos (m/cos (.x v))
secsinh (m/sinh (.y v))
seccosh (m/cosh (.y v))
secden (/ (* amount 2.0) (+ (m/cos (* 2.0 (.x v)))
(m/cosh (* 2.0 (.y v)))))]
(Vec2. (* secden seccos seccosh)
(* secden secsin secsinh))))))
(defn secant2
"Secant2"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (* amount (v/mag v))
cr (m/cos r)
icr (/ 1.0 (if (zero? cr) m/EPSILON cr))
ny (if (neg? cr)
(* amount (inc icr))
(* amount (dec icr)))]
(Vec2. (* amount (.x v)) ny)))))
(defn sech2bs
"Sech"
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sn (m/sin (* (.y v) y1))
cn (m/cos (* (.y v) y2))
snh (m/sinh (* (.x v) x1))
cnh (m/cosh (* (.x v) x2))
d (+ (m/cos (* 2.0 (.y v)))
(m/cosh (* 2.0 (.x v))))
d (if (zero? d) m/EPSILON d)
den (/ 2.0 d)]
(Vec2. (* amount den cn cnh)
(* (- amount) den sn snh))))))
(defn sech
"Sech"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sn (m/sin (.y v))
cn (m/cos (.y v))
snh (m/sinh (.x v))
cnh (m/cosh (.x v))
d (+ (m/cos (* 2.0 (.y v)))
(m/cosh (* 2.0 (.x v))))
d (if (zero? d) m/EPSILON d)
den (/ 2.0 d)]
(Vec2. (* amount den cn cnh)
(* (- amount) den sn snh))))))
(defn separation
([] {:type :regular
:config (fn [] {:x (r/drand -1.2 1.2)
:y (r/drand -1.2 1.2)
:xinside (r/drand -1.2 1.2)
:yinside (r/drand -1.2 1.2)})})
([^double amount {:keys [^double x ^double y ^double xinside ^double yinside]}]
(let [sx2 (* x x)
sy2 (* y y)]
(fn [^Vec2 v]
(let [xx (m/sqrt (+ (* (.x v) (.x v)) sx2))
xi (* (.x v) xinside)
yy (m/sqrt (+ (* (.y v) (.y v)) sy2))
yi (* (.y v) yinside)]
(v/mult (Vec2. (if (pos? (.x v)) (- xx xi) (- (+ xx xi)))
(if (pos? (.y v)) (- yy yi) (- (+ yy yi)))) amount))))))
(defn shift
([] {:type :regular
:config (fn [] {:angle (r/drand 360.0)
:shift-x (r/drand -1.0 1.0)
:shift-y (r/drand -1.0 1.0)})})
([^double amount {:keys [^double angle ^double shift-x ^double shift-y]}]
(let [ang (m/radians angle)
sn (m/sin ang)
cs (m/cos ang)]
(fn [^Vec2 v]
(v/mult (Vec2. (- (+ (.x v) (* cs shift-x)) (* sn shift-y))
(- (.y v) (* cs shift-y) (* sn shift-x))) amount)))))
(defn shredlin
([] {:type :regular
:config (fn [] {:xdistance (u/sdrand 0.2 2.0)
:ydistance (u/sdrand 0.2 2.0)
:xwidth (u/sdrand 0.1 2.0)
:ywidth (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double xdistance ^double ydistance ^double xwidth ^double ywidth]}]
(let [asxd (* amount xdistance)
asyd (* amount ydistance)
sxw- (- 1.0 xwidth)
syw- (- 1.0 ywidth)]
(fn [^Vec2 v]
(let [xpos (if (neg? (.x v)) -0.5 0.5)
ypos (if (neg? (.y v)) -0.5 0.5)
xrng (/ (.x v) xdistance)
ixrng (int xrng)
yrng (/ (.y v) ydistance)
iyrng (int yrng)]
(Vec2. (* asxd (+ (* (- xrng ixrng) xwidth) ixrng (* xpos sxw-)))
(* asyd (+ (* (- yrng iyrng) ywidth) iyrng (* ypos syw-)))))))))
(defn shredrad
"ShreadRad"
([] {:type :regular
:config (fn [] {:n (r/randval (u/sirand 1 9) (u/sdrand 0.0001 8.0))
:width (r/drand -2.0 2.0)})})
([^double amount {:keys [^double n ^double width]}]
(let [sa (/ m/TWO_PI n)
sa2 (* 0.5 sa)
sa2sw (* sa2 width)
pi3 (* 3.0 m/PI)]
(fn [v]
(let [ang (v/heading v)
rad (v/mag v)
xang (/ (+ ang pi3 sa2) sa)
ixang (unchecked-int xang)
zang (- (* sa (+ ixang (* width (- xang ixang)))) m/PI sa2sw)]
(Vec2. (* amount rad (m/cos zang))
(* amount rad (m/sin zang))))))))
(defn sigmoid
([] {:type :regular
:config (fn [] {:shiftx (r/drand -2.0 2.0)
:shifty (r/drand -2.0 2.0)})})
([^double amount {:keys [^double shiftx ^double shifty]}]
(let [[ax sx] (if (< -1.0 shiftx 1.0)
(if (zero? shiftx)
[1.0 m/EPSILON]
[(if (neg? shiftx) -1.0 1.0) (/ shiftx)])
[1.0 shiftx])
[ay sy] (if (< -1.0 shifty 1.0)
(if (zero? shifty)
[1.0 m/EPSILON]
[(if (neg? shifty) -1.0 1.0) (/ shifty)])
[1.0 shifty])
s (v/mult (Vec2. sx sy) -5.0)
a (Vec2. ax ay)
vv (* 2.0 (m/abs amount))]
(fn [^Vec2 v]
(-> (v/ediv a (v/shift (v/exp (v/emult v s)) 1.0))
(v/shift -0.5)
(v/mult vv))))))
(defn sin2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sinsin (m/sin (* (.x v) x1))
sincos (m/cos (* (.x v) x2))
sinsinh (m/sinh (* (.y v) y1))
sincosh (m/cosh (* (.y v) y2))]
(Vec2. (* amount sinsin sincosh)
(* amount sincos sinsinh))))))
(defn sin
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sinsin (m/sin (.x v) )
sincos (m/cos (.x v) )
sinsinh (m/sinh (.y v))
sincosh (m/cosh (.y v))]
(Vec2. (* amount sinsin sincosh)
(* amount sincos sinsinh))))))
(defn sineblur
([] {:type :pattern
:config (fn [] {:power (r/randval 0.2 1.0 (r/drand 0.1 2.2))})})
([^double amount {:keys [^double power]}]
(let [power (max 0.0 power)
am (/ amount m/PI)]
(fn [_]
(let [ang (r/drand m/TWO_PI)
r (* am (if (m/one? power)
(m/acos (r/drand -1.0 1.0))
(m/acos (dec (* 2.0 (m/exp (* (m/log (r/drand)) power)))))))]
(Vec2. (* r (m/cos ang))
(* r (m/sin ang))))))))
(defn sinh2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sinhsin (m/sin (* (.y v) y1))
sinhcos (m/cos (* (.y v) y2))
sinhsinh (m/sinh (* (.x v) x1))
sinhcosh (m/cosh (* (.x v) x2))]
(Vec2. (* amount sinhsinh sinhcos)
(* amount sinhcosh sinhsin))))))
(defn sinh
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sinhsin (m/sin (.y v))
sinhcos (m/cos (.y v))
sinhsinh (m/sinh (.x v))
sinhcosh (m/cosh (.x v))]
(Vec2. (* amount sinhsinh sinhcos)
(* amount sinhcosh sinhsin))))))
(defn sintrange
([] {:type :regular
:config (fn [] {:w (r/drand -1.2 1.2)})})
([^double amount {:keys [^double w]}]
(fn [^Vec2 v]
(let [xx (* (.x v) (.x v))
yy (* (.y v) (.y v))
wv (- w (* w (+ xx yy)))]
(Vec2. (* amount (m/sin (.x v)) (+ xx wv))
(* amount (m/sin (.y v)) (+ yy wv)))))))
(defn sinusgrid
([] {:type :regular
:config (fn [] {:ampx (u/sdrand 0.1 0.9)
:ampy (u/sdrand 0.1 0.9)
:freqx (u/sdrand 0.1 5.0)
:freqy (u/sdrand 0.1 5.0)})})
([^double amount {:keys [^double ampx ^double ampy ^double freqx ^double freqy]}]
(let [fx (* freqx m/TWO_PI)
fy (* freqy m/TWO_PI)]
(fn [^Vec2 v]
(let [sx (- (m/cos (* (.x v) fx)))
sy (- (m/cos (* (.y v) fy)))
tx (m/lerp (.x v) sx ampx)
ty (m/lerp (.y v) sy ampy)]
(Vec2. (* amount tx) (* amount ty)))))))
(defn sinusoidal
"Sinusoidal"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(Vec2. (* amount (m/sin (.x v))) (* amount (m/sin (.y v)))))))
(defn spherical
"Spherical"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(v/mult v (/ amount (+ m/EPSILON (v/magsq v)))))))
(defn sphericaln
([] {:type :random
:config (fn [] {:power (u/sdrand 1.0 8.0)
:dist (u/sdrand 0.1 3.0)})})
([^double amount {:keys [^double power ^double dist]}]
(let [fpower (/ m/TWO_PI (m/floor power))]
(fn [^Vec2 v]
(let [R (/ amount (m/pow (v/mag v) dist))
N (int (m/floor (r/drand power)))
alpha (+ (v/heading v) (* N fpower))]
(Vec2. (* R (m/cos alpha))
(* R (m/sin alpha))))))))
(defn spiral
"Spiral"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (+ m/EPSILON (v/mag v))
revr (/ 1.0 r)
sina (* (.x v) revr)
cosa (* (.y v) revr)
sinr (m/sin r)
cosr (m/cos r)]
(Vec2. (* amount revr (+ cosa sinr))
(* amount revr (- sina cosr)))))))
(defn spiralwing
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [c1 (* (.x v) (.x v))
c2 (* (.y v) (.y v))
d (/ amount (+ c1 c2 m/EPSILON))
c2 (m/sin c2)]
(Vec2. (* d (m/cos c1) c2)
(* d (m/sin c1) c2))))))
(defn spligon
([] {:type :regular
:config (fn [] {:sides (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))
:r (u/sdrand 0.5 1.5)
:i (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))})})
([^double amount {:keys [^double sides ^double r ^double i]}]
(let [th (/ sides m/TWO_PI)
thi (/ th)
j (/ (* m/PI i) (* -2.0 sides))]
(fn [^Vec2 v]
(let [t (+ j (* thi (m/floor (* (v/heading v) th))))
dx (* r (m/sin t))
dy (* r (m/cos t))]
(Vec2. (* amount (+ (.x v) dx))
(* amount (+ (.y v) dy))))))))
(defn splipticbs
([] {:type :random
:config (fn [] {:x (r/drand -1.0 1.0)
:y (r/drand -1.0 1.0)})})
([^double amount {:keys [^double x ^double y]}]
(let [v- (/ amount m/HALF_PI)]
(fn [^Vec2 v]
(let [tmp (inc (v/magsq v))
x2 (* 2.0 (.x v))
xmax (* 0.5 (+ (m/sqrt (+ tmp x2))
(m/sqrt (- tmp x2))))
a (/ (.x v) xmax)
b (m/safe-sqrt (- 1.0 (* a a)))
xx (+ (* v- (m/atan2 a b)) (if-not (neg? (.x v)) x (- x)))
yy (+ (* v- (m/log (+ xmax (m/safe-sqrt (dec xmax))))) y)]
(Vec2. xx (r/randval yy (- yy))))))))
(defn splitbrdr
([] {:type :random
:config (fn [] {:x (r/drand -1.0 1.0)
:y (r/drand -1.0 1.0)
:px (r/drand -0.5 0.5)
:py (r/drand -0.5 0.5)})})
([^double amount {:keys [^double x ^double y ^double px ^double py]}]
(let [p (Vec2. px py)]
(fn [^Vec2 v]
(let [B (inc (* 0.25 (v/magsq v)))
b (/ amount B)
V (v/add (v/mult v b) (v/emult v p))
^Vec2 round (Vec2. (m/rint (.x v)) (m/rint (.y v)))
^Vec2 offset (v/mult (Vec2. (- (.x v) (.x round))
(- (.y v) (.y round))) 0.5)
roffset (v/add offset round)]
(r/randval 0.25
(-> roffset
(v/mult amount)
(v/add V))
(if (>= (m/abs (.x offset))
(m/abs (.y offset)))
(if-not (neg? (.x offset))
(-> roffset
(v/add (Vec2. x (/ (* y (.y offset)) (.x offset))))
(v/mult amount)
(v/add V))
(-> roffset
(v/sub (Vec2. y (/ (* y (.y offset)) (.x offset))))
(v/mult amount)
(v/add V)))
(if-not (neg? (.y offset))
(-> roffset
(v/add (Vec2. (/ (* y (.x offset)) (.y offset)) y))
(v/mult amount)
(v/add V))
(-> roffset
(v/sub (Vec2. (/ (* x (.x offset)) (.y offset)) y))
(v/mult amount)
(v/add V))))))))))
(defn split
"Split"
([] {:type :regular
:config (fn [] {:xsplit (r/drand m/-TWO_PI m/TWO_PI)
:ysplit (r/drand m/-TWO_PI m/TWO_PI)})})
([^double amount {:keys [^double xsplit ^double ysplit]}]
(fn [^Vec2 v]
(Vec2. (if (pos? (m/cos (* (.x v) xsplit)))
(* amount (.y v))
(- (* amount (.y v))))
(if (pos? (m/cos (* (.y v) ysplit)))
(* amount (.x v))
(- (* amount (.x v))))))))
(defn splits
([] {:type :regular
:config (fn [] {:x (r/drand -1.5 1.5)
:y (r/drand -1.5 1.5)})})
([^double amount {:keys [^double x ^double y]}]
(fn [^Vec2 v]
(Vec2. (if (pos? (.x v))
(* amount (+ (.x v) x))
(* amount (- (.x v) x)))
(if (pos? (.y v))
(* amount (+ (.y v) y))
(* amount (- (.y v) y)))))))
(defn sqrt-acosech
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acosech)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-acosh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acosh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-acoth
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acoth)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-asech
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/asech)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-asinh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/asinh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-atanh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/atanh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn square
"Square"
([] {:type :pattern})
([^double amount _]
(fn [_]
(Vec2. (* amount (r/drand -0.5 0.5))
(* amount (r/drand -0.5 0.5))))))
(defn squarize
([] {:type :regular})
([^double amount _]
(fn [v]
(let [s (v/mag v)
a (v/heading v)
a (if (neg? a) (+ a m/TWO_PI) a)
p (* 4.0 s a m/M_1_PI)]
(-> (cond
(<= p s) (Vec2. s p)
(<= p (* 3.0 s)) (Vec2. (- (* 2.0 s) p) s)
(<= p (* 5.0 s)) (Vec2. (- s) (- (* 4.0 s) p))
(<= p (* 7.0 s)) (Vec2. (- p (* 6.0 s)) (- s))
:else (Vec2. s (- p (* 8.0 s))))
(v/mult amount))))))
(defn squircular
([] {:type :regular})
([^double amount _]
(let [a2 (* amount amount)]
(fn [^Vec2 v]
(let [u (.x v)
u2 (* u u)
v (.y v)
v2 (* v v)
r (+ u2 v2)
rs (m/sqrt r)
xs (m/sgn u)
r (m/sqrt (- (* a2 r) (* 4.0 u2 v2)))
r (m/sqrt (inc (- (/ u2 v2) (/ (* rs r) (* amount v2)))))
r (/ r m/SQRT2)]
(Vec2. (* xs r)
(* (/ v u) r)))))))
(defn squirrel
"Squirrel"
([] {:type :regular
:config (fn [] {:a (r/drand m/EPSILON 4.0)
:b (r/drand m/EPSILON 4.0)})})
([^double amount {:keys [^double a ^double b]}]
(fn [^Vec2 v]
(let [u (m/sqrt (+ (* a (m/sq (.x v)))
(* b (m/sq (.y v)))))]
(Vec2. (* amount (m/cos u) (m/tan (.x v)))
(* amount (m/sin u) (m/tan (.y v))))))))
(defn squish
([] {:type :random
:config (fn [] {:power (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))})})
([^double amount {:keys [^double power]}]
(let [inv-power (/ power)]
(fn [^Vec2 v]
(let [x (m/abs (.x v))
y (m/abs (.y v))
^Vec2 sp (if (> x y)
(Vec2. x (if (pos? (.x v))
(.y v)
(- (* 4.0 x) (.y v))))
(Vec2. y (if (pos? (.y v))
(- (* 2.0 y) (.x v))
(+ (* 6.0 y) (.x v)))))
s (.x sp)
p (* inv-power (+ (.y sp) (* 8.0 s (m/floor (r/drand power)))))]
(-> (cond
(<= p s) (Vec2. s p)
(<= p (* 3.0 s)) (Vec2. (- (* 2.0 s) p) s)
(<= p (* 5.0 s)) (Vec2. (- s) (- (* 4.0 s) p))
(<= p (* 7.0 s)) (Vec2. (- p (* 6.0 s)) (- s))
:else (Vec2. s (- p (* 8.0 s))))
(v/mult amount)))))))
(defn starblur
([] {:type :pattern
:config (fn [] {:power (r/randval (u/sirand 2 10) (u/sdrand 0.1 10.0))
:range (u/sdrand 0.1 1.5)})})
([^double amount {:keys [^double power ^double range]}]
(let [alpha (/ m/PI power)
length (m/sqrt (inc (- (* range range) (* 2.0 range (m/cos alpha)))))
alpha (m/asin (/ (* (m/sin alpha) range) length))
calpha (m/cos alpha)
salpha (m/sin alpha)
power2 (* 2.0 power)
ppower (/ m/TWO_PI power)]
(fn [_]
(let [f (r/drand power2)
angle (m/trunc f)
iangle (int angle)
f (- f angle)
x (* f length)
z (m/sqrt (inc (- (* x x) (* 2.0 x calpha))))
angle (- (if (even? iangle)
(+ (* ppower (quot iangle 2)) (m/asin (/ (* x salpha) z)))
(- (* ppower (quot iangle 2)) (m/asin (/ (* x salpha) z))))
m/M_PI_2)
z (* z (m/sqrt (r/drand)))]
(Vec2. (* amount z (m/cos angle))
(* amount z (m/sin angle))))))))
(defn stripes
([] {:type :regular
:config (fn [] {:space (r/drand -2.0 2.0)
:warp (r/drand -2.0 2.0)})})
([^double amount {:keys [^double space ^double warp]}]
(let [space- (- 1.0 space)]
(fn [^Vec2 v]
(let [roundx (m/floor (+ (.x v) 0.5))
offsetx (- (.x v) roundx)]
(-> (Vec2. (+ (* offsetx space-) roundx)
(+ (.y v) (* offsetx offsetx warp)))
(v/mult amount)))))))
(defn stripfit
([] {:type :regular
:config (fn [] {:dx (r/drand -3.0 3.0)})})
([^double amount {:keys [^double dx]}]
(let [dxp (* -0.5 dx)]
(fn [^Vec2 v]
(cond
(> (.y v) 1.0) (let [fity (mod (inc (.y v)) 2.0)]
(Vec2. (+ (* amount (.x v)) (* dxp (inc (- (.y v) fity))))
(* amount (dec fity))))
(< (.y v) -1.0) (let [fity (mod (- 1.0 (.y v)) 2.0)]
(Vec2. (+ (* amount (.x v)) (* dxp (dec (+ (.y v) fity))))
(* amount (- 1.0 fity))))
:else (v/mult v amount))))))
(defn supershape
"Supershape"
([] {:type :random
:config (fn [] {:rnd (r/drand -1.0 1.0)
:m (r/drand m/TWO_PI)
:n1 (r/drand -5.0 5.0)
:n2 (r/drand -5.0 5.0)
:n3 (r/drand -5.0 5.0)
:holes (r/drand -1.0 1.0)})})
([^double amount {:keys [^double rnd ^double m ^double n1 ^double n2 ^double n3 ^double holes]}]
(let [pm-4 (/ m 4.0)
pneg1-n1 (/ -1.0 n1)]
(fn [^Vec2 v]
(let [theta (+ (* pm-4 (v/heading v)) m/M_PI_4)
st (m/sin theta)
ct (m/cos theta)
t1 (m/pow (m/abs ct) n2)
t2 (m/pow (m/abs st) n3)
mag (v/mag v)
r (/ (* (* amount (- (+ (r/drand rnd) (* (- 1.0 rnd) mag)) holes))
(m/pow (+ t1 t2) pneg1-n1)) mag)]
(v/mult v r))))))
(defn svensson
([] {:type :regular
:config (fn [] {:a (r/drand -3.0 3.0)
:b (r/drand -3.0 3.0)
:c (r/drand -3.0 3.0)
:d (r/drand -3.0 3.0)})})
([^double amount {:keys [^double a ^double b ^double c ^double d]}]
(fn [^Vec2 v]
(let [ax (* a (.x v))
by (* b (.y v))]
(Vec2. (* amount (- (* d (m/sin ax)) (m/sin by)))
(* amount (+ (* c (m/cos ax)) (m/cos by))))))))
(defn swirl3
"Swirl3"
([] {:type :regular
:config (fn [] {:shift (r/drand -3.0 3.0)})})
([^double amount {:keys [^double shift]}]
(fn [^Vec2 v]
(let [rad (v/magsq v)
ang (+ (v/heading v) (* shift (m/log rad)))
s (m/sin ang)
c (m/cos ang)
arad (* amount rad)]
(Vec2. (* arad c) (* arad s))))))
(defn swirl
"Swirl"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (v/magsq v)
c1 (m/sin r)
c2 (m/cos r)]
(Vec2. (* amount (- (* c1 (.x v)) (* c2 (.y v))))
(* amount (+ (* c2 (.x v)) (* c1 (.y v)))))))))
(defmacro ^:private sym-transform
[a b c d e f]
(let [v (vary-meta (gensym "v") assoc :tag 'Vec2)]
`(fn [~v] (Vec2. (+ (* ~a (.x ~v)) (* ~b (.y ~v)) ~c)
(+ (* ~d (.x ~v)) (* ~e (.y ~v)) ~f)))))
(defn- get-symband
[{:keys [id ^double stepx ^double stepy]}]
(let [sx (/ stepx 2.0)
sy (/ stepy 2.0)
-sx (- sx)
-sy (- sy)]
(case (int id)
0 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 -sy)
(sym-transform 1.0 0.0 sx 0.0 1.0 sy)]
1 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 -sy)
(sym-transform 1.0 0.0 sx 0.0 -1.0 (inc sy))]
2 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 -1.0 (+ sy 0.5))]
3 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 1.0 (+ sy 0.5))]
4 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform 1.0 0.0 (dec sx) 0.0 -1.0 (+ sy 0.5))]
5 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 1.0 (- sy 0.5))
(sym-transform 1.0 0.0 (dec -sx) 0.0 -1.0 (+ -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 -1.0 (+ sy 0.5))]
6 [(sym-transform 1.0 0.0 (- -sx 2.0) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (+ sx 2.0) 0.0 1.0 (- sy 0.5))
(sym-transform 1.0 0.0 sx 0.0 -1.0 (+ sy 0.5))
(sym-transform -1.0 0.0 -sx 0.0 -1.0 (+ -sy 0.5))])))
(defn symband
([] {:type :random
:config (fn [] {:stepx (r/drand -2.0 2.0)
:stepy (r/drand -2.0 2.0)
:id (r/irand 7)})})
([^double amount opts]
(let [transform (get-symband opts)]
(fn [v]
(let [f (rand-nth transform)]
(v/mult (f v) amount))))))
(defn- get-symnet
[{:keys [id ^double spacex ^double spacey ^double stepx ^double stepy]}]
(let [spx (/ spacex 2.0)
spy (/ spacey 2.0)
-spx (- spx)
-spy (- spy)
stx (/ stepx 2.0)
sty (/ stepy 2.0)
-stx (- stx)
-sty (- sty)]
(case (int id)
0[(sym-transform -1.0 0.0 -spx 0.0 -1.0 -spy)
(sym-transform 0.0 1.0 -spx -1.0 0.0 -spy)
(sym-transform 0.0 -1.0 spx 1.0 0.0 spy)
(sym-transform 1.0 0.0 spx 0.0 1.0 spy)]
1 [(sym-transform 1.0 0.0 (+ spacex stx) 0.0 1.0 (+ spacey sty))
(sym-transform -1.0 0.0 (- stx spacex) 0.0 -1.0 (- sty spacey))
(sym-transform 0.0 1.0 (+ spacex stx) -1.0 0.0 (- sty spacey))
(sym-transform 0.0 -1.0 (- stx spacex) 1.0 0.0 (+ spacey sty))
(sym-transform -1.0 0.0 (- -stx spacex) 0.0 1.0 (- spacey sty))
(sym-transform 0.0 -1.0 (- -stx spacex) -1.0 0.0 (- -sty spacey))
(sym-transform 0.0 1.0 (- spacex stx) 1.0 0.0 (- spacey sty))
(sym-transform 1.0 0.0 (- spacex stx) 0.0 -1.0 (- spacey -sty))])))
;; TODO: add more
(defn symnet
([] {:type :random
:config (fn [] {:space (r/drand -3.0 3.0)
:spacex (r/drand -3.0 3.0)
:spacey (r/drand -3.0 3.0)
:stepx (r/drand -2.0 2.0)
:stepy (r/drand -2.0 2.0)
:id (r/irand 2)})})
([^double amount {:keys [^double space] :as opts}]
(let [transform (get-symnet opts)
vspace (Vec2. space space)]
(fn [v]
(let [f (rand-nth transform)]
(v/mult (f (v/add vspace v)) amount))))))
;;
(defn secant
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (* amount (v/mag v))
cr (* amount (m/cos r))
icr (/ 1.0 (if (zero? cr) m/EPSILON cr))]
(Vec2. (* amount (.x v)) icr)))))
| null | https://raw.githubusercontent.com/generateme/fastmath/9281fd6fb7668c180e12acb3763ecc7f8c977e40/src/fastmath/fields/s.clj | clojure | TODO: add more
| (ns fastmath.fields.s
(:require [fastmath.core :as m]
[fastmath.random :as r]
[fastmath.vector :as v]
[fastmath.fields.utils :as u]
[fastmath.complex :as c])
(:import [fastmath.vector Vec2]))
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defn stwin-jw
"STwin JWildfire version"
([] {:type :regular
:config (fn [] {:distort (r/drand -6.0 6.0)
:multiplier (u/sdrand 0.0001 3.0)
:offset-xy (r/drand -1.0 1.0)
:offset-x2 (r/drand -1.0 1.0)
:offset-y2 (r/drand -1.0 1.0)
:multiplier2 (u/sdrand 0.0001 2.0)
:multiplier3 (u/sdrand 0.0001 2.0)})})
([^double amount {:keys [^double distort ^double multiplier
^double offset-xy ^double offset-x2 ^double offset-y2
^double multiplier2 ^double multiplier3]}]
(let [amultiplier (* amount multiplier)
om-x2 (* offset-x2 multiplier2)
om-y2 (* offset-y2 multiplier2)
om-xy (* offset-xy multiplier3)]
(fn [^Vec2 v]
(let [x (* (.x v) amultiplier)
y (* (.y v) amultiplier)
x2 (+ (* x x) om-x2)
y2 (+ (* y y) om-y2)
x2+y2 (+ x2 y2)
x2-y2 (- x2 y2)
div (if (zero? x2+y2) 1.0 x2+y2)
result (/ (* x2-y2 (m/sin (* m/TWO_PI distort (+ x y om-xy)))) div)]
(Vec2. (+ (* amount (.x v)) result)
(+ (* amount (.y v)) result)))))))
(defn stwin
"STwin by Xyrus-02, -vincent.deviantart.com/art/STwin-Plugin-136504836"
([] {:type :regular
:config (fn [] {:distort (r/drand -6.0 6.0)
:multiplier (u/sdrand 0.001 3.0)})})
([^double amount {:keys [^double distort ^double multiplier]}]
(let [amultiplier (* amount multiplier)]
(fn [^Vec2 v]
(let [x (* (.x v) amultiplier)
y (* (.y v) amultiplier)
x2 (* x x)
y2 (* y y)
x2+y2 (+ x2 y2)
x2-y2 (- x2 y2)
div (if (zero? x2+y2) 1.0 x2+y2)
result (/ (* x2-y2 (m/sin (* m/TWO_PI distort (+ x y)))) div)]
(Vec2. (+ (* amount (.x v)) result)
(+ (* amount (.y v)) result)))))))
(defn sattractor
([] {:type :random
:config (fn [] {:m (r/randval (r/irand 2 15) (r/drand 2.0 15.0))})})
([^double amount {:keys [^double m]}]
(let [m (max 2.0 m)
im (int m)
a (mapv #(m/cos (* m/TWO_PI (/ ^long % m))) (range im))
b (mapv #(m/sin (* m/TWO_PI (/ ^long % m))) (range im))
hamount (* 0.5 amount)]
(fn [^Vec2 v]
(let [l (r/irand im)
^double al (a l)
^double bl (b l)]
(-> (r/randval
(Vec2. (+ (* 0.5 (.x v)) al)
(+ (* 0.5 (.y v)) bl))
(let [xx (* (.x v) (.x v))]
(Vec2. (+ (* (.x v) al)
(* (.y v) bl)
(* xx bl))
(+ (* (.y v) al)
(* (.x v) bl -1.0)
(* xx al)))))
(v/mult hamount)))))))
(defn- scrambly-mx-randflip
[^long idxmin ^long idxmax ^long seed v]
(reduce (fn [v [^long j ^long prn]]
(let [ridx (inc j)]
(if (> idxmax ridx)
(let [ridx (+ ridx (mod prn (- idxmax ridx)))]
(-> v
(assoc ridx (v j))
(assoc j (v ridx))))
(reduced v)))) v (map vector
(range idxmin Integer/MAX_VALUE)
(next (iterate (fn [^long prn]
(let [prn (+ (* prn 1103515245) 12345)
prn (bit-or (bit-and prn 0xffff0000)
(bit-and 0xff00
(bit-shift-left prn 8))
(bit-and 0xff
(bit-shift-right prn 8)))
prn (if-not (zero? (bit-and prn 4))
(- prn seed)
(bit-xor prn seed))]
(if (neg? prn) (- prn) prn))) 1)))))
(defn scrambly
([] {:type :regular
:config (fn [] {:l (r/irand 3 26)
:seed (r/randval (r/irand 51) (r/irand))
:byrows (r/brand)
:cellsize (u/sdrand 1.0 5.0)})})
([^double amount {:keys [^long l ^long seed byrows ^double cellsize]}]
(let [LL (m/constrain (long (m/abs l)) 3 25)
LL2 (* LL LL)
mx-rd (int-array (if (< seed 50)
(map (fn [^long j] (mod (+ seed j 1) LL2)) (range LL2))
(let [tmp (vec (range LL2))]
(if byrows
(scrambly-mx-randflip 0 LL2 seed tmp)
(reduce (fn [t ^long j]
(scrambly-mx-randflip (* j LL)
(* (inc j) LL)
(+ seed j)
t)) tmp (range LL))))))
cella (/ cellsize LL)
mzcella (* 0.5 cellsize)
cellainv (/ cella)]
(fn [^Vec2 v]
(let [^Vec2 V (-> (v/shift v mzcella)
(v/mult cellainv))
^Vec2 I (v/floor V)]
(if (or (neg? (.x I))
(neg? (.y I))
(>= (.x I) LL)
(>= (.y I) LL))
(v/mult v amount)
(let [V (v/sub V I)
swp (aget mx-rd (+ (.x I) (* LL (.y I))))
I (Vec2. (quot swp LL) (mod swp LL))]
(-> (v/add V I)
(v/mult cella)
(v/shift (- mzcella))
(v/mult amount)))))))))
(defn scry2
([] {:type :regular
:config (fn [] {:sides (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))
:star (u/sdrand 0.01 1.2)
:circle (u/sdrand 0.01 1.2)})})
([^double amount {:keys [^double sides ^double star ^double circle]}]
(let [a (/ m/TWO_PI sides)
sina (m/sin a)
cosa (m/cos a)
a (* m/M_PI_2 -1.0 star)
sins (m/sin a)
coss (m/cos a)
a (* m/M_PI_2 circle)
sinc (m/sin a)
cosc (m/cos a)
sides- (m/abs (dec sides))
ramount (/ amount)]
(fn [^Vec2 v]
(let [xrt (.x v)
yrt (.y v)
r2 (+ (* xrt coss) (* (m/abs yrt) sins))
circle (v/mag v)
^double r2 (loop [r2 r2 xrt xrt yrt yrt i (long 0)]
(if (< i sides-)
(let [nxrt (- (* xrt cosa) (* yrt sina))
nyrt (+ (* xrt sina) (* yrt cosa))]
(recur (max r2 (+ (* nxrt coss) (* (m/abs nyrt) sins))) nxrt nyrt (inc i)))
(+ (* r2 cosc) (* circle sinc))))
r1 r2
r2 (if (> sides- 1) (* r2 r2) (* (m/abs r2) r2))]
(v/mult v (/ (* r1 (+ r2 ramount)))))))))
(defn scry
"Scry"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [t (v/magsq v)
d (-> 1.0
(/ amount)
(+ t)
(* (m/sqrt t))
(+ m/EPSILON))
r (/ 1.0 d)]
(v/mult v r)))))
(defn sec2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [secsin (m/sin (* (.x v) x1))
seccos (m/cos (* (.x v) x2))
secsinh (m/sinh (* (.y v) y1))
seccosh (m/cosh (* (.y v) y2))
secden (/ (* amount 2.0) (+ (m/cos (* 2.0 (.x v)))
(m/cosh (* 2.0 (.y v)))))]
(Vec2. (* secden seccos seccosh)
(* secden secsin secsinh))))))
(defn sec
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [secsin (m/sin (.x v))
seccos (m/cos (.x v))
secsinh (m/sinh (.y v))
seccosh (m/cosh (.y v))
secden (/ (* amount 2.0) (+ (m/cos (* 2.0 (.x v)))
(m/cosh (* 2.0 (.y v)))))]
(Vec2. (* secden seccos seccosh)
(* secden secsin secsinh))))))
(defn secant2
"Secant2"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (* amount (v/mag v))
cr (m/cos r)
icr (/ 1.0 (if (zero? cr) m/EPSILON cr))
ny (if (neg? cr)
(* amount (inc icr))
(* amount (dec icr)))]
(Vec2. (* amount (.x v)) ny)))))
(defn sech2bs
"Sech"
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sn (m/sin (* (.y v) y1))
cn (m/cos (* (.y v) y2))
snh (m/sinh (* (.x v) x1))
cnh (m/cosh (* (.x v) x2))
d (+ (m/cos (* 2.0 (.y v)))
(m/cosh (* 2.0 (.x v))))
d (if (zero? d) m/EPSILON d)
den (/ 2.0 d)]
(Vec2. (* amount den cn cnh)
(* (- amount) den sn snh))))))
(defn sech
"Sech"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sn (m/sin (.y v))
cn (m/cos (.y v))
snh (m/sinh (.x v))
cnh (m/cosh (.x v))
d (+ (m/cos (* 2.0 (.y v)))
(m/cosh (* 2.0 (.x v))))
d (if (zero? d) m/EPSILON d)
den (/ 2.0 d)]
(Vec2. (* amount den cn cnh)
(* (- amount) den sn snh))))))
(defn separation
([] {:type :regular
:config (fn [] {:x (r/drand -1.2 1.2)
:y (r/drand -1.2 1.2)
:xinside (r/drand -1.2 1.2)
:yinside (r/drand -1.2 1.2)})})
([^double amount {:keys [^double x ^double y ^double xinside ^double yinside]}]
(let [sx2 (* x x)
sy2 (* y y)]
(fn [^Vec2 v]
(let [xx (m/sqrt (+ (* (.x v) (.x v)) sx2))
xi (* (.x v) xinside)
yy (m/sqrt (+ (* (.y v) (.y v)) sy2))
yi (* (.y v) yinside)]
(v/mult (Vec2. (if (pos? (.x v)) (- xx xi) (- (+ xx xi)))
(if (pos? (.y v)) (- yy yi) (- (+ yy yi)))) amount))))))
(defn shift
([] {:type :regular
:config (fn [] {:angle (r/drand 360.0)
:shift-x (r/drand -1.0 1.0)
:shift-y (r/drand -1.0 1.0)})})
([^double amount {:keys [^double angle ^double shift-x ^double shift-y]}]
(let [ang (m/radians angle)
sn (m/sin ang)
cs (m/cos ang)]
(fn [^Vec2 v]
(v/mult (Vec2. (- (+ (.x v) (* cs shift-x)) (* sn shift-y))
(- (.y v) (* cs shift-y) (* sn shift-x))) amount)))))
(defn shredlin
([] {:type :regular
:config (fn [] {:xdistance (u/sdrand 0.2 2.0)
:ydistance (u/sdrand 0.2 2.0)
:xwidth (u/sdrand 0.1 2.0)
:ywidth (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double xdistance ^double ydistance ^double xwidth ^double ywidth]}]
(let [asxd (* amount xdistance)
asyd (* amount ydistance)
sxw- (- 1.0 xwidth)
syw- (- 1.0 ywidth)]
(fn [^Vec2 v]
(let [xpos (if (neg? (.x v)) -0.5 0.5)
ypos (if (neg? (.y v)) -0.5 0.5)
xrng (/ (.x v) xdistance)
ixrng (int xrng)
yrng (/ (.y v) ydistance)
iyrng (int yrng)]
(Vec2. (* asxd (+ (* (- xrng ixrng) xwidth) ixrng (* xpos sxw-)))
(* asyd (+ (* (- yrng iyrng) ywidth) iyrng (* ypos syw-)))))))))
(defn shredrad
"ShreadRad"
([] {:type :regular
:config (fn [] {:n (r/randval (u/sirand 1 9) (u/sdrand 0.0001 8.0))
:width (r/drand -2.0 2.0)})})
([^double amount {:keys [^double n ^double width]}]
(let [sa (/ m/TWO_PI n)
sa2 (* 0.5 sa)
sa2sw (* sa2 width)
pi3 (* 3.0 m/PI)]
(fn [v]
(let [ang (v/heading v)
rad (v/mag v)
xang (/ (+ ang pi3 sa2) sa)
ixang (unchecked-int xang)
zang (- (* sa (+ ixang (* width (- xang ixang)))) m/PI sa2sw)]
(Vec2. (* amount rad (m/cos zang))
(* amount rad (m/sin zang))))))))
(defn sigmoid
([] {:type :regular
:config (fn [] {:shiftx (r/drand -2.0 2.0)
:shifty (r/drand -2.0 2.0)})})
([^double amount {:keys [^double shiftx ^double shifty]}]
(let [[ax sx] (if (< -1.0 shiftx 1.0)
(if (zero? shiftx)
[1.0 m/EPSILON]
[(if (neg? shiftx) -1.0 1.0) (/ shiftx)])
[1.0 shiftx])
[ay sy] (if (< -1.0 shifty 1.0)
(if (zero? shifty)
[1.0 m/EPSILON]
[(if (neg? shifty) -1.0 1.0) (/ shifty)])
[1.0 shifty])
s (v/mult (Vec2. sx sy) -5.0)
a (Vec2. ax ay)
vv (* 2.0 (m/abs amount))]
(fn [^Vec2 v]
(-> (v/ediv a (v/shift (v/exp (v/emult v s)) 1.0))
(v/shift -0.5)
(v/mult vv))))))
(defn sin2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sinsin (m/sin (* (.x v) x1))
sincos (m/cos (* (.x v) x2))
sinsinh (m/sinh (* (.y v) y1))
sincosh (m/cosh (* (.y v) y2))]
(Vec2. (* amount sinsin sincosh)
(* amount sincos sinsinh))))))
(defn sin
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sinsin (m/sin (.x v) )
sincos (m/cos (.x v) )
sinsinh (m/sinh (.y v))
sincosh (m/cosh (.y v))]
(Vec2. (* amount sinsin sincosh)
(* amount sincos sinsinh))))))
(defn sineblur
([] {:type :pattern
:config (fn [] {:power (r/randval 0.2 1.0 (r/drand 0.1 2.2))})})
([^double amount {:keys [^double power]}]
(let [power (max 0.0 power)
am (/ amount m/PI)]
(fn [_]
(let [ang (r/drand m/TWO_PI)
r (* am (if (m/one? power)
(m/acos (r/drand -1.0 1.0))
(m/acos (dec (* 2.0 (m/exp (* (m/log (r/drand)) power)))))))]
(Vec2. (* r (m/cos ang))
(* r (m/sin ang))))))))
(defn sinh2bs
([] {:type :regular
:config (fn [] {:x1 (u/sdrand 0.1 2.0)
:x2 (u/sdrand 0.1 2.0)
:y1 (u/sdrand 0.1 2.0)
:y2 (u/sdrand 0.1 2.0)})})
([^double amount {:keys [^double x1 ^double x2 ^double y1 ^double y2]}]
(fn [^Vec2 v]
(let [sinhsin (m/sin (* (.y v) y1))
sinhcos (m/cos (* (.y v) y2))
sinhsinh (m/sinh (* (.x v) x1))
sinhcosh (m/cosh (* (.x v) x2))]
(Vec2. (* amount sinhsinh sinhcos)
(* amount sinhcosh sinhsin))))))
(defn sinh
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [sinhsin (m/sin (.y v))
sinhcos (m/cos (.y v))
sinhsinh (m/sinh (.x v))
sinhcosh (m/cosh (.x v))]
(Vec2. (* amount sinhsinh sinhcos)
(* amount sinhcosh sinhsin))))))
(defn sintrange
([] {:type :regular
:config (fn [] {:w (r/drand -1.2 1.2)})})
([^double amount {:keys [^double w]}]
(fn [^Vec2 v]
(let [xx (* (.x v) (.x v))
yy (* (.y v) (.y v))
wv (- w (* w (+ xx yy)))]
(Vec2. (* amount (m/sin (.x v)) (+ xx wv))
(* amount (m/sin (.y v)) (+ yy wv)))))))
(defn sinusgrid
([] {:type :regular
:config (fn [] {:ampx (u/sdrand 0.1 0.9)
:ampy (u/sdrand 0.1 0.9)
:freqx (u/sdrand 0.1 5.0)
:freqy (u/sdrand 0.1 5.0)})})
([^double amount {:keys [^double ampx ^double ampy ^double freqx ^double freqy]}]
(let [fx (* freqx m/TWO_PI)
fy (* freqy m/TWO_PI)]
(fn [^Vec2 v]
(let [sx (- (m/cos (* (.x v) fx)))
sy (- (m/cos (* (.y v) fy)))
tx (m/lerp (.x v) sx ampx)
ty (m/lerp (.y v) sy ampy)]
(Vec2. (* amount tx) (* amount ty)))))))
(defn sinusoidal
"Sinusoidal"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(Vec2. (* amount (m/sin (.x v))) (* amount (m/sin (.y v)))))))
(defn spherical
"Spherical"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(v/mult v (/ amount (+ m/EPSILON (v/magsq v)))))))
(defn sphericaln
([] {:type :random
:config (fn [] {:power (u/sdrand 1.0 8.0)
:dist (u/sdrand 0.1 3.0)})})
([^double amount {:keys [^double power ^double dist]}]
(let [fpower (/ m/TWO_PI (m/floor power))]
(fn [^Vec2 v]
(let [R (/ amount (m/pow (v/mag v) dist))
N (int (m/floor (r/drand power)))
alpha (+ (v/heading v) (* N fpower))]
(Vec2. (* R (m/cos alpha))
(* R (m/sin alpha))))))))
(defn spiral
"Spiral"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (+ m/EPSILON (v/mag v))
revr (/ 1.0 r)
sina (* (.x v) revr)
cosa (* (.y v) revr)
sinr (m/sin r)
cosr (m/cos r)]
(Vec2. (* amount revr (+ cosa sinr))
(* amount revr (- sina cosr)))))))
(defn spiralwing
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [c1 (* (.x v) (.x v))
c2 (* (.y v) (.y v))
d (/ amount (+ c1 c2 m/EPSILON))
c2 (m/sin c2)]
(Vec2. (* d (m/cos c1) c2)
(* d (m/sin c1) c2))))))
(defn spligon
([] {:type :regular
:config (fn [] {:sides (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))
:r (u/sdrand 0.5 1.5)
:i (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))})})
([^double amount {:keys [^double sides ^double r ^double i]}]
(let [th (/ sides m/TWO_PI)
thi (/ th)
j (/ (* m/PI i) (* -2.0 sides))]
(fn [^Vec2 v]
(let [t (+ j (* thi (m/floor (* (v/heading v) th))))
dx (* r (m/sin t))
dy (* r (m/cos t))]
(Vec2. (* amount (+ (.x v) dx))
(* amount (+ (.y v) dy))))))))
(defn splipticbs
([] {:type :random
:config (fn [] {:x (r/drand -1.0 1.0)
:y (r/drand -1.0 1.0)})})
([^double amount {:keys [^double x ^double y]}]
(let [v- (/ amount m/HALF_PI)]
(fn [^Vec2 v]
(let [tmp (inc (v/magsq v))
x2 (* 2.0 (.x v))
xmax (* 0.5 (+ (m/sqrt (+ tmp x2))
(m/sqrt (- tmp x2))))
a (/ (.x v) xmax)
b (m/safe-sqrt (- 1.0 (* a a)))
xx (+ (* v- (m/atan2 a b)) (if-not (neg? (.x v)) x (- x)))
yy (+ (* v- (m/log (+ xmax (m/safe-sqrt (dec xmax))))) y)]
(Vec2. xx (r/randval yy (- yy))))))))
(defn splitbrdr
([] {:type :random
:config (fn [] {:x (r/drand -1.0 1.0)
:y (r/drand -1.0 1.0)
:px (r/drand -0.5 0.5)
:py (r/drand -0.5 0.5)})})
([^double amount {:keys [^double x ^double y ^double px ^double py]}]
(let [p (Vec2. px py)]
(fn [^Vec2 v]
(let [B (inc (* 0.25 (v/magsq v)))
b (/ amount B)
V (v/add (v/mult v b) (v/emult v p))
^Vec2 round (Vec2. (m/rint (.x v)) (m/rint (.y v)))
^Vec2 offset (v/mult (Vec2. (- (.x v) (.x round))
(- (.y v) (.y round))) 0.5)
roffset (v/add offset round)]
(r/randval 0.25
(-> roffset
(v/mult amount)
(v/add V))
(if (>= (m/abs (.x offset))
(m/abs (.y offset)))
(if-not (neg? (.x offset))
(-> roffset
(v/add (Vec2. x (/ (* y (.y offset)) (.x offset))))
(v/mult amount)
(v/add V))
(-> roffset
(v/sub (Vec2. y (/ (* y (.y offset)) (.x offset))))
(v/mult amount)
(v/add V)))
(if-not (neg? (.y offset))
(-> roffset
(v/add (Vec2. (/ (* y (.x offset)) (.y offset)) y))
(v/mult amount)
(v/add V))
(-> roffset
(v/sub (Vec2. (/ (* x (.x offset)) (.y offset)) y))
(v/mult amount)
(v/add V))))))))))
(defn split
"Split"
([] {:type :regular
:config (fn [] {:xsplit (r/drand m/-TWO_PI m/TWO_PI)
:ysplit (r/drand m/-TWO_PI m/TWO_PI)})})
([^double amount {:keys [^double xsplit ^double ysplit]}]
(fn [^Vec2 v]
(Vec2. (if (pos? (m/cos (* (.x v) xsplit)))
(* amount (.y v))
(- (* amount (.y v))))
(if (pos? (m/cos (* (.y v) ysplit)))
(* amount (.x v))
(- (* amount (.x v))))))))
(defn splits
([] {:type :regular
:config (fn [] {:x (r/drand -1.5 1.5)
:y (r/drand -1.5 1.5)})})
([^double amount {:keys [^double x ^double y]}]
(fn [^Vec2 v]
(Vec2. (if (pos? (.x v))
(* amount (+ (.x v) x))
(* amount (- (.x v) x)))
(if (pos? (.y v))
(* amount (+ (.y v) y))
(* amount (- (.y v) y)))))))
(defn sqrt-acosech
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acosech)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-acosh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acosh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-acoth
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/acoth)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-asech
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/asech)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-asinh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/asinh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn sqrt-atanh
([] {:type :random})
([^double amount _]
(let [atwopi (* amount m/M_2_PI)]
(fn [z]
(let [z (-> (c/sqrt z)
(c/atanh)
(c/scale atwopi))]
(r/randval z (c/neg z)))))))
(defn square
"Square"
([] {:type :pattern})
([^double amount _]
(fn [_]
(Vec2. (* amount (r/drand -0.5 0.5))
(* amount (r/drand -0.5 0.5))))))
(defn squarize
([] {:type :regular})
([^double amount _]
(fn [v]
(let [s (v/mag v)
a (v/heading v)
a (if (neg? a) (+ a m/TWO_PI) a)
p (* 4.0 s a m/M_1_PI)]
(-> (cond
(<= p s) (Vec2. s p)
(<= p (* 3.0 s)) (Vec2. (- (* 2.0 s) p) s)
(<= p (* 5.0 s)) (Vec2. (- s) (- (* 4.0 s) p))
(<= p (* 7.0 s)) (Vec2. (- p (* 6.0 s)) (- s))
:else (Vec2. s (- p (* 8.0 s))))
(v/mult amount))))))
(defn squircular
([] {:type :regular})
([^double amount _]
(let [a2 (* amount amount)]
(fn [^Vec2 v]
(let [u (.x v)
u2 (* u u)
v (.y v)
v2 (* v v)
r (+ u2 v2)
rs (m/sqrt r)
xs (m/sgn u)
r (m/sqrt (- (* a2 r) (* 4.0 u2 v2)))
r (m/sqrt (inc (- (/ u2 v2) (/ (* rs r) (* amount v2)))))
r (/ r m/SQRT2)]
(Vec2. (* xs r)
(* (/ v u) r)))))))
(defn squirrel
"Squirrel"
([] {:type :regular
:config (fn [] {:a (r/drand m/EPSILON 4.0)
:b (r/drand m/EPSILON 4.0)})})
([^double amount {:keys [^double a ^double b]}]
(fn [^Vec2 v]
(let [u (m/sqrt (+ (* a (m/sq (.x v)))
(* b (m/sq (.y v)))))]
(Vec2. (* amount (m/cos u) (m/tan (.x v)))
(* amount (m/sin u) (m/tan (.y v))))))))
(defn squish
([] {:type :random
:config (fn [] {:power (r/randval (u/sirand 1 10) (u/sdrand 0.1 10.0))})})
([^double amount {:keys [^double power]}]
(let [inv-power (/ power)]
(fn [^Vec2 v]
(let [x (m/abs (.x v))
y (m/abs (.y v))
^Vec2 sp (if (> x y)
(Vec2. x (if (pos? (.x v))
(.y v)
(- (* 4.0 x) (.y v))))
(Vec2. y (if (pos? (.y v))
(- (* 2.0 y) (.x v))
(+ (* 6.0 y) (.x v)))))
s (.x sp)
p (* inv-power (+ (.y sp) (* 8.0 s (m/floor (r/drand power)))))]
(-> (cond
(<= p s) (Vec2. s p)
(<= p (* 3.0 s)) (Vec2. (- (* 2.0 s) p) s)
(<= p (* 5.0 s)) (Vec2. (- s) (- (* 4.0 s) p))
(<= p (* 7.0 s)) (Vec2. (- p (* 6.0 s)) (- s))
:else (Vec2. s (- p (* 8.0 s))))
(v/mult amount)))))))
(defn starblur
([] {:type :pattern
:config (fn [] {:power (r/randval (u/sirand 2 10) (u/sdrand 0.1 10.0))
:range (u/sdrand 0.1 1.5)})})
([^double amount {:keys [^double power ^double range]}]
(let [alpha (/ m/PI power)
length (m/sqrt (inc (- (* range range) (* 2.0 range (m/cos alpha)))))
alpha (m/asin (/ (* (m/sin alpha) range) length))
calpha (m/cos alpha)
salpha (m/sin alpha)
power2 (* 2.0 power)
ppower (/ m/TWO_PI power)]
(fn [_]
(let [f (r/drand power2)
angle (m/trunc f)
iangle (int angle)
f (- f angle)
x (* f length)
z (m/sqrt (inc (- (* x x) (* 2.0 x calpha))))
angle (- (if (even? iangle)
(+ (* ppower (quot iangle 2)) (m/asin (/ (* x salpha) z)))
(- (* ppower (quot iangle 2)) (m/asin (/ (* x salpha) z))))
m/M_PI_2)
z (* z (m/sqrt (r/drand)))]
(Vec2. (* amount z (m/cos angle))
(* amount z (m/sin angle))))))))
(defn stripes
([] {:type :regular
:config (fn [] {:space (r/drand -2.0 2.0)
:warp (r/drand -2.0 2.0)})})
([^double amount {:keys [^double space ^double warp]}]
(let [space- (- 1.0 space)]
(fn [^Vec2 v]
(let [roundx (m/floor (+ (.x v) 0.5))
offsetx (- (.x v) roundx)]
(-> (Vec2. (+ (* offsetx space-) roundx)
(+ (.y v) (* offsetx offsetx warp)))
(v/mult amount)))))))
(defn stripfit
([] {:type :regular
:config (fn [] {:dx (r/drand -3.0 3.0)})})
([^double amount {:keys [^double dx]}]
(let [dxp (* -0.5 dx)]
(fn [^Vec2 v]
(cond
(> (.y v) 1.0) (let [fity (mod (inc (.y v)) 2.0)]
(Vec2. (+ (* amount (.x v)) (* dxp (inc (- (.y v) fity))))
(* amount (dec fity))))
(< (.y v) -1.0) (let [fity (mod (- 1.0 (.y v)) 2.0)]
(Vec2. (+ (* amount (.x v)) (* dxp (dec (+ (.y v) fity))))
(* amount (- 1.0 fity))))
:else (v/mult v amount))))))
(defn supershape
"Supershape"
([] {:type :random
:config (fn [] {:rnd (r/drand -1.0 1.0)
:m (r/drand m/TWO_PI)
:n1 (r/drand -5.0 5.0)
:n2 (r/drand -5.0 5.0)
:n3 (r/drand -5.0 5.0)
:holes (r/drand -1.0 1.0)})})
([^double amount {:keys [^double rnd ^double m ^double n1 ^double n2 ^double n3 ^double holes]}]
(let [pm-4 (/ m 4.0)
pneg1-n1 (/ -1.0 n1)]
(fn [^Vec2 v]
(let [theta (+ (* pm-4 (v/heading v)) m/M_PI_4)
st (m/sin theta)
ct (m/cos theta)
t1 (m/pow (m/abs ct) n2)
t2 (m/pow (m/abs st) n3)
mag (v/mag v)
r (/ (* (* amount (- (+ (r/drand rnd) (* (- 1.0 rnd) mag)) holes))
(m/pow (+ t1 t2) pneg1-n1)) mag)]
(v/mult v r))))))
(defn svensson
([] {:type :regular
:config (fn [] {:a (r/drand -3.0 3.0)
:b (r/drand -3.0 3.0)
:c (r/drand -3.0 3.0)
:d (r/drand -3.0 3.0)})})
([^double amount {:keys [^double a ^double b ^double c ^double d]}]
(fn [^Vec2 v]
(let [ax (* a (.x v))
by (* b (.y v))]
(Vec2. (* amount (- (* d (m/sin ax)) (m/sin by)))
(* amount (+ (* c (m/cos ax)) (m/cos by))))))))
(defn swirl3
"Swirl3"
([] {:type :regular
:config (fn [] {:shift (r/drand -3.0 3.0)})})
([^double amount {:keys [^double shift]}]
(fn [^Vec2 v]
(let [rad (v/magsq v)
ang (+ (v/heading v) (* shift (m/log rad)))
s (m/sin ang)
c (m/cos ang)
arad (* amount rad)]
(Vec2. (* arad c) (* arad s))))))
(defn swirl
"Swirl"
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (v/magsq v)
c1 (m/sin r)
c2 (m/cos r)]
(Vec2. (* amount (- (* c1 (.x v)) (* c2 (.y v))))
(* amount (+ (* c2 (.x v)) (* c1 (.y v)))))))))
(defmacro ^:private sym-transform
[a b c d e f]
(let [v (vary-meta (gensym "v") assoc :tag 'Vec2)]
`(fn [~v] (Vec2. (+ (* ~a (.x ~v)) (* ~b (.y ~v)) ~c)
(+ (* ~d (.x ~v)) (* ~e (.y ~v)) ~f)))))
(defn- get-symband
[{:keys [id ^double stepx ^double stepy]}]
(let [sx (/ stepx 2.0)
sy (/ stepy 2.0)
-sx (- sx)
-sy (- sy)]
(case (int id)
0 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 -sy)
(sym-transform 1.0 0.0 sx 0.0 1.0 sy)]
1 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 -sy)
(sym-transform 1.0 0.0 sx 0.0 -1.0 (inc sy))]
2 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 -1.0 (+ sy 0.5))]
3 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 1.0 (+ sy 0.5))]
4 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform 1.0 0.0 (dec sx) 0.0 -1.0 (+ sy 0.5))]
5 [(sym-transform 1.0 0.0 (dec -sx) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 1.0 (- sy 0.5))
(sym-transform 1.0 0.0 (dec -sx) 0.0 -1.0 (+ -sy 0.5))
(sym-transform -1.0 0.0 (inc sx) 0.0 -1.0 (+ sy 0.5))]
6 [(sym-transform 1.0 0.0 (- -sx 2.0) 0.0 1.0 (- -sy 0.5))
(sym-transform -1.0 0.0 (+ sx 2.0) 0.0 1.0 (- sy 0.5))
(sym-transform 1.0 0.0 sx 0.0 -1.0 (+ sy 0.5))
(sym-transform -1.0 0.0 -sx 0.0 -1.0 (+ -sy 0.5))])))
(defn symband
([] {:type :random
:config (fn [] {:stepx (r/drand -2.0 2.0)
:stepy (r/drand -2.0 2.0)
:id (r/irand 7)})})
([^double amount opts]
(let [transform (get-symband opts)]
(fn [v]
(let [f (rand-nth transform)]
(v/mult (f v) amount))))))
(defn- get-symnet
[{:keys [id ^double spacex ^double spacey ^double stepx ^double stepy]}]
(let [spx (/ spacex 2.0)
spy (/ spacey 2.0)
-spx (- spx)
-spy (- spy)
stx (/ stepx 2.0)
sty (/ stepy 2.0)
-stx (- stx)
-sty (- sty)]
(case (int id)
0[(sym-transform -1.0 0.0 -spx 0.0 -1.0 -spy)
(sym-transform 0.0 1.0 -spx -1.0 0.0 -spy)
(sym-transform 0.0 -1.0 spx 1.0 0.0 spy)
(sym-transform 1.0 0.0 spx 0.0 1.0 spy)]
1 [(sym-transform 1.0 0.0 (+ spacex stx) 0.0 1.0 (+ spacey sty))
(sym-transform -1.0 0.0 (- stx spacex) 0.0 -1.0 (- sty spacey))
(sym-transform 0.0 1.0 (+ spacex stx) -1.0 0.0 (- sty spacey))
(sym-transform 0.0 -1.0 (- stx spacex) 1.0 0.0 (+ spacey sty))
(sym-transform -1.0 0.0 (- -stx spacex) 0.0 1.0 (- spacey sty))
(sym-transform 0.0 -1.0 (- -stx spacex) -1.0 0.0 (- -sty spacey))
(sym-transform 0.0 1.0 (- spacex stx) 1.0 0.0 (- spacey sty))
(sym-transform 1.0 0.0 (- spacex stx) 0.0 -1.0 (- spacey -sty))])))
(defn symnet
([] {:type :random
:config (fn [] {:space (r/drand -3.0 3.0)
:spacex (r/drand -3.0 3.0)
:spacey (r/drand -3.0 3.0)
:stepx (r/drand -2.0 2.0)
:stepy (r/drand -2.0 2.0)
:id (r/irand 2)})})
([^double amount {:keys [^double space] :as opts}]
(let [transform (get-symnet opts)
vspace (Vec2. space space)]
(fn [v]
(let [f (rand-nth transform)]
(v/mult (f (v/add vspace v)) amount))))))
(defn secant
([] {:type :regular})
([^double amount _]
(fn [^Vec2 v]
(let [r (* amount (v/mag v))
cr (* amount (m/cos r))
icr (/ 1.0 (if (zero? cr) m/EPSILON cr))]
(Vec2. (* amount (.x v)) icr)))))
|
722b5980fbb5fad5d8505b75ef6c821a6af35ee982a640d6db017d366c0a9e5e | wireapp/wire-server | Conversation.hs | {-# LANGUAGE OverloadedStrings #-}
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Network.Wire.Client.API.Conversation
( postOtrMessage,
createConv,
getConv,
addMembers,
removeMember,
memberUpdate,
module M,
)
where
import Bilge
import Control.Monad.Catch (MonadThrow)
import Data.ByteString.Conversion
import Data.Id
import Data.List.NonEmpty hiding (cons, toList)
import Data.List1
import Data.Range
import Data.Text (pack)
import Imports
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status hiding (statusCode)
import Network.Wire.Client.API.Push as M (ConvEvent (..), SimpleMembers (..), UserIdList (..))
import Network.Wire.Client.HTTP
import Network.Wire.Client.Monad (ClientException (ParseError))
import Network.Wire.Client.Session
import Wire.API.Conversation as M hiding (memberUpdate)
import Wire.API.Conversation.Protocol as M
import Wire.API.Conversation.Role (roleNameWireAdmin)
import Wire.API.Event.Conversation as M (MemberUpdateData)
import Wire.API.Message as M
postOtrMessage :: MonadSession m => ConvId -> NewOtrMessage -> m ClientMismatch
postOtrMessage cnv msg = sessionRequest req rsc readBody
where
req =
method POST
. paths ["conversations", toByteString' cnv, "otr", "messages"]
. acceptJson
. json msg
$ empty
rsc = status201 :| [status412]
| Add one or more users and ( in case of success ) return the event
-- corresponding to the users addition.
--
-- If some users can not be added to the conversation, 'UnexpectedResponse'
-- will be thrown. It's not possible that some users will be added and
-- others will not.
addMembers :: (MonadSession m, MonadThrow m) => ConvId -> List1 UserId -> m (Maybe (ConvEvent SimpleMembers))
addMembers cnv mems = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> Just <$> responseJsonThrow (ParseError . pack) rs
204 -> pure Nothing
_ -> unexpected rs "addMembers: status code"
where
req =
method POST
. paths ["conversations", toByteString' cnv, "members"]
. acceptJson
. json (newInvite mems)
$ empty
rsc = status200 :| [status204]
-- | Remove a user and (in case of success) return the event corresponding
-- to the user removal.
removeMember :: (MonadSession m, MonadThrow m) => ConvId -> UserId -> m (Maybe (ConvEvent UserIdList))
removeMember cnv mem = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> Just <$> responseJsonThrow (ParseError . pack) rs
204 -> pure Nothing
_ -> unexpected rs "removeMember: status code"
where
req =
method DELETE
. paths ["conversations", toByteString' cnv, "members", toByteString' mem]
. acceptJson
$ empty
rsc = status200 :| [status204]
FUTUREWORK : probably should be ' Wire . API.Conversation . Member . MemberUpdate ' .
memberUpdate :: MonadSession m => ConvId -> MemberUpdateData -> m ()
memberUpdate cnv updt = sessionRequest req rsc (const $ pure ())
where
req =
method PUT
. paths ["conversations", toByteString' cnv, "self"]
. acceptJson
. json updt
$ empty
rsc = status200 :| []
getConv :: (MonadSession m, MonadThrow m) => ConvId -> m (Maybe Conversation)
getConv cnv = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> responseJsonThrow (ParseError . pack) rs
404 -> pure Nothing
_ -> unexpected rs "getConv: status code"
where
req =
method GET
. paths ["conversations", toByteString' cnv]
. acceptJson
$ empty
rsc = status200 :| [status404]
-- | Create a conversation with the session user in it and any number of
other users ( possibly zero ) .
createConv ::
MonadSession m =>
-- | Other users to add to the conversation
[UserId] ->
-- | Conversation name
Maybe Text ->
m Conversation
createConv users name = sessionRequest req rsc readBody
where
req =
method POST
. path "conversations"
. acceptJson
. json (NewConv users [] (name >>= checked) mempty Nothing Nothing Nothing Nothing roleNameWireAdmin M.ProtocolProteusTag)
$ empty
rsc = status201 :| []
| null | https://raw.githubusercontent.com/wireapp/wire-server/7f6a2903f2435736b9a498a853a48c3c5abdfb8d/libs/api-client/src/Network/Wire/Client/API/Conversation.hs | haskell | # LANGUAGE OverloadedStrings #
This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>.
corresponding to the users addition.
If some users can not be added to the conversation, 'UnexpectedResponse'
will be thrown. It's not possible that some users will be added and
others will not.
| Remove a user and (in case of success) return the event corresponding
to the user removal.
| Create a conversation with the session user in it and any number of
| Other users to add to the conversation
| Conversation name |
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Network.Wire.Client.API.Conversation
( postOtrMessage,
createConv,
getConv,
addMembers,
removeMember,
memberUpdate,
module M,
)
where
import Bilge
import Control.Monad.Catch (MonadThrow)
import Data.ByteString.Conversion
import Data.Id
import Data.List.NonEmpty hiding (cons, toList)
import Data.List1
import Data.Range
import Data.Text (pack)
import Imports
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status hiding (statusCode)
import Network.Wire.Client.API.Push as M (ConvEvent (..), SimpleMembers (..), UserIdList (..))
import Network.Wire.Client.HTTP
import Network.Wire.Client.Monad (ClientException (ParseError))
import Network.Wire.Client.Session
import Wire.API.Conversation as M hiding (memberUpdate)
import Wire.API.Conversation.Protocol as M
import Wire.API.Conversation.Role (roleNameWireAdmin)
import Wire.API.Event.Conversation as M (MemberUpdateData)
import Wire.API.Message as M
postOtrMessage :: MonadSession m => ConvId -> NewOtrMessage -> m ClientMismatch
postOtrMessage cnv msg = sessionRequest req rsc readBody
where
req =
method POST
. paths ["conversations", toByteString' cnv, "otr", "messages"]
. acceptJson
. json msg
$ empty
rsc = status201 :| [status412]
| Add one or more users and ( in case of success ) return the event
addMembers :: (MonadSession m, MonadThrow m) => ConvId -> List1 UserId -> m (Maybe (ConvEvent SimpleMembers))
addMembers cnv mems = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> Just <$> responseJsonThrow (ParseError . pack) rs
204 -> pure Nothing
_ -> unexpected rs "addMembers: status code"
where
req =
method POST
. paths ["conversations", toByteString' cnv, "members"]
. acceptJson
. json (newInvite mems)
$ empty
rsc = status200 :| [status204]
removeMember :: (MonadSession m, MonadThrow m) => ConvId -> UserId -> m (Maybe (ConvEvent UserIdList))
removeMember cnv mem = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> Just <$> responseJsonThrow (ParseError . pack) rs
204 -> pure Nothing
_ -> unexpected rs "removeMember: status code"
where
req =
method DELETE
. paths ["conversations", toByteString' cnv, "members", toByteString' mem]
. acceptJson
$ empty
rsc = status200 :| [status204]
FUTUREWORK : probably should be ' Wire . API.Conversation . Member . MemberUpdate ' .
memberUpdate :: MonadSession m => ConvId -> MemberUpdateData -> m ()
memberUpdate cnv updt = sessionRequest req rsc (const $ pure ())
where
req =
method PUT
. paths ["conversations", toByteString' cnv, "self"]
. acceptJson
. json updt
$ empty
rsc = status200 :| []
getConv :: (MonadSession m, MonadThrow m) => ConvId -> m (Maybe Conversation)
getConv cnv = do
rs <- sessionRequest req rsc consumeBody
case statusCode rs of
200 -> responseJsonThrow (ParseError . pack) rs
404 -> pure Nothing
_ -> unexpected rs "getConv: status code"
where
req =
method GET
. paths ["conversations", toByteString' cnv]
. acceptJson
$ empty
rsc = status200 :| [status404]
other users ( possibly zero ) .
createConv ::
MonadSession m =>
[UserId] ->
Maybe Text ->
m Conversation
createConv users name = sessionRequest req rsc readBody
where
req =
method POST
. path "conversations"
. acceptJson
. json (NewConv users [] (name >>= checked) mempty Nothing Nothing Nothing Nothing roleNameWireAdmin M.ProtocolProteusTag)
$ empty
rsc = status201 :| []
|
2f68c1ec458dbe6d5c605a217bd9b667e7123667429b361efcf2cbabddc81492 | exercism/haskell | Roman.hs | module Roman (numerals) where
numerals :: Int -> Maybe String
numerals = Just . go numeralMap
where
go pairs@((value, digits):pairs') n
| n >= value = digits ++ go pairs (n - value)
| otherwise = go pairs' n
go [] _ = ""
numeralMap = [ (1000, "M"), (900, "CM")
, (500, "D"), (400, "CD")
, (100, "C"), (90, "XC")
, (50, "L"), (40, "XL")
, (10, "X"), (9, "IX")
, (5, "V"), (4, "IV")
, (1, "I") ]
| null | https://raw.githubusercontent.com/exercism/haskell/ae17e9fc5ca736a228db6dda5e3f3b057fa6f3d0/exercises/practice/roman-numerals/.meta/examples/success-standard/src/Roman.hs | haskell | module Roman (numerals) where
numerals :: Int -> Maybe String
numerals = Just . go numeralMap
where
go pairs@((value, digits):pairs') n
| n >= value = digits ++ go pairs (n - value)
| otherwise = go pairs' n
go [] _ = ""
numeralMap = [ (1000, "M"), (900, "CM")
, (500, "D"), (400, "CD")
, (100, "C"), (90, "XC")
, (50, "L"), (40, "XL")
, (10, "X"), (9, "IX")
, (5, "V"), (4, "IV")
, (1, "I") ]
|
|
d0824324f9f52519fb2065c0d182e76c326f59d2910f94aeba4b930bfbc0fed0 | sgbj/MaximaSharp | marray.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1981 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module array)
User array utilities originally due to CFFK .
;;; Note that on the lisp level we regard as an array either
( 1 ) a symbol whose ARRAY property is a common lisp array
;;; [i.e., (symbol-array 'symbol)
;;; == (get 'symbol 'array) => some array] or
( 2 ) a common lisp array .
;;; On the maxima level a declared array not of type HASH or FUNCTIONAL
;;; is either
( 1 m ) a symbol whose ARRAY mproperty is of type ( 1 )
;;; [i.e., (symbol-array (mget 'symbol 'array)) => some array] or
( 2 m ) it is of type ( 2 ) ( and then called a ` fast ' array ) .
;;; Such an array is of type (1m) iff it was created with ARRAY
;;; with USE_FAST_ARRAYS being set to FALSE.
;;;
;;; Curiously enough, ARRAY(...,TYPE,...) (which currently can only be
;;; used for USE_FAST_ARRAYS:FALSE) results in an array which is
simultaneously of type ( 1 ) and ( 1 m ) .
(defun $listarray (ary)
(cons '(mlist)
(cond ((mget ary 'hashar)
(mapcar #'(lambda (subs) ($arrayapply ary subs))
(cdddr (meval (list '($arrayinfo) ary)))))
((mget ary 'array) (listarray (mget ary 'array)))
((arrayp ary)
(if (eql (array-rank ary) 1)
(coerce ary 'list)
(coerce (make-array (apply '* (array-dimensions ary))
:displaced-to ary
:element-type (array-element-type ary))
'list)))
((hash-table-p ary)
(let (vals (tab ary))
(maphash #'(lambda (x &rest l) l
(unless (eq x 'dim1) (push (gethash x tab) vals)))
ary)
(reverse vals)))
((eq (marray-type ary) '$functional)
(cdr ($listarray (mgenarray-content ary))))
(t
(merror (intl:gettext "listarray: argument must be an array; found: ~M")
ary)))))
(defmfun $fillarray (ary1 ary2)
(let ((ary
(or (mget ary1 'array)
(and (arrayp ary1) ary1)
(merror (intl:gettext "fillarray: first argument must be a declared array; found: ~M") ary1))))
(fillarray ary
(cond (($listp ary2) (cdr ary2))
((get (mget ary2 'array) 'array))
((arrayp ary2) ary2)
(t
(merror (intl:gettext "fillarray: second argument must be an array or list; found: ~M") ary2))))
ary1))
(defun getvalue (sym)
(and (symbolp sym) (boundp sym) (symbol-value sym)))
(defmspec $rearray (l)
(setq l (cdr l))
(let ((ar (car l))
(dims (mapcar #'meval (cdr l))))
(cond ($use_fast_arrays
(setf (symbol-value ar) (rearray-aux ar (getvalue ar) dims)))
(t
(rearray-aux ar (getvalue ar) dims)))))
(defun rearray-aux (ar val dims &aux marray-sym)
(cond ((arrayp val)
(apply 'lispm-rearray val dims))
((arrayp (get ar 'array))
(setf (get ar 'array) (apply 'lispm-rearray (get ar 'array) dims)))
((setq marray-sym (mget ar 'array))
(rearray-aux marray-sym nil dims)
ar)
(t (merror (intl:gettext "rearray: argument is not an array: ~A") ar))))
(defun lispm-rearray (ar &rest dims)
(cond ((eql (array-rank ar) (length dims))
(adjust-array ar (mapcar #'1+ (copy-list dims)) :element-type (array-element-type ar) ))
(t (merror (intl:gettext "rearray: arrays must have the same number of subscripts.")))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/marray.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
Note that on the lisp level we regard as an array either
[i.e., (symbol-array 'symbol)
== (get 'symbol 'array) => some array] or
On the maxima level a declared array not of type HASH or FUNCTIONAL
is either
[i.e., (symbol-array (mget 'symbol 'array)) => some array] or
Such an array is of type (1m) iff it was created with ARRAY
with USE_FAST_ARRAYS being set to FALSE.
Curiously enough, ARRAY(...,TYPE,...) (which currently can only be
used for USE_FAST_ARRAYS:FALSE) results in an array which is |
(in-package :maxima)
(macsyma-module array)
User array utilities originally due to CFFK .
( 1 ) a symbol whose ARRAY property is a common lisp array
( 2 ) a common lisp array .
( 1 m ) a symbol whose ARRAY mproperty is of type ( 1 )
( 2 m ) it is of type ( 2 ) ( and then called a ` fast ' array ) .
simultaneously of type ( 1 ) and ( 1 m ) .
(defun $listarray (ary)
(cons '(mlist)
(cond ((mget ary 'hashar)
(mapcar #'(lambda (subs) ($arrayapply ary subs))
(cdddr (meval (list '($arrayinfo) ary)))))
((mget ary 'array) (listarray (mget ary 'array)))
((arrayp ary)
(if (eql (array-rank ary) 1)
(coerce ary 'list)
(coerce (make-array (apply '* (array-dimensions ary))
:displaced-to ary
:element-type (array-element-type ary))
'list)))
((hash-table-p ary)
(let (vals (tab ary))
(maphash #'(lambda (x &rest l) l
(unless (eq x 'dim1) (push (gethash x tab) vals)))
ary)
(reverse vals)))
((eq (marray-type ary) '$functional)
(cdr ($listarray (mgenarray-content ary))))
(t
(merror (intl:gettext "listarray: argument must be an array; found: ~M")
ary)))))
(defmfun $fillarray (ary1 ary2)
(let ((ary
(or (mget ary1 'array)
(and (arrayp ary1) ary1)
(merror (intl:gettext "fillarray: first argument must be a declared array; found: ~M") ary1))))
(fillarray ary
(cond (($listp ary2) (cdr ary2))
((get (mget ary2 'array) 'array))
((arrayp ary2) ary2)
(t
(merror (intl:gettext "fillarray: second argument must be an array or list; found: ~M") ary2))))
ary1))
(defun getvalue (sym)
(and (symbolp sym) (boundp sym) (symbol-value sym)))
(defmspec $rearray (l)
(setq l (cdr l))
(let ((ar (car l))
(dims (mapcar #'meval (cdr l))))
(cond ($use_fast_arrays
(setf (symbol-value ar) (rearray-aux ar (getvalue ar) dims)))
(t
(rearray-aux ar (getvalue ar) dims)))))
(defun rearray-aux (ar val dims &aux marray-sym)
(cond ((arrayp val)
(apply 'lispm-rearray val dims))
((arrayp (get ar 'array))
(setf (get ar 'array) (apply 'lispm-rearray (get ar 'array) dims)))
((setq marray-sym (mget ar 'array))
(rearray-aux marray-sym nil dims)
ar)
(t (merror (intl:gettext "rearray: argument is not an array: ~A") ar))))
(defun lispm-rearray (ar &rest dims)
(cond ((eql (array-rank ar) (length dims))
(adjust-array ar (mapcar #'1+ (copy-list dims)) :element-type (array-element-type ar) ))
(t (merror (intl:gettext "rearray: arrays must have the same number of subscripts.")))))
|
b4ed0436eb8165c9db899c0ba21da3995518cb4f23024cae2198eff2780515d2 | jimcrayne/jhc | read016.hs | -- !!! Checking that both import lists and 'hiding' lists might
-- !!! be empty.
module ShouldCompile where
import List ()
import List hiding ()
x :: Int
x = 1
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/0_parse/2_pass/ghc/read016.hs | haskell | !!! Checking that both import lists and 'hiding' lists might
!!! be empty. | module ShouldCompile where
import List ()
import List hiding ()
x :: Int
x = 1
|
58a152a4236e901419672435fe497507b67e8832741a7a66b13f19bcd3e59bd7 | theodormoroianu/SecondYearCourses | examen.hs | import Control.Monad
import Data.Maybe
type Name = String
data Term
= Var Name
| Con Integer
| Term :+: Term
| Term :/: Term
| Lam Name Term
| App Term Term
| Out Term
deriving Show
pgm1 =
App (Lam "x" (Var "x" :+: Var "x"))
(Out (Con 10) :+: Out (Con 3))
newtype Writer a = Writer { runwriter :: Maybe (a, String) }
instance Monad Writer where
return a = Writer $ Just (a, "")
x >>= f =
case runwriter x of
Just (val1, str1) ->
case runwriter (f val1) of
Just (val2, str2) ->
Writer $ Just (val2, str1 ++ "\n" ++ str2)
_ -> Writer Nothing
_ -> Writer Nothing
instance Applicative Writer where
pure = return
f <*> g = do
x <- f
y <- g
return $ x y
instance Functor Writer where
fmap f a = pure f <*> a
type M a = Writer a
showM :: Show a => M a -> String
showM ma =
case runwriter ma of
Just (w, a) -> "Output: " ++ a ++ ", value: " ++ show w
Nothing -> "Nothing"
data Value
= Num Integer
| Fun (Value -> M Value)
type Env = [(Name, Value)]
instance Show Value where
show (Num x) = show x
show (Fun _) = "<function>"
get :: Name -> Env -> M Value
get name env =
case lookup name env of
Just a -> return a
_ -> Writer Nothing
tell :: String -> M ()
tell s = Writer $ Just ((), s)
interp :: Term -> Env -> M Value
interp (Var name) env = get name env
interp (Con i) _ = return $ Num i
interp (a :+: b) env = do
x1 <- interp a env
x2 <- interp b env
case (x1, x2) of
(Num a, Num b) -> return $ Num (a + b)
_ -> Writer Nothing
interp (a :/: b) env = do
x1 <- interp a env
x2 <- interp b env
case (x1, x2) of
(_, Num 0) -> Writer Nothing
(Num a, Num b) -> return $ Num $ a `div` b
_ -> Writer Nothing
interp (Lam name term) env =
return (Fun (\val -> interp term ((name, val) : env)))
interp (App a b) env = do
v1 <- interp a env
v2 <- interp b env
case v1 of
Fun f -> f v2
_ -> Writer Nothing
interp (Out x) env = do
v <- interp x env
tell $ "Value is " ++ show v
return v
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/90807f90572912424ac9c7b3a12b47172d7f494c/FLP/ExamenHaskell/SimulareExamen/examen.hs | haskell | import Control.Monad
import Data.Maybe
type Name = String
data Term
= Var Name
| Con Integer
| Term :+: Term
| Term :/: Term
| Lam Name Term
| App Term Term
| Out Term
deriving Show
pgm1 =
App (Lam "x" (Var "x" :+: Var "x"))
(Out (Con 10) :+: Out (Con 3))
newtype Writer a = Writer { runwriter :: Maybe (a, String) }
instance Monad Writer where
return a = Writer $ Just (a, "")
x >>= f =
case runwriter x of
Just (val1, str1) ->
case runwriter (f val1) of
Just (val2, str2) ->
Writer $ Just (val2, str1 ++ "\n" ++ str2)
_ -> Writer Nothing
_ -> Writer Nothing
instance Applicative Writer where
pure = return
f <*> g = do
x <- f
y <- g
return $ x y
instance Functor Writer where
fmap f a = pure f <*> a
type M a = Writer a
showM :: Show a => M a -> String
showM ma =
case runwriter ma of
Just (w, a) -> "Output: " ++ a ++ ", value: " ++ show w
Nothing -> "Nothing"
data Value
= Num Integer
| Fun (Value -> M Value)
type Env = [(Name, Value)]
instance Show Value where
show (Num x) = show x
show (Fun _) = "<function>"
get :: Name -> Env -> M Value
get name env =
case lookup name env of
Just a -> return a
_ -> Writer Nothing
tell :: String -> M ()
tell s = Writer $ Just ((), s)
interp :: Term -> Env -> M Value
interp (Var name) env = get name env
interp (Con i) _ = return $ Num i
interp (a :+: b) env = do
x1 <- interp a env
x2 <- interp b env
case (x1, x2) of
(Num a, Num b) -> return $ Num (a + b)
_ -> Writer Nothing
interp (a :/: b) env = do
x1 <- interp a env
x2 <- interp b env
case (x1, x2) of
(_, Num 0) -> Writer Nothing
(Num a, Num b) -> return $ Num $ a `div` b
_ -> Writer Nothing
interp (Lam name term) env =
return (Fun (\val -> interp term ((name, val) : env)))
interp (App a b) env = do
v1 <- interp a env
v2 <- interp b env
case v1 of
Fun f -> f v2
_ -> Writer Nothing
interp (Out x) env = do
v <- interp x env
tell $ "Value is " ++ show v
return v
|
|
877599bf94b20b5eb1b9a57e080a2276f67f75ad4373c8dafa58cc1e12d80219 | fakedata-haskell/fakedata | VForVendetta.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.VForVendetta where
import Config
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseVForVendetta :: FromJSON a => FakerSettings -> Value -> Parser a
parseVForVendetta settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
vForVendetta <- faker .: "v_for_vendetta"
pure vForVendetta
parseVForVendetta settings val =
fail $ "expected Object, but got " <> (show val)
parseVForVendettaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseVForVendettaField settings txt val = do
vForVendetta <- parseVForVendetta settings val
field <- vForVendetta .:? txt .!= mempty
pure field
parseVForVendettaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseVForVendettaFields settings txts val = do
vForVendetta <- parseVForVendetta settings val
helper vForVendetta txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParser "vForVendetta" "characters")
$(genProvider "vForVendetta" "characters")
$(genParser "vForVendetta" "speeches")
$(genProvider "vForVendetta" "speeches")
$(genParser "vForVendetta" "quotes")
$(genProvider "vForVendetta" "quotes")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/VForVendetta.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.VForVendetta where
import Config
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseVForVendetta :: FromJSON a => FakerSettings -> Value -> Parser a
parseVForVendetta settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
vForVendetta <- faker .: "v_for_vendetta"
pure vForVendetta
parseVForVendetta settings val =
fail $ "expected Object, but got " <> (show val)
parseVForVendettaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseVForVendettaField settings txt val = do
vForVendetta <- parseVForVendetta settings val
field <- vForVendetta .:? txt .!= mempty
pure field
parseVForVendettaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseVForVendettaFields settings txts val = do
vForVendetta <- parseVForVendetta settings val
helper vForVendetta txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParser "vForVendetta" "characters")
$(genProvider "vForVendetta" "characters")
$(genParser "vForVendetta" "speeches")
$(genProvider "vForVendetta" "speeches")
$(genParser "vForVendetta" "quotes")
$(genProvider "vForVendetta" "quotes")
|
a8a8afaf7162b3392417c5ae34e8df1542272aaac5a89f160f4b7e109daef45c | dharmatech/psilab | urman-tutorial-paint.sps |
(import (rnrs)
(ypsilon cairo)
(psilab cairo with-cairo))
(let ((surface (cairo_image_surface_create CAIRO_FORMAT_ARGB32 120 120)))
(let ((cr (cairo_create surface)))
(with-cairo cr
(scale 120 120)
(set_source_rgb 0 0 0)
(paint_with_alpha 0.5)
(destroy)))
(cairo_surface_write_to_png surface "paint.png")
(cairo_surface_destroy surface)) | null | https://raw.githubusercontent.com/dharmatech/psilab/16b60e4ae63e3405d74117a50cd9ea313c179b33/cairo/examples/urman-tutorial-paint.sps | scheme |
(import (rnrs)
(ypsilon cairo)
(psilab cairo with-cairo))
(let ((surface (cairo_image_surface_create CAIRO_FORMAT_ARGB32 120 120)))
(let ((cr (cairo_create surface)))
(with-cairo cr
(scale 120 120)
(set_source_rgb 0 0 0)
(paint_with_alpha 0.5)
(destroy)))
(cairo_surface_write_to_png surface "paint.png")
(cairo_surface_destroy surface)) |
|
44689e2554c19273e9cf4be435d3e4fa5405cba27b53c0cc271a3e4d209eb7db | aionescu/dynasty | Parser.hs | module Language.Dynasty.Parser(parse, varOpChars) where
import Control.Monad.Combinators.Expr(Operator(..), makeExprParser)
import Data.Bifunctor(first)
import Data.Foldable(foldl')
import Data.Function(on, (&))
import Data.Functor((<&>), ($>))
import Data.List(foldl1')
import Data.Text(Text)
import Data.Text qualified as T
import Data.Void(Void)
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Megaparsec.Char.Lexer qualified as L
import Language.Dynasty.Syntax
type Parser = Parsec Void Text
lineComm :: Parser ()
lineComm = L.skipLineComment "--"
blockComm :: Parser ()
blockComm = L.skipBlockCommentNested "{-" "-}"
shebang :: Parser ()
shebang = L.skipLineComment "#!" <* newline
sc :: Parser ()
sc = L.space space1 lineComm blockComm
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: Text -> Parser Text
symbol = L.symbol sc
btwn :: Text -> Text -> Parser a -> Parser a
btwn = between `on` symbol
reservedNames :: [Text]
reservedNames =
[ "unsafejs"
, "module", "import"
, "case", "of"
, "let", "and", "in"
, "NaN", "Infinity"
, "do", "then"
]
reservedOps :: [Text]
reservedOps = ["=", "\\", "->", "<-", "|", "@"]
ident :: Parser Char -> Parser Text
ident fstChar =
try (notReserved . T.pack =<< ((:) <$> fstChar <*> many sndChar) <?> "Identifier")
where
sndChar = alphaNumChar <|> char '\''
notReserved i
| i `elem` reservedNames = fail $ "Reserved name " <> show i
| otherwise = pure i
varOpChars :: String
varOpChars = "!#$%&*+./<=>?@\\^|-~;"
opChars :: String
opChars = ':' : varOpChars
operator' :: Parser Char -> Parser Text
operator' fstChar =
try (notReserved . T.pack =<< ((:) <$> fstChar <*> many opChar) <?> "Operator")
where
opChar = oneOf opChars
notReserved i
| i `elem` reservedOps = fail $ "Reserved operator " <> show i
| otherwise = pure i
operator :: Parser Char -> Parser Text
operator = lexeme . operator'
varName' :: Parser Text
varName' = ident lowerChar
varName :: Parser Text
varName = lexeme varName'
ctorName' :: Parser Text
ctorName' = ident upperChar
ctorName :: Parser Text
ctorName = lexeme ctorName'
data Fixity = L | R
inf :: Fixity -> Parser (a -> a -> a) -> Operator Parser a
inf L = InfixL
inf R = InfixR
opE :: Parser Char -> Parser (Expr -> Expr -> Expr)
opE c = operator c <&> \o a b -> (Var (Unqual o) `App` a) `App` b
opCtor :: Parser Text
opCtor = operator (char ':')
opInfixE :: Parser (Expr -> Expr -> Expr)
opInfixE = between (char '`') (symbol "`") varName' <&> \o a b -> (Var (Unqual o) `App` a) `App` b
opInfixCtor :: Parser Text
opInfixCtor = between (char '`') (symbol "`") ctorName
varId :: Parser Text
varId = varName <|> try (between (char '(') (symbol ")") $ operator' $ oneOf varOpChars)
ctorId :: Parser Text
ctorId = ctorName <|> try (between (char '(') (symbol ")") $ operator' $ char ':')
tupLit :: ([a] -> a) -> Parser a -> Parser a
tupLit mk term = btwn "(" ")" $ mkTup <$> (try term `sepBy` symbol ",")
where
mkTup [a] = a
mkTup l = mk l
recLit :: Parser a -> Parser [(Id, Maybe a)]
recLit term =
btwn "{" "}" (field `sepBy` symbol ",") <?> "Record literal"
where
field = (,) <$> varId <*> optional (symbol "=" *> term)
listLit :: Parser a -> Parser [a]
listLit term = btwn "[" "]" (term `sepBy` symbol ",") <?> "List literal"
signed :: Num a => Parser (a -> a)
signed = char '-' $> negate <|> pure id
number :: Parser Number
number =
choice
[ NaN <$ symbol "NaN"
, Inf <$ symbol "Infinity"
, NegInf <$ symbol "-Infinity"
, Num <$> (signed <*> lexeme L.scientific)
]
<?> "Integer literal"
strLit :: Parser Text
strLit = lexeme (char '\"' *> manyTill L.charLiteral (char '\"') <&> T.pack) <?> "String literal"
caseBranches :: Parser [(Pat, Expr)]
caseBranches =
optional (symbol "|")
*> sepBy1 ((,) <$> (pat <* symbol "->" ) <*> expr) (symbol "|")
lamCase :: Parser Expr
lamCase = symbol "case" *> (LamCase <$> caseBranches)
lamVars :: Parser Expr
lamVars = Lam <$> (some patSimple <* symbol "->") <*> expr
lam :: Parser Expr
lam = symbol "\\" *> (try lamCase <|> lamVars)
binding :: Parser (Id, Expr)
binding = (,) <$> varId <*> (args <*> (symbol "=" *> expr))
where
args = Lam <$> some patSimple <|> pure id
bindingGroup :: Parser BindingGroup
bindingGroup = try binding `sepBy` symbol "and"
let' :: Parser Expr
let' =
Let
<$> (symbol "let" *> bindingGroup)
<*> (symbol "in" *> expr)
case' :: Parser Expr
case' = Case <$> (symbol "case" *> expr <* symbol "of") <*> caseBranches
unsafeJS :: Parser Expr
unsafeJS =
UnsafeJS
<$> (symbol "unsafejs" *> (btwn "[" "]" (varId `sepBy` symbol ",") <|> pure []))
<*> strLit
do' :: Parser Expr
do' = Do (Unqual ">>=") <$> (symbol "do" *> some (try $ stmt <* symbol "then")) <*> expr
where
stmt = (,) <$> optional (try $ pat <* symbol "<-") <*> expr
qualVar :: Parser Expr
qualVar = (Var .) . Qual <$> try (T.intercalate "." <$> some (ctorName' <* char '.')) <*> varId
exprSimple :: Parser Expr
exprSimple =
choice
[ try qualVar
, (`CtorLit` []) <$> ctorId
, Var . Unqual <$> varId
, tupLit TupLit expr
, let', lam, case', unsafeJS, do'
, RecLit <$> recLit expr
, ListLit <$> listLit expr
, try $ NumLit <$> number
, StrLit <$> strLit
]
<?> "Expression"
wildcard :: Parser Pat
wildcard = symbol "_" $> Wildcard
asPat :: Parser Pat
asPat = As <$> (varId <* symbol "@") <*> patSimple
patSimple :: Parser Pat
patSimple =
choice
[ (`CtorPat` []) <$> ctorId
, try asPat
, VarPat <$> varId
, tupLit TupPat pat
, RecPat <$> recLit pat
, ListPat <$> listLit pat
, try $ NumPat <$> number
, StrPat <$> strLit
, wildcard
]
<?> "Pattern"
patCtorApp :: Parser Pat
patCtorApp = try (CtorPat <$> ctorId <*> some patSimple) <|> patSimple
patOps :: [[Operator Parser Pat]]
patOps =
[ [ inf R $ ctorPat <$> opCtor ]
, [ inf R $ ctorPat <$> opInfixCtor ]
]
where
ctorPat o a b = CtorPat o [a, b]
pat :: Parser Pat
pat = makeExprParser patCtorApp patOps
exprField :: Parser Expr
exprField = foldl' (&) <$> exprSimple <*> many (try $ char '.' *> field)
where
field = flip CtorField <$> lexeme L.decimal <|> flip RecField <$> varId
exprApp :: Parser Expr
exprApp =
try (CtorLit <$> ctorId <*> some exprField)
<|> foldl1' App <$> some exprField
exprOps :: [[Operator Parser Expr]]
exprOps =
[ [ inf R $ opE $ char '^' ]
, [ inf L $ opE $ oneOf @[] "*/%" ]
, [ inf L $ opE $ oneOf @[] "+-&" ]
, [ inf R $ opE $ char ';' ]
, [ inf R $ opE $ oneOf @[] "@." ]
, [ inf R $ opE $ oneOf @[] "<>" ]
, [ inf L $ opE $ oneOf @[] "=!|~" ]
, [ inf R $ opE $ oneOf @[] "$@\\?" ]
, [ inf R $ ctorLit <$> opCtor ]
, [ inf L opInfixE ]
, [ inf R $ ctorLit <$> opInfixCtor ]
]
where
ctorLit o a b = CtorLit o [a, b]
expr :: Parser Expr
expr = makeExprParser exprApp exprOps
modName :: Parser Id
modName = lexeme $ T.intercalate "." <$> ctorName' `sepBy1` char '.'
import' :: Parser Id
import' = symbol "import" *> modName
module' :: Parser Module
module' =
Module
<$> (symbol "module" *> modName)
<*> many import'
<*> bindingGroup
<*> pure []
withShebang :: Parser a -> Parser a
withShebang p = optional shebang *> optional sc *> p <* eof
parseModule :: FilePath -> Text -> Either Text Module
parseModule path = first (T.pack . errorBundlePretty) . runParser (withShebang module') path
parse :: [(FilePath, Text)] -> Either Text Program
parse ms = Program "" <$> traverse (uncurry parseModule) ms
| null | https://raw.githubusercontent.com/aionescu/dynasty/aac0e7ae563e4c8ae7aede69498193e694efcf96/src/Language/Dynasty/Parser.hs | haskell | module Language.Dynasty.Parser(parse, varOpChars) where
import Control.Monad.Combinators.Expr(Operator(..), makeExprParser)
import Data.Bifunctor(first)
import Data.Foldable(foldl')
import Data.Function(on, (&))
import Data.Functor((<&>), ($>))
import Data.List(foldl1')
import Data.Text(Text)
import Data.Text qualified as T
import Data.Void(Void)
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Megaparsec.Char.Lexer qualified as L
import Language.Dynasty.Syntax
type Parser = Parsec Void Text
lineComm :: Parser ()
lineComm = L.skipLineComment "--"
blockComm :: Parser ()
blockComm = L.skipBlockCommentNested "{-" "-}"
shebang :: Parser ()
shebang = L.skipLineComment "#!" <* newline
sc :: Parser ()
sc = L.space space1 lineComm blockComm
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: Text -> Parser Text
symbol = L.symbol sc
btwn :: Text -> Text -> Parser a -> Parser a
btwn = between `on` symbol
reservedNames :: [Text]
reservedNames =
[ "unsafejs"
, "module", "import"
, "case", "of"
, "let", "and", "in"
, "NaN", "Infinity"
, "do", "then"
]
reservedOps :: [Text]
reservedOps = ["=", "\\", "->", "<-", "|", "@"]
ident :: Parser Char -> Parser Text
ident fstChar =
try (notReserved . T.pack =<< ((:) <$> fstChar <*> many sndChar) <?> "Identifier")
where
sndChar = alphaNumChar <|> char '\''
notReserved i
| i `elem` reservedNames = fail $ "Reserved name " <> show i
| otherwise = pure i
varOpChars :: String
varOpChars = "!#$%&*+./<=>?@\\^|-~;"
opChars :: String
opChars = ':' : varOpChars
operator' :: Parser Char -> Parser Text
operator' fstChar =
try (notReserved . T.pack =<< ((:) <$> fstChar <*> many opChar) <?> "Operator")
where
opChar = oneOf opChars
notReserved i
| i `elem` reservedOps = fail $ "Reserved operator " <> show i
| otherwise = pure i
operator :: Parser Char -> Parser Text
operator = lexeme . operator'
varName' :: Parser Text
varName' = ident lowerChar
varName :: Parser Text
varName = lexeme varName'
ctorName' :: Parser Text
ctorName' = ident upperChar
ctorName :: Parser Text
ctorName = lexeme ctorName'
data Fixity = L | R
inf :: Fixity -> Parser (a -> a -> a) -> Operator Parser a
inf L = InfixL
inf R = InfixR
opE :: Parser Char -> Parser (Expr -> Expr -> Expr)
opE c = operator c <&> \o a b -> (Var (Unqual o) `App` a) `App` b
opCtor :: Parser Text
opCtor = operator (char ':')
opInfixE :: Parser (Expr -> Expr -> Expr)
opInfixE = between (char '`') (symbol "`") varName' <&> \o a b -> (Var (Unqual o) `App` a) `App` b
opInfixCtor :: Parser Text
opInfixCtor = between (char '`') (symbol "`") ctorName
varId :: Parser Text
varId = varName <|> try (between (char '(') (symbol ")") $ operator' $ oneOf varOpChars)
ctorId :: Parser Text
ctorId = ctorName <|> try (between (char '(') (symbol ")") $ operator' $ char ':')
tupLit :: ([a] -> a) -> Parser a -> Parser a
tupLit mk term = btwn "(" ")" $ mkTup <$> (try term `sepBy` symbol ",")
where
mkTup [a] = a
mkTup l = mk l
recLit :: Parser a -> Parser [(Id, Maybe a)]
recLit term =
btwn "{" "}" (field `sepBy` symbol ",") <?> "Record literal"
where
field = (,) <$> varId <*> optional (symbol "=" *> term)
listLit :: Parser a -> Parser [a]
listLit term = btwn "[" "]" (term `sepBy` symbol ",") <?> "List literal"
signed :: Num a => Parser (a -> a)
signed = char '-' $> negate <|> pure id
number :: Parser Number
number =
choice
[ NaN <$ symbol "NaN"
, Inf <$ symbol "Infinity"
, NegInf <$ symbol "-Infinity"
, Num <$> (signed <*> lexeme L.scientific)
]
<?> "Integer literal"
strLit :: Parser Text
strLit = lexeme (char '\"' *> manyTill L.charLiteral (char '\"') <&> T.pack) <?> "String literal"
caseBranches :: Parser [(Pat, Expr)]
caseBranches =
optional (symbol "|")
*> sepBy1 ((,) <$> (pat <* symbol "->" ) <*> expr) (symbol "|")
lamCase :: Parser Expr
lamCase = symbol "case" *> (LamCase <$> caseBranches)
lamVars :: Parser Expr
lamVars = Lam <$> (some patSimple <* symbol "->") <*> expr
lam :: Parser Expr
lam = symbol "\\" *> (try lamCase <|> lamVars)
binding :: Parser (Id, Expr)
binding = (,) <$> varId <*> (args <*> (symbol "=" *> expr))
where
args = Lam <$> some patSimple <|> pure id
bindingGroup :: Parser BindingGroup
bindingGroup = try binding `sepBy` symbol "and"
let' :: Parser Expr
let' =
Let
<$> (symbol "let" *> bindingGroup)
<*> (symbol "in" *> expr)
case' :: Parser Expr
case' = Case <$> (symbol "case" *> expr <* symbol "of") <*> caseBranches
unsafeJS :: Parser Expr
unsafeJS =
UnsafeJS
<$> (symbol "unsafejs" *> (btwn "[" "]" (varId `sepBy` symbol ",") <|> pure []))
<*> strLit
do' :: Parser Expr
do' = Do (Unqual ">>=") <$> (symbol "do" *> some (try $ stmt <* symbol "then")) <*> expr
where
stmt = (,) <$> optional (try $ pat <* symbol "<-") <*> expr
qualVar :: Parser Expr
qualVar = (Var .) . Qual <$> try (T.intercalate "." <$> some (ctorName' <* char '.')) <*> varId
exprSimple :: Parser Expr
exprSimple =
choice
[ try qualVar
, (`CtorLit` []) <$> ctorId
, Var . Unqual <$> varId
, tupLit TupLit expr
, let', lam, case', unsafeJS, do'
, RecLit <$> recLit expr
, ListLit <$> listLit expr
, try $ NumLit <$> number
, StrLit <$> strLit
]
<?> "Expression"
wildcard :: Parser Pat
wildcard = symbol "_" $> Wildcard
asPat :: Parser Pat
asPat = As <$> (varId <* symbol "@") <*> patSimple
patSimple :: Parser Pat
patSimple =
choice
[ (`CtorPat` []) <$> ctorId
, try asPat
, VarPat <$> varId
, tupLit TupPat pat
, RecPat <$> recLit pat
, ListPat <$> listLit pat
, try $ NumPat <$> number
, StrPat <$> strLit
, wildcard
]
<?> "Pattern"
patCtorApp :: Parser Pat
patCtorApp = try (CtorPat <$> ctorId <*> some patSimple) <|> patSimple
patOps :: [[Operator Parser Pat]]
patOps =
[ [ inf R $ ctorPat <$> opCtor ]
, [ inf R $ ctorPat <$> opInfixCtor ]
]
where
ctorPat o a b = CtorPat o [a, b]
pat :: Parser Pat
pat = makeExprParser patCtorApp patOps
exprField :: Parser Expr
exprField = foldl' (&) <$> exprSimple <*> many (try $ char '.' *> field)
where
field = flip CtorField <$> lexeme L.decimal <|> flip RecField <$> varId
exprApp :: Parser Expr
exprApp =
try (CtorLit <$> ctorId <*> some exprField)
<|> foldl1' App <$> some exprField
exprOps :: [[Operator Parser Expr]]
exprOps =
[ [ inf R $ opE $ char '^' ]
, [ inf L $ opE $ oneOf @[] "*/%" ]
, [ inf L $ opE $ oneOf @[] "+-&" ]
, [ inf R $ opE $ char ';' ]
, [ inf R $ opE $ oneOf @[] "@." ]
, [ inf R $ opE $ oneOf @[] "<>" ]
, [ inf L $ opE $ oneOf @[] "=!|~" ]
, [ inf R $ opE $ oneOf @[] "$@\\?" ]
, [ inf R $ ctorLit <$> opCtor ]
, [ inf L opInfixE ]
, [ inf R $ ctorLit <$> opInfixCtor ]
]
where
ctorLit o a b = CtorLit o [a, b]
expr :: Parser Expr
expr = makeExprParser exprApp exprOps
modName :: Parser Id
modName = lexeme $ T.intercalate "." <$> ctorName' `sepBy1` char '.'
import' :: Parser Id
import' = symbol "import" *> modName
module' :: Parser Module
module' =
Module
<$> (symbol "module" *> modName)
<*> many import'
<*> bindingGroup
<*> pure []
withShebang :: Parser a -> Parser a
withShebang p = optional shebang *> optional sc *> p <* eof
parseModule :: FilePath -> Text -> Either Text Module
parseModule path = first (T.pack . errorBundlePretty) . runParser (withShebang module') path
parse :: [(FilePath, Text)] -> Either Text Program
parse ms = Program "" <$> traverse (uncurry parseModule) ms
|
|
4a63e32e5d27004f921aa771f45ae3b173e4012d11c14d4ac1a460316e15cbd0 | kappamodeler/kappa | fragments.ml | (** Implementation of fragments for ODE *)
open Tools
open Config_complx
open Data_structures
open Annotated_contact_map
open Views
open Pb_sig
open Rooted_path
open Fragments_sig
open Error_handler
open Ode_print
(** Set this boolean to true to dump more debugging information *)
let trace = false
let debug = false
let cannonical_debug = false
let merge_debug = false
let map_debug = false
let complete_debug = false
let split_debug = false
let apply_blist_debug = false
let release_debug = false
let get_denum_debug = false
let error i s m =
unsafe_frozen m (Some "Complx") (Some "fragments.ml") s (Some ("line "^(string_of_int i))) (fun () -> raise Exit)
module New_Fragment =
(struct
* new definition of fragments , a fragments is an ordered list of views and a list of back bonds : in the list of views , the head is the view that has the smallest i d , then the list give the depth - first exploration of the graph ; back_bonds denote the edges that are not visited during the depth - first exploration integer denotes positions in the list starting from 0 .
In the case when there is two views with minimal indices , we chose the one that give the smallest final result , with respect to the polymorphic function compare
In the case when there is two views with minimal indices, we chose the one that give the smallest final result, with respect to the polymorphic function compare *)
type fragment =
{
views:int list ;
back_bonds: ((int * string) * (int * string)) list
}
(** definition of the empty fragment for the new type definition *)
let empty_fragment =
{views = [];
back_bonds = []}
(** Pretty-print function for new fragment type *)
let print_fragment a =
let _ = print_string "Fragments\n" in
let _ = print_string "Views: " in
let _ =
List.fold_left
(fun i j ->
let _ = if i>0 then print_string "," in
let _ = print_int j in
(i+1))
0 a.views in
let _ = print_newline () in
let _ = print_string "Back_bonds:" in
let _ =
List.fold_left
(fun bool ((i,s),(i',s')) ->
let _ = if bool then print_string "," in
let _ = print_int i in
let _ = print_string "." in
let _ = print_string s in
let _ = print_string "--" in
let _ = print_string s' in
let _ = print_string "." in
let _ = print_int i' in
true)
false
a.back_bonds in
let _ = print_newline () in
()
(** optional pretty print function for new fragment, it only pretty print when the compilation has been made with trace=true *)
let trace_print_fragment =
if trace then print_fragment
else (fun _ -> ())
type view_id = int
type node_id = string
module NodeMap = Map2.Make (struct type t = node_id let compare = compare end)
(** new type definition for subspecies:
rooted paths are associated with views,
bonds are encoded both as a list and a map,
each bond has to be encoded in both direction *)
type subspecies =
{
bonds_map: (rooted_path*site_type) SitetypeMap.t RPathMap.t;
subspecies_views:view_id RPathMap.t;
}
let is_empty_species s = RPathMap.is_empty s.subspecies_views
let iter_views_in_species f sp =
RPathMap.iter (fun _ -> f) sp.subspecies_views
let iter_views f fragment =
List.iter f fragment.views
let fold_bonds f species =
RPathMap.fold
(fun rp ->
SitetypeMap.fold
(fun site (rp',site') -> f ((rp,site),(rp',site')))
)
species.bonds_map
let iter_bonds f species =
RPathMap.iter
(fun rp ->
SitetypeMap.iter
(fun site (rp',site') -> f ((rp,site),(rp',site')))
)
species.bonds_map
(** pretty print*)
let print_species sp =
let _ = print_string "SPECIES: \n" in
let _ = print_string " VIEWS: \n" in
let _ =
RPathMap.iter
(fun rp i ->
print_string " ";
print_rpath rp;
print_string ":";
print_int i;
print_newline ())
sp.subspecies_views in
let _ = print_string " BONDS: \n" in
let _ =
iter_bonds
(fun ((rp,s),(rp',s')) ->
print_string " ";
print_rpath rp;
print_string ".";
print_string s;
print_string "--";
print_string s';
print_string ".";
print_rpath rp';
print_newline ())
sp
in
let _ = print_newline () in
()
(** empty species *)
let empty_species =
{
(* bonds=[];*)
bonds_map=RPathMap.empty;
subspecies_views=RPathMap.empty
}
(** to add a bond within a subspecies *)
let add_bond_to_subspecies subspecies (rp,s) (rp',s') =
let bonds_map =
let fadd a b c map =
let oldmap =
try
RPathMap.find a map
with
Not_found ->
SitetypeMap.empty
in
RPathMap.add a (SitetypeMap.add b c oldmap) map
in
fadd rp s (rp',s')
(fadd rp' s' (rp,s) subspecies.bonds_map) in
{subspecies
with bonds_map = bonds_map}
let release_bond_from_subspecies subspecies (rp,s) (rp',s') =
let _ =
if release_debug
then
begin
print_string "RELEASE BOND: \n";
print_rpath rp;
print_string "\n";
print_string s;
print_string "\n";
print_rpath rp';
print_string "\n";
print_string s';
print_string "\n";
print_species subspecies
end in
let bonds_map =
let update a b map =
let oldmap =
try
RPathMap.find a map
with
Not_found ->
SitetypeMap.empty
in
let site_map = SitetypeMap.remove b oldmap in
if SitetypeMap.is_empty site_map
then
RPathMap.remove a map
else
RPathMap.add a (site_map) map
in
update rp s
(update rp' s' subspecies.bonds_map) in
let rep = {subspecies with bonds_map = bonds_map} in
let _ =
if release_debug
then
begin
print_string "RELEASE BOND RESULT: \n";
print_species rep
end in
rep
let fetch_partner subspecies (rp,s) =
try
Some
(SitetypeMap.find
s
(RPathMap.find rp subspecies.bonds_map
)
)
with
Not_found -> None
(** to add a view to a subspecies *)
let add_view_to_subspecies subspecies rp view =
let subspecies =
{subspecies
with subspecies_views = RPathMap.add rp view subspecies.subspecies_views} in
match rp.path
with [] -> subspecies
| t::q ->
let ((_,s),(_,s')) = t in
add_bond_to_subspecies subspecies (rp,s) ({rp with path = q},s')
(** compute the cannonical fragment associated with a subspecies *)
let canonical_fragment_of_subspecies graph =
let _ =
if cannonical_debug
then
begin
print_string "START CANONICAL_FRAGMENT\n";
print_species graph;
end
in
let result =
RPathMap.fold
(fun path i key ->
match key
with None -> Some ([path],i)
| Some (path',i') ->
begin
match compare i i' with
-1 -> Some ([path],i)
| 0 -> Some (path::path',i')
| 1 -> Some (path',i')
| _ -> error 46 None None
end)
graph.subspecies_views
None
in
let path,key =
match result with
None -> error 168 None None
| Some (a,b) -> a,b in
let candidate =
List.map
(fun path ->
let rec vide working_list n black_list sol =
match working_list with
[] -> sol
| (bond,t)::q ->
try
let _ = RPathMap.find t black_list in
vide q n black_list sol
with Not_found ->
let black_list = RPathMap.add t n black_list in
let edges =
try
RPathMap.find t graph.bonds_map
with
Not_found -> SitetypeMap.empty
in
let edges =
match bond
with None -> edges
| Some (_,_,s') -> SitetypeMap.remove s' edges
in
let working_list',sol' =
SitetypeMap.fold
(fun s (a',s') (wl,sol) ->
try
let n' = RPathMap.find a' black_list in
(wl,{sol with back_bonds = ((n,s),(n',s'))::sol.back_bonds})
with
Not_found ->
(Some (t,s,s'),a')::wl,sol)
edges (q,sol) in
let sol' =
{sol' with
views =
(try
RPathMap.find t graph.subspecies_views::sol'.views
with
Not_found ->
begin
print_string "ERROR 311\n";
RPathMap.iter
(fun rp v ->
(try
(let _ = RPathMap.find rp graph.subspecies_views in ())
with
Not_found -> print_string "!!!ERROR");
print_rpath rp;
print_string ":";
print_int v;
print_string ";";
print_newline ())
graph.subspecies_views;
print_species graph;
print_newline ();
print_rpath t;
print_string ";";
print_newline ();
print_rpath path;
print_string ";";
print_newline ();
error 311 None None
end)} in
vide working_list' (n+1) black_list sol'
in
let sol = vide [None,path] 0 RPathMap.empty empty_fragment in
let sol = {back_bonds = List.rev sol.back_bonds;
views = List.rev sol.views} in
sol)
path in
let rec aux a b n =
match a with
(t:fragment)::q ->
trace_print_fragment t;
if compare t b <0
then aux q t 1
else if compare t b = 0
then aux q b (n+1)
else aux q b 1
| [] -> (b,n) in
let sol =
match candidate with t::q -> (trace_print_fragment t;aux q t 1)
| [] -> error 371 None None
in
let _ =
if cannonical_debug
then
print_string "END_CANONICAL\n"
in
sol
(*
(* TEST *)
let _ =
if debug then
let inv (a,b) = (b,a) in
let g b = {path = b;root= ""} in
let a =
embedding=
StringMap.add " 1 " [ ]
( StringMap.add " 2 " [ ( " 2","a"),("1","a " ) ]
( StringMap.add " 3 " [ ( " 3","a"),("1","b " ) ]
( StringMap.add " 4 " [ ( " 4","b"),("2","b");("2","a"),("1","a " ) ]
StringMap.empty ) ) ) ;
reverse_embedding =
PathMap.add [ ] " 1 "
( PathMap.add [ ( " 2","a"),("1","a " ) ] " 2 "
( PathMap.add [ ( " 3","a"),("1","b " ) ] " 3 "
( PathMap.add [ ( " 4","b"),("2","b");("2","a"),("1","a " ) ] " 4 "
PathMap.empty ) ) ) ;
StringMap.add "1" []
(StringMap.add "2" [("2","a"),("1","a")]
(StringMap.add "3" [("3","a"),("1","b")]
(StringMap.add "4" [("4","b"),("2","b");("2","a"),("1","a")]
StringMap.empty))) ;
reverse_embedding =
PathMap.add [] "1"
(PathMap.add [("2","a"),("1","a")] "2"
(PathMap.add [("3","a"),("1","b")] "3"
(PathMap.add [("4","b"),("2","b");("2","a"),("1","a")] "4"
PathMap.empty))) ;*)
(* bonds =
[(g [],"a"),(g [("2","a"),("1","a")],"a") ;
(g [],"b"),(g [("3","a"),("1","b")],"a") ;
(g [("2","a"),("1","a")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"b");
(g [("3","a"),("1","b")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"a");
inv ((g [],"a"),(g [("2","a"),("1","a")],"a")) ;
inv ((g [],"b"),(g [("3","a"),("1","b")],"a")) ;
inv ((g [("2","a"),("1","a")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"b"));
inv ((g [("3","a"),("1","b")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"a"))
] ;*)
bonds_map =
RPathMap.add (g [])
(SitetypeMap.add
"a" (g [("2","a"),("1","a")],"a")
(SitetypeMap.add
"b" (g [("3","a"),("1","b")],"a")
SitetypeMap.empty))
(RPathMap.add (g [("2","a"),("1","a")])
(SitetypeMap.add
"a" (g [],"a")
(SitetypeMap.add
"b" (g [("1","a"),("2","b");("2","a"),("1","a")],"b")
SitetypeMap.empty))
(RPathMap.add (g [("3","a"),("1","b")])
(SitetypeMap.add
"a" (g [],"b")
(SitetypeMap.add
"b" (g [("1","a"),("2","b");("2","a"),("1","a")],"a")
SitetypeMap.empty))
(RPathMap.add
(g [("1","a"),("2","b");("2","a"),("1","a")])
(SitetypeMap.add
"b" (g [("2","a"),("1","a")],"b")
(SitetypeMap.add
"a" (g [("3","a"),("1","b")],"b")
SitetypeMap.empty))
RPathMap.empty)))
;
subspecies_views =
RPathMap.add (g []) 1
(RPathMap.add (g [("2","a"),("1","a")]) 2
(RPathMap.add (g [("3","a"),("1","b")]) 3
(RPathMap.add (g [("1","a"),("2","b");("2","a"),("1","a")]) 1
RPathMap.empty))) } in
let _ = print_subspecies a in
let b = canonical_fragment_of_subspecies a in
let _ = print_fragment b in ()
*)
(* END OF TEST*)
(** emptyness test for fragments *)
let is_empty_fragment x = x.views=[]
(** the following map shift the roots of a subspecies:
a function defined the new address (as a rooted path) of some former root,
the address of child of this root is also updates *)
let shift_subspecies subspecies shift =
let shift rp =
try
let rp' = StringMap.find rp.root shift
in
{rp' with path=rp.path@rp'.path}
with
Not_found -> rp in
{
bonds_map =
RPathMap.fold
(fun rp site_map bonds_map ->
let srp = shift rp in
RPathMap.add
srp
(SitetypeMap.map
(fun (rp',s') -> shift rp',s')
site_map)
bonds_map)
subspecies.bonds_map
RPathMap.empty;
subspecies_views =
RPathMap.fold
(fun a b map ->
let a' = shift a in
if a = a' then map
else
let image = RPathMap.find a map in
let map = RPathMap.remove a map in
let map = RPathMap.add a' image map in
map)
subspecies.subspecies_views
subspecies.subspecies_views }
let merge sp1 sp2 =
let _ =
if merge_debug
then
begin
print_string "MERGE \n";
print_species sp1 ;
print_species sp2
end
in
let sp =
{bonds_map =
RPathMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun _ b c ->
SitetypeMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun a b c -> if b=c then b else error 513 None None)
b
c)
sp1.bonds_map
sp2.bonds_map ;
subspecies_views =
RPathMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun _ b c -> if b=c then b else (error 522 None None ))
sp1.subspecies_views sp2.subspecies_views } in
let _ =
if merge_debug
then
begin
print_species sp
end
in sp
let get_denum_with_recursive_memoization
((agent_to_int_to_nlist:Views.views_id list StringListMap.t StringMap.t),
(view_of_tp_i:(Views.views_id -> 'a Views.views)),
(ode_handler:('b,'a,'c,'d,'e,'f,'g) ode_handler)) level bool =
(** If the boolean is true then this function associates a maximal list of compatible fragments to a bond *)
(** If the boolean is false then this function associated a maximal list of fragments to a bond *)
(** This function is hash consed *)
let inc_black x black =
let old =
try StringMap.find x black
with
Not_found -> 0
in
StringMap.add x (old+1) black
in
let black_listed x black =
let old =
try StringMap.find x black
with
Not_found -> 0
in
old > 1
in
let hash = Hashtbl.create 200001 in
let rec fetch black (x:Pb_sig.name_specie*string*string*string) =
try Hashtbl.find hash x
with
Not_found ->
let rep = compute black x in
let _ =
if level > 0
then Hashtbl.add hash x rep
in
rep
and
compute black (a,s,a',s') =
if black_listed a black
then error 555 None (Some "Infinite set of fragments")
else
let fetch = if level = 2 then fetch else compute in
let black = inc_black a black in
let ag1,s1,ag2,s2 = (a,s,a',s') in
let ag_ref = ag1 in
let s_ref = s1 in
let _ =
if get_denum_debug
then
begin
print_string "COMPUTE\n";
print_string ag1;
print_string s1;
print_string ag2;
print_string s2;
print_string " ";
print_string (if bool then "TRUE\n" else "FALSE\n");
end in
let tp_list = (*here is the list of all template piece for agent a containing site s*)
try
StringListMap.find
[s]
(StringMap.find a agent_to_int_to_nlist)
with Not_found -> error 577 None None
in
let _ =
if get_denum_debug
then
begin
print_string "ALL POTENTIAL PARTNER\n";
List.iter
(fun i -> print_int i;print_string " ")
tp_list;
print_newline ();
end
in
let tp_list =
if bool (*dealing with compatibility *)
then
let classe = (*select a class of sites for the agent *)
try
interface_of_view (view_of_tp_i (List.hd tp_list))
with
_ -> error 597 None None
in
List.filter (*filter out the one that are ot compatible*)
(* TO DO improve by computing directly the list when compatibility relation is already known *)
(fun tp ->
let view = view_of_tp_i tp in
(interface_of_view view = classe)
)
tp_list
else tp_list in
List.fold_left
(fun liste tp ->
let view = view_of_tp_i tp in
if
TODO hash cons the function between bonds and views compatible with this bond
match l with [] -> false
| t::q ->
begin
match ode_handler.b_of_var (fst t),snd(t) with AL((x,y,z),(t,u)),bool
when x=ag1 && y=ag1 && z=s1 && t=ag2 && u = s2 -> bool
| _ -> aux q
end
in aux (valuation_of_view view)
then (* the view has to be kept *)
let _ =
if get_denum_debug then
begin
print_int tp;
print_newline ()
end
in
let pending_bonds =
String4Set.fold
(fun ((ag1,s1),(ag2,s2)) pending_bonds ->
if ag1 = ag_ref && s1=s_ref
then pending_bonds
else (
let _ =
if get_denum_debug
then
begin
print_string ag2;
print_string s2;
print_string ag1;
print_string s1;
print_newline ()
end in
(ag2,s2,ag1,s1))::pending_bonds)
(pending_edges view) []
in
let rpath =
{empty_rpath
with path = [(a,s),(a',s')]} in
let species = add_view_to_subspecies empty_species rpath tp in
let _ =
if get_denum_debug
then
print_species species
in
let species_list =
List.fold_left
(fun prefix bond ->
let (a,s,a',s') = bond in
let rpath'=
{rpath with
path = ((a,s),(a',s'))::rpath.path} in
let extension = fetch black bond in
List.fold_left
(fun liste extension ->
List.fold_left
(fun liste subspecies ->
let shifted_extension =
shift_subspecies
extension
(StringMap.add "" rpath StringMap.empty) in
let ext_subspecies = merge shifted_extension subspecies in
let rep =
add_bond_to_subspecies
ext_subspecies
(rpath',s)
(rpath,s') in
let _ =
if get_denum_debug
then
begin
print_string "RECOMP\n";
print_string "BASE\n";
print_species subspecies;
print_string "\nEXT\n";
print_species extension;
print_string "\nSHIFTED EXT\n";
print_species shifted_extension;
print_string "\nPATHs\n";
print_rpath rpath;
print_string "\n";
print_string s;
print_string "\n";
print_rpath rpath';
print_string "\n";
print_string s';
print_string "\n";
print_string "\nRESULT\n";
print_species rep ;
print_string "\n"
end
in
rep::liste)
liste prefix)
[] extension)
[species] pending_bonds
in
let _ =
if get_denum_debug
then
begin
print_string "SPECIE LIST \n" ;
List.iter print_species species_list
end
in
List.fold_left
(fun list a -> a::list)
liste
species_list
else liste)
[]
tp_list
in fetch StringMap.empty
let get_denum
= (fun x ->
get_denum_with_recursive_memoization x 0 ,
get_denum_with_recursive_memoization x 1 ,
get_denum_with_recursive_memoization x 2)
let complete_subspecies (pending_edges,view_of_tp_i,keep_this_link,get_denum) subspecies =
(** This function takes a subspecies and build the list of the fragments that extend it *)
let _ =
if complete_debug
then
begin
print_string "COMPLETE: ";
print_newline ();
print_species subspecies
end in
let target (*set of the typed site to be connected to the frontier of the subspecies by a solid line *)
, map (*map each target site to the rooted path of the agent it is connected to and the type of the connected site and the potential extentions of this bond *)
=
RPathMap.fold
(fun rp tp (target,map) ->
let pending_edges = pending_edges (view_of_tp_i tp) in
String4Set.fold
(fun (y1,y2) (target,map) ->
if
begin (*not an internal edges *)
try
let _ =
SitetypeMap.find (snd y1)
(RPathMap.find rp subspecies.bonds_map) in
true
with
Not_found -> false
end
&&
begin (*a solid edge *)
keep_this_link y1 y2
end
then
(target,map)
else
(
String2Set.add y1 target,
(*String2Map.add y1 (rp,y2,get_denum (fst y2,snd y2,fst y1,snd y1)) map*)
(y1,rp,y2,get_denum (fst y2,snd y2,fst y1,snd y1))::map))
pending_edges
(target,map))
subspecies.subspecies_views
(String2Set.empty,(*String2Map.empty*)[]) in
let _ =
if map_debug
then
begin
print_string "MAP:\n";
String2Map .
(fun (y1,rp,y2,ext_list) ->
print_string (fst y2);
print_string ".";
print_string (snd y2);
print_rpath rp;
print_string (fst y1);
print_string ".";
print_string (snd y1);
print_newline ();
List.iter print_species ext_list)
map
end
in
let sol =
(*String2Map.fold*) List.fold_left
sol_list
let rp' = {rp with path = (*(y2,y1)::*)rp.path} in
List.fold_left
(fun pre_sol_list extension ->
List.fold_left
(fun sol_list pre_sol ->
let extended_sol =
add_bond_to_subspecies
(merge
pre_sol
(shift_subspecies
extension
(StringMap.add "" rp' StringMap.empty)))
( rp , snd y1 ) ( rp',snd y2 )
extended_sol::sol_list
)
pre_sol_list sol_list
)
[] extension_list
)
[subspecies] map in
let _ =
if complete_debug
then
begin
print_string "COMPLETE RESULT\n";
List.iter print_species sol
end
in
sol
(** this primitive split a species into a list of maximal connected subspecies *)
let split_subspecies data_structure ode_handler contact_map subspecies =
let _ =
if split_debug
then
begin
print_string "SPLIT \n";
print_species subspecies
end in
let rec aux to_visit current_rp_list available_rpaths list =
match to_visit with
[] ->
begin
let list' = current_rp_list::list in
if
RPathSet.is_empty available_rpaths
then
list'
else
let rpath = RPathSet.min_elt available_rpaths in
aux
[rpath]
[]
available_rpaths
list'
end
| rpath::q when not (RPathSet.mem rpath available_rpaths) ->
aux q current_rp_list available_rpaths list
| rpath::q ->
let available_rpaths' = RPathSet.remove rpath available_rpaths in
let q' =
let sitemap =
try
RPathMap.find rpath subspecies.bonds_map
with
Not_found ->
SitetypeMap.empty
in
SitetypeMap.fold
(fun _ (a,_) q' ->
if RPathSet.mem a available_rpaths
then
a::q'
else
q')
sitemap
q in
let current_rp_list' = rpath::current_rp_list in
aux
q'
current_rp_list'
available_rpaths'
list
in
let rp_set =
RPathMap.fold
(fun a _ -> RPathSet.add a)
subspecies.subspecies_views
RPathSet.empty in
let _ =
if split_debug
then
begin
print_string "RP_SET \n";
RPathSet.iter
(fun rp -> print_rpath rp;print_newline ())
rp_set
end
in
let rp_list_list =
if RPathSet.is_empty rp_set
then
[]
else
let min = RPathSet.min_elt rp_set in
aux [min] [] rp_set []
in
let hash,_ = (* hash maps each rp to a class identifier *)
List.fold_left
(fun (hash,id) rp_list ->
List.fold_left
(fun hash rp ->
RPathMap.add rp id hash)
hash rp_list,id+1)
(RPathMap.empty,0)
rp_list_list in
let views_map =
RPathMap.fold
(fun rp v map ->
let i =
try
RPathMap.find rp hash
with
Not_found ->
begin
print_rpath rp;
error 829 None None
end
in
let old =
try
IntMap.find i map
with
Not_found ->
RPathMap.empty
in
IntMap.add i (RPathMap.add rp v old) map)
subspecies.subspecies_views IntMap.empty in
let species_map_without_bonds =
IntMap.map (fun list -> {empty_species with subspecies_views = list}) views_map in
let species_map_with_bonds =
fold_bonds
(fun ((a,b),(c,d)) bonds_map ->
let i =
try
RPathMap.find a hash
with
Not_found ->
error 952 None None
in
let old =
try
IntMap.find i bonds_map
with
Not_found -> error 959 None None
in
IntMap.add i (add_bond_to_subspecies old (a,b) (c,d)) bonds_map)
subspecies
species_map_without_bonds
in
let sol =
IntMap.fold
(fun _ a l -> a::l)
species_map_with_bonds
[]
in
let _ =
if split_debug
then
begin
print_string "SPLIT RESULT \n";
List.iter
print_species
sol
end
in sol
let is_agent_in_species x s =
try
(let _ = RPathMap.find (build_empty_path x) s.subspecies_views in true)
with
Not_found -> false
type hash = string list RPathMap.t
let dump_hash x =
let _ =
RPathMap.iter
(fun rp l ->
print_rpath rp ;
print_string " : ";
List.iter print_string l;
print_newline ())
x in
print_newline ()
let empty_hash = RPathMap.empty
let check_compatibility data_structure hash subspecies =
let l =
RPathMap.fold
(fun a b sol -> (a,b)::sol)
subspecies.subspecies_views []
in
let rec aux hash' l =
match l with [] -> hash',true
| (rpath,tp_i)::q ->
let view = view_of_tp_i tp_i data_structure.interface_map in
let int =
StringSet.fold
(fun site b -> site::b)
(interface_of_view view).kept_sites
[]
in
try
if
RPathMap.find rpath hash = int
then
aux hash' q
else
hash,false
with
Not_found ->
aux
(RPathMap.add rpath int hash')
q
in
aux hash l
let apply_blist_with_species ode_handler data_structure keep_link rule_id species blist free_sites =
let _ =
if apply_blist_debug
then
begin
print_string "APPLY BLIST \n";
print_string " BLIST : \n";
List.iter
(fun (b,bool) ->
print_string " ";
print_b b;
print_string (if bool then "T" else "F");
print_newline ())
blist;
print_string " Species : \n";
print_species species
end in
let update = RPathMap.empty in
let get a modified =
try
Some (RPathMap.find a modified)
with
Not_found ->
try
let tp_i = RPathMap.find a species.subspecies_views in
let view = view_of_tp_i tp_i data_structure.interface_map in
Some (view.agent,view.valuation_map)
with
Not_found -> None
in
deal with blist
let update,subspecies =
List.fold_left
(fun (modified,subspecies) (b,bool) ->
let f b rp modified =
let b' = downgrade_b b in
let ((agent_type:string),
(v:'a BMap.t)) =
match get rp modified with
None -> error 1076 (Some "update blist") None
|Some rep -> rep
in
let v' = BMap.add b' bool v in
RPathMap.add
rp
(agent_type,v')
modified in
match
b
with
M((agent_id,_,_),_) when agent_id<> "" ->
f b (build_empty_path agent_id) modified,
subspecies
| B(agent_id,agent_type,site) | AL((agent_id,agent_type,site),_) when agent_id <> "" ->
let rp = build_empty_path agent_id in
if not bool
then
try
let (rp',site') =
SitetypeMap.find
site
(RPathMap.find
(build_empty_path agent_id)
species.bonds_map)
in
let (agent_type',v') =
match get rp' modified
with None -> error 1105 None None
|Some a -> a
in
let modified = f (B(agent_type,agent_type,site)) rp modified in
let modified = f (AL((agent_type,agent_type,site),(agent_type',site'))) rp modified in
let modified = f (B(agent_type',agent_type',site')) rp' modified in
let modified = f (AL((agent_type',agent_type',site'),(agent_type,site))) rp' modified in
modified,
release_bond_from_subspecies
subspecies
(rp,site)
(rp',site')
with
Not_found ->
f b rp modified,subspecies
else
f b rp modified,subspecies
| L((agent_id,agent_type,site),(agent_id',agent_type',site')) ->
modified,
(if bool
then add_bond_to_subspecies
else
release_bond_from_subspecies)
subspecies
((build_empty_path agent_id),site)
((build_empty_path agent_id'),site')
| _ -> modified,subspecies)
(update,species)
blist
in
(* deal with side_effects due to agent removal *)
let update,subspecies =
List.fold_left
(fun (update,subspecies) ((rp,a,s),(rp',s')) ->
try
let rep = get rp' update in
match rep
with Some (agent_type,v) ->
let v' = BMap.add (B(agent_type,agent_type,s')) false v in
let v' = BMap.add (AL((agent_type,agent_type,s'),(a,s))) false v' in
RPathMap.add
rp'
(agent_type,v')
update,
subspecies
| None -> update,subspecies
with
Not_found -> update,subspecies)
(update,subspecies) free_sites
in
let stringblist (x,bmap) =
let hashkey =
(x,List.sort compare (BMap.fold (fun b bool l -> (b,bool)::l) bmap [])) in
try
StringBListMap.find hashkey data_structure.blist_to_template
with
Not_found ->
let _ = print_string x in
let _ = print_newline () in
let _ =
BMap.iter
(fun b bool ->
print_b b;
if bool
then
print_string "T\n"
else
print_string "F\n")
bmap in
error 1343 None (Some "Try to hash unknown view")
in
let species =
{subspecies
with subspecies_views =
RPathMap.fold
(fun rp x map ->
RPathMap.add
rp
(stringblist x)
map)
update
subspecies.subspecies_views
}
in
let _ =
if apply_blist_debug
then
begin
print_string "APPLY BLIST RESULT \n";
print_string " Species : \n";
print_species species
end
in species
let plug_views_in_subspecies agent_id view_id sp =
{sp
with
subspecies_views =
RPathMap.add (build_empty_path agent_id) view_id sp.subspecies_views}
let rec scan_list f l =
match l
with
[] -> None
| t::q ->
begin
match f t
with
None -> scan_list f q
| x -> x
end
let scan_views f fragment =
scan_list f fragment.views
let scan_views_in_species f sp =
let views = RPathMap.fold (fun _ t q -> t::q) sp.subspecies_views [] in
scan_list f views
let fold_views f fragment a =
List.fold_left
(fun sol x -> f x sol)
a
fragment.views
let is_empty_species sp = RPathMap.is_empty sp.subspecies_views
let get_views_from_agent_id view_map agent_id agent_type sp =
try
let view_id =
RPathMap.find (build_empty_path agent_id) sp.subspecies_views
in
Some (view_id,view_map view_id)
with
Not_found ->
None
let canonical_form = canonical_fragment_of_subspecies
let build_species agent_of_views view_map extension =
let species = empty_species in
let species =
StringMap.fold
(fun agent_id view_id species ->
add_view_to_subspecies species (build_empty_path agent_id) view_id)
view_map
species
in
let species =
List.fold_left
(fun species ((a,b),view_id) ->
add_view_to_subspecies species (build_rpath a b) view_id)
species
extension
in
species
let get_neighbour species ( agent_id , site ) agent_type ' =
try
let ( rp',s ' ) =
SitetypeMap.find
site
( RPathMap.find
( build_empty_path agent_id )
species.bonds_map
)
in
if rp'.path = [ ]
then rp'.root
else error 1405 None
with
Not_found - >
error 1069 None
try
let (rp',s') =
SitetypeMap.find
site
(RPathMap.find
(build_empty_path agent_id)
species.bonds_map
)
in
if rp'.path = []
then rp'.root
else error 1405 None
with
Not_found ->
error 1069 None
*)
let add_bond_to_subspecies sp (a,s) (a',s') =
add_bond_to_subspecies sp (build_empty_path a,s) (build_empty_path a',s')
module FragMap = Map2.Make (struct type t = fragment let compare = compare end)
module RootedFragMap = Map2.Make (struct type t = (rooted_path * view_id) * fragment let compare = compare end)
module BondSet = Set.Make (struct type t = (int*string) * (int*string) let compare = compare end)
let compute_edges fragment view_data_structure=
let stack = [] in
let views = fragment.views in
let back_bonds = fragment.back_bonds in
let fadd ((i,s),(i',s')) map =
let aux (i,s) (i',s') map =
let old =
try IntMap.find i map
with
Not_found -> StringMap.empty
in
IntMap.add i (StringMap.add s (i',s') old) map in
aux (i,s) (i',s') (aux (i',s') (i,s) map)
in
let occupied,bonds =
List.fold_left
(fun (set,map) x -> BondSet.add x set,fadd x map)
(BondSet.empty,IntMap.empty)
back_bonds in
let counter,stack,bonds =
List.fold_left
(fun (i,stack,bonds) view ->
let view = view_of_tp_i view view_data_structure.interface_map in
let target = view.Views.target in
let check,last,stack =
match stack with
[] -> None,None,[]
| (t,i)::q -> Some t,Some i,q in
let bonds,stack =
String2Map.fold
(fun (a,b) (c,d) (bonds,stack) ->
if check = Some ((c,d),(a,b))
then
match last with
None -> error 1451 None None
| Some i' ->
begin
fadd ((i',d),(i,b)) bonds,
stack
end
else
if
begin
try
let _ =
StringMap.find b (IntMap.find i bonds)
in true
with
Not_found -> false
end
then
bonds,stack
else
bonds,(((a,b),(c,d)),i)::stack)
target
(bonds,stack)
in
(i+1,stack,bonds))
(0,stack,bonds)
views in
bonds
let remove_agent_in_species ode_handler data_structure keep_link rule_id (species,free_sites) agent =
let rp = (build_empty_path agent) in
let get_dual_binding =
let map =
try
RPathMap.find rp species.bonds_map
with
Not_found -> SitetypeMap.empty
in
SitetypeMap.fold
(fun s (rp2,s2) bindings -> ((rp,agent,s),(rp2,s2))::bindings)
map []
in
let frem (a,s) map =
let old = try RPathMap.find a map with Not_found -> SitetypeMap.empty in
let new' = SitetypeMap.remove s old in
if SitetypeMap.is_empty new' then
RPathMap.remove a map
else
RPathMap.add a new' map in
let frem ((a,_,s),(a',s')) map =
frem (a,s) (frem (a',s') map) in
let bonds_map =
List.fold_left
(fun bonds_map x -> frem x bonds_map)
(species.bonds_map)
get_dual_binding
in
let free_sites =
List.fold_left
(fun l x -> x::l)
free_sites
get_dual_binding
in
let subspecies_views = RPathMap.remove rp species.subspecies_views in
{bonds_map = bonds_map;
subspecies_views = subspecies_views},free_sites
let pretty_print
stdprint
fragment
handler
ode_handler
views_data_structure
keep_this_link
empty
bool
=
let bonds = compute_edges fragment views_data_structure in
let fadd_free site site_map =
let tuple =
try (StringMap.find site site_map)
with Not_found ->
tuple_bot
in
let tuple' = {tuple with is_bound = Init false} in
StringMap.add site tuple' site_map in
let fadd_sign site s site_map =
let tuple =
try
StringMap.find site site_map
with
Not_found ->
tuple_bot in
let tuple' = {tuple with mark = Init s} in
StringMap.add site tuple' site_map in
let aux n (i,s) tuple_map =
let (ag,old) =
try
IntMap.find i tuple_map
with
Not_found -> error 1511 None None in
let tuple =
try
StringMap.find s old
with
Not_found -> tuple_bot
in
let tuple' = {tuple
with link = Init (bound_of_number n)
}
in
IntMap.add i (ag,StringMap.add s tuple' old) tuple_map in
let add_link (i,s) (i',s') (n,tuple_map) =
let tuple_map =
aux n (i,s) (aux n (i',s') tuple_map)
in
(n+1,tuple_map)
in
let counter,tuple_map,stack =
List.fold_left
(fun (counter,map,stack) view_id ->
let view = view_of_tp_i view_id views_data_structure.interface_map in
let agent = agent_of_view view in
let sigma = valuation_of_view view in
let tuple,stack =
List.fold_left
(fun (tuple,stack) (b,bool) ->
match ode_handler.b_of_var b,bool with
B(_,_,s),false -> fadd_free s tuple,stack
| M((_,_,s),mark),true -> fadd_sign s mark tuple,stack
| AL((_,a,s),(b,s')),true when
not (keep_this_link (a,s) (b,s')) ->
tuple,(counter,s,b,s')::stack
| _ -> tuple,stack)
(StringMap.empty,stack)
sigma
in
((counter+1),
IntMap.add counter (agent,tuple) map,
stack))
(0,IntMap.empty,[])
fragment.views
in
let (n,tuple_map) =
IntMap.fold
(fun i site_map ->
StringMap.fold
(fun s (i',s') (tuple_map) ->
if compare (i,s) (i',s')<= 0
then add_link (i,s) (i',s') tuple_map
else
tuple_map)
site_map)
bonds
(1,tuple_map)
in
let (n,tuple_map,counter) =
List.fold_left
(fun (n,tuple_map,counter) (i,s,b,s') ->
if not bool
then
let tuple = tuple_bot in
let tuple_map =
IntMap.add
counter
(b,StringMap.add s' tuple StringMap.empty)
tuple_map in
let n,tuple_map =
add_link
(i,s)
(counter,s')
(n,tuple_map) in
n,tuple_map,counter+1
else
let ag,sitemap =
try
IntMap.find i tuple_map
with
Not_found ->
error 1611 None None
in
let tuple =
try
StringMap.find s sitemap
with
Not_found -> tuple_bot
in
let tuple' = {tuple with link = Init(b,s')} in
let tuple_map =
IntMap.add i (ag,StringMap.add s tuple' sitemap) tuple_map in
(n,tuple_map,counter))
(n,tuple_map,counter)
stack in
let _ =
IntMap.fold
(fun _ (ag,tuple) bool ->
let _ =
if bool then () in
let pretty = StringMap.add ag tuple StringMap.empty in
let l =
print_pretty
handler
ag
(fun x->true)
((pretty,pretty),0)
tuple_known
empty
(if bool then handler.agent_separator () else "")
(fun x->x)
(fun x->x)
None
None in
let _ =
List.iter
(pprint_string stdprint)
(List.rev
((fun (_,a,_) -> a)
l)) in
true
)
tuple_map false in
()
let root_of_species x =
match
RPathMap.fold
(fun rp i sol ->
match sol with None -> Some (rp,i)
| Some (rp',_) when compare rp rp'>0 -> Some (rp,i)
| _ -> sol)
x.subspecies_views
None
with
None -> error 1660 None None
| Some i -> i
end:Fragments)
| null | https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/complx_rep/ODE/fragments.ml | ocaml | * Implementation of fragments for ODE
* Set this boolean to true to dump more debugging information
* definition of the empty fragment for the new type definition
* Pretty-print function for new fragment type
* optional pretty print function for new fragment, it only pretty print when the compilation has been made with trace=true
* new type definition for subspecies:
rooted paths are associated with views,
bonds are encoded both as a list and a map,
each bond has to be encoded in both direction
* pretty print
* empty species
bonds=[];
* to add a bond within a subspecies
* to add a view to a subspecies
* compute the cannonical fragment associated with a subspecies
(* TEST
bonds =
[(g [],"a"),(g [("2","a"),("1","a")],"a") ;
(g [],"b"),(g [("3","a"),("1","b")],"a") ;
(g [("2","a"),("1","a")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"b");
(g [("3","a"),("1","b")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"a");
inv ((g [],"a"),(g [("2","a"),("1","a")],"a")) ;
inv ((g [],"b"),(g [("3","a"),("1","b")],"a")) ;
inv ((g [("2","a"),("1","a")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"b"));
inv ((g [("3","a"),("1","b")],"b"),(g [("1","a"),("2","b");("2","a"),("1","a")],"a"))
] ;
END OF TEST
* emptyness test for fragments
* the following map shift the roots of a subspecies:
a function defined the new address (as a rooted path) of some former root,
the address of child of this root is also updates
* If the boolean is true then this function associates a maximal list of compatible fragments to a bond
* If the boolean is false then this function associated a maximal list of fragments to a bond
* This function is hash consed
here is the list of all template piece for agent a containing site s
dealing with compatibility
select a class of sites for the agent
filter out the one that are ot compatible
TO DO improve by computing directly the list when compatibility relation is already known
the view has to be kept
* This function takes a subspecies and build the list of the fragments that extend it
set of the typed site to be connected to the frontier of the subspecies by a solid line
map each target site to the rooted path of the agent it is connected to and the type of the connected site and the potential extentions of this bond
not an internal edges
a solid edge
String2Map.add y1 (rp,y2,get_denum (fst y2,snd y2,fst y1,snd y1)) map
String2Map.empty
String2Map.fold
(y2,y1)::
* this primitive split a species into a list of maximal connected subspecies
hash maps each rp to a class identifier
deal with side_effects due to agent removal |
open Tools
open Config_complx
open Data_structures
open Annotated_contact_map
open Views
open Pb_sig
open Rooted_path
open Fragments_sig
open Error_handler
open Ode_print
let trace = false
let debug = false
let cannonical_debug = false
let merge_debug = false
let map_debug = false
let complete_debug = false
let split_debug = false
let apply_blist_debug = false
let release_debug = false
let get_denum_debug = false
let error i s m =
unsafe_frozen m (Some "Complx") (Some "fragments.ml") s (Some ("line "^(string_of_int i))) (fun () -> raise Exit)
module New_Fragment =
(struct
* new definition of fragments , a fragments is an ordered list of views and a list of back bonds : in the list of views , the head is the view that has the smallest i d , then the list give the depth - first exploration of the graph ; back_bonds denote the edges that are not visited during the depth - first exploration integer denotes positions in the list starting from 0 .
In the case when there is two views with minimal indices , we chose the one that give the smallest final result , with respect to the polymorphic function compare
In the case when there is two views with minimal indices, we chose the one that give the smallest final result, with respect to the polymorphic function compare *)
type fragment =
{
views:int list ;
back_bonds: ((int * string) * (int * string)) list
}
let empty_fragment =
{views = [];
back_bonds = []}
let print_fragment a =
let _ = print_string "Fragments\n" in
let _ = print_string "Views: " in
let _ =
List.fold_left
(fun i j ->
let _ = if i>0 then print_string "," in
let _ = print_int j in
(i+1))
0 a.views in
let _ = print_newline () in
let _ = print_string "Back_bonds:" in
let _ =
List.fold_left
(fun bool ((i,s),(i',s')) ->
let _ = if bool then print_string "," in
let _ = print_int i in
let _ = print_string "." in
let _ = print_string s in
let _ = print_string "--" in
let _ = print_string s' in
let _ = print_string "." in
let _ = print_int i' in
true)
false
a.back_bonds in
let _ = print_newline () in
()
let trace_print_fragment =
if trace then print_fragment
else (fun _ -> ())
type view_id = int
type node_id = string
module NodeMap = Map2.Make (struct type t = node_id let compare = compare end)
type subspecies =
{
bonds_map: (rooted_path*site_type) SitetypeMap.t RPathMap.t;
subspecies_views:view_id RPathMap.t;
}
let is_empty_species s = RPathMap.is_empty s.subspecies_views
let iter_views_in_species f sp =
RPathMap.iter (fun _ -> f) sp.subspecies_views
let iter_views f fragment =
List.iter f fragment.views
let fold_bonds f species =
RPathMap.fold
(fun rp ->
SitetypeMap.fold
(fun site (rp',site') -> f ((rp,site),(rp',site')))
)
species.bonds_map
let iter_bonds f species =
RPathMap.iter
(fun rp ->
SitetypeMap.iter
(fun site (rp',site') -> f ((rp,site),(rp',site')))
)
species.bonds_map
let print_species sp =
let _ = print_string "SPECIES: \n" in
let _ = print_string " VIEWS: \n" in
let _ =
RPathMap.iter
(fun rp i ->
print_string " ";
print_rpath rp;
print_string ":";
print_int i;
print_newline ())
sp.subspecies_views in
let _ = print_string " BONDS: \n" in
let _ =
iter_bonds
(fun ((rp,s),(rp',s')) ->
print_string " ";
print_rpath rp;
print_string ".";
print_string s;
print_string "--";
print_string s';
print_string ".";
print_rpath rp';
print_newline ())
sp
in
let _ = print_newline () in
()
let empty_species =
{
bonds_map=RPathMap.empty;
subspecies_views=RPathMap.empty
}
let add_bond_to_subspecies subspecies (rp,s) (rp',s') =
let bonds_map =
let fadd a b c map =
let oldmap =
try
RPathMap.find a map
with
Not_found ->
SitetypeMap.empty
in
RPathMap.add a (SitetypeMap.add b c oldmap) map
in
fadd rp s (rp',s')
(fadd rp' s' (rp,s) subspecies.bonds_map) in
{subspecies
with bonds_map = bonds_map}
let release_bond_from_subspecies subspecies (rp,s) (rp',s') =
let _ =
if release_debug
then
begin
print_string "RELEASE BOND: \n";
print_rpath rp;
print_string "\n";
print_string s;
print_string "\n";
print_rpath rp';
print_string "\n";
print_string s';
print_string "\n";
print_species subspecies
end in
let bonds_map =
let update a b map =
let oldmap =
try
RPathMap.find a map
with
Not_found ->
SitetypeMap.empty
in
let site_map = SitetypeMap.remove b oldmap in
if SitetypeMap.is_empty site_map
then
RPathMap.remove a map
else
RPathMap.add a (site_map) map
in
update rp s
(update rp' s' subspecies.bonds_map) in
let rep = {subspecies with bonds_map = bonds_map} in
let _ =
if release_debug
then
begin
print_string "RELEASE BOND RESULT: \n";
print_species rep
end in
rep
let fetch_partner subspecies (rp,s) =
try
Some
(SitetypeMap.find
s
(RPathMap.find rp subspecies.bonds_map
)
)
with
Not_found -> None
let add_view_to_subspecies subspecies rp view =
let subspecies =
{subspecies
with subspecies_views = RPathMap.add rp view subspecies.subspecies_views} in
match rp.path
with [] -> subspecies
| t::q ->
let ((_,s),(_,s')) = t in
add_bond_to_subspecies subspecies (rp,s) ({rp with path = q},s')
let canonical_fragment_of_subspecies graph =
let _ =
if cannonical_debug
then
begin
print_string "START CANONICAL_FRAGMENT\n";
print_species graph;
end
in
let result =
RPathMap.fold
(fun path i key ->
match key
with None -> Some ([path],i)
| Some (path',i') ->
begin
match compare i i' with
-1 -> Some ([path],i)
| 0 -> Some (path::path',i')
| 1 -> Some (path',i')
| _ -> error 46 None None
end)
graph.subspecies_views
None
in
let path,key =
match result with
None -> error 168 None None
| Some (a,b) -> a,b in
let candidate =
List.map
(fun path ->
let rec vide working_list n black_list sol =
match working_list with
[] -> sol
| (bond,t)::q ->
try
let _ = RPathMap.find t black_list in
vide q n black_list sol
with Not_found ->
let black_list = RPathMap.add t n black_list in
let edges =
try
RPathMap.find t graph.bonds_map
with
Not_found -> SitetypeMap.empty
in
let edges =
match bond
with None -> edges
| Some (_,_,s') -> SitetypeMap.remove s' edges
in
let working_list',sol' =
SitetypeMap.fold
(fun s (a',s') (wl,sol) ->
try
let n' = RPathMap.find a' black_list in
(wl,{sol with back_bonds = ((n,s),(n',s'))::sol.back_bonds})
with
Not_found ->
(Some (t,s,s'),a')::wl,sol)
edges (q,sol) in
let sol' =
{sol' with
views =
(try
RPathMap.find t graph.subspecies_views::sol'.views
with
Not_found ->
begin
print_string "ERROR 311\n";
RPathMap.iter
(fun rp v ->
(try
(let _ = RPathMap.find rp graph.subspecies_views in ())
with
Not_found -> print_string "!!!ERROR");
print_rpath rp;
print_string ":";
print_int v;
print_string ";";
print_newline ())
graph.subspecies_views;
print_species graph;
print_newline ();
print_rpath t;
print_string ";";
print_newline ();
print_rpath path;
print_string ";";
print_newline ();
error 311 None None
end)} in
vide working_list' (n+1) black_list sol'
in
let sol = vide [None,path] 0 RPathMap.empty empty_fragment in
let sol = {back_bonds = List.rev sol.back_bonds;
views = List.rev sol.views} in
sol)
path in
let rec aux a b n =
match a with
(t:fragment)::q ->
trace_print_fragment t;
if compare t b <0
then aux q t 1
else if compare t b = 0
then aux q b (n+1)
else aux q b 1
| [] -> (b,n) in
let sol =
match candidate with t::q -> (trace_print_fragment t;aux q t 1)
| [] -> error 371 None None
in
let _ =
if cannonical_debug
then
print_string "END_CANONICAL\n"
in
sol
let _ =
if debug then
let inv (a,b) = (b,a) in
let g b = {path = b;root= ""} in
let a =
embedding=
StringMap.add " 1 " [ ]
( StringMap.add " 2 " [ ( " 2","a"),("1","a " ) ]
( StringMap.add " 3 " [ ( " 3","a"),("1","b " ) ]
( StringMap.add " 4 " [ ( " 4","b"),("2","b");("2","a"),("1","a " ) ]
StringMap.empty ) ) ) ;
reverse_embedding =
PathMap.add [ ] " 1 "
( PathMap.add [ ( " 2","a"),("1","a " ) ] " 2 "
( PathMap.add [ ( " 3","a"),("1","b " ) ] " 3 "
( PathMap.add [ ( " 4","b"),("2","b");("2","a"),("1","a " ) ] " 4 "
PathMap.empty ) ) ) ;
StringMap.add "1" []
(StringMap.add "2" [("2","a"),("1","a")]
(StringMap.add "3" [("3","a"),("1","b")]
(StringMap.add "4" [("4","b"),("2","b");("2","a"),("1","a")]
StringMap.empty))) ;
reverse_embedding =
PathMap.add [] "1"
(PathMap.add [("2","a"),("1","a")] "2"
(PathMap.add [("3","a"),("1","b")] "3"
(PathMap.add [("4","b"),("2","b");("2","a"),("1","a")] "4"
PathMap.empty))) ;*)
bonds_map =
RPathMap.add (g [])
(SitetypeMap.add
"a" (g [("2","a"),("1","a")],"a")
(SitetypeMap.add
"b" (g [("3","a"),("1","b")],"a")
SitetypeMap.empty))
(RPathMap.add (g [("2","a"),("1","a")])
(SitetypeMap.add
"a" (g [],"a")
(SitetypeMap.add
"b" (g [("1","a"),("2","b");("2","a"),("1","a")],"b")
SitetypeMap.empty))
(RPathMap.add (g [("3","a"),("1","b")])
(SitetypeMap.add
"a" (g [],"b")
(SitetypeMap.add
"b" (g [("1","a"),("2","b");("2","a"),("1","a")],"a")
SitetypeMap.empty))
(RPathMap.add
(g [("1","a"),("2","b");("2","a"),("1","a")])
(SitetypeMap.add
"b" (g [("2","a"),("1","a")],"b")
(SitetypeMap.add
"a" (g [("3","a"),("1","b")],"b")
SitetypeMap.empty))
RPathMap.empty)))
;
subspecies_views =
RPathMap.add (g []) 1
(RPathMap.add (g [("2","a"),("1","a")]) 2
(RPathMap.add (g [("3","a"),("1","b")]) 3
(RPathMap.add (g [("1","a"),("2","b");("2","a"),("1","a")]) 1
RPathMap.empty))) } in
let _ = print_subspecies a in
let b = canonical_fragment_of_subspecies a in
let _ = print_fragment b in ()
*)
let is_empty_fragment x = x.views=[]
let shift_subspecies subspecies shift =
let shift rp =
try
let rp' = StringMap.find rp.root shift
in
{rp' with path=rp.path@rp'.path}
with
Not_found -> rp in
{
bonds_map =
RPathMap.fold
(fun rp site_map bonds_map ->
let srp = shift rp in
RPathMap.add
srp
(SitetypeMap.map
(fun (rp',s') -> shift rp',s')
site_map)
bonds_map)
subspecies.bonds_map
RPathMap.empty;
subspecies_views =
RPathMap.fold
(fun a b map ->
let a' = shift a in
if a = a' then map
else
let image = RPathMap.find a map in
let map = RPathMap.remove a map in
let map = RPathMap.add a' image map in
map)
subspecies.subspecies_views
subspecies.subspecies_views }
let merge sp1 sp2 =
let _ =
if merge_debug
then
begin
print_string "MERGE \n";
print_species sp1 ;
print_species sp2
end
in
let sp =
{bonds_map =
RPathMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun _ b c ->
SitetypeMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun a b c -> if b=c then b else error 513 None None)
b
c)
sp1.bonds_map
sp2.bonds_map ;
subspecies_views =
RPathMap.map2
(fun _ b -> b)
(fun _ b -> b)
(fun _ b c -> if b=c then b else (error 522 None None ))
sp1.subspecies_views sp2.subspecies_views } in
let _ =
if merge_debug
then
begin
print_species sp
end
in sp
let get_denum_with_recursive_memoization
((agent_to_int_to_nlist:Views.views_id list StringListMap.t StringMap.t),
(view_of_tp_i:(Views.views_id -> 'a Views.views)),
(ode_handler:('b,'a,'c,'d,'e,'f,'g) ode_handler)) level bool =
let inc_black x black =
let old =
try StringMap.find x black
with
Not_found -> 0
in
StringMap.add x (old+1) black
in
let black_listed x black =
let old =
try StringMap.find x black
with
Not_found -> 0
in
old > 1
in
let hash = Hashtbl.create 200001 in
let rec fetch black (x:Pb_sig.name_specie*string*string*string) =
try Hashtbl.find hash x
with
Not_found ->
let rep = compute black x in
let _ =
if level > 0
then Hashtbl.add hash x rep
in
rep
and
compute black (a,s,a',s') =
if black_listed a black
then error 555 None (Some "Infinite set of fragments")
else
let fetch = if level = 2 then fetch else compute in
let black = inc_black a black in
let ag1,s1,ag2,s2 = (a,s,a',s') in
let ag_ref = ag1 in
let s_ref = s1 in
let _ =
if get_denum_debug
then
begin
print_string "COMPUTE\n";
print_string ag1;
print_string s1;
print_string ag2;
print_string s2;
print_string " ";
print_string (if bool then "TRUE\n" else "FALSE\n");
end in
try
StringListMap.find
[s]
(StringMap.find a agent_to_int_to_nlist)
with Not_found -> error 577 None None
in
let _ =
if get_denum_debug
then
begin
print_string "ALL POTENTIAL PARTNER\n";
List.iter
(fun i -> print_int i;print_string " ")
tp_list;
print_newline ();
end
in
let tp_list =
then
try
interface_of_view (view_of_tp_i (List.hd tp_list))
with
_ -> error 597 None None
in
(fun tp ->
let view = view_of_tp_i tp in
(interface_of_view view = classe)
)
tp_list
else tp_list in
List.fold_left
(fun liste tp ->
let view = view_of_tp_i tp in
if
TODO hash cons the function between bonds and views compatible with this bond
match l with [] -> false
| t::q ->
begin
match ode_handler.b_of_var (fst t),snd(t) with AL((x,y,z),(t,u)),bool
when x=ag1 && y=ag1 && z=s1 && t=ag2 && u = s2 -> bool
| _ -> aux q
end
in aux (valuation_of_view view)
let _ =
if get_denum_debug then
begin
print_int tp;
print_newline ()
end
in
let pending_bonds =
String4Set.fold
(fun ((ag1,s1),(ag2,s2)) pending_bonds ->
if ag1 = ag_ref && s1=s_ref
then pending_bonds
else (
let _ =
if get_denum_debug
then
begin
print_string ag2;
print_string s2;
print_string ag1;
print_string s1;
print_newline ()
end in
(ag2,s2,ag1,s1))::pending_bonds)
(pending_edges view) []
in
let rpath =
{empty_rpath
with path = [(a,s),(a',s')]} in
let species = add_view_to_subspecies empty_species rpath tp in
let _ =
if get_denum_debug
then
print_species species
in
let species_list =
List.fold_left
(fun prefix bond ->
let (a,s,a',s') = bond in
let rpath'=
{rpath with
path = ((a,s),(a',s'))::rpath.path} in
let extension = fetch black bond in
List.fold_left
(fun liste extension ->
List.fold_left
(fun liste subspecies ->
let shifted_extension =
shift_subspecies
extension
(StringMap.add "" rpath StringMap.empty) in
let ext_subspecies = merge shifted_extension subspecies in
let rep =
add_bond_to_subspecies
ext_subspecies
(rpath',s)
(rpath,s') in
let _ =
if get_denum_debug
then
begin
print_string "RECOMP\n";
print_string "BASE\n";
print_species subspecies;
print_string "\nEXT\n";
print_species extension;
print_string "\nSHIFTED EXT\n";
print_species shifted_extension;
print_string "\nPATHs\n";
print_rpath rpath;
print_string "\n";
print_string s;
print_string "\n";
print_rpath rpath';
print_string "\n";
print_string s';
print_string "\n";
print_string "\nRESULT\n";
print_species rep ;
print_string "\n"
end
in
rep::liste)
liste prefix)
[] extension)
[species] pending_bonds
in
let _ =
if get_denum_debug
then
begin
print_string "SPECIE LIST \n" ;
List.iter print_species species_list
end
in
List.fold_left
(fun list a -> a::list)
liste
species_list
else liste)
[]
tp_list
in fetch StringMap.empty
let get_denum
= (fun x ->
get_denum_with_recursive_memoization x 0 ,
get_denum_with_recursive_memoization x 1 ,
get_denum_with_recursive_memoization x 2)
let complete_subspecies (pending_edges,view_of_tp_i,keep_this_link,get_denum) subspecies =
let _ =
if complete_debug
then
begin
print_string "COMPLETE: ";
print_newline ();
print_species subspecies
end in
=
RPathMap.fold
(fun rp tp (target,map) ->
let pending_edges = pending_edges (view_of_tp_i tp) in
String4Set.fold
(fun (y1,y2) (target,map) ->
if
try
let _ =
SitetypeMap.find (snd y1)
(RPathMap.find rp subspecies.bonds_map) in
true
with
Not_found -> false
end
&&
keep_this_link y1 y2
end
then
(target,map)
else
(
String2Set.add y1 target,
(y1,rp,y2,get_denum (fst y2,snd y2,fst y1,snd y1))::map))
pending_edges
(target,map))
subspecies.subspecies_views
let _ =
if map_debug
then
begin
print_string "MAP:\n";
String2Map .
(fun (y1,rp,y2,ext_list) ->
print_string (fst y2);
print_string ".";
print_string (snd y2);
print_rpath rp;
print_string (fst y1);
print_string ".";
print_string (snd y1);
print_newline ();
List.iter print_species ext_list)
map
end
in
let sol =
sol_list
List.fold_left
(fun pre_sol_list extension ->
List.fold_left
(fun sol_list pre_sol ->
let extended_sol =
add_bond_to_subspecies
(merge
pre_sol
(shift_subspecies
extension
(StringMap.add "" rp' StringMap.empty)))
( rp , snd y1 ) ( rp',snd y2 )
extended_sol::sol_list
)
pre_sol_list sol_list
)
[] extension_list
)
[subspecies] map in
let _ =
if complete_debug
then
begin
print_string "COMPLETE RESULT\n";
List.iter print_species sol
end
in
sol
let split_subspecies data_structure ode_handler contact_map subspecies =
let _ =
if split_debug
then
begin
print_string "SPLIT \n";
print_species subspecies
end in
let rec aux to_visit current_rp_list available_rpaths list =
match to_visit with
[] ->
begin
let list' = current_rp_list::list in
if
RPathSet.is_empty available_rpaths
then
list'
else
let rpath = RPathSet.min_elt available_rpaths in
aux
[rpath]
[]
available_rpaths
list'
end
| rpath::q when not (RPathSet.mem rpath available_rpaths) ->
aux q current_rp_list available_rpaths list
| rpath::q ->
let available_rpaths' = RPathSet.remove rpath available_rpaths in
let q' =
let sitemap =
try
RPathMap.find rpath subspecies.bonds_map
with
Not_found ->
SitetypeMap.empty
in
SitetypeMap.fold
(fun _ (a,_) q' ->
if RPathSet.mem a available_rpaths
then
a::q'
else
q')
sitemap
q in
let current_rp_list' = rpath::current_rp_list in
aux
q'
current_rp_list'
available_rpaths'
list
in
let rp_set =
RPathMap.fold
(fun a _ -> RPathSet.add a)
subspecies.subspecies_views
RPathSet.empty in
let _ =
if split_debug
then
begin
print_string "RP_SET \n";
RPathSet.iter
(fun rp -> print_rpath rp;print_newline ())
rp_set
end
in
let rp_list_list =
if RPathSet.is_empty rp_set
then
[]
else
let min = RPathSet.min_elt rp_set in
aux [min] [] rp_set []
in
List.fold_left
(fun (hash,id) rp_list ->
List.fold_left
(fun hash rp ->
RPathMap.add rp id hash)
hash rp_list,id+1)
(RPathMap.empty,0)
rp_list_list in
let views_map =
RPathMap.fold
(fun rp v map ->
let i =
try
RPathMap.find rp hash
with
Not_found ->
begin
print_rpath rp;
error 829 None None
end
in
let old =
try
IntMap.find i map
with
Not_found ->
RPathMap.empty
in
IntMap.add i (RPathMap.add rp v old) map)
subspecies.subspecies_views IntMap.empty in
let species_map_without_bonds =
IntMap.map (fun list -> {empty_species with subspecies_views = list}) views_map in
let species_map_with_bonds =
fold_bonds
(fun ((a,b),(c,d)) bonds_map ->
let i =
try
RPathMap.find a hash
with
Not_found ->
error 952 None None
in
let old =
try
IntMap.find i bonds_map
with
Not_found -> error 959 None None
in
IntMap.add i (add_bond_to_subspecies old (a,b) (c,d)) bonds_map)
subspecies
species_map_without_bonds
in
let sol =
IntMap.fold
(fun _ a l -> a::l)
species_map_with_bonds
[]
in
let _ =
if split_debug
then
begin
print_string "SPLIT RESULT \n";
List.iter
print_species
sol
end
in sol
let is_agent_in_species x s =
try
(let _ = RPathMap.find (build_empty_path x) s.subspecies_views in true)
with
Not_found -> false
type hash = string list RPathMap.t
let dump_hash x =
let _ =
RPathMap.iter
(fun rp l ->
print_rpath rp ;
print_string " : ";
List.iter print_string l;
print_newline ())
x in
print_newline ()
let empty_hash = RPathMap.empty
let check_compatibility data_structure hash subspecies =
let l =
RPathMap.fold
(fun a b sol -> (a,b)::sol)
subspecies.subspecies_views []
in
let rec aux hash' l =
match l with [] -> hash',true
| (rpath,tp_i)::q ->
let view = view_of_tp_i tp_i data_structure.interface_map in
let int =
StringSet.fold
(fun site b -> site::b)
(interface_of_view view).kept_sites
[]
in
try
if
RPathMap.find rpath hash = int
then
aux hash' q
else
hash,false
with
Not_found ->
aux
(RPathMap.add rpath int hash')
q
in
aux hash l
let apply_blist_with_species ode_handler data_structure keep_link rule_id species blist free_sites =
let _ =
if apply_blist_debug
then
begin
print_string "APPLY BLIST \n";
print_string " BLIST : \n";
List.iter
(fun (b,bool) ->
print_string " ";
print_b b;
print_string (if bool then "T" else "F");
print_newline ())
blist;
print_string " Species : \n";
print_species species
end in
let update = RPathMap.empty in
let get a modified =
try
Some (RPathMap.find a modified)
with
Not_found ->
try
let tp_i = RPathMap.find a species.subspecies_views in
let view = view_of_tp_i tp_i data_structure.interface_map in
Some (view.agent,view.valuation_map)
with
Not_found -> None
in
deal with blist
let update,subspecies =
List.fold_left
(fun (modified,subspecies) (b,bool) ->
let f b rp modified =
let b' = downgrade_b b in
let ((agent_type:string),
(v:'a BMap.t)) =
match get rp modified with
None -> error 1076 (Some "update blist") None
|Some rep -> rep
in
let v' = BMap.add b' bool v in
RPathMap.add
rp
(agent_type,v')
modified in
match
b
with
M((agent_id,_,_),_) when agent_id<> "" ->
f b (build_empty_path agent_id) modified,
subspecies
| B(agent_id,agent_type,site) | AL((agent_id,agent_type,site),_) when agent_id <> "" ->
let rp = build_empty_path agent_id in
if not bool
then
try
let (rp',site') =
SitetypeMap.find
site
(RPathMap.find
(build_empty_path agent_id)
species.bonds_map)
in
let (agent_type',v') =
match get rp' modified
with None -> error 1105 None None
|Some a -> a
in
let modified = f (B(agent_type,agent_type,site)) rp modified in
let modified = f (AL((agent_type,agent_type,site),(agent_type',site'))) rp modified in
let modified = f (B(agent_type',agent_type',site')) rp' modified in
let modified = f (AL((agent_type',agent_type',site'),(agent_type,site))) rp' modified in
modified,
release_bond_from_subspecies
subspecies
(rp,site)
(rp',site')
with
Not_found ->
f b rp modified,subspecies
else
f b rp modified,subspecies
| L((agent_id,agent_type,site),(agent_id',agent_type',site')) ->
modified,
(if bool
then add_bond_to_subspecies
else
release_bond_from_subspecies)
subspecies
((build_empty_path agent_id),site)
((build_empty_path agent_id'),site')
| _ -> modified,subspecies)
(update,species)
blist
in
let update,subspecies =
List.fold_left
(fun (update,subspecies) ((rp,a,s),(rp',s')) ->
try
let rep = get rp' update in
match rep
with Some (agent_type,v) ->
let v' = BMap.add (B(agent_type,agent_type,s')) false v in
let v' = BMap.add (AL((agent_type,agent_type,s'),(a,s))) false v' in
RPathMap.add
rp'
(agent_type,v')
update,
subspecies
| None -> update,subspecies
with
Not_found -> update,subspecies)
(update,subspecies) free_sites
in
let stringblist (x,bmap) =
let hashkey =
(x,List.sort compare (BMap.fold (fun b bool l -> (b,bool)::l) bmap [])) in
try
StringBListMap.find hashkey data_structure.blist_to_template
with
Not_found ->
let _ = print_string x in
let _ = print_newline () in
let _ =
BMap.iter
(fun b bool ->
print_b b;
if bool
then
print_string "T\n"
else
print_string "F\n")
bmap in
error 1343 None (Some "Try to hash unknown view")
in
let species =
{subspecies
with subspecies_views =
RPathMap.fold
(fun rp x map ->
RPathMap.add
rp
(stringblist x)
map)
update
subspecies.subspecies_views
}
in
let _ =
if apply_blist_debug
then
begin
print_string "APPLY BLIST RESULT \n";
print_string " Species : \n";
print_species species
end
in species
let plug_views_in_subspecies agent_id view_id sp =
{sp
with
subspecies_views =
RPathMap.add (build_empty_path agent_id) view_id sp.subspecies_views}
let rec scan_list f l =
match l
with
[] -> None
| t::q ->
begin
match f t
with
None -> scan_list f q
| x -> x
end
let scan_views f fragment =
scan_list f fragment.views
let scan_views_in_species f sp =
let views = RPathMap.fold (fun _ t q -> t::q) sp.subspecies_views [] in
scan_list f views
let fold_views f fragment a =
List.fold_left
(fun sol x -> f x sol)
a
fragment.views
let is_empty_species sp = RPathMap.is_empty sp.subspecies_views
let get_views_from_agent_id view_map agent_id agent_type sp =
try
let view_id =
RPathMap.find (build_empty_path agent_id) sp.subspecies_views
in
Some (view_id,view_map view_id)
with
Not_found ->
None
let canonical_form = canonical_fragment_of_subspecies
let build_species agent_of_views view_map extension =
let species = empty_species in
let species =
StringMap.fold
(fun agent_id view_id species ->
add_view_to_subspecies species (build_empty_path agent_id) view_id)
view_map
species
in
let species =
List.fold_left
(fun species ((a,b),view_id) ->
add_view_to_subspecies species (build_rpath a b) view_id)
species
extension
in
species
let get_neighbour species ( agent_id , site ) agent_type ' =
try
let ( rp',s ' ) =
SitetypeMap.find
site
( RPathMap.find
( build_empty_path agent_id )
species.bonds_map
)
in
if rp'.path = [ ]
then rp'.root
else error 1405 None
with
Not_found - >
error 1069 None
try
let (rp',s') =
SitetypeMap.find
site
(RPathMap.find
(build_empty_path agent_id)
species.bonds_map
)
in
if rp'.path = []
then rp'.root
else error 1405 None
with
Not_found ->
error 1069 None
*)
let add_bond_to_subspecies sp (a,s) (a',s') =
add_bond_to_subspecies sp (build_empty_path a,s) (build_empty_path a',s')
module FragMap = Map2.Make (struct type t = fragment let compare = compare end)
module RootedFragMap = Map2.Make (struct type t = (rooted_path * view_id) * fragment let compare = compare end)
module BondSet = Set.Make (struct type t = (int*string) * (int*string) let compare = compare end)
let compute_edges fragment view_data_structure=
let stack = [] in
let views = fragment.views in
let back_bonds = fragment.back_bonds in
let fadd ((i,s),(i',s')) map =
let aux (i,s) (i',s') map =
let old =
try IntMap.find i map
with
Not_found -> StringMap.empty
in
IntMap.add i (StringMap.add s (i',s') old) map in
aux (i,s) (i',s') (aux (i',s') (i,s) map)
in
let occupied,bonds =
List.fold_left
(fun (set,map) x -> BondSet.add x set,fadd x map)
(BondSet.empty,IntMap.empty)
back_bonds in
let counter,stack,bonds =
List.fold_left
(fun (i,stack,bonds) view ->
let view = view_of_tp_i view view_data_structure.interface_map in
let target = view.Views.target in
let check,last,stack =
match stack with
[] -> None,None,[]
| (t,i)::q -> Some t,Some i,q in
let bonds,stack =
String2Map.fold
(fun (a,b) (c,d) (bonds,stack) ->
if check = Some ((c,d),(a,b))
then
match last with
None -> error 1451 None None
| Some i' ->
begin
fadd ((i',d),(i,b)) bonds,
stack
end
else
if
begin
try
let _ =
StringMap.find b (IntMap.find i bonds)
in true
with
Not_found -> false
end
then
bonds,stack
else
bonds,(((a,b),(c,d)),i)::stack)
target
(bonds,stack)
in
(i+1,stack,bonds))
(0,stack,bonds)
views in
bonds
let remove_agent_in_species ode_handler data_structure keep_link rule_id (species,free_sites) agent =
let rp = (build_empty_path agent) in
let get_dual_binding =
let map =
try
RPathMap.find rp species.bonds_map
with
Not_found -> SitetypeMap.empty
in
SitetypeMap.fold
(fun s (rp2,s2) bindings -> ((rp,agent,s),(rp2,s2))::bindings)
map []
in
let frem (a,s) map =
let old = try RPathMap.find a map with Not_found -> SitetypeMap.empty in
let new' = SitetypeMap.remove s old in
if SitetypeMap.is_empty new' then
RPathMap.remove a map
else
RPathMap.add a new' map in
let frem ((a,_,s),(a',s')) map =
frem (a,s) (frem (a',s') map) in
let bonds_map =
List.fold_left
(fun bonds_map x -> frem x bonds_map)
(species.bonds_map)
get_dual_binding
in
let free_sites =
List.fold_left
(fun l x -> x::l)
free_sites
get_dual_binding
in
let subspecies_views = RPathMap.remove rp species.subspecies_views in
{bonds_map = bonds_map;
subspecies_views = subspecies_views},free_sites
let pretty_print
stdprint
fragment
handler
ode_handler
views_data_structure
keep_this_link
empty
bool
=
let bonds = compute_edges fragment views_data_structure in
let fadd_free site site_map =
let tuple =
try (StringMap.find site site_map)
with Not_found ->
tuple_bot
in
let tuple' = {tuple with is_bound = Init false} in
StringMap.add site tuple' site_map in
let fadd_sign site s site_map =
let tuple =
try
StringMap.find site site_map
with
Not_found ->
tuple_bot in
let tuple' = {tuple with mark = Init s} in
StringMap.add site tuple' site_map in
let aux n (i,s) tuple_map =
let (ag,old) =
try
IntMap.find i tuple_map
with
Not_found -> error 1511 None None in
let tuple =
try
StringMap.find s old
with
Not_found -> tuple_bot
in
let tuple' = {tuple
with link = Init (bound_of_number n)
}
in
IntMap.add i (ag,StringMap.add s tuple' old) tuple_map in
let add_link (i,s) (i',s') (n,tuple_map) =
let tuple_map =
aux n (i,s) (aux n (i',s') tuple_map)
in
(n+1,tuple_map)
in
let counter,tuple_map,stack =
List.fold_left
(fun (counter,map,stack) view_id ->
let view = view_of_tp_i view_id views_data_structure.interface_map in
let agent = agent_of_view view in
let sigma = valuation_of_view view in
let tuple,stack =
List.fold_left
(fun (tuple,stack) (b,bool) ->
match ode_handler.b_of_var b,bool with
B(_,_,s),false -> fadd_free s tuple,stack
| M((_,_,s),mark),true -> fadd_sign s mark tuple,stack
| AL((_,a,s),(b,s')),true when
not (keep_this_link (a,s) (b,s')) ->
tuple,(counter,s,b,s')::stack
| _ -> tuple,stack)
(StringMap.empty,stack)
sigma
in
((counter+1),
IntMap.add counter (agent,tuple) map,
stack))
(0,IntMap.empty,[])
fragment.views
in
let (n,tuple_map) =
IntMap.fold
(fun i site_map ->
StringMap.fold
(fun s (i',s') (tuple_map) ->
if compare (i,s) (i',s')<= 0
then add_link (i,s) (i',s') tuple_map
else
tuple_map)
site_map)
bonds
(1,tuple_map)
in
let (n,tuple_map,counter) =
List.fold_left
(fun (n,tuple_map,counter) (i,s,b,s') ->
if not bool
then
let tuple = tuple_bot in
let tuple_map =
IntMap.add
counter
(b,StringMap.add s' tuple StringMap.empty)
tuple_map in
let n,tuple_map =
add_link
(i,s)
(counter,s')
(n,tuple_map) in
n,tuple_map,counter+1
else
let ag,sitemap =
try
IntMap.find i tuple_map
with
Not_found ->
error 1611 None None
in
let tuple =
try
StringMap.find s sitemap
with
Not_found -> tuple_bot
in
let tuple' = {tuple with link = Init(b,s')} in
let tuple_map =
IntMap.add i (ag,StringMap.add s tuple' sitemap) tuple_map in
(n,tuple_map,counter))
(n,tuple_map,counter)
stack in
let _ =
IntMap.fold
(fun _ (ag,tuple) bool ->
let _ =
if bool then () in
let pretty = StringMap.add ag tuple StringMap.empty in
let l =
print_pretty
handler
ag
(fun x->true)
((pretty,pretty),0)
tuple_known
empty
(if bool then handler.agent_separator () else "")
(fun x->x)
(fun x->x)
None
None in
let _ =
List.iter
(pprint_string stdprint)
(List.rev
((fun (_,a,_) -> a)
l)) in
true
)
tuple_map false in
()
let root_of_species x =
match
RPathMap.fold
(fun rp i sol ->
match sol with None -> Some (rp,i)
| Some (rp',_) when compare rp rp'>0 -> Some (rp,i)
| _ -> sol)
x.subspecies_views
None
with
None -> error 1660 None None
| Some i -> i
end:Fragments)
|
4d0fd39a23b95123dcca14d99b17faafc0c31c6433345fa0cce34817bf0bbe71 | LeventErkok/sbv | AOC_2021_24.hs | -----------------------------------------------------------------------------
-- |
-- Module : Documentation.SBV.Examples.Puzzles.AOC_2021_24
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
A solution to the advent - of - code problem , 2021 , day 24 : < > .
--
-- Here is a high-level summary: We are essentially modeling the ALU of a fictional
computer with 4 integer registers ( w , x , y , z ) , and 6 instructions ( inp , add , , div , mod , eql ) .
-- You are given a program (hilariously called "monad"), and your goal is to figure out what
-- the maximum and minimum inputs you can provide to this program such that when it runs
register z ends up with the value 1 . Please refer to the above link for the full description .
--
While there are multiple ways to solve this problem in SBV , the solution here demonstrates
how to turn programs in this fictional language into actual Haskell / SBV programs , i.e. ,
-- developing a little EDSL (embedded domain-specific language) for it. Hopefully this
-- should provide a template for other similar programs.
-----------------------------------------------------------------------------
{-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE NegativeLiterals #
{-# OPTIONS_GHC -Wall -Werror #-}
module Documentation.SBV.Examples.Puzzles.AOC_2021_24 where
import Prelude hiding (read, mod, div)
import Data.Maybe
import qualified Data.Map.Strict as M
import qualified Control.Monad.State.Lazy as ST
import Data.SBV
-----------------------------------------------------------------------------------------------
-- * Registers, values, and the ALU
-----------------------------------------------------------------------------------------------
-- | A Register in the machine, identified by its name.
type Register = String
| We operate on 64 - bit signed integers . It is also possible to use the unbounded integers here
-- as the problem description doesn't mention any size limitations. But performance isn't as good
with unbounded integers , and 64 - bit signed bit - vectors seem to fit the bill just fine , much
like any other modern processor these days .
type Value = SInt64
-- | An item of data to be processed. We can either be referring to a named register, or an immediate value.
data Data = Reg {register :: Register}
| Imm Int64
| ' ' instance for ' Data ' . This is merely there for us to be able to represent programs in a
-- natural way, i.e, lifting integers (positive and negative). Other methods are neither implemented
-- nor needed.
instance Num Data where
fromInteger = Imm . fromIntegral
(+) = error "+ : unimplemented"
(*) = error "* : unimplemented"
negate (Imm i) = Imm (-i)
negate Reg{} = error "negate: unimplemented"
abs = error "abs : unimplemented"
signum = error "signum: unimplemented"
-- | Shorthand for the @w@ register.
w :: Data
w = Reg "w"
-- | Shorthand for the @x@ register.
x :: Data
x = Reg "x"
-- | Shorthand for the @y@ register.
y :: Data
y = Reg "y"
-- | Shorthand for the @z@ register.
z :: Data
z = Reg "z"
-- | The state of the machine. We keep track of the data values, along with the input parameters.
data State = State { env :: M.Map Register Value -- ^ Values of registers
, inputs :: [Value] -- ^ Input parameters, stored in reverse.
}
| The ALU is simply a state transformer , manipulating the state , wrapped around SBV 's ' Symbolic ' monad .
type ALU = ST.StateT State Symbolic
-----------------------------------------------------------------------------------------------
-- * Operations
-----------------------------------------------------------------------------------------------
-- | Reading a value. For a register, we simply look it up in the environment.
-- For an immediate, we simply return it.
read :: Data -> ALU Value
read (Reg r) = ST.get >>= \st -> pure $ fromJust (r `M.lookup` env st)
read (Imm i) = pure $ literal i
-- | Writing a value. We update the registers.
write :: Data -> Value -> ALU ()
write d v = ST.modify' $ \st -> st{env = M.insert (register d) v (env st)}
-- | Reading an input value. In this version, we simply write a free symbolic value
-- to the specified register, and keep track of the inputs explicitly.
inp :: Data -> ALU ()
inp a = do v <- ST.lift free_
write a v
ST.modify' $ \st -> st{inputs = v : inputs st}
-- | Addition.
add :: Data -> Data -> ALU ()
add a b = write a =<< (+) <$> read a <*> read b
-- | Multiplication.
mul :: Data -> Data -> ALU ()
mul a b = write a =<< (*) <$> read a <*> read b
-- | Division.
div :: Data -> Data -> ALU ()
div a b = write a =<< sDiv <$> read a <*> read b
-- | Modulus.
mod :: Data -> Data -> ALU ()
mod a b = write a =<< sMod <$> read a <*> read b
-- | Equality.
eql :: Data -> Data -> ALU ()
eql a b = write a . oneIf =<< (.==) <$> read a <*> read b
-----------------------------------------------------------------------------------------------
-- * Running a program
-----------------------------------------------------------------------------------------------
-- | Run a given program, returning the final state. We simply start with the initial
environment mapping all registers to zero , as specified in the problem specification .
run :: ALU () -> Symbolic State
run pgm = ST.execStateT pgm initState
where initState = State { env = M.fromList [(register r, 0) | r <- [w, x, y, z]]
, inputs = []
}
-----------------------------------------------------------------------------------------------
-- * Solving the puzzle
--
-----------------------------------------------------------------------------------------------
-- | We simply run the 'monad' program, and specify the constraints at the end. We take a boolean
-- as a parameter, choosing whether we want to minimize or maximize the model-number. We have:
--
-- >>> puzzle True
-- Optimal model:
Maximum model number = 96918996924991 : : Int64
-- >>> puzzle False
-- Optimal model:
Minimum model number = 91811241911641 : : Int64
puzzle :: Bool -> IO ()
puzzle shouldMaximize = print =<< optimizeWith z3{isNonModelVar = (/= finalVar)} Lexicographic problem
where finalVar | shouldMaximize = "Maximum model number"
| True = "Minimum model number"
problem = do State{env, inputs} <- run monad
-- The final z value should be 0
constrain $ fromJust (register z `M.lookup` env) .== 0
-- Digits of the model number, stored in reverse
let digits = reverse inputs
-- Each digit is between 1-9
ST.forM_ digits $ \d -> constrain $ d `inRange` (1, 9)
-- Digits spell out the model number. We minimize/maximize this value as requested:
let modelNum = foldl (\sofar d -> 10 * sofar + d) 0 digits
-- maximize/minimize the digits as requested
if shouldMaximize
then maximize "goal" modelNum
else minimize "goal" modelNum
-- For display purposes, create a variable to assign to modelNum
modelNumV <- free finalVar
constrain $ modelNumV .== modelNum
| The program we need to crack . Note that different users get different programs on the Advent - Of - Code site , so this is simply one example .
You can simply cut - and - paste your version instead . ( Do n't forget the pragma @NegativeLiterals@ to GHC so @add x -1@ parses correctly as @add x ( -1)@. )
monad :: ALU ()
monad = do inp w
mul x 0
add x z
mod x 26
div z 1
add x 11
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 13
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 12
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 1
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 15
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 15
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 10
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 2
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -1
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 2
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 14
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -8
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 8
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -7
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 14
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -8
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 12
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 11
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 7
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -2
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 14
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -2
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 13
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -13
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 6
mul y x
add z y
# ANN module ( " HLint : ignore Reduce duplication " : : String ) #
| null | https://raw.githubusercontent.com/LeventErkok/sbv/9cd3662cb6ae31a95b99570f91ae4639807dc1ab/Documentation/SBV/Examples/Puzzles/AOC_2021_24.hs | haskell | ---------------------------------------------------------------------------
|
Module : Documentation.SBV.Examples.Puzzles.AOC_2021_24
License : BSD3
Maintainer:
Stability : experimental
Here is a high-level summary: We are essentially modeling the ALU of a fictional
You are given a program (hilariously called "monad"), and your goal is to figure out what
the maximum and minimum inputs you can provide to this program such that when it runs
developing a little EDSL (embedded domain-specific language) for it. Hopefully this
should provide a template for other similar programs.
---------------------------------------------------------------------------
# LANGUAGE NamedFieldPuns #
# OPTIONS_GHC -Wall -Werror #
---------------------------------------------------------------------------------------------
* Registers, values, and the ALU
---------------------------------------------------------------------------------------------
| A Register in the machine, identified by its name.
as the problem description doesn't mention any size limitations. But performance isn't as good
| An item of data to be processed. We can either be referring to a named register, or an immediate value.
natural way, i.e, lifting integers (positive and negative). Other methods are neither implemented
nor needed.
| Shorthand for the @w@ register.
| Shorthand for the @x@ register.
| Shorthand for the @y@ register.
| Shorthand for the @z@ register.
| The state of the machine. We keep track of the data values, along with the input parameters.
^ Values of registers
^ Input parameters, stored in reverse.
---------------------------------------------------------------------------------------------
* Operations
---------------------------------------------------------------------------------------------
| Reading a value. For a register, we simply look it up in the environment.
For an immediate, we simply return it.
| Writing a value. We update the registers.
| Reading an input value. In this version, we simply write a free symbolic value
to the specified register, and keep track of the inputs explicitly.
| Addition.
| Multiplication.
| Division.
| Modulus.
| Equality.
---------------------------------------------------------------------------------------------
* Running a program
---------------------------------------------------------------------------------------------
| Run a given program, returning the final state. We simply start with the initial
---------------------------------------------------------------------------------------------
* Solving the puzzle
---------------------------------------------------------------------------------------------
| We simply run the 'monad' program, and specify the constraints at the end. We take a boolean
as a parameter, choosing whether we want to minimize or maximize the model-number. We have:
>>> puzzle True
Optimal model:
>>> puzzle False
Optimal model:
The final z value should be 0
Digits of the model number, stored in reverse
Each digit is between 1-9
Digits spell out the model number. We minimize/maximize this value as requested:
maximize/minimize the digits as requested
For display purposes, create a variable to assign to modelNum | Copyright : ( c )
A solution to the advent - of - code problem , 2021 , day 24 : < > .
computer with 4 integer registers ( w , x , y , z ) , and 6 instructions ( inp , add , , div , mod , eql ) .
register z ends up with the value 1 . Please refer to the above link for the full description .
While there are multiple ways to solve this problem in SBV , the solution here demonstrates
how to turn programs in this fictional language into actual Haskell / SBV programs , i.e. ,
# LANGUAGE NegativeLiterals #
module Documentation.SBV.Examples.Puzzles.AOC_2021_24 where
import Prelude hiding (read, mod, div)
import Data.Maybe
import qualified Data.Map.Strict as M
import qualified Control.Monad.State.Lazy as ST
import Data.SBV
type Register = String
| We operate on 64 - bit signed integers . It is also possible to use the unbounded integers here
with unbounded integers , and 64 - bit signed bit - vectors seem to fit the bill just fine , much
like any other modern processor these days .
type Value = SInt64
data Data = Reg {register :: Register}
| Imm Int64
| ' ' instance for ' Data ' . This is merely there for us to be able to represent programs in a
instance Num Data where
fromInteger = Imm . fromIntegral
(+) = error "+ : unimplemented"
(*) = error "* : unimplemented"
negate (Imm i) = Imm (-i)
negate Reg{} = error "negate: unimplemented"
abs = error "abs : unimplemented"
signum = error "signum: unimplemented"
w :: Data
w = Reg "w"
x :: Data
x = Reg "x"
y :: Data
y = Reg "y"
z :: Data
z = Reg "z"
}
| The ALU is simply a state transformer , manipulating the state , wrapped around SBV 's ' Symbolic ' monad .
type ALU = ST.StateT State Symbolic
read :: Data -> ALU Value
read (Reg r) = ST.get >>= \st -> pure $ fromJust (r `M.lookup` env st)
read (Imm i) = pure $ literal i
write :: Data -> Value -> ALU ()
write d v = ST.modify' $ \st -> st{env = M.insert (register d) v (env st)}
inp :: Data -> ALU ()
inp a = do v <- ST.lift free_
write a v
ST.modify' $ \st -> st{inputs = v : inputs st}
add :: Data -> Data -> ALU ()
add a b = write a =<< (+) <$> read a <*> read b
mul :: Data -> Data -> ALU ()
mul a b = write a =<< (*) <$> read a <*> read b
div :: Data -> Data -> ALU ()
div a b = write a =<< sDiv <$> read a <*> read b
mod :: Data -> Data -> ALU ()
mod a b = write a =<< sMod <$> read a <*> read b
eql :: Data -> Data -> ALU ()
eql a b = write a . oneIf =<< (.==) <$> read a <*> read b
environment mapping all registers to zero , as specified in the problem specification .
run :: ALU () -> Symbolic State
run pgm = ST.execStateT pgm initState
where initState = State { env = M.fromList [(register r, 0) | r <- [w, x, y, z]]
, inputs = []
}
Maximum model number = 96918996924991 : : Int64
Minimum model number = 91811241911641 : : Int64
puzzle :: Bool -> IO ()
puzzle shouldMaximize = print =<< optimizeWith z3{isNonModelVar = (/= finalVar)} Lexicographic problem
where finalVar | shouldMaximize = "Maximum model number"
| True = "Minimum model number"
problem = do State{env, inputs} <- run monad
constrain $ fromJust (register z `M.lookup` env) .== 0
let digits = reverse inputs
ST.forM_ digits $ \d -> constrain $ d `inRange` (1, 9)
let modelNum = foldl (\sofar d -> 10 * sofar + d) 0 digits
if shouldMaximize
then maximize "goal" modelNum
else minimize "goal" modelNum
modelNumV <- free finalVar
constrain $ modelNumV .== modelNum
| The program we need to crack . Note that different users get different programs on the Advent - Of - Code site , so this is simply one example .
You can simply cut - and - paste your version instead . ( Do n't forget the pragma @NegativeLiterals@ to GHC so @add x -1@ parses correctly as @add x ( -1)@. )
monad :: ALU ()
monad = do inp w
mul x 0
add x z
mod x 26
div z 1
add x 11
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 13
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 12
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 1
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 15
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 15
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 10
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 2
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -1
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 2
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 14
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 5
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -8
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 8
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -7
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 14
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -8
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 12
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 1
add x 11
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 7
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -2
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 14
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -2
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 13
mul y x
add z y
inp w
mul x 0
add x z
mod x 26
div z 26
add x -13
eql x w
eql x 0
mul y 0
add y 25
mul y x
add y 1
mul z y
mul y 0
add y w
add y 6
mul y x
add z y
# ANN module ( " HLint : ignore Reduce duplication " : : String ) #
|
085268034601b53b6f3f7f584b462cb25666ddca62526c53dfc834b1cd6b6a97 | MLanguage/mlang | parse_utils.mli | Copyright ( C ) 2019 - 2021 Inria , contributor :
< >
This program is free software : you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program . If not , see < / > .
<>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see </>. *)
(** Helpers for parsing *)
(** {1 Frontend variable names}*)
(** A parsed variable can be a regular variable or an integer literal *)
type parse_val = ParseVar of Mast.variable | ParseInt of int
val mk_position : Lexing.position * Lexing.position -> Pos.t
val parse_variable :
Lexing.position * Lexing.position -> string -> Mast.variable
(** Checks whether the variable contains parameters *)
val parse_variable_name : Lexing.position * Lexing.position -> string -> string
(** Checks whether the string is entirely capitalized *)
val parse_string : string -> string
(** Removes the quotes *)
val parse_variable_or_int :
Lexing.position * Lexing.position -> string -> parse_val
val parse_table_index :
Lexing.position * Lexing.position -> string -> Mast.table_index
(** Table index can be integer or [X], the generic table index variable *)
val parse_func_name : 'a -> string -> string
* { 1 Literal parsing }
val parse_int : Lexing.position * Lexing.position -> string -> int
(** Checks whether is it actually an integer*)
val parse_literal : Lexing.position * Lexing.position -> string -> Mast.literal
| null | https://raw.githubusercontent.com/MLanguage/mlang/a8749761a48b47e28ecc4a0390b3873615d2a9b5/src/mlang/m_frontend/parse_utils.mli | ocaml | * Helpers for parsing
* {1 Frontend variable names}
* A parsed variable can be a regular variable or an integer literal
* Checks whether the variable contains parameters
* Checks whether the string is entirely capitalized
* Removes the quotes
* Table index can be integer or [X], the generic table index variable
* Checks whether is it actually an integer | Copyright ( C ) 2019 - 2021 Inria , contributor :
< >
This program is free software : you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option ) any later
version .
This program is distributed in the hope that it will be useful , but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
this program . If not , see < / > .
<>
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program. If not, see </>. *)
type parse_val = ParseVar of Mast.variable | ParseInt of int
val mk_position : Lexing.position * Lexing.position -> Pos.t
val parse_variable :
Lexing.position * Lexing.position -> string -> Mast.variable
val parse_variable_name : Lexing.position * Lexing.position -> string -> string
val parse_string : string -> string
val parse_variable_or_int :
Lexing.position * Lexing.position -> string -> parse_val
val parse_table_index :
Lexing.position * Lexing.position -> string -> Mast.table_index
val parse_func_name : 'a -> string -> string
* { 1 Literal parsing }
val parse_int : Lexing.position * Lexing.position -> string -> int
val parse_literal : Lexing.position * Lexing.position -> string -> Mast.literal
|
058ae1d829cde9d96e38731783ef0d33c0842b8e67d7131e2dd3c0e172b6a12e | finnishtransportagency/harja | vkm_komponentti.clj | (ns harja.palvelin.integraatiot.vkm.vkm-komponentti
(:require [com.stuartsierra.component :as component]
[hiccup.core :refer [html]]
[taoensso.timbre :as log]
[harja.palvelin.integraatiot.integraatiotapahtuma :as integraatiotapahtuma]
[harja.palvelin.integraatiot.api.tyokalut.virheet :as virheet]
[harja.pvm :as pvm]
[cheshire.core :as cheshire]
[clojure.core :as core]
[clojure.string :as string])
(:use [slingshot.slingshot :only [throw+ try+]]))
(defprotocol Tieosoitemuunnos
(muunna-osoitteet-verkolta-toiselle
[this tieosoiteet]
"Muuntaa annetut tieosoitteet päivän verkolta toiselle. Jokaisella tieosoitteella täytyy olla mäpissä :vkm-id avain
kohdistamista varten."))
(defn- onko-lopun-tunniste? [tunniste]
(string/includes? tunniste "loppu"))
(defn yhdista-vkm-ajoradat
"VKM-vastauksesta saattaa tulla useampi ajorata per kohde, yhdistetään ne."
[vkm-osoitteet]
(mapv (fn [[tunniste kohteet]]
(if (= (count kohteet) 1)
(first kohteet)
(let [ensimmainen-kohde (first kohteet)]
(merge ensimmainen-kohde
{"ajorata" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "ajorata") kohteet))
"osa" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "osa") kohteet))
"etaisyys" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "etaisyys") kohteet))}))))
(group-by #(get % "tunniste") vkm-osoitteet)))
(defn- alku-ja-loppuosa-tunnisteet-tasmaa? [alkuosa loppuosa]
(let [alkuosan-tunniste (get alkuosa "tunniste")
loppuosan-tunniste (get loppuosa "tunniste" (:tunniste loppuosa))]
(and (=
(string/replace loppuosan-tunniste #"loppu" "alku")
alkuosan-tunniste)
(not= loppuosan-tunniste alkuosan-tunniste))))
(defn tunniste->yha-id
"Parsii yha-id:n tunnisteesta. Toimii sekä kohteen että alikohteen tunnisteille.
Oletetaan, että yha-id:ssä ei ole viivoja"
[tunniste]
(Integer/parseInt (second (reverse (string/split tunniste #"-")))))
(defn- vkm-palautusarvo->tieosoitteet [vkm-osoitteet tieosoitteet]
(map (fn [alkuosa]
(let [vkm-loppuosat (filter (partial alku-ja-loppuosa-tunnisteet-tasmaa? alkuosa) vkm-osoitteet)
_ (when (< 1 (count vkm-loppuosat))
(log/error "VKM Palautusarvoista löytyi useampi loppuosa alkukohteella!"))
vkm-loppuosa (first vkm-loppuosat)
alku-virheet (get alkuosa "virheet")
loppu-virheet (get vkm-loppuosa "virheet")
Muunnettavat tieosoitteet , palautetaan jos VKM : .
alku-tieosoite (first (filter #(= (:tunniste %) (get alkuosa "tunniste")) tieosoitteet))
loppu-tieosoite (first (filter (partial alku-ja-loppuosa-tunnisteet-tasmaa? alkuosa) tieosoitteet))]
(merge {:yha-id (tunniste->yha-id (get alkuosa "tunniste" (:tunniste alku-tieosoite)))
:tie (get alkuosa "tie" (:tie alku-tieosoite))
:aosa (get alkuosa "osa" (:osa alku-tieosoite))
:losa (get vkm-loppuosa "osa" (:osa loppu-tieosoite))
:aet (get alkuosa "etaisyys" (:etaisyys alku-tieosoite))
:let (get vkm-loppuosa "etaisyys" (:etaisyys loppu-tieosoite))}
(when (or alku-virheet loppu-virheet)
{:virheet
{:alku alku-virheet
:loppu loppu-virheet}}))))
(filter #(string/includes? (get % "tunniste") "alku") vkm-osoitteet)))
(defn osoitteet-vkm-vastauksesta [tieosoitteet vastaus]
(if vastaus
(let [osoitteet-vastauksesta (cheshire/decode vastaus)
vkm-osoitteet (mapv #(get % "properties") (get osoitteet-vastauksesta "features"))
yhdistetyt-vkm-osoitteet (-> vkm-osoitteet
(yhdista-vkm-ajoradat)
(vkm-palautusarvo->tieosoitteet tieosoitteet))]
yhdistetyt-vkm-osoitteet)
tieosoitteet))
(defn kohteen-tunnus [kohde teksti]
(str "kohde-" (:yha-id kohde) (when teksti "-") teksti))
(defn alikohteen-tunnus [kohde alikohde teksti]
(str "alikohde-" (:yha-id kohde) "-" (:yha-id alikohde) (when teksti "-") teksti))
(defn yllapitokohde->vkm-parametrit [kohteet tilannepvm kohdepvm]
"Hakee tieosoitteet kohteista ja niiden alikohteista."
(into []
(mapcat (fn [kohde]
(let [tr (:tierekisteriosoitevali kohde)]
(concat
[{:tunniste (kohteen-tunnus kohde "alku")
:tie (:tienumero tr)
:osa (:aosa tr)
:etaisyys (:aet tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}
{:tunniste (kohteen-tunnus kohde "loppu")
:tie (:tienumero tr)
:osa (:losa tr)
:etaisyys (:let tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}]
(mapcat (fn [alikohde]
(let [tr (:tierekisteriosoitevali alikohde)]
[{:tunniste (alikohteen-tunnus kohde alikohde "alku")
:tie (:tienumero tr)
:osa (:aosa tr)
:etaisyys (:aet tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}
{:tunniste (alikohteen-tunnus kohde alikohde "loppu")
:tie (:tienumero tr)
:osa (:losa tr)
:etaisyys (:let tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}]))
(:alikohteet kohde)))))
kohteet)))
(defn muunna-tieosoitteet-verkolta-toiselle [{:keys [db integraatioloki url]} tieosoitteet]
(when url
(let [url (str url "muunna")]
(try+
(integraatiotapahtuma/suorita-integraatio
db integraatioloki "vkm" "osoitemuunnos" nil
(fn [konteksti]
(let [parametrit {:json (cheshire/encode tieosoitteet)}
http-asetukset {:metodi :POST
:url url
:lomakedatana? true}
{vastaus :body} (integraatiotapahtuma/laheta konteksti :http http-asetukset parametrit)]
(osoitteet-vkm-vastauksesta tieosoitteet vastaus))))
(catch [:type virheet/+ulkoinen-kasittelyvirhe-koodi+] {:keys [virheet]}
false)))))
(defrecord VKM [url]
component/Lifecycle
(start [this]
(assoc this :url url))
(stop [this]
this)
Tieosoitemuunnos
(muunna-osoitteet-verkolta-toiselle [this tieosoitteet]
(muunna-tieosoitteet-verkolta-toiselle this tieosoitteet)))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/aa5c64044e47d65c85ca2fdb18f08a61f21a3548/src/clj/harja/palvelin/integraatiot/vkm/vkm_komponentti.clj | clojure | (ns harja.palvelin.integraatiot.vkm.vkm-komponentti
(:require [com.stuartsierra.component :as component]
[hiccup.core :refer [html]]
[taoensso.timbre :as log]
[harja.palvelin.integraatiot.integraatiotapahtuma :as integraatiotapahtuma]
[harja.palvelin.integraatiot.api.tyokalut.virheet :as virheet]
[harja.pvm :as pvm]
[cheshire.core :as cheshire]
[clojure.core :as core]
[clojure.string :as string])
(:use [slingshot.slingshot :only [throw+ try+]]))
(defprotocol Tieosoitemuunnos
(muunna-osoitteet-verkolta-toiselle
[this tieosoiteet]
"Muuntaa annetut tieosoitteet päivän verkolta toiselle. Jokaisella tieosoitteella täytyy olla mäpissä :vkm-id avain
kohdistamista varten."))
(defn- onko-lopun-tunniste? [tunniste]
(string/includes? tunniste "loppu"))
(defn yhdista-vkm-ajoradat
"VKM-vastauksesta saattaa tulla useampi ajorata per kohde, yhdistetään ne."
[vkm-osoitteet]
(mapv (fn [[tunniste kohteet]]
(if (= (count kohteet) 1)
(first kohteet)
(let [ensimmainen-kohde (first kohteet)]
(merge ensimmainen-kohde
{"ajorata" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "ajorata") kohteet))
"osa" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "osa") kohteet))
"etaisyys" (apply (if (onko-lopun-tunniste? tunniste) max min)
(mapv #(get % "etaisyys") kohteet))}))))
(group-by #(get % "tunniste") vkm-osoitteet)))
(defn- alku-ja-loppuosa-tunnisteet-tasmaa? [alkuosa loppuosa]
(let [alkuosan-tunniste (get alkuosa "tunniste")
loppuosan-tunniste (get loppuosa "tunniste" (:tunniste loppuosa))]
(and (=
(string/replace loppuosan-tunniste #"loppu" "alku")
alkuosan-tunniste)
(not= loppuosan-tunniste alkuosan-tunniste))))
(defn tunniste->yha-id
"Parsii yha-id:n tunnisteesta. Toimii sekä kohteen että alikohteen tunnisteille.
Oletetaan, että yha-id:ssä ei ole viivoja"
[tunniste]
(Integer/parseInt (second (reverse (string/split tunniste #"-")))))
(defn- vkm-palautusarvo->tieosoitteet [vkm-osoitteet tieosoitteet]
(map (fn [alkuosa]
(let [vkm-loppuosat (filter (partial alku-ja-loppuosa-tunnisteet-tasmaa? alkuosa) vkm-osoitteet)
_ (when (< 1 (count vkm-loppuosat))
(log/error "VKM Palautusarvoista löytyi useampi loppuosa alkukohteella!"))
vkm-loppuosa (first vkm-loppuosat)
alku-virheet (get alkuosa "virheet")
loppu-virheet (get vkm-loppuosa "virheet")
Muunnettavat tieosoitteet , palautetaan jos VKM : .
alku-tieosoite (first (filter #(= (:tunniste %) (get alkuosa "tunniste")) tieosoitteet))
loppu-tieosoite (first (filter (partial alku-ja-loppuosa-tunnisteet-tasmaa? alkuosa) tieosoitteet))]
(merge {:yha-id (tunniste->yha-id (get alkuosa "tunniste" (:tunniste alku-tieosoite)))
:tie (get alkuosa "tie" (:tie alku-tieosoite))
:aosa (get alkuosa "osa" (:osa alku-tieosoite))
:losa (get vkm-loppuosa "osa" (:osa loppu-tieosoite))
:aet (get alkuosa "etaisyys" (:etaisyys alku-tieosoite))
:let (get vkm-loppuosa "etaisyys" (:etaisyys loppu-tieosoite))}
(when (or alku-virheet loppu-virheet)
{:virheet
{:alku alku-virheet
:loppu loppu-virheet}}))))
(filter #(string/includes? (get % "tunniste") "alku") vkm-osoitteet)))
(defn osoitteet-vkm-vastauksesta [tieosoitteet vastaus]
(if vastaus
(let [osoitteet-vastauksesta (cheshire/decode vastaus)
vkm-osoitteet (mapv #(get % "properties") (get osoitteet-vastauksesta "features"))
yhdistetyt-vkm-osoitteet (-> vkm-osoitteet
(yhdista-vkm-ajoradat)
(vkm-palautusarvo->tieosoitteet tieosoitteet))]
yhdistetyt-vkm-osoitteet)
tieosoitteet))
(defn kohteen-tunnus [kohde teksti]
(str "kohde-" (:yha-id kohde) (when teksti "-") teksti))
(defn alikohteen-tunnus [kohde alikohde teksti]
(str "alikohde-" (:yha-id kohde) "-" (:yha-id alikohde) (when teksti "-") teksti))
(defn yllapitokohde->vkm-parametrit [kohteet tilannepvm kohdepvm]
"Hakee tieosoitteet kohteista ja niiden alikohteista."
(into []
(mapcat (fn [kohde]
(let [tr (:tierekisteriosoitevali kohde)]
(concat
[{:tunniste (kohteen-tunnus kohde "alku")
:tie (:tienumero tr)
:osa (:aosa tr)
:etaisyys (:aet tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}
{:tunniste (kohteen-tunnus kohde "loppu")
:tie (:tienumero tr)
:osa (:losa tr)
:etaisyys (:let tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}]
(mapcat (fn [alikohde]
(let [tr (:tierekisteriosoitevali alikohde)]
[{:tunniste (alikohteen-tunnus kohde alikohde "alku")
:tie (:tienumero tr)
:osa (:aosa tr)
:etaisyys (:aet tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}
{:tunniste (alikohteen-tunnus kohde alikohde "loppu")
:tie (:tienumero tr)
:osa (:losa tr)
:etaisyys (:let tr)
:ajorata (:ajorata tr)
:tilannepvm (pvm/pvm tilannepvm)
:kohdepvm (pvm/pvm kohdepvm)
:palautusarvot "2"}]))
(:alikohteet kohde)))))
kohteet)))
(defn muunna-tieosoitteet-verkolta-toiselle [{:keys [db integraatioloki url]} tieosoitteet]
(when url
(let [url (str url "muunna")]
(try+
(integraatiotapahtuma/suorita-integraatio
db integraatioloki "vkm" "osoitemuunnos" nil
(fn [konteksti]
(let [parametrit {:json (cheshire/encode tieosoitteet)}
http-asetukset {:metodi :POST
:url url
:lomakedatana? true}
{vastaus :body} (integraatiotapahtuma/laheta konteksti :http http-asetukset parametrit)]
(osoitteet-vkm-vastauksesta tieosoitteet vastaus))))
(catch [:type virheet/+ulkoinen-kasittelyvirhe-koodi+] {:keys [virheet]}
false)))))
(defrecord VKM [url]
component/Lifecycle
(start [this]
(assoc this :url url))
(stop [this]
this)
Tieosoitemuunnos
(muunna-osoitteet-verkolta-toiselle [this tieosoitteet]
(muunna-tieosoitteet-verkolta-toiselle this tieosoitteet)))
|
|
696c8299952177c8402e7c6e7cf9a1180c35d3922483132a0891d4ff42f34d05 | ayato-p/kuuga | project.clj | (defproject example "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[ayato_p/kuuga "0.1.0-SNAPSHOT"]
[hiccup "2.0.0-alpha1"]
[org.clojure/clojure "1.8.0"]
[ring "1.6.2"]]
:main ^:skip-aot example.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| null | https://raw.githubusercontent.com/ayato-p/kuuga/37035f30a0a17251109f88bad6cf14e060687ed7/examples/bootstrap/project.clj | clojure | (defproject example "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[ayato_p/kuuga "0.1.0-SNAPSHOT"]
[hiccup "2.0.0-alpha1"]
[org.clojure/clojure "1.8.0"]
[ring "1.6.2"]]
:main ^:skip-aot example.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
|
e1e6dadd11d482566313cf801a25f8e2d9648b34c1b199cf8119a0fb466374dd | wdebeaum/step | wide.lisp | ;;;;
W::WIDE
;;;;
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::WIDE
(wordfeats (W::MORPH (:FORMS (-ER))))
(SENSES
((meta-data :origin calo :entry-date 20031222 :change-date 20090731 :wn ("wide%3:00:00") :comments html-purchasing-cfellorpus)
(EXAMPLE "a wide road")
(LF-PARENT ONT::BROAD)
)
we want to use the no - premod meaning first
( ( meta - data : origin calo : entry - date 20031222 : change - date nil : wn ( " wide%3:00:00 " ) : comments html - purchasing - corpus )
( EXAMPLE " a 5 foot wide road " )
( LF - PARENT ONT::linear - D )
( )
( PREFERENCE 0.98 )
; )
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/wide.lisp | lisp |
) | W::WIDE
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::WIDE
(wordfeats (W::MORPH (:FORMS (-ER))))
(SENSES
((meta-data :origin calo :entry-date 20031222 :change-date 20090731 :wn ("wide%3:00:00") :comments html-purchasing-cfellorpus)
(EXAMPLE "a wide road")
(LF-PARENT ONT::BROAD)
)
we want to use the no - premod meaning first
( ( meta - data : origin calo : entry - date 20031222 : change - date nil : wn ( " wide%3:00:00 " ) : comments html - purchasing - corpus )
( EXAMPLE " a 5 foot wide road " )
( LF - PARENT ONT::linear - D )
( )
( PREFERENCE 0.98 )
)
)
))
|
aec4099a7284623cf73a73824d25fbdbb71136756d928d6e8b53856add7051ee | emilaxelsson/ag-graph | Variables.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
-- | A generic interface to constructs that bind or represent variables
module Variables
( IsVar (..)
, HasVars (..)
, EqConstr (..)
, alphaEq
) where
import qualified Data.Foldable as Foldable
import Data.Set (Set)
import qualified Data.Set as Set
import Tree
import Mapping
class IsVar v where
-- | Construct a variable from a fresh identifier
newVar :: Integer -> v
class (Functor f, IsVar v) => HasVars f v where
| Indicates whether the @f@ constructor is a variable .
isVar :: f a -> Maybe v
isVar _ = Nothing
-- | Construct a variable expression
mkVar :: v -> f a
| Indicates the set of variables bound by the @f@ constructor
-- for each argument of the constructor.
bindsVars :: Mapping m a => f a -> m (Set v)
bindsVars _ = Mapping.empty
| Rename the variables bound by the @f@ constructor
renameVars :: f (a, Set v) -> f a
renameVars f = fmap fst f
class EqConstr f where
eqConstr :: f a -> f a -> Bool
alphaEq' :: forall v f . (EqConstr f, HasVars f v, Traversable f, Eq v)
=> [(v,v)] -> Tree f -> Tree f -> Bool
alphaEq' env (In var1) (In var2)
| Just v1 <- isVar var1
, Just v2 <- isVar var2
= case (lookup v1 env, lookup v2 env') of
(Nothing, Nothing) -> v1==v2 -- Free variables
(Just v2', Just v1') -> v1==v1' && v2==v2'
_ -> False
where
env' = [(v2,v1) | (v1,v2) <- env]
alphaEq' env (In f) (In g)
= eqConstr f g
&& all (checkChildren env)
( zip
(Foldable.toList $ number f)
(Foldable.toList $ number g)
)
where
checkChildren :: [(v,v)] -> (Numbered (Tree f), Numbered (Tree f)) -> Bool
checkChildren env (Numbered i1 t1, Numbered i2 t2)
= length vs1 == length vs2 && alphaEq' (zip vs1 vs2 ++ env) t1 t2
where
vs1 = Set.toList $ lookupNumMap Set.empty i1 (bindsVars $ number f)
vs2 = Set.toList $ lookupNumMap Set.empty i2 (bindsVars $ number g)
-- | Alpha-equivalence
alphaEq :: forall proxy v f
. (EqConstr f, HasVars f v, Traversable f, Eq v)
=> proxy v -> Tree f -> Tree f -> Bool
alphaEq _ = alphaEq' ([] :: [(v,v)])
| null | https://raw.githubusercontent.com/emilaxelsson/ag-graph/50fb1ebb819e1ed0bd3b97e8a9f82bb9310e782f/src/Variables.hs | haskell | | A generic interface to constructs that bind or represent variables
| Construct a variable from a fresh identifier
| Construct a variable expression
for each argument of the constructor.
Free variables
| Alpha-equivalence | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
module Variables
( IsVar (..)
, HasVars (..)
, EqConstr (..)
, alphaEq
) where
import qualified Data.Foldable as Foldable
import Data.Set (Set)
import qualified Data.Set as Set
import Tree
import Mapping
class IsVar v where
newVar :: Integer -> v
class (Functor f, IsVar v) => HasVars f v where
| Indicates whether the @f@ constructor is a variable .
isVar :: f a -> Maybe v
isVar _ = Nothing
mkVar :: v -> f a
| Indicates the set of variables bound by the @f@ constructor
bindsVars :: Mapping m a => f a -> m (Set v)
bindsVars _ = Mapping.empty
| Rename the variables bound by the @f@ constructor
renameVars :: f (a, Set v) -> f a
renameVars f = fmap fst f
class EqConstr f where
eqConstr :: f a -> f a -> Bool
alphaEq' :: forall v f . (EqConstr f, HasVars f v, Traversable f, Eq v)
=> [(v,v)] -> Tree f -> Tree f -> Bool
alphaEq' env (In var1) (In var2)
| Just v1 <- isVar var1
, Just v2 <- isVar var2
= case (lookup v1 env, lookup v2 env') of
(Just v2', Just v1') -> v1==v1' && v2==v2'
_ -> False
where
env' = [(v2,v1) | (v1,v2) <- env]
alphaEq' env (In f) (In g)
= eqConstr f g
&& all (checkChildren env)
( zip
(Foldable.toList $ number f)
(Foldable.toList $ number g)
)
where
checkChildren :: [(v,v)] -> (Numbered (Tree f), Numbered (Tree f)) -> Bool
checkChildren env (Numbered i1 t1, Numbered i2 t2)
= length vs1 == length vs2 && alphaEq' (zip vs1 vs2 ++ env) t1 t2
where
vs1 = Set.toList $ lookupNumMap Set.empty i1 (bindsVars $ number f)
vs2 = Set.toList $ lookupNumMap Set.empty i2 (bindsVars $ number g)
alphaEq :: forall proxy v f
. (EqConstr f, HasVars f v, Traversable f, Eq v)
=> proxy v -> Tree f -> Tree f -> Bool
alphaEq _ = alphaEq' ([] :: [(v,v)])
|
88311f15f1f26412bff8fe8f46cd7308efddafda85f8d9899c496dd0f2184974 | lfe/lfe | lfe_internal.erl | Copyright ( c ) 2016 - 2021
%%
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.
File :
Author :
Purpose : Define Lisp Flavoured Erlang internals .
Define LFE internal , guards and other internal stuff .
-module(lfe_internal).
%% General library functions.
-export([is_bif/2,is_guard_bif/2,is_erl_bif/2,is_lfe_bif/2]).
-export([is_core_form/1,is_core_func/2]).
-export([is_type/2]).
%% -compile([export_all]).
%% is_bif(Name, Arity) -> bool().
%% is_guard_bif(Name, Arity) -> bool().
%% is_erl_bif(Name, Arity) -> bool().
%% Collected tests for valid BIFs in expressions and guards.
is_bif(Name, Ar) ->
is_core_func(Name, Ar)
%% orelse is_lfe_bif(Name, Ar)
orelse is_erl_bif(Name, Ar).
is_guard_bif(Op ,Ar) ->
erl_internal:guard_bif(Op, Ar)
orelse erl_internal:arith_op(Op, Ar)
orelse erl_internal:bool_op(Op, Ar)
orelse erl_internal:comp_op(Op, Ar).
is_erl_bif(Op, Ar) ->
erl_internal:bif(Op, Ar)
orelse erl_internal:arith_op(Op, Ar)
orelse erl_internal:bool_op(Op, Ar)
orelse erl_internal:comp_op(Op, Ar)
orelse erl_internal:list_op(Op, Ar)
orelse erl_internal:send_op(Op, Ar).
%% is_core_form(Form) -> bool().
Return true if Form ( name ) is one of the LFE core forms , else false .
Core data special forms .
is_core_form(quote) -> true;
is_core_form(cons) -> true;
is_core_form(car) -> true;
is_core_form(cdr) -> true;
is_core_form(list) -> true;
is_core_form(tuple) -> true;
is_core_form(tref) -> true;
is_core_form(tset) -> true;
is_core_form(binary) -> true;
is_core_form(map) -> true;
is_core_form(msiz) -> true;
is_core_form(mref) -> true;
is_core_form(mset) -> true;
is_core_form(mupd) -> true;
is_core_form(mrem) -> true;
is_core_form('map-size') -> true;
is_core_form('map-get') -> true;
is_core_form('map-set') -> true;
is_core_form('map-update') -> true;
is_core_form('map-remove') -> true;
Core record special forms .
is_core_form('record') -> true;
%% make-record has been deprecated but we sill accept it for now.
is_core_form('make-record') -> true;
is_core_form('is-record') -> true;
is_core_form('record-index') -> true;
is_core_form('record-field') -> true;
is_core_form('record-update') -> true;
Core struct special forms .
is_core_form('struct') -> true;
is_core_form('is-struct') -> true;
is_core_form('struct-field') -> true;
is_core_form('struct-update') -> true;
%% Function forms.
is_core_form(function) -> true;
Core closure special forms .
is_core_form(lambda) -> true;
is_core_form('match-lambda') -> true;
is_core_form('let') -> true;
is_core_form('let-function') -> true;
is_core_form('letrec-function') -> true;
is_core_form('let-macro') -> true;
Core control special forms .
is_core_form('progn') -> true;
is_core_form('if') -> true;
is_core_form('case') -> true;
is_core_form('receive') -> true;
is_core_form('catch') -> true;
is_core_form('try') -> true;
is_core_form('funcall') -> true;
is_core_form(call) -> true;
%% List/binary comprehensions.
is_core_form('lc') -> true;
is_core_form('list-comp') -> true;
is_core_form('bc') -> true;
is_core_form('binary-comp') -> true;
Core definition special forms .
is_core_form('eval-when-compile') -> true;
is_core_form('define-module') -> true;
is_core_form('extend-module') -> true;
is_core_form('define-type') -> true;
is_core_form('define-opaque-type') -> true;
is_core_form('define-function-spec') -> true;
is_core_form('define-function') -> true;
is_core_form('define-macro') -> true;
is_core_form('define-record') -> true;
is_core_form('define-struct') -> true;
%% And don't forget when.
is_core_form('when') -> true;
%% Everything else is not a core form.
is_core_form(_) -> false.
%% is_core_func(Name, Arity) -> bool().
Return true if Name / Arity is one of the LFE core functions , else
%% false. For those which can take multiple arguments we accept any
%% number and push checking to run time.
is_core_func(cons, 2) -> true;
is_core_func(car, 1) -> true;
is_core_func(cdr, 1) -> true;
is_core_func(list, Ar) when Ar >= 0 -> true;
is_core_func(tuple, Ar) when Ar >= 0 -> true;
is_core_func(tref, 2) -> true;
is_core_func(tset, 3) -> true;
is_core_func(binary, Ar) when Ar >= 0 -> true;
is_core_func(map, Ar) when Ar >= 0, (Ar rem 2) =:= 0 -> true;
is_core_func(msiz, 1) -> true;
is_core_func(mref, 2) -> true;
is_core_func(mset, Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func(mupd, Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func(mrem, Ar) when Ar >= 1 -> true;
is_core_func('map-size', 1) -> true;
is_core_func('map-get', 2) -> true;
is_core_func('map-set', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('map-update', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('map-remove', Ar) when Ar >= 1 -> true;
Core record special functions .
is_core_func('record', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
%% make-record has been deprecated but we sill accept it for now.
is_core_func('make-record', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('is-record', 2) -> true;
is_core_func('record-index', 2) -> true;
is_core_func('record-field', 3) -> true;
is_core_func('record-update', Ar) when Ar >= 2, (Ar rem 2) =:= 0 -> true;
Core struct special functions .
is_core_func('struct', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('is-struct', Ar) when Ar =:= 1; Ar =:= 2 -> true;
is_core_func('struct-field', 3) -> true;
is_core_func('struct-update', Ar) when Ar >= 2, (Ar rem 2) =:= 0 -> true;
%% List/binary comprehensions.
is_core_func('lc', 2) -> true;
is_core_func('list-comp', 2) -> true;
is_core_func('bc', 2) -> true;
is_core_func('binary-comp', 2) -> true;
Core control special functions .
is_core_func(funcall, Ar) when Ar >= 1 -> true;
is_core_func(call, Ar) when Ar >= 2 -> true;
is_core_func(_, _) -> false.
%% is_lfe_bif(Name, Arity) -> bool().
%% Return true if Name/Arity is one of the standard LFE bifs defined
%% in the lfe module.
is_lfe_bif(eval, 1) -> true;
is_lfe_bif(eval, 2) -> true;
is_lfe_bif('macro-function', 1) -> true;
is_lfe_bif('macro-function', 2) -> true;
is_lfe_bif(macroexpand, 1) -> true;
is_lfe_bif(macroexpand, 2) -> true;
is_lfe_bif('macroexpand-1', 1) -> true;
is_lfe_bif('macroexpand-1', 2) -> true;
is_lfe_bif('macroexpand-all', 1) -> true;
is_lfe_bif('macroexpand-all', 2) -> true;
is_lfe_bif(_, _) -> false.
%% is_type(NAme, Arity) -> bool().
%% Return true if Name/Arity is a predefined type.
is_type('UNION', Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(call, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(lambda, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(map, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(range, 2) -> true;
is_type(bitstring, 2) -> true;
is_type(tuple, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(Name, Arity) ->
erl_internal:is_type(Name, Arity).
| null | https://raw.githubusercontent.com/lfe/lfe/f333690822f696c4884726038dee3ce446c1c016/src/lfe_internal.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.
General library functions.
-compile([export_all]).
is_bif(Name, Arity) -> bool().
is_guard_bif(Name, Arity) -> bool().
is_erl_bif(Name, Arity) -> bool().
Collected tests for valid BIFs in expressions and guards.
orelse is_lfe_bif(Name, Ar)
is_core_form(Form) -> bool().
make-record has been deprecated but we sill accept it for now.
Function forms.
List/binary comprehensions.
And don't forget when.
Everything else is not a core form.
is_core_func(Name, Arity) -> bool().
false. For those which can take multiple arguments we accept any
number and push checking to run time.
make-record has been deprecated but we sill accept it for now.
List/binary comprehensions.
is_lfe_bif(Name, Arity) -> bool().
Return true if Name/Arity is one of the standard LFE bifs defined
in the lfe module.
is_type(NAme, Arity) -> bool().
Return true if Name/Arity is a predefined type. | Copyright ( c ) 2016 - 2021
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
File :
Author :
Purpose : Define Lisp Flavoured Erlang internals .
Define LFE internal , guards and other internal stuff .
-module(lfe_internal).
-export([is_bif/2,is_guard_bif/2,is_erl_bif/2,is_lfe_bif/2]).
-export([is_core_form/1,is_core_func/2]).
-export([is_type/2]).
is_bif(Name, Ar) ->
is_core_func(Name, Ar)
orelse is_erl_bif(Name, Ar).
is_guard_bif(Op ,Ar) ->
erl_internal:guard_bif(Op, Ar)
orelse erl_internal:arith_op(Op, Ar)
orelse erl_internal:bool_op(Op, Ar)
orelse erl_internal:comp_op(Op, Ar).
is_erl_bif(Op, Ar) ->
erl_internal:bif(Op, Ar)
orelse erl_internal:arith_op(Op, Ar)
orelse erl_internal:bool_op(Op, Ar)
orelse erl_internal:comp_op(Op, Ar)
orelse erl_internal:list_op(Op, Ar)
orelse erl_internal:send_op(Op, Ar).
Return true if Form ( name ) is one of the LFE core forms , else false .
Core data special forms .
is_core_form(quote) -> true;
is_core_form(cons) -> true;
is_core_form(car) -> true;
is_core_form(cdr) -> true;
is_core_form(list) -> true;
is_core_form(tuple) -> true;
is_core_form(tref) -> true;
is_core_form(tset) -> true;
is_core_form(binary) -> true;
is_core_form(map) -> true;
is_core_form(msiz) -> true;
is_core_form(mref) -> true;
is_core_form(mset) -> true;
is_core_form(mupd) -> true;
is_core_form(mrem) -> true;
is_core_form('map-size') -> true;
is_core_form('map-get') -> true;
is_core_form('map-set') -> true;
is_core_form('map-update') -> true;
is_core_form('map-remove') -> true;
Core record special forms .
is_core_form('record') -> true;
is_core_form('make-record') -> true;
is_core_form('is-record') -> true;
is_core_form('record-index') -> true;
is_core_form('record-field') -> true;
is_core_form('record-update') -> true;
Core struct special forms .
is_core_form('struct') -> true;
is_core_form('is-struct') -> true;
is_core_form('struct-field') -> true;
is_core_form('struct-update') -> true;
is_core_form(function) -> true;
Core closure special forms .
is_core_form(lambda) -> true;
is_core_form('match-lambda') -> true;
is_core_form('let') -> true;
is_core_form('let-function') -> true;
is_core_form('letrec-function') -> true;
is_core_form('let-macro') -> true;
Core control special forms .
is_core_form('progn') -> true;
is_core_form('if') -> true;
is_core_form('case') -> true;
is_core_form('receive') -> true;
is_core_form('catch') -> true;
is_core_form('try') -> true;
is_core_form('funcall') -> true;
is_core_form(call) -> true;
is_core_form('lc') -> true;
is_core_form('list-comp') -> true;
is_core_form('bc') -> true;
is_core_form('binary-comp') -> true;
Core definition special forms .
is_core_form('eval-when-compile') -> true;
is_core_form('define-module') -> true;
is_core_form('extend-module') -> true;
is_core_form('define-type') -> true;
is_core_form('define-opaque-type') -> true;
is_core_form('define-function-spec') -> true;
is_core_form('define-function') -> true;
is_core_form('define-macro') -> true;
is_core_form('define-record') -> true;
is_core_form('define-struct') -> true;
is_core_form('when') -> true;
is_core_form(_) -> false.
Return true if Name / Arity is one of the LFE core functions , else
is_core_func(cons, 2) -> true;
is_core_func(car, 1) -> true;
is_core_func(cdr, 1) -> true;
is_core_func(list, Ar) when Ar >= 0 -> true;
is_core_func(tuple, Ar) when Ar >= 0 -> true;
is_core_func(tref, 2) -> true;
is_core_func(tset, 3) -> true;
is_core_func(binary, Ar) when Ar >= 0 -> true;
is_core_func(map, Ar) when Ar >= 0, (Ar rem 2) =:= 0 -> true;
is_core_func(msiz, 1) -> true;
is_core_func(mref, 2) -> true;
is_core_func(mset, Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func(mupd, Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func(mrem, Ar) when Ar >= 1 -> true;
is_core_func('map-size', 1) -> true;
is_core_func('map-get', 2) -> true;
is_core_func('map-set', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('map-update', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('map-remove', Ar) when Ar >= 1 -> true;
Core record special functions .
is_core_func('record', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('make-record', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('is-record', 2) -> true;
is_core_func('record-index', 2) -> true;
is_core_func('record-field', 3) -> true;
is_core_func('record-update', Ar) when Ar >= 2, (Ar rem 2) =:= 0 -> true;
Core struct special functions .
is_core_func('struct', Ar) when Ar >= 1, (Ar rem 2) =:= 1 -> true;
is_core_func('is-struct', Ar) when Ar =:= 1; Ar =:= 2 -> true;
is_core_func('struct-field', 3) -> true;
is_core_func('struct-update', Ar) when Ar >= 2, (Ar rem 2) =:= 0 -> true;
is_core_func('lc', 2) -> true;
is_core_func('list-comp', 2) -> true;
is_core_func('bc', 2) -> true;
is_core_func('binary-comp', 2) -> true;
Core control special functions .
is_core_func(funcall, Ar) when Ar >= 1 -> true;
is_core_func(call, Ar) when Ar >= 2 -> true;
is_core_func(_, _) -> false.
is_lfe_bif(eval, 1) -> true;
is_lfe_bif(eval, 2) -> true;
is_lfe_bif('macro-function', 1) -> true;
is_lfe_bif('macro-function', 2) -> true;
is_lfe_bif(macroexpand, 1) -> true;
is_lfe_bif(macroexpand, 2) -> true;
is_lfe_bif('macroexpand-1', 1) -> true;
is_lfe_bif('macroexpand-1', 2) -> true;
is_lfe_bif('macroexpand-all', 1) -> true;
is_lfe_bif('macroexpand-all', 2) -> true;
is_lfe_bif(_, _) -> false.
is_type('UNION', Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(call, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(lambda, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(map, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(range, 2) -> true;
is_type(bitstring, 2) -> true;
is_type(tuple, Ar) -> is_integer(Ar) and (Ar >= 0);
is_type(Name, Arity) ->
erl_internal:is_type(Name, Arity).
|
981f8a8e8f5dca42539d61ce0af43b88418c26f57eb251c0c114d45fd870ba2d | camlp5/camlp5 | papr_phony_macro.ml | (* camlp5r *)
q_phony.ml , v
Copyright ( c ) INRIA 2007 - 2017
#directory ".";
#load "pa_extend.cmo";
#load "pa_extprint.cmo";
#load "q_MLast.cmo";
#load "pa_pprintf.cmo";
open Pcaml;
EXTEND
GLOBAL: str_item expr;
str_item: FIRST
[ [ x = macro_def -> <:str_item< $exp:x$ >> ] ]
;
expr: FIRST
[ [ x = macro_def -> x ] ]
;
macro_def:
[ [ "DEFINE"; i = UIDENT -> <:expr< DEFINE $uid:i$ >>
| "IFDEF"; e = dexpr; "THEN"; d = expr_or_macro; "END" ->
<:expr< if $e$ then $d$ else () >>
| "IFDEF"; e = dexpr; "THEN"; d1 = expr_or_macro; "ELSE";
d2 = expr_or_macro; "END" ->
<:expr< if $e$ then $d1$ else $d2$ >>
| "IFNDEF"; e = dexpr; "THEN"; d = expr_or_macro; "END" ->
<:expr< if $e$ then $d$ else () >>
| "IFNDEF"; e = dexpr; "THEN"; d1 = expr_or_macro; "ELSE";
d2 = expr_or_macro; "END" ->
<:expr< if $e$ then $d1$ else $d2$ >> ] ]
;
expr_or_macro:
[ [ d = macro_def -> d
| e = expr -> e ] ]
;
dexpr:
[ [ x = SELF; "OR"; y = SELF -> <:expr< $x$ || $y$ >> ]
| [ x = SELF; "AND"; y = SELF -> <:expr< $x$ && $y$ >> ]
| [ "NOT"; x = SELF -> <:expr< NOT $x$ >> ]
| [ i = UIDENT -> <:expr< $uid:i$ >>
| "("; x = SELF; ")" -> x ] ]
;
END;
#load "pa_extfun.cmo";
open Pretty;
open Pcaml;
open Prtools;
value expr = Eprinter.apply pr_expr;
value rec dexpr pc =
fun
[ <:expr< $x$ || $y$ >> -> pprintf pc "%p OR %p" dexpr x dexpr1 y
| z -> dexpr1 pc z ]
and dexpr1 pc =
fun
[ z -> dexpr2 pc z ]
and dexpr2 pc =
fun
[ z -> dexpr3 pc z ]
and dexpr3 pc =
fun
[ <:expr< $uid:i$ >> -> pprintf pc "%s" i
| _ -> pprintf pc "dexpr not impl" ]
;
value expr_or_macro pc =
fun
[ <:expr< DEFINE $uid:i$ >> -> pprintf pc "DEFINE %s" i
| e -> expr pc e ]
;
value macro_def pc =
fun
[ <:expr< IFDEF $e$ $d$ >> ->
pprintf pc "@[<a>IFDEF %p THEN@;%p@ END@]" dexpr e expr_or_macro d
| <:expr< IFDEF $e$ $d1$ $d2$ >> ->
pprintf pc "@[<a>IFDEF %p THEN@;%p@ ELSE@;%p@ END@]" dexpr e
expr_or_macro d1 expr_or_macro d2
| _ -> assert False ]
;
try
EXTEND_PRINTER
pr_expr: LEVEL "apply"
[ [ <:expr< IFDEF $_$ $_$ >> as z -> macro_def pc z
| <:expr< IFDEF $_$ $_$ $_$ >> as z -> macro_def pc z ] ]
;
END
with
[ Failure _ -> () ];
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/etc/papr_phony_macro.ml | ocaml | camlp5r | q_phony.ml , v
Copyright ( c ) INRIA 2007 - 2017
#directory ".";
#load "pa_extend.cmo";
#load "pa_extprint.cmo";
#load "q_MLast.cmo";
#load "pa_pprintf.cmo";
open Pcaml;
EXTEND
GLOBAL: str_item expr;
str_item: FIRST
[ [ x = macro_def -> <:str_item< $exp:x$ >> ] ]
;
expr: FIRST
[ [ x = macro_def -> x ] ]
;
macro_def:
[ [ "DEFINE"; i = UIDENT -> <:expr< DEFINE $uid:i$ >>
| "IFDEF"; e = dexpr; "THEN"; d = expr_or_macro; "END" ->
<:expr< if $e$ then $d$ else () >>
| "IFDEF"; e = dexpr; "THEN"; d1 = expr_or_macro; "ELSE";
d2 = expr_or_macro; "END" ->
<:expr< if $e$ then $d1$ else $d2$ >>
| "IFNDEF"; e = dexpr; "THEN"; d = expr_or_macro; "END" ->
<:expr< if $e$ then $d$ else () >>
| "IFNDEF"; e = dexpr; "THEN"; d1 = expr_or_macro; "ELSE";
d2 = expr_or_macro; "END" ->
<:expr< if $e$ then $d1$ else $d2$ >> ] ]
;
expr_or_macro:
[ [ d = macro_def -> d
| e = expr -> e ] ]
;
dexpr:
[ [ x = SELF; "OR"; y = SELF -> <:expr< $x$ || $y$ >> ]
| [ x = SELF; "AND"; y = SELF -> <:expr< $x$ && $y$ >> ]
| [ "NOT"; x = SELF -> <:expr< NOT $x$ >> ]
| [ i = UIDENT -> <:expr< $uid:i$ >>
| "("; x = SELF; ")" -> x ] ]
;
END;
#load "pa_extfun.cmo";
open Pretty;
open Pcaml;
open Prtools;
value expr = Eprinter.apply pr_expr;
value rec dexpr pc =
fun
[ <:expr< $x$ || $y$ >> -> pprintf pc "%p OR %p" dexpr x dexpr1 y
| z -> dexpr1 pc z ]
and dexpr1 pc =
fun
[ z -> dexpr2 pc z ]
and dexpr2 pc =
fun
[ z -> dexpr3 pc z ]
and dexpr3 pc =
fun
[ <:expr< $uid:i$ >> -> pprintf pc "%s" i
| _ -> pprintf pc "dexpr not impl" ]
;
value expr_or_macro pc =
fun
[ <:expr< DEFINE $uid:i$ >> -> pprintf pc "DEFINE %s" i
| e -> expr pc e ]
;
value macro_def pc =
fun
[ <:expr< IFDEF $e$ $d$ >> ->
pprintf pc "@[<a>IFDEF %p THEN@;%p@ END@]" dexpr e expr_or_macro d
| <:expr< IFDEF $e$ $d1$ $d2$ >> ->
pprintf pc "@[<a>IFDEF %p THEN@;%p@ ELSE@;%p@ END@]" dexpr e
expr_or_macro d1 expr_or_macro d2
| _ -> assert False ]
;
try
EXTEND_PRINTER
pr_expr: LEVEL "apply"
[ [ <:expr< IFDEF $_$ $_$ >> as z -> macro_def pc z
| <:expr< IFDEF $_$ $_$ $_$ >> as z -> macro_def pc z ] ]
;
END
with
[ Failure _ -> () ];
|
28514b798f5abb9c44cf6aaab4a849e78aed5e703562e05597cb9df1caefc3b2 | input-output-hk/cardano-wallet | Logging.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
-- |
Copyright : © 2018 - 2020 IOHK
-- License: Apache-2.0
--
-- This module contains utility functions for logging and mapping trace data.
module Cardano.Wallet.Logging
* Conversions from BM framework
trMessage
, trMessageText
-- * Formatting typed messages as plain text
, transformTextTrace
, stdoutTextTracer
-- * Logging helpers
, traceWithExceptT
, traceResult
, formatResultMsg
, formatResultMsgWith
, resultSeverity
-- * Logging and timing IO actions
, BracketLog
, BracketLog' (..)
, LoggedException (..)
, bracketTracer
, bracketTracer'
, produceTimings
-- * Tracer conversions
, unliftIOTracer
, flatContramapTracer
) where
import Prelude
import Cardano.BM.Data.LogItem
( LOContent (..), LogObject (..), LoggerName, mkLOMeta )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..)
, HasSeverityAnnotation (..)
, Transformable (..)
)
import Cardano.BM.Trace
( Trace )
import Control.DeepSeq
( NFData (..) )
import Control.Monad
( when )
import Control.Monad.Catch
( MonadMask )
import Control.Monad.IO.Unlift
( MonadIO (..), MonadUnliftIO )
import Control.Monad.Trans.Except
( ExceptT (..), runExceptT )
import Control.Tracer
( Tracer (..), contramap, natTracer, nullTracer, traceWith )
import Control.Tracer.Transformers.ObserveOutcome
( Outcome (..)
, OutcomeFidelity (..)
, OutcomeProgressionStatus (..)
, mkOutcomeExtractor
)
import Data.Aeson
( ToJSON (..), Value (Null), object, (.=) )
import Data.Foldable
( forM_ )
import Data.Functor
( ($>) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock
( DiffTime )
import Data.Time.Clock.System
( getSystemTime, systemToTAITime )
import Data.Time.Clock.TAI
( AbsoluteTime, diffAbsoluteTime )
import Fmt
( Buildable (..), Builder, blockListF, blockMapF, nameF )
import GHC.Exts
( IsList (..) )
import GHC.Generics
( Generic )
import UnliftIO.Exception
( Exception (..)
, SomeException (..)
, displayException
, isSyncException
, withException
)
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text.Encoding as T
| Converts a ' Text ' trace into any other type of trace that has a ' ToText '
-- instance.
transformTextTrace :: ToText a => Trace IO Text -> Trace IO a
transformTextTrace = contramap (fmap . fmap $ toText) . filterNonEmpty
| Tracer transformer which transforms traced items to their ' ToText '
representation and further traces them as a ' LogObject ' . If the ' '
-- representation is empty, then no tracing happens.
trMessageText
:: (MonadIO m, ToText a, HasPrivacyAnnotation a, HasSeverityAnnotation a)
=> Tracer m (LoggerName, LogObject Text)
-> Tracer m a
trMessageText tr = Tracer $ \arg -> do
let msg = toText arg
tracer = if msg == mempty then nullTracer else tr
meta <- mkLOMeta (getSeverityAnnotation arg) (getPrivacyAnnotation arg)
traceWith tracer (mempty, LogObject mempty meta (LogMessage msg))
| Tracer transformer which converts ' Trace m a ' to ' Tracer m a ' by wrapping
typed log messages into a ' LogObject ' .
trMessage
:: (MonadIO m, HasPrivacyAnnotation a, HasSeverityAnnotation a)
=> Tracer m (LoggerName, LogObject a)
-> Tracer m a
trMessage tr = Tracer $ \arg -> do
meta <- mkLOMeta (getSeverityAnnotation arg) (getPrivacyAnnotation arg)
traceWith tr (mempty, LogObject mempty meta (LogMessage arg))
instance forall m a. (MonadIO m, ToText a, HasPrivacyAnnotation a, HasSeverityAnnotation a) => Transformable Text m a where
trTransformer _verb = Tracer . traceWith . trMessageText
-- | Trace transformer which removes empty traces.
filterNonEmpty
:: forall m a. (Monad m, Monoid a, Eq a)
=> Trace m a
-> Trace m a
filterNonEmpty tr = Tracer $ \arg -> do
when (nonEmptyMessage $ loContent $ snd arg) $
traceWith tr arg
where
nonEmptyMessage (LogMessage msg) = msg /= mempty
nonEmptyMessage _ = True
| Creates a tracer that prints any ' ToText ' log message . This is useful for
debugging functions in the REPL , when you need a ' Tracer ' object .
stdoutTextTracer :: (MonadIO m, ToText a) => Tracer m a
stdoutTextTracer = Tracer $ liftIO . B8.putStrLn . T.encodeUtf8 . toText
{-------------------------------------------------------------------------------
Logging helpers
-------------------------------------------------------------------------------}
| Run an ' ExceptT ' action , then trace its result , all in one step .
-- This is a more basic version of 'resultTracer'.
traceWithExceptT :: Monad m => Tracer m (Either e a) -> ExceptT e m a -> ExceptT e m a
traceWithExceptT tr (ExceptT action) = ExceptT $ do
res <- action
traceWith tr res
pure res
-- | Log around an 'ExceptT' action. The result of the action is captured as an
-- 'Either' in the log message. Other unexpected exceptions are captured in the
-- 'BracketLog''.
traceResult
:: MonadUnliftIO m
=> Tracer m (BracketLog' (Either e r))
-> ExceptT e m r
-> ExceptT e m r
traceResult tr = ExceptT . bracketTracer' id tr . runExceptT
| Format a tracer message from ' ' as multiline text .
formatResultMsg
:: (Show e, IsList t, Item t ~ (Text, v), Buildable v, Buildable r)
=> Text
-- ^ Function name.
-> t
-- ^ Input parameters.
-> BracketLog' (Either e r)
-- ^ Logging around function.
-> Builder
formatResultMsg = formatResultMsgWith (nameF "ERROR" . build . show) build
-- | Same as 'formatResultMsg', but accepts result formatters as parameters.
formatResultMsgWith
:: (IsList t, Item t ~ (Text, v), Buildable v)
=> (e -> Builder)
-- ^ Error message formatter
-> (r -> Builder)
-- ^ Result formatter
-> Text
-- ^ Function name.
-> t
-- ^ Input parameters.
-> BracketLog' (Either e r)
-- ^ Logging around function.
-> Builder
formatResultMsgWith err fmt title params b = nameF (build title) $ blockListF
[ nameF "inputs" (blockMapF params)
, buildBracketLog (either err fmt) b
]
| A good default mapping of message severities for ' ' .
resultSeverity :: Severity -> BracketLog' (Either e r) -> Severity
resultSeverity base = \case
BracketStart -> base
BracketFinish (Left _) -> Error
BracketFinish (Right _) -> base
BracketException _ -> Error
BracketAsyncException _ -> base
------------------------------------------------------------------------------
Logging of Exceptions
------------------------------------------------------------------------------
Logging of Exceptions
-------------------------------------------------------------------------------}
-- | Exception wrapper with typeclass instances that exception types often don't
-- have.
newtype LoggedException e = LoggedException e
deriving (Generic, Show, Ord)
instance NFData e => NFData (LoggedException e)
instance NFData (LoggedException SomeException) where
rnf (LoggedException e) = rnf (show e)
instance Exception e => ToText (LoggedException e)
instance Exception e => Buildable (LoggedException e) where
build (LoggedException e) = build $ displayException e
instance Show e => Eq (LoggedException e) where
a == b = show a == show b
instance Exception e => ToJSON (LoggedException e) where
toJSON e = object ["exception" .= toText e]
exceptionMsg :: SomeException -> (BracketLog' r)
exceptionMsg e = if isSyncException e
then BracketException $ LoggedException e
else BracketAsyncException $ LoggedException e
------------------------------------------------------------------------------
Bracketed logging
------------------------------------------------------------------------------
Bracketed logging
-------------------------------------------------------------------------------}
-- | Used for tracing around an action.
data BracketLog' r
= BracketStart
-- ^ Logged before the action starts.
| BracketFinish r
-- ^ Logged after the action finishes.
| BracketException (LoggedException SomeException)
-- ^ Logged when the action throws an exception.
| BracketAsyncException (LoggedException SomeException)
-- ^ Logged when the action receives an async exception.
deriving (Generic, Show, Eq, ToJSON, Functor)
instance Buildable r => ToText (BracketLog' r)
instance Buildable r => Buildable (BracketLog' r) where
build = buildBracketLog build
buildBracketLog :: (t -> Builder) -> BracketLog' t -> Builder
buildBracketLog toBuilder = \case
BracketStart -> "start"
BracketFinish (toBuilder -> r)
| r == mempty -> "finish"
| otherwise -> "finish: " <> r
BracketException e -> "exception: " <> build e
BracketAsyncException e -> "cancelled: " <> build e
instance HasPrivacyAnnotation (BracketLog' r)
instance HasSeverityAnnotation (BracketLog' r) where
-- | Default severities for 'BracketLog' - the enclosing log message may of
-- course use different values.
getSeverityAnnotation = \case
BracketStart -> Debug
BracketFinish _ -> Debug
BracketException _ -> Error
BracketAsyncException _ -> Debug
-- | Placeholder for some unspecified result value in 'BracketLog' - it could be
@()@ , or anything else .
data SomeResult = SomeResult deriving (Generic, Show, Eq)
instance Buildable SomeResult where
build SomeResult = mempty
instance ToJSON SomeResult where
toJSON SomeResult = Null
-- | Trace around an action, where the result doesn't matter.
type BracketLog = BracketLog' SomeResult
-- | Run a monadic action with 'BracketLog' traced around it.
bracketTracer :: MonadUnliftIO m => Tracer m BracketLog -> m a -> m a
bracketTracer = bracketTracer'' id (const SomeResult)
-- | Run a monadic action with 'BracketLog' traced around it.
bracketTracer'
:: MonadUnliftIO m
=> (r -> a)
-- ^ Transform value into log message.
-> Tracer m (BracketLog' a)
^ Tracer .
-> m r
-- ^ Action.
-> m r
bracketTracer' = bracketTracer'' id
-- | Run a monadic action with 'BracketLog' traced around it.
bracketTracer''
:: MonadUnliftIO m
=> (b -> r)
-- ^ Transform value into result.
-> (b -> a)
-- ^ Transform value into log message.
-> Tracer m (BracketLog' a)
^ Tracer .
-> m b
-- ^ Action to produce value.
-> m r
bracketTracer'' res msg tr action = do
traceWith tr BracketStart
withException
(action >>= \val -> traceWith tr (BracketFinish (msg val)) $> res val)
(traceWith tr . exceptionMsg)
instance MonadIO m => Outcome m (BracketLog' r) where
type IntermediateValue (BracketLog' r) = AbsoluteTime
type OutcomeMetric (BracketLog' r) = DiffTime
classifyObservable = pure . \case
BracketStart -> OutcomeStarts
BracketFinish _ -> OutcomeEnds
BracketException _ -> OutcomeEnds
BracketAsyncException _ -> OutcomeEnds
NOTE : The functions are required so that measurements are
-- correct at times when leap seconds are applied. This is following the
-- tracer-transformers example.
captureObservableValue _ = systemToTAITime <$> liftIO getSystemTime
computeOutcomeMetric _ x y = pure $ diffAbsoluteTime y x
-- Pair up bracketlogs with some context information
instance MonadIO m => Outcome m (ctx, BracketLog) where
type IntermediateValue (ctx, BracketLog) = (ctx, IntermediateValue BracketLog)
type OutcomeMetric (ctx, BracketLog) = (ctx, OutcomeMetric BracketLog)
classifyObservable (_ctx, b) = classifyObservable b
captureObservableValue (ctx, b) =
(ctx,) <$> captureObservableValue b
computeOutcomeMetric (ctx, b) (_, x) (_, y) =
(ctx,) <$> computeOutcomeMetric b x y
-- | Get metric results from 'mkOutcomeExtractor' and throw away the rest.
fiddleOutcome
:: Monad m
=> Tracer m (ctx, DiffTime)
-> Tracer m (Either (ctx, BracketLog) (OutcomeFidelity (ctx, DiffTime)))
fiddleOutcome tr = Tracer $ \case
Right (ProgressedNormally dt) -> runTracer tr dt
_ -> pure ()
-- | Simplified wrapper for 'mkOutcomeExtractor'. This produces a timings
' Tracer ' from a ' Tracer ' of messages @a@ , and a function which can extract
the ' BracketLog ' from
--
-- The extractor function can provide @ctx@, which could be the name of the
-- timed operation for example.
--
-- The produced tracer will make just one trace for each finished bracket.
-- It contains the @ctx@ from the extractor and the time difference.
produceTimings
:: (MonadUnliftIO m, MonadMask m)
=> (a -> Maybe (ctx, BracketLog))
-- ^ Function to extract BracketLog messages from @a@, paired with context.
-> Tracer m (ctx, DiffTime)
-- ^ The timings tracer, has time deltas for each finished bracket.
-> m (Tracer m a)
produceTimings f trDiffTime = do
extractor <- mkOutcomeExtractor
let trOutcome = fiddleOutcome trDiffTime
trBracket = extractor trOutcome
tr = flatContramapTracer f trBracket
pure tr
------------------------------------------------------------------------------
Tracer conversions
------------------------------------------------------------------------------
Tracer conversions
-------------------------------------------------------------------------------}
| Convert an IO tracer to a ' m ' tracer .
unliftIOTracer :: MonadIO m => Tracer IO a -> Tracer m a
unliftIOTracer = natTracer liftIO
| Conditional mapping of a ' Tracer ' .
flatContramapTracer
:: Monad m
=> (a -> Maybe b)
-> Tracer m b
-> Tracer m a
flatContramapTracer p tr = Tracer $ \a -> forM_ (p a) (runTracer tr)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/7b541e0b11fdd69b30d94104dbd5fa633ff1d5c3/lib/wallet/src/Cardano/Wallet/Logging.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE RankNTypes #
|
License: Apache-2.0
This module contains utility functions for logging and mapping trace data.
* Formatting typed messages as plain text
* Logging helpers
* Logging and timing IO actions
* Tracer conversions
instance.
representation is empty, then no tracing happens.
| Trace transformer which removes empty traces.
------------------------------------------------------------------------------
Logging helpers
------------------------------------------------------------------------------
This is a more basic version of 'resultTracer'.
| Log around an 'ExceptT' action. The result of the action is captured as an
'Either' in the log message. Other unexpected exceptions are captured in the
'BracketLog''.
^ Function name.
^ Input parameters.
^ Logging around function.
| Same as 'formatResultMsg', but accepts result formatters as parameters.
^ Error message formatter
^ Result formatter
^ Function name.
^ Input parameters.
^ Logging around function.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Exception wrapper with typeclass instances that exception types often don't
have.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Used for tracing around an action.
^ Logged before the action starts.
^ Logged after the action finishes.
^ Logged when the action throws an exception.
^ Logged when the action receives an async exception.
| Default severities for 'BracketLog' - the enclosing log message may of
course use different values.
| Placeholder for some unspecified result value in 'BracketLog' - it could be
| Trace around an action, where the result doesn't matter.
| Run a monadic action with 'BracketLog' traced around it.
| Run a monadic action with 'BracketLog' traced around it.
^ Transform value into log message.
^ Action.
| Run a monadic action with 'BracketLog' traced around it.
^ Transform value into result.
^ Transform value into log message.
^ Action to produce value.
correct at times when leap seconds are applied. This is following the
tracer-transformers example.
Pair up bracketlogs with some context information
| Get metric results from 'mkOutcomeExtractor' and throw away the rest.
| Simplified wrapper for 'mkOutcomeExtractor'. This produces a timings
The extractor function can provide @ctx@, which could be the name of the
timed operation for example.
The produced tracer will make just one trace for each finished bracket.
It contains the @ctx@ from the extractor and the time difference.
^ Function to extract BracketLog messages from @a@, paired with context.
^ The timings tracer, has time deltas for each finished bracket.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------} | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
Copyright : © 2018 - 2020 IOHK
module Cardano.Wallet.Logging
* Conversions from BM framework
trMessage
, trMessageText
, transformTextTrace
, stdoutTextTracer
, traceWithExceptT
, traceResult
, formatResultMsg
, formatResultMsgWith
, resultSeverity
, BracketLog
, BracketLog' (..)
, LoggedException (..)
, bracketTracer
, bracketTracer'
, produceTimings
, unliftIOTracer
, flatContramapTracer
) where
import Prelude
import Cardano.BM.Data.LogItem
( LOContent (..), LogObject (..), LoggerName, mkLOMeta )
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..)
, HasSeverityAnnotation (..)
, Transformable (..)
)
import Cardano.BM.Trace
( Trace )
import Control.DeepSeq
( NFData (..) )
import Control.Monad
( when )
import Control.Monad.Catch
( MonadMask )
import Control.Monad.IO.Unlift
( MonadIO (..), MonadUnliftIO )
import Control.Monad.Trans.Except
( ExceptT (..), runExceptT )
import Control.Tracer
( Tracer (..), contramap, natTracer, nullTracer, traceWith )
import Control.Tracer.Transformers.ObserveOutcome
( Outcome (..)
, OutcomeFidelity (..)
, OutcomeProgressionStatus (..)
, mkOutcomeExtractor
)
import Data.Aeson
( ToJSON (..), Value (Null), object, (.=) )
import Data.Foldable
( forM_ )
import Data.Functor
( ($>) )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock
( DiffTime )
import Data.Time.Clock.System
( getSystemTime, systemToTAITime )
import Data.Time.Clock.TAI
( AbsoluteTime, diffAbsoluteTime )
import Fmt
( Buildable (..), Builder, blockListF, blockMapF, nameF )
import GHC.Exts
( IsList (..) )
import GHC.Generics
( Generic )
import UnliftIO.Exception
( Exception (..)
, SomeException (..)
, displayException
, isSyncException
, withException
)
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text.Encoding as T
| Converts a ' Text ' trace into any other type of trace that has a ' ToText '
transformTextTrace :: ToText a => Trace IO Text -> Trace IO a
transformTextTrace = contramap (fmap . fmap $ toText) . filterNonEmpty
| Tracer transformer which transforms traced items to their ' ToText '
representation and further traces them as a ' LogObject ' . If the ' '
trMessageText
:: (MonadIO m, ToText a, HasPrivacyAnnotation a, HasSeverityAnnotation a)
=> Tracer m (LoggerName, LogObject Text)
-> Tracer m a
trMessageText tr = Tracer $ \arg -> do
let msg = toText arg
tracer = if msg == mempty then nullTracer else tr
meta <- mkLOMeta (getSeverityAnnotation arg) (getPrivacyAnnotation arg)
traceWith tracer (mempty, LogObject mempty meta (LogMessage msg))
| Tracer transformer which converts ' Trace m a ' to ' Tracer m a ' by wrapping
typed log messages into a ' LogObject ' .
trMessage
:: (MonadIO m, HasPrivacyAnnotation a, HasSeverityAnnotation a)
=> Tracer m (LoggerName, LogObject a)
-> Tracer m a
trMessage tr = Tracer $ \arg -> do
meta <- mkLOMeta (getSeverityAnnotation arg) (getPrivacyAnnotation arg)
traceWith tr (mempty, LogObject mempty meta (LogMessage arg))
instance forall m a. (MonadIO m, ToText a, HasPrivacyAnnotation a, HasSeverityAnnotation a) => Transformable Text m a where
trTransformer _verb = Tracer . traceWith . trMessageText
filterNonEmpty
:: forall m a. (Monad m, Monoid a, Eq a)
=> Trace m a
-> Trace m a
filterNonEmpty tr = Tracer $ \arg -> do
when (nonEmptyMessage $ loContent $ snd arg) $
traceWith tr arg
where
nonEmptyMessage (LogMessage msg) = msg /= mempty
nonEmptyMessage _ = True
| Creates a tracer that prints any ' ToText ' log message . This is useful for
debugging functions in the REPL , when you need a ' Tracer ' object .
stdoutTextTracer :: (MonadIO m, ToText a) => Tracer m a
stdoutTextTracer = Tracer $ liftIO . B8.putStrLn . T.encodeUtf8 . toText
| Run an ' ExceptT ' action , then trace its result , all in one step .
traceWithExceptT :: Monad m => Tracer m (Either e a) -> ExceptT e m a -> ExceptT e m a
traceWithExceptT tr (ExceptT action) = ExceptT $ do
res <- action
traceWith tr res
pure res
traceResult
:: MonadUnliftIO m
=> Tracer m (BracketLog' (Either e r))
-> ExceptT e m r
-> ExceptT e m r
traceResult tr = ExceptT . bracketTracer' id tr . runExceptT
| Format a tracer message from ' ' as multiline text .
formatResultMsg
:: (Show e, IsList t, Item t ~ (Text, v), Buildable v, Buildable r)
=> Text
-> t
-> BracketLog' (Either e r)
-> Builder
formatResultMsg = formatResultMsgWith (nameF "ERROR" . build . show) build
formatResultMsgWith
:: (IsList t, Item t ~ (Text, v), Buildable v)
=> (e -> Builder)
-> (r -> Builder)
-> Text
-> t
-> BracketLog' (Either e r)
-> Builder
formatResultMsgWith err fmt title params b = nameF (build title) $ blockListF
[ nameF "inputs" (blockMapF params)
, buildBracketLog (either err fmt) b
]
| A good default mapping of message severities for ' ' .
resultSeverity :: Severity -> BracketLog' (Either e r) -> Severity
resultSeverity base = \case
BracketStart -> base
BracketFinish (Left _) -> Error
BracketFinish (Right _) -> base
BracketException _ -> Error
BracketAsyncException _ -> base
Logging of Exceptions
Logging of Exceptions
newtype LoggedException e = LoggedException e
deriving (Generic, Show, Ord)
instance NFData e => NFData (LoggedException e)
instance NFData (LoggedException SomeException) where
rnf (LoggedException e) = rnf (show e)
instance Exception e => ToText (LoggedException e)
instance Exception e => Buildable (LoggedException e) where
build (LoggedException e) = build $ displayException e
instance Show e => Eq (LoggedException e) where
a == b = show a == show b
instance Exception e => ToJSON (LoggedException e) where
toJSON e = object ["exception" .= toText e]
exceptionMsg :: SomeException -> (BracketLog' r)
exceptionMsg e = if isSyncException e
then BracketException $ LoggedException e
else BracketAsyncException $ LoggedException e
Bracketed logging
Bracketed logging
data BracketLog' r
= BracketStart
| BracketFinish r
| BracketException (LoggedException SomeException)
| BracketAsyncException (LoggedException SomeException)
deriving (Generic, Show, Eq, ToJSON, Functor)
instance Buildable r => ToText (BracketLog' r)
instance Buildable r => Buildable (BracketLog' r) where
build = buildBracketLog build
buildBracketLog :: (t -> Builder) -> BracketLog' t -> Builder
buildBracketLog toBuilder = \case
BracketStart -> "start"
BracketFinish (toBuilder -> r)
| r == mempty -> "finish"
| otherwise -> "finish: " <> r
BracketException e -> "exception: " <> build e
BracketAsyncException e -> "cancelled: " <> build e
instance HasPrivacyAnnotation (BracketLog' r)
instance HasSeverityAnnotation (BracketLog' r) where
getSeverityAnnotation = \case
BracketStart -> Debug
BracketFinish _ -> Debug
BracketException _ -> Error
BracketAsyncException _ -> Debug
@()@ , or anything else .
data SomeResult = SomeResult deriving (Generic, Show, Eq)
instance Buildable SomeResult where
build SomeResult = mempty
instance ToJSON SomeResult where
toJSON SomeResult = Null
type BracketLog = BracketLog' SomeResult
bracketTracer :: MonadUnliftIO m => Tracer m BracketLog -> m a -> m a
bracketTracer = bracketTracer'' id (const SomeResult)
bracketTracer'
:: MonadUnliftIO m
=> (r -> a)
-> Tracer m (BracketLog' a)
^ Tracer .
-> m r
-> m r
bracketTracer' = bracketTracer'' id
bracketTracer''
:: MonadUnliftIO m
=> (b -> r)
-> (b -> a)
-> Tracer m (BracketLog' a)
^ Tracer .
-> m b
-> m r
bracketTracer'' res msg tr action = do
traceWith tr BracketStart
withException
(action >>= \val -> traceWith tr (BracketFinish (msg val)) $> res val)
(traceWith tr . exceptionMsg)
instance MonadIO m => Outcome m (BracketLog' r) where
type IntermediateValue (BracketLog' r) = AbsoluteTime
type OutcomeMetric (BracketLog' r) = DiffTime
classifyObservable = pure . \case
BracketStart -> OutcomeStarts
BracketFinish _ -> OutcomeEnds
BracketException _ -> OutcomeEnds
BracketAsyncException _ -> OutcomeEnds
NOTE : The functions are required so that measurements are
captureObservableValue _ = systemToTAITime <$> liftIO getSystemTime
computeOutcomeMetric _ x y = pure $ diffAbsoluteTime y x
instance MonadIO m => Outcome m (ctx, BracketLog) where
type IntermediateValue (ctx, BracketLog) = (ctx, IntermediateValue BracketLog)
type OutcomeMetric (ctx, BracketLog) = (ctx, OutcomeMetric BracketLog)
classifyObservable (_ctx, b) = classifyObservable b
captureObservableValue (ctx, b) =
(ctx,) <$> captureObservableValue b
computeOutcomeMetric (ctx, b) (_, x) (_, y) =
(ctx,) <$> computeOutcomeMetric b x y
fiddleOutcome
:: Monad m
=> Tracer m (ctx, DiffTime)
-> Tracer m (Either (ctx, BracketLog) (OutcomeFidelity (ctx, DiffTime)))
fiddleOutcome tr = Tracer $ \case
Right (ProgressedNormally dt) -> runTracer tr dt
_ -> pure ()
' Tracer ' from a ' Tracer ' of messages @a@ , and a function which can extract
the ' BracketLog ' from
produceTimings
:: (MonadUnliftIO m, MonadMask m)
=> (a -> Maybe (ctx, BracketLog))
-> Tracer m (ctx, DiffTime)
-> m (Tracer m a)
produceTimings f trDiffTime = do
extractor <- mkOutcomeExtractor
let trOutcome = fiddleOutcome trDiffTime
trBracket = extractor trOutcome
tr = flatContramapTracer f trBracket
pure tr
Tracer conversions
Tracer conversions
| Convert an IO tracer to a ' m ' tracer .
unliftIOTracer :: MonadIO m => Tracer IO a -> Tracer m a
unliftIOTracer = natTracer liftIO
| Conditional mapping of a ' Tracer ' .
flatContramapTracer
:: Monad m
=> (a -> Maybe b)
-> Tracer m b
-> Tracer m a
flatContramapTracer p tr = Tracer $ \a -> forM_ (p a) (runTracer tr)
|
3d3b7a142136ff7ba5925f4dfb0b5e269362404adc723dc1adefbe6e7fd69018 | well-typed/optics | Magic.hs | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE UndecidableInstances #
# OPTIONS_HADDOCK not - home #
-- | This module is intended for internal use only, and may change without
-- warning in subsequent releases.
module Optics.Internal.Magic where
-- | How about a magic trick? I'm gonna make the coverage condition disappear.
class Dysfunctional field k s t a b | field s -> k t a b
, field t -> k s a b
-- | Show something useful when type inference goes into a loop and stops with
-- "reduction stack overflow" message (sometimes happens when trying to infer
-- types of local bindings when monomorphism restriction is enabled).
instance
( TypeInferenceLoop
"Type inference for the local binding failed. Write the type"
"signature yourself or disable monomorphism restriction with"
"NoMonomorphismRestriction LANGUAGE pragma so GHC infers it."
field k s t a b
) => Dysfunctional field k s t a b
class TypeInferenceLoop msg1 msg2 msg3 field k s t a b | field s -> k t a b
, field t -> k s a b
-- | Including the instance head in the context lifts the coverage condition for
-- all type variables in the instance. A dirty trick until we have
-- -proposals/ghc-proposals/pull/374 and can do it
-- properly.
instance
( TypeInferenceLoop msg1 msg2 msg3 field k s t a b
) => TypeInferenceLoop msg1 msg2 msg3 field k s t a b
| null | https://raw.githubusercontent.com/well-typed/optics/7cc3f9c334cdf69feaf10f58b11d3dbe2f98812c/optics-core/src/Optics/Internal/Magic.hs | haskell | | This module is intended for internal use only, and may change without
warning in subsequent releases.
| How about a magic trick? I'm gonna make the coverage condition disappear.
| Show something useful when type inference goes into a loop and stops with
"reduction stack overflow" message (sometimes happens when trying to infer
types of local bindings when monomorphism restriction is enabled).
| Including the instance head in the context lifts the coverage condition for
all type variables in the instance. A dirty trick until we have
-proposals/ghc-proposals/pull/374 and can do it
properly. | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE UndecidableInstances #
# OPTIONS_HADDOCK not - home #
module Optics.Internal.Magic where
class Dysfunctional field k s t a b | field s -> k t a b
, field t -> k s a b
instance
( TypeInferenceLoop
"Type inference for the local binding failed. Write the type"
"signature yourself or disable monomorphism restriction with"
"NoMonomorphismRestriction LANGUAGE pragma so GHC infers it."
field k s t a b
) => Dysfunctional field k s t a b
class TypeInferenceLoop msg1 msg2 msg3 field k s t a b | field s -> k t a b
, field t -> k s a b
instance
( TypeInferenceLoop msg1 msg2 msg3 field k s t a b
) => TypeInferenceLoop msg1 msg2 msg3 field k s t a b
|
55f1f1c338901f45e1eb2f0c8df9968db34a0a65bc898473deb298cdb2fa6f41 | jumarko/clojure-experiments | day_06.clj | (ns clojure-experiments.advent-of-code.advent-2022.day-06
"
Input:
Parsing signal - looking for start-of-packet marker (4 unique characters)
"
(:require
[clojure-experiments.advent-of-code.advent-2022.utils :as utils]
[clojure-experiments.macros.macros :refer [assert=]]))
(def input (first (utils/read-input "06")))
(def sample-input "mjqjpqmgbljsphdztnvjfqwrcgsmlb")
;;; Part 1
(defn packet-start [signal-code]
(reduce (fn [[index prefix :as acc] ch]
(if (= 4 (count (set prefix)))
;; they are all unique
(reduced acc)
[(inc index)
(str (subs prefix (if (= 4 (count prefix)) 1 0))
ch)]))
[0 ""]
signal-code))
(packet-start sample-input)
= > [ 7 " jpqm " ]
(defn start-of-packet [signal-code]
(first (packet-start signal-code)))
(assert= 7 (start-of-packet sample-input))
;; some more examples:
(assert= 5 (start-of-packet "bvwbjplbgvbhsrlpgdmjqwftvncz"))
(assert= 6 (start-of-packet "nppdvjthqldpwncqszvftbrmjlhg"))
(assert= 10 (start-of-packet "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"))
(assert= 11 (start-of-packet "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
Part 1 solution :
(assert= 1134 (start-of-packet input))
Part 2 :
You also need to look at start - of - message marker , that is 14 distinct characters .
;; let's modify `packet-start` slightly to make the length of the prefix dynamic
(defn message-start [signal-code prefix-length]
(reduce (fn [[index prefix :as acc] ch]
(if (= prefix-length (count (set prefix)))
;; they are all unique
(reduced acc)
[(inc index)
(str (subs prefix (if (= prefix-length (count prefix)) 1 0))
ch)]))
[0 ""]
signal-code))
(defn start-of-packet [signal-code]
(first (message-start signal-code 4)))
(assert= 11 (start-of-packet "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
(defn start-of-message [signal-code]
(first (message-start signal-code 14)))
(assert= 19 (start-of-message sample-input))
;; some more examples:
(assert= 23 (start-of-message "bvwbjplbgvbhsrlpgdmjqwftvncz"))
(assert= 23 (start-of-message "nppdvjthqldpwncqszvftbrmjlhg"))
(assert= 29 (start-of-message "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"))
(assert= 26 (start-of-message "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
Part 2 solution :
(assert= 2263 (start-of-message input))
;;; Try an alternative implementation
;; map-indexed with multiple arguments could work, right?
;; - except that `map-indexed` doesn't take multiple collections
;; => so just `map`
(defn message-start [signal-code prefix-length]
(->> (apply map (fn [i & chars] (when (= (count chars) (count (set chars)))
[i (apply str chars)]))
(range prefix-length (count signal-code))
(take prefix-length (iterate next signal-code)))
(remove nil?)
first))
(message-start sample-input 4)
= > [ 7 " jpqm " ]
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
;; Even simpler version using `partition`
(take 4 (partition 4 1 sample-input))
= > ( ( \m \j \q \j ) ( \j \q \j ) ( \q \j \q ) ( \j \m ) )
(defn message-start [signal-code prefix-length]
(->> (map-indexed (fn [i chars]
(when (= (count chars) (count (set chars)))
[(+ i prefix-length) (apply str chars)]))
(partition prefix-length 1 signal-code))
(remove nil?)
first))
(message-start sample-input 4)
= > [ 7 " jpqm " ]
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
;; even simpler is to use `keep-indexed`
(defn message-start [signal-code prefix-length]
(first (keep-indexed (fn [i chars]
(when (= (count chars) (count (set chars)))
[(+ i prefix-length) (apply str chars)]))
(partition prefix-length 1 signal-code))))
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/6ef2589bd6415a56581169a94d98beb2a4796400/src/clojure_experiments/advent_of_code/advent_2022/day_06.clj | clojure | Part 1
they are all unique
some more examples:
let's modify `packet-start` slightly to make the length of the prefix dynamic
they are all unique
some more examples:
Try an alternative implementation
map-indexed with multiple arguments could work, right?
- except that `map-indexed` doesn't take multiple collections
=> so just `map`
Even simpler version using `partition`
even simpler is to use `keep-indexed` | (ns clojure-experiments.advent-of-code.advent-2022.day-06
"
Input:
Parsing signal - looking for start-of-packet marker (4 unique characters)
"
(:require
[clojure-experiments.advent-of-code.advent-2022.utils :as utils]
[clojure-experiments.macros.macros :refer [assert=]]))
(def input (first (utils/read-input "06")))
(def sample-input "mjqjpqmgbljsphdztnvjfqwrcgsmlb")
(defn packet-start [signal-code]
(reduce (fn [[index prefix :as acc] ch]
(if (= 4 (count (set prefix)))
(reduced acc)
[(inc index)
(str (subs prefix (if (= 4 (count prefix)) 1 0))
ch)]))
[0 ""]
signal-code))
(packet-start sample-input)
= > [ 7 " jpqm " ]
(defn start-of-packet [signal-code]
(first (packet-start signal-code)))
(assert= 7 (start-of-packet sample-input))
(assert= 5 (start-of-packet "bvwbjplbgvbhsrlpgdmjqwftvncz"))
(assert= 6 (start-of-packet "nppdvjthqldpwncqszvftbrmjlhg"))
(assert= 10 (start-of-packet "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"))
(assert= 11 (start-of-packet "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
Part 1 solution :
(assert= 1134 (start-of-packet input))
Part 2 :
You also need to look at start - of - message marker , that is 14 distinct characters .
(defn message-start [signal-code prefix-length]
(reduce (fn [[index prefix :as acc] ch]
(if (= prefix-length (count (set prefix)))
(reduced acc)
[(inc index)
(str (subs prefix (if (= prefix-length (count prefix)) 1 0))
ch)]))
[0 ""]
signal-code))
(defn start-of-packet [signal-code]
(first (message-start signal-code 4)))
(assert= 11 (start-of-packet "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
(defn start-of-message [signal-code]
(first (message-start signal-code 14)))
(assert= 19 (start-of-message sample-input))
(assert= 23 (start-of-message "bvwbjplbgvbhsrlpgdmjqwftvncz"))
(assert= 23 (start-of-message "nppdvjthqldpwncqszvftbrmjlhg"))
(assert= 29 (start-of-message "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"))
(assert= 26 (start-of-message "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"))
Part 2 solution :
(assert= 2263 (start-of-message input))
(defn message-start [signal-code prefix-length]
(->> (apply map (fn [i & chars] (when (= (count chars) (count (set chars)))
[i (apply str chars)]))
(range prefix-length (count signal-code))
(take prefix-length (iterate next signal-code)))
(remove nil?)
first))
(message-start sample-input 4)
= > [ 7 " jpqm " ]
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
(take 4 (partition 4 1 sample-input))
= > ( ( \m \j \q \j ) ( \j \q \j ) ( \q \j \q ) ( \j \m ) )
(defn message-start [signal-code prefix-length]
(->> (map-indexed (fn [i chars]
(when (= (count chars) (count (set chars)))
[(+ i prefix-length) (apply str chars)]))
(partition prefix-length 1 signal-code))
(remove nil?)
first))
(message-start sample-input 4)
= > [ 7 " jpqm " ]
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
(defn message-start [signal-code prefix-length]
(first (keep-indexed (fn [i chars]
(when (= (count chars) (count (set chars)))
[(+ i prefix-length) (apply str chars)]))
(partition prefix-length 1 signal-code))))
(assert= 7 (start-of-packet sample-input))
(assert= 1134 (start-of-packet input))
(assert= 2263 (start-of-message input))
|
53dd04664ad0b1baacf7cfce03e30610705eea741adeb0cf2bf2f65dff360529 | lpgauth/httpc_bench | httpc_bench.erl | -module(httpc_bench).
-include("httpc_bench.hrl").
-export([
run/0
]).
-define(N, 2048000).
-define(CLIENTS, [
httpc_bench_buoy,
httpc_bench_dlhttpc,
httpc_bench_hackney,
httpc_bench_httpc,
httpc_bench_ibrowse,
httpc_bench_katipo
]).
-define(CONCURENCIES, [32, 64, 128, 512, 2048, 4096]).
-define(POOL_SIZES, [8, 16, 32, 64, 128, 256]).
%% public
run() ->
error_logger:tty(false),
io:format("Running benchmark...~n~n" ++
"Client PoolSize Concurency Requests/s Error %~n" ++
[$= || _ <- lists:seq(1, 49)] ++ "~n", []),
run_client(?CLIENTS, ?POOL_SIZES, ?CONCURENCIES, ?N).
%% private
lookup(Key, List) ->
case lists:keyfind(Key, 1, List) of
false -> undefined;
{_, Value} -> Value
end.
name(Client, PoolSize, Concurency) ->
list_to_atom(Client ++ "_" ++ integer_to_list(PoolSize) ++
"_" ++ integer_to_list(Concurency)).
run_client([], _PoolSizes, _Concurencies, _N) ->
ok;
run_client([Client | T], PoolSizes, Concurencies, N) ->
run_pool_size(Client, PoolSizes, Concurencies, N),
run_client(T, PoolSizes, Concurencies, N).
run_pool_size(_Client, [], _Concurencies, _N) ->
ok;
run_pool_size(Client, [PoolSize | T], Concurencies, N) ->
run_concurency(Client, PoolSize, Concurencies, N),
run_pool_size(Client, T, Concurencies, N).
run_concurency(_Client, _PoolSize, [], _N) ->
ok;
run_concurency(Client, PoolSize, [Concurency | T], N) ->
Client:start(PoolSize),
{_Prefix, Client2} = lists:split(12, atom_to_list(Client)),
Name = name(Client2, PoolSize, Concurency),
Fun = fun() -> Client:get() end,
Results = timing_hdr:run(Fun, [
{name, Name},
{concurrency, Concurency},
{iterations, N},
{output, "output/" ++ atom_to_list(Name)}
]),
Qps = lookup(success, Results) / (lookup(total_time, Results) / 1000000),
Errors = lookup(errors, Results) / lookup(iterations, Results) * 100,
io:format("~-8s ~7B ~11B ~11B ~8.1f~n",
[Client2, PoolSize, Concurency, trunc(Qps), Errors]),
Client:stop(),
run_concurency(Client, PoolSize, T, N).
| null | https://raw.githubusercontent.com/lpgauth/httpc_bench/5430ddd569dcecf2c120ca424493c336df44284f/src/httpc_bench.erl | erlang | public
private | -module(httpc_bench).
-include("httpc_bench.hrl").
-export([
run/0
]).
-define(N, 2048000).
-define(CLIENTS, [
httpc_bench_buoy,
httpc_bench_dlhttpc,
httpc_bench_hackney,
httpc_bench_httpc,
httpc_bench_ibrowse,
httpc_bench_katipo
]).
-define(CONCURENCIES, [32, 64, 128, 512, 2048, 4096]).
-define(POOL_SIZES, [8, 16, 32, 64, 128, 256]).
run() ->
error_logger:tty(false),
io:format("Running benchmark...~n~n" ++
"Client PoolSize Concurency Requests/s Error %~n" ++
[$= || _ <- lists:seq(1, 49)] ++ "~n", []),
run_client(?CLIENTS, ?POOL_SIZES, ?CONCURENCIES, ?N).
lookup(Key, List) ->
case lists:keyfind(Key, 1, List) of
false -> undefined;
{_, Value} -> Value
end.
name(Client, PoolSize, Concurency) ->
list_to_atom(Client ++ "_" ++ integer_to_list(PoolSize) ++
"_" ++ integer_to_list(Concurency)).
run_client([], _PoolSizes, _Concurencies, _N) ->
ok;
run_client([Client | T], PoolSizes, Concurencies, N) ->
run_pool_size(Client, PoolSizes, Concurencies, N),
run_client(T, PoolSizes, Concurencies, N).
run_pool_size(_Client, [], _Concurencies, _N) ->
ok;
run_pool_size(Client, [PoolSize | T], Concurencies, N) ->
run_concurency(Client, PoolSize, Concurencies, N),
run_pool_size(Client, T, Concurencies, N).
run_concurency(_Client, _PoolSize, [], _N) ->
ok;
run_concurency(Client, PoolSize, [Concurency | T], N) ->
Client:start(PoolSize),
{_Prefix, Client2} = lists:split(12, atom_to_list(Client)),
Name = name(Client2, PoolSize, Concurency),
Fun = fun() -> Client:get() end,
Results = timing_hdr:run(Fun, [
{name, Name},
{concurrency, Concurency},
{iterations, N},
{output, "output/" ++ atom_to_list(Name)}
]),
Qps = lookup(success, Results) / (lookup(total_time, Results) / 1000000),
Errors = lookup(errors, Results) / lookup(iterations, Results) * 100,
io:format("~-8s ~7B ~11B ~11B ~8.1f~n",
[Client2, PoolSize, Concurency, trunc(Qps), Errors]),
Client:stop(),
run_concurency(Client, PoolSize, T, N).
|
ff60197ca84ee50055e5b1b79b59a4c4105763ee24478e03cef3c598ccd4f1a4 | foreverbell/project-euler-solutions | 249.hs |
import Common.Numbers.Primes (primesTo, testPrime)
import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed ((!))
import Data.List (foldl')
dynamic :: Int -> [Int] -> V.Vector Int -> V.Vector Int
dynamic _ [] dp = dp
dynamic modulo (x:xs) dp = dynamic modulo xs dp' where
dp' = V.fromList $ map (\i -> (dp!i + dp!((i - x) `mod` n)) `rem` modulo) [0 .. n - 1]
n = V.length dp
solve n modulo = dynamic modulo primes dp where
dp = V.fromList (1 : replicate (sum primes) 0)
primes = primesTo n
main = print $ foldl' helper 0 $ zip [0 .. ] $ V.toList (solve 5000 modulo) where
helper s (i, ways) = if testPrime i
then (s + ways) `rem` modulo
else s
modulo = 10^16
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/249.hs | haskell |
import Common.Numbers.Primes (primesTo, testPrime)
import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed ((!))
import Data.List (foldl')
dynamic :: Int -> [Int] -> V.Vector Int -> V.Vector Int
dynamic _ [] dp = dp
dynamic modulo (x:xs) dp = dynamic modulo xs dp' where
dp' = V.fromList $ map (\i -> (dp!i + dp!((i - x) `mod` n)) `rem` modulo) [0 .. n - 1]
n = V.length dp
solve n modulo = dynamic modulo primes dp where
dp = V.fromList (1 : replicate (sum primes) 0)
primes = primesTo n
main = print $ foldl' helper 0 $ zip [0 .. ] $ V.toList (solve 5000 modulo) where
helper s (i, ways) = if testPrime i
then (s + ways) `rem` modulo
else s
modulo = 10^16
|
|
a24bfba928e610dc8349cf111f2b566169ba59b8c8831ee871c708ce025745b2 | ygmpkk/house | Prep.hs |
Preprocess a module to normalize it in the following ways :
( 1 ) Saturate all constructor and primop applications .
( 2 ) Arrange that any non - trivial expression of unlifted kind ( ' # ' )
is turned into the scrutinee of a Case .
After these preprocessing steps , Core can be interpreted ( or given an operational semantics )
ignoring type information almost completely .
Preprocess a module to normalize it in the following ways:
(1) Saturate all constructor and primop applications.
(2) Arrange that any non-trivial expression of unlifted kind ('#')
is turned into the scrutinee of a Case.
After these preprocessing steps, Core can be interpreted (or given an operational semantics)
ignoring type information almost completely.
-}
module Prep where
import Prims
import Core
import Printer
import Env
import Check
primArgTys :: Env Var [Ty]
primArgTys = efromlist (map f Prims.primVals)
where f (v,t) = (v,atys)
where (_,atys,_) = splitTy t
prepModule :: Menv -> Module -> Module
prepModule globalEnv (Module mn tdefs vdefgs) =
Module mn tdefs vdefgs'
where
(_,vdefgs') = foldl prepTopVdefg (eempty,[]) vdefgs
prepTopVdefg (venv,vdefgs) vdefg = (venv',vdefgs ++ [vdefg'])
where (venv',vdefg') = prepVdefg (venv,eempty) vdefg
prepVdefg (env@(venv,_)) (Nonrec(Vdef(("",x),t,e))) =
(eextend venv (x,t), Nonrec(Vdef(("",x),t,prepExp env e)))
prepVdefg (env@(venv,_)) (Nonrec(Vdef(qx,t,e))) =
(venv, Nonrec(Vdef(qx,t,prepExp env e)))
prepVdefg (venv,tvenv) (Rec vdefs) =
(venv',Rec [Vdef(qx,t,prepExp (venv',tvenv) e) | Vdef(qx,t,e) <- vdefs])
where venv' = foldl eextend venv [(x,t) | Vdef(("",x),t,_) <- vdefs]
prepExp env (Var qv) = Var qv
prepExp env (Dcon qdc) = Dcon qdc
prepExp env (Lit l) = Lit l
prepExp env e@(App _ _) = unwindApp env e []
prepExp env e@(Appt _ _) = unwindApp env e []
prepExp (venv,tvenv) (Lam (Vb vb) e) = Lam (Vb vb) (prepExp (eextend venv vb,tvenv) e)
prepExp (venv,tvenv) (Lam (Tb tb) e) = Lam (Tb tb) (prepExp (venv,eextend tvenv tb) e)
prepExp env@(venv,tvenv) (Let (Nonrec(Vdef(("",x),t,b))) e) | kindof tvenv t == Kunlifted && suspends b =
Case (prepExp env b) (x,t) [Adefault (prepExp (eextend venv (x,t),tvenv) e)]
prepExp (venv,tvenv) (Let vdefg e) = Let vdefg' (prepExp (venv',tvenv) e)
where (venv',vdefg') = prepVdefg (venv,tvenv) vdefg
prepExp env@(venv,tvenv) (Case e vb alts) = Case (prepExp env e) vb (map (prepAlt (eextend venv vb,tvenv)) alts)
prepExp env (Coerce t e) = Coerce t (prepExp env e)
prepExp env (Note s e) = Note s (prepExp env e)
prepExp env (External s t) = External s t
prepAlt (venv,tvenv) (Acon qdc tbs vbs e) = Acon qdc tbs vbs (prepExp (foldl eextend venv vbs,foldl eextend tvenv tbs) e)
prepAlt env (Alit l e) = Alit l (prepExp env e)
prepAlt env (Adefault e) = Adefault (prepExp env e)
unwindApp env (App e1 e2) as = unwindApp env e1 (Left e2:as)
unwindApp env (Appt e t) as = unwindApp env e (Right t:as)
unwindApp env (op@(Dcon qdc)) as =
etaExpand (drop n atys) (rewindApp env op as)
where (tbs,atys0,_) = splitTy (qlookup cenv_ eempty qdc)
atys = map (substl (map fst tbs) ts) atys0
ts = [t | Right t <- as]
n = length [e | Left e <- as]
unwindApp env (op@(Var(m,p))) as | m == primMname =
etaExpand (drop n atys) (rewindApp env op as)
where Just atys = elookup primArgTys p
n = length [e | Left e <- as]
unwindApp env op as = rewindApp env op as
etaExpand ts e = foldl g e [('$':(show i),t) | (i,t) <- zip [1..] ts]
where g e (v,t) = Lam (Vb(v,t)) (App e (Var ("",v)))
rewindApp env e [] = e
rewindApp env@(venv,tvenv) e1 (Left e2:as) | kindof tvenv t == Kunlifted && suspends e2 =
Case (prepExp env' e2) (v,t)
[Adefault (rewindApp env' (App e1 (Var ("",v))) as)]
where v = freshVar venv
t = typeofExp env e2
env' = (eextend venv (v,t),tvenv)
rewindApp env e1 (Left e2:as) = rewindApp env (App e1 (prepExp env e2)) as
rewindApp env e (Right t:as) = rewindApp env (Appt e t) as
one simple way !
typeofExp :: (Venv,Tvenv) -> Exp -> Ty
typeofExp (venv,_) (Var qv) = qlookup venv_ venv qv
typeofExp env (Dcon qdc) = qlookup cenv_ eempty qdc
typeofExp env (Lit l) = typeofLit l
where typeofLit (Lint _ t) = t
typeofLit (Lrational _ t) = t
typeofLit (Lchar _ t) = t
typeofLit (Lstring _ t) = t
typeofExp env (App e1 e2) = t
where (Tapp(Tapp _ t0) t) = typeofExp env e1
typeofExp env (Appt e t) = substl [tv] [t] t'
where (Tforall (tv,_) t') = typeofExp env e
typeofExp (venv,tvenv) (Lam (Vb(v,t)) e) = tArrow t (typeofExp (eextend venv (v,t),tvenv) e)
typeofExp (venv,tvenv) (Lam (Tb tb) e) = Tforall tb (typeofExp (venv,eextend tvenv tb) e)
typeofExp (venv,tvenv) (Let vdefg e) = typeofExp (venv',tvenv) e
where venv' = case vdefg of
Nonrec (Vdef((_,x),t,_)) -> eextend venv (x,t)
Rec vdefs -> foldl eextend venv [(x,t) | Vdef((_,x),t,_) <- vdefs]
typeofExp (venv,tvenv) (Case _ vb (alt:_)) = typeofAlt (eextend venv vb,tvenv) alt
where typeofAlt (venv,tvenv) (Acon _ tbs vbs e) = typeofExp (foldl eextend venv vbs,foldl eextend tvenv tbs) e
typeofAlt env (Alit _ e) = typeofExp env e
typeofAlt env (Adefault e) = typeofExp env e
typeofExp env (Coerce t _) = t
typeofExp env (Note _ e) = typeofExp env e
typeofExp env (External _ t) = t
{- Return false for those expressions for which Interp.suspendExp buidds a thunk. -}
suspends (Var _) = False
suspends (Lit _) = False
suspends (Lam (Vb _) _) = False
suspends (Lam _ e) = suspends e
suspends (Appt e _) = suspends e
suspends (Coerce _ e) = suspends e
suspends (Note _ e) = suspends e
suspends (External _ _) = False
suspends _ = True
kindof :: Tvenv -> Ty -> Kind
kindof tvenv (Tvar tv) =
case elookup tvenv tv of
Just k -> k
Nothing -> error ("impossible Tyvar " ++ show tv)
kindof tvenv (Tcon qtc) = qlookup tcenv_ eempty qtc
kindof tvenv (Tapp t1 t2) = k2
where Karrow _ k2 = kindof tvenv t1
kindof tvenv (Tforall _ t) = kindof tvenv t
mlookup :: (Envs -> Env a b) -> Env a b -> Mname -> Env a b
mlookup _ local_env "" = local_env
mlookup selector _ m =
case elookup globalEnv m of
Just env -> selector env
Nothing -> error ("undefined module name: " ++ m)
qlookup :: (Ord a, Show a) => (Envs -> Env a b) -> Env a b -> (Mname,a) -> b
qlookup selector local_env (m,k) =
case elookup (mlookup selector local_env m) k of
Just v -> v
Nothing -> error ("undefined identifier: " ++ show k)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/ghc/utils/ext-core/Prep.hs | haskell | Return false for those expressions for which Interp.suspendExp buidds a thunk. |
Preprocess a module to normalize it in the following ways :
( 1 ) Saturate all constructor and primop applications .
( 2 ) Arrange that any non - trivial expression of unlifted kind ( ' # ' )
is turned into the scrutinee of a Case .
After these preprocessing steps , Core can be interpreted ( or given an operational semantics )
ignoring type information almost completely .
Preprocess a module to normalize it in the following ways:
(1) Saturate all constructor and primop applications.
(2) Arrange that any non-trivial expression of unlifted kind ('#')
is turned into the scrutinee of a Case.
After these preprocessing steps, Core can be interpreted (or given an operational semantics)
ignoring type information almost completely.
-}
module Prep where
import Prims
import Core
import Printer
import Env
import Check
primArgTys :: Env Var [Ty]
primArgTys = efromlist (map f Prims.primVals)
where f (v,t) = (v,atys)
where (_,atys,_) = splitTy t
prepModule :: Menv -> Module -> Module
prepModule globalEnv (Module mn tdefs vdefgs) =
Module mn tdefs vdefgs'
where
(_,vdefgs') = foldl prepTopVdefg (eempty,[]) vdefgs
prepTopVdefg (venv,vdefgs) vdefg = (venv',vdefgs ++ [vdefg'])
where (venv',vdefg') = prepVdefg (venv,eempty) vdefg
prepVdefg (env@(venv,_)) (Nonrec(Vdef(("",x),t,e))) =
(eextend venv (x,t), Nonrec(Vdef(("",x),t,prepExp env e)))
prepVdefg (env@(venv,_)) (Nonrec(Vdef(qx,t,e))) =
(venv, Nonrec(Vdef(qx,t,prepExp env e)))
prepVdefg (venv,tvenv) (Rec vdefs) =
(venv',Rec [Vdef(qx,t,prepExp (venv',tvenv) e) | Vdef(qx,t,e) <- vdefs])
where venv' = foldl eextend venv [(x,t) | Vdef(("",x),t,_) <- vdefs]
prepExp env (Var qv) = Var qv
prepExp env (Dcon qdc) = Dcon qdc
prepExp env (Lit l) = Lit l
prepExp env e@(App _ _) = unwindApp env e []
prepExp env e@(Appt _ _) = unwindApp env e []
prepExp (venv,tvenv) (Lam (Vb vb) e) = Lam (Vb vb) (prepExp (eextend venv vb,tvenv) e)
prepExp (venv,tvenv) (Lam (Tb tb) e) = Lam (Tb tb) (prepExp (venv,eextend tvenv tb) e)
prepExp env@(venv,tvenv) (Let (Nonrec(Vdef(("",x),t,b))) e) | kindof tvenv t == Kunlifted && suspends b =
Case (prepExp env b) (x,t) [Adefault (prepExp (eextend venv (x,t),tvenv) e)]
prepExp (venv,tvenv) (Let vdefg e) = Let vdefg' (prepExp (venv',tvenv) e)
where (venv',vdefg') = prepVdefg (venv,tvenv) vdefg
prepExp env@(venv,tvenv) (Case e vb alts) = Case (prepExp env e) vb (map (prepAlt (eextend venv vb,tvenv)) alts)
prepExp env (Coerce t e) = Coerce t (prepExp env e)
prepExp env (Note s e) = Note s (prepExp env e)
prepExp env (External s t) = External s t
prepAlt (venv,tvenv) (Acon qdc tbs vbs e) = Acon qdc tbs vbs (prepExp (foldl eextend venv vbs,foldl eextend tvenv tbs) e)
prepAlt env (Alit l e) = Alit l (prepExp env e)
prepAlt env (Adefault e) = Adefault (prepExp env e)
unwindApp env (App e1 e2) as = unwindApp env e1 (Left e2:as)
unwindApp env (Appt e t) as = unwindApp env e (Right t:as)
unwindApp env (op@(Dcon qdc)) as =
etaExpand (drop n atys) (rewindApp env op as)
where (tbs,atys0,_) = splitTy (qlookup cenv_ eempty qdc)
atys = map (substl (map fst tbs) ts) atys0
ts = [t | Right t <- as]
n = length [e | Left e <- as]
unwindApp env (op@(Var(m,p))) as | m == primMname =
etaExpand (drop n atys) (rewindApp env op as)
where Just atys = elookup primArgTys p
n = length [e | Left e <- as]
unwindApp env op as = rewindApp env op as
etaExpand ts e = foldl g e [('$':(show i),t) | (i,t) <- zip [1..] ts]
where g e (v,t) = Lam (Vb(v,t)) (App e (Var ("",v)))
rewindApp env e [] = e
rewindApp env@(venv,tvenv) e1 (Left e2:as) | kindof tvenv t == Kunlifted && suspends e2 =
Case (prepExp env' e2) (v,t)
[Adefault (rewindApp env' (App e1 (Var ("",v))) as)]
where v = freshVar venv
t = typeofExp env e2
env' = (eextend venv (v,t),tvenv)
rewindApp env e1 (Left e2:as) = rewindApp env (App e1 (prepExp env e2)) as
rewindApp env e (Right t:as) = rewindApp env (Appt e t) as
one simple way !
typeofExp :: (Venv,Tvenv) -> Exp -> Ty
typeofExp (venv,_) (Var qv) = qlookup venv_ venv qv
typeofExp env (Dcon qdc) = qlookup cenv_ eempty qdc
typeofExp env (Lit l) = typeofLit l
where typeofLit (Lint _ t) = t
typeofLit (Lrational _ t) = t
typeofLit (Lchar _ t) = t
typeofLit (Lstring _ t) = t
typeofExp env (App e1 e2) = t
where (Tapp(Tapp _ t0) t) = typeofExp env e1
typeofExp env (Appt e t) = substl [tv] [t] t'
where (Tforall (tv,_) t') = typeofExp env e
typeofExp (venv,tvenv) (Lam (Vb(v,t)) e) = tArrow t (typeofExp (eextend venv (v,t),tvenv) e)
typeofExp (venv,tvenv) (Lam (Tb tb) e) = Tforall tb (typeofExp (venv,eextend tvenv tb) e)
typeofExp (venv,tvenv) (Let vdefg e) = typeofExp (venv',tvenv) e
where venv' = case vdefg of
Nonrec (Vdef((_,x),t,_)) -> eextend venv (x,t)
Rec vdefs -> foldl eextend venv [(x,t) | Vdef((_,x),t,_) <- vdefs]
typeofExp (venv,tvenv) (Case _ vb (alt:_)) = typeofAlt (eextend venv vb,tvenv) alt
where typeofAlt (venv,tvenv) (Acon _ tbs vbs e) = typeofExp (foldl eextend venv vbs,foldl eextend tvenv tbs) e
typeofAlt env (Alit _ e) = typeofExp env e
typeofAlt env (Adefault e) = typeofExp env e
typeofExp env (Coerce t _) = t
typeofExp env (Note _ e) = typeofExp env e
typeofExp env (External _ t) = t
suspends (Var _) = False
suspends (Lit _) = False
suspends (Lam (Vb _) _) = False
suspends (Lam _ e) = suspends e
suspends (Appt e _) = suspends e
suspends (Coerce _ e) = suspends e
suspends (Note _ e) = suspends e
suspends (External _ _) = False
suspends _ = True
kindof :: Tvenv -> Ty -> Kind
kindof tvenv (Tvar tv) =
case elookup tvenv tv of
Just k -> k
Nothing -> error ("impossible Tyvar " ++ show tv)
kindof tvenv (Tcon qtc) = qlookup tcenv_ eempty qtc
kindof tvenv (Tapp t1 t2) = k2
where Karrow _ k2 = kindof tvenv t1
kindof tvenv (Tforall _ t) = kindof tvenv t
mlookup :: (Envs -> Env a b) -> Env a b -> Mname -> Env a b
mlookup _ local_env "" = local_env
mlookup selector _ m =
case elookup globalEnv m of
Just env -> selector env
Nothing -> error ("undefined module name: " ++ m)
qlookup :: (Ord a, Show a) => (Envs -> Env a b) -> Env a b -> (Mname,a) -> b
qlookup selector local_env (m,k) =
case elookup (mlookup selector local_env m) k of
Just v -> v
Nothing -> error ("undefined identifier: " ++ show k)
|
40685ffc45791cb4ed327e52d02f6bfb2829ba9c529b8182bbe5367c94b723a3 | manuel-serrano/hop | xml.scm | ;*=====================================================================*/
* serrano / prgm / project / hop/3.5.x / runtime / xml.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Dec 8 05:43:46 2004 * /
* Last change : Thu Jan 20 09:19:18 2022 ( serrano ) * /
* Copyright : 2004 - 22 * /
;* ------------------------------------------------------------- */
;* Simple XML producer/writer for HOP. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __hop_xml
(library web)
(include "param.sch"
"xml.sch")
(import __hop_types
__hop_xml-types
__hop_mime
__hop_misc
__hop_param
__hop_configure
__hop_clientc
__hop_priv
__hop_read-js
__hop_http-error
__hop_css
__hop_charset)
(use __hop_js-comp)
(export (xml-constructor-add! ::symbol ::procedure)
(%make-xml-element ::symbol ::pair-nil)
(xml-markup-is? ::obj ::symbol)
(xml-make-id::obj #!optional id tag)
(xml-event-handler-attribute?::bool ::keyword)
(hop-get-xml-backend::xml-backend ::symbol)
(hop-xhtml-xmlns::pair-nil)
(hop-xhtml-xmlns-set! ::pair-nil)
(hop-xml-backend::xml-backend)
(hop-xml-backend-set! ::obj)
(xml-body ::obj ::obj)
(generic xml-primitive-value ::obj ::obj)
(generic xml-unpack ::obj ::obj)
(generic xml-write ::obj ::output-port ::xml-backend)
(generic xml-write-attribute ::obj ::keyword ::output-port ::xml-backend)
(generic xml-write-expression ::obj ::output-port)
(xml-write-attributes ::pair-nil ::output-port ::xml-backend)
(generic xml-attribute-encode ::obj)
(generic xml-to-errstring::bstring ::obj)
(xml-url-for-each ::obj ::procedure)
(xml->string ::obj ::xml-backend)
(parse-html ::input-port ::long)
(string->html ::bstring)
(string->xml ::bstring)
(xml-tilde->expression::bstring ::xml-tilde)
(xml-tilde->statement::bstring ::xml-tilde)
(xml-tilde->return::bstring ::xml-tilde)
(xml-tilde->attribute::bstring ::xml-tilde)
(xml-tilde->sexp ::xml-tilde)
(sexp->xml-tilde::xml-tilde expr #!key env menv %context)
(xml-tilde*::xml-tilde ::xml-tilde . rest)
(<TILDE> ::obj #!key src loc)
(<DELAY> . ::obj)
(<PRAGMA> . ::obj)))
;*---------------------------------------------------------------------*/
;* object-serializer ::xml-markup ... */
;* ------------------------------------------------------------- */
;* WARNING: Module initialization prevents this declaration to be */
;* moved to xml_types! */
;*---------------------------------------------------------------------*/
(register-class-serialization! xml-markup
;; use a fake ad-hoc serializer to simplify client-side
;; unserializer implementation
(lambda (o ctx) o)
(lambda (o ctx) o))
(register-class-serialization! xml-tilde
(lambda (o ctx)
;; force the compilation of the attributes
(xml-tilde->statement o)
o)
(lambda (o ctx)
o))
;*---------------------------------------------------------------------*/
;* hop-xhtml-xmlns ... */
;*---------------------------------------------------------------------*/
(define-parameter hop-xhtml-xmlns
'(:xmlns ""
:xmlns:svg "")
(lambda (v)
(let loop ((l v))
(cond
((null? l)
v)
((and (keyword? (car l)) (pair? (cdr l)) (string? (cadr l)))
(loop (cddr l)))
(else
(error "hop-xhtml-xmlns" "Illegal namespaces" v))))))
;*---------------------------------------------------------------------*/
;* *html-backend* ... */
;*---------------------------------------------------------------------*/
(define *html-4.01-backend*
(instantiate::xml-backend
(id 'html-4.01)
(mime-type "text/html")
(doctype "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"\">")
* ( doctype " < ! DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\ " \" / TR / html4 / loose.dtd\ " > " ) * /
(html-attributes '())
(no-end-tags-elements '(link))
(empty-end-tag #f)
;; the meta-format contains the closing >
(meta-delimiter ">")))
;*---------------------------------------------------------------------*/
;* *html5-backend* ... */
;*---------------------------------------------------------------------*/
(define *html5-backend*
(instantiate::xml-backend
(id 'html-5)
(mime-type "text/html")
(doctype "<!DOCTYPE html>")
(html-attributes '())
(no-end-tags-elements '(link))
;; the meta-format contains the closing >
(meta-delimiter ">")))
;*---------------------------------------------------------------------*/
* * - backend * ... * /
;*---------------------------------------------------------------------*/
(define *xhtml-backend*
(instantiate::xml-backend
(id 'xhtml-1.0)
(mime-type "application/xhtml+xml")
(doctype "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN\" \"-math-svg/xhtml-math-svg.dtd\" [<!ENTITY nbsp \" \"><!ENTITY OverBar \"¯\"><!ENTITY OverBrace \"︷\">]>")
(html-attributes (hop-xhtml-xmlns))
(header-format "<?xml version=\"1.0\" encoding=\"~a\"?>\n")
(no-end-tags-elements '())
;; XHTML scripts have to be protected
(cdata-start "\n<![CDATA[\n")
(cdata-stop "]]>\n")
;; the meta-format contains the closing />
(meta-delimiter "/>")))
;*---------------------------------------------------------------------*/
;* hop-xml-backend ... */
;*---------------------------------------------------------------------*/
(define-parameter hop-xml-backend
*html5-backend*
(lambda (v)
(if (isa? v xml-backend)
v
(hop-get-xml-backend v))))
;*---------------------------------------------------------------------*/
;* hop-get-xml-backend ... */
;*---------------------------------------------------------------------*/
(define (hop-get-xml-backend id)
(case id
((html html-4.01)
*html-4.01-backend*)
((html5 html-5)
*html5-backend*)
((xhtml xhtml-1.0)
*xhtml-backend*)
(else
(error "hop-get-xml-backend" "Illegal backend" id))))
;*---------------------------------------------------------------------*/
;* *xml-constructors* ... */
;*---------------------------------------------------------------------*/
(define *xml-constructors* (make-hashtable))
;*---------------------------------------------------------------------*/
;* xml-constructor-add! ... */
;*---------------------------------------------------------------------*/
(define (xml-constructor-add! id proc)
(if (not (correct-arity? proc 1))
(error "xml-constructor-add!" "Illegal constructor" proc)
(hashtable-put! *xml-constructors* id proc)))
;*---------------------------------------------------------------------*/
;* %xml-constructor ... */
;*---------------------------------------------------------------------*/
(define-method (%xml-constructor o::xml-markup)
(call-next-method)
(with-access::xml-markup o (body tag attributes)
(for-each (lambda (attr)
(when (isa? attr xml-tilde)
(with-access::xml-tilde attr (parent)
(set! parent o))))
attributes)
(let loop ((es body))
(cond
((pair? es)
(let ((e (car es)))
(cond
((isa? e xml-element)
(with-access::xml-element e (parent)
(set! parent o)))
((isa? e xml-tilde)
(with-access::xml-tilde e (parent)
(set! parent o)))
((pair? e)
(loop e))))
(loop (cdr es)))
((isa? es xml-element)
(with-access::xml-element es (parent)
(set! parent o)))
((isa? es xml-tilde)
(with-access::xml-tilde es (parent)
(set! parent o)))))
o))
;*---------------------------------------------------------------------*/
;* %xml-constructor ::xml-element ... */
;*---------------------------------------------------------------------*/
(define-method (%xml-constructor o::xml-element)
(call-next-method)
(with-access::xml-element o (id)
(let ((hook (hashtable-get *xml-constructors* id)))
(when (procedure? hook)
(hook o)))
o))
;*---------------------------------------------------------------------*/
;* %make-xml-element ... */
;*---------------------------------------------------------------------*/
(define (%make-xml-element el args)
(define (symbol-upcase s)
(string->symbol (string-upcase! (symbol->string s))))
(define (el->string el)
(string-append "<" (string-upcase (symbol->string! el)) ">"))
(let loop ((a args)
(attr '())
(body '())
(id #unspecified)
(ctx #f))
(cond
((null? a)
(instantiate::xml-element
(tag el)
(attributes (reverse! attr))
(id (xml-make-id id))
(body (reverse! body))))
((keyword? (car a))
(cond
((not (pair? (cdr a)))
(error (el->string el) "Illegal attribute" (car a)))
((eq? (car a) :id)
(let ((v (xml-primitive-value (cadr a) ctx)))
(if (or (string? v) (not v))
(loop (cddr a) attr body v ctx)
(bigloo-type-error el "string" (cadr a)))))
((eq? (car a) :class)
(let ((v (xml-primitive-value (cadr a) ctx)))
(cond
((or (string? v) (not v))
(loop (cddr a) (cons* v (car a) attr) body id ctx))
((symbol? v)
(loop (cddr a) (cons* (symbol->string! v) (car a) attr) body id ctx))
((eq? v #unspecified)
(loop (cddr a) attr body id ctx))
((isa? v xml-tilde)
(loop (cddr a) (cons* (cadr a) (car a) attr) body id ctx))
(else
(bigloo-type-error el "string" (cadr a))))))
((eq? (car a) :%context)
(loop (cddr a) attr body id (cadr a)))
(else
(loop (cddr a) (cons* (cadr a) (car a) attr) body id ctx))))
((null? (car a))
(loop (cdr a) attr body id ctx))
((xml-unpack (car a) ctx)
=>
(lambda (l)
(if (not (or (null? (cdr a)) (pair? (cdr a))))
(error (el->string el) "Illegal arguments"
`(,(el->string el) ,@args))
(if (or (pair? l) (null? l))
(loop (append l (cdr a)) attr body id ctx)
(loop (cdr a) attr (cons (car a) body) id ctx)))))
(else
(loop (cdr a) attr (cons (car a) body) id ctx)))))
;*---------------------------------------------------------------------*/
;* xml-markup-is? ... */
;*---------------------------------------------------------------------*/
(define (xml-markup-is? o t)
(when (isa? o xml-markup)
(with-access::xml-markup o (tag)
(eq? tag t))))
;*---------------------------------------------------------------------*/
;* id-count ... */
;*---------------------------------------------------------------------*/
(define id-count
0)
;*---------------------------------------------------------------------*/
;* xml-make-id ... */
;*---------------------------------------------------------------------*/
(define (xml-make-id #!optional id tag)
(if (string? id)
id
(let ((n (fixnum->string id-count)))
(set! id-count (+fx 1 id-count))
(cond
((symbol? id)
(string-append (symbol->string! id) n))
((symbol? tag)
(string-append (symbol->string! tag) n))
(else
(string-append "G" n))))))
;*---------------------------------------------------------------------*/
;* xml-event-handler-attribute? ... */
;* ------------------------------------------------------------- */
;* This is a gross hack. Currently, we consider that all attributes */
;* whose name start with "on" are event handlers! */
;*---------------------------------------------------------------------*/
(define (xml-event-handler-attribute? keyword)
(substring-ci-at? (keyword->string! keyword) "on" 0))
;*---------------------------------------------------------------------*/
;* xml-body ... */
;*---------------------------------------------------------------------*/
(define (xml-body body ctx)
(if (null? body)
body
(let ((el (xml-unpack (car body) ctx)))
(if (pair? el)
(append el (xml-body (cdr body) ctx))
(cons el (xml-body (cdr body) ctx))))))
;*---------------------------------------------------------------------*/
;* xml-primitive-value ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-primitive-value x::obj ctx)
x)
;*---------------------------------------------------------------------*/
;* xml-unpack ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-unpack obj::obj ctx)
obj)
;*---------------------------------------------------------------------*/
;* xml-write ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-write obj p backend)
(cond
((string? obj)
(with-access::xml-backend backend (security)
(if (isa? security security-manager)
(with-access::security-manager security (string-sanitize)
(let ((s (string-sanitize obj)))
(when (string? s)
(display s p))))
(display obj p))))
((integer? obj)
(display obj p))
((flonum? obj)
(if (nanfl? obj)
(display "NaN" p)
(display obj p)))
((number? obj)
(display obj p))
((symbol? obj)
;; don't display symbols otherwise inner defines generate HTML codes!
#unspecified)
((pair? obj)
(for-each (lambda (o) (xml-write o p backend)) obj))
((date? obj)
(display obj p))
((null? obj)
#unspecified)
((eq? obj #unspecified)
#unspecified)
((eq? obj #f)
#unspecified)
((eq? obj #t)
#unspecified)
((char? obj)
(display obj p))
((ucs2-string? obj)
(let ((s (charset-convert (ucs2-string->utf8-string obj)
'UTF-8 (hop-charset))))
(xml-write s p backend)))
(else
(error "xml" "bad XML object" (xml-to-errstring obj)))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-verbatim ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-verbatim p backend)
(with-access::xml-verbatim obj (data)
(display data p)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-comment ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-comment p backend)
(with-access::xml-comment obj (data)
(display "<!--" p)
(display-string data p)
(display "-->" p)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-if ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-if p backend)
(with-access::xml-if obj (test then otherwise)
(if (test)
(xml-write then p backend)
(xml-write otherwise p backend))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-cdata ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-cdata p backend)
(with-access::xml-cdata obj (tag body attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(display ">" p)
(unless (or (not body) (null? body))
(when cdata-start (display cdata-start p))
(xml-write body p backend)
(when cdata-stop (display cdata-stop p)))
(display "</" p)
(display tag p)
(display ">" p))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-style ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-style p backend)
(define (xml-write-style el p)
(call-with-input-string el
(lambda (ip)
(let ((hss (hop-read-hss ip)))
(if (isa? hss css-stylesheet)
(css-write (hss-compile hss) p)
(error "xml-write" "Illegal style sheet" el))))))
(with-access::xml-style obj (tag body attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(display ">" p)
(unless (or (not body) (null? body))
(when cdata-start (display cdata-start p))
(let ((op (open-output-string)))
(for-each (lambda (el)
(if (string? el)
(display el op)
(xml-write el op backend)))
body)
(xml-write-style (close-output-port op) p))
(when cdata-stop (display cdata-stop p)))
(display "</" p)
(display tag p)
(display ">" p))))
;*---------------------------------------------------------------------*/
;* xml-write-script-tag ... */
;*---------------------------------------------------------------------*/
(define (xml-write-script-tag p closing::bstring)
(let ((mt (hop-mime-type)))
(if (string=? mt "application/x-javascript")
(display "<script" p)
(begin
(display "<script type='" p)
(display mt p)
(display "'" p)))
(display closing p)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-tilde ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-tilde p backend)
(with-access::xml-tilde obj (body parent)
(if (xml-markup-is? parent 'script)
(xml-write (xml-tilde->statement obj) p backend)
(with-access::xml-backend backend (cdata-start cdata-stop)
(xml-write-script-tag p ">")
(when cdata-start (display cdata-start p))
(display (xml-tilde->statement obj) p)
(when cdata-stop (display cdata-stop p))
(display "</script>" p)))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-delay ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-delay p backend)
(with-access::xml-delay obj (thunk)
(xml-write (thunk) p backend)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-markup ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-markup p backend)
(with-access::xml-markup obj (tag attributes body)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (security no-end-tags-elements)
(cond
((and (eq? tag 'head) (>=fx (hop-security) 3))
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(when (isa? security security-manager)
(for-each (lambda (r)
(xml-write-script-tag p " src='")
(display r p)
(display "'</script>" p))
(with-access::security-manager security (runtime) runtime)))
(display "</" p)
(display tag p)
(display ">" p))
((or (pair? body) (eq? tag 'script) (eq? tag 'title))
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p))
((memq tag no-end-tags-elements)
(display ">" p))
(else
(display "/>" p))))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-meta ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-meta p backend)
(with-access::xml-meta obj (tag attributes content body)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (mime-type meta-delimiter)
(cond
((string? content)
(display " content='" p)
(fprintf p content mime-type (hop-charset))
(display "'" p))
(content
(display " content='" p)
(display mime-type p)
(display "; charset=" p)
(display (hop-charset) p)
(display "'" p)))
(display meta-delimiter p))
(newline p)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-element ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-element p backend)
(with-access::xml-element obj (tag id attributes body)
(with-access::xml-backend backend (abbrev-emptyp no-end-tags-elements)
(cond
((and (null? body) (null? attributes))
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(if abbrev-emptyp
(display "/>" p)
(begin
(display "></" p)
(display tag p)
(display ">" p))))
((null? body)
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(cond
(abbrev-emptyp
(display "/>" p))
((memq tag no-end-tags-elements)
(display ">" p))
(else
(display ">" p)
(display "</" p)
(display tag p)
(display ">" p))))
(else
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p)))
(xml-write-initializations obj p backend))))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-empty-element ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-empty-element p backend)
(with-access::xml-empty-element obj (tag id attributes)
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (empty-end-tag)
(display (if empty-end-tag "/>" ">") p))
(xml-write-initializations obj p backend)))
;*---------------------------------------------------------------------*/
;* xml-write ::xml-html ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::xml-html p backend)
(if (>=fx (hop-clientc-debug-unbound) 1)
(xml-write-html/unbound-check obj p backend)
(xml-write-html obj p backend)))
;*---------------------------------------------------------------------*/
;* xml-write-html/unbound-check ... */
;*---------------------------------------------------------------------*/
(define (xml-write-html/unbound-check obj::xml-html p backend)
(with-access::xml-html obj (body)
;; check the unbound variables
(let ((env (make-hashtable)))
(xml-tilde-unbound body env)
(let* ((l (hashtable-map env
(lambda (k v) (when v (cons k v)))))
(lf (let loop ((x l))
(when (pair? x) (or (car x) (loop (cdr x)))))))
(if (pair? lf)
we got at least one
(with-handler
(lambda (e)
(exception-notify e)
(let* ((m (if (epair? (cdr lf))
(match-case (cer (cdr lf))
((at ?file . ?-)
(format "~a: unbound variable" file))
(else
"Unbound variables"))
"Unbound variables"))
(r (http-internal-error e m #f)))
(with-access::http-response-xml r (xml)
(xml-write-html xml p backend))))
(error/source-location "<HTML>"
(format "Unbound client-side variable: ~a" (car lf))
(cadr lf)
(cddr lf)))
;; everything is fine
(xml-write-html obj p backend))))))
;*---------------------------------------------------------------------*/
;* xml-write-html ... */
;*---------------------------------------------------------------------*/
(define (xml-write-html obj::xml-html p backend)
(with-access::xml-backend backend (header-format doctype html-attributes)
(when header-format
(fprintf p header-format (hop-charset)))
(display doctype p)
(newline p)
(with-access::xml-html obj (tag attributes body)
(display "<" p)
(display tag p)
(let ((hattr (let loop ((hattr html-attributes))
(cond
((null? hattr)
'())
((plist-assq (car hattr) attributes)
(loop (cddr hattr)))
(else
(cons* (car hattr)
(cadr hattr)
(loop (cddr hattr))))))))
(xml-write-attributes hattr p backend))
(xml-write-attributes attributes p backend)
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p))))
;*---------------------------------------------------------------------*/
;* xml-write-attributes ... */
;*---------------------------------------------------------------------*/
(define (xml-write-attributes attr p backend)
(let loop ((a attr))
(when (pair? a)
(display " " p)
(unless (pair? (cdr a))
(error "xml-write-attributes" "Illegal attributes" attr))
(xml-write-attribute (cadr a) (car a) p backend)
(loop (cddr a)))))
;*---------------------------------------------------------------------*/
;* xml-write-attribute ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-write-attribute attr::obj id p backend)
;; boolean false attribute has no value, xml-tilde are initialized
(unless (or (eq? attr #f) (eq? attr #unspecified)
(char=? (string-ref (keyword->string! id) 0) #\%))
(display (keyword->string! id) p)
;; boolean true attribute has no value
(display "='" p)
(cond
((eq? attr #t)
(display (keyword->string! id) p))
((procedure? attr)
(if (isa? (procedure-attr attr) hop-service)
(with-access::hop-service (procedure-attr attr) (path)
(display path p))
(error "xml"
"Illegal procedure argument in XML attribute"
id)))
((with-access::xml-backend backend (security) security)
=>
(lambda (sm)
(if (isa? sm security-manager)
(with-access::security-manager sm (attribute-sanitize)
(let ((a (xml-attribute-encode attr)))
(display (attribute-sanitize a id) p)))
(error "xml-write-attribute" "Illegal security-manager" sm))))
(else
(display (xml-attribute-encode attr) p)))
(display "'" p)))
;*---------------------------------------------------------------------*/
;* xml-write-attribute ::xml-tilde ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write-attribute attr::xml-tilde id p backend)
(when (xml-event-handler-attribute? id)
(display (keyword->string! id) p)
(display "='" p)
(with-access::xml-backend backend ((sm security))
(if (isa? sm security-manager)
(with-access::security-manager sm (attribute-sanitize)
(display (attribute-sanitize attr id) p))
(display (xml-tilde->attribute attr) p)))
(display "'" p)))
;*---------------------------------------------------------------------*/
;* xml-write-attribute ::hop-service ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write-attribute attr::hop-service id p backend)
(display (keyword->string! id) p)
(display "='" p)
(with-access::hop-service attr (path)
(display path p))
(display "'" p))
;*---------------------------------------------------------------------*/
;* xml-write-attribute ::xml-lazy-attribute ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write-attribute attr::xml-lazy-attribute id p backend)
(with-access::xml-lazy-attribute attr (proc)
(xml-write-attribute (proc) id p backend)))
;*---------------------------------------------------------------------*/
;* xml-attribute-encode ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-attribute-encode obj)
(if (not (string? obj))
obj
(let ((ol (string-length obj)))
(define (count str ol)
(let loop ((i 0)
(j 0))
(if (=fx i ol)
j
(let ((c (string-ref str i)))
(if (char=? c #\')
(loop (+fx i 1) (+fx j 5))
(loop (+fx i 1) (+fx j 1)))))))
(define (encode str ol nl)
(if (=fx nl ol)
obj
(let ((nstr (make-string nl)))
(let loop ((i 0)
(j 0))
(if (=fx j nl)
nstr
(let ((c (string-ref str i)))
(case c
((#\')
(string-set! nstr j #\&)
(string-set! nstr (+fx j 1) #\#)
(string-set! nstr (+fx j 2) #\3)
(string-set! nstr (+fx j 3) #\9)
(string-set! nstr (+fx j 4) #\;)
(loop (+fx i 1) (+fx j 5)))
(else
(string-set! nstr j c)
(loop (+fx i 1) (+fx j 1))))))))))
(encode obj ol (count obj ol)))))
;*---------------------------------------------------------------------*/
;* xml-to-errstring ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-to-errstring o::obj)
(call-with-output-string
(lambda (op)
(write-circle o op)
(display " `" op)
(display (typeof o) op)
(display "'" op))))
;*---------------------------------------------------------------------*/
;* xml-write-initializations ... */
;*---------------------------------------------------------------------*/
(define (xml-write-initializations obj p backend)
(with-access::xml-element obj (id attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(let loop ((attrs attributes)
(var #f))
(cond
((null? attrs)
(when var
(when cdata-stop (display cdata-stop p))
(display "}, false );</script>" p)))
((and (isa? (cadr attrs) xml-tilde)
(not (xml-event-handler-attribute? (car attrs))))
(if var
(begin
(xml-write-initialization (car attrs) (cadr attrs) var p)
(newline p)
(loop (cddr attrs) var))
(let ((var (gensym)))
(xml-write-script-tag p ">")
(when cdata-start (display cdata-start p))
(display "hop_add_event_listener( \"" p)
(display id p)
(display "\", \"ready\", function (e) {" p)
(display "var " p)
(display var p)
(display " = e.value;" p)
(loop attrs var))))
(else
(loop (cddr attrs) var)))))))
;*---------------------------------------------------------------------*/
;* xml-write-initialization ... */
;*---------------------------------------------------------------------*/
(define (xml-write-initialization id tilde var p)
(display "hop.reactAttribute( function() { return " p)
(if (eq? id :style)
(xml-write-style-initialization tilde var p)
(begin
(display var p)
(display "[\"" p)
(display (if (eq? id :class) "className" (keyword->string! id)) p)
(display "\"]=" p)
(xml-write-expression tilde p)
(display ";" p)))
(display "}.bind( this ) );" p))
;*---------------------------------------------------------------------*/
;* xml-write-style-initialization ... */
;* ------------------------------------------------------------- */
;* Style is special because it is a read-only attributes and */
* because its value can be evaluated to a JavaScript object . * /
;*---------------------------------------------------------------------*/
(define (xml-write-style-initialization tilde var p)
(display "hop_style_attribute_set(" p)
(display var p)
(display "," p)
(xml-write-expression tilde p)
(display ");" p))
;*---------------------------------------------------------------------*/
;* xml->string ... */
;*---------------------------------------------------------------------*/
(define (xml->string obj backend)
(with-output-to-string
(lambda ()
(xml-write obj (current-output-port) backend))))
;*---------------------------------------------------------------------*/
;* eval-markup ... */
;*---------------------------------------------------------------------*/
(define (eval-markup constr attributes body)
(case constr
((<HEAD>)
The Hop head constructor is special because it implicitly introduces
the Hop rts . In order to avoid this here , head is explicitly created .
(instantiate::xml-markup
(tag 'head)
(attributes attributes)
(body body)))
(else
(let* ((a (append-map (lambda (a)
(list (symbol->keyword (car a)) (cdr a)))
attributes))
(constr (with-handler
(lambda (e)
(with-access::&error e (msg)
(if (string=? msg "Unbound variable")
;; create an opaque XML object
(lambda l
(instantiate::xml-markup
(tag constr)
(attributes a)
(body body)))
;; re-raise the other errors
(raise e))))
(eval constr))))
(if (procedure? constr)
(apply constr (append a body))
(error "string->xml" "Illegal markup" constr))))))
;*---------------------------------------------------------------------*/
;* parse-html ... */
;*---------------------------------------------------------------------*/
(define (parse-html ip clen)
(html-parse ip
:content-length clen
:eoi (lambda (o) (isa? o xml-markup))
:procedure (lambda (tag attributes body)
(let ((constr (string->symbol
(string-append
"<"
(string-upcase (symbol->string! tag))
">"))))
(eval-markup constr attributes body)))))
;*---------------------------------------------------------------------*/
;* string->html ... */
;*---------------------------------------------------------------------*/
(define (string->html h)
(call-with-input-string h (lambda (ip) (parse-html ip 0))))
;*---------------------------------------------------------------------*/
;* string->xml ... */
;*---------------------------------------------------------------------*/
(define (string->xml h)
(call-with-input-string h
(lambda (in)
(xml-parse in
:content-length 0
:procedure (lambda (tag attributes body)
(let ((constr (string->symbol
(string-append
"<"
(string-upcase (symbol->string! tag))
">"))))
(eval-markup constr attributes body)))))))
;*---------------------------------------------------------------------*/
;* xml-tilde->expression ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde->expression::bstring obj)
(with-access::xml-tilde obj (%js-expression body debug)
(unless (string? %js-expression)
(with-access::clientc (hop-clientc) (precompiled->JS-expression)
(set! %js-expression (precompiled->JS-expression body debug))))
%js-expression))
;*---------------------------------------------------------------------*/
;* xml-tilde->statement ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde->statement::bstring obj)
(define (element-attribute el)
(with-access::xml-element el (attributes)
(let loop ((attributes attributes))
(if (or (null? attributes) (null? (cdr attributes)))
#f
(if (and (keyword? (car attributes))
(eq? (cadr attributes) obj))
(car attributes)
(loop (cddr attributes)))))))
(define (parent-context parent)
(cond
((string? parent)
;; I'm not sure this will be ever used...
parent)
((isa? parent xml-element)
;; find the attribute (if any)
(with-access::xml-element parent (tag id)
(let ((attr (element-attribute parent)))
(cond
((eq? id #unspecified)
(symbol->string tag))
((not attr)
(format "~a#~a" tag id))
(else
(format "~a#~a.~a" tag id (keyword->string attr)))))))
(else
"")))
(define (js-catch-callback/location stmt parent file point)
;; this is an inlined version of hop_callback (hop-lib.js)
(let ((ctx (gensym 'ctx)))
(format "var ~a=hop_callback_html_context( \"~a\", \"~a\", ~a );
hop_current_stack_context = ~a;
try { ~a } catch( e ) {
hop_callback_handler(e, ~a); }"
ctx
(string-replace (xml-attribute-encode (parent-context parent))
#\Newline #\Space)
file point ctx stmt
ctx)))
(define (js-catch-callback stmt parent)
(let ((ctx (gensym 'ctx)))
(format "var ~a=hop_callback_listener_context( \"~a\" );
hop_current_stack_context = ~a;
try { ~a } catch( e ) { hop_callback_handler(e, ~a); }"
ctx
(string-replace (xml-attribute-encode (parent-context parent))
#\Newline #\Space)
ctx
stmt
ctx)))
(with-access::xml-tilde obj (%js-statement body loc parent debug)
(unless (string? %js-statement)
(with-access::clientc (hop-clientc) (precompiled->JS-statement)
(let ((stmt (precompiled->JS-statement body debug)))
(if debug
(match-case loc
((at (and (? string?) ?file) (and (? integer?) ?point))
(set! %js-statement
(js-catch-callback/location stmt parent file point)))
(else
(set! %js-statement
(js-catch-callback stmt parent))))
(set! %js-statement stmt)))))
%js-statement))
;*---------------------------------------------------------------------*/
;* xml-tilde->return ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde->return::bstring obj)
(with-access::xml-tilde obj (%js-return body debug)
(when (not (string? %js-return))
(with-access::clientc (hop-clientc) (precompiled->JS-return)
(set! %js-return (precompiled->JS-return body debug))))
%js-return))
;*---------------------------------------------------------------------*/
;* xml-tilde->attribute ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde->attribute obj)
(with-access::xml-tilde obj (%js-attribute)
(if (string? %js-attribute)
%js-attribute
(let ((js-attr (xml-attribute-encode (xml-tilde->statement obj))))
(set! %js-attribute js-attr)
js-attr))))
;*---------------------------------------------------------------------*/
;* xml-tilde->sexp ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde->sexp obj)
(define (wrapper o)
`(pragma
,(call-with-output-string
(lambda (op)
(obj->javascript-attr o op)))))
(with-access::xml-tilde obj (lang body %js-expression)
(if (eq? lang 'javascript)
`(pragma ,%js-expression)
(with-access::clientc (hop-clientc) (precompiled->sexp)
(precompiled->sexp body wrapper)))))
;*---------------------------------------------------------------------*/
;* sexp->xml-tilde ... */
;*---------------------------------------------------------------------*/
(define (sexp->xml-tilde obj #!key env menv %context)
(with-access::clientc (hop-clientc) (macroe sexp->precompiled)
(let* ((env (or env (current-module-clientc-import)))
(menv (or menv (macroe)))
(c (sexp->precompiled obj env menv %context)))
(<TILDE> c :src obj))))
;*---------------------------------------------------------------------*/
;* <TILDE> ... */
;*---------------------------------------------------------------------*/
(define (<TILDE> body #!key src loc)
(instantiate::xml-tilde
(body body)
(src src)
(loc loc)))
;*---------------------------------------------------------------------*/
;* <DELAY> ... */
;*---------------------------------------------------------------------*/
(define-tag <DELAY> ((id #unspecified string)
body)
(if (and (pair? body) (procedure? (car body)) (correct-arity? (car body) 0))
(instantiate::xml-delay
(id (xml-make-id id))
(thunk (car body)))
(error "<DELAY>" "Illegal thunk" (car body))))
;*---------------------------------------------------------------------*/
;* <PRAGMA> ... */
;*---------------------------------------------------------------------*/
(define (<PRAGMA> . obj)
(cond
((and (pair? obj) (null? (cdr obj)) (string? (car obj)))
(instantiate::xml-verbatim (data (car obj))))
((every string? obj)
(instantiate::xml-verbatim (data (apply string-append obj))))
(else
(error "<PRAGMA>" "Illegal arguments" obj))))
;*---------------------------------------------------------------------*/
;* xml-write-expression ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-write-expression obj p)
(cond
((string? obj)
(display "'" p)
(display (string-escape obj #\') p)
(display "'" p))
((eq? obj #t)
(display "true" p))
((eq? obj #f)
(display "false" p))
((eq? obj #unspecified)
(display "undefined" p))
(else
(display obj p))))
;*---------------------------------------------------------------------*/
;* xml-write-expression ::xml-tilde ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write-expression obj::xml-tilde p)
(display (xml-tilde->expression obj) p))
;*---------------------------------------------------------------------*/
;* xml-tilde-unbound ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-tilde-unbound obj::obj env)
(if (pair? obj)
(for-each (lambda (x) (xml-tilde-unbound x env)) obj)
'()))
;*---------------------------------------------------------------------*/
;* xml-tilde-unbound ::xml-if ... */
;*---------------------------------------------------------------------*/
(define-method (xml-tilde-unbound obj::xml-if env)
(with-access::xml-if obj (test then otherwise)
(xml-tilde-unbound test env)
(xml-tilde-unbound then env)
(xml-tilde-unbound otherwise env)))
;*---------------------------------------------------------------------*/
;* xml-tilde-unbound ::xml-markup ... */
;*---------------------------------------------------------------------*/
(define-method (xml-tilde-unbound obj::xml-markup env)
(with-access::xml-markup obj (tag body attributes)
(xml-tilde-unbound body env)
(let ((old (hashtable-get env 'event)))
(unless old (hashtable-put! env 'event #f))
(for-each (lambda (a)
(when (isa? a xml-tilde)
(xml-tilde-unbound a env)))
attributes)
(unless old (hashtable-remove! env 'event)))))
;*---------------------------------------------------------------------*/
;* xml-tilde-unbound ::xml-tilde ... */
;*---------------------------------------------------------------------*/
(define-method (xml-tilde-unbound obj::xml-tilde env)
(define (source-location src)
(when (epair? src) (cer src)))
(with-access::xml-tilde obj (body src)
(with-access::clientc (hop-clientc)
(precompiled-declared-variables precompiled-free-variables)
(when (vector? body)
(for-each (lambda (v)
(let ((v (car v)))
(hashtable-update! env v (lambda (x) #f) #f)))
(precompiled-declared-variables body))
(for-each (lambda (v)
(let ((v (car v))
(loc (caddr v)))
(hashtable-update! env v (lambda (x) #f)
(cons src (or loc (source-location src))))))
(precompiled-free-variables body))))))
;*---------------------------------------------------------------------*/
;* xml-url-for-each ... */
;* ------------------------------------------------------------- */
* Apply proc to all the URLs ( href , ) found in OBJ . * /
;*---------------------------------------------------------------------*/
(define (xml-url-for-each obj::obj proc::procedure)
(xml-url-for-each-inner obj (make-cell #f) proc))
;*---------------------------------------------------------------------*/
;* xml-url-base ... */
;*---------------------------------------------------------------------*/
(define (xml-url-base s base)
(if (char=? (string-ref s 0) #\/)
s
(let ((b (cell-ref base)))
(if (or (not (string? b)) (string-null? b))
s
(string-append b s)))))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-attributes ... */
;*---------------------------------------------------------------------*/
(define (xml-url-for-each-attributes obj base::cell key proc)
(with-access::xml-cdata obj (tag body attributes)
(with-access::xml-markup obj (attributes)
(let ((a (plist-assq key attributes)))
(when (and a (string? (cadr a)))
(unless (or (string-prefix? "data:" (cadr a))
(string-prefix? "http:" (cadr a))
(string-prefix? "https:" (cadr a)))
(let* ((i (string-index (cadr a) #\?))
(s (if i (substring (cadr a) 0 i) (cadr a))))
(unless (string-null? s)
(proc obj (xml-url-base s base))))))))))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ... */
;*---------------------------------------------------------------------*/
(define-generic (xml-url-for-each-inner obj::obj base::cell proc::procedure)
(when (pair? obj)
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) obj)))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ::xml-markup ... */
;*---------------------------------------------------------------------*/
(define-method (xml-url-for-each-inner obj::xml-markup base proc)
(with-access::xml-markup obj (tag body attributes)
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) body)
(when (eq? tag 'head)
(let ((a (plist-assq :%authorizations attributes)))
(when (pair? a)
(cond
((string? (cadr a))
(proc obj (xml-url-base a base)))
((list? (cadr a))
(for-each (lambda (a) (proc obj (xml-url-base a base)))
(cadr a)))))))))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ::xml-element ... */
;*---------------------------------------------------------------------*/
(define-method (xml-url-for-each-inner obj::xml-element base proc)
(with-access::xml-element obj (tag body)
(case tag
((link)
(xml-url-for-each-attributes obj base :href proc)))
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) body)))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ::xml-cdata ... */
;*---------------------------------------------------------------------*/
(define-method (xml-url-for-each-inner obj::xml-cdata base proc)
(xml-url-for-each-attributes obj base :src proc)
(call-next-method))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ::xml-svg ... */
;*---------------------------------------------------------------------*/
(define-method (xml-url-for-each-inner obj::xml-svg base proc)
(xml-url-for-each-attributes obj base :src proc)
(call-next-method))
;*---------------------------------------------------------------------*/
;* xml-url-for-each-inner ::xml-empty-element ... */
;*---------------------------------------------------------------------*/
(define-method (xml-url-for-each-inner obj::xml-empty-element base proc)
(with-access::xml-empty-element obj (tag attributes)
(case tag
((img)
(xml-url-for-each-attributes obj base :src proc))
((base)
(let ((h (plist-assq :href attributes)))
(when (and (pair? h) (string? (cadr h)))
(cell-set! base (cadr h))))))))
;*---------------------------------------------------------------------*/
;* xml-tilde* ... */
;*---------------------------------------------------------------------*/
(define (xml-tilde* t0::xml-tilde . rest)
(let ((err (filter (lambda (x) (not (isa? x xml-tilde))) rest)))
(when (pair? err)
(bigloo-type-error "xml-tilde*" "xml-tilde" (car err))))
(duplicate::xml-tilde t0
(src (map (lambda (t)
(with-access::xml-tilde t (src)
src))
(cons t0 rest)))
(%js-expression (apply string-append
(cons (xml-tilde->expression t0)
(append-map (lambda (t)
(list ","
(xml-tilde->expression t)))
rest))))
(%js-statement (apply string-append
(cons (xml-tilde->statement t0)
(append-map (lambda (t)
(list ";"
(xml-tilde->statement t)))
rest))))
(%js-return (cond
((null? rest)
(xml-tilde->return t0))
((null? (cdr rest))
(string-append
(xml-tilde->statement t0)
";"
(xml-tilde->return (car rest))))
((null? (cddr rest))
(string-append
(xml-tilde->statement t0)
";"
(xml-tilde->statement (car rest))
";"
(xml-tilde->return (cadr rest))))
(else
(string-append
(apply string-append
(cons (xml-tilde->statement t0)
(append
(append-map (lambda (t)
(list ";"
(xml-tilde->statement t)))
(reverse (cdr (reverse rest)))))))
";"
(xml-tilde->return (car (last-pair rest)))))))
(%js-attribute (apply string-append
(cons (xml-tilde->expression t0)
(append-map (lambda (t)
(list ";"
(xml-tilde->expression t)))
rest))))))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/6fc069a4f8b60c4e76f34c3d77df56bf8787b6cb/runtime/xml.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* Simple XML producer/writer for HOP. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* object-serializer ::xml-markup ... */
* ------------------------------------------------------------- */
* WARNING: Module initialization prevents this declaration to be */
* moved to xml_types! */
*---------------------------------------------------------------------*/
use a fake ad-hoc serializer to simplify client-side
unserializer implementation
force the compilation of the attributes
*---------------------------------------------------------------------*/
* hop-xhtml-xmlns ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *html-backend* ... */
*---------------------------------------------------------------------*/
the meta-format contains the closing >
*---------------------------------------------------------------------*/
* *html5-backend* ... */
*---------------------------------------------------------------------*/
the meta-format contains the closing >
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
\"><!ENTITY OverBar \"¯\"><!ENTITY OverBrace \"︷\">]>")
XHTML scripts have to be protected
the meta-format contains the closing />
*---------------------------------------------------------------------*/
* hop-xml-backend ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-get-xml-backend ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *xml-constructors* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-constructor-add! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %xml-constructor ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %xml-constructor ::xml-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %make-xml-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-markup-is? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* id-count ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-make-id ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-event-handler-attribute? ... */
* ------------------------------------------------------------- */
* This is a gross hack. Currently, we consider that all attributes */
* whose name start with "on" are event handlers! */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-body ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-primitive-value ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-unpack ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ... */
*---------------------------------------------------------------------*/
don't display symbols otherwise inner defines generate HTML codes!
*---------------------------------------------------------------------*/
* xml-write ::xml-verbatim ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-comment ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-if ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-cdata ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-style ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-script-tag ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-tilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-delay ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-markup ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-meta ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-empty-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::xml-html ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-html/unbound-check ... */
*---------------------------------------------------------------------*/
check the unbound variables
everything is fine
*---------------------------------------------------------------------*/
* xml-write-html ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-attributes ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-attribute ::obj ... */
*---------------------------------------------------------------------*/
boolean false attribute has no value, xml-tilde are initialized
boolean true attribute has no value
*---------------------------------------------------------------------*/
* xml-write-attribute ::xml-tilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-attribute ::hop-service ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-attribute ::xml-lazy-attribute ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-attribute-encode ... */
*---------------------------------------------------------------------*/
)
*---------------------------------------------------------------------*/
* xml-to-errstring ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-initializations ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-initialization ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-style-initialization ... */
* ------------------------------------------------------------- */
* Style is special because it is a read-only attributes and */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml->string ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* eval-markup ... */
*---------------------------------------------------------------------*/
create an opaque XML object
re-raise the other errors
*---------------------------------------------------------------------*/
* parse-html ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* string->html ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* string->xml ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde->expression ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde->statement ... */
*---------------------------------------------------------------------*/
I'm not sure this will be ever used...
find the attribute (if any)
this is an inlined version of hop_callback (hop-lib.js)
}"
}"
*---------------------------------------------------------------------*/
* xml-tilde->return ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde->attribute ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde->sexp ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* sexp->xml-tilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <TILDE> ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <DELAY> ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <PRAGMA> ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-expression ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write-expression ::xml-tilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde-unbound ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde-unbound ::xml-if ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde-unbound ::xml-markup ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde-unbound ::xml-tilde ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each ... */
* ------------------------------------------------------------- */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-base ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-attributes ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ::xml-markup ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ::xml-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ::xml-cdata ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ::xml-svg ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-url-for-each-inner ::xml-empty-element ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-tilde* ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / hop/3.5.x / runtime / xml.scm * /
* Author : * /
* Creation : We d Dec 8 05:43:46 2004 * /
* Last change : Thu Jan 20 09:19:18 2022 ( serrano ) * /
* Copyright : 2004 - 22 * /
(module __hop_xml
(library web)
(include "param.sch"
"xml.sch")
(import __hop_types
__hop_xml-types
__hop_mime
__hop_misc
__hop_param
__hop_configure
__hop_clientc
__hop_priv
__hop_read-js
__hop_http-error
__hop_css
__hop_charset)
(use __hop_js-comp)
(export (xml-constructor-add! ::symbol ::procedure)
(%make-xml-element ::symbol ::pair-nil)
(xml-markup-is? ::obj ::symbol)
(xml-make-id::obj #!optional id tag)
(xml-event-handler-attribute?::bool ::keyword)
(hop-get-xml-backend::xml-backend ::symbol)
(hop-xhtml-xmlns::pair-nil)
(hop-xhtml-xmlns-set! ::pair-nil)
(hop-xml-backend::xml-backend)
(hop-xml-backend-set! ::obj)
(xml-body ::obj ::obj)
(generic xml-primitive-value ::obj ::obj)
(generic xml-unpack ::obj ::obj)
(generic xml-write ::obj ::output-port ::xml-backend)
(generic xml-write-attribute ::obj ::keyword ::output-port ::xml-backend)
(generic xml-write-expression ::obj ::output-port)
(xml-write-attributes ::pair-nil ::output-port ::xml-backend)
(generic xml-attribute-encode ::obj)
(generic xml-to-errstring::bstring ::obj)
(xml-url-for-each ::obj ::procedure)
(xml->string ::obj ::xml-backend)
(parse-html ::input-port ::long)
(string->html ::bstring)
(string->xml ::bstring)
(xml-tilde->expression::bstring ::xml-tilde)
(xml-tilde->statement::bstring ::xml-tilde)
(xml-tilde->return::bstring ::xml-tilde)
(xml-tilde->attribute::bstring ::xml-tilde)
(xml-tilde->sexp ::xml-tilde)
(sexp->xml-tilde::xml-tilde expr #!key env menv %context)
(xml-tilde*::xml-tilde ::xml-tilde . rest)
(<TILDE> ::obj #!key src loc)
(<DELAY> . ::obj)
(<PRAGMA> . ::obj)))
(register-class-serialization! xml-markup
(lambda (o ctx) o)
(lambda (o ctx) o))
(register-class-serialization! xml-tilde
(lambda (o ctx)
(xml-tilde->statement o)
o)
(lambda (o ctx)
o))
(define-parameter hop-xhtml-xmlns
'(:xmlns ""
:xmlns:svg "")
(lambda (v)
(let loop ((l v))
(cond
((null? l)
v)
((and (keyword? (car l)) (pair? (cdr l)) (string? (cadr l)))
(loop (cddr l)))
(else
(error "hop-xhtml-xmlns" "Illegal namespaces" v))))))
(define *html-4.01-backend*
(instantiate::xml-backend
(id 'html-4.01)
(mime-type "text/html")
(doctype "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"\">")
* ( doctype " < ! DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\ " \" / TR / html4 / loose.dtd\ " > " ) * /
(html-attributes '())
(no-end-tags-elements '(link))
(empty-end-tag #f)
(meta-delimiter ">")))
(define *html5-backend*
(instantiate::xml-backend
(id 'html-5)
(mime-type "text/html")
(doctype "<!DOCTYPE html>")
(html-attributes '())
(no-end-tags-elements '(link))
(meta-delimiter ">")))
* * - backend * ... * /
(define *xhtml-backend*
(instantiate::xml-backend
(id 'xhtml-1.0)
(mime-type "application/xhtml+xml")
(html-attributes (hop-xhtml-xmlns))
(header-format "<?xml version=\"1.0\" encoding=\"~a\"?>\n")
(no-end-tags-elements '())
(cdata-start "\n<![CDATA[\n")
(cdata-stop "]]>\n")
(meta-delimiter "/>")))
(define-parameter hop-xml-backend
*html5-backend*
(lambda (v)
(if (isa? v xml-backend)
v
(hop-get-xml-backend v))))
(define (hop-get-xml-backend id)
(case id
((html html-4.01)
*html-4.01-backend*)
((html5 html-5)
*html5-backend*)
((xhtml xhtml-1.0)
*xhtml-backend*)
(else
(error "hop-get-xml-backend" "Illegal backend" id))))
(define *xml-constructors* (make-hashtable))
(define (xml-constructor-add! id proc)
(if (not (correct-arity? proc 1))
(error "xml-constructor-add!" "Illegal constructor" proc)
(hashtable-put! *xml-constructors* id proc)))
(define-method (%xml-constructor o::xml-markup)
(call-next-method)
(with-access::xml-markup o (body tag attributes)
(for-each (lambda (attr)
(when (isa? attr xml-tilde)
(with-access::xml-tilde attr (parent)
(set! parent o))))
attributes)
(let loop ((es body))
(cond
((pair? es)
(let ((e (car es)))
(cond
((isa? e xml-element)
(with-access::xml-element e (parent)
(set! parent o)))
((isa? e xml-tilde)
(with-access::xml-tilde e (parent)
(set! parent o)))
((pair? e)
(loop e))))
(loop (cdr es)))
((isa? es xml-element)
(with-access::xml-element es (parent)
(set! parent o)))
((isa? es xml-tilde)
(with-access::xml-tilde es (parent)
(set! parent o)))))
o))
(define-method (%xml-constructor o::xml-element)
(call-next-method)
(with-access::xml-element o (id)
(let ((hook (hashtable-get *xml-constructors* id)))
(when (procedure? hook)
(hook o)))
o))
(define (%make-xml-element el args)
(define (symbol-upcase s)
(string->symbol (string-upcase! (symbol->string s))))
(define (el->string el)
(string-append "<" (string-upcase (symbol->string! el)) ">"))
(let loop ((a args)
(attr '())
(body '())
(id #unspecified)
(ctx #f))
(cond
((null? a)
(instantiate::xml-element
(tag el)
(attributes (reverse! attr))
(id (xml-make-id id))
(body (reverse! body))))
((keyword? (car a))
(cond
((not (pair? (cdr a)))
(error (el->string el) "Illegal attribute" (car a)))
((eq? (car a) :id)
(let ((v (xml-primitive-value (cadr a) ctx)))
(if (or (string? v) (not v))
(loop (cddr a) attr body v ctx)
(bigloo-type-error el "string" (cadr a)))))
((eq? (car a) :class)
(let ((v (xml-primitive-value (cadr a) ctx)))
(cond
((or (string? v) (not v))
(loop (cddr a) (cons* v (car a) attr) body id ctx))
((symbol? v)
(loop (cddr a) (cons* (symbol->string! v) (car a) attr) body id ctx))
((eq? v #unspecified)
(loop (cddr a) attr body id ctx))
((isa? v xml-tilde)
(loop (cddr a) (cons* (cadr a) (car a) attr) body id ctx))
(else
(bigloo-type-error el "string" (cadr a))))))
((eq? (car a) :%context)
(loop (cddr a) attr body id (cadr a)))
(else
(loop (cddr a) (cons* (cadr a) (car a) attr) body id ctx))))
((null? (car a))
(loop (cdr a) attr body id ctx))
((xml-unpack (car a) ctx)
=>
(lambda (l)
(if (not (or (null? (cdr a)) (pair? (cdr a))))
(error (el->string el) "Illegal arguments"
`(,(el->string el) ,@args))
(if (or (pair? l) (null? l))
(loop (append l (cdr a)) attr body id ctx)
(loop (cdr a) attr (cons (car a) body) id ctx)))))
(else
(loop (cdr a) attr (cons (car a) body) id ctx)))))
(define (xml-markup-is? o t)
(when (isa? o xml-markup)
(with-access::xml-markup o (tag)
(eq? tag t))))
(define id-count
0)
(define (xml-make-id #!optional id tag)
(if (string? id)
id
(let ((n (fixnum->string id-count)))
(set! id-count (+fx 1 id-count))
(cond
((symbol? id)
(string-append (symbol->string! id) n))
((symbol? tag)
(string-append (symbol->string! tag) n))
(else
(string-append "G" n))))))
(define (xml-event-handler-attribute? keyword)
(substring-ci-at? (keyword->string! keyword) "on" 0))
(define (xml-body body ctx)
(if (null? body)
body
(let ((el (xml-unpack (car body) ctx)))
(if (pair? el)
(append el (xml-body (cdr body) ctx))
(cons el (xml-body (cdr body) ctx))))))
(define-generic (xml-primitive-value x::obj ctx)
x)
(define-generic (xml-unpack obj::obj ctx)
obj)
(define-generic (xml-write obj p backend)
(cond
((string? obj)
(with-access::xml-backend backend (security)
(if (isa? security security-manager)
(with-access::security-manager security (string-sanitize)
(let ((s (string-sanitize obj)))
(when (string? s)
(display s p))))
(display obj p))))
((integer? obj)
(display obj p))
((flonum? obj)
(if (nanfl? obj)
(display "NaN" p)
(display obj p)))
((number? obj)
(display obj p))
((symbol? obj)
#unspecified)
((pair? obj)
(for-each (lambda (o) (xml-write o p backend)) obj))
((date? obj)
(display obj p))
((null? obj)
#unspecified)
((eq? obj #unspecified)
#unspecified)
((eq? obj #f)
#unspecified)
((eq? obj #t)
#unspecified)
((char? obj)
(display obj p))
((ucs2-string? obj)
(let ((s (charset-convert (ucs2-string->utf8-string obj)
'UTF-8 (hop-charset))))
(xml-write s p backend)))
(else
(error "xml" "bad XML object" (xml-to-errstring obj)))))
(define-method (xml-write obj::xml-verbatim p backend)
(with-access::xml-verbatim obj (data)
(display data p)))
(define-method (xml-write obj::xml-comment p backend)
(with-access::xml-comment obj (data)
(display "<!--" p)
(display-string data p)
(display "-->" p)))
(define-method (xml-write obj::xml-if p backend)
(with-access::xml-if obj (test then otherwise)
(if (test)
(xml-write then p backend)
(xml-write otherwise p backend))))
(define-method (xml-write obj::xml-cdata p backend)
(with-access::xml-cdata obj (tag body attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(display ">" p)
(unless (or (not body) (null? body))
(when cdata-start (display cdata-start p))
(xml-write body p backend)
(when cdata-stop (display cdata-stop p)))
(display "</" p)
(display tag p)
(display ">" p))))
(define-method (xml-write obj::xml-style p backend)
(define (xml-write-style el p)
(call-with-input-string el
(lambda (ip)
(let ((hss (hop-read-hss ip)))
(if (isa? hss css-stylesheet)
(css-write (hss-compile hss) p)
(error "xml-write" "Illegal style sheet" el))))))
(with-access::xml-style obj (tag body attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(display ">" p)
(unless (or (not body) (null? body))
(when cdata-start (display cdata-start p))
(let ((op (open-output-string)))
(for-each (lambda (el)
(if (string? el)
(display el op)
(xml-write el op backend)))
body)
(xml-write-style (close-output-port op) p))
(when cdata-stop (display cdata-stop p)))
(display "</" p)
(display tag p)
(display ">" p))))
(define (xml-write-script-tag p closing::bstring)
(let ((mt (hop-mime-type)))
(if (string=? mt "application/x-javascript")
(display "<script" p)
(begin
(display "<script type='" p)
(display mt p)
(display "'" p)))
(display closing p)))
(define-method (xml-write obj::xml-tilde p backend)
(with-access::xml-tilde obj (body parent)
(if (xml-markup-is? parent 'script)
(xml-write (xml-tilde->statement obj) p backend)
(with-access::xml-backend backend (cdata-start cdata-stop)
(xml-write-script-tag p ">")
(when cdata-start (display cdata-start p))
(display (xml-tilde->statement obj) p)
(when cdata-stop (display cdata-stop p))
(display "</script>" p)))))
(define-method (xml-write obj::xml-delay p backend)
(with-access::xml-delay obj (thunk)
(xml-write (thunk) p backend)))
(define-method (xml-write obj::xml-markup p backend)
(with-access::xml-markup obj (tag attributes body)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (security no-end-tags-elements)
(cond
((and (eq? tag 'head) (>=fx (hop-security) 3))
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(when (isa? security security-manager)
(for-each (lambda (r)
(xml-write-script-tag p " src='")
(display r p)
(display "'</script>" p))
(with-access::security-manager security (runtime) runtime)))
(display "</" p)
(display tag p)
(display ">" p))
((or (pair? body) (eq? tag 'script) (eq? tag 'title))
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p))
((memq tag no-end-tags-elements)
(display ">" p))
(else
(display "/>" p))))))
(define-method (xml-write obj::xml-meta p backend)
(with-access::xml-meta obj (tag attributes content body)
(display "<" p)
(display tag p)
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (mime-type meta-delimiter)
(cond
((string? content)
(display " content='" p)
(fprintf p content mime-type (hop-charset))
(display "'" p))
(content
(display " content='" p)
(display mime-type p)
(display "; charset=" p)
(display (hop-charset) p)
(display "'" p)))
(display meta-delimiter p))
(newline p)))
(define-method (xml-write obj::xml-element p backend)
(with-access::xml-element obj (tag id attributes body)
(with-access::xml-backend backend (abbrev-emptyp no-end-tags-elements)
(cond
((and (null? body) (null? attributes))
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(if abbrev-emptyp
(display "/>" p)
(begin
(display "></" p)
(display tag p)
(display ">" p))))
((null? body)
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(cond
(abbrev-emptyp
(display "/>" p))
((memq tag no-end-tags-elements)
(display ">" p))
(else
(display ">" p)
(display "</" p)
(display tag p)
(display ">" p))))
(else
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p)))
(xml-write-initializations obj p backend))))
(define-method (xml-write obj::xml-empty-element p backend)
(with-access::xml-empty-element obj (tag id attributes)
(display "<" p)
(display tag p)
(unless (eq? id #unspecified)
(display " id='" p)
(display id p)
(display "'" p))
(xml-write-attributes attributes p backend)
(with-access::xml-backend backend (empty-end-tag)
(display (if empty-end-tag "/>" ">") p))
(xml-write-initializations obj p backend)))
(define-method (xml-write obj::xml-html p backend)
(if (>=fx (hop-clientc-debug-unbound) 1)
(xml-write-html/unbound-check obj p backend)
(xml-write-html obj p backend)))
(define (xml-write-html/unbound-check obj::xml-html p backend)
(with-access::xml-html obj (body)
(let ((env (make-hashtable)))
(xml-tilde-unbound body env)
(let* ((l (hashtable-map env
(lambda (k v) (when v (cons k v)))))
(lf (let loop ((x l))
(when (pair? x) (or (car x) (loop (cdr x)))))))
(if (pair? lf)
we got at least one
(with-handler
(lambda (e)
(exception-notify e)
(let* ((m (if (epair? (cdr lf))
(match-case (cer (cdr lf))
((at ?file . ?-)
(format "~a: unbound variable" file))
(else
"Unbound variables"))
"Unbound variables"))
(r (http-internal-error e m #f)))
(with-access::http-response-xml r (xml)
(xml-write-html xml p backend))))
(error/source-location "<HTML>"
(format "Unbound client-side variable: ~a" (car lf))
(cadr lf)
(cddr lf)))
(xml-write-html obj p backend))))))
(define (xml-write-html obj::xml-html p backend)
(with-access::xml-backend backend (header-format doctype html-attributes)
(when header-format
(fprintf p header-format (hop-charset)))
(display doctype p)
(newline p)
(with-access::xml-html obj (tag attributes body)
(display "<" p)
(display tag p)
(let ((hattr (let loop ((hattr html-attributes))
(cond
((null? hattr)
'())
((plist-assq (car hattr) attributes)
(loop (cddr hattr)))
(else
(cons* (car hattr)
(cadr hattr)
(loop (cddr hattr))))))))
(xml-write-attributes hattr p backend))
(xml-write-attributes attributes p backend)
(display ">" p)
(for-each (lambda (b) (xml-write b p backend)) body)
(display "</" p)
(display tag p)
(display ">" p))))
(define (xml-write-attributes attr p backend)
(let loop ((a attr))
(when (pair? a)
(display " " p)
(unless (pair? (cdr a))
(error "xml-write-attributes" "Illegal attributes" attr))
(xml-write-attribute (cadr a) (car a) p backend)
(loop (cddr a)))))
(define-generic (xml-write-attribute attr::obj id p backend)
(unless (or (eq? attr #f) (eq? attr #unspecified)
(char=? (string-ref (keyword->string! id) 0) #\%))
(display (keyword->string! id) p)
(display "='" p)
(cond
((eq? attr #t)
(display (keyword->string! id) p))
((procedure? attr)
(if (isa? (procedure-attr attr) hop-service)
(with-access::hop-service (procedure-attr attr) (path)
(display path p))
(error "xml"
"Illegal procedure argument in XML attribute"
id)))
((with-access::xml-backend backend (security) security)
=>
(lambda (sm)
(if (isa? sm security-manager)
(with-access::security-manager sm (attribute-sanitize)
(let ((a (xml-attribute-encode attr)))
(display (attribute-sanitize a id) p)))
(error "xml-write-attribute" "Illegal security-manager" sm))))
(else
(display (xml-attribute-encode attr) p)))
(display "'" p)))
(define-method (xml-write-attribute attr::xml-tilde id p backend)
(when (xml-event-handler-attribute? id)
(display (keyword->string! id) p)
(display "='" p)
(with-access::xml-backend backend ((sm security))
(if (isa? sm security-manager)
(with-access::security-manager sm (attribute-sanitize)
(display (attribute-sanitize attr id) p))
(display (xml-tilde->attribute attr) p)))
(display "'" p)))
(define-method (xml-write-attribute attr::hop-service id p backend)
(display (keyword->string! id) p)
(display "='" p)
(with-access::hop-service attr (path)
(display path p))
(display "'" p))
(define-method (xml-write-attribute attr::xml-lazy-attribute id p backend)
(with-access::xml-lazy-attribute attr (proc)
(xml-write-attribute (proc) id p backend)))
(define-generic (xml-attribute-encode obj)
(if (not (string? obj))
obj
(let ((ol (string-length obj)))
(define (count str ol)
(let loop ((i 0)
(j 0))
(if (=fx i ol)
j
(let ((c (string-ref str i)))
(if (char=? c #\')
(loop (+fx i 1) (+fx j 5))
(loop (+fx i 1) (+fx j 1)))))))
(define (encode str ol nl)
(if (=fx nl ol)
obj
(let ((nstr (make-string nl)))
(let loop ((i 0)
(j 0))
(if (=fx j nl)
nstr
(let ((c (string-ref str i)))
(case c
((#\')
(string-set! nstr j #\&)
(string-set! nstr (+fx j 1) #\#)
(string-set! nstr (+fx j 2) #\3)
(string-set! nstr (+fx j 3) #\9)
(loop (+fx i 1) (+fx j 5)))
(else
(string-set! nstr j c)
(loop (+fx i 1) (+fx j 1))))))))))
(encode obj ol (count obj ol)))))
(define-generic (xml-to-errstring o::obj)
(call-with-output-string
(lambda (op)
(write-circle o op)
(display " `" op)
(display (typeof o) op)
(display "'" op))))
(define (xml-write-initializations obj p backend)
(with-access::xml-element obj (id attributes)
(with-access::xml-backend backend (cdata-start cdata-stop)
(let loop ((attrs attributes)
(var #f))
(cond
((null? attrs)
(when var
(when cdata-stop (display cdata-stop p))
(display "}, false );</script>" p)))
((and (isa? (cadr attrs) xml-tilde)
(not (xml-event-handler-attribute? (car attrs))))
(if var
(begin
(xml-write-initialization (car attrs) (cadr attrs) var p)
(newline p)
(loop (cddr attrs) var))
(let ((var (gensym)))
(xml-write-script-tag p ">")
(when cdata-start (display cdata-start p))
(display "hop_add_event_listener( \"" p)
(display id p)
(display "\", \"ready\", function (e) {" p)
(display "var " p)
(display var p)
(display " = e.value;" p)
(loop attrs var))))
(else
(loop (cddr attrs) var)))))))
(define (xml-write-initialization id tilde var p)
(display "hop.reactAttribute( function() { return " p)
(if (eq? id :style)
(xml-write-style-initialization tilde var p)
(begin
(display var p)
(display "[\"" p)
(display (if (eq? id :class) "className" (keyword->string! id)) p)
(display "\"]=" p)
(xml-write-expression tilde p)
(display ";" p)))
(display "}.bind( this ) );" p))
* because its value can be evaluated to a JavaScript object . * /
(define (xml-write-style-initialization tilde var p)
(display "hop_style_attribute_set(" p)
(display var p)
(display "," p)
(xml-write-expression tilde p)
(display ");" p))
(define (xml->string obj backend)
(with-output-to-string
(lambda ()
(xml-write obj (current-output-port) backend))))
(define (eval-markup constr attributes body)
(case constr
((<HEAD>)
The Hop head constructor is special because it implicitly introduces
the Hop rts . In order to avoid this here , head is explicitly created .
(instantiate::xml-markup
(tag 'head)
(attributes attributes)
(body body)))
(else
(let* ((a (append-map (lambda (a)
(list (symbol->keyword (car a)) (cdr a)))
attributes))
(constr (with-handler
(lambda (e)
(with-access::&error e (msg)
(if (string=? msg "Unbound variable")
(lambda l
(instantiate::xml-markup
(tag constr)
(attributes a)
(body body)))
(raise e))))
(eval constr))))
(if (procedure? constr)
(apply constr (append a body))
(error "string->xml" "Illegal markup" constr))))))
(define (parse-html ip clen)
(html-parse ip
:content-length clen
:eoi (lambda (o) (isa? o xml-markup))
:procedure (lambda (tag attributes body)
(let ((constr (string->symbol
(string-append
"<"
(string-upcase (symbol->string! tag))
">"))))
(eval-markup constr attributes body)))))
(define (string->html h)
(call-with-input-string h (lambda (ip) (parse-html ip 0))))
(define (string->xml h)
(call-with-input-string h
(lambda (in)
(xml-parse in
:content-length 0
:procedure (lambda (tag attributes body)
(let ((constr (string->symbol
(string-append
"<"
(string-upcase (symbol->string! tag))
">"))))
(eval-markup constr attributes body)))))))
(define (xml-tilde->expression::bstring obj)
(with-access::xml-tilde obj (%js-expression body debug)
(unless (string? %js-expression)
(with-access::clientc (hop-clientc) (precompiled->JS-expression)
(set! %js-expression (precompiled->JS-expression body debug))))
%js-expression))
(define (xml-tilde->statement::bstring obj)
(define (element-attribute el)
(with-access::xml-element el (attributes)
(let loop ((attributes attributes))
(if (or (null? attributes) (null? (cdr attributes)))
#f
(if (and (keyword? (car attributes))
(eq? (cadr attributes) obj))
(car attributes)
(loop (cddr attributes)))))))
(define (parent-context parent)
(cond
((string? parent)
parent)
((isa? parent xml-element)
(with-access::xml-element parent (tag id)
(let ((attr (element-attribute parent)))
(cond
((eq? id #unspecified)
(symbol->string tag))
((not attr)
(format "~a#~a" tag id))
(else
(format "~a#~a.~a" tag id (keyword->string attr)))))))
(else
"")))
(define (js-catch-callback/location stmt parent file point)
(let ((ctx (gensym 'ctx)))
try { ~a } catch( e ) {
ctx
(string-replace (xml-attribute-encode (parent-context parent))
#\Newline #\Space)
file point ctx stmt
ctx)))
(define (js-catch-callback stmt parent)
(let ((ctx (gensym 'ctx)))
ctx
(string-replace (xml-attribute-encode (parent-context parent))
#\Newline #\Space)
ctx
stmt
ctx)))
(with-access::xml-tilde obj (%js-statement body loc parent debug)
(unless (string? %js-statement)
(with-access::clientc (hop-clientc) (precompiled->JS-statement)
(let ((stmt (precompiled->JS-statement body debug)))
(if debug
(match-case loc
((at (and (? string?) ?file) (and (? integer?) ?point))
(set! %js-statement
(js-catch-callback/location stmt parent file point)))
(else
(set! %js-statement
(js-catch-callback stmt parent))))
(set! %js-statement stmt)))))
%js-statement))
(define (xml-tilde->return::bstring obj)
(with-access::xml-tilde obj (%js-return body debug)
(when (not (string? %js-return))
(with-access::clientc (hop-clientc) (precompiled->JS-return)
(set! %js-return (precompiled->JS-return body debug))))
%js-return))
(define (xml-tilde->attribute obj)
(with-access::xml-tilde obj (%js-attribute)
(if (string? %js-attribute)
%js-attribute
(let ((js-attr (xml-attribute-encode (xml-tilde->statement obj))))
(set! %js-attribute js-attr)
js-attr))))
(define (xml-tilde->sexp obj)
(define (wrapper o)
`(pragma
,(call-with-output-string
(lambda (op)
(obj->javascript-attr o op)))))
(with-access::xml-tilde obj (lang body %js-expression)
(if (eq? lang 'javascript)
`(pragma ,%js-expression)
(with-access::clientc (hop-clientc) (precompiled->sexp)
(precompiled->sexp body wrapper)))))
(define (sexp->xml-tilde obj #!key env menv %context)
(with-access::clientc (hop-clientc) (macroe sexp->precompiled)
(let* ((env (or env (current-module-clientc-import)))
(menv (or menv (macroe)))
(c (sexp->precompiled obj env menv %context)))
(<TILDE> c :src obj))))
(define (<TILDE> body #!key src loc)
(instantiate::xml-tilde
(body body)
(src src)
(loc loc)))
(define-tag <DELAY> ((id #unspecified string)
body)
(if (and (pair? body) (procedure? (car body)) (correct-arity? (car body) 0))
(instantiate::xml-delay
(id (xml-make-id id))
(thunk (car body)))
(error "<DELAY>" "Illegal thunk" (car body))))
(define (<PRAGMA> . obj)
(cond
((and (pair? obj) (null? (cdr obj)) (string? (car obj)))
(instantiate::xml-verbatim (data (car obj))))
((every string? obj)
(instantiate::xml-verbatim (data (apply string-append obj))))
(else
(error "<PRAGMA>" "Illegal arguments" obj))))
(define-generic (xml-write-expression obj p)
(cond
((string? obj)
(display "'" p)
(display (string-escape obj #\') p)
(display "'" p))
((eq? obj #t)
(display "true" p))
((eq? obj #f)
(display "false" p))
((eq? obj #unspecified)
(display "undefined" p))
(else
(display obj p))))
(define-method (xml-write-expression obj::xml-tilde p)
(display (xml-tilde->expression obj) p))
(define-generic (xml-tilde-unbound obj::obj env)
(if (pair? obj)
(for-each (lambda (x) (xml-tilde-unbound x env)) obj)
'()))
(define-method (xml-tilde-unbound obj::xml-if env)
(with-access::xml-if obj (test then otherwise)
(xml-tilde-unbound test env)
(xml-tilde-unbound then env)
(xml-tilde-unbound otherwise env)))
(define-method (xml-tilde-unbound obj::xml-markup env)
(with-access::xml-markup obj (tag body attributes)
(xml-tilde-unbound body env)
(let ((old (hashtable-get env 'event)))
(unless old (hashtable-put! env 'event #f))
(for-each (lambda (a)
(when (isa? a xml-tilde)
(xml-tilde-unbound a env)))
attributes)
(unless old (hashtable-remove! env 'event)))))
(define-method (xml-tilde-unbound obj::xml-tilde env)
(define (source-location src)
(when (epair? src) (cer src)))
(with-access::xml-tilde obj (body src)
(with-access::clientc (hop-clientc)
(precompiled-declared-variables precompiled-free-variables)
(when (vector? body)
(for-each (lambda (v)
(let ((v (car v)))
(hashtable-update! env v (lambda (x) #f) #f)))
(precompiled-declared-variables body))
(for-each (lambda (v)
(let ((v (car v))
(loc (caddr v)))
(hashtable-update! env v (lambda (x) #f)
(cons src (or loc (source-location src))))))
(precompiled-free-variables body))))))
* Apply proc to all the URLs ( href , ) found in OBJ . * /
(define (xml-url-for-each obj::obj proc::procedure)
(xml-url-for-each-inner obj (make-cell #f) proc))
(define (xml-url-base s base)
(if (char=? (string-ref s 0) #\/)
s
(let ((b (cell-ref base)))
(if (or (not (string? b)) (string-null? b))
s
(string-append b s)))))
(define (xml-url-for-each-attributes obj base::cell key proc)
(with-access::xml-cdata obj (tag body attributes)
(with-access::xml-markup obj (attributes)
(let ((a (plist-assq key attributes)))
(when (and a (string? (cadr a)))
(unless (or (string-prefix? "data:" (cadr a))
(string-prefix? "http:" (cadr a))
(string-prefix? "https:" (cadr a)))
(let* ((i (string-index (cadr a) #\?))
(s (if i (substring (cadr a) 0 i) (cadr a))))
(unless (string-null? s)
(proc obj (xml-url-base s base))))))))))
(define-generic (xml-url-for-each-inner obj::obj base::cell proc::procedure)
(when (pair? obj)
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) obj)))
(define-method (xml-url-for-each-inner obj::xml-markup base proc)
(with-access::xml-markup obj (tag body attributes)
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) body)
(when (eq? tag 'head)
(let ((a (plist-assq :%authorizations attributes)))
(when (pair? a)
(cond
((string? (cadr a))
(proc obj (xml-url-base a base)))
((list? (cadr a))
(for-each (lambda (a) (proc obj (xml-url-base a base)))
(cadr a)))))))))
(define-method (xml-url-for-each-inner obj::xml-element base proc)
(with-access::xml-element obj (tag body)
(case tag
((link)
(xml-url-for-each-attributes obj base :href proc)))
(for-each (lambda (o) (xml-url-for-each-inner o base proc)) body)))
(define-method (xml-url-for-each-inner obj::xml-cdata base proc)
(xml-url-for-each-attributes obj base :src proc)
(call-next-method))
(define-method (xml-url-for-each-inner obj::xml-svg base proc)
(xml-url-for-each-attributes obj base :src proc)
(call-next-method))
(define-method (xml-url-for-each-inner obj::xml-empty-element base proc)
(with-access::xml-empty-element obj (tag attributes)
(case tag
((img)
(xml-url-for-each-attributes obj base :src proc))
((base)
(let ((h (plist-assq :href attributes)))
(when (and (pair? h) (string? (cadr h)))
(cell-set! base (cadr h))))))))
(define (xml-tilde* t0::xml-tilde . rest)
(let ((err (filter (lambda (x) (not (isa? x xml-tilde))) rest)))
(when (pair? err)
(bigloo-type-error "xml-tilde*" "xml-tilde" (car err))))
(duplicate::xml-tilde t0
(src (map (lambda (t)
(with-access::xml-tilde t (src)
src))
(cons t0 rest)))
(%js-expression (apply string-append
(cons (xml-tilde->expression t0)
(append-map (lambda (t)
(list ","
(xml-tilde->expression t)))
rest))))
(%js-statement (apply string-append
(cons (xml-tilde->statement t0)
(append-map (lambda (t)
(list ";"
(xml-tilde->statement t)))
rest))))
(%js-return (cond
((null? rest)
(xml-tilde->return t0))
((null? (cdr rest))
(string-append
(xml-tilde->statement t0)
";"
(xml-tilde->return (car rest))))
((null? (cddr rest))
(string-append
(xml-tilde->statement t0)
";"
(xml-tilde->statement (car rest))
";"
(xml-tilde->return (cadr rest))))
(else
(string-append
(apply string-append
(cons (xml-tilde->statement t0)
(append
(append-map (lambda (t)
(list ";"
(xml-tilde->statement t)))
(reverse (cdr (reverse rest)))))))
";"
(xml-tilde->return (car (last-pair rest)))))))
(%js-attribute (apply string-append
(cons (xml-tilde->expression t0)
(append-map (lambda (t)
(list ";"
(xml-tilde->expression t)))
rest))))))
|
11574210cbf1cd78ca78cae2cf8dea17c9c1ce5b742c1be307332004ec7c0a61 | HaskellZhangSong/Introduction_to_Haskell_2ed_source | SpawnSupervised.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveAnyClass #-}
module Main where
import GHC.Generics
import Data.Binary
import Data.Rank1Typeable
import Control.Monad
import Control.Distributed.Process
import Control.Distributed.Process.Closure
import Control.Distributed.Process.Node (initRemoteTable, runProcess)
import Control.Distributed.Process.Backend.SimpleLocalnet
data Task = Task ProcessId Double Double
deriving (Generic, Typeable, Binary)
doTask :: Double -> Double -> Process Double
doTask n d = do
when (d == 0) $ die "Denominator cannot be zero!"
return (n / d)
worker :: NodeId -> Process ()
worker nid = forever $ do
Task pid n d <- expect
res <- callLocal $ doTask n d
send pid res
remotable ['worker]
main :: IO ()
main = do
backend <- initializeBackend "localhost" "2000" $ __remoteTable initRemoteTable
node <- newLocalNode backend
runProcess node $ do
nid <- getSelfNode
pid <- getSelfPid
(wpid, _) <- spawnSupervised nid ($(mkClosure 'worker) nid)
send wpid $ Task pid 5 2
receiveWait
[ match $ \(res :: Double) ->
liftIO $ putStrLn $ "Succeed: " ++ show res
, match $ \(pmn :: ProcessMonitorNotification) ->
liftIO $ putStrLn $ "Worker died: " ++ show pmn ]
| null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C21/SpawnSupervised.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveAnyClass # | # LANGUAGE TemplateHaskell #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DeriveGeneric #
module Main where
import GHC.Generics
import Data.Binary
import Data.Rank1Typeable
import Control.Monad
import Control.Distributed.Process
import Control.Distributed.Process.Closure
import Control.Distributed.Process.Node (initRemoteTable, runProcess)
import Control.Distributed.Process.Backend.SimpleLocalnet
data Task = Task ProcessId Double Double
deriving (Generic, Typeable, Binary)
doTask :: Double -> Double -> Process Double
doTask n d = do
when (d == 0) $ die "Denominator cannot be zero!"
return (n / d)
worker :: NodeId -> Process ()
worker nid = forever $ do
Task pid n d <- expect
res <- callLocal $ doTask n d
send pid res
remotable ['worker]
main :: IO ()
main = do
backend <- initializeBackend "localhost" "2000" $ __remoteTable initRemoteTable
node <- newLocalNode backend
runProcess node $ do
nid <- getSelfNode
pid <- getSelfPid
(wpid, _) <- spawnSupervised nid ($(mkClosure 'worker) nid)
send wpid $ Task pid 5 2
receiveWait
[ match $ \(res :: Double) ->
liftIO $ putStrLn $ "Succeed: " ++ show res
, match $ \(pmn :: ProcessMonitorNotification) ->
liftIO $ putStrLn $ "Worker died: " ++ show pmn ]
|
bb26779a1b5af0fbc5e5d17c6a83e52bff0710a14c5e51a27d64316e0f894c16 | ocamllabs/ocaml-modular-implicits | test.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
open Printf;;
let flush_all () = flush stdout; flush stderr;;
let message s = print_string s; print_newline ();;
let error_occurred = ref false;;
let immediate_failure = ref true;;
let error () =
if !immediate_failure then exit 2 else begin
error_occurred := true;
flush_all ();
false
end;;
let success () = flush_all (); true;;
let function_tested = ref "";;
let testing_function s =
flush_all ();
function_tested := s;
print_newline();
message s;;
let test test_number eq_fun (answer, correct_answer) =
flush_all ();
if not (eq_fun answer correct_answer) then begin
fprintf stderr ">>> Bad result (%s, test %d)\n" !function_tested test_number;
error ()
end else begin
printf " %d..." test_number;
success ()
end;;
let failure_test test_number fun_to_test arg =
flush_all ();
try
fun_to_test arg;
fprintf stderr ">>> Failure expected (%s, test %d)\n"
!function_tested test_number;
error ()
with _ ->
printf " %d..." test_number;
success ();;
let failwith_test test_number fun_to_test arg correct_failure =
flush_all ();
try
fun_to_test arg;
fprintf stderr ">>> Failure expected (%s, test %d)\n"
!function_tested test_number;
error ()
with x ->
if x = correct_failure then begin
printf " %d..." test_number;
success ()
end else begin
fprintf stderr ">>> Bad failure (%s, test %d)\n"
!function_tested test_number;
error ()
end;;
let end_tests () =
flush_all ();
print_newline ();
if !error_occurred then begin
print_endline "************* TESTS FAILED ****************"; exit 2
end else begin
print_endline "************* TESTS COMPLETED SUCCESSFULLY ****************";
exit 0
end;;
let eq = (==);;
let eq_int (i: int) (j: int) = (i = j);;
let eq_string (i: string) (j: string) = (i = j);;
let eq_nativeint (i: nativeint) (j: nativeint) = (i = j);;
let eq_int32 (i: int32) (j: int32) = (i = j);;
let eq_int64 (i: int64) (j: int64) = (i = j);;
let sixtyfour = (1 lsl 31) <> 0;;
let rec gcd_int i1 i2 =
if i2 = 0 then abs i1 else gcd_int i2 (i1 mod i2);;
let rec num_bits_int_aux n =
if n = 0 then 0 else succ(num_bits_int_aux (n lsr 1));;
let num_bits_int n = num_bits_int_aux (abs n);;
let sign_int i = if i = 0 then 0 else if i > 0 then 1 else -1;;
let length_of_int = Sys.word_size - 2;;
let monster_int = 1 lsl length_of_int;;
let biggest_int = monster_int - 1;;
let least_int = - biggest_int;;
let compare_int n1 n2 =
if n1 == n2 then 0 else if n1 > n2 then 1 else -1;;
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/lib-num/test.ml | ocaml | *********************************************************************
OCaml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Printf;;
let flush_all () = flush stdout; flush stderr;;
let message s = print_string s; print_newline ();;
let error_occurred = ref false;;
let immediate_failure = ref true;;
let error () =
if !immediate_failure then exit 2 else begin
error_occurred := true;
flush_all ();
false
end;;
let success () = flush_all (); true;;
let function_tested = ref "";;
let testing_function s =
flush_all ();
function_tested := s;
print_newline();
message s;;
let test test_number eq_fun (answer, correct_answer) =
flush_all ();
if not (eq_fun answer correct_answer) then begin
fprintf stderr ">>> Bad result (%s, test %d)\n" !function_tested test_number;
error ()
end else begin
printf " %d..." test_number;
success ()
end;;
let failure_test test_number fun_to_test arg =
flush_all ();
try
fun_to_test arg;
fprintf stderr ">>> Failure expected (%s, test %d)\n"
!function_tested test_number;
error ()
with _ ->
printf " %d..." test_number;
success ();;
let failwith_test test_number fun_to_test arg correct_failure =
flush_all ();
try
fun_to_test arg;
fprintf stderr ">>> Failure expected (%s, test %d)\n"
!function_tested test_number;
error ()
with x ->
if x = correct_failure then begin
printf " %d..." test_number;
success ()
end else begin
fprintf stderr ">>> Bad failure (%s, test %d)\n"
!function_tested test_number;
error ()
end;;
let end_tests () =
flush_all ();
print_newline ();
if !error_occurred then begin
print_endline "************* TESTS FAILED ****************"; exit 2
end else begin
print_endline "************* TESTS COMPLETED SUCCESSFULLY ****************";
exit 0
end;;
let eq = (==);;
let eq_int (i: int) (j: int) = (i = j);;
let eq_string (i: string) (j: string) = (i = j);;
let eq_nativeint (i: nativeint) (j: nativeint) = (i = j);;
let eq_int32 (i: int32) (j: int32) = (i = j);;
let eq_int64 (i: int64) (j: int64) = (i = j);;
let sixtyfour = (1 lsl 31) <> 0;;
let rec gcd_int i1 i2 =
if i2 = 0 then abs i1 else gcd_int i2 (i1 mod i2);;
let rec num_bits_int_aux n =
if n = 0 then 0 else succ(num_bits_int_aux (n lsr 1));;
let num_bits_int n = num_bits_int_aux (abs n);;
let sign_int i = if i = 0 then 0 else if i > 0 then 1 else -1;;
let length_of_int = Sys.word_size - 2;;
let monster_int = 1 lsl length_of_int;;
let biggest_int = monster_int - 1;;
let least_int = - biggest_int;;
let compare_int n1 n2 =
if n1 == n2 then 0 else if n1 > n2 then 1 else -1;;
|
3b5b6e4cc8d316407fc98e36561d22e6441b1ac4ed778cd9820fc37ce43efbd2 | stevenvar/OMicroB | avr.mli | (*******************************************************************************)
(* *)
(* Generic avr pin communication library *)
(* *)
(*******************************************************************************)
type level = HIGH | LOW
type mode = INPUT | OUTPUT | INPUT_PULLUP
module type AvrPins = sig
type 'a pin
type register
type bit
val port_of_pin: 'a pin -> register
val ddr_of_pin: 'a pin -> register
val input_of_pin: 'a pin -> register
val port_bit_of_pin : 'a pin -> bit
val ddr_bit_of_pin : 'a pin -> bit
val input_bit_of_pin : 'a pin -> bit
val pin_mode : 'a pin -> mode -> unit
val digital_write : [ `DWRITE ] pin -> level -> unit
val digital_read : [ `DREAD ] pin -> level
val analog_read : [ `AREAD ] pin -> int
val write_register : register -> int -> unit
val read_register : register -> int
val set_bit : register -> bit -> unit
val clear_bit : register -> bit -> unit
val read_bit : register -> bit -> bool
val pin_change_callback: [ `DREAD ] pin -> (unit -> unit) -> unit
end
val delay : int -> unit
val millis : unit -> int
module Serial : sig
val init : unit -> unit
val read : unit -> char
val write : char -> unit
val write_string : string -> unit
val write_int : int -> unit
end
module type Timer = sig
val set_period : int -> unit
val set_callback : (unit -> unit) -> unit
end
module Timer0: Timer
module Timer2: Timer
| null | https://raw.githubusercontent.com/stevenvar/OMicroB/99a2e781f9511137090aaba3c09e2e920c0dbc77/targets/avr/avr.mli | ocaml | *****************************************************************************
Generic avr pin communication library
***************************************************************************** |
type level = HIGH | LOW
type mode = INPUT | OUTPUT | INPUT_PULLUP
module type AvrPins = sig
type 'a pin
type register
type bit
val port_of_pin: 'a pin -> register
val ddr_of_pin: 'a pin -> register
val input_of_pin: 'a pin -> register
val port_bit_of_pin : 'a pin -> bit
val ddr_bit_of_pin : 'a pin -> bit
val input_bit_of_pin : 'a pin -> bit
val pin_mode : 'a pin -> mode -> unit
val digital_write : [ `DWRITE ] pin -> level -> unit
val digital_read : [ `DREAD ] pin -> level
val analog_read : [ `AREAD ] pin -> int
val write_register : register -> int -> unit
val read_register : register -> int
val set_bit : register -> bit -> unit
val clear_bit : register -> bit -> unit
val read_bit : register -> bit -> bool
val pin_change_callback: [ `DREAD ] pin -> (unit -> unit) -> unit
end
val delay : int -> unit
val millis : unit -> int
module Serial : sig
val init : unit -> unit
val read : unit -> char
val write : char -> unit
val write_string : string -> unit
val write_int : int -> unit
end
module type Timer = sig
val set_period : int -> unit
val set_callback : (unit -> unit) -> unit
end
module Timer0: Timer
module Timer2: Timer
|
bd3f1aef1d4e513809c1e0d0bba8b521d25e19f3983fb9abbf3a9ab7f82a2f35 | Decentralized-Pictures/T4L3NT | data.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
module Command = struct
type t =
Activate a protocol
| Activate of {
protocol: Protocol_hash.t ;
fitness: Fitness.t ;
protocol_parameters : MBytes.t ;
}
Activate a protocol as a testchain
| Activate_testchain of {
protocol: Protocol_hash.t ;
delay: Int64.t ;
}
let mk_case name args =
let open Data_encoding in
conv
(fun o -> ((), o))
(fun ((), o) -> o)
(merge_objs
(obj1 (req "command" (constant name)))
args)
let encoding =
let open Data_encoding in
union ~tag_size:`Uint8 [
case (Tag 0)
~title:"Activate"
(mk_case "activate"
(obj3
(req "hash" Protocol_hash.encoding)
(req "fitness" Fitness.encoding)
(req "protocol_parameters" Variable.bytes)
))
(function
| Activate { protocol ; fitness ; protocol_parameters} ->
Some (protocol, fitness, protocol_parameters)
| _ -> None)
(fun (protocol, fitness, protocol_parameters) ->
Activate { protocol ; fitness ; protocol_parameters }) ;
case (Tag 1)
~title:"Activate_testchain"
(mk_case "activate_testchain"
(obj2
(req "hash" Protocol_hash.encoding)
(req "validity_time" int64)))
(function
| Activate_testchain { protocol ; delay } ->
Some (protocol, delay)
| _ -> None)
(fun (protocol, delay) ->
Activate_testchain { protocol ; delay }) ;
]
let signed_encoding =
let open Data_encoding in
obj2
(req "content" encoding)
(req "signature" Signature.encoding)
let forge shell command =
Data_encoding.Binary.to_bytes_exn
(Data_encoding.tup2 Block_header.shell_header_encoding encoding)
(shell, command)
end
module Pubkey = struct
let pubkey_key = ["genesis_key"]
let default =
Signature.Public_key.of_b58check_exn
"edpkvVCdQtDJHPnkmfRZuuHWKzFetH9N9nGP8F7zkwM2BJpjbvAU1N"
let get_pubkey ctxt =
Context.get ctxt pubkey_key >>= function
| None -> Lwt.return default
| Some b ->
match Data_encoding.Binary.of_bytes Signature.Public_key.encoding b with
| None -> Lwt.return default
| Some pk -> Lwt.return pk
let set_pubkey ctxt v =
Context.set ctxt pubkey_key @@
Data_encoding.Binary.to_bytes_exn Signature.Public_key.encoding v
let sandbox_encoding =
let open Data_encoding in
merge_objs
(obj1 (req "genesis_pubkey" Signature.Public_key.encoding))
Data_encoding.unit
let may_change_default ctxt json =
match Data_encoding.Json.destruct sandbox_encoding json with
| exception _ ->
Lwt.return ctxt
| (pubkey, ()) ->
set_pubkey ctxt pubkey >>= fun ctxt ->
Lwt.return ctxt
end
module Init = struct
type error += Incompatible_protocol_version
let version_key = ["version"]
(* This key should always be populated for every version of the
protocol. It's absence meaning that the context is empty. *)
let version_value = "genesis"
let check_inited ctxt =
Context.get ctxt version_key >>= function
| None -> failwith "Internal error: uninitialized context."
| Some version ->
if Compare.String.(version_value <> MBytes.to_string version) then
failwith "Internal error: incompatible protocol version" ;
return_unit
let tag_first_block ctxt =
Context.get ctxt version_key >>= function
| None ->
Context.set
ctxt version_key (MBytes.of_string version_value) >>= fun ctxt ->
return ctxt
| Some _version ->
failwith "Internal error: previously initialized context." ;
end
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_000_Ps9mPmXa/lib_protocol/data.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
This key should always be populated for every version of the
protocol. It's absence meaning that the context is empty. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
module Command = struct
type t =
Activate a protocol
| Activate of {
protocol: Protocol_hash.t ;
fitness: Fitness.t ;
protocol_parameters : MBytes.t ;
}
Activate a protocol as a testchain
| Activate_testchain of {
protocol: Protocol_hash.t ;
delay: Int64.t ;
}
let mk_case name args =
let open Data_encoding in
conv
(fun o -> ((), o))
(fun ((), o) -> o)
(merge_objs
(obj1 (req "command" (constant name)))
args)
let encoding =
let open Data_encoding in
union ~tag_size:`Uint8 [
case (Tag 0)
~title:"Activate"
(mk_case "activate"
(obj3
(req "hash" Protocol_hash.encoding)
(req "fitness" Fitness.encoding)
(req "protocol_parameters" Variable.bytes)
))
(function
| Activate { protocol ; fitness ; protocol_parameters} ->
Some (protocol, fitness, protocol_parameters)
| _ -> None)
(fun (protocol, fitness, protocol_parameters) ->
Activate { protocol ; fitness ; protocol_parameters }) ;
case (Tag 1)
~title:"Activate_testchain"
(mk_case "activate_testchain"
(obj2
(req "hash" Protocol_hash.encoding)
(req "validity_time" int64)))
(function
| Activate_testchain { protocol ; delay } ->
Some (protocol, delay)
| _ -> None)
(fun (protocol, delay) ->
Activate_testchain { protocol ; delay }) ;
]
let signed_encoding =
let open Data_encoding in
obj2
(req "content" encoding)
(req "signature" Signature.encoding)
let forge shell command =
Data_encoding.Binary.to_bytes_exn
(Data_encoding.tup2 Block_header.shell_header_encoding encoding)
(shell, command)
end
module Pubkey = struct
let pubkey_key = ["genesis_key"]
let default =
Signature.Public_key.of_b58check_exn
"edpkvVCdQtDJHPnkmfRZuuHWKzFetH9N9nGP8F7zkwM2BJpjbvAU1N"
let get_pubkey ctxt =
Context.get ctxt pubkey_key >>= function
| None -> Lwt.return default
| Some b ->
match Data_encoding.Binary.of_bytes Signature.Public_key.encoding b with
| None -> Lwt.return default
| Some pk -> Lwt.return pk
let set_pubkey ctxt v =
Context.set ctxt pubkey_key @@
Data_encoding.Binary.to_bytes_exn Signature.Public_key.encoding v
let sandbox_encoding =
let open Data_encoding in
merge_objs
(obj1 (req "genesis_pubkey" Signature.Public_key.encoding))
Data_encoding.unit
let may_change_default ctxt json =
match Data_encoding.Json.destruct sandbox_encoding json with
| exception _ ->
Lwt.return ctxt
| (pubkey, ()) ->
set_pubkey ctxt pubkey >>= fun ctxt ->
Lwt.return ctxt
end
module Init = struct
type error += Incompatible_protocol_version
let version_key = ["version"]
let version_value = "genesis"
let check_inited ctxt =
Context.get ctxt version_key >>= function
| None -> failwith "Internal error: uninitialized context."
| Some version ->
if Compare.String.(version_value <> MBytes.to_string version) then
failwith "Internal error: incompatible protocol version" ;
return_unit
let tag_first_block ctxt =
Context.get ctxt version_key >>= function
| None ->
Context.set
ctxt version_key (MBytes.of_string version_value) >>= fun ctxt ->
return ctxt
| Some _version ->
failwith "Internal error: previously initialized context." ;
end
|
fff836bdfc3702feeecd7d40a994439de8fc7fc039e5140b36a7e4f2435d2d45 | kumarshantanu/ring-sse-middleware | immutant_test.clj | 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 LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns ring-sse-middleware.immutant-test
(:require
[ring-sse-middleware.test-util :as tu]
[ring-sse-middleware.core :as r]
[ring-sse-middleware.adapter.immutant :as adapter]
[immutant.web :as immutant]))
(def wrapped-handler (-> tu/handler
(r/streaming-middleware adapter/generate-stream)))
(defn -main
[& args]
(println "Starting Immutant server")
(immutant/run wrapped-handler
{:port 3000}))
| null | https://raw.githubusercontent.com/kumarshantanu/ring-sse-middleware/67dae006cfda2fa2fef93eea92557aeffff0b6a7/test/ring_sse_middleware/immutant_test.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 LICENSE 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. | Copyright ( c ) . All rights reserved .
(ns ring-sse-middleware.immutant-test
(:require
[ring-sse-middleware.test-util :as tu]
[ring-sse-middleware.core :as r]
[ring-sse-middleware.adapter.immutant :as adapter]
[immutant.web :as immutant]))
(def wrapped-handler (-> tu/handler
(r/streaming-middleware adapter/generate-stream)))
(defn -main
[& args]
(println "Starting Immutant server")
(immutant/run wrapped-handler
{:port 3000}))
|
d2d8808a7c619f0909dc6b88b5b2fd7511fbde674fb6c87b7c896ea4d57da299 | sjl/temperance | circle.lisp | (in-package :temperance.test.circle)
(defmacro is-circle-contents (circle values)
`(is (equal ,values
(circle-to-list ,circle))))
(define-test empty-circles
(is (circle-empty-p (make-empty-circle)))
(is (circle-empty-p (make-circle-with nil)))
(is (not (circle-empty-p (make-circle-with (list 1))))))
(define-test making-circle-with
(is-circle-contents
(make-circle-with (list))
nil)
(is-circle-contents
(make-circle-with (list 1 2 3))
(list 1 2 3))
(is-circle-contents
(make-circle-with '(foo))
(list 'foo))
(is-circle-contents
(make-circle-with '((foo)))
(list (list 'foo))))
(define-test prepending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-prepend c (list 1))
(is-circle-contents c '(1))
(circle-prepend c (list 2 3))
(is-circle-contents c '(2 3 1))
(circle-prepend c nil)
(is-circle-contents c '(2 3 1))))
(define-test appending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-append c (list 1))
(is-circle-contents c '(1))
(circle-append c (list 2 3))
(is-circle-contents c '(1 2 3))
(circle-append c nil)
(is-circle-contents c '(1 2 3))))
(define-test appending-and-prepending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-append c (list 1))
(is-circle-contents c '(1))
(circle-prepend c (list 'a 'b))
(is-circle-contents c '(a b 1))
(circle-append c (list 'p 'q))
(is-circle-contents c '(a b 1 p q))))
(define-test moving-forward
(let ((c (make-circle-with (list 1 2 3 4))))
(is (equal
'(1 2 3 4)
(loop :for node = (circle-forward c) :then (circle-forward node)
:while node
:collect (circle-value node))))))
(define-test moving-backward
(let ((c (make-circle-with (list 1 2 3 4))))
(is (equal
'(4 3 2 1)
(loop :for node = (circle-backward c) :then (circle-backward node)
:while node
:collect (circle-value node))))))
(define-test rotating
(let ((c (make-circle-with (list 1 2 3 4))))
(is-circle-contents (circle-rotate c 0)
'(1 2 3 4))
(is-circle-contents (circle-rotate c 1)
'(1 2 3 4))
(is-circle-contents (circle-rotate c 2)
'(2 3 4 1))
(is-circle-contents (circle-rotate c 3)
'(3 4 1 2))
(is-circle-contents (circle-rotate c 4)
'(4 1 2 3))
(is-circle-contents (circle-rotate c 5)
'(1 2 3 4))
(is-circle-contents (circle-rotate c -1)
'(4 1 2 3))
(is-circle-contents (circle-rotate c -2)
'(3 4 1 2))
(is-circle-contents (circle-rotate c -3)
'(2 3 4 1))
(is-circle-contents (circle-rotate c -4)
'(1 2 3 4))
(is-circle-contents (circle-rotate (circle-rotate c 2) 0)
'(2 3 4 1))
(is-circle-contents (circle-rotate (circle-rotate c 2) 1)
'(3 4 1 2))
(is-circle-contents (circle-rotate (circle-rotate c 2) 2)
'(4 1 2 3))
(is-circle-contents (circle-rotate (circle-rotate c 2) -2)
'(1 2 3 4))
(is-circle-contents (circle-rotate (circle-rotate c 3) -1)
'(2 3 4 1))))
(define-test retrieving-nth
(let* ((data (list 'a 'b 'c 'd))
(c (make-circle-with data)))
(loop :for i :from 0 :below 4
:for v :in data
:do (is (eql v (circle-value (circle-nth c i)))))))
(define-test inserting-before
(let ((c (make-circle-with (list 1 2 3))))
(circle-insert-before c 'a)
(is-circle-contents c '(1 2 3 a))
(circle-insert-before (circle-nth c 0) 'b)
(is-circle-contents c '(b 1 2 3 a))
(circle-insert-before (circle-nth c 1) 'c)
(is-circle-contents c '(b c 1 2 3 a))
(circle-insert-before (circle-nth c 2) 'd)
(is-circle-contents c '(b c d 1 2 3 a))
(circle-insert-before (circle-nth c -1) 'e)
(is-circle-contents c '(b c d 1 2 3 e a))))
(define-test inserting-after
(let ((c (make-circle-with (list 1 2 3))))
(circle-insert-after c 'a)
(is-circle-contents c '(a 1 2 3))
(circle-insert-after (circle-nth c 0) 'b)
(is-circle-contents c '(a b 1 2 3))
(circle-insert-after (circle-nth c 1) 'c)
(is-circle-contents c '(a b c 1 2 3))
(circle-insert-after (circle-nth c 2) 'd)
(is-circle-contents c '(a b c d 1 2 3))
(circle-insert-after (circle-nth c -1) 'x)
(is-circle-contents c '(a b c d 1 2 3 x))))
(define-test checking-sentinel
(let ((c (make-circle-with (list 1 2 3))))
(is (circle-sentinel-p c))
(is (not (circle-sentinel-p (circle-nth c 0))))
(is (not (circle-sentinel-p (circle-nth c 1))))
(is (not (circle-sentinel-p (circle-nth c 2))))
(is (circle-sentinel-p (circle-nth c 3))))
(is (circle-sentinel-p (make-empty-circle)))
(is (circle-sentinel-p (circle-nth (make-empty-circle) 0)))
(is (circle-sentinel-p (circle-nth (make-empty-circle) -1))))
(define-test removing
(let ((c (make-circle-with (list 1 2 3))))
(signals simple-error (circle-remove c))
(is-circle-contents c '(1 2 3))
(circle-remove (circle-nth c 0))
(is-circle-contents c '(2 3))
(circle-remove (circle-nth c 1))
(is-circle-contents c '(2))
(circle-remove (circle-nth c 0))
(is-circle-contents c '())))
(define-test removing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-remove (circle-nth c 1))
'(1 3 4 5 6))
(is (not (circle-backward-remove (circle-nth c 0))))
(is-circle-contents c '(3 4 5 6))
(is-circle-contents (circle-backward-remove (circle-nth c -1))
'(5 3 4))
(is-circle-contents c '(3 4 5))))
(define-test removing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-remove (circle-nth c 1))
'(3 4 5 6 1))
(is (not (circle-forward-remove (circle-nth c -1))))
(is-circle-contents c '(1 3 4 5))))
(define-test replacing
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(circle-replace (circle-nth c 0) 'foo)
(is-circle-contents c '(foo 2 3 4 5 6))
(circle-replace (circle-nth c 0) 'bar)
(is-circle-contents c '(bar 2 3 4 5 6))
(circle-replace (circle-nth c 1) 'a)
(is-circle-contents c '(bar a 3 4 5 6))
(circle-replace (circle-nth c 2) 'b)
(is-circle-contents c '(bar a b 4 5 6))
(circle-replace (circle-nth c -1) 'c)
(is-circle-contents c '(bar a b 4 5 c))))
(define-test replacing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 1) 'foo)
'(1 foo 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 1) 'bar)
'(1 bar 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 2) 'a)
'(bar a 4 5 6 1))
(is (not (circle-backward-replace (circle-nth c 0) 'dogs)))
(is-circle-contents c '(dogs bar a 4 5 6))))
(define-test replacing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-replace (circle-nth c 1) 'foo)
'(3 4 5 6 1 foo))
(is-circle-contents (circle-forward-replace (circle-nth c 1) 'bar)
'(3 4 5 6 1 bar))
(is (not (circle-forward-replace (circle-nth c -1) 'cats)))
(is-circle-contents c '(1 bar 3 4 5 cats))))
(define-test splicing
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(circle-splice (circle-nth c 0) (list 'a 'b))
(is-circle-contents c '(a b 2 3 4 5 6))
(circle-splice (circle-nth c 1) (list 'c))
(is-circle-contents c '(a c 2 3 4 5 6))
(circle-splice (circle-nth c -1) (list 'dogs 'cats))
(is-circle-contents c '(a c 2 3 4 5 dogs cats))
(circle-splice (circle-nth c 3) nil)
(is-circle-contents c '(a c 2 4 5 dogs cats))))
(define-test splicing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-splice (circle-nth c 2) '(a b))
'(2 a b 4 5 6 1))
(is-circle-contents (circle-backward-splice (circle-nth c -1) '())
'(5 1 2 a b 4))
(is (not (circle-backward-splice (circle-nth c 0) '(first second))))
(is-circle-contents c '(first second 2 a b 4 5))))
(define-test splicing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-splice (circle-nth c 0) '(a b))
'(2 3 4 5 6 a b))
(is-circle-contents (circle-forward-splice (circle-nth c 1) '())
'(2 3 4 5 6 a))
(is (not (circle-forward-splice (circle-nth c -1) '(last))))
(is-circle-contents c '(a 2 3 4 5 last))))
| null | https://raw.githubusercontent.com/sjl/temperance/f7e68f46b7afaeecf643c009eb2e130500556e31/test/circle.lisp | lisp | (in-package :temperance.test.circle)
(defmacro is-circle-contents (circle values)
`(is (equal ,values
(circle-to-list ,circle))))
(define-test empty-circles
(is (circle-empty-p (make-empty-circle)))
(is (circle-empty-p (make-circle-with nil)))
(is (not (circle-empty-p (make-circle-with (list 1))))))
(define-test making-circle-with
(is-circle-contents
(make-circle-with (list))
nil)
(is-circle-contents
(make-circle-with (list 1 2 3))
(list 1 2 3))
(is-circle-contents
(make-circle-with '(foo))
(list 'foo))
(is-circle-contents
(make-circle-with '((foo)))
(list (list 'foo))))
(define-test prepending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-prepend c (list 1))
(is-circle-contents c '(1))
(circle-prepend c (list 2 3))
(is-circle-contents c '(2 3 1))
(circle-prepend c nil)
(is-circle-contents c '(2 3 1))))
(define-test appending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-append c (list 1))
(is-circle-contents c '(1))
(circle-append c (list 2 3))
(is-circle-contents c '(1 2 3))
(circle-append c nil)
(is-circle-contents c '(1 2 3))))
(define-test appending-and-prepending
(let ((c (make-empty-circle)))
(is-circle-contents c nil)
(circle-append c (list 1))
(is-circle-contents c '(1))
(circle-prepend c (list 'a 'b))
(is-circle-contents c '(a b 1))
(circle-append c (list 'p 'q))
(is-circle-contents c '(a b 1 p q))))
(define-test moving-forward
(let ((c (make-circle-with (list 1 2 3 4))))
(is (equal
'(1 2 3 4)
(loop :for node = (circle-forward c) :then (circle-forward node)
:while node
:collect (circle-value node))))))
(define-test moving-backward
(let ((c (make-circle-with (list 1 2 3 4))))
(is (equal
'(4 3 2 1)
(loop :for node = (circle-backward c) :then (circle-backward node)
:while node
:collect (circle-value node))))))
(define-test rotating
(let ((c (make-circle-with (list 1 2 3 4))))
(is-circle-contents (circle-rotate c 0)
'(1 2 3 4))
(is-circle-contents (circle-rotate c 1)
'(1 2 3 4))
(is-circle-contents (circle-rotate c 2)
'(2 3 4 1))
(is-circle-contents (circle-rotate c 3)
'(3 4 1 2))
(is-circle-contents (circle-rotate c 4)
'(4 1 2 3))
(is-circle-contents (circle-rotate c 5)
'(1 2 3 4))
(is-circle-contents (circle-rotate c -1)
'(4 1 2 3))
(is-circle-contents (circle-rotate c -2)
'(3 4 1 2))
(is-circle-contents (circle-rotate c -3)
'(2 3 4 1))
(is-circle-contents (circle-rotate c -4)
'(1 2 3 4))
(is-circle-contents (circle-rotate (circle-rotate c 2) 0)
'(2 3 4 1))
(is-circle-contents (circle-rotate (circle-rotate c 2) 1)
'(3 4 1 2))
(is-circle-contents (circle-rotate (circle-rotate c 2) 2)
'(4 1 2 3))
(is-circle-contents (circle-rotate (circle-rotate c 2) -2)
'(1 2 3 4))
(is-circle-contents (circle-rotate (circle-rotate c 3) -1)
'(2 3 4 1))))
(define-test retrieving-nth
(let* ((data (list 'a 'b 'c 'd))
(c (make-circle-with data)))
(loop :for i :from 0 :below 4
:for v :in data
:do (is (eql v (circle-value (circle-nth c i)))))))
(define-test inserting-before
(let ((c (make-circle-with (list 1 2 3))))
(circle-insert-before c 'a)
(is-circle-contents c '(1 2 3 a))
(circle-insert-before (circle-nth c 0) 'b)
(is-circle-contents c '(b 1 2 3 a))
(circle-insert-before (circle-nth c 1) 'c)
(is-circle-contents c '(b c 1 2 3 a))
(circle-insert-before (circle-nth c 2) 'd)
(is-circle-contents c '(b c d 1 2 3 a))
(circle-insert-before (circle-nth c -1) 'e)
(is-circle-contents c '(b c d 1 2 3 e a))))
(define-test inserting-after
(let ((c (make-circle-with (list 1 2 3))))
(circle-insert-after c 'a)
(is-circle-contents c '(a 1 2 3))
(circle-insert-after (circle-nth c 0) 'b)
(is-circle-contents c '(a b 1 2 3))
(circle-insert-after (circle-nth c 1) 'c)
(is-circle-contents c '(a b c 1 2 3))
(circle-insert-after (circle-nth c 2) 'd)
(is-circle-contents c '(a b c d 1 2 3))
(circle-insert-after (circle-nth c -1) 'x)
(is-circle-contents c '(a b c d 1 2 3 x))))
(define-test checking-sentinel
(let ((c (make-circle-with (list 1 2 3))))
(is (circle-sentinel-p c))
(is (not (circle-sentinel-p (circle-nth c 0))))
(is (not (circle-sentinel-p (circle-nth c 1))))
(is (not (circle-sentinel-p (circle-nth c 2))))
(is (circle-sentinel-p (circle-nth c 3))))
(is (circle-sentinel-p (make-empty-circle)))
(is (circle-sentinel-p (circle-nth (make-empty-circle) 0)))
(is (circle-sentinel-p (circle-nth (make-empty-circle) -1))))
(define-test removing
(let ((c (make-circle-with (list 1 2 3))))
(signals simple-error (circle-remove c))
(is-circle-contents c '(1 2 3))
(circle-remove (circle-nth c 0))
(is-circle-contents c '(2 3))
(circle-remove (circle-nth c 1))
(is-circle-contents c '(2))
(circle-remove (circle-nth c 0))
(is-circle-contents c '())))
(define-test removing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-remove (circle-nth c 1))
'(1 3 4 5 6))
(is (not (circle-backward-remove (circle-nth c 0))))
(is-circle-contents c '(3 4 5 6))
(is-circle-contents (circle-backward-remove (circle-nth c -1))
'(5 3 4))
(is-circle-contents c '(3 4 5))))
(define-test removing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-remove (circle-nth c 1))
'(3 4 5 6 1))
(is (not (circle-forward-remove (circle-nth c -1))))
(is-circle-contents c '(1 3 4 5))))
(define-test replacing
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(circle-replace (circle-nth c 0) 'foo)
(is-circle-contents c '(foo 2 3 4 5 6))
(circle-replace (circle-nth c 0) 'bar)
(is-circle-contents c '(bar 2 3 4 5 6))
(circle-replace (circle-nth c 1) 'a)
(is-circle-contents c '(bar a 3 4 5 6))
(circle-replace (circle-nth c 2) 'b)
(is-circle-contents c '(bar a b 4 5 6))
(circle-replace (circle-nth c -1) 'c)
(is-circle-contents c '(bar a b 4 5 c))))
(define-test replacing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 1) 'foo)
'(1 foo 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 1) 'bar)
'(1 bar 3 4 5 6))
(is-circle-contents (circle-backward-replace (circle-nth c 2) 'a)
'(bar a 4 5 6 1))
(is (not (circle-backward-replace (circle-nth c 0) 'dogs)))
(is-circle-contents c '(dogs bar a 4 5 6))))
(define-test replacing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-replace (circle-nth c 1) 'foo)
'(3 4 5 6 1 foo))
(is-circle-contents (circle-forward-replace (circle-nth c 1) 'bar)
'(3 4 5 6 1 bar))
(is (not (circle-forward-replace (circle-nth c -1) 'cats)))
(is-circle-contents c '(1 bar 3 4 5 cats))))
(define-test splicing
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(circle-splice (circle-nth c 0) (list 'a 'b))
(is-circle-contents c '(a b 2 3 4 5 6))
(circle-splice (circle-nth c 1) (list 'c))
(is-circle-contents c '(a c 2 3 4 5 6))
(circle-splice (circle-nth c -1) (list 'dogs 'cats))
(is-circle-contents c '(a c 2 3 4 5 dogs cats))
(circle-splice (circle-nth c 3) nil)
(is-circle-contents c '(a c 2 4 5 dogs cats))))
(define-test splicing-backward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-backward-splice (circle-nth c 2) '(a b))
'(2 a b 4 5 6 1))
(is-circle-contents (circle-backward-splice (circle-nth c -1) '())
'(5 1 2 a b 4))
(is (not (circle-backward-splice (circle-nth c 0) '(first second))))
(is-circle-contents c '(first second 2 a b 4 5))))
(define-test splicing-forward
(let ((c (make-circle-with (list 1 2 3 4 5 6))))
(is-circle-contents c '(1 2 3 4 5 6))
(is-circle-contents (circle-forward-splice (circle-nth c 0) '(a b))
'(2 3 4 5 6 a b))
(is-circle-contents (circle-forward-splice (circle-nth c 1) '())
'(2 3 4 5 6 a))
(is (not (circle-forward-splice (circle-nth c -1) '(last))))
(is-circle-contents c '(a 2 3 4 5 last))))
|
|
3cad2623c10c1b820a46d2b18b60a9c5b3536aea35cfae2c234c479cd425eb9d | HealthSamurai/stresty | core.cljc | (ns app.users.core
(:require
[zframes.re-frame :as zrf]
[anti.button]
[app.routes :refer [href]]
[stylo.core :refer [c]]
[app.pages :as pages]
[app.users.form]))
(zrf/reg-sub
db
(fn [db _] (get db ::db)))
(zrf/reg-event-fx
load-users
[(zrf/path ::db)]
(fn [_ _]
{:http/fetch [{:uri "/User"
:unbundle true
:params {:_count 1000}
:path [::db :users]}]}))
(zrf/reg-sub
users
:<- [db]
(fn [db _]
(get-in db [:users :data])))
(zrf/reg-event-fx
index
[(zrf/path ::db)]
(fn [_ [_ phase _]]
(cond
(= :init phase)
{:dispatch-n [[load-users]]})))
(zrf/defview grid
[users]
[:div {:class (c :divide-y)}
(for [u users]
[:div {:key (:id u)
:class (c :flex :flex-col [:py 1])}
[:a {:class (c :font-bold)
:href (href "users" (:id u))} (:id u)]
[:div {:class (c [:space-x 2])}
[:span {:class (c [:text :gray-600] :font-thin)} "email:"]
(if (:email u) [:span {} (:email u)] [:span {:class (c :italic)} "not defined"])
[:span {:class (c [:text :gray-600] :font-thin)} "role:"]
(if (:roleName u) [:span {} (:roleName u)] [:span {:class (c :italic)} "not defined"])]])])
(zrf/defview page
[]
[:div
[:div {:class (c [:py 8] :w-max-full [:w 200] :mx-auto [:space-y 2])}
[:div {:class (c :flex)}
[anti.button/zf-button {:class (c :ml-auto)
:type "primary"
:on-click [:zframes.routing/redirect {:uri (href "users/new")}]}
"New user"]]
[grid]]])
(pages/reg-page index page)
| null | https://raw.githubusercontent.com/HealthSamurai/stresty/130cedde6bf53e07fe25a6b0b13b8bf70846f15a/src-ui/app/users/core.cljc | clojure | (ns app.users.core
(:require
[zframes.re-frame :as zrf]
[anti.button]
[app.routes :refer [href]]
[stylo.core :refer [c]]
[app.pages :as pages]
[app.users.form]))
(zrf/reg-sub
db
(fn [db _] (get db ::db)))
(zrf/reg-event-fx
load-users
[(zrf/path ::db)]
(fn [_ _]
{:http/fetch [{:uri "/User"
:unbundle true
:params {:_count 1000}
:path [::db :users]}]}))
(zrf/reg-sub
users
:<- [db]
(fn [db _]
(get-in db [:users :data])))
(zrf/reg-event-fx
index
[(zrf/path ::db)]
(fn [_ [_ phase _]]
(cond
(= :init phase)
{:dispatch-n [[load-users]]})))
(zrf/defview grid
[users]
[:div {:class (c :divide-y)}
(for [u users]
[:div {:key (:id u)
:class (c :flex :flex-col [:py 1])}
[:a {:class (c :font-bold)
:href (href "users" (:id u))} (:id u)]
[:div {:class (c [:space-x 2])}
[:span {:class (c [:text :gray-600] :font-thin)} "email:"]
(if (:email u) [:span {} (:email u)] [:span {:class (c :italic)} "not defined"])
[:span {:class (c [:text :gray-600] :font-thin)} "role:"]
(if (:roleName u) [:span {} (:roleName u)] [:span {:class (c :italic)} "not defined"])]])])
(zrf/defview page
[]
[:div
[:div {:class (c [:py 8] :w-max-full [:w 200] :mx-auto [:space-y 2])}
[:div {:class (c :flex)}
[anti.button/zf-button {:class (c :ml-auto)
:type "primary"
:on-click [:zframes.routing/redirect {:uri (href "users/new")}]}
"New user"]]
[grid]]])
(pages/reg-page index page)
|
|
170c7ca25c4f011e063c4975d42b8ae637d9d824eba5c709564be8ee547abfad | ruhler/smten | Functor.hs |
# LANGUAGE NoImplicitPrelude #
module Smten.Base.Data.Functor (
Functor(fmap), (<$), (<$>),
) where
import GHC.Base(Functor(..))
infixl 4 <$>
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap
| null | https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-base/Smten/Base/Data/Functor.hs | haskell |
# LANGUAGE NoImplicitPrelude #
module Smten.Base.Data.Functor (
Functor(fmap), (<$), (<$>),
) where
import GHC.Base(Functor(..))
infixl 4 <$>
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap
|
|
2d2b56595dbb80598482c16855399ebf63b176951001a5bed425a7cee01c5b40 | ocaml-sf/learn-ocaml-corpus | prelude.ml | type var = int
type formula =
| FConst of bool
| FConn of bool * formula * formula
| FNeg of formula
| FVar of var
type env = var -> bool
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/sat/prelude.ml | ocaml | type var = int
type formula =
| FConst of bool
| FConn of bool * formula * formula
| FNeg of formula
| FVar of var
type env = var -> bool
|
|
a4f15964b78f1a85ba3a3b182726a7b4a9c5238a4e4d14b608e1239bed878e94 | janestreet/learn-ocaml-workshop | bot.ml | open! Core
open! Async
* This is a simple client which takes a variety of command - line parameters for
the purpose of connecting to a single channel on an IRC server , sending one
message , and then disconnecting . No validation is done of the parameters .
There are various TODO items below that are probably worth pursuing if you
are going to reuse any of this code in your bot .
the purpose of connecting to a single channel on an IRC server, sending one
message, and then disconnecting. No validation is done of the parameters.
There are various TODO items below that are probably worth pursuing if you
are going to reuse any of this code in your bot. *)
let command () =
let open Command.Let_syntax in
Command.async
~summary:"Simple IRC bot which just sends a single message and disconnects"
[%map_open
let where_to_connect =
let%map host_and_port =
flag "server" (required host_and_port)
~doc:"HOST:PORT of IRC server"
in
Tcp.Where_to_connect.of_host_and_port host_and_port
and nick =
TODO : Check the RFC for valid characters and exit with an error if
the NICK contains any of them .
the NICK contains any of them. *)
flag "nick" (required string)
~doc:"NICK nickname to use on the IRC server"
and full_name =
flag "full-name" (required string)
~doc:"NAME full name to register with the server"
and channel =
flag "channel" (required string)
~doc:"CHAN channel to send the message to, including the '#' if \
relevant"
and message =
anon ("MESSAGE" %: string)
in
fun () ->
Tcp.with_connection where_to_connect
(fun _socket reader writer ->
TODO : Check that the total length of the message(s ) being sent
to the server never exceed the 512 character limit .
to the server never exceed the 512 character limit. *)
let write_line line =
(* Convenience wrapper to ensure we don't forget to end lines
in \r\n. *)
printf ">>> %s\n" line;
Writer.write_line writer line ~line_ending:Writer.Line_ending.Dos
in
write_line (sprintf "NICK %s" nick);
write_line (sprintf "USER %s * * :%s" nick full_name);
write_line (sprintf "JOIN :%s" channel);
write_line (sprintf "PRIVMSG %s :%s" channel message);
write_line (sprintf "QUIT");
Writer.flushed writer
>>= fun () ->
(* TODO: In practice, you'll want to check that the replies you
receive in response to sending each of the messages below
indicate success before continuing on to additional
commands.*)
Pipe.iter
(Reader.lines reader)
~f:(fun reply ->
printf "<<< %s\n" reply;
Deferred.unit);
)
]
;;
let () = Command.run (command ())
| null | https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/04-bigger-projects/irc-bot/bin/bot.ml | ocaml | Convenience wrapper to ensure we don't forget to end lines
in \r\n.
TODO: In practice, you'll want to check that the replies you
receive in response to sending each of the messages below
indicate success before continuing on to additional
commands. | open! Core
open! Async
* This is a simple client which takes a variety of command - line parameters for
the purpose of connecting to a single channel on an IRC server , sending one
message , and then disconnecting . No validation is done of the parameters .
There are various TODO items below that are probably worth pursuing if you
are going to reuse any of this code in your bot .
the purpose of connecting to a single channel on an IRC server, sending one
message, and then disconnecting. No validation is done of the parameters.
There are various TODO items below that are probably worth pursuing if you
are going to reuse any of this code in your bot. *)
let command () =
let open Command.Let_syntax in
Command.async
~summary:"Simple IRC bot which just sends a single message and disconnects"
[%map_open
let where_to_connect =
let%map host_and_port =
flag "server" (required host_and_port)
~doc:"HOST:PORT of IRC server"
in
Tcp.Where_to_connect.of_host_and_port host_and_port
and nick =
TODO : Check the RFC for valid characters and exit with an error if
the NICK contains any of them .
the NICK contains any of them. *)
flag "nick" (required string)
~doc:"NICK nickname to use on the IRC server"
and full_name =
flag "full-name" (required string)
~doc:"NAME full name to register with the server"
and channel =
flag "channel" (required string)
~doc:"CHAN channel to send the message to, including the '#' if \
relevant"
and message =
anon ("MESSAGE" %: string)
in
fun () ->
Tcp.with_connection where_to_connect
(fun _socket reader writer ->
TODO : Check that the total length of the message(s ) being sent
to the server never exceed the 512 character limit .
to the server never exceed the 512 character limit. *)
let write_line line =
printf ">>> %s\n" line;
Writer.write_line writer line ~line_ending:Writer.Line_ending.Dos
in
write_line (sprintf "NICK %s" nick);
write_line (sprintf "USER %s * * :%s" nick full_name);
write_line (sprintf "JOIN :%s" channel);
write_line (sprintf "PRIVMSG %s :%s" channel message);
write_line (sprintf "QUIT");
Writer.flushed writer
>>= fun () ->
Pipe.iter
(Reader.lines reader)
~f:(fun reply ->
printf "<<< %s\n" reply;
Deferred.unit);
)
]
;;
let () = Command.run (command ())
|
3a6a4c1a555aaa6aa4959230841f766ad227aa875f68433b5a204bb18594fac5 | GillianPlatform/Gillian | MonadicSVal.ml | include SVal
open Gil_syntax
open Monadic
open Delayed.Syntax
module DO = Delayed_option
module DR = Delayed_result
exception NotACompCertValue of Expr.t
module Patterns = struct
open Formula.Infix
let number e =
let open Expr in
(typeof e) #== (type_ NumberType)
let integer e =
let open Expr in
(typeof e) #== (type_ IntType)
let int_typ, float_typ, single_typ, long_typ =
let open Expr in
let open CConstants.VTypes in
let num_typ int_t typ_str x =
(typeof x) #== (type_ ListType)
#&& ((list_length x) #== (int 2))
#&& ((list_nth x 0) #== (string typ_str))
#&& ((typeof (list_nth x 1)) #== (type_ int_t))
in
( num_typ IntType int_type,
num_typ NumberType float_type,
num_typ NumberType single_type,
num_typ IntType long_type )
let undefined x = x #== (Expr.Lit Undefined)
let obj x =
let open Expr in
(typeof x) #== (type_ ListType)
#&& ((list_length x) #== (int 2))
#&& ((typeof (list_nth x 0)) #== (type_ ObjectType))
#&& ((typeof (list_nth x 1)) #== (type_ IntType))
end
let of_chunk_and_expr chunk e =
let return = Delayed.return in
let open Patterns in
let* e = Delayed.reduce e in
match e with
| Expr.Lit Undefined -> return SUndefined
| _ -> (
match Chunk.type_of chunk with
| Tlong when Compcert.Archi.ptr64 -> (
match%ent e with
| integer -> return (SVlong e)
| obj -> (
match e with
| EList [ ALoc l; o ] -> return (Sptr (l, o))
| _ ->
Fmt.failwith
"of_chunk_and_expr: Not a location, but should be: %a"
Expr.pp e))
| Tint when not Compcert.Archi.ptr64 -> (
match%ent e with
| integer -> return (SVint e)
| obj -> (
match e with
| EList [ ALoc l; o ] -> return (Sptr (l, o))
| _ ->
Fmt.failwith
"of_chunk_and_expr: Not a location, but should be: %a"
Expr.pp e))
| Tlong -> return (SVlong e)
| Tint ->
let open Formula.Infix in
let i k = Expr.int k in
let learned =
match chunk with
| Mint8unsigned -> [ (i 0) #<= e; e #<= (i 255) ]
| _ -> []
in
return ~learned (SVint e)
| Tfloat -> return (SVfloat e)
| Tsingle -> return (SVsingle e)
| Tany32 | Tany64 -> Fmt.failwith "Unhandled chunk: %a" Chunk.pp chunk)
let of_gil_expr sval_e =
let open Formula.Infix in
let open Patterns in
Logging.verbose (fun fmt -> fmt "OF_GIL_EXPR : %a" Expr.pp sval_e);
let* sval_e = Delayed.reduce sval_e in
match%ent sval_e with
| undefined -> DO.some SUndefined
| obj ->
let loc_expr = Expr.list_nth sval_e 0 in
let ofs = Expr.list_nth sval_e 1 in
let* ofs = Delayed.reduce ofs in
let* loc_opt = Delayed.resolve_loc loc_expr in
let loc, learned =
match loc_opt with
| Some l -> (l, [])
| None ->
let aloc = ALoc.alloc () in
let learned = [ loc_expr #== (ALoc aloc) ] in
(aloc, learned)
in
DO.some ~learned (Sptr (loc, ofs))
| int_typ -> DO.some (SVint (Expr.list_nth sval_e 1))
| float_typ -> DO.some (SVfloat (Expr.list_nth sval_e 1))
| long_typ -> DO.some (SVlong (Expr.list_nth sval_e 1))
| single_typ -> DO.some (SVsingle (Expr.list_nth sval_e 1))
| _ -> DO.none ()
let of_gil_expr_exn sval_e =
let* value_opt = of_gil_expr sval_e in
match value_opt with
| None -> raise (NotACompCertValue sval_e)
| Some value -> Delayed.return value
let to_gil_expr_undelayed = to_gil_expr
let to_gil_expr sval =
let exp, typings = to_gil_expr_undelayed sval in
let typing_pfs =
List.map
(fun (e, t) ->
let open Expr in
let open Formula.Infix in
(typeof e) #== (type_ t))
typings
in
Delayed.return ~learned:typing_pfs exp
let sure_is_zero = function
| SVint (Lit (Int z)) when Z.equal z Z.zero -> true
| SVlong (Lit (Int z)) when Z.equal z Z.zero -> true
| SVfloat (Lit (Num 0.)) | SVsingle (Lit (Num 0.)) -> true
| _ -> false
module SVArray = struct
type t =
| Arr of Expr.t
(** the parameter should be a list representing a *NON-EMPTY* list *)
| AllUndef
| AllZeros
[@@deriving yojson]
let reduce t =
let open Delayed.Syntax in
match t with
| Arr e ->
let+ reduced = Delayed.reduce e in
Arr reduced
| _ -> Delayed.return t
let pp fmt = function
| Arr e -> Expr.pp fmt e
| AllUndef -> Fmt.string fmt "AllUndef"
| AllZeros -> Fmt.string fmt "AllZeros"
let empty = Arr (EList [])
let is_empty =
let open Formula.Infix in
function
| Arr e -> (Expr.list_length e) #== (Expr.int 0)
| _ -> False
let sure_is_all_zeros = function
| Arr (EList l) ->
List.for_all
(function
| Expr.Lit (Int z) when Z.equal z Z.zero -> true
| _ -> false)
l
| AllZeros -> true
| _ -> false
let equal arr_a arr_b =
match (arr_a, arr_b) with
| Arr a, Arr b -> Expr.equal a b
| AllUndef, AllUndef | AllZeros, AllZeros -> true
| _ -> false
let conc_to_abst_undelayed conc =
let rev_l, gamma =
List.fold_left
(fun (acc, gamma) sval ->
let new_el, new_gamma = SVal.to_gil_expr sval in
(new_el :: acc, new_gamma @ gamma))
([], []) conc
in
let learned =
List.map
(let open Formula.Infix in
fun (e, t) -> (Expr.typeof e) #== (Expr.type_ t))
gamma
in
(Expr.EList (List.rev rev_l), learned)
let conc_to_abst conc =
let e, learned = conc_to_abst_undelayed conc in
Delayed.return ~learned e
let undefined_pf ?size arr_exp =
let size =
match size with
| None -> Expr.list_length arr_exp
| Some size -> size
in
let open Formula.Infix in
let zero = Expr.int 0 in
let size = Engine.Reduction.reduce_lexpr size in
match size with
| Lit (Int x) ->
Logging.verbose (fun fmt ->
fmt "Undefined pf: Concrete: %a" Expr.pp size);
let undefs =
Expr.Lit (LList (List.init (Z.to_int x) (fun _ -> Literal.Undefined)))
in
arr_exp #== undefs
| _ ->
Logging.verbose (fun fmt ->
fmt "Undefined pf: not as concrete: %a" Expr.pp size);
let i = LVar.alloc () in
let i_e = Expr.LVar i in
forall
[ (i, Some IntType) ]
zero #<= i_e #&& (i_e #< size)
#=> ((Expr.list_nth_e arr_exp i_e) #== (Lit Undefined))
let zeros_pf ?size arr_exp =
let size =
match size with
| None -> Expr.list_length arr_exp
| Some size -> size
in
let open Formula.Infix in
let size = Engine.Reduction.reduce_lexpr size in
match size with
| Lit (Int x) ->
Logging.verbose (fun fmt -> fmt "Zeros pf: Concrete: %a" Expr.pp size);
let zeros =
Expr.Lit
(LList (List.init (Z.to_int x) (fun _ -> Literal.Int Z.zero)))
in
arr_exp #== zeros
| _ ->
Logging.verbose (fun fmt ->
fmt "Zeros pf: not as concrete: %a" Expr.pp size);
let is_zero e = e #== (Expr.int 0) in
let i = LVar.alloc () in
let i_e = Expr.LVar i in
let zero = Expr.int 0 in
forall
[ (i, Some IntType) ]
zero #<= i_e #&& (i_e #< size)
#=> (is_zero (Expr.list_nth_e arr_exp i_e))
let to_arr_with_size arr s =
let open Formula.Infix in
let allocate_array_lvar (descr : ?size:Expr.t -> Expr.t -> Formula.t) =
let x = LVar.alloc () in
let learned_types = [ (x, Gil_syntax.Type.ListType) ] in
let x = Expr.LVar x in
let learned = [ (Expr.list_length x) #== s; descr ~size:s x ] in
Delayed.return ~learned ~learned_types x
in
match arr with
| Arr e -> Delayed.return e
| AllUndef -> allocate_array_lvar undefined_pf
| AllZeros -> allocate_array_lvar zeros_pf
let concat_knowing_size (left, left_size) (right, right_size) =
let open Delayed in
let open Delayed.Syntax in
match (left, right) with
| Arr a, Arr b -> return (Arr (Expr.list_cat a b))
| AllUndef, AllUndef -> return AllUndef
| AllZeros, AllZeros -> return AllZeros
| left, right ->
let* left = to_arr_with_size left left_size in
let+ right = to_arr_with_size right right_size in
Arr (Expr.list_cat left right)
let concat left right =
match (left, right) with
| Arr a, Arr b -> Some (Arr (Expr.list_cat a b))
| AllUndef, AllUndef -> Some AllUndef
| AllZeros, AllZeros -> Some AllZeros
| _ -> None
(** This already assumes the value is a number and not a pointer *)
let to_single_value ~chunk = function
| Arr (EList [ a ]) ->
let+ v = of_chunk_and_expr chunk a in
Some v
| AllZeros -> DO.some (zero_of_chunk chunk)
| AllUndef -> DO.some SUndefined
| _ -> DO.none ()
let singleton = function
(* Assuming that the chunk is correct already *)
| SVfloat e | SVint e | SVlong e | SVsingle e -> Arr (Expr.EList [ e ])
| Sptr _ as ptr ->
let e_ptr, _ = to_gil_expr_undelayed ptr in
Arr (Expr.EList [ e_ptr ])
| SUndefined -> AllUndef
let array_sub arr o len : t =
match arr with
| AllZeros -> AllZeros
| AllUndef -> AllUndef
| Arr e -> Arr (Expr.list_sub ~lst:e ~start:o ~size:len)
(** This assumes chunks are properly respected outside of the call of this function *)
let array_cons (el : SVal.t) arr = concat (singleton el) arr
let array_append arr el = concat arr (singleton el)
let to_gil_expr_undelayed ~chunk ~range svarr =
let chunk_size = Chunk.size_expr chunk in
let size =
let open Expr.Infix in
let low, high = range in
(high - low) / chunk_size
in
let f_of_all_same ~describing_pf ~concrete_single =
match size with
| Lit (Int n) ->
(Expr.EList (Utils.List_utils.make (Z.to_int n) concrete_single), [])
| _ ->
let open Formula.Infix in
let arr = LVar.alloc () in
let arr_e = Expr.LVar arr in
let learned =
let open Expr in
[
(typeof arr_e) #== (type_ ListType);
(list_length arr_e) #== size;
describing_pf arr_e;
]
in
(arr_e, learned)
in
match svarr with
| Arr e ->
let open Formula.Infix in
let learned =
[
(Expr.typeof e) #== (Expr.type_ ListType);
(Expr.list_length e) #== size;
]
in
(e, learned)
| AllZeros ->
f_of_all_same ~concrete_single:Expr.zero_i ~describing_pf:zeros_pf
| AllUndef ->
f_of_all_same ~concrete_single:(Expr.Lit Undefined)
~describing_pf:undefined_pf
let to_gil_expr ~chunk ~range (svarr : t) : Expr.t Delayed.t =
let e, learned = to_gil_expr_undelayed ~chunk ~range svarr in
Delayed.return ~learned e
let of_gil_expr_exn expr = Arr expr
* Only call on Mint8Unsigned arrays
let learn_chunk ~chunk ~size arr =
let bounds =
match chunk with
| Chunk.Mint8unsigned -> Some (0, 255)
| _ -> None
(* Should be completed later *)
in
let* size = Delayed.reduce size in
match bounds with
| None -> Delayed.return ()
| Some (low, high) -> (
match arr with
| Arr (EList e) ->
let i k = Expr.int k in
let learned =
List.concat_map
(function
| Expr.Lit Undefined -> []
| x ->
let open Formula.Infix in
[ (i low) #<= x; x #<= (i high) ])
e
in
Delayed.return ~learned ()
| Arr e -> (
match size with
| Expr.Lit (Int n) ->
let i k = Expr.int k in
let learned =
List.concat
(List.init (Z.to_int n) (fun k ->
let x = Expr.list_nth e k in
let open Formula.Infix in
[ (i low) #<= x; x #<= (i high) ]))
in
Delayed.return ~learned ()
| _ -> Delayed.return ())
| _ -> Delayed.return ())
(* type nonrec t = Conc of t list | Abst of Expr.t | AllUndef | AllZeros *)
let subst ~le_subst t =
match t with
| Arr e ->
let s = le_subst e in
if s == e then t else Arr s
| AllUndef -> AllUndef
| AllZeros -> AllZeros
end
module Infix = struct
let ( @: ) = SVArray.concat
let ( ^: ) = SVArray.array_cons
let ( ^:? ) a b = Option.bind b (fun b -> a ^: b)
end
| null | https://raw.githubusercontent.com/GillianPlatform/Gillian/42d0e2aae9fa6b0992a5bc300525cc8d360c3c96/Gillian-C/lib/MonadicSVal.ml | ocaml | * the parameter should be a list representing a *NON-EMPTY* list
* This already assumes the value is a number and not a pointer
Assuming that the chunk is correct already
* This assumes chunks are properly respected outside of the call of this function
Should be completed later
type nonrec t = Conc of t list | Abst of Expr.t | AllUndef | AllZeros | include SVal
open Gil_syntax
open Monadic
open Delayed.Syntax
module DO = Delayed_option
module DR = Delayed_result
exception NotACompCertValue of Expr.t
module Patterns = struct
open Formula.Infix
let number e =
let open Expr in
(typeof e) #== (type_ NumberType)
let integer e =
let open Expr in
(typeof e) #== (type_ IntType)
let int_typ, float_typ, single_typ, long_typ =
let open Expr in
let open CConstants.VTypes in
let num_typ int_t typ_str x =
(typeof x) #== (type_ ListType)
#&& ((list_length x) #== (int 2))
#&& ((list_nth x 0) #== (string typ_str))
#&& ((typeof (list_nth x 1)) #== (type_ int_t))
in
( num_typ IntType int_type,
num_typ NumberType float_type,
num_typ NumberType single_type,
num_typ IntType long_type )
let undefined x = x #== (Expr.Lit Undefined)
let obj x =
let open Expr in
(typeof x) #== (type_ ListType)
#&& ((list_length x) #== (int 2))
#&& ((typeof (list_nth x 0)) #== (type_ ObjectType))
#&& ((typeof (list_nth x 1)) #== (type_ IntType))
end
let of_chunk_and_expr chunk e =
let return = Delayed.return in
let open Patterns in
let* e = Delayed.reduce e in
match e with
| Expr.Lit Undefined -> return SUndefined
| _ -> (
match Chunk.type_of chunk with
| Tlong when Compcert.Archi.ptr64 -> (
match%ent e with
| integer -> return (SVlong e)
| obj -> (
match e with
| EList [ ALoc l; o ] -> return (Sptr (l, o))
| _ ->
Fmt.failwith
"of_chunk_and_expr: Not a location, but should be: %a"
Expr.pp e))
| Tint when not Compcert.Archi.ptr64 -> (
match%ent e with
| integer -> return (SVint e)
| obj -> (
match e with
| EList [ ALoc l; o ] -> return (Sptr (l, o))
| _ ->
Fmt.failwith
"of_chunk_and_expr: Not a location, but should be: %a"
Expr.pp e))
| Tlong -> return (SVlong e)
| Tint ->
let open Formula.Infix in
let i k = Expr.int k in
let learned =
match chunk with
| Mint8unsigned -> [ (i 0) #<= e; e #<= (i 255) ]
| _ -> []
in
return ~learned (SVint e)
| Tfloat -> return (SVfloat e)
| Tsingle -> return (SVsingle e)
| Tany32 | Tany64 -> Fmt.failwith "Unhandled chunk: %a" Chunk.pp chunk)
let of_gil_expr sval_e =
let open Formula.Infix in
let open Patterns in
Logging.verbose (fun fmt -> fmt "OF_GIL_EXPR : %a" Expr.pp sval_e);
let* sval_e = Delayed.reduce sval_e in
match%ent sval_e with
| undefined -> DO.some SUndefined
| obj ->
let loc_expr = Expr.list_nth sval_e 0 in
let ofs = Expr.list_nth sval_e 1 in
let* ofs = Delayed.reduce ofs in
let* loc_opt = Delayed.resolve_loc loc_expr in
let loc, learned =
match loc_opt with
| Some l -> (l, [])
| None ->
let aloc = ALoc.alloc () in
let learned = [ loc_expr #== (ALoc aloc) ] in
(aloc, learned)
in
DO.some ~learned (Sptr (loc, ofs))
| int_typ -> DO.some (SVint (Expr.list_nth sval_e 1))
| float_typ -> DO.some (SVfloat (Expr.list_nth sval_e 1))
| long_typ -> DO.some (SVlong (Expr.list_nth sval_e 1))
| single_typ -> DO.some (SVsingle (Expr.list_nth sval_e 1))
| _ -> DO.none ()
let of_gil_expr_exn sval_e =
let* value_opt = of_gil_expr sval_e in
match value_opt with
| None -> raise (NotACompCertValue sval_e)
| Some value -> Delayed.return value
let to_gil_expr_undelayed = to_gil_expr
let to_gil_expr sval =
let exp, typings = to_gil_expr_undelayed sval in
let typing_pfs =
List.map
(fun (e, t) ->
let open Expr in
let open Formula.Infix in
(typeof e) #== (type_ t))
typings
in
Delayed.return ~learned:typing_pfs exp
let sure_is_zero = function
| SVint (Lit (Int z)) when Z.equal z Z.zero -> true
| SVlong (Lit (Int z)) when Z.equal z Z.zero -> true
| SVfloat (Lit (Num 0.)) | SVsingle (Lit (Num 0.)) -> true
| _ -> false
module SVArray = struct
type t =
| Arr of Expr.t
| AllUndef
| AllZeros
[@@deriving yojson]
let reduce t =
let open Delayed.Syntax in
match t with
| Arr e ->
let+ reduced = Delayed.reduce e in
Arr reduced
| _ -> Delayed.return t
let pp fmt = function
| Arr e -> Expr.pp fmt e
| AllUndef -> Fmt.string fmt "AllUndef"
| AllZeros -> Fmt.string fmt "AllZeros"
let empty = Arr (EList [])
let is_empty =
let open Formula.Infix in
function
| Arr e -> (Expr.list_length e) #== (Expr.int 0)
| _ -> False
let sure_is_all_zeros = function
| Arr (EList l) ->
List.for_all
(function
| Expr.Lit (Int z) when Z.equal z Z.zero -> true
| _ -> false)
l
| AllZeros -> true
| _ -> false
let equal arr_a arr_b =
match (arr_a, arr_b) with
| Arr a, Arr b -> Expr.equal a b
| AllUndef, AllUndef | AllZeros, AllZeros -> true
| _ -> false
let conc_to_abst_undelayed conc =
let rev_l, gamma =
List.fold_left
(fun (acc, gamma) sval ->
let new_el, new_gamma = SVal.to_gil_expr sval in
(new_el :: acc, new_gamma @ gamma))
([], []) conc
in
let learned =
List.map
(let open Formula.Infix in
fun (e, t) -> (Expr.typeof e) #== (Expr.type_ t))
gamma
in
(Expr.EList (List.rev rev_l), learned)
let conc_to_abst conc =
let e, learned = conc_to_abst_undelayed conc in
Delayed.return ~learned e
let undefined_pf ?size arr_exp =
let size =
match size with
| None -> Expr.list_length arr_exp
| Some size -> size
in
let open Formula.Infix in
let zero = Expr.int 0 in
let size = Engine.Reduction.reduce_lexpr size in
match size with
| Lit (Int x) ->
Logging.verbose (fun fmt ->
fmt "Undefined pf: Concrete: %a" Expr.pp size);
let undefs =
Expr.Lit (LList (List.init (Z.to_int x) (fun _ -> Literal.Undefined)))
in
arr_exp #== undefs
| _ ->
Logging.verbose (fun fmt ->
fmt "Undefined pf: not as concrete: %a" Expr.pp size);
let i = LVar.alloc () in
let i_e = Expr.LVar i in
forall
[ (i, Some IntType) ]
zero #<= i_e #&& (i_e #< size)
#=> ((Expr.list_nth_e arr_exp i_e) #== (Lit Undefined))
let zeros_pf ?size arr_exp =
let size =
match size with
| None -> Expr.list_length arr_exp
| Some size -> size
in
let open Formula.Infix in
let size = Engine.Reduction.reduce_lexpr size in
match size with
| Lit (Int x) ->
Logging.verbose (fun fmt -> fmt "Zeros pf: Concrete: %a" Expr.pp size);
let zeros =
Expr.Lit
(LList (List.init (Z.to_int x) (fun _ -> Literal.Int Z.zero)))
in
arr_exp #== zeros
| _ ->
Logging.verbose (fun fmt ->
fmt "Zeros pf: not as concrete: %a" Expr.pp size);
let is_zero e = e #== (Expr.int 0) in
let i = LVar.alloc () in
let i_e = Expr.LVar i in
let zero = Expr.int 0 in
forall
[ (i, Some IntType) ]
zero #<= i_e #&& (i_e #< size)
#=> (is_zero (Expr.list_nth_e arr_exp i_e))
let to_arr_with_size arr s =
let open Formula.Infix in
let allocate_array_lvar (descr : ?size:Expr.t -> Expr.t -> Formula.t) =
let x = LVar.alloc () in
let learned_types = [ (x, Gil_syntax.Type.ListType) ] in
let x = Expr.LVar x in
let learned = [ (Expr.list_length x) #== s; descr ~size:s x ] in
Delayed.return ~learned ~learned_types x
in
match arr with
| Arr e -> Delayed.return e
| AllUndef -> allocate_array_lvar undefined_pf
| AllZeros -> allocate_array_lvar zeros_pf
let concat_knowing_size (left, left_size) (right, right_size) =
let open Delayed in
let open Delayed.Syntax in
match (left, right) with
| Arr a, Arr b -> return (Arr (Expr.list_cat a b))
| AllUndef, AllUndef -> return AllUndef
| AllZeros, AllZeros -> return AllZeros
| left, right ->
let* left = to_arr_with_size left left_size in
let+ right = to_arr_with_size right right_size in
Arr (Expr.list_cat left right)
let concat left right =
match (left, right) with
| Arr a, Arr b -> Some (Arr (Expr.list_cat a b))
| AllUndef, AllUndef -> Some AllUndef
| AllZeros, AllZeros -> Some AllZeros
| _ -> None
let to_single_value ~chunk = function
| Arr (EList [ a ]) ->
let+ v = of_chunk_and_expr chunk a in
Some v
| AllZeros -> DO.some (zero_of_chunk chunk)
| AllUndef -> DO.some SUndefined
| _ -> DO.none ()
let singleton = function
| SVfloat e | SVint e | SVlong e | SVsingle e -> Arr (Expr.EList [ e ])
| Sptr _ as ptr ->
let e_ptr, _ = to_gil_expr_undelayed ptr in
Arr (Expr.EList [ e_ptr ])
| SUndefined -> AllUndef
let array_sub arr o len : t =
match arr with
| AllZeros -> AllZeros
| AllUndef -> AllUndef
| Arr e -> Arr (Expr.list_sub ~lst:e ~start:o ~size:len)
let array_cons (el : SVal.t) arr = concat (singleton el) arr
let array_append arr el = concat arr (singleton el)
let to_gil_expr_undelayed ~chunk ~range svarr =
let chunk_size = Chunk.size_expr chunk in
let size =
let open Expr.Infix in
let low, high = range in
(high - low) / chunk_size
in
let f_of_all_same ~describing_pf ~concrete_single =
match size with
| Lit (Int n) ->
(Expr.EList (Utils.List_utils.make (Z.to_int n) concrete_single), [])
| _ ->
let open Formula.Infix in
let arr = LVar.alloc () in
let arr_e = Expr.LVar arr in
let learned =
let open Expr in
[
(typeof arr_e) #== (type_ ListType);
(list_length arr_e) #== size;
describing_pf arr_e;
]
in
(arr_e, learned)
in
match svarr with
| Arr e ->
let open Formula.Infix in
let learned =
[
(Expr.typeof e) #== (Expr.type_ ListType);
(Expr.list_length e) #== size;
]
in
(e, learned)
| AllZeros ->
f_of_all_same ~concrete_single:Expr.zero_i ~describing_pf:zeros_pf
| AllUndef ->
f_of_all_same ~concrete_single:(Expr.Lit Undefined)
~describing_pf:undefined_pf
let to_gil_expr ~chunk ~range (svarr : t) : Expr.t Delayed.t =
let e, learned = to_gil_expr_undelayed ~chunk ~range svarr in
Delayed.return ~learned e
let of_gil_expr_exn expr = Arr expr
* Only call on Mint8Unsigned arrays
let learn_chunk ~chunk ~size arr =
let bounds =
match chunk with
| Chunk.Mint8unsigned -> Some (0, 255)
| _ -> None
in
let* size = Delayed.reduce size in
match bounds with
| None -> Delayed.return ()
| Some (low, high) -> (
match arr with
| Arr (EList e) ->
let i k = Expr.int k in
let learned =
List.concat_map
(function
| Expr.Lit Undefined -> []
| x ->
let open Formula.Infix in
[ (i low) #<= x; x #<= (i high) ])
e
in
Delayed.return ~learned ()
| Arr e -> (
match size with
| Expr.Lit (Int n) ->
let i k = Expr.int k in
let learned =
List.concat
(List.init (Z.to_int n) (fun k ->
let x = Expr.list_nth e k in
let open Formula.Infix in
[ (i low) #<= x; x #<= (i high) ]))
in
Delayed.return ~learned ()
| _ -> Delayed.return ())
| _ -> Delayed.return ())
let subst ~le_subst t =
match t with
| Arr e ->
let s = le_subst e in
if s == e then t else Arr s
| AllUndef -> AllUndef
| AllZeros -> AllZeros
end
module Infix = struct
let ( @: ) = SVArray.concat
let ( ^: ) = SVArray.array_cons
let ( ^:? ) a b = Option.bind b (fun b -> a ^: b)
end
|
6a8a22e9c008bc8263bba5852b70d6fb5370e3dca2085158ec14f8aafdabee2b | borgeby/jarl | strings_test.cljc | (ns jarl.builtins.strings-test
(:require [test.utils :refer [testing-builtin]]
#?(:clj [clojure.test :refer [deftest]]
:cljs [cljs.test :refer [deftest]])))
(deftest builtin-concat-test
(testing-builtin "concat"
[", " ["a" "b" "c"]] "a, b, c"
["🙂" ["🙃" "🙃" "🙃"]] "🙃🙂🙃🙂🙃"
; concat sets
[", " #{"a", "b", "c"}] "a, b, c"
[", " #{"c", "b", "a"}] "a, b, c"))
(deftest builtin-contains-test
(testing-builtin "contains"
["some text included" "text"] true
["some ünicÖde works" "ünicÖde"] true
["negative test" "positive"] false
["🍧🍨🧁🍰🍮" "🍨🧁🍰"] true))
(deftest builtin-endswith-test
(testing-builtin "endswith"
["some text included" "included"] true
["some ünicÖde" "ünicÖde"] true
["negative test" "positive"] false))
(deftest builtin-format-int-test
(testing-builtin "format_int"
[10 10] "10"
[10 2] "1010"
[10 16] "a"))
#?(:clj
(deftest builtin-indexof-test
(testing-builtin "indexof"
["some text included" "text"] 5
["some ünicÖde" "ünicÖde"] 5
["negative test" "positive"] -1
["🍧🍨🧁🍰🍮" "🍮"] 4)))
#?(:clj
(deftest builtin-indexof-n-test
(testing-builtin "indexof_n"
["some text included" "e"] [3 6 16]
["some ünicÖde" "Ö"] [9]
["negative test" "positive"] []
["🍧🍮🍨🧁🍰🍮" "🍮"] [1 5])))
(deftest builtin-lower-test
(testing-builtin "lower"
["ABBA"] "abba"
["ÛnicÖde"] "ûnicöde"))
(deftest builtin-replace-test
(testing-builtin "replace"
["abba" "a" "e"] "ebbe"
["abba" "e" "a"] "abba"
["ÛnicÖde" "Ö" "o"] "Ûnicode"))
(deftest builtin-strings-reverse-test
(testing-builtin "strings.reverse"
["abba"] "abba"
["ÛnicÖde"] "edÖcinÛ"))
#?(:clj
(deftest builtin-split-test
(testing-builtin "split"
["a,b,c" ","] ["a" "b" "c"]
["abc", ","] ["abc"]
["abc" ""] ["a" "b" "c"]
["abc" "a"] ["" "bc"]
["åäö" ""] ["å" "ä" "ö"]
[",a,b,,c", ","] ["", "a", "b", "", "c"]
; regex escape
["a[b[c" "["] ["a" "b" "c"]
["a*b*c" "*"] ["a" "b" "c"]
string and are the same ( quirk )
["abc", "abc"] ["" ""])))
(deftest builtin-startswith-test
(testing-builtin "startswith"
["some text included" "some"] true
["ünicÖde everywhere" "ünicÖde"] true
["negative test" "positive"] false))
#?(:clj
(deftest builtin-substring-test
(testing-builtin "substring"
["abcde" 1 3] "bcd"
["aaa" 4 -1] ""
["aaa" 3 3] ""
["abcde" 0 5] "abcde"
["ünicÖde" 4 1] "Ö"
["a" 0 100] "a"
["everything" 0 -1] "everything"
; code points
["⭐🚀🙂" 0 1] "⭐"
["⭐🚀🙂" 1 1] "🚀"
["⭐🚀🙂" 0 -1] "⭐🚀🙂"
["⭐🚀🙂" 1 -1] "🚀🙂"
["𨦇𨦈𥻘" 1 2] "𨦈𥻘"
; negative offset
["a" -1 1] [:jarl.exceptions/builtin-exception "negative offset"])))
(deftest builtin-trim-test
(testing-builtin "trim"
["abcde" "ae"] "bcd"
["abcde" "cbae"] "d"
["aalalaah" "ah"] "lal"
[" test " " t"] "es"
["foo" "foo"] ""))
(deftest builtin-trim-left-test
(testing-builtin "trim_left"
["abcde" "x"] "abcde"
["abcde" "cba"] "de"
["åäö" "åä"] "ö"
[" test" " t"] "est"
["foo" "foo"] ""))
(deftest builtin-trim-prefix-test
(testing-builtin "trim_prefix"
["some text included" "some "] "text included"
["ünicÖde everywhere" "ünicÖde "] "everywhere"
["negative test" "positive"] "negative test"))
(deftest builtin-trim-right-test
(testing-builtin "trim_right"
["abcde" "x"] "abcde"
["abcde" "cde"] "ab"
["åäö" "öä"] "å"
["test " " t"] "tes"))
(deftest builtin-trim-suffix-test
(testing-builtin "trim_suffix"
["some text included" " included"] "some text"
["ünicÖde everywhere" " everywhere"] "ünicÖde"
["negative test" "positive"] "negative test"))
(deftest builtin-trim-space-test
(testing-builtin "trim_space"
[" foo "] "foo"
["foo"] "foo"
["\n\t foo\n \n"] "foo"))
(deftest builtin-upper-test
(testing-builtin "upper"
["abba"] "ABBA"
["ûnicöde"] "ÛNICÖDE"))
;(deftest builtin-sprintf-test
( testing - builtin " sprintf "
; ["ab%s%s" ["c" "d"]] "abcd"
[ " % v " , [ ( BigDecimal . " 2e308 " ) ] ] " 2e308 " ) )
| null | https://raw.githubusercontent.com/borgeby/jarl/2659afc6c72afb961cb1e98b779beb2b0b5d79c6/core/src/test/cljc/jarl/builtins/strings_test.cljc | clojure | concat sets
regex escape
code points
negative offset
(deftest builtin-sprintf-test
["ab%s%s" ["c" "d"]] "abcd" | (ns jarl.builtins.strings-test
(:require [test.utils :refer [testing-builtin]]
#?(:clj [clojure.test :refer [deftest]]
:cljs [cljs.test :refer [deftest]])))
(deftest builtin-concat-test
(testing-builtin "concat"
[", " ["a" "b" "c"]] "a, b, c"
["🙂" ["🙃" "🙃" "🙃"]] "🙃🙂🙃🙂🙃"
[", " #{"a", "b", "c"}] "a, b, c"
[", " #{"c", "b", "a"}] "a, b, c"))
(deftest builtin-contains-test
(testing-builtin "contains"
["some text included" "text"] true
["some ünicÖde works" "ünicÖde"] true
["negative test" "positive"] false
["🍧🍨🧁🍰🍮" "🍨🧁🍰"] true))
(deftest builtin-endswith-test
(testing-builtin "endswith"
["some text included" "included"] true
["some ünicÖde" "ünicÖde"] true
["negative test" "positive"] false))
(deftest builtin-format-int-test
(testing-builtin "format_int"
[10 10] "10"
[10 2] "1010"
[10 16] "a"))
#?(:clj
(deftest builtin-indexof-test
(testing-builtin "indexof"
["some text included" "text"] 5
["some ünicÖde" "ünicÖde"] 5
["negative test" "positive"] -1
["🍧🍨🧁🍰🍮" "🍮"] 4)))
#?(:clj
(deftest builtin-indexof-n-test
(testing-builtin "indexof_n"
["some text included" "e"] [3 6 16]
["some ünicÖde" "Ö"] [9]
["negative test" "positive"] []
["🍧🍮🍨🧁🍰🍮" "🍮"] [1 5])))
(deftest builtin-lower-test
(testing-builtin "lower"
["ABBA"] "abba"
["ÛnicÖde"] "ûnicöde"))
(deftest builtin-replace-test
(testing-builtin "replace"
["abba" "a" "e"] "ebbe"
["abba" "e" "a"] "abba"
["ÛnicÖde" "Ö" "o"] "Ûnicode"))
(deftest builtin-strings-reverse-test
(testing-builtin "strings.reverse"
["abba"] "abba"
["ÛnicÖde"] "edÖcinÛ"))
#?(:clj
(deftest builtin-split-test
(testing-builtin "split"
["a,b,c" ","] ["a" "b" "c"]
["abc", ","] ["abc"]
["abc" ""] ["a" "b" "c"]
["abc" "a"] ["" "bc"]
["åäö" ""] ["å" "ä" "ö"]
[",a,b,,c", ","] ["", "a", "b", "", "c"]
["a[b[c" "["] ["a" "b" "c"]
["a*b*c" "*"] ["a" "b" "c"]
string and are the same ( quirk )
["abc", "abc"] ["" ""])))
(deftest builtin-startswith-test
(testing-builtin "startswith"
["some text included" "some"] true
["ünicÖde everywhere" "ünicÖde"] true
["negative test" "positive"] false))
#?(:clj
(deftest builtin-substring-test
(testing-builtin "substring"
["abcde" 1 3] "bcd"
["aaa" 4 -1] ""
["aaa" 3 3] ""
["abcde" 0 5] "abcde"
["ünicÖde" 4 1] "Ö"
["a" 0 100] "a"
["everything" 0 -1] "everything"
["⭐🚀🙂" 0 1] "⭐"
["⭐🚀🙂" 1 1] "🚀"
["⭐🚀🙂" 0 -1] "⭐🚀🙂"
["⭐🚀🙂" 1 -1] "🚀🙂"
["𨦇𨦈𥻘" 1 2] "𨦈𥻘"
["a" -1 1] [:jarl.exceptions/builtin-exception "negative offset"])))
(deftest builtin-trim-test
(testing-builtin "trim"
["abcde" "ae"] "bcd"
["abcde" "cbae"] "d"
["aalalaah" "ah"] "lal"
[" test " " t"] "es"
["foo" "foo"] ""))
(deftest builtin-trim-left-test
(testing-builtin "trim_left"
["abcde" "x"] "abcde"
["abcde" "cba"] "de"
["åäö" "åä"] "ö"
[" test" " t"] "est"
["foo" "foo"] ""))
(deftest builtin-trim-prefix-test
(testing-builtin "trim_prefix"
["some text included" "some "] "text included"
["ünicÖde everywhere" "ünicÖde "] "everywhere"
["negative test" "positive"] "negative test"))
(deftest builtin-trim-right-test
(testing-builtin "trim_right"
["abcde" "x"] "abcde"
["abcde" "cde"] "ab"
["åäö" "öä"] "å"
["test " " t"] "tes"))
(deftest builtin-trim-suffix-test
(testing-builtin "trim_suffix"
["some text included" " included"] "some text"
["ünicÖde everywhere" " everywhere"] "ünicÖde"
["negative test" "positive"] "negative test"))
(deftest builtin-trim-space-test
(testing-builtin "trim_space"
[" foo "] "foo"
["foo"] "foo"
["\n\t foo\n \n"] "foo"))
(deftest builtin-upper-test
(testing-builtin "upper"
["abba"] "ABBA"
["ûnicöde"] "ÛNICÖDE"))
( testing - builtin " sprintf "
[ " % v " , [ ( BigDecimal . " 2e308 " ) ] ] " 2e308 " ) )
|
008d88445a23e87ecda630c12f6958e4ab246161c106944577a09f548be8e19b | pyr/cyanite | config.clj | (ns io.cyanite.config
"Yaml config parser, with a poor man's dependency injector"
(:require [com.stuartsierra.component :as component]
[clj-yaml.core :refer [parse-string]]
[clojure.tools.logging :refer [error info debug]]))
(def default-logging
"Default logging configuration. Refer to
for details."
{:pattern "%p [%d] %t - %c - %m%n"
:external false
:console true
:files []
:level "info"})
(defn load-path
"Try to find a pathname, on the command line, in
system properties or the environment and load it."
[path]
(-> (or path
(System/getProperty "cyanite.configuration")
(System/getenv "CYANITE_CONFIGURATION")
"/etc/cyanite.yaml")
slurp
parse-string))
| null | https://raw.githubusercontent.com/pyr/cyanite/2b9a1f26df808abdad3465dd1946036749b93000/src/io/cyanite/config.clj | clojure | (ns io.cyanite.config
"Yaml config parser, with a poor man's dependency injector"
(:require [com.stuartsierra.component :as component]
[clj-yaml.core :refer [parse-string]]
[clojure.tools.logging :refer [error info debug]]))
(def default-logging
"Default logging configuration. Refer to
for details."
{:pattern "%p [%d] %t - %c - %m%n"
:external false
:console true
:files []
:level "info"})
(defn load-path
"Try to find a pathname, on the command line, in
system properties or the environment and load it."
[path]
(-> (or path
(System/getProperty "cyanite.configuration")
(System/getenv "CYANITE_CONFIGURATION")
"/etc/cyanite.yaml")
slurp
parse-string))
|
|
7f255ebdfd4e5633e9c90ce4fe0c955e3fdd9e2663d13128e9869f53f76d91de | brendanhay/gogol | Add.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 : . WebmasterTools . Webmasters . Sites . Add
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Adds a site to the set of the user\ 's sites in Search Console .
--
-- /See:/ <-tools/ Search Console API Reference> for @webmasters.sites.add@.
module Gogol.WebmasterTools.Webmasters.Sites.Add
( -- * Resource
WebmastersSitesAddResource,
-- ** Constructing a Request
WebmastersSitesAdd (..),
newWebmastersSitesAdd,
)
where
import qualified Gogol.Prelude as Core
import Gogol.WebmasterTools.Types
| A resource alias for @webmasters.sites.add@ method which the
-- 'WebmastersSitesAdd' request conforms to.
type WebmastersSitesAddResource =
"webmasters"
Core.:> "v3"
Core.:> "sites"
Core.:> Core.Capture "siteUrl" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Put '[Core.JSON] ()
| Adds a site to the set of the user\ 's sites in Search Console .
--
-- /See:/ 'newWebmastersSitesAdd' smart constructor.
newtype WebmastersSitesAdd = WebmastersSitesAdd
{ -- | The URL of the site to add.
siteUrl :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'WebmastersSitesAdd' with the minimum fields required to make a request.
newWebmastersSitesAdd ::
-- | The URL of the site to add. See 'siteUrl'.
Core.Text ->
WebmastersSitesAdd
newWebmastersSitesAdd siteUrl = WebmastersSitesAdd {siteUrl = siteUrl}
instance Core.GoogleRequest WebmastersSitesAdd where
type Rs WebmastersSitesAdd = ()
type
Scopes WebmastersSitesAdd =
'[Webmasters'FullControl]
requestClient WebmastersSitesAdd {..} =
go
siteUrl
(Core.Just Core.AltJSON)
webmasterToolsService
where
go =
Core.buildClient
(Core.Proxy :: Core.Proxy WebmastersSitesAddResource)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-webmaster-tools/gen/Gogol/WebmasterTools/Webmasters/Sites/Add.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
/See:/ <-tools/ Search Console API Reference> for @webmasters.sites.add@.
* Resource
** Constructing a Request
'WebmastersSitesAdd' request conforms to.
/See:/ 'newWebmastersSitesAdd' smart constructor.
| The URL of the site to add.
| Creates a value of 'WebmastersSitesAdd' with the minimum fields required to make a request.
| The URL of the site to add. See 'siteUrl'. | # 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 : . WebmasterTools . Webmasters . Sites . Add
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Adds a site to the set of the user\ 's sites in Search Console .
module Gogol.WebmasterTools.Webmasters.Sites.Add
WebmastersSitesAddResource,
WebmastersSitesAdd (..),
newWebmastersSitesAdd,
)
where
import qualified Gogol.Prelude as Core
import Gogol.WebmasterTools.Types
| A resource alias for @webmasters.sites.add@ method which the
type WebmastersSitesAddResource =
"webmasters"
Core.:> "v3"
Core.:> "sites"
Core.:> Core.Capture "siteUrl" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Put '[Core.JSON] ()
| Adds a site to the set of the user\ 's sites in Search Console .
newtype WebmastersSitesAdd = WebmastersSitesAdd
siteUrl :: Core.Text
}
deriving (Core.Eq, Core.Show, Core.Generic)
newWebmastersSitesAdd ::
Core.Text ->
WebmastersSitesAdd
newWebmastersSitesAdd siteUrl = WebmastersSitesAdd {siteUrl = siteUrl}
instance Core.GoogleRequest WebmastersSitesAdd where
type Rs WebmastersSitesAdd = ()
type
Scopes WebmastersSitesAdd =
'[Webmasters'FullControl]
requestClient WebmastersSitesAdd {..} =
go
siteUrl
(Core.Just Core.AltJSON)
webmasterToolsService
where
go =
Core.buildClient
(Core.Proxy :: Core.Proxy WebmastersSitesAddResource)
Core.mempty
|
0f0388b1e2b5c3022f4393fdae8d8176cc030395f1dbde95ca3cc1039b3ab1c6 | haroldcarr/learn-haskell-coq-ml-etc | TimWilliamsStreaming.hs | # LANGUAGE DeriveFunctor #
# LANGUAGE InstanceSigs #
{-# LANGUAGE LambdaCase #-}
module TimWilliamsStreaming where
-- ListT done right
-- list elements 'a' interleaved with effect 'm'
newtype ListT m a = ListT { runListT :: m (Step m a) }
deriving Functor
data Step m a
= Cons a (ListT m a)
| Nil
deriving Functor
instance Monad m => Semigroup (ListT m a) where
(<>) = undefined
instance Monad m => Monoid (ListT m a) where
mempty = ListT $ return Nil
mappend (ListT m) s' = ListT $ m >>= \case
Cons a s -> return $ Cons a (s `mappend` s')
Nil -> runListT s'
concat :: Monad m => ListT m (ListT m a) -> ListT m a
concat (ListT m) = ListT $ m >>= \case
Cons s ss -> runListT $ s `mappend` TimWilliamsStreaming.concat ss
Nil -> return Nil
instance Monad m => Applicative (ListT m) where
pure a = ListT $ return $ Cons a mempty
(<*>) = undefined
instance Monad m => Monad (ListT m) where
return = pure
(>>=) :: ListT m a -> (a -> ListT m b) -> ListT m b
s >>= f = TimWilliamsStreaming.concat $ fmap f s
instance MonadTrans ListT where
lift = ListT $ m >>= \a -> return (Cons a mempty)
instance MonadIO m => MonadIO (ListT m) where
liftIO = lift (liftIO m) | null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/ghc-extensions/src/TimWilliamsStreaming.hs | haskell | # LANGUAGE LambdaCase #
ListT done right
list elements 'a' interleaved with effect 'm' | # LANGUAGE DeriveFunctor #
# LANGUAGE InstanceSigs #
module TimWilliamsStreaming where
newtype ListT m a = ListT { runListT :: m (Step m a) }
deriving Functor
data Step m a
= Cons a (ListT m a)
| Nil
deriving Functor
instance Monad m => Semigroup (ListT m a) where
(<>) = undefined
instance Monad m => Monoid (ListT m a) where
mempty = ListT $ return Nil
mappend (ListT m) s' = ListT $ m >>= \case
Cons a s -> return $ Cons a (s `mappend` s')
Nil -> runListT s'
concat :: Monad m => ListT m (ListT m a) -> ListT m a
concat (ListT m) = ListT $ m >>= \case
Cons s ss -> runListT $ s `mappend` TimWilliamsStreaming.concat ss
Nil -> return Nil
instance Monad m => Applicative (ListT m) where
pure a = ListT $ return $ Cons a mempty
(<*>) = undefined
instance Monad m => Monad (ListT m) where
return = pure
(>>=) :: ListT m a -> (a -> ListT m b) -> ListT m b
s >>= f = TimWilliamsStreaming.concat $ fmap f s
instance MonadTrans ListT where
lift = ListT $ m >>= \a -> return (Cons a mempty)
instance MonadIO m => MonadIO (ListT m) where
liftIO = lift (liftIO m) |
f589afbf6567b0bde25c3cf23f93836242c0b83e79fc3833a891838be416764a | ConsenSysMesh/Fae | Collect.hs | import Blockchain.Fae.Contracts
import Blockchain.Fae.Currency
import Blockchain.Fae.Transactions.TX$aucTX.Auction
body :: AuctionResult Coin String -> FaeTX String
body (Remit c) = do
deposit c "self"
return "Collected"
body _ = error "unexpected result"
| null | https://raw.githubusercontent.com/ConsenSysMesh/Fae/3ff023f70fa403e9cef80045907e415ccd88d7e8/demos/Auction/Collect.hs | haskell | import Blockchain.Fae.Contracts
import Blockchain.Fae.Currency
import Blockchain.Fae.Transactions.TX$aucTX.Auction
body :: AuctionResult Coin String -> FaeTX String
body (Remit c) = do
deposit c "self"
return "Collected"
body _ = error "unexpected result"
|
|
bc615703fc95be11d53107f8ab6295af233d1a85273cc702354889b9854f5123 | jgoerzen/hsh | ShellEquivs.hs | # LANGUAGE ScopedTypeVariables #
Shell Equivalents
Copyright ( C ) 2004 - 2009 < >
Please see the COPYRIGHT file
Copyright (C) 2004-2009 John Goerzen <>
Please see the COPYRIGHT file
-}
|
Module : HSH.ShellEquivs
Copyright : Copyright ( C ) 2009
License : GNU LGPL , version 2.1 or above
Maintainer : < >
Stability : provisional
Portability : portable
Copyright ( c ) 2006 - 2009 , jgoerzen\@complete.org
This module provides shell - like commands . Most , but not all , are designed
to be used directly as part of a HSH pipeline . All may be used outside
HSH entirely as well .
Module : HSH.ShellEquivs
Copyright : Copyright (C) 2009 John Goerzen
License : GNU LGPL, version 2.1 or above
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
Copyright (c) 2006-2009 John Goerzen, jgoerzen\@complete.org
This module provides shell-like commands. Most, but not all, are designed
to be used directly as part of a HSH pipeline. All may be used outside
HSH entirely as well.
-}
# LANGUAGE ScopedTypeVariables #
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
#define __HSH_POSIX__
#else
#define __HSH_WINDOWS__
#endif
module HSH.ShellEquivs(
abspath,
appendTo,
basename,
bracketCD,
catFrom,
catBytes,
catBytesFrom,
catTo,
#ifdef __HSH_POSIX__
catToFIFO,
#endif
cd,
cut,
cutR,
dirname,
discard,
echo,
exit,
glob,
grep,
grepV,
egrep,
egrepV,
joinLines,
lower,
upper,
mkdir,
numberLines,
pwd,
#ifdef __HSH_POSIX__
readlink,
readlinkabs,
#endif
rev,
revW,
HSH.Command.setenv,
space,
unspace,
tac,
tee,
#ifdef __HSH_POSIX__
teeFIFO,
#endif
tr,
trd,
wcW,
wcL,
HSH.Command.unsetenv,
uniq,
) where
import Data.List (genericLength, intersperse, isInfixOf, nub)
import Data.Char (toLower, toUpper)
import Text.Regex (matchRegex, mkRegex)
import Text.Printf (printf)
import Control.Monad (foldM)
import System.Directory hiding (createDirectory, isSymbolicLink)
import qualified Control.Exception as E
import System . FilePath ( splitPath )
#ifdef __HSH_POSIX__
import System.Posix.Files (getFileStatus, isSymbolicLink, readSymbolicLink)
import System.Posix.User (getEffectiveUserName, getUserEntryForName, homeDirectory)
import System.Posix.Directory (createDirectory)
import System.Posix.Types (FileMode())
import System.Posix.IO
import System.Posix.Error
#endif
import System.Path (absNormPath, bracketCWD)
import System.Exit
import System.IO
import System.Process
import qualified System.Directory as SD
import qualified System.Path.Glob as Glob (glob)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import System.IO.Unsafe(unsafeInterleaveIO)
import HSH.Channel
import HSH.Command(setenv, unsetenv)
{- | Return the absolute path of the arg. Raises an error if the
computation is impossible. This is a thin wrapper around
System.Path.absNormPath. Unix/Linux users note:
System.Path.absNormPath is known to produce odd results when
a tilde expansion is requested; you might prefer 'glob' to this
function if you know your input is free of wildcards. See
for details. -}
abspath :: FilePath -> IO FilePath
abspath inp =
do p <- pwd
case absNormPath p inp of
Nothing -> fail $ "Cannot make " ++ show inp ++ " absolute within " ++
show p
Just x -> return x
{- | The filename part of a path -}
basename :: FilePath -> FilePath
basename = snd . splitpath
{- | The directory part of a path -}
dirname :: FilePath -> FilePath
dirname = fst . splitpath
| Changes the current working directory to the given path , executes
the given I\/O action , then changes back to the original directory ,
even if the I\/O action raised an exception .
This is an alias for the MissingH function System . Path.bracketCWD .
the given I\/O action, then changes back to the original directory,
even if the I\/O action raised an exception.
This is an alias for the MissingH function System.Path.bracketCWD. -}
bracketCD :: FilePath -> IO a -> IO a
bracketCD = bracketCWD
| Load the specified files and display them , one at a time .
The special file @-@ means to display the input . If it is not given ,
no input is processed at all .
@-@ may be given a maximum of one time .
See also ' catBytes ' .
The special file @-@ means to display the input. If it is not given,
no input is processed at all.
@-@ may be given a maximum of one time.
See also 'catBytes' . -}
catFrom :: [FilePath] -> Channel -> IO Channel
catFrom fplist ichan =
do r <- foldM foldfunc BSL.empty fplist
return (toChannel r)
where foldfunc accum fp =
case fp of
"-" -> do c <- chanAsBSL ichan
return (BSL.append accum c)
fn -> do c <- BSL.readFile fn
return (BSL.append accum c)
| Copy data from input to output , optionally with a fixed
maximum size , in bytes . Processes data using ByteStrings internally ,
so be aware of any possible UTF-8 conversions .
You may wish to use @hSetBuffering h ( BlockBuffering Nothing)@ prior to calling
this function for optimal performance .
See also ' catFrom ' , ' catBytesFrom '
maximum size, in bytes. Processes data using ByteStrings internally,
so be aware of any possible UTF-8 conversions.
You may wish to use @hSetBuffering h (BlockBuffering Nothing)@ prior to calling
this function for optimal performance.
See also 'catFrom', 'catBytesFrom' -}
catBytes :: (Maybe Integer) -- ^ Maximum amount of data to transfer
-> Channel -- ^ Handle for input
-> IO Channel
catBytes count hr = catBytesFrom hr count hr
| Generic version of ' catBytes ' ; reads data from specified Channel , and
ignores stdin .
ignores stdin.
-}
catBytesFrom :: Channel -- ^ Handle to read from
-> (Maybe Integer) -- ^ Maximum amount of data to transfer
-> Channel -- ^ Handle for input (ignored)
-> IO Channel
catBytesFrom (ChanHandle hr) count cignore =
case count of
Nothing -> return (ChanHandle hr)
Just m -> do c <- BSL.hGet hr (fromIntegral m)
return (ChanBSL c)
catBytesFrom cinput count cignore =
case count of
Nothing -> return cinput
Just m -> do r <- chanAsBSL cinput
return (ChanBSL (BSL.take (fromIntegral m) r))
{- | Takes input, writes it to the specified file, and does not pass it on.
The return value is the empty string. See also 'catToBS',
'catToFIFO' -}
catTo :: FilePath -> Channel -> IO Channel
catTo fp ichan =
do ofile <- openFile fp WriteMode
chanToHandle True ichan ofile
return (ChanString "")
#ifdef __HSH_POSIX__
| Like ' catTo ' , but opens the destination in ReadWriteMode instead of
ReadOnlyMode . Due to an oddity of the Haskell IO system , this is required
when writing to a named pipe ( FIFO ) even if you will never read from it .
This call will BLOCK all threads on open until a reader connects .
This is provided in addition to ' catTo ' because you may want to cat to
something that you do not have permission to read from .
This function is only available on POSIX platforms .
See also ' catTo '
ReadOnlyMode. Due to an oddity of the Haskell IO system, this is required
when writing to a named pipe (FIFO) even if you will never read from it.
This call will BLOCK all threads on open until a reader connects.
This is provided in addition to 'catTo' because you may want to cat to
something that you do not have permission to read from.
This function is only available on POSIX platforms.
See also 'catTo' -}
catToFIFO :: FilePath -> Channel -> IO Channel
catToFIFO fp ichan =
do h <- fifoOpen fp
chanToHandle True ichan h
return (ChanString "")
fifoOpen :: FilePath -> IO Handle
fifoOpen fp =
do fd <- throwErrnoPathIf (< 0) "HSH fifoOpen" fp $
openFd fp WriteOnly Nothing defaultFileFlags
fdToHandle fd
#endif
{- | Like 'catTo', but appends to the file. -}
appendTo :: FilePath -> String -> IO String
appendTo fp inp =
do appendFile fp inp
return ""
| An alias for System . Directory.setCurrentDirectory .
Want to change to a user\ 's home directory ? Try this :
> glob " ~jgoerzen " > > = cd . head
See also ' bracketCD ' .
Want to change to a user\'s home directory? Try this:
> glob "~jgoerzen" >>= cd . head
See also 'bracketCD'.
-}
cd :: FilePath -> IO ()
cd = setCurrentDirectory
| Split a list by a given character and select the nth list .
> cut ' ' 2 " foo bar baz quux " - > " bar "
> cut ' ' 2 "foo bar baz quux" -> "bar"
-}
cut :: Integer -> Char -> String -> String
cut pos = cutR [pos]
{- | Read all input and produce no output. Discards input completely. -}
discard :: Channel -> IO Channel
discard inh =
do c <- chanAsBSL inh
E.evaluate (BSL.length c)
return (ChanString "")
| Split a list by a given character and select ranges of the resultant lists .
> cutR [ 2 .. 4 ] ' ' " foo bar baz quux foobar " - > " baz quux foobar "
> cutR [ 1 .. 1000 ] ' ' " foo bar baz quux foobar " - > " bar baz quux foobar "
> cutR [ -1000 .. 1000 ] ' ' " foo bar baz quux foobar " - > " foo bar baz quux foobar "
Note that too large and too small indices are essentially ignored .
> cutR [2..4] ' ' "foo bar baz quux foobar" -> "baz quux foobar"
> cutR [1..1000] ' ' "foo bar baz quux foobar" -> "bar baz quux foobar"
> cutR [-1000..1000] ' ' "foo bar baz quux foobar" -> "foo bar baz quux foobar"
Note that too large and too small indices are essentially ignored.
-}
cutR :: [Integer] -> Char -> String -> String
cutR nums delim z = drop 1 $ concat [delim:x | (x, y) <- zip string [0..], elem y nums]
where string = split delim z
| Takes a string and sends it on as standard output .
The input to this function is never read .
You can pass this thing a String , a ByteString , or even a Handle .
See also ' echoBS ' .
The input to this function is never read.
You can pass this thing a String, a ByteString, or even a Handle.
See also 'echoBS'. -}
echo :: Channelizable a => a -> Channel -> IO Channel
echo inp _ = return . toChannel $ inp
{- | Search for the regexp in the lines. Return those that match. -}
egrep :: String -> [String] -> [String]
egrep pat = filter (ismatch regex)
where regex = mkRegex pat
ismatch r inp = case matchRegex r inp of
Nothing -> False
Just _ -> True
{- | Search for the regexp in the lines. Return those that do NOT match. -}
egrepV :: String -> [String] -> [String]
egrepV pat = filter (not . ismatch regex)
where regex = mkRegex pat
ismatch r inp = case matchRegex r inp of
Nothing -> False
Just _ -> True
{- | Exits with the specified error code. 0 indicates no error. -}
exit :: Int -> IO a
exit code
| code == 0 = exitWith ExitSuccess
| otherwise = exitWith (ExitFailure code)
| Takes a pattern . Returns a list of names that match that pattern .
Handles :
> ~username at beginning of file to expand to user 's home dir
> ? matches exactly one character
> * matches zero or more characters
> [ list ] matches any character in list
> [ ! list ] matches any character not in list
The result of a tilde expansion on a nonexistant username is to do no
tilde expansion .
The tilde with no username equates to the current user .
Non - tilde expansion is done by the MissingH module System . Path . Glob .
Handles:
>~username at beginning of file to expand to user's home dir
>? matches exactly one character
>* matches zero or more characters
>[list] matches any character in list
>[!list] matches any character not in list
The result of a tilde expansion on a nonexistant username is to do no
tilde expansion.
The tilde with no username equates to the current user.
Non-tilde expansion is done by the MissingH module System.Path.Glob. -}
glob :: FilePath -> IO [FilePath]
glob inp@('~':remainder) =
E.catch expanduser (\(e::E.SomeException) -> Glob.glob rest)
where (username, rest) = span (/= '/') remainder
#ifdef __HSH_POSIX__
expanduser =
do lookupuser <-
if username /= ""
then return username
else getEffectiveUserName
ue <- getUserEntryForName lookupuser
Glob.glob (homeDirectory ue ++ rest)
#else
expanduser = fail "non-posix; will be caught above"
#endif
glob x = Glob.glob x
{- | Search for the string in the lines. Return those that match.
Same as:
> grep needle = filter (isInfixOf needle)
-}
grep :: String -> [String] -> [String]
grep = filter . isInfixOf
{- | Search for the string in the lines. Return those that do NOT match. -}
grepV :: String -> [String] -> [String]
grepV needle = filter (not . isInfixOf needle)
-- | Join lines of a file
joinLines :: [String] -> [String]
joinLines = return . concat
#ifdef __HSH_POSIX__
| Creates the given directory . A value of 0o755 for mode would be typical .
An alias for System . . Directory.createDirectory .
The second argument will be ignored on non - POSIX systems .
An alias for System.Posix.Directory.createDirectory.
The second argument will be ignored on non-POSIX systems. -}
mkdir :: FilePath -> FileMode -> IO ()
mkdir = createDirectory
#else
mkdir :: FilePath -> a -> IO ()
mkdir fp _ = SD.createDirectory fp
#endif
{- | Number each line of a file -}
numberLines :: [String] -> [String]
numberLines = zipWith (printf "%3d %s") [(1::Int)..]
| An alias for System . .
pwd :: IO FilePath
pwd = getCurrentDirectory
#ifdef __HSH_POSIX__
| Return the destination that the given symlink points to .
An alias for System . . Files.readSymbolicLink
This function is only available on POSIX platforms .
An alias for System.Posix.Files.readSymbolicLink
This function is only available on POSIX platforms. -}
readlink :: FilePath -> IO FilePath
readlink fp =
do issym <- (getFileStatus fp >>= return . isSymbolicLink)
if issym
then readSymbolicLink fp
else return fp
{- | As 'readlink', but turns the result into an absolute path.
This function is only available on POSIX platforms. -}
readlinkabs :: FilePath -> IO FilePath
readlinkabs inp =
do issym <- (getFileStatus inp >>= return . isSymbolicLink)
if issym
then do rl <- readlink inp
case absNormPath (dirname inp) rl of
Nothing -> fail $ "Cannot make " ++ show rl ++ " absolute within " ++
show (dirname inp)
Just x -> return x
else abspath inp
#endif
{- | Reverse characters on each line (rev) -}
rev, revW :: [String] -> [String]
rev = map reverse
{- | Reverse words on each line -}
revW = map (unwords . reverse . words)
{- | Reverse lines in a String (like Unix tac).
Implemented as:
> tac = reverse
See 'uniq'. -}
tac :: [String] -> [String]
tac = reverse
{- | Takes input, writes it to all the specified files, and passes it on.
This function does /NOT/ buffer input.
See also 'catFrom'. -}
tee :: [FilePath] -> Channel -> IO Channel
tee fplist inp = teeBSGeneric (\fp -> openFile fp WriteMode) fplist inp
#ifdef __HSH_POSIX__
{- | FIFO-safe version of 'tee'.
This call will BLOCK all threads on open until a reader connects.
This function is only available on POSIX platforms. -}
teeFIFO :: [FilePath] -> Channel -> IO Channel
teeFIFO fplist inp = teeBSGeneric fifoOpen fplist inp
#endif
teeBSGeneric :: (FilePath -> IO Handle)
-> [FilePath]
-> Channel -> IO Channel
teeBSGeneric openfunc fplist ichan =
do handles <- mapM openfunc fplist
inp <- chanAsBSL ichan
resultChunks <- hProcChunks handles (BSL.toChunks inp)
return (ChanBSL $ BSL.fromChunks resultChunks)
where hProcChunks :: [Handle] -> [BS.ByteString] -> IO [BS.ByteString]
hProcChunks handles chunks = unsafeInterleaveIO $
case chunks of
[] -> do mapM_ hClose handles
return [BS.empty]
(x:xs) -> do mapM_ (\h -> BS.hPutStr h x) handles
remainder <- hProcChunks handles xs
return (x : remainder)
{- | Translate a character x to y, like:
>tr 'e' 'f'
Or, in sed,
>y//
-}
tr :: Char -> Char -> String -> String
tr a b = map (\x -> if x == a then b else x)
{- | Delete specified character in a string. -}
trd :: Char -> String -> String
trd = filter . (/=)
{- | Remove duplicate lines from a file (like Unix uniq).
Takes a String representing a file or output and plugs it through lines and then nub to uniqify on a line basis. -}
uniq :: String -> String
uniq = unlines . nub . lines
{- | Double space a file; add an empty line between each line. -}
space :: [String] -> [String]
space = intersperse ""
{- | Inverse of double 'space'; drop all empty lines. -}
unspace :: [String] -> [String]
unspace = filter (not . null)
{- | Convert a string to all lower case -}
lower :: String -> String
lower = map toLower
{- | Convert a string to all upper case -}
upper :: String -> String
upper = map toUpper
{- | Count number of lines. Like wc -l -}
wcL :: [String] -> [String]
wcL inp = [show (genericLength inp :: Integer)]
{- | Count number of words in a file (like wc -w) -}
wcW :: [String] -> [String]
wcW inp = [show ((genericLength $ words $ unlines inp) :: Integer)]
{- Utility function.
> split ' ' "foo bar baz" -> ["foo","bar","baz"] -}
split :: Char -> String -> [String]
split c s = case rest of
[] -> [chunk]
_:rst -> chunk : split c rst
where (chunk, rest) = break (==c) s
-- TODO: Perhaps simplify to make use of split
splitpath :: String -> (String, String)
splitpath "" = (".", ".")
splitpath "/" = ("/", "/")
splitpath p
| last p == '/' = splitpath (init p)
| not ('/' `elem` p) = (".", p)
| head p == '/' && length (filter (== '/') p) == 1 = ("/", tail p)
| otherwise = (\(base, dir) -> (reverse (tail dir), reverse base))
(break (== '/') (reverse p))
| null | https://raw.githubusercontent.com/jgoerzen/hsh/047197b789bf2ab63c87dcf7acf78db5f7687cf1/HSH/ShellEquivs.hs | haskell | | Return the absolute path of the arg. Raises an error if the
computation is impossible. This is a thin wrapper around
System.Path.absNormPath. Unix/Linux users note:
System.Path.absNormPath is known to produce odd results when
a tilde expansion is requested; you might prefer 'glob' to this
function if you know your input is free of wildcards. See
for details.
| The filename part of a path
| The directory part of a path
^ Maximum amount of data to transfer
^ Handle for input
^ Handle to read from
^ Maximum amount of data to transfer
^ Handle for input (ignored)
| Takes input, writes it to the specified file, and does not pass it on.
The return value is the empty string. See also 'catToBS',
'catToFIFO'
| Like 'catTo', but appends to the file.
| Read all input and produce no output. Discards input completely.
| Search for the regexp in the lines. Return those that match.
| Search for the regexp in the lines. Return those that do NOT match.
| Exits with the specified error code. 0 indicates no error.
| Search for the string in the lines. Return those that match.
Same as:
> grep needle = filter (isInfixOf needle)
| Search for the string in the lines. Return those that do NOT match.
| Join lines of a file
| Number each line of a file
| As 'readlink', but turns the result into an absolute path.
This function is only available on POSIX platforms.
| Reverse characters on each line (rev)
| Reverse words on each line
| Reverse lines in a String (like Unix tac).
Implemented as:
> tac = reverse
See 'uniq'.
| Takes input, writes it to all the specified files, and passes it on.
This function does /NOT/ buffer input.
See also 'catFrom'.
| FIFO-safe version of 'tee'.
This call will BLOCK all threads on open until a reader connects.
This function is only available on POSIX platforms.
| Translate a character x to y, like:
>tr 'e' 'f'
Or, in sed,
>y//
| Delete specified character in a string.
| Remove duplicate lines from a file (like Unix uniq).
Takes a String representing a file or output and plugs it through lines and then nub to uniqify on a line basis.
| Double space a file; add an empty line between each line.
| Inverse of double 'space'; drop all empty lines.
| Convert a string to all lower case
| Convert a string to all upper case
| Count number of lines. Like wc -l
| Count number of words in a file (like wc -w)
Utility function.
> split ' ' "foo bar baz" -> ["foo","bar","baz"]
TODO: Perhaps simplify to make use of split | # LANGUAGE ScopedTypeVariables #
Shell Equivalents
Copyright ( C ) 2004 - 2009 < >
Please see the COPYRIGHT file
Copyright (C) 2004-2009 John Goerzen <>
Please see the COPYRIGHT file
-}
|
Module : HSH.ShellEquivs
Copyright : Copyright ( C ) 2009
License : GNU LGPL , version 2.1 or above
Maintainer : < >
Stability : provisional
Portability : portable
Copyright ( c ) 2006 - 2009 , jgoerzen\@complete.org
This module provides shell - like commands . Most , but not all , are designed
to be used directly as part of a HSH pipeline . All may be used outside
HSH entirely as well .
Module : HSH.ShellEquivs
Copyright : Copyright (C) 2009 John Goerzen
License : GNU LGPL, version 2.1 or above
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
Copyright (c) 2006-2009 John Goerzen, jgoerzen\@complete.org
This module provides shell-like commands. Most, but not all, are designed
to be used directly as part of a HSH pipeline. All may be used outside
HSH entirely as well.
-}
# LANGUAGE ScopedTypeVariables #
#if !(defined(mingw32_HOST_OS) || defined(mingw32_TARGET_OS) || defined(__MINGW32__))
#define __HSH_POSIX__
#else
#define __HSH_WINDOWS__
#endif
module HSH.ShellEquivs(
abspath,
appendTo,
basename,
bracketCD,
catFrom,
catBytes,
catBytesFrom,
catTo,
#ifdef __HSH_POSIX__
catToFIFO,
#endif
cd,
cut,
cutR,
dirname,
discard,
echo,
exit,
glob,
grep,
grepV,
egrep,
egrepV,
joinLines,
lower,
upper,
mkdir,
numberLines,
pwd,
#ifdef __HSH_POSIX__
readlink,
readlinkabs,
#endif
rev,
revW,
HSH.Command.setenv,
space,
unspace,
tac,
tee,
#ifdef __HSH_POSIX__
teeFIFO,
#endif
tr,
trd,
wcW,
wcL,
HSH.Command.unsetenv,
uniq,
) where
import Data.List (genericLength, intersperse, isInfixOf, nub)
import Data.Char (toLower, toUpper)
import Text.Regex (matchRegex, mkRegex)
import Text.Printf (printf)
import Control.Monad (foldM)
import System.Directory hiding (createDirectory, isSymbolicLink)
import qualified Control.Exception as E
import System . FilePath ( splitPath )
#ifdef __HSH_POSIX__
import System.Posix.Files (getFileStatus, isSymbolicLink, readSymbolicLink)
import System.Posix.User (getEffectiveUserName, getUserEntryForName, homeDirectory)
import System.Posix.Directory (createDirectory)
import System.Posix.Types (FileMode())
import System.Posix.IO
import System.Posix.Error
#endif
import System.Path (absNormPath, bracketCWD)
import System.Exit
import System.IO
import System.Process
import qualified System.Directory as SD
import qualified System.Path.Glob as Glob (glob)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import System.IO.Unsafe(unsafeInterleaveIO)
import HSH.Channel
import HSH.Command(setenv, unsetenv)
abspath :: FilePath -> IO FilePath
abspath inp =
do p <- pwd
case absNormPath p inp of
Nothing -> fail $ "Cannot make " ++ show inp ++ " absolute within " ++
show p
Just x -> return x
basename :: FilePath -> FilePath
basename = snd . splitpath
dirname :: FilePath -> FilePath
dirname = fst . splitpath
| Changes the current working directory to the given path , executes
the given I\/O action , then changes back to the original directory ,
even if the I\/O action raised an exception .
This is an alias for the MissingH function System . Path.bracketCWD .
the given I\/O action, then changes back to the original directory,
even if the I\/O action raised an exception.
This is an alias for the MissingH function System.Path.bracketCWD. -}
bracketCD :: FilePath -> IO a -> IO a
bracketCD = bracketCWD
| Load the specified files and display them , one at a time .
The special file @-@ means to display the input . If it is not given ,
no input is processed at all .
@-@ may be given a maximum of one time .
See also ' catBytes ' .
The special file @-@ means to display the input. If it is not given,
no input is processed at all.
@-@ may be given a maximum of one time.
See also 'catBytes' . -}
catFrom :: [FilePath] -> Channel -> IO Channel
catFrom fplist ichan =
do r <- foldM foldfunc BSL.empty fplist
return (toChannel r)
where foldfunc accum fp =
case fp of
"-" -> do c <- chanAsBSL ichan
return (BSL.append accum c)
fn -> do c <- BSL.readFile fn
return (BSL.append accum c)
| Copy data from input to output , optionally with a fixed
maximum size , in bytes . Processes data using ByteStrings internally ,
so be aware of any possible UTF-8 conversions .
You may wish to use @hSetBuffering h ( BlockBuffering Nothing)@ prior to calling
this function for optimal performance .
See also ' catFrom ' , ' catBytesFrom '
maximum size, in bytes. Processes data using ByteStrings internally,
so be aware of any possible UTF-8 conversions.
You may wish to use @hSetBuffering h (BlockBuffering Nothing)@ prior to calling
this function for optimal performance.
See also 'catFrom', 'catBytesFrom' -}
-> IO Channel
catBytes count hr = catBytesFrom hr count hr
| Generic version of ' catBytes ' ; reads data from specified Channel , and
ignores stdin .
ignores stdin.
-}
-> IO Channel
catBytesFrom (ChanHandle hr) count cignore =
case count of
Nothing -> return (ChanHandle hr)
Just m -> do c <- BSL.hGet hr (fromIntegral m)
return (ChanBSL c)
catBytesFrom cinput count cignore =
case count of
Nothing -> return cinput
Just m -> do r <- chanAsBSL cinput
return (ChanBSL (BSL.take (fromIntegral m) r))
catTo :: FilePath -> Channel -> IO Channel
catTo fp ichan =
do ofile <- openFile fp WriteMode
chanToHandle True ichan ofile
return (ChanString "")
#ifdef __HSH_POSIX__
| Like ' catTo ' , but opens the destination in ReadWriteMode instead of
ReadOnlyMode . Due to an oddity of the Haskell IO system , this is required
when writing to a named pipe ( FIFO ) even if you will never read from it .
This call will BLOCK all threads on open until a reader connects .
This is provided in addition to ' catTo ' because you may want to cat to
something that you do not have permission to read from .
This function is only available on POSIX platforms .
See also ' catTo '
ReadOnlyMode. Due to an oddity of the Haskell IO system, this is required
when writing to a named pipe (FIFO) even if you will never read from it.
This call will BLOCK all threads on open until a reader connects.
This is provided in addition to 'catTo' because you may want to cat to
something that you do not have permission to read from.
This function is only available on POSIX platforms.
See also 'catTo' -}
catToFIFO :: FilePath -> Channel -> IO Channel
catToFIFO fp ichan =
do h <- fifoOpen fp
chanToHandle True ichan h
return (ChanString "")
fifoOpen :: FilePath -> IO Handle
fifoOpen fp =
do fd <- throwErrnoPathIf (< 0) "HSH fifoOpen" fp $
openFd fp WriteOnly Nothing defaultFileFlags
fdToHandle fd
#endif
appendTo :: FilePath -> String -> IO String
appendTo fp inp =
do appendFile fp inp
return ""
| An alias for System . Directory.setCurrentDirectory .
Want to change to a user\ 's home directory ? Try this :
> glob " ~jgoerzen " > > = cd . head
See also ' bracketCD ' .
Want to change to a user\'s home directory? Try this:
> glob "~jgoerzen" >>= cd . head
See also 'bracketCD'.
-}
cd :: FilePath -> IO ()
cd = setCurrentDirectory
| Split a list by a given character and select the nth list .
> cut ' ' 2 " foo bar baz quux " - > " bar "
> cut ' ' 2 "foo bar baz quux" -> "bar"
-}
cut :: Integer -> Char -> String -> String
cut pos = cutR [pos]
discard :: Channel -> IO Channel
discard inh =
do c <- chanAsBSL inh
E.evaluate (BSL.length c)
return (ChanString "")
| Split a list by a given character and select ranges of the resultant lists .
> cutR [ 2 .. 4 ] ' ' " foo bar baz quux foobar " - > " baz quux foobar "
> cutR [ 1 .. 1000 ] ' ' " foo bar baz quux foobar " - > " bar baz quux foobar "
> cutR [ -1000 .. 1000 ] ' ' " foo bar baz quux foobar " - > " foo bar baz quux foobar "
Note that too large and too small indices are essentially ignored .
> cutR [2..4] ' ' "foo bar baz quux foobar" -> "baz quux foobar"
> cutR [1..1000] ' ' "foo bar baz quux foobar" -> "bar baz quux foobar"
> cutR [-1000..1000] ' ' "foo bar baz quux foobar" -> "foo bar baz quux foobar"
Note that too large and too small indices are essentially ignored.
-}
cutR :: [Integer] -> Char -> String -> String
cutR nums delim z = drop 1 $ concat [delim:x | (x, y) <- zip string [0..], elem y nums]
where string = split delim z
| Takes a string and sends it on as standard output .
The input to this function is never read .
You can pass this thing a String , a ByteString , or even a Handle .
See also ' echoBS ' .
The input to this function is never read.
You can pass this thing a String, a ByteString, or even a Handle.
See also 'echoBS'. -}
echo :: Channelizable a => a -> Channel -> IO Channel
echo inp _ = return . toChannel $ inp
egrep :: String -> [String] -> [String]
egrep pat = filter (ismatch regex)
where regex = mkRegex pat
ismatch r inp = case matchRegex r inp of
Nothing -> False
Just _ -> True
egrepV :: String -> [String] -> [String]
egrepV pat = filter (not . ismatch regex)
where regex = mkRegex pat
ismatch r inp = case matchRegex r inp of
Nothing -> False
Just _ -> True
exit :: Int -> IO a
exit code
| code == 0 = exitWith ExitSuccess
| otherwise = exitWith (ExitFailure code)
| Takes a pattern . Returns a list of names that match that pattern .
Handles :
> ~username at beginning of file to expand to user 's home dir
> ? matches exactly one character
> * matches zero or more characters
> [ list ] matches any character in list
> [ ! list ] matches any character not in list
The result of a tilde expansion on a nonexistant username is to do no
tilde expansion .
The tilde with no username equates to the current user .
Non - tilde expansion is done by the MissingH module System . Path . Glob .
Handles:
>~username at beginning of file to expand to user's home dir
>? matches exactly one character
>* matches zero or more characters
>[list] matches any character in list
>[!list] matches any character not in list
The result of a tilde expansion on a nonexistant username is to do no
tilde expansion.
The tilde with no username equates to the current user.
Non-tilde expansion is done by the MissingH module System.Path.Glob. -}
glob :: FilePath -> IO [FilePath]
glob inp@('~':remainder) =
E.catch expanduser (\(e::E.SomeException) -> Glob.glob rest)
where (username, rest) = span (/= '/') remainder
#ifdef __HSH_POSIX__
expanduser =
do lookupuser <-
if username /= ""
then return username
else getEffectiveUserName
ue <- getUserEntryForName lookupuser
Glob.glob (homeDirectory ue ++ rest)
#else
expanduser = fail "non-posix; will be caught above"
#endif
glob x = Glob.glob x
grep :: String -> [String] -> [String]
grep = filter . isInfixOf
grepV :: String -> [String] -> [String]
grepV needle = filter (not . isInfixOf needle)
joinLines :: [String] -> [String]
joinLines = return . concat
#ifdef __HSH_POSIX__
| Creates the given directory . A value of 0o755 for mode would be typical .
An alias for System . . Directory.createDirectory .
The second argument will be ignored on non - POSIX systems .
An alias for System.Posix.Directory.createDirectory.
The second argument will be ignored on non-POSIX systems. -}
mkdir :: FilePath -> FileMode -> IO ()
mkdir = createDirectory
#else
mkdir :: FilePath -> a -> IO ()
mkdir fp _ = SD.createDirectory fp
#endif
numberLines :: [String] -> [String]
numberLines = zipWith (printf "%3d %s") [(1::Int)..]
| An alias for System . .
pwd :: IO FilePath
pwd = getCurrentDirectory
#ifdef __HSH_POSIX__
| Return the destination that the given symlink points to .
An alias for System . . Files.readSymbolicLink
This function is only available on POSIX platforms .
An alias for System.Posix.Files.readSymbolicLink
This function is only available on POSIX platforms. -}
readlink :: FilePath -> IO FilePath
readlink fp =
do issym <- (getFileStatus fp >>= return . isSymbolicLink)
if issym
then readSymbolicLink fp
else return fp
readlinkabs :: FilePath -> IO FilePath
readlinkabs inp =
do issym <- (getFileStatus inp >>= return . isSymbolicLink)
if issym
then do rl <- readlink inp
case absNormPath (dirname inp) rl of
Nothing -> fail $ "Cannot make " ++ show rl ++ " absolute within " ++
show (dirname inp)
Just x -> return x
else abspath inp
#endif
rev, revW :: [String] -> [String]
rev = map reverse
revW = map (unwords . reverse . words)
tac :: [String] -> [String]
tac = reverse
tee :: [FilePath] -> Channel -> IO Channel
tee fplist inp = teeBSGeneric (\fp -> openFile fp WriteMode) fplist inp
#ifdef __HSH_POSIX__
teeFIFO :: [FilePath] -> Channel -> IO Channel
teeFIFO fplist inp = teeBSGeneric fifoOpen fplist inp
#endif
teeBSGeneric :: (FilePath -> IO Handle)
-> [FilePath]
-> Channel -> IO Channel
teeBSGeneric openfunc fplist ichan =
do handles <- mapM openfunc fplist
inp <- chanAsBSL ichan
resultChunks <- hProcChunks handles (BSL.toChunks inp)
return (ChanBSL $ BSL.fromChunks resultChunks)
where hProcChunks :: [Handle] -> [BS.ByteString] -> IO [BS.ByteString]
hProcChunks handles chunks = unsafeInterleaveIO $
case chunks of
[] -> do mapM_ hClose handles
return [BS.empty]
(x:xs) -> do mapM_ (\h -> BS.hPutStr h x) handles
remainder <- hProcChunks handles xs
return (x : remainder)
tr :: Char -> Char -> String -> String
tr a b = map (\x -> if x == a then b else x)
trd :: Char -> String -> String
trd = filter . (/=)
uniq :: String -> String
uniq = unlines . nub . lines
space :: [String] -> [String]
space = intersperse ""
unspace :: [String] -> [String]
unspace = filter (not . null)
lower :: String -> String
lower = map toLower
upper :: String -> String
upper = map toUpper
wcL :: [String] -> [String]
wcL inp = [show (genericLength inp :: Integer)]
wcW :: [String] -> [String]
wcW inp = [show ((genericLength $ words $ unlines inp) :: Integer)]
split :: Char -> String -> [String]
split c s = case rest of
[] -> [chunk]
_:rst -> chunk : split c rst
where (chunk, rest) = break (==c) s
splitpath :: String -> (String, String)
splitpath "" = (".", ".")
splitpath "/" = ("/", "/")
splitpath p
| last p == '/' = splitpath (init p)
| not ('/' `elem` p) = (".", p)
| head p == '/' && length (filter (== '/') p) == 1 = ("/", tail p)
| otherwise = (\(base, dir) -> (reverse (tail dir), reverse base))
(break (== '/') (reverse p))
|
eba1f6c10240b69cdbd4292ace14609c80eaf927474a0c64809a4ca0ae862231 | ocaml/odoc | type_of.ml | Type_of.ml
(* Deals with expanding `module type of` expressions *)
open Odoc_model
open Lang
module Id = Odoc_model.Paths.Identifier
let again = ref false
let rec signature : Env.t -> Signature.t -> Signature.t =
fun env sg ->
let items, _ = signature_items env sg.items in
{ sg with items }
and signature_items : Env.t -> Signature.item list -> _ =
fun initial_env s ->
let open Signature in
let rec loop items env xs =
match xs with
| [] -> (List.rev items, env)
| item :: rest -> (
match item with
| Module (Nonrec, _) -> assert false
| Module (r, m) ->
let add_to_env env m =
let ty =
Component.Delayed.(
put (fun () -> Component.Of_Lang.(module_ (empty ()) m)))
in
Env.add_module (m.id :> Paths.Identifier.Path.Module.t) ty [] env
in
let env =
match r with
| Nonrec -> assert false
| Ordinary | And -> env
| Rec ->
let rec find modules rest =
match rest with
| Module (And, m') :: sgs -> find (m' :: modules) sgs
| Module (_, _) :: _ -> List.rev modules
| _ :: sgs -> find modules sgs
| [] -> List.rev modules
in
let modules = find [ m ] rest in
List.fold_left add_to_env env modules
in
let m' = module_ env m in
let env'' =
match r with
| Nonrec -> assert false
| And | Rec -> env
| Ordinary -> add_to_env env m'
in
loop (Module (r, m') :: items) env'' rest
| ModuleSubstitution m ->
let env' = Env.open_module_substitution m env in
loop (item :: items) env' rest
| ModuleType mt ->
let m' = module_type env mt in
let ty = Component.Of_Lang.(module_type (empty ()) m') in
let env' = Env.add_module_type mt.id ty env in
loop (ModuleType (module_type env mt) :: items) env' rest
| Include i ->
let i', env' = include_ env i in
loop (Include i' :: items) env' rest
| item -> loop (item :: items) env rest)
in
loop [] initial_env s
and module_ env m =
match m.type_ with
| Alias _ -> m
| ModuleType expr ->
{
m with
type_ = ModuleType (module_type_expr env (m.id :> Id.Signature.t) expr);
}
and module_type env m =
match m.expr with
| None -> m
| Some expr ->
{
m with
expr = Some (module_type_expr env (m.id :> Id.Signature.t) expr);
}
and module_type_expr_typeof env (id : Id.Signature.t) t =
let open Odoc_model.Lang.ModuleType in
let p, strengthen =
match t.t_desc with ModPath p -> (p, false) | StructInclude p -> (p, true)
in
let cp = Component.Of_Lang.(module_path (empty ()) p) in
let open Expand_tools in
let open Utils.ResultMonad in
Tools.expansion_of_module_path env ~strengthen cp >>= handle_expansion env id
>>= fun (_env, e) -> Ok e
and module_type_expr env (id : Id.Signature.t) expr =
match expr with
| Path _ -> expr
| Functor (Unit, expr) -> Functor (Unit, module_type_expr env id expr)
| Functor (Named p, expr) ->
let env = Env.add_functor_parameter (Named p) env in
Functor (Named (functor_parameter env p), module_type_expr env id expr)
| Signature sg -> Signature (signature env sg)
| With w -> With { w with w_expr = u_module_type_expr env id w.w_expr }
| TypeOf t -> (
match module_type_expr_typeof env id t with
| Ok e ->
let se = Lang_of.(simple_expansion (empty ()) id e) in
TypeOf { t with t_expansion = Some (simple_expansion env se) }
| Error e
when Errors.is_unexpanded_module_type_of (e :> Errors.Tools_error.any)
->
again := true;
expr
| Error _e -> expr)
and u_module_type_expr env id expr =
match expr with
| Path _ -> expr
| Signature sg -> Signature (signature env sg)
| With (subs, w) -> With (subs, u_module_type_expr env id w)
| TypeOf t -> (
match module_type_expr_typeof env id t with
| Ok e ->
let se = Lang_of.(simple_expansion (empty ()) id e) in
TypeOf { t with t_expansion = Some (simple_expansion env se) }
| Error e
when Errors.is_unexpanded_module_type_of (e :> Errors.Tools_error.any)
->
again := true;
expr
| Error _e -> expr)
and functor_parameter env p =
{ p with expr = module_type_expr env (p.id :> Id.Signature.t) p.expr }
and simple_expansion :
Env.t -> ModuleType.simple_expansion -> ModuleType.simple_expansion =
fun env -> function
| Signature sg -> Signature (signature env sg)
| Functor (Named n, sg) ->
Functor (Named (functor_parameter env n), simple_expansion env sg)
| Functor (Unit, sg) -> Functor (Unit, simple_expansion env sg)
and include_ env i =
let decl =
match i.decl with
| Alias _ -> i.decl
| ModuleType t -> ModuleType (u_module_type_expr env i.parent t)
in
let items, env' =
let { Include.content; _ } = i.expansion in
signature_items env content.items
in
( {
i with
expansion =
{ i.expansion with content = { i.expansion.content with items } };
decl;
},
env' )
let signature env =
let rec loop sg =
again := false;
let sg' = signature env sg in
Tools.reset_caches ();
if !again then if sg' = sg then sg else loop sg' else sg'
in
loop
| null | https://raw.githubusercontent.com/ocaml/odoc/7acd9d9be85a299c1c3a532013199f1838eb194a/src/xref2/type_of.ml | ocaml | Deals with expanding `module type of` expressions | Type_of.ml
open Odoc_model
open Lang
module Id = Odoc_model.Paths.Identifier
let again = ref false
let rec signature : Env.t -> Signature.t -> Signature.t =
fun env sg ->
let items, _ = signature_items env sg.items in
{ sg with items }
and signature_items : Env.t -> Signature.item list -> _ =
fun initial_env s ->
let open Signature in
let rec loop items env xs =
match xs with
| [] -> (List.rev items, env)
| item :: rest -> (
match item with
| Module (Nonrec, _) -> assert false
| Module (r, m) ->
let add_to_env env m =
let ty =
Component.Delayed.(
put (fun () -> Component.Of_Lang.(module_ (empty ()) m)))
in
Env.add_module (m.id :> Paths.Identifier.Path.Module.t) ty [] env
in
let env =
match r with
| Nonrec -> assert false
| Ordinary | And -> env
| Rec ->
let rec find modules rest =
match rest with
| Module (And, m') :: sgs -> find (m' :: modules) sgs
| Module (_, _) :: _ -> List.rev modules
| _ :: sgs -> find modules sgs
| [] -> List.rev modules
in
let modules = find [ m ] rest in
List.fold_left add_to_env env modules
in
let m' = module_ env m in
let env'' =
match r with
| Nonrec -> assert false
| And | Rec -> env
| Ordinary -> add_to_env env m'
in
loop (Module (r, m') :: items) env'' rest
| ModuleSubstitution m ->
let env' = Env.open_module_substitution m env in
loop (item :: items) env' rest
| ModuleType mt ->
let m' = module_type env mt in
let ty = Component.Of_Lang.(module_type (empty ()) m') in
let env' = Env.add_module_type mt.id ty env in
loop (ModuleType (module_type env mt) :: items) env' rest
| Include i ->
let i', env' = include_ env i in
loop (Include i' :: items) env' rest
| item -> loop (item :: items) env rest)
in
loop [] initial_env s
and module_ env m =
match m.type_ with
| Alias _ -> m
| ModuleType expr ->
{
m with
type_ = ModuleType (module_type_expr env (m.id :> Id.Signature.t) expr);
}
and module_type env m =
match m.expr with
| None -> m
| Some expr ->
{
m with
expr = Some (module_type_expr env (m.id :> Id.Signature.t) expr);
}
and module_type_expr_typeof env (id : Id.Signature.t) t =
let open Odoc_model.Lang.ModuleType in
let p, strengthen =
match t.t_desc with ModPath p -> (p, false) | StructInclude p -> (p, true)
in
let cp = Component.Of_Lang.(module_path (empty ()) p) in
let open Expand_tools in
let open Utils.ResultMonad in
Tools.expansion_of_module_path env ~strengthen cp >>= handle_expansion env id
>>= fun (_env, e) -> Ok e
and module_type_expr env (id : Id.Signature.t) expr =
match expr with
| Path _ -> expr
| Functor (Unit, expr) -> Functor (Unit, module_type_expr env id expr)
| Functor (Named p, expr) ->
let env = Env.add_functor_parameter (Named p) env in
Functor (Named (functor_parameter env p), module_type_expr env id expr)
| Signature sg -> Signature (signature env sg)
| With w -> With { w with w_expr = u_module_type_expr env id w.w_expr }
| TypeOf t -> (
match module_type_expr_typeof env id t with
| Ok e ->
let se = Lang_of.(simple_expansion (empty ()) id e) in
TypeOf { t with t_expansion = Some (simple_expansion env se) }
| Error e
when Errors.is_unexpanded_module_type_of (e :> Errors.Tools_error.any)
->
again := true;
expr
| Error _e -> expr)
and u_module_type_expr env id expr =
match expr with
| Path _ -> expr
| Signature sg -> Signature (signature env sg)
| With (subs, w) -> With (subs, u_module_type_expr env id w)
| TypeOf t -> (
match module_type_expr_typeof env id t with
| Ok e ->
let se = Lang_of.(simple_expansion (empty ()) id e) in
TypeOf { t with t_expansion = Some (simple_expansion env se) }
| Error e
when Errors.is_unexpanded_module_type_of (e :> Errors.Tools_error.any)
->
again := true;
expr
| Error _e -> expr)
and functor_parameter env p =
{ p with expr = module_type_expr env (p.id :> Id.Signature.t) p.expr }
and simple_expansion :
Env.t -> ModuleType.simple_expansion -> ModuleType.simple_expansion =
fun env -> function
| Signature sg -> Signature (signature env sg)
| Functor (Named n, sg) ->
Functor (Named (functor_parameter env n), simple_expansion env sg)
| Functor (Unit, sg) -> Functor (Unit, simple_expansion env sg)
and include_ env i =
let decl =
match i.decl with
| Alias _ -> i.decl
| ModuleType t -> ModuleType (u_module_type_expr env i.parent t)
in
let items, env' =
let { Include.content; _ } = i.expansion in
signature_items env content.items
in
( {
i with
expansion =
{ i.expansion with content = { i.expansion.content with items } };
decl;
},
env' )
let signature env =
let rec loop sg =
again := false;
let sg' = signature env sg in
Tools.reset_caches ();
if !again then if sg' = sg then sg else loop sg' else sg'
in
loop
|
8c929296133777a5b0f777b47f33aac31fc4c392df45ea13383f5d4bd1d0a4d3 | helvm/helma | Symbol.hs | module HelVM.HelMA.Automata.SubLeq.Symbol where
type Symbol = Int
type SymbolList = [Symbol]
| null | https://raw.githubusercontent.com/helvm/helma/cf220d7db1441780ba7fcc4f29cf1eec7b6f1e73/hs/src/HelVM/HelMA/Automata/SubLeq/Symbol.hs | haskell | module HelVM.HelMA.Automata.SubLeq.Symbol where
type Symbol = Int
type SymbolList = [Symbol]
|
|
8b082306bcf5d8d95b810120cb89a07e66cee0a0a3ea69b82b20a3140696e1c6 | manutter51/woolybear | icons.cljs | (ns woolybear.ad.catalog.icons
"Catalog and demonstrations of available icon components."
(:require [woolybear.ad.catalog.utils :as acu]
[woolybear.ad.layout :as layout]
[woolybear.ad.containers :as containers]
[woolybear.ad.icons :as icons]
[woolybear.ad.images :as images]))
(defn catalog
[]
[:div
(acu/demo "Simple Image"
"See / for handy Bulma classes you
can apply to images to set the placeholder size."
[layout/padded
[images/image {:src "/img/logo.png"
:extra-classes #{:is-4by1 :adc-width-20}}]]
'[layout/padded
[images/image {:src "/img/logo.png"
:extra-classes #{:is-4by1 :adc-width-20}}]])
(acu/demo "Standard Icons"
"Simple, FontAwesome-based icons."
[containers/bar
[icons/icon {:icon "check"}]
[icons/icon {:icon "edit"}]
[icons/icon {:icon "save"}]
[icons/icon {:icon "share"}]]
'[containers/bar
[icons/icon {:icon "check"}]
[icons/icon {:icon "edit"}]
[icons/icon {:icon "save"}]
[icons/icon {:icon "share"}]])
(acu/demo "Colored Icons"
"FontAwesome icons are treated as text by the browser, so you can use
Bulma text classes like has-text-success to color your icons."
[containers/bar
[icons/icon {:icon "check" :extra-classes :has-text-success}]
[icons/icon {:icon "edit" :extra-classes :has-text-danger}]
[icons/icon {:icon "save" :extra-classes :has-text-info}]
[icons/icon {:icon "share" :extra-classes :has-text-primary}]]
'[containers/bar
[icons/icon {:icon "check" :extra-classes :has-text-success}]
[icons/icon {:icon "edit" :extra-classes :has-text-danger}]
[icons/icon {:icon "save" :extra-classes :has-text-info}]
[icons/icon {:icon "share" :extra-classes :has-text-primary}]])
(acu/demo "Small Icons"
[containers/bar
[icons/icon {:icon "check" :size :small}]
[icons/icon {:icon "edit" :size :small}]
[icons/icon {:icon "save" :size :small}]
[icons/icon {:icon "share" :size :small}]]
'[containers/bar
[icons/icon {:icon "check" :size :small}]
[icons/icon {:icon "edit" :size :small}]
[icons/icon {:icon "save" :size :small}]
[icons/icon {:icon "share" :size :small}]])
(acu/demo "Medium Icons"
[containers/bar
[icons/icon {:icon "music" :size :medium}]
[icons/icon {:icon "globe-americas" :size :medium}]
[icons/icon {:icon "microphone" :size :medium}]
[icons/icon {:icon "ellipsis-h" :size :medium}]]
'[containers/bar
[icons/icon {:icon "music" :size :medium}]
[icons/icon {:icon "globe-americas" :size :medium}]
[icons/icon {:icon "microphone" :size :medium}]
[icons/icon {:icon "ellipsis-h" :size :medium}]])
(acu/demo "Large Icons"
[containers/bar
[icons/icon {:icon "backward" :size :large}]
[icons/icon {:icon "stop" :size :large}]
[icons/icon {:icon "play" :size :large}]
[icons/icon {:icon "forward" :size :large}]]
'[containers/bar
[icons/icon {:icon "backward" :size :large}]
[icons/icon {:icon "stop" :size :large}]
[icons/icon {:icon "play" :size :large}]
[icons/icon {:icon "forward" :size :large}]])
(acu/demo "Brand Icons"
"Brand icons from the (free) FontAwesome collection."
[containers/bar
[icons/icon {:icon "google" :brand? true}]
[icons/icon {:icon "jenkins" :brand? true}]
[icons/icon {:icon "facebook" :brand? true}]
[icons/icon {:icon "amazon" :brand? true}]
]
'[containers/bar
[icons/icon {:icon "google" :brand? true}]
[icons/icon {:icon "jenkins" :brand? true}]
[icons/icon {:icon "facebook" :brand? true}]
[icons/icon {:icon "amazon" :brand? true}]
])
(acu/demo "Clickable Icons"
"Watch the JS console for messages when clicking icons."
[containers/bar
[icons/icon {:icon "comment"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :comment-icon]))}]
[icons/icon {:icon "gamepad"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :gamepad-icon]))}]
[icons/icon {:icon "frog"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :frog-icon]))}]
[icons/icon {:icon "helicopter"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :helicopter-icon]))}]
]
'[containers/bar
[icons/icon {:icon "comment"
:on-click [:icon-demo/clicked :comment-icon]}]
[icons/icon {:icon "gamepad"
:on-click [:icon-demo/clicked :gamepad-icon]}]
[icons/icon {:icon "frog"
:on-click [:icon-demo/clicked :frog-icon]}]
[icons/icon {:icon "helicopter"
:on-click [:icon-demo/clicked :helicopter-icon]}]
])
])
| null | https://raw.githubusercontent.com/manutter51/woolybear/a7f820dfb2f51636122d56d1500baefe5733eb25/src/cljs/woolybear/ad/catalog/icons.cljs | clojure | (ns woolybear.ad.catalog.icons
"Catalog and demonstrations of available icon components."
(:require [woolybear.ad.catalog.utils :as acu]
[woolybear.ad.layout :as layout]
[woolybear.ad.containers :as containers]
[woolybear.ad.icons :as icons]
[woolybear.ad.images :as images]))
(defn catalog
[]
[:div
(acu/demo "Simple Image"
"See / for handy Bulma classes you
can apply to images to set the placeholder size."
[layout/padded
[images/image {:src "/img/logo.png"
:extra-classes #{:is-4by1 :adc-width-20}}]]
'[layout/padded
[images/image {:src "/img/logo.png"
:extra-classes #{:is-4by1 :adc-width-20}}]])
(acu/demo "Standard Icons"
"Simple, FontAwesome-based icons."
[containers/bar
[icons/icon {:icon "check"}]
[icons/icon {:icon "edit"}]
[icons/icon {:icon "save"}]
[icons/icon {:icon "share"}]]
'[containers/bar
[icons/icon {:icon "check"}]
[icons/icon {:icon "edit"}]
[icons/icon {:icon "save"}]
[icons/icon {:icon "share"}]])
(acu/demo "Colored Icons"
"FontAwesome icons are treated as text by the browser, so you can use
Bulma text classes like has-text-success to color your icons."
[containers/bar
[icons/icon {:icon "check" :extra-classes :has-text-success}]
[icons/icon {:icon "edit" :extra-classes :has-text-danger}]
[icons/icon {:icon "save" :extra-classes :has-text-info}]
[icons/icon {:icon "share" :extra-classes :has-text-primary}]]
'[containers/bar
[icons/icon {:icon "check" :extra-classes :has-text-success}]
[icons/icon {:icon "edit" :extra-classes :has-text-danger}]
[icons/icon {:icon "save" :extra-classes :has-text-info}]
[icons/icon {:icon "share" :extra-classes :has-text-primary}]])
(acu/demo "Small Icons"
[containers/bar
[icons/icon {:icon "check" :size :small}]
[icons/icon {:icon "edit" :size :small}]
[icons/icon {:icon "save" :size :small}]
[icons/icon {:icon "share" :size :small}]]
'[containers/bar
[icons/icon {:icon "check" :size :small}]
[icons/icon {:icon "edit" :size :small}]
[icons/icon {:icon "save" :size :small}]
[icons/icon {:icon "share" :size :small}]])
(acu/demo "Medium Icons"
[containers/bar
[icons/icon {:icon "music" :size :medium}]
[icons/icon {:icon "globe-americas" :size :medium}]
[icons/icon {:icon "microphone" :size :medium}]
[icons/icon {:icon "ellipsis-h" :size :medium}]]
'[containers/bar
[icons/icon {:icon "music" :size :medium}]
[icons/icon {:icon "globe-americas" :size :medium}]
[icons/icon {:icon "microphone" :size :medium}]
[icons/icon {:icon "ellipsis-h" :size :medium}]])
(acu/demo "Large Icons"
[containers/bar
[icons/icon {:icon "backward" :size :large}]
[icons/icon {:icon "stop" :size :large}]
[icons/icon {:icon "play" :size :large}]
[icons/icon {:icon "forward" :size :large}]]
'[containers/bar
[icons/icon {:icon "backward" :size :large}]
[icons/icon {:icon "stop" :size :large}]
[icons/icon {:icon "play" :size :large}]
[icons/icon {:icon "forward" :size :large}]])
(acu/demo "Brand Icons"
"Brand icons from the (free) FontAwesome collection."
[containers/bar
[icons/icon {:icon "google" :brand? true}]
[icons/icon {:icon "jenkins" :brand? true}]
[icons/icon {:icon "facebook" :brand? true}]
[icons/icon {:icon "amazon" :brand? true}]
]
'[containers/bar
[icons/icon {:icon "google" :brand? true}]
[icons/icon {:icon "jenkins" :brand? true}]
[icons/icon {:icon "facebook" :brand? true}]
[icons/icon {:icon "amazon" :brand? true}]
])
(acu/demo "Clickable Icons"
"Watch the JS console for messages when clicking icons."
[containers/bar
[icons/icon {:icon "comment"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :comment-icon]))}]
[icons/icon {:icon "gamepad"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :gamepad-icon]))}]
[icons/icon {:icon "frog"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :frog-icon]))}]
[icons/icon {:icon "helicopter"
:on-click (fn [_] (js/console.log "Dispatched %o.", [:icon-demo/clicked :helicopter-icon]))}]
]
'[containers/bar
[icons/icon {:icon "comment"
:on-click [:icon-demo/clicked :comment-icon]}]
[icons/icon {:icon "gamepad"
:on-click [:icon-demo/clicked :gamepad-icon]}]
[icons/icon {:icon "frog"
:on-click [:icon-demo/clicked :frog-icon]}]
[icons/icon {:icon "helicopter"
:on-click [:icon-demo/clicked :helicopter-icon]}]
])
])
|
|
185a73d6241c0358de269709232459238505bc89cabfbfab11c93a67a6843f91 | v-kolesnikov/sicp | 2_35.clj | (ns sicp.chapter02.2-35)
(defn count-leaves
[tree]
(let [f #(if (list? %)
(count-leaves %)
1)]
(->> tree
(map f)
(reduce + 0))))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/src/sicp/chapter02/2_35.clj | clojure | (ns sicp.chapter02.2-35)
(defn count-leaves
[tree]
(let [f #(if (list? %)
(count-leaves %)
1)]
(->> tree
(map f)
(reduce + 0))))
|
|
66a151765e5d6862a7cf1c9da6fdb21b0b63b2baa939c4f302a798d9babd24d2 | zack-bitcoin/verkle | verkle_app.erl | -module(verkle_app).
-behaviour(application).
-include("constants.hrl").
%% Application callbacks
-export([start/2, stop/1]).
start(_StartType , _ ) - >
start(normal, []) ->
Size = 2,
,
ID = tree01,
KeyLength = 5,%in bytes
KeyLength = ?nwidth div ?nindex,%in bytes
Amount = 1000000,
%Mode = ram,
Mode = hd,
Meta = 1,
verkle_sup:start_link(KeyLength, Size, ID, Amount, Meta, Mode, "").
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/zack-bitcoin/verkle/cdcae51abb9a9cb7db3fda4afcef49e2673fe15d/src/verkle_app.erl | erlang | Application callbacks
in bytes
in bytes
Mode = ram, | -module(verkle_app).
-behaviour(application).
-include("constants.hrl").
-export([start/2, stop/1]).
start(_StartType , _ ) - >
start(normal, []) ->
Size = 2,
,
ID = tree01,
Amount = 1000000,
Mode = hd,
Meta = 1,
verkle_sup:start_link(KeyLength, Size, ID, Amount, Meta, Mode, "").
stop(_State) ->
ok.
|
7972b3645e09b6ac2735392a302cdcbfa6fd25a7327860c9c2c5ecaae795179d | quek/paiprolog | unify.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*-
;;; Code from Paradigms of Artificial Intelligence Programming
Copyright ( c ) 1991
;;;; File unify.lisp: Unification functions
(in-package "PAIPROLOG")
(defparameter *occurs-check* t "Should we do the occurs check?")
(defun unify (x y &optional (bindings no-bindings))
"See if x and y match with given bindings."
(cond ((eq bindings fail) fail)
((eql x y) bindings)
((variable-p x) (unify-variable x y bindings))
((variable-p y) (unify-variable y x bindings))
((and (consp x) (consp y))
(unify (rest x) (rest y)
(unify (first x) (first y) bindings)))
(t fail)))
(defun unify-variable (var x bindings)
"Unify var with x, using (and maybe extending) bindings."
(cond ((get-binding var bindings)
(unify (lookup var bindings) x bindings))
((and (variable-p x) (get-binding x bindings))
(unify var (lookup x bindings) bindings))
((and *occurs-check* (occurs-check var x bindings))
fail)
(t (extend-bindings var x bindings))))
(defun occurs-check (var x bindings)
"Does var occur anywhere inside x?"
(cond ((eq var x) t)
((and (variable-p x) (get-binding x bindings))
(occurs-check var (lookup x bindings) bindings))
((consp x) (or (occurs-check var (first x) bindings)
(occurs-check var (rest x) bindings)))
(t nil)))
;;; ==============================
(defun subst-bindings (bindings x)
"Substitute the value of variables in bindings into x,
taking recursively bound variables into account."
(cond ((eq bindings fail) fail)
((eq bindings no-bindings) x)
((and (variable-p x) (get-binding x bindings))
(subst-bindings bindings (lookup x bindings)))
((atom x) x)
(t (reuse-cons (subst-bindings bindings (car x))
(subst-bindings bindings (cdr x))
x))))
;;; ==============================
(defun unifier (x y)
"Return something that unifies with both x and y (or fail)."
(subst-bindings (unify x y) x))
| null | https://raw.githubusercontent.com/quek/paiprolog/012d6bb255d8af7f1c8b1d061dcd8a474fb3b57a/unify.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; -*-
Code from Paradigms of Artificial Intelligence Programming
File unify.lisp: Unification functions
==============================
============================== | Copyright ( c ) 1991
(in-package "PAIPROLOG")
(defparameter *occurs-check* t "Should we do the occurs check?")
(defun unify (x y &optional (bindings no-bindings))
"See if x and y match with given bindings."
(cond ((eq bindings fail) fail)
((eql x y) bindings)
((variable-p x) (unify-variable x y bindings))
((variable-p y) (unify-variable y x bindings))
((and (consp x) (consp y))
(unify (rest x) (rest y)
(unify (first x) (first y) bindings)))
(t fail)))
(defun unify-variable (var x bindings)
"Unify var with x, using (and maybe extending) bindings."
(cond ((get-binding var bindings)
(unify (lookup var bindings) x bindings))
((and (variable-p x) (get-binding x bindings))
(unify var (lookup x bindings) bindings))
((and *occurs-check* (occurs-check var x bindings))
fail)
(t (extend-bindings var x bindings))))
(defun occurs-check (var x bindings)
"Does var occur anywhere inside x?"
(cond ((eq var x) t)
((and (variable-p x) (get-binding x bindings))
(occurs-check var (lookup x bindings) bindings))
((consp x) (or (occurs-check var (first x) bindings)
(occurs-check var (rest x) bindings)))
(t nil)))
(defun subst-bindings (bindings x)
"Substitute the value of variables in bindings into x,
taking recursively bound variables into account."
(cond ((eq bindings fail) fail)
((eq bindings no-bindings) x)
((and (variable-p x) (get-binding x bindings))
(subst-bindings bindings (lookup x bindings)))
((atom x) x)
(t (reuse-cons (subst-bindings bindings (car x))
(subst-bindings bindings (cdr x))
x))))
(defun unifier (x y)
"Return something that unifies with both x and y (or fail)."
(subst-bindings (unify x y) x))
|
a5611e4b0b3609a3b5122d2d180878991020e0f4a25c2b3d4076605184747e3c | cenary-lang/cenary | StackTL.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RebindableSyntax #
# LANGUAGE TupleSections #
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Cenary.EvmAPI.StackTL where
import Control.Monad.Indexed
import GHC.TypeLits
import Prelude hiding ((>>))
data StackElem = Jumpdest
data Stack (name :: Symbol) (elems :: [StackElem]) = Stack
type family Push (elem :: *) (s :: *) :: * where
e `Push` (Stack name xs) = Stack name ((TyToElem e) ': xs)
type family Pop s :: (StackElem, *) where
Pop (Stack name (x ': xs)) = '(x, Stack name xs)
Pop (Stack name '[]) =
TypeError
( 'Text "You cannot pop from an empty stack!"
':$$: 'Text "While trying to pop from the stack named " ':<>: 'ShowType name
)
push :: (newStack ~ Push ty givenStack) => givenStack -> ty -> m newStack
push _ _ = undefined
type family ElemToTy (s :: StackElem) :: * where
ElemToTy 'Jumpdest = Int
type family TyToElem (s :: *) :: StackElem where
TyToElem Int = 'Jumpdest
pop :: (Monad m, '(elem, newStack) ~ Pop givenStack) => givenStack -> m (ElemToTy elem, newStack)
pop = undefined
type EmptyStack = Stack "MyStack" '[]
newtype IxState is os a = IxState { runIState :: is -> (os, a) }
instance IxFunctor IxState where
imap f (IxState stateF) = IxState $ \is ->
let (os, a) = stateF is
in (os, f a)
instance IxPointed IxState where
ireturn v = IxState (, v)
instance IxApplicative IxState where
iap (IxState stateFf) (IxState stateF) = IxState $ \is ->
let (os, f) = stateFf is
(os2, a) = stateF os
in (os2, f a)
instance IxMonad IxState where
ibind f (IxState ija) = IxState $ \i ->
let (j, a) = ija i
IxState jkb = f a
in jkb j
toBC :: StackElem -> String
toBC Jumpdest = "0x02"
ixpush :: x -> IxState (MyState stack) (MyState (x `Push` stack)) ()
ixpush _ = IxState $ \(MyState bc) -> (MyState bc, ())
ixpop :: ('(elem, newStack) ~ Pop stack) => IxState (MyState stack) (MyState newStack) ()
ixpop = IxState $ \(MyState bc) -> (MyState bc, ())
ixop :: Show x => x -> IxState (MyState stack) (MyState stack) ()
ixop x = IxState $ \(MyState bc) -> (MyState (bc ++ show x), ())
type family Shrink (vals :: [a]) (n :: Nat) :: [a] where
Shrink xs 0 = xs
Shrink (x ': xs) v = Shrink xs (v - 1)
type family Extend (val :: a) (vals :: [a]) (n :: Nat) :: [a] where
Extend _ xs 0 = xs
Extend x xs n = Extend x (x ': xs) (n - 1)
type StackModify pop push a = forall name x xs. IxState (MyState (Stack name (Extend x xs pop))) (MyState (Stack name (Extend x xs push))) a
newAdd :: StackModify 2 1 ()
newAdd = undefined
ixadd :: IxState (MyState (Stack name (x ': y ': xs))) (MyState (Stack name (k ': xs))) ()
ixadd = undefined
(>>>>) :: IxState i o a -> IxState o j b -> IxState i j b
a >>>> b = a >>>= \_ -> b
infixl 3 >>>>
data MyState stack = MyState
{ _bytecode :: String
}
comp :: IxState (MyState EmptyStack) (MyState EmptyStack) ()
comp = do
ixpush (5 :: Integer)
ixpush (3 :: Integer)
Arbitrary runtime computation inside
newAdd
ixpop
where (>>) = (>>>>)
-- wow :: IO ()
-- wow = do
< - push ( undefined : : EmptyStack ) ( 3 : : Int )
< - push stack1 ( 4 : : Int )
( _ , ) < - pop ( stack2 )
( _ , stack4 ) < - pop stack3
-- pure ()
| null | https://raw.githubusercontent.com/cenary-lang/cenary/bf5ab4ac6bbc2353b072d32de2f3bc86cbc88266/src/Cenary/EvmAPI/StackTL.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE PolyKinds #
# LANGUAGE RankNTypes #
# LANGUAGE TypeFamilies #
wow :: IO ()
wow = do
pure () | # LANGUAGE RebindableSyntax #
# LANGUAGE TupleSections #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Cenary.EvmAPI.StackTL where
import Control.Monad.Indexed
import GHC.TypeLits
import Prelude hiding ((>>))
data StackElem = Jumpdest
data Stack (name :: Symbol) (elems :: [StackElem]) = Stack
type family Push (elem :: *) (s :: *) :: * where
e `Push` (Stack name xs) = Stack name ((TyToElem e) ': xs)
type family Pop s :: (StackElem, *) where
Pop (Stack name (x ': xs)) = '(x, Stack name xs)
Pop (Stack name '[]) =
TypeError
( 'Text "You cannot pop from an empty stack!"
':$$: 'Text "While trying to pop from the stack named " ':<>: 'ShowType name
)
push :: (newStack ~ Push ty givenStack) => givenStack -> ty -> m newStack
push _ _ = undefined
type family ElemToTy (s :: StackElem) :: * where
ElemToTy 'Jumpdest = Int
type family TyToElem (s :: *) :: StackElem where
TyToElem Int = 'Jumpdest
pop :: (Monad m, '(elem, newStack) ~ Pop givenStack) => givenStack -> m (ElemToTy elem, newStack)
pop = undefined
type EmptyStack = Stack "MyStack" '[]
newtype IxState is os a = IxState { runIState :: is -> (os, a) }
instance IxFunctor IxState where
imap f (IxState stateF) = IxState $ \is ->
let (os, a) = stateF is
in (os, f a)
instance IxPointed IxState where
ireturn v = IxState (, v)
instance IxApplicative IxState where
iap (IxState stateFf) (IxState stateF) = IxState $ \is ->
let (os, f) = stateFf is
(os2, a) = stateF os
in (os2, f a)
instance IxMonad IxState where
ibind f (IxState ija) = IxState $ \i ->
let (j, a) = ija i
IxState jkb = f a
in jkb j
toBC :: StackElem -> String
toBC Jumpdest = "0x02"
ixpush :: x -> IxState (MyState stack) (MyState (x `Push` stack)) ()
ixpush _ = IxState $ \(MyState bc) -> (MyState bc, ())
ixpop :: ('(elem, newStack) ~ Pop stack) => IxState (MyState stack) (MyState newStack) ()
ixpop = IxState $ \(MyState bc) -> (MyState bc, ())
ixop :: Show x => x -> IxState (MyState stack) (MyState stack) ()
ixop x = IxState $ \(MyState bc) -> (MyState (bc ++ show x), ())
type family Shrink (vals :: [a]) (n :: Nat) :: [a] where
Shrink xs 0 = xs
Shrink (x ': xs) v = Shrink xs (v - 1)
type family Extend (val :: a) (vals :: [a]) (n :: Nat) :: [a] where
Extend _ xs 0 = xs
Extend x xs n = Extend x (x ': xs) (n - 1)
type StackModify pop push a = forall name x xs. IxState (MyState (Stack name (Extend x xs pop))) (MyState (Stack name (Extend x xs push))) a
newAdd :: StackModify 2 1 ()
newAdd = undefined
ixadd :: IxState (MyState (Stack name (x ': y ': xs))) (MyState (Stack name (k ': xs))) ()
ixadd = undefined
(>>>>) :: IxState i o a -> IxState o j b -> IxState i j b
a >>>> b = a >>>= \_ -> b
infixl 3 >>>>
data MyState stack = MyState
{ _bytecode :: String
}
comp :: IxState (MyState EmptyStack) (MyState EmptyStack) ()
comp = do
ixpush (5 :: Integer)
ixpush (3 :: Integer)
Arbitrary runtime computation inside
newAdd
ixpop
where (>>) = (>>>>)
< - push ( undefined : : EmptyStack ) ( 3 : : Int )
< - push stack1 ( 4 : : Int )
( _ , ) < - pop ( stack2 )
( _ , stack4 ) < - pop stack3
|
089e3a7af0eb238e0bdfe0a7383fb5b1a8750de56e77bc7193344d36f06db36e | PacktPublishing/Haskell-High-Performance-Programming | tuples.hs | -- file: tuples.hs
import Data.Array.Accelerate as A
import Data.Array.Accelerate.CUDA
f1 :: (Exp Int, Exp Int) -> Acc (Scalar Int)
f1 (x, y) = unit (x + y)
f2 :: Exp (Int, Int) -> Acc (Scalar Int)
f2 e = let (x, y) = unlift e :: (Exp Int, Exp Int)
in unit (x + y)
main = let
xs = [run $ f1 (x, y) | x <- [1..10], y <- [1..10]]
ys = [run $ f2 $ lift ((x, y) :: (Int, Int)) | x <- [1..10], y <- [1..10]]
in print xs
| null | https://raw.githubusercontent.com/PacktPublishing/Haskell-High-Performance-Programming/2b1bfdb8102129be41e8d79c7e9caf12100c5556/Chapter11/tuples.hs | haskell | file: tuples.hs |
import Data.Array.Accelerate as A
import Data.Array.Accelerate.CUDA
f1 :: (Exp Int, Exp Int) -> Acc (Scalar Int)
f1 (x, y) = unit (x + y)
f2 :: Exp (Int, Int) -> Acc (Scalar Int)
f2 e = let (x, y) = unlift e :: (Exp Int, Exp Int)
in unit (x + y)
main = let
xs = [run $ f1 (x, y) | x <- [1..10], y <- [1..10]]
ys = [run $ f2 $ lift ((x, y) :: (Int, Int)) | x <- [1..10], y <- [1..10]]
in print xs
|
21578bac1546e1ae29934cc0aaf611a6e3008308920ed3c5c2a6975edcc6c7d8 | jimcrayne/jhc | Show.hs | # OPTIONS_JHC -fno - prelude #
module Jhc.Show where
import Jhc.Int
import Jhc.Basics
type ShowS = String -> String
class Show a where
showsPrec :: Int -> a -> ShowS
show :: a -> String
showList :: [a] -> ShowS
complete definition :
-- show or showsPrec
showsPrec _ x s = show x ++ s
show x = showsPrec zero x ""
showList [] = showString "[]"
showList (x:xs) = showChar '[' . shows x . showl xs
where showl [] = showChar ']'
showl (x:xs) = showChar ',' . shows x .
showl xs
shows :: (Show a) => a -> ShowS
shows = showsPrec zero
{-# INLINE showChar, showString #-}
showChar :: Char -> ShowS
showChar = (:)
showString :: String -> ShowS
showString = (++)
showParen :: Bool -> ShowS -> ShowS
showParen b p = if b then showChar '(' . p . showChar ')' else p
instance Show () where
showsPrec _ () = showString "()"
instance (Show a, Show b) => Show (a,b) where
showsPrec _ (x,y) = showChar '(' . shows x . showChar ',' .
shows y . showChar ')'
instance (Show a, Show b, Show c) => Show (a, b, c) where
showsPrec _ (x,y,z) = showChar '(' . shows x . showChar ',' .
shows y . showChar ',' .
shows z . showChar ')'
instance Show a => Show [a] where
showsPrec p = showList
instance Show Bool where
showsPrec d (False) = showString "False"
showsPrec d (True) = showString "True"
instance Show Ordering where
showsPrec d (LT) = showString "LT"
showsPrec d (EQ) = showString "EQ"
showsPrec d (GT) = showString "GT"
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/lib/jhc/Jhc/Show.hs | haskell | show or showsPrec
# INLINE showChar, showString # | # OPTIONS_JHC -fno - prelude #
module Jhc.Show where
import Jhc.Int
import Jhc.Basics
type ShowS = String -> String
class Show a where
showsPrec :: Int -> a -> ShowS
show :: a -> String
showList :: [a] -> ShowS
complete definition :
showsPrec _ x s = show x ++ s
show x = showsPrec zero x ""
showList [] = showString "[]"
showList (x:xs) = showChar '[' . shows x . showl xs
where showl [] = showChar ']'
showl (x:xs) = showChar ',' . shows x .
showl xs
shows :: (Show a) => a -> ShowS
shows = showsPrec zero
showChar :: Char -> ShowS
showChar = (:)
showString :: String -> ShowS
showString = (++)
showParen :: Bool -> ShowS -> ShowS
showParen b p = if b then showChar '(' . p . showChar ')' else p
instance Show () where
showsPrec _ () = showString "()"
instance (Show a, Show b) => Show (a,b) where
showsPrec _ (x,y) = showChar '(' . shows x . showChar ',' .
shows y . showChar ')'
instance (Show a, Show b, Show c) => Show (a, b, c) where
showsPrec _ (x,y,z) = showChar '(' . shows x . showChar ',' .
shows y . showChar ',' .
shows z . showChar ')'
instance Show a => Show [a] where
showsPrec p = showList
instance Show Bool where
showsPrec d (False) = showString "False"
showsPrec d (True) = showString "True"
instance Show Ordering where
showsPrec d (LT) = showString "LT"
showsPrec d (EQ) = showString "EQ"
showsPrec d (GT) = showString "GT"
|
63be6a6231f914d9761fac84a7c4622e6a1d421731b71542ae5f5431d1093f82 | robert-strandh/Cluster | neg.lisp | (cl:in-package #:cluster)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Mnemonic NEG
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Negate a 32 - bit GPR or memory location .
Negate a 32 - bit GPR .
(define-instruction "NEG"
:modes (32 64)
:operands ((gpr 32))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm))
Negate a 32 - bit memory location
(define-instruction "NEG"
:modes (32 )
:operands ((memory 32))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:lock t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Negate a 64 - bit GPR or memory location .
Negate a 64 - bit GPR .
(define-instruction "NEG"
:modes (64)
:operands ((gpr 64))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:rex.w t)
Negate a 64 - bit memory location
(define-instruction "NEG"
:modes (64)
:operands ((memory 64))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:lock t
:rex.w t)
| null | https://raw.githubusercontent.com/robert-strandh/Cluster/370410b1c685f2afd77f959a46ba49923a31a33c/x86-instruction-database/neg.lisp | lisp |
Mnemonic NEG
| (cl:in-package #:cluster)
Negate a 32 - bit GPR or memory location .
Negate a 32 - bit GPR .
(define-instruction "NEG"
:modes (32 64)
:operands ((gpr 32))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm))
Negate a 32 - bit memory location
(define-instruction "NEG"
:modes (32 )
:operands ((memory 32))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:lock t)
Negate a 64 - bit GPR or memory location .
Negate a 64 - bit GPR .
(define-instruction "NEG"
:modes (64)
:operands ((gpr 64))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:rex.w t)
Negate a 64 - bit memory location
(define-instruction "NEG"
:modes (64)
:operands ((memory 64))
:opcodes (#xF7)
:opcode-extension 3
:encoding (modrm)
:lock t
:rex.w t)
|
2b2735f4f035f68675ac00cf00b5c22bc259520e487efa6e15ed8604c5e2e6b3 | helins/binf.cljc | leb128.cljc | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns helins.binf.test.leb128
"Testing LEB128 utilities."
{:author "Adam Helins"}
(:require [clojure.test :as T]
[clojure.test.check.properties :as TC.prop]
[helins.binf :as binf]
[helins.binf.buffer :as binf.buffer]
[helins.binf.gen :as binf.gen]
[helins.binf.int64 :as binf.int64]
[helins.binf.leb128 :as binf.leb128]
[helins.mprop :as mprop]))
;;;;;;;;;; int32
(T/deftest u32
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-u32 0))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-u32 0)))
(T/is (= 0
(-> v
(binf/seek 0)
(binf.leb128/rr-u32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-u32 4294967295))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-u32 4294967295)))
(T/is (= 4294967295
(-> v
(binf/seek 0)
(binf.leb128/rr-u32))))))
(T/deftest i32
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 0))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= 0
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 2147483647))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-i32 2147483647)))
(T/is (= 2147483647
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 -2147483648))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-i32 -2147483648)))
(T/is (= -2147483648
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 -42))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= -42
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf/wr-b8 0x7F))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= -1
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))))
int64
(T/deftest u64
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-u64 (binf.int64/u* 0)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-u64 (binf.int64/u* 0))))
(T/is (= (binf.int64/u* 0)
(-> v
(binf/seek 0)
(binf.leb128/rr-u64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-u64 (binf.int64/u* 18446744073709551615)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-u64 (binf.int64/u* 18446744073709551615))))
(T/is (= (binf.int64/u* 18446744073709551615)
(-> v
(binf/seek 0)
(binf.leb128/rr-u64))))))
(T/deftest i64
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* 0)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* 0))))
(T/is (= (binf.int64/i* 0)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* 9223372036854775807)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* 9223372036854775807))))
(T/is (= (binf.int64/i* 9223372036854775807)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* -9223372036854775808)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -9223372036854775808))))
(T/is (= (binf.int64/i* -9223372036854775808)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* -42)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -42))))
(T/is (= (binf.int64/i* -42)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf/wr-b8 0x7F))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -1))))
(T/is (= (binf.int64/i* -1)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))))
;;;;;;;;;; Generative testing
(def view-gen
(-> (binf.leb128/n-byte-max 64)
binf.buffer/alloc
binf/view))
(mprop/deftest gen-i32
{:ratio-num 200}
(TC.prop/for-all [i32 binf.gen/i32]
(= i32
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-i32 i32)
(binf/seek 0)
binf.leb128/rr-i32))))
(mprop/deftest gen-u32
{:ratio-num 200}
(TC.prop/for-all [u32 binf.gen/u32]
(= u32
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-u32 u32)
(binf/seek 0)
binf.leb128/rr-u32))))
(mprop/deftest gen-i64
{:ratio-num 200}
(TC.prop/for-all [i64 binf.gen/i64]
(= i64
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-i64 i64)
(binf/seek 0)
binf.leb128/rr-i64))))
(mprop/deftest gen-u64
{:ratio-num 200}
(TC.prop/for-all [u64 binf.gen/u64]
(= u64
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-u64 u64)
(binf/seek 0)
binf.leb128/rr-u64))))
| null | https://raw.githubusercontent.com/helins/binf.cljc/202abed33c3ebc3a323253f4f4c731595e21366e/src/test/helins/binf/test/leb128.cljc | clojure | int32
Generative testing | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns helins.binf.test.leb128
"Testing LEB128 utilities."
{:author "Adam Helins"}
(:require [clojure.test :as T]
[clojure.test.check.properties :as TC.prop]
[helins.binf :as binf]
[helins.binf.buffer :as binf.buffer]
[helins.binf.gen :as binf.gen]
[helins.binf.int64 :as binf.int64]
[helins.binf.leb128 :as binf.leb128]
[helins.mprop :as mprop]))
(T/deftest u32
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-u32 0))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-u32 0)))
(T/is (= 0
(-> v
(binf/seek 0)
(binf.leb128/rr-u32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-u32 4294967295))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-u32 4294967295)))
(T/is (= 4294967295
(-> v
(binf/seek 0)
(binf.leb128/rr-u32))))))
(T/deftest i32
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 0))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= 0
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 2147483647))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-i32 2147483647)))
(T/is (= 2147483647
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 -2147483648))
(T/is (= (binf.leb128/n-byte-max 32)
(binf/position v)
(binf.leb128/n-byte-i32 -2147483648)))
(T/is (= -2147483648
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i32 -42))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= -42
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))
(-> v
(binf/seek 0)
(binf/wr-b8 0x7F))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i32 0)))
(T/is (= -1
(-> v
(binf/seek 0)
(binf.leb128/rr-i32))))))
int64
(T/deftest u64
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-u64 (binf.int64/u* 0)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-u64 (binf.int64/u* 0))))
(T/is (= (binf.int64/u* 0)
(-> v
(binf/seek 0)
(binf.leb128/rr-u64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-u64 (binf.int64/u* 18446744073709551615)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-u64 (binf.int64/u* 18446744073709551615))))
(T/is (= (binf.int64/u* 18446744073709551615)
(-> v
(binf/seek 0)
(binf.leb128/rr-u64))))))
(T/deftest i64
(let [v (binf/view (binf.buffer/alloc 32))]
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* 0)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* 0))))
(T/is (= (binf.int64/i* 0)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* 9223372036854775807)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* 9223372036854775807))))
(T/is (= (binf.int64/i* 9223372036854775807)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* -9223372036854775808)))
(T/is (= (binf.leb128/n-byte-max 64)
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -9223372036854775808))))
(T/is (= (binf.int64/i* -9223372036854775808)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf.leb128/wr-i64 (binf.int64/i* -42)))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -42))))
(T/is (= (binf.int64/i* -42)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))
(-> v
(binf/seek 0)
(binf/wr-b8 0x7F))
(T/is (= 1
(binf/position v)
(binf.leb128/n-byte-i64 (binf.int64/i* -1))))
(T/is (= (binf.int64/i* -1)
(-> v
(binf/seek 0)
(binf.leb128/rr-i64))))))
(def view-gen
(-> (binf.leb128/n-byte-max 64)
binf.buffer/alloc
binf/view))
(mprop/deftest gen-i32
{:ratio-num 200}
(TC.prop/for-all [i32 binf.gen/i32]
(= i32
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-i32 i32)
(binf/seek 0)
binf.leb128/rr-i32))))
(mprop/deftest gen-u32
{:ratio-num 200}
(TC.prop/for-all [u32 binf.gen/u32]
(= u32
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-u32 u32)
(binf/seek 0)
binf.leb128/rr-u32))))
(mprop/deftest gen-i64
{:ratio-num 200}
(TC.prop/for-all [i64 binf.gen/i64]
(= i64
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-i64 i64)
(binf/seek 0)
binf.leb128/rr-i64))))
(mprop/deftest gen-u64
{:ratio-num 200}
(TC.prop/for-all [u64 binf.gen/u64]
(= u64
(-> view-gen
(binf/seek 0)
(binf.leb128/wr-u64 u64)
(binf/seek 0)
binf.leb128/rr-u64))))
|
15579f3b66d56dcf304a0f85a2af3d03b30183f9bc86303c529ec284d77c13b8 | nutanix/papiea-clj | engine_test.clj | (ns papiea.engine-test
(:require [clojure.test :refer :all]
[papiea.engine :as c]))
(deftest merge-entities-status
(testing "merging the same data should make no difference"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]]
(is (= (into #{} old) (into #{} (c/merge-entities-status old old))))))
(testing "merging data where status has changed value should be reflected in the merge"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]]
(is (= (into #{} new) (into #{} (c/merge-entities-status old new)))))
)
(testing "merging data where status has added a new item should be reflected in the merge"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}
{:metadata {:uuid "44"}
:status {:name "new item"
:state "stopped"}}]]
(is (= (into #{} new) (into #{} (c/merge-entities-status old new)))))
)
(testing "merging data where status has removed an item. The resulting merge should have its status be nil"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}]]
(is (= #{{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status nil}} (into #{} (c/merge-entities-status old new)))))
)
)
| null | https://raw.githubusercontent.com/nutanix/papiea-clj/dd842703cf034d93b8651542892c7bd4ac204e29/test/papiea/engine_test.clj | clojure | (ns papiea.engine-test
(:require [clojure.test :refer :all]
[papiea.engine :as c]))
(deftest merge-entities-status
(testing "merging the same data should make no difference"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]]
(is (= (into #{} old) (into #{} (c/merge-entities-status old old))))))
(testing "merging data where status has changed value should be reflected in the merge"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]]
(is (= (into #{} new) (into #{} (c/merge-entities-status old new)))))
)
(testing "merging data where status has added a new item should be reflected in the merge"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}
{:metadata {:uuid "44"}
:status {:name "new item"
:state "stopped"}}]]
(is (= (into #{} new) (into #{} (c/merge-entities-status old new)))))
)
(testing "merging data where status has removed an item. The resulting merge should have its status be nil"
(let [old [{:metadata {:uuid "12"}
:status {:name "test1"
:state "started"}}
{:metadata {:uuid "15"}
:status {:name "another"
:state "started"}}]
new [{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}]]
(is (= #{{:metadata {:uuid "12"}
:status {:name "test1"
:state "CHANGED"}}
{:metadata {:uuid "15"}
:status nil}} (into #{} (c/merge-entities-status old new)))))
)
)
|
|
3c86052087a1cf5a9c5deea8ea8e9429c439c30c944dd961f7e03dde1da30601 | simmone/racket-simple-xlsx | sheet-lib.rkt | #lang racket
(require "../xlsx/xlsx.rkt")
(require "../sheet/sheet.rkt")
(require "dimension.rkt")
(provide (contract-out
[get-sheet-dimension (-> string?)]
[get-rows-count (-> natural?)]
[get-sheet-ref-rows-count (-> natural? natural?)]
[get-sheet-name-rows-count (-> string? natural?)]
[get-sheet-*name*-rows-count (-> string? natural?)]
[get-cols-count (-> natural?)]
[get-sheet-ref-cols-count (-> natural? natural?)]
[get-sheet-name-cols-count (-> string? natural?)]
[get-sheet-*name*-cols-count (-> string? natural?)]
[get-row-cells (-> natural? (listof string?))]
[get-sheet-ref-row-cells (-> natural? natural? (listof string?))]
[get-sheet-name-row-cells (-> string? natural? (listof string?))]
[get-sheet-*name*-row-cells (-> string? natural? (listof string?))]
[get-col-cells (-> (or/c natural? string?) (listof string?))]
[get-sheet-ref-col-cells (-> natural? (or/c natural? string?) (listof string?))]
[get-sheet-name-col-cells (-> string? (or/c natural? string?) (listof string?))]
[get-sheet-*name*-col-cells (-> string? (or/c natural? string?) (listof string?))]
[get-cell (-> string? cell-value?)]
[get-sheet-ref-cell (-> natural? string? cell-value?)]
[get-sheet-name-cell (-> string? string? cell-value?)]
[get-sheet-*name*-cell (-> string? string? cell-value?)]
[set-cell! (-> string? cell-value? void?)]
[set-sheet-ref-cell! (-> natural? string? cell-value? void?)]
[set-sheet-name-cell! (-> string? string? cell-value? void?)]
[set-sheet-*name*-cell! (-> string? string? cell-value? void?)]
[get-row (-> natural? (listof cell-value?))]
[get-sheet-ref-row (-> natural? natural? (listof cell-value?))]
[get-sheet-name-row (-> string? natural? (listof cell-value?))]
[get-sheet-*name*-row (-> string? natural? (listof cell-value?))]
[set-row! (-> natural? (listof cell-value?) void?)]
[set-sheet-ref-row! (-> natural? natural? (listof cell-value?) void?)]
[set-sheet-name-row! (-> string? natural? (listof cell-value?) void?)]
[set-sheet-*name*-row! (-> string? natural? (listof cell-value?) void?)]
[get-rows (-> (listof (listof cell-value?)))]
[get-sheet-ref-rows (-> natural? (listof (listof cell-value?)))]
[get-sheet-name-rows (-> string? (listof (listof cell-value?)))]
[get-sheet-*name*-rows (-> string? (listof (listof cell-value?)))]
[set-rows! (-> (listof (listof cell-value?)) void?)]
[set-sheet-ref-rows! (-> natural? (listof (listof cell-value?)) void?)]
[set-sheet-name-rows! (-> string? (listof (listof cell-value?)) void?)]
[set-sheet-*name*-rows! (-> string? (listof (listof cell-value?)) void?)]
[get-col (-> (or/c natural? string?) (listof cell-value?))]
[get-sheet-ref-col (-> natural? (or/c natural? string?) (listof cell-value?))]
[get-sheet-name-col (-> string? (or/c natural? string?) (listof cell-value?))]
[get-sheet-*name*-col (-> string? (or/c natural? string?) (listof cell-value?))]
[set-col! (-> (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-ref-col! (-> natural? (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-name-col! (-> string? (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-*name*-col! (-> string? (or/c natural? string?) (listof cell-value?) void?)]
[get-cols (-> (listof (listof cell-value?)))]
[get-sheet-ref-cols (-> natural? (listof (listof cell-value?)))]
[get-sheet-name-cols (-> string? (listof (listof cell-value?)))]
[get-sheet-*name*-cols (-> string? (listof (listof cell-value?)))]
[set-cols! (-> (listof (listof cell-value?)) void?)]
[set-sheet-ref-cols! (-> natural? (listof (listof cell-value?)) void?)]
[set-sheet-name-cols! (-> string? (listof (listof cell-value?)) void?)]
[set-sheet-*name*-cols! (-> string? (listof (listof cell-value?)) void?)]
[get-range-values (-> string? (listof cell-value?))]
[get-sheet-ref-range-values (-> natural? string? (listof cell-value?))]
[get-sheet-name-range-values (-> string? string? (listof cell-value?))]
[get-sheet-*name*-range-values (-> string? string? (listof cell-value?))]
[squash-shared-strings-map (-> void?)]
))
(define (get-sheet-dimension)
(DATA-SHEET-dimension (*CURRENT_SHEET*)))
(define (get-rows-count)
(car (range->capacity (DATA-SHEET-dimension (*CURRENT_SHEET*)))))
(define (get-sheet-ref-rows-count sheet_index) (with-sheet-ref sheet_index (lambda () (get-rows-count))))
(define (get-sheet-name-rows-count sheet_name) (with-sheet-name sheet_name (lambda () (get-rows-count))))
(define (get-sheet-*name*-rows-count search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-rows-count))))
(define (get-cols-count)
(cdr (range->capacity (DATA-SHEET-dimension (*CURRENT_SHEET*)))))
(define (get-sheet-ref-cols-count sheet_index) (with-sheet-ref sheet_index (lambda () (get-cols-count))))
(define (get-sheet-name-cols-count sheet_name) (with-sheet-name sheet_name (lambda () (get-cols-count))))
(define (get-sheet-*name*-cols-count search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-cols-count))))
(define (get-row-cells row_index)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index start_col]
[cells '()])
(if (<= loop_col_index end_col)
(loop
(add1 loop_col_index)
(cons
(row_col->cell row_index loop_col_index)
cells))
(reverse cells)))))
(define (get-sheet-ref-row-cells sheet_index row_index) (with-sheet-ref sheet_index (lambda () (get-row-cells row_index))))
(define (get-sheet-name-row-cells sheet_name row_index) (with-sheet-name sheet_name (lambda () (get-row-cells row_index))))
(define (get-sheet-*name*-row-cells search_sheet_name row_index) (with-sheet-*name* search_sheet_name (lambda () (get-row-cells row_index))))
(define (get-col-cells col)
(cond
[(string? col)
(get-col-number-cells (col_abc->number col))]
[(natural? col)
(get-col-number-cells col)]))
(define (get-col-number-cells col_index)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index start_row]
[cells '()])
(if (<= loop_row_index end_row)
(loop
(add1 loop_row_index)
(cons
(row_col->cell loop_row_index col_index)
cells))
(reverse cells)))))
(define (get-sheet-ref-col-cells sheet_index col_index) (with-sheet-ref sheet_index (lambda () (get-col-cells col_index))))
(define (get-sheet-name-col-cells sheet_name col_index) (with-sheet-name sheet_name (lambda () (get-col-cells col_index))))
(define (get-sheet-*name*-col-cells search_sheet_name col_index) (with-sheet-*name* search_sheet_name (lambda () (get-col-cells col_index))))
(define (get-cell cell)
(hash-ref (DATA-SHEET-cell->value_hash (*CURRENT_SHEET*)) cell ""))
(define (get-sheet-ref-cell sheet_index cell) (with-sheet-ref sheet_index (lambda () (get-cell cell))))
(define (get-sheet-name-cell sheet_name cell) (with-sheet-name sheet_name (lambda () (get-cell cell))))
(define (get-sheet-*name*-cell search_sheet_name cell) (with-sheet-*name* search_sheet_name (lambda () (get-cell cell))))
(define (set-cell! cell value)
(hash-set! (DATA-SHEET-cell->value_hash (*CURRENT_SHEET*)) cell value))
(define (set-sheet-ref-cell! sheet_index cell value) (with-sheet-ref sheet_index (lambda () (set-cell! cell value))))
(define (set-sheet-name-cell! sheet_name cell value) (with-sheet-name sheet_name (lambda () (set-cell! cell value))))
(define (set-sheet-*name*-cell! search_sheet_name cell value) (with-sheet-*name* search_sheet_name (lambda () (set-cell! cell value))))
(define (get-row row_index)
(map
(lambda (cell)
(get-cell cell))
(get-row-cells row_index)))
(define (get-sheet-ref-row sheet_index row_index) (with-sheet-ref sheet_index (lambda () (get-row row_index))))
(define (get-sheet-name-row sheet_name row_index) (with-sheet-name sheet_name (lambda () (get-row row_index))))
(define (get-sheet-*name*-row search_sheet_name row_index) (with-sheet-*name* search_sheet_name (lambda () (get-row row_index))))
(define (set-row! row_index cell_list)
(let loop ([cell_strs (get-row-cells row_index)]
[cell_values cell_list])
(when (not (null? cell_strs))
(set-cell! (car cell_strs) (if (null? cell_values) "" (car cell_values)))
(loop (cdr cell_strs) (cdr cell_values)))))
(define (set-sheet-ref-row! sheet_index row_index cell_list) (with-sheet-ref sheet_index (lambda () (set-row! row_index cell_list))))
(define (set-sheet-name-row! sheet_name row_index cell_list) (with-sheet-name sheet_name (lambda () (set-row! row_index cell_list))))
(define (set-sheet-*name*-row! search_sheet_name row_index cell_list) (with-sheet-*name* search_sheet_name (lambda () (set-row! row_index cell_list))))
(define (get-rows)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index start_row]
[rows '()])
(if (<= loop_row_index end_row)
(loop
(add1 loop_row_index)
(cons
(get-row loop_row_index)
rows))
(reverse rows)))))
(define (get-sheet-ref-rows sheet_index) (with-sheet-ref sheet_index (lambda () (get-rows))))
(define (get-sheet-name-rows sheet_name) (with-sheet-name sheet_name (lambda () (get-rows))))
(define (get-sheet-*name*-rows search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-rows))))
(define (set-rows! rows)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index 0]
[actual_loop_row_index start_row])
(when (<= actual_loop_row_index end_row)
(set-row! actual_loop_row_index (list-ref rows loop_row_index))
(loop (add1 loop_row_index) (add1 actual_loop_row_index))))))
(define (set-sheet-ref-rows! sheet_index rows) (with-sheet-ref sheet_index (lambda () (set-rows! rows))))
(define (set-sheet-name-rows! sheet_name rows) (with-sheet-name sheet_name (lambda () (set-rows! rows))))
(define (set-sheet-*name*-rows! search_sheet_name rows) (with-sheet-*name* search_sheet_name (lambda () (set-rows! rows))))
(define (get-col col_index)
(map
(lambda (cell)
(get-cell cell))
(get-col-cells col_index)))
(define (get-sheet-ref-col sheet_index col_index) (with-sheet-ref sheet_index (lambda () (get-col col_index))))
(define (get-sheet-name-col sheet_name col_index) (with-sheet-name sheet_name (lambda () (get-col col_index))))
(define (get-sheet-*name*-col search_sheet_name col_index) (with-sheet-*name* search_sheet_name (lambda () (get-col col_index))))
(define (set-col! col_index cell_list)
(let loop ([cell_strs (get-col-cells col_index)]
[cell_values cell_list])
(when (not (null? cell_strs))
(set-cell! (car cell_strs) (if (null? cell_values) "" (car cell_values)))
(loop (cdr cell_strs) (cdr cell_values)))))
(define (set-sheet-ref-col! sheet_index col_index cell_list) (with-sheet-ref sheet_index (lambda () (set-col! col_index cell_list))))
(define (set-sheet-name-col! sheet_name col_index cell_list) (with-sheet-name sheet_name (lambda () (set-col! col_index cell_list))))
(define (set-sheet-*name*-col! search_sheet_name col_index cell_list) (with-sheet-*name* search_sheet_name (lambda () (set-col! col_index cell_list))))
(define (get-cols)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index start_col]
[cols '()])
(if (<= loop_col_index end_col)
(loop
(add1 loop_col_index)
(cons
(get-col loop_col_index)
cols))
(reverse cols)))))
(define (get-sheet-ref-cols sheet_index) (with-sheet-ref sheet_index (lambda () (get-cols))))
(define (get-sheet-name-cols sheet_name) (with-sheet-name sheet_name (lambda () (get-cols))))
(define (get-sheet-*name*-cols search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-cols))))
(define (set-cols! cols)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index 0]
[actual_loop_col_index start_col])
(when (<= actual_loop_col_index end_col)
(set-col! actual_loop_col_index (list-ref cols loop_col_index))
(loop (add1 loop_col_index) (add1 actual_loop_col_index))))))
(define (set-sheet-ref-cols! sheet_index cols) (with-sheet-ref sheet_index (lambda () (set-cols! cols))))
(define (set-sheet-name-cols! sheet_name cols) (with-sheet-name sheet_name (lambda () (set-cols! cols))))
(define (set-sheet-*name*-cols! search_sheet_name cols) (with-sheet-*name* search_sheet_name (lambda () (set-cols! cols))))
(define (get-range-values range_str)
(map
(lambda (cell)
(get-cell cell))
(cell_range->cell_list range_str)))
(define (get-sheet-ref-range-values sheet_index range_str) (with-sheet-ref sheet_index (lambda () (get-range-values range_str))))
(define (get-sheet-name-range-values sheet_name range_str) (with-sheet-name sheet_name (lambda () (get-range-values range_str))))
(define (get-sheet-*name*-range-values search_sheet_name range_str) (with-sheet-*name* search_sheet_name (lambda () (get-range-values range_str))))
(define (squash-shared-strings-map)
(let ([shared_string->index_map (XLSX-shared_string->index_map (*XLSX*))]
[shared_index->string_map (XLSX-shared_index->string_map (*XLSX*))])
(hash-clear! shared_string->index_map)
(hash-clear! shared_index->string_map)
(let loop ([sheets (XLSX-sheet_list (*XLSX*))]
[sheet_index 0]
[sheet_string_index 0])
(when (not (null? sheets))
(if (DATA-SHEET? (car sheets))
(loop (cdr sheets) (add1 sheet_index)
(with-sheet-ref
sheet_index
(lambda ()
(let loop-row ([rows (get-rows)]
[row_string_index sheet_string_index])
(if (not (null? rows))
(loop-row
(cdr rows)
(let loop-cell ([row_cells (car rows)]
[cell_string_index row_string_index])
(if (not (null? row_cells))
(let ([cell_value (car row_cells)])
(if (string? cell_value)
(if (not (hash-has-key? shared_string->index_map cell_value))
(begin
(hash-set! shared_string->index_map cell_value cell_string_index)
(hash-set! shared_index->string_map cell_string_index cell_value)
(loop-cell (cdr row_cells) (add1 cell_string_index)))
(loop-cell (cdr row_cells) cell_string_index))
(loop-cell (cdr row_cells) cell_string_index)))
cell_string_index)))
row_string_index)))))
(loop (cdr sheets) (add1 sheet_index) sheet_string_index))))))
| null | https://raw.githubusercontent.com/simmone/racket-simple-xlsx/b6b1598aa493c2a625b9e4afe6b343480a62b816/simple-xlsx/lib/sheet-lib.rkt | racket | #lang racket
(require "../xlsx/xlsx.rkt")
(require "../sheet/sheet.rkt")
(require "dimension.rkt")
(provide (contract-out
[get-sheet-dimension (-> string?)]
[get-rows-count (-> natural?)]
[get-sheet-ref-rows-count (-> natural? natural?)]
[get-sheet-name-rows-count (-> string? natural?)]
[get-sheet-*name*-rows-count (-> string? natural?)]
[get-cols-count (-> natural?)]
[get-sheet-ref-cols-count (-> natural? natural?)]
[get-sheet-name-cols-count (-> string? natural?)]
[get-sheet-*name*-cols-count (-> string? natural?)]
[get-row-cells (-> natural? (listof string?))]
[get-sheet-ref-row-cells (-> natural? natural? (listof string?))]
[get-sheet-name-row-cells (-> string? natural? (listof string?))]
[get-sheet-*name*-row-cells (-> string? natural? (listof string?))]
[get-col-cells (-> (or/c natural? string?) (listof string?))]
[get-sheet-ref-col-cells (-> natural? (or/c natural? string?) (listof string?))]
[get-sheet-name-col-cells (-> string? (or/c natural? string?) (listof string?))]
[get-sheet-*name*-col-cells (-> string? (or/c natural? string?) (listof string?))]
[get-cell (-> string? cell-value?)]
[get-sheet-ref-cell (-> natural? string? cell-value?)]
[get-sheet-name-cell (-> string? string? cell-value?)]
[get-sheet-*name*-cell (-> string? string? cell-value?)]
[set-cell! (-> string? cell-value? void?)]
[set-sheet-ref-cell! (-> natural? string? cell-value? void?)]
[set-sheet-name-cell! (-> string? string? cell-value? void?)]
[set-sheet-*name*-cell! (-> string? string? cell-value? void?)]
[get-row (-> natural? (listof cell-value?))]
[get-sheet-ref-row (-> natural? natural? (listof cell-value?))]
[get-sheet-name-row (-> string? natural? (listof cell-value?))]
[get-sheet-*name*-row (-> string? natural? (listof cell-value?))]
[set-row! (-> natural? (listof cell-value?) void?)]
[set-sheet-ref-row! (-> natural? natural? (listof cell-value?) void?)]
[set-sheet-name-row! (-> string? natural? (listof cell-value?) void?)]
[set-sheet-*name*-row! (-> string? natural? (listof cell-value?) void?)]
[get-rows (-> (listof (listof cell-value?)))]
[get-sheet-ref-rows (-> natural? (listof (listof cell-value?)))]
[get-sheet-name-rows (-> string? (listof (listof cell-value?)))]
[get-sheet-*name*-rows (-> string? (listof (listof cell-value?)))]
[set-rows! (-> (listof (listof cell-value?)) void?)]
[set-sheet-ref-rows! (-> natural? (listof (listof cell-value?)) void?)]
[set-sheet-name-rows! (-> string? (listof (listof cell-value?)) void?)]
[set-sheet-*name*-rows! (-> string? (listof (listof cell-value?)) void?)]
[get-col (-> (or/c natural? string?) (listof cell-value?))]
[get-sheet-ref-col (-> natural? (or/c natural? string?) (listof cell-value?))]
[get-sheet-name-col (-> string? (or/c natural? string?) (listof cell-value?))]
[get-sheet-*name*-col (-> string? (or/c natural? string?) (listof cell-value?))]
[set-col! (-> (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-ref-col! (-> natural? (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-name-col! (-> string? (or/c natural? string?) (listof cell-value?) void?)]
[set-sheet-*name*-col! (-> string? (or/c natural? string?) (listof cell-value?) void?)]
[get-cols (-> (listof (listof cell-value?)))]
[get-sheet-ref-cols (-> natural? (listof (listof cell-value?)))]
[get-sheet-name-cols (-> string? (listof (listof cell-value?)))]
[get-sheet-*name*-cols (-> string? (listof (listof cell-value?)))]
[set-cols! (-> (listof (listof cell-value?)) void?)]
[set-sheet-ref-cols! (-> natural? (listof (listof cell-value?)) void?)]
[set-sheet-name-cols! (-> string? (listof (listof cell-value?)) void?)]
[set-sheet-*name*-cols! (-> string? (listof (listof cell-value?)) void?)]
[get-range-values (-> string? (listof cell-value?))]
[get-sheet-ref-range-values (-> natural? string? (listof cell-value?))]
[get-sheet-name-range-values (-> string? string? (listof cell-value?))]
[get-sheet-*name*-range-values (-> string? string? (listof cell-value?))]
[squash-shared-strings-map (-> void?)]
))
(define (get-sheet-dimension)
(DATA-SHEET-dimension (*CURRENT_SHEET*)))
(define (get-rows-count)
(car (range->capacity (DATA-SHEET-dimension (*CURRENT_SHEET*)))))
(define (get-sheet-ref-rows-count sheet_index) (with-sheet-ref sheet_index (lambda () (get-rows-count))))
(define (get-sheet-name-rows-count sheet_name) (with-sheet-name sheet_name (lambda () (get-rows-count))))
(define (get-sheet-*name*-rows-count search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-rows-count))))
(define (get-cols-count)
(cdr (range->capacity (DATA-SHEET-dimension (*CURRENT_SHEET*)))))
(define (get-sheet-ref-cols-count sheet_index) (with-sheet-ref sheet_index (lambda () (get-cols-count))))
(define (get-sheet-name-cols-count sheet_name) (with-sheet-name sheet_name (lambda () (get-cols-count))))
(define (get-sheet-*name*-cols-count search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-cols-count))))
(define (get-row-cells row_index)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index start_col]
[cells '()])
(if (<= loop_col_index end_col)
(loop
(add1 loop_col_index)
(cons
(row_col->cell row_index loop_col_index)
cells))
(reverse cells)))))
(define (get-sheet-ref-row-cells sheet_index row_index) (with-sheet-ref sheet_index (lambda () (get-row-cells row_index))))
(define (get-sheet-name-row-cells sheet_name row_index) (with-sheet-name sheet_name (lambda () (get-row-cells row_index))))
(define (get-sheet-*name*-row-cells search_sheet_name row_index) (with-sheet-*name* search_sheet_name (lambda () (get-row-cells row_index))))
(define (get-col-cells col)
(cond
[(string? col)
(get-col-number-cells (col_abc->number col))]
[(natural? col)
(get-col-number-cells col)]))
(define (get-col-number-cells col_index)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index start_row]
[cells '()])
(if (<= loop_row_index end_row)
(loop
(add1 loop_row_index)
(cons
(row_col->cell loop_row_index col_index)
cells))
(reverse cells)))))
(define (get-sheet-ref-col-cells sheet_index col_index) (with-sheet-ref sheet_index (lambda () (get-col-cells col_index))))
(define (get-sheet-name-col-cells sheet_name col_index) (with-sheet-name sheet_name (lambda () (get-col-cells col_index))))
(define (get-sheet-*name*-col-cells search_sheet_name col_index) (with-sheet-*name* search_sheet_name (lambda () (get-col-cells col_index))))
(define (get-cell cell)
(hash-ref (DATA-SHEET-cell->value_hash (*CURRENT_SHEET*)) cell ""))
(define (get-sheet-ref-cell sheet_index cell) (with-sheet-ref sheet_index (lambda () (get-cell cell))))
(define (get-sheet-name-cell sheet_name cell) (with-sheet-name sheet_name (lambda () (get-cell cell))))
(define (get-sheet-*name*-cell search_sheet_name cell) (with-sheet-*name* search_sheet_name (lambda () (get-cell cell))))
(define (set-cell! cell value)
(hash-set! (DATA-SHEET-cell->value_hash (*CURRENT_SHEET*)) cell value))
(define (set-sheet-ref-cell! sheet_index cell value) (with-sheet-ref sheet_index (lambda () (set-cell! cell value))))
(define (set-sheet-name-cell! sheet_name cell value) (with-sheet-name sheet_name (lambda () (set-cell! cell value))))
(define (set-sheet-*name*-cell! search_sheet_name cell value) (with-sheet-*name* search_sheet_name (lambda () (set-cell! cell value))))
(define (get-row row_index)
(map
(lambda (cell)
(get-cell cell))
(get-row-cells row_index)))
(define (get-sheet-ref-row sheet_index row_index) (with-sheet-ref sheet_index (lambda () (get-row row_index))))
(define (get-sheet-name-row sheet_name row_index) (with-sheet-name sheet_name (lambda () (get-row row_index))))
(define (get-sheet-*name*-row search_sheet_name row_index) (with-sheet-*name* search_sheet_name (lambda () (get-row row_index))))
(define (set-row! row_index cell_list)
(let loop ([cell_strs (get-row-cells row_index)]
[cell_values cell_list])
(when (not (null? cell_strs))
(set-cell! (car cell_strs) (if (null? cell_values) "" (car cell_values)))
(loop (cdr cell_strs) (cdr cell_values)))))
(define (set-sheet-ref-row! sheet_index row_index cell_list) (with-sheet-ref sheet_index (lambda () (set-row! row_index cell_list))))
(define (set-sheet-name-row! sheet_name row_index cell_list) (with-sheet-name sheet_name (lambda () (set-row! row_index cell_list))))
(define (set-sheet-*name*-row! search_sheet_name row_index cell_list) (with-sheet-*name* search_sheet_name (lambda () (set-row! row_index cell_list))))
(define (get-rows)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index start_row]
[rows '()])
(if (<= loop_row_index end_row)
(loop
(add1 loop_row_index)
(cons
(get-row loop_row_index)
rows))
(reverse rows)))))
(define (get-sheet-ref-rows sheet_index) (with-sheet-ref sheet_index (lambda () (get-rows))))
(define (get-sheet-name-rows sheet_name) (with-sheet-name sheet_name (lambda () (get-rows))))
(define (get-sheet-*name*-rows search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-rows))))
(define (set-rows! rows)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_row (caar range_row_col)]
[end_row (cadr range_row_col)])
(let loop ([loop_row_index 0]
[actual_loop_row_index start_row])
(when (<= actual_loop_row_index end_row)
(set-row! actual_loop_row_index (list-ref rows loop_row_index))
(loop (add1 loop_row_index) (add1 actual_loop_row_index))))))
(define (set-sheet-ref-rows! sheet_index rows) (with-sheet-ref sheet_index (lambda () (set-rows! rows))))
(define (set-sheet-name-rows! sheet_name rows) (with-sheet-name sheet_name (lambda () (set-rows! rows))))
(define (set-sheet-*name*-rows! search_sheet_name rows) (with-sheet-*name* search_sheet_name (lambda () (set-rows! rows))))
(define (get-col col_index)
(map
(lambda (cell)
(get-cell cell))
(get-col-cells col_index)))
(define (get-sheet-ref-col sheet_index col_index) (with-sheet-ref sheet_index (lambda () (get-col col_index))))
(define (get-sheet-name-col sheet_name col_index) (with-sheet-name sheet_name (lambda () (get-col col_index))))
(define (get-sheet-*name*-col search_sheet_name col_index) (with-sheet-*name* search_sheet_name (lambda () (get-col col_index))))
(define (set-col! col_index cell_list)
(let loop ([cell_strs (get-col-cells col_index)]
[cell_values cell_list])
(when (not (null? cell_strs))
(set-cell! (car cell_strs) (if (null? cell_values) "" (car cell_values)))
(loop (cdr cell_strs) (cdr cell_values)))))
(define (set-sheet-ref-col! sheet_index col_index cell_list) (with-sheet-ref sheet_index (lambda () (set-col! col_index cell_list))))
(define (set-sheet-name-col! sheet_name col_index cell_list) (with-sheet-name sheet_name (lambda () (set-col! col_index cell_list))))
(define (set-sheet-*name*-col! search_sheet_name col_index cell_list) (with-sheet-*name* search_sheet_name (lambda () (set-col! col_index cell_list))))
(define (get-cols)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index start_col]
[cols '()])
(if (<= loop_col_index end_col)
(loop
(add1 loop_col_index)
(cons
(get-col loop_col_index)
cols))
(reverse cols)))))
(define (get-sheet-ref-cols sheet_index) (with-sheet-ref sheet_index (lambda () (get-cols))))
(define (get-sheet-name-cols sheet_name) (with-sheet-name sheet_name (lambda () (get-cols))))
(define (get-sheet-*name*-cols search_sheet_name) (with-sheet-*name* search_sheet_name (lambda () (get-cols))))
(define (set-cols! cols)
(let* ([range_row_col (range->row_col_pair (DATA-SHEET-dimension (*CURRENT_SHEET*)))]
[start_col (cdar range_row_col)]
[end_col (cddr range_row_col)])
(let loop ([loop_col_index 0]
[actual_loop_col_index start_col])
(when (<= actual_loop_col_index end_col)
(set-col! actual_loop_col_index (list-ref cols loop_col_index))
(loop (add1 loop_col_index) (add1 actual_loop_col_index))))))
(define (set-sheet-ref-cols! sheet_index cols) (with-sheet-ref sheet_index (lambda () (set-cols! cols))))
(define (set-sheet-name-cols! sheet_name cols) (with-sheet-name sheet_name (lambda () (set-cols! cols))))
(define (set-sheet-*name*-cols! search_sheet_name cols) (with-sheet-*name* search_sheet_name (lambda () (set-cols! cols))))
(define (get-range-values range_str)
(map
(lambda (cell)
(get-cell cell))
(cell_range->cell_list range_str)))
(define (get-sheet-ref-range-values sheet_index range_str) (with-sheet-ref sheet_index (lambda () (get-range-values range_str))))
(define (get-sheet-name-range-values sheet_name range_str) (with-sheet-name sheet_name (lambda () (get-range-values range_str))))
(define (get-sheet-*name*-range-values search_sheet_name range_str) (with-sheet-*name* search_sheet_name (lambda () (get-range-values range_str))))
(define (squash-shared-strings-map)
(let ([shared_string->index_map (XLSX-shared_string->index_map (*XLSX*))]
[shared_index->string_map (XLSX-shared_index->string_map (*XLSX*))])
(hash-clear! shared_string->index_map)
(hash-clear! shared_index->string_map)
(let loop ([sheets (XLSX-sheet_list (*XLSX*))]
[sheet_index 0]
[sheet_string_index 0])
(when (not (null? sheets))
(if (DATA-SHEET? (car sheets))
(loop (cdr sheets) (add1 sheet_index)
(with-sheet-ref
sheet_index
(lambda ()
(let loop-row ([rows (get-rows)]
[row_string_index sheet_string_index])
(if (not (null? rows))
(loop-row
(cdr rows)
(let loop-cell ([row_cells (car rows)]
[cell_string_index row_string_index])
(if (not (null? row_cells))
(let ([cell_value (car row_cells)])
(if (string? cell_value)
(if (not (hash-has-key? shared_string->index_map cell_value))
(begin
(hash-set! shared_string->index_map cell_value cell_string_index)
(hash-set! shared_index->string_map cell_string_index cell_value)
(loop-cell (cdr row_cells) (add1 cell_string_index)))
(loop-cell (cdr row_cells) cell_string_index))
(loop-cell (cdr row_cells) cell_string_index)))
cell_string_index)))
row_string_index)))))
(loop (cdr sheets) (add1 sheet_index) sheet_string_index))))))
|
|
a632f4eaad927f5d8ceb5ef72441683773d880979bd70503e73ca6cf1da11144 | LesBoloss-es/xoshiro | libCrusher.mli | val run : name:string -> (unit -> int) -> unit
| null | https://raw.githubusercontent.com/LesBoloss-es/xoshiro/a2719c6108afb308bd37c0eb65deb9dba45cf9d1/utils/crusher/libCrusher.mli | ocaml | val run : name:string -> (unit -> int) -> unit
|
|
9eb2e229fc13bc5408b85a3f42e5643eba1e4fe81c823cd4ec381375b0c561a9 | cobaweel/piffle | PifflePiffle.hs | Piffle , Copyright ( C ) 2007 , . This program is free
software ; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option )
any later version . This program is distributed in the hope that it
will be useful , but WITHOUT ANY WARRANTY ; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE .
See the GNU General Public License for more details . You should
have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. ,
59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option)
any later version. This program is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should
have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -}
module PifflePiffle where
import CommonUtil
import Compiler
import Piffle
tFile = return . id
| null | https://raw.githubusercontent.com/cobaweel/piffle/7c4cfb5301c5c55c229098d3938d3b023d69cde4/src/PifflePiffle.hs | haskell | Piffle , Copyright ( C ) 2007 , . This program is free
software ; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software
Foundation ; either version 2 of the License , or ( at your option )
any later version . This program is distributed in the hope that it
will be useful , but WITHOUT ANY WARRANTY ; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE .
See the GNU General Public License for more details . You should
have received a copy of the GNU General Public License along with
this program ; if not , write to the Free Software Foundation , Inc. ,
59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option)
any later version. This program is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should
have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -}
module PifflePiffle where
import CommonUtil
import Compiler
import Piffle
tFile = return . id
|
|
1d1c82e0d5fe3b2b242a25e2933f41d4576b9cc346b678267f4fc92530d46110 | fluree/ledger | sql_query.clj | (ns fluree.db.ledger.docs.query.sql-query
(:require [clojure.test :refer :all]
[clojure.stacktrace :refer [root-cause]]
[fluree.db.test-helpers :as test]
[fluree.db.ledger.docs.getting-started.basic-schema :as basic]
[fluree.db.api :as fdb]
[fluree.db.util.core :as utils]
[clojure.core.async :as async]
[clojure.set :refer [subset?]]))
(use-fixtures :once test/test-system-deprecated)
(deftest query-tests
(testing "Select all chats"
(let [query "select * from chat"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 chats
(is (= 3 (count data)))
;; the keys for every chat should be _id, message, person, instant, or comments
(is (every? (fn [chat]
(every? #(boolean (#{"_id" "chat/message" :_id "chat/person"
"chat/instant" "chat/comments"} %)) (keys chat))) data))))
(testing "Select all persons of age 25"
(let [query "select * from person where age = 25"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 1 person
(is (= 1 (count data)))
the keys for every person should be _ i d , follows , age , active , favMovies ,
;; favNums, handle, fullName
(is (every? (fn [item]
(every? #(boolean (#{"_id" "person/follows" :_id "person/age"
"person/active" "person/favMovies"
"person/favNums" "person/favArtists"
"person/handle" "person/fullName"} %))
(keys item))) data))))
(testing "Select all persons older or younger than 34"
(let [query "select * from person where age < 34 OR age > 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 4 people
(is (= 4 (count data)))))
(testing "Select all persons younger than 34"
(let [query "select * from person where age < 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 people
(is (= 2 (count data)))))
(testing "Select all persons 34 years of age or less"
(let [query "select * from person where age <= 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 people
(is (= 3 (count data)))))
(testing "Select all persons older than 34"
(let [query "select * from person where age > 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 people
(is (= 2 (count data)))))
(testing "Select all persons 34 years of age or older"
(let [query "select * from person where age >= 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 people
(is (= 3 (count data)))))
(testing "Select all persons older than 34 with a favNum less than 50"
(let [query "select * from person where age > 34 and favNums < 50"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 items returned
(is (= 2 (count data)))))
(testing "Select all persons older than 34 or who have a favNum less than 50"
(let [query "select * from person where age > 34 or favNums < 50"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 12 items returned
(is (= 12 (count data))))))
(deftest tests-independent
(basic/add-collections*)
(basic/add-predicates)
(basic/add-sample-data)
(basic/graphql-txn)
(query-tests))
| null | https://raw.githubusercontent.com/fluree/ledger/31f3e11a0648501b0a8cc6148177e54c67420042/test/fluree/db/ledger/docs/query/sql_query.clj | clojure | the keys for every chat should be _id, message, person, instant, or comments
favNums, handle, fullName | (ns fluree.db.ledger.docs.query.sql-query
(:require [clojure.test :refer :all]
[clojure.stacktrace :refer [root-cause]]
[fluree.db.test-helpers :as test]
[fluree.db.ledger.docs.getting-started.basic-schema :as basic]
[fluree.db.api :as fdb]
[fluree.db.util.core :as utils]
[clojure.core.async :as async]
[clojure.set :refer [subset?]]))
(use-fixtures :once test/test-system-deprecated)
(deftest query-tests
(testing "Select all chats"
(let [query "select * from chat"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 chats
(is (= 3 (count data)))
(is (every? (fn [chat]
(every? #(boolean (#{"_id" "chat/message" :_id "chat/person"
"chat/instant" "chat/comments"} %)) (keys chat))) data))))
(testing "Select all persons of age 25"
(let [query "select * from person where age = 25"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 1 person
(is (= 1 (count data)))
the keys for every person should be _ i d , follows , age , active , favMovies ,
(is (every? (fn [item]
(every? #(boolean (#{"_id" "person/follows" :_id "person/age"
"person/active" "person/favMovies"
"person/favNums" "person/favArtists"
"person/handle" "person/fullName"} %))
(keys item))) data))))
(testing "Select all persons older or younger than 34"
(let [query "select * from person where age < 34 OR age > 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 4 people
(is (= 4 (count data)))))
(testing "Select all persons younger than 34"
(let [query "select * from person where age < 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 people
(is (= 2 (count data)))))
(testing "Select all persons 34 years of age or less"
(let [query "select * from person where age <= 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 people
(is (= 3 (count data)))))
(testing "Select all persons older than 34"
(let [query "select * from person where age > 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 people
(is (= 2 (count data)))))
(testing "Select all persons 34 years of age or older"
(let [query "select * from person where age >= 34"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 3 people
(is (= 3 (count data)))))
(testing "Select all persons older than 34 with a favNum less than 50"
(let [query "select * from person where age > 34 and favNums < 50"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 2 items returned
(is (= 2 (count data)))))
(testing "Select all persons older than 34 or who have a favNum less than 50"
(let [query "select * from person where age > 34 or favNums < 50"
data (-> (basic/get-db test/ledger-chat)
(fdb/sql-async query)
(async/<!!))]
should be 12 items returned
(is (= 12 (count data))))))
(deftest tests-independent
(basic/add-collections*)
(basic/add-predicates)
(basic/add-sample-data)
(basic/graphql-txn)
(query-tests))
|
0d97718e7fe5cb3d9e4c2bc31f5b3e1356020d0058c03c28896636ba8f716958 | sunng87/diehard | circuit_breaker.clj | (ns diehard.circuit-breaker
(:require [diehard.util :as u])
(:import [java.time Duration]
[java.util List]
[dev.failsafe CircuitBreaker]
[dev.failsafe.function CheckedBiPredicate]))
(def ^{:const true :no-doc true}
allowed-circuit-breaker-option-keys
#{:failure-threshold :failure-threshold-ratio :failure-threshold-ratio-in-period
:failure-rate-threshold-in-period
:success-threshold :success-threshold-ratio
:delay-ms :timeout-ms
:fail-if :fail-on :fail-when
:on-open :on-close :on-half-open})
(defn circuit-breaker [opts]
(u/verify-opt-map-keys-with-spec :circuit-breaker/circuit-breaker opts)
(let [cb (CircuitBreaker/builder)]
(when (contains? opts :fail-on)
(.handle cb ^List (u/as-vector (:fail-on opts))))
(when (contains? opts :fail-if)
(.handleIf cb ^CheckedBiPredicate (u/bipredicate (:fail-if opts))))
(when (contains? opts :fail-when)
(.handleResult cb (:fail-when opts)))
(when-let [delay (:delay-ms opts)]
(.withDelay cb (Duration/ofMillis delay)))
(when-let [failure-threshold (:failure-threshold opts)]
(.withFailureThreshold cb failure-threshold))
(when-let [[^int failures ^int executions] (:failure-threshold-ratio opts)]
(.withFailureThreshold cb failures executions))
(when-let [[failures executions period-ms]
(:failure-threshold-ratio-in-period opts)]
(.withFailureThreshold cb failures executions (Duration/ofMillis period-ms)))
(when-let [[failure-rate executions period-ms]
(:failure-rate-threshold-in-period opts)]
(.withFailureRateThreshold cb failure-rate executions (Duration/ofMillis period-ms)))
(when-let [success-threshold (:success-threshold opts)]
(.withSuccessThreshold cb success-threshold))
(when-let [[successes executions] (:success-threshold-ratio opts)]
(.withSuccessThreshold cb successes executions))
(when-let [on-open (:on-open opts)]
(.onOpen cb (u/wrap-event-listener on-open)))
(when-let [on-half-open (:on-half-open opts)]
(.onHalfOpen cb (u/wrap-event-listener on-half-open)))
(when-let [on-close (:on-close opts)]
(.onClose cb (u/wrap-event-listener on-close)))
(.build cb)))
(defn state
"Get current state of this circuit breaker, values in `:open`, `:closed` and `half-open` "
[^CircuitBreaker cb]
(cond
(.isOpen cb) :open
(.isClosed cb) :closed
:else :half-open))
(defn allow-execution?
"Test if this circuit breaker allow code execution. The result is based
on current state:
* `:open` will deny all execution requests
* `:close` allows all executions
* `:half-open` only allows some of execution requests"
[^CircuitBreaker cb]
(.allowsExecution cb))
| null | https://raw.githubusercontent.com/sunng87/diehard/53d16f2e43e796239c58d4f0976c147c29932a6d/src/diehard/circuit_breaker.clj | clojure | (ns diehard.circuit-breaker
(:require [diehard.util :as u])
(:import [java.time Duration]
[java.util List]
[dev.failsafe CircuitBreaker]
[dev.failsafe.function CheckedBiPredicate]))
(def ^{:const true :no-doc true}
allowed-circuit-breaker-option-keys
#{:failure-threshold :failure-threshold-ratio :failure-threshold-ratio-in-period
:failure-rate-threshold-in-period
:success-threshold :success-threshold-ratio
:delay-ms :timeout-ms
:fail-if :fail-on :fail-when
:on-open :on-close :on-half-open})
(defn circuit-breaker [opts]
(u/verify-opt-map-keys-with-spec :circuit-breaker/circuit-breaker opts)
(let [cb (CircuitBreaker/builder)]
(when (contains? opts :fail-on)
(.handle cb ^List (u/as-vector (:fail-on opts))))
(when (contains? opts :fail-if)
(.handleIf cb ^CheckedBiPredicate (u/bipredicate (:fail-if opts))))
(when (contains? opts :fail-when)
(.handleResult cb (:fail-when opts)))
(when-let [delay (:delay-ms opts)]
(.withDelay cb (Duration/ofMillis delay)))
(when-let [failure-threshold (:failure-threshold opts)]
(.withFailureThreshold cb failure-threshold))
(when-let [[^int failures ^int executions] (:failure-threshold-ratio opts)]
(.withFailureThreshold cb failures executions))
(when-let [[failures executions period-ms]
(:failure-threshold-ratio-in-period opts)]
(.withFailureThreshold cb failures executions (Duration/ofMillis period-ms)))
(when-let [[failure-rate executions period-ms]
(:failure-rate-threshold-in-period opts)]
(.withFailureRateThreshold cb failure-rate executions (Duration/ofMillis period-ms)))
(when-let [success-threshold (:success-threshold opts)]
(.withSuccessThreshold cb success-threshold))
(when-let [[successes executions] (:success-threshold-ratio opts)]
(.withSuccessThreshold cb successes executions))
(when-let [on-open (:on-open opts)]
(.onOpen cb (u/wrap-event-listener on-open)))
(when-let [on-half-open (:on-half-open opts)]
(.onHalfOpen cb (u/wrap-event-listener on-half-open)))
(when-let [on-close (:on-close opts)]
(.onClose cb (u/wrap-event-listener on-close)))
(.build cb)))
(defn state
"Get current state of this circuit breaker, values in `:open`, `:closed` and `half-open` "
[^CircuitBreaker cb]
(cond
(.isOpen cb) :open
(.isClosed cb) :closed
:else :half-open))
(defn allow-execution?
"Test if this circuit breaker allow code execution. The result is based
on current state:
* `:open` will deny all execution requests
* `:close` allows all executions
* `:half-open` only allows some of execution requests"
[^CircuitBreaker cb]
(.allowsExecution cb))
|
|
5080a2a73e58621e48cbc71e5b69a224b240c1aa6ab877589b427d0f035add4c | cirodrig/triolet | Print.hs |
module SystemF.Print
(PrintFlags(..), defaultPrintFlags,
pprLit, pprVar, pprPat, pprExp, pprFun, pprFDef, pprModule,
pprVarFlags, pprPatFlags, pprExpFlags, pprFunFlags, pprFDefFlags
)
where
import Data.Maybe
import Text.PrettyPrint.HughesPJ
import Common.Error
import Common.Identifier
import Common.Label
import Export
import Type.Type
import Type.Var
import Builtins.Builtins
import SystemF.Syntax
pprPat :: PatSF -> Doc
pprPat = pprPatFlags defaultPrintFlags
pprExp :: ExpSF -> Doc
pprExp = pprExpFlags defaultPrintFlags
pprFun :: FunSF -> Doc
pprFun = pprFunFlags defaultPrintFlags
pprFDef :: FDef SF -> Doc
pprFDef = pprFDefFlags defaultPrintFlags
pprGDef :: GDef SF -> Doc
pprGDef = pprGDefFlags defaultPrintFlags
pprExport :: Export SF -> Doc
pprExport (Export pos spec f) =
text "export" <+> pprExportSpec spec $$ nest 2 (pprFun f)
pprModule :: Module SF -> Doc
pprModule (Module module_name [] defs exports) =
text "module" <+> text (showModuleName module_name) $$
vcat (map (braces . vcat . map pprGDef . defGroupMembers) defs) $$
vcat (map pprExport exports)
data PrintFlags =
PrintFlags
{ printVariableIDs :: !Bool
}
defaultPrintFlags =
PrintFlags
{ printVariableIDs = True
}
-- Helper function for printing tuple syntax
tuple :: [Doc] -> Doc
tuple xs = parens $ sep $ punctuate comma xs
list :: [Doc] -> Doc
list xs = brackets $ sep $ punctuate comma xs
pprExportSpec :: ExportSpec -> Doc
pprExportSpec (ExportSpec lang name) =
text (foreignLanguageName lang) <+> text (show name)
pprVarFlags :: PrintFlags -> Var -> Doc
pprVarFlags flags v = pprVar v
pprLit (IntL n _) = text (show n)
pprLit (FloatL f _) = text (show f)
pprPatFlags :: PrintFlags -> PatSF -> Doc
pprPatFlags flags pat =
case pat
of VarP v ty -> pprVarFlags flags v <+> colon <+> pprType ty
pprTyPatFlags :: PrintFlags -> TyPat -> Doc
pprTyPatFlags flags (TyPat (v ::: ty)) =
pprVar v <+> colon <+> pprType ty
pprExpFlags :: PrintFlags -> ExpSF -> Doc
pprExpFlags flags expression = pprExpFlagsPrec flags precOuter expression
-- Precedences for expression printing.
-- If an expression has precedence P, and it's shown in a context with
-- precedence Q > P, then it needs parentheses.
parenthesize prec doc context
| context > prec = parens doc
| otherwise = doc
precOuter = 0 -- Outermost precedence; commas; parentheses
precTyAnnot = 1 -- Type annotation (x : t)
precTyApp = 10 -- Type application (f @ x)
precApp = 10 -- Application (f x)
pprTypeAnnotation :: Doc -> Doc -> Int -> Doc
pprTypeAnnotation val ty context =
parenthesize precTyAnnot (val <+> colon <+> ty) context
pprExpFlagsPrec :: PrintFlags -> Int -> ExpSF -> Doc
pprExpFlagsPrec flags prec (ExpSF expression) =
case expression
of VarE {expVar = v} ->
pprVarFlags flags v
LitE {expLit = l} -> pprLit l
ConE _ (VarCon op ty_args ex_types) size_params ty_obj args ->
let op_doc = pprVar op
tDoc = [text "@" <> pprType t | t <- ty_args]
spDoc
| null size_params = empty
| otherwise = list $ map (pprExpFlagsPrec flags precOuter) size_params
eDoc = [text "&" <> pprType t | t <- ex_types]
tobDoc =
case ty_obj
of Nothing -> empty
Just e -> brackets $ pprExpFlagsPrec flags precOuter e
aDoc = map (pprExpFlagsPrec flags precOuter) args
in hang op_doc 4 (tuple (tDoc ++ [spDoc] ++ eDoc ++ [tobDoc] ++ aDoc))
AppE {expOper = e, expTyArgs = ts, expArgs = es} ->
let eDoc = pprExpFlagsPrec flags precTyApp e
tDoc = [text "@" <> pprType t | t <- ts]
aDoc = map (pprExpFlagsPrec flags precOuter) es
in hang eDoc 4 (tuple (tDoc ++ aDoc))
LamE {expFun = f} ->
pprFunFlags flags f
LetE {expBinder = pat, expValue = rhs, expBody = body} ->
let e1 = hang (pprPatFlags flags pat <+> equals) 2
(pprExpFlags flags rhs)
e2 = pprExpFlags flags body
in text "let" <+> e1 $$ e2
LetfunE {expDefs = ds, expBody = body} ->
let defsText = vcat $ map (pprFDefFlags flags) $ defGroupMembers ds
e = pprExpFlags flags body
in text "letrec" $$ nest 2 defsText $$ text "in" <+> e
CaseE {expScrutinee = e, expAlternatives = [AltSF alt1, AltSF alt2]}
| is_true (altCon alt1) && is_false (altCon alt2) ->
pprIf flags e (altBody alt1) (altBody alt2)
| is_true (altCon alt2) && is_false (altCon alt1) ->
pprIf flags e (altBody alt2) (altBody alt1)
CaseE {expScrutinee = e, expAlternatives = alts} ->
let doc = text "case" <+> pprExpFlagsPrec flags precOuter e $$
text "of" <+> vcat (map (pprAltFlags flags) alts)
in parenthesize precOuter doc prec
CoerceE inf from_t to_t b ->
let coercion_doc = pprType from_t <+> text "=>" <+> pprType to_t
b_doc = pprExpFlagsPrec flags precOuter b
in hang (text "coerce" <+> parens coercion_doc) 4 b_doc
ArrayE inf ty es ->
let es_doc = punctuate comma $ map (pprExpFlagsPrec flags precOuter) es
in text "array" <+> parens (pprType ty) <+> braces (fsep es_doc)
where
is_true (VarDeCon op _ _) = op `isCoreBuiltin` The_True
is_true _ = False
is_false (VarDeCon op _ _) = op `isCoreBuiltin` The_False
is_false _ = False
pprIf flags cond tr fa =
let condText = pprExpFlags flags cond
trText = pprExpFlags flags tr
faText = pprExpFlags flags fa
in text "if" <+> condText $$
text "then" <+> trText $$
text "else" <+> faText
pprAltFlags :: PrintFlags -> AltSF -> Doc
pprAltFlags flags (AltSF (Alt con ty_ob_param params body)) =
let pattern =
case con
of VarDeCon op ty_args ex_types ->
let ty_args_doc = map (text "@" <>) $ map pprType ty_args
ty_ob_doc = maybe empty (brackets . pprPatFlags flags) ty_ob_param
params_doc = [parens $ pprPatFlags flags p | p <- params]
in pprVar op <+> sep (ty_args_doc ++ [ty_ob_doc] ++ params_doc)
TupleDeCon _
| isJust ty_ob_param ->
internalError "pprAltFlags: Unexpected parameter"
TupleDeCon _ ->
parens $ sep $ punctuate (text ",") $
map (pprPatFlags flags) params
body_doc = pprExpFlagsPrec flags precOuter body
in hang (pattern <> text ".") 2 body_doc
-- UTF-8 for lowercase lambda
lambda = text "lambda"
-- Print the function parameters, as they would appear in a lambda expression
-- or function definition.
pprFunParameters :: Bool -> PrintFlags -> FunSF -> Doc
pprFunParameters isLambda flags (FunSF fun) = sep param_doc
where
param_doc =
-- Type parameters
map ty_param (funTyParams fun) ++
-- Value parameters
map (parens . pprPatFlags flags) (funParams fun) ++
-- Return type
[introduce_return_type $ pprType (funReturn fun)]
introduce_return_type t
| isLambda = nest (-3) $ text "->" <+> t
| otherwise = nest (-2) $ colon <+> t
ty_param p = text "@" <> parens (pprTyPatFlags flags p)
pprFunFlags :: PrintFlags -> FunSF -> Doc
pprFunFlags flags fun =
let params = pprFunParameters True flags fun
body = pprExpFlags flags $ funBody (fromFunSF fun)
in hang (lambda <+> params <> text ".") 4 body
pprFDefFlags flags (Def v _ fun) =
let params = pprFunParameters False flags fun
body = pprExpFlags flags $ funBody (fromFunSF fun)
in hang (pprVarFlags flags v <+> params <+> equals) 4 body
pprGDefFlags flags (Def v a (FunEnt fun)) =
pprFDefFlags flags (Def v a fun)
pprGDefFlags flags (Def v _ (DataEnt const)) =
let type_doc = pprType (constType const)
value = pprExpFlags flags $ constExp const
in hang (pprVarFlags flags v <+> colon <+> type_doc <+> equals) 4 value
| null | https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/src/program/SystemF/Print.hs | haskell | Helper function for printing tuple syntax
Precedences for expression printing.
If an expression has precedence P, and it's shown in a context with
precedence Q > P, then it needs parentheses.
Outermost precedence; commas; parentheses
Type annotation (x : t)
Type application (f @ x)
Application (f x)
UTF-8 for lowercase lambda
Print the function parameters, as they would appear in a lambda expression
or function definition.
Type parameters
Value parameters
Return type |
module SystemF.Print
(PrintFlags(..), defaultPrintFlags,
pprLit, pprVar, pprPat, pprExp, pprFun, pprFDef, pprModule,
pprVarFlags, pprPatFlags, pprExpFlags, pprFunFlags, pprFDefFlags
)
where
import Data.Maybe
import Text.PrettyPrint.HughesPJ
import Common.Error
import Common.Identifier
import Common.Label
import Export
import Type.Type
import Type.Var
import Builtins.Builtins
import SystemF.Syntax
pprPat :: PatSF -> Doc
pprPat = pprPatFlags defaultPrintFlags
pprExp :: ExpSF -> Doc
pprExp = pprExpFlags defaultPrintFlags
pprFun :: FunSF -> Doc
pprFun = pprFunFlags defaultPrintFlags
pprFDef :: FDef SF -> Doc
pprFDef = pprFDefFlags defaultPrintFlags
pprGDef :: GDef SF -> Doc
pprGDef = pprGDefFlags defaultPrintFlags
pprExport :: Export SF -> Doc
pprExport (Export pos spec f) =
text "export" <+> pprExportSpec spec $$ nest 2 (pprFun f)
pprModule :: Module SF -> Doc
pprModule (Module module_name [] defs exports) =
text "module" <+> text (showModuleName module_name) $$
vcat (map (braces . vcat . map pprGDef . defGroupMembers) defs) $$
vcat (map pprExport exports)
data PrintFlags =
PrintFlags
{ printVariableIDs :: !Bool
}
defaultPrintFlags =
PrintFlags
{ printVariableIDs = True
}
tuple :: [Doc] -> Doc
tuple xs = parens $ sep $ punctuate comma xs
list :: [Doc] -> Doc
list xs = brackets $ sep $ punctuate comma xs
pprExportSpec :: ExportSpec -> Doc
pprExportSpec (ExportSpec lang name) =
text (foreignLanguageName lang) <+> text (show name)
pprVarFlags :: PrintFlags -> Var -> Doc
pprVarFlags flags v = pprVar v
pprLit (IntL n _) = text (show n)
pprLit (FloatL f _) = text (show f)
pprPatFlags :: PrintFlags -> PatSF -> Doc
pprPatFlags flags pat =
case pat
of VarP v ty -> pprVarFlags flags v <+> colon <+> pprType ty
pprTyPatFlags :: PrintFlags -> TyPat -> Doc
pprTyPatFlags flags (TyPat (v ::: ty)) =
pprVar v <+> colon <+> pprType ty
pprExpFlags :: PrintFlags -> ExpSF -> Doc
pprExpFlags flags expression = pprExpFlagsPrec flags precOuter expression
parenthesize prec doc context
| context > prec = parens doc
| otherwise = doc
pprTypeAnnotation :: Doc -> Doc -> Int -> Doc
pprTypeAnnotation val ty context =
parenthesize precTyAnnot (val <+> colon <+> ty) context
pprExpFlagsPrec :: PrintFlags -> Int -> ExpSF -> Doc
pprExpFlagsPrec flags prec (ExpSF expression) =
case expression
of VarE {expVar = v} ->
pprVarFlags flags v
LitE {expLit = l} -> pprLit l
ConE _ (VarCon op ty_args ex_types) size_params ty_obj args ->
let op_doc = pprVar op
tDoc = [text "@" <> pprType t | t <- ty_args]
spDoc
| null size_params = empty
| otherwise = list $ map (pprExpFlagsPrec flags precOuter) size_params
eDoc = [text "&" <> pprType t | t <- ex_types]
tobDoc =
case ty_obj
of Nothing -> empty
Just e -> brackets $ pprExpFlagsPrec flags precOuter e
aDoc = map (pprExpFlagsPrec flags precOuter) args
in hang op_doc 4 (tuple (tDoc ++ [spDoc] ++ eDoc ++ [tobDoc] ++ aDoc))
AppE {expOper = e, expTyArgs = ts, expArgs = es} ->
let eDoc = pprExpFlagsPrec flags precTyApp e
tDoc = [text "@" <> pprType t | t <- ts]
aDoc = map (pprExpFlagsPrec flags precOuter) es
in hang eDoc 4 (tuple (tDoc ++ aDoc))
LamE {expFun = f} ->
pprFunFlags flags f
LetE {expBinder = pat, expValue = rhs, expBody = body} ->
let e1 = hang (pprPatFlags flags pat <+> equals) 2
(pprExpFlags flags rhs)
e2 = pprExpFlags flags body
in text "let" <+> e1 $$ e2
LetfunE {expDefs = ds, expBody = body} ->
let defsText = vcat $ map (pprFDefFlags flags) $ defGroupMembers ds
e = pprExpFlags flags body
in text "letrec" $$ nest 2 defsText $$ text "in" <+> e
CaseE {expScrutinee = e, expAlternatives = [AltSF alt1, AltSF alt2]}
| is_true (altCon alt1) && is_false (altCon alt2) ->
pprIf flags e (altBody alt1) (altBody alt2)
| is_true (altCon alt2) && is_false (altCon alt1) ->
pprIf flags e (altBody alt2) (altBody alt1)
CaseE {expScrutinee = e, expAlternatives = alts} ->
let doc = text "case" <+> pprExpFlagsPrec flags precOuter e $$
text "of" <+> vcat (map (pprAltFlags flags) alts)
in parenthesize precOuter doc prec
CoerceE inf from_t to_t b ->
let coercion_doc = pprType from_t <+> text "=>" <+> pprType to_t
b_doc = pprExpFlagsPrec flags precOuter b
in hang (text "coerce" <+> parens coercion_doc) 4 b_doc
ArrayE inf ty es ->
let es_doc = punctuate comma $ map (pprExpFlagsPrec flags precOuter) es
in text "array" <+> parens (pprType ty) <+> braces (fsep es_doc)
where
is_true (VarDeCon op _ _) = op `isCoreBuiltin` The_True
is_true _ = False
is_false (VarDeCon op _ _) = op `isCoreBuiltin` The_False
is_false _ = False
pprIf flags cond tr fa =
let condText = pprExpFlags flags cond
trText = pprExpFlags flags tr
faText = pprExpFlags flags fa
in text "if" <+> condText $$
text "then" <+> trText $$
text "else" <+> faText
pprAltFlags :: PrintFlags -> AltSF -> Doc
pprAltFlags flags (AltSF (Alt con ty_ob_param params body)) =
let pattern =
case con
of VarDeCon op ty_args ex_types ->
let ty_args_doc = map (text "@" <>) $ map pprType ty_args
ty_ob_doc = maybe empty (brackets . pprPatFlags flags) ty_ob_param
params_doc = [parens $ pprPatFlags flags p | p <- params]
in pprVar op <+> sep (ty_args_doc ++ [ty_ob_doc] ++ params_doc)
TupleDeCon _
| isJust ty_ob_param ->
internalError "pprAltFlags: Unexpected parameter"
TupleDeCon _ ->
parens $ sep $ punctuate (text ",") $
map (pprPatFlags flags) params
body_doc = pprExpFlagsPrec flags precOuter body
in hang (pattern <> text ".") 2 body_doc
lambda = text "lambda"
pprFunParameters :: Bool -> PrintFlags -> FunSF -> Doc
pprFunParameters isLambda flags (FunSF fun) = sep param_doc
where
param_doc =
map ty_param (funTyParams fun) ++
map (parens . pprPatFlags flags) (funParams fun) ++
[introduce_return_type $ pprType (funReturn fun)]
introduce_return_type t
| isLambda = nest (-3) $ text "->" <+> t
| otherwise = nest (-2) $ colon <+> t
ty_param p = text "@" <> parens (pprTyPatFlags flags p)
pprFunFlags :: PrintFlags -> FunSF -> Doc
pprFunFlags flags fun =
let params = pprFunParameters True flags fun
body = pprExpFlags flags $ funBody (fromFunSF fun)
in hang (lambda <+> params <> text ".") 4 body
pprFDefFlags flags (Def v _ fun) =
let params = pprFunParameters False flags fun
body = pprExpFlags flags $ funBody (fromFunSF fun)
in hang (pprVarFlags flags v <+> params <+> equals) 4 body
pprGDefFlags flags (Def v a (FunEnt fun)) =
pprFDefFlags flags (Def v a fun)
pprGDefFlags flags (Def v _ (DataEnt const)) =
let type_doc = pprType (constType const)
value = pprExpFlags flags $ constExp const
in hang (pprVarFlags flags v <+> colon <+> type_doc <+> equals) 4 value
|
d01ed6b18006b1077df18b5e639302a17d5380a1b4cca60d4b8e897ae344bd4e | ULTRAKID/emqx_plugin_kafka | emqx_plugin_kafka_app.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2019 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_plugin_kafka_app).
-behaviour(application).
-emqx_plugin(?MODULE).
-export([ start/2
, stop/1
]).
start(_StartType, _StartArgs) ->
{ok, Sup} = emqx_plugin_kafka_sup:start_link(),
emqx_plugin_kafka:load(application:get_all_env()),
{ok, Sup}.
stop(_State) ->
emqx_plugin_kafka:unload().
| null | https://raw.githubusercontent.com/ULTRAKID/emqx_plugin_kafka/0ef6cd954e53be63b786725b6b39ec3016c527db/src/emqx_plugin_kafka_app.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------- | Copyright ( c ) 2019 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_plugin_kafka_app).
-behaviour(application).
-emqx_plugin(?MODULE).
-export([ start/2
, stop/1
]).
start(_StartType, _StartArgs) ->
{ok, Sup} = emqx_plugin_kafka_sup:start_link(),
emqx_plugin_kafka:load(application:get_all_env()),
{ok, Sup}.
stop(_State) ->
emqx_plugin_kafka:unload().
|
837d5d49338735538c04e7580ba270d56c89cf87b50802fa2884bb2bfcf82821 | kowainik/colourista | Colourista.hs | # LANGUAGE ImplicitParams #
module Test.Colourista
( colouristaSpec
) where
import Data.ByteString (ByteString)
import Data.Text (Text)
import Test.Hspec (Spec, describe, it, shouldBe)
import Colourista (formatWith, italic, red, reset, yellow)
import Colourista.Short (b, i, u)
colouristaSpec :: Spec
colouristaSpec = describe "Colourista tests" $ do
describe "Colour codes are actual strings" $ do
it "Yellow: String" $
yellow @String `shouldBe` "\ESC[93m"
it "Yellow: Text" $
yellow @Text `shouldBe` "\ESC[93m"
it "Yellow: ByteString" $
yellow @ByteString `shouldBe` "\ESC[93m"
it "Reset: Text" $
reset @Text `shouldBe` "\ESC[0m"
describe "Colourista.Short" $ do
it "Bold" $
b @Text "bold" `shouldBe` "\ESC[1mbold\ESC[0m"
it "Italic" $
i @Text "italic" `shouldBe` "\ESC[3mitalic\ESC[0m"
it "Underline" $
u @Text "underline" `shouldBe` "\ESC[4munderline\ESC[0m"
describe "'formatWith' works" $ do
it "Format with empty list" $
formatWith @Text [] "text" `shouldBe` "text"
it "Format with red italic" $
formatWith @Text [red, italic] "text" `shouldBe` "\ESC[91m\ESC[3mtext\ESC[0m"
| null | https://raw.githubusercontent.com/kowainik/colourista/704c2f1c1ffb4f96a863d36922c0fddec42043e7/test/Test/Colourista.hs | haskell | # LANGUAGE ImplicitParams #
module Test.Colourista
( colouristaSpec
) where
import Data.ByteString (ByteString)
import Data.Text (Text)
import Test.Hspec (Spec, describe, it, shouldBe)
import Colourista (formatWith, italic, red, reset, yellow)
import Colourista.Short (b, i, u)
colouristaSpec :: Spec
colouristaSpec = describe "Colourista tests" $ do
describe "Colour codes are actual strings" $ do
it "Yellow: String" $
yellow @String `shouldBe` "\ESC[93m"
it "Yellow: Text" $
yellow @Text `shouldBe` "\ESC[93m"
it "Yellow: ByteString" $
yellow @ByteString `shouldBe` "\ESC[93m"
it "Reset: Text" $
reset @Text `shouldBe` "\ESC[0m"
describe "Colourista.Short" $ do
it "Bold" $
b @Text "bold" `shouldBe` "\ESC[1mbold\ESC[0m"
it "Italic" $
i @Text "italic" `shouldBe` "\ESC[3mitalic\ESC[0m"
it "Underline" $
u @Text "underline" `shouldBe` "\ESC[4munderline\ESC[0m"
describe "'formatWith' works" $ do
it "Format with empty list" $
formatWith @Text [] "text" `shouldBe` "text"
it "Format with red italic" $
formatWith @Text [red, italic] "text" `shouldBe` "\ESC[91m\ESC[3mtext\ESC[0m"
|
|
b31958f09ce732f7ecc43ddbdd3b1171c946ca73ac8855e9c19cfb0365f2353d | GaloisInc/macaw | PersistentState.hs | |
Copyright : ( c ) Galois , Inc 2015 - 2017
Maintainer : < >
This defines the monad used to map Reopt blocks to Crucible .
Copyright : (c) Galois, Inc 2015-2017
Maintainer : Joe Hendrix <>
This defines the monad used to map Reopt blocks to Crucible.
-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Data.Macaw.Symbolic.PersistentState
( -- * CrucPersistentState
CrucPersistentState(..)
, initCrucPersistentState
-- * Types
, ToCrucibleType
, ToCrucibleFloatInfo
, FromCrucibleFloatInfo
, CtxToCrucibleType
, ArchRegContext
, typeToCrucible
, floatInfoToCrucible
, floatInfoFromCrucible
, typeCtxToCrucible
, macawListSize
, macawListIndexToCrucible
, macawListToCrucible
, macawListToCrucibleM
, typeListToCrucible
, macawAssignToCruc
, macawAssignToCrucM
, memReprToCrucible
-- * Register index map
, RegIndexMap
, mkRegIndexMap
, IndexPair(..)
-- * Values
, MacawCrucibleValue(..)
) where
import qualified Data.Kind as K
import qualified Data.Macaw.CFG as M
import qualified Data.Macaw.Types as M
import Data.Parameterized.Classes
import Data.Parameterized.Context
import qualified Data.Parameterized.List as P
import Data.Parameterized.Map (MapF)
import qualified Data.Parameterized.Map as MapF
import Data.Parameterized.Nonce (NonceGenerator)
import Data.Parameterized.TraversableF
import Data.Parameterized.TraversableFC
import qualified Lang.Crucible.CFG.Reg as CR
import qualified Lang.Crucible.LLVM.MemModel as MM
import qualified Lang.Crucible.Types as C
------------------------------------------------------------------------
-- Type mappings
| float types into Crucible float types
type family ToCrucibleFloatInfo (fi :: M.FloatInfo) :: C.FloatInfo where
ToCrucibleFloatInfo M.HalfFloat = C.HalfFloat
ToCrucibleFloatInfo M.SingleFloat = C.SingleFloat
ToCrucibleFloatInfo M.DoubleFloat = C.DoubleFloat
ToCrucibleFloatInfo M.QuadFloat = C.QuadFloat
ToCrucibleFloatInfo M.X86_80Float = C.X86_80Float
type family ToCrucibleTypeList (l :: [M.Type]) :: Ctx C.CrucibleType where
ToCrucibleTypeList '[] = EmptyCtx
ToCrucibleTypeList (h ': l) = ToCrucibleTypeList l ::> ToCrucibleType h
| A type family that converts types ( ' M.Type ' ) into Crucible types
( ' C.CrucibleType ' )
--
-- Most values are of type 'M.BVType' (bitvectors) - these are represented in
Crucible as ' MM.LLVMPointerType ' , which are special bitvectors that can also
be pointers in the memory model .
type family ToCrucibleType (tp :: M.Type) :: C.CrucibleType where
ToCrucibleType (M.BVType w) = MM.LLVMPointerType w
ToCrucibleType (M.FloatType fi) = C.FloatType (ToCrucibleFloatInfo fi)
ToCrucibleType ('M.TupleType l) = C.StructType (ToCrucibleTypeList l)
ToCrucibleType M.BoolType = C.BaseToType C.BaseBoolType
ToCrucibleType ('M.VecType n tp) = C.VectorType (ToCrucibleType tp)
| Convert Crucible float types into float types
type family FromCrucibleFloatInfo (fi :: C.FloatInfo) :: M.FloatInfo where
FromCrucibleFloatInfo C.HalfFloat = M.HalfFloat
FromCrucibleFloatInfo C.SingleFloat = M.SingleFloat
FromCrucibleFloatInfo C.DoubleFloat = M.DoubleFloat
FromCrucibleFloatInfo C.QuadFloat = M.QuadFloat
FromCrucibleFloatInfo C.X86_80Float = M.X86_80Float
type family CtxToCrucibleType (mtp :: Ctx M.Type) :: Ctx C.CrucibleType where
CtxToCrucibleType EmptyCtx = EmptyCtx
CtxToCrucibleType (c ::> tp) = CtxToCrucibleType c ::> ToCrucibleType tp
-- | Create the variables from a collection of registers.
macawAssignToCruc ::
(forall tp . f tp -> g (ToCrucibleType tp)) ->
Assignment f ctx ->
Assignment g (CtxToCrucibleType ctx)
macawAssignToCruc f a =
case a of
Empty -> empty
b :> x -> macawAssignToCruc f b :> f x
| Convert a ' Ctx . Assignment ' of macaw values into a ' Ctx . Assignment ' of Crucible values
macawAssignToCrucM :: Applicative m
=> (forall tp . f tp -> m (g (ToCrucibleType tp)))
-> Assignment f ctx
-> m (Assignment g (CtxToCrucibleType ctx))
macawAssignToCrucM f a =
case a of
Empty -> pure empty
b :> x -> (:>) <$> macawAssignToCrucM f b <*> f x
| run - time type representatives into their Crucible equivalents
typeToCrucible :: M.TypeRepr tp -> C.TypeRepr (ToCrucibleType tp)
typeToCrucible tp =
case tp of
M.BoolTypeRepr -> C.BoolRepr
M.BVTypeRepr w -> MM.LLVMPointerRepr w
M.FloatTypeRepr fi -> C.FloatRepr $ floatInfoToCrucible fi
M.TupleTypeRepr a -> C.StructRepr (typeListToCrucible a)
M.VecTypeRepr _n e -> C.VectorRepr (typeToCrucible e)
| floating point run - time representatives into their Crucible equivalents
floatInfoToCrucible
:: M.FloatInfoRepr fi -> C.FloatInfoRepr (ToCrucibleFloatInfo fi)
floatInfoToCrucible = \case
M.HalfFloatRepr -> knownRepr
M.SingleFloatRepr -> knownRepr
M.DoubleFloatRepr -> knownRepr
M.QuadFloatRepr -> knownRepr
M.X86_80FloatRepr -> knownRepr
| Convert Crucible floating point run - time representatives into their Macaw equivalents
floatInfoFromCrucible
:: C.FloatInfoRepr fi -> M.FloatInfoRepr (FromCrucibleFloatInfo fi)
floatInfoFromCrucible = \case
C.HalfFloatRepr -> knownRepr
C.SingleFloatRepr -> knownRepr
C.DoubleFloatRepr -> knownRepr
C.QuadFloatRepr -> knownRepr
C.X86_80FloatRepr -> knownRepr
fi ->
error $ "Unsupported Crucible floating-point format in Macaw: " ++ show fi
| Convert a list over types to a context over crucible types .
--
-- N.B. The order of elements is reversed.
macawListToCrucible :: (forall tp . a tp -> b (ToCrucibleType tp))
-> P.List a ctx
-> Assignment b (ToCrucibleTypeList ctx)
macawListToCrucible f x =
case x of
P.Nil -> Empty
h P.:< r -> macawListToCrucible f r :> f h
| Convert a list over types to a context over crucible types .
--
-- N.B. The order of elements is reversed.
macawListToCrucibleM :: Applicative m
=> (forall tp . a tp -> m (b (ToCrucibleType tp)))
-> P.List a ctx
-> m (Assignment b (ToCrucibleTypeList ctx))
macawListToCrucibleM f x =
case x of
P.Nil -> pure Empty
h P.:< r -> (:>) <$> macawListToCrucibleM f r <*> f h
macawListSize :: P.List a ctx -> Size (ToCrucibleTypeList ctx)
macawListSize P.Nil = zeroSize
macawListSize (_ P.:< r) = incSize (macawListSize r)
macawListIndexToCrucible :: Size (ToCrucibleTypeList ctx) -> P.Index ctx tp -> Index (ToCrucibleTypeList ctx) (ToCrucibleType tp)
macawListIndexToCrucible sz P.IndexHere = lastIndex sz
macawListIndexToCrucible sz (P.IndexThere x) = skipIndex (macawListIndexToCrucible (decSize sz) x)
typeListToCrucible :: P.List M.TypeRepr ctx -> Assignment C.TypeRepr (ToCrucibleTypeList ctx)
typeListToCrucible = macawListToCrucible typeToCrucible
-- | Return the types associated with a register assignment.
typeCtxToCrucible ::
Assignment M.TypeRepr ctx ->
Assignment C.TypeRepr (CtxToCrucibleType ctx)
typeCtxToCrucible = macawAssignToCruc typeToCrucible
memReprToCrucible :: M.MemRepr tp -> C.TypeRepr (ToCrucibleType tp)
memReprToCrucible = typeToCrucible . M.typeRepr
------------------------------------------------------------------------
-- RegIndexMap
-- | Type family for architecture registers
--
-- This specifies the type of each register in the register file for a given architecture. For example,
-- it might be something like
--
> EmptyCtx : :> BVType 64 : :> BVType 64 : :> BVType 32
--
For a hypothetical architecture with two 64 bit general purpose registers and
a single 32 bit flags register .
type family ArchRegContext (arch :: K.Type) :: Ctx M.Type
| This relates an index from macaw to Crucible .
data IndexPair ctx tp = IndexPair
{ macawIndex :: !(Index ctx tp)
, crucibleIndex :: !(Index (CtxToCrucibleType ctx) (ToCrucibleType tp))
}
-- | This extends the indices in the pair.
extendIndexPair :: IndexPair ctx tp -> IndexPair (ctx::>utp) tp
extendIndexPair (IndexPair i j) = IndexPair (extendIndex i) (extendIndex j)
type RegIndexMap arch = MapF (M.ArchReg arch) (IndexPair (ArchRegContext arch))
mkRegIndexMap :: OrdF r
=> Assignment r ctx
-> Size (CtxToCrucibleType ctx)
-> MapF r (IndexPair ctx)
mkRegIndexMap Empty _ = MapF.empty
mkRegIndexMap (a :> r) csz =
case viewSize csz of
IncSize csz0 ->
let m = fmapF extendIndexPair (mkRegIndexMap a csz0)
idx = IndexPair (nextIndex (size a)) (nextIndex csz0)
in MapF.insert r idx m
------------------------------------------------------------------------
-- Misc types
| A Crucible value with a type .
newtype MacawCrucibleValue f tp = MacawCrucibleValue (f (ToCrucibleType tp))
instance FunctorFC MacawCrucibleValue where
fmapFC f (MacawCrucibleValue v) = MacawCrucibleValue (f v)
instance FoldableFC MacawCrucibleValue where
foldrFC f x (MacawCrucibleValue v) = f v x
instance TraversableFC MacawCrucibleValue where
traverseFC f (MacawCrucibleValue v) = MacawCrucibleValue <$> f v
instance ShowF f => ShowF (MacawCrucibleValue f)
instance ShowF f => Show (MacawCrucibleValue f tp) where
showsPrec p (MacawCrucibleValue v) = showsPrecF p v
------------------------------------------------------------------------
-- CrucPersistentState
-- | State that needs to be persisted across block translations
data CrucPersistentState ids s
= CrucPersistentState
{ nonceGen :: NonceGenerator IO s
^ Generator used to get fresh ids for Crucible atoms .
, assignValueMap ::
!(MapF (M.AssignId ids) (MacawCrucibleValue (CR.Atom s)))
^ Map assign i d to associated Crucible value .
}
-- | Initial crucible persistent state
initCrucPersistentState :: NonceGenerator IO s
-> CrucPersistentState ids s
initCrucPersistentState ng =
CrucPersistentState
{ nonceGen = ng
, assignValueMap = MapF.empty
}
| null | https://raw.githubusercontent.com/GaloisInc/macaw/fbd7bce2176ff6ccd22c5d185309bde49d267534/symbolic/src/Data/Macaw/Symbolic/PersistentState.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
* CrucPersistentState
* Types
* Register index map
* Values
----------------------------------------------------------------------
Type mappings
Most values are of type 'M.BVType' (bitvectors) - these are represented in
| Create the variables from a collection of registers.
N.B. The order of elements is reversed.
N.B. The order of elements is reversed.
| Return the types associated with a register assignment.
----------------------------------------------------------------------
RegIndexMap
| Type family for architecture registers
This specifies the type of each register in the register file for a given architecture. For example,
it might be something like
| This extends the indices in the pair.
----------------------------------------------------------------------
Misc types
----------------------------------------------------------------------
CrucPersistentState
| State that needs to be persisted across block translations
| Initial crucible persistent state | |
Copyright : ( c ) Galois , Inc 2015 - 2017
Maintainer : < >
This defines the monad used to map Reopt blocks to Crucible .
Copyright : (c) Galois, Inc 2015-2017
Maintainer : Joe Hendrix <>
This defines the monad used to map Reopt blocks to Crucible.
-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Data.Macaw.Symbolic.PersistentState
CrucPersistentState(..)
, initCrucPersistentState
, ToCrucibleType
, ToCrucibleFloatInfo
, FromCrucibleFloatInfo
, CtxToCrucibleType
, ArchRegContext
, typeToCrucible
, floatInfoToCrucible
, floatInfoFromCrucible
, typeCtxToCrucible
, macawListSize
, macawListIndexToCrucible
, macawListToCrucible
, macawListToCrucibleM
, typeListToCrucible
, macawAssignToCruc
, macawAssignToCrucM
, memReprToCrucible
, RegIndexMap
, mkRegIndexMap
, IndexPair(..)
, MacawCrucibleValue(..)
) where
import qualified Data.Kind as K
import qualified Data.Macaw.CFG as M
import qualified Data.Macaw.Types as M
import Data.Parameterized.Classes
import Data.Parameterized.Context
import qualified Data.Parameterized.List as P
import Data.Parameterized.Map (MapF)
import qualified Data.Parameterized.Map as MapF
import Data.Parameterized.Nonce (NonceGenerator)
import Data.Parameterized.TraversableF
import Data.Parameterized.TraversableFC
import qualified Lang.Crucible.CFG.Reg as CR
import qualified Lang.Crucible.LLVM.MemModel as MM
import qualified Lang.Crucible.Types as C
| float types into Crucible float types
type family ToCrucibleFloatInfo (fi :: M.FloatInfo) :: C.FloatInfo where
ToCrucibleFloatInfo M.HalfFloat = C.HalfFloat
ToCrucibleFloatInfo M.SingleFloat = C.SingleFloat
ToCrucibleFloatInfo M.DoubleFloat = C.DoubleFloat
ToCrucibleFloatInfo M.QuadFloat = C.QuadFloat
ToCrucibleFloatInfo M.X86_80Float = C.X86_80Float
type family ToCrucibleTypeList (l :: [M.Type]) :: Ctx C.CrucibleType where
ToCrucibleTypeList '[] = EmptyCtx
ToCrucibleTypeList (h ': l) = ToCrucibleTypeList l ::> ToCrucibleType h
| A type family that converts types ( ' M.Type ' ) into Crucible types
( ' C.CrucibleType ' )
Crucible as ' MM.LLVMPointerType ' , which are special bitvectors that can also
be pointers in the memory model .
type family ToCrucibleType (tp :: M.Type) :: C.CrucibleType where
ToCrucibleType (M.BVType w) = MM.LLVMPointerType w
ToCrucibleType (M.FloatType fi) = C.FloatType (ToCrucibleFloatInfo fi)
ToCrucibleType ('M.TupleType l) = C.StructType (ToCrucibleTypeList l)
ToCrucibleType M.BoolType = C.BaseToType C.BaseBoolType
ToCrucibleType ('M.VecType n tp) = C.VectorType (ToCrucibleType tp)
| Convert Crucible float types into float types
type family FromCrucibleFloatInfo (fi :: C.FloatInfo) :: M.FloatInfo where
FromCrucibleFloatInfo C.HalfFloat = M.HalfFloat
FromCrucibleFloatInfo C.SingleFloat = M.SingleFloat
FromCrucibleFloatInfo C.DoubleFloat = M.DoubleFloat
FromCrucibleFloatInfo C.QuadFloat = M.QuadFloat
FromCrucibleFloatInfo C.X86_80Float = M.X86_80Float
type family CtxToCrucibleType (mtp :: Ctx M.Type) :: Ctx C.CrucibleType where
CtxToCrucibleType EmptyCtx = EmptyCtx
CtxToCrucibleType (c ::> tp) = CtxToCrucibleType c ::> ToCrucibleType tp
macawAssignToCruc ::
(forall tp . f tp -> g (ToCrucibleType tp)) ->
Assignment f ctx ->
Assignment g (CtxToCrucibleType ctx)
macawAssignToCruc f a =
case a of
Empty -> empty
b :> x -> macawAssignToCruc f b :> f x
| Convert a ' Ctx . Assignment ' of macaw values into a ' Ctx . Assignment ' of Crucible values
macawAssignToCrucM :: Applicative m
=> (forall tp . f tp -> m (g (ToCrucibleType tp)))
-> Assignment f ctx
-> m (Assignment g (CtxToCrucibleType ctx))
macawAssignToCrucM f a =
case a of
Empty -> pure empty
b :> x -> (:>) <$> macawAssignToCrucM f b <*> f x
| run - time type representatives into their Crucible equivalents
typeToCrucible :: M.TypeRepr tp -> C.TypeRepr (ToCrucibleType tp)
typeToCrucible tp =
case tp of
M.BoolTypeRepr -> C.BoolRepr
M.BVTypeRepr w -> MM.LLVMPointerRepr w
M.FloatTypeRepr fi -> C.FloatRepr $ floatInfoToCrucible fi
M.TupleTypeRepr a -> C.StructRepr (typeListToCrucible a)
M.VecTypeRepr _n e -> C.VectorRepr (typeToCrucible e)
| floating point run - time representatives into their Crucible equivalents
floatInfoToCrucible
:: M.FloatInfoRepr fi -> C.FloatInfoRepr (ToCrucibleFloatInfo fi)
floatInfoToCrucible = \case
M.HalfFloatRepr -> knownRepr
M.SingleFloatRepr -> knownRepr
M.DoubleFloatRepr -> knownRepr
M.QuadFloatRepr -> knownRepr
M.X86_80FloatRepr -> knownRepr
| Convert Crucible floating point run - time representatives into their Macaw equivalents
floatInfoFromCrucible
:: C.FloatInfoRepr fi -> M.FloatInfoRepr (FromCrucibleFloatInfo fi)
floatInfoFromCrucible = \case
C.HalfFloatRepr -> knownRepr
C.SingleFloatRepr -> knownRepr
C.DoubleFloatRepr -> knownRepr
C.QuadFloatRepr -> knownRepr
C.X86_80FloatRepr -> knownRepr
fi ->
error $ "Unsupported Crucible floating-point format in Macaw: " ++ show fi
| Convert a list over types to a context over crucible types .
macawListToCrucible :: (forall tp . a tp -> b (ToCrucibleType tp))
-> P.List a ctx
-> Assignment b (ToCrucibleTypeList ctx)
macawListToCrucible f x =
case x of
P.Nil -> Empty
h P.:< r -> macawListToCrucible f r :> f h
| Convert a list over types to a context over crucible types .
macawListToCrucibleM :: Applicative m
=> (forall tp . a tp -> m (b (ToCrucibleType tp)))
-> P.List a ctx
-> m (Assignment b (ToCrucibleTypeList ctx))
macawListToCrucibleM f x =
case x of
P.Nil -> pure Empty
h P.:< r -> (:>) <$> macawListToCrucibleM f r <*> f h
macawListSize :: P.List a ctx -> Size (ToCrucibleTypeList ctx)
macawListSize P.Nil = zeroSize
macawListSize (_ P.:< r) = incSize (macawListSize r)
macawListIndexToCrucible :: Size (ToCrucibleTypeList ctx) -> P.Index ctx tp -> Index (ToCrucibleTypeList ctx) (ToCrucibleType tp)
macawListIndexToCrucible sz P.IndexHere = lastIndex sz
macawListIndexToCrucible sz (P.IndexThere x) = skipIndex (macawListIndexToCrucible (decSize sz) x)
typeListToCrucible :: P.List M.TypeRepr ctx -> Assignment C.TypeRepr (ToCrucibleTypeList ctx)
typeListToCrucible = macawListToCrucible typeToCrucible
typeCtxToCrucible ::
Assignment M.TypeRepr ctx ->
Assignment C.TypeRepr (CtxToCrucibleType ctx)
typeCtxToCrucible = macawAssignToCruc typeToCrucible
memReprToCrucible :: M.MemRepr tp -> C.TypeRepr (ToCrucibleType tp)
memReprToCrucible = typeToCrucible . M.typeRepr
> EmptyCtx : :> BVType 64 : :> BVType 64 : :> BVType 32
For a hypothetical architecture with two 64 bit general purpose registers and
a single 32 bit flags register .
type family ArchRegContext (arch :: K.Type) :: Ctx M.Type
| This relates an index from macaw to Crucible .
data IndexPair ctx tp = IndexPair
{ macawIndex :: !(Index ctx tp)
, crucibleIndex :: !(Index (CtxToCrucibleType ctx) (ToCrucibleType tp))
}
extendIndexPair :: IndexPair ctx tp -> IndexPair (ctx::>utp) tp
extendIndexPair (IndexPair i j) = IndexPair (extendIndex i) (extendIndex j)
type RegIndexMap arch = MapF (M.ArchReg arch) (IndexPair (ArchRegContext arch))
mkRegIndexMap :: OrdF r
=> Assignment r ctx
-> Size (CtxToCrucibleType ctx)
-> MapF r (IndexPair ctx)
mkRegIndexMap Empty _ = MapF.empty
mkRegIndexMap (a :> r) csz =
case viewSize csz of
IncSize csz0 ->
let m = fmapF extendIndexPair (mkRegIndexMap a csz0)
idx = IndexPair (nextIndex (size a)) (nextIndex csz0)
in MapF.insert r idx m
| A Crucible value with a type .
newtype MacawCrucibleValue f tp = MacawCrucibleValue (f (ToCrucibleType tp))
instance FunctorFC MacawCrucibleValue where
fmapFC f (MacawCrucibleValue v) = MacawCrucibleValue (f v)
instance FoldableFC MacawCrucibleValue where
foldrFC f x (MacawCrucibleValue v) = f v x
instance TraversableFC MacawCrucibleValue where
traverseFC f (MacawCrucibleValue v) = MacawCrucibleValue <$> f v
instance ShowF f => ShowF (MacawCrucibleValue f)
instance ShowF f => Show (MacawCrucibleValue f tp) where
showsPrec p (MacawCrucibleValue v) = showsPrecF p v
data CrucPersistentState ids s
= CrucPersistentState
{ nonceGen :: NonceGenerator IO s
^ Generator used to get fresh ids for Crucible atoms .
, assignValueMap ::
!(MapF (M.AssignId ids) (MacawCrucibleValue (CR.Atom s)))
^ Map assign i d to associated Crucible value .
}
initCrucPersistentState :: NonceGenerator IO s
-> CrucPersistentState ids s
initCrucPersistentState ng =
CrucPersistentState
{ nonceGen = ng
, assignValueMap = MapF.empty
}
|
c201a0d626affebb5859c2198cb7a7fd9996e3db61d9de29c8293c7c493e06b9 | Frama-C/Frama-C-snapshot | inout_domain.mli | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** Computation of inputs of outputs. *)
module D: Abstract_domain.Leaf
with type value = Cvalue.V.t
and type location = Precise_locs.precise_location
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/domains/inout_domain.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* Computation of inputs of outputs. | This file is part of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
module D: Abstract_domain.Leaf
with type value = Cvalue.V.t
and type location = Precise_locs.precise_location
|
7f158c8206c2253b92c0c8bc1fdbc05cabfe78e7ef4853b39688feeafb740f05 | nasa/Common-Metadata-Repository | user.clj | (ns user
"A dev namespace that supports Proto-REPL.
It seems that Proto-REPL doesn't support the flexible approach that lein
uses: any configurable ns can be the starting ns for a REPL. As such, this
minimal ns was created for Proto-REPL users, so they too can have an env
that supports startup and shutdown."
(:require
[cheshire.core :as json]
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[cmr.metadata.proxy.repl :as dev]
[org.httpkit.client :as httpc]))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/metadata-proxy/dev-resources/src/user.clj | clojure | (ns user
"A dev namespace that supports Proto-REPL.
It seems that Proto-REPL doesn't support the flexible approach that lein
uses: any configurable ns can be the starting ns for a REPL. As such, this
minimal ns was created for Proto-REPL users, so they too can have an env
that supports startup and shutdown."
(:require
[cheshire.core :as json]
[clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.tools.namespace.repl :as repl]
[clojusc.system-manager.core :refer :all]
[cmr.metadata.proxy.repl :as dev]
[org.httpkit.client :as httpc]))
|
|
74f4edd816035340e0dd0bb5fffd58124b5b48cbd7c787574b5a7fe826067049 | tonymorris/geo-gpx | TextL.hs | module Data.Geo.GPX.Lens.TextL where
import Data.Lens.Common
class TextL a where
textL :: Lens a (Maybe String)
| null | https://raw.githubusercontent.com/tonymorris/geo-gpx/526b59ec403293c810c2ba08d2c006dc526e8bf9/src/Data/Geo/GPX/Lens/TextL.hs | haskell | module Data.Geo.GPX.Lens.TextL where
import Data.Lens.Common
class TextL a where
textL :: Lens a (Maybe String)
|
|
747b9d6b9e849f600e517a2663c81ab0e955f206dcad017eeeb2b8000d4e1e4d | emqx/emqx | emqx_delayed.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 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_delayed).
-behaviour(gen_server).
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/types.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("snabbkaffe/include/snabbkaffe.hrl").
-include_lib("emqx/include/emqx_hooks.hrl").
Mnesia bootstrap
-export([mnesia/1]).
-boot_mnesia({mnesia, [boot]}).
-export([
start_link/0,
on_message_publish/1
]).
%% gen_server callbacks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
%% gen_server callbacks
-export([
load/0,
unload/0,
load_or_unload/1,
get_conf/1,
update_config/1,
list/1,
get_delayed_message/1,
get_delayed_message/2,
delete_delayed_message/1,
delete_delayed_message/2,
cluster_list/1
]).
%% exports for query
-export([
qs2ms/2,
format_delayed/1,
format_delayed/2
]).
-export([
post_config_update/5
]).
%% exported for `emqx_telemetry'
-export([get_basic_usage_info/0]).
-record(delayed_message, {key, delayed, msg}).
-type delayed_message() :: #delayed_message{}.
-type with_id_return() :: ok | {error, not_found}.
-type with_id_return(T) :: {ok, T} | {error, not_found}.
-export_type([with_id_return/0, with_id_return/1]).
-type state() :: #{
publish_timer := maybe(timer:tref()),
publish_at := non_neg_integer(),
stats_timer := maybe(reference()),
stats_fun := maybe(fun((pos_integer()) -> ok))
}.
%% sync ms with record change
-define(QUERY_MS(Id), [{{delayed_message, {'_', Id}, '_', '_'}, [], ['$_']}]).
-define(DELETE_MS(Id), [{{delayed_message, {'$1', Id}, '_', '_'}, [], ['$1']}]).
-define(TAB, ?MODULE).
-define(SERVER, ?MODULE).
-define(MAX_INTERVAL, 4294967).
-define(FORMAT_FUN, {?MODULE, format_delayed}).
-define(NOW, erlang:system_time(milli_seconds)).
%%--------------------------------------------------------------------
Mnesia bootstrap
%%--------------------------------------------------------------------
mnesia(boot) ->
ok = mria:create_table(?TAB, [
{type, ordered_set},
{storage, disc_copies},
{local_content, true},
{record_name, delayed_message},
{attributes, record_info(fields, delayed_message)}
]).
%%--------------------------------------------------------------------
%% Hooks
%%--------------------------------------------------------------------
on_message_publish(
Msg = #message{
id = Id,
topic = <<"$delayed/", Topic/binary>>,
timestamp = Ts
}
) ->
[Delay, Topic1] = binary:split(Topic, <<"/">>),
{PubAt, Delayed} =
case binary_to_integer(Delay) of
Interval when Interval < ?MAX_INTERVAL ->
{Interval * 1000 + Ts, Interval};
Timestamp ->
%% Check malicious timestamp?
Internal = Timestamp - erlang:round(Ts / 1000),
case Internal > ?MAX_INTERVAL of
true -> error(invalid_delayed_timestamp);
false -> {Timestamp * 1000, Internal}
end
end,
PubMsg = Msg#message{topic = Topic1},
Headers = PubMsg#message.headers,
case store(#delayed_message{key = {PubAt, Id}, delayed = Delayed, msg = PubMsg}) of
ok -> ok;
{error, Error} -> ?SLOG(error, #{msg => "store_delayed_message_fail", error => Error})
end,
{stop, PubMsg#message{headers = Headers#{allow_publish => false}}};
on_message_publish(Msg) ->
{ok, Msg}.
%%--------------------------------------------------------------------
%% Start delayed publish server
%%--------------------------------------------------------------------
-spec start_link() -> emqx_types:startlink_ret().
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
-spec store(delayed_message()) -> ok | {error, atom()}.
store(DelayedMsg) ->
gen_server:call(?SERVER, {store, DelayedMsg}, infinity).
get_conf(Key) ->
emqx_conf:get([delayed, Key]).
load() ->
load_or_unload(true).
unload() ->
load_or_unload(false).
load_or_unload(Bool) ->
gen_server:call(?SERVER, {do_load_or_unload, Bool}).
list(Params) ->
emqx_mgmt_api:paginate(?TAB, Params, ?FORMAT_FUN).
cluster_list(Params) ->
emqx_mgmt_api:cluster_query(
?TAB,
Params,
[],
fun ?MODULE:qs2ms/2,
fun ?MODULE:format_delayed/2
).
-spec qs2ms(atom(), {list(), list()}) -> emqx_mgmt_api:match_spec_and_filter().
qs2ms(_Table, {_Qs, _Fuzzy}) ->
#{
match_spec => [{'$1', [], ['$1']}],
fuzzy_fun => undefined
}.
format_delayed(Delayed) ->
format_delayed(node(), Delayed).
format_delayed(WhichNode, Delayed) ->
format_delayed(WhichNode, Delayed, false).
format_delayed(
WhichNode,
#delayed_message{
key = {ExpectTimeStamp, Id},
delayed = Delayed,
msg = #message{
topic = Topic,
from = From,
headers = Headers,
qos = Qos,
timestamp = PublishTimeStamp,
payload = Payload
}
},
WithPayload
) ->
PublishTime = to_rfc3339(PublishTimeStamp div 1000),
ExpectTime = to_rfc3339(ExpectTimeStamp div 1000),
RemainingTime = ExpectTimeStamp - ?NOW,
Result = #{
msgid => emqx_guid:to_hexstr(Id),
node => WhichNode,
publish_at => PublishTime,
delayed_interval => Delayed,
delayed_remaining => RemainingTime div 1000,
expected_at => ExpectTime,
topic => Topic,
qos => Qos,
from_clientid => From,
from_username => maps:get(username, Headers, undefined)
},
case WithPayload of
true ->
Result#{payload => Payload};
_ ->
Result
end.
to_rfc3339(Timestamp) ->
list_to_binary(calendar:system_time_to_rfc3339(Timestamp, [{unit, second}])).
-spec get_delayed_message(binary()) -> with_id_return(map()).
get_delayed_message(Id) ->
case ets:select(?TAB, ?QUERY_MS(Id)) of
[] ->
{error, not_found};
Rows ->
Message = hd(Rows),
{ok, format_delayed(node(), Message, true)}
end.
get_delayed_message(Node, Id) when Node =:= node() ->
get_delayed_message(Id);
get_delayed_message(Node, Id) ->
emqx_delayed_proto_v1:get_delayed_message(Node, Id).
-spec delete_delayed_message(binary()) -> with_id_return().
delete_delayed_message(Id) ->
case ets:select(?TAB, ?DELETE_MS(Id)) of
[] ->
{error, not_found};
Rows ->
Timestamp = hd(Rows),
mria:dirty_delete(?TAB, {Timestamp, Id})
end.
delete_delayed_message(Node, Id) when Node =:= node() ->
delete_delayed_message(Id);
delete_delayed_message(Node, Id) ->
emqx_delayed_proto_v1:delete_delayed_message(Node, Id).
update_config(Config) ->
emqx_conf:update([delayed], Config, #{rawconf_with_defaults => true, override_to => cluster}).
post_config_update(_KeyPath, _ConfigReq, NewConf, _OldConf, _AppEnvs) ->
Enable = maps:get(enable, NewConf, undefined),
load_or_unload(Enable).
%%--------------------------------------------------------------------
%% gen_server callback
%%--------------------------------------------------------------------
init([]) ->
ok = mria:wait_for_tables([?TAB]),
erlang:process_flag(trap_exit, true),
emqx_conf:add_handler([delayed], ?MODULE),
State =
ensure_stats_event(
ensure_publish_timer(#{
publish_timer => undefined,
publish_at => 0,
stats_timer => undefined,
stats_fun => undefined
})
),
{ok, do_load_or_unload(emqx:get_config([delayed, enable]), State)}.
handle_call({store, DelayedMsg = #delayed_message{key = Key}}, _From, State) ->
Size = mnesia:table_info(?TAB, size),
case get_conf(max_delayed_messages) of
0 ->
ok = mria:dirty_write(?TAB, DelayedMsg),
emqx_metrics:inc('messages.delayed'),
{reply, ok, ensure_publish_timer(Key, State)};
Max when Size >= Max ->
{reply, {error, max_delayed_messages_full}, State};
Max when Size < Max ->
ok = mria:dirty_write(?TAB, DelayedMsg),
emqx_metrics:inc('messages.delayed'),
{reply, ok, ensure_publish_timer(Key, State)}
end;
handle_call({do_load_or_unload, Bool}, _From, State0) ->
State = do_load_or_unload(Bool, State0),
{reply, ok, State};
handle_call(Req, _From, State) ->
?tp(error, emqx_delayed_unexpected_call, #{call => Req}),
{reply, ignored, State}.
handle_cast(Msg, State) ->
?tp(error, emqx_delayed_unexpected_cast, #{cast => Msg}),
{noreply, State}.
%% Do Publish...
handle_info({timeout, TRef, do_publish}, State = #{publish_timer := TRef}) ->
DeletedKeys = do_publish(mnesia:dirty_first(?TAB), ?NOW),
lists:foreach(fun(Key) -> mria:dirty_delete(?TAB, Key) end, DeletedKeys),
{noreply, ensure_publish_timer(State#{publish_timer := undefined, publish_at := 0})};
handle_info(stats, State = #{stats_fun := StatsFun}) ->
StatsTimer = erlang:send_after(timer:seconds(1), self(), stats),
StatsFun(delayed_count()),
{noreply, State#{stats_timer := StatsTimer}, hibernate};
handle_info(Info, State) ->
?tp(error, emqx_delayed_unexpected_info, #{info => Info}),
{noreply, State}.
terminate(_Reason, #{stats_timer := StatsTimer} = State) ->
emqx_conf:remove_handler([delayed]),
emqx_misc:cancel_timer(StatsTimer),
do_load_or_unload(false, State).
code_change(_Vsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
%% Telemetry
%%--------------------------------------------------------------------
-spec get_basic_usage_info() -> #{delayed_message_count => non_neg_integer()}.
get_basic_usage_info() ->
DelayedCount =
case ets:info(?TAB, size) of
undefined -> 0;
Num -> Num
end,
#{delayed_message_count => DelayedCount}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
%% Ensure the stats
-spec ensure_stats_event(state()) -> state().
ensure_stats_event(State) ->
StatsFun = emqx_stats:statsfun('delayed.count', 'delayed.max'),
StatsTimer = erlang:send_after(timer:seconds(1), self(), stats),
State#{stats_fun := StatsFun, stats_timer := StatsTimer}.
%% Ensure publish timer
-spec ensure_publish_timer(state()) -> state().
ensure_publish_timer(State) ->
ensure_publish_timer(mnesia:dirty_first(?TAB), State).
ensure_publish_timer('$end_of_table', State) ->
State#{publish_timer := undefined, publish_at := 0};
ensure_publish_timer({Ts, _Id}, State = #{publish_timer := undefined}) ->
ensure_publish_timer(Ts, ?NOW, State);
ensure_publish_timer({Ts, _Id}, State = #{publish_timer := TRef, publish_at := PubAt}) when
Ts < PubAt
->
ok = emqx_misc:cancel_timer(TRef),
ensure_publish_timer(Ts, ?NOW, State);
ensure_publish_timer(_Key, State) ->
State.
ensure_publish_timer(Ts, Now, State) ->
Interval = max(1, Ts - Now),
TRef = emqx_misc:start_timer(Interval, do_publish),
State#{publish_timer := TRef, publish_at := Now + Interval}.
do_publish(Key, Now) ->
do_publish(Key, Now, []).
%% Do publish
do_publish('$end_of_table', _Now, Acc) ->
Acc;
do_publish({Ts, _Id}, Now, Acc) when Ts > Now ->
Acc;
do_publish(Key = {Ts, _Id}, Now, Acc) when Ts =< Now ->
case mnesia:dirty_read(?TAB, Key) of
[] ->
ok;
[#delayed_message{msg = Msg}] ->
case emqx_banned:look_up({clientid, Msg#message.from}) of
[] ->
emqx_pool:async_submit(fun emqx:publish/1, [Msg]);
_ ->
?tp(
notice,
ignore_delayed_message_publish,
#{
reason => "client is banned",
clienid => Msg#message.from
}
),
ok
end
end,
do_publish(mnesia:dirty_next(?TAB, Key), Now, [Key | Acc]).
-spec delayed_count() -> non_neg_integer().
delayed_count() -> mnesia:table_info(?TAB, size).
do_load_or_unload(true, State) ->
emqx_hooks:put('message.publish', {?MODULE, on_message_publish, []}, ?HP_DELAY_PUB),
State;
do_load_or_unload(false, #{publish_timer := PubTimer} = State) ->
emqx_hooks:del('message.publish', {?MODULE, on_message_publish}),
emqx_misc:cancel_timer(PubTimer),
ets:delete_all_objects(?TAB),
State#{publish_timer := undefined, publish_at := 0};
do_load_or_unload(_, State) ->
State.
| null | https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_modules/src/emqx_delayed.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.
--------------------------------------------------------------------
gen_server callbacks
gen_server callbacks
exports for query
exported for `emqx_telemetry'
sync ms with record change
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Hooks
--------------------------------------------------------------------
Check malicious timestamp?
--------------------------------------------------------------------
Start delayed publish server
--------------------------------------------------------------------
--------------------------------------------------------------------
gen_server callback
--------------------------------------------------------------------
Do Publish...
--------------------------------------------------------------------
Telemetry
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Ensure the stats
Ensure publish timer
Do publish | Copyright ( c ) 2020 - 2023 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_delayed).
-behaviour(gen_server).
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/types.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("snabbkaffe/include/snabbkaffe.hrl").
-include_lib("emqx/include/emqx_hooks.hrl").
Mnesia bootstrap
-export([mnesia/1]).
-boot_mnesia({mnesia, [boot]}).
-export([
start_link/0,
on_message_publish/1
]).
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-export([
load/0,
unload/0,
load_or_unload/1,
get_conf/1,
update_config/1,
list/1,
get_delayed_message/1,
get_delayed_message/2,
delete_delayed_message/1,
delete_delayed_message/2,
cluster_list/1
]).
-export([
qs2ms/2,
format_delayed/1,
format_delayed/2
]).
-export([
post_config_update/5
]).
-export([get_basic_usage_info/0]).
-record(delayed_message, {key, delayed, msg}).
-type delayed_message() :: #delayed_message{}.
-type with_id_return() :: ok | {error, not_found}.
-type with_id_return(T) :: {ok, T} | {error, not_found}.
-export_type([with_id_return/0, with_id_return/1]).
-type state() :: #{
publish_timer := maybe(timer:tref()),
publish_at := non_neg_integer(),
stats_timer := maybe(reference()),
stats_fun := maybe(fun((pos_integer()) -> ok))
}.
-define(QUERY_MS(Id), [{{delayed_message, {'_', Id}, '_', '_'}, [], ['$_']}]).
-define(DELETE_MS(Id), [{{delayed_message, {'$1', Id}, '_', '_'}, [], ['$1']}]).
-define(TAB, ?MODULE).
-define(SERVER, ?MODULE).
-define(MAX_INTERVAL, 4294967).
-define(FORMAT_FUN, {?MODULE, format_delayed}).
-define(NOW, erlang:system_time(milli_seconds)).
Mnesia bootstrap
mnesia(boot) ->
ok = mria:create_table(?TAB, [
{type, ordered_set},
{storage, disc_copies},
{local_content, true},
{record_name, delayed_message},
{attributes, record_info(fields, delayed_message)}
]).
on_message_publish(
Msg = #message{
id = Id,
topic = <<"$delayed/", Topic/binary>>,
timestamp = Ts
}
) ->
[Delay, Topic1] = binary:split(Topic, <<"/">>),
{PubAt, Delayed} =
case binary_to_integer(Delay) of
Interval when Interval < ?MAX_INTERVAL ->
{Interval * 1000 + Ts, Interval};
Timestamp ->
Internal = Timestamp - erlang:round(Ts / 1000),
case Internal > ?MAX_INTERVAL of
true -> error(invalid_delayed_timestamp);
false -> {Timestamp * 1000, Internal}
end
end,
PubMsg = Msg#message{topic = Topic1},
Headers = PubMsg#message.headers,
case store(#delayed_message{key = {PubAt, Id}, delayed = Delayed, msg = PubMsg}) of
ok -> ok;
{error, Error} -> ?SLOG(error, #{msg => "store_delayed_message_fail", error => Error})
end,
{stop, PubMsg#message{headers = Headers#{allow_publish => false}}};
on_message_publish(Msg) ->
{ok, Msg}.
-spec start_link() -> emqx_types:startlink_ret().
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
-spec store(delayed_message()) -> ok | {error, atom()}.
store(DelayedMsg) ->
gen_server:call(?SERVER, {store, DelayedMsg}, infinity).
get_conf(Key) ->
emqx_conf:get([delayed, Key]).
load() ->
load_or_unload(true).
unload() ->
load_or_unload(false).
load_or_unload(Bool) ->
gen_server:call(?SERVER, {do_load_or_unload, Bool}).
list(Params) ->
emqx_mgmt_api:paginate(?TAB, Params, ?FORMAT_FUN).
cluster_list(Params) ->
emqx_mgmt_api:cluster_query(
?TAB,
Params,
[],
fun ?MODULE:qs2ms/2,
fun ?MODULE:format_delayed/2
).
-spec qs2ms(atom(), {list(), list()}) -> emqx_mgmt_api:match_spec_and_filter().
qs2ms(_Table, {_Qs, _Fuzzy}) ->
#{
match_spec => [{'$1', [], ['$1']}],
fuzzy_fun => undefined
}.
format_delayed(Delayed) ->
format_delayed(node(), Delayed).
format_delayed(WhichNode, Delayed) ->
format_delayed(WhichNode, Delayed, false).
format_delayed(
WhichNode,
#delayed_message{
key = {ExpectTimeStamp, Id},
delayed = Delayed,
msg = #message{
topic = Topic,
from = From,
headers = Headers,
qos = Qos,
timestamp = PublishTimeStamp,
payload = Payload
}
},
WithPayload
) ->
PublishTime = to_rfc3339(PublishTimeStamp div 1000),
ExpectTime = to_rfc3339(ExpectTimeStamp div 1000),
RemainingTime = ExpectTimeStamp - ?NOW,
Result = #{
msgid => emqx_guid:to_hexstr(Id),
node => WhichNode,
publish_at => PublishTime,
delayed_interval => Delayed,
delayed_remaining => RemainingTime div 1000,
expected_at => ExpectTime,
topic => Topic,
qos => Qos,
from_clientid => From,
from_username => maps:get(username, Headers, undefined)
},
case WithPayload of
true ->
Result#{payload => Payload};
_ ->
Result
end.
to_rfc3339(Timestamp) ->
list_to_binary(calendar:system_time_to_rfc3339(Timestamp, [{unit, second}])).
-spec get_delayed_message(binary()) -> with_id_return(map()).
get_delayed_message(Id) ->
case ets:select(?TAB, ?QUERY_MS(Id)) of
[] ->
{error, not_found};
Rows ->
Message = hd(Rows),
{ok, format_delayed(node(), Message, true)}
end.
get_delayed_message(Node, Id) when Node =:= node() ->
get_delayed_message(Id);
get_delayed_message(Node, Id) ->
emqx_delayed_proto_v1:get_delayed_message(Node, Id).
-spec delete_delayed_message(binary()) -> with_id_return().
delete_delayed_message(Id) ->
case ets:select(?TAB, ?DELETE_MS(Id)) of
[] ->
{error, not_found};
Rows ->
Timestamp = hd(Rows),
mria:dirty_delete(?TAB, {Timestamp, Id})
end.
delete_delayed_message(Node, Id) when Node =:= node() ->
delete_delayed_message(Id);
delete_delayed_message(Node, Id) ->
emqx_delayed_proto_v1:delete_delayed_message(Node, Id).
update_config(Config) ->
emqx_conf:update([delayed], Config, #{rawconf_with_defaults => true, override_to => cluster}).
post_config_update(_KeyPath, _ConfigReq, NewConf, _OldConf, _AppEnvs) ->
Enable = maps:get(enable, NewConf, undefined),
load_or_unload(Enable).
init([]) ->
ok = mria:wait_for_tables([?TAB]),
erlang:process_flag(trap_exit, true),
emqx_conf:add_handler([delayed], ?MODULE),
State =
ensure_stats_event(
ensure_publish_timer(#{
publish_timer => undefined,
publish_at => 0,
stats_timer => undefined,
stats_fun => undefined
})
),
{ok, do_load_or_unload(emqx:get_config([delayed, enable]), State)}.
handle_call({store, DelayedMsg = #delayed_message{key = Key}}, _From, State) ->
Size = mnesia:table_info(?TAB, size),
case get_conf(max_delayed_messages) of
0 ->
ok = mria:dirty_write(?TAB, DelayedMsg),
emqx_metrics:inc('messages.delayed'),
{reply, ok, ensure_publish_timer(Key, State)};
Max when Size >= Max ->
{reply, {error, max_delayed_messages_full}, State};
Max when Size < Max ->
ok = mria:dirty_write(?TAB, DelayedMsg),
emqx_metrics:inc('messages.delayed'),
{reply, ok, ensure_publish_timer(Key, State)}
end;
handle_call({do_load_or_unload, Bool}, _From, State0) ->
State = do_load_or_unload(Bool, State0),
{reply, ok, State};
handle_call(Req, _From, State) ->
?tp(error, emqx_delayed_unexpected_call, #{call => Req}),
{reply, ignored, State}.
handle_cast(Msg, State) ->
?tp(error, emqx_delayed_unexpected_cast, #{cast => Msg}),
{noreply, State}.
handle_info({timeout, TRef, do_publish}, State = #{publish_timer := TRef}) ->
DeletedKeys = do_publish(mnesia:dirty_first(?TAB), ?NOW),
lists:foreach(fun(Key) -> mria:dirty_delete(?TAB, Key) end, DeletedKeys),
{noreply, ensure_publish_timer(State#{publish_timer := undefined, publish_at := 0})};
handle_info(stats, State = #{stats_fun := StatsFun}) ->
StatsTimer = erlang:send_after(timer:seconds(1), self(), stats),
StatsFun(delayed_count()),
{noreply, State#{stats_timer := StatsTimer}, hibernate};
handle_info(Info, State) ->
?tp(error, emqx_delayed_unexpected_info, #{info => Info}),
{noreply, State}.
terminate(_Reason, #{stats_timer := StatsTimer} = State) ->
emqx_conf:remove_handler([delayed]),
emqx_misc:cancel_timer(StatsTimer),
do_load_or_unload(false, State).
code_change(_Vsn, State, _Extra) ->
{ok, State}.
-spec get_basic_usage_info() -> #{delayed_message_count => non_neg_integer()}.
get_basic_usage_info() ->
DelayedCount =
case ets:info(?TAB, size) of
undefined -> 0;
Num -> Num
end,
#{delayed_message_count => DelayedCount}.
Internal functions
-spec ensure_stats_event(state()) -> state().
ensure_stats_event(State) ->
StatsFun = emqx_stats:statsfun('delayed.count', 'delayed.max'),
StatsTimer = erlang:send_after(timer:seconds(1), self(), stats),
State#{stats_fun := StatsFun, stats_timer := StatsTimer}.
-spec ensure_publish_timer(state()) -> state().
ensure_publish_timer(State) ->
ensure_publish_timer(mnesia:dirty_first(?TAB), State).
ensure_publish_timer('$end_of_table', State) ->
State#{publish_timer := undefined, publish_at := 0};
ensure_publish_timer({Ts, _Id}, State = #{publish_timer := undefined}) ->
ensure_publish_timer(Ts, ?NOW, State);
ensure_publish_timer({Ts, _Id}, State = #{publish_timer := TRef, publish_at := PubAt}) when
Ts < PubAt
->
ok = emqx_misc:cancel_timer(TRef),
ensure_publish_timer(Ts, ?NOW, State);
ensure_publish_timer(_Key, State) ->
State.
ensure_publish_timer(Ts, Now, State) ->
Interval = max(1, Ts - Now),
TRef = emqx_misc:start_timer(Interval, do_publish),
State#{publish_timer := TRef, publish_at := Now + Interval}.
do_publish(Key, Now) ->
do_publish(Key, Now, []).
do_publish('$end_of_table', _Now, Acc) ->
Acc;
do_publish({Ts, _Id}, Now, Acc) when Ts > Now ->
Acc;
do_publish(Key = {Ts, _Id}, Now, Acc) when Ts =< Now ->
case mnesia:dirty_read(?TAB, Key) of
[] ->
ok;
[#delayed_message{msg = Msg}] ->
case emqx_banned:look_up({clientid, Msg#message.from}) of
[] ->
emqx_pool:async_submit(fun emqx:publish/1, [Msg]);
_ ->
?tp(
notice,
ignore_delayed_message_publish,
#{
reason => "client is banned",
clienid => Msg#message.from
}
),
ok
end
end,
do_publish(mnesia:dirty_next(?TAB, Key), Now, [Key | Acc]).
-spec delayed_count() -> non_neg_integer().
delayed_count() -> mnesia:table_info(?TAB, size).
do_load_or_unload(true, State) ->
emqx_hooks:put('message.publish', {?MODULE, on_message_publish, []}, ?HP_DELAY_PUB),
State;
do_load_or_unload(false, #{publish_timer := PubTimer} = State) ->
emqx_hooks:del('message.publish', {?MODULE, on_message_publish}),
emqx_misc:cancel_timer(PubTimer),
ets:delete_all_objects(?TAB),
State#{publish_timer := undefined, publish_at := 0};
do_load_or_unload(_, State) ->
State.
|
57102c4f468191eb7ce2c85bfb616ec896d048a518a7dc54f5c4ce7dfb93688d | onyx-platform/onyx | zookeeper.clj | (ns onyx.mocked.zookeeper
(:require [com.stuartsierra.component :as component]
[taoensso.timbre :refer [info error warn fatal]]
[onyx.log.replica]
[onyx.checkpoint :as checkpoint]
[onyx.extensions :as extensions])
(:import [org.apache.zookeeper KeeperException$BadVersionException]))
(defrecord FakeZooKeeper [config]
component/Lifecycle
(start [component] component)
(stop [component] component))
(defn fake-zookeeper [entries store checkpoints config]
(map->FakeZooKeeper {:entries entries
:store store
:checkpoints checkpoints
:entry-num 0
:config config}))
(defmethod extensions/write-log-entry FakeZooKeeper
[log data]
(swap! (:entries log)
(fn [entries]
(conj (vec entries)
(assoc data :message-id (count entries)))))
log)
(defmethod extensions/read-log-entry FakeZooKeeper
[{:keys [entries]} n]
(get @entries n))
(defmethod extensions/register-pulse FakeZooKeeper
[& all])
(defmethod extensions/on-delete FakeZooKeeper
[& all])
(defmethod extensions/group-exists? FakeZooKeeper
[& all]
;; Always show true - we will always manually leave
true)
(defmethod extensions/subscribe-to-log FakeZooKeeper
[log & _]
(onyx.log.replica/starting-replica (:config log)))
(defmethod extensions/write-chunk :default
[log kw chunk id]
(cond
(= :task kw)
(swap! (:store log) assoc [kw id (:id chunk)] chunk)
(= :exception kw)
(do (info "Task Exception:" chunk)
(throw chunk))
:else
(swap! (:store log) assoc [kw id] chunk))
log)
(defmethod extensions/read-chunk :default
[log kw id & rst]
(if (= :task kw)
(get @(:store log) [kw id (first rst)])
(get @(:store log) [kw id])))
(defmethod checkpoint/write-checkpoint FakeZooKeeper
[log tenancy-id job-id replica-version epoch task-id slot-id checkpoint-type checkpoint]
(info "Writing checkpoint:" replica-version epoch task-id slot-id)
(swap! (:checkpoints log)
assoc-in
[tenancy-id :checkpoints job-id [replica-version epoch] [task-id slot-id checkpoint-type]]
checkpoint))
(defmethod checkpoint/complete? FakeZooKeeper
[_]
;; synchronous write means it's already completed
true)
(defmethod checkpoint/cancel! FakeZooKeeper
[_])
(defmethod checkpoint/stop FakeZooKeeper
[log]
;; zookeeper connection is shared with peer group, so we don't want to stop it
log)
(defmethod checkpoint/write-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id coordinate version]
(let [path [tenancy-id :latest job-id]]
(-> (swap! (:checkpoints log)
update-in
path
(fn [v]
(if (= (or (:version v) 0) version)
{:version (inc version)
:coordinate coordinate}
(throw (KeeperException$BadVersionException.
(str "failed write " version " vs " (:version v)))))))
(get-in path))))
(defmethod checkpoint/assume-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id]
(let [exists (get-in @(:checkpoints log) [tenancy-id :latest job-id])
version (get exists :version 0)
coordinate (get exists :coordinate)]
(:version (checkpoint/write-checkpoint-coordinate log tenancy-id job-id
coordinate version))))
(defmethod checkpoint/read-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id]
(get-in @(:checkpoints log) [tenancy-id :latest job-id :coordinate]))
(defmethod checkpoint/read-checkpoint FakeZooKeeper
[log tenancy-id job-id replica-version epoch task-id slot-id checkpoint-type]
(-> @(:checkpoints log)
(get tenancy-id)
:checkpoints
(get job-id)
(get [replica-version epoch])
(get [task-id slot-id checkpoint-type])))
| null | https://raw.githubusercontent.com/onyx-platform/onyx/74f9ae58cdbcfcb1163464595f1e6ae6444c9782/test/onyx/mocked/zookeeper.clj | clojure | Always show true - we will always manually leave
synchronous write means it's already completed
zookeeper connection is shared with peer group, so we don't want to stop it | (ns onyx.mocked.zookeeper
(:require [com.stuartsierra.component :as component]
[taoensso.timbre :refer [info error warn fatal]]
[onyx.log.replica]
[onyx.checkpoint :as checkpoint]
[onyx.extensions :as extensions])
(:import [org.apache.zookeeper KeeperException$BadVersionException]))
(defrecord FakeZooKeeper [config]
component/Lifecycle
(start [component] component)
(stop [component] component))
(defn fake-zookeeper [entries store checkpoints config]
(map->FakeZooKeeper {:entries entries
:store store
:checkpoints checkpoints
:entry-num 0
:config config}))
(defmethod extensions/write-log-entry FakeZooKeeper
[log data]
(swap! (:entries log)
(fn [entries]
(conj (vec entries)
(assoc data :message-id (count entries)))))
log)
(defmethod extensions/read-log-entry FakeZooKeeper
[{:keys [entries]} n]
(get @entries n))
(defmethod extensions/register-pulse FakeZooKeeper
[& all])
(defmethod extensions/on-delete FakeZooKeeper
[& all])
(defmethod extensions/group-exists? FakeZooKeeper
[& all]
true)
(defmethod extensions/subscribe-to-log FakeZooKeeper
[log & _]
(onyx.log.replica/starting-replica (:config log)))
(defmethod extensions/write-chunk :default
[log kw chunk id]
(cond
(= :task kw)
(swap! (:store log) assoc [kw id (:id chunk)] chunk)
(= :exception kw)
(do (info "Task Exception:" chunk)
(throw chunk))
:else
(swap! (:store log) assoc [kw id] chunk))
log)
(defmethod extensions/read-chunk :default
[log kw id & rst]
(if (= :task kw)
(get @(:store log) [kw id (first rst)])
(get @(:store log) [kw id])))
(defmethod checkpoint/write-checkpoint FakeZooKeeper
[log tenancy-id job-id replica-version epoch task-id slot-id checkpoint-type checkpoint]
(info "Writing checkpoint:" replica-version epoch task-id slot-id)
(swap! (:checkpoints log)
assoc-in
[tenancy-id :checkpoints job-id [replica-version epoch] [task-id slot-id checkpoint-type]]
checkpoint))
(defmethod checkpoint/complete? FakeZooKeeper
[_]
true)
(defmethod checkpoint/cancel! FakeZooKeeper
[_])
(defmethod checkpoint/stop FakeZooKeeper
[log]
log)
(defmethod checkpoint/write-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id coordinate version]
(let [path [tenancy-id :latest job-id]]
(-> (swap! (:checkpoints log)
update-in
path
(fn [v]
(if (= (or (:version v) 0) version)
{:version (inc version)
:coordinate coordinate}
(throw (KeeperException$BadVersionException.
(str "failed write " version " vs " (:version v)))))))
(get-in path))))
(defmethod checkpoint/assume-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id]
(let [exists (get-in @(:checkpoints log) [tenancy-id :latest job-id])
version (get exists :version 0)
coordinate (get exists :coordinate)]
(:version (checkpoint/write-checkpoint-coordinate log tenancy-id job-id
coordinate version))))
(defmethod checkpoint/read-checkpoint-coordinate FakeZooKeeper
[log tenancy-id job-id]
(get-in @(:checkpoints log) [tenancy-id :latest job-id :coordinate]))
(defmethod checkpoint/read-checkpoint FakeZooKeeper
[log tenancy-id job-id replica-version epoch task-id slot-id checkpoint-type]
(-> @(:checkpoints log)
(get tenancy-id)
:checkpoints
(get job-id)
(get [replica-version epoch])
(get [task-id slot-id checkpoint-type])))
|
3959b9f976c6893d1aacb332b831a3622d0d29673fd1c3029714607510e26315 | bugarela/GADTInference | nested2.hs | data T a where {TInt :: (a ~ Int) => a -> T a; TBool :: (a ~ Bool) => a -> T a; TAny :: a -> T a}
e = let f = (\z -> case z of {(TInt x, y) -> (case y of {TBool _ -> True; TInt _ -> 1});(TBool x, y) -> (case y of {TBool _ -> 1; TInt _ -> True})}) in f
| null | https://raw.githubusercontent.com/bugarela/GADTInference/dd179f6df2cd76055c25c33da3187a60815688d1/examples/notInferred/nested2.hs | haskell | data T a where {TInt :: (a ~ Int) => a -> T a; TBool :: (a ~ Bool) => a -> T a; TAny :: a -> T a}
e = let f = (\z -> case z of {(TInt x, y) -> (case y of {TBool _ -> True; TInt _ -> 1});(TBool x, y) -> (case y of {TBool _ -> 1; TInt _ -> True})}) in f
|
|
5f1b948f921942f035eb26aa6780bd0af45e3047042be46ed94f9c5fc7f394e2 | earl-ducaine/cl-garnet | line-constraint.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The Garnet User Interface Development Environment . ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This code was written as part of the Garnet project at ;;;
Carnegie Mellon University , and has been placed in the public ; ; ;
domain . If you are using this code or any part of Garnet , ; ; ;
;;; please contact to be put on the mailing list. ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; This file contains the functions that implement the line constraint
;;; menu functionality.
;;;
CHANGE LOG
;;;
07/14/93 amickish - Removed gadget from list of ignored variables in
;;; LINE-UNCONSTRAIN-FN
;;; 08/24/92 amickish - Removed gadget from list of ignored variables in
;;; LINE-CUSTOM-FN
(in-package :garnet-gadgets)
(defun attach-line-constraint (interactor obj)
(declare (ignore interactor obj))
(declare (special *constraint-gadget*))
(let ((p (g-value *constraint-gadget* :obj-to-constrain))
(s (g-value *constraint-gadget* :obj-to-reference))
(p-where (g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(s-where (g-value LINE-CON-SEC-SEL-AGG :where-attach)))
(when (and p s p-where s-where)
(if (is-a-line-p p)
(if (is-a-line-p s)
(attach-line-to-line)
(attach-line-to-box))
(if (is-a-line-p s)
(attach-box-to-line)
(attach-box-to-box))))))
(defun attach-box-to-box ()
(constraint-gadget-error
"Unimplemented: cannot constrain a non-line to a non-line."))
(defun ATTACH-LINE-TO-LINE ()
(let* ((where-attach-line-1 (g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(where-attach-line-2 (g-value LINE-CON-SEC-SEL-AGG :where-attach)))
(case where-attach-line-1
(0 (attach-constraint *line-constraint-menu* :x1 :x1-over :x1-offset
(aref *x1-to-line* where-attach-line-2))
(attach-constraint *line-constraint-menu* :y1 :y1-over :y1-offset
(aref *y1-to-line* where-attach-line-2)))
(1 (attach-constraint *line-constraint-menu* :x2 :x2-over :x2-offset
(aref *x2-to-line* where-attach-line-2))
(attach-constraint *line-constraint-menu* :y2 :y2-over :y2-offset
(aref *y2-to-line* where-attach-line-2))))))
;; The box is the primary selection, and will be set with constraints
;; to the line.
(defun attach-box-to-line ()
(declare (special *constraint-gadget* *line-constraint-menu*))
(let* ((where-attach-box
(g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(where-attach-line
(g-value LINE-CON-SEC-SEL-AGG :where-attach))
(box (g-value *constraint-gadget* :obj-to-constrain))
(constraint-vectors
(cond ((is-a-p box opal:circle)
(aref *box-to-line* 0 where-attach-line))
((is-a-p box opal:roundtangle)
(aref *box-to-line* 1 where-attach-line))
(t
(aref *box-to-line* 2 where-attach-line))))
(left-vector (car constraint-vectors))
(top-vector (cdr constraint-vectors)))
(attach-constraint *line-constraint-menu* :left :left-over :left-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :top :top-over :top-offset
(nth where-attach-box top-vector))))
place a constraint on the endpoint of a line . The pair ( )
refer to the leftmost point and the pair ( x2,y2 ) refer to the
;;; rightmost point.
(defun attach-line-to-box ()
(declare (special *line-constraint-menu* *constraint-gadget*))
(let* ((where-attach-box
(g-value LINE-CON-SEC-SEL-AGG :where-attach))
(where-attach-line
(g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(box (g-value *constraint-gadget* :obj-to-reference))
(constraint-vectors
(cond ((is-a-p box opal:circle)
(aref *line-to-box* 0 where-attach-line))
((is-a-p box opal:roundtangle)
(aref *line-to-box* 1 where-attach-line))
(t
(aref *line-to-box* 2 where-attach-line))))
(left-vector (car constraint-vectors))
(top-vector (cdr constraint-vectors)))
(case where-attach-line
(0 (attach-constraint *line-constraint-menu* :x1 :x1-over :x1-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :y1 :y1-over :y1-offset
(nth where-attach-box top-vector)))
(1 (attach-constraint *line-constraint-menu* :x2 :x2-over :x2-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :y2 :y2-over :y2-offset
(nth where-attach-box top-vector))))))
store an integer position in one of a line 's position slots
(defun set-position-slot (gadget value)
(declare (special *constraint-gadget*))
(when (valid-integer-p gadget value)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain))
(slot (g-value gadget :slot)))
(cg-destroy-constraint obj slot)
(s-value obj slot (read-from-string value)))))
(defun set-x-offset (gadget value)
(declare (special *line-constraint-menu* *constraint-gadget*))
;; first determine if the offset is valid
(when (not (valid-integer-p gadget value))
(return-from set-x-offset))
(let ((x-offset (read-from-string value)))
;; store the offset in the line constraint menu
(s-value *line-constraint-menu* :x1-offset x-offset)
(s-value *line-constraint-menu* :x2-offset x-offset)
(s-value *line-constraint-menu* :left-offset x-offset)
;; if the offset should be placed in the appropriate offset slot
;; of the primary selection, do so
(if (g-value LINE-CON-PRIM-SEL-AGG :active)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain)))
(if (is-a-line-p obj)
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
(case sel
(0 (when (set-offset-p :x1)
(s-value obj :x1-offset x-offset)))
(1 (when (set-offset-p :x2)
(s-value obj :x2-offset x-offset)))
;; if an endpoint is not selected, determine if
;; either endpoint is constrained
(t
(cond ((set-offset-p :x1)
(s-value obj :x1-offset x-offset))
((set-offset-p :x2)
(s-value obj :x2-offset x-offset))))))
(when (set-offset-p :left)
(s-value obj :left-offset x-offset)))))))
(defun set-y-offset (gadget value)
(declare (special *line-constraint-menu* *constraint-gadget*))
;; first determine if the offset is valid
(when (not (valid-integer-p gadget value))
(return-from set-y-offset))
(let ((y-offset (read-from-string value)))
;; store the offset in the line constraint menu
(s-value *line-constraint-menu* :y1-offset y-offset)
(s-value *line-constraint-menu* :y2-offset y-offset)
(s-value *line-constraint-menu* :top-offset y-offset)
;; if the offset should be placed in the appropriate offset slot
;; of the primary selection, do so
(if (g-value LINE-CON-PRIM-SEL-AGG :active)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain)))
(if (is-a-line-p obj)
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
(case sel
(0 (when (set-offset-p :y1)
(s-value obj :y1-offset y-offset)))
(1 (when (set-offset-p :y2)
(s-value obj :y2-offset y-offset)))
;; if an endpoint is not selected, determine if
;; either endpoint is constrained
(t
(cond ((set-offset-p :y1)
(s-value obj :y1-offset y-offset))
((set-offset-p :y2)
(s-value obj :y2-offset y-offset))))))
(when (set-offset-p :top)
(s-value obj :top-offset y-offset)))))))
;; when either the unconstrain or customize buttons are hit, call this
;; function to clear the line buttons
(defun deselect-line-buttons (&optional (only-s-selection-p nil))
(declare (special LINE-CON-PRIM-SEL-AGG LINE-CON-SEC-SEL-AGG))
(when (not only-s-selection-p)
(deselect-constraint-button
(g-value LINE-CON-PRIM-SEL-AGG :line :buttons))
(deselect-constraint-button
(g-value LINE-CON-PRIM-SEL-AGG :box :buttons)))
(deselect-constraint-button
(g-value LINE-CON-SEC-SEL-AGG :line :buttons))
(deselect-constraint-button
(g-value LINE-CON-SEC-SEL-AGG :box :buttons)))
(defun LINE-CUSTOM-FN (gadget string)
(declare (ignore string))
(declare (special *constraint-gadget-query-window*))
(deselect-line-buttons)
(multiple-value-bind (left top)
(opal:convert-coordinates (g-value gadget :window)
(g-value gadget :left)
(opal:bottom gadget)
nil)
(c32 nil nil :left left :top top)))
(defun LINE-UNCONSTRAIN-FN (gadget string)
(declare (ignore string))
(declare (special *constraint-gadget*))
(let ((obj (g-value *constraint-gadget* :obj-to-constrain))
(reference-obj (g-value *constraint-gadget* :obj-to-reference)))
(when obj
(if (not (is-a-line-p obj))
(progn
(deselect-line-buttons)
(cg-destroy-constraint obj :left)
(cg-destroy-constraint obj :top))
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
;; if the user has selected an endpoint to unconstrain, or
;; if it is possible to determine the endpoint to unconstrain
;; without the user's intervention, unconstrain the endpoint.
;; if the user has not selected an endpoint to unconstrain
;; and both endpoints are constrained, ask the user to select
;; an endpoint to unconstrain
(when (null sel)
(cond (reference-obj
(cond ((and (formula-p (get-value obj :x1))
(depends-on-p obj reference-obj :x1)
(formula-p (get-value obj :x2))
(depends-on-p obj reference-obj :x2))
(constraint-gadget-error "Both endpoints are constrained. Please select one of
the two endpoints of the line in the primary
selection box and press unconstrain again")
(s-value gadget :value nil)
(return-from line-unconstrain-fn))
((and (formula-p (get-value obj :x1))
(depends-on-p obj reference-obj :x1))
(setf sel 0))
((and (formula-p (get-value obj :x2))
(depends-on-p obj reference-obj :x2))
(setf sel 1))
(t nil)))
;; no reference object
(t
(cond ((and (formula-p (get-value obj :x1))
(formula-p (get-value obj :x2)))
(constraint-gadget-error "Both endpoints are constrained. Please select one of
the two endpoints of the line in the primary
selection box and press unconstrain again")
(s-value gadget :value nil)
(return-from line-unconstrain-fn))
((formula-p (get-value obj :x1))
(setf sel 0))
((formula-p (get-value obj :x2))
(setf sel 1))
(t nil)))))
(when sel
(deselect-line-buttons)
(case sel
(0 (cg-destroy-constraint obj :x1)
(cg-destroy-constraint obj :y1))
(1 (cg-destroy-constraint obj :x2)
(cg-destroy-constraint obj :y2)))
))))))
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/lapidary/line-constraint.lisp | lisp | Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*-
; ;
This code was written as part of the Garnet project at ;;;
; ;
; ;
please contact to be put on the mailing list. ;;;
This file contains the functions that implement the line constraint
menu functionality.
LINE-UNCONSTRAIN-FN
08/24/92 amickish - Removed gadget from list of ignored variables in
LINE-CUSTOM-FN
The box is the primary selection, and will be set with constraints
to the line.
rightmost point.
first determine if the offset is valid
store the offset in the line constraint menu
if the offset should be placed in the appropriate offset slot
of the primary selection, do so
if an endpoint is not selected, determine if
either endpoint is constrained
first determine if the offset is valid
store the offset in the line constraint menu
if the offset should be placed in the appropriate offset slot
of the primary selection, do so
if an endpoint is not selected, determine if
either endpoint is constrained
when either the unconstrain or customize buttons are hit, call this
function to clear the line buttons
if the user has selected an endpoint to unconstrain, or
if it is possible to determine the endpoint to unconstrain
without the user's intervention, unconstrain the endpoint.
if the user has not selected an endpoint to unconstrain
and both endpoints are constrained, ask the user to select
an endpoint to unconstrain
no reference object | CHANGE LOG
07/14/93 amickish - Removed gadget from list of ignored variables in
(in-package :garnet-gadgets)
(defun attach-line-constraint (interactor obj)
(declare (ignore interactor obj))
(declare (special *constraint-gadget*))
(let ((p (g-value *constraint-gadget* :obj-to-constrain))
(s (g-value *constraint-gadget* :obj-to-reference))
(p-where (g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(s-where (g-value LINE-CON-SEC-SEL-AGG :where-attach)))
(when (and p s p-where s-where)
(if (is-a-line-p p)
(if (is-a-line-p s)
(attach-line-to-line)
(attach-line-to-box))
(if (is-a-line-p s)
(attach-box-to-line)
(attach-box-to-box))))))
(defun attach-box-to-box ()
(constraint-gadget-error
"Unimplemented: cannot constrain a non-line to a non-line."))
(defun ATTACH-LINE-TO-LINE ()
(let* ((where-attach-line-1 (g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(where-attach-line-2 (g-value LINE-CON-SEC-SEL-AGG :where-attach)))
(case where-attach-line-1
(0 (attach-constraint *line-constraint-menu* :x1 :x1-over :x1-offset
(aref *x1-to-line* where-attach-line-2))
(attach-constraint *line-constraint-menu* :y1 :y1-over :y1-offset
(aref *y1-to-line* where-attach-line-2)))
(1 (attach-constraint *line-constraint-menu* :x2 :x2-over :x2-offset
(aref *x2-to-line* where-attach-line-2))
(attach-constraint *line-constraint-menu* :y2 :y2-over :y2-offset
(aref *y2-to-line* where-attach-line-2))))))
(defun attach-box-to-line ()
(declare (special *constraint-gadget* *line-constraint-menu*))
(let* ((where-attach-box
(g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(where-attach-line
(g-value LINE-CON-SEC-SEL-AGG :where-attach))
(box (g-value *constraint-gadget* :obj-to-constrain))
(constraint-vectors
(cond ((is-a-p box opal:circle)
(aref *box-to-line* 0 where-attach-line))
((is-a-p box opal:roundtangle)
(aref *box-to-line* 1 where-attach-line))
(t
(aref *box-to-line* 2 where-attach-line))))
(left-vector (car constraint-vectors))
(top-vector (cdr constraint-vectors)))
(attach-constraint *line-constraint-menu* :left :left-over :left-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :top :top-over :top-offset
(nth where-attach-box top-vector))))
place a constraint on the endpoint of a line . The pair ( )
refer to the leftmost point and the pair ( x2,y2 ) refer to the
(defun attach-line-to-box ()
(declare (special *line-constraint-menu* *constraint-gadget*))
(let* ((where-attach-box
(g-value LINE-CON-SEC-SEL-AGG :where-attach))
(where-attach-line
(g-value LINE-CON-PRIM-SEL-AGG :where-attach))
(box (g-value *constraint-gadget* :obj-to-reference))
(constraint-vectors
(cond ((is-a-p box opal:circle)
(aref *line-to-box* 0 where-attach-line))
((is-a-p box opal:roundtangle)
(aref *line-to-box* 1 where-attach-line))
(t
(aref *line-to-box* 2 where-attach-line))))
(left-vector (car constraint-vectors))
(top-vector (cdr constraint-vectors)))
(case where-attach-line
(0 (attach-constraint *line-constraint-menu* :x1 :x1-over :x1-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :y1 :y1-over :y1-offset
(nth where-attach-box top-vector)))
(1 (attach-constraint *line-constraint-menu* :x2 :x2-over :x2-offset
(nth where-attach-box left-vector))
(attach-constraint *line-constraint-menu* :y2 :y2-over :y2-offset
(nth where-attach-box top-vector))))))
store an integer position in one of a line 's position slots
(defun set-position-slot (gadget value)
(declare (special *constraint-gadget*))
(when (valid-integer-p gadget value)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain))
(slot (g-value gadget :slot)))
(cg-destroy-constraint obj slot)
(s-value obj slot (read-from-string value)))))
(defun set-x-offset (gadget value)
(declare (special *line-constraint-menu* *constraint-gadget*))
(when (not (valid-integer-p gadget value))
(return-from set-x-offset))
(let ((x-offset (read-from-string value)))
(s-value *line-constraint-menu* :x1-offset x-offset)
(s-value *line-constraint-menu* :x2-offset x-offset)
(s-value *line-constraint-menu* :left-offset x-offset)
(if (g-value LINE-CON-PRIM-SEL-AGG :active)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain)))
(if (is-a-line-p obj)
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
(case sel
(0 (when (set-offset-p :x1)
(s-value obj :x1-offset x-offset)))
(1 (when (set-offset-p :x2)
(s-value obj :x2-offset x-offset)))
(t
(cond ((set-offset-p :x1)
(s-value obj :x1-offset x-offset))
((set-offset-p :x2)
(s-value obj :x2-offset x-offset))))))
(when (set-offset-p :left)
(s-value obj :left-offset x-offset)))))))
(defun set-y-offset (gadget value)
(declare (special *line-constraint-menu* *constraint-gadget*))
(when (not (valid-integer-p gadget value))
(return-from set-y-offset))
(let ((y-offset (read-from-string value)))
(s-value *line-constraint-menu* :y1-offset y-offset)
(s-value *line-constraint-menu* :y2-offset y-offset)
(s-value *line-constraint-menu* :top-offset y-offset)
(if (g-value LINE-CON-PRIM-SEL-AGG :active)
(let ((obj (g-value *constraint-gadget* :obj-to-constrain)))
(if (is-a-line-p obj)
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
(case sel
(0 (when (set-offset-p :y1)
(s-value obj :y1-offset y-offset)))
(1 (when (set-offset-p :y2)
(s-value obj :y2-offset y-offset)))
(t
(cond ((set-offset-p :y1)
(s-value obj :y1-offset y-offset))
((set-offset-p :y2)
(s-value obj :y2-offset y-offset))))))
(when (set-offset-p :top)
(s-value obj :top-offset y-offset)))))))
(defun deselect-line-buttons (&optional (only-s-selection-p nil))
(declare (special LINE-CON-PRIM-SEL-AGG LINE-CON-SEC-SEL-AGG))
(when (not only-s-selection-p)
(deselect-constraint-button
(g-value LINE-CON-PRIM-SEL-AGG :line :buttons))
(deselect-constraint-button
(g-value LINE-CON-PRIM-SEL-AGG :box :buttons)))
(deselect-constraint-button
(g-value LINE-CON-SEC-SEL-AGG :line :buttons))
(deselect-constraint-button
(g-value LINE-CON-SEC-SEL-AGG :box :buttons)))
(defun LINE-CUSTOM-FN (gadget string)
(declare (ignore string))
(declare (special *constraint-gadget-query-window*))
(deselect-line-buttons)
(multiple-value-bind (left top)
(opal:convert-coordinates (g-value gadget :window)
(g-value gadget :left)
(opal:bottom gadget)
nil)
(c32 nil nil :left left :top top)))
(defun LINE-UNCONSTRAIN-FN (gadget string)
(declare (ignore string))
(declare (special *constraint-gadget*))
(let ((obj (g-value *constraint-gadget* :obj-to-constrain))
(reference-obj (g-value *constraint-gadget* :obj-to-reference)))
(when obj
(if (not (is-a-line-p obj))
(progn
(deselect-line-buttons)
(cg-destroy-constraint obj :left)
(cg-destroy-constraint obj :top))
(let ((sel (g-value LINE-CON-PRIM-SEL-AGG :where-attach)))
(when (null sel)
(cond (reference-obj
(cond ((and (formula-p (get-value obj :x1))
(depends-on-p obj reference-obj :x1)
(formula-p (get-value obj :x2))
(depends-on-p obj reference-obj :x2))
(constraint-gadget-error "Both endpoints are constrained. Please select one of
the two endpoints of the line in the primary
selection box and press unconstrain again")
(s-value gadget :value nil)
(return-from line-unconstrain-fn))
((and (formula-p (get-value obj :x1))
(depends-on-p obj reference-obj :x1))
(setf sel 0))
((and (formula-p (get-value obj :x2))
(depends-on-p obj reference-obj :x2))
(setf sel 1))
(t nil)))
(t
(cond ((and (formula-p (get-value obj :x1))
(formula-p (get-value obj :x2)))
(constraint-gadget-error "Both endpoints are constrained. Please select one of
the two endpoints of the line in the primary
selection box and press unconstrain again")
(s-value gadget :value nil)
(return-from line-unconstrain-fn))
((formula-p (get-value obj :x1))
(setf sel 0))
((formula-p (get-value obj :x2))
(setf sel 1))
(t nil)))))
(when sel
(deselect-line-buttons)
(case sel
(0 (cg-destroy-constraint obj :x1)
(cg-destroy-constraint obj :y1))
(1 (cg-destroy-constraint obj :x2)
(cg-destroy-constraint obj :y2)))
))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.