_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 |
|---|---|---|---|---|---|---|---|---|
e9f62aef57f61436efd96d88ac70de343316b99942a6d6db8a1515c190ba3a50 | NorfairKing/intray | Server.hs | # LANGUAGE RecordWildCards #
module Intray.Web.Server
( intrayWebServer,
)
where
import Control.Monad.Logger
import qualified Data.Text as T
import Database.Persist.Sqlite
import Import
import Intray.Web.Server.Application ()
import Intray.Web.Server.Foundation
import Intray.Web.Server.OptParse
import qualified Network.HTTP.Client.TLS as Http
import Yesod
intrayWebServer :: IO ()
intrayWebServer = do
settings <- getSettings
pPrint settings
runIntrayWebServer settings
runIntrayWebServer :: Settings -> IO ()
runIntrayWebServer Settings {..} =
runStderrLoggingT $
filterLogger (\_ ll -> ll >= setLogLevel) $
withSqlitePoolInfo (mkSqliteConnectionInfo $ T.pack setLoginCacheFile) 1 $
\pool -> do
man <- liftIO Http.newTlsManager
let app =
App
{ appHttpManager = man,
appStatic = myStatic,
appTracking = setTracking,
appVerification = setVerification,
appAPIBaseUrl = setAPIBaseUrl,
appConnectionPool = pool
}
liftIO $ do
runSqlPool (runMigration migrateLoginCache) pool
warp setPort app
| null | https://raw.githubusercontent.com/NorfairKing/intray/0f272c63ff44fc7869964ca22f6195b855810543/intray-web-server/src/Intray/Web/Server.hs | haskell | # LANGUAGE RecordWildCards #
module Intray.Web.Server
( intrayWebServer,
)
where
import Control.Monad.Logger
import qualified Data.Text as T
import Database.Persist.Sqlite
import Import
import Intray.Web.Server.Application ()
import Intray.Web.Server.Foundation
import Intray.Web.Server.OptParse
import qualified Network.HTTP.Client.TLS as Http
import Yesod
intrayWebServer :: IO ()
intrayWebServer = do
settings <- getSettings
pPrint settings
runIntrayWebServer settings
runIntrayWebServer :: Settings -> IO ()
runIntrayWebServer Settings {..} =
runStderrLoggingT $
filterLogger (\_ ll -> ll >= setLogLevel) $
withSqlitePoolInfo (mkSqliteConnectionInfo $ T.pack setLoginCacheFile) 1 $
\pool -> do
man <- liftIO Http.newTlsManager
let app =
App
{ appHttpManager = man,
appStatic = myStatic,
appTracking = setTracking,
appVerification = setVerification,
appAPIBaseUrl = setAPIBaseUrl,
appConnectionPool = pool
}
liftIO $ do
runSqlPool (runMigration migrateLoginCache) pool
warp setPort app
| |
4cf258f43a7ecb2d3d52ca684aa02f6261758e037bd030839c2c6d4b1309e700 | litxio/ptghci | Config.hs | # LANGUAGE TemplateHaskell #
module Language.Haskell.PtGhci.Config where
import Language.Haskell.PtGhci.Prelude
import Lens.Micro.TH
import Text.Printf
import Data.Aeson
import System.Directory
import System.FilePath
import Data.Yaml (decodeFileEither, prettyPrintParseException)
import qualified Data.Aeson.Types as A (Options (..), Parser)
import Language.Haskell.PtGhci.Exception
data Verbosity = Critical | Error | Warn | Info | Debug | Trace
deriving (Enum, Eq, Ord, Show, Generic)
instance FromJSON Verbosity
data Config = Config
{ _verbosity :: Maybe Verbosity
, _logFile :: Maybe FilePath
, _webBrowser :: Maybe Text
, _ghciCommand :: Maybe Text
} deriving (Show, Generic)
makeLenses ''Config
instance FromJSON Config where
parseJSON = dropOneAndParse
| Drop the first character ( leading underscore ) from the field names
dropOneAndParse :: (Generic a, GFromJSON Zero (Rep a)) => Value -> A.Parser a
dropOneAndParse = genericParseJSON opts
where
opts = defaultOptions {A.fieldLabelModifier = drop 1}
defaultConfig = Config Nothing Nothing Nothing Nothing
getConfig :: IO Config
getConfig = do
configPath <- findConfigLocation
case configPath of
Just p -> loadConfig p
Nothing -> return defaultConfig
loadConfig :: FilePath -> IO Config
loadConfig path = do
eitherConfig <- decodeFileEither path
case eitherConfig of
Left ex -> throwIO $ ConfigurationError $ toS
(printf "Error parsing configuration file %s: %s"
path (prettyPrintParseException ex) :: String)
Right c -> return c
findConfigLocation :: IO (Maybe FilePath)
findConfigLocation = do
homeDir <- getHomeDirectory
p1 <- checkPath "ptghci.yaml"
p2 <- checkPath ".ptghci.yaml"
p3 <- checkPath $ homeDir </> ".ptghci.yaml"
return $ p1 <|> p2 <|> p3
where
checkPath :: FilePath -> IO (Maybe FilePath)
checkPath p = do
b <- doesFileExist p
return $ if b then Just p else Nothing
| null | https://raw.githubusercontent.com/litxio/ptghci/bbb3c5fdf2e73a557864b6b1e26833fffb34fc84/src/Language/Haskell/PtGhci/Config.hs | haskell | # LANGUAGE TemplateHaskell #
module Language.Haskell.PtGhci.Config where
import Language.Haskell.PtGhci.Prelude
import Lens.Micro.TH
import Text.Printf
import Data.Aeson
import System.Directory
import System.FilePath
import Data.Yaml (decodeFileEither, prettyPrintParseException)
import qualified Data.Aeson.Types as A (Options (..), Parser)
import Language.Haskell.PtGhci.Exception
data Verbosity = Critical | Error | Warn | Info | Debug | Trace
deriving (Enum, Eq, Ord, Show, Generic)
instance FromJSON Verbosity
data Config = Config
{ _verbosity :: Maybe Verbosity
, _logFile :: Maybe FilePath
, _webBrowser :: Maybe Text
, _ghciCommand :: Maybe Text
} deriving (Show, Generic)
makeLenses ''Config
instance FromJSON Config where
parseJSON = dropOneAndParse
| Drop the first character ( leading underscore ) from the field names
dropOneAndParse :: (Generic a, GFromJSON Zero (Rep a)) => Value -> A.Parser a
dropOneAndParse = genericParseJSON opts
where
opts = defaultOptions {A.fieldLabelModifier = drop 1}
defaultConfig = Config Nothing Nothing Nothing Nothing
getConfig :: IO Config
getConfig = do
configPath <- findConfigLocation
case configPath of
Just p -> loadConfig p
Nothing -> return defaultConfig
loadConfig :: FilePath -> IO Config
loadConfig path = do
eitherConfig <- decodeFileEither path
case eitherConfig of
Left ex -> throwIO $ ConfigurationError $ toS
(printf "Error parsing configuration file %s: %s"
path (prettyPrintParseException ex) :: String)
Right c -> return c
findConfigLocation :: IO (Maybe FilePath)
findConfigLocation = do
homeDir <- getHomeDirectory
p1 <- checkPath "ptghci.yaml"
p2 <- checkPath ".ptghci.yaml"
p3 <- checkPath $ homeDir </> ".ptghci.yaml"
return $ p1 <|> p2 <|> p3
where
checkPath :: FilePath -> IO (Maybe FilePath)
checkPath p = do
b <- doesFileExist p
return $ if b then Just p else Nothing
| |
efeec21e41cde02c8ee28f6bf55db358d46aca2acc27b3181f05e6f7ec73a65f | dvdt/xvsy | core.clj | (ns xvsy.core
(:require [clojure.tools.logging :as log]
[clojure.data.json]
[ring.util.codec]
[clojure.algo.generic.functor :refer [fmap]])
(:require (xvsy [geom :as geom]
[ggsql :as ggsql]
[macros :as macros]
[scale :as scale]
[stat :as stat]
[aesthetics :as aesthetics]
[legend :as legend]
[utils :as utils]
[conf :as conf]
[plot :as plot]
[ui :as ui]))
(:require [korma.core :as core]
[hiccup.core :refer [html]]))
(def ^:dynamic *options* nil)
(defn x-facet-spec=y-facet-spec? [facet-spec]
(= (get-in facet-spec [0 1])
(get-in facet-spec [1 1])))
(defn aes-label
"Returns svg element for x label based on the given spec"
[{{col-name :name} :col
{stat-name :name} :stat
:as mapping}]
(cond (nil? mapping) ""
(map? mapping) (let [stat-label (if (#{:id :bin} stat-name) "" (str (name stat-name) " "))
label (str stat-label col-name)]
[:text {:class "aes-label"
:font-family conf/*font-family*
:font-size conf/*font-size*} label])
:else ""))
(defn x-label [mapping]
(update-in (aes-label mapping) [1] #(assoc % :dy "20px")))
(defn y-label
"Returns svg element for x label based on the given spec"
[mapping]
(if (nil? mapping) ""
(update-in (aes-label mapping) [1]
#(assoc % :transform "translate(15 0) rotate(270 0 0)"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public
(defn head-dataset
"Returns the n rows of the dataset, the number of total rows, and
summary statistics for each of the columns."
[dataset & {n :n :or {n 5}}]
(let [cols (keys (get-in @ggsql/datasets [dataset :cols]))]
(as-> dataset $
(@ggsql/datasets $)
(korma.core/select* $)
(apply korma.core/fields $ cols)
(korma.core/limit $ 10))))
(defn col-stats
"Returns a query for the number of non-null rows for a column. If
column is numeric, also returns max, min and mean. For factor
columns, returns the number of unique factors."
[dataset [col-name {:keys [factor]}]]
(assert (get-in @ggsql/datasets [dataset :cols col-name]))
(let [ent (-> (@ggsql/datasets dataset)
korma.core/select*
(korma.core/where (not= col-name nil)))]
(if (true? factor)
;; TODO: this only works for big query. Fix to be able to use postgres?
(korma.core/fields ent [(korma.core/raw (format "COUNT(DISTINCT %s)" col-name))
:cnt_distinct])
(-> ent
(korma.core/aggregate (count col-name) :cnt)
(korma.core/aggregate (avg col-name) :avg)
(korma.core/aggregate (min col-name) :min)
(korma.core/aggregate (max col-name) :max)))))
(defn factor
"Specifies that the given column in a dataset is a factor
(i.e. categorical) variable."
[col-name]
{:name col-name :factor true})
(defn non-factor
[col-name]
{:name col-name :factor false})
(defn spec
[dataset geom & {:keys [aes]}]
(let [data-ent (@xvsy.ggsql/datasets dataset)
factor-specd-aes
(map (fn [[aes-key mapping]]
(let [col-name (get-in mapping [:col :name])
col-factor? (get-in mapping [:col :factor])
data-factor? (get-in data-ent [:cols col-name :factor])]
[aes-key (assoc-in mapping [:col :factor]
(if (nil? col-factor?) data-factor? col-factor?))]))
aes)]
{:dataset dataset :geom geom
:aesthetics (into {} factor-specd-aes)}))
(defn ->plot-spec
"Returns a Korma-comaptible hashmap for executing an SQL query.
params -
geom: an instance of xvsy.geom/Geom. Geoms represent chart types (e.g. bar, point, line)
aes-mappings: Aesthetics mappings define how data are mapped to a
plot. aes-mappings is a hashmap of aesthetic=>mapping, where mapping
specifies a column and a SQL function to apply to it. For example
the aes-mapping,
{:x {:col {:name :my-col-name :factor false}
:stat {:name :count}}}
corresponds to `SELECT COUNT(my-col-name) as x`.
where-preds: a sequence of where predicates. Each predicate takes the form [sql-func expr test].
[\"<\" x 1] corresponds to `x < 1`
entity: a kormasql entity
facets: mappings (same form as for aesthetics) for plot facets.
Should deconstruct to [facet_x_mapping facet_y_mapping]."
[^xvsy.geom.Geom geom aes-mappings where-preds entity facet-mappings]
(let [facet-mappings (filter identity facet-mappings)]
(assert (reduce (fn [acc [a m]] (and a (utils/factor? m))) true facet-mappings)
"All facet-mappings must be factors.")
(-> (korma.core/select* entity)
(assoc :aesthetics {})
(aesthetics/aes aes-mappings)
(aesthetics/order aes-mappings)
(aesthetics/where where-preds)
(aesthetics/facet facet-mappings))))
(defn plot-svg
"Takes a plot specification from the http api (see xvsy.handlers),
generates a SQL query, executes that SQL query, renders svg elements
for the query results in accordance to that plot spec, and returns
that hiccup SVG vector"
[width height inline spec]
(let [geom (or conf/*geom* (geom/default-geom (:geom spec)))
entity (@ggsql/datasets (:dataset spec))
facet-spec [(if-let [facet (get-in spec [:aesthetics :facet_x])] [:facet_x facet])
(if-let [facet (get-in spec [:aesthetics :facet_y])] [:facet_y facet])]
aesthetics (-> spec :aesthetics (dissoc :facet_x) (dissoc :facet_y))
where s [ [ " in " " Dest " ( map # ( str \ " % \") [ " LAX " " IAH " " ORD " " ATL " " " ] ) ] ]
wheres (or (if (map? (:where spec))
(ui/unreactify-wheres (:where spec))
(:where spec))
[])
plot-spec (->plot-spec geom aesthetics wheres entity facet-spec)
layer-data (ggsql/exec plot-spec)
scalars (geom/guess-scalars geom (:aesthetics plot-spec))
scalar-trainers (fmap #(partial scale/train-global-scalars %) scalars)
facetter-trainers (if (x-facet-spec=y-facet-spec? facet-spec)
scale/facet-wrap
scale/facet-grid)
p (plot/->plot geom scalar-trainers facetter-trainers layer-data)
[_ _ [geom-w geom-h]] (plot/area-dims width height (:facet-scalars p))]
(macros/with-conf {:geom geom
:x (or conf/*x* [0 geom-w])
:y (or conf/*y* [geom-h 0])
:x-label (or conf/*x-label* (x-label (:x aesthetics)))
:y-label (or conf/*y-label* (y-label (:y aesthetics)))
:fill-label (or conf/*fill-label* (aes-label (:fill aesthetics)))
:color-label (or conf/*color-label* (aes-label (:color aesthetics)))}
(doall (time (hiccup.core/html
(list "<?xml version=\"1.0\" standalone=\"no\"?>"
\newline
(if (not inline)
(str "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"
\"\">"
\newline))
(plot/layout-geoms [width height] geom p))))))))
(def m-plot-svg (memoize plot-svg))
(defn qspec
"Convenience function for concisely specifying plots. Use in
conjunction with `plot-svg`."
[dataset geom & {:keys [aes where]}]
(let [dataset (name dataset)
data-ent (@xvsy.ggsql/datasets dataset)
_ (assert data-ent)
factor-specd-aes
(map (fn [[aes-key mapping]]
(cond (map? mapping)
(let [col-name (name (get-in mapping [:col :name]))
col-factor? (get-in mapping [:col :factor])
data-factor? (get-in data-ent [:cols col-name :factor])]
[aes-key (assoc-in mapping [:col :factor]
(if (nil? col-factor?) data-factor? col-factor?))])
:else [aes-key mapping]))
aes)]
{:dataset dataset :geom geom
:aesthetics (into {} factor-specd-aes)
:where (or where [])}))
(defn ->urlencode-spec
"Converts a clojure plot spec into a urlencoded spec"
[spec]
(-> spec
(assoc :where (ui/reactify-wheres (:where spec)))
clojure.data.json/json-str
ring.util.codec/url-encode))
| null | https://raw.githubusercontent.com/dvdt/xvsy/ff29b96affc6723bb9c66da1011f31900af679dd/src/clj/xvsy/core.clj | clojure |
Public
TODO: this only works for big query. Fix to be able to use postgres? | (ns xvsy.core
(:require [clojure.tools.logging :as log]
[clojure.data.json]
[ring.util.codec]
[clojure.algo.generic.functor :refer [fmap]])
(:require (xvsy [geom :as geom]
[ggsql :as ggsql]
[macros :as macros]
[scale :as scale]
[stat :as stat]
[aesthetics :as aesthetics]
[legend :as legend]
[utils :as utils]
[conf :as conf]
[plot :as plot]
[ui :as ui]))
(:require [korma.core :as core]
[hiccup.core :refer [html]]))
(def ^:dynamic *options* nil)
(defn x-facet-spec=y-facet-spec? [facet-spec]
(= (get-in facet-spec [0 1])
(get-in facet-spec [1 1])))
(defn aes-label
"Returns svg element for x label based on the given spec"
[{{col-name :name} :col
{stat-name :name} :stat
:as mapping}]
(cond (nil? mapping) ""
(map? mapping) (let [stat-label (if (#{:id :bin} stat-name) "" (str (name stat-name) " "))
label (str stat-label col-name)]
[:text {:class "aes-label"
:font-family conf/*font-family*
:font-size conf/*font-size*} label])
:else ""))
(defn x-label [mapping]
(update-in (aes-label mapping) [1] #(assoc % :dy "20px")))
(defn y-label
"Returns svg element for x label based on the given spec"
[mapping]
(if (nil? mapping) ""
(update-in (aes-label mapping) [1]
#(assoc % :transform "translate(15 0) rotate(270 0 0)"))))
(defn head-dataset
"Returns the n rows of the dataset, the number of total rows, and
summary statistics for each of the columns."
[dataset & {n :n :or {n 5}}]
(let [cols (keys (get-in @ggsql/datasets [dataset :cols]))]
(as-> dataset $
(@ggsql/datasets $)
(korma.core/select* $)
(apply korma.core/fields $ cols)
(korma.core/limit $ 10))))
(defn col-stats
"Returns a query for the number of non-null rows for a column. If
column is numeric, also returns max, min and mean. For factor
columns, returns the number of unique factors."
[dataset [col-name {:keys [factor]}]]
(assert (get-in @ggsql/datasets [dataset :cols col-name]))
(let [ent (-> (@ggsql/datasets dataset)
korma.core/select*
(korma.core/where (not= col-name nil)))]
(if (true? factor)
(korma.core/fields ent [(korma.core/raw (format "COUNT(DISTINCT %s)" col-name))
:cnt_distinct])
(-> ent
(korma.core/aggregate (count col-name) :cnt)
(korma.core/aggregate (avg col-name) :avg)
(korma.core/aggregate (min col-name) :min)
(korma.core/aggregate (max col-name) :max)))))
(defn factor
"Specifies that the given column in a dataset is a factor
(i.e. categorical) variable."
[col-name]
{:name col-name :factor true})
(defn non-factor
[col-name]
{:name col-name :factor false})
(defn spec
[dataset geom & {:keys [aes]}]
(let [data-ent (@xvsy.ggsql/datasets dataset)
factor-specd-aes
(map (fn [[aes-key mapping]]
(let [col-name (get-in mapping [:col :name])
col-factor? (get-in mapping [:col :factor])
data-factor? (get-in data-ent [:cols col-name :factor])]
[aes-key (assoc-in mapping [:col :factor]
(if (nil? col-factor?) data-factor? col-factor?))]))
aes)]
{:dataset dataset :geom geom
:aesthetics (into {} factor-specd-aes)}))
(defn ->plot-spec
"Returns a Korma-comaptible hashmap for executing an SQL query.
params -
geom: an instance of xvsy.geom/Geom. Geoms represent chart types (e.g. bar, point, line)
aes-mappings: Aesthetics mappings define how data are mapped to a
plot. aes-mappings is a hashmap of aesthetic=>mapping, where mapping
specifies a column and a SQL function to apply to it. For example
the aes-mapping,
{:x {:col {:name :my-col-name :factor false}
:stat {:name :count}}}
corresponds to `SELECT COUNT(my-col-name) as x`.
where-preds: a sequence of where predicates. Each predicate takes the form [sql-func expr test].
[\"<\" x 1] corresponds to `x < 1`
entity: a kormasql entity
facets: mappings (same form as for aesthetics) for plot facets.
Should deconstruct to [facet_x_mapping facet_y_mapping]."
[^xvsy.geom.Geom geom aes-mappings where-preds entity facet-mappings]
(let [facet-mappings (filter identity facet-mappings)]
(assert (reduce (fn [acc [a m]] (and a (utils/factor? m))) true facet-mappings)
"All facet-mappings must be factors.")
(-> (korma.core/select* entity)
(assoc :aesthetics {})
(aesthetics/aes aes-mappings)
(aesthetics/order aes-mappings)
(aesthetics/where where-preds)
(aesthetics/facet facet-mappings))))
(defn plot-svg
"Takes a plot specification from the http api (see xvsy.handlers),
generates a SQL query, executes that SQL query, renders svg elements
for the query results in accordance to that plot spec, and returns
that hiccup SVG vector"
[width height inline spec]
(let [geom (or conf/*geom* (geom/default-geom (:geom spec)))
entity (@ggsql/datasets (:dataset spec))
facet-spec [(if-let [facet (get-in spec [:aesthetics :facet_x])] [:facet_x facet])
(if-let [facet (get-in spec [:aesthetics :facet_y])] [:facet_y facet])]
aesthetics (-> spec :aesthetics (dissoc :facet_x) (dissoc :facet_y))
where s [ [ " in " " Dest " ( map # ( str \ " % \") [ " LAX " " IAH " " ORD " " ATL " " " ] ) ] ]
wheres (or (if (map? (:where spec))
(ui/unreactify-wheres (:where spec))
(:where spec))
[])
plot-spec (->plot-spec geom aesthetics wheres entity facet-spec)
layer-data (ggsql/exec plot-spec)
scalars (geom/guess-scalars geom (:aesthetics plot-spec))
scalar-trainers (fmap #(partial scale/train-global-scalars %) scalars)
facetter-trainers (if (x-facet-spec=y-facet-spec? facet-spec)
scale/facet-wrap
scale/facet-grid)
p (plot/->plot geom scalar-trainers facetter-trainers layer-data)
[_ _ [geom-w geom-h]] (plot/area-dims width height (:facet-scalars p))]
(macros/with-conf {:geom geom
:x (or conf/*x* [0 geom-w])
:y (or conf/*y* [geom-h 0])
:x-label (or conf/*x-label* (x-label (:x aesthetics)))
:y-label (or conf/*y-label* (y-label (:y aesthetics)))
:fill-label (or conf/*fill-label* (aes-label (:fill aesthetics)))
:color-label (or conf/*color-label* (aes-label (:color aesthetics)))}
(doall (time (hiccup.core/html
(list "<?xml version=\"1.0\" standalone=\"no\"?>"
\newline
(if (not inline)
(str "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"
\"\">"
\newline))
(plot/layout-geoms [width height] geom p))))))))
(def m-plot-svg (memoize plot-svg))
(defn qspec
"Convenience function for concisely specifying plots. Use in
conjunction with `plot-svg`."
[dataset geom & {:keys [aes where]}]
(let [dataset (name dataset)
data-ent (@xvsy.ggsql/datasets dataset)
_ (assert data-ent)
factor-specd-aes
(map (fn [[aes-key mapping]]
(cond (map? mapping)
(let [col-name (name (get-in mapping [:col :name]))
col-factor? (get-in mapping [:col :factor])
data-factor? (get-in data-ent [:cols col-name :factor])]
[aes-key (assoc-in mapping [:col :factor]
(if (nil? col-factor?) data-factor? col-factor?))])
:else [aes-key mapping]))
aes)]
{:dataset dataset :geom geom
:aesthetics (into {} factor-specd-aes)
:where (or where [])}))
(defn ->urlencode-spec
"Converts a clojure plot spec into a urlencoded spec"
[spec]
(-> spec
(assoc :where (ui/reactify-wheres (:where spec)))
clojure.data.json/json-str
ring.util.codec/url-encode))
|
f433f8793881ff7f0d36bbd67fb39b9643b6f34868d2f0d228158dd05daa15a1 | expipiplus1/vulkan | PipelineDepthStencilStateCreateFlagBits.hs | {-# language CPP #-}
No documentation found for Chapter " PipelineDepthStencilStateCreateFlagBits "
module Vulkan.Core10.Enums.PipelineDepthStencilStateCreateFlagBits ( PipelineDepthStencilStateCreateFlags
, PipelineDepthStencilStateCreateFlagBits( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT
, PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT
, ..
)
) where
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type PipelineDepthStencilStateCreateFlags = PipelineDepthStencilStateCreateFlagBits
| VkPipelineDepthStencilStateCreateFlagBits - Bitmask specifying
additional depth\/stencil state information .
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_EXT_rasterization_order_attachment_access VK_EXT_rasterization_order_attachment_access>,
-- 'PipelineDepthStencilStateCreateFlags'
newtype PipelineDepthStencilStateCreateFlagBits = PipelineDepthStencilStateCreateFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- | 'PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT'
-- indicates that access to the stencil aspects of depth\/stencil and input
-- attachments will have implicit framebuffer-local memory dependencies.
-- See
-- <-extensions/html/vkspec.html#renderpass-feedbackloop renderpass feedback loops>
-- for more information.
pattern PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT = PipelineDepthStencilStateCreateFlagBits 0x00000002
-- | 'PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT'
-- indicates that access to the depth aspects of depth\/stencil and input
-- attachments will have implicit framebuffer-local memory dependencies.
-- See
-- <-extensions/html/vkspec.html#renderpass-feedbackloop renderpass feedback loops>
-- for more information.
pattern PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT = PipelineDepthStencilStateCreateFlagBits 0x00000001
conNamePipelineDepthStencilStateCreateFlagBits :: String
conNamePipelineDepthStencilStateCreateFlagBits = "PipelineDepthStencilStateCreateFlagBits"
enumPrefixPipelineDepthStencilStateCreateFlagBits :: String
enumPrefixPipelineDepthStencilStateCreateFlagBits = "PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_"
showTablePipelineDepthStencilStateCreateFlagBits :: [(PipelineDepthStencilStateCreateFlagBits, String)]
showTablePipelineDepthStencilStateCreateFlagBits =
[
( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT
, "STENCIL_ACCESS_BIT_EXT"
)
,
( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT
, "DEPTH_ACCESS_BIT_EXT"
)
]
instance Show PipelineDepthStencilStateCreateFlagBits where
showsPrec =
enumShowsPrec
enumPrefixPipelineDepthStencilStateCreateFlagBits
showTablePipelineDepthStencilStateCreateFlagBits
conNamePipelineDepthStencilStateCreateFlagBits
(\(PipelineDepthStencilStateCreateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read PipelineDepthStencilStateCreateFlagBits where
readPrec =
enumReadPrec
enumPrefixPipelineDepthStencilStateCreateFlagBits
showTablePipelineDepthStencilStateCreateFlagBits
conNamePipelineDepthStencilStateCreateFlagBits
PipelineDepthStencilStateCreateFlagBits
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/70d8cca16893f8de76c0eb89e79e73f5a455db76/src/Vulkan/Core10/Enums/PipelineDepthStencilStateCreateFlagBits.hs | haskell | # language CPP #
= See Also
<-extensions/html/vkspec.html#VK_EXT_rasterization_order_attachment_access VK_EXT_rasterization_order_attachment_access>,
'PipelineDepthStencilStateCreateFlags'
| 'PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT'
indicates that access to the stencil aspects of depth\/stencil and input
attachments will have implicit framebuffer-local memory dependencies.
See
<-extensions/html/vkspec.html#renderpass-feedbackloop renderpass feedback loops>
for more information.
| 'PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT'
indicates that access to the depth aspects of depth\/stencil and input
attachments will have implicit framebuffer-local memory dependencies.
See
<-extensions/html/vkspec.html#renderpass-feedbackloop renderpass feedback loops>
for more information. | No documentation found for Chapter " PipelineDepthStencilStateCreateFlagBits "
module Vulkan.Core10.Enums.PipelineDepthStencilStateCreateFlagBits ( PipelineDepthStencilStateCreateFlags
, PipelineDepthStencilStateCreateFlagBits( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT
, PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT
, ..
)
) where
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
type PipelineDepthStencilStateCreateFlags = PipelineDepthStencilStateCreateFlagBits
| VkPipelineDepthStencilStateCreateFlagBits - Bitmask specifying
additional depth\/stencil state information .
newtype PipelineDepthStencilStateCreateFlagBits = PipelineDepthStencilStateCreateFlagBits Flags
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
pattern PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT = PipelineDepthStencilStateCreateFlagBits 0x00000002
pattern PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT = PipelineDepthStencilStateCreateFlagBits 0x00000001
conNamePipelineDepthStencilStateCreateFlagBits :: String
conNamePipelineDepthStencilStateCreateFlagBits = "PipelineDepthStencilStateCreateFlagBits"
enumPrefixPipelineDepthStencilStateCreateFlagBits :: String
enumPrefixPipelineDepthStencilStateCreateFlagBits = "PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_"
showTablePipelineDepthStencilStateCreateFlagBits :: [(PipelineDepthStencilStateCreateFlagBits, String)]
showTablePipelineDepthStencilStateCreateFlagBits =
[
( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT
, "STENCIL_ACCESS_BIT_EXT"
)
,
( PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT
, "DEPTH_ACCESS_BIT_EXT"
)
]
instance Show PipelineDepthStencilStateCreateFlagBits where
showsPrec =
enumShowsPrec
enumPrefixPipelineDepthStencilStateCreateFlagBits
showTablePipelineDepthStencilStateCreateFlagBits
conNamePipelineDepthStencilStateCreateFlagBits
(\(PipelineDepthStencilStateCreateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read PipelineDepthStencilStateCreateFlagBits where
readPrec =
enumReadPrec
enumPrefixPipelineDepthStencilStateCreateFlagBits
showTablePipelineDepthStencilStateCreateFlagBits
conNamePipelineDepthStencilStateCreateFlagBits
PipelineDepthStencilStateCreateFlagBits
|
bddff57e4c748cc5e75227cba32f10c934dc3251fa37758fba58fc6dc379503f | planetfederal/signal | input.clj | Copyright 2016 - 2018 Boundless ,
;;
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.
(ns signal.components.http.input
(:require [signal.components.http.intercept :as intercept]
[signal.components.http.response :as response]
[signal.components.input-manager :as input-manager-api]
[signal.components.processor :as processorapi]
[signal.components.http.auth :refer [check-auth]]))
(defn http-get-all-inputs
[input-comp _]
(response/ok (input-manager-api/all input-comp)))
(defn http-get-input
[input-comp request]
(let [input (input-manager-api/find-by-id input-comp
(get-in request [:path-params :id]))]
(response/ok input)))
(defn http-put-inputs
[input-comp request]
(if (some? (input-manager-api/modify input-comp
(get-in request [:path-params :id])
(:json-params request)))
(response/ok "success")
(response/error "error updating input")))
(defn http-post-inputs
[input-comp request]
(if-let [input (input-manager-api/create input-comp (:json-params request))]
(response/ok input)
(response/error "Error creating input")))
(defn http-delete-inputs
[input-comp request]
(let [id (get-in request [:path-params :id])]
(if (input-manager-api/delete input-comp id)
(response/ok "success")
(response/error "could not delete input: " id))))
(defn routes
"Makes routes for the current inputs"
[input-comp]
#{["/api/inputs" :get
(conj intercept/common-interceptors check-auth
(partial http-get-all-inputs input-comp))
:route-name :get-inputs]
["/api/inputs/:id" :get
(conj intercept/common-interceptors check-auth
(partial http-get-input input-comp))
:route-name :get-input]
["/api/inputs/:id" :put
(conj intercept/common-interceptors check-auth
(partial http-put-inputs input-comp))
:route-name :put-input]
["/api/inputs" :post
(conj intercept/common-interceptors check-auth
(partial http-post-inputs input-comp))
:route-name :post-input]
["/api/inputs/:id" :delete
(conj intercept/common-interceptors check-auth
(partial http-delete-inputs input-comp))
:route-name :delete-input]})
| null | https://raw.githubusercontent.com/planetfederal/signal/e3eae56c753f0a56614ba8522278057ab2358c96/src/signal/components/http/input.clj | clojure |
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 2016 - 2018 Boundless ,
distributed under the License is distributed on an " AS IS " BASIS ,
(ns signal.components.http.input
(:require [signal.components.http.intercept :as intercept]
[signal.components.http.response :as response]
[signal.components.input-manager :as input-manager-api]
[signal.components.processor :as processorapi]
[signal.components.http.auth :refer [check-auth]]))
(defn http-get-all-inputs
[input-comp _]
(response/ok (input-manager-api/all input-comp)))
(defn http-get-input
[input-comp request]
(let [input (input-manager-api/find-by-id input-comp
(get-in request [:path-params :id]))]
(response/ok input)))
(defn http-put-inputs
[input-comp request]
(if (some? (input-manager-api/modify input-comp
(get-in request [:path-params :id])
(:json-params request)))
(response/ok "success")
(response/error "error updating input")))
(defn http-post-inputs
[input-comp request]
(if-let [input (input-manager-api/create input-comp (:json-params request))]
(response/ok input)
(response/error "Error creating input")))
(defn http-delete-inputs
[input-comp request]
(let [id (get-in request [:path-params :id])]
(if (input-manager-api/delete input-comp id)
(response/ok "success")
(response/error "could not delete input: " id))))
(defn routes
"Makes routes for the current inputs"
[input-comp]
#{["/api/inputs" :get
(conj intercept/common-interceptors check-auth
(partial http-get-all-inputs input-comp))
:route-name :get-inputs]
["/api/inputs/:id" :get
(conj intercept/common-interceptors check-auth
(partial http-get-input input-comp))
:route-name :get-input]
["/api/inputs/:id" :put
(conj intercept/common-interceptors check-auth
(partial http-put-inputs input-comp))
:route-name :put-input]
["/api/inputs" :post
(conj intercept/common-interceptors check-auth
(partial http-post-inputs input-comp))
:route-name :post-input]
["/api/inputs/:id" :delete
(conj intercept/common-interceptors check-auth
(partial http-delete-inputs input-comp))
:route-name :delete-input]})
|
3de9189e7d7a12c794e421a6af4de5720e5dfffa400389ae1eb7191df9591081 | richardharrington/robotwar | register_test.clj | (ns robotwar.register-test
(:use [clojure.test]
[midje.sweet]
[robotwar.register])
(:require [robotwar.world :as world]))
(def world (world/init-world [""]))
(def robot-path [:robots 0])
(def reg-path [:robots 0 :brain :registers])
(def registers (get-in world reg-path))
(def get-registers #(get-in % reg-path))
(deftest storage-register-test
(testing "can write and read to storage register's :val field"
(let [new-world (write-register (registers "A") world 42)
new-registers (get-registers new-world)]
(is (= (read-register (new-registers "A") new-world)
42))
(is (= (get-in new-registers ["A" :val])
42)))))
(deftest index-data-pair-test
(testing "registers whose index numbers are push to INDEX can
be referenced by accessing DATA"
(let [world1 (write-register (registers "A") world 42)
registers1 (get-registers world1)
world2 (write-register (registers1 "INDEX") world1 1)
registers2 (get-registers world2)
world3 (write-register (registers2 "DATA") world2 100)
registers3 (get-registers world3)]
(is (= (read-register (registers2 "DATA") world2)
42))
(is (= (read-register (registers3 "A") world3)
100)))))
(deftest random-test
(testing "write to random register's :val field,
and read a series of numbers all different
from random register"
(let [new-world (write-register (registers "RANDOM") world 1000)
new-registers (get-registers new-world)
random-nums (repeatedly 5 (partial read-register (new-registers "RANDOM") new-world))]
(is (= (get-in new-registers ["RANDOM" :val])
1000))
(is (every? #(< -1 % 1000) random-nums))
(is (apply not= random-nums)))))
(deftest read-only-test
(testing "can read from read-only registers, but not write to them
(and also the robot fields don't get written to)"
(let [world1 (assoc-in world [:robots 0 :damage] 50.0)
registers1 (get-registers world1)
world2 (write-register (registers "DAMAGE") world1 25)
registers2 (get-registers world2)]
(is (= (read-register (registers1 "DAMAGE") world1)
50))
(is (= (read-register (registers2 "DAMAGE") world2)
50))
(is (= (get-in world2 [:robots 0 :damage])
50.0)))))
(deftest read-write-test
(testing "can read and write from registers that are interfaces
for robot fields, and also those robot fields get written to"
(let [new-world (write-register (registers "SPEEDX") world 90)
new-registers (get-registers new-world)]
(is (= (read-register (new-registers "SPEEDX") new-world)
90))
(is (= (get-in new-world [:robots 0 :desired-v-x])
9.0)))))
| null | https://raw.githubusercontent.com/richardharrington/robotwar/7f826649dd1a141fdacebb30d843773ceb5fee1f/test/robotwar/register_test.clj | clojure | (ns robotwar.register-test
(:use [clojure.test]
[midje.sweet]
[robotwar.register])
(:require [robotwar.world :as world]))
(def world (world/init-world [""]))
(def robot-path [:robots 0])
(def reg-path [:robots 0 :brain :registers])
(def registers (get-in world reg-path))
(def get-registers #(get-in % reg-path))
(deftest storage-register-test
(testing "can write and read to storage register's :val field"
(let [new-world (write-register (registers "A") world 42)
new-registers (get-registers new-world)]
(is (= (read-register (new-registers "A") new-world)
42))
(is (= (get-in new-registers ["A" :val])
42)))))
(deftest index-data-pair-test
(testing "registers whose index numbers are push to INDEX can
be referenced by accessing DATA"
(let [world1 (write-register (registers "A") world 42)
registers1 (get-registers world1)
world2 (write-register (registers1 "INDEX") world1 1)
registers2 (get-registers world2)
world3 (write-register (registers2 "DATA") world2 100)
registers3 (get-registers world3)]
(is (= (read-register (registers2 "DATA") world2)
42))
(is (= (read-register (registers3 "A") world3)
100)))))
(deftest random-test
(testing "write to random register's :val field,
and read a series of numbers all different
from random register"
(let [new-world (write-register (registers "RANDOM") world 1000)
new-registers (get-registers new-world)
random-nums (repeatedly 5 (partial read-register (new-registers "RANDOM") new-world))]
(is (= (get-in new-registers ["RANDOM" :val])
1000))
(is (every? #(< -1 % 1000) random-nums))
(is (apply not= random-nums)))))
(deftest read-only-test
(testing "can read from read-only registers, but not write to them
(and also the robot fields don't get written to)"
(let [world1 (assoc-in world [:robots 0 :damage] 50.0)
registers1 (get-registers world1)
world2 (write-register (registers "DAMAGE") world1 25)
registers2 (get-registers world2)]
(is (= (read-register (registers1 "DAMAGE") world1)
50))
(is (= (read-register (registers2 "DAMAGE") world2)
50))
(is (= (get-in world2 [:robots 0 :damage])
50.0)))))
(deftest read-write-test
(testing "can read and write from registers that are interfaces
for robot fields, and also those robot fields get written to"
(let [new-world (write-register (registers "SPEEDX") world 90)
new-registers (get-registers new-world)]
(is (= (read-register (new-registers "SPEEDX") new-world)
90))
(is (= (get-in new-world [:robots 0 :desired-v-x])
9.0)))))
| |
4ecc6927d98e2a3713a5d32b2be8ba636900f8b5c974c6a3e148a479d48e8ed3 | billstclair/trubanc-lisp | tests.lisp | (in-package :cl-user)
(defpackage :alexandria-tests
(:use :cl :alexandria #+sbcl :sb-rt #-sbcl :rtest)
(:import-from #+sbcl :sb-rt #-sbcl :rtest
#:*compile-tests* #:*expected-failures*))
(in-package :alexandria-tests)
(defun run-tests (&key ((:compiled *compile-tests)))
(do-tests))
;;;; Arrays
(deftest copy-array.1
(let* ((orig (vector 1 2 3))
(copy (copy-array orig)))
(values (eq orig copy) (equalp orig copy)))
nil t)
(deftest copy-array.2
(let ((orig (make-array 1024 :fill-pointer 0)))
(vector-push-extend 1 orig)
(vector-push-extend 2 orig)
(vector-push-extend 3 orig)
(let ((copy (copy-array orig)))
(values (eq orig copy) (equalp orig copy)
(array-has-fill-pointer-p copy)
(eql (fill-pointer orig) (fill-pointer copy)))))
nil t t t)
(deftest array-index.1
(typep 0 'array-index)
t)
;;;; Conditions
(deftest unwind-protect-case.1
(let (result)
(unwind-protect-case ()
(random 10)
(:normal (push :normal result))
(:abort (push :abort result))
(:always (push :always result)))
result)
(:always :normal))
(deftest unwind-protect-case.2
(let (result)
(unwind-protect-case ()
(random 10)
(:always (push :always result))
(:normal (push :normal result))
(:abort (push :abort result)))
result)
(:normal :always))
(deftest unwind-protect-case.3
(let (result1 result2 result3)
(ignore-errors
(unwind-protect-case ()
(error "FOOF!")
(:normal (push :normal result1))
(:abort (push :abort result1))
(:always (push :always result1))))
(catch 'foof
(unwind-protect-case ()
(throw 'foof 42)
(:normal (push :normal result2))
(:abort (push :abort result2))
(:always (push :always result2))))
(block foof
(unwind-protect-case ()
(return-from foof 42)
(:normal (push :normal result3))
(:abort (push :abort result3))
(:always (push :always result3))))
(values result1 result2 result3))
(:always :abort)
(:always :abort)
(:always :abort))
(deftest unwind-protect-case.4
(let (result)
(unwind-protect-case (aborted-p)
(random 42)
(:always (setq result aborted-p)))
result)
nil)
(deftest unwind-protect-case.5
(let (result)
(block foof
(unwind-protect-case (aborted-p)
(return-from foof)
(:always (setq result aborted-p))))
result)
t)
;;;; Control flow
(deftest switch.1
(switch (13 :test =)
(12 :oops)
(13.0 :yay))
:yay)
(deftest switch.2
(switch (13)
((+ 12 2) :oops)
((- 13 1) :oops2)
(t :yay))
:yay)
(deftest eswitch.1
(let ((x 13))
(eswitch (x :test =)
(12 :oops)
(13.0 :yay)))
:yay)
(deftest eswitch.2
(let ((x 13))
(eswitch (x :key 1+)
(11 :oops)
(14 :yay)))
:yay)
(deftest cswitch.1
(cswitch (13 :test =)
(12 :oops)
(13.0 :yay))
:yay)
(deftest cswitch.2
(cswitch (13 :key 1-)
(12 :yay)
(13.0 :oops))
:yay)
(deftest whichever.1
(let ((x (whichever 1 2 3)))
(and (member x '(1 2 3)) t))
t)
(deftest whichever.2
(let* ((a 1)
(b 2)
(c 3)
(x (whichever a b c)))
(and (member x '(1 2 3)) t))
t)
(deftest xor.1
(xor nil nil 1 nil)
1
t)
;;;; Definitions
(deftest define-constant.1
(let ((name (gensym)))
(eval `(define-constant ,name "FOO" :test 'equal))
(eval `(define-constant ,name "FOO" :test 'equal))
(values (equal "FOO" (symbol-value name))
(constantp name)))
t
t)
(deftest define-constant.2
(let ((name (gensym)))
(eval `(define-constant ,name 13))
(eval `(define-constant ,name 13))
(values (eql 13 (symbol-value name))
(constantp name)))
t
t)
;;;; Errors
TYPEP is specified to return a generalized boolean and , for
example , ECL exploits this by returning the superclasses of ERROR
;;; in this case.
(defun errorp (x)
(not (null (typep x 'error))))
(deftest required-argument.1
(multiple-value-bind (res err)
(ignore-errors (required-argument))
(errorp err))
t)
;;;; Hash tables
(deftest ensure-hash-table.1
(let ((table (make-hash-table))
(x (list 1)))
(multiple-value-bind (value already-there)
(ensure-gethash x table 42)
(and (= value 42)
(not already-there)
(= 42 (gethash x table))
(multiple-value-bind (value2 already-there2)
(ensure-gethash x table 13)
(and (= value2 42)
already-there2
(= 42 (gethash x table)))))))
t)
#+clisp (pushnew 'copy-hash-table.1 *expected-failures*)
(deftest copy-hash-table.1
(let ((orig (make-hash-table :test 'eq :size 123))
(foo "foo"))
(setf (gethash orig orig) t
(gethash foo orig) t)
(let ((eq-copy (copy-hash-table orig))
(eql-copy (copy-hash-table orig :test 'eql))
(equal-copy (copy-hash-table orig :test 'equal))
CLISP overflows the stack with this bit .
;; See <>.
#-clisp (equalp-copy (copy-hash-table orig :test 'equalp)))
(list (eql (hash-table-size eq-copy) (hash-table-size orig))
(eql (hash-table-rehash-size eq-copy)
(hash-table-rehash-size orig))
(hash-table-count eql-copy)
(gethash orig eq-copy)
(gethash (copy-seq foo) eql-copy)
(gethash foo eql-copy)
(gethash (copy-seq foo) equal-copy)
(gethash "FOO" equal-copy)
#-clisp (gethash "FOO" equalp-copy))))
(t t 2 t nil t t nil t))
(deftest copy-hash-table.2
(let ((ht (make-hash-table))
(list (list :list (vector :A :B :C))))
(setf (gethash 'list ht) list)
(let* ((shallow-copy (copy-hash-table ht))
(deep1-copy (copy-hash-table ht :key 'copy-list))
(list (gethash 'list ht))
(shallow-list (gethash 'list shallow-copy))
(deep1-list (gethash 'list deep1-copy)))
(list (eq ht shallow-copy)
(eq ht deep1-copy)
(eq list shallow-list)
(eq list deep1-list) ; outer list was copied.
(eq (second list) (second shallow-list))
(eq (second list) (second deep1-list)) ; inner vector wasn't copied.
)))
(nil nil t nil t t))
(deftest maphash-keys.1
(let ((keys nil)
(table (make-hash-table)))
(declare (notinline maphash-keys))
(dotimes (i 10)
(setf (gethash i table) t))
(maphash-keys (lambda (k) (push k keys)) table)
(set-equal keys '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest maphash-values.1
(let ((vals nil)
(table (make-hash-table)))
(declare (notinline maphash-values))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(maphash-values (lambda (v) (push v vals)) table)
(set-equal vals '(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)))
t)
(deftest hash-table-keys.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) t))
(set-equal (hash-table-keys table) '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest hash-table-values.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash (gensym) table) i))
(set-equal (hash-table-values table) '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest hash-table-alist.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(let ((alist (hash-table-alist table)))
(list (length alist)
(assoc 0 alist)
(assoc 3 alist)
(assoc 9 alist)
(assoc nil alist))))
(10 (0 . 0) (3 . -3) (9 . -9) nil))
(deftest hash-table-plist.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(let ((plist (hash-table-plist table)))
(list (length plist)
(getf plist 0)
(getf plist 2)
(getf plist 7)
(getf plist nil))))
(20 0 -2 -7 nil))
#+clisp (pushnew 'alist-hash-table.1 *expected-failures*)
(deftest alist-hash-table.1
(let* ((alist '((0 a) (1 b) (2 c)))
(table (alist-hash-table alist)))
(list (hash-table-count table)
(gethash 0 table)
(gethash 1 table)
(gethash 2 table)
CLISP returns EXT : FASTHASH - EQL .
(3 (a) (b) (c) eql))
#+clisp (pushnew 'plist-hash-table.1 *expected-failures*)
(deftest plist-hash-table.1
(let* ((plist '(:a 1 :b 2 :c 3))
(table (plist-hash-table plist :test 'eq)))
(list (hash-table-count table)
(gethash :a table)
(gethash :b table)
(gethash :c table)
(gethash 2 table)
(gethash nil table)
CLISP returns EXT : FASTHASH - EQ .
(3 1 2 3 nil nil eq))
;;;; Functions
(deftest disjoin.1
(let ((disjunction (disjoin (lambda (x)
(and (consp x) :cons))
(lambda (x)
(and (stringp x) :string)))))
(list (funcall disjunction 'zot)
(funcall disjunction '(foo bar))
(funcall disjunction "test")))
(nil :cons :string))
(deftest conjoin.1
(let ((conjunction (conjoin #'consp
(lambda (x)
(stringp (car x)))
(lambda (x)
(char (car x) 0)))))
(list (funcall conjunction 'zot)
(funcall conjunction '(foo))
(funcall conjunction '("foo"))))
(nil nil #\f))
(deftest compose.1
(let ((composite (compose '1+
(lambda (x)
(* x 2))
#'read-from-string)))
(funcall composite "1"))
3)
(deftest compose.2
(let ((composite
(locally (declare (notinline compose))
(compose '1+
(lambda (x)
(* x 2))
#'read-from-string))))
(funcall composite "2"))
5)
(deftest compose.3
(let ((compose-form (funcall (compiler-macro-function 'compose)
'(compose '1+
(lambda (x)
(* x 2))
#'read-from-string)
nil)))
(let ((fun (funcall (compile nil `(lambda () ,compose-form)))))
(funcall fun "3")))
7)
(deftest multiple-value-compose.1
(let ((composite (multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s)))))))
(multiple-value-list (funcall composite "2 7")))
(3 1))
(deftest multiple-value-compose.2
(let ((composite (locally (declare (notinline multiple-value-compose))
(multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s))))))))
(multiple-value-list (funcall composite "2 11")))
(5 1))
(deftest multiple-value-compose.3
(let ((compose-form (funcall (compiler-macro-function 'multiple-value-compose)
'(multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s)))))
nil)))
(let ((fun (funcall (compile nil `(lambda () ,compose-form)))))
(multiple-value-list (funcall fun "2 9"))))
(4 1))
(deftest curry.1
(let ((curried (curry '+ 3)))
(funcall curried 1 5))
9)
(deftest curry.2
(let ((curried (locally (declare (notinline curry))
(curry '* 2 3))))
(funcall curried 7))
42)
(deftest curry.3
(let ((curried-form (funcall (compiler-macro-function 'curry)
'(curry '/ 8)
nil)))
(let ((fun (funcall (compile nil `(lambda () ,curried-form)))))
(funcall fun 2)))
4)
(deftest rcurry.1
(let ((r (rcurry '/ 2)))
(funcall r 8))
4)
(deftest named-lambda.1
(let ((fac (named-lambda fac (x)
(if (> x 1)
(* x (fac (- x 1)))
x))))
(funcall fac 5))
120)
(deftest named-lambda.2
(let ((fac (named-lambda fac (&key x)
(if (> x 1)
(* x (fac :x (- x 1)))
x))))
(funcall fac :x 5))
120)
;;;; Lists
(deftest alist-plist.1
(alist-plist '((a . 1) (b . 2) (c . 3)))
(a 1 b 2 c 3))
(deftest plist-alist.1
(plist-alist '(a 1 b 2 c 3))
((a . 1) (b . 2) (c . 3)))
(deftest unionf.1
(let* ((list (list 1 2 3))
(orig list))
(unionf list (list 1 2 4))
(values (equal orig (list 1 2 3))
(eql (length list) 4)
(set-difference list (list 1 2 3 4))
(set-difference (list 1 2 3 4) list)))
t
t
nil
nil)
(deftest nunionf.1
(let ((list (list 1 2 3)))
(nunionf list (list 1 2 4))
(values (eql (length list) 4)
(set-difference (list 1 2 3 4) list)
(set-difference list (list 1 2 3 4))))
t
nil
nil)
(deftest appendf.1
(let* ((list (list 1 2 3))
(orig list))
(appendf list '(4 5 6) '(7 8))
(list list (eq list orig)))
((1 2 3 4 5 6 7 8) nil))
(deftest nconcf.1
(let ((list1 (list 1 2 3))
(list2 (list 4 5 6)))
(nconcf list1 list2 (list 7 8 9))
list1)
(1 2 3 4 5 6 7 8 9))
(deftest circular-list.1
(let ((circle (circular-list 1 2 3)))
(list (first circle)
(second circle)
(third circle)
(fourth circle)
(eq circle (nthcdr 3 circle))))
(1 2 3 1 t))
(deftest circular-list-p.1
(let* ((circle (circular-list 1 2 3 4))
(tree (list circle circle))
(dotted (cons circle t))
(proper (list 1 2 3 circle))
(tailcirc (list* 1 2 3 circle)))
(list (circular-list-p circle)
(circular-list-p tree)
(circular-list-p dotted)
(circular-list-p proper)
(circular-list-p tailcirc)))
(t nil nil nil t))
(deftest circular-list-p.2
(circular-list-p 'foo)
nil)
(deftest circular-tree-p.1
(let* ((circle (circular-list 1 2 3 4))
(tree1 (list circle circle))
(tree2 (let* ((level2 (list 1 nil 2))
(level1 (list level2)))
(setf (second level2) level1)
level1))
(dotted (cons circle t))
(proper (list 1 2 3 circle))
(tailcirc (list* 1 2 3 circle))
(quite-proper (list 1 2 3))
(quite-dotted (list 1 (cons 2 3))))
(list (circular-tree-p circle)
(circular-tree-p tree1)
(circular-tree-p tree2)
(circular-tree-p dotted)
(circular-tree-p proper)
(circular-tree-p tailcirc)
(circular-tree-p quite-proper)
(circular-tree-p quite-dotted)))
(t t t t t t nil nil))
(deftest proper-list-p.1
(let ((l1 (list 1))
(l2 (list 1 2))
(l3 (cons 1 2))
(l4 (list (cons 1 2) 3))
(l5 (circular-list 1 2)))
(list (proper-list-p l1)
(proper-list-p l2)
(proper-list-p l3)
(proper-list-p l4)
(proper-list-p l5)))
(t t nil t nil))
(deftest proper-list-p.2
(proper-list-p '(1 2 . 3))
nil)
(deftest proper-list.type.1
(let ((l1 (list 1))
(l2 (list 1 2))
(l3 (cons 1 2))
(l4 (list (cons 1 2) 3))
(l5 (circular-list 1 2)))
(list (typep l1 'proper-list)
(typep l2 'proper-list)
(typep l3 'proper-list)
(typep l4 'proper-list)
(typep l5 'proper-list)))
(t t nil t nil))
(deftest proper-list-length.1
(values
(proper-list-length nil)
(proper-list-length (list 1))
(proper-list-length (list 2 2))
(proper-list-length (list 3 3 3))
(proper-list-length (list 4 4 4 4))
(proper-list-length (list 5 5 5 5 5))
(proper-list-length (list 6 6 6 6 6 6))
(proper-list-length (list 7 7 7 7 7 7 7))
(proper-list-length (list 8 8 8 8 8 8 8 8))
(proper-list-length (list 9 9 9 9 9 9 9 9 9)))
0 1 2 3 4 5 6 7 8 9)
(deftest proper-list-length.2
(flet ((plength (x)
(handler-case
(proper-list-length x)
(type-error ()
:ok))))
(values
(plength (list* 1))
(plength (list* 2 2))
(plength (list* 3 3 3))
(plength (list* 4 4 4 4))
(plength (list* 5 5 5 5 5))
(plength (list* 6 6 6 6 6 6))
(plength (list* 7 7 7 7 7 7 7))
(plength (list* 8 8 8 8 8 8 8 8))
(plength (list* 9 9 9 9 9 9 9 9 9))))
:ok :ok :ok
:ok :ok :ok
:ok :ok :ok)
(deftest lastcar.1
(let ((l1 (list 1))
(l2 (list 1 2)))
(list (lastcar l1)
(lastcar l2)))
(1 2))
(deftest lastcar.error.2
(handler-case
(progn
(lastcar (circular-list 1 2 3))
nil)
(error ()
t))
t)
(deftest setf-lastcar.1
(let ((l (list 1 2 3 4)))
(values (lastcar l)
(progn
(setf (lastcar l) 42)
(lastcar l))))
4
42)
(deftest setf-lastcar.2
(let ((l (circular-list 1 2 3)))
(multiple-value-bind (res err)
(ignore-errors (setf (lastcar l) 4))
(typep err 'type-error)))
t)
(deftest make-circular-list.1
(let ((l (make-circular-list 3 :initial-element :x)))
(setf (car l) :y)
(list (eq l (nthcdr 3 l))
(first l)
(second l)
(third l)
(fourth l)))
(t :y :x :x :y))
(deftest circular-list.type.1
(let* ((l1 (list 1 2 3))
(l2 (circular-list 1 2 3))
(l3 (list* 1 2 3 l2)))
(list (typep l1 'circular-list)
(typep l2 'circular-list)
(typep l3 'circular-list)))
(nil t t))
(deftest ensure-list.1
(let ((x (list 1))
(y 2))
(list (ensure-list x)
(ensure-list y)))
((1) (2)))
(deftest ensure-cons.1
(let ((x (cons 1 2))
(y nil)
(z "foo"))
(values (ensure-cons x)
(ensure-cons y)
(ensure-cons z)))
(1 . 2)
(nil)
("foo"))
(deftest setp.1
(setp '(1))
t)
(deftest setp.2
(setp nil)
t)
(deftest setp.3
(setp "foo")
nil)
(deftest setp.4
(setp '(1 2 3 1))
nil)
(deftest setp.5
(setp '(1 2 3))
t)
(deftest setp.6
(setp '(a :a))
t)
(deftest setp.7
(setp '(a :a) :key 'character)
nil)
(deftest setp.8
(setp '(a :a) :key 'character :test (constantly nil))
t)
(deftest set-equal.1
(set-equal '(1 2 3) '(3 1 2))
t)
(deftest set-equal.2
(set-equal '("Xa") '("Xb")
:test (lambda (a b) (eql (char a 0) (char b 0))))
t)
(deftest set-equal.3
(set-equal '(1 2) '(4 2))
nil)
(deftest set-equal.4
(set-equal '(a b c) '(:a :b :c) :key 'string :test 'equal)
t)
(deftest set-equal.5
(set-equal '(a d c) '(:a :b :c) :key 'string :test 'equal)
nil)
(deftest set-equal.6
(set-equal '(a b c) '(a b c d))
nil)
(deftest map-product.1
(map-product 'cons '(2 3) '(1 4))
((2 . 1) (2 . 4) (3 . 1) (3 . 4)))
(deftest map-product.2
(map-product #'cons '(2 3) '(1 4))
((2 . 1) (2 . 4) (3 . 1) (3 . 4)))
(deftest flatten.1
(flatten '((1) 2 (((3 4))) ((((5)) 6)) 7))
(1 2 3 4 5 6 7))
(deftest remove-from-plist.1
(let ((orig '(a 1 b 2 c 3 d 4)))
(list (remove-from-plist orig 'a 'c)
(remove-from-plist orig 'b 'd)
(remove-from-plist orig 'b)
(remove-from-plist orig 'a)
(remove-from-plist orig 'd 42 "zot")
(remove-from-plist orig 'a 'b 'c 'd)
(remove-from-plist orig 'a 'b 'c 'd 'x)
(equal orig '(a 1 b 2 c 3 d 4))))
((b 2 d 4)
(a 1 c 3)
(a 1 c 3 d 4)
(b 2 c 3 d 4)
(a 1 b 2 c 3)
nil
nil
t))
(deftest mappend.1
(mappend (compose 'list '*) '(1 2 3) '(1 2 3))
(1 4 9))
;;;; Numbers
(deftest clamp.1
(list (clamp 1.5 1 2)
(clamp 2.0 1 2)
(clamp 1.0 1 2)
(clamp 3 1 2)
(clamp 0 1 2))
(1.5 2.0 1.0 2 1))
(deftest gaussian-random.1
(let ((min -0.2)
(max +0.2))
(multiple-value-bind (g1 g2)
(gaussian-random min max)
(values (<= min g1 max)
(<= min g2 max)
(/= g1 g2) ;uh
)))
t
t
t)
(deftest iota.1
(iota 3)
(0 1 2))
(deftest iota.2
(iota 3 :start 0.0d0)
(0.0d0 1.0d0 2.0d0))
(deftest iota.3
(iota 3 :start 2 :step 3.0)
(2.0 5.0 8.0))
(deftest map-iota.1
(let (all)
(declare (notinline map-iota))
(values (map-iota (lambda (x) (push x all))
3
:start 2
:step 1.1d0)
all))
3
(4.2d0 3.1d0 2.0d0))
(deftest lerp.1
(lerp 0.5 1 2)
1.5)
(deftest lerp.2
(lerp 0.1 1 2)
1.1)
(deftest mean.1
(mean '(1 2 3))
2)
(deftest mean.2
(mean '(1 2 3 4))
5/2)
(deftest mean.3
(mean '(1 2 10))
13/3)
(deftest median.1
(median '(100 0 99 1 98 2 97))
97)
(deftest median.2
(median '(100 0 99 1 98 2 97 96))
195/2)
(deftest variance.1
(variance (list 1 2 3))
2/3)
(deftest standard-deviation.1
(< 0 (standard-deviation (list 1 2 3)) 1)
t)
(deftest maxf.1
(let ((x 1))
(maxf x 2)
x)
2)
(deftest maxf.2
(let ((x 1))
(maxf x 0)
x)
1)
(deftest maxf.3
(let ((x 1)
(c 0))
(maxf x (incf c))
(list x c))
(1 1))
(deftest maxf.4
(let ((xv (vector 0 0 0))
(p 0))
(maxf (svref xv (incf p)) (incf p))
(list p xv))
(2 #(0 2 0)))
(deftest minf.1
(let ((y 1))
(minf y 0)
y)
0)
(deftest minf.2
(let ((xv (vector 10 10 10))
(p 0))
(minf (svref xv (incf p)) (incf p))
(list p xv))
(2 #(10 2 10)))
;;;; Arrays
#+nil
(deftest array-index.type)
#+nil
(deftest copy-array)
;;;; Sequences
(deftest rotate.1
(list (rotate (list 1 2 3) 0)
(rotate (list 1 2 3) 1)
(rotate (list 1 2 3) 2)
(rotate (list 1 2 3) 3)
(rotate (list 1 2 3) 4))
((1 2 3)
(3 1 2)
(2 3 1)
(1 2 3)
(3 1 2)))
(deftest rotate.2
(list (rotate (vector 1 2 3 4) 0)
(rotate (vector 1 2 3 4))
(rotate (vector 1 2 3 4) 2)
(rotate (vector 1 2 3 4) 3)
(rotate (vector 1 2 3 4) 4)
(rotate (vector 1 2 3 4) 5))
(#(1 2 3 4)
#(4 1 2 3)
#(3 4 1 2)
#(2 3 4 1)
#(1 2 3 4)
#(4 1 2 3)))
(deftest rotate.3
(list (rotate (list 1 2 3) 0)
(rotate (list 1 2 3) -1)
(rotate (list 1 2 3) -2)
(rotate (list 1 2 3) -3)
(rotate (list 1 2 3) -4))
((1 2 3)
(2 3 1)
(3 1 2)
(1 2 3)
(2 3 1)))
(deftest rotate.4
(list (rotate (vector 1 2 3 4) 0)
(rotate (vector 1 2 3 4) -1)
(rotate (vector 1 2 3 4) -2)
(rotate (vector 1 2 3 4) -3)
(rotate (vector 1 2 3 4) -4)
(rotate (vector 1 2 3 4) -5))
(#(1 2 3 4)
#(2 3 4 1)
#(3 4 1 2)
#(4 1 2 3)
#(1 2 3 4)
#(2 3 4 1)))
(deftest rotate.5
(values (rotate (list 1) 17)
(rotate (list 1) -5))
(1)
(1))
(deftest shuffle.1
(let ((s (shuffle (iota 100))))
(list (equal s (iota 100))
(every (lambda (x)
(member x s))
(iota 100))
(every (lambda (x)
(typep x '(integer 0 99)))
s)))
(nil t t))
(deftest shuffle.2
(let ((s (shuffle (coerce (iota 100) 'vector))))
(list (equal s (coerce (iota 100) 'vector))
(every (lambda (x)
(find x s))
(iota 100))
(every (lambda (x)
(typep x '(integer 0 99)))
s)))
(nil t t))
(deftest random-elt.1
(let ((s1 #(1 2 3 4))
(s2 '(1 2 3 4)))
(list (dotimes (i 1000 nil)
(unless (member (random-elt s1) s2)
(return nil))
(when (/= (random-elt s1) (random-elt s1))
(return t)))
(dotimes (i 1000 nil)
(unless (member (random-elt s2) s2)
(return nil))
(when (/= (random-elt s2) (random-elt s2))
(return t)))))
(t t))
(deftest removef.1
(let* ((x '(1 2 3))
(x* x)
(y #(1 2 3))
(y* y))
(removef x 1)
(removef y 3)
(list x x* y y*))
((2 3)
(1 2 3)
#(1 2)
#(1 2 3)))
(deftest deletef.1
(let* ((x (list 1 2 3))
(x* x)
(y (vector 1 2 3)))
(deletef x 2)
(deletef y 1)
(list x x* y))
((1 3)
(1 3)
#(2 3)))
(deftest map-permutations.1
(let ((seq (list 1 2 3))
(seen nil)
(ok t))
(map-permutations (lambda (s)
(unless (set-equal s seq)
(setf ok nil))
(when (member s seen :test 'equal)
(setf ok nil))
(push s seen))
seq
:copy t)
(values ok (length seen)))
t
6)
(deftest proper-sequence.type.1
(mapcar (lambda (x)
(typep x 'proper-sequence))
(list (list 1 2 3)
(vector 1 2 3)
#2a((1 2) (3 4))
(circular-list 1 2 3 4)))
(t t nil nil))
(deftest emptyp.1
(mapcar #'emptyp
(list (list 1)
(circular-list 1)
nil
(vector)
(vector 1)))
(nil nil t t nil))
(deftest sequence-of-length-p.1
(mapcar #'sequence-of-length-p
(list nil
#()
(list 1)
(vector 1)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2))
(list 0
0
1
1
2
2
1
1
4
4))
(t t t t t t nil nil nil nil))
(deftest length=.1
(mapcar #'length=
(list nil
#()
(list 1)
(vector 1)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2))
(list 0
0
1
1
2
2
1
1
4
4))
(t t t t t t nil nil nil nil))
(deftest length=.2
;; test the compiler macro
(macrolet ((x (&rest args)
(funcall
(compile nil
`(lambda ()
(length= ,@args))))))
(list (x 2 '(1 2))
(x '(1 2) '(3 4))
(x '(1 2) 2)
(x '(1 2) 2 '(3 4))
(x 1 2 3)))
(t t t t nil))
(deftest copy-sequence.1
(let ((l (list 1 2 3))
(v (vector #\a #\b #\c)))
(declare (notinline copy-sequence))
(let ((l.list (copy-sequence 'list l))
(l.vector (copy-sequence 'vector l))
(l.spec-v (copy-sequence '(vector fixnum) l))
(v.vector (copy-sequence 'vector v))
(v.list (copy-sequence 'list v))
(v.string (copy-sequence 'string v)))
(list (member l (list l.list l.vector l.spec-v))
(member v (list v.vector v.list v.string))
(equal l.list l)
(equalp l.vector #(1 2 3))
(eql (upgraded-array-element-type 'fixnum)
(array-element-type l.spec-v))
(equalp v.vector v)
(equal v.list '(#\a #\b #\c))
(equal "abc" v.string))))
(nil nil t t t t t t))
(deftest first-elt.1
(mapcar #'first-elt
(list (list 1 2 3)
"abc"
(vector :a :b :c)))
(1 #\a :a))
(deftest first-elt.error.1
(mapcar (lambda (x)
(handler-case
(first-elt x)
(type-error ()
:type-error)))
(list nil
#()
12
:zot))
(:type-error
:type-error
:type-error
:type-error))
(deftest setf-first-elt.1
(let ((l (list 1 2 3))
(s (copy-seq "foobar"))
(v (vector :a :b :c)))
(setf (first-elt l) -1
(first-elt s) #\x
(first-elt v) 'zot)
(values l s v))
(-1 2 3)
"xoobar"
#(zot :b :c))
(deftest setf-first-elt.error.1
(let ((l 'foo))
(multiple-value-bind (res err)
(ignore-errors (setf (first-elt l) 4))
(typep err 'type-error)))
t)
(deftest last-elt.1
(mapcar #'last-elt
(list (list 1 2 3)
(vector :a :b :c)
"FOOBAR"
#*001
#*010))
(3 :c #\R 1 0))
(deftest last-elt.error.1
(mapcar (lambda (x)
(handler-case
(last-elt x)
(type-error ()
:type-error)))
(list nil
#()
12
:zot
(circular-list 1 2 3)
(list* 1 2 3 (circular-list 4 5))))
(:type-error
:type-error
:type-error
:type-error
:type-error
:type-error))
(deftest setf-last-elt.1
(let ((l (list 1 2 3))
(s (copy-seq "foobar"))
(b (copy-seq #*010101001)))
(setf (last-elt l) '???
(last-elt s) #\?
(last-elt b) 0)
(values l s b))
(1 2 ???)
"fooba?"
#*010101000)
(deftest setf-last-elt.error.1
(handler-case
(setf (last-elt 'foo) 13)
(type-error ()
:type-error))
:type-error)
(deftest starts-with.1
(list (starts-with 1 '(1 2 3))
(starts-with 1 #(1 2 3))
(starts-with #\x "xyz")
(starts-with 2 '(1 2 3))
(starts-with 3 #(1 2 3))
(starts-with 1 1)
(starts-with nil nil))
(t t t nil nil nil nil))
(deftest starts-with.2
(values (starts-with 1 '(-1 2 3) :key '-)
(starts-with "foo" '("foo" "bar") :test 'equal)
(starts-with "f" '(#\f) :key 'string :test 'equal)
(starts-with -1 '(0 1 2) :key #'1+)
(starts-with "zot" '("ZOT") :test 'equal))
t
t
t
nil
nil)
(deftest ends-with.1
(list (ends-with 3 '(1 2 3))
(ends-with 3 #(1 2 3))
(ends-with #\z "xyz")
(ends-with 2 '(1 2 3))
(ends-with 1 #(1 2 3))
(ends-with 1 1)
(ends-with nil nil))
(t t t nil nil nil nil))
(deftest ends-with.2
(values (ends-with 2 '(0 13 1) :key '1+)
(ends-with "foo" (vector "bar" "foo") :test 'equal)
(ends-with "X" (vector 1 2 #\X) :key 'string :test 'equal)
(ends-with "foo" "foo" :test 'equal))
t
t
t
nil)
(deftest ends-with.error.1
(handler-case
(ends-with 3 (circular-list 3 3 3 1 3 3))
(type-error ()
:type-error))
:type-error)
(deftest sequences.passing-improper-lists
(macrolet ((signals-error-p (form)
`(handler-case
(progn ,form nil)
(type-error (e)
t)))
(cut (fn &rest args)
(with-gensyms (arg)
(print`(lambda (,arg)
(apply ,fn (list ,@(substitute arg '_ args))))))))
(let ((circular-list (make-circular-list 5 :initial-element :foo))
(dotted-list (list* 'a 'b 'c 'd)))
(loop for nth from 0
for fn in (list
(cut #'lastcar _)
(cut #'rotate _ 3)
(cut #'rotate _ -3)
(cut #'shuffle _)
(cut #'random-elt _)
(cut #'last-elt _)
(cut #'ends-with :foo _))
nconcing
(let ((on-circular-p (signals-error-p (funcall fn circular-list)))
(on-dotted-p (signals-error-p (funcall fn dotted-list))))
(when (or (not on-circular-p) (not on-dotted-p))
(append
(unless on-circular-p
(let ((*print-circle* t))
(list
(format nil
"No appropriate error signalled when passing ~S to ~Ath entry."
circular-list nth))))
(unless on-dotted-p
(list
(format nil
"No appropriate error signalled when passing ~S to ~Ath entry."
dotted-list nth)))))))))
nil)
(deftest with-unique-names.1
(let ((*gensym-counter* 0))
(let ((syms (with-unique-names (foo bar quux)
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("FOO0" "BAR1" "QUUX2")
(mapcar #'symbol-name syms)))))
(nil t))
(deftest with-unique-names.2
(let ((*gensym-counter* 0))
(let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux #\q))
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("_foo_0" "-BAR-1" "q2")
(mapcar #'symbol-name syms)))))
(nil t))
(deftest with-unique-names.3
(let ((*gensym-counter* 0))
(multiple-value-bind (res err)
(ignore-errors
(eval
'(let ((syms
(with-unique-names ((foo "_foo_") (bar -bar-) (quux 42))
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("_foo_0" "-BAR-1" "q2")
(mapcar #'symbol-name syms))))))
(errorp err)))
t)
(deftest once-only.1
(macrolet ((cons1.good (x)
(once-only (x)
`(cons ,x ,x)))
(cons1.bad (x)
`(cons ,x ,x)))
(let ((y 0))
(list (cons1.good (incf y))
y
(cons1.bad (incf y))
y)))
((1 . 1) 1 (2 . 3) 3))
(deftest once-only.2
(macrolet ((cons1 (x)
(once-only ((y x))
`(cons ,y ,y))))
(let ((z 0))
(list (cons1 (incf z))
z
(cons1 (incf z)))))
((1 . 1) 1 (2 . 2)))
(deftest parse-body.1
(parse-body '("doc" "body") :documentation t)
("body")
nil
"doc")
(deftest parse-body.2
(parse-body '("body") :documentation t)
("body")
nil
nil)
(deftest parse-body.3
(parse-body '("doc" "body"))
("doc" "body")
nil
nil)
(deftest parse-body.4
(parse-body '((declare (foo)) "doc" (declare (bar)) body) :documentation t)
(body)
((declare (foo)) (declare (bar)))
"doc")
(deftest parse-body.5
(parse-body '((declare (foo)) "doc" (declare (bar)) body))
("doc" (declare (bar)) body)
((declare (foo)))
nil)
(deftest parse-body.6
(multiple-value-bind (res err)
(ignore-errors
(parse-body '("foo" "bar" "quux")
:documentation t))
(errorp err))
t)
;;;; Symbols
(deftest ensure-symbol.1
(ensure-symbol :cons :cl)
cons
:external)
(deftest ensure-symbol.2
(ensure-symbol "CONS" :alexandria)
cons
:inherited)
(deftest ensure-symbol.3
(ensure-symbol 'foo :keyword)
:foo
:external)
(deftest ensure-symbol.4
(ensure-symbol #\* :alexandria)
*
:inherited)
(deftest format-symbol.1
(let ((s (format-symbol nil "X-~D" 13)))
(list (symbol-package s)
(symbol-name s)))
(nil "X-13"))
(deftest format-symbol.2
(format-symbol :keyword "SYM-~A" :bolic)
:sym-bolic)
(deftest format-symbol.3
(let ((*package* (find-package :cl)))
(format-symbol t "FIND-~A" 'package))
find-package)
(deftest make-keyword.1
(list (make-keyword 'zot)
(make-keyword "FOO")
(make-keyword #\Q))
(:zot :foo :q))
(deftest make-gensym-list.1
(let ((*gensym-counter* 0))
(let ((syms (make-gensym-list 3 "FOO")))
(list (find-if 'symbol-package syms)
(equal '("FOO0" "FOO1" "FOO2")
(mapcar 'symbol-name syms)))))
(nil t))
(deftest make-gensym-list.2
(let ((*gensym-counter* 0))
(let ((syms (make-gensym-list 3)))
(list (find-if 'symbol-package syms)
(equal '("G0" "G1" "G2")
(mapcar 'symbol-name syms)))))
(nil t))
;;;; Type-system
(deftest of-type.1
(locally
(declare (notinline of-type))
(let ((f (of-type 'string)))
(list (funcall f "foo")
(funcall f 'bar))))
(t nil))
(deftest type=.1
(type= 'string 'string)
t
t)
(deftest type=.2
(type= 'list '(or null cons))
t
t)
(deftest type=.3
(type= 'null '(and symbol list))
t
t)
(deftest type=.4
(type= 'string '(satisfies emptyp))
nil
nil)
(deftest type=.5
(type= 'string 'list)
nil
t)
(macrolet
((test (type numbers)
`(deftest ,(format-symbol t "CDR5.~A" type)
(let ((numbers ,numbers))
(values (mapcar (of-type ',(format-symbol t "NEGATIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "NON-POSITIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "NON-NEGATIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "POSITIVE-~A" type)) numbers)))
(t t t nil nil nil nil)
(t t t t nil nil nil)
(nil nil nil t t t t)
(nil nil nil nil t t t))))
(test fixnum (list most-negative-fixnum -42 -1 0 1 42 most-positive-fixnum))
(test integer (list (1- most-negative-fixnum) -42 -1 0 1 42 (1+ most-positive-fixnum)))
(test rational (list (1- most-negative-fixnum) -42/13 -1 0 1 42/13 (1+ most-positive-fixnum)))
(test real (list most-negative-long-float -42/13 -1 0 1 42/13 most-positive-long-float))
(test float (list most-negative-short-float -42.02 -1.0 0.0 1.0 42.02 most-positive-short-float))
(test short-float (list most-negative-short-float -42.02s0 -1.0s0 0.0s0 1.0s0 42.02s0 most-positive-short-float))
(test single-float (list most-negative-single-float -42.02f0 -1.0f0 0.0f0 1.0f0 42.02f0 most-positive-single-float))
(test double-float (list most-negative-double-float -42.02d0 -1.0d0 0.0d0 1.0d0 42.02d0 most-positive-double-float))
(test long-float (list most-negative-long-float -42.02l0 -1.0l0 0.0l0 1.0l0 42.02l0 most-positive-long-float)))
;;;; Bindings
(declaim (notinline opaque))
(defun opaque (x)
x)
(deftest if-let.1
(if-let (x (opaque :ok))
x
:bad)
:ok)
(deftest if-let.2
(if-let (x (opaque nil))
:bad
(and (not x) :ok))
:ok)
(deftest if-let.3
(let ((x 1))
(if-let ((x 2)
(y x))
(+ x y)
:oops))
3)
(deftest if-let.4
(if-let ((x 1)
(y nil))
:oops
(and (not y) x))
1)
(deftest if-let.5
(if-let (x)
:oops
(not x))
t)
(deftest if-let.error.1
(handler-case
(eval '(if-let x
:oops
:oops))
(type-error ()
:type-error))
:type-error)
(deftest when-let.1
(when-let (x (opaque :ok))
(setf x (cons x x))
x)
(:ok . :ok))
(deftest when-let.2
(when-let ((x 1)
(y nil)
(z 3))
:oops)
nil)
(deftest when-let.3
(let ((x 1))
(when-let ((x 2)
(y x))
(+ x y)))
3)
(deftest when-let.error.1
(handler-case
(eval '(when-let x :oops))
(type-error ()
:type-error))
:type-error)
(deftest when-let*.1
(let ((x 1))
(when-let* ((x 2)
(y x))
(+ x y)))
4)
(deftest when-let*.2
(let ((y 1))
(when-let* (x y)
(1+ x)))
2)
(deftest when-let*.3
(when-let* ((x t)
(y (consp x))
(z (error "OOPS")))
t)
nil)
(deftest when-let*.error.1
(handler-case
(eval '(when-let* x :oops))
(type-error ()
:type-error))
:type-error)
(deftest nth-value-or.1
(multiple-value-bind (a b c)
(nth-value-or 1
(values 1 nil 1)
(values 2 2 2))
(= a b c 2))
t)
(deftest doplist.1
(let (keys values)
(doplist (k v '(a 1 b 2 c 3) (values t (reverse keys) (reverse values) k v))
(push k keys)
(push v values)))
t
(a b c)
(1 2 3)
nil
nil)
| null | https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/alexandria/tests.lisp | lisp | Arrays
Conditions
Control flow
Definitions
Errors
in this case.
Hash tables
See <>.
outer list was copied.
inner vector wasn't copied.
Functions
Lists
Numbers
uh
Arrays
Sequences
test the compiler macro
Symbols
Type-system
Bindings | (in-package :cl-user)
(defpackage :alexandria-tests
(:use :cl :alexandria #+sbcl :sb-rt #-sbcl :rtest)
(:import-from #+sbcl :sb-rt #-sbcl :rtest
#:*compile-tests* #:*expected-failures*))
(in-package :alexandria-tests)
(defun run-tests (&key ((:compiled *compile-tests)))
(do-tests))
(deftest copy-array.1
(let* ((orig (vector 1 2 3))
(copy (copy-array orig)))
(values (eq orig copy) (equalp orig copy)))
nil t)
(deftest copy-array.2
(let ((orig (make-array 1024 :fill-pointer 0)))
(vector-push-extend 1 orig)
(vector-push-extend 2 orig)
(vector-push-extend 3 orig)
(let ((copy (copy-array orig)))
(values (eq orig copy) (equalp orig copy)
(array-has-fill-pointer-p copy)
(eql (fill-pointer orig) (fill-pointer copy)))))
nil t t t)
(deftest array-index.1
(typep 0 'array-index)
t)
(deftest unwind-protect-case.1
(let (result)
(unwind-protect-case ()
(random 10)
(:normal (push :normal result))
(:abort (push :abort result))
(:always (push :always result)))
result)
(:always :normal))
(deftest unwind-protect-case.2
(let (result)
(unwind-protect-case ()
(random 10)
(:always (push :always result))
(:normal (push :normal result))
(:abort (push :abort result)))
result)
(:normal :always))
(deftest unwind-protect-case.3
(let (result1 result2 result3)
(ignore-errors
(unwind-protect-case ()
(error "FOOF!")
(:normal (push :normal result1))
(:abort (push :abort result1))
(:always (push :always result1))))
(catch 'foof
(unwind-protect-case ()
(throw 'foof 42)
(:normal (push :normal result2))
(:abort (push :abort result2))
(:always (push :always result2))))
(block foof
(unwind-protect-case ()
(return-from foof 42)
(:normal (push :normal result3))
(:abort (push :abort result3))
(:always (push :always result3))))
(values result1 result2 result3))
(:always :abort)
(:always :abort)
(:always :abort))
(deftest unwind-protect-case.4
(let (result)
(unwind-protect-case (aborted-p)
(random 42)
(:always (setq result aborted-p)))
result)
nil)
(deftest unwind-protect-case.5
(let (result)
(block foof
(unwind-protect-case (aborted-p)
(return-from foof)
(:always (setq result aborted-p))))
result)
t)
(deftest switch.1
(switch (13 :test =)
(12 :oops)
(13.0 :yay))
:yay)
(deftest switch.2
(switch (13)
((+ 12 2) :oops)
((- 13 1) :oops2)
(t :yay))
:yay)
(deftest eswitch.1
(let ((x 13))
(eswitch (x :test =)
(12 :oops)
(13.0 :yay)))
:yay)
(deftest eswitch.2
(let ((x 13))
(eswitch (x :key 1+)
(11 :oops)
(14 :yay)))
:yay)
(deftest cswitch.1
(cswitch (13 :test =)
(12 :oops)
(13.0 :yay))
:yay)
(deftest cswitch.2
(cswitch (13 :key 1-)
(12 :yay)
(13.0 :oops))
:yay)
(deftest whichever.1
(let ((x (whichever 1 2 3)))
(and (member x '(1 2 3)) t))
t)
(deftest whichever.2
(let* ((a 1)
(b 2)
(c 3)
(x (whichever a b c)))
(and (member x '(1 2 3)) t))
t)
(deftest xor.1
(xor nil nil 1 nil)
1
t)
(deftest define-constant.1
(let ((name (gensym)))
(eval `(define-constant ,name "FOO" :test 'equal))
(eval `(define-constant ,name "FOO" :test 'equal))
(values (equal "FOO" (symbol-value name))
(constantp name)))
t
t)
(deftest define-constant.2
(let ((name (gensym)))
(eval `(define-constant ,name 13))
(eval `(define-constant ,name 13))
(values (eql 13 (symbol-value name))
(constantp name)))
t
t)
TYPEP is specified to return a generalized boolean and , for
example , ECL exploits this by returning the superclasses of ERROR
(defun errorp (x)
(not (null (typep x 'error))))
(deftest required-argument.1
(multiple-value-bind (res err)
(ignore-errors (required-argument))
(errorp err))
t)
(deftest ensure-hash-table.1
(let ((table (make-hash-table))
(x (list 1)))
(multiple-value-bind (value already-there)
(ensure-gethash x table 42)
(and (= value 42)
(not already-there)
(= 42 (gethash x table))
(multiple-value-bind (value2 already-there2)
(ensure-gethash x table 13)
(and (= value2 42)
already-there2
(= 42 (gethash x table)))))))
t)
#+clisp (pushnew 'copy-hash-table.1 *expected-failures*)
(deftest copy-hash-table.1
(let ((orig (make-hash-table :test 'eq :size 123))
(foo "foo"))
(setf (gethash orig orig) t
(gethash foo orig) t)
(let ((eq-copy (copy-hash-table orig))
(eql-copy (copy-hash-table orig :test 'eql))
(equal-copy (copy-hash-table orig :test 'equal))
CLISP overflows the stack with this bit .
#-clisp (equalp-copy (copy-hash-table orig :test 'equalp)))
(list (eql (hash-table-size eq-copy) (hash-table-size orig))
(eql (hash-table-rehash-size eq-copy)
(hash-table-rehash-size orig))
(hash-table-count eql-copy)
(gethash orig eq-copy)
(gethash (copy-seq foo) eql-copy)
(gethash foo eql-copy)
(gethash (copy-seq foo) equal-copy)
(gethash "FOO" equal-copy)
#-clisp (gethash "FOO" equalp-copy))))
(t t 2 t nil t t nil t))
(deftest copy-hash-table.2
(let ((ht (make-hash-table))
(list (list :list (vector :A :B :C))))
(setf (gethash 'list ht) list)
(let* ((shallow-copy (copy-hash-table ht))
(deep1-copy (copy-hash-table ht :key 'copy-list))
(list (gethash 'list ht))
(shallow-list (gethash 'list shallow-copy))
(deep1-list (gethash 'list deep1-copy)))
(list (eq ht shallow-copy)
(eq ht deep1-copy)
(eq list shallow-list)
(eq (second list) (second shallow-list))
)))
(nil nil t nil t t))
(deftest maphash-keys.1
(let ((keys nil)
(table (make-hash-table)))
(declare (notinline maphash-keys))
(dotimes (i 10)
(setf (gethash i table) t))
(maphash-keys (lambda (k) (push k keys)) table)
(set-equal keys '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest maphash-values.1
(let ((vals nil)
(table (make-hash-table)))
(declare (notinline maphash-values))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(maphash-values (lambda (v) (push v vals)) table)
(set-equal vals '(0 -1 -2 -3 -4 -5 -6 -7 -8 -9)))
t)
(deftest hash-table-keys.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) t))
(set-equal (hash-table-keys table) '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest hash-table-values.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash (gensym) table) i))
(set-equal (hash-table-values table) '(0 1 2 3 4 5 6 7 8 9)))
t)
(deftest hash-table-alist.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(let ((alist (hash-table-alist table)))
(list (length alist)
(assoc 0 alist)
(assoc 3 alist)
(assoc 9 alist)
(assoc nil alist))))
(10 (0 . 0) (3 . -3) (9 . -9) nil))
(deftest hash-table-plist.1
(let ((table (make-hash-table)))
(dotimes (i 10)
(setf (gethash i table) (- i)))
(let ((plist (hash-table-plist table)))
(list (length plist)
(getf plist 0)
(getf plist 2)
(getf plist 7)
(getf plist nil))))
(20 0 -2 -7 nil))
#+clisp (pushnew 'alist-hash-table.1 *expected-failures*)
(deftest alist-hash-table.1
(let* ((alist '((0 a) (1 b) (2 c)))
(table (alist-hash-table alist)))
(list (hash-table-count table)
(gethash 0 table)
(gethash 1 table)
(gethash 2 table)
CLISP returns EXT : FASTHASH - EQL .
(3 (a) (b) (c) eql))
#+clisp (pushnew 'plist-hash-table.1 *expected-failures*)
(deftest plist-hash-table.1
(let* ((plist '(:a 1 :b 2 :c 3))
(table (plist-hash-table plist :test 'eq)))
(list (hash-table-count table)
(gethash :a table)
(gethash :b table)
(gethash :c table)
(gethash 2 table)
(gethash nil table)
CLISP returns EXT : FASTHASH - EQ .
(3 1 2 3 nil nil eq))
(deftest disjoin.1
(let ((disjunction (disjoin (lambda (x)
(and (consp x) :cons))
(lambda (x)
(and (stringp x) :string)))))
(list (funcall disjunction 'zot)
(funcall disjunction '(foo bar))
(funcall disjunction "test")))
(nil :cons :string))
(deftest conjoin.1
(let ((conjunction (conjoin #'consp
(lambda (x)
(stringp (car x)))
(lambda (x)
(char (car x) 0)))))
(list (funcall conjunction 'zot)
(funcall conjunction '(foo))
(funcall conjunction '("foo"))))
(nil nil #\f))
(deftest compose.1
(let ((composite (compose '1+
(lambda (x)
(* x 2))
#'read-from-string)))
(funcall composite "1"))
3)
(deftest compose.2
(let ((composite
(locally (declare (notinline compose))
(compose '1+
(lambda (x)
(* x 2))
#'read-from-string))))
(funcall composite "2"))
5)
(deftest compose.3
(let ((compose-form (funcall (compiler-macro-function 'compose)
'(compose '1+
(lambda (x)
(* x 2))
#'read-from-string)
nil)))
(let ((fun (funcall (compile nil `(lambda () ,compose-form)))))
(funcall fun "3")))
7)
(deftest multiple-value-compose.1
(let ((composite (multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s)))))))
(multiple-value-list (funcall composite "2 7")))
(3 1))
(deftest multiple-value-compose.2
(let ((composite (locally (declare (notinline multiple-value-compose))
(multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s))))))))
(multiple-value-list (funcall composite "2 11")))
(5 1))
(deftest multiple-value-compose.3
(let ((compose-form (funcall (compiler-macro-function 'multiple-value-compose)
'(multiple-value-compose
#'truncate
(lambda (x y)
(values y x))
(lambda (x)
(with-input-from-string (s x)
(values (read s) (read s)))))
nil)))
(let ((fun (funcall (compile nil `(lambda () ,compose-form)))))
(multiple-value-list (funcall fun "2 9"))))
(4 1))
(deftest curry.1
(let ((curried (curry '+ 3)))
(funcall curried 1 5))
9)
(deftest curry.2
(let ((curried (locally (declare (notinline curry))
(curry '* 2 3))))
(funcall curried 7))
42)
(deftest curry.3
(let ((curried-form (funcall (compiler-macro-function 'curry)
'(curry '/ 8)
nil)))
(let ((fun (funcall (compile nil `(lambda () ,curried-form)))))
(funcall fun 2)))
4)
(deftest rcurry.1
(let ((r (rcurry '/ 2)))
(funcall r 8))
4)
(deftest named-lambda.1
(let ((fac (named-lambda fac (x)
(if (> x 1)
(* x (fac (- x 1)))
x))))
(funcall fac 5))
120)
(deftest named-lambda.2
(let ((fac (named-lambda fac (&key x)
(if (> x 1)
(* x (fac :x (- x 1)))
x))))
(funcall fac :x 5))
120)
(deftest alist-plist.1
(alist-plist '((a . 1) (b . 2) (c . 3)))
(a 1 b 2 c 3))
(deftest plist-alist.1
(plist-alist '(a 1 b 2 c 3))
((a . 1) (b . 2) (c . 3)))
(deftest unionf.1
(let* ((list (list 1 2 3))
(orig list))
(unionf list (list 1 2 4))
(values (equal orig (list 1 2 3))
(eql (length list) 4)
(set-difference list (list 1 2 3 4))
(set-difference (list 1 2 3 4) list)))
t
t
nil
nil)
(deftest nunionf.1
(let ((list (list 1 2 3)))
(nunionf list (list 1 2 4))
(values (eql (length list) 4)
(set-difference (list 1 2 3 4) list)
(set-difference list (list 1 2 3 4))))
t
nil
nil)
(deftest appendf.1
(let* ((list (list 1 2 3))
(orig list))
(appendf list '(4 5 6) '(7 8))
(list list (eq list orig)))
((1 2 3 4 5 6 7 8) nil))
(deftest nconcf.1
(let ((list1 (list 1 2 3))
(list2 (list 4 5 6)))
(nconcf list1 list2 (list 7 8 9))
list1)
(1 2 3 4 5 6 7 8 9))
(deftest circular-list.1
(let ((circle (circular-list 1 2 3)))
(list (first circle)
(second circle)
(third circle)
(fourth circle)
(eq circle (nthcdr 3 circle))))
(1 2 3 1 t))
(deftest circular-list-p.1
(let* ((circle (circular-list 1 2 3 4))
(tree (list circle circle))
(dotted (cons circle t))
(proper (list 1 2 3 circle))
(tailcirc (list* 1 2 3 circle)))
(list (circular-list-p circle)
(circular-list-p tree)
(circular-list-p dotted)
(circular-list-p proper)
(circular-list-p tailcirc)))
(t nil nil nil t))
(deftest circular-list-p.2
(circular-list-p 'foo)
nil)
(deftest circular-tree-p.1
(let* ((circle (circular-list 1 2 3 4))
(tree1 (list circle circle))
(tree2 (let* ((level2 (list 1 nil 2))
(level1 (list level2)))
(setf (second level2) level1)
level1))
(dotted (cons circle t))
(proper (list 1 2 3 circle))
(tailcirc (list* 1 2 3 circle))
(quite-proper (list 1 2 3))
(quite-dotted (list 1 (cons 2 3))))
(list (circular-tree-p circle)
(circular-tree-p tree1)
(circular-tree-p tree2)
(circular-tree-p dotted)
(circular-tree-p proper)
(circular-tree-p tailcirc)
(circular-tree-p quite-proper)
(circular-tree-p quite-dotted)))
(t t t t t t nil nil))
(deftest proper-list-p.1
(let ((l1 (list 1))
(l2 (list 1 2))
(l3 (cons 1 2))
(l4 (list (cons 1 2) 3))
(l5 (circular-list 1 2)))
(list (proper-list-p l1)
(proper-list-p l2)
(proper-list-p l3)
(proper-list-p l4)
(proper-list-p l5)))
(t t nil t nil))
(deftest proper-list-p.2
(proper-list-p '(1 2 . 3))
nil)
(deftest proper-list.type.1
(let ((l1 (list 1))
(l2 (list 1 2))
(l3 (cons 1 2))
(l4 (list (cons 1 2) 3))
(l5 (circular-list 1 2)))
(list (typep l1 'proper-list)
(typep l2 'proper-list)
(typep l3 'proper-list)
(typep l4 'proper-list)
(typep l5 'proper-list)))
(t t nil t nil))
(deftest proper-list-length.1
(values
(proper-list-length nil)
(proper-list-length (list 1))
(proper-list-length (list 2 2))
(proper-list-length (list 3 3 3))
(proper-list-length (list 4 4 4 4))
(proper-list-length (list 5 5 5 5 5))
(proper-list-length (list 6 6 6 6 6 6))
(proper-list-length (list 7 7 7 7 7 7 7))
(proper-list-length (list 8 8 8 8 8 8 8 8))
(proper-list-length (list 9 9 9 9 9 9 9 9 9)))
0 1 2 3 4 5 6 7 8 9)
(deftest proper-list-length.2
(flet ((plength (x)
(handler-case
(proper-list-length x)
(type-error ()
:ok))))
(values
(plength (list* 1))
(plength (list* 2 2))
(plength (list* 3 3 3))
(plength (list* 4 4 4 4))
(plength (list* 5 5 5 5 5))
(plength (list* 6 6 6 6 6 6))
(plength (list* 7 7 7 7 7 7 7))
(plength (list* 8 8 8 8 8 8 8 8))
(plength (list* 9 9 9 9 9 9 9 9 9))))
:ok :ok :ok
:ok :ok :ok
:ok :ok :ok)
(deftest lastcar.1
(let ((l1 (list 1))
(l2 (list 1 2)))
(list (lastcar l1)
(lastcar l2)))
(1 2))
(deftest lastcar.error.2
(handler-case
(progn
(lastcar (circular-list 1 2 3))
nil)
(error ()
t))
t)
(deftest setf-lastcar.1
(let ((l (list 1 2 3 4)))
(values (lastcar l)
(progn
(setf (lastcar l) 42)
(lastcar l))))
4
42)
(deftest setf-lastcar.2
(let ((l (circular-list 1 2 3)))
(multiple-value-bind (res err)
(ignore-errors (setf (lastcar l) 4))
(typep err 'type-error)))
t)
(deftest make-circular-list.1
(let ((l (make-circular-list 3 :initial-element :x)))
(setf (car l) :y)
(list (eq l (nthcdr 3 l))
(first l)
(second l)
(third l)
(fourth l)))
(t :y :x :x :y))
(deftest circular-list.type.1
(let* ((l1 (list 1 2 3))
(l2 (circular-list 1 2 3))
(l3 (list* 1 2 3 l2)))
(list (typep l1 'circular-list)
(typep l2 'circular-list)
(typep l3 'circular-list)))
(nil t t))
(deftest ensure-list.1
(let ((x (list 1))
(y 2))
(list (ensure-list x)
(ensure-list y)))
((1) (2)))
(deftest ensure-cons.1
(let ((x (cons 1 2))
(y nil)
(z "foo"))
(values (ensure-cons x)
(ensure-cons y)
(ensure-cons z)))
(1 . 2)
(nil)
("foo"))
(deftest setp.1
(setp '(1))
t)
(deftest setp.2
(setp nil)
t)
(deftest setp.3
(setp "foo")
nil)
(deftest setp.4
(setp '(1 2 3 1))
nil)
(deftest setp.5
(setp '(1 2 3))
t)
(deftest setp.6
(setp '(a :a))
t)
(deftest setp.7
(setp '(a :a) :key 'character)
nil)
(deftest setp.8
(setp '(a :a) :key 'character :test (constantly nil))
t)
(deftest set-equal.1
(set-equal '(1 2 3) '(3 1 2))
t)
(deftest set-equal.2
(set-equal '("Xa") '("Xb")
:test (lambda (a b) (eql (char a 0) (char b 0))))
t)
(deftest set-equal.3
(set-equal '(1 2) '(4 2))
nil)
(deftest set-equal.4
(set-equal '(a b c) '(:a :b :c) :key 'string :test 'equal)
t)
(deftest set-equal.5
(set-equal '(a d c) '(:a :b :c) :key 'string :test 'equal)
nil)
(deftest set-equal.6
(set-equal '(a b c) '(a b c d))
nil)
(deftest map-product.1
(map-product 'cons '(2 3) '(1 4))
((2 . 1) (2 . 4) (3 . 1) (3 . 4)))
(deftest map-product.2
(map-product #'cons '(2 3) '(1 4))
((2 . 1) (2 . 4) (3 . 1) (3 . 4)))
(deftest flatten.1
(flatten '((1) 2 (((3 4))) ((((5)) 6)) 7))
(1 2 3 4 5 6 7))
(deftest remove-from-plist.1
(let ((orig '(a 1 b 2 c 3 d 4)))
(list (remove-from-plist orig 'a 'c)
(remove-from-plist orig 'b 'd)
(remove-from-plist orig 'b)
(remove-from-plist orig 'a)
(remove-from-plist orig 'd 42 "zot")
(remove-from-plist orig 'a 'b 'c 'd)
(remove-from-plist orig 'a 'b 'c 'd 'x)
(equal orig '(a 1 b 2 c 3 d 4))))
((b 2 d 4)
(a 1 c 3)
(a 1 c 3 d 4)
(b 2 c 3 d 4)
(a 1 b 2 c 3)
nil
nil
t))
(deftest mappend.1
(mappend (compose 'list '*) '(1 2 3) '(1 2 3))
(1 4 9))
(deftest clamp.1
(list (clamp 1.5 1 2)
(clamp 2.0 1 2)
(clamp 1.0 1 2)
(clamp 3 1 2)
(clamp 0 1 2))
(1.5 2.0 1.0 2 1))
(deftest gaussian-random.1
(let ((min -0.2)
(max +0.2))
(multiple-value-bind (g1 g2)
(gaussian-random min max)
(values (<= min g1 max)
(<= min g2 max)
)))
t
t
t)
(deftest iota.1
(iota 3)
(0 1 2))
(deftest iota.2
(iota 3 :start 0.0d0)
(0.0d0 1.0d0 2.0d0))
(deftest iota.3
(iota 3 :start 2 :step 3.0)
(2.0 5.0 8.0))
(deftest map-iota.1
(let (all)
(declare (notinline map-iota))
(values (map-iota (lambda (x) (push x all))
3
:start 2
:step 1.1d0)
all))
3
(4.2d0 3.1d0 2.0d0))
(deftest lerp.1
(lerp 0.5 1 2)
1.5)
(deftest lerp.2
(lerp 0.1 1 2)
1.1)
(deftest mean.1
(mean '(1 2 3))
2)
(deftest mean.2
(mean '(1 2 3 4))
5/2)
(deftest mean.3
(mean '(1 2 10))
13/3)
(deftest median.1
(median '(100 0 99 1 98 2 97))
97)
(deftest median.2
(median '(100 0 99 1 98 2 97 96))
195/2)
(deftest variance.1
(variance (list 1 2 3))
2/3)
(deftest standard-deviation.1
(< 0 (standard-deviation (list 1 2 3)) 1)
t)
(deftest maxf.1
(let ((x 1))
(maxf x 2)
x)
2)
(deftest maxf.2
(let ((x 1))
(maxf x 0)
x)
1)
(deftest maxf.3
(let ((x 1)
(c 0))
(maxf x (incf c))
(list x c))
(1 1))
(deftest maxf.4
(let ((xv (vector 0 0 0))
(p 0))
(maxf (svref xv (incf p)) (incf p))
(list p xv))
(2 #(0 2 0)))
(deftest minf.1
(let ((y 1))
(minf y 0)
y)
0)
(deftest minf.2
(let ((xv (vector 10 10 10))
(p 0))
(minf (svref xv (incf p)) (incf p))
(list p xv))
(2 #(10 2 10)))
#+nil
(deftest array-index.type)
#+nil
(deftest copy-array)
(deftest rotate.1
(list (rotate (list 1 2 3) 0)
(rotate (list 1 2 3) 1)
(rotate (list 1 2 3) 2)
(rotate (list 1 2 3) 3)
(rotate (list 1 2 3) 4))
((1 2 3)
(3 1 2)
(2 3 1)
(1 2 3)
(3 1 2)))
(deftest rotate.2
(list (rotate (vector 1 2 3 4) 0)
(rotate (vector 1 2 3 4))
(rotate (vector 1 2 3 4) 2)
(rotate (vector 1 2 3 4) 3)
(rotate (vector 1 2 3 4) 4)
(rotate (vector 1 2 3 4) 5))
(#(1 2 3 4)
#(4 1 2 3)
#(3 4 1 2)
#(2 3 4 1)
#(1 2 3 4)
#(4 1 2 3)))
(deftest rotate.3
(list (rotate (list 1 2 3) 0)
(rotate (list 1 2 3) -1)
(rotate (list 1 2 3) -2)
(rotate (list 1 2 3) -3)
(rotate (list 1 2 3) -4))
((1 2 3)
(2 3 1)
(3 1 2)
(1 2 3)
(2 3 1)))
(deftest rotate.4
(list (rotate (vector 1 2 3 4) 0)
(rotate (vector 1 2 3 4) -1)
(rotate (vector 1 2 3 4) -2)
(rotate (vector 1 2 3 4) -3)
(rotate (vector 1 2 3 4) -4)
(rotate (vector 1 2 3 4) -5))
(#(1 2 3 4)
#(2 3 4 1)
#(3 4 1 2)
#(4 1 2 3)
#(1 2 3 4)
#(2 3 4 1)))
(deftest rotate.5
(values (rotate (list 1) 17)
(rotate (list 1) -5))
(1)
(1))
(deftest shuffle.1
(let ((s (shuffle (iota 100))))
(list (equal s (iota 100))
(every (lambda (x)
(member x s))
(iota 100))
(every (lambda (x)
(typep x '(integer 0 99)))
s)))
(nil t t))
(deftest shuffle.2
(let ((s (shuffle (coerce (iota 100) 'vector))))
(list (equal s (coerce (iota 100) 'vector))
(every (lambda (x)
(find x s))
(iota 100))
(every (lambda (x)
(typep x '(integer 0 99)))
s)))
(nil t t))
(deftest random-elt.1
(let ((s1 #(1 2 3 4))
(s2 '(1 2 3 4)))
(list (dotimes (i 1000 nil)
(unless (member (random-elt s1) s2)
(return nil))
(when (/= (random-elt s1) (random-elt s1))
(return t)))
(dotimes (i 1000 nil)
(unless (member (random-elt s2) s2)
(return nil))
(when (/= (random-elt s2) (random-elt s2))
(return t)))))
(t t))
(deftest removef.1
(let* ((x '(1 2 3))
(x* x)
(y #(1 2 3))
(y* y))
(removef x 1)
(removef y 3)
(list x x* y y*))
((2 3)
(1 2 3)
#(1 2)
#(1 2 3)))
(deftest deletef.1
(let* ((x (list 1 2 3))
(x* x)
(y (vector 1 2 3)))
(deletef x 2)
(deletef y 1)
(list x x* y))
((1 3)
(1 3)
#(2 3)))
(deftest map-permutations.1
(let ((seq (list 1 2 3))
(seen nil)
(ok t))
(map-permutations (lambda (s)
(unless (set-equal s seq)
(setf ok nil))
(when (member s seen :test 'equal)
(setf ok nil))
(push s seen))
seq
:copy t)
(values ok (length seen)))
t
6)
(deftest proper-sequence.type.1
(mapcar (lambda (x)
(typep x 'proper-sequence))
(list (list 1 2 3)
(vector 1 2 3)
#2a((1 2) (3 4))
(circular-list 1 2 3 4)))
(t t nil nil))
(deftest emptyp.1
(mapcar #'emptyp
(list (list 1)
(circular-list 1)
nil
(vector)
(vector 1)))
(nil nil t t nil))
(deftest sequence-of-length-p.1
(mapcar #'sequence-of-length-p
(list nil
#()
(list 1)
(vector 1)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2))
(list 0
0
1
1
2
2
1
1
4
4))
(t t t t t t nil nil nil nil))
(deftest length=.1
(mapcar #'length=
(list nil
#()
(list 1)
(vector 1)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2)
(list 1 2)
(vector 1 2))
(list 0
0
1
1
2
2
1
1
4
4))
(t t t t t t nil nil nil nil))
(deftest length=.2
(macrolet ((x (&rest args)
(funcall
(compile nil
`(lambda ()
(length= ,@args))))))
(list (x 2 '(1 2))
(x '(1 2) '(3 4))
(x '(1 2) 2)
(x '(1 2) 2 '(3 4))
(x 1 2 3)))
(t t t t nil))
(deftest copy-sequence.1
(let ((l (list 1 2 3))
(v (vector #\a #\b #\c)))
(declare (notinline copy-sequence))
(let ((l.list (copy-sequence 'list l))
(l.vector (copy-sequence 'vector l))
(l.spec-v (copy-sequence '(vector fixnum) l))
(v.vector (copy-sequence 'vector v))
(v.list (copy-sequence 'list v))
(v.string (copy-sequence 'string v)))
(list (member l (list l.list l.vector l.spec-v))
(member v (list v.vector v.list v.string))
(equal l.list l)
(equalp l.vector #(1 2 3))
(eql (upgraded-array-element-type 'fixnum)
(array-element-type l.spec-v))
(equalp v.vector v)
(equal v.list '(#\a #\b #\c))
(equal "abc" v.string))))
(nil nil t t t t t t))
(deftest first-elt.1
(mapcar #'first-elt
(list (list 1 2 3)
"abc"
(vector :a :b :c)))
(1 #\a :a))
(deftest first-elt.error.1
(mapcar (lambda (x)
(handler-case
(first-elt x)
(type-error ()
:type-error)))
(list nil
#()
12
:zot))
(:type-error
:type-error
:type-error
:type-error))
(deftest setf-first-elt.1
(let ((l (list 1 2 3))
(s (copy-seq "foobar"))
(v (vector :a :b :c)))
(setf (first-elt l) -1
(first-elt s) #\x
(first-elt v) 'zot)
(values l s v))
(-1 2 3)
"xoobar"
#(zot :b :c))
(deftest setf-first-elt.error.1
(let ((l 'foo))
(multiple-value-bind (res err)
(ignore-errors (setf (first-elt l) 4))
(typep err 'type-error)))
t)
(deftest last-elt.1
(mapcar #'last-elt
(list (list 1 2 3)
(vector :a :b :c)
"FOOBAR"
#*001
#*010))
(3 :c #\R 1 0))
(deftest last-elt.error.1
(mapcar (lambda (x)
(handler-case
(last-elt x)
(type-error ()
:type-error)))
(list nil
#()
12
:zot
(circular-list 1 2 3)
(list* 1 2 3 (circular-list 4 5))))
(:type-error
:type-error
:type-error
:type-error
:type-error
:type-error))
(deftest setf-last-elt.1
(let ((l (list 1 2 3))
(s (copy-seq "foobar"))
(b (copy-seq #*010101001)))
(setf (last-elt l) '???
(last-elt s) #\?
(last-elt b) 0)
(values l s b))
(1 2 ???)
"fooba?"
#*010101000)
(deftest setf-last-elt.error.1
(handler-case
(setf (last-elt 'foo) 13)
(type-error ()
:type-error))
:type-error)
(deftest starts-with.1
(list (starts-with 1 '(1 2 3))
(starts-with 1 #(1 2 3))
(starts-with #\x "xyz")
(starts-with 2 '(1 2 3))
(starts-with 3 #(1 2 3))
(starts-with 1 1)
(starts-with nil nil))
(t t t nil nil nil nil))
(deftest starts-with.2
(values (starts-with 1 '(-1 2 3) :key '-)
(starts-with "foo" '("foo" "bar") :test 'equal)
(starts-with "f" '(#\f) :key 'string :test 'equal)
(starts-with -1 '(0 1 2) :key #'1+)
(starts-with "zot" '("ZOT") :test 'equal))
t
t
t
nil
nil)
(deftest ends-with.1
(list (ends-with 3 '(1 2 3))
(ends-with 3 #(1 2 3))
(ends-with #\z "xyz")
(ends-with 2 '(1 2 3))
(ends-with 1 #(1 2 3))
(ends-with 1 1)
(ends-with nil nil))
(t t t nil nil nil nil))
(deftest ends-with.2
(values (ends-with 2 '(0 13 1) :key '1+)
(ends-with "foo" (vector "bar" "foo") :test 'equal)
(ends-with "X" (vector 1 2 #\X) :key 'string :test 'equal)
(ends-with "foo" "foo" :test 'equal))
t
t
t
nil)
(deftest ends-with.error.1
(handler-case
(ends-with 3 (circular-list 3 3 3 1 3 3))
(type-error ()
:type-error))
:type-error)
(deftest sequences.passing-improper-lists
(macrolet ((signals-error-p (form)
`(handler-case
(progn ,form nil)
(type-error (e)
t)))
(cut (fn &rest args)
(with-gensyms (arg)
(print`(lambda (,arg)
(apply ,fn (list ,@(substitute arg '_ args))))))))
(let ((circular-list (make-circular-list 5 :initial-element :foo))
(dotted-list (list* 'a 'b 'c 'd)))
(loop for nth from 0
for fn in (list
(cut #'lastcar _)
(cut #'rotate _ 3)
(cut #'rotate _ -3)
(cut #'shuffle _)
(cut #'random-elt _)
(cut #'last-elt _)
(cut #'ends-with :foo _))
nconcing
(let ((on-circular-p (signals-error-p (funcall fn circular-list)))
(on-dotted-p (signals-error-p (funcall fn dotted-list))))
(when (or (not on-circular-p) (not on-dotted-p))
(append
(unless on-circular-p
(let ((*print-circle* t))
(list
(format nil
"No appropriate error signalled when passing ~S to ~Ath entry."
circular-list nth))))
(unless on-dotted-p
(list
(format nil
"No appropriate error signalled when passing ~S to ~Ath entry."
dotted-list nth)))))))))
nil)
(deftest with-unique-names.1
(let ((*gensym-counter* 0))
(let ((syms (with-unique-names (foo bar quux)
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("FOO0" "BAR1" "QUUX2")
(mapcar #'symbol-name syms)))))
(nil t))
(deftest with-unique-names.2
(let ((*gensym-counter* 0))
(let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux #\q))
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("_foo_0" "-BAR-1" "q2")
(mapcar #'symbol-name syms)))))
(nil t))
(deftest with-unique-names.3
(let ((*gensym-counter* 0))
(multiple-value-bind (res err)
(ignore-errors
(eval
'(let ((syms
(with-unique-names ((foo "_foo_") (bar -bar-) (quux 42))
(list foo bar quux))))
(list (find-if #'symbol-package syms)
(equal '("_foo_0" "-BAR-1" "q2")
(mapcar #'symbol-name syms))))))
(errorp err)))
t)
(deftest once-only.1
(macrolet ((cons1.good (x)
(once-only (x)
`(cons ,x ,x)))
(cons1.bad (x)
`(cons ,x ,x)))
(let ((y 0))
(list (cons1.good (incf y))
y
(cons1.bad (incf y))
y)))
((1 . 1) 1 (2 . 3) 3))
(deftest once-only.2
(macrolet ((cons1 (x)
(once-only ((y x))
`(cons ,y ,y))))
(let ((z 0))
(list (cons1 (incf z))
z
(cons1 (incf z)))))
((1 . 1) 1 (2 . 2)))
(deftest parse-body.1
(parse-body '("doc" "body") :documentation t)
("body")
nil
"doc")
(deftest parse-body.2
(parse-body '("body") :documentation t)
("body")
nil
nil)
(deftest parse-body.3
(parse-body '("doc" "body"))
("doc" "body")
nil
nil)
(deftest parse-body.4
(parse-body '((declare (foo)) "doc" (declare (bar)) body) :documentation t)
(body)
((declare (foo)) (declare (bar)))
"doc")
(deftest parse-body.5
(parse-body '((declare (foo)) "doc" (declare (bar)) body))
("doc" (declare (bar)) body)
((declare (foo)))
nil)
(deftest parse-body.6
(multiple-value-bind (res err)
(ignore-errors
(parse-body '("foo" "bar" "quux")
:documentation t))
(errorp err))
t)
(deftest ensure-symbol.1
(ensure-symbol :cons :cl)
cons
:external)
(deftest ensure-symbol.2
(ensure-symbol "CONS" :alexandria)
cons
:inherited)
(deftest ensure-symbol.3
(ensure-symbol 'foo :keyword)
:foo
:external)
(deftest ensure-symbol.4
(ensure-symbol #\* :alexandria)
*
:inherited)
(deftest format-symbol.1
(let ((s (format-symbol nil "X-~D" 13)))
(list (symbol-package s)
(symbol-name s)))
(nil "X-13"))
(deftest format-symbol.2
(format-symbol :keyword "SYM-~A" :bolic)
:sym-bolic)
(deftest format-symbol.3
(let ((*package* (find-package :cl)))
(format-symbol t "FIND-~A" 'package))
find-package)
(deftest make-keyword.1
(list (make-keyword 'zot)
(make-keyword "FOO")
(make-keyword #\Q))
(:zot :foo :q))
(deftest make-gensym-list.1
(let ((*gensym-counter* 0))
(let ((syms (make-gensym-list 3 "FOO")))
(list (find-if 'symbol-package syms)
(equal '("FOO0" "FOO1" "FOO2")
(mapcar 'symbol-name syms)))))
(nil t))
(deftest make-gensym-list.2
(let ((*gensym-counter* 0))
(let ((syms (make-gensym-list 3)))
(list (find-if 'symbol-package syms)
(equal '("G0" "G1" "G2")
(mapcar 'symbol-name syms)))))
(nil t))
(deftest of-type.1
(locally
(declare (notinline of-type))
(let ((f (of-type 'string)))
(list (funcall f "foo")
(funcall f 'bar))))
(t nil))
(deftest type=.1
(type= 'string 'string)
t
t)
(deftest type=.2
(type= 'list '(or null cons))
t
t)
(deftest type=.3
(type= 'null '(and symbol list))
t
t)
(deftest type=.4
(type= 'string '(satisfies emptyp))
nil
nil)
(deftest type=.5
(type= 'string 'list)
nil
t)
(macrolet
((test (type numbers)
`(deftest ,(format-symbol t "CDR5.~A" type)
(let ((numbers ,numbers))
(values (mapcar (of-type ',(format-symbol t "NEGATIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "NON-POSITIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "NON-NEGATIVE-~A" type)) numbers)
(mapcar (of-type ',(format-symbol t "POSITIVE-~A" type)) numbers)))
(t t t nil nil nil nil)
(t t t t nil nil nil)
(nil nil nil t t t t)
(nil nil nil nil t t t))))
(test fixnum (list most-negative-fixnum -42 -1 0 1 42 most-positive-fixnum))
(test integer (list (1- most-negative-fixnum) -42 -1 0 1 42 (1+ most-positive-fixnum)))
(test rational (list (1- most-negative-fixnum) -42/13 -1 0 1 42/13 (1+ most-positive-fixnum)))
(test real (list most-negative-long-float -42/13 -1 0 1 42/13 most-positive-long-float))
(test float (list most-negative-short-float -42.02 -1.0 0.0 1.0 42.02 most-positive-short-float))
(test short-float (list most-negative-short-float -42.02s0 -1.0s0 0.0s0 1.0s0 42.02s0 most-positive-short-float))
(test single-float (list most-negative-single-float -42.02f0 -1.0f0 0.0f0 1.0f0 42.02f0 most-positive-single-float))
(test double-float (list most-negative-double-float -42.02d0 -1.0d0 0.0d0 1.0d0 42.02d0 most-positive-double-float))
(test long-float (list most-negative-long-float -42.02l0 -1.0l0 0.0l0 1.0l0 42.02l0 most-positive-long-float)))
(declaim (notinline opaque))
(defun opaque (x)
x)
(deftest if-let.1
(if-let (x (opaque :ok))
x
:bad)
:ok)
(deftest if-let.2
(if-let (x (opaque nil))
:bad
(and (not x) :ok))
:ok)
(deftest if-let.3
(let ((x 1))
(if-let ((x 2)
(y x))
(+ x y)
:oops))
3)
(deftest if-let.4
(if-let ((x 1)
(y nil))
:oops
(and (not y) x))
1)
(deftest if-let.5
(if-let (x)
:oops
(not x))
t)
(deftest if-let.error.1
(handler-case
(eval '(if-let x
:oops
:oops))
(type-error ()
:type-error))
:type-error)
(deftest when-let.1
(when-let (x (opaque :ok))
(setf x (cons x x))
x)
(:ok . :ok))
(deftest when-let.2
(when-let ((x 1)
(y nil)
(z 3))
:oops)
nil)
(deftest when-let.3
(let ((x 1))
(when-let ((x 2)
(y x))
(+ x y)))
3)
(deftest when-let.error.1
(handler-case
(eval '(when-let x :oops))
(type-error ()
:type-error))
:type-error)
(deftest when-let*.1
(let ((x 1))
(when-let* ((x 2)
(y x))
(+ x y)))
4)
(deftest when-let*.2
(let ((y 1))
(when-let* (x y)
(1+ x)))
2)
(deftest when-let*.3
(when-let* ((x t)
(y (consp x))
(z (error "OOPS")))
t)
nil)
(deftest when-let*.error.1
(handler-case
(eval '(when-let* x :oops))
(type-error ()
:type-error))
:type-error)
(deftest nth-value-or.1
(multiple-value-bind (a b c)
(nth-value-or 1
(values 1 nil 1)
(values 2 2 2))
(= a b c 2))
t)
(deftest doplist.1
(let (keys values)
(doplist (k v '(a 1 b 2 c 3) (values t (reverse keys) (reverse values) k v))
(push k keys)
(push v values)))
t
(a b c)
(1 2 3)
nil
nil)
|
ef331fa996129590cdeb9d4d2f0d247122ef81f6e9f80643514040861cf8a10c | ocaml-multicore/multicoretests | lin_tests.ml | open QCheck
open Lin.Internal [@@alert "-internal"]
module Spec =
struct
type t = int Queue.t
let m = Mutex.create ()
type cmd =
| Add of int'
| Take
| Take_opt
| Peek
| Peek_opt
| Clear
| Is_empty
| Fold of fct * int'
| Length [@@deriving qcheck, show { with_path = false }]
and int' = int [@gen Gen.nat]
and fct = (int -> int -> int) fun_ [@printer fun fmt f -> fprintf fmt "%s" (Fn.print f)] [@gen (fun2 Observable.int Observable.int small_int).gen]
let shrink_cmd c = match c with
| Take
| Take_opt
| Peek
| Peek_opt
| Clear
| Is_empty
| Length -> Iter.empty
| Add i -> Iter.map (fun i -> Add i) (Shrink.int i)
| Fold (f,i) ->
Iter.(
(map (fun f -> Fold (f,i)) (Fn.shrink f))
<+>
(map (fun i -> Fold (f,i)) (Shrink.int i)))
type res =
| RAdd
| RTake of ((int, exn) result [@equal (=)])
| RTake_opt of int option
| RPeek of ((int, exn) result [@equal (=)])
| RPeek_opt of int option
| RClear
| RIs_empty of bool
| RFold of int
| RLength of int [@@deriving show { with_path = false }, eq]
let init () = Queue.create ()
let cleanup _ = ()
end
module QConf =
struct
include Spec
let run c q = match c with
| Add i -> Queue.add i q; RAdd
| Take -> RTake (Util.protect Queue.take q)
| Take_opt -> RTake_opt (Queue.take_opt q)
| Peek -> RPeek (Util.protect Queue.peek q)
| Peek_opt -> RPeek_opt (Queue.peek_opt q)
| Length -> RLength (Queue.length q)
| Is_empty -> RIs_empty (Queue.is_empty q)
| Fold (f, a) -> RFold (Queue.fold (Fn.apply f) a q)
| Clear -> Queue.clear q; RClear
end
module QMutexConf =
struct
include Spec
let run c q = match c with
| Add i -> Mutex.lock m;
Queue.add i q;
Mutex.unlock m; RAdd
| Take -> Mutex.lock m;
let r = Util.protect Queue.take q in
Mutex.unlock m;
RTake r
| Take_opt -> Mutex.lock m;
let r = Queue.take_opt q in
Mutex.unlock m;
RTake_opt r
| Peek -> Mutex.lock m;
let r = Util.protect Queue.peek q in
Mutex.unlock m;
RPeek r
| Peek_opt -> Mutex.lock m;
let r = Queue.peek_opt q in
Mutex.unlock m;
RPeek_opt r
| Length -> Mutex.lock m;
let l = Queue.length q in
Mutex.unlock m;
RLength l
| Is_empty -> Mutex.lock m;
let b = Queue.is_empty q in
Mutex.unlock m;
RIs_empty b
| Fold (f, a) -> Mutex.lock m;
let r = (Queue.fold (Fn.apply f) a q) in
Mutex.unlock m;
RFold r
| Clear -> Mutex.lock m;
Queue.clear q;
Mutex.unlock m;
RClear
end
module QMT_domain = Lin_domain.Make_internal(QMutexConf) [@alert "-internal"]
module QMT_thread = Lin_thread.Make_internal(QMutexConf) [@alert "-internal"]
module QT_domain = Lin_domain.Make_internal(QConf) [@alert "-internal"]
module QT_thread = Lin_thread.Make_internal(QConf) [@alert "-internal"]
;;
QCheck_base_runner.run_tests_main [
QMT_domain.lin_test ~count:1000 ~name:"Lin Queue test with Domain and mutex";
QMT_thread.lin_test ~count:1000 ~name:"Lin Queue test with Thread and mutex";
QT_domain.neg_lin_test ~count:1000 ~name:"Lin Queue test with Domain without mutex";
QT_thread.lin_test ~count:1000 ~name:"Lin Queue test with Thread without mutex";
]
| null | https://raw.githubusercontent.com/ocaml-multicore/multicoretests/3e0f2ceb72eaf334e97252140ae5d40bf6461b96/src/queue/lin_tests.ml | ocaml | open QCheck
open Lin.Internal [@@alert "-internal"]
module Spec =
struct
type t = int Queue.t
let m = Mutex.create ()
type cmd =
| Add of int'
| Take
| Take_opt
| Peek
| Peek_opt
| Clear
| Is_empty
| Fold of fct * int'
| Length [@@deriving qcheck, show { with_path = false }]
and int' = int [@gen Gen.nat]
and fct = (int -> int -> int) fun_ [@printer fun fmt f -> fprintf fmt "%s" (Fn.print f)] [@gen (fun2 Observable.int Observable.int small_int).gen]
let shrink_cmd c = match c with
| Take
| Take_opt
| Peek
| Peek_opt
| Clear
| Is_empty
| Length -> Iter.empty
| Add i -> Iter.map (fun i -> Add i) (Shrink.int i)
| Fold (f,i) ->
Iter.(
(map (fun f -> Fold (f,i)) (Fn.shrink f))
<+>
(map (fun i -> Fold (f,i)) (Shrink.int i)))
type res =
| RAdd
| RTake of ((int, exn) result [@equal (=)])
| RTake_opt of int option
| RPeek of ((int, exn) result [@equal (=)])
| RPeek_opt of int option
| RClear
| RIs_empty of bool
| RFold of int
| RLength of int [@@deriving show { with_path = false }, eq]
let init () = Queue.create ()
let cleanup _ = ()
end
module QConf =
struct
include Spec
let run c q = match c with
| Add i -> Queue.add i q; RAdd
| Take -> RTake (Util.protect Queue.take q)
| Take_opt -> RTake_opt (Queue.take_opt q)
| Peek -> RPeek (Util.protect Queue.peek q)
| Peek_opt -> RPeek_opt (Queue.peek_opt q)
| Length -> RLength (Queue.length q)
| Is_empty -> RIs_empty (Queue.is_empty q)
| Fold (f, a) -> RFold (Queue.fold (Fn.apply f) a q)
| Clear -> Queue.clear q; RClear
end
module QMutexConf =
struct
include Spec
let run c q = match c with
| Add i -> Mutex.lock m;
Queue.add i q;
Mutex.unlock m; RAdd
| Take -> Mutex.lock m;
let r = Util.protect Queue.take q in
Mutex.unlock m;
RTake r
| Take_opt -> Mutex.lock m;
let r = Queue.take_opt q in
Mutex.unlock m;
RTake_opt r
| Peek -> Mutex.lock m;
let r = Util.protect Queue.peek q in
Mutex.unlock m;
RPeek r
| Peek_opt -> Mutex.lock m;
let r = Queue.peek_opt q in
Mutex.unlock m;
RPeek_opt r
| Length -> Mutex.lock m;
let l = Queue.length q in
Mutex.unlock m;
RLength l
| Is_empty -> Mutex.lock m;
let b = Queue.is_empty q in
Mutex.unlock m;
RIs_empty b
| Fold (f, a) -> Mutex.lock m;
let r = (Queue.fold (Fn.apply f) a q) in
Mutex.unlock m;
RFold r
| Clear -> Mutex.lock m;
Queue.clear q;
Mutex.unlock m;
RClear
end
module QMT_domain = Lin_domain.Make_internal(QMutexConf) [@alert "-internal"]
module QMT_thread = Lin_thread.Make_internal(QMutexConf) [@alert "-internal"]
module QT_domain = Lin_domain.Make_internal(QConf) [@alert "-internal"]
module QT_thread = Lin_thread.Make_internal(QConf) [@alert "-internal"]
;;
QCheck_base_runner.run_tests_main [
QMT_domain.lin_test ~count:1000 ~name:"Lin Queue test with Domain and mutex";
QMT_thread.lin_test ~count:1000 ~name:"Lin Queue test with Thread and mutex";
QT_domain.neg_lin_test ~count:1000 ~name:"Lin Queue test with Domain without mutex";
QT_thread.lin_test ~count:1000 ~name:"Lin Queue test with Thread without mutex";
]
| |
cac23b4f4f64a649a38def82234995831082e4bf1ed141ccc700da8b0eccde30 | minikN/dots | packages.scm | (define-module (config packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (gnu build chromium-extension)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages curl)
#:use-module (gnu packages gl)
#:use-module (gnu packages gnome)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages pulseaudio)
#:use-module (gnu packages sdl)
#:use-module (gnu packages video)
#:use-module (gnu packages web)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix gexp)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (nongnu packages steam-client)
;; #:use-module (gnu packages gcc)
# : use - module ( gnu packages libusb )
;; #:use-module (gnu packages llvm)
;; #:use-module (guix build-system linux-module)
;; #:use-module (nonguix build-system binary)
)
(define-public steamos-modeswitch-inhibitor
(package
(name "steamos-modeswitch-inhibitor")
(version "1.10")
(source (origin
(method url-fetch)
(uri
(string-append
"-modeswitch-inhibitor/steamos-modeswitch-inhibitor_"
version
".tar.xz"))
(sha256
(base32
"1lskfb4l87s3naz2gmc22q0xzvlhblywf5z8lsiqnkrrxnpbbwj7"))))
(native-inputs
(list autoconf
automake
pkg-config))
(inputs
(list libxxf86vm
libx11
libxrender
libxrandr))
(build-system gnu-build-system)
(home-page "-modeswitch-inhibitor/")
(synopsis "SteamOS Mode Switch Inhibitor")
(description "Shared library which fakes any mode switch attempts to prevent full screen apps from changing resolution.")
(license license:gpl3+)))
(define-public steamos-compositor-plus
(let ((commit "e4b99dd5f56a388aa24fe3055d0e983cb3d5d32a")
( commit " 7c0011cf91e87c30c2a630fee915ead58ef9dcf5 " )
(revision "0")
(version "1.3.0"))
(package
(name "steamos-compositor-plus")
(version (git-version version revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-compositor-plus")
(commit commit)))
(sha256
(base32 "0rqckj05389djc4ahzfy98p3z0p884gbbl94lbm06za72bhnidr5")
( base32 " 1bjl517bw10w18f4amdz3kwzkdz8w6wg8md2bk3wpqjrn26p45gd " )
)
(file-name (git-file-name name version))))
(arguments
(list
#:phases
#~(modify-phases
%standard-phases
(add-after 'patch-source-shebangs 'copy-scripts
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(share (string-append out "/share"))
(src (string-append share "/steamos-compositor-plus/bin"))
(scripts (string-append bin "/scripts")))
(mkdir-p scripts)
(copy-recursively "./usr/share" share)
(copy-recursively "./usr/bin" bin)
(find-files src (lambda (file stat)
(symlink file (string-append scripts "/" (basename file))))))))
(add-after 'copy-scripts 'patch-bin
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(share (string-append out "/share"))
(src (string-append share "/steamos-compositor-plus/bin"))
(bin (string-append out "/bin"))
(aplay (string-append (assoc-ref inputs "alsa-utils") "/bin/aplay"))
(pamixer (string-append (assoc-ref inputs "pamixer") "/bin/pamixer"))
(udevadm (string-append (assoc-ref inputs "eudev") "/bin/udevadm"))
(xset (string-append (assoc-ref inputs "xset") "/bin/xset"))
(xrandr (string-append (assoc-ref inputs "xrandr") "/bin/xrandr"))
(xinput (string-append (assoc-ref inputs "xinput") "/bin/xinput"))
(grep (string-append (assoc-ref inputs "grep") "/bin/grep"))
(steam (string-append (assoc-ref inputs "steam") "/bin/steam"))
(modeswitch-inhibitor (string-append
(assoc-ref inputs "steamos-modeswitch-inhibitor")
"/lib/libmodeswitch_inhibitor.so")))
(substitute* "./usr/bin/steamos-session"
;; No need to export scripts to PATH.
(("export.+\\{PATH\\}" line) (string-append "#" line))
(("\"steam ") (string-append "\"" steam " "))
(("export.+so" line) (string-append "export" " " "LD_PRELOAD=" modeswitch-inhibitor))
(("set_hd_mode.sh") (string-append bin "/scripts/set_hd_mode.sh"))
(("loadargb_cursor") (string-append bin "/loadargb_cursor"))
(("cp") "ln -s")
(("/usr/share/icons/steam/arrow.png")
(string-append share "/icons/steam/arrow.png"))
(("/usr/share/pixmaps/steam-bootstrapper.jpg")
(string-append share "/pixmaps/steam-bootstrapper.jpg"))
(("steamcompmgr") (string-append bin "/steamcompmgr"))
(("steam-browser.desktop") (string-append share "/applications/steam-browser.desktop"))
(("xset") xset))
(substitute* (string-append src "/set_hd_mode.sh")
(("xrandr") xrandr)
(("egrep") "grep -E")
(("grep") grep)
(("xinput") xinput)
(("udevadm") udevadm))
(substitute* (string-append src "/screen_toggle.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/brightness_up.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/brightness_down.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/audio_volup.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append src "/audio_voldown.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append src "/audio_mute.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append share "/xsessions/steamos.desktop")
(("steamos-session") (string-append bin "/steamos-session")))
(substitute* (string-append share "/applications/steam-browser.desktop")
(("steam ") (string-append steam " ")))
)))
(add-after 'patch-bin 'copy-bin
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "./usr/bin/steamos-session" bin)
(chmod (string-append bin "/steamos-session") #o555)))))))
(native-inputs
(list autoconf
automake
pkg-config))
(propagated-inputs
(list xinit
xorg-server))
(inputs
(list alsa-utils
eudev
grep
libxxf86vm
libx11
libxrender
libxcomposite
libgudev
glu
pamixer
sdl-image
steam
xinput
xset
xrandr
steamos-modeswitch-inhibitor))
(build-system gnu-build-system)
(home-page "-compositor-plus")
(synopsis "Compositor used by SteamOS 2.x with some added tweaks and fixes")
(description "This is a fork of the SteamOS compositor, currently based on
version 1.35. It includes out of the box 4k (3840x2160) support, allows adjusting
resolution/refresh rate through a configuration file, hides the annoying color
flashing on startup of Proton games and adds a fix for games that start in
the background, including Dead Cells, The Count Lucanor, most Feral games
and probably others.")
(license license:gpl3+))))
(define-public rofi-ttv
(let ((commit "e9c722481b740196165f840771b3ae58b7291694")
(revision "0")
(version "0.1"))
(package
(name "rofi-ttv")
(version (git-version version revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-ttv")
(commit commit)))
(sha256
(base32 "1m6jf87gsspi2qmhnf4p2ibqp0g1kvcnphcji8qf4z39x73f7jym"))
(file-name (git-file-name name version))))
(build-system gnu-build-system)
(inputs (list
curl
jq
rofi
youtube-dl
mpv))
(arguments
`(#:tests?
#f
#:phases
(modify-phases
%standard-phases
(delete 'configure)
(delete 'install)
(delete 'build)
(add-after 'unpack 'patch-bin
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(curl (string-append (assoc-ref inputs "curl") "/bin/curl"))
(jq (string-append (assoc-ref inputs "jq") "/bin/jq"))
(rofi (string-append (assoc-ref inputs "rofi") "/bin/rofi"))
(youtube-dl (string-append (assoc-ref inputs "youtube-dl") "/bin/youtube-dl"))
(mpv (string-append (assoc-ref inputs "mpv") "/bin/mpv")))
(substitute* "./rofi-ttv"
(("curl") curl)
(("jq") jq)
(("rofi ") (string-append rofi " "))
(("youtube-dl") youtube-dl)
(("mpv") mpv)))))
(add-after 'patch-bin 'copy-bin
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "./rofi-ttv" bin)
(chmod (string-append bin "/rofi-ttv") #o555)))))))
(home-page "-doc")
(synopsis "A scripts that uses rofi, youtube-dl and mpv to view twitch streams.")
(description "A scripts that uses rofi, youtube-dl and mpv to view twitch streams.")
(license license:expat))))
(define-public chromium-web-store
(package
(name "chromium-web-store")
(version "1.4.4.3")
(home-page "-web-store")
(source (origin
(method git-fetch)
(uri (git-reference
(url home-page)
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"17jp05dpd8lk8k7fi56jdbhiisx4ajylr6kax01mzfkwfhkd0q9d"))))
(build-system copy-build-system)
(outputs '("chromium"))
(arguments
'(#:phases
(modify-phases %standard-phases
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(copy-recursively "src" (assoc-ref outputs "chromium")))))))
(synopsis "Allows adding extensions from chrome web store on ungoogled-chromium")
(description "This extension brings the following functionality to
ungoogled-chromium (and other forks that lack web store support):
@itemize
@item Allows installing extensions directly from chrome web store.
@item Automatically checks for updates to your installed extensions and displays
them on the badge.
@end itemize")
(license license:expat)))
(define-public chromium-web-store/chromium
(make-chromium-extension chromium-web-store "chromium"))
;; (define-public evdi
;; (package
;; (name "evdi")
;; (version "1.12.0")
;; (source
;; (origin
;; (method git-fetch)
;; (uri (git-reference
( url " " )
( commit " bdc258b25df4d00f222fde0e3c5003bf88ef17b5 " ) ) )
;; (file-name (git-file-name name version))
;; (sha256
( base32 " 1yi7mbyvxm9lsx6i1xbwp2bihwgzhwxkydk1kbngw5a5kw9azpws " ) ) ) )
;; (build-system linux-module-build-system)
;; (arguments
;; `(#:tests? #f ;; no test suite
;; #:phases
;; (modify-phases %standard-phases
;; (add-after 'unpack 'chdir
;; (lambda _ (chdir "module"))))))
;; (home-page "")
( synopsis " EVDI Linux kernel module " )
;; (description
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
;; that enables management of multiple screens, allowing user-space programs to
;; take control over what happens with the image.")
;; (license license:gpl2)))
;; (define-public libevdi
;; (package
( name " " )
;; (version "1.12.0")
;; (source
;; (origin
;; (method git-fetch)
;; (uri (git-reference
( url " " )
( commit " bdc258b25df4d00f222fde0e3c5003bf88ef17b5 " ) ) )
;; (file-name (git-file-name name version))
;; (sha256
( base32 " 1yi7mbyvxm9lsx6i1xbwp2bihwgzhwxkydk1kbngw5a5kw9azpws " ) ) ) )
( build - system gnu - build - system )
;; (arguments
;; `(#:tests? #f ;; no test suite
;; #:make-flags `("CC=gcc")
;; #:phases
;; (modify-phases %standard-phases
;; (delete 'configure) ;; no configure script
;; (replace 'install
;; (lambda* (#:key outputs #:allow-other-keys)
;; (let* ((out (assoc-ref outputs "out"))
;; (lib (string-append out "/lib")))
( mkdir - p lib )
;; (copy-file "libevdi.so" (string-append lib "/libevdi.so")))))
;; (add-after 'unpack 'chdir
;; (lambda _ (chdir "library"))))))
;; (inputs
( list ) )
;; (home-page "")
( synopsis " EVDI Linux kernel module " )
;; (description
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
;; that enables management of multiple screens, allowing user-space programs to
;; take control over what happens with the image.")
;; (license license:lgpl2.1)))
;; (define-public displaylink
;; (package
( name " " )
( version " 5.6.1 " )
;; (source
;; (origin
;; (method url-fetch/zipbomb)
;; (uri (string-append
;; "-08/DisplayLink%20USB%20Graphics%20Software%20for%20Ubuntu"
;; version
;; "-EXE.zip"))
;; (sha256
;; (base32
" 1hihsz35ccydzx04r8r9kz0hvqwj5fgr8zpzvwyhfxp2m549f9w9 " ) )
;; (file-name (string-append name "-" version ".zip"))))
;; (supported-systems '("x86_64-linux"))
;; (build-system binary-build-system)
;; (inputs
;; (list
;; libusb
;; glibc
;; `(,gcc "lib")
;; `(,util-linux "lib")
;; ))
;; (arguments
;; (list
;; #:validate-runpath? #f
;; #:patchelf-plan
;; #~'(("lib/DisplayLinkManager"
;; ("util-linux"
;; "gcc"
;; "glibc"
" " ) ) )
;; #:phases
;; #~(modify-phases %standard-phases
;; (add-after 'unpack 'unpack-runfile
;; (lambda* _
;; (let* ((lib (string-append #$output "/lib"))
( ( string - append # $ output " /bin " ) )
;; (src-file (car (find-files "." "\\.run$")))
( src - folder ( string - drop - right src - file 4 ) ) )
( invoke " sh " src - file " --keep " " --noexec " )
;; (rename-file (string-append src-folder "/") "lib")
;; (copy-recursively "lib/aarch64-linux-gnu/" "lib/")
;; (delete-file-recursively "lib/arm-linux-gnueabihf")
;; (delete-file-recursively "lib/aarch64-linux-gnu")
;; (delete-file-recursively "lib/x64-ubuntu-1604")
;; (delete-file-recursively "lib/x86-ubuntu-1604")
( delete - file - recursively " _ _ " )
;; (delete-file src-file)
;; (delete-file (car (find-files "." "\\.txt$"))))))
;; (add-after 'install 'symlink-binary
;; (lambda _
( mkdir - p ( string - append # $ output " /bin " ) )
;; (symlink (string-append #$output "/lib/DisplayLinkManager")
;; (string-append #$output "/bin/DisplayLinkManager"))
;; (invoke "ls" "-la" #$output)))
;; ;; (add-after 'install 'wrap-where-patchelf-does-not-work
;; ;; (lambda _
;; ;; (wrap-program (string-append #$output "/lib/DisplayLinkManager")
;; ;; `("LD_LIBRARY_PATH" ":" prefix
;; ;; (,(string-join
;; ;; (list
;; ;; (string-append #$(this-package-input "gcc") "/lib")
;; ;; (string-append #$output "/lib")
;; ;; #$output)
;; ;; ":"))))))
;; )))
;; (home-page "")
( synopsis " EVDI Linux kernel module " )
;; (description
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
;; that enables management of multiple screens, allowing
;; displaylink
;; user-space programs to
;; take control over what happens with the image.")
;; (license license:lgpl2.1)))
| null | https://raw.githubusercontent.com/minikN/dots/c303bbd6fd5a355dc013904f588d5646ca56cf1a/config/packages.scm | scheme | #:use-module (gnu packages gcc)
#:use-module (gnu packages llvm)
#:use-module (guix build-system linux-module)
#:use-module (nonguix build-system binary)
No need to export scripts to PATH.
(define-public evdi
(package
(name "evdi")
(version "1.12.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(file-name (git-file-name name version))
(sha256
(build-system linux-module-build-system)
(arguments
`(#:tests? #f ;; no test suite
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'chdir
(lambda _ (chdir "module"))))))
(home-page "")
(description
that enables management of multiple screens, allowing user-space programs to
take control over what happens with the image.")
(license license:gpl2)))
(define-public libevdi
(package
(version "1.12.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(file-name (git-file-name name version))
(sha256
(arguments
`(#:tests? #f ;; no test suite
#:make-flags `("CC=gcc")
#:phases
(modify-phases %standard-phases
(delete 'configure) ;; no configure script
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(lib (string-append out "/lib")))
(copy-file "libevdi.so" (string-append lib "/libevdi.so")))))
(add-after 'unpack 'chdir
(lambda _ (chdir "library"))))))
(inputs
(home-page "")
(description
that enables management of multiple screens, allowing user-space programs to
take control over what happens with the image.")
(license license:lgpl2.1)))
(define-public displaylink
(package
(source
(origin
(method url-fetch/zipbomb)
(uri (string-append
"-08/DisplayLink%20USB%20Graphics%20Software%20for%20Ubuntu"
version
"-EXE.zip"))
(sha256
(base32
(file-name (string-append name "-" version ".zip"))))
(supported-systems '("x86_64-linux"))
(build-system binary-build-system)
(inputs
(list
libusb
glibc
`(,gcc "lib")
`(,util-linux "lib")
))
(arguments
(list
#:validate-runpath? #f
#:patchelf-plan
#~'(("lib/DisplayLinkManager"
("util-linux"
"gcc"
"glibc"
#:phases
#~(modify-phases %standard-phases
(add-after 'unpack 'unpack-runfile
(lambda* _
(let* ((lib (string-append #$output "/lib"))
(src-file (car (find-files "." "\\.run$")))
(rename-file (string-append src-folder "/") "lib")
(copy-recursively "lib/aarch64-linux-gnu/" "lib/")
(delete-file-recursively "lib/arm-linux-gnueabihf")
(delete-file-recursively "lib/aarch64-linux-gnu")
(delete-file-recursively "lib/x64-ubuntu-1604")
(delete-file-recursively "lib/x86-ubuntu-1604")
(delete-file src-file)
(delete-file (car (find-files "." "\\.txt$"))))))
(add-after 'install 'symlink-binary
(lambda _
(symlink (string-append #$output "/lib/DisplayLinkManager")
(string-append #$output "/bin/DisplayLinkManager"))
(invoke "ls" "-la" #$output)))
;; (add-after 'install 'wrap-where-patchelf-does-not-work
;; (lambda _
;; (wrap-program (string-append #$output "/lib/DisplayLinkManager")
;; `("LD_LIBRARY_PATH" ":" prefix
;; (,(string-join
;; (list
;; (string-append #$(this-package-input "gcc") "/lib")
;; (string-append #$output "/lib")
;; #$output)
;; ":"))))))
)))
(home-page "")
(description
that enables management of multiple screens, allowing
displaylink
user-space programs to
take control over what happens with the image.")
(license license:lgpl2.1))) | (define-module (config packages)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (gnu build chromium-extension)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages curl)
#:use-module (gnu packages gl)
#:use-module (gnu packages gnome)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages pulseaudio)
#:use-module (gnu packages sdl)
#:use-module (gnu packages video)
#:use-module (gnu packages web)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix gexp)
#:use-module (guix git-download)
#:use-module (guix packages)
#:use-module (nongnu packages steam-client)
# : use - module ( gnu packages libusb )
)
(define-public steamos-modeswitch-inhibitor
(package
(name "steamos-modeswitch-inhibitor")
(version "1.10")
(source (origin
(method url-fetch)
(uri
(string-append
"-modeswitch-inhibitor/steamos-modeswitch-inhibitor_"
version
".tar.xz"))
(sha256
(base32
"1lskfb4l87s3naz2gmc22q0xzvlhblywf5z8lsiqnkrrxnpbbwj7"))))
(native-inputs
(list autoconf
automake
pkg-config))
(inputs
(list libxxf86vm
libx11
libxrender
libxrandr))
(build-system gnu-build-system)
(home-page "-modeswitch-inhibitor/")
(synopsis "SteamOS Mode Switch Inhibitor")
(description "Shared library which fakes any mode switch attempts to prevent full screen apps from changing resolution.")
(license license:gpl3+)))
(define-public steamos-compositor-plus
(let ((commit "e4b99dd5f56a388aa24fe3055d0e983cb3d5d32a")
( commit " 7c0011cf91e87c30c2a630fee915ead58ef9dcf5 " )
(revision "0")
(version "1.3.0"))
(package
(name "steamos-compositor-plus")
(version (git-version version revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-compositor-plus")
(commit commit)))
(sha256
(base32 "0rqckj05389djc4ahzfy98p3z0p884gbbl94lbm06za72bhnidr5")
( base32 " 1bjl517bw10w18f4amdz3kwzkdz8w6wg8md2bk3wpqjrn26p45gd " )
)
(file-name (git-file-name name version))))
(arguments
(list
#:phases
#~(modify-phases
%standard-phases
(add-after 'patch-source-shebangs 'copy-scripts
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(share (string-append out "/share"))
(src (string-append share "/steamos-compositor-plus/bin"))
(scripts (string-append bin "/scripts")))
(mkdir-p scripts)
(copy-recursively "./usr/share" share)
(copy-recursively "./usr/bin" bin)
(find-files src (lambda (file stat)
(symlink file (string-append scripts "/" (basename file))))))))
(add-after 'copy-scripts 'patch-bin
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(share (string-append out "/share"))
(src (string-append share "/steamos-compositor-plus/bin"))
(bin (string-append out "/bin"))
(aplay (string-append (assoc-ref inputs "alsa-utils") "/bin/aplay"))
(pamixer (string-append (assoc-ref inputs "pamixer") "/bin/pamixer"))
(udevadm (string-append (assoc-ref inputs "eudev") "/bin/udevadm"))
(xset (string-append (assoc-ref inputs "xset") "/bin/xset"))
(xrandr (string-append (assoc-ref inputs "xrandr") "/bin/xrandr"))
(xinput (string-append (assoc-ref inputs "xinput") "/bin/xinput"))
(grep (string-append (assoc-ref inputs "grep") "/bin/grep"))
(steam (string-append (assoc-ref inputs "steam") "/bin/steam"))
(modeswitch-inhibitor (string-append
(assoc-ref inputs "steamos-modeswitch-inhibitor")
"/lib/libmodeswitch_inhibitor.so")))
(substitute* "./usr/bin/steamos-session"
(("export.+\\{PATH\\}" line) (string-append "#" line))
(("\"steam ") (string-append "\"" steam " "))
(("export.+so" line) (string-append "export" " " "LD_PRELOAD=" modeswitch-inhibitor))
(("set_hd_mode.sh") (string-append bin "/scripts/set_hd_mode.sh"))
(("loadargb_cursor") (string-append bin "/loadargb_cursor"))
(("cp") "ln -s")
(("/usr/share/icons/steam/arrow.png")
(string-append share "/icons/steam/arrow.png"))
(("/usr/share/pixmaps/steam-bootstrapper.jpg")
(string-append share "/pixmaps/steam-bootstrapper.jpg"))
(("steamcompmgr") (string-append bin "/steamcompmgr"))
(("steam-browser.desktop") (string-append share "/applications/steam-browser.desktop"))
(("xset") xset))
(substitute* (string-append src "/set_hd_mode.sh")
(("xrandr") xrandr)
(("egrep") "grep -E")
(("grep") grep)
(("xinput") xinput)
(("udevadm") udevadm))
(substitute* (string-append src "/screen_toggle.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/brightness_up.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/brightness_down.sh")
(("xrandr") xrandr))
(substitute* (string-append src "/audio_volup.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append src "/audio_voldown.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append src "/audio_mute.sh")
(("aplay") aplay)
(("pamixer") pamixer))
(substitute* (string-append share "/xsessions/steamos.desktop")
(("steamos-session") (string-append bin "/steamos-session")))
(substitute* (string-append share "/applications/steam-browser.desktop")
(("steam ") (string-append steam " ")))
)))
(add-after 'patch-bin 'copy-bin
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "./usr/bin/steamos-session" bin)
(chmod (string-append bin "/steamos-session") #o555)))))))
(native-inputs
(list autoconf
automake
pkg-config))
(propagated-inputs
(list xinit
xorg-server))
(inputs
(list alsa-utils
eudev
grep
libxxf86vm
libx11
libxrender
libxcomposite
libgudev
glu
pamixer
sdl-image
steam
xinput
xset
xrandr
steamos-modeswitch-inhibitor))
(build-system gnu-build-system)
(home-page "-compositor-plus")
(synopsis "Compositor used by SteamOS 2.x with some added tweaks and fixes")
(description "This is a fork of the SteamOS compositor, currently based on
version 1.35. It includes out of the box 4k (3840x2160) support, allows adjusting
resolution/refresh rate through a configuration file, hides the annoying color
flashing on startup of Proton games and adds a fix for games that start in
the background, including Dead Cells, The Count Lucanor, most Feral games
and probably others.")
(license license:gpl3+))))
(define-public rofi-ttv
(let ((commit "e9c722481b740196165f840771b3ae58b7291694")
(revision "0")
(version "0.1"))
(package
(name "rofi-ttv")
(version (git-version version revision commit))
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-ttv")
(commit commit)))
(sha256
(base32 "1m6jf87gsspi2qmhnf4p2ibqp0g1kvcnphcji8qf4z39x73f7jym"))
(file-name (git-file-name name version))))
(build-system gnu-build-system)
(inputs (list
curl
jq
rofi
youtube-dl
mpv))
(arguments
`(#:tests?
#f
#:phases
(modify-phases
%standard-phases
(delete 'configure)
(delete 'install)
(delete 'build)
(add-after 'unpack 'patch-bin
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(curl (string-append (assoc-ref inputs "curl") "/bin/curl"))
(jq (string-append (assoc-ref inputs "jq") "/bin/jq"))
(rofi (string-append (assoc-ref inputs "rofi") "/bin/rofi"))
(youtube-dl (string-append (assoc-ref inputs "youtube-dl") "/bin/youtube-dl"))
(mpv (string-append (assoc-ref inputs "mpv") "/bin/mpv")))
(substitute* "./rofi-ttv"
(("curl") curl)
(("jq") jq)
(("rofi ") (string-append rofi " "))
(("youtube-dl") youtube-dl)
(("mpv") mpv)))))
(add-after 'patch-bin 'copy-bin
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(install-file "./rofi-ttv" bin)
(chmod (string-append bin "/rofi-ttv") #o555)))))))
(home-page "-doc")
(synopsis "A scripts that uses rofi, youtube-dl and mpv to view twitch streams.")
(description "A scripts that uses rofi, youtube-dl and mpv to view twitch streams.")
(license license:expat))))
(define-public chromium-web-store
(package
(name "chromium-web-store")
(version "1.4.4.3")
(home-page "-web-store")
(source (origin
(method git-fetch)
(uri (git-reference
(url home-page)
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"17jp05dpd8lk8k7fi56jdbhiisx4ajylr6kax01mzfkwfhkd0q9d"))))
(build-system copy-build-system)
(outputs '("chromium"))
(arguments
'(#:phases
(modify-phases %standard-phases
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(copy-recursively "src" (assoc-ref outputs "chromium")))))))
(synopsis "Allows adding extensions from chrome web store on ungoogled-chromium")
(description "This extension brings the following functionality to
ungoogled-chromium (and other forks that lack web store support):
@itemize
@item Allows installing extensions directly from chrome web store.
@item Automatically checks for updates to your installed extensions and displays
them on the badge.
@end itemize")
(license license:expat)))
(define-public chromium-web-store/chromium
(make-chromium-extension chromium-web-store "chromium"))
( url " " )
( commit " bdc258b25df4d00f222fde0e3c5003bf88ef17b5 " ) ) )
( base32 " 1yi7mbyvxm9lsx6i1xbwp2bihwgzhwxkydk1kbngw5a5kw9azpws " ) ) ) )
( synopsis " EVDI Linux kernel module " )
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
( name " " )
( url " " )
( commit " bdc258b25df4d00f222fde0e3c5003bf88ef17b5 " ) ) )
( base32 " 1yi7mbyvxm9lsx6i1xbwp2bihwgzhwxkydk1kbngw5a5kw9azpws " ) ) ) )
( build - system gnu - build - system )
( mkdir - p lib )
( list ) )
( synopsis " EVDI Linux kernel module " )
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
( name " " )
( version " 5.6.1 " )
" 1hihsz35ccydzx04r8r9kz0hvqwj5fgr8zpzvwyhfxp2m549f9w9 " ) )
" " ) ) )
( ( string - append # $ output " /bin " ) )
( src - folder ( string - drop - right src - file 4 ) ) )
( invoke " sh " src - file " --keep " " --noexec " )
( delete - file - recursively " _ _ " )
( mkdir - p ( string - append # $ output " /bin " ) )
( synopsis " EVDI Linux kernel module " )
" The @acronym{EVDI , Extensible Virtual Display Interface } is a Linux kernel module
|
6dc0f3d84ca771d0872108e674f477eae8299c14d339ff163f89801babd43938 | kumarshantanu/lein-sub | core_test.clj | (ns child.core-test
(:use clojure.test
child.core))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1)))) | null | https://raw.githubusercontent.com/kumarshantanu/lein-sub/4ddbb83359b2f9b6435ffd5b9c012b81e28de1ac/subtest/child/test/child/core_test.clj | clojure | (ns child.core-test
(:use clojure.test
child.core))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1)))) | |
aeaaf817999eda4fc082241bb213d0c99a2acca6a2bef1f989a39ab18a9784b5 | music-suite/music-suite | Score.hs | # LANGUAGE NoMonomorphismRestriction #
module Main where
import Music.Prelude hiding (snareDrum)
import Util
{-
Encoding of standard popular-music rhythms
Sources:
-lessons/live-lessons-archive/7-essential-drum-beats/
etc.
-}
music = fmap toNote basic1
-- TODO proper percussion support
openHiHat = d'
closeHiHat = d
hiHat = g'
bassDrum = f
snareDrum = c'
basic1 = toPattern
[ "xxxxxxxx"
, "b s b s " ]
basic1WithOpenClose = toPattern
[ "+o+o+o+o"
, "xxxxxxxx"
, "b s b s " ]
toPattern :: [String] -> Score Pitch
toPattern patterns = compress (fromIntegral $ maximum $ fmap length patterns) $ ppar $ fmap (removeRests . pseq . fmap g) patterns
where
g ' ' = rest
g 'x' = hiHat
g 'b' = bassDrum
g 's' = snareDrum
toNote = fromPitch
main = defaultMain music
| null | https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/examples/pieces/PopRhythms/Score.hs | haskell |
Encoding of standard popular-music rhythms
Sources:
-lessons/live-lessons-archive/7-essential-drum-beats/
etc.
TODO proper percussion support | # LANGUAGE NoMonomorphismRestriction #
module Main where
import Music.Prelude hiding (snareDrum)
import Util
music = fmap toNote basic1
openHiHat = d'
closeHiHat = d
hiHat = g'
bassDrum = f
snareDrum = c'
basic1 = toPattern
[ "xxxxxxxx"
, "b s b s " ]
basic1WithOpenClose = toPattern
[ "+o+o+o+o"
, "xxxxxxxx"
, "b s b s " ]
toPattern :: [String] -> Score Pitch
toPattern patterns = compress (fromIntegral $ maximum $ fmap length patterns) $ ppar $ fmap (removeRests . pseq . fmap g) patterns
where
g ' ' = rest
g 'x' = hiHat
g 'b' = bassDrum
g 's' = snareDrum
toNote = fromPitch
main = defaultMain music
|
e36b46ca3bf3d3b49609d96d2ca194d95922e26ed74ae112cef94f39c3100eb7 | xmonad/xmonad-contrib | IM.hs | # LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.IM
Description : Layout modfier for multi - windowed instant messengers like Psi or Tkabber .
Copyright : ( c ) , < >
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Roman Cheplyaka <>
-- Stability : unstable
-- Portability : unportable
--
Layout modfier suitable for workspace with multi - windowed instant messenger
-- (like Psi or Tkabber).
--
-----------------------------------------------------------------------------
module XMonad.Layout.IM (
-- * Usage
-- $usage
-- * Hints
-- $hints
-- * TODO
$ todo
Property(..), IM(..), withIM, gridIM,
AddRoster,
) where
import XMonad
import XMonad.Layout.Grid
import XMonad.Layout.LayoutModifier
import XMonad.Prelude
import XMonad.Util.WindowProperties
import qualified XMonad.StackSet as S
import Control.Arrow (first)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad . Layout . IM
-- > import Data.Ratio ((%))
--
Then edit your @layoutHook@ by adding IM modifier to layout which you prefer
-- for managing your chat windows (Grid in this example, another useful choice
-- to consider is Tabbed layout).
--
> myLayout = withIM ( 1%7 ) ( ClassName " Tkabber " ) Grid ||| Full ||| etc ..
-- > main = xmonad def { layoutHook = myLayout }
--
-- Here @1%7@ is the part of the screen which your roster will occupy,
\"Tkabber\"@ tells xmonad which window is actually your roster .
--
-- Screenshot: <:Xmonad-layout-im.png>
--
-- For more detailed instructions on editing the layoutHook see
-- <#customizing-xmonad the tutorial> and
-- "XMonad.Doc.Extending#Editing_the_layout_hook".
-- $hints
--
To launch IM layout automatically on your IM workspace use " XMonad . Layout . PerWorkspace " .
--
-- By default the roster window will appear on the left side.
-- To place roster window on the right side, use @reflectHoriz@ from
" XMonad . Layout . Reflect " module .
$ todo
-- This item are questionable. Please let me know if you find them useful.
--
* shrink\/expand
--
| Data type for LayoutModifier which converts given layout to IM - layout
-- (with dedicated space for the roster and original layout for chat windows)
data AddRoster a = AddRoster Rational Property deriving (Read, Show)
instance LayoutModifier AddRoster Window where
modifyLayout (AddRoster ratio prop) = applyIM ratio prop
modifierDescription _ = "IM"
| Modifier which converts given layout to IM - layout ( with dedicated
-- space for roster and original layout for chat windows)
withIM :: LayoutClass l a => Rational -> Property -> l a -> ModifiedLayout AddRoster l a
withIM ratio prop = ModifiedLayout $ AddRoster ratio prop
-- | IM layout modifier applied to the Grid layout
gridIM :: Rational -> Property -> ModifiedLayout AddRoster Grid a
gridIM ratio prop = withIM ratio prop Grid
-- | Internal function for adding space for the roster specified by
-- the property and running original layout for all chat windows
applyIM :: (LayoutClass l Window) =>
Rational
-> Property
-> S.Workspace WorkspaceId (l Window) Window
-> Rectangle
-> X ([(Window, Rectangle)], Maybe (l Window))
applyIM ratio prop wksp rect = do
let stack = S.stack wksp
let ws = S.integrate' stack
let (masterRect, slaveRect) = splitHorizontallyBy ratio rect
master <- findM (hasProperty prop) ws
case master of
Just w -> do
let filteredStack = stack >>= S.filter (w /=)
wrs <- runLayout (wksp {S.stack = filteredStack}) slaveRect
return (first ((w, masterRect) :) wrs)
Nothing -> runLayout wksp rect
-- | This is for compatibility with old configs only and will be removed in future versions!
data IM a = IM Rational Property deriving (Read, Show)
instance LayoutClass IM Window where
description _ = "IM"
doLayout (IM r prop) rect stack = do
let ws = S.integrate stack
let (masterRect, slaveRect) = splitHorizontallyBy r rect
master <- findM (hasProperty prop) ws
let positions = case master of
Just w -> (w, masterRect) : arrange defaultRatio slaveRect (filter (w /=) ws)
Nothing -> arrange defaultRatio rect ws
return (positions, Nothing)
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/e406e27139a14b3f06dc6d3e5ba2886376ee7a41/XMonad/Layout/IM.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Layout.IM
License : BSD-style (see LICENSE)
Maintainer : Roman Cheplyaka <>
Stability : unstable
Portability : unportable
(like Psi or Tkabber).
---------------------------------------------------------------------------
* Usage
$usage
* Hints
$hints
* TODO
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
> import Data.Ratio ((%))
for managing your chat windows (Grid in this example, another useful choice
to consider is Tabbed layout).
> main = xmonad def { layoutHook = myLayout }
Here @1%7@ is the part of the screen which your roster will occupy,
Screenshot: <:Xmonad-layout-im.png>
For more detailed instructions on editing the layoutHook see
<#customizing-xmonad the tutorial> and
"XMonad.Doc.Extending#Editing_the_layout_hook".
$hints
By default the roster window will appear on the left side.
To place roster window on the right side, use @reflectHoriz@ from
This item are questionable. Please let me know if you find them useful.
(with dedicated space for the roster and original layout for chat windows)
space for roster and original layout for chat windows)
| IM layout modifier applied to the Grid layout
| Internal function for adding space for the roster specified by
the property and running original layout for all chat windows
| This is for compatibility with old configs only and will be removed in future versions! | # LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts #
Description : Layout modfier for multi - windowed instant messengers like Psi or Tkabber .
Copyright : ( c ) , < >
Layout modfier suitable for workspace with multi - windowed instant messenger
module XMonad.Layout.IM (
$ todo
Property(..), IM(..), withIM, gridIM,
AddRoster,
) where
import XMonad
import XMonad.Layout.Grid
import XMonad.Layout.LayoutModifier
import XMonad.Prelude
import XMonad.Util.WindowProperties
import qualified XMonad.StackSet as S
import Control.Arrow (first)
> import XMonad . Layout . IM
Then edit your @layoutHook@ by adding IM modifier to layout which you prefer
> myLayout = withIM ( 1%7 ) ( ClassName " Tkabber " ) Grid ||| Full ||| etc ..
\"Tkabber\"@ tells xmonad which window is actually your roster .
To launch IM layout automatically on your IM workspace use " XMonad . Layout . PerWorkspace " .
" XMonad . Layout . Reflect " module .
$ todo
* shrink\/expand
| Data type for LayoutModifier which converts given layout to IM - layout
data AddRoster a = AddRoster Rational Property deriving (Read, Show)
instance LayoutModifier AddRoster Window where
modifyLayout (AddRoster ratio prop) = applyIM ratio prop
modifierDescription _ = "IM"
| Modifier which converts given layout to IM - layout ( with dedicated
withIM :: LayoutClass l a => Rational -> Property -> l a -> ModifiedLayout AddRoster l a
withIM ratio prop = ModifiedLayout $ AddRoster ratio prop
gridIM :: Rational -> Property -> ModifiedLayout AddRoster Grid a
gridIM ratio prop = withIM ratio prop Grid
applyIM :: (LayoutClass l Window) =>
Rational
-> Property
-> S.Workspace WorkspaceId (l Window) Window
-> Rectangle
-> X ([(Window, Rectangle)], Maybe (l Window))
applyIM ratio prop wksp rect = do
let stack = S.stack wksp
let ws = S.integrate' stack
let (masterRect, slaveRect) = splitHorizontallyBy ratio rect
master <- findM (hasProperty prop) ws
case master of
Just w -> do
let filteredStack = stack >>= S.filter (w /=)
wrs <- runLayout (wksp {S.stack = filteredStack}) slaveRect
return (first ((w, masterRect) :) wrs)
Nothing -> runLayout wksp rect
data IM a = IM Rational Property deriving (Read, Show)
instance LayoutClass IM Window where
description _ = "IM"
doLayout (IM r prop) rect stack = do
let ws = S.integrate stack
let (masterRect, slaveRect) = splitHorizontallyBy r rect
master <- findM (hasProperty prop) ws
let positions = case master of
Just w -> (w, masterRect) : arrange defaultRatio slaveRect (filter (w /=) ws)
Nothing -> arrange defaultRatio rect ws
return (positions, Nothing)
|
210d3bd4de063022b7fb356484f1eb54f0da736c1d6e8de578b4c91eac293ab4 | clj-kafka/franzy | schema.clj | (ns franzy.common.schema
"Basic schemas for validating Kafka configs, types, functions, etc."
(:require [schema.core :as s]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Basic validations - many of these can probably be replaced by things inside Schema...ongoing struggle
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def Function
"Schema for a target that must be a function."
(s/pred fn? 'fn?))
(def AnyButNil
"Schema for a value that can be anything but nil."
(s/pred some? 'not-nil?))
(def NonEmptyString
"Schema for a string that cannot be blank."
(s/constrained s/Str (complement clojure.string/blank?) 'blank?))
(defn gt-eq-zero? [x]
(>= x 0))
(def GreaterThanOrEqualToZero
"Schema for a number greater than or equal to zero."
(s/pred gt-eq-zero? 'GreaterThanOrEqualToZero?))
(def Positive
"Schema for a positive Number."
(s/pred pos? 'pos?))
Following " Java " schemas below are for general interop .
Clojure will coerce to the right type , warn , throw , etc . , however when dealing with interop , we do n't want any fun surprises .
;; Moreover, we also would like a friendly message why, rather than from the compiler or further down in a stack trace.
;; Likewise, we want to ensure when a schema is checked that we know a value is out of range, especially for a particular config-related value.
(def CoercableInt
"Schema for a value that is coercable without overflow to a Integer."
(s/constrained s/Int #(<= Integer/MIN_VALUE % Integer/MAX_VALUE) 'coercable-int?))
(def CoercableLong
"Schema for a value that is coercable without overflow to a Long."
(s/constrained s/Int #(<= Long/MIN_VALUE % Long/MAX_VALUE) 'coercable-long?))
(def CoercableShort
"Schema for a value that is coercable without overflow to a Short."
(s/constrained s/Int #(<= Short/MIN_VALUE % Short/MAX_VALUE) 'coercable-short?))
(def CoercableDouble
"Schema for a value that is coercable without overflow to a Double."
s/Num)
(def NegativeDefaultNumber
"Schema for defaults that assume -1 as a null/not set. This schema is mainly for composition with other Schemas."
(s/pred (partial <= -1) 'snegativedefaultnumber?))
(def PosInt
"Schema for positive integers."
(s/constrained CoercableInt pos?))
(def SPosInt
"Schema for positive, zero inclusive integers."
(s/constrained CoercableInt gt-eq-zero?))
(def SPosIntWithDefault
"Schema for positive, zero inclusive integers that can also have -1 as a default value."
(s/either SPosInt NegativeDefaultNumber))
(def PosLong
"Schema for positive longs."
(s/constrained CoercableLong pos?))
(def SPosLong
"Schema for positive, zero inclusive longs."
(s/constrained CoercableLong gt-eq-zero?))
(def SPosLongWithDefault
"Schema for positive, zero inclusive longs that can also have -1 as a default value."
(s/either SPosLong NegativeDefaultNumber))
(def PosShort
"Schema for positive shorts."
(s/constrained CoercableShort pos?))
(def SPosShort
"Schema for positive, zero inclusive shorts."
(s/constrained CoercableLong gt-eq-zero?))
(def SPosShortWithDefault
"Schema for positive, zero inclusive shorts that can have also have -1 as a default value."
(s/either SPosShort NegativeDefaultNumber))
(def PosDouble
"Schema for positive doubles."
(s/constrained CoercableDouble pos?))
(def SPosDouble
"Schema for positive, zero inclusive doubles."
(s/constrained CoercableDouble gt-eq-zero?))
(def SPosDoubleWithDefault
"Schema for positive, zero inclusive doubles that can have also have -1 as a default value."
(s/either SPosDouble NegativeDefaultNumber))
(def NamespacedKeyword
"Schema for keywords that must be namespaced, i.e. :my-namespace/my-keyword"
(s/pred (fn [kw]
(and (keyword? kw)
(namespace kw)))
'keyword-namespaced?))
(def NotEmpty
"Schema for collections that must not be empty."
(s/pred (complement empty?) 'not-empty?))
(def StringOrList
"Schema for a value that can be a string or a collection."
(s/pred (fn [x] (cond
(string? x)
true
(sequential? x)
true)) 'string-or-list?))
(def NonEmptyStringOrList
"Schema for a value that can be a string or a collection."
(s/pred (fn [x] (cond
(string? x)
(if (clojure.string/blank? x) false true)
(sequential? x)
(if (empty? x) false true))) 'non-empty-string-or-list?))
(def StringOrStringList
"Schema for a value that can be a string or string collection."
(s/pred (fn [x] (cond
(string? x)
true
(sequential? x)
(every? string? x)))
'string-or-string-list?))
(def NonEmptyStringOrStringList
"Schema for a value that can be a non-empty string or string collection."
(s/pred (fn [x] (cond
(string? x)
(if (clojure.string/blank? x) false true)
(sequential? x)
(if (empty? x) false (every? #(and (string? %) (not (clojure.string/blank? %))) x))))
'non-empty-string-or-string-list?))
| null | https://raw.githubusercontent.com/clj-kafka/franzy/6c2e2e65ad137d2bcbc04ff6e671f97ea8c0e380/common/src/franzy/common/schema.clj | clojure |
Basic validations - many of these can probably be replaced by things inside Schema...ongoing struggle
Moreover, we also would like a friendly message why, rather than from the compiler or further down in a stack trace.
Likewise, we want to ensure when a schema is checked that we know a value is out of range, especially for a particular config-related value. | (ns franzy.common.schema
"Basic schemas for validating Kafka configs, types, functions, etc."
(:require [schema.core :as s]))
(def Function
"Schema for a target that must be a function."
(s/pred fn? 'fn?))
(def AnyButNil
"Schema for a value that can be anything but nil."
(s/pred some? 'not-nil?))
(def NonEmptyString
"Schema for a string that cannot be blank."
(s/constrained s/Str (complement clojure.string/blank?) 'blank?))
(defn gt-eq-zero? [x]
(>= x 0))
(def GreaterThanOrEqualToZero
"Schema for a number greater than or equal to zero."
(s/pred gt-eq-zero? 'GreaterThanOrEqualToZero?))
(def Positive
"Schema for a positive Number."
(s/pred pos? 'pos?))
Following " Java " schemas below are for general interop .
Clojure will coerce to the right type , warn , throw , etc . , however when dealing with interop , we do n't want any fun surprises .
(def CoercableInt
"Schema for a value that is coercable without overflow to a Integer."
(s/constrained s/Int #(<= Integer/MIN_VALUE % Integer/MAX_VALUE) 'coercable-int?))
(def CoercableLong
"Schema for a value that is coercable without overflow to a Long."
(s/constrained s/Int #(<= Long/MIN_VALUE % Long/MAX_VALUE) 'coercable-long?))
(def CoercableShort
"Schema for a value that is coercable without overflow to a Short."
(s/constrained s/Int #(<= Short/MIN_VALUE % Short/MAX_VALUE) 'coercable-short?))
(def CoercableDouble
"Schema for a value that is coercable without overflow to a Double."
s/Num)
(def NegativeDefaultNumber
"Schema for defaults that assume -1 as a null/not set. This schema is mainly for composition with other Schemas."
(s/pred (partial <= -1) 'snegativedefaultnumber?))
(def PosInt
"Schema for positive integers."
(s/constrained CoercableInt pos?))
(def SPosInt
"Schema for positive, zero inclusive integers."
(s/constrained CoercableInt gt-eq-zero?))
(def SPosIntWithDefault
"Schema for positive, zero inclusive integers that can also have -1 as a default value."
(s/either SPosInt NegativeDefaultNumber))
(def PosLong
"Schema for positive longs."
(s/constrained CoercableLong pos?))
(def SPosLong
"Schema for positive, zero inclusive longs."
(s/constrained CoercableLong gt-eq-zero?))
(def SPosLongWithDefault
"Schema for positive, zero inclusive longs that can also have -1 as a default value."
(s/either SPosLong NegativeDefaultNumber))
(def PosShort
"Schema for positive shorts."
(s/constrained CoercableShort pos?))
(def SPosShort
"Schema for positive, zero inclusive shorts."
(s/constrained CoercableLong gt-eq-zero?))
(def SPosShortWithDefault
"Schema for positive, zero inclusive shorts that can have also have -1 as a default value."
(s/either SPosShort NegativeDefaultNumber))
(def PosDouble
"Schema for positive doubles."
(s/constrained CoercableDouble pos?))
(def SPosDouble
"Schema for positive, zero inclusive doubles."
(s/constrained CoercableDouble gt-eq-zero?))
(def SPosDoubleWithDefault
"Schema for positive, zero inclusive doubles that can have also have -1 as a default value."
(s/either SPosDouble NegativeDefaultNumber))
(def NamespacedKeyword
"Schema for keywords that must be namespaced, i.e. :my-namespace/my-keyword"
(s/pred (fn [kw]
(and (keyword? kw)
(namespace kw)))
'keyword-namespaced?))
(def NotEmpty
"Schema for collections that must not be empty."
(s/pred (complement empty?) 'not-empty?))
(def StringOrList
"Schema for a value that can be a string or a collection."
(s/pred (fn [x] (cond
(string? x)
true
(sequential? x)
true)) 'string-or-list?))
(def NonEmptyStringOrList
"Schema for a value that can be a string or a collection."
(s/pred (fn [x] (cond
(string? x)
(if (clojure.string/blank? x) false true)
(sequential? x)
(if (empty? x) false true))) 'non-empty-string-or-list?))
(def StringOrStringList
"Schema for a value that can be a string or string collection."
(s/pred (fn [x] (cond
(string? x)
true
(sequential? x)
(every? string? x)))
'string-or-string-list?))
(def NonEmptyStringOrStringList
"Schema for a value that can be a non-empty string or string collection."
(s/pred (fn [x] (cond
(string? x)
(if (clojure.string/blank? x) false true)
(sequential? x)
(if (empty? x) false (every? #(and (string? %) (not (clojure.string/blank? %))) x))))
'non-empty-string-or-string-list?))
|
043283d816d37a44499fbab7748bd0b44aaaded9f66a0ef75a9d4ac57e416508 | DSiSc/why3 | printer.mli | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
open Wstdlib
open Ident
open Ty
open Term
open Decl
open Theory
open Task
(** Register printers *)
type prelude = string list
type prelude_map = prelude Mid.t
type interface = string list
type interface_map = interface Mid.t
type blacklist = string list
Makes it possible to estabilish traceability from names
in the output of the printer to elements of AST in its input .
in the output of the printer to elements of AST in its input. *)
type printer_mapping = {
lsymbol_m : string -> Term.lsymbol;
vc_term_loc : Loc.position option;
(* The position of the term that triggers the VC *)
queried_terms : Term.term Mstr.t;
(* The list of terms that were queried for the counter-example
by the printer *)
list_projections: Sstr.t;
(* List of projections as printed in the model *)
list_records: ((string * string) list) Mstr.t;
}
type printer_args = {
env : Env.env;
prelude : prelude;
th_prelude : prelude_map;
blacklist : blacklist;
mutable printer_mapping : printer_mapping;
}
type printer = printer_args -> ?old:in_channel -> task Pp.pp
val get_default_printer_mapping : printer_mapping
val register_printer : desc:Pp.formatted -> string -> printer -> unit
val lookup_printer : string -> printer
val list_printers : unit -> (string * Pp.formatted) list
* { 2 Use printers }
val print_prelude : prelude Pp.pp
val print_th_prelude : task -> prelude_map Pp.pp
val print_interface : interface Pp.pp
val meta_syntax_type : meta
val meta_syntax_logic : meta
val meta_syntax_converter : meta
val meta_syntax_literal : meta
val meta_remove_prop : meta
val meta_remove_logic : meta
val meta_remove_type : meta
val meta_realized_theory : meta
val syntax_type : tysymbol -> string -> bool -> tdecl
val syntax_logic : lsymbol -> string -> bool -> tdecl
val syntax_converter : lsymbol -> string -> bool -> tdecl
val syntax_literal : tysymbol -> string -> bool -> tdecl
val remove_prop : prsymbol -> tdecl
val check_syntax_type: tysymbol -> string -> unit
val check_syntax_logic: lsymbol -> string -> unit
type syntax_map = (string*int) Mid.t
(* [syntax_map] maps the idents of removed props to "" *)
type converter_map = (string*int) Mls.t
val get_syntax_map : task -> syntax_map
val add_syntax_map : tdecl -> syntax_map -> syntax_map
(* interprets a declaration as a syntax rule, if any *)
val get_converter_map : task -> converter_map
val get_rliteral_map : task -> syntax_map
val add_rliteral_map : tdecl -> syntax_map -> syntax_map
val query_syntax : syntax_map -> ident -> string option
val query_converter : converter_map -> lsymbol -> string option
val syntax_arguments : string -> 'a Pp.pp -> 'a list Pp.pp
(** (syntax_arguments templ print_arg fmt l) prints in the formatter fmt
the list l using the template templ and the printer print_arg *)
val gen_syntax_arguments_typed :
('a -> 'b) -> ('a -> 'b array) -> string -> 'a Pp.pp -> 'b Pp.pp -> 'a -> 'a list Pp.pp
val syntax_arguments_typed :
string -> term Pp.pp -> ty Pp.pp -> term -> term list Pp.pp
(** (syntax_arguments templ print_arg fmt l) prints in the formatter fmt
the list l using the template templ and the printer print_arg *)
val syntax_range_literal :
string -> Number.integer_constant Pp.pp
val syntax_float_literal :
string -> Number.float_format -> Number.real_constant Pp.pp
* { 2 pretty - printing transformations ( useful for caching ) }
val on_syntax_map : (syntax_map -> 'a Trans.trans) -> 'a Trans.trans
val on_converter_map : (converter_map -> 'a Trans.trans) -> 'a Trans.trans
val sprint_tdecl :
('a -> Format.formatter -> Theory.tdecl -> 'a * string list) ->
Theory.tdecl -> 'a * string list -> 'a * string list
val sprint_decl :
('a -> Format.formatter -> Decl.decl -> 'a * string list) ->
Theory.tdecl -> 'a * string list -> 'a * string list
* { 2 Exceptions to use in transformations and printers }
exception UnsupportedType of ty * string
exception UnsupportedTerm of term * string
exception UnsupportedDecl of decl * string
exception NotImplemented of string
val unsupportedType : ty -> string -> 'a
val unsupportedTerm : term -> string -> 'a
val unsupportedPattern : pattern -> string -> 'a
val unsupportedDecl : decl -> string -> 'a
val notImplemented : string -> 'a
(** {3 Functions that catch inner error} *)
exception Unsupported of string
* This exception must be raised only inside a call
of one of the catch _ * functions below
of one of the catch_* functions below *)
val unsupported : string -> 'a
val catch_unsupportedType : (ty -> 'a) -> (ty -> 'a)
* [ catch_unsupportedType f ] return a function which applied on [ arg ] :
- return [ f arg ] if [ f arg ] does not raise { ! Unsupported } exception
- raise [ UnsupportedType ( arg , s ) ] if [ f arg ] raises [ Unsupported s ]
- return [f arg] if [f arg] does not raise {!Unsupported} exception
- raise [UnsupportedType (arg,s)] if [f arg] raises [Unsupported s]*)
val catch_unsupportedTerm : (term -> 'a) -> (term -> 'a)
* same as { ! catch_unsupportedType } but use [ UnsupportedExpr ]
instead of [ UnsupportedType ]
instead of [UnsupportedType]*)
val catch_unsupportedDecl : (decl -> 'a) -> (decl -> 'a)
* same as { ! catch_unsupportedType } but use [ UnsupportedDecl ]
instead of [ UnsupportedType ]
instead of [UnsupportedType] *)
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/core/printer.mli | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
******************************************************************
* Register printers
The position of the term that triggers the VC
The list of terms that were queried for the counter-example
by the printer
List of projections as printed in the model
[syntax_map] maps the idents of removed props to ""
interprets a declaration as a syntax rule, if any
* (syntax_arguments templ print_arg fmt l) prints in the formatter fmt
the list l using the template templ and the printer print_arg
* (syntax_arguments templ print_arg fmt l) prints in the formatter fmt
the list l using the template templ and the printer print_arg
* {3 Functions that catch inner error} | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
General Public License version 2.1 , with the special exception
open Wstdlib
open Ident
open Ty
open Term
open Decl
open Theory
open Task
type prelude = string list
type prelude_map = prelude Mid.t
type interface = string list
type interface_map = interface Mid.t
type blacklist = string list
Makes it possible to estabilish traceability from names
in the output of the printer to elements of AST in its input .
in the output of the printer to elements of AST in its input. *)
type printer_mapping = {
lsymbol_m : string -> Term.lsymbol;
vc_term_loc : Loc.position option;
queried_terms : Term.term Mstr.t;
list_projections: Sstr.t;
list_records: ((string * string) list) Mstr.t;
}
type printer_args = {
env : Env.env;
prelude : prelude;
th_prelude : prelude_map;
blacklist : blacklist;
mutable printer_mapping : printer_mapping;
}
type printer = printer_args -> ?old:in_channel -> task Pp.pp
val get_default_printer_mapping : printer_mapping
val register_printer : desc:Pp.formatted -> string -> printer -> unit
val lookup_printer : string -> printer
val list_printers : unit -> (string * Pp.formatted) list
* { 2 Use printers }
val print_prelude : prelude Pp.pp
val print_th_prelude : task -> prelude_map Pp.pp
val print_interface : interface Pp.pp
val meta_syntax_type : meta
val meta_syntax_logic : meta
val meta_syntax_converter : meta
val meta_syntax_literal : meta
val meta_remove_prop : meta
val meta_remove_logic : meta
val meta_remove_type : meta
val meta_realized_theory : meta
val syntax_type : tysymbol -> string -> bool -> tdecl
val syntax_logic : lsymbol -> string -> bool -> tdecl
val syntax_converter : lsymbol -> string -> bool -> tdecl
val syntax_literal : tysymbol -> string -> bool -> tdecl
val remove_prop : prsymbol -> tdecl
val check_syntax_type: tysymbol -> string -> unit
val check_syntax_logic: lsymbol -> string -> unit
type syntax_map = (string*int) Mid.t
type converter_map = (string*int) Mls.t
val get_syntax_map : task -> syntax_map
val add_syntax_map : tdecl -> syntax_map -> syntax_map
val get_converter_map : task -> converter_map
val get_rliteral_map : task -> syntax_map
val add_rliteral_map : tdecl -> syntax_map -> syntax_map
val query_syntax : syntax_map -> ident -> string option
val query_converter : converter_map -> lsymbol -> string option
val syntax_arguments : string -> 'a Pp.pp -> 'a list Pp.pp
val gen_syntax_arguments_typed :
('a -> 'b) -> ('a -> 'b array) -> string -> 'a Pp.pp -> 'b Pp.pp -> 'a -> 'a list Pp.pp
val syntax_arguments_typed :
string -> term Pp.pp -> ty Pp.pp -> term -> term list Pp.pp
val syntax_range_literal :
string -> Number.integer_constant Pp.pp
val syntax_float_literal :
string -> Number.float_format -> Number.real_constant Pp.pp
* { 2 pretty - printing transformations ( useful for caching ) }
val on_syntax_map : (syntax_map -> 'a Trans.trans) -> 'a Trans.trans
val on_converter_map : (converter_map -> 'a Trans.trans) -> 'a Trans.trans
val sprint_tdecl :
('a -> Format.formatter -> Theory.tdecl -> 'a * string list) ->
Theory.tdecl -> 'a * string list -> 'a * string list
val sprint_decl :
('a -> Format.formatter -> Decl.decl -> 'a * string list) ->
Theory.tdecl -> 'a * string list -> 'a * string list
* { 2 Exceptions to use in transformations and printers }
exception UnsupportedType of ty * string
exception UnsupportedTerm of term * string
exception UnsupportedDecl of decl * string
exception NotImplemented of string
val unsupportedType : ty -> string -> 'a
val unsupportedTerm : term -> string -> 'a
val unsupportedPattern : pattern -> string -> 'a
val unsupportedDecl : decl -> string -> 'a
val notImplemented : string -> 'a
exception Unsupported of string
* This exception must be raised only inside a call
of one of the catch _ * functions below
of one of the catch_* functions below *)
val unsupported : string -> 'a
val catch_unsupportedType : (ty -> 'a) -> (ty -> 'a)
* [ catch_unsupportedType f ] return a function which applied on [ arg ] :
- return [ f arg ] if [ f arg ] does not raise { ! Unsupported } exception
- raise [ UnsupportedType ( arg , s ) ] if [ f arg ] raises [ Unsupported s ]
- return [f arg] if [f arg] does not raise {!Unsupported} exception
- raise [UnsupportedType (arg,s)] if [f arg] raises [Unsupported s]*)
val catch_unsupportedTerm : (term -> 'a) -> (term -> 'a)
* same as { ! catch_unsupportedType } but use [ UnsupportedExpr ]
instead of [ UnsupportedType ]
instead of [UnsupportedType]*)
val catch_unsupportedDecl : (decl -> 'a) -> (decl -> 'a)
* same as { ! catch_unsupportedType } but use [ UnsupportedDecl ]
instead of [ UnsupportedType ]
instead of [UnsupportedType] *)
|
1832bb0e27bc7877eb0124bcbd679c5ec54d24c5a94e9ec3a868bef94d6f33ec | Nutr1t07/wl-bot | Unity.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Core.Web.Unity where
import Control.Exception
import Control.Lens
import Core.Data.Mirai as Q
import Core.Data.Telegram as T
import Core.Type.Unity.Request as U
import Core.Web.Mirai as Q
import Core.Web.Telegram as T
import Data.Aeson
import Data.ByteString.Lazy
import Data.Maybe
import Network.Wreq
import Utils.Config
import Utils.Logging
import Core.Type.Universal ( Platform(QQ, Telegram)
, TargetType
( Group
, Private
, Temp
)
)
import Utils.Env
type RB = Response ByteString
sendMsg :: U.SendMsg -> Env -> IO ()
sendMsg m e = do
s <- try (sendMsg' m e) :: IO (Either SomeException ())
case s of
Right _ -> return ()
Left err -> logErr "Sending msg" $ show err
sendMsg' :: U.SendMsg -> Env -> IO ()
sendMsg' msg env = case msg ^. target_plat of
Telegram -> case T.transMsg msg of
Left p -> () <$ postTgRequest' (config ^. tg_token) "sendPhoto" p
Right s -> () <$ postTgRequest
(config ^. tg_token)
(if isJust $ msg ^. imgUrl then "sendPhoto" else "sendMessage")
(toJSON s)
QQ -> case msg ^. target_type of
Private -> Q.sendPrivMsg (msg ^. chat_id) (Q.transMsg msg) env
Temp ->
Q.sendTempMsg (msg ^. user_id) (msg ^. chat_id) (Q.transMsg msg) env
Group ->
Q.sendGrpMsg (msg ^. chat_id) (Q.transMsg msg) env (msg ^. reply_id)
where config = cfg env
retry3Times :: IO a -> IO a
retry3Times action = (catch' . catch' . catch') action
where catch' a = catch action (\e -> const a (e :: SomeException))
| null | https://raw.githubusercontent.com/Nutr1t07/wl-bot/985e27caf2d492c32e5e73b64f0bc5f718e72c76/src/Core/Web/Unity.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes # | module Core.Web.Unity where
import Control.Exception
import Control.Lens
import Core.Data.Mirai as Q
import Core.Data.Telegram as T
import Core.Type.Unity.Request as U
import Core.Web.Mirai as Q
import Core.Web.Telegram as T
import Data.Aeson
import Data.ByteString.Lazy
import Data.Maybe
import Network.Wreq
import Utils.Config
import Utils.Logging
import Core.Type.Universal ( Platform(QQ, Telegram)
, TargetType
( Group
, Private
, Temp
)
)
import Utils.Env
type RB = Response ByteString
sendMsg :: U.SendMsg -> Env -> IO ()
sendMsg m e = do
s <- try (sendMsg' m e) :: IO (Either SomeException ())
case s of
Right _ -> return ()
Left err -> logErr "Sending msg" $ show err
sendMsg' :: U.SendMsg -> Env -> IO ()
sendMsg' msg env = case msg ^. target_plat of
Telegram -> case T.transMsg msg of
Left p -> () <$ postTgRequest' (config ^. tg_token) "sendPhoto" p
Right s -> () <$ postTgRequest
(config ^. tg_token)
(if isJust $ msg ^. imgUrl then "sendPhoto" else "sendMessage")
(toJSON s)
QQ -> case msg ^. target_type of
Private -> Q.sendPrivMsg (msg ^. chat_id) (Q.transMsg msg) env
Temp ->
Q.sendTempMsg (msg ^. user_id) (msg ^. chat_id) (Q.transMsg msg) env
Group ->
Q.sendGrpMsg (msg ^. chat_id) (Q.transMsg msg) env (msg ^. reply_id)
where config = cfg env
retry3Times :: IO a -> IO a
retry3Times action = (catch' . catch' . catch') action
where catch' a = catch action (\e -> const a (e :: SomeException))
|
8d1dd9ec487cfe6fa9f61bce3efb85d0dab8410d6392718918356b70aa9a717e | 2600hz/kazoo | kzd_auth_module_config.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
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 /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(kzd_auth_module_config).
-export([new/0]).
-export([enabled/1, enabled/2, set_enabled/2]).
-export([log_failed_attempts/1, log_failed_attempts/2, set_log_failed_attempts/2]).
-export([log_successful_attempts/1, log_successful_attempts/2, set_log_successful_attempts/2]).
-export([multi_factor/1, multi_factor/2, set_multi_factor/2]).
-export([multi_factor_account_id/1, multi_factor_account_id/2, set_multi_factor_account_id/2]).
-export([multi_factor_configuration_id/1, multi_factor_configuration_id/2, set_multi_factor_configuration_id/2]).
-export([multi_factor_enabled/1, multi_factor_enabled/2, set_multi_factor_enabled/2]).
-export([multi_factor_include_subaccounts/1, multi_factor_include_subaccounts/2, set_multi_factor_include_subaccounts/2]).
-export([token_auth_expiry_s/1, token_auth_expiry_s/2, set_token_auth_expiry_s/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"auth_module_config">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec enabled(doc()) -> kz_term:api_boolean().
enabled(Doc) ->
enabled(Doc, 'undefined').
-spec enabled(doc(), Default) -> boolean() | Default.
enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"enabled">>], Doc, Default).
-spec set_enabled(doc(), boolean()) -> doc().
set_enabled(Doc, Enabled) ->
kz_json:set_value([<<"enabled">>], Enabled, Doc).
-spec log_failed_attempts(doc()) -> kz_term:api_boolean().
log_failed_attempts(Doc) ->
log_failed_attempts(Doc, 'undefined').
-spec log_failed_attempts(doc(), Default) -> boolean() | Default.
log_failed_attempts(Doc, Default) ->
kz_json:get_boolean_value([<<"log_failed_attempts">>], Doc, Default).
-spec set_log_failed_attempts(doc(), boolean()) -> doc().
set_log_failed_attempts(Doc, LogFailedAttempts) ->
kz_json:set_value([<<"log_failed_attempts">>], LogFailedAttempts, Doc).
-spec log_successful_attempts(doc()) -> kz_term:api_boolean().
log_successful_attempts(Doc) ->
log_successful_attempts(Doc, 'undefined').
-spec log_successful_attempts(doc(), Default) -> boolean() | Default.
log_successful_attempts(Doc, Default) ->
kz_json:get_boolean_value([<<"log_successful_attempts">>], Doc, Default).
-spec set_log_successful_attempts(doc(), boolean()) -> doc().
set_log_successful_attempts(Doc, LogSuccessfulAttempts) ->
kz_json:set_value([<<"log_successful_attempts">>], LogSuccessfulAttempts, Doc).
-spec multi_factor(doc()) -> kz_term:api_object().
multi_factor(Doc) ->
multi_factor(Doc, 'undefined').
-spec multi_factor(doc(), Default) -> kz_json:object() | Default.
multi_factor(Doc, Default) ->
kz_json:get_json_value([<<"multi_factor">>], Doc, Default).
-spec set_multi_factor(doc(), kz_json:object()) -> doc().
set_multi_factor(Doc, MultiFactor) ->
kz_json:set_value([<<"multi_factor">>], MultiFactor, Doc).
-spec multi_factor_account_id(doc()) -> kz_term:api_binary().
multi_factor_account_id(Doc) ->
multi_factor_account_id(Doc, 'undefined').
-spec multi_factor_account_id(doc(), Default) -> binary() | Default.
multi_factor_account_id(Doc, Default) ->
kz_json:get_binary_value([<<"multi_factor">>, <<"account_id">>], Doc, Default).
-spec set_multi_factor_account_id(doc(), binary()) -> doc().
set_multi_factor_account_id(Doc, MultiFactorAccountId) ->
kz_json:set_value([<<"multi_factor">>, <<"account_id">>], MultiFactorAccountId, Doc).
-spec multi_factor_configuration_id(doc()) -> kz_term:api_binary().
multi_factor_configuration_id(Doc) ->
multi_factor_configuration_id(Doc, 'undefined').
-spec multi_factor_configuration_id(doc(), Default) -> binary() | Default.
multi_factor_configuration_id(Doc, Default) ->
kz_json:get_binary_value([<<"multi_factor">>, <<"configuration_id">>], Doc, Default).
-spec set_multi_factor_configuration_id(doc(), binary()) -> doc().
set_multi_factor_configuration_id(Doc, MultiFactorConfigurationId) ->
kz_json:set_value([<<"multi_factor">>, <<"configuration_id">>], MultiFactorConfigurationId, Doc).
-spec multi_factor_enabled(doc()) -> kz_term:api_boolean().
multi_factor_enabled(Doc) ->
multi_factor_enabled(Doc, 'undefined').
-spec multi_factor_enabled(doc(), Default) -> boolean() | Default.
multi_factor_enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"multi_factor">>, <<"enabled">>], Doc, Default).
-spec set_multi_factor_enabled(doc(), boolean()) -> doc().
set_multi_factor_enabled(Doc, MultiFactorEnabled) ->
kz_json:set_value([<<"multi_factor">>, <<"enabled">>], MultiFactorEnabled, Doc).
-spec multi_factor_include_subaccounts(doc()) -> kz_term:api_boolean().
multi_factor_include_subaccounts(Doc) ->
multi_factor_include_subaccounts(Doc, 'undefined').
-spec multi_factor_include_subaccounts(doc(), Default) -> boolean() | Default.
multi_factor_include_subaccounts(Doc, Default) ->
kz_json:get_boolean_value([<<"multi_factor">>, <<"include_subaccounts">>], Doc, Default).
-spec set_multi_factor_include_subaccounts(doc(), boolean()) -> doc().
set_multi_factor_include_subaccounts(Doc, MultiFactorIncludeSubaccounts) ->
kz_json:set_value([<<"multi_factor">>, <<"include_subaccounts">>], MultiFactorIncludeSubaccounts, Doc).
-spec token_auth_expiry_s(doc()) -> kz_term:api_integer().
token_auth_expiry_s(Doc) ->
token_auth_expiry_s(Doc, 'undefined').
-spec token_auth_expiry_s(doc(), Default) -> integer() | Default.
token_auth_expiry_s(Doc, Default) ->
kz_json:get_integer_value([<<"token_auth_expiry_s">>], Doc, Default).
-spec set_token_auth_expiry_s(doc(), integer()) -> doc().
set_token_auth_expiry_s(Doc, TokenAuthenticationExpiryS) ->
kz_json:set_value([<<"token_auth_expiry_s">>], TokenAuthenticationExpiryS, Doc).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_auth_module_config.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
----------------------------------------------------------------------------- | ( C ) 2010 - 2020 , 2600Hz
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 /.
-module(kzd_auth_module_config).
-export([new/0]).
-export([enabled/1, enabled/2, set_enabled/2]).
-export([log_failed_attempts/1, log_failed_attempts/2, set_log_failed_attempts/2]).
-export([log_successful_attempts/1, log_successful_attempts/2, set_log_successful_attempts/2]).
-export([multi_factor/1, multi_factor/2, set_multi_factor/2]).
-export([multi_factor_account_id/1, multi_factor_account_id/2, set_multi_factor_account_id/2]).
-export([multi_factor_configuration_id/1, multi_factor_configuration_id/2, set_multi_factor_configuration_id/2]).
-export([multi_factor_enabled/1, multi_factor_enabled/2, set_multi_factor_enabled/2]).
-export([multi_factor_include_subaccounts/1, multi_factor_include_subaccounts/2, set_multi_factor_include_subaccounts/2]).
-export([token_auth_expiry_s/1, token_auth_expiry_s/2, set_token_auth_expiry_s/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"auth_module_config">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec enabled(doc()) -> kz_term:api_boolean().
enabled(Doc) ->
enabled(Doc, 'undefined').
-spec enabled(doc(), Default) -> boolean() | Default.
enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"enabled">>], Doc, Default).
-spec set_enabled(doc(), boolean()) -> doc().
set_enabled(Doc, Enabled) ->
kz_json:set_value([<<"enabled">>], Enabled, Doc).
-spec log_failed_attempts(doc()) -> kz_term:api_boolean().
log_failed_attempts(Doc) ->
log_failed_attempts(Doc, 'undefined').
-spec log_failed_attempts(doc(), Default) -> boolean() | Default.
log_failed_attempts(Doc, Default) ->
kz_json:get_boolean_value([<<"log_failed_attempts">>], Doc, Default).
-spec set_log_failed_attempts(doc(), boolean()) -> doc().
set_log_failed_attempts(Doc, LogFailedAttempts) ->
kz_json:set_value([<<"log_failed_attempts">>], LogFailedAttempts, Doc).
-spec log_successful_attempts(doc()) -> kz_term:api_boolean().
log_successful_attempts(Doc) ->
log_successful_attempts(Doc, 'undefined').
-spec log_successful_attempts(doc(), Default) -> boolean() | Default.
log_successful_attempts(Doc, Default) ->
kz_json:get_boolean_value([<<"log_successful_attempts">>], Doc, Default).
-spec set_log_successful_attempts(doc(), boolean()) -> doc().
set_log_successful_attempts(Doc, LogSuccessfulAttempts) ->
kz_json:set_value([<<"log_successful_attempts">>], LogSuccessfulAttempts, Doc).
-spec multi_factor(doc()) -> kz_term:api_object().
multi_factor(Doc) ->
multi_factor(Doc, 'undefined').
-spec multi_factor(doc(), Default) -> kz_json:object() | Default.
multi_factor(Doc, Default) ->
kz_json:get_json_value([<<"multi_factor">>], Doc, Default).
-spec set_multi_factor(doc(), kz_json:object()) -> doc().
set_multi_factor(Doc, MultiFactor) ->
kz_json:set_value([<<"multi_factor">>], MultiFactor, Doc).
-spec multi_factor_account_id(doc()) -> kz_term:api_binary().
multi_factor_account_id(Doc) ->
multi_factor_account_id(Doc, 'undefined').
-spec multi_factor_account_id(doc(), Default) -> binary() | Default.
multi_factor_account_id(Doc, Default) ->
kz_json:get_binary_value([<<"multi_factor">>, <<"account_id">>], Doc, Default).
-spec set_multi_factor_account_id(doc(), binary()) -> doc().
set_multi_factor_account_id(Doc, MultiFactorAccountId) ->
kz_json:set_value([<<"multi_factor">>, <<"account_id">>], MultiFactorAccountId, Doc).
-spec multi_factor_configuration_id(doc()) -> kz_term:api_binary().
multi_factor_configuration_id(Doc) ->
multi_factor_configuration_id(Doc, 'undefined').
-spec multi_factor_configuration_id(doc(), Default) -> binary() | Default.
multi_factor_configuration_id(Doc, Default) ->
kz_json:get_binary_value([<<"multi_factor">>, <<"configuration_id">>], Doc, Default).
-spec set_multi_factor_configuration_id(doc(), binary()) -> doc().
set_multi_factor_configuration_id(Doc, MultiFactorConfigurationId) ->
kz_json:set_value([<<"multi_factor">>, <<"configuration_id">>], MultiFactorConfigurationId, Doc).
-spec multi_factor_enabled(doc()) -> kz_term:api_boolean().
multi_factor_enabled(Doc) ->
multi_factor_enabled(Doc, 'undefined').
-spec multi_factor_enabled(doc(), Default) -> boolean() | Default.
multi_factor_enabled(Doc, Default) ->
kz_json:get_boolean_value([<<"multi_factor">>, <<"enabled">>], Doc, Default).
-spec set_multi_factor_enabled(doc(), boolean()) -> doc().
set_multi_factor_enabled(Doc, MultiFactorEnabled) ->
kz_json:set_value([<<"multi_factor">>, <<"enabled">>], MultiFactorEnabled, Doc).
-spec multi_factor_include_subaccounts(doc()) -> kz_term:api_boolean().
multi_factor_include_subaccounts(Doc) ->
multi_factor_include_subaccounts(Doc, 'undefined').
-spec multi_factor_include_subaccounts(doc(), Default) -> boolean() | Default.
multi_factor_include_subaccounts(Doc, Default) ->
kz_json:get_boolean_value([<<"multi_factor">>, <<"include_subaccounts">>], Doc, Default).
-spec set_multi_factor_include_subaccounts(doc(), boolean()) -> doc().
set_multi_factor_include_subaccounts(Doc, MultiFactorIncludeSubaccounts) ->
kz_json:set_value([<<"multi_factor">>, <<"include_subaccounts">>], MultiFactorIncludeSubaccounts, Doc).
-spec token_auth_expiry_s(doc()) -> kz_term:api_integer().
token_auth_expiry_s(Doc) ->
token_auth_expiry_s(Doc, 'undefined').
-spec token_auth_expiry_s(doc(), Default) -> integer() | Default.
token_auth_expiry_s(Doc, Default) ->
kz_json:get_integer_value([<<"token_auth_expiry_s">>], Doc, Default).
-spec set_token_auth_expiry_s(doc(), integer()) -> doc().
set_token_auth_expiry_s(Doc, TokenAuthenticationExpiryS) ->
kz_json:set_value([<<"token_auth_expiry_s">>], TokenAuthenticationExpiryS, Doc).
|
4350075e95d026731c00143cc564e998e764e50f68d463c55d5db8c5f9022ebc | vimus/libmpd-haskell | Status.hs | # LANGUAGE OverloadedStrings , TupleSections #
|
Module : Network . MPD.Applicative . Status
Copyright : ( c ) Joachim Fasting 2012
License : MIT
Maintainer :
Stability : stable
Portability : unportable
Querying MPD 's status .
Module : Network.MPD.Applicative.Status
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer :
Stability : stable
Portability : unportable
Querying MPD's status.
-}
module Network.MPD.Applicative.Status
( clearError
, currentSong
, idle
, noidle
, status
, stats
) where
import Control.Monad
import Control.Arrow ((***))
import Network.MPD.Util
import Network.MPD.Applicative.Internal
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Commands.Parse
import Network.MPD.Commands.Types
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
-- | Clear current error message in status.
clearError :: Command ()
clearError = Command emptyResponse ["clearerror"]
-- | Song metadata for currently playing song, if any.
currentSong :: Command (Maybe Song)
currentSong = Command (liftParser parseMaybeSong) ["currentsong"]
takeSubsystems :: [ByteString] -> Either String [Subsystem]
takeSubsystems = mapM f . toAssocList
where
f :: (ByteString, ByteString) -> Either String Subsystem
f ("changed", system) =
case system of
"database" -> Right DatabaseS
"update" -> Right UpdateS
"stored_playlist" -> Right StoredPlaylistS
"playlist" -> Right PlaylistS
"player" -> Right PlayerS
"mixer" -> Right MixerS
"output" -> Right OutputS
"options" -> Right OptionsS
"partition" -> Right PartitionS
"sticker" -> Right StickerS
"subscription" -> Right SubscriptionS
"message" -> Right MessageS
"neighbor" -> Right NeighborS
"mount" -> Right MountS
k -> Left ("Unknown subsystem: " ++ UTF8.toString k)
f x = Left ("idle: Unexpected " ++ show x)
| Wait until there is noteworthy change in one or more of MPD 's
-- subsystems.
-- When active, only 'noidle' commands are allowed.
idle :: [Subsystem] -> Command [Subsystem]
idle ss = Command (liftParser takeSubsystems) c
where
c = ["idle" <@> foldr (<++>) (Args []) ss]
-- | Cancel an 'idle' request.
noidle :: Command ()
noidle = Command emptyResponse ["noidle"]
-- | Get database statistics.
stats :: Command Stats
stats = Command (liftParser parseStats) ["stats"]
-- | Get the current status of the player.
status :: Command Status
status = Command (liftParser parseStatus) ["status"]
where
-- Builds a 'Status' instance from an assoc. list.
parseStatus :: [ByteString] -> Either String Status
parseStatus = foldM go def . toAssocList
where
go a p@(k, v) = case k of
"volume" -> vol $ \x -> a { stVolume = x }
"repeat" -> bool $ \x -> a { stRepeat = x }
"random" -> bool $ \x -> a { stRandom = x }
"single" -> single $ \x -> a { stSingle = x }
"consume" -> bool $ \x -> a { stConsume = x }
"playlist" -> num $ \x -> a { stPlaylistVersion = x }
"playlistlength" -> num $ \x -> a { stPlaylistLength = x }
"state" -> state $ \x -> a { stState = x }
"song" -> int $ \x -> a { stSongPos = Just x }
"songid" -> int $ \x -> a { stSongID = Just $ Id x }
"nextsong" -> int $ \x -> a { stNextSongPos = Just x }
"nextsongid" -> int $ \x -> a { stNextSongID = Just $ Id x }
"time" -> time $ \x -> a { stTime = Just x }
"elapsed" -> frac $ \x -> a { stTime = fmap ((x,) . snd) (stTime a) }
"duration" -> frac $ \x -> a { stTime = fmap ((,x) . fst) (stTime a) }
"bitrate" -> int $ \x -> a { stBitrate = Just x }
"xfade" -> num $ \x -> a { stXFadeWidth = x }
"mixrampdb" -> frac $ \x -> a { stMixRampdB = x }
"mixrampdelay" -> frac $ \x -> a { stMixRampDelay = x }
"audio" -> audio $ \x -> a { stAudio = x }
"updating_db" -> num $ \x -> a { stUpdatingDb = Just x }
"error" -> Right a { stError = Just (UTF8.toString v) }
"partition" -> Right a { stPartition = UTF8.toString v }
_ -> Right a
where
unexpectedPair = Left ("unexpected key-value pair: " ++ show p)
int f = maybe unexpectedPair (Right . f) (parseNum v :: Maybe Int)
num f = maybe unexpectedPair (Right . f) (parseNum v)
bool f = maybe unexpectedPair (Right . f) (parseBool v)
frac f = maybe unexpectedPair (Right . f) (parseFrac v)
single f = maybe unexpectedPair (Right . f) (parseSingle v)
This is sometimes " audio : 0:?:0 " , so we ignore any parse
-- errors.
audio f = Right $ maybe a f (parseTriple ':' parseNum v)
time f = case parseFrac *** parseFrac $ breakChar ':' v of
(Just a_, Just b) -> (Right . f) (a_, b)
_ -> unexpectedPair
state f = case v of
"play" -> (Right . f) Playing
"pause" -> (Right . f) Paused
"stop" -> (Right . f) Stopped
_ -> unexpectedPair
-- A volume of -1 indicates an audio backend w/o a mixer
vol f = case (parseNum v :: Maybe Int) of
Nothing -> unexpectedPair -- does it really make sense to fail here? when does this occur?
Just v' -> (Right . f) (g v')
where g n | n < 0 = Nothing
| otherwise = Just $ fromIntegral n
| null | https://raw.githubusercontent.com/vimus/libmpd-haskell/1ec02deba33ce2a16012d8f0954e648eb4b5c485/src/Network/MPD/Applicative/Status.hs | haskell | | Clear current error message in status.
| Song metadata for currently playing song, if any.
subsystems.
When active, only 'noidle' commands are allowed.
| Cancel an 'idle' request.
| Get database statistics.
| Get the current status of the player.
Builds a 'Status' instance from an assoc. list.
errors.
A volume of -1 indicates an audio backend w/o a mixer
does it really make sense to fail here? when does this occur? | # LANGUAGE OverloadedStrings , TupleSections #
|
Module : Network . MPD.Applicative . Status
Copyright : ( c ) Joachim Fasting 2012
License : MIT
Maintainer :
Stability : stable
Portability : unportable
Querying MPD 's status .
Module : Network.MPD.Applicative.Status
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer :
Stability : stable
Portability : unportable
Querying MPD's status.
-}
module Network.MPD.Applicative.Status
( clearError
, currentSong
, idle
, noidle
, status
, stats
) where
import Control.Monad
import Control.Arrow ((***))
import Network.MPD.Util
import Network.MPD.Applicative.Internal
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Commands.Parse
import Network.MPD.Commands.Types
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
clearError :: Command ()
clearError = Command emptyResponse ["clearerror"]
currentSong :: Command (Maybe Song)
currentSong = Command (liftParser parseMaybeSong) ["currentsong"]
takeSubsystems :: [ByteString] -> Either String [Subsystem]
takeSubsystems = mapM f . toAssocList
where
f :: (ByteString, ByteString) -> Either String Subsystem
f ("changed", system) =
case system of
"database" -> Right DatabaseS
"update" -> Right UpdateS
"stored_playlist" -> Right StoredPlaylistS
"playlist" -> Right PlaylistS
"player" -> Right PlayerS
"mixer" -> Right MixerS
"output" -> Right OutputS
"options" -> Right OptionsS
"partition" -> Right PartitionS
"sticker" -> Right StickerS
"subscription" -> Right SubscriptionS
"message" -> Right MessageS
"neighbor" -> Right NeighborS
"mount" -> Right MountS
k -> Left ("Unknown subsystem: " ++ UTF8.toString k)
f x = Left ("idle: Unexpected " ++ show x)
| Wait until there is noteworthy change in one or more of MPD 's
idle :: [Subsystem] -> Command [Subsystem]
idle ss = Command (liftParser takeSubsystems) c
where
c = ["idle" <@> foldr (<++>) (Args []) ss]
noidle :: Command ()
noidle = Command emptyResponse ["noidle"]
stats :: Command Stats
stats = Command (liftParser parseStats) ["stats"]
status :: Command Status
status = Command (liftParser parseStatus) ["status"]
where
parseStatus :: [ByteString] -> Either String Status
parseStatus = foldM go def . toAssocList
where
go a p@(k, v) = case k of
"volume" -> vol $ \x -> a { stVolume = x }
"repeat" -> bool $ \x -> a { stRepeat = x }
"random" -> bool $ \x -> a { stRandom = x }
"single" -> single $ \x -> a { stSingle = x }
"consume" -> bool $ \x -> a { stConsume = x }
"playlist" -> num $ \x -> a { stPlaylistVersion = x }
"playlistlength" -> num $ \x -> a { stPlaylistLength = x }
"state" -> state $ \x -> a { stState = x }
"song" -> int $ \x -> a { stSongPos = Just x }
"songid" -> int $ \x -> a { stSongID = Just $ Id x }
"nextsong" -> int $ \x -> a { stNextSongPos = Just x }
"nextsongid" -> int $ \x -> a { stNextSongID = Just $ Id x }
"time" -> time $ \x -> a { stTime = Just x }
"elapsed" -> frac $ \x -> a { stTime = fmap ((x,) . snd) (stTime a) }
"duration" -> frac $ \x -> a { stTime = fmap ((,x) . fst) (stTime a) }
"bitrate" -> int $ \x -> a { stBitrate = Just x }
"xfade" -> num $ \x -> a { stXFadeWidth = x }
"mixrampdb" -> frac $ \x -> a { stMixRampdB = x }
"mixrampdelay" -> frac $ \x -> a { stMixRampDelay = x }
"audio" -> audio $ \x -> a { stAudio = x }
"updating_db" -> num $ \x -> a { stUpdatingDb = Just x }
"error" -> Right a { stError = Just (UTF8.toString v) }
"partition" -> Right a { stPartition = UTF8.toString v }
_ -> Right a
where
unexpectedPair = Left ("unexpected key-value pair: " ++ show p)
int f = maybe unexpectedPair (Right . f) (parseNum v :: Maybe Int)
num f = maybe unexpectedPair (Right . f) (parseNum v)
bool f = maybe unexpectedPair (Right . f) (parseBool v)
frac f = maybe unexpectedPair (Right . f) (parseFrac v)
single f = maybe unexpectedPair (Right . f) (parseSingle v)
This is sometimes " audio : 0:?:0 " , so we ignore any parse
audio f = Right $ maybe a f (parseTriple ':' parseNum v)
time f = case parseFrac *** parseFrac $ breakChar ':' v of
(Just a_, Just b) -> (Right . f) (a_, b)
_ -> unexpectedPair
state f = case v of
"play" -> (Right . f) Playing
"pause" -> (Right . f) Paused
"stop" -> (Right . f) Stopped
_ -> unexpectedPair
vol f = case (parseNum v :: Maybe Int) of
Just v' -> (Right . f) (g v')
where g n | n < 0 = Nothing
| otherwise = Just $ fromIntegral n
|
2c00275a80dba50cc710990e534aeeaed04c341039389dfb968136f46b78f7c2 | ChicagoBoss/ChicagoBoss | boss_compiler_adapter_lfe.erl | %%-------------------------------------------------------------------
@author
ChicagoBoss Team and contributors , see file in root directory
%% @end
This file is part of ChicagoBoss project .
See file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_compiler_adapter_lfe).
-compile(export_all).
file_extensions() -> ["lfe"].
controller_module(AppName, Controller) -> lists:concat([AppName, "_", Controller, "_controller"]).
module_name_for_file(_AppName, File) -> filename:basename(File, ".lfe").
compile_controller(File, Options) ->
do_compile(File, Options).
compile(File, Options) ->
do_compile(File, Options).
do_compile(File, Options) ->
CompilerOptions = lfe_compiler_options(Options),
case lfe_comp:file(File, CompilerOptions) of
{ok, Module, Binary, _Warnings} ->
{module, Module} = code:load_binary(Module, File, Binary),
ok = case proplists:get_value(out_dir, Options) of
undefined -> ok;
OutDir ->
OutFile = filename:join([OutDir, filename:basename(File, ".lfe") ++ ".beam"]),
file:write_file(OutFile, Binary)
end,
{ok, Module};
Other ->
Other
end.
lfe_compiler_options(Options) ->
[verbose, return, binary] ++ proplists:get_value(compiler_options, Options, []).
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/src/boss/compiler_adapters/boss_compiler_adapter_lfe.erl | erlang | -------------------------------------------------------------------
@end
for license information, see LICENSE file in root directory
@end
@doc
------------------------------------------------------------------- | @author
ChicagoBoss Team and contributors , see file in root directory
This file is part of ChicagoBoss project .
See file in root directory
-module(boss_compiler_adapter_lfe).
-compile(export_all).
file_extensions() -> ["lfe"].
controller_module(AppName, Controller) -> lists:concat([AppName, "_", Controller, "_controller"]).
module_name_for_file(_AppName, File) -> filename:basename(File, ".lfe").
compile_controller(File, Options) ->
do_compile(File, Options).
compile(File, Options) ->
do_compile(File, Options).
do_compile(File, Options) ->
CompilerOptions = lfe_compiler_options(Options),
case lfe_comp:file(File, CompilerOptions) of
{ok, Module, Binary, _Warnings} ->
{module, Module} = code:load_binary(Module, File, Binary),
ok = case proplists:get_value(out_dir, Options) of
undefined -> ok;
OutDir ->
OutFile = filename:join([OutDir, filename:basename(File, ".lfe") ++ ".beam"]),
file:write_file(OutFile, Binary)
end,
{ok, Module};
Other ->
Other
end.
lfe_compiler_options(Options) ->
[verbose, return, binary] ++ proplists:get_value(compiler_options, Options, []).
|
8279f29e4753df5fedcf644a088d4cbc0ace273b1fb325f286d577e686adf24f | ocaml-community/obus | oBus_property.ml |
* oBus_property.ml
* ----------------
* Copyright : ( c ) 2010 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* oBus_property.ml
* ----------------
* Copyright : (c) 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
let section = Lwt_log.Section.make "obus(property)"
open Lwt.Infix
open Lwt_react
open OBus_interfaces.Org_freedesktop_DBus_Properties
(* +-----------------------------------------------------------------+
| Types |
+-----------------------------------------------------------------+ *)
module String_map = Map.Make(String)
type map = (OBus_context.t * OBus_value.V.single) String_map.t
type monitor = OBus_proxy.t -> OBus_name.interface -> Lwt_switch.t -> map signal Lwt.t
type ('a, 'access) t = {
p_interface : OBus_name.interface;
(* The interface of the property. *)
p_member : OBus_name.member;
(* The name of the property. *)
p_proxy : OBus_proxy.t;
(* The object owning the property. *)
p_monitor : monitor;
(* Monitor for this property. *)
p_cast : OBus_context.t -> OBus_value.V.single -> 'a;
p_make : 'a -> OBus_value.V.single;
}
type 'a r = ('a, [ `readable ]) t
type 'a w = ('a, [ `writable ]) t
type 'a rw = ('a, [ `readable | `writable ]) t
type group = {
g_interface : OBus_name.interface;
(* The interface of the group *)
g_proxy : OBus_proxy.t;
(* The object owning the group of properties *)
g_monitor : monitor;
(* Monitor for this group. *)
}
module Group_map = Map.Make
(struct
type t = OBus_name.bus * OBus_path.t * OBus_name.interface
Groups are indexed by :
- name of the owner of the property
- path of the object owning the property
- interfaec of the property
- name of the owner of the property
- path of the object owning the property
- interfaec of the property *)
let compare = Stdlib.compare
end)
(* Type of a cache for a group *)
type cache = {
mutable c_count : int;
(* Numbers of monitored properties using this group. *)
c_map : map signal;
(* The signal holding the current state of properties. *)
c_switch : Lwt_switch.t;
Switch for the signal used to monitor the group .
}
type info = {
mutable cache : cache Lwt.t Group_map.t;
(* Cache of all monitored properties. *)
}
(* +-----------------------------------------------------------------+
| Default monitor |
+-----------------------------------------------------------------+ *)
let update_map context dict map =
List.fold_left (fun map (name, value) -> String_map.add name (context, value) map) map dict
let map_of_list context dict =
update_map context dict String_map.empty
let get_all_no_cache proxy interface =
OBus_method.call_with_context m_GetAll proxy interface
let default_monitor proxy interface switch =
let%lwt event =
OBus_signal.connect ~switch
(OBus_signal.with_filters
(OBus_match.make_arguments [(0, OBus_match.AF_string interface)])
(OBus_signal.with_context
(OBus_signal.make s_PropertiesChanged proxy)))
and context, dict = get_all_no_cache proxy interface in
Lwt.return (S.map snd
(S.fold_s ~eq:(fun (_, a) (_, b) -> String_map.equal (=) a b)
(fun (_, map) (sig_context, (interface, updates, invalidates)) ->
if invalidates = [] then
Lwt.return (sig_context, update_map sig_context updates map)
else
let%lwt context, dict = get_all_no_cache proxy interface in
Lwt.return (sig_context, map_of_list context dict))
(context, map_of_list context dict)
event))
(* +-----------------------------------------------------------------+
| Property creation |
+-----------------------------------------------------------------+ *)
let make ?(monitor=default_monitor) desc proxy = {
p_interface = OBus_member.Property.interface desc;
p_member = OBus_member.Property.member desc;
p_proxy = proxy;
p_monitor = monitor;
p_cast = (fun context value -> OBus_value.C.cast_single (OBus_member.Property.typ desc) value);
p_make = (OBus_value.C.make_single (OBus_member.Property.typ desc));
}
let group ?(monitor=default_monitor) proxy interface = {
g_proxy = proxy;
g_interface = interface;
g_monitor = monitor;
}
(* +-----------------------------------------------------------------+
| Transformations |
+-----------------------------------------------------------------+ *)
let map_rw f g property = {
property with
p_cast = (fun context x -> f (property.p_cast context x));
p_make = (fun x -> property.p_make (g x));
}
let map_rw_with_context f g property = {
property with
p_cast = (fun context x -> f context (property.p_cast context x));
p_make = (fun x -> property.p_make (g x));
}
let map_r f property = {
property with
p_cast = (fun context x -> f (property.p_cast context x));
p_make = (fun x -> assert false);
}
let map_r_with_context f property = {
property with
p_cast = (fun context x -> f context (property.p_cast context x));
p_make = (fun x -> assert false);
}
let map_w g property = {
property with
p_cast = (fun context x -> assert false);
p_make = (fun x -> property.p_make (g x));
}
(* +-----------------------------------------------------------------+
| Operations on maps |
+-----------------------------------------------------------------+ *)
let find property map =
let context, value = String_map.find property.p_member map in
property.p_cast context value
let find_with_context property map =
let context, value = String_map.find property.p_member map in
(context, property.p_cast context value)
let find_value name map =
let context, value = String_map.find name map in
value
let find_value_with_context name map =
String_map.find name map
let print_map pp map =
let open Format in
pp_open_box pp 2;
pp_print_string pp "{";
pp_print_cut pp ();
pp_open_hvbox pp 0;
String_map.iter
(fun name (context, value) ->
pp_open_box pp 0;
pp_print_string pp name;
pp_print_space pp ();
pp_print_string pp "=";
pp_print_space pp ();
OBus_value.V.print_single pp value;
pp_print_string pp ";";
pp_close_box pp ();
pp_print_cut pp ())
map;
pp_close_box pp ();
pp_print_cut pp ();
pp_print_string pp "}";
pp_close_box pp ()
let string_of_map map =
let open Format in
let buf = Buffer.create 42 in
let pp = formatter_of_buffer buf in
pp_set_margin pp max_int;
print_map pp map;
pp_print_flush pp ();
Buffer.contents buf
(* +-----------------------------------------------------------------+
| Properties reading/writing |
+-----------------------------------------------------------------+ *)
let key = OBus_connection.new_key ()
let get_with_context prop =
match OBus_connection.get (OBus_proxy.connection prop.p_proxy) key with
| Some info -> begin
match
try
Some(Group_map.find (OBus_proxy.name prop.p_proxy,
OBus_proxy.path prop.p_proxy,
prop.p_interface) info.cache)
with Not_found ->
None
with
| Some cache_thread ->
let%lwt cache = cache_thread in
Lwt.return (find_with_context prop (S.value cache.c_map))
| None ->
let%lwt context, value = OBus_method.call_with_context m_Get prop.p_proxy (prop.p_interface, prop.p_member) in
Lwt.return (context, prop.p_cast context value)
end
| None ->
let%lwt context, value = OBus_method.call_with_context m_Get prop.p_proxy (prop.p_interface, prop.p_member) in
Lwt.return (context, prop.p_cast context value)
let get prop =
get_with_context prop >|= snd
let set prop value =
OBus_method.call m_Set prop.p_proxy (prop.p_interface, prop.p_member, prop.p_make value)
let get_group group =
match OBus_connection.get (OBus_proxy.connection group.g_proxy) key with
| Some info -> begin
match
try
Some(Group_map.find (OBus_proxy.name group.g_proxy,
OBus_proxy.path group.g_proxy,
group.g_interface) info.cache)
with Not_found ->
None
with
| Some cache_thread ->
let%lwt cache = cache_thread in
Lwt.return (S.value cache.c_map)
| None ->
let%lwt context, dict = get_all_no_cache group.g_proxy group.g_interface in
Lwt.return (map_of_list context dict)
end
| None ->
let%lwt context, dict = get_all_no_cache group.g_proxy group.g_interface in
Lwt.return (map_of_list context dict)
(* +-----------------------------------------------------------------+
| Monitoring |
+-----------------------------------------------------------------+ *)
let finalise disable _ =
ignore (Lazy.force disable)
let monitor_group ?switch group =
Lwt_switch.check switch;
let cache_key = (OBus_proxy.name group.g_proxy, OBus_proxy.path group.g_proxy, group.g_interface) in
let info =
match OBus_connection.get (OBus_proxy.connection group.g_proxy) key with
| Some info ->
info
| None ->
let info = { cache = Group_map.empty } in
OBus_connection.set (OBus_proxy.connection group.g_proxy) key (Some info);
info
in
let%lwt cache =
match
try
Some(Group_map.find cache_key info.cache)
with Not_found ->
None
with
| Some cache_thread ->
cache_thread
| None ->
let waiter, wakener = Lwt.wait () in
info.cache <- Group_map.add cache_key waiter info.cache;
let switch = Lwt_switch.create () in
try%lwt
let%lwt signal = group.g_monitor group.g_proxy group.g_interface switch in
let cache = {
c_count = 0;
c_map = signal;
c_switch = switch;
} in
Lwt.wakeup wakener cache;
Lwt.return cache
with exn ->
info.cache <- Group_map.remove cache_key info.cache;
Lwt.wakeup_exn wakener exn;
let%lwt () = Lwt_switch.turn_off switch in
Lwt.fail exn
in
cache.c_count <- cache.c_count + 1;
let disable = lazy(
try%lwt
cache.c_count <- cache.c_count - 1;
if cache.c_count = 0 then begin
info.cache <- Group_map.remove cache_key info.cache;
Lwt_switch.turn_off cache.c_switch
end else
Lwt.return ()
with exn ->
let%lwt () =
Lwt_log.warning_f
~section
~exn
"failed to disable monitoring of properties for interface %S on object %S from %S"
group.g_interface
(OBus_path.to_string (OBus_proxy.path group.g_proxy))
(OBus_proxy.name group.g_proxy)
in
Lwt.fail exn
) in
let signal = S.with_finaliser (finalise disable) cache.c_map in
let%lwt () =
Lwt_switch.add_hook_or_exec
switch
(fun () ->
S.stop signal;
Lazy.force disable)
in
Lwt.return signal
let monitor ?switch prop =
let%lwt signal = monitor_group ?switch { g_interface = prop.p_interface;
g_proxy = prop.p_proxy;
g_monitor = prop.p_monitor } in
Lwt.return (S.map (find prop) signal)
| null | https://raw.githubusercontent.com/ocaml-community/obus/03129dac072e7a7370c2c92b9d447e47f784b7c7/src/protocol/oBus_property.ml | ocaml | +-----------------------------------------------------------------+
| Types |
+-----------------------------------------------------------------+
The interface of the property.
The name of the property.
The object owning the property.
Monitor for this property.
The interface of the group
The object owning the group of properties
Monitor for this group.
Type of a cache for a group
Numbers of monitored properties using this group.
The signal holding the current state of properties.
Cache of all monitored properties.
+-----------------------------------------------------------------+
| Default monitor |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Property creation |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Transformations |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Operations on maps |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Properties reading/writing |
+-----------------------------------------------------------------+
+-----------------------------------------------------------------+
| Monitoring |
+-----------------------------------------------------------------+ |
* oBus_property.ml
* ----------------
* Copyright : ( c ) 2010 , < >
* Licence : BSD3
*
* This file is a part of obus , an ocaml implementation of D - Bus .
* oBus_property.ml
* ----------------
* Copyright : (c) 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of obus, an ocaml implementation of D-Bus.
*)
let section = Lwt_log.Section.make "obus(property)"
open Lwt.Infix
open Lwt_react
open OBus_interfaces.Org_freedesktop_DBus_Properties
module String_map = Map.Make(String)
type map = (OBus_context.t * OBus_value.V.single) String_map.t
type monitor = OBus_proxy.t -> OBus_name.interface -> Lwt_switch.t -> map signal Lwt.t
type ('a, 'access) t = {
p_interface : OBus_name.interface;
p_member : OBus_name.member;
p_proxy : OBus_proxy.t;
p_monitor : monitor;
p_cast : OBus_context.t -> OBus_value.V.single -> 'a;
p_make : 'a -> OBus_value.V.single;
}
type 'a r = ('a, [ `readable ]) t
type 'a w = ('a, [ `writable ]) t
type 'a rw = ('a, [ `readable | `writable ]) t
type group = {
g_interface : OBus_name.interface;
g_proxy : OBus_proxy.t;
g_monitor : monitor;
}
module Group_map = Map.Make
(struct
type t = OBus_name.bus * OBus_path.t * OBus_name.interface
Groups are indexed by :
- name of the owner of the property
- path of the object owning the property
- interfaec of the property
- name of the owner of the property
- path of the object owning the property
- interfaec of the property *)
let compare = Stdlib.compare
end)
type cache = {
mutable c_count : int;
c_map : map signal;
c_switch : Lwt_switch.t;
Switch for the signal used to monitor the group .
}
type info = {
mutable cache : cache Lwt.t Group_map.t;
}
let update_map context dict map =
List.fold_left (fun map (name, value) -> String_map.add name (context, value) map) map dict
let map_of_list context dict =
update_map context dict String_map.empty
let get_all_no_cache proxy interface =
OBus_method.call_with_context m_GetAll proxy interface
let default_monitor proxy interface switch =
let%lwt event =
OBus_signal.connect ~switch
(OBus_signal.with_filters
(OBus_match.make_arguments [(0, OBus_match.AF_string interface)])
(OBus_signal.with_context
(OBus_signal.make s_PropertiesChanged proxy)))
and context, dict = get_all_no_cache proxy interface in
Lwt.return (S.map snd
(S.fold_s ~eq:(fun (_, a) (_, b) -> String_map.equal (=) a b)
(fun (_, map) (sig_context, (interface, updates, invalidates)) ->
if invalidates = [] then
Lwt.return (sig_context, update_map sig_context updates map)
else
let%lwt context, dict = get_all_no_cache proxy interface in
Lwt.return (sig_context, map_of_list context dict))
(context, map_of_list context dict)
event))
let make ?(monitor=default_monitor) desc proxy = {
p_interface = OBus_member.Property.interface desc;
p_member = OBus_member.Property.member desc;
p_proxy = proxy;
p_monitor = monitor;
p_cast = (fun context value -> OBus_value.C.cast_single (OBus_member.Property.typ desc) value);
p_make = (OBus_value.C.make_single (OBus_member.Property.typ desc));
}
let group ?(monitor=default_monitor) proxy interface = {
g_proxy = proxy;
g_interface = interface;
g_monitor = monitor;
}
let map_rw f g property = {
property with
p_cast = (fun context x -> f (property.p_cast context x));
p_make = (fun x -> property.p_make (g x));
}
let map_rw_with_context f g property = {
property with
p_cast = (fun context x -> f context (property.p_cast context x));
p_make = (fun x -> property.p_make (g x));
}
let map_r f property = {
property with
p_cast = (fun context x -> f (property.p_cast context x));
p_make = (fun x -> assert false);
}
let map_r_with_context f property = {
property with
p_cast = (fun context x -> f context (property.p_cast context x));
p_make = (fun x -> assert false);
}
let map_w g property = {
property with
p_cast = (fun context x -> assert false);
p_make = (fun x -> property.p_make (g x));
}
let find property map =
let context, value = String_map.find property.p_member map in
property.p_cast context value
let find_with_context property map =
let context, value = String_map.find property.p_member map in
(context, property.p_cast context value)
let find_value name map =
let context, value = String_map.find name map in
value
let find_value_with_context name map =
String_map.find name map
let print_map pp map =
let open Format in
pp_open_box pp 2;
pp_print_string pp "{";
pp_print_cut pp ();
pp_open_hvbox pp 0;
String_map.iter
(fun name (context, value) ->
pp_open_box pp 0;
pp_print_string pp name;
pp_print_space pp ();
pp_print_string pp "=";
pp_print_space pp ();
OBus_value.V.print_single pp value;
pp_print_string pp ";";
pp_close_box pp ();
pp_print_cut pp ())
map;
pp_close_box pp ();
pp_print_cut pp ();
pp_print_string pp "}";
pp_close_box pp ()
let string_of_map map =
let open Format in
let buf = Buffer.create 42 in
let pp = formatter_of_buffer buf in
pp_set_margin pp max_int;
print_map pp map;
pp_print_flush pp ();
Buffer.contents buf
let key = OBus_connection.new_key ()
let get_with_context prop =
match OBus_connection.get (OBus_proxy.connection prop.p_proxy) key with
| Some info -> begin
match
try
Some(Group_map.find (OBus_proxy.name prop.p_proxy,
OBus_proxy.path prop.p_proxy,
prop.p_interface) info.cache)
with Not_found ->
None
with
| Some cache_thread ->
let%lwt cache = cache_thread in
Lwt.return (find_with_context prop (S.value cache.c_map))
| None ->
let%lwt context, value = OBus_method.call_with_context m_Get prop.p_proxy (prop.p_interface, prop.p_member) in
Lwt.return (context, prop.p_cast context value)
end
| None ->
let%lwt context, value = OBus_method.call_with_context m_Get prop.p_proxy (prop.p_interface, prop.p_member) in
Lwt.return (context, prop.p_cast context value)
let get prop =
get_with_context prop >|= snd
let set prop value =
OBus_method.call m_Set prop.p_proxy (prop.p_interface, prop.p_member, prop.p_make value)
let get_group group =
match OBus_connection.get (OBus_proxy.connection group.g_proxy) key with
| Some info -> begin
match
try
Some(Group_map.find (OBus_proxy.name group.g_proxy,
OBus_proxy.path group.g_proxy,
group.g_interface) info.cache)
with Not_found ->
None
with
| Some cache_thread ->
let%lwt cache = cache_thread in
Lwt.return (S.value cache.c_map)
| None ->
let%lwt context, dict = get_all_no_cache group.g_proxy group.g_interface in
Lwt.return (map_of_list context dict)
end
| None ->
let%lwt context, dict = get_all_no_cache group.g_proxy group.g_interface in
Lwt.return (map_of_list context dict)
let finalise disable _ =
ignore (Lazy.force disable)
let monitor_group ?switch group =
Lwt_switch.check switch;
let cache_key = (OBus_proxy.name group.g_proxy, OBus_proxy.path group.g_proxy, group.g_interface) in
let info =
match OBus_connection.get (OBus_proxy.connection group.g_proxy) key with
| Some info ->
info
| None ->
let info = { cache = Group_map.empty } in
OBus_connection.set (OBus_proxy.connection group.g_proxy) key (Some info);
info
in
let%lwt cache =
match
try
Some(Group_map.find cache_key info.cache)
with Not_found ->
None
with
| Some cache_thread ->
cache_thread
| None ->
let waiter, wakener = Lwt.wait () in
info.cache <- Group_map.add cache_key waiter info.cache;
let switch = Lwt_switch.create () in
try%lwt
let%lwt signal = group.g_monitor group.g_proxy group.g_interface switch in
let cache = {
c_count = 0;
c_map = signal;
c_switch = switch;
} in
Lwt.wakeup wakener cache;
Lwt.return cache
with exn ->
info.cache <- Group_map.remove cache_key info.cache;
Lwt.wakeup_exn wakener exn;
let%lwt () = Lwt_switch.turn_off switch in
Lwt.fail exn
in
cache.c_count <- cache.c_count + 1;
let disable = lazy(
try%lwt
cache.c_count <- cache.c_count - 1;
if cache.c_count = 0 then begin
info.cache <- Group_map.remove cache_key info.cache;
Lwt_switch.turn_off cache.c_switch
end else
Lwt.return ()
with exn ->
let%lwt () =
Lwt_log.warning_f
~section
~exn
"failed to disable monitoring of properties for interface %S on object %S from %S"
group.g_interface
(OBus_path.to_string (OBus_proxy.path group.g_proxy))
(OBus_proxy.name group.g_proxy)
in
Lwt.fail exn
) in
let signal = S.with_finaliser (finalise disable) cache.c_map in
let%lwt () =
Lwt_switch.add_hook_or_exec
switch
(fun () ->
S.stop signal;
Lazy.force disable)
in
Lwt.return signal
let monitor ?switch prop =
let%lwt signal = monitor_group ?switch { g_interface = prop.p_interface;
g_proxy = prop.p_proxy;
g_monitor = prop.p_monitor } in
Lwt.return (S.map (find prop) signal)
|
04665f350fc486cbf6478c742fa5130a0520fcb05095e5ef5821b8f280a51bdf | vseloved/prj-algo3 | lab01_improve.lisp | ;;;;
lab 01 for Advanced Algo course
second iteration -- more efficient algo
made by
;;;;
(defconstant +dfile+ "lab01_dict")
(defconstant +maxwordlen+ 24)
;;; key -> word, value -> freq
(defparameter *ngram* (make-hash-table :size 1000000 :test 'equal))
;;; key -> word word, value -> freq
(defparameter *ngram2* (make-hash-table :size 1000000 :test 'equal))
our broken text without whitespaces ( getting from STDIN )
(defparameter *text* nil)
;;; tree path
(defparameter *tree* (make-hash-table))
;;; Debug snippets
(defun pr (a) (format t "~a~%" a))
(defun pr2 (a b) (format t "~a~a~%" a b))
(defun prt (a) (format t "type is ~a, value is ~a~%" (type-of a) a))
check if first char A or a
(defun is-char-valid (word)
(cond ((char-equal (char word 0) #\a) t)
((char-equal (char word 0) #\A) t)
((char-equal (char word 0) #\I) t)))
;;; add parsed ngram to hashtable
(defun add-ngram (word freq ht del)
(when del
(setf freq (floor freq 100000)))
(cond ((> (length word) 1) (setf (gethash word ht) freq))
((and (= (length word) 1) (is-char-valid word)) (setf (gethash word ht) freq))))
;;; parse ngram, format: word[tab]frequency
(defun parse-ngram (line ht del)
(dotimes (i (length line))
(when (char-equal (char line i) #\Tab)
(add-ngram (subseq line 0 i)(parse-integer (subseq line i (length line))) ht del))))
read file with
(defun fill-ngram(fname ht del)
(let ((in (open fname :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do (parse-ngram line ht del)))
(close in))
(pr " read -> parse finish"))
;;;
;;; Hashtable helpers
;;;
(defun print-dict-kvp (key value)
(format t "~a -> ~a~%" key value))
(defun print-ht-debug(ht)
(with-hash-table-iterator (i ht)
(loop (multiple-value-bind (entry-p key value) (i)
(if entry-p
(print-dict-kvp key value)
(return))))))
read text from stdin
;;; assume than in input "ourtextwithoutspaces" and double quotes surrounding
(defun read-text ()
(setf *text* (read)))
(defun parse-text()
(get-words *tree* *text* 0 nil 1 0 0)
(get-all-path *tree* 0 0 (make-array 32767))
(print-fixed-text 0 0 *text* *path* *depth*))
(defun freqp (seq)
(let ((freq (gethash (string-downcase seq) *ngram*)))
(if (not freq) 0 freq)))
(defun concat2 (seq prevSeq)
(concatenate 'string prevSeq " " seq))
(defun freqp2 (seq prevSeq)
(let ((freq (gethash (concat2 seq prevSeq) *ngram2*)))
(if (not freq) 1 freq)))
(defun wordp (seq prevSeq)
(if (> (freqp seq) 0) t nil))
(defun valid-len (txt i)
(if (< i (length txt)) t nil))
(defun max-bounds (st txt)
(min (length txt) (+ st +maxwordlen+)))
(defun get-words (ht txt start prevSeq memcost wordcost depth)
(let ((st (+ start 1)))
(when (valid-len txt start)
(let ((end (max-bounds st txt)))
(loop for i from st to end
do (collect-word ht prevSeq (subseq txt start i) i txt memcost wordcost depth))))))
(defun collect-word (ht prevSeq seq index txt memcost wordcost depth)
(let ((cost (freqp2 seq prevSeq)))
(when (wordp seq prevSeq)
(setf wordcost (+ wordcost (freqp seq)))
(setf memcost (+ memcost cost))
(when (and ( > depth 12) (< memcost 10000))
( format t " bad path d = ~a mem = ~a~% " depth )
(return-from collect-word))
(when (and (= cost 1) (> memcost 10000))
(setf memcost (floor memcost 10)))
( format t " ~a ~a - > cost : : ~a wordcost : ~a ~% " prevSeq seq cost memcost wordcost )
(setf (gethash index ht) (cons (+ memcost wordcost) (make-hash-table)))
(get-words (cdr (gethash index ht)) txt index seq memcost wordcost (+ depth 1))))
)
(defun get-prev-cost (arr n)
(if (> n 0) (cdr (aref arr (- n 1))) 0))
;;; print fixed text
;;; array - (cons index . cost)
(defun print-fixed-text (pos spacepos text arr n)
(when (< pos (length text))
(when (eql pos (car (aref arr spacepos)))
(format t " ")
(when (< spacepos n)
(setf spacepos (+ 1 spacepos))))
(format t "~a" (char text pos))
(print-fixed-text (+ pos 1) spacepos text arr n)))
;;; TODO: refactoring
(defparameter *path* (make-array 32767))
(defparameter *bestcost* 0)
(defparameter *depth* 0)
(defun check-path (arr d)
(let ((cost (get-prev-cost arr d)))
(when (> cost *bestcost*)
(setf *bestcost* cost)
(setf *depth* d)
(copy-path arr d))))
(defun copy-path (arr d)
(dotimes (i d)
(setf (aref *path* i) (aref arr i))))
;;; array - (cons index . cost)
(defun get-all-path(ht key d arr)
(if (> (hash-table-count ht) 0)
(with-hash-table-iterator (iter ht)
(loop (multiple-value-bind (entry-p key value) (iter)
(if entry-p
(progn (setf (aref arr d) (cons key (car (gethash key ht)))) (get-all-path (cdr (gethash key ht)) key (+ d 1) arr))
(return)))))
(check-path arr d)))
;;;
;;; Asserts
;;;
(defun assert-ngram()
(pr2 "hash b = " (gethash "b" *ngram*))
(pr2 "hash A = " (gethash "b" *ngram*))
(pr2 "hash Hello = " (gethash (string-downcase "Hello") *ngram*))
(pr2 "hash hello = " (gethash "hello" *ngram*))
(pr2 "hash a = " (gethash "a" *ngram*)))
(defun assert-cost()
(pr2 "cost hello world = " (freqp2 "world" "hello"))
(pr2 "cost low or = " (freqp2 "or" "low"))
(pr2 "cost with a = " (freqp2 "a" "with"))
(pr2 "cost super inefficient = " (freqp2 "inefficient" "super"))
(pr2 "cost 2nd century = " (freqp2 "century" "2nd")))
(defun all-asserts()
(assert-ngram)
(assert-cost))
;;;
;;; main
;;;
(defun my-main()
(fill-ngram "count_1w.txt" *ngram* t)
(fill-ngram "count_2w.txt" *ngram2* nil)
;; (all-asserts)
(read-text)
(parse-text))
(my-main)
| null | https://raw.githubusercontent.com/vseloved/prj-algo3/ed485ca730e42cd1bba757fd3f409b51ddb43c03/tasks/a.kishchenko/lab01/lab01_improve.lisp | lisp |
key -> word, value -> freq
key -> word word, value -> freq
tree path
Debug snippets
add parsed ngram to hashtable
parse ngram, format: word[tab]frequency
Hashtable helpers
assume than in input "ourtextwithoutspaces" and double quotes surrounding
print fixed text
array - (cons index . cost)
TODO: refactoring
array - (cons index . cost)
Asserts
main
(all-asserts) | lab 01 for Advanced Algo course
second iteration -- more efficient algo
made by
(defconstant +dfile+ "lab01_dict")
(defconstant +maxwordlen+ 24)
(defparameter *ngram* (make-hash-table :size 1000000 :test 'equal))
(defparameter *ngram2* (make-hash-table :size 1000000 :test 'equal))
our broken text without whitespaces ( getting from STDIN )
(defparameter *text* nil)
(defparameter *tree* (make-hash-table))
(defun pr (a) (format t "~a~%" a))
(defun pr2 (a b) (format t "~a~a~%" a b))
(defun prt (a) (format t "type is ~a, value is ~a~%" (type-of a) a))
check if first char A or a
(defun is-char-valid (word)
(cond ((char-equal (char word 0) #\a) t)
((char-equal (char word 0) #\A) t)
((char-equal (char word 0) #\I) t)))
(defun add-ngram (word freq ht del)
(when del
(setf freq (floor freq 100000)))
(cond ((> (length word) 1) (setf (gethash word ht) freq))
((and (= (length word) 1) (is-char-valid word)) (setf (gethash word ht) freq))))
(defun parse-ngram (line ht del)
(dotimes (i (length line))
(when (char-equal (char line i) #\Tab)
(add-ngram (subseq line 0 i)(parse-integer (subseq line i (length line))) ht del))))
read file with
(defun fill-ngram(fname ht del)
(let ((in (open fname :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do (parse-ngram line ht del)))
(close in))
(pr " read -> parse finish"))
(defun print-dict-kvp (key value)
(format t "~a -> ~a~%" key value))
(defun print-ht-debug(ht)
(with-hash-table-iterator (i ht)
(loop (multiple-value-bind (entry-p key value) (i)
(if entry-p
(print-dict-kvp key value)
(return))))))
read text from stdin
(defun read-text ()
(setf *text* (read)))
(defun parse-text()
(get-words *tree* *text* 0 nil 1 0 0)
(get-all-path *tree* 0 0 (make-array 32767))
(print-fixed-text 0 0 *text* *path* *depth*))
(defun freqp (seq)
(let ((freq (gethash (string-downcase seq) *ngram*)))
(if (not freq) 0 freq)))
(defun concat2 (seq prevSeq)
(concatenate 'string prevSeq " " seq))
(defun freqp2 (seq prevSeq)
(let ((freq (gethash (concat2 seq prevSeq) *ngram2*)))
(if (not freq) 1 freq)))
(defun wordp (seq prevSeq)
(if (> (freqp seq) 0) t nil))
(defun valid-len (txt i)
(if (< i (length txt)) t nil))
(defun max-bounds (st txt)
(min (length txt) (+ st +maxwordlen+)))
(defun get-words (ht txt start prevSeq memcost wordcost depth)
(let ((st (+ start 1)))
(when (valid-len txt start)
(let ((end (max-bounds st txt)))
(loop for i from st to end
do (collect-word ht prevSeq (subseq txt start i) i txt memcost wordcost depth))))))
(defun collect-word (ht prevSeq seq index txt memcost wordcost depth)
(let ((cost (freqp2 seq prevSeq)))
(when (wordp seq prevSeq)
(setf wordcost (+ wordcost (freqp seq)))
(setf memcost (+ memcost cost))
(when (and ( > depth 12) (< memcost 10000))
( format t " bad path d = ~a mem = ~a~% " depth )
(return-from collect-word))
(when (and (= cost 1) (> memcost 10000))
(setf memcost (floor memcost 10)))
( format t " ~a ~a - > cost : : ~a wordcost : ~a ~% " prevSeq seq cost memcost wordcost )
(setf (gethash index ht) (cons (+ memcost wordcost) (make-hash-table)))
(get-words (cdr (gethash index ht)) txt index seq memcost wordcost (+ depth 1))))
)
(defun get-prev-cost (arr n)
(if (> n 0) (cdr (aref arr (- n 1))) 0))
(defun print-fixed-text (pos spacepos text arr n)
(when (< pos (length text))
(when (eql pos (car (aref arr spacepos)))
(format t " ")
(when (< spacepos n)
(setf spacepos (+ 1 spacepos))))
(format t "~a" (char text pos))
(print-fixed-text (+ pos 1) spacepos text arr n)))
(defparameter *path* (make-array 32767))
(defparameter *bestcost* 0)
(defparameter *depth* 0)
(defun check-path (arr d)
(let ((cost (get-prev-cost arr d)))
(when (> cost *bestcost*)
(setf *bestcost* cost)
(setf *depth* d)
(copy-path arr d))))
(defun copy-path (arr d)
(dotimes (i d)
(setf (aref *path* i) (aref arr i))))
(defun get-all-path(ht key d arr)
(if (> (hash-table-count ht) 0)
(with-hash-table-iterator (iter ht)
(loop (multiple-value-bind (entry-p key value) (iter)
(if entry-p
(progn (setf (aref arr d) (cons key (car (gethash key ht)))) (get-all-path (cdr (gethash key ht)) key (+ d 1) arr))
(return)))))
(check-path arr d)))
(defun assert-ngram()
(pr2 "hash b = " (gethash "b" *ngram*))
(pr2 "hash A = " (gethash "b" *ngram*))
(pr2 "hash Hello = " (gethash (string-downcase "Hello") *ngram*))
(pr2 "hash hello = " (gethash "hello" *ngram*))
(pr2 "hash a = " (gethash "a" *ngram*)))
(defun assert-cost()
(pr2 "cost hello world = " (freqp2 "world" "hello"))
(pr2 "cost low or = " (freqp2 "or" "low"))
(pr2 "cost with a = " (freqp2 "a" "with"))
(pr2 "cost super inefficient = " (freqp2 "inefficient" "super"))
(pr2 "cost 2nd century = " (freqp2 "century" "2nd")))
(defun all-asserts()
(assert-ngram)
(assert-cost))
(defun my-main()
(fill-ngram "count_1w.txt" *ngram* t)
(fill-ngram "count_2w.txt" *ngram2* nil)
(read-text)
(parse-text))
(my-main)
|
1120190dc64fba8b0e292ef815afaa4fd1ff2c6c03e203d5bd457532a81d4bc9 | NorfairKing/the-notes | Main.hs | module NumberTheory.Main where
import Notes
import qualified Data.Text as T
import qualified Prelude as P (Int, map, mod, (+), (<),
(^))
import Functions.Basics.Macro
import Functions.BinaryOperation.Terms
import Functions.Jections.Terms
import Groups.Macro
import Groups.Terms
import Logic.FirstOrderLogic.Macro
import Logic.PropositionalLogic.Macro
import Relations.Basics.Terms
import Relations.Equivalence.Macro
import Relations.Equivalence.Terms
import Sets.Basics.Terms
import NumberTheory.Macro
import NumberTheory.Terms
numberTheoryC :: Note
numberTheoryC = chapter "Number Theory" $ do
naturalNumbersS
wholeNumbersS
divisibilityS
moduloS
naturalNumbersS :: Note
naturalNumbersS = section "Natural numbers" $ do
naturalNumbersDefinition
naturalNumbersAddition
naturalNumbersSubtraction
naturalNumbersMultiplication
naturalNumbersDivision
naturalNumbersDefinition :: Note
naturalNumbersDefinition = de $ do
s [naturalNumbers', m nats, "are inductively defined as follows"]
itemize $ do
item $ m $ 0 === emptyset
let n = "n"
item $ m $ succ n === n ∪ setof n
naturalNumbersAddition :: Note
naturalNumbersAddition = de $ do
s [the, addition', "of", naturalNumbers, "is a", binaryOperation, m addN_, "defined recursively as follows"]
let n = "n"
ma $ n `addN` 0 === n === 0 `addN` n
let m = "m"
ma $ succ n + m === succ (n `addN` m)
naturalNumbersSubtraction :: Note
naturalNumbersSubtraction = de $ do
s [the, subtraction', "of", naturalNumbers, "is a", binaryOperation, m subN_, "defined in terms of", addition, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `subN` b =: c, "holds if", m $ c `addN` b =: a, "holds"]
naturalNumbersMultiplication :: Note
naturalNumbersMultiplication = de $ do
s [the, multiplication', "of", naturalNumbers, "is a", binaryOperation, m mulN_, "defined in terms of", addition, "as follows"]
let n = "n"
ma $ n `mulN` 0 === 0 === 0 `mulN` n
ma $ n `mulN` 1 === n === 1 `mulN` n
let m = "m"
ma $ succ n `mulN` m === m `addN` (pars $ n `mulN` m)
naturalNumbersDivision :: Note
naturalNumbersDivision = de $ do
s [the, division', "of", naturalNumbers, "is a", binaryOperation, m divN_, "defined in terms of", multiplication, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `divN` b =: c, "holds if", m $ c `mulN` b =: a, "holds"]
s [m $ a `divN` b, "is often written as", m $ a / b]
wholeNumbersS :: Note
wholeNumbersS = do
wholeNumbersDefinition
wholeNumbersEquivalentDefinition
naturalNumbersSubsetofWholeNumbersUnderInjection
wholeNumbersAddition
wholeNumbersSubtraction
wholeNumbersMultiplication
wholeNumbersDivision
wholeNumbersDefinition :: Note
wholeNumbersDefinition = de $ do
s [wholeNumbers', or, integers', m ints, "are defined as the", equivalenceClasses, "of", m $ naturals ^ 2, "with respect to the following", equivalenceRelation]
let (a, b, c, d) = ("a", "b", "c", "d")
-- b - a = d - c
ma $ wholen a b .~ wholen c d === b + c =: d + a
nte $ do
s ["Intuitively, an", element, m $ wholen a b, "represents", m $ b - a, "even if that", element, "does not exist in", m nats]
wholeNumbersEquivalentDefinition :: Note
wholeNumbersEquivalentDefinition = nte $ do
let pos = "+"
neg = "-"
s [wholeNumbers, "can equivalently be defined using two abstract elements", m pos, and, m neg, "as the", set, m $ setofs [pos, neg] ⨯ nats]
s ["Then there is no need to use", equivalenceClasses, "but we have to come up with suitable definitions of", m pos, and, m neg]
s ["For example, we can use the following definitions"]
ma $ pos === emptyset <> qquad <> text and <> qquad <> neg === setof emptyset
naturalNumbersSubsetofWholeNumbersUnderInjection :: Note
naturalNumbersSubsetofWholeNumbersUnderInjection = nte $ do
let i = "i"
s ["We regard the", set, "of", naturalNumbers, "as a", subset, "of the", wholeNumbers, "under the following", injection, m i]
let a = "a"
ma $ func i nats ints a $ wholen 0 a
wholeNumbersAddition :: Note
wholeNumbersAddition = de $ do
s [the, addition, m addZ_, "of", wholeNumbers, "is defined as the component-wise", addition, "of", naturalNumbers]
let (a, b, c, d) = ("a", "b", "c", "d")
ma $ wholen a b `addZ` wholen c d === wholen (a `addN` c) (b `addN` d)
s ["As such, we abbreviate", m $ wholen 0 a, "as", m a]
wholeNumbersSubtraction :: Note
wholeNumbersSubtraction = de $ do
s [the, subtraction', "of", wholeNumbers, "is a", binaryOperation, m subZ_, "defined in terms of", addition, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `subZ` b =: c, "holds if", m $ c `addZ` b =: a, "holds"]
wholeNumbersMultiplication :: Note
wholeNumbersMultiplication = de $ do
s [the, multiplication', "of", wholeNumbers, "is a", binaryOperation, m mulZ_, "defined in terms of", addition, "as follows"]
let n = "n"
ma $ n `mulZ` 0 === 0 === 0 `mulZ` n
ma $ n `mulZ` 1 === n === 1 `mulZ` n
let m = "m"
ma $ succ n `mulZ` m === m `addZ` (pars $ n `mulZ` m)
wholeNumbersDivision :: Note
wholeNumbersDivision = de $ do
s [the, division', "of", wholeNumbers, "is a", binaryOperation, m divN_, "defined in terms of", multiplication, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `divZ` b =: c, "holds if", m $ c `mulZ` b =: a, "holds"]
s [m $ a `divZ` b, "is often written as", m $ a / b]
divisibilityS :: Note
divisibilityS = section "Divisibilty" $ do
divisibilityDefinition
dividesTransitive
dividesMultiples
productDivides
gcdDefinition
lcmDefinition
todo "gcdExistence"
todo "lcmExistence"
bezoutIdentityLemma
lcmGcdProduct
primeDefinition
coprimeDefinition
coprimeDivisionCancels
coprimeDividesProduct
coprimeCompound
gcdMultiplicative
gcdMultiplicativeConsequence
divisibilityDefinition :: Note
divisibilityDefinition = de $ do
todo "define divisibility more abstractly in integrity domains"
let a = "a"
let b = "b"
let c = "c"
s ["We define a", wholeNumber, m a, "to be", divisible', "by another", wholeNumber, m b, "if there exists a", wholeNumber, m c, "such that", m $ a `divZ` b =: c]
s ["We then call", m b, "a", divisor', "of", m a, and, m c, "the", quotient']
ma $ a .| b === te (c ∈ ints) (a * c =: b)
dividesTransitive :: Note
dividesTransitive = prop $ do
lab dividesTransitivePropertyLabel
s [the, divides, relation, is, transitive_]
let a = "a"
let b = "b"
let c = "c"
ma $ fa (cs [a, b, c] ∈ ints) $ (pars $ a .| b) ∧ (pars $ b .| c) ⇒ (pars $ a .| c)
proof $ do
let x = "x"
s ["Because", m a, divides, m b <> ", there exists an", integer, m x, "as follows"]
ma $ a * x =: b
let y = "y"
s ["Because", m b, divides, m c <> ", there exists an", integer, m y, "as follows"]
ma $ b * y =: c
s ["Now we conclude that", m a, divides, m c, with, quotient, m $ x * y]
ma $ a * x * y =: c
dividesMultiples :: Note
dividesMultiples = prop $ do
lab dividesMultiplesPropertyLabel
let a = "a"
let b = "b"
let r = "r"
s ["Let", m a, and, m b, be, integers, "such that", m a, divides, m b]
ma $ fa (r ∈ ints) $ (a .| b) ⇒ (a .| (r * b))
proof $ do
let q = "q"
s ["Because", m a, divides, m b, "there exists an", integer, m q, "as follows"]
ma $ a * q =: b
s ["Let", m r, "be arbitrary"]
s ["Now, ", m a, divides, m $ r * b, "because of the following equation which we obtain by multiplying", m r, "to both sides of the previous equation"]
ma $ a * (q * r) =: b * r
productDivides :: Note
productDivides = prop $ do
lab productDividesPropertyLabel
let a = "a"
b = "b"
c = "c"
d = "d"
ab = a * b
cd = c * d
s ["Let", csa [m a, m b, m c, m d], be, integers, "such that", m a, divides, m b, and, m c, divides, m d <> ", then", m ab, divides, m cd]
ma $ (pars $ a .| b) ∧ (pars $ c .| d) ⇒ (ab .| cd)
proof $ do
let q = "q"
s ["Because", m a, divides, m b, "there exists a", m q, "as follows"]
ma $ a * q =: b
let r = "r"
s ["Because", m c, divides, m d, "there exists a", m r, "as follows"]
ma $ c * q =: d
s ["When we multiply these equations, we find that", m ab, divides, m cd, with, quotient, m $ q * r]
ma $ ab * q * r =: cd
gcdDefinition :: Note
gcdDefinition = de $ do
let a = "a"
b = "b"
g = "g"
c = "c"
s [the, greatestCommonDivisor', m $ gcd a b, "of two", integers, m a, and, m b, "is defined as follow"]
ma $ g =: gcd a b === (pars $ g .| a) ∧ (pars $ g .| b) ∧ (not $ pars $ te (c ∈ ints) $ (pars $ c .| a) ∧ (pars $ c .| b) ∧ (pars $ c < g))
lcmDefinition :: Note
lcmDefinition = de $ do
let a = "a"
b = "b"
l = "l"
c = "c"
s [the, leastCommonMultiple', m $ lcm a b, "of two", integers, m a, and, m b, "is defined as follow"]
ma $ l =: lcm a b === (pars $ a .| l) ∧ (pars $ b .| l) ∧ (not $ pars $ te (c ∈ ints) $ (pars $ a .| c) ∧ (pars $ b .| c) ∧ (pars $ c < l))
bezoutIdentityLemma :: Note
bezoutIdentityLemma = lem $ do
lab bezoutsIdentityLemmaLabel
let a = "a"
b = "b"
x = "x"
y = "y"
s ["Let", m a, and, m b, "be nonzero", integers, "then there exist", integers, m x, and, m y, "as follows"]
ma $ a * x + b * y =: gcd a b
todo "write this down correctly"
toprove
lcmGcdProduct :: Note
lcmGcdProduct = prop $ do
let a = "a"
b = "b"
ab = a * b
gab = gcd a b
lab = lcm a b
s ["Let", m a, and, m b, be, integers]
ma $ gab * lab =: a * b
proof $ do
let p = "p"
s ["Because", m gab, divides, m a <> ", it also divides", m ab, ref dividesMultiplesPropertyLabel, "so there exists an", integer, m p, "as follows"]
ma $ gab * p =: ab
s ["We now prove that", m p, "equals", m lab]
itemize $ do
let x = "x"
item $ do
s [m a, divides, m p]
newline
s ["Because", m gab, divides, m b <> ", there exists an", m x, "as follows"]
ma $ gab * x =: b
s ["Multiply both sides by", m a, "and we get the following"]
ma $ gab * x * a =: ab
s ["Equate this with the equation that we found for", m ab, "earlier, and we conclude that", m a, divides, m p, with, quotient, m x]
let y = "y"
item $ do
s [m b, divides, m p]
newline
s ["Because", m gab, divides, m a <> ", there exists an", m y, "as follows"]
ma $ gab * y =: a
s ["Multiply both sides by", m b, "and we get the following"]
ma $ gab * y * b =: ab
s ["Equate this with the equation that we found for", m ab, "earlier, and we conclude that", m b, divides, m p, with, quotient, m y]
item $ do
s ["There is no smaller", integer, "like that"]
newline
let z = "z"
s ["Suppose", m z, "is an", integer, "that is", divisible, by, m a, and, m b]
let k = "k"
k1 = k !: 1
k2 = k !: 2
ma $ z =: a * k1 <> quad <> text and <> quad <> z =: b * k2
let u = "u"
v = "v"
s ["By", bezoutsLemma <> ", there must exist two", integers, m u, and, m v, "as follows"]
ma $ gab =: a * u + b * v
s ["Now observe the following"]
aligneqs (z * gab)
[ z * (pars $ a * u + b * v)
, z * a * u + z * b * v
, (pars $ b * k2) * a * u + (pars $ a * k1) * b * v
, (a * b) * (pars $ k2 * u + k1 * v)
, (gab * p) * (pars $ k2 * u + k1 * v)
]
s ["We concude that", m p, divides, m z]
ma $ z =: p * (pars $ k2 * u + k1 * v)
coprimeDivisionCancels :: Note
coprimeDivisionCancels = prop $ do
lab coprimeDivisionCancelsPropertyLabel
let a = "a"
b = "b"
c = "c"
bc = b * c
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, divides, m bc, and, m a, and, m c, are, coprime <> ", then", m a, divides, m b]
ma $ (pars $ a .| bc) ∧ (pars $ a `copr` c) ⇒ (pars $ a .| b)
proof $ do
let n = "n"
s ["Because", m a, divides, m bc <> ", there exists an", integer, m n, "as follows"]
ma $ n * a =: bc
let x = "x"
y = "y"
s ["By", bezoutsLemma <> ", there must exist two", integers, m x, and, m y, "as follows"]
ma $ 1 =: a * x + c * y
s ["Multiply", m b, "on both sides of this equation to obtain the following"]
ma $ b =: a * b * x + b * c * y
s ["Now substitute", m bc]
ma $ b =: a * b * x + a * n * y
s ["Seperate out", m a, "to conclude that", m a, divides, m b, with, quotient, m $ b * x + n * y]
ma $ b =: a * (pars $ b * x + n * y)
coprimeDividesProduct :: Note
coprimeDividesProduct = prop $ do
lab coprimeDividesProductPropertyLabel
let a = "a"
b = "b"
c = "c"
ab = a * b
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, divides, m b, and, m a, divides, m c, and, m a, and, m b, are, coprime <> ", then", m ab, divides, m c]
ma $ (pars $ a .| c) ∧ (pars $ b .| c) ∧ (pars $ gcd a b =: 1) ⇒ (pars $ ab .| c)
proof $ do
let q = "q"
s ["Because", m a, divides, m c, "there exists a", m q, "as follows"]
ma $ a * q =: c
s ["Because", m b, divides, m $ a * q, but, m a, and, m b, are, coprime, "we conclude that", m b, divides, m q, ref coprimeDivisionCancelsPropertyLabel]
s ["Because", m b, divides, m q, "there must exist an", integer, m p, "as follows"]
let p = "p"
ma $ b * p =: q
s ["We now find that", m ab, divides, m c, with, quotient, m p]
ma $ a * b * p =: c
primeDefinition :: Note
primeDefinition = de $ do
let a = "a"
s ["An", integer, m a, "is called", prime', "if it its largest", divisor <> ", different from", m a, "itself, is", m 1]
coprimeDefinition :: Note
coprimeDefinition = de $ do
lab coprimeDefinitionLabel
lab relativelyPrimeDefinitionLabel
let a = "a"
b = "b"
s ["Two", integers, m a, and, m b, "are considered", cso [coprime', relativelyPrime', mutuallyPrime], "if their", greatestCommonDivisor, "is one"]
ma $ a `copr` b === gcd a b =: 1
s ["Equivalently, their", leastCommonMultiple, is, m $ a * b]
toprove
coprimeCompound :: Note
coprimeCompound = prop $ do
lab coprimeCompoundPropertyLabel
let a = "a"
b = "b"
c = "c"
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime <> ", then", m $ gcd a c, and, m $ gcd b c, are, coprime]
ma $ (a `copr` b) ⇒ fa (c ∈ ints) (gcd a c `copr` gcd b c)
proof $ do
s ["Suppose, for the sake of contradiction, that", m $ gcd a c, and, m $ gcd b c, "are not", coprime]
s ["This would mean the following"]
let g = "g"
ma $ gcd (gcd a c) (gcd b c) =: g > 1
s ["This means that", m g, divides, m $ gcd a c, and, m $ gcd b c, and, "therefore transitively", m a, and, m b, ref dividesTransitivePropertyLabel]
s ["Because", m a, and, m b, are, coprime, "the", greatestCommonDivisor, "of", m a, and, m b, is, m 1, "so", m g, "cannot be a", divisor, "of", m a, and, m b]
s ["We arrive at a contradiction"]
gcdMultiplicative :: Note
gcdMultiplicative = prop $ do
lab gcdMultiplicativePropertyLabel
let a = "a"
b = "b"
c = "c"
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime]
let ab = a * b
gab = gcd ab c
ga = gcd a c
gb = gcd b c
gab_ = ga * gb
g = "g"
ma $ gab =: ga * gb
proof $ do
s ["We prove the three components of the", greatestCommonDivisor, "separately"]
s ["Define", m $ g =: gab_]
itemize $ do
item $ do
s [m g, divides, m ab, ref productDividesPropertyLabel]
item $ do
s [m g, divides, m c, ref coprimeCompoundPropertyLabel, ref coprimeDividesProductPropertyLabel]
item $ do
s [m g, "is the smallest", integer, "that does so"]
newline
let z = "z"
s ["Suppose there was an", integer, m z, "that divided both", m ab, and, m c]
let x = "x"
y = "y"
s ["That would mean that there exist integers", m x, and, m y]
ma $ z * x =: ab <> quad <> text and <> quad <> z * y =: c
let t = "t"
u = "u"
v = "v"
w = "w"
s ["According to", bezoutsLemma, ref bezoutsIdentityLemmaLabel <> ", there must exist", integers, csa [m t, m u, m v, m w], "as follows"]
ma $ g =: (pars $ t * a + u * c) * (pars $ v * b + w * c)
s ["Now observe the following"]
aligneqs g
[ t * a * v * b + t * a * w * c + u * c * v * b + u * c * w * c
, z * x * t * v + z * y * t * a * w + z * y * u * v * b + z * y * u * c * w
, z * (pars $ x * t * v + y * t * a * w + y * u * v * b + y * u * c * w)
]
s ["We conclude that", m z, divides, m g]
gcdMultiplicativeConsequence :: Note
gcdMultiplicativeConsequence = con $ do
lab gcdMultiplicativeConsequenceLabel
let a = "a"
b = "b"
c = "c"
bc = b * c
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime]
s [m a, and, m bc, are, coprime, "if and only if both", m a, and, m b <> ",", and, m a, and, m c, are, coprime]
proof $ do
s ["Proof of an equivalence"]
itemize $ do
item $ do
s ["If", m $ a `copr` bc, "holds, then", m $ gcd a c * gcd b c, "must be one", ref gcdMultiplicativePropertyLabel]
s ["Because they are", integers <> ", this means that both", m $ gcd a c, and, m $ gcd b c, "must be one and therefore, by definition,", m $ a `copr` c, and, m $ b `copr` c, "hold"]
item $ do
s ["If both", m $ a `copr` c, and, m $ b `copr` c, "hold, then the product of their", greatestCommonDivisors, "must be one and therefore", m a, and, m bc, coprime]
moduloS :: Note
moduloS = section "Modular arithmetic" $ do
oddEvenDefinition
modularIntegersDefinition
solutionOfLinearCongruenceTheorem
chineseRemainderTheoremPart
quadraticResidueDefinition
quadraticResidueExamples
quadraticResiduesInPrimeGroup
oneFourthQuadraticResidues
legendreSymbolDefinition
legendreSymbolExamples
eulerCriterionLegendreSymbol
jacobiSymbolDefinition
jacobiSymbolExamples
modularIntegersDefinition :: Note
modularIntegersDefinition = de $ do
let n = "n"
s [the, integers, "modulo an", integer, m n, "are defined as the following", quotientGroup]
ma $ intmod n === qgrp ints (n <> ints)
let a = "a"
b = "b"
q = "q"
s ["We say that an", integer, m a, is, congruent', with, "an", integer, m b, "modulo an", integer, m n, "if there exists an", integer, m q, "such that", m $ a =: b + q * n, "holds"]
ma $ eqmod n a b === te (q ∈ ints) (a =: b + q * n)
todo "fully formalize once we have a good chapter on groups"
oddEvenDefinition :: Note
oddEvenDefinition = de $ do
s ["An", integer, "is called", odd', "if it is", congruent, with, m 1, modulo, m 2]
s ["If it is instead", congruent, with, m 0, modulo, m 2 <> ", then we call it", even']
solutionOfLinearCongruenceTheorem :: Note
solutionOfLinearCongruenceTheorem = thm $ do
lab solutionOfLinearCongruenceTheoremLabel
let a = "a"
n = "n"
b = "b"
s ["Let", csa [m a, m b, m n], be, integers]
let x = "x"
s ["There exists an", integer, m x, "as follows if and only if", m $ gcd a n, divides, m b]
s [m b, "is unique if", m a, and, m n, are, coprime]
ma $ (pars $ gcd a n .| b) ⇔ (pars $ te (x ∈ ints) $ eqmod n (a * x) b)
proof $ do
s ["Proof of an equivalence"]
itemize $ do
item $ do
let y = "y"
s ["If", m $ gcd a n, divides, m b, "then there exists an", integer, m y, "as follows"]
ma $ gcd a n * y =: b
let p = "p"
q = "q"
s [bezoutsLemma, "tells us that there exist", integers, m p, and, m q, "as follows"]
ma $ gcd a n =: a * p + n * q
s ["If we substitute this in the above equation, we get the following"]
ma $ a * p * y + n * q * y =: b
s ["If we now look at the second term on the left-hand side, we see that it's divisible by", m n, "so it dissappears when viewed modulo", m n]
ma $ eqmod n (a * p * y) b
s ["We find that", m $ p * y, "is a valid candidate for", m x]
newline
let u = "u"
s ["Now, assume", m a, and, m n, are, coprime, and, m u, "is another such", integer, "solution"]
s ["If", m n, "equals", m 1 <> ", then", m x, "is trivially unique, because it's always zero"]
s ["Otherwise, note that", m a, "cannot be zero because then the", greatestCommonDivisor, "of", m a, and, m n, "would be", m n, "instead of", m 1]
ma $ eqmod n (a * x) (a * u)
s ["We divide out", m a, "which we're allowed to do because", m a, "is not zero"]
s ["We find that", m x, and, m u, "are equal and therefore", m x, "is unique"]
item $ do
s ["Let", m x, "be an", integer, "as follows"]
ma $ eqmod n (a * x) b
let f = "f"
s ["This means that there exists an", integer, m f, "as follows"]
ma $ a * x + f * n =: b
let p = "p"
q = "q"
g = gcd a n
s ["Now,", m $ gcd a n, divides, m a, and, m n, "so there exist", integers, m p, and, m q, "as follows"]
ma $ g * p =: a <> qquad <> text and <> qquad <> g * q =: n
s ["After substitution, we find the following"]
ma $ g * p * x + g * q * f =: b
s ["We conclude that", m g, divides, m b, with, quotient, m $ p * x + q * f]
chineseRemainderTheoremPart :: Note
chineseRemainderTheoremPart = thm $ do
lab chineseRemainderTheoremLabel
lab chineseRemainderTheoremDefinitionLabel
s [the, chineseRemainderTheorem']
newline
let n = "n"
k = "k"
a = "a"
(n1, n2, nk, ns) = buildList n k
(a1, a2, ak, as) = buildList a k
s ["Let", m ns, "be a list of", pairwiseCoprime, integers]
let x = "x"
s ["For any given list of", integers, m as <> ", there exists an", integer, m x, "as follows"]
ma $ centeredBelowEachOther $
[ eqmod n1 x a1
, eqmod n2 x a2
, vdots
, eqmod nk x ak
]
let i = "i"
let ni = n !: i
s ["Furthermore, the solution is unique modulo", m $ prodcmp i ni]
proof $ do
let nn = "N"
s ["Let", m nn, "be the product", m $ prodcmpr (i =: 1) k ni]
let nni = nn !: i
s ["Define", m nni, "as", m $ nn / nk]
newline
s ["Because the", integers, m ns, are, pairwiseCoprime <> ",", m nni, and, m ni, "are also", coprime, ref gcdMultiplicativeConsequenceLabel]
ma $ gcd nni ni =: 1
let x = "x"
xi = x !: i
s ["This means that the", linearCongruence, m $ eqmod nk (nni * xi) 1, "has some unique solution", m xi, ref solutionOfLinearCongruenceTheoremLabel]
let ai = a !: i
s ["Define", m $ x =: sumcmpr (i =: 1) k (ai * nni * xi)]
s ["We will now prove that", m x, "satisfies all the", linearCongruences]
s ["Let", m i, "therefore be arbitrary"]
let j = "j"
nj = n !: j
s ["Note first that for any", m j, "different from", m i <> ",", m nj, divides, m nni]
ma $ eqmod ni nj 0
s ["We find that the following holds"]
ma $ eqmod ni x (ai * nni * xi)
s ["Finally, because", m $ nni * xi, "was found to be congruent with", m 1, "modulo", m ni, "we find that", m x, "is congruent with", m ai]
newline
s ["Now we only have to prove that this solution is unique modulo", m n]
let y = "y"
s ["Suppose that", m y, "was another solution of the system"]
s ["This means that each", m ni, divides, m $ y - x, "but because each of the moduli are", coprime, "we find that also", m nn, divides, m $ y - x, ref coprimeDividesProductPropertyLabel]
s ["That is,", m y, and, m x, are, congruent, modulo, m nn]
quadraticResidueDefinition :: Note
quadraticResidueDefinition = de $ do
lab quadraticResidueDefinitionLabel
let n = "n"
x = "r"
y = "q"
s ["A", quadraticResidue', "modulo an", integer, m n, "is an", integer, m x, "such that there exists an", integer, m y, "as follows"]
ma $ eqmod n (y ^ 2) x
quadraticResidueExamples :: Note
quadraticResidueExamples = do
ex $ do
let n = "n"
s [m 0, and, m 1, "are always", quadraticResidues, "in", m $ intmod n, for, m $ n > 1, because, m $ eqmod n (0 ^ 2) 0, and, m $ eqmod n (1 ^ 2) 1]
ex $ do
s ["In", m (intmod 7) <> ",", m 2, "is a", quadraticResidue, because, m $ eqmod 7 (5 ^ 2) 2]
ex $ do
s ["In", m $ intmod 5, ", the", quadraticResidues, are, csa [m 0, m 1, m 4], because, csa [m $ eqmod 5 (0 ^ 2) 0, m $ eqmod 5 (1 ^ 2) 1, m $ eqmod 5 (2 ^ 2) 4]]
ex $ do
s ["In", m $ intmod 35, ", the", quadraticResidues, are, "the following", elements]
ma $ cs [0, 1, 4, 9, 11, 14, 15, 16, 21, 25, 29, 30]
ex $ do
s ["Here are the", quadraticResidues, "(different from", m 0, and, m 1 <> ") modulo some small", integers]
let rawn :: P.Int -> Note
rawn = raw . T.pack . show
let n = 20
newline
hereFigure $ linedTable
((raw "n\\setminus q") : P.map rawn [1 .. n])
( P.map (\i -> do
rawn i : (P.map (\j -> if j P.< (i P.+ 1) then (rawn $ j P.^ (2 :: P.Int) `P.mod` i) else mempty) [1 .. n])
) [0 .. n])
quadraticResiduesInPrimeGroup :: Note
quadraticResiduesInPrimeGroup = thm $ do
let p = "p"
a = "a"
s ["Let", m p, "be an", odd, prime, and, m a, "an", integer, "that is not", divisible, by, m p]
let g = "g"
s ["Let", m g, "be a", generator, "of", m $ intmgrp p]
let q = "q"
itemize $ do
item $ do
s [m a, "is a", quadraticResidue, modulo, m p, "if and only if there exists an", integer, m q, "such that", m $ eqmod p a (g ^ (2 * q)), "holds"]
item $ do
s [m a, "is not a", quadraticResidue, modulo, m p, "if and only if there exists an", integer, m q, "such that", m $ eqmod p a (g ^ (2 * q + 1)), "holds"]
proof $ do
s ["Because", m a, "is not", divisible, by, m p <> ",", m a, "is an", element, "of", m $ int0mod p]
itemize $ do
item $ do
let x = "x"
s ["Suppose", m a, "is a", quadraticResidue, modulo, m p, "then there exists an", integer, m x, "as follows"]
ma $ eqmod p (x^2) a
s [m x, "must then be an", element, "of", m $ int0mod p]
s ["Because", m g, "is a", generator, for, m (intmgrp p) <> ", there must exist an", integer, m q, "as follows"]
ma $ eqmod p x (g ^ q)
s ["This means that we have found the", m q, "that we were looking for"]
ma $ eqmod p a (g ^ (2 * q))
s ["The other direction is trivial"]
item $ do
toprove
oneFourthQuadraticResidues :: Note
oneFourthQuadraticResidues = thm $ do
let p = "p"
q = "q"
n = "n"
s ["Let", m p, and, m q, "be two", odd, primes, and, define, m $ n =: p * q]
s [m $ 1 / 4, "of the", elements, "in", m $ int0mod n, are, quadraticResidues, modulo, m n]
toprove
legendreSymbolDefinition :: Note
legendreSymbolDefinition = de $ do
let a = "a"
p = "p"
s ["Let", m a, "be an", integer, and, m p, "an", odd, prime]
s [the, legendreSymbol', "of", m a, over, m p, "is defined as follows"]
ma $ (leg a p ===) $ cases $ do
1 & text "if " <> m a <> text (" is a " <> quadraticResidue <> " " <> modulo <> " ") <> m p <> text " and " <> neg (p .| a)
lnbk
(-1) & text "if " <> m a <> text (" is not a " <> quadraticResidue <> " " <> modulo <> " ") <> m p
lnbk
0 & text "if " <> p .| a
legendreSymbolExamples :: Note
legendreSymbolExamples = do
ex $ do
s ["Note that", m $ 4 ^ 2 =: 16, and, m $ eqmod 11 16 5]
ma $ leg 5 11 =: 1
ex $ do
ma $ leg 6 11 =: -1
eulerCriterionLegendreSymbol :: Note
eulerCriterionLegendreSymbol = thm $ do
s [eulersCriterion', for, legendreSymbols]
let a = "a"
p = "p"
s ["Let", m a, "be an", integer, and, m p, "an", integer, odd, prime]
let l = leg a p
ap = a ^ ((p - 1) / 2)
ma $ eqmod p l ap
proof $ do
s ["We have to prove three cases:"]
itemize $ do
item $ do
s [m ap, is, m 0, modulo, m p, "if and only if", m $ leg a p, is, m 0]
newline
let n = "n"
s ["if", m p, divides, m a, "then there exists an", m n, "as follows"]
ma $ (n * p) ^ ((p - 1) / 2)
s ["This is clearly", divisible, by, m p, "and therefore the following holds"]
ma $ eqmod p ap 0
item $ do
s [m ap, is, m 1, modulo, m p, "if and only if", m a, "is a", quadraticResidue, modulo, m p]
newline
toprove
item $ do
s [m ap, is, m (-1), modulo, m p, "if and only if", m a, "is not a", quadraticResidue, modulo, m p]
newline
toprove
jacobiSymbolDefinition :: Note
jacobiSymbolDefinition = de $ do
let a = "a"
n = "n"
s ["Let", m a, "be an", integer, and, m n, "an", odd, naturalNumber, "with the following", primeFactorization]
let p = "p"
t = "t"
(p1, p2, pt, _) = buildList p t
v = "v"
(v1, v2, vt, _) = buildList v t
i = "i"
pi = p !: i
vi = v !: i
let (^) = (.^:)
ma $ n =: p1 ^ v1 * p2 ^ v2 * dotsb * pt ^ vt =: prodcmpr (i =: 1) t (pi ^ vi)
s [the, jacobiSymbol', "of", m a, over, m p, "is defined as follows"]
ma $ jac a n === (leg a p1) ^ v1 * (leg a p2) ^ v2 * dotsb * (leg a pt) ^ vt =: prodcmpr (i =: 1) t ((leg a pi) ^ vi)
jacobiSymbolExamples :: Note
jacobiSymbolExamples = do
let (^) = (.^:)
ex $ do
ma $ jac 5 9 =: jac 5 (3 ^ 2) =: (leg 5 3) ^ 2 =: 1
ex $ do
ma $ jac 5 12 =: jac 5 (3 * 2 ^ 2) =: (leg 5 3) * (leg 5 2) ^ 2 =: -1
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/NumberTheory/Main.hs | haskell | b - a = d - c | module NumberTheory.Main where
import Notes
import qualified Data.Text as T
import qualified Prelude as P (Int, map, mod, (+), (<),
(^))
import Functions.Basics.Macro
import Functions.BinaryOperation.Terms
import Functions.Jections.Terms
import Groups.Macro
import Groups.Terms
import Logic.FirstOrderLogic.Macro
import Logic.PropositionalLogic.Macro
import Relations.Basics.Terms
import Relations.Equivalence.Macro
import Relations.Equivalence.Terms
import Sets.Basics.Terms
import NumberTheory.Macro
import NumberTheory.Terms
numberTheoryC :: Note
numberTheoryC = chapter "Number Theory" $ do
naturalNumbersS
wholeNumbersS
divisibilityS
moduloS
naturalNumbersS :: Note
naturalNumbersS = section "Natural numbers" $ do
naturalNumbersDefinition
naturalNumbersAddition
naturalNumbersSubtraction
naturalNumbersMultiplication
naturalNumbersDivision
naturalNumbersDefinition :: Note
naturalNumbersDefinition = de $ do
s [naturalNumbers', m nats, "are inductively defined as follows"]
itemize $ do
item $ m $ 0 === emptyset
let n = "n"
item $ m $ succ n === n ∪ setof n
naturalNumbersAddition :: Note
naturalNumbersAddition = de $ do
s [the, addition', "of", naturalNumbers, "is a", binaryOperation, m addN_, "defined recursively as follows"]
let n = "n"
ma $ n `addN` 0 === n === 0 `addN` n
let m = "m"
ma $ succ n + m === succ (n `addN` m)
naturalNumbersSubtraction :: Note
naturalNumbersSubtraction = de $ do
s [the, subtraction', "of", naturalNumbers, "is a", binaryOperation, m subN_, "defined in terms of", addition, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `subN` b =: c, "holds if", m $ c `addN` b =: a, "holds"]
naturalNumbersMultiplication :: Note
naturalNumbersMultiplication = de $ do
s [the, multiplication', "of", naturalNumbers, "is a", binaryOperation, m mulN_, "defined in terms of", addition, "as follows"]
let n = "n"
ma $ n `mulN` 0 === 0 === 0 `mulN` n
ma $ n `mulN` 1 === n === 1 `mulN` n
let m = "m"
ma $ succ n `mulN` m === m `addN` (pars $ n `mulN` m)
naturalNumbersDivision :: Note
naturalNumbersDivision = de $ do
s [the, division', "of", naturalNumbers, "is a", binaryOperation, m divN_, "defined in terms of", multiplication, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `divN` b =: c, "holds if", m $ c `mulN` b =: a, "holds"]
s [m $ a `divN` b, "is often written as", m $ a / b]
wholeNumbersS :: Note
wholeNumbersS = do
wholeNumbersDefinition
wholeNumbersEquivalentDefinition
naturalNumbersSubsetofWholeNumbersUnderInjection
wholeNumbersAddition
wholeNumbersSubtraction
wholeNumbersMultiplication
wholeNumbersDivision
wholeNumbersDefinition :: Note
wholeNumbersDefinition = de $ do
s [wholeNumbers', or, integers', m ints, "are defined as the", equivalenceClasses, "of", m $ naturals ^ 2, "with respect to the following", equivalenceRelation]
let (a, b, c, d) = ("a", "b", "c", "d")
ma $ wholen a b .~ wholen c d === b + c =: d + a
nte $ do
s ["Intuitively, an", element, m $ wholen a b, "represents", m $ b - a, "even if that", element, "does not exist in", m nats]
wholeNumbersEquivalentDefinition :: Note
wholeNumbersEquivalentDefinition = nte $ do
let pos = "+"
neg = "-"
s [wholeNumbers, "can equivalently be defined using two abstract elements", m pos, and, m neg, "as the", set, m $ setofs [pos, neg] ⨯ nats]
s ["Then there is no need to use", equivalenceClasses, "but we have to come up with suitable definitions of", m pos, and, m neg]
s ["For example, we can use the following definitions"]
ma $ pos === emptyset <> qquad <> text and <> qquad <> neg === setof emptyset
naturalNumbersSubsetofWholeNumbersUnderInjection :: Note
naturalNumbersSubsetofWholeNumbersUnderInjection = nte $ do
let i = "i"
s ["We regard the", set, "of", naturalNumbers, "as a", subset, "of the", wholeNumbers, "under the following", injection, m i]
let a = "a"
ma $ func i nats ints a $ wholen 0 a
wholeNumbersAddition :: Note
wholeNumbersAddition = de $ do
s [the, addition, m addZ_, "of", wholeNumbers, "is defined as the component-wise", addition, "of", naturalNumbers]
let (a, b, c, d) = ("a", "b", "c", "d")
ma $ wholen a b `addZ` wholen c d === wholen (a `addN` c) (b `addN` d)
s ["As such, we abbreviate", m $ wholen 0 a, "as", m a]
wholeNumbersSubtraction :: Note
wholeNumbersSubtraction = de $ do
s [the, subtraction', "of", wholeNumbers, "is a", binaryOperation, m subZ_, "defined in terms of", addition, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `subZ` b =: c, "holds if", m $ c `addZ` b =: a, "holds"]
wholeNumbersMultiplication :: Note
wholeNumbersMultiplication = de $ do
s [the, multiplication', "of", wholeNumbers, "is a", binaryOperation, m mulZ_, "defined in terms of", addition, "as follows"]
let n = "n"
ma $ n `mulZ` 0 === 0 === 0 `mulZ` n
ma $ n `mulZ` 1 === n === 1 `mulZ` n
let m = "m"
ma $ succ n `mulZ` m === m `addZ` (pars $ n `mulZ` m)
wholeNumbersDivision :: Note
wholeNumbersDivision = de $ do
s [the, division', "of", wholeNumbers, "is a", binaryOperation, m divN_, "defined in terms of", multiplication, "as follows"]
let a = "a"
let b = "b"
let c = "c"
s ["We say that", m $ a `divZ` b =: c, "holds if", m $ c `mulZ` b =: a, "holds"]
s [m $ a `divZ` b, "is often written as", m $ a / b]
divisibilityS :: Note
divisibilityS = section "Divisibilty" $ do
divisibilityDefinition
dividesTransitive
dividesMultiples
productDivides
gcdDefinition
lcmDefinition
todo "gcdExistence"
todo "lcmExistence"
bezoutIdentityLemma
lcmGcdProduct
primeDefinition
coprimeDefinition
coprimeDivisionCancels
coprimeDividesProduct
coprimeCompound
gcdMultiplicative
gcdMultiplicativeConsequence
divisibilityDefinition :: Note
divisibilityDefinition = de $ do
todo "define divisibility more abstractly in integrity domains"
let a = "a"
let b = "b"
let c = "c"
s ["We define a", wholeNumber, m a, "to be", divisible', "by another", wholeNumber, m b, "if there exists a", wholeNumber, m c, "such that", m $ a `divZ` b =: c]
s ["We then call", m b, "a", divisor', "of", m a, and, m c, "the", quotient']
ma $ a .| b === te (c ∈ ints) (a * c =: b)
dividesTransitive :: Note
dividesTransitive = prop $ do
lab dividesTransitivePropertyLabel
s [the, divides, relation, is, transitive_]
let a = "a"
let b = "b"
let c = "c"
ma $ fa (cs [a, b, c] ∈ ints) $ (pars $ a .| b) ∧ (pars $ b .| c) ⇒ (pars $ a .| c)
proof $ do
let x = "x"
s ["Because", m a, divides, m b <> ", there exists an", integer, m x, "as follows"]
ma $ a * x =: b
let y = "y"
s ["Because", m b, divides, m c <> ", there exists an", integer, m y, "as follows"]
ma $ b * y =: c
s ["Now we conclude that", m a, divides, m c, with, quotient, m $ x * y]
ma $ a * x * y =: c
dividesMultiples :: Note
dividesMultiples = prop $ do
lab dividesMultiplesPropertyLabel
let a = "a"
let b = "b"
let r = "r"
s ["Let", m a, and, m b, be, integers, "such that", m a, divides, m b]
ma $ fa (r ∈ ints) $ (a .| b) ⇒ (a .| (r * b))
proof $ do
let q = "q"
s ["Because", m a, divides, m b, "there exists an", integer, m q, "as follows"]
ma $ a * q =: b
s ["Let", m r, "be arbitrary"]
s ["Now, ", m a, divides, m $ r * b, "because of the following equation which we obtain by multiplying", m r, "to both sides of the previous equation"]
ma $ a * (q * r) =: b * r
productDivides :: Note
productDivides = prop $ do
lab productDividesPropertyLabel
let a = "a"
b = "b"
c = "c"
d = "d"
ab = a * b
cd = c * d
s ["Let", csa [m a, m b, m c, m d], be, integers, "such that", m a, divides, m b, and, m c, divides, m d <> ", then", m ab, divides, m cd]
ma $ (pars $ a .| b) ∧ (pars $ c .| d) ⇒ (ab .| cd)
proof $ do
let q = "q"
s ["Because", m a, divides, m b, "there exists a", m q, "as follows"]
ma $ a * q =: b
let r = "r"
s ["Because", m c, divides, m d, "there exists a", m r, "as follows"]
ma $ c * q =: d
s ["When we multiply these equations, we find that", m ab, divides, m cd, with, quotient, m $ q * r]
ma $ ab * q * r =: cd
gcdDefinition :: Note
gcdDefinition = de $ do
let a = "a"
b = "b"
g = "g"
c = "c"
s [the, greatestCommonDivisor', m $ gcd a b, "of two", integers, m a, and, m b, "is defined as follow"]
ma $ g =: gcd a b === (pars $ g .| a) ∧ (pars $ g .| b) ∧ (not $ pars $ te (c ∈ ints) $ (pars $ c .| a) ∧ (pars $ c .| b) ∧ (pars $ c < g))
lcmDefinition :: Note
lcmDefinition = de $ do
let a = "a"
b = "b"
l = "l"
c = "c"
s [the, leastCommonMultiple', m $ lcm a b, "of two", integers, m a, and, m b, "is defined as follow"]
ma $ l =: lcm a b === (pars $ a .| l) ∧ (pars $ b .| l) ∧ (not $ pars $ te (c ∈ ints) $ (pars $ a .| c) ∧ (pars $ b .| c) ∧ (pars $ c < l))
bezoutIdentityLemma :: Note
bezoutIdentityLemma = lem $ do
lab bezoutsIdentityLemmaLabel
let a = "a"
b = "b"
x = "x"
y = "y"
s ["Let", m a, and, m b, "be nonzero", integers, "then there exist", integers, m x, and, m y, "as follows"]
ma $ a * x + b * y =: gcd a b
todo "write this down correctly"
toprove
lcmGcdProduct :: Note
lcmGcdProduct = prop $ do
let a = "a"
b = "b"
ab = a * b
gab = gcd a b
lab = lcm a b
s ["Let", m a, and, m b, be, integers]
ma $ gab * lab =: a * b
proof $ do
let p = "p"
s ["Because", m gab, divides, m a <> ", it also divides", m ab, ref dividesMultiplesPropertyLabel, "so there exists an", integer, m p, "as follows"]
ma $ gab * p =: ab
s ["We now prove that", m p, "equals", m lab]
itemize $ do
let x = "x"
item $ do
s [m a, divides, m p]
newline
s ["Because", m gab, divides, m b <> ", there exists an", m x, "as follows"]
ma $ gab * x =: b
s ["Multiply both sides by", m a, "and we get the following"]
ma $ gab * x * a =: ab
s ["Equate this with the equation that we found for", m ab, "earlier, and we conclude that", m a, divides, m p, with, quotient, m x]
let y = "y"
item $ do
s [m b, divides, m p]
newline
s ["Because", m gab, divides, m a <> ", there exists an", m y, "as follows"]
ma $ gab * y =: a
s ["Multiply both sides by", m b, "and we get the following"]
ma $ gab * y * b =: ab
s ["Equate this with the equation that we found for", m ab, "earlier, and we conclude that", m b, divides, m p, with, quotient, m y]
item $ do
s ["There is no smaller", integer, "like that"]
newline
let z = "z"
s ["Suppose", m z, "is an", integer, "that is", divisible, by, m a, and, m b]
let k = "k"
k1 = k !: 1
k2 = k !: 2
ma $ z =: a * k1 <> quad <> text and <> quad <> z =: b * k2
let u = "u"
v = "v"
s ["By", bezoutsLemma <> ", there must exist two", integers, m u, and, m v, "as follows"]
ma $ gab =: a * u + b * v
s ["Now observe the following"]
aligneqs (z * gab)
[ z * (pars $ a * u + b * v)
, z * a * u + z * b * v
, (pars $ b * k2) * a * u + (pars $ a * k1) * b * v
, (a * b) * (pars $ k2 * u + k1 * v)
, (gab * p) * (pars $ k2 * u + k1 * v)
]
s ["We concude that", m p, divides, m z]
ma $ z =: p * (pars $ k2 * u + k1 * v)
coprimeDivisionCancels :: Note
coprimeDivisionCancels = prop $ do
lab coprimeDivisionCancelsPropertyLabel
let a = "a"
b = "b"
c = "c"
bc = b * c
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, divides, m bc, and, m a, and, m c, are, coprime <> ", then", m a, divides, m b]
ma $ (pars $ a .| bc) ∧ (pars $ a `copr` c) ⇒ (pars $ a .| b)
proof $ do
let n = "n"
s ["Because", m a, divides, m bc <> ", there exists an", integer, m n, "as follows"]
ma $ n * a =: bc
let x = "x"
y = "y"
s ["By", bezoutsLemma <> ", there must exist two", integers, m x, and, m y, "as follows"]
ma $ 1 =: a * x + c * y
s ["Multiply", m b, "on both sides of this equation to obtain the following"]
ma $ b =: a * b * x + b * c * y
s ["Now substitute", m bc]
ma $ b =: a * b * x + a * n * y
s ["Seperate out", m a, "to conclude that", m a, divides, m b, with, quotient, m $ b * x + n * y]
ma $ b =: a * (pars $ b * x + n * y)
coprimeDividesProduct :: Note
coprimeDividesProduct = prop $ do
lab coprimeDividesProductPropertyLabel
let a = "a"
b = "b"
c = "c"
ab = a * b
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, divides, m b, and, m a, divides, m c, and, m a, and, m b, are, coprime <> ", then", m ab, divides, m c]
ma $ (pars $ a .| c) ∧ (pars $ b .| c) ∧ (pars $ gcd a b =: 1) ⇒ (pars $ ab .| c)
proof $ do
let q = "q"
s ["Because", m a, divides, m c, "there exists a", m q, "as follows"]
ma $ a * q =: c
s ["Because", m b, divides, m $ a * q, but, m a, and, m b, are, coprime, "we conclude that", m b, divides, m q, ref coprimeDivisionCancelsPropertyLabel]
s ["Because", m b, divides, m q, "there must exist an", integer, m p, "as follows"]
let p = "p"
ma $ b * p =: q
s ["We now find that", m ab, divides, m c, with, quotient, m p]
ma $ a * b * p =: c
primeDefinition :: Note
primeDefinition = de $ do
let a = "a"
s ["An", integer, m a, "is called", prime', "if it its largest", divisor <> ", different from", m a, "itself, is", m 1]
coprimeDefinition :: Note
coprimeDefinition = de $ do
lab coprimeDefinitionLabel
lab relativelyPrimeDefinitionLabel
let a = "a"
b = "b"
s ["Two", integers, m a, and, m b, "are considered", cso [coprime', relativelyPrime', mutuallyPrime], "if their", greatestCommonDivisor, "is one"]
ma $ a `copr` b === gcd a b =: 1
s ["Equivalently, their", leastCommonMultiple, is, m $ a * b]
toprove
coprimeCompound :: Note
coprimeCompound = prop $ do
lab coprimeCompoundPropertyLabel
let a = "a"
b = "b"
c = "c"
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime <> ", then", m $ gcd a c, and, m $ gcd b c, are, coprime]
ma $ (a `copr` b) ⇒ fa (c ∈ ints) (gcd a c `copr` gcd b c)
proof $ do
s ["Suppose, for the sake of contradiction, that", m $ gcd a c, and, m $ gcd b c, "are not", coprime]
s ["This would mean the following"]
let g = "g"
ma $ gcd (gcd a c) (gcd b c) =: g > 1
s ["This means that", m g, divides, m $ gcd a c, and, m $ gcd b c, and, "therefore transitively", m a, and, m b, ref dividesTransitivePropertyLabel]
s ["Because", m a, and, m b, are, coprime, "the", greatestCommonDivisor, "of", m a, and, m b, is, m 1, "so", m g, "cannot be a", divisor, "of", m a, and, m b]
s ["We arrive at a contradiction"]
gcdMultiplicative :: Note
gcdMultiplicative = prop $ do
lab gcdMultiplicativePropertyLabel
let a = "a"
b = "b"
c = "c"
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime]
let ab = a * b
gab = gcd ab c
ga = gcd a c
gb = gcd b c
gab_ = ga * gb
g = "g"
ma $ gab =: ga * gb
proof $ do
s ["We prove the three components of the", greatestCommonDivisor, "separately"]
s ["Define", m $ g =: gab_]
itemize $ do
item $ do
s [m g, divides, m ab, ref productDividesPropertyLabel]
item $ do
s [m g, divides, m c, ref coprimeCompoundPropertyLabel, ref coprimeDividesProductPropertyLabel]
item $ do
s [m g, "is the smallest", integer, "that does so"]
newline
let z = "z"
s ["Suppose there was an", integer, m z, "that divided both", m ab, and, m c]
let x = "x"
y = "y"
s ["That would mean that there exist integers", m x, and, m y]
ma $ z * x =: ab <> quad <> text and <> quad <> z * y =: c
let t = "t"
u = "u"
v = "v"
w = "w"
s ["According to", bezoutsLemma, ref bezoutsIdentityLemmaLabel <> ", there must exist", integers, csa [m t, m u, m v, m w], "as follows"]
ma $ g =: (pars $ t * a + u * c) * (pars $ v * b + w * c)
s ["Now observe the following"]
aligneqs g
[ t * a * v * b + t * a * w * c + u * c * v * b + u * c * w * c
, z * x * t * v + z * y * t * a * w + z * y * u * v * b + z * y * u * c * w
, z * (pars $ x * t * v + y * t * a * w + y * u * v * b + y * u * c * w)
]
s ["We conclude that", m z, divides, m g]
gcdMultiplicativeConsequence :: Note
gcdMultiplicativeConsequence = con $ do
lab gcdMultiplicativeConsequenceLabel
let a = "a"
b = "b"
c = "c"
bc = b * c
s ["Let", csa [m a, m b, m c], be, integers, "such that", m a, and, m b, are, coprime]
s [m a, and, m bc, are, coprime, "if and only if both", m a, and, m b <> ",", and, m a, and, m c, are, coprime]
proof $ do
s ["Proof of an equivalence"]
itemize $ do
item $ do
s ["If", m $ a `copr` bc, "holds, then", m $ gcd a c * gcd b c, "must be one", ref gcdMultiplicativePropertyLabel]
s ["Because they are", integers <> ", this means that both", m $ gcd a c, and, m $ gcd b c, "must be one and therefore, by definition,", m $ a `copr` c, and, m $ b `copr` c, "hold"]
item $ do
s ["If both", m $ a `copr` c, and, m $ b `copr` c, "hold, then the product of their", greatestCommonDivisors, "must be one and therefore", m a, and, m bc, coprime]
moduloS :: Note
moduloS = section "Modular arithmetic" $ do
oddEvenDefinition
modularIntegersDefinition
solutionOfLinearCongruenceTheorem
chineseRemainderTheoremPart
quadraticResidueDefinition
quadraticResidueExamples
quadraticResiduesInPrimeGroup
oneFourthQuadraticResidues
legendreSymbolDefinition
legendreSymbolExamples
eulerCriterionLegendreSymbol
jacobiSymbolDefinition
jacobiSymbolExamples
modularIntegersDefinition :: Note
modularIntegersDefinition = de $ do
let n = "n"
s [the, integers, "modulo an", integer, m n, "are defined as the following", quotientGroup]
ma $ intmod n === qgrp ints (n <> ints)
let a = "a"
b = "b"
q = "q"
s ["We say that an", integer, m a, is, congruent', with, "an", integer, m b, "modulo an", integer, m n, "if there exists an", integer, m q, "such that", m $ a =: b + q * n, "holds"]
ma $ eqmod n a b === te (q ∈ ints) (a =: b + q * n)
todo "fully formalize once we have a good chapter on groups"
oddEvenDefinition :: Note
oddEvenDefinition = de $ do
s ["An", integer, "is called", odd', "if it is", congruent, with, m 1, modulo, m 2]
s ["If it is instead", congruent, with, m 0, modulo, m 2 <> ", then we call it", even']
solutionOfLinearCongruenceTheorem :: Note
solutionOfLinearCongruenceTheorem = thm $ do
lab solutionOfLinearCongruenceTheoremLabel
let a = "a"
n = "n"
b = "b"
s ["Let", csa [m a, m b, m n], be, integers]
let x = "x"
s ["There exists an", integer, m x, "as follows if and only if", m $ gcd a n, divides, m b]
s [m b, "is unique if", m a, and, m n, are, coprime]
ma $ (pars $ gcd a n .| b) ⇔ (pars $ te (x ∈ ints) $ eqmod n (a * x) b)
proof $ do
s ["Proof of an equivalence"]
itemize $ do
item $ do
let y = "y"
s ["If", m $ gcd a n, divides, m b, "then there exists an", integer, m y, "as follows"]
ma $ gcd a n * y =: b
let p = "p"
q = "q"
s [bezoutsLemma, "tells us that there exist", integers, m p, and, m q, "as follows"]
ma $ gcd a n =: a * p + n * q
s ["If we substitute this in the above equation, we get the following"]
ma $ a * p * y + n * q * y =: b
s ["If we now look at the second term on the left-hand side, we see that it's divisible by", m n, "so it dissappears when viewed modulo", m n]
ma $ eqmod n (a * p * y) b
s ["We find that", m $ p * y, "is a valid candidate for", m x]
newline
let u = "u"
s ["Now, assume", m a, and, m n, are, coprime, and, m u, "is another such", integer, "solution"]
s ["If", m n, "equals", m 1 <> ", then", m x, "is trivially unique, because it's always zero"]
s ["Otherwise, note that", m a, "cannot be zero because then the", greatestCommonDivisor, "of", m a, and, m n, "would be", m n, "instead of", m 1]
ma $ eqmod n (a * x) (a * u)
s ["We divide out", m a, "which we're allowed to do because", m a, "is not zero"]
s ["We find that", m x, and, m u, "are equal and therefore", m x, "is unique"]
item $ do
s ["Let", m x, "be an", integer, "as follows"]
ma $ eqmod n (a * x) b
let f = "f"
s ["This means that there exists an", integer, m f, "as follows"]
ma $ a * x + f * n =: b
let p = "p"
q = "q"
g = gcd a n
s ["Now,", m $ gcd a n, divides, m a, and, m n, "so there exist", integers, m p, and, m q, "as follows"]
ma $ g * p =: a <> qquad <> text and <> qquad <> g * q =: n
s ["After substitution, we find the following"]
ma $ g * p * x + g * q * f =: b
s ["We conclude that", m g, divides, m b, with, quotient, m $ p * x + q * f]
chineseRemainderTheoremPart :: Note
chineseRemainderTheoremPart = thm $ do
lab chineseRemainderTheoremLabel
lab chineseRemainderTheoremDefinitionLabel
s [the, chineseRemainderTheorem']
newline
let n = "n"
k = "k"
a = "a"
(n1, n2, nk, ns) = buildList n k
(a1, a2, ak, as) = buildList a k
s ["Let", m ns, "be a list of", pairwiseCoprime, integers]
let x = "x"
s ["For any given list of", integers, m as <> ", there exists an", integer, m x, "as follows"]
ma $ centeredBelowEachOther $
[ eqmod n1 x a1
, eqmod n2 x a2
, vdots
, eqmod nk x ak
]
let i = "i"
let ni = n !: i
s ["Furthermore, the solution is unique modulo", m $ prodcmp i ni]
proof $ do
let nn = "N"
s ["Let", m nn, "be the product", m $ prodcmpr (i =: 1) k ni]
let nni = nn !: i
s ["Define", m nni, "as", m $ nn / nk]
newline
s ["Because the", integers, m ns, are, pairwiseCoprime <> ",", m nni, and, m ni, "are also", coprime, ref gcdMultiplicativeConsequenceLabel]
ma $ gcd nni ni =: 1
let x = "x"
xi = x !: i
s ["This means that the", linearCongruence, m $ eqmod nk (nni * xi) 1, "has some unique solution", m xi, ref solutionOfLinearCongruenceTheoremLabel]
let ai = a !: i
s ["Define", m $ x =: sumcmpr (i =: 1) k (ai * nni * xi)]
s ["We will now prove that", m x, "satisfies all the", linearCongruences]
s ["Let", m i, "therefore be arbitrary"]
let j = "j"
nj = n !: j
s ["Note first that for any", m j, "different from", m i <> ",", m nj, divides, m nni]
ma $ eqmod ni nj 0
s ["We find that the following holds"]
ma $ eqmod ni x (ai * nni * xi)
s ["Finally, because", m $ nni * xi, "was found to be congruent with", m 1, "modulo", m ni, "we find that", m x, "is congruent with", m ai]
newline
s ["Now we only have to prove that this solution is unique modulo", m n]
let y = "y"
s ["Suppose that", m y, "was another solution of the system"]
s ["This means that each", m ni, divides, m $ y - x, "but because each of the moduli are", coprime, "we find that also", m nn, divides, m $ y - x, ref coprimeDividesProductPropertyLabel]
s ["That is,", m y, and, m x, are, congruent, modulo, m nn]
quadraticResidueDefinition :: Note
quadraticResidueDefinition = de $ do
lab quadraticResidueDefinitionLabel
let n = "n"
x = "r"
y = "q"
s ["A", quadraticResidue', "modulo an", integer, m n, "is an", integer, m x, "such that there exists an", integer, m y, "as follows"]
ma $ eqmod n (y ^ 2) x
quadraticResidueExamples :: Note
quadraticResidueExamples = do
ex $ do
let n = "n"
s [m 0, and, m 1, "are always", quadraticResidues, "in", m $ intmod n, for, m $ n > 1, because, m $ eqmod n (0 ^ 2) 0, and, m $ eqmod n (1 ^ 2) 1]
ex $ do
s ["In", m (intmod 7) <> ",", m 2, "is a", quadraticResidue, because, m $ eqmod 7 (5 ^ 2) 2]
ex $ do
s ["In", m $ intmod 5, ", the", quadraticResidues, are, csa [m 0, m 1, m 4], because, csa [m $ eqmod 5 (0 ^ 2) 0, m $ eqmod 5 (1 ^ 2) 1, m $ eqmod 5 (2 ^ 2) 4]]
ex $ do
s ["In", m $ intmod 35, ", the", quadraticResidues, are, "the following", elements]
ma $ cs [0, 1, 4, 9, 11, 14, 15, 16, 21, 25, 29, 30]
ex $ do
s ["Here are the", quadraticResidues, "(different from", m 0, and, m 1 <> ") modulo some small", integers]
let rawn :: P.Int -> Note
rawn = raw . T.pack . show
let n = 20
newline
hereFigure $ linedTable
((raw "n\\setminus q") : P.map rawn [1 .. n])
( P.map (\i -> do
rawn i : (P.map (\j -> if j P.< (i P.+ 1) then (rawn $ j P.^ (2 :: P.Int) `P.mod` i) else mempty) [1 .. n])
) [0 .. n])
quadraticResiduesInPrimeGroup :: Note
quadraticResiduesInPrimeGroup = thm $ do
let p = "p"
a = "a"
s ["Let", m p, "be an", odd, prime, and, m a, "an", integer, "that is not", divisible, by, m p]
let g = "g"
s ["Let", m g, "be a", generator, "of", m $ intmgrp p]
let q = "q"
itemize $ do
item $ do
s [m a, "is a", quadraticResidue, modulo, m p, "if and only if there exists an", integer, m q, "such that", m $ eqmod p a (g ^ (2 * q)), "holds"]
item $ do
s [m a, "is not a", quadraticResidue, modulo, m p, "if and only if there exists an", integer, m q, "such that", m $ eqmod p a (g ^ (2 * q + 1)), "holds"]
proof $ do
s ["Because", m a, "is not", divisible, by, m p <> ",", m a, "is an", element, "of", m $ int0mod p]
itemize $ do
item $ do
let x = "x"
s ["Suppose", m a, "is a", quadraticResidue, modulo, m p, "then there exists an", integer, m x, "as follows"]
ma $ eqmod p (x^2) a
s [m x, "must then be an", element, "of", m $ int0mod p]
s ["Because", m g, "is a", generator, for, m (intmgrp p) <> ", there must exist an", integer, m q, "as follows"]
ma $ eqmod p x (g ^ q)
s ["This means that we have found the", m q, "that we were looking for"]
ma $ eqmod p a (g ^ (2 * q))
s ["The other direction is trivial"]
item $ do
toprove
oneFourthQuadraticResidues :: Note
oneFourthQuadraticResidues = thm $ do
let p = "p"
q = "q"
n = "n"
s ["Let", m p, and, m q, "be two", odd, primes, and, define, m $ n =: p * q]
s [m $ 1 / 4, "of the", elements, "in", m $ int0mod n, are, quadraticResidues, modulo, m n]
toprove
legendreSymbolDefinition :: Note
legendreSymbolDefinition = de $ do
let a = "a"
p = "p"
s ["Let", m a, "be an", integer, and, m p, "an", odd, prime]
s [the, legendreSymbol', "of", m a, over, m p, "is defined as follows"]
ma $ (leg a p ===) $ cases $ do
1 & text "if " <> m a <> text (" is a " <> quadraticResidue <> " " <> modulo <> " ") <> m p <> text " and " <> neg (p .| a)
lnbk
(-1) & text "if " <> m a <> text (" is not a " <> quadraticResidue <> " " <> modulo <> " ") <> m p
lnbk
0 & text "if " <> p .| a
legendreSymbolExamples :: Note
legendreSymbolExamples = do
ex $ do
s ["Note that", m $ 4 ^ 2 =: 16, and, m $ eqmod 11 16 5]
ma $ leg 5 11 =: 1
ex $ do
ma $ leg 6 11 =: -1
eulerCriterionLegendreSymbol :: Note
eulerCriterionLegendreSymbol = thm $ do
s [eulersCriterion', for, legendreSymbols]
let a = "a"
p = "p"
s ["Let", m a, "be an", integer, and, m p, "an", integer, odd, prime]
let l = leg a p
ap = a ^ ((p - 1) / 2)
ma $ eqmod p l ap
proof $ do
s ["We have to prove three cases:"]
itemize $ do
item $ do
s [m ap, is, m 0, modulo, m p, "if and only if", m $ leg a p, is, m 0]
newline
let n = "n"
s ["if", m p, divides, m a, "then there exists an", m n, "as follows"]
ma $ (n * p) ^ ((p - 1) / 2)
s ["This is clearly", divisible, by, m p, "and therefore the following holds"]
ma $ eqmod p ap 0
item $ do
s [m ap, is, m 1, modulo, m p, "if and only if", m a, "is a", quadraticResidue, modulo, m p]
newline
toprove
item $ do
s [m ap, is, m (-1), modulo, m p, "if and only if", m a, "is not a", quadraticResidue, modulo, m p]
newline
toprove
jacobiSymbolDefinition :: Note
jacobiSymbolDefinition = de $ do
let a = "a"
n = "n"
s ["Let", m a, "be an", integer, and, m n, "an", odd, naturalNumber, "with the following", primeFactorization]
let p = "p"
t = "t"
(p1, p2, pt, _) = buildList p t
v = "v"
(v1, v2, vt, _) = buildList v t
i = "i"
pi = p !: i
vi = v !: i
let (^) = (.^:)
ma $ n =: p1 ^ v1 * p2 ^ v2 * dotsb * pt ^ vt =: prodcmpr (i =: 1) t (pi ^ vi)
s [the, jacobiSymbol', "of", m a, over, m p, "is defined as follows"]
ma $ jac a n === (leg a p1) ^ v1 * (leg a p2) ^ v2 * dotsb * (leg a pt) ^ vt =: prodcmpr (i =: 1) t ((leg a pi) ^ vi)
jacobiSymbolExamples :: Note
jacobiSymbolExamples = do
let (^) = (.^:)
ex $ do
ma $ jac 5 9 =: jac 5 (3 ^ 2) =: (leg 5 3) ^ 2 =: 1
ex $ do
ma $ jac 5 12 =: jac 5 (3 * 2 ^ 2) =: (leg 5 3) * (leg 5 2) ^ 2 =: -1
|
e9c6537c97bb2de7c8116afcf4f0a1335f58fea933e0fed95de64c626fb3e6bb | racket/libs | info.rkt | #lang setup/infotab
SPDX - License - Identifier : ( Apache-2.0 OR MIT )
;; THIS FILE IS AUTO-GENERATED FROM racket/src/native-libs/install.rkt
(define collection 'multi)
(define deps '("base"))
(define pkg-desc "native libraries for \"base\" package")
(define pkg-authors '(mflatt))
(define version "1.2")
(define license '((Apache-2.0 OR MIT) AND (LGPL-3.0-or-later AND OpenSSL)))
| null | https://raw.githubusercontent.com/racket/libs/ebcea119197dc0cb86be1ccbbfbe5806f7280976/racket-win32-i386-3/info.rkt | racket | THIS FILE IS AUTO-GENERATED FROM racket/src/native-libs/install.rkt | #lang setup/infotab
SPDX - License - Identifier : ( Apache-2.0 OR MIT )
(define collection 'multi)
(define deps '("base"))
(define pkg-desc "native libraries for \"base\" package")
(define pkg-authors '(mflatt))
(define version "1.2")
(define license '((Apache-2.0 OR MIT) AND (LGPL-3.0-or-later AND OpenSSL)))
|
1cd58d6839a2490b09ad654ad3a8744b5e7c96edf8f18e212ac959e5930498a2 | jgm/texmath | Commands.hs | {-# LANGUAGE OverloadedStrings #-}
Copyright ( C ) 2009 - 2022 < >
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
Copyright (C) 2009-2022 John MacFarlane <>
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
-}
| Lookup tables for TeX commands .
-}
module Text.TeXMath.Readers.TeX.Commands
( styleOps
, textOps
, enclosures
, operators
, symbols
, siUnitMap
)
where
import qualified Data.Map as M
import Text.TeXMath.Types
import Text.TeXMath.Unicode.ToTeX (symbolMap)
import Data.Text (Text)
import Data.Ratio ((%))
Note : cal and scr are treated the same way , as unicode is lacking such two different sets for those .
styleOps :: M.Map Text ([Exp] -> Exp)
styleOps = M.fromList
[ ("\\mathrm", EStyled TextNormal)
, ("\\mathup", EStyled TextNormal)
, ("\\mathbf", EStyled TextBold)
, ("\\boldsymbol", EStyled TextBold)
, ("\\bm", EStyled TextBold)
, ("\\symbf", EStyled TextBold)
, ("\\mathbold", EStyled TextBold)
, ("\\pmb", EStyled TextBold)
, ("\\mathbfup", EStyled TextBold)
, ("\\mathit", EStyled TextItalic)
, ("\\mathtt", EStyled TextMonospace)
, ("\\texttt", EStyled TextMonospace)
, ("\\mathsf", EStyled TextSansSerif)
, ("\\mathsfup", EStyled TextSansSerif)
, ("\\mathbb", EStyled TextDoubleStruck)
mathds package
, ("\\mathcal", EStyled TextScript)
, ("\\mathscr", EStyled TextScript)
, ("\\mathfrak", EStyled TextFraktur)
, ("\\mathbfit", EStyled TextBoldItalic)
, ("\\mathbfsfup", EStyled TextSansSerifBold)
, ("\\mathbfsfit", EStyled TextSansSerifBoldItalic)
, ("\\mathbfscr", EStyled TextBoldScript)
, ("\\mathbffrak", EStyled TextBoldFraktur)
, ("\\mathbfcal", EStyled TextBoldScript)
, ("\\mathsfit", EStyled TextSansSerifItalic)
]
textOps :: M.Map Text (Text -> Exp)
textOps = M.fromList
[ ("\\textrm", (EText TextNormal))
, ("\\text", (EText TextNormal))
, ("\\textbf", (EText TextBold))
, ("\\textit", (EText TextItalic))
, ("\\texttt", (EText TextMonospace))
, ("\\textsf", (EText TextSansSerif))
, ("\\mbox", (EText TextNormal))
]
enclosures :: M.Map Text Exp
enclosures = M.fromList
[ ("(", ESymbol Open "(")
, (")", ESymbol Close ")")
, ("[", ESymbol Open "[")
, ("]", ESymbol Close "]")
, ("\\{", ESymbol Open "{")
, ("\\}", ESymbol Close "}")
, ("\\lbrack", ESymbol Open "[")
, ("\\lbrace", ESymbol Open "{")
, ("\\rbrack", ESymbol Close "]")
, ("\\rbrace", ESymbol Close "}")
, ("\\llbracket", ESymbol Open "\x27E6")
, ("\\rrbracket", ESymbol Close "\x27E7")
, ("\\langle", ESymbol Open "\x27E8")
, ("\\rangle", ESymbol Close "\x27E9")
, ("\\lfloor", ESymbol Open "\x230A")
, ("\\rfloor", ESymbol Close "\x230B")
, ("\\lceil", ESymbol Open "\x2308")
, ("\\rceil", ESymbol Close "\x2309")
, ("|", ESymbol Close "|")
, ("|", ESymbol Open "|")
, ("\\|", ESymbol Open "\x2225")
, ("\\|", ESymbol Close "\x2225")
, ("\\lvert", ESymbol Open "\x7C")
, ("\\rvert", ESymbol Close "\x7C")
, ("\\vert", ESymbol Close "\x7C")
, ("\\lVert", ESymbol Open "\x2225")
, ("\\rVert", ESymbol Close "\x2225")
, ("\\Vert", ESymbol Close "\x2016")
, ("\\ulcorner", ESymbol Open "\x231C")
, ("\\urcorner", ESymbol Close "\x231D")
]
operators :: M.Map Text Exp
operators = M.fromList [
("+", ESymbol Bin "+")
, ("-", ESymbol Bin "\x2212")
, ("*", ESymbol Bin "*")
, ("@", ESymbol Ord "@")
, (",", ESymbol Pun ",")
, (".", ESymbol Ord ".")
, (";", ESymbol Pun ";")
, (":", ESymbol Rel ":")
, ("?", ESymbol Ord "?")
, (">", ESymbol Rel ">")
, ("<", ESymbol Rel "<")
, ("!", ESymbol Ord "!")
, ("'", ESymbol Ord "\x2032")
, ("''", ESymbol Ord "\x2033")
, ("'''", ESymbol Ord "\x2034")
, ("''''", ESymbol Ord "\x2057")
, ("=", ESymbol Rel "=")
, (":=", ESymbol Rel ":=")
, ("/", ESymbol Ord "/")
, ("~", ESpace (4/18)) ]
symbols :: M.Map Text Exp
symbols = symbolMapOverrides <> symbolMap
-- These are the cases where texmath historically diverged
-- from symbolMap. We may want to remove some of these overrides,
-- but for now we keep them so behavior doesn't change.
symbolMapOverrides :: M.Map Text Exp
symbolMapOverrides = M.fromList
[ ("\\\n",ESpace (2 % 9))
, ("\\ ",ESpace (2 % 9))
, ("\\!",ESpace ((-1) % 6))
, ("\\,",ESpace (1 % 6))
, ("\\:",ESpace (2 % 9))
, ("\\;",ESpace (5 % 18))
, ("\\>",ESpace (2 % 9))
, ("\\AC",ESymbol Ord "\9190")
, ("\\Box",ESymbol Op "\9633")
, ("\\Delta",EIdentifier "\916")
, ("\\Diamond",ESymbol Op "\9671")
, ("\\Gamma",EIdentifier "\915")
, ("\\Im",ESymbol Ord "\8465")
, ("\\Join",ESymbol Rel "\8904")
, ("\\Lambda",EIdentifier "\923")
, ("\\Lbrbrak",ESymbol Open "\12312")
, ("\\Longleftarrow",ESymbol Rel "\8656")
, ("\\Longleftrightarrow",ESymbol Rel "\8660")
, ("\\Longrightarrow",ESymbol Rel "\8658")
, ("\\Omega",EIdentifier "\937")
, ("\\Phi",EIdentifier "\934")
, ("\\Pi",EIdentifier "\928")
, ("\\Pr",EMathOperator "Pr")
, ("\\Psi",EIdentifier "\936")
, ("\\Rbrbrak",ESymbol Close "\12313")
, ("\\Re",ESymbol Ord "\8476")
, ("\\Sigma",EIdentifier "\931")
, ("\\Theta",EIdentifier "\920")
, ("\\Upsilon",EIdentifier "\933")
, ("\\Xi",EIdentifier "\926")
, ("\\^",ESymbol Ord "^")
, ("\\alpha",EIdentifier "\945")
, ("\\amalg",ESymbol Bin "\8720")
, ("\\arccos",EMathOperator "arccos")
, ("\\arcsin",EMathOperator "arcsin")
, ("\\arctan",EMathOperator "arctan")
, ("\\arg",EMathOperator "arg")
, ("\\ast",ESymbol Bin "*")
, ("\\backslash",ESymbol Bin "\8726")
, ("\\bar",ESymbol Accent "\8254")
, ("\\barwedge",ESymbol Bin "\8965")
, ("\\beta",EIdentifier "\946")
, ("\\bigcirc",ESymbol Bin "\9675")
, ("\\blacklozenge",ESymbol Ord "\11047")
, ("\\blacksquare",ESymbol Ord "\9724")
, ("\\blacktriangleleft",ESymbol Bin "\9666")
, ("\\blacktriangleright",ESymbol Bin "\9656")
, ("\\cdot",ESymbol Bin "\8901")
, ("\\chi",EIdentifier "\967")
, ("\\cos",EMathOperator "cos")
, ("\\cosh",EMathOperator "cosh")
, ("\\cot",EMathOperator "cot")
, ("\\coth",EMathOperator "coth")
, ("\\csc",EMathOperator "csc")
, ("\\dag",ESymbol Bin "\8224")
, ("\\ddag",ESymbol Bin "\8225")
, ("\\deg",EMathOperator "deg")
, ("\\delta",EIdentifier "\948")
, ("\\det",EMathOperator "det")
, ("\\diamond",ESymbol Op "\8900")
, ("\\digamma",ESymbol Alpha "\989")
, ("\\dim",EMathOperator "dim")
, ("\\dots",ESymbol Ord "\8230")
, ("\\dotsb",ESymbol Ord "\8943")
, ("\\dotsc",ESymbol Ord "\8230")
, ("\\dotsi",ESymbol Ord "\8943")
, ("\\dotsm",ESymbol Ord "\8943")
, ("\\dotso",ESymbol Ord "\8230")
, ("\\emptyset",ESymbol Ord "\8709")
, ("\\epsilon",EIdentifier "\1013")
, ("\\eqcolon",ESymbol Rel "\8789")
, ("\\eta",EIdentifier "\951")
, ("\\exists",ESymbol Op "\8707")
, ("\\exp",EMathOperator "exp")
, ("\\forall",ESymbol Op "\8704")
, ("\\gamma",EIdentifier "\947")
, ("\\gcd",EMathOperator "gcd")
, ("\\geqslant",ESymbol Rel "\8805")
, ("\\gt",ESymbol Rel ">")
, ("\\hbar",ESymbol Ord "\8463")
, ("\\hdots",ESymbol Ord "\8230")
, ("\\hom",EMathOperator "hom")
, ("\\iff",ESymbol Rel "\8660")
, ("\\inf",EMathOperator "inf")
, ("\\iota",EIdentifier "\953")
, ("\\kappa",EIdentifier "\954")
, ("\\ker",EMathOperator "ker")
, ("\\lambda",EIdentifier "\955")
, ("\\lbrbrak",ESymbol Open "\12308")
, ("\\leqslant",ESymbol Rel "\8804")
, ("\\lg",EMathOperator "lg")
, ("\\lhd",ESymbol Bin "\8882")
, ("\\lim",EMathOperator "lim")
, ("\\liminf",EMathOperator "liminf")
, ("\\limsup",EMathOperator "limsup")
, ("\\llbracket",ESymbol Open "\12314")
, ("\\ln",EMathOperator "ln")
, ("\\log",EMathOperator "log")
, ("\\longleftarrow",ESymbol Rel "\8592")
, ("\\longleftrightarrow",ESymbol Rel "\8596")
, ("\\longmapsto",ESymbol Rel "\8614")
, ("\\longrightarrow",ESymbol Rel "\8594")
, ("\\lozenge",ESymbol Op "\9674")
, ("\\lt",ESymbol Rel "<")
, ("\\max",EMathOperator "max")
, ("\\mid",ESymbol Bin "\8739")
, ("\\min",EMathOperator "min")
, ("\\models",ESymbol Rel "\8872")
, ("\\mu",EIdentifier "\956")
, ("\\neg",ESymbol Op "\172")
, ("\\nu",EIdentifier "\957")
, ("\\omega",EIdentifier "\969")
, ("\\overbar",ESymbol Accent "\175")
, ("\\overline",ESymbol TOver "\175")
, ("\\overrightarrow",ESymbol Accent "\8407")
, ("\\perp",ESymbol Rel "\8869")
, ("\\phi",EIdentifier "\981")
, ("\\pi",EIdentifier "\960")
, ("\\preceq",ESymbol Rel "\8828")
, ("\\psi",EIdentifier "\968")
, ("\\qquad",ESpace (2 % 1))
, ("\\quad",ESpace (1 % 1))
, ("\\rbrbrak",ESymbol Close "\12309")
, ("\\rhd",ESymbol Bin "\8883")
, ("\\rho",EIdentifier "\961")
, ("\\rrbracket",ESymbol Close "\12315")
, ("\\sec",EMathOperator "sec")
, ("\\setminus",ESymbol Bin "\\")
, ("\\sigma",EIdentifier "\963")
, ("\\sim",ESymbol Rel "\8764")
, ("\\sin",EMathOperator "sin")
, ("\\sinh",EMathOperator "sinh")
, ("\\square",ESymbol Ord "\9643")
, ("\\succeq",ESymbol Rel "\8829")
, ("\\sup",EMathOperator "sup")
, ("\\tan",EMathOperator "tan")
, ("\\tanh",EMathOperator "tanh")
, ("\\tau",EIdentifier "\964")
, ("\\therefore",ESymbol Pun "\8756")
, ("\\theta",EIdentifier "\952")
, ("\\triangle",ESymbol Ord "\9651")
, ("\\triangleleft",ESymbol Bin "\8882")
, ("\\triangleright",ESymbol Bin "\8883")
, ("\\underbar",ESymbol TUnder "\817")
, ("\\underline",ESymbol TUnder "_")
, ("\\unlhd",ESymbol Bin "\8884")
, ("\\unrhd",ESymbol Bin "\8885")
, ("\\upUpsilon",ESymbol Alpha "\978")
, ("\\upsilon",EIdentifier "\965")
, ("\\varDelta",EIdentifier "\120549")
, ("\\varGamma",EIdentifier "\120548")
, ("\\varLambda",EIdentifier "\120556")
, ("\\varOmega",EIdentifier "\120570")
, ("\\varPhi",EIdentifier "\120567")
, ("\\varPi",EIdentifier "\120561")
, ("\\varPsi",EIdentifier "\120569")
, ("\\varSigma",EIdentifier "\120564")
, ("\\varTheta",EIdentifier "\120553")
, ("\\varUpsilon",EIdentifier "\120566")
, ("\\varXi",EIdentifier "\120559")
, ("\\varepsilon",EIdentifier "\949")
, ("\\varnothing",ESymbol Ord "\8960")
, ("\\varphi",EIdentifier "\966")
, ("\\varrho",ESymbol Alpha "\120602")
, ("\\varsigma",ESymbol Alpha "\120589")
, ("\\vartheta",EIdentifier "\977")
, ("\\vdots",ESymbol Ord "\8942")
, ("\\vec",ESymbol Accent "\8407")
, ("\\wp",ESymbol Ord "\8472")
, ("\\wr",ESymbol Ord "\8768")
, ("\\xi",EIdentifier "\958")
, ("\\zeta",EIdentifier "\950")
]
siUnitMap :: M.Map Text Exp
siUnitMap = M.fromList
[ ("fg", str "fg")
, ("pg", str "pg")
, ("ng", str "ng")
, ("ug", str "μg")
, ("mg", str "mg")
, ("g", str "g")
, ("kg", str "kg")
, ("amu", str "u")
, ("pm", str "pm")
, ("nm", str "nm")
, ("um", str "μm")
, ("mm", str "mm")
, ("cm", str "cm")
, ("dm", str "dm")
, ("m", str "m")
, ("km", str "km")
, ("as", str "as")
, ("fs", str "fs")
, ("ps", str "ps")
, ("ns", str "ns")
, ("us", str "μs")
, ("ms", str "ms")
, ("s", str "s")
, ("fmol", str "fmol")
, ("pmol", str "pmol")
, ("nmol", str "nmol")
, ("umol", str "μmol")
, ("mmol", str "mmol")
, ("mol", str "mol")
, ("kmol", str "kmol")
, ("pA", str "pA")
, ("nA", str "nA")
, ("uA", str "μA")
, ("mA", str "mA")
, ("A", str "A")
, ("kA", str "kA")
, ("ul", str "μl")
, ("ml", str "ml")
, ("l", str "l")
, ("hl", str "hl")
, ("uL", str "μL")
, ("mL", str "mL")
, ("L", str "L")
, ("hL", str "hL")
, ("mHz", str "mHz")
, ("Hz", str "Hz")
, ("kHz", str "kHz")
, ("MHz", str "MHz")
, ("GHz", str "GHz")
, ("THz", str "THz")
, ("mN", str "mN")
, ("N", str "N")
, ("kN", str "kN")
, ("MN", str "MN")
, ("Pa", str "Pa")
, ("kPa", str "kPa")
, ("MPa", str "MPa")
, ("GPa", str "GPa")
, ("mohm", str "mΩ")
, ("kohm", str "kΩ")
, ("Mohm", str "MΩ")
, ("pV", str "pV")
, ("nV", str "nV")
, ("uV", str "μV")
, ("mV", str "mV")
, ("V", str "V")
, ("kV", str "kV")
, ("W", str "W")
, ("uW", str "μW")
, ("mW", str "mW")
, ("kW", str "kW")
, ("MW", str "MW")
, ("GW", str "GW")
, ("J", str "J")
, ("uJ", str "μJ")
, ("mJ", str "mJ")
, ("kJ", str "kJ")
, ("eV", str "eV")
, ("meV", str "meV")
, ("keV", str "keV")
, ("MeV", str "MeV")
, ("GeV", str "GeV")
, ("TeV", str "TeV")
, ("kWh", str "kWh")
, ("F", str "F")
, ("fF", str "fF")
, ("pF", str "pF")
, ("K", str "K")
, ("dB", str "dB")
, ("ampere", str "A")
, ("angstrom", str "Å")
, ("arcmin", str "′")
, ("arcminute", str "′")
, ("arcsecond", str "″")
, ("astronomicalunit", str "ua")
, ("atomicmassunit", str "u")
, ("atto", str "a")
, ("bar", str "bar")
, ("barn", str "b")
, ("becquerel", str "Bq")
, ("bel", str "B")
, ("bohr", ESuper (EText TextItalic "a") (ENumber "0"))
, ("candela", str "cd")
, ("celsius", str "°C")
, ("centi", str "c")
, ("clight", ESuper (EText TextItalic "c") (ENumber "0"))
, ("coulomb", str "C")
, ("dalton", str "Da")
, ("day", str "d")
, ("deca", str "d")
, ("deci", str "d")
, ("decibel", str "db")
, ("degreeCelsius",str "°C")
, ("degree", str "°")
, ("deka", str "d")
, ("electronmass", ESuper (EText TextItalic "m") (EText TextItalic "e"))
, ("electronvolt", str "eV")
, ("elementarycharge", EText TextItalic "e")
, ("exa", str "E")
, ("farad", str "F")
, ("femto", str "f")
, ("giga", str "G")
, ("gram", str "g")
, ("gray", str "Gy")
, ("hartree", ESuper (EText TextItalic "E") (EText TextItalic "h"))
, ("hectare", str "ha")
, ("hecto", str "h")
, ("henry", str "H")
, ("hertz", str "Hz")
, ("hour", str "h")
, ("joule", str "J")
, ("katal", str "kat")
, ("kelvin", str "K")
, ("kilo", str "k")
, ("kilogram", str "kg")
, ("knot", str "kn")
, ("liter", str "L")
, ("litre", str "l")
, ("lumen", str "lm")
, ("lux", str "lx")
, ("mega", str "M")
, ("meter", str "m")
, ("metre", str "m")
, ("micro", str "μ")
, ("milli", str "m")
, ("minute", str "min")
, ("mmHg", str "mmHg")
, ("mole", str "mol")
, ("nano", str "n")
, ("nauticalmile", str "M")
, ("neper", str "Np")
, ("newton", str "N")
, ("ohm", str "Ω")
, ("Pa", str "Pa")
, ("pascal", str "Pa")
, ("percent", str "%")
, ("per", str "/")
, ("peta", str "P")
, ("pico", str "p")
, ("planckbar", EText TextItalic "\x210f")
, ("radian", str "rad")
, ("second", str "s")
, ("siemens", str "S")
, ("sievert", str "Sv")
, ("steradian", str "sr")
, ("tera", str "T")
, ("tesla", str "T")
, ("tonne", str "t")
, ("volt", str "V")
, ("watt", str "W")
, ("weber", str "Wb")
, ("yocto", str "y")
, ("yotta", str "Y")
, ("zepto", str "z")
, ("zetta", str "Z")
]
where
str = EText TextNormal
| null | https://raw.githubusercontent.com/jgm/texmath/df209eb0e390518dae407d9b2a4984782be2fb1f/src/Text/TeXMath/Readers/TeX/Commands.hs | haskell | # LANGUAGE OverloadedStrings #
These are the cases where texmath historically diverged
from symbolMap. We may want to remove some of these overrides,
but for now we keep them so behavior doesn't change. |
Copyright ( C ) 2009 - 2022 < >
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
Copyright (C) 2009-2022 John MacFarlane <>
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
-}
| Lookup tables for TeX commands .
-}
module Text.TeXMath.Readers.TeX.Commands
( styleOps
, textOps
, enclosures
, operators
, symbols
, siUnitMap
)
where
import qualified Data.Map as M
import Text.TeXMath.Types
import Text.TeXMath.Unicode.ToTeX (symbolMap)
import Data.Text (Text)
import Data.Ratio ((%))
Note : cal and scr are treated the same way , as unicode is lacking such two different sets for those .
styleOps :: M.Map Text ([Exp] -> Exp)
styleOps = M.fromList
[ ("\\mathrm", EStyled TextNormal)
, ("\\mathup", EStyled TextNormal)
, ("\\mathbf", EStyled TextBold)
, ("\\boldsymbol", EStyled TextBold)
, ("\\bm", EStyled TextBold)
, ("\\symbf", EStyled TextBold)
, ("\\mathbold", EStyled TextBold)
, ("\\pmb", EStyled TextBold)
, ("\\mathbfup", EStyled TextBold)
, ("\\mathit", EStyled TextItalic)
, ("\\mathtt", EStyled TextMonospace)
, ("\\texttt", EStyled TextMonospace)
, ("\\mathsf", EStyled TextSansSerif)
, ("\\mathsfup", EStyled TextSansSerif)
, ("\\mathbb", EStyled TextDoubleStruck)
mathds package
, ("\\mathcal", EStyled TextScript)
, ("\\mathscr", EStyled TextScript)
, ("\\mathfrak", EStyled TextFraktur)
, ("\\mathbfit", EStyled TextBoldItalic)
, ("\\mathbfsfup", EStyled TextSansSerifBold)
, ("\\mathbfsfit", EStyled TextSansSerifBoldItalic)
, ("\\mathbfscr", EStyled TextBoldScript)
, ("\\mathbffrak", EStyled TextBoldFraktur)
, ("\\mathbfcal", EStyled TextBoldScript)
, ("\\mathsfit", EStyled TextSansSerifItalic)
]
textOps :: M.Map Text (Text -> Exp)
textOps = M.fromList
[ ("\\textrm", (EText TextNormal))
, ("\\text", (EText TextNormal))
, ("\\textbf", (EText TextBold))
, ("\\textit", (EText TextItalic))
, ("\\texttt", (EText TextMonospace))
, ("\\textsf", (EText TextSansSerif))
, ("\\mbox", (EText TextNormal))
]
enclosures :: M.Map Text Exp
enclosures = M.fromList
[ ("(", ESymbol Open "(")
, (")", ESymbol Close ")")
, ("[", ESymbol Open "[")
, ("]", ESymbol Close "]")
, ("\\{", ESymbol Open "{")
, ("\\}", ESymbol Close "}")
, ("\\lbrack", ESymbol Open "[")
, ("\\lbrace", ESymbol Open "{")
, ("\\rbrack", ESymbol Close "]")
, ("\\rbrace", ESymbol Close "}")
, ("\\llbracket", ESymbol Open "\x27E6")
, ("\\rrbracket", ESymbol Close "\x27E7")
, ("\\langle", ESymbol Open "\x27E8")
, ("\\rangle", ESymbol Close "\x27E9")
, ("\\lfloor", ESymbol Open "\x230A")
, ("\\rfloor", ESymbol Close "\x230B")
, ("\\lceil", ESymbol Open "\x2308")
, ("\\rceil", ESymbol Close "\x2309")
, ("|", ESymbol Close "|")
, ("|", ESymbol Open "|")
, ("\\|", ESymbol Open "\x2225")
, ("\\|", ESymbol Close "\x2225")
, ("\\lvert", ESymbol Open "\x7C")
, ("\\rvert", ESymbol Close "\x7C")
, ("\\vert", ESymbol Close "\x7C")
, ("\\lVert", ESymbol Open "\x2225")
, ("\\rVert", ESymbol Close "\x2225")
, ("\\Vert", ESymbol Close "\x2016")
, ("\\ulcorner", ESymbol Open "\x231C")
, ("\\urcorner", ESymbol Close "\x231D")
]
operators :: M.Map Text Exp
operators = M.fromList [
("+", ESymbol Bin "+")
, ("-", ESymbol Bin "\x2212")
, ("*", ESymbol Bin "*")
, ("@", ESymbol Ord "@")
, (",", ESymbol Pun ",")
, (".", ESymbol Ord ".")
, (";", ESymbol Pun ";")
, (":", ESymbol Rel ":")
, ("?", ESymbol Ord "?")
, (">", ESymbol Rel ">")
, ("<", ESymbol Rel "<")
, ("!", ESymbol Ord "!")
, ("'", ESymbol Ord "\x2032")
, ("''", ESymbol Ord "\x2033")
, ("'''", ESymbol Ord "\x2034")
, ("''''", ESymbol Ord "\x2057")
, ("=", ESymbol Rel "=")
, (":=", ESymbol Rel ":=")
, ("/", ESymbol Ord "/")
, ("~", ESpace (4/18)) ]
symbols :: M.Map Text Exp
symbols = symbolMapOverrides <> symbolMap
symbolMapOverrides :: M.Map Text Exp
symbolMapOverrides = M.fromList
[ ("\\\n",ESpace (2 % 9))
, ("\\ ",ESpace (2 % 9))
, ("\\!",ESpace ((-1) % 6))
, ("\\,",ESpace (1 % 6))
, ("\\:",ESpace (2 % 9))
, ("\\;",ESpace (5 % 18))
, ("\\>",ESpace (2 % 9))
, ("\\AC",ESymbol Ord "\9190")
, ("\\Box",ESymbol Op "\9633")
, ("\\Delta",EIdentifier "\916")
, ("\\Diamond",ESymbol Op "\9671")
, ("\\Gamma",EIdentifier "\915")
, ("\\Im",ESymbol Ord "\8465")
, ("\\Join",ESymbol Rel "\8904")
, ("\\Lambda",EIdentifier "\923")
, ("\\Lbrbrak",ESymbol Open "\12312")
, ("\\Longleftarrow",ESymbol Rel "\8656")
, ("\\Longleftrightarrow",ESymbol Rel "\8660")
, ("\\Longrightarrow",ESymbol Rel "\8658")
, ("\\Omega",EIdentifier "\937")
, ("\\Phi",EIdentifier "\934")
, ("\\Pi",EIdentifier "\928")
, ("\\Pr",EMathOperator "Pr")
, ("\\Psi",EIdentifier "\936")
, ("\\Rbrbrak",ESymbol Close "\12313")
, ("\\Re",ESymbol Ord "\8476")
, ("\\Sigma",EIdentifier "\931")
, ("\\Theta",EIdentifier "\920")
, ("\\Upsilon",EIdentifier "\933")
, ("\\Xi",EIdentifier "\926")
, ("\\^",ESymbol Ord "^")
, ("\\alpha",EIdentifier "\945")
, ("\\amalg",ESymbol Bin "\8720")
, ("\\arccos",EMathOperator "arccos")
, ("\\arcsin",EMathOperator "arcsin")
, ("\\arctan",EMathOperator "arctan")
, ("\\arg",EMathOperator "arg")
, ("\\ast",ESymbol Bin "*")
, ("\\backslash",ESymbol Bin "\8726")
, ("\\bar",ESymbol Accent "\8254")
, ("\\barwedge",ESymbol Bin "\8965")
, ("\\beta",EIdentifier "\946")
, ("\\bigcirc",ESymbol Bin "\9675")
, ("\\blacklozenge",ESymbol Ord "\11047")
, ("\\blacksquare",ESymbol Ord "\9724")
, ("\\blacktriangleleft",ESymbol Bin "\9666")
, ("\\blacktriangleright",ESymbol Bin "\9656")
, ("\\cdot",ESymbol Bin "\8901")
, ("\\chi",EIdentifier "\967")
, ("\\cos",EMathOperator "cos")
, ("\\cosh",EMathOperator "cosh")
, ("\\cot",EMathOperator "cot")
, ("\\coth",EMathOperator "coth")
, ("\\csc",EMathOperator "csc")
, ("\\dag",ESymbol Bin "\8224")
, ("\\ddag",ESymbol Bin "\8225")
, ("\\deg",EMathOperator "deg")
, ("\\delta",EIdentifier "\948")
, ("\\det",EMathOperator "det")
, ("\\diamond",ESymbol Op "\8900")
, ("\\digamma",ESymbol Alpha "\989")
, ("\\dim",EMathOperator "dim")
, ("\\dots",ESymbol Ord "\8230")
, ("\\dotsb",ESymbol Ord "\8943")
, ("\\dotsc",ESymbol Ord "\8230")
, ("\\dotsi",ESymbol Ord "\8943")
, ("\\dotsm",ESymbol Ord "\8943")
, ("\\dotso",ESymbol Ord "\8230")
, ("\\emptyset",ESymbol Ord "\8709")
, ("\\epsilon",EIdentifier "\1013")
, ("\\eqcolon",ESymbol Rel "\8789")
, ("\\eta",EIdentifier "\951")
, ("\\exists",ESymbol Op "\8707")
, ("\\exp",EMathOperator "exp")
, ("\\forall",ESymbol Op "\8704")
, ("\\gamma",EIdentifier "\947")
, ("\\gcd",EMathOperator "gcd")
, ("\\geqslant",ESymbol Rel "\8805")
, ("\\gt",ESymbol Rel ">")
, ("\\hbar",ESymbol Ord "\8463")
, ("\\hdots",ESymbol Ord "\8230")
, ("\\hom",EMathOperator "hom")
, ("\\iff",ESymbol Rel "\8660")
, ("\\inf",EMathOperator "inf")
, ("\\iota",EIdentifier "\953")
, ("\\kappa",EIdentifier "\954")
, ("\\ker",EMathOperator "ker")
, ("\\lambda",EIdentifier "\955")
, ("\\lbrbrak",ESymbol Open "\12308")
, ("\\leqslant",ESymbol Rel "\8804")
, ("\\lg",EMathOperator "lg")
, ("\\lhd",ESymbol Bin "\8882")
, ("\\lim",EMathOperator "lim")
, ("\\liminf",EMathOperator "liminf")
, ("\\limsup",EMathOperator "limsup")
, ("\\llbracket",ESymbol Open "\12314")
, ("\\ln",EMathOperator "ln")
, ("\\log",EMathOperator "log")
, ("\\longleftarrow",ESymbol Rel "\8592")
, ("\\longleftrightarrow",ESymbol Rel "\8596")
, ("\\longmapsto",ESymbol Rel "\8614")
, ("\\longrightarrow",ESymbol Rel "\8594")
, ("\\lozenge",ESymbol Op "\9674")
, ("\\lt",ESymbol Rel "<")
, ("\\max",EMathOperator "max")
, ("\\mid",ESymbol Bin "\8739")
, ("\\min",EMathOperator "min")
, ("\\models",ESymbol Rel "\8872")
, ("\\mu",EIdentifier "\956")
, ("\\neg",ESymbol Op "\172")
, ("\\nu",EIdentifier "\957")
, ("\\omega",EIdentifier "\969")
, ("\\overbar",ESymbol Accent "\175")
, ("\\overline",ESymbol TOver "\175")
, ("\\overrightarrow",ESymbol Accent "\8407")
, ("\\perp",ESymbol Rel "\8869")
, ("\\phi",EIdentifier "\981")
, ("\\pi",EIdentifier "\960")
, ("\\preceq",ESymbol Rel "\8828")
, ("\\psi",EIdentifier "\968")
, ("\\qquad",ESpace (2 % 1))
, ("\\quad",ESpace (1 % 1))
, ("\\rbrbrak",ESymbol Close "\12309")
, ("\\rhd",ESymbol Bin "\8883")
, ("\\rho",EIdentifier "\961")
, ("\\rrbracket",ESymbol Close "\12315")
, ("\\sec",EMathOperator "sec")
, ("\\setminus",ESymbol Bin "\\")
, ("\\sigma",EIdentifier "\963")
, ("\\sim",ESymbol Rel "\8764")
, ("\\sin",EMathOperator "sin")
, ("\\sinh",EMathOperator "sinh")
, ("\\square",ESymbol Ord "\9643")
, ("\\succeq",ESymbol Rel "\8829")
, ("\\sup",EMathOperator "sup")
, ("\\tan",EMathOperator "tan")
, ("\\tanh",EMathOperator "tanh")
, ("\\tau",EIdentifier "\964")
, ("\\therefore",ESymbol Pun "\8756")
, ("\\theta",EIdentifier "\952")
, ("\\triangle",ESymbol Ord "\9651")
, ("\\triangleleft",ESymbol Bin "\8882")
, ("\\triangleright",ESymbol Bin "\8883")
, ("\\underbar",ESymbol TUnder "\817")
, ("\\underline",ESymbol TUnder "_")
, ("\\unlhd",ESymbol Bin "\8884")
, ("\\unrhd",ESymbol Bin "\8885")
, ("\\upUpsilon",ESymbol Alpha "\978")
, ("\\upsilon",EIdentifier "\965")
, ("\\varDelta",EIdentifier "\120549")
, ("\\varGamma",EIdentifier "\120548")
, ("\\varLambda",EIdentifier "\120556")
, ("\\varOmega",EIdentifier "\120570")
, ("\\varPhi",EIdentifier "\120567")
, ("\\varPi",EIdentifier "\120561")
, ("\\varPsi",EIdentifier "\120569")
, ("\\varSigma",EIdentifier "\120564")
, ("\\varTheta",EIdentifier "\120553")
, ("\\varUpsilon",EIdentifier "\120566")
, ("\\varXi",EIdentifier "\120559")
, ("\\varepsilon",EIdentifier "\949")
, ("\\varnothing",ESymbol Ord "\8960")
, ("\\varphi",EIdentifier "\966")
, ("\\varrho",ESymbol Alpha "\120602")
, ("\\varsigma",ESymbol Alpha "\120589")
, ("\\vartheta",EIdentifier "\977")
, ("\\vdots",ESymbol Ord "\8942")
, ("\\vec",ESymbol Accent "\8407")
, ("\\wp",ESymbol Ord "\8472")
, ("\\wr",ESymbol Ord "\8768")
, ("\\xi",EIdentifier "\958")
, ("\\zeta",EIdentifier "\950")
]
siUnitMap :: M.Map Text Exp
siUnitMap = M.fromList
[ ("fg", str "fg")
, ("pg", str "pg")
, ("ng", str "ng")
, ("ug", str "μg")
, ("mg", str "mg")
, ("g", str "g")
, ("kg", str "kg")
, ("amu", str "u")
, ("pm", str "pm")
, ("nm", str "nm")
, ("um", str "μm")
, ("mm", str "mm")
, ("cm", str "cm")
, ("dm", str "dm")
, ("m", str "m")
, ("km", str "km")
, ("as", str "as")
, ("fs", str "fs")
, ("ps", str "ps")
, ("ns", str "ns")
, ("us", str "μs")
, ("ms", str "ms")
, ("s", str "s")
, ("fmol", str "fmol")
, ("pmol", str "pmol")
, ("nmol", str "nmol")
, ("umol", str "μmol")
, ("mmol", str "mmol")
, ("mol", str "mol")
, ("kmol", str "kmol")
, ("pA", str "pA")
, ("nA", str "nA")
, ("uA", str "μA")
, ("mA", str "mA")
, ("A", str "A")
, ("kA", str "kA")
, ("ul", str "μl")
, ("ml", str "ml")
, ("l", str "l")
, ("hl", str "hl")
, ("uL", str "μL")
, ("mL", str "mL")
, ("L", str "L")
, ("hL", str "hL")
, ("mHz", str "mHz")
, ("Hz", str "Hz")
, ("kHz", str "kHz")
, ("MHz", str "MHz")
, ("GHz", str "GHz")
, ("THz", str "THz")
, ("mN", str "mN")
, ("N", str "N")
, ("kN", str "kN")
, ("MN", str "MN")
, ("Pa", str "Pa")
, ("kPa", str "kPa")
, ("MPa", str "MPa")
, ("GPa", str "GPa")
, ("mohm", str "mΩ")
, ("kohm", str "kΩ")
, ("Mohm", str "MΩ")
, ("pV", str "pV")
, ("nV", str "nV")
, ("uV", str "μV")
, ("mV", str "mV")
, ("V", str "V")
, ("kV", str "kV")
, ("W", str "W")
, ("uW", str "μW")
, ("mW", str "mW")
, ("kW", str "kW")
, ("MW", str "MW")
, ("GW", str "GW")
, ("J", str "J")
, ("uJ", str "μJ")
, ("mJ", str "mJ")
, ("kJ", str "kJ")
, ("eV", str "eV")
, ("meV", str "meV")
, ("keV", str "keV")
, ("MeV", str "MeV")
, ("GeV", str "GeV")
, ("TeV", str "TeV")
, ("kWh", str "kWh")
, ("F", str "F")
, ("fF", str "fF")
, ("pF", str "pF")
, ("K", str "K")
, ("dB", str "dB")
, ("ampere", str "A")
, ("angstrom", str "Å")
, ("arcmin", str "′")
, ("arcminute", str "′")
, ("arcsecond", str "″")
, ("astronomicalunit", str "ua")
, ("atomicmassunit", str "u")
, ("atto", str "a")
, ("bar", str "bar")
, ("barn", str "b")
, ("becquerel", str "Bq")
, ("bel", str "B")
, ("bohr", ESuper (EText TextItalic "a") (ENumber "0"))
, ("candela", str "cd")
, ("celsius", str "°C")
, ("centi", str "c")
, ("clight", ESuper (EText TextItalic "c") (ENumber "0"))
, ("coulomb", str "C")
, ("dalton", str "Da")
, ("day", str "d")
, ("deca", str "d")
, ("deci", str "d")
, ("decibel", str "db")
, ("degreeCelsius",str "°C")
, ("degree", str "°")
, ("deka", str "d")
, ("electronmass", ESuper (EText TextItalic "m") (EText TextItalic "e"))
, ("electronvolt", str "eV")
, ("elementarycharge", EText TextItalic "e")
, ("exa", str "E")
, ("farad", str "F")
, ("femto", str "f")
, ("giga", str "G")
, ("gram", str "g")
, ("gray", str "Gy")
, ("hartree", ESuper (EText TextItalic "E") (EText TextItalic "h"))
, ("hectare", str "ha")
, ("hecto", str "h")
, ("henry", str "H")
, ("hertz", str "Hz")
, ("hour", str "h")
, ("joule", str "J")
, ("katal", str "kat")
, ("kelvin", str "K")
, ("kilo", str "k")
, ("kilogram", str "kg")
, ("knot", str "kn")
, ("liter", str "L")
, ("litre", str "l")
, ("lumen", str "lm")
, ("lux", str "lx")
, ("mega", str "M")
, ("meter", str "m")
, ("metre", str "m")
, ("micro", str "μ")
, ("milli", str "m")
, ("minute", str "min")
, ("mmHg", str "mmHg")
, ("mole", str "mol")
, ("nano", str "n")
, ("nauticalmile", str "M")
, ("neper", str "Np")
, ("newton", str "N")
, ("ohm", str "Ω")
, ("Pa", str "Pa")
, ("pascal", str "Pa")
, ("percent", str "%")
, ("per", str "/")
, ("peta", str "P")
, ("pico", str "p")
, ("planckbar", EText TextItalic "\x210f")
, ("radian", str "rad")
, ("second", str "s")
, ("siemens", str "S")
, ("sievert", str "Sv")
, ("steradian", str "sr")
, ("tera", str "T")
, ("tesla", str "T")
, ("tonne", str "t")
, ("volt", str "V")
, ("watt", str "W")
, ("weber", str "Wb")
, ("yocto", str "y")
, ("yotta", str "Y")
, ("zepto", str "z")
, ("zetta", str "Z")
]
where
str = EText TextNormal
|
5fc8a5031201b3b575f21f84ed5feb1ed5b67f94347df3ae68a5600ca85c770d | stritzinger/opcua | codec_binary_tests.erl | -module(codec_binary_tests).
-include_lib("eunit/include/eunit.hrl").
-include("opcua.hrl").
-include("opcua_internal.hrl").
t_test_() ->
{setup,
fun setup/0,
fun cleanup/1,
[
fun open_secure_channel_request/0,
fun open_secure_channel_response/0,
fun create_session_request/0,
fun create_session_response/0,
fun activate_session_request/0,
fun activate_session_request2/0,
fun activate_session_response/0,
fun read_request/0,
fun read_response/0,
fun browse_request/0,
fun browse_response/0
]}.
setup() ->
{ok, Apps} = application:ensure_all_started(opcua),
Apps.
cleanup(Apps) ->
opcua_test_util:without_error_logger(fun() ->
[ok = application:stop(A) || A <- Apps]
end).
%% This little helper does the major testing:
%%
1 . encode some data according to a NodeId
2 . decode the result again and check if it
%% matches the original data
3 . decode another example from the python
%% implementation which encoded the same
%% data and check if the data matches
%% again (hex dumps are from wireshark)
%%
%% Why not compare the encoded binaries
directly ? Because NodeIds can be encoded
%% in different ways and hence you can get
%% binaries holding the same data even though
%% the binaries are not the same!
assert_codec(NodeId, ToBeEncoded, EncodedComp) ->
{Encoded, _} = opcua_codec_binary:encode(NodeId, ToBeEncoded),
{Decoded, EmptyBin} = opcua_codec_binary:decode(NodeId, Encoded),
?assertEqual(<<>>, EmptyBin),
?assertEqual(ToBeEncoded, Decoded),
BinEncodedComp = opcua_util:hex_to_bin(EncodedComp),
{DecodedComp, EmptyBin1} = opcua_codec_binary:decode(NodeId, BinEncodedComp),
?assertEqual(<<>>, EmptyBin1),
?assertEqual(ToBeEncoded, DecodedComp).
open_secure_channel_request() ->
NodeId = #opcua_node_id{value = 444},
ToBeEncoded = #{
request_header => #{
authentication_token => #opcua_node_id{value = 0},
timestamp => 132061913263422630,
request_handle => 1,
return_diagnostics => 0,
audit_entry_id => undefined,
timeout_hint => 1000,
additional_header => #opcua_extension_object{}
},
client_protocol_version => 0,
request_type => issue,
security_mode => none,
client_nonce => <<>>,
requested_lifetime => 3600000
},
Encoded = "0000a6bc6c449c2dd5010100000000000000ffff"
"ffffe80300000000000000000000000000010000"
"000000000080ee3600",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
open_secure_channel_response() ->
NodeId = #opcua_node_id{value = 447},
ToBeEncoded = #{
response_header => #{
timestamp => 132061913263430080,
request_handle => 1,
service_result => good,
service_diagnostics => #opcua_diagnostic_info{},
string_table => [],
additional_header => #opcua_extension_object{}
},
server_protocol_version => 0,
security_token => #{
channel_id => 6,
token_id => 14,
created_at => 132061913263429970,
revised_lifetime => 3600000
},
server_nonce => <<>>
},
Encoded = "c0d96c449c2dd501010000000000000000000000"
"0000000000000000060000000e00000052d96c44"
"9c2dd50180ee360000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
create_session_request() ->
NodeId = #opcua_node_id{value = 459},
ToBeEncoded = #{
client_certificate => undefined,
client_description => #{
application_name => #opcua_localized_text{text = <<"Pure Python Client">>},
application_type => client,
application_uri => <<"urn:freeopcua:client">>,
discovery_profile_uri => undefined,
discovery_urls => [],
gateway_server_uri => undefined,
product_uri => <<"urn:freeopcua.github.io:client">>
},
client_nonce => opcua_util:hex_to_bin("dcb709b91898921af025"
"dabacbfdcfaa4891d0cd"
"9fe09a3addb2e094db40"
"48dc"),
endpoint_url => <<"opc.tcp:4840">>,
max_response_message_size => 0,
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{},
request_handle => 2,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263439110
},
requested_session_timeout => 3600000.0,
server_uri => undefined,
session_name => <<"Pure Python Client Session1">>
},
Encoded = "000006fd6c449c2dd5010200000000000000ffff"
"ffffe80300000000001400000075726e3a667265"
"656f706375613a636c69656e741e00000075726e"
"3a667265656f706375612e6769746875622e696f"
"3a636c69656e7402120000005075726520507974"
"686f6e20436c69656e7401000000ffffffffffff"
"ffff00000000ffffffff180000006f70632e7463"
"703a2f2f6c6f63616c686f73743a343834301b00"
"00005075726520507974686f6e20436c69656e74"
"2053657373696f6e3120000000dcb709b9189892"
"1af025dabacbfdcfaa4891d0cd9fe09a3addb2e0"
"94db4048dcffffffff0000000040774b41000000"
"00",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
create_session_response() ->
NodeId = #opcua_node_id{value = 462},
ToBeEncoded = #{
authentication_token => #opcua_node_id{value = 1001},
max_request_message_size => 65536,
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 2,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263448480
},
revised_session_timeout => 3600000.0,
server_certificate => undefined,
server_endpoints => [#{
endpoint_url => <<"opc.tcp:4840/freeopcua/server/">>,
security_level => 0,
security_mode => none,
security_policy_uri => <<"#None">>,
server => #{
application_name => #opcua_localized_text{text = <<"FreeOpcUa Python Server">>},
application_type => client_and_server,
application_uri => <<"urn:freeopcua:python:server">>,
discovery_profile_uri => undefined,
discovery_urls => [<<"opc.tcp:4840/freeopcua/server/">>],
gateway_server_uri => undefined,
product_uri => <<"urn:freeopcua.github.io:python:server">>
},
server_certificate => undefined,
transport_profile_uri => <<"-Profile/"
"Transport/uatcp-uasc-uabinary">>,
user_identity_tokens => [
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"anonymous">>,
token_type => anonymous
},
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"certificate_basic256sha256">>,
token_type => certificate
},
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"username">>,
token_type => user_name
}
]
}],
server_nonce => opcua_util:hex_to_bin("68924a95b8434526a36c"
"b9373085289748b9dd60"
"fbdff38153339e7844ef"
"8c14"),
server_signature => #{
algorithm => <<"#rsa-sha1">>,
signature => <<>>
},
server_software_certificates => [],
session_id => #opcua_node_id{value = 11}
},
Encoded = "a0216d449c2dd501020000000000000000000000"
"000000000200000b000000020000e90300000000"
"000040774b412000000068924a95b8434526a36c"
"b9373085289748b9dd60fbdff38153339e7844ef"
"8c14ffffffff010000002a0000006f70632e7463"
"703a2f2f3132372e302e302e313a343834302f66"
"7265656f706375612f7365727665722f1b000000"
"75726e3a667265656f706375613a707974686f6e"
"3a7365727665722500000075726e3a667265656f"
"706375612e6769746875622e696f3a707974686f"
"6e3a7365727665720217000000467265654f7063"
"556120507974686f6e2053657276657202000000"
"ffffffffffffffff01000000280000006f70632e"
"7463703a2f2f302e302e302e303a343834302f66"
"7265656f706375612f7365727665722fffffffff"
"010000002f000000687474703a2f2f6f7063666f"
"756e646174696f6e2e6f72672f55412f53656375"
"72697479506f6c696379234e6f6e650300000009"
"000000616e6f6e796d6f757300000000ffffffff"
"ffffffffffffffff1a0000006365727469666963"
"6174655f62617369633235367368613235360200"
"0000ffffffffffffffffffffffff080000007573"
"65726e616d6501000000ffffffffffffffffffff"
"ffff41000000687474703a2f2f6f7063666f756e"
"646174696f6e2e6f72672f55412d50726f66696c"
"652f5472616e73706f72742f75617463702d7561"
"73632d756162696e61727900000000002a000000"
"687474703a2f2f7777772e77332e6f72672f3230"
"30302f30392f786d6c64736967237273612d7368"
"61310000000000000100",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
activate_session_request() ->
NodeId = #opcua_node_id{value = 465},
ToBeEncoded = #{
client_signature => #{
algorithm => <<"#rsa-sha1">>,
signature => <<>>
},
client_software_certificates => [],
locale_ids => [<<"en">>],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 3,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263467530
},
user_identity_token => #opcua_extension_object{
type_id = #opcua_node_id{value = 319},
encoding = byte_string,
body = #{policy_id => <<"anonymous">>}
},
user_token_signature => #{
algorithm => undefined,
signature => undefined
}
},
Encoded = "020000e90300000a6c6d449c2dd5010300000000"
"000000ffffffffe80300000000002a0000006874"
"74703a2f2f7777772e77332e6f72672f32303030"
"2f30392f786d6c64736967237273612d73686131"
"00000000000000000100000002000000656e0100"
"4101010d00000009000000616e6f6e796d6f7573"
"ffffffffffffffff",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
activate_session_request2() ->
NodeId = #opcua_node_id{value = 465},
ToBeEncoded = #{
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token =>
#opcua_node_id{type = opaque,
value = <<146,98,106,42,4,39,212,89,251,151,210,95,27,133,
43,87,120,238,177,107,111,74,77,158,226,200,170,
228,93,144,255,30>>},
request_handle => 0,
return_diagnostics => 0,
timeout_hint => 60000,
timestamp => 132101111289102600
},
client_signature => #{
algorithm => undefined,
signature => undefined
},
client_software_certificates => [],
locale_ids => [<<"en">>],
user_identity_token =>
#opcua_extension_object{
type_id = #opcua_node_id{value = 319},
encoding = byte_string,
body = #{policy_id => <<"anonymous">>}
},
user_token_signature => #{
algorithm => undefined,
signature => undefined
}
},
Encoded = "0500002000000092626A2A0427D459FB9"
"7D25F1B852B5778EEB16B6F4A4D9EE2C8AAE45D90"
"FF1E0841D2C44251D5010000000000000000FFFFF"
"FFF60EA0000000000FFFFFFFFFFFFFFFFFFFFFFFF"
"0100000002000000656E01004101010D000000090"
"00000616E6F6E796D6F7573FFFFFFFFFFFFFFFF",
assert_codec(NodeId, ToBeEncoded, Encoded).
activate_session_response() ->
NodeId = #opcua_node_id{value = 468},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 3,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263475920
},
results => [],
server_nonce => opcua_util:hex_to_bin("8cc1b4736f99ed415e0c"
"8c7396ff156b65ac17a2"
"fbefa7867d0cd84225ec"
"0ddb")
},
Encoded = "d08c6d449c2dd501030000000000000000000000"
"00000000200000008cc1b4736f99ed415e0c8c73"
"96ff156b65ac17a2fbefa7867d0cd84225ec0ddb"
"0000000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
read_request() ->
NodeId = #opcua_node_id{value = 629},
ToBeEncoded = #{
max_age => 0.0,
nodes_to_read => [
#{
attribute_id => 4,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 3,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 1,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 2,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
}
],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 4,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263484640
},
timestamps_to_return => source
},
Encoded = "020000e9030000e0ae6d449c2dd5010400000000"
"000000ffffffffe8030000000000000000000000"
"00000000000004000000005404000000ffffffff"
"0000ffffffff005403000000ffffffff0000ffff"
"ffff005401000000ffffffff0000ffffffff0054"
"02000000ffffffff0000ffffffff",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
read_response() ->
NodeId = #opcua_node_id{value = 632},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 4,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263494150
},
results => [
#opcua_data_value{value = #opcua_variant{type = localized_text,
value = #opcua_localized_text{text = <<"Root">>}}},
#opcua_data_value{value = #opcua_variant{type = qualified_name,
value = #opcua_qualified_name{name = <<"Root">>}}},
#opcua_data_value{value = #opcua_variant{type = node_id,
value = #opcua_node_id{value = 84}}},
#opcua_data_value{value = #opcua_variant{type = int32,
value = 1}}
]
},
Encoded = "06d46d449c2dd501040000000000000000000000"
"000000000400000003150204000000526f6f7400"
"0000000314000004000000526f6f740000000003"
"1102000054000000000000000306010000000000"
"000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
browse_request() ->
NodeId = #opcua_node_id{value = 525},
ToBeEncoded = #{
nodes_to_browse => [#{
browse_direction => forward,
include_subtypes => true,
node_class_mask => 0,
node_id => #opcua_node_id{value = 84},
reference_type_id => #opcua_node_id{value = 33},
result_mask => 63
}],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 5,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263633950
},
requested_max_references_per_node => 0,
view => #{
timestamp => 0,
view_id => #opcua_node_id{},
view_version => 0
}
},
Encoded = "020000e90300001ef66f449c2dd5010500000000"
"000000ffffffffe8030000000000000000000000"
"0000000000000000000000000100000000540000"
"0000002101000000003f000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
browse_response() ->
NodeId = #opcua_node_id{value = 528},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 5,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263644760
},
results => [#{
continuation_point => undefined,
references => [
#{
browse_name => #opcua_qualified_name{name = <<"Objects">>},
display_name => #opcua_localized_text{text = <<"Objects">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 85}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
},
#{
browse_name => #opcua_qualified_name{name = <<"Types">>},
display_name => #opcua_localized_text{text = <<"Types">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 86}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
},
#{
browse_name => #opcua_qualified_name{name = <<"Views">>},
display_name => #opcua_localized_text{text = <<"Views">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 87}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
}
],
status_code => good
}]
},
Encoded = "582070449c2dd501050000000000000000000000"
"000000000100000000000000ffffffff03000000"
"0200002300000001020000550000000000070000"
"004f626a6563747302070000004f626a65637473"
"010000000200003d000000020000230000000102"
"0000560000000000050000005479706573020500"
"00005479706573010000000200003d0000000200"
"0023000000010200005700000000000500000056"
"6965777302050000005669657773010000000200"
"003d00000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
| null | https://raw.githubusercontent.com/stritzinger/opcua/a9802f829f80e6961871653f4d3c932f9496ba99/test/codec_binary_tests.erl | erlang | This little helper does the major testing:
matches the original data
implementation which encoded the same
data and check if the data matches
again (hex dumps are from wireshark)
Why not compare the encoded binaries
in different ways and hence you can get
binaries holding the same data even though
the binaries are not the same! | -module(codec_binary_tests).
-include_lib("eunit/include/eunit.hrl").
-include("opcua.hrl").
-include("opcua_internal.hrl").
t_test_() ->
{setup,
fun setup/0,
fun cleanup/1,
[
fun open_secure_channel_request/0,
fun open_secure_channel_response/0,
fun create_session_request/0,
fun create_session_response/0,
fun activate_session_request/0,
fun activate_session_request2/0,
fun activate_session_response/0,
fun read_request/0,
fun read_response/0,
fun browse_request/0,
fun browse_response/0
]}.
setup() ->
{ok, Apps} = application:ensure_all_started(opcua),
Apps.
cleanup(Apps) ->
opcua_test_util:without_error_logger(fun() ->
[ok = application:stop(A) || A <- Apps]
end).
1 . encode some data according to a NodeId
2 . decode the result again and check if it
3 . decode another example from the python
directly ? Because NodeIds can be encoded
assert_codec(NodeId, ToBeEncoded, EncodedComp) ->
{Encoded, _} = opcua_codec_binary:encode(NodeId, ToBeEncoded),
{Decoded, EmptyBin} = opcua_codec_binary:decode(NodeId, Encoded),
?assertEqual(<<>>, EmptyBin),
?assertEqual(ToBeEncoded, Decoded),
BinEncodedComp = opcua_util:hex_to_bin(EncodedComp),
{DecodedComp, EmptyBin1} = opcua_codec_binary:decode(NodeId, BinEncodedComp),
?assertEqual(<<>>, EmptyBin1),
?assertEqual(ToBeEncoded, DecodedComp).
open_secure_channel_request() ->
NodeId = #opcua_node_id{value = 444},
ToBeEncoded = #{
request_header => #{
authentication_token => #opcua_node_id{value = 0},
timestamp => 132061913263422630,
request_handle => 1,
return_diagnostics => 0,
audit_entry_id => undefined,
timeout_hint => 1000,
additional_header => #opcua_extension_object{}
},
client_protocol_version => 0,
request_type => issue,
security_mode => none,
client_nonce => <<>>,
requested_lifetime => 3600000
},
Encoded = "0000a6bc6c449c2dd5010100000000000000ffff"
"ffffe80300000000000000000000000000010000"
"000000000080ee3600",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
open_secure_channel_response() ->
NodeId = #opcua_node_id{value = 447},
ToBeEncoded = #{
response_header => #{
timestamp => 132061913263430080,
request_handle => 1,
service_result => good,
service_diagnostics => #opcua_diagnostic_info{},
string_table => [],
additional_header => #opcua_extension_object{}
},
server_protocol_version => 0,
security_token => #{
channel_id => 6,
token_id => 14,
created_at => 132061913263429970,
revised_lifetime => 3600000
},
server_nonce => <<>>
},
Encoded = "c0d96c449c2dd501010000000000000000000000"
"0000000000000000060000000e00000052d96c44"
"9c2dd50180ee360000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
create_session_request() ->
NodeId = #opcua_node_id{value = 459},
ToBeEncoded = #{
client_certificate => undefined,
client_description => #{
application_name => #opcua_localized_text{text = <<"Pure Python Client">>},
application_type => client,
application_uri => <<"urn:freeopcua:client">>,
discovery_profile_uri => undefined,
discovery_urls => [],
gateway_server_uri => undefined,
product_uri => <<"urn:freeopcua.github.io:client">>
},
client_nonce => opcua_util:hex_to_bin("dcb709b91898921af025"
"dabacbfdcfaa4891d0cd"
"9fe09a3addb2e094db40"
"48dc"),
endpoint_url => <<"opc.tcp:4840">>,
max_response_message_size => 0,
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{},
request_handle => 2,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263439110
},
requested_session_timeout => 3600000.0,
server_uri => undefined,
session_name => <<"Pure Python Client Session1">>
},
Encoded = "000006fd6c449c2dd5010200000000000000ffff"
"ffffe80300000000001400000075726e3a667265"
"656f706375613a636c69656e741e00000075726e"
"3a667265656f706375612e6769746875622e696f"
"3a636c69656e7402120000005075726520507974"
"686f6e20436c69656e7401000000ffffffffffff"
"ffff00000000ffffffff180000006f70632e7463"
"703a2f2f6c6f63616c686f73743a343834301b00"
"00005075726520507974686f6e20436c69656e74"
"2053657373696f6e3120000000dcb709b9189892"
"1af025dabacbfdcfaa4891d0cd9fe09a3addb2e0"
"94db4048dcffffffff0000000040774b41000000"
"00",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
create_session_response() ->
NodeId = #opcua_node_id{value = 462},
ToBeEncoded = #{
authentication_token => #opcua_node_id{value = 1001},
max_request_message_size => 65536,
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 2,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263448480
},
revised_session_timeout => 3600000.0,
server_certificate => undefined,
server_endpoints => [#{
endpoint_url => <<"opc.tcp:4840/freeopcua/server/">>,
security_level => 0,
security_mode => none,
security_policy_uri => <<"#None">>,
server => #{
application_name => #opcua_localized_text{text = <<"FreeOpcUa Python Server">>},
application_type => client_and_server,
application_uri => <<"urn:freeopcua:python:server">>,
discovery_profile_uri => undefined,
discovery_urls => [<<"opc.tcp:4840/freeopcua/server/">>],
gateway_server_uri => undefined,
product_uri => <<"urn:freeopcua.github.io:python:server">>
},
server_certificate => undefined,
transport_profile_uri => <<"-Profile/"
"Transport/uatcp-uasc-uabinary">>,
user_identity_tokens => [
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"anonymous">>,
token_type => anonymous
},
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"certificate_basic256sha256">>,
token_type => certificate
},
#{
issued_token_type => undefined,
issuer_endpoint_url => undefined,
security_policy_uri => undefined,
policy_id => <<"username">>,
token_type => user_name
}
]
}],
server_nonce => opcua_util:hex_to_bin("68924a95b8434526a36c"
"b9373085289748b9dd60"
"fbdff38153339e7844ef"
"8c14"),
server_signature => #{
algorithm => <<"#rsa-sha1">>,
signature => <<>>
},
server_software_certificates => [],
session_id => #opcua_node_id{value = 11}
},
Encoded = "a0216d449c2dd501020000000000000000000000"
"000000000200000b000000020000e90300000000"
"000040774b412000000068924a95b8434526a36c"
"b9373085289748b9dd60fbdff38153339e7844ef"
"8c14ffffffff010000002a0000006f70632e7463"
"703a2f2f3132372e302e302e313a343834302f66"
"7265656f706375612f7365727665722f1b000000"
"75726e3a667265656f706375613a707974686f6e"
"3a7365727665722500000075726e3a667265656f"
"706375612e6769746875622e696f3a707974686f"
"6e3a7365727665720217000000467265654f7063"
"556120507974686f6e2053657276657202000000"
"ffffffffffffffff01000000280000006f70632e"
"7463703a2f2f302e302e302e303a343834302f66"
"7265656f706375612f7365727665722fffffffff"
"010000002f000000687474703a2f2f6f7063666f"
"756e646174696f6e2e6f72672f55412f53656375"
"72697479506f6c696379234e6f6e650300000009"
"000000616e6f6e796d6f757300000000ffffffff"
"ffffffffffffffff1a0000006365727469666963"
"6174655f62617369633235367368613235360200"
"0000ffffffffffffffffffffffff080000007573"
"65726e616d6501000000ffffffffffffffffffff"
"ffff41000000687474703a2f2f6f7063666f756e"
"646174696f6e2e6f72672f55412d50726f66696c"
"652f5472616e73706f72742f75617463702d7561"
"73632d756162696e61727900000000002a000000"
"687474703a2f2f7777772e77332e6f72672f3230"
"30302f30392f786d6c64736967237273612d7368"
"61310000000000000100",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
activate_session_request() ->
NodeId = #opcua_node_id{value = 465},
ToBeEncoded = #{
client_signature => #{
algorithm => <<"#rsa-sha1">>,
signature => <<>>
},
client_software_certificates => [],
locale_ids => [<<"en">>],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 3,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263467530
},
user_identity_token => #opcua_extension_object{
type_id = #opcua_node_id{value = 319},
encoding = byte_string,
body = #{policy_id => <<"anonymous">>}
},
user_token_signature => #{
algorithm => undefined,
signature => undefined
}
},
Encoded = "020000e90300000a6c6d449c2dd5010300000000"
"000000ffffffffe80300000000002a0000006874"
"74703a2f2f7777772e77332e6f72672f32303030"
"2f30392f786d6c64736967237273612d73686131"
"00000000000000000100000002000000656e0100"
"4101010d00000009000000616e6f6e796d6f7573"
"ffffffffffffffff",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
activate_session_request2() ->
NodeId = #opcua_node_id{value = 465},
ToBeEncoded = #{
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token =>
#opcua_node_id{type = opaque,
value = <<146,98,106,42,4,39,212,89,251,151,210,95,27,133,
43,87,120,238,177,107,111,74,77,158,226,200,170,
228,93,144,255,30>>},
request_handle => 0,
return_diagnostics => 0,
timeout_hint => 60000,
timestamp => 132101111289102600
},
client_signature => #{
algorithm => undefined,
signature => undefined
},
client_software_certificates => [],
locale_ids => [<<"en">>],
user_identity_token =>
#opcua_extension_object{
type_id = #opcua_node_id{value = 319},
encoding = byte_string,
body = #{policy_id => <<"anonymous">>}
},
user_token_signature => #{
algorithm => undefined,
signature => undefined
}
},
Encoded = "0500002000000092626A2A0427D459FB9"
"7D25F1B852B5778EEB16B6F4A4D9EE2C8AAE45D90"
"FF1E0841D2C44251D5010000000000000000FFFFF"
"FFF60EA0000000000FFFFFFFFFFFFFFFFFFFFFFFF"
"0100000002000000656E01004101010D000000090"
"00000616E6F6E796D6F7573FFFFFFFFFFFFFFFF",
assert_codec(NodeId, ToBeEncoded, Encoded).
activate_session_response() ->
NodeId = #opcua_node_id{value = 468},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 3,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263475920
},
results => [],
server_nonce => opcua_util:hex_to_bin("8cc1b4736f99ed415e0c"
"8c7396ff156b65ac17a2"
"fbefa7867d0cd84225ec"
"0ddb")
},
Encoded = "d08c6d449c2dd501030000000000000000000000"
"00000000200000008cc1b4736f99ed415e0c8c73"
"96ff156b65ac17a2fbefa7867d0cd84225ec0ddb"
"0000000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
read_request() ->
NodeId = #opcua_node_id{value = 629},
ToBeEncoded = #{
max_age => 0.0,
nodes_to_read => [
#{
attribute_id => 4,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 3,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 1,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
},
#{
attribute_id => 2,
data_encoding => #opcua_qualified_name{},
index_range => undefined,
node_id => #opcua_node_id{value = 84}
}
],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 4,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263484640
},
timestamps_to_return => source
},
Encoded = "020000e9030000e0ae6d449c2dd5010400000000"
"000000ffffffffe8030000000000000000000000"
"00000000000004000000005404000000ffffffff"
"0000ffffffff005403000000ffffffff0000ffff"
"ffff005401000000ffffffff0000ffffffff0054"
"02000000ffffffff0000ffffffff",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
read_response() ->
NodeId = #opcua_node_id{value = 632},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 4,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263494150
},
results => [
#opcua_data_value{value = #opcua_variant{type = localized_text,
value = #opcua_localized_text{text = <<"Root">>}}},
#opcua_data_value{value = #opcua_variant{type = qualified_name,
value = #opcua_qualified_name{name = <<"Root">>}}},
#opcua_data_value{value = #opcua_variant{type = node_id,
value = #opcua_node_id{value = 84}}},
#opcua_data_value{value = #opcua_variant{type = int32,
value = 1}}
]
},
Encoded = "06d46d449c2dd501040000000000000000000000"
"000000000400000003150204000000526f6f7400"
"0000000314000004000000526f6f740000000003"
"1102000054000000000000000306010000000000"
"000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
browse_request() ->
NodeId = #opcua_node_id{value = 525},
ToBeEncoded = #{
nodes_to_browse => [#{
browse_direction => forward,
include_subtypes => true,
node_class_mask => 0,
node_id => #opcua_node_id{value = 84},
reference_type_id => #opcua_node_id{value = 33},
result_mask => 63
}],
request_header => #{
additional_header => #opcua_extension_object{},
audit_entry_id => undefined,
authentication_token => #opcua_node_id{value = 1001},
request_handle => 5,
return_diagnostics => 0,
timeout_hint => 1000,
timestamp => 132061913263633950
},
requested_max_references_per_node => 0,
view => #{
timestamp => 0,
view_id => #opcua_node_id{},
view_version => 0
}
},
Encoded = "020000e90300001ef66f449c2dd5010500000000"
"000000ffffffffe8030000000000000000000000"
"0000000000000000000000000100000000540000"
"0000002101000000003f000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
browse_response() ->
NodeId = #opcua_node_id{value = 528},
ToBeEncoded = #{
diagnostic_infos => [],
response_header => #{
additional_header => #opcua_extension_object{},
request_handle => 5,
service_diagnostics => #opcua_diagnostic_info{},
service_result => good,
string_table => [],
timestamp => 132061913263644760
},
results => [#{
continuation_point => undefined,
references => [
#{
browse_name => #opcua_qualified_name{name = <<"Objects">>},
display_name => #opcua_localized_text{text = <<"Objects">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 85}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
},
#{
browse_name => #opcua_qualified_name{name = <<"Types">>},
display_name => #opcua_localized_text{text = <<"Types">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 86}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
},
#{
browse_name => #opcua_qualified_name{name = <<"Views">>},
display_name => #opcua_localized_text{text = <<"Views">>},
is_forward => true,
node_class => object,
node_id => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 87}},
reference_type_id => #opcua_node_id{value = 35},
type_definition => #opcua_expanded_node_id{node_id = #opcua_node_id{value = 61}}
}
],
status_code => good
}]
},
Encoded = "582070449c2dd501050000000000000000000000"
"000000000100000000000000ffffffff03000000"
"0200002300000001020000550000000000070000"
"004f626a6563747302070000004f626a65637473"
"010000000200003d000000020000230000000102"
"0000560000000000050000005479706573020500"
"00005479706573010000000200003d0000000200"
"0023000000010200005700000000000500000056"
"6965777302050000005669657773010000000200"
"003d00000000000000",
assert_codec(NodeId, ToBeEncoded, Encoded),
ok.
|
103a180b980b5b314fd3469070a3e2b739516e38ab0201276b622181013d80d3 | ninjudd/cake | task.clj | (ns cake.task
(:use cake
[bake.core :only [print-stacktrace log verbose?]]
[cake.file :only [file newer? touch]]
[cake.utils.version :only [version-mismatch?]]
[cake.project :only [add-group]]
[useful.utils :only [verify adjoin]]
[useful.map :only [update filter-vals]]
[uncle.core :only [*task-name*]]
[clojure.set :only [difference]]
[clojure.string :only [split]]
[clojure.java.io :only [writer]]
[clojure.data.xml :only [sexp-as-element emit]]))
(declare tasks)
(declare run?)
(def implicit-tasks
{'upgrade ["Upgrade cake to the most current version."]
'ps ["List running cake jvm processes for all projects."]
'log ["Tail the cake log file. Optionally pass the number of lines of history to show."]
'kill ["Kill running cake jvm processes. Use -9 to force."]
'killall ["Kill all running cake jvm processes for all projects."]
'console ["Open jconsole on your project. Optionally pass the number of tiled windows."]
'pid ["Print the pid of the cake jvm running in the current directory."]
'port ["Print the port of the cake jvm running in the current directory."]})
(defn parse-task-opts [forms]
(let [[deps forms] (if (set? (first forms))
[(first forms) (rest forms)]
[#{} forms])
deps (set (map #(if-not (symbol? %) (eval %) %) deps))
[docs forms] (split-with string? forms)
[destruct forms] (if (map? (first forms))
[(first forms) (rest forms)]
[{} forms])
[pred forms] (if (= :when (first forms))
`[~(second forms) ~(drop 2 forms)]
[true forms])]
{:deps (list `quote deps) :docs (vec docs) :actions forms :destruct destruct :pred pred}))
(defn append-task! [name task]
(let [tasks-var (or (resolve 'task-defs)
(intern *ns* 'task-defs (atom {})))]
(swap! @tasks-var update name adjoin task)))
(defn- expand-prefix
"Converts a vector of the form [prefix sym1 sym1] to (prefix.sym1 prefix.sym2)"
[ns]
(if (sequential? ns)
(map #(symbol (str (name (first ns)) "." (name %)))
(rest ns))
(list ns)))
(defmacro require-tasks!
"Require all the specified namespaces and add them to the list of task namespaces."
[namespaces]
(let [namespaces (mapcat expand-prefix namespaces)]
`(do (defonce ~'required-tasks (atom []))
(apply require '~namespaces)
(swap! ~'required-tasks into '~namespaces))))
(defn- resolve-var [ns sym]
(when-let [ns (find-ns ns)]
(when-let [var (ns-resolve ns sym)]
@@var)))
(defn task-namespaces
"Returns all required task namespaces for the given namespace (including transitive requirements)."
[namespace]
(when namespace
(try (require namespace)
(catch java.io.FileNotFoundException e
(when (and (not= 'tasks namespace)
(not= "deps" (first *args*)))
(println "warning: unable to find tasks namespace" namespace)
(println " if you've added a new plugin to :dev-dependencies you must run 'cake deps' to install it"))))
(into [namespace]
(mapcat task-namespaces
(resolve-var namespace 'required-tasks)))))
(defn default-tasks []
(if (= "global" (:artifact-id *project*))
'[cake.tasks.global tasks]
'[cake.tasks.default tasks]))
(defn combine-task [task1 task2]
(when-not (= {:replace true} task2)
(let [task1 (or (when-not (:replace task2) task1)
{:actions [] :docs [] :deps #{} :bake-deps []})]
(adjoin (update task1 :deps difference (:remove-deps task2))
(select-keys task2 [:actions :docs :deps])))))
(defn plugin-namespace [dep]
(let [plugin-name (-> dep first name)]
(when-let [ns (second (re-matches #"^cake-(.*)$" plugin-name))]
(symbol (str "cake.tasks." ns)))))
(defn get-tasks []
(reduce
(fn [tasks ns]
(if-let [ns-tasks (resolve-var ns 'task-defs)]
(merge-with combine-task tasks ns-tasks)
tasks))
{}
(mapcat task-namespaces
(concat (default-tasks)
(map plugin-namespace
(filter-vals (:dependencies *project*) :plugin))
(:tasks *project*)))))
(defn task-run-file [taskname]
(file ".cake" "run" taskname))
(defn run-file-task? [target-file deps]
(let [{file-deps true task-deps false} (group-by string? deps)]
(or (not (.exists target-file))
(some #(newer? % target-file)
(into file-deps
(map #(task-run-file %)
task-deps)))
(empty? deps))))
(defn- expand-defile-path [path]
(file (.replaceAll path "\\+context\\+" (str (:context *project*)))))
(defmulti generate-file
(fn [forms]
(let [parts (-> *File* (.toString) (.split "\\."))]
(when (< 1 (count parts))
(-> parts last keyword)))))
(defmacro with-outfile [& forms]
`(with-open [f# (writer *File*)]
(binding [*out* f#]
~@forms)))
(defmethod generate-file nil
[forms]
(with-outfile
(doseq [form forms]
(println form))))
(defmethod generate-file :clj
[forms]
(with-outfile
(doseq [form forms]
(prn form)
(println))))
(defmethod generate-file :xml
[forms]
(with-outfile
(emit (sexp-as-element forms) :indent 2)
(println)))
(defn- run-actions
"Execute task actions in order. Construct file output if task is a defile"
[task]
(let [results (doall (for [action (:actions task) :when action]
(action *opts*)))]
(when *File*
(when-let [output (seq (remove nil? results))]
(log "generating file")
(generate-file output)))))
(defmacro without-circular-deps [taskname & forms]
`(do (verify (not= :in-progress (run? ~taskname))
(str "circular dependency found in task: " ~taskname))
(when-not (run? ~taskname)
(set! run? (assoc run? ~taskname :in-progress))
~@forms
(set! run? (assoc run? ~taskname true)))))
(defn check-bake-deps [task]
(doseq [[project version] (:bake-deps task)]
(let [actual (get-in *project* [:dependencies (add-group project) :version])]
(when (version-mismatch? version actual)
(log (str (format "Warning: cannot find required dependency %s %s" project version)
(when actual (str "; found " actual))))))))
(defn run-task
"Execute the specified task after executing all prerequisite tasks."
[taskname]
(if-not (bound? #'tasks)
;; create the tasks and run? bindings if it hasn't been done yet.
(binding [tasks (get-tasks)
run? {}]
(run-task taskname))
(let [task (get tasks taskname)]
(if (and (nil? task)
(not (string? taskname)))
(println "unknown task:" taskname)
(without-circular-deps taskname
(doseq [dep (:deps task)] (run-task dep)) ;; run dependencies
(binding [*current-task* taskname
*task-name* (name taskname)
*File* (if-not (symbol? taskname) (expand-defile-path taskname))]
(when (verbose?)
(log "Starting..."))
(check-bake-deps task)
(run-actions task))
(when (symbol? taskname)
(touch (task-run-file taskname))))))))
| null | https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/src/cake/task.clj | clojure | create the tasks and run? bindings if it hasn't been done yet.
run dependencies | (ns cake.task
(:use cake
[bake.core :only [print-stacktrace log verbose?]]
[cake.file :only [file newer? touch]]
[cake.utils.version :only [version-mismatch?]]
[cake.project :only [add-group]]
[useful.utils :only [verify adjoin]]
[useful.map :only [update filter-vals]]
[uncle.core :only [*task-name*]]
[clojure.set :only [difference]]
[clojure.string :only [split]]
[clojure.java.io :only [writer]]
[clojure.data.xml :only [sexp-as-element emit]]))
(declare tasks)
(declare run?)
(def implicit-tasks
{'upgrade ["Upgrade cake to the most current version."]
'ps ["List running cake jvm processes for all projects."]
'log ["Tail the cake log file. Optionally pass the number of lines of history to show."]
'kill ["Kill running cake jvm processes. Use -9 to force."]
'killall ["Kill all running cake jvm processes for all projects."]
'console ["Open jconsole on your project. Optionally pass the number of tiled windows."]
'pid ["Print the pid of the cake jvm running in the current directory."]
'port ["Print the port of the cake jvm running in the current directory."]})
(defn parse-task-opts [forms]
(let [[deps forms] (if (set? (first forms))
[(first forms) (rest forms)]
[#{} forms])
deps (set (map #(if-not (symbol? %) (eval %) %) deps))
[docs forms] (split-with string? forms)
[destruct forms] (if (map? (first forms))
[(first forms) (rest forms)]
[{} forms])
[pred forms] (if (= :when (first forms))
`[~(second forms) ~(drop 2 forms)]
[true forms])]
{:deps (list `quote deps) :docs (vec docs) :actions forms :destruct destruct :pred pred}))
(defn append-task! [name task]
(let [tasks-var (or (resolve 'task-defs)
(intern *ns* 'task-defs (atom {})))]
(swap! @tasks-var update name adjoin task)))
(defn- expand-prefix
"Converts a vector of the form [prefix sym1 sym1] to (prefix.sym1 prefix.sym2)"
[ns]
(if (sequential? ns)
(map #(symbol (str (name (first ns)) "." (name %)))
(rest ns))
(list ns)))
(defmacro require-tasks!
"Require all the specified namespaces and add them to the list of task namespaces."
[namespaces]
(let [namespaces (mapcat expand-prefix namespaces)]
`(do (defonce ~'required-tasks (atom []))
(apply require '~namespaces)
(swap! ~'required-tasks into '~namespaces))))
(defn- resolve-var [ns sym]
(when-let [ns (find-ns ns)]
(when-let [var (ns-resolve ns sym)]
@@var)))
(defn task-namespaces
"Returns all required task namespaces for the given namespace (including transitive requirements)."
[namespace]
(when namespace
(try (require namespace)
(catch java.io.FileNotFoundException e
(when (and (not= 'tasks namespace)
(not= "deps" (first *args*)))
(println "warning: unable to find tasks namespace" namespace)
(println " if you've added a new plugin to :dev-dependencies you must run 'cake deps' to install it"))))
(into [namespace]
(mapcat task-namespaces
(resolve-var namespace 'required-tasks)))))
(defn default-tasks []
(if (= "global" (:artifact-id *project*))
'[cake.tasks.global tasks]
'[cake.tasks.default tasks]))
(defn combine-task [task1 task2]
(when-not (= {:replace true} task2)
(let [task1 (or (when-not (:replace task2) task1)
{:actions [] :docs [] :deps #{} :bake-deps []})]
(adjoin (update task1 :deps difference (:remove-deps task2))
(select-keys task2 [:actions :docs :deps])))))
(defn plugin-namespace [dep]
(let [plugin-name (-> dep first name)]
(when-let [ns (second (re-matches #"^cake-(.*)$" plugin-name))]
(symbol (str "cake.tasks." ns)))))
(defn get-tasks []
(reduce
(fn [tasks ns]
(if-let [ns-tasks (resolve-var ns 'task-defs)]
(merge-with combine-task tasks ns-tasks)
tasks))
{}
(mapcat task-namespaces
(concat (default-tasks)
(map plugin-namespace
(filter-vals (:dependencies *project*) :plugin))
(:tasks *project*)))))
(defn task-run-file [taskname]
(file ".cake" "run" taskname))
(defn run-file-task? [target-file deps]
(let [{file-deps true task-deps false} (group-by string? deps)]
(or (not (.exists target-file))
(some #(newer? % target-file)
(into file-deps
(map #(task-run-file %)
task-deps)))
(empty? deps))))
(defn- expand-defile-path [path]
(file (.replaceAll path "\\+context\\+" (str (:context *project*)))))
(defmulti generate-file
(fn [forms]
(let [parts (-> *File* (.toString) (.split "\\."))]
(when (< 1 (count parts))
(-> parts last keyword)))))
(defmacro with-outfile [& forms]
`(with-open [f# (writer *File*)]
(binding [*out* f#]
~@forms)))
(defmethod generate-file nil
[forms]
(with-outfile
(doseq [form forms]
(println form))))
(defmethod generate-file :clj
[forms]
(with-outfile
(doseq [form forms]
(prn form)
(println))))
(defmethod generate-file :xml
[forms]
(with-outfile
(emit (sexp-as-element forms) :indent 2)
(println)))
(defn- run-actions
"Execute task actions in order. Construct file output if task is a defile"
[task]
(let [results (doall (for [action (:actions task) :when action]
(action *opts*)))]
(when *File*
(when-let [output (seq (remove nil? results))]
(log "generating file")
(generate-file output)))))
(defmacro without-circular-deps [taskname & forms]
`(do (verify (not= :in-progress (run? ~taskname))
(str "circular dependency found in task: " ~taskname))
(when-not (run? ~taskname)
(set! run? (assoc run? ~taskname :in-progress))
~@forms
(set! run? (assoc run? ~taskname true)))))
(defn check-bake-deps [task]
(doseq [[project version] (:bake-deps task)]
(let [actual (get-in *project* [:dependencies (add-group project) :version])]
(when (version-mismatch? version actual)
(log (str (format "Warning: cannot find required dependency %s %s" project version)
(when actual (str "; found " actual))))))))
(defn run-task
"Execute the specified task after executing all prerequisite tasks."
[taskname]
(if-not (bound? #'tasks)
(binding [tasks (get-tasks)
run? {}]
(run-task taskname))
(let [task (get tasks taskname)]
(if (and (nil? task)
(not (string? taskname)))
(println "unknown task:" taskname)
(without-circular-deps taskname
(binding [*current-task* taskname
*task-name* (name taskname)
*File* (if-not (symbol? taskname) (expand-defile-path taskname))]
(when (verbose?)
(log "Starting..."))
(check-bake-deps task)
(run-actions task))
(when (symbol? taskname)
(touch (task-run-file taskname))))))))
|
d66bdcd3b054a6cb6a575cb364d455685e589db4336ca703048b9199c1d139ef | esl/MongooseIM | mod_muc_light_api.erl | @doc Provide an interface for frontends ( like graphql or ctl ) to manage MUC Light rooms .
-module(mod_muc_light_api).
-export([create_room/3,
create_room/4,
invite_to_room/3,
change_room_config/3,
change_affiliation/4,
send_message/3,
send_message/4,
delete_room/2,
delete_room/1,
get_room_messages/3,
get_room_messages/4,
get_room_messages/5,
get_user_rooms/1,
get_room_info/1,
get_room_info/2,
get_room_aff/1,
get_room_aff/2,
get_blocking_list/1,
set_blocking/2
]).
-include("mod_muc_light.hrl").
-include("mongoose.hrl").
-include("jlib.hrl").
-include("mongoose_rsm.hrl").
-type room() :: #{jid := jid:jid(),
aff_users := aff_users(),
options := map()}.
-export_type([room/0]).
-define(ROOM_DELETED_SUCC_RESULT, {ok, "Room deleted successfully"}).
-define(USER_NOT_ROOM_MEMBER_RESULT, {not_room_member, "Given user does not occupy this room"}).
-define(ROOM_NOT_FOUND_RESULT, {room_not_found, "Room not found"}).
-define(MUC_SERVER_NOT_FOUND_RESULT, {muc_server_not_found, "MUC Light server not found"}).
-define(VALIDATION_ERROR_RESULT(Key, Reason),
{validation_error, io_lib:format("Validation failed for key: ~ts with reason ~p",
[Key, Reason])}).
-spec create_room(jid:lserver(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found |
max_occupants_reached | validation_error, iolist()}.
create_room(MUCLightDomain, CreatorJID, Config) ->
M = #{user => CreatorJID, room => jid:make_bare(<<>>, MUCLightDomain), options => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun create_room_raw/1]).
-spec create_room(jid:lserver(), jid:luser(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found | already_exists |
max_occupants_reached | validation_error, iolist()}.
create_room(MUCLightDomain, RoomID, CreatorJID, Config) ->
M = #{user => CreatorJID, room => jid:make_bare(RoomID, MUCLightDomain), options => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun create_room_raw/1]).
-spec invite_to_room(jid:jid(), jid:jid(), jid:jid()) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
invite_to_room(RoomJID, SenderJID, RecipientJID) ->
M = #{user => SenderJID, room => RoomJID, recipient => RecipientJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun do_invite_to_room/1]).
-spec change_room_config(jid:jid(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member |
not_allowed | validation_error, iolist()}.
change_room_config(RoomJID, UserJID, Config) ->
M = #{user => UserJID, room => RoomJID, config => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_change_room_config/1]).
-spec change_affiliation(jid:jid(), jid:jid(), jid:jid(), add | remove) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member |
not_allowed, iolist()}.
change_affiliation(RoomJID, SenderJID, RecipientJID, Op) ->
M = #{user => SenderJID, room => RoomJID, recipient => RecipientJID, op => Op},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun check_aff_permission/1, fun do_change_affiliation/1]).
-spec send_message(jid:jid(), jid:jid(), binary()) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
send_message(RoomJID, SenderJID, Text) when is_binary(Text) ->
Body = #xmlel{name = <<"body">>, children = [#xmlcdata{content = Text}]},
send_message(RoomJID, SenderJID, [Body], []).
-spec send_message(jid:jid(), jid:jid(), [exml:element()], [exml:attr()]) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
send_message(RoomJID, SenderJID, Children, ExtraAttrs) ->
M = #{user => SenderJID, room => RoomJID, children => Children, attrs => ExtraAttrs},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1, fun do_send_message/1]).
-spec delete_room(jid:jid(), jid:jid()) ->
{ok | not_allowed | room_not_found | not_room_member | muc_server_not_found , iolist()}.
delete_room(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun check_delete_permission/1, fun do_delete_room/1]).
-spec delete_room(jid:jid()) -> {ok | muc_server_not_found | room_not_found, iolist()}.
delete_room(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_delete_room/1]).
-spec get_room_messages(jid:jid(), jid:jid(), integer() | undefined,
mod_mam:unix_timestamp() | undefined) ->
{ok, list()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member |
internal, iolist()}.
get_room_messages(RoomJID, UserJID, PageSize, Before) ->
M = #{user => UserJID, room => RoomJID, page_size => PageSize, before => Before},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun do_get_room_messages/1]).
-spec get_room_messages(jid:jid(), integer() | undefined,
mod_mam:unix_timestamp() | undefined) ->
{ok, [mod_mam:message_row()]} | {muc_server_not_found | room_not_found | internal, iolist()}.
get_room_messages(RoomJID, PageSize, Before) ->
M = #{user => undefined, room => RoomJID, page_size => PageSize, before => Before},
fold(M, [fun check_muc_domain/1, fun check_room/1, fun do_get_room_messages/1]).
-spec get_room_info(jid:jid(), jid:jid()) ->
{ok, room()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member,
iolist()}.
get_room_info(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_get_room_info/1,
fun check_room_member/1, fun return_info/1]).
-spec get_room_info(jid:jid()) -> {ok, room()} | {muc_server_not_found | room_not_found, iolist()}.
get_room_info(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_get_room_info/1, fun return_info/1]).
-spec get_room_aff(jid:jid(), jid:jid()) ->
{ok, aff_users()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member,
iolist()}.
get_room_aff(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_get_room_aff/1,
fun check_room_member/1, fun return_aff/1]).
-spec get_room_aff(jid:jid()) ->
{ok, aff_users()} | {muc_server_not_found | room_not_found, iolist()}.
get_room_aff(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_get_room_aff/1, fun return_aff/1]).
-spec get_user_rooms(jid:jid()) ->
{ok, [RoomUS :: jid:simple_bare_jid()]} | {user_not_found, iolist()}.
get_user_rooms(UserJID) ->
fold(#{user => UserJID}, [fun check_user/1, fun do_get_user_rooms/1]).
-spec get_blocking_list(jid:jid()) -> {ok, [blocking_item()]} | {user_not_found, iolist()}.
get_blocking_list(UserJID) ->
fold(#{user => UserJID}, [fun check_user/1, fun do_get_blocking_list/1]).
-spec set_blocking(jid:jid(), [blocking_item()]) -> {ok | user_not_found, iolist()}.
set_blocking(UserJID, Items) ->
fold(#{user => UserJID, items => Items}, [fun check_user/1, fun do_set_blocking_list/1]).
Internal : steps used in
check_user(M = #{user := UserJID = #jid{lserver = LServer}}) ->
case mongoose_domain_api:get_domain_host_type(LServer) of
{ok, HostType} ->
case ejabberd_auth:does_user_exist(HostType, UserJID, stored) of
true -> M#{user_host_type => HostType};
false -> {user_not_found, "Given user does not exist"}
end;
{error, not_found} ->
{user_not_found, "User's domain does not exist"}
end.
check_muc_domain(M = #{room := #jid{lserver = LServer}}) ->
case mongoose_domain_api:get_subdomain_host_type(LServer) of
{ok, HostType} ->
M#{muc_host_type => HostType};
{error, not_found} ->
?MUC_SERVER_NOT_FOUND_RESULT
end.
check_room_member(M = #{user := UserJID, aff_users := AffUsers}) ->
case get_aff(jid:to_lus(UserJID), AffUsers) of
none ->
?USER_NOT_ROOM_MEMBER_RESULT;
_ ->
M
end.
create_room_raw(#{room := InRoomJID, user := CreatorJID, options := Options}) ->
Config = make_room_config(Options),
case mod_muc_light:try_to_create_room(CreatorJID, InRoomJID, Config) of
{ok, RoomJID, #create{aff_users = AffUsers, raw_config = Conf}} ->
{ok, make_room(RoomJID, Conf, AffUsers)};
{error, exists} ->
{already_exists, "Room already exists"};
{error, max_occupants_reached} ->
{max_occupants_reached, "Max occupants number reached"};
{error, {Key, Reason}} ->
?VALIDATION_ERROR_RESULT(Key, Reason)
end.
do_invite_to_room(#{user := SenderJID, room := RoomJID, recipient := RecipientJID}) ->
S = jid:to_bare(SenderJID),
R = jid:to_bare(RoomJID),
RecipientBin = jid:to_binary(jid:to_bare(RecipientJID)),
Changes = query(?NS_MUC_LIGHT_AFFILIATIONS, [affiliate(RecipientBin, <<"member">>)]),
ejabberd_router:route(S, R, iq(jid:to_binary(S), jid:to_binary(R), <<"set">>, [Changes])),
{ok, "User invited successfully"}.
do_change_room_config(#{user := UserJID, room := RoomJID, config := Config,
muc_host_type := HostType}) ->
UserUS = jid:to_bare(UserJID),
ConfigReq = #config{ raw_config = maps:to_list(Config) },
#jid{lserver = LServer} = UserJID,
#jid{luser = RoomID, lserver = MUCServer} = RoomJID,
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => LServer, host_type => HostType}),
case mod_muc_light:change_room_config(UserUS, RoomID, MUCServer, ConfigReq, Acc) of
{ok, RoomJID, KV} ->
{ok, make_room(RoomJID, KV, [])};
{error, item_not_found} ->
?USER_NOT_ROOM_MEMBER_RESULT;
{error, not_allowed} ->
{not_allowed, "Given user does not have permission to change config"};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT;
{error, {Key, Reason}} ->
?VALIDATION_ERROR_RESULT(Key, Reason)
end.
check_aff_permission(M = #{user := UserJID, recipient := RecipientJID, aff := Aff, op := Op}) ->
case {Aff, Op} of
{member, remove} when RecipientJID =:= UserJID ->
M;
{owner, _} ->
M;
_ -> {not_allowed, "Given user does not have permission to change affiliations"}
end.
check_delete_permission(M = #{aff := owner}) -> M;
check_delete_permission(#{}) -> {not_allowed, "Given user cannot delete this room"}.
get_user_aff(M = #{muc_host_type := HostType, user := UserJID, room := RoomJID}) ->
case get_room_user_aff(HostType, RoomJID, UserJID) of
{ok, owner} ->
M#{aff => owner};
{ok, member} ->
M#{aff => member};
{ok, none} ->
?USER_NOT_ROOM_MEMBER_RESULT;
{error, room_not_found} ->
?ROOM_NOT_FOUND_RESULT
end.
do_change_affiliation(#{user := SenderJID, room := RoomJID, recipient := RecipientJID, op := Op}) ->
RecipientBare = jid:to_bare(RecipientJID),
S = jid:to_bare(SenderJID),
Changes = query(?NS_MUC_LIGHT_AFFILIATIONS,
[affiliate(jid:to_binary(RecipientBare), op_to_aff(Op))]),
ejabberd_router:route(S, RoomJID, iq(jid:to_binary(S), jid:to_binary(RoomJID),
<<"set">>, [Changes])),
{ok, "Affiliation change request sent successfully"}.
do_send_message(#{user := SenderJID, room := RoomJID, children := Children, attrs := ExtraAttrs}) ->
SenderBare = jid:to_bare(SenderJID),
RoomBare = jid:to_bare(RoomJID),
Stanza = #xmlel{name = <<"message">>,
attrs = [{<<"type">>, <<"groupchat">>} | ExtraAttrs],
children = Children},
ejabberd_router:route(SenderBare, RoomBare, Stanza),
{ok, "Message sent successfully"}.
do_delete_room(#{room := RoomJID}) ->
case mod_muc_light:delete_room(jid:to_lus(RoomJID)) of
ok ->
?ROOM_DELETED_SUCC_RESULT;
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
do_get_room_messages(#{user := CallerJID, room := RoomJID, page_size := PageSize, before := Before,
muc_host_type := HostType}) ->
get_room_messages(HostType, RoomJID, CallerJID, PageSize, Before).
%% Exported for mod_muc_api
get_room_messages(HostType, RoomJID, CallerJID, PageSize, Before) ->
ArchiveID = mod_mam_muc:archive_id_int(HostType, RoomJID),
Now = os:system_time(microsecond),
End = maybe_before(Before, Now),
RSM = #rsm_in{direction = before, id = undefined},
Params = #{archive_id => ArchiveID,
owner_jid => RoomJID,
rsm => RSM,
borders => undefined,
start_ts => undefined,
end_ts => End,
now => Now,
with_jid => undefined,
search_text => undefined,
page_size => PageSize,
limit_passed => true,
max_result_limit => 50,
is_simple => true},
case mod_mam_muc:lookup_messages(HostType, maybe_caller_jid(CallerJID, Params)) of
{ok, {_, _, Messages}} ->
{ok, Messages};
{error, Term} ->
{internal, io_lib:format("Internal error occured ~p", [Term])}
end.
do_get_room_info(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:get_info(HostType, jid:to_lus(RoomJID)) of
{ok, Config, AffUsers, _Version} ->
M#{aff_users => AffUsers, options => Config};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
return_info(#{room := RoomJID, aff_users := AffUsers, options := Config}) ->
{ok, make_room(jid:to_binary(RoomJID), Config, AffUsers)}.
do_get_room_aff(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:get_aff_users(HostType, jid:to_lus(RoomJID)) of
{ok, AffUsers, _Version} ->
M#{aff_users => AffUsers};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
return_aff(#{aff_users := AffUsers}) ->
{ok, AffUsers}.
check_room(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:room_exists(HostType, jid:to_lus(RoomJID)) of
true ->
M;
false ->
?ROOM_NOT_FOUND_RESULT
end.
do_get_user_rooms(#{user := UserJID, user_host_type := HostType}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
{ok, mod_muc_light_db_backend:get_user_rooms(HostType, jid:to_lus(UserJID), MUCServer)}.
do_get_blocking_list(#{user := UserJID, user_host_type := HostType}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
{ok, mod_muc_light_db_backend:get_blocking(HostType, jid:to_lus(UserJID), MUCServer)}.
do_set_blocking_list(#{user := UserJID, user_host_type := HostType, items := Items}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
Q = query(?NS_MUC_LIGHT_BLOCKING, [blocking_item(I) || I <- Items]),
Iq = iq(jid:to_binary(UserJID), MUCServer, <<"set">>, [Q]),
ejabberd_router:route(UserJID, jid:from_binary(MUCServer), Iq),
{ok, "User blocking list updated successfully"}.
%% Internal: helpers
-spec blocking_item(blocking_item()) -> exml:element().
blocking_item({What, Action, Who}) ->
#xmlel{name = atom_to_binary(What),
attrs = [{<<"action">>, atom_to_binary(Action)}],
children = [#xmlcdata{ content = jid:to_binary(Who)}]
}.
-spec make_room_config(map()) -> create_req_props().
make_room_config(Options) ->
#create{raw_config = maps:to_list(Options)}.
-spec get_room_user_aff(mongooseim:host_type(), jid:jid(), jid:jid()) ->
{ok, aff()} | {error, room_not_found}.
get_room_user_aff(HostType, RoomJID, UserJID) ->
RoomUS = jid:to_lus(RoomJID),
UserUS = jid:to_lus(UserJID),
case mod_muc_light_db_backend:get_aff_users(HostType, RoomUS) of
{ok, Affs, _Version} ->
{ok, get_aff(UserUS, Affs)};
{error, not_exists} ->
{error, room_not_found}
end.
-spec get_aff(jid:simple_bare_jid(), aff_users()) -> aff().
get_aff(UserUS, Affs) ->
case lists:keyfind(UserUS, 1, Affs) of
{_, Aff} -> Aff;
false -> none
end.
make_room(JID, #config{ raw_config = Options}, AffUsers) ->
make_room(JID, Options, AffUsers);
make_room(JID, Options, AffUsers) when is_list(Options) ->
make_room(JID, maps:from_list(ensure_keys_are_binaries(Options)), AffUsers);
make_room(JID, Options, AffUsers) when is_map(Options) ->
#{jid => JID, aff_users => AffUsers, options => Options}.
ensure_keys_are_binaries([{K, _}|_] = Conf) when is_binary(K) ->
Conf;
ensure_keys_are_binaries(Conf) ->
[{atom_to_binary(K), V} || {K, V} <- Conf].
iq(To, From, Type, Children) ->
UUID = uuid:uuid_to_string(uuid:get_v4(), binary_standard),
#xmlel{name = <<"iq">>,
attrs = [{<<"from">>, From},
{<<"to">>, To},
{<<"type">>, Type},
{<<"id">>, UUID}],
children = Children
}.
query(NS, Children) when is_binary(NS), is_list(Children) ->
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, NS}],
children = Children
}.
affiliate(JID, Kind) when is_binary(JID), is_binary(Kind) ->
#xmlel{name = <<"user">>,
attrs = [{<<"affiliation">>, Kind}],
children = [ #xmlcdata{ content = JID } ]
}.
maybe_before(undefined, Now) ->
Now;
maybe_before(Timestamp, _) ->
Timestamp.
maybe_caller_jid(undefined, Params) ->
Params;
maybe_caller_jid(CallerJID, Params) ->
Params#{caller_jid => CallerJID}.
op_to_aff(add) -> <<"member">>;
op_to_aff(remove) -> <<"none">>.
fold({_, _} = Result, _) ->
Result;
fold(M, [Step | Rest]) when is_map(M) ->
fold(Step(M), Rest).
| null | https://raw.githubusercontent.com/esl/MongooseIM/557e26591f6589653eec551641d98f96c9760838/src/muc_light/mod_muc_light_api.erl | erlang | Exported for mod_muc_api
Internal: helpers | @doc Provide an interface for frontends ( like graphql or ctl ) to manage MUC Light rooms .
-module(mod_muc_light_api).
-export([create_room/3,
create_room/4,
invite_to_room/3,
change_room_config/3,
change_affiliation/4,
send_message/3,
send_message/4,
delete_room/2,
delete_room/1,
get_room_messages/3,
get_room_messages/4,
get_room_messages/5,
get_user_rooms/1,
get_room_info/1,
get_room_info/2,
get_room_aff/1,
get_room_aff/2,
get_blocking_list/1,
set_blocking/2
]).
-include("mod_muc_light.hrl").
-include("mongoose.hrl").
-include("jlib.hrl").
-include("mongoose_rsm.hrl").
-type room() :: #{jid := jid:jid(),
aff_users := aff_users(),
options := map()}.
-export_type([room/0]).
-define(ROOM_DELETED_SUCC_RESULT, {ok, "Room deleted successfully"}).
-define(USER_NOT_ROOM_MEMBER_RESULT, {not_room_member, "Given user does not occupy this room"}).
-define(ROOM_NOT_FOUND_RESULT, {room_not_found, "Room not found"}).
-define(MUC_SERVER_NOT_FOUND_RESULT, {muc_server_not_found, "MUC Light server not found"}).
-define(VALIDATION_ERROR_RESULT(Key, Reason),
{validation_error, io_lib:format("Validation failed for key: ~ts with reason ~p",
[Key, Reason])}).
-spec create_room(jid:lserver(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found |
max_occupants_reached | validation_error, iolist()}.
create_room(MUCLightDomain, CreatorJID, Config) ->
M = #{user => CreatorJID, room => jid:make_bare(<<>>, MUCLightDomain), options => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun create_room_raw/1]).
-spec create_room(jid:lserver(), jid:luser(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found | already_exists |
max_occupants_reached | validation_error, iolist()}.
create_room(MUCLightDomain, RoomID, CreatorJID, Config) ->
M = #{user => CreatorJID, room => jid:make_bare(RoomID, MUCLightDomain), options => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun create_room_raw/1]).
-spec invite_to_room(jid:jid(), jid:jid(), jid:jid()) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
invite_to_room(RoomJID, SenderJID, RecipientJID) ->
M = #{user => SenderJID, room => RoomJID, recipient => RecipientJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun do_invite_to_room/1]).
-spec change_room_config(jid:jid(), jid:jid(), map()) ->
{ok, room()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member |
not_allowed | validation_error, iolist()}.
change_room_config(RoomJID, UserJID, Config) ->
M = #{user => UserJID, room => RoomJID, config => Config},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_change_room_config/1]).
-spec change_affiliation(jid:jid(), jid:jid(), jid:jid(), add | remove) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member |
not_allowed, iolist()}.
change_affiliation(RoomJID, SenderJID, RecipientJID, Op) ->
M = #{user => SenderJID, room => RoomJID, recipient => RecipientJID, op => Op},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun check_aff_permission/1, fun do_change_affiliation/1]).
-spec send_message(jid:jid(), jid:jid(), binary()) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
send_message(RoomJID, SenderJID, Text) when is_binary(Text) ->
Body = #xmlel{name = <<"body">>, children = [#xmlcdata{content = Text}]},
send_message(RoomJID, SenderJID, [Body], []).
-spec send_message(jid:jid(), jid:jid(), [exml:element()], [exml:attr()]) ->
{ok | user_not_found | muc_server_not_found | room_not_found | not_room_member, iolist()}.
send_message(RoomJID, SenderJID, Children, ExtraAttrs) ->
M = #{user => SenderJID, room => RoomJID, children => Children, attrs => ExtraAttrs},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1, fun do_send_message/1]).
-spec delete_room(jid:jid(), jid:jid()) ->
{ok | not_allowed | room_not_found | not_room_member | muc_server_not_found , iolist()}.
delete_room(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun check_delete_permission/1, fun do_delete_room/1]).
-spec delete_room(jid:jid()) -> {ok | muc_server_not_found | room_not_found, iolist()}.
delete_room(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_delete_room/1]).
-spec get_room_messages(jid:jid(), jid:jid(), integer() | undefined,
mod_mam:unix_timestamp() | undefined) ->
{ok, list()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member |
internal, iolist()}.
get_room_messages(RoomJID, UserJID, PageSize, Before) ->
M = #{user => UserJID, room => RoomJID, page_size => PageSize, before => Before},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun get_user_aff/1,
fun do_get_room_messages/1]).
-spec get_room_messages(jid:jid(), integer() | undefined,
mod_mam:unix_timestamp() | undefined) ->
{ok, [mod_mam:message_row()]} | {muc_server_not_found | room_not_found | internal, iolist()}.
get_room_messages(RoomJID, PageSize, Before) ->
M = #{user => undefined, room => RoomJID, page_size => PageSize, before => Before},
fold(M, [fun check_muc_domain/1, fun check_room/1, fun do_get_room_messages/1]).
-spec get_room_info(jid:jid(), jid:jid()) ->
{ok, room()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member,
iolist()}.
get_room_info(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_get_room_info/1,
fun check_room_member/1, fun return_info/1]).
-spec get_room_info(jid:jid()) -> {ok, room()} | {muc_server_not_found | room_not_found, iolist()}.
get_room_info(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_get_room_info/1, fun return_info/1]).
-spec get_room_aff(jid:jid(), jid:jid()) ->
{ok, aff_users()} | {user_not_found | muc_server_not_found | room_not_found | not_room_member,
iolist()}.
get_room_aff(RoomJID, UserJID) ->
M = #{user => UserJID, room => RoomJID},
fold(M, [fun check_user/1, fun check_muc_domain/1, fun do_get_room_aff/1,
fun check_room_member/1, fun return_aff/1]).
-spec get_room_aff(jid:jid()) ->
{ok, aff_users()} | {muc_server_not_found | room_not_found, iolist()}.
get_room_aff(RoomJID) ->
M = #{room => RoomJID},
fold(M, [fun check_muc_domain/1, fun do_get_room_aff/1, fun return_aff/1]).
-spec get_user_rooms(jid:jid()) ->
{ok, [RoomUS :: jid:simple_bare_jid()]} | {user_not_found, iolist()}.
get_user_rooms(UserJID) ->
fold(#{user => UserJID}, [fun check_user/1, fun do_get_user_rooms/1]).
-spec get_blocking_list(jid:jid()) -> {ok, [blocking_item()]} | {user_not_found, iolist()}.
get_blocking_list(UserJID) ->
fold(#{user => UserJID}, [fun check_user/1, fun do_get_blocking_list/1]).
-spec set_blocking(jid:jid(), [blocking_item()]) -> {ok | user_not_found, iolist()}.
set_blocking(UserJID, Items) ->
fold(#{user => UserJID, items => Items}, [fun check_user/1, fun do_set_blocking_list/1]).
Internal : steps used in
check_user(M = #{user := UserJID = #jid{lserver = LServer}}) ->
case mongoose_domain_api:get_domain_host_type(LServer) of
{ok, HostType} ->
case ejabberd_auth:does_user_exist(HostType, UserJID, stored) of
true -> M#{user_host_type => HostType};
false -> {user_not_found, "Given user does not exist"}
end;
{error, not_found} ->
{user_not_found, "User's domain does not exist"}
end.
check_muc_domain(M = #{room := #jid{lserver = LServer}}) ->
case mongoose_domain_api:get_subdomain_host_type(LServer) of
{ok, HostType} ->
M#{muc_host_type => HostType};
{error, not_found} ->
?MUC_SERVER_NOT_FOUND_RESULT
end.
check_room_member(M = #{user := UserJID, aff_users := AffUsers}) ->
case get_aff(jid:to_lus(UserJID), AffUsers) of
none ->
?USER_NOT_ROOM_MEMBER_RESULT;
_ ->
M
end.
create_room_raw(#{room := InRoomJID, user := CreatorJID, options := Options}) ->
Config = make_room_config(Options),
case mod_muc_light:try_to_create_room(CreatorJID, InRoomJID, Config) of
{ok, RoomJID, #create{aff_users = AffUsers, raw_config = Conf}} ->
{ok, make_room(RoomJID, Conf, AffUsers)};
{error, exists} ->
{already_exists, "Room already exists"};
{error, max_occupants_reached} ->
{max_occupants_reached, "Max occupants number reached"};
{error, {Key, Reason}} ->
?VALIDATION_ERROR_RESULT(Key, Reason)
end.
do_invite_to_room(#{user := SenderJID, room := RoomJID, recipient := RecipientJID}) ->
S = jid:to_bare(SenderJID),
R = jid:to_bare(RoomJID),
RecipientBin = jid:to_binary(jid:to_bare(RecipientJID)),
Changes = query(?NS_MUC_LIGHT_AFFILIATIONS, [affiliate(RecipientBin, <<"member">>)]),
ejabberd_router:route(S, R, iq(jid:to_binary(S), jid:to_binary(R), <<"set">>, [Changes])),
{ok, "User invited successfully"}.
do_change_room_config(#{user := UserJID, room := RoomJID, config := Config,
muc_host_type := HostType}) ->
UserUS = jid:to_bare(UserJID),
ConfigReq = #config{ raw_config = maps:to_list(Config) },
#jid{lserver = LServer} = UserJID,
#jid{luser = RoomID, lserver = MUCServer} = RoomJID,
Acc = mongoose_acc:new(#{location => ?LOCATION, lserver => LServer, host_type => HostType}),
case mod_muc_light:change_room_config(UserUS, RoomID, MUCServer, ConfigReq, Acc) of
{ok, RoomJID, KV} ->
{ok, make_room(RoomJID, KV, [])};
{error, item_not_found} ->
?USER_NOT_ROOM_MEMBER_RESULT;
{error, not_allowed} ->
{not_allowed, "Given user does not have permission to change config"};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT;
{error, {Key, Reason}} ->
?VALIDATION_ERROR_RESULT(Key, Reason)
end.
check_aff_permission(M = #{user := UserJID, recipient := RecipientJID, aff := Aff, op := Op}) ->
case {Aff, Op} of
{member, remove} when RecipientJID =:= UserJID ->
M;
{owner, _} ->
M;
_ -> {not_allowed, "Given user does not have permission to change affiliations"}
end.
check_delete_permission(M = #{aff := owner}) -> M;
check_delete_permission(#{}) -> {not_allowed, "Given user cannot delete this room"}.
get_user_aff(M = #{muc_host_type := HostType, user := UserJID, room := RoomJID}) ->
case get_room_user_aff(HostType, RoomJID, UserJID) of
{ok, owner} ->
M#{aff => owner};
{ok, member} ->
M#{aff => member};
{ok, none} ->
?USER_NOT_ROOM_MEMBER_RESULT;
{error, room_not_found} ->
?ROOM_NOT_FOUND_RESULT
end.
do_change_affiliation(#{user := SenderJID, room := RoomJID, recipient := RecipientJID, op := Op}) ->
RecipientBare = jid:to_bare(RecipientJID),
S = jid:to_bare(SenderJID),
Changes = query(?NS_MUC_LIGHT_AFFILIATIONS,
[affiliate(jid:to_binary(RecipientBare), op_to_aff(Op))]),
ejabberd_router:route(S, RoomJID, iq(jid:to_binary(S), jid:to_binary(RoomJID),
<<"set">>, [Changes])),
{ok, "Affiliation change request sent successfully"}.
do_send_message(#{user := SenderJID, room := RoomJID, children := Children, attrs := ExtraAttrs}) ->
SenderBare = jid:to_bare(SenderJID),
RoomBare = jid:to_bare(RoomJID),
Stanza = #xmlel{name = <<"message">>,
attrs = [{<<"type">>, <<"groupchat">>} | ExtraAttrs],
children = Children},
ejabberd_router:route(SenderBare, RoomBare, Stanza),
{ok, "Message sent successfully"}.
do_delete_room(#{room := RoomJID}) ->
case mod_muc_light:delete_room(jid:to_lus(RoomJID)) of
ok ->
?ROOM_DELETED_SUCC_RESULT;
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
do_get_room_messages(#{user := CallerJID, room := RoomJID, page_size := PageSize, before := Before,
muc_host_type := HostType}) ->
get_room_messages(HostType, RoomJID, CallerJID, PageSize, Before).
get_room_messages(HostType, RoomJID, CallerJID, PageSize, Before) ->
ArchiveID = mod_mam_muc:archive_id_int(HostType, RoomJID),
Now = os:system_time(microsecond),
End = maybe_before(Before, Now),
RSM = #rsm_in{direction = before, id = undefined},
Params = #{archive_id => ArchiveID,
owner_jid => RoomJID,
rsm => RSM,
borders => undefined,
start_ts => undefined,
end_ts => End,
now => Now,
with_jid => undefined,
search_text => undefined,
page_size => PageSize,
limit_passed => true,
max_result_limit => 50,
is_simple => true},
case mod_mam_muc:lookup_messages(HostType, maybe_caller_jid(CallerJID, Params)) of
{ok, {_, _, Messages}} ->
{ok, Messages};
{error, Term} ->
{internal, io_lib:format("Internal error occured ~p", [Term])}
end.
do_get_room_info(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:get_info(HostType, jid:to_lus(RoomJID)) of
{ok, Config, AffUsers, _Version} ->
M#{aff_users => AffUsers, options => Config};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
return_info(#{room := RoomJID, aff_users := AffUsers, options := Config}) ->
{ok, make_room(jid:to_binary(RoomJID), Config, AffUsers)}.
do_get_room_aff(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:get_aff_users(HostType, jid:to_lus(RoomJID)) of
{ok, AffUsers, _Version} ->
M#{aff_users => AffUsers};
{error, not_exists} ->
?ROOM_NOT_FOUND_RESULT
end.
return_aff(#{aff_users := AffUsers}) ->
{ok, AffUsers}.
check_room(M = #{room := RoomJID, muc_host_type := HostType}) ->
case mod_muc_light_db_backend:room_exists(HostType, jid:to_lus(RoomJID)) of
true ->
M;
false ->
?ROOM_NOT_FOUND_RESULT
end.
do_get_user_rooms(#{user := UserJID, user_host_type := HostType}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
{ok, mod_muc_light_db_backend:get_user_rooms(HostType, jid:to_lus(UserJID), MUCServer)}.
do_get_blocking_list(#{user := UserJID, user_host_type := HostType}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
{ok, mod_muc_light_db_backend:get_blocking(HostType, jid:to_lus(UserJID), MUCServer)}.
do_set_blocking_list(#{user := UserJID, user_host_type := HostType, items := Items}) ->
MUCServer = mod_muc_light_utils:server_host_to_muc_host(HostType, UserJID#jid.lserver),
Q = query(?NS_MUC_LIGHT_BLOCKING, [blocking_item(I) || I <- Items]),
Iq = iq(jid:to_binary(UserJID), MUCServer, <<"set">>, [Q]),
ejabberd_router:route(UserJID, jid:from_binary(MUCServer), Iq),
{ok, "User blocking list updated successfully"}.
-spec blocking_item(blocking_item()) -> exml:element().
blocking_item({What, Action, Who}) ->
#xmlel{name = atom_to_binary(What),
attrs = [{<<"action">>, atom_to_binary(Action)}],
children = [#xmlcdata{ content = jid:to_binary(Who)}]
}.
-spec make_room_config(map()) -> create_req_props().
make_room_config(Options) ->
#create{raw_config = maps:to_list(Options)}.
-spec get_room_user_aff(mongooseim:host_type(), jid:jid(), jid:jid()) ->
{ok, aff()} | {error, room_not_found}.
get_room_user_aff(HostType, RoomJID, UserJID) ->
RoomUS = jid:to_lus(RoomJID),
UserUS = jid:to_lus(UserJID),
case mod_muc_light_db_backend:get_aff_users(HostType, RoomUS) of
{ok, Affs, _Version} ->
{ok, get_aff(UserUS, Affs)};
{error, not_exists} ->
{error, room_not_found}
end.
-spec get_aff(jid:simple_bare_jid(), aff_users()) -> aff().
get_aff(UserUS, Affs) ->
case lists:keyfind(UserUS, 1, Affs) of
{_, Aff} -> Aff;
false -> none
end.
make_room(JID, #config{ raw_config = Options}, AffUsers) ->
make_room(JID, Options, AffUsers);
make_room(JID, Options, AffUsers) when is_list(Options) ->
make_room(JID, maps:from_list(ensure_keys_are_binaries(Options)), AffUsers);
make_room(JID, Options, AffUsers) when is_map(Options) ->
#{jid => JID, aff_users => AffUsers, options => Options}.
ensure_keys_are_binaries([{K, _}|_] = Conf) when is_binary(K) ->
Conf;
ensure_keys_are_binaries(Conf) ->
[{atom_to_binary(K), V} || {K, V} <- Conf].
iq(To, From, Type, Children) ->
UUID = uuid:uuid_to_string(uuid:get_v4(), binary_standard),
#xmlel{name = <<"iq">>,
attrs = [{<<"from">>, From},
{<<"to">>, To},
{<<"type">>, Type},
{<<"id">>, UUID}],
children = Children
}.
query(NS, Children) when is_binary(NS), is_list(Children) ->
#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, NS}],
children = Children
}.
affiliate(JID, Kind) when is_binary(JID), is_binary(Kind) ->
#xmlel{name = <<"user">>,
attrs = [{<<"affiliation">>, Kind}],
children = [ #xmlcdata{ content = JID } ]
}.
maybe_before(undefined, Now) ->
Now;
maybe_before(Timestamp, _) ->
Timestamp.
maybe_caller_jid(undefined, Params) ->
Params;
maybe_caller_jid(CallerJID, Params) ->
Params#{caller_jid => CallerJID}.
op_to_aff(add) -> <<"member">>;
op_to_aff(remove) -> <<"none">>.
fold({_, _} = Result, _) ->
Result;
fold(M, [Step | Rest]) when is_map(M) ->
fold(Step(M), Rest).
|
6c2e0673d4c51945120f64f59efb5ffb5756685b57943c192f08429eed5dccc1 | ucsd-progsys/liquidhaskell | EmptySig.hs | -- This can't catch parse errors
@ LIQUID " --expect - error - containing = parse specification " @
module EmptySig where
{-@ :: foo -> x:Int -> {v:Int | v > x} @-}
foo :: Int -> Int
foo x = x - 1
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/parsing-errors/EmptySig.hs | haskell | This can't catch parse errors
@ :: foo -> x:Int -> {v:Int | v > x} @ | @ LIQUID " --expect - error - containing = parse specification " @
module EmptySig where
foo :: Int -> Int
foo x = x - 1
|
42b2db469dd311ed108d7032ac69b6d38b1a577ffd2dadfc84271f08cf81c6a0 | Zetawar/zetawar | util.cljc | (ns zetawar.util
#?(:cljs
(:require-macros [zetawar.util :refer [inspect]])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Accessors
(defn solo
"Like first, but throws if more than one item."
[coll]
(assert (not (next coll)))
(first coll))
(defn only
"Like first, but throws unless exactly one item."
[coll]
(assert (not (next coll)))
(if-let [result (first coll)]
result
(assert false)))
(defn ssolo
"Same as (solo (solo coll))."
[coll]
(solo (solo coll)))
(defn oonly
"Same as (only (only coll))."
[coll]
(only (only coll)))
(defn select-values
"Returns a vector containing only those values who's key is in ks."
[m ks]
(reduce #(if-let [v (m %2)] (conj %1 v) %1) [] ks))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Math
(defn abs [x]
(#?(:clj Math/abs :cljs js/Math.abs) x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Debugging
(defn log-inspect [expr result]
#?(:cljs (js/console.debug expr result)))
(defn- inspect-1 [expr]
`(let [result# ~expr]
(zetawar.util/log-inspect '~expr result#)
result#))
#?(:clj
(do
(defmacro inspect [& exprs]
`(do ~@(map inspect-1 exprs)))
(defmacro breakpoint []
'(do (js* "debugger;")
nil)) ; (prevent "return debugger;" in compiled javascript)
)
)
| null | https://raw.githubusercontent.com/Zetawar/zetawar/dc1ee8d27afcac1cd98904859289012c2806e58c/src/cljc/zetawar/util.cljc | clojure |
Math
Debugging
(prevent "return debugger;" in compiled javascript) | (ns zetawar.util
#?(:cljs
(:require-macros [zetawar.util :refer [inspect]])))
Accessors
(defn solo
"Like first, but throws if more than one item."
[coll]
(assert (not (next coll)))
(first coll))
(defn only
"Like first, but throws unless exactly one item."
[coll]
(assert (not (next coll)))
(if-let [result (first coll)]
result
(assert false)))
(defn ssolo
"Same as (solo (solo coll))."
[coll]
(solo (solo coll)))
(defn oonly
"Same as (only (only coll))."
[coll]
(only (only coll)))
(defn select-values
"Returns a vector containing only those values who's key is in ks."
[m ks]
(reduce #(if-let [v (m %2)] (conj %1 v) %1) [] ks))
(defn abs [x]
(#?(:clj Math/abs :cljs js/Math.abs) x))
(defn log-inspect [expr result]
#?(:cljs (js/console.debug expr result)))
(defn- inspect-1 [expr]
`(let [result# ~expr]
(zetawar.util/log-inspect '~expr result#)
result#))
#?(:clj
(do
(defmacro inspect [& exprs]
`(do ~@(map inspect-1 exprs)))
(defmacro breakpoint []
'(do (js* "debugger;")
)
)
|
6186da5f1fba319a00ad173fcc57949cb132582b3f078f8481d642c2025e5130 | BrunoBonacci/1config | hierarchical.clj | (ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :no-doc true}
com.brunobonacci.oneconfig.backends.hierarchical
(:refer-clojure :exclude [find load list])
(:require [com.brunobonacci.oneconfig.backend :refer :all]
[com.brunobonacci.oneconfig.util :refer [list-entries]]))
(deftype HierarchicalBackend [read-stores write-stores]
IConfigClient
(find [_ {:keys [key env version change-num] :as config-entry}]
(some #(find % config-entry) read-stores))
IConfigBackend
(load [_ {:keys [key env version change-num] :as config-entry}]
(some #(load % config-entry) read-stores))
(save [_ config-entry]
(run! #(save % config-entry) write-stores))
(list [_ filters]
(->> read-stores
(mapcat #(list % filters))
(list-entries filters))))
(defn hierarchical-backend
[read-stores write-stores]
(HierarchicalBackend.
(remove nil? read-stores)
(remove nil? write-stores)))
| null | https://raw.githubusercontent.com/BrunoBonacci/1config/4cf8284b1b490253ac617bec9d2348c3234931e6/1config-core/src/com/brunobonacci/oneconfig/backends/hierarchical.clj | clojure | (ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :no-doc true}
com.brunobonacci.oneconfig.backends.hierarchical
(:refer-clojure :exclude [find load list])
(:require [com.brunobonacci.oneconfig.backend :refer :all]
[com.brunobonacci.oneconfig.util :refer [list-entries]]))
(deftype HierarchicalBackend [read-stores write-stores]
IConfigClient
(find [_ {:keys [key env version change-num] :as config-entry}]
(some #(find % config-entry) read-stores))
IConfigBackend
(load [_ {:keys [key env version change-num] :as config-entry}]
(some #(load % config-entry) read-stores))
(save [_ config-entry]
(run! #(save % config-entry) write-stores))
(list [_ filters]
(->> read-stores
(mapcat #(list % filters))
(list-entries filters))))
(defn hierarchical-backend
[read-stores write-stores]
(HierarchicalBackend.
(remove nil? read-stores)
(remove nil? write-stores)))
| |
c84388fcbfe4e37b58b572e024dc7e00328aa495ba6d4d39498fbabf51934fe5 | robeverest/cufft | FFT.hs | -- |
Module : Foreign .
Copyright : [ 2013 .. 2018 ] ,
-- License : BSD
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
The cuFFT library is an implementation of Fast Fourier Transform ( FFT )
operations for NVIDIA GPUs .
--
The FFT is a divide - and - conquer algorithm for efficiently computing discrete
Fourier transforms of real- or complex - valued data sets . It is one of the
-- most important and widely used numerical algorithms in computational physics
-- and general signals processing. The cuFFT library provides a simple interface
for computing FFTs on a NVIDIA GPU .
--
-- To use operations from the cuFFT library, the user must allocate the required
-- arrays in the GPU memory space, fill them with data, call the desired
-- sequence of cuFFT library functions, then copy the results from the GPU
-- memory back to the host.
--
-- The < cuda> package can be used for
writing to and retrieving data from the GPU .
--
-- [/Example/]
--
-- _TODO_
--
-- [/Additional information/]
--
For more information , see the NVIDIA cuFFT documentation :
--
-- <>
--
module Foreign.CUDA.FFT (
-- * Control
module Foreign.CUDA.FFT.Plan,
module Foreign.CUDA.FFT.Stream,
module Foreign.CUDA.FFT.Error,
-- * Operations
module Foreign.CUDA.FFT.Execute,
) where
import Foreign.CUDA.FFT.Error ( CUFFTException(..) )
import Foreign.CUDA.FFT.Execute
import Foreign.CUDA.FFT.Plan hiding ( useHandle )
import Foreign.CUDA.FFT.Stream
| null | https://raw.githubusercontent.com/robeverest/cufft/4ca4d3b834369ce2f1ae5c37f4ab93d41f901512/Foreign/CUDA/FFT.hs | haskell | |
License : BSD
Stability : experimental
most important and widely used numerical algorithms in computational physics
and general signals processing. The cuFFT library provides a simple interface
To use operations from the cuFFT library, the user must allocate the required
arrays in the GPU memory space, fill them with data, call the desired
sequence of cuFFT library functions, then copy the results from the GPU
memory back to the host.
The < cuda> package can be used for
[/Example/]
_TODO_
[/Additional information/]
<>
* Control
* Operations | Module : Foreign .
Copyright : [ 2013 .. 2018 ] ,
Maintainer : < >
Portability : non - portable ( GHC extensions )
The cuFFT library is an implementation of Fast Fourier Transform ( FFT )
operations for NVIDIA GPUs .
The FFT is a divide - and - conquer algorithm for efficiently computing discrete
Fourier transforms of real- or complex - valued data sets . It is one of the
for computing FFTs on a NVIDIA GPU .
writing to and retrieving data from the GPU .
For more information , see the NVIDIA cuFFT documentation :
module Foreign.CUDA.FFT (
module Foreign.CUDA.FFT.Plan,
module Foreign.CUDA.FFT.Stream,
module Foreign.CUDA.FFT.Error,
module Foreign.CUDA.FFT.Execute,
) where
import Foreign.CUDA.FFT.Error ( CUFFTException(..) )
import Foreign.CUDA.FFT.Execute
import Foreign.CUDA.FFT.Plan hiding ( useHandle )
import Foreign.CUDA.FFT.Stream
|
e9b8f65f2a890d43d57be5e0755ff836491857c663dcc569c00d1659336e7e26 | sky-big/RabbitMQ | webmachine_deps.erl | @author < >
@author < >
2007 - 2008 Basho Technologies
%%
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.
%% @doc Ensure that the relatively-installed dependencies are on the code
%% loading path, and locate resources relative
%% to this application's path.
-module(webmachine_deps).
-author('Justin Sheehy <>').
-author('Andy Gross <>').
-export([ensure/0, ensure/1]).
-export([get_base_dir/0, get_base_dir/1]).
-export([local_path/1, local_path/2]).
-export([deps_on_path/0, new_siblings/1]).
( ) - > [ ProjNameAndVers ]
%% @doc List of project dependencies on the path.
deps_on_path() ->
ordsets:from_list([filename:basename(filename:dirname(X)) || X <- code:get_path()]).
) - > [ Dir ]
%% @doc Find new siblings paths relative to Module that aren't already on the
%% code path.
new_siblings(Module) ->
Existing = deps_on_path(),
SiblingEbin = [ X || X <- filelib:wildcard(local_path(["deps", "*", "ebin"], Module)),
filename:basename(filename:dirname(X)) /= %% don't include self
filename:basename(filename:dirname(
filename:dirname(
filename:dirname(X)))) ],
Siblings = [filename:dirname(X) || X <- SiblingEbin,
ordsets:is_element(
filename:basename(filename:dirname(X)),
Existing) =:= false],
lists:filter(fun filelib:is_dir/1,
lists:append([[filename:join([X, "ebin"]),
filename:join([X, "include"])] ||
X <- Siblings])).
) - > ok
%% @doc Ensure that all ebin and include paths for dependencies
%% of the application for Module are on the code path.
ensure(Module) ->
code:add_paths(new_siblings(Module)),
ok.
@spec ensure ( ) - > ok
%% @doc Ensure that the ebin and include paths for dependencies of
%% this application are on the code path. Equivalent to
%% ensure(?Module).
ensure() ->
ensure(?MODULE).
get_base_dir(Module ) - > string ( )
%% @doc Return the application directory for Module. It assumes Module is in
a standard OTP layout application in the ebin or src directory .
get_base_dir(Module) ->
{file, Here} = code:is_loaded(Module),
filename:dirname(filename:dirname(Here)).
( ) - > string ( )
%% @doc Return the application directory for this application. Equivalent to
%% get_base_dir(?MODULE).
get_base_dir() ->
get_base_dir(?MODULE).
( ) ] , Module ) - > string ( )
@doc Return an application - relative directory from Module 's application .
local_path(Components, Module) ->
filename:join([get_base_dir(Module) | Components]).
local_path(Components ) - > string ( )
%% @doc Return an application-relative directory for this application.
%% Equivalent to local_path(Components, ?MODULE).
local_path(Components) ->
local_path(Components, ?MODULE).
| null | https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/webmachine-wrapper/webmachine-git/src/webmachine_deps.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.
limitations under the License.
@doc Ensure that the relatively-installed dependencies are on the code
loading path, and locate resources relative
to this application's path.
@doc List of project dependencies on the path.
@doc Find new siblings paths relative to Module that aren't already on the
code path.
don't include self
@doc Ensure that all ebin and include paths for dependencies
of the application for Module are on the code path.
@doc Ensure that the ebin and include paths for dependencies of
this application are on the code path. Equivalent to
ensure(?Module).
@doc Return the application directory for Module. It assumes Module is in
@doc Return the application directory for this application. Equivalent to
get_base_dir(?MODULE).
@doc Return an application-relative directory for this application.
Equivalent to local_path(Components, ?MODULE). | @author < >
@author < >
2007 - 2008 Basho Technologies
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
See the License for the specific language governing permissions and
-module(webmachine_deps).
-author('Justin Sheehy <>').
-author('Andy Gross <>').
-export([ensure/0, ensure/1]).
-export([get_base_dir/0, get_base_dir/1]).
-export([local_path/1, local_path/2]).
-export([deps_on_path/0, new_siblings/1]).
( ) - > [ ProjNameAndVers ]
deps_on_path() ->
ordsets:from_list([filename:basename(filename:dirname(X)) || X <- code:get_path()]).
) - > [ Dir ]
new_siblings(Module) ->
Existing = deps_on_path(),
SiblingEbin = [ X || X <- filelib:wildcard(local_path(["deps", "*", "ebin"], Module)),
filename:basename(filename:dirname(
filename:dirname(
filename:dirname(X)))) ],
Siblings = [filename:dirname(X) || X <- SiblingEbin,
ordsets:is_element(
filename:basename(filename:dirname(X)),
Existing) =:= false],
lists:filter(fun filelib:is_dir/1,
lists:append([[filename:join([X, "ebin"]),
filename:join([X, "include"])] ||
X <- Siblings])).
) - > ok
ensure(Module) ->
code:add_paths(new_siblings(Module)),
ok.
@spec ensure ( ) - > ok
ensure() ->
ensure(?MODULE).
get_base_dir(Module ) - > string ( )
a standard OTP layout application in the ebin or src directory .
get_base_dir(Module) ->
{file, Here} = code:is_loaded(Module),
filename:dirname(filename:dirname(Here)).
( ) - > string ( )
get_base_dir() ->
get_base_dir(?MODULE).
( ) ] , Module ) - > string ( )
@doc Return an application - relative directory from Module 's application .
local_path(Components, Module) ->
filename:join([get_base_dir(Module) | Components]).
local_path(Components ) - > string ( )
local_path(Components) ->
local_path(Components, ?MODULE).
|
623de5dcc01333006f5e47cc14e5313f1d3403ac1f96ccce3fc732eac60357be | The-closed-eye-of-love/pixiv | Spec.hs | # LANGUAGE AllowAmbiguousTypes #
module Main (main) where
import Data.Aeson
import qualified Data.ByteString.Lazy as LBS
import Network.HTTP.Client.TLS (newTlsManager)
import Web.Pixiv.Download
import Web.Pixiv.Types
main :: IO ()
main = do
testDecode @Comments "test/illust_comments.json"
testDecode @Illusts "test/illust_related.json"
testDecode @UserDetail "test/user_detail.json"
testDecode @Illusts "test/user_illusts.json"
testDecode @TrendingTags "test/trending_tags.json"
testDecode @Illusts "test/search_illust.json"
testDecode @UserPreviews "test/user_follower.json"
testDecode @UserPreviews "test/user_following.json"
testDecode @UserPreviews "test/user_mypixiv.json"
manager <- newTlsManager
pillust <- eitherDecodeFileStrict @IllustWrapper "test/illust_detail.json"
case pillust of
Left err -> fail err
Right IllustWrapper {..} -> do
mresult <- runDownloadM manager $ downloadSingleIllust _illust
case mresult of
Just result -> LBS.writeFile "temp.jpg" result >> putStrLn "Write jpg"
_ -> fail "Failed to download"
pmetadata <- eitherDecodeFileStrict @UgoiraMetadataWrapper "test/ugoira_metadata.json"
case pmetadata of
Left err -> fail err
Right UgoiraMetadataWrapper {..} -> do
mresult <- runDownloadM manager $ downloadUgoiraToMP4 _ugoiraMetadata Nothing
case mresult of
Just (stderr, result) -> do
putStrLn stderr
LBS.writeFile "temp.mp4" result >> putStrLn "Write mp4"
_ -> fail "Failed to download"
testDecode :: forall v. (FromJSON v) => FilePath -> IO ()
testDecode path =
eitherDecodeFileStrict @v path >>= \case
Left err -> fail err
Right _ -> putStrLn "Pass"
| null | https://raw.githubusercontent.com/The-closed-eye-of-love/pixiv/5a9cbe28dd52d2bc80db3320a5311750b837a17b/test/Spec.hs | haskell | # LANGUAGE AllowAmbiguousTypes #
module Main (main) where
import Data.Aeson
import qualified Data.ByteString.Lazy as LBS
import Network.HTTP.Client.TLS (newTlsManager)
import Web.Pixiv.Download
import Web.Pixiv.Types
main :: IO ()
main = do
testDecode @Comments "test/illust_comments.json"
testDecode @Illusts "test/illust_related.json"
testDecode @UserDetail "test/user_detail.json"
testDecode @Illusts "test/user_illusts.json"
testDecode @TrendingTags "test/trending_tags.json"
testDecode @Illusts "test/search_illust.json"
testDecode @UserPreviews "test/user_follower.json"
testDecode @UserPreviews "test/user_following.json"
testDecode @UserPreviews "test/user_mypixiv.json"
manager <- newTlsManager
pillust <- eitherDecodeFileStrict @IllustWrapper "test/illust_detail.json"
case pillust of
Left err -> fail err
Right IllustWrapper {..} -> do
mresult <- runDownloadM manager $ downloadSingleIllust _illust
case mresult of
Just result -> LBS.writeFile "temp.jpg" result >> putStrLn "Write jpg"
_ -> fail "Failed to download"
pmetadata <- eitherDecodeFileStrict @UgoiraMetadataWrapper "test/ugoira_metadata.json"
case pmetadata of
Left err -> fail err
Right UgoiraMetadataWrapper {..} -> do
mresult <- runDownloadM manager $ downloadUgoiraToMP4 _ugoiraMetadata Nothing
case mresult of
Just (stderr, result) -> do
putStrLn stderr
LBS.writeFile "temp.mp4" result >> putStrLn "Write mp4"
_ -> fail "Failed to download"
testDecode :: forall v. (FromJSON v) => FilePath -> IO ()
testDecode path =
eitherDecodeFileStrict @v path >>= \case
Left err -> fail err
Right _ -> putStrLn "Pass"
| |
1a81b4e2db5caa45dc3708a9153137cbd917f99d188c47da640f3781a4dc4c71 | erlang-lager/lager | lager_transform.erl | Copyright ( c ) 2011 - 2012 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%% @doc The parse transform used for lager messages.
%% This parse transform rewrites functions calls to lager:Severity/1,2 into
%% a more complicated function that captures module, function, line, pid and
%% time as well. The entire function call is then wrapped in a case that
%% checks the lager_config 'loglevel' value, so the code isn't executed if
%% nothing wishes to consume the message.
-module(lager_transform).
-include("lager.hrl").
-export([parse_transform/2]).
@private
parse_transform(AST, Options) ->
TruncSize = proplists:get_value(lager_truncation_size, Options, ?DEFAULT_TRUNCATION),
Enable = proplists:get_value(lager_print_records_flag, Options, true),
Sinks = [lager] ++ proplists:get_value(lager_extra_sinks, Options, []),
Functions = proplists:get_value(lager_function_transforms, Options, []),
put(print_records_flag, Enable),
put(truncation_size, TruncSize),
put(sinks, Sinks),
put(functions, lists:keysort(1, Functions)),
erlang:put(records, []),
%% .app file should either be in the outdir, or the same dir as the source file
guess_application(proplists:get_value(outdir, Options), hd(AST)),
walk_ast([], AST).
walk_ast(Acc, []) ->
case get(print_records_flag) of
true ->
insert_record_attribute(Acc);
false ->
lists:reverse(Acc)
end;
walk_ast(Acc, [{attribute, _, module, {Module, _PmodArgs}}=H|T]) ->
%% A wild parameterized module appears!
put(module, Module),
walk_ast([H|Acc], T);
walk_ast(Acc, [{attribute, _, module, Module}=H|T]) ->
put(module, Module),
walk_ast([H|Acc], T);
walk_ast(Acc, [{attribute, _, lager_function_transforms, FromModule }=H|T]) ->
%% Merge transform options from the module over the compile options
FromOptions = get(functions),
put(functions, orddict:merge(fun(_Key, _V1, V2) -> V2 end, FromOptions, lists:keysort(1, FromModule))),
walk_ast([H|Acc], T);
walk_ast(Acc, [{function, Line, Name, Arity, Clauses}|T]) ->
put(function, Name),
walk_ast([{function, Line, Name, Arity,
walk_clauses([], Clauses)}|Acc], T);
walk_ast(Acc, [{attribute, _, record, {Name, Fields}}=H|T]) ->
FieldNames = lists:map(fun record_field_name/1, Fields),
stash_record({Name, FieldNames}),
walk_ast([H|Acc], T);
walk_ast(Acc, [H|T]) ->
walk_ast([H|Acc], T).
record_field_name({record_field, _, {atom, _, FieldName}}) ->
FieldName;
record_field_name({record_field, _, {atom, _, FieldName}, _Default}) ->
FieldName;
record_field_name({typed_record_field, Field, _Type}) ->
record_field_name(Field).
walk_clauses(Acc, []) ->
lists:reverse(Acc);
walk_clauses(Acc, [{clause, Line, Arguments, Guards, Body}|T]) ->
walk_clauses([{clause, Line, Arguments, Guards, walk_body([], Body)}|Acc], T).
walk_body(Acc, []) ->
lists:reverse(Acc);
walk_body(Acc, [H|T]) ->
walk_body([transform_statement(H, get(sinks))|Acc], T).
transform_statement({call, Line, {remote, _Line1, {atom, _Line2, Module},
{atom, _Line3, Function}}, Arguments0} = Stmt,
Sinks) ->
case lists:member(Module, Sinks) of
true ->
case lists:member(Function, ?LEVELS) of
true ->
SinkName = lager_util:make_internal_sink_name(Module),
do_transform(Line, SinkName, Function, Arguments0);
false ->
case lists:keyfind(Function, 1, ?LEVELS_UNSAFE) of
{Function, Severity} ->
SinkName = lager_util:make_internal_sink_name(Module),
do_transform(Line, SinkName, Severity, Arguments0, unsafe);
false ->
Stmt
end
end;
false ->
list_to_tuple(transform_statement(tuple_to_list(Stmt), Sinks))
end;
transform_statement(Stmt, Sinks) when is_tuple(Stmt) ->
list_to_tuple(transform_statement(tuple_to_list(Stmt), Sinks));
transform_statement(Stmt, Sinks) when is_list(Stmt) ->
[transform_statement(S, Sinks) || S <- Stmt];
transform_statement(Stmt, _Sinks) ->
Stmt.
add_function_transforms(_Line, DefaultAttrs, []) ->
DefaultAttrs;
add_function_transforms(Line, DefaultAttrs, [{Atom, on_emit, {Module, Function}}|Remainder]) ->
NewFunction = {tuple, Line, [
{atom, Line, Atom},
{'fun', Line, {
function, {atom, Line, Module}, {atom, Line, Function}, {integer, Line, 0}
}}
]},
add_function_transforms(Line, {cons, Line, NewFunction, DefaultAttrs}, Remainder);
add_function_transforms(Line, DefaultAttrs, [{Atom, on_log, {Module, Function}}|Remainder]) ->
NewFunction = {tuple, Line, [
{atom, Line, Atom},
{call, Line, {remote, Line, {atom, Line, Module}, {atom, Line, Function}}, []}
]},
add_function_transforms(Line, {cons, Line, NewFunction, DefaultAttrs}, Remainder).
build_dynamic_attrs(Line) ->
{cons, Line, {tuple, Line, [
{atom, Line, pid},
{call, Line, {atom, Line, pid_to_list}, [
{call, Line, {atom, Line ,self}, []}]}]},
{cons, Line, {tuple, Line, [
{atom, Line, node},
{call, Line, {atom, Line, node}, []}]},
get the metadata with lager : ) , this will always return a list so we can use it as the tail here
{call, Line, {remote, Line, {atom, Line, lager}, {atom, Line, md}}, []}}}.
build_mf_attrs(Line, Attrs0) ->
{cons, Line, {tuple, Line, [
{atom, Line, module}, {atom, Line, get(module)}]},
{cons, Line, {tuple, Line, [
{atom, Line, function}, {atom, Line, get(function)}]},
Attrs0}}.
build_loc_attrs(Line, Attrs0) when is_integer(Line) ->
{cons, Line, {tuple, Line, [
{atom, Line, line}, {integer, Line, Line}]},
Attrs0};
build_loc_attrs(Line = {LineNum, Col}, Attrs0) when is_integer(LineNum), is_integer(Col) ->
{cons, Line, {tuple, Line, [
{atom, Line, line}, {integer, Line, LineNum}]},
{cons, Line, {tuple, Line, [
{atom, Line, col}, {integer, Line, Col}]},
Attrs0}}.
do_transform(Line, SinkName, Severity, Arguments0) ->
do_transform(Line, SinkName, Severity, Arguments0, safe).
do_transform(Line, SinkName, Severity, Arguments0, Safety) ->
SeverityAsInt=lager_util:level_to_num(Severity),
DefaultAttrs0 = build_mf_attrs(Line, build_loc_attrs(Line, build_dynamic_attrs(Line))),
Functions = get(functions),
DefaultAttrs1 = add_function_transforms(Line, DefaultAttrs0, Functions),
DefaultAttrs = case erlang:get(application) of
undefined ->
DefaultAttrs1;
App ->
%% stick the application in the attribute list
concat_lists({cons, Line, {tuple, Line, [
{atom, Line, application},
{atom, Line, App}]},
{nil, Line}}, DefaultAttrs1)
end,
{Meta, Message, Arguments} = handle_args(DefaultAttrs, Line, Arguments0),
%% Generate some unique variable names so we don't accidentally export from case clauses.
Note that these are not actual atoms , but the AST treats variable names as atoms .
LevelVar = make_varname("__Level", Line),
TracesVar = make_varname("__Traces", Line),
PidVar = make_varname("__Pid", Line),
LogFun = case Safety of
safe ->
do_log;
unsafe ->
do_log_unsafe
end,
%% Wrap the call to lager:dispatch_log/6 in case that will avoid doing any work if this message is not eligible for logging
See lager.erl ( lines 89 - 100 ) for lager : dispatch_log/6
case { whereis(Sink ) , whereis(?DEFAULT_SINK ) , lager_config : , loglevel } , { ? LOG_NONE , [ ] } ) } of
{'case',Line,
{tuple,Line,
[{call,Line,{atom,Line,whereis},[{atom,Line,SinkName}]},
{call,Line,{atom,Line,whereis},[{atom,Line,?DEFAULT_SINK}]},
{call,Line,
{remote,Line,{atom,Line,lager_config},{atom,Line,get}},
[{tuple,Line,[{atom,Line,SinkName},{atom,Line,loglevel}]},
{tuple,Line,[{integer,Line,0},{nil,Line}]}]}]},
%% {undefined, undefined, _} -> {error, lager_not_running};
[{clause,Line,
[{tuple,Line,
[{atom,Line,undefined},{atom,Line,undefined},{var,Line,'_'}]}],
[],
[{tuple, erl_anno:set_generated(true, Line), [{atom, Line, error},{atom, Line, lager_not_running}]}]
},
%% {undefined, _, _} -> {error, {sink_not_configured, Sink}};
{clause,Line,
[{tuple,Line,
[{atom,Line,undefined},{var,Line,'_'},{var,Line,'_'}]}],
[],
[{tuple, erl_anno:set_generated(true, Line), [{atom,Line,error}, {tuple,Line,[{atom,Line,sink_not_configured},{atom,Line,SinkName}]}]}]
},
{ SinkPid , _ , { Level , Traces } } when ... - > lager : do_log/9 ;
{clause,Line,
[{tuple,Line,
[{var,Line,PidVar},
{var,Line,'_'},
{tuple,Line,[{var,Line,LevelVar},{var,Line,TracesVar}]}]}],
[[{op, Line, 'orelse',
{op, Line, '/=', {op, Line, 'band', {var, Line, LevelVar}, {integer, Line, SeverityAsInt}}, {integer, Line, 0}},
{op, Line, '/=', {var, Line, TracesVar}, {nil, Line}}}]],
[{call,Line,{remote, Line, {atom, Line, lager}, {atom, Line, LogFun}},
[{atom,Line,Severity},
Meta,
Message,
Arguments,
{integer, Line, get(truncation_size)},
{integer, Line, SeverityAsInt},
{var, Line, LevelVar},
{var, Line, TracesVar},
{atom, Line, SinkName},
{var, Line, PidVar}]}]},
%% _ -> ok
{clause,Line,[{var,Line,'_'}],[],[{atom,Line,ok}]}]}.
handle_args(DefaultAttrs, Line, [{cons, LineNum, {tuple, _, _}, _} = Attrs]) ->
{concat_lists(DefaultAttrs, Attrs), {string, LineNum, ""}, {atom, Line, none}};
handle_args(DefaultAttrs, Line, [Format]) ->
{DefaultAttrs, Format, {atom, Line, none}};
handle_args(DefaultAttrs, Line, [Arg1, Arg2]) ->
%% some ambiguity here, figure out if these arguments are
[ Format , ] or [ Attr , Format ] .
%% The trace attributes will be a list of tuples, so check
%% for that.
case {element(1, Arg1), Arg1} of
{_, {cons, _, {tuple, _, _}, _}} ->
{concat_lists(Arg1, DefaultAttrs),
Arg2, {atom, Line, none}};
{Type, _} when Type == var;
Type == lc;
Type == call;
Type == record_field ->
crap , its not a literal . look at the second
%% argument to see if it is a string
case Arg2 of
{string, _, _} ->
{concat_lists(Arg1, DefaultAttrs),
Arg2, {atom, Line, none}};
_ ->
%% not a string, going to have to guess
%% it's the argument list
{DefaultAttrs, Arg1, Arg2}
end;
_ ->
{DefaultAttrs, Arg1, Arg2}
end;
handle_args(DefaultAttrs, _Line, [Attrs, Format, Args]) ->
{concat_lists(Attrs, DefaultAttrs), Format, Args}.
make_varname(Prefix, CallAnno) ->
list_to_atom(Prefix ++ atom_to_list(get(module)) ++ integer_to_list(erl_anno:line(CallAnno))).
concat 2 list ASTs by replacing the terminating [ ] in A with the contents of B
concat_lists({var, Line, _Name}=Var, B) ->
%% concatenating a var with a cons
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Var, B}]};
concat_lists({lc, Line, _Body, _Generator} = LC, B) ->
concatenating a LC with a cons
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, LC, B}]};
concat_lists({call, Line, _Function, _Args} = Call, B) ->
%% concatenating a call with a cons
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Call, B}]};
concat_lists({record_field, Line, _Var, _Record, _Field} = Rec, B) ->
%% concatenating a record_field with a cons
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Rec, B}]};
concat_lists({nil, _Line}, B) ->
B;
concat_lists({cons, Line, Element, Tail}, B) ->
{cons, Line, Element, concat_lists(Tail, B)}.
stash_record(Record) ->
Records = case erlang:get(records) of
undefined ->
[];
R ->
R
end,
erlang:put(records, [Record|Records]).
insert_record_attribute(AST) ->
lists:foldl(fun({attribute, Line, module, _}=E, Acc) ->
[E, {attribute, Line, lager_records, erlang:get(records)}|Acc];
(E, Acc) ->
[E|Acc]
end, [], AST).
guess_application(Dirname, Attr) when Dirname /= undefined ->
case find_app_file(Dirname) of
no_idea ->
%% try it based on source file directory (app.src most likely)
guess_application(undefined, Attr);
_ ->
ok
end;
guess_application(undefined, {attribute, _, file, {Filename, _}}) ->
Dir = filename:dirname(Filename),
find_app_file(Dir);
guess_application(_, _) ->
ok.
find_app_file(Dir) ->
case filelib:wildcard(Dir++"/*.{app,app.src}") of
[] ->
no_idea;
[File] ->
case file:consult(File) of
{ok, [{application, Appname, _Attributes}|_]} ->
erlang:put(application, Appname);
_ ->
no_idea
end;
_ ->
%% multiple files, uh oh
no_idea
end.
| null | https://raw.githubusercontent.com/erlang-lager/lager/d25595530b34605621c1fcb8c56666ed3bfa1c3d/src/lager_transform.erl | erlang |
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
@doc The parse transform used for lager messages.
This parse transform rewrites functions calls to lager:Severity/1,2 into
a more complicated function that captures module, function, line, pid and
time as well. The entire function call is then wrapped in a case that
checks the lager_config 'loglevel' value, so the code isn't executed if
nothing wishes to consume the message.
.app file should either be in the outdir, or the same dir as the source file
A wild parameterized module appears!
Merge transform options from the module over the compile options
stick the application in the attribute list
Generate some unique variable names so we don't accidentally export from case clauses.
Wrap the call to lager:dispatch_log/6 in case that will avoid doing any work if this message is not eligible for logging
{undefined, undefined, _} -> {error, lager_not_running};
{undefined, _, _} -> {error, {sink_not_configured, Sink}};
_ -> ok
some ambiguity here, figure out if these arguments are
The trace attributes will be a list of tuples, so check
for that.
argument to see if it is a string
not a string, going to have to guess
it's the argument list
concatenating a var with a cons
concatenating a call with a cons
concatenating a record_field with a cons
try it based on source file directory (app.src most likely)
multiple files, uh oh | Copyright ( c ) 2011 - 2012 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(lager_transform).
-include("lager.hrl").
-export([parse_transform/2]).
@private
parse_transform(AST, Options) ->
TruncSize = proplists:get_value(lager_truncation_size, Options, ?DEFAULT_TRUNCATION),
Enable = proplists:get_value(lager_print_records_flag, Options, true),
Sinks = [lager] ++ proplists:get_value(lager_extra_sinks, Options, []),
Functions = proplists:get_value(lager_function_transforms, Options, []),
put(print_records_flag, Enable),
put(truncation_size, TruncSize),
put(sinks, Sinks),
put(functions, lists:keysort(1, Functions)),
erlang:put(records, []),
guess_application(proplists:get_value(outdir, Options), hd(AST)),
walk_ast([], AST).
walk_ast(Acc, []) ->
case get(print_records_flag) of
true ->
insert_record_attribute(Acc);
false ->
lists:reverse(Acc)
end;
walk_ast(Acc, [{attribute, _, module, {Module, _PmodArgs}}=H|T]) ->
put(module, Module),
walk_ast([H|Acc], T);
walk_ast(Acc, [{attribute, _, module, Module}=H|T]) ->
put(module, Module),
walk_ast([H|Acc], T);
walk_ast(Acc, [{attribute, _, lager_function_transforms, FromModule }=H|T]) ->
FromOptions = get(functions),
put(functions, orddict:merge(fun(_Key, _V1, V2) -> V2 end, FromOptions, lists:keysort(1, FromModule))),
walk_ast([H|Acc], T);
walk_ast(Acc, [{function, Line, Name, Arity, Clauses}|T]) ->
put(function, Name),
walk_ast([{function, Line, Name, Arity,
walk_clauses([], Clauses)}|Acc], T);
walk_ast(Acc, [{attribute, _, record, {Name, Fields}}=H|T]) ->
FieldNames = lists:map(fun record_field_name/1, Fields),
stash_record({Name, FieldNames}),
walk_ast([H|Acc], T);
walk_ast(Acc, [H|T]) ->
walk_ast([H|Acc], T).
record_field_name({record_field, _, {atom, _, FieldName}}) ->
FieldName;
record_field_name({record_field, _, {atom, _, FieldName}, _Default}) ->
FieldName;
record_field_name({typed_record_field, Field, _Type}) ->
record_field_name(Field).
walk_clauses(Acc, []) ->
lists:reverse(Acc);
walk_clauses(Acc, [{clause, Line, Arguments, Guards, Body}|T]) ->
walk_clauses([{clause, Line, Arguments, Guards, walk_body([], Body)}|Acc], T).
walk_body(Acc, []) ->
lists:reverse(Acc);
walk_body(Acc, [H|T]) ->
walk_body([transform_statement(H, get(sinks))|Acc], T).
transform_statement({call, Line, {remote, _Line1, {atom, _Line2, Module},
{atom, _Line3, Function}}, Arguments0} = Stmt,
Sinks) ->
case lists:member(Module, Sinks) of
true ->
case lists:member(Function, ?LEVELS) of
true ->
SinkName = lager_util:make_internal_sink_name(Module),
do_transform(Line, SinkName, Function, Arguments0);
false ->
case lists:keyfind(Function, 1, ?LEVELS_UNSAFE) of
{Function, Severity} ->
SinkName = lager_util:make_internal_sink_name(Module),
do_transform(Line, SinkName, Severity, Arguments0, unsafe);
false ->
Stmt
end
end;
false ->
list_to_tuple(transform_statement(tuple_to_list(Stmt), Sinks))
end;
transform_statement(Stmt, Sinks) when is_tuple(Stmt) ->
list_to_tuple(transform_statement(tuple_to_list(Stmt), Sinks));
transform_statement(Stmt, Sinks) when is_list(Stmt) ->
[transform_statement(S, Sinks) || S <- Stmt];
transform_statement(Stmt, _Sinks) ->
Stmt.
add_function_transforms(_Line, DefaultAttrs, []) ->
DefaultAttrs;
add_function_transforms(Line, DefaultAttrs, [{Atom, on_emit, {Module, Function}}|Remainder]) ->
NewFunction = {tuple, Line, [
{atom, Line, Atom},
{'fun', Line, {
function, {atom, Line, Module}, {atom, Line, Function}, {integer, Line, 0}
}}
]},
add_function_transforms(Line, {cons, Line, NewFunction, DefaultAttrs}, Remainder);
add_function_transforms(Line, DefaultAttrs, [{Atom, on_log, {Module, Function}}|Remainder]) ->
NewFunction = {tuple, Line, [
{atom, Line, Atom},
{call, Line, {remote, Line, {atom, Line, Module}, {atom, Line, Function}}, []}
]},
add_function_transforms(Line, {cons, Line, NewFunction, DefaultAttrs}, Remainder).
build_dynamic_attrs(Line) ->
{cons, Line, {tuple, Line, [
{atom, Line, pid},
{call, Line, {atom, Line, pid_to_list}, [
{call, Line, {atom, Line ,self}, []}]}]},
{cons, Line, {tuple, Line, [
{atom, Line, node},
{call, Line, {atom, Line, node}, []}]},
get the metadata with lager : ) , this will always return a list so we can use it as the tail here
{call, Line, {remote, Line, {atom, Line, lager}, {atom, Line, md}}, []}}}.
build_mf_attrs(Line, Attrs0) ->
{cons, Line, {tuple, Line, [
{atom, Line, module}, {atom, Line, get(module)}]},
{cons, Line, {tuple, Line, [
{atom, Line, function}, {atom, Line, get(function)}]},
Attrs0}}.
build_loc_attrs(Line, Attrs0) when is_integer(Line) ->
{cons, Line, {tuple, Line, [
{atom, Line, line}, {integer, Line, Line}]},
Attrs0};
build_loc_attrs(Line = {LineNum, Col}, Attrs0) when is_integer(LineNum), is_integer(Col) ->
{cons, Line, {tuple, Line, [
{atom, Line, line}, {integer, Line, LineNum}]},
{cons, Line, {tuple, Line, [
{atom, Line, col}, {integer, Line, Col}]},
Attrs0}}.
do_transform(Line, SinkName, Severity, Arguments0) ->
do_transform(Line, SinkName, Severity, Arguments0, safe).
do_transform(Line, SinkName, Severity, Arguments0, Safety) ->
SeverityAsInt=lager_util:level_to_num(Severity),
DefaultAttrs0 = build_mf_attrs(Line, build_loc_attrs(Line, build_dynamic_attrs(Line))),
Functions = get(functions),
DefaultAttrs1 = add_function_transforms(Line, DefaultAttrs0, Functions),
DefaultAttrs = case erlang:get(application) of
undefined ->
DefaultAttrs1;
App ->
concat_lists({cons, Line, {tuple, Line, [
{atom, Line, application},
{atom, Line, App}]},
{nil, Line}}, DefaultAttrs1)
end,
{Meta, Message, Arguments} = handle_args(DefaultAttrs, Line, Arguments0),
Note that these are not actual atoms , but the AST treats variable names as atoms .
LevelVar = make_varname("__Level", Line),
TracesVar = make_varname("__Traces", Line),
PidVar = make_varname("__Pid", Line),
LogFun = case Safety of
safe ->
do_log;
unsafe ->
do_log_unsafe
end,
See lager.erl ( lines 89 - 100 ) for lager : dispatch_log/6
case { whereis(Sink ) , whereis(?DEFAULT_SINK ) , lager_config : , loglevel } , { ? LOG_NONE , [ ] } ) } of
{'case',Line,
{tuple,Line,
[{call,Line,{atom,Line,whereis},[{atom,Line,SinkName}]},
{call,Line,{atom,Line,whereis},[{atom,Line,?DEFAULT_SINK}]},
{call,Line,
{remote,Line,{atom,Line,lager_config},{atom,Line,get}},
[{tuple,Line,[{atom,Line,SinkName},{atom,Line,loglevel}]},
{tuple,Line,[{integer,Line,0},{nil,Line}]}]}]},
[{clause,Line,
[{tuple,Line,
[{atom,Line,undefined},{atom,Line,undefined},{var,Line,'_'}]}],
[],
[{tuple, erl_anno:set_generated(true, Line), [{atom, Line, error},{atom, Line, lager_not_running}]}]
},
{clause,Line,
[{tuple,Line,
[{atom,Line,undefined},{var,Line,'_'},{var,Line,'_'}]}],
[],
[{tuple, erl_anno:set_generated(true, Line), [{atom,Line,error}, {tuple,Line,[{atom,Line,sink_not_configured},{atom,Line,SinkName}]}]}]
},
{ SinkPid , _ , { Level , Traces } } when ... - > lager : do_log/9 ;
{clause,Line,
[{tuple,Line,
[{var,Line,PidVar},
{var,Line,'_'},
{tuple,Line,[{var,Line,LevelVar},{var,Line,TracesVar}]}]}],
[[{op, Line, 'orelse',
{op, Line, '/=', {op, Line, 'band', {var, Line, LevelVar}, {integer, Line, SeverityAsInt}}, {integer, Line, 0}},
{op, Line, '/=', {var, Line, TracesVar}, {nil, Line}}}]],
[{call,Line,{remote, Line, {atom, Line, lager}, {atom, Line, LogFun}},
[{atom,Line,Severity},
Meta,
Message,
Arguments,
{integer, Line, get(truncation_size)},
{integer, Line, SeverityAsInt},
{var, Line, LevelVar},
{var, Line, TracesVar},
{atom, Line, SinkName},
{var, Line, PidVar}]}]},
{clause,Line,[{var,Line,'_'}],[],[{atom,Line,ok}]}]}.
handle_args(DefaultAttrs, Line, [{cons, LineNum, {tuple, _, _}, _} = Attrs]) ->
{concat_lists(DefaultAttrs, Attrs), {string, LineNum, ""}, {atom, Line, none}};
handle_args(DefaultAttrs, Line, [Format]) ->
{DefaultAttrs, Format, {atom, Line, none}};
handle_args(DefaultAttrs, Line, [Arg1, Arg2]) ->
[ Format , ] or [ Attr , Format ] .
case {element(1, Arg1), Arg1} of
{_, {cons, _, {tuple, _, _}, _}} ->
{concat_lists(Arg1, DefaultAttrs),
Arg2, {atom, Line, none}};
{Type, _} when Type == var;
Type == lc;
Type == call;
Type == record_field ->
crap , its not a literal . look at the second
case Arg2 of
{string, _, _} ->
{concat_lists(Arg1, DefaultAttrs),
Arg2, {atom, Line, none}};
_ ->
{DefaultAttrs, Arg1, Arg2}
end;
_ ->
{DefaultAttrs, Arg1, Arg2}
end;
handle_args(DefaultAttrs, _Line, [Attrs, Format, Args]) ->
{concat_lists(Attrs, DefaultAttrs), Format, Args}.
make_varname(Prefix, CallAnno) ->
list_to_atom(Prefix ++ atom_to_list(get(module)) ++ integer_to_list(erl_anno:line(CallAnno))).
concat 2 list ASTs by replacing the terminating [ ] in A with the contents of B
concat_lists({var, Line, _Name}=Var, B) ->
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Var, B}]};
concat_lists({lc, Line, _Body, _Generator} = LC, B) ->
concatenating a LC with a cons
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, LC, B}]};
concat_lists({call, Line, _Function, _Args} = Call, B) ->
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Call, B}]};
concat_lists({record_field, Line, _Var, _Record, _Field} = Rec, B) ->
{call, Line, {remote, Line, {atom, Line, lists},{atom, Line, flatten}},
[{cons, Line, Rec, B}]};
concat_lists({nil, _Line}, B) ->
B;
concat_lists({cons, Line, Element, Tail}, B) ->
{cons, Line, Element, concat_lists(Tail, B)}.
stash_record(Record) ->
Records = case erlang:get(records) of
undefined ->
[];
R ->
R
end,
erlang:put(records, [Record|Records]).
insert_record_attribute(AST) ->
lists:foldl(fun({attribute, Line, module, _}=E, Acc) ->
[E, {attribute, Line, lager_records, erlang:get(records)}|Acc];
(E, Acc) ->
[E|Acc]
end, [], AST).
guess_application(Dirname, Attr) when Dirname /= undefined ->
case find_app_file(Dirname) of
no_idea ->
guess_application(undefined, Attr);
_ ->
ok
end;
guess_application(undefined, {attribute, _, file, {Filename, _}}) ->
Dir = filename:dirname(Filename),
find_app_file(Dir);
guess_application(_, _) ->
ok.
find_app_file(Dir) ->
case filelib:wildcard(Dir++"/*.{app,app.src}") of
[] ->
no_idea;
[File] ->
case file:consult(File) of
{ok, [{application, Appname, _Attributes}|_]} ->
erlang:put(application, Appname);
_ ->
no_idea
end;
_ ->
no_idea
end.
|
c4e725f874b290a702dcc8074f9cb6621a05d7a103bcf32fe0378e2335b3da85 | Functional-AutoDiff/STALINGRAD | saddle-FF-ikarus.scm | (define (run)
(let* ((start (list 1.0 1.0))
(f (lambda (x1 y1 x2 y2)
(d- (d+ (sqr x1) (sqr y1)) (d+ (sqr x2) (sqr y2)))))
(x1*-y1*
(multivariate-argmin-F
(lambda (x1-y1)
(multivariate-max-F
(lambda (x2-y2)
(f (car x1-y1) (car (cdr x1-y1)) (car x2-y2) (car (cdr x2-y2))))
start))
start))
(x1* (car x1*-y1*))
(y1* (car (cdr x1*-y1*)))
(x2*-y2*
(multivariate-argmax-F
(lambda (x2-y2) (f x1* y1* (car x2-y2) (car (cdr x2-y2)))) start))
(x2* (car x2*-y2*))
(y2* (car (cdr x2*-y2*))))
(list (list (write-real x1*) (write-real y1*))
(list (write-real x2*) (write-real y2*)))))
| null | https://raw.githubusercontent.com/Functional-AutoDiff/STALINGRAD/8a782171872d5caf414ef9f8b9b0efebaace3b51/examples/examples2009/saddle-FF-ikarus.scm | scheme | (define (run)
(let* ((start (list 1.0 1.0))
(f (lambda (x1 y1 x2 y2)
(d- (d+ (sqr x1) (sqr y1)) (d+ (sqr x2) (sqr y2)))))
(x1*-y1*
(multivariate-argmin-F
(lambda (x1-y1)
(multivariate-max-F
(lambda (x2-y2)
(f (car x1-y1) (car (cdr x1-y1)) (car x2-y2) (car (cdr x2-y2))))
start))
start))
(x1* (car x1*-y1*))
(y1* (car (cdr x1*-y1*)))
(x2*-y2*
(multivariate-argmax-F
(lambda (x2-y2) (f x1* y1* (car x2-y2) (car (cdr x2-y2)))) start))
(x2* (car x2*-y2*))
(y2* (car (cdr x2*-y2*))))
(list (list (write-real x1*) (write-real y1*))
(list (write-real x2*) (write-real y2*)))))
| |
607ef60346559c24c41b57ea29f8d92effc15ffc93f30401503070d3df2dd499 | ProjectMAC/propagators | test-utils.scm | ;;; ----------------------------------------------------------------------
Copyright 2009 Massachusetts Institute of Technology .
;;; ----------------------------------------------------------------------
This file is part of Propagator Network Prototype .
;;;
Propagator Network Prototype 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.
;;;
Propagator Network Prototype 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 Propagator Network Prototype . If not , see
;;; </>.
;;; ----------------------------------------------------------------------
(declare (usual-integrations make-cell cell?))
;;; For looking for memory leaks
(define (garbage-collect-to-stability)
;; This loop is necessary because gc-daemons may make more things
;; unreachable; in principle for arbitrarily many iterations of the
;; gc.
(let loop ((old-memory -1)
(new-memory (gc-flip)))
;; Poke the eq-properties table to make it rehash and clean itself
(eq-get 'full-lexical 'grumble)
(if (< (abs (- new-memory old-memory)) 10)
new-memory
(loop new-memory (gc-flip)))))
(define (memory-loss-from thunk)
(let ((initial-memory (garbage-collect-to-stability)))
(thunk)
(- initial-memory (garbage-collect-to-stability))))
(define (repeat count thunk)
(let loop ((count count))
(if (<= count 0)
'ok
(begin
(thunk)
(loop (- count 1))))))
;; This version is a thunk combinator!
(define ((repeated count thunk))
(repeat count thunk))
;; To make sure the memory for the primes that hash tables use gets
;; allocated now, before I start poking said hash tables.
(let ((upto 150000))
(let force-prime-numbers ((primes prime-numbers-stream))
(if (< upto (car primes))
(car primes)
(force-prime-numbers (force (cdr primes))))))
;;; For stabilizing the string values of printouts that include hash
;;; numbers.
(define (force-hash-number number)
(let loop ((the-hash-number (hash (list 'foo))))
(cond ((> the-hash-number number)
(error "Cannot set hash number to" number))
((= the-hash-number number)
'done)
(else (loop (hash (list 'foo)))))))
| null | https://raw.githubusercontent.com/ProjectMAC/propagators/add671f009e62441e77735a88980b6b21fad7a79/support/test-utils.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
you can
redistribute it and/or modify it under the terms of the GNU
any later version.
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.
</>.
----------------------------------------------------------------------
For looking for memory leaks
This loop is necessary because gc-daemons may make more things
unreachable; in principle for arbitrarily many iterations of the
gc.
Poke the eq-properties table to make it rehash and clean itself
This version is a thunk combinator!
To make sure the memory for the primes that hash tables use gets
allocated now, before I start poking said hash tables.
For stabilizing the string values of printouts that include hash
numbers. | Copyright 2009 Massachusetts Institute of Technology .
This file is part of Propagator Network Prototype .
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Propagator Network Prototype is distributed in the hope that it
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
(declare (usual-integrations make-cell cell?))
(define (garbage-collect-to-stability)
(let loop ((old-memory -1)
(new-memory (gc-flip)))
(eq-get 'full-lexical 'grumble)
(if (< (abs (- new-memory old-memory)) 10)
new-memory
(loop new-memory (gc-flip)))))
(define (memory-loss-from thunk)
(let ((initial-memory (garbage-collect-to-stability)))
(thunk)
(- initial-memory (garbage-collect-to-stability))))
(define (repeat count thunk)
(let loop ((count count))
(if (<= count 0)
'ok
(begin
(thunk)
(loop (- count 1))))))
(define ((repeated count thunk))
(repeat count thunk))
(let ((upto 150000))
(let force-prime-numbers ((primes prime-numbers-stream))
(if (< upto (car primes))
(car primes)
(force-prime-numbers (force (cdr primes))))))
(define (force-hash-number number)
(let loop ((the-hash-number (hash (list 'foo))))
(cond ((> the-hash-number number)
(error "Cannot set hash number to" number))
((= the-hash-number number)
'done)
(else (loop (hash (list 'foo)))))))
|
0cd2143f8807709d6cf1b0fd337d71c481ab50342cf993097610b03587f07f46 | haskell-opengl/OpenGL | DataType.hs | {-# OPTIONS_HADDOCK hide #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.DataType
Copyright : ( c ) 2002 - 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
This is a purely internal module for ( un-)marshaling DataType .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.DataType (
DataType(..), marshalDataType, unmarshalDataType,
DataRepresentation(..), unmarshalDataRepresentation
) where
import Graphics.GL
--------------------------------------------------------------------------------
basically table 8.7 ( pixel data type parameter ) plus a few additions
data DataType =
UnsignedByte
| Byte
| UnsignedShort
| Short
| UnsignedInt
| Int
| HalfFloat
| Float
| UnsignedByte332
| UnsignedByte233Rev
| UnsignedShort565
| UnsignedShort565Rev
| UnsignedShort4444
| UnsignedShort4444Rev
| UnsignedShort5551
| UnsignedShort1555Rev
| UnsignedInt8888
| UnsignedInt8888Rev
| UnsignedInt1010102
| UnsignedInt2101010Rev
| UnsignedInt248
| UnsignedInt10f11f11fRev
| UnsignedInt5999Rev
| Float32UnsignedInt248Rev
pixel data , deprecated in 3.1
MESA_ycbcr_texture / APPLE_ycbcr_422
MESA_ycbcr_texture / APPLE_ycbcr_422
| Double -- vertex arrays (EXT_vertex_array, now core)
CallLists
CallLists
CallLists
deriving ( Eq, Ord, Show )
marshalDataType :: DataType -> GLenum
marshalDataType x = case x of
UnsignedByte -> GL_UNSIGNED_BYTE
Byte -> GL_BYTE
UnsignedShort -> GL_UNSIGNED_SHORT
Short -> GL_SHORT
UnsignedInt -> GL_UNSIGNED_INT
Int -> GL_INT
HalfFloat -> GL_HALF_FLOAT
Float -> GL_FLOAT
UnsignedByte332 -> GL_UNSIGNED_BYTE_3_3_2
UnsignedByte233Rev -> GL_UNSIGNED_BYTE_2_3_3_REV
UnsignedShort565 -> GL_UNSIGNED_SHORT_5_6_5
UnsignedShort565Rev -> GL_UNSIGNED_SHORT_5_6_5_REV
UnsignedShort4444 -> GL_UNSIGNED_SHORT_4_4_4_4
UnsignedShort4444Rev -> GL_UNSIGNED_SHORT_4_4_4_4_REV
UnsignedShort5551 -> GL_UNSIGNED_SHORT_5_5_5_1
UnsignedShort1555Rev -> GL_UNSIGNED_SHORT_1_5_5_5_REV
UnsignedInt8888 -> GL_UNSIGNED_INT_8_8_8_8
UnsignedInt8888Rev -> GL_UNSIGNED_INT_8_8_8_8_REV
UnsignedInt1010102 -> GL_UNSIGNED_INT_10_10_10_2
UnsignedInt2101010Rev -> GL_UNSIGNED_INT_2_10_10_10_REV
UnsignedInt248 -> GL_UNSIGNED_INT_24_8
UnsignedInt10f11f11fRev -> GL_UNSIGNED_INT_10F_11F_11F_REV
UnsignedInt5999Rev -> GL_UNSIGNED_INT_5_9_9_9_REV
Float32UnsignedInt248Rev -> GL_FLOAT_32_UNSIGNED_INT_24_8_REV
Bitmap -> GL_BITMAP
UnsignedShort88 -> GL_UNSIGNED_SHORT_8_8_APPLE
UnsignedShort88Rev -> GL_UNSIGNED_SHORT_8_8_REV_APPLE
Double -> GL_DOUBLE
TwoBytes -> GL_2_BYTES
ThreeBytes -> GL_3_BYTES
FourBytes -> GL_4_BYTES
unmarshalDataType :: GLenum -> DataType
unmarshalDataType x
| x == GL_UNSIGNED_BYTE = UnsignedByte
| x == GL_BYTE = Byte
| x == GL_UNSIGNED_SHORT = UnsignedShort
| x == GL_SHORT = Short
| x == GL_UNSIGNED_INT = UnsignedInt
| x == GL_INT = Int
| x == GL_HALF_FLOAT = HalfFloat
| x == GL_FLOAT = Float
| x == GL_UNSIGNED_BYTE_3_3_2 = UnsignedByte332
| x == GL_UNSIGNED_BYTE_2_3_3_REV = UnsignedByte233Rev
| x == GL_UNSIGNED_SHORT_5_6_5 = UnsignedShort565
| x == GL_UNSIGNED_SHORT_5_6_5_REV = UnsignedShort565Rev
| x == GL_UNSIGNED_SHORT_4_4_4_4 = UnsignedShort4444
| x == GL_UNSIGNED_SHORT_4_4_4_4_REV = UnsignedShort4444Rev
| x == GL_UNSIGNED_SHORT_5_5_5_1 = UnsignedShort5551
| x == GL_UNSIGNED_SHORT_1_5_5_5_REV = UnsignedShort1555Rev
| x == GL_UNSIGNED_INT_8_8_8_8 = UnsignedInt8888
| x == GL_UNSIGNED_INT_8_8_8_8_REV = UnsignedInt8888Rev
| x == GL_UNSIGNED_INT_10_10_10_2 = UnsignedInt1010102
| x == GL_UNSIGNED_INT_2_10_10_10_REV = UnsignedInt2101010Rev
| x == GL_UNSIGNED_INT_24_8 = UnsignedInt248
| x == GL_UNSIGNED_INT_10F_11F_11F_REV = UnsignedInt10f11f11fRev
| x == GL_UNSIGNED_INT_5_9_9_9_REV = UnsignedInt5999Rev
| x == GL_FLOAT_32_UNSIGNED_INT_24_8_REV = Float32UnsignedInt248Rev
| x == GL_BITMAP = Bitmap
| x == GL_UNSIGNED_SHORT_8_8_APPLE = UnsignedShort88
| x == GL_UNSIGNED_SHORT_8_8_REV_APPLE = UnsignedShort88Rev
| x == GL_DOUBLE = Double
| x == GL_2_BYTES = TwoBytes
| x == GL_3_BYTES = ThreeBytes
| x == GL_4_BYTES = FourBytes
| otherwise = error ("unmarshalDataType: illegal value " ++ show x)
data DataRepresentation
= SignedNormalizedRepresentation
| UnsignedNormalizedRepresentation
| FloatRepresentation
| IntRepresentation
| UnsignedIntRepresentation
deriving ( Eq, Ord, Show )
unmarshalDataRepresentation :: GLenum -> Maybe DataRepresentation
unmarshalDataRepresentation x
| x == GL_SIGNED_NORMALIZED = Just SignedNormalizedRepresentation
| x == GL_UNSIGNED_NORMALIZED = Just UnsignedNormalizedRepresentation
| x == GL_FLOAT = Just FloatRepresentation
| x == GL_INT = Just IntRepresentation
| x == GL_UNSIGNED_INT = Just UnsignedIntRepresentation
| x == GL_NONE = Nothing
| otherwise = error $ "unmarshalDataRepresentation: illegal value " ++ show x
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGL/f7af8fe04b0f19c260a85c9ebcad612737cd7c8c/src/Graphics/Rendering/OpenGL/GL/DataType.hs | haskell | # OPTIONS_HADDOCK hide #
------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.DataType
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
------------------------------------------------------------------------------
vertex arrays (EXT_vertex_array, now core) | Copyright : ( c ) 2002 - 2019
Maintainer : < >
This is a purely internal module for ( un-)marshaling DataType .
module Graphics.Rendering.OpenGL.GL.DataType (
DataType(..), marshalDataType, unmarshalDataType,
DataRepresentation(..), unmarshalDataRepresentation
) where
import Graphics.GL
basically table 8.7 ( pixel data type parameter ) plus a few additions
data DataType =
UnsignedByte
| Byte
| UnsignedShort
| Short
| UnsignedInt
| Int
| HalfFloat
| Float
| UnsignedByte332
| UnsignedByte233Rev
| UnsignedShort565
| UnsignedShort565Rev
| UnsignedShort4444
| UnsignedShort4444Rev
| UnsignedShort5551
| UnsignedShort1555Rev
| UnsignedInt8888
| UnsignedInt8888Rev
| UnsignedInt1010102
| UnsignedInt2101010Rev
| UnsignedInt248
| UnsignedInt10f11f11fRev
| UnsignedInt5999Rev
| Float32UnsignedInt248Rev
pixel data , deprecated in 3.1
MESA_ycbcr_texture / APPLE_ycbcr_422
MESA_ycbcr_texture / APPLE_ycbcr_422
CallLists
CallLists
CallLists
deriving ( Eq, Ord, Show )
marshalDataType :: DataType -> GLenum
marshalDataType x = case x of
UnsignedByte -> GL_UNSIGNED_BYTE
Byte -> GL_BYTE
UnsignedShort -> GL_UNSIGNED_SHORT
Short -> GL_SHORT
UnsignedInt -> GL_UNSIGNED_INT
Int -> GL_INT
HalfFloat -> GL_HALF_FLOAT
Float -> GL_FLOAT
UnsignedByte332 -> GL_UNSIGNED_BYTE_3_3_2
UnsignedByte233Rev -> GL_UNSIGNED_BYTE_2_3_3_REV
UnsignedShort565 -> GL_UNSIGNED_SHORT_5_6_5
UnsignedShort565Rev -> GL_UNSIGNED_SHORT_5_6_5_REV
UnsignedShort4444 -> GL_UNSIGNED_SHORT_4_4_4_4
UnsignedShort4444Rev -> GL_UNSIGNED_SHORT_4_4_4_4_REV
UnsignedShort5551 -> GL_UNSIGNED_SHORT_5_5_5_1
UnsignedShort1555Rev -> GL_UNSIGNED_SHORT_1_5_5_5_REV
UnsignedInt8888 -> GL_UNSIGNED_INT_8_8_8_8
UnsignedInt8888Rev -> GL_UNSIGNED_INT_8_8_8_8_REV
UnsignedInt1010102 -> GL_UNSIGNED_INT_10_10_10_2
UnsignedInt2101010Rev -> GL_UNSIGNED_INT_2_10_10_10_REV
UnsignedInt248 -> GL_UNSIGNED_INT_24_8
UnsignedInt10f11f11fRev -> GL_UNSIGNED_INT_10F_11F_11F_REV
UnsignedInt5999Rev -> GL_UNSIGNED_INT_5_9_9_9_REV
Float32UnsignedInt248Rev -> GL_FLOAT_32_UNSIGNED_INT_24_8_REV
Bitmap -> GL_BITMAP
UnsignedShort88 -> GL_UNSIGNED_SHORT_8_8_APPLE
UnsignedShort88Rev -> GL_UNSIGNED_SHORT_8_8_REV_APPLE
Double -> GL_DOUBLE
TwoBytes -> GL_2_BYTES
ThreeBytes -> GL_3_BYTES
FourBytes -> GL_4_BYTES
unmarshalDataType :: GLenum -> DataType
unmarshalDataType x
| x == GL_UNSIGNED_BYTE = UnsignedByte
| x == GL_BYTE = Byte
| x == GL_UNSIGNED_SHORT = UnsignedShort
| x == GL_SHORT = Short
| x == GL_UNSIGNED_INT = UnsignedInt
| x == GL_INT = Int
| x == GL_HALF_FLOAT = HalfFloat
| x == GL_FLOAT = Float
| x == GL_UNSIGNED_BYTE_3_3_2 = UnsignedByte332
| x == GL_UNSIGNED_BYTE_2_3_3_REV = UnsignedByte233Rev
| x == GL_UNSIGNED_SHORT_5_6_5 = UnsignedShort565
| x == GL_UNSIGNED_SHORT_5_6_5_REV = UnsignedShort565Rev
| x == GL_UNSIGNED_SHORT_4_4_4_4 = UnsignedShort4444
| x == GL_UNSIGNED_SHORT_4_4_4_4_REV = UnsignedShort4444Rev
| x == GL_UNSIGNED_SHORT_5_5_5_1 = UnsignedShort5551
| x == GL_UNSIGNED_SHORT_1_5_5_5_REV = UnsignedShort1555Rev
| x == GL_UNSIGNED_INT_8_8_8_8 = UnsignedInt8888
| x == GL_UNSIGNED_INT_8_8_8_8_REV = UnsignedInt8888Rev
| x == GL_UNSIGNED_INT_10_10_10_2 = UnsignedInt1010102
| x == GL_UNSIGNED_INT_2_10_10_10_REV = UnsignedInt2101010Rev
| x == GL_UNSIGNED_INT_24_8 = UnsignedInt248
| x == GL_UNSIGNED_INT_10F_11F_11F_REV = UnsignedInt10f11f11fRev
| x == GL_UNSIGNED_INT_5_9_9_9_REV = UnsignedInt5999Rev
| x == GL_FLOAT_32_UNSIGNED_INT_24_8_REV = Float32UnsignedInt248Rev
| x == GL_BITMAP = Bitmap
| x == GL_UNSIGNED_SHORT_8_8_APPLE = UnsignedShort88
| x == GL_UNSIGNED_SHORT_8_8_REV_APPLE = UnsignedShort88Rev
| x == GL_DOUBLE = Double
| x == GL_2_BYTES = TwoBytes
| x == GL_3_BYTES = ThreeBytes
| x == GL_4_BYTES = FourBytes
| otherwise = error ("unmarshalDataType: illegal value " ++ show x)
data DataRepresentation
= SignedNormalizedRepresentation
| UnsignedNormalizedRepresentation
| FloatRepresentation
| IntRepresentation
| UnsignedIntRepresentation
deriving ( Eq, Ord, Show )
unmarshalDataRepresentation :: GLenum -> Maybe DataRepresentation
unmarshalDataRepresentation x
| x == GL_SIGNED_NORMALIZED = Just SignedNormalizedRepresentation
| x == GL_UNSIGNED_NORMALIZED = Just UnsignedNormalizedRepresentation
| x == GL_FLOAT = Just FloatRepresentation
| x == GL_INT = Just IntRepresentation
| x == GL_UNSIGNED_INT = Just UnsignedIntRepresentation
| x == GL_NONE = Nothing
| otherwise = error $ "unmarshalDataRepresentation: illegal value " ++ show x
|
09c6f1d9ad135ec90beeff8bf8c0994bc83746fe6194c75795698dcee5376da0 | davexunit/guile-2d | ftgl.scm | ;;; guile-2d
Copyright ( C ) 2013 >
;;;
;;; Guile-2d is free software: you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; Guile-2d is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Lesser General Public License for more details.
;;;
You should have received a copy of the GNU Lesser General Public
;;; License along with this program. If not, see
;;; </>.
;;; Commentary:
;;
Quick and dirty wrapper for the library .
;;
;;; Code:
(define-module (2d wrappers ftgl)
#:use-module (system foreign)
#:use-module (2d wrappers util)
#:use-module (ice-9 format))
(define libftgl (dynamic-link "libftgl"))
(define-syntax-rule (define-foreign name ret string-name args)
(define name
(pointer->procedure ret (dynamic-func string-name libftgl) args)))
;;;
;;; Enums
;;;
(define-enumeration ftgl-render-mode
(front #x0001)
(back #x0002)
(side #x0004)
(all #xffff))
(define-enumeration ftgl-text-alignment
(left 0)
(center 1)
(right 2)
(justify 3))
(export ftgl-render-mode
ftgl-text-alignment)
;;;
;;; Fonts
;;;
(define-wrapped-pointer-type <ftgl-font>
ftgl-font?
wrap-ftgl-font unwrap-ftgl-font
(lambda (r port)
(let ((font (unwrap-ftgl-font r)))
(format port
"<ftgl-font ~x>"
(pointer-address font)))))
(define-foreign %ftgl-create-texture-font
'* "ftglCreateTextureFont" '(*))
(define-foreign %ftgl-set-font-face-size
void "ftglSetFontFaceSize" (list '* unsigned-int unsigned-int))
(define-foreign %ftgl-render-font
void "ftglRenderFont" (list '* '* unsigned-int))
(define-foreign %ftgl-get-font-descender
float "ftglGetFontDescender" '(*))
(define-foreign %ftgl-get-font-ascender
float "ftglGetFontAscender" '(*))
(define (ftgl-create-texture-font filename)
(unless (file-exists? filename)
(throw 'font-not-found filename))
(let ((font (%ftgl-create-texture-font (string->pointer filename))))
(when (null-pointer? font)
(throw 'font-load-failure filename))
(wrap-ftgl-font font)))
(define (ftgl-set-font-face-size font size res)
(%ftgl-set-font-face-size (unwrap-ftgl-font font) size res))
(define (ftgl-render-font font text render-mode)
(%ftgl-render-font (unwrap-ftgl-font font)
(string->pointer text)
render-mode))
(define (ftgl-get-font-descender font)
(%ftgl-get-font-descender (unwrap-ftgl-font font)))
(define (ftgl-get-font-ascender font)
(%ftgl-get-font-ascender (unwrap-ftgl-font font)))
(export ftgl-create-texture-font
ftgl-set-font-face-size
ftgl-render-font
ftgl-get-font-descender
ftgl-get-font-ascender)
;;;
SimpleLayout
;;;
(define-wrapped-pointer-type <ftgl-simple-layout>
ftgl-simple-layout?
wrap-ftgl-simple-layout unwrap-ftgl-simple-layout
(lambda (r port)
(let ((simple-layout (unwrap-ftgl-simple-layout r)))
(format port
"<ftgl-simple-layout ~x>"
(pointer-address simple-layout)))))
(define-foreign %ftgl-create-simple-layout
'* "ftglCreateSimpleLayout" '())
(define-foreign %ftgl-destroy-layout
void "ftglDestroyLayout" '(*))
(define-foreign %ftgl-set-layout-font
void "ftglSetLayoutFont" '(* *))
(define-foreign %ftgl-get-layout-font
'* "ftglGetLayoutFont" '(*))
(define-foreign %ftgl-set-layout-line-length
void "ftglSetLayoutLineLength" (list '* float))
(define-foreign %ftgl-get-layout-line-length
float "ftglGetLayoutLineLength" '(*))
(define-foreign %ftgl-set-layout-alignment
void "ftglSetLayoutAlignment" (list '* int))
(define-foreign %ftgl-get-layout-alignment
int "ftglGetLayoutAlignement" '(*))
(define-foreign %ftgl-set-layout-line-spacing
void "ftglSetLayoutLineSpacing" (list '* float))
;; For some reason this symbol is not found.
;; (define-foreign %ftgl-get-layout-line-spacing
;; float "ftglGetLayoutLineSpacing" '(*))
(define-foreign %ftgl-render-layout
void "ftglRenderLayout" (list '* '* int))
(define (ftgl-create-layout)
(wrap-ftgl-simple-layout
(%ftgl-create-simple-layout)))
(define (ftgl-destroy-layout layout)
(%ftgl-destroy-layout (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-font layout font)
(%ftgl-set-layout-font (unwrap-ftgl-simple-layout layout)
(unwrap-ftgl-font font)))
(define (ftgl-get-layout-font layout)
(wrap-ftgl-font
(%ftgl-get-layout-font (unwrap-ftgl-simple-layout layout))))
(define (ftgl-set-layout-line-length layout line-length)
(%ftgl-set-layout-line-length (unwrap-ftgl-simple-layout layout)
line-length))
(define (ftgl-get-layout-line-length layout)
(%ftgl-get-layout-line-length (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-alignment layout alignment)
(%ftgl-set-layout-alignment (unwrap-ftgl-simple-layout layout)
alignment))
(define (ftgl-get-layout-alignment layout)
(%ftgl-get-layout-alignment (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-line-spacing layout spacing)
(%ftgl-set-layout-line-spacing (unwrap-ftgl-simple-layout layout)
spacing))
(define (ftgl-render-layout layout text mode)
(%ftgl-render-layout (unwrap-ftgl-simple-layout layout)
(string->pointer text)
mode))
(export ftgl-create-layout
ftgl-destroy-layout
ftgl-set-layout-font
ftgl-get-layout-font
ftgl-set-layout-line-length
ftgl-get-layout-line-length
ftgl-set-layout-alignment
ftgl-get-layout-alignment
ftgl-set-layout-line-spacing
ftgl-render-layout)
| null | https://raw.githubusercontent.com/davexunit/guile-2d/83d9dfab5b04a337565cb2798847b15e4fbd7786/2d/wrappers/ftgl.scm | scheme | guile-2d
Guile-2d is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
License, or (at your option) any later version.
Guile-2d 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.
License along with this program. If not, see
</>.
Commentary:
Code:
Enums
Fonts
For some reason this symbol is not found.
(define-foreign %ftgl-get-layout-line-spacing
float "ftglGetLayoutLineSpacing" '(*)) | Copyright ( C ) 2013 >
published by the Free Software Foundation , either version 3 of the
You should have received a copy of the GNU Lesser General Public
Quick and dirty wrapper for the library .
(define-module (2d wrappers ftgl)
#:use-module (system foreign)
#:use-module (2d wrappers util)
#:use-module (ice-9 format))
(define libftgl (dynamic-link "libftgl"))
(define-syntax-rule (define-foreign name ret string-name args)
(define name
(pointer->procedure ret (dynamic-func string-name libftgl) args)))
(define-enumeration ftgl-render-mode
(front #x0001)
(back #x0002)
(side #x0004)
(all #xffff))
(define-enumeration ftgl-text-alignment
(left 0)
(center 1)
(right 2)
(justify 3))
(export ftgl-render-mode
ftgl-text-alignment)
(define-wrapped-pointer-type <ftgl-font>
ftgl-font?
wrap-ftgl-font unwrap-ftgl-font
(lambda (r port)
(let ((font (unwrap-ftgl-font r)))
(format port
"<ftgl-font ~x>"
(pointer-address font)))))
(define-foreign %ftgl-create-texture-font
'* "ftglCreateTextureFont" '(*))
(define-foreign %ftgl-set-font-face-size
void "ftglSetFontFaceSize" (list '* unsigned-int unsigned-int))
(define-foreign %ftgl-render-font
void "ftglRenderFont" (list '* '* unsigned-int))
(define-foreign %ftgl-get-font-descender
float "ftglGetFontDescender" '(*))
(define-foreign %ftgl-get-font-ascender
float "ftglGetFontAscender" '(*))
(define (ftgl-create-texture-font filename)
(unless (file-exists? filename)
(throw 'font-not-found filename))
(let ((font (%ftgl-create-texture-font (string->pointer filename))))
(when (null-pointer? font)
(throw 'font-load-failure filename))
(wrap-ftgl-font font)))
(define (ftgl-set-font-face-size font size res)
(%ftgl-set-font-face-size (unwrap-ftgl-font font) size res))
(define (ftgl-render-font font text render-mode)
(%ftgl-render-font (unwrap-ftgl-font font)
(string->pointer text)
render-mode))
(define (ftgl-get-font-descender font)
(%ftgl-get-font-descender (unwrap-ftgl-font font)))
(define (ftgl-get-font-ascender font)
(%ftgl-get-font-ascender (unwrap-ftgl-font font)))
(export ftgl-create-texture-font
ftgl-set-font-face-size
ftgl-render-font
ftgl-get-font-descender
ftgl-get-font-ascender)
SimpleLayout
(define-wrapped-pointer-type <ftgl-simple-layout>
ftgl-simple-layout?
wrap-ftgl-simple-layout unwrap-ftgl-simple-layout
(lambda (r port)
(let ((simple-layout (unwrap-ftgl-simple-layout r)))
(format port
"<ftgl-simple-layout ~x>"
(pointer-address simple-layout)))))
(define-foreign %ftgl-create-simple-layout
'* "ftglCreateSimpleLayout" '())
(define-foreign %ftgl-destroy-layout
void "ftglDestroyLayout" '(*))
(define-foreign %ftgl-set-layout-font
void "ftglSetLayoutFont" '(* *))
(define-foreign %ftgl-get-layout-font
'* "ftglGetLayoutFont" '(*))
(define-foreign %ftgl-set-layout-line-length
void "ftglSetLayoutLineLength" (list '* float))
(define-foreign %ftgl-get-layout-line-length
float "ftglGetLayoutLineLength" '(*))
(define-foreign %ftgl-set-layout-alignment
void "ftglSetLayoutAlignment" (list '* int))
(define-foreign %ftgl-get-layout-alignment
int "ftglGetLayoutAlignement" '(*))
(define-foreign %ftgl-set-layout-line-spacing
void "ftglSetLayoutLineSpacing" (list '* float))
(define-foreign %ftgl-render-layout
void "ftglRenderLayout" (list '* '* int))
(define (ftgl-create-layout)
(wrap-ftgl-simple-layout
(%ftgl-create-simple-layout)))
(define (ftgl-destroy-layout layout)
(%ftgl-destroy-layout (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-font layout font)
(%ftgl-set-layout-font (unwrap-ftgl-simple-layout layout)
(unwrap-ftgl-font font)))
(define (ftgl-get-layout-font layout)
(wrap-ftgl-font
(%ftgl-get-layout-font (unwrap-ftgl-simple-layout layout))))
(define (ftgl-set-layout-line-length layout line-length)
(%ftgl-set-layout-line-length (unwrap-ftgl-simple-layout layout)
line-length))
(define (ftgl-get-layout-line-length layout)
(%ftgl-get-layout-line-length (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-alignment layout alignment)
(%ftgl-set-layout-alignment (unwrap-ftgl-simple-layout layout)
alignment))
(define (ftgl-get-layout-alignment layout)
(%ftgl-get-layout-alignment (unwrap-ftgl-simple-layout layout)))
(define (ftgl-set-layout-line-spacing layout spacing)
(%ftgl-set-layout-line-spacing (unwrap-ftgl-simple-layout layout)
spacing))
(define (ftgl-render-layout layout text mode)
(%ftgl-render-layout (unwrap-ftgl-simple-layout layout)
(string->pointer text)
mode))
(export ftgl-create-layout
ftgl-destroy-layout
ftgl-set-layout-font
ftgl-get-layout-font
ftgl-set-layout-line-length
ftgl-get-layout-line-length
ftgl-set-layout-alignment
ftgl-get-layout-alignment
ftgl-set-layout-line-spacing
ftgl-render-layout)
|
65d5a5f00321d5f9a2c027ac961184784125286774efc2c6a570dac47259f3e8 | tebello-thejane/bitx.hs | Order.hs | {-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Bitcoin.BitX.Private.Order
Copyright : 2016 Tebello Thejane
-- License : BSD3
--
-- Maintainer : Tebello Thejane <zyxoas+>
-- Stability : Experimental
Portability : non - portable ( GHC Extensions )
--
-- Creating and working with orders
--
-- Trading on the market is done by submitting trade orders. After a new order has been created,
-- it is submitted for processing by the order matching engine. The order then either matches
-- against an existing order in the order book and is filled or it rests in the order book until it
-- is stopped.
--
-----------------------------------------------------------------------------
module Network.Bitcoin.BitX.Private.Order
(
getAllOrders,
postOrder,
stopOrder,
getOrder,
postMarketOrder,
getAllTrades
) where
import Network.Bitcoin.BitX.Internal
import Network.Bitcoin.BitX.Types
import qualified Data.Text as Txt
import Network.Bitcoin.BitX.Response
import Data.Monoid ((<>))
import Data.Time (UTCTime)
import Network.Bitcoin.BitX.Types.Internal (timeToTimestamp)
| Returns a list of the most recently placed orders .
If the second parameter is @Nothing@ then this will return orders for all markets , whereas if it is
@Just cpy@ for some @CcyPair cpy@ then the results will be specific to that market .
If the third parameter is @Nothing@ then this will return orders in all states , whereas if it is
@Just COMPLETE@ or @Just PENDING@ then it will return only completed or pending orders , respectively .
This list is truncated after 100 items .
@Perm_R_Orders@ permission is required .
If the second parameter is @Nothing@ then this will return orders for all markets, whereas if it is
@Just cpy@ for some @CcyPair cpy@ then the results will be specific to that market.
If the third parameter is @Nothing@ then this will return orders in all states, whereas if it is
@Just COMPLETE@ or @Just PENDING@ then it will return only completed or pending orders, respectively.
This list is truncated after 100 items.
@Perm_R_Orders@ permission is required.
-}
getAllOrders :: BitXAuth -> Maybe CcyPair -> Maybe RequestStatus -> IO (BitXAPIResponse [PrivateOrder])
getAllOrders auth cpair stat = simpleBitXGetAuth_ auth url
where
url = "listorders" <> case (cpair, stat) of
(Nothing, Nothing) -> ""
(Just pr, Nothing) -> "?pair=" <> Txt.pack (show pr)
(Nothing, Just st) -> "?state=" <> Txt.pack (show st)
(Just pr, Just st) -> "?pair=" <> Txt.pack (show pr) <> "&state=" <> Txt.pack (show st)
{- | Create a new order.
__Warning! Orders cannot be reversed once they have executed. Please ensure your program has been__
__thoroughly tested before submitting orders.__
@Perm_W_Orders@ permission is required.
-}
postOrder :: BitXAuth -> OrderRequest -> IO (BitXAPIResponse OrderID)
postOrder auth oreq = simpleBitXPOSTAuth_ auth oreq "postorder"
{- | Request to stop an order.
@Perm_W_Orders@ permission is required.
-}
stopOrder :: BitXAuth -> OrderID -> IO (BitXAPIResponse RequestSuccess)
stopOrder auth oid = simpleBitXPOSTAuth_ auth oid "stoporder"
{- | Get an order by its ID
@Perm_R_Orders@ permission is required.
-}
getOrder :: BitXAuth -> OrderID -> IO (BitXAPIResponse PrivateOrder)
getOrder auth oid = simpleBitXGetAuth_ auth $ "orders/" <> oid
{- | Create a new market order.
__Warning! Orders cannot be reversed once they have executed. Please ensure your program has been__
__thoroughly tested before submitting orders.__
A market order executes immediately, and either buys as much bitcoin that can be
bought for a set amount of fiat currency, or sells a set amount of bitcoin for
as much fiat as possible.
Use order type @BID@ to buy bitcoin or @ASK@ to sell.
@Perm_W_Orders@ permission is required.
-}
postMarketOrder :: BitXAuth -> MarketOrderRequest -> IO (BitXAPIResponse OrderID)
postMarketOrder auth moreq = simpleBitXPOSTAuth_ auth moreq "marketorder"
| Returns a list of your recent trades for a given pair , sorted by oldest first .
@Perm_R_Orders@ permission is required .
@Perm_R_Orders@ permission is required.
-}
getAllTrades :: BitXAuth -> CcyPair -> Maybe UTCTime -> Maybe Integer -> IO (BitXAPIResponse [PrivateTrade])
getAllTrades auth cpair since limit = simpleBitXGetAuth_ auth url
where
url = "listtrades?pair=" <> (Txt.pack $ show cpair) <> case (since, limit) of
(Nothing, Nothing) -> ""
(Just sn, Nothing) -> "&since=" <> Txt.pack (show (timeToTimestamp sn))
(Nothing, Just lm) -> "&limit=" <> Txt.pack (show lm)
(Just sn, Just lm) -> "&since=" <> Txt.pack (show (timeToTimestamp sn)) <> "&limit=" <> Txt.pack (show lm)
| null | https://raw.githubusercontent.com/tebello-thejane/bitx.hs/d5b1211656192b90381732ee31ca631e5031041b/src/Network/Bitcoin/BitX/Private/Order.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
|
Module : Network.Bitcoin.BitX.Private.Order
License : BSD3
Maintainer : Tebello Thejane <zyxoas+>
Stability : Experimental
Creating and working with orders
Trading on the market is done by submitting trade orders. After a new order has been created,
it is submitted for processing by the order matching engine. The order then either matches
against an existing order in the order book and is filled or it rests in the order book until it
is stopped.
---------------------------------------------------------------------------
| Create a new order.
__Warning! Orders cannot be reversed once they have executed. Please ensure your program has been__
__thoroughly tested before submitting orders.__
@Perm_W_Orders@ permission is required.
| Request to stop an order.
@Perm_W_Orders@ permission is required.
| Get an order by its ID
@Perm_R_Orders@ permission is required.
| Create a new market order.
__Warning! Orders cannot be reversed once they have executed. Please ensure your program has been__
__thoroughly tested before submitting orders.__
A market order executes immediately, and either buys as much bitcoin that can be
bought for a set amount of fiat currency, or sells a set amount of bitcoin for
as much fiat as possible.
Use order type @BID@ to buy bitcoin or @ASK@ to sell.
@Perm_W_Orders@ permission is required.
|
Copyright : 2016 Tebello Thejane
Portability : non - portable ( GHC Extensions )
module Network.Bitcoin.BitX.Private.Order
(
getAllOrders,
postOrder,
stopOrder,
getOrder,
postMarketOrder,
getAllTrades
) where
import Network.Bitcoin.BitX.Internal
import Network.Bitcoin.BitX.Types
import qualified Data.Text as Txt
import Network.Bitcoin.BitX.Response
import Data.Monoid ((<>))
import Data.Time (UTCTime)
import Network.Bitcoin.BitX.Types.Internal (timeToTimestamp)
| Returns a list of the most recently placed orders .
If the second parameter is @Nothing@ then this will return orders for all markets , whereas if it is
@Just cpy@ for some @CcyPair cpy@ then the results will be specific to that market .
If the third parameter is @Nothing@ then this will return orders in all states , whereas if it is
@Just COMPLETE@ or @Just PENDING@ then it will return only completed or pending orders , respectively .
This list is truncated after 100 items .
@Perm_R_Orders@ permission is required .
If the second parameter is @Nothing@ then this will return orders for all markets, whereas if it is
@Just cpy@ for some @CcyPair cpy@ then the results will be specific to that market.
If the third parameter is @Nothing@ then this will return orders in all states, whereas if it is
@Just COMPLETE@ or @Just PENDING@ then it will return only completed or pending orders, respectively.
This list is truncated after 100 items.
@Perm_R_Orders@ permission is required.
-}
getAllOrders :: BitXAuth -> Maybe CcyPair -> Maybe RequestStatus -> IO (BitXAPIResponse [PrivateOrder])
getAllOrders auth cpair stat = simpleBitXGetAuth_ auth url
where
url = "listorders" <> case (cpair, stat) of
(Nothing, Nothing) -> ""
(Just pr, Nothing) -> "?pair=" <> Txt.pack (show pr)
(Nothing, Just st) -> "?state=" <> Txt.pack (show st)
(Just pr, Just st) -> "?pair=" <> Txt.pack (show pr) <> "&state=" <> Txt.pack (show st)
postOrder :: BitXAuth -> OrderRequest -> IO (BitXAPIResponse OrderID)
postOrder auth oreq = simpleBitXPOSTAuth_ auth oreq "postorder"
stopOrder :: BitXAuth -> OrderID -> IO (BitXAPIResponse RequestSuccess)
stopOrder auth oid = simpleBitXPOSTAuth_ auth oid "stoporder"
getOrder :: BitXAuth -> OrderID -> IO (BitXAPIResponse PrivateOrder)
getOrder auth oid = simpleBitXGetAuth_ auth $ "orders/" <> oid
postMarketOrder :: BitXAuth -> MarketOrderRequest -> IO (BitXAPIResponse OrderID)
postMarketOrder auth moreq = simpleBitXPOSTAuth_ auth moreq "marketorder"
| Returns a list of your recent trades for a given pair , sorted by oldest first .
@Perm_R_Orders@ permission is required .
@Perm_R_Orders@ permission is required.
-}
getAllTrades :: BitXAuth -> CcyPair -> Maybe UTCTime -> Maybe Integer -> IO (BitXAPIResponse [PrivateTrade])
getAllTrades auth cpair since limit = simpleBitXGetAuth_ auth url
where
url = "listtrades?pair=" <> (Txt.pack $ show cpair) <> case (since, limit) of
(Nothing, Nothing) -> ""
(Just sn, Nothing) -> "&since=" <> Txt.pack (show (timeToTimestamp sn))
(Nothing, Just lm) -> "&limit=" <> Txt.pack (show lm)
(Just sn, Just lm) -> "&since=" <> Txt.pack (show (timeToTimestamp sn)) <> "&limit=" <> Txt.pack (show lm)
|
d1fb900ce466618450f36ab1141bde8aca6e46be82c997345769f894db5b32d3 | ichko/fmi-fp-2020-21 | XMLParserTemplate.hs | # LANGUAGE NamedFieldPuns #
module XMLParser where
import Control.Applicative
import Data.Char
import ParserUtils
import Prelude hiding (span)
type Attribute = (String, String)
data TagElement = TagElement
{ name :: String,
attributes :: [Attribute],
children :: [XMLObject]
}
deriving (Show, Read, Eq)
data XMLObject
= Text String
| Element TagElement
deriving (Show, Read, Eq)
xmlParser :: Parser XMLObject
xmlParser = Text <$> nomAll -- Implement This
| null | https://raw.githubusercontent.com/ichko/fmi-fp-2020-21/83dea8db7666e7a8a372d82301d71c79d5b798ff/hw/2/task-2/XMLParserTemplate.hs | haskell | Implement This | # LANGUAGE NamedFieldPuns #
module XMLParser where
import Control.Applicative
import Data.Char
import ParserUtils
import Prelude hiding (span)
type Attribute = (String, String)
data TagElement = TagElement
{ name :: String,
attributes :: [Attribute],
children :: [XMLObject]
}
deriving (Show, Read, Eq)
data XMLObject
= Text String
| Element TagElement
deriving (Show, Read, Eq)
xmlParser :: Parser XMLObject
|
8bd21737ab592a90228d96fb9c00e5d073da1324d050d57ecd474c5d9b66db16 | aggieben/weblocks | scaffold.lisp |
(in-package :weblocks)
(export '(form-scaffold typespec->form-view-field-parser))
(defclass form-scaffold (scaffold)
()
(:documentation "Form scaffold."))
(defmethod generate-scaffold-view ((scaffold form-scaffold) object-class)
(make-instance (scaffold-view-type scaffold)
:inherit-from nil
:fields (mapcar
(curry #'generate-scaffold-view-field scaffold object-class)
(class-visible-slots object-class :readablep t :writablep t))))
(defmethod generate-scaffold-view-field ((scaffold form-scaffold)
object-class dsd)
(let ((slot-type (slot-definition-type dsd)))
(apply #'make-instance (scaffold-view-field-type scaffold)
:slot-name (slot-definition-name dsd)
:label (humanize-name (slot-definition-name dsd))
:requiredp (and slot-type (not (typep nil slot-type)))
(append
(extract-view-property-from-type :present-as #'typespec->view-field-presentation
scaffold dsd)
(extract-view-property-from-type :parse-as #'typespec->form-view-field-parser
scaffold dsd)))))
;;; Type introspection protocol
(defgeneric typespec->form-view-field-parser (scaffold typespec args)
(:documentation "Converts a typespec to a parser argument. See
'typespec->view-field-presentation' for more information.")
(:method ((scaffold form-scaffold) typespec args)
(declare (ignore typespec args))
nil))
| null | https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/src/views/formview/scaffold.lisp | lisp | Type introspection protocol |
(in-package :weblocks)
(export '(form-scaffold typespec->form-view-field-parser))
(defclass form-scaffold (scaffold)
()
(:documentation "Form scaffold."))
(defmethod generate-scaffold-view ((scaffold form-scaffold) object-class)
(make-instance (scaffold-view-type scaffold)
:inherit-from nil
:fields (mapcar
(curry #'generate-scaffold-view-field scaffold object-class)
(class-visible-slots object-class :readablep t :writablep t))))
(defmethod generate-scaffold-view-field ((scaffold form-scaffold)
object-class dsd)
(let ((slot-type (slot-definition-type dsd)))
(apply #'make-instance (scaffold-view-field-type scaffold)
:slot-name (slot-definition-name dsd)
:label (humanize-name (slot-definition-name dsd))
:requiredp (and slot-type (not (typep nil slot-type)))
(append
(extract-view-property-from-type :present-as #'typespec->view-field-presentation
scaffold dsd)
(extract-view-property-from-type :parse-as #'typespec->form-view-field-parser
scaffold dsd)))))
(defgeneric typespec->form-view-field-parser (scaffold typespec args)
(:documentation "Converts a typespec to a parser argument. See
'typespec->view-field-presentation' for more information.")
(:method ((scaffold form-scaffold) typespec args)
(declare (ignore typespec args))
nil))
|
933a869057689f46f5cc875a72e96acd4453513c941fbee1fddd48e4c70915ff | otakup0pe/magicbeam | thunder_gen_server.erl | -module(thunder_gen_server).
-export([start_link/3, start_link/4, call/2, call/3, cast/2]).
-include("magicbeam.hrl").
start_link(CB, Opaque, Args) ->
wait(),
gen_server:start_link(CB, Opaque, Args).
start_link(Name, CB, Opaque, Args) ->
wait(),
gen_server:start_link(Name, CB, Opaque, Args).
call(N, M) ->
wait(),
gen_server:call(N, M).
call(N, M, T) ->
wait(),
gen_server:call(N, M, T).
cast(N, M) ->
wait(),
gen_server:cast(N, M).
wait() ->
magicbeam_util:random(?THUNDER_GS_MIN, ?THUNDER_GS_MAX).
| null | https://raw.githubusercontent.com/otakup0pe/magicbeam/e8907b0c3ed1afa96c4e635e4f6b345aacdb88ee/src/thunder_gen_server.erl | erlang | -module(thunder_gen_server).
-export([start_link/3, start_link/4, call/2, call/3, cast/2]).
-include("magicbeam.hrl").
start_link(CB, Opaque, Args) ->
wait(),
gen_server:start_link(CB, Opaque, Args).
start_link(Name, CB, Opaque, Args) ->
wait(),
gen_server:start_link(Name, CB, Opaque, Args).
call(N, M) ->
wait(),
gen_server:call(N, M).
call(N, M, T) ->
wait(),
gen_server:call(N, M, T).
cast(N, M) ->
wait(),
gen_server:cast(N, M).
wait() ->
magicbeam_util:random(?THUNDER_GS_MIN, ?THUNDER_GS_MAX).
| |
095e2604456991f50fc116ea4c0a3745d9bb576eb9b0d2424690b6442f7ea762 | svenpanne/EOPL3 | exercise-B-02.rkt | #lang eopl
; ------------------------------------------------------------------------------
; Exercise B.2
;
; separated-list is a bit restricted and expects a string as a separator, but we
; need a nonterminal or a token.
| null | https://raw.githubusercontent.com/svenpanne/EOPL3/3fc14c4dbb1c53a37bd67399eba34cea8f8234cc/appendixB/exercise-B-02.rkt | racket | ------------------------------------------------------------------------------
Exercise B.2
separated-list is a bit restricted and expects a string as a separator, but we
need a nonterminal or a token. | #lang eopl
|
d60f1b1385dc303e1eccdebe99fc6899a2bd29320624a4cfce9f0c52bde7dfbf | andreas/mirage-swim | stack_ext.ml | open V1
open Core_kernel.Std
(* Make Ipaddr.V4.t compatible with bin_io and sexp *)
module Make(S : STACKV4) = struct
include S
module Ipv4Binable = Bin_prot.Utils.Make_binable(struct
module Binable = String
type t = Ipaddr.V4.t
let to_binable = Ipaddr.V4.to_bytes
let of_binable = Ipaddr.V4.of_bytes_exn
end)
let bin_size_ipv4addr = Ipv4Binable.bin_size_t
let bin_write_ipv4addr = Ipv4Binable.bin_write_t
let bin_read_ipv4addr = Ipv4Binable.bin_read_t
let ipv4addr_of_sexp t =
t
|> Sexp.to_string
|> Ipaddr.V4.of_string_exn
let sexp_of_ipv4addr t =
t
|> Ipaddr.V4.to_string
|> Sexp.of_string
end
| null | https://raw.githubusercontent.com/andreas/mirage-swim/23d893db0894ea1fe7012de8e1da03f36faf893a/stack_ext.ml | ocaml | Make Ipaddr.V4.t compatible with bin_io and sexp | open V1
open Core_kernel.Std
module Make(S : STACKV4) = struct
include S
module Ipv4Binable = Bin_prot.Utils.Make_binable(struct
module Binable = String
type t = Ipaddr.V4.t
let to_binable = Ipaddr.V4.to_bytes
let of_binable = Ipaddr.V4.of_bytes_exn
end)
let bin_size_ipv4addr = Ipv4Binable.bin_size_t
let bin_write_ipv4addr = Ipv4Binable.bin_write_t
let bin_read_ipv4addr = Ipv4Binable.bin_read_t
let ipv4addr_of_sexp t =
t
|> Sexp.to_string
|> Ipaddr.V4.of_string_exn
let sexp_of_ipv4addr t =
t
|> Ipaddr.V4.to_string
|> Sexp.of_string
end
|
34193419fc49a135eb4aa35db07cd247b945f6f57f3b7492e7ab45c7b70160f5 | digital-asset/ghc | tc079.hs | # OPTIONS_GHC -fno - warn - redundant - constraints #
-- !!! small class decl with local polymorphism;
-- !!! "easy" to check default methods and such...
! ! ! ( this is the example given in TcClassDcl )
--
module ShouldSucceed where
class Foo a where
op1 :: a -> Bool
op2 :: Ord b => a -> b -> b -> b
op1 x = True
op2 x y z = if (op1 x) && (y < z) then y else z
instance Foo Int where {}
instance Foo a => Foo [a] where {}
| null | https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/typecheck/should_compile/tc079.hs | haskell | !!! small class decl with local polymorphism;
!!! "easy" to check default methods and such...
| # OPTIONS_GHC -fno - warn - redundant - constraints #
! ! ! ( this is the example given in TcClassDcl )
module ShouldSucceed where
class Foo a where
op1 :: a -> Bool
op2 :: Ord b => a -> b -> b -> b
op1 x = True
op2 x y z = if (op1 x) && (y < z) then y else z
instance Foo Int where {}
instance Foo a => Foo [a] where {}
|
3f6ca63beaddc53290bf4bfd8aa9f823ac39008181ef48184d3342b0e5a4d2d8 | alanz/ghc-exactprint | Test10396.hs | # LANGUAGE ScopedTypeVariables #
module Test10396 where
errors :: IO ()
errors= do
let ls :: Int = undefined
return ()
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/Test10396.hs | haskell | # LANGUAGE ScopedTypeVariables #
module Test10396 where
errors :: IO ()
errors= do
let ls :: Int = undefined
return ()
| |
2c8093e05003d9c5ba74ebbee7dcda41faad85411db53c319e8c66f6b6f62b83 | ruricolist/lisp-magick-wand | types.lisp | ImageMagick binding for Common Lisp
Copyright ( c ) 2006 , 2007 , 2008 , 2009 < >
;;;; All rights reserved.
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions are met:
;;;;
;;;; * Redistributions of source code must retain the above copyright notice,
;;;; this list of conditions and the following disclaimer.
;;;; * Redistributions in binary form must reproduce the above copyright
;;;; notice, this list of conditions and the following disclaimer in the
;;;; documentation and/or other materials provided with the distribution.
;;;; * Neither the name of the author nor the names of his contributors may
;;;; be used to endorse or promote products derived from this software
;;;; without specific prior written permission.
;;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
;;;; THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
;;;; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
;;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ;
;;;; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
;;;; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
;;;; ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :lisp-magick-wand)
(defmagickfun "MagickRelinquishMemory" :pointer ((ptr :pointer)))
(defmacro defmagicktype (name base-type)
`(cffi:define-foreign-type ,(type-name-to-class-name name) () ()
(:actual-type ,base-type)
(:simple-parser ,name)))
(defmacro defmagicktrans (method-name (value-arg (type-arg type-name)
&rest other-args)
&body body)
`(defmethod ,method-name (,value-arg (,type-arg ,(type-name-to-class-name type-name))
,@other-args)
,@body))
;; size_t
(defmagicktype size-t :uint)
(defmagicktrans cffi:expand-to-foreign (value (type size-t)) value)
(defmagicktrans cffi:expand-from-foreign (value (type size-t)) value)
;; magick-double
(defmagicktype magick-double :double)
(defmagicktrans cffi:expand-to-foreign (value (type magick-double))
`(coerce ,value 'double-float))
(defmagicktrans cffi:expand-from-foreign (value (type magick-double))
value)
(defmagicktrans cffi:translate-to-foreign (value (type magick-double))
(values (coerce value 'double-float) nil))
Quantum
(declaim (inline byte->quantum quantum->byte))
#+lisp-magick-wand:quantum-8
(progn
(defmagicktype quantum :uint8)
(defun byte->quantum (b) b)
(defun quantum->byte (b) b))
#+lisp-magick-wand:quantum-16
(progn
(defmagicktype quantum :uint16)
(defun byte->quantum (b) (* b 257))
(defun quantum->byte (b) (values (truncate b 257))))
#+lisp-magick-wand:quantum-32
(progn
(defmagicktype quantum :uint32)
(defun byte->quantum (b) (* b 16843009))
(defun quantum->byte (b) (values (truncate b 16843009))))
#+(and lisp-magick-wand:quantum-64 cffi-features:no-long-long)
(error "your version of imagemagick uses a quantum size of 64bit,
but cffi doesn't support long long on your lisp implementation.")
#+(and lisp-magick-wand:quantum-64 (not cffi-features:no-long-long))
(progn
(defmagicktype quantum :uint64)
(defun byte->quantum (b) (* b 72340172838076673))
(defun quantum->byte (b) (values (truncate b 72340172838076673))))
#-(or lisp-magick-wand:quantum-8 lisp-magick-wand:quantum-16
lisp-magick-wand:quantum-32 lisp-magick-wand:quantum-64)
(error "quantum size feature not defined")
(defmagicktrans cffi:expand-to-foreign (value (type quantum)) value)
(defmagicktrans cffi:expand-from-foreign (value (type quantum)) value)
Boolean
(defmethod %error-condition (value (type (eql :boolean)))
`(not ,value))
;; String Types
;; this is cffi:defctype (and not defmagicktype) on purpose
;; - we want to inherit :string's translators
(cffi:defctype magick-string :string)
(defmethod %error-condition (value (type (eql 'magick-string)))
`(null ,value))
(defmagicktype magick-string/free :pointer)
(defmagicktrans cffi:translate-from-foreign (value (type magick-string/free))
(prog1
(cffi:foreign-string-to-lisp value)
(unless (cffi:null-pointer-p value)
(relinquish-memory value))))
(defmagicktrans cffi:translate-to-foreign (value (type magick-string/free))
(values (cffi:foreign-string-alloc value) t))
(defmagicktrans cffi:free-translated-object (value (type magick-string/free) free-p)
(when free-p
(cffi:foreign-string-free value)))
(defmagicktrans cffi:expand-from-foreign (value (type magick-string/free))
(let ((g (gensym)))
`(let ((,g ,value))
(prog1
(cffi:foreign-string-to-lisp ,g)
(unless (cffi:null-pointer-p ,g)
(relinquish-memory ,g))))))
(defmethod %error-condition (value (type (eql 'magick-string/free)))
`(null ,value))
MagickWand
(defmagicktype magick-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type magick-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type magick-wand)) value)
(defmethod %error-condition (value (type (eql 'magick-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'magick-wand)))
`(signal-magick-wand-error ,wand))
PixelWand
(defmagicktype pixel-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type pixel-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type pixel-wand)) value)
(defmethod %error-condition (value (type (eql 'pixel-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'pixel-wand)))
`(signal-pixel-wand-error ,wand))
DrawingWand
(defmagicktype drawing-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type drawing-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type drawing-wand)) value)
(defmethod %error-condition (value (type (eql 'drawing-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'drawing-wand)))
`(signal-drawing-wand-error ,wand))
| null | https://raw.githubusercontent.com/ruricolist/lisp-magick-wand/82ee7b8a9c3bbbd871602f5aad9b29d109f2fb8d/types.lisp | lisp | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of his contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
LOSS OF USE , DATA , OR PROFITS ;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
size_t
magick-double
String Types
this is cffi:defctype (and not defmagicktype) on purpose
- we want to inherit :string's translators | ImageMagick binding for Common Lisp
Copyright ( c ) 2006 , 2007 , 2008 , 2009 < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
(in-package :lisp-magick-wand)
(defmagickfun "MagickRelinquishMemory" :pointer ((ptr :pointer)))
(defmacro defmagicktype (name base-type)
`(cffi:define-foreign-type ,(type-name-to-class-name name) () ()
(:actual-type ,base-type)
(:simple-parser ,name)))
(defmacro defmagicktrans (method-name (value-arg (type-arg type-name)
&rest other-args)
&body body)
`(defmethod ,method-name (,value-arg (,type-arg ,(type-name-to-class-name type-name))
,@other-args)
,@body))
(defmagicktype size-t :uint)
(defmagicktrans cffi:expand-to-foreign (value (type size-t)) value)
(defmagicktrans cffi:expand-from-foreign (value (type size-t)) value)
(defmagicktype magick-double :double)
(defmagicktrans cffi:expand-to-foreign (value (type magick-double))
`(coerce ,value 'double-float))
(defmagicktrans cffi:expand-from-foreign (value (type magick-double))
value)
(defmagicktrans cffi:translate-to-foreign (value (type magick-double))
(values (coerce value 'double-float) nil))
Quantum
(declaim (inline byte->quantum quantum->byte))
#+lisp-magick-wand:quantum-8
(progn
(defmagicktype quantum :uint8)
(defun byte->quantum (b) b)
(defun quantum->byte (b) b))
#+lisp-magick-wand:quantum-16
(progn
(defmagicktype quantum :uint16)
(defun byte->quantum (b) (* b 257))
(defun quantum->byte (b) (values (truncate b 257))))
#+lisp-magick-wand:quantum-32
(progn
(defmagicktype quantum :uint32)
(defun byte->quantum (b) (* b 16843009))
(defun quantum->byte (b) (values (truncate b 16843009))))
#+(and lisp-magick-wand:quantum-64 cffi-features:no-long-long)
(error "your version of imagemagick uses a quantum size of 64bit,
but cffi doesn't support long long on your lisp implementation.")
#+(and lisp-magick-wand:quantum-64 (not cffi-features:no-long-long))
(progn
(defmagicktype quantum :uint64)
(defun byte->quantum (b) (* b 72340172838076673))
(defun quantum->byte (b) (values (truncate b 72340172838076673))))
#-(or lisp-magick-wand:quantum-8 lisp-magick-wand:quantum-16
lisp-magick-wand:quantum-32 lisp-magick-wand:quantum-64)
(error "quantum size feature not defined")
(defmagicktrans cffi:expand-to-foreign (value (type quantum)) value)
(defmagicktrans cffi:expand-from-foreign (value (type quantum)) value)
Boolean
(defmethod %error-condition (value (type (eql :boolean)))
`(not ,value))
(cffi:defctype magick-string :string)
(defmethod %error-condition (value (type (eql 'magick-string)))
`(null ,value))
(defmagicktype magick-string/free :pointer)
(defmagicktrans cffi:translate-from-foreign (value (type magick-string/free))
(prog1
(cffi:foreign-string-to-lisp value)
(unless (cffi:null-pointer-p value)
(relinquish-memory value))))
(defmagicktrans cffi:translate-to-foreign (value (type magick-string/free))
(values (cffi:foreign-string-alloc value) t))
(defmagicktrans cffi:free-translated-object (value (type magick-string/free) free-p)
(when free-p
(cffi:foreign-string-free value)))
(defmagicktrans cffi:expand-from-foreign (value (type magick-string/free))
(let ((g (gensym)))
`(let ((,g ,value))
(prog1
(cffi:foreign-string-to-lisp ,g)
(unless (cffi:null-pointer-p ,g)
(relinquish-memory ,g))))))
(defmethod %error-condition (value (type (eql 'magick-string/free)))
`(null ,value))
MagickWand
(defmagicktype magick-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type magick-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type magick-wand)) value)
(defmethod %error-condition (value (type (eql 'magick-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'magick-wand)))
`(signal-magick-wand-error ,wand))
PixelWand
(defmagicktype pixel-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type pixel-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type pixel-wand)) value)
(defmethod %error-condition (value (type (eql 'pixel-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'pixel-wand)))
`(signal-pixel-wand-error ,wand))
DrawingWand
(defmagicktype drawing-wand :pointer)
(defmagicktrans cffi:expand-to-foreign (value (type drawing-wand)) value)
(defmagicktrans cffi:expand-from-foreign (value (type drawing-wand)) value)
(defmethod %error-condition (value (type (eql 'drawing-wand)))
`(cffi:null-pointer-p ,value))
(defmethod %error-signalling-code (wand (type (eql 'drawing-wand)))
`(signal-drawing-wand-error ,wand))
|
71db626867d6f2eab9f2ad16ceeade05b1e597c4972695fc06cdc6dd2ce064cf | esl/escalus | escalus_history_h.erl | -module(escalus_history_h).
-behaviour(gen_event).
-export([get_history/1]).
-export([init/1,
terminate/2,
handle_info/2,
handle_call/2,
handle_event/2,
code_change/3]).
-record(state, {
events :: list()
}).
-spec get_history(escalus_event:manager()) -> list().
get_history(Mgr) ->
gen_event:call(Mgr, escalus_history_h, get_history).
init([]) ->
S = #state{
events = []
},
{ok, S}.
handle_event({incoming_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(incoming_stanza, Jid, Stanza, State)};
handle_event({outgoing_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(outgoing_stanza, Jid, Stanza, State)};
handle_event({pop_incoming_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(pop_incoming_stanza, Jid, Stanza, State)};
handle_event(story_start, State) ->
{ok, save_story_event(story_start, State)};
handle_event(story_end, State) ->
{ok, save_story_event(story_end, State)};
handle_event(_Event, State) ->
{ok, State}.
handle_info(_, State) ->
{ok, State}.
handle_call(get_history, State=#state{events=Events}) ->
{ok, lists:reverse(Events), State}.
code_change(_, _, State) ->
{ok, State}.
terminate(_, _) ->
ok.
%% ===================================================================
%% Helpers
%% ===================================================================
save_stanza(Type, Jid, Stanza, State=#state{events = Events}) ->
State#state{
events = [{stanza, Type, Jid, erlang:system_time(microsecond), Stanza}|Events]}.
save_story_event(Type, State=#state{events = Events}) ->
State#state{
events = [{story, Type, erlang:system_time(microsecond)}|Events]}.
| null | https://raw.githubusercontent.com/esl/escalus/ac5e813ac96c0cdb5d5ac738d63d992f5f948585/src/escalus_history_h.erl | erlang | ===================================================================
Helpers
=================================================================== | -module(escalus_history_h).
-behaviour(gen_event).
-export([get_history/1]).
-export([init/1,
terminate/2,
handle_info/2,
handle_call/2,
handle_event/2,
code_change/3]).
-record(state, {
events :: list()
}).
-spec get_history(escalus_event:manager()) -> list().
get_history(Mgr) ->
gen_event:call(Mgr, escalus_history_h, get_history).
init([]) ->
S = #state{
events = []
},
{ok, S}.
handle_event({incoming_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(incoming_stanza, Jid, Stanza, State)};
handle_event({outgoing_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(outgoing_stanza, Jid, Stanza, State)};
handle_event({pop_incoming_stanza, Jid, Stanza}, State) ->
{ok, save_stanza(pop_incoming_stanza, Jid, Stanza, State)};
handle_event(story_start, State) ->
{ok, save_story_event(story_start, State)};
handle_event(story_end, State) ->
{ok, save_story_event(story_end, State)};
handle_event(_Event, State) ->
{ok, State}.
handle_info(_, State) ->
{ok, State}.
handle_call(get_history, State=#state{events=Events}) ->
{ok, lists:reverse(Events), State}.
code_change(_, _, State) ->
{ok, State}.
terminate(_, _) ->
ok.
save_stanza(Type, Jid, Stanza, State=#state{events = Events}) ->
State#state{
events = [{stanza, Type, Jid, erlang:system_time(microsecond), Stanza}|Events]}.
save_story_event(Type, State=#state{events = Events}) ->
State#state{
events = [{story, Type, erlang:system_time(microsecond)}|Events]}.
|
6f25ed1169ab3abf093e095425a78a80e39c0e00c45bdf53d7a3c16b9d78a071 | tokenrove/imago | file.lisp | ;;; IMAGO library
;;; File handling facility
;;;
Copyright ( C ) 2004 - 2005 ( )
;;;
;;; The authors grant you the rights to distribute
;;; and use this software as governed by the terms
of the Lisp Lesser GNU Public License
;;; (),
;;; known as the LLGPL.
(in-package :imago)
(defparameter *image-file-readers* (make-hash-table :test #'equal))
(defparameter *image-file-writers* (make-hash-table :test #'equal))
(defun read-image (filename &key (errorp t))
"Reads an image from a file. If the file format is not recognized,
depending on the value of :ERRORP, either throws an error or returns NIL."
(declare (type (or pathname string) filename))
(let ((reader (gethash
(string-downcase
(pathname-type (pathname filename)))
*image-file-readers*)))
(if (null reader)
(and errorp (error 'unknown-format :pathname filename))
(funcall reader filename))))
(defun write-image (image filename &key (errorp t))
"Writes an image IMAGE to a file. If the file format is not recognized,
depending on the value of :ERRORP, either throws an error or returns NIL."
(declare (type (or pathname string) filename)
(type image image))
(let ((writer (gethash
(string-downcase
(pathname-type (pathname filename)))
*image-file-writers*)))
(if (null writer)
(and errorp (error 'unknown-format :pathname filename))
(funcall writer image filename))))
(defun register-image-io-function (extensions function table)
(declare (type function function))
(map nil
(lambda (extension)
(declare (type string extension))
(setf (gethash extension table) function))
extensions))
(defun register-image-reader (extensions function)
"Register a reader function for some file extensions. The FUNCTION
must take a FILESPEC as argument, and return an IMAGE."
(register-image-io-function
extensions function
*image-file-readers*))
(defun register-image-writer (extensions function)
"Register a writer function for some file extensions. The FUNCTION
must take an IMAGE and FILESPEC as arguments. To gain full control of
writing options use specific WRITE-* functions."
(register-image-io-function
extensions function
*image-file-writers*))
(defun register-image-io-functions (extensions &key reader writer)
"This function is just a shorthand for REGISTER-IMAGE-READER and
REGISTER-IMAGE-WRITER. Whenever READER and WRITER are not NIL, imago
registers that I/O handler for the specified EXTENSIONS."
(declare (type (or null function) reader writer))
(when reader
(register-image-reader extensions reader))
(when writer
(register-image-writer extensions writer)))
| null | https://raw.githubusercontent.com/tokenrove/imago/b4befb2bc9b6843be153e6efd2ab52fb21103302/src/file.lisp | lisp | IMAGO library
File handling facility
The authors grant you the rights to distribute
and use this software as governed by the terms
(),
known as the LLGPL. | Copyright ( C ) 2004 - 2005 ( )
of the Lisp Lesser GNU Public License
(in-package :imago)
(defparameter *image-file-readers* (make-hash-table :test #'equal))
(defparameter *image-file-writers* (make-hash-table :test #'equal))
(defun read-image (filename &key (errorp t))
"Reads an image from a file. If the file format is not recognized,
depending on the value of :ERRORP, either throws an error or returns NIL."
(declare (type (or pathname string) filename))
(let ((reader (gethash
(string-downcase
(pathname-type (pathname filename)))
*image-file-readers*)))
(if (null reader)
(and errorp (error 'unknown-format :pathname filename))
(funcall reader filename))))
(defun write-image (image filename &key (errorp t))
"Writes an image IMAGE to a file. If the file format is not recognized,
depending on the value of :ERRORP, either throws an error or returns NIL."
(declare (type (or pathname string) filename)
(type image image))
(let ((writer (gethash
(string-downcase
(pathname-type (pathname filename)))
*image-file-writers*)))
(if (null writer)
(and errorp (error 'unknown-format :pathname filename))
(funcall writer image filename))))
(defun register-image-io-function (extensions function table)
(declare (type function function))
(map nil
(lambda (extension)
(declare (type string extension))
(setf (gethash extension table) function))
extensions))
(defun register-image-reader (extensions function)
"Register a reader function for some file extensions. The FUNCTION
must take a FILESPEC as argument, and return an IMAGE."
(register-image-io-function
extensions function
*image-file-readers*))
(defun register-image-writer (extensions function)
"Register a writer function for some file extensions. The FUNCTION
must take an IMAGE and FILESPEC as arguments. To gain full control of
writing options use specific WRITE-* functions."
(register-image-io-function
extensions function
*image-file-writers*))
(defun register-image-io-functions (extensions &key reader writer)
"This function is just a shorthand for REGISTER-IMAGE-READER and
REGISTER-IMAGE-WRITER. Whenever READER and WRITER are not NIL, imago
registers that I/O handler for the specified EXTENSIONS."
(declare (type (or null function) reader writer))
(when reader
(register-image-reader extensions reader))
(when writer
(register-image-writer extensions writer)))
|
6318c45610716839e4490ca8c75756d997e6cf117739f852853566f9b4763378 | racket/gui | base.rkt | #lang scheme/base
(require (except-in mred
make-gui-namespace
make-gui-empty-namespace))
(provide (all-from-out mred)
make-gui-namespace
make-gui-empty-namespace)
(define-namespace-anchor anchor)
(define (make-gui-empty-namespace)
(let ([ns (make-base-empty-namespace)])
(namespace-attach-module (namespace-anchor->empty-namespace anchor)
'scheme/gui/base
ns)
ns))
(define (make-gui-namespace)
(let ([ns (make-gui-empty-namespace)])
(parameterize ([current-namespace ns])
(namespace-require 'scheme/base)
(namespace-require 'scheme/gui/base)
(namespace-require 'scheme/class))
ns))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/scheme/gui/base.rkt | racket | #lang scheme/base
(require (except-in mred
make-gui-namespace
make-gui-empty-namespace))
(provide (all-from-out mred)
make-gui-namespace
make-gui-empty-namespace)
(define-namespace-anchor anchor)
(define (make-gui-empty-namespace)
(let ([ns (make-base-empty-namespace)])
(namespace-attach-module (namespace-anchor->empty-namespace anchor)
'scheme/gui/base
ns)
ns))
(define (make-gui-namespace)
(let ([ns (make-gui-empty-namespace)])
(parameterize ([current-namespace ns])
(namespace-require 'scheme/base)
(namespace-require 'scheme/gui/base)
(namespace-require 'scheme/class))
ns))
| |
ba87ed288cee4941058ee1b79e0fac44887857912bb5457cae171d19417e125e | bravit/hid-examples | dynvalues-gadt.hs | {-# LANGUAGE GADTs #-}
data DynValue a where
S :: String -> DynValue String
C :: Char -> DynValue Char
B :: Bool -> DynValue Bool
getValue :: DynValue a -> a
getValue (B b) = b
getValue (C c) = c
getValue (S s) = s
printValue :: DynValue a -> IO ()
printValue (B b) = print b
printValue (C c) = print c
printValue (S s) = print s
data WrappedDynValue where
Wrap :: DynValue a -> WrappedDynValue
fromString :: String -> WrappedDynValue
fromString str
| str `elem` ["y", "yes", "true"] = Wrap (B True)
| str `elem` ["n", "no", "false"] = Wrap (B False)
| length str == 1 = Wrap (C $ head str)
| otherwise = Wrap (S str)
printWDValue :: WrappedDynValue -> IO ()
printWDValue (Wrap dv) = printValue dv
main :: IO ()
main = mapM_ (printWDValue . fromString) ["y", "no", "xxx", "c"]
| null | https://raw.githubusercontent.com/bravit/hid-examples/913e116b7ee9c7971bba10fe70ae0b61bfb9391b/ch11/dynvalues-gadt.hs | haskell | # LANGUAGE GADTs # |
data DynValue a where
S :: String -> DynValue String
C :: Char -> DynValue Char
B :: Bool -> DynValue Bool
getValue :: DynValue a -> a
getValue (B b) = b
getValue (C c) = c
getValue (S s) = s
printValue :: DynValue a -> IO ()
printValue (B b) = print b
printValue (C c) = print c
printValue (S s) = print s
data WrappedDynValue where
Wrap :: DynValue a -> WrappedDynValue
fromString :: String -> WrappedDynValue
fromString str
| str `elem` ["y", "yes", "true"] = Wrap (B True)
| str `elem` ["n", "no", "false"] = Wrap (B False)
| length str == 1 = Wrap (C $ head str)
| otherwise = Wrap (S str)
printWDValue :: WrappedDynValue -> IO ()
printWDValue (Wrap dv) = printValue dv
main :: IO ()
main = mapM_ (printWDValue . fromString) ["y", "no", "xxx", "c"]
|
8ad72ec46f8f6d0e8a3259cb2ec99bb670227e7453d207dfd3a405f0499b9d93 | ggreif/dynamic-loader | PathLoader.hs | ----------------------------------------------------------------------------
-- |
-- Module : PathLoader
Copyright : ( c ) Hampus Ram 2004 , 2012
-- License : BSD-style (see LICENSE)
--
-- Maintainer : ggreif+
-- Stability : experimental
Portability : non - portable ( ghc > = 7.6 only )
--
-- A module that implements dynamic loading.
-- Has smart handling of dependencies and
-- is thread safe.
--
----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables, ConstraintKinds #-}
module System.Plugins.PathLoader (LoadedModule,
ModuleType (..),
setBasePath,
addDependency,
setDependencies,
delDependency,
delAllDeps,
withDependencies,
loadModule,
unloadModule,
unloadModuleQuiet,
loadFunction,
loadQualifiedFunction,
moduleLoadedAt,
loadedModules,
DL.addDLL) where
import Control.Concurrent.MVar
import Data.List
import qualified Data.HashTable.IO as HT
import Data.Hashable
import Data.IORef
import System.IO.Unsafe
import System.Directory
import Data.Time
import Control.Exception (catch, SomeException)
import System.Plugins.Criteria.LoadCriterion
import System.Plugins.Criteria.UnsafeCriterion
import qualified System.Plugins.DynamicLoader as DL
type Loadable c t t' = (LoadCriterion c t, Effective c t ~ IO t')
data LoadedModule = LM FilePath ModuleType
data ModuleType = MT_Module
| MT_Package
deriving (Eq, Ord, Show)
type ModuleWT = (ModuleType, FilePath)
type PathDynamics = Either DL.DynamicModule DL.DynamicPackage
type PathDep = [ModuleWT]
-- PM reference_count type time module
data PathModule = PM { pm_refc :: !Int,
pm_time :: UTCTime,
pm_deps :: PathDep,
pm_module :: PathDynamics }
-- base_path dependency_map modules
type PathEnvData = (Maybe FilePath,
HT.BasicHashTable String [ModuleWT],
HT.BasicHashTable String PathModule)
New PathEnv that uses both an IORef and a MVar
to make it possible to have non blocking functions
that inspect the state .
New PathEnv that uses both an IORef and a MVar
to make it possible to have non blocking functions
that inspect the state.
-}
type PathEnv = (MVar (), IORef PathEnvData)
withPathEnv :: Loadable c t t' => Criterion c t -> PathEnv -> (PathEnvData -> Effective c t) -> Effective c t
withPathEnv _ (mvar, ioref) f
= withMVar mvar (\_ -> readIORef ioref >>= f)
withPathEnvNB :: PathEnv -> (PathEnvData -> IO b) -> IO b
withPathEnvNB (_, ioref) f = readIORef ioref >>= f
modifyPathEnv_ :: PathEnv -> (PathEnvData -> IO PathEnvData) -> IO ()
modifyPathEnv_ (mvar, ioref) f
= withMVar mvar (\_ -> readIORef ioref >>= f >>= writeIORef ioref)
# NOINLINE env #
env :: PathEnv
env = unsafePerformIO (do modh <- HT.new
deph <- HT.new
mvar <- newMVar ()
ioref <- newIORef (Nothing, deph, modh)
return (mvar, ioref))
|
Set the base path used in figuring out module names . If not set the default
( i.e. currentDirectory ) will be used .
Set the base path used in figuring out module names. If not set the default
(i.e. currentDirectory) will be used.
-}
setBasePath :: Maybe FilePath -> IO ()
setBasePath mpath
= modifyPathEnv_ env (\(_, deph, modh) -> return (mpath, deph, modh))
|
Add a module dependency . Any dependencies must be added /before/ any
calls to loadModule\/loadPackage or symbols will not be resolved with a
crash as result .
Add a module dependency. Any dependencies must be added /before/ any
calls to loadModule\/loadPackage or symbols will not be resolved with a
crash as result.
-}
addDependency :: FilePath -> (ModuleType, FilePath) -> IO ()
addDependency from to = withPathEnv UnsafeCriterion env (addDependency' from to)
addDependency' :: FilePath -> (ModuleType, FilePath) -> PathEnvData -> IO ()
addDependency' from to (_, deph, _)
= insertHT_C union deph from [to]
{-|
Set all dependencies. All previous dependencies are removed.
-}
setDependencies :: FilePath -> [(ModuleType, FilePath)] -> IO ()
setDependencies from to = withPathEnv UnsafeCriterion env (setDependencies' from to)
setDependencies' :: FilePath -> [(ModuleType, FilePath)] ->
PathEnvData -> IO ()
setDependencies' from to (_, deph, _)
= insertHT deph from to
{-|
Delete a module dependency.
-}
delDependency :: FilePath -> (ModuleType, FilePath) -> IO ()
delDependency from to = withPathEnv UnsafeCriterion env (delDependency' from to)
delDependency' :: FilePath -> (ModuleType, FilePath) -> PathEnvData -> IO ()
delDependency' from to (_, deph, _)
= modifyHT (\\[to]) deph from
{-|
Delete all dependencies for a module. Same behaviour as
@setDependencies path []@.
-}
delAllDeps :: FilePath -> IO ()
delAllDeps from = withPathEnv UnsafeCriterion env (delAllDeps' from)
delAllDeps' :: FilePath -> PathEnvData -> IO ()
delAllDeps' from (_, deph, _)
= deleteHT deph from
{-|
Do something with the current dependencies of a module. You can't use
(blocking) functions from this module in the function given to
withDependencies. If you do so, a deadlock will occur.
-}
withDependencies :: Loadable c t t' => Criterion c t -> FilePath
-> (Maybe [(ModuleType, FilePath)] -> Effective c t) -> Effective c t
withDependencies crit from f
= withPathEnv crit env (\(_,deph,_) -> lookupHT deph from >>= f)
|
Load a module ( or package ) and modules ( or packages ) it depends on . It
is possible to load a module many times without any error
occuring . However to unload a module one needs to call @unloadModule@
the same number of times .
Before loading any modules you should add wich dependencies it has
with ( and which dependencies the modules upon which it
depends have ) .
If the module already has been loaded nothing will be done except
updating the reference count . I.e. if dependencies have been updated
they will be ignored until the module has been completely unloaded and
loaded again .
If any error occurs an exception is thrown .
Load a module (or package) and modules (or packages) it depends on. It
is possible to load a module many times without any error
occuring. However to unload a module one needs to call @unloadModule@
the same number of times.
Before loading any modules you should add wich dependencies it has
with addDependency (and which dependencies the modules upon which it
depends have).
If the module already has been loaded nothing will be done except
updating the reference count. I.e. if dependencies have been updated
they will be ignored until the module has been completely unloaded and
loaded again.
If any error occurs an exception is thrown.
-}
loadModule :: FilePath -> ModuleType -> IO LoadedModule
loadModule m mt
= do withPathEnv UnsafeCriterion env (\env -> do loadModuleWithDep (mt, m) env
DL.resolveFunctions
return (LM m mt))
loadModuleWithDep :: (ModuleType, FilePath) -> PathEnvData -> IO ()
loadModuleWithDep nwt@(_, name) env@(_, _, modh)
= do mpm <- lookupHT modh name
(pm, depmods) <- midLoadModule mpm nwt env
insertHT modh name pm
mapM_ (\modwt -> loadModuleWithDep modwt env) depmods
midLoadModule :: Maybe PathModule -> (ModuleType, FilePath) ->
PathEnvData -> IO (PathModule, PathDep)
midLoadModule (Just pm) _ _ = return $ (pm { pm_refc = pm_refc pm + 1 },
pm_deps pm)
midLoadModule Nothing nwt@(_, name) env@(_, deph, _)
= do (sd, time) <- lowLoadModule nwt env
depmods <- lookupDefHT deph [] name
return (PM 1 time depmods sd, depmods)
lowLoadModule :: ModuleWT -> PathEnvData -> IO (PathDynamics, UTCTime)
lowLoadModule (MT_Package, name) (_, _, _)
= do lp <- DL.loadPackageFromPath name
time <- getModificationTime (DL.dp_path lp)
return (Right lp, time)
lowLoadModule (MT_Module, name) (mpath, _, _)
= do lm <- DL.loadModuleFromPath name mpath
time <- getModificationTime (DL.dm_path lm)
return (Left lm, time)
{-|
Unload a module and all modules it depends on. This unloading only
occurs if the module isn't needed by any other libraries or hasn't
been loaded more than once. An exception is thrown in case of error.
-}
unloadModule :: LoadedModule -> IO ()
unloadModule (LM name _)
= withPathEnv UnsafeCriterion env (unloadModuleWithDep name)
{-|
Same as @unloadModule@ just doesn't trow any exceptions on error.
-}
unloadModuleQuiet :: LoadedModule -> IO ()
unloadModuleQuiet (LM name _)
= withPathEnv UnsafeCriterion env (\env -> catch (unloadModuleWithDep name env)
(\(_ :: SomeException) -> return ()))
unloadModuleWithDep :: FilePath -> PathEnvData -> IO ()
unloadModuleWithDep name env@(_, _, modh)
= do mpm <- lookupHT modh name
pm <- maybe (fail $ "Module " ++ name ++ " not loaded")
return mpm
if pm_refc pm > 1
then do insertHT modh name (pm { pm_refc = pm_refc pm - 1 })
else do lowUnloadModule (pm_module pm)
deleteHT modh name
mapM_ (\(_, m) -> unloadModuleWithDep m env) (pm_deps pm)
lowUnloadModule :: PathDynamics -> IO ()
lowUnloadModule (Left lm) = DL.unloadModule lm
lowUnloadModule (Right lp) = DL.unloadPackage lp
{-|
Load a function from a module. It cannot load functions from packages
and will throw an exception if one tries to do so. Also throws if an
error occurs.
It seems (but I'm unsure) like any functions loaded will continue to
be valid even after the module it resides in is unloaded. It will also
still be valid if a new version of that module is loaded (it will thus
still call the old function).
-}
loadFunction :: Loadable c t t' => Criterion c t -> LoadedModule -> String -> Effective c t
loadFunction crit (LM m MT_Module) name
= withPathEnv crit env (loadFunction' m name)
where loadFunction' mname fname (_, _, modh)
= do mpm <- HT.lookup modh mname
pm <- maybe (fail $ "Module " ++ mname ++ " isn't loaded")
return mpm
let Left dm = pm_module pm
DL.loadFunction dm fname
loadFunction _ _ _ = fail "You cannot load functions from a package."
|
Load a qualified function from a module or package . It will throw an
exception if an error occurs . Same restriction as for
DynamicLinker.loadQualifiedFunction applies here too .
Load a qualified function from a module or package. It will throw an
exception if an error occurs. Same restriction as for
DynamicLinker.loadQualifiedFunction applies here too.
-}
loadQualifiedFunction :: Loadable c t t' => Criterion c t -> String -> Effective c t
loadQualifiedFunction crit name
= withPathEnv crit env (loadQualifiedFunction' name)
where loadQualifiedFunction' qname _ = DL.loadQualifiedFunction qname
{-|
Give the modification time for a loded module. Will throw an exception
if the module isn't loaded.
-}
moduleLoadedAt :: LoadedModule -> IO UTCTime
moduleLoadedAt (LM m _)
= withPathEnvNB env (moduleLoadedAt' m)
moduleLoadedAt' :: FilePath -> PathEnvData -> IO UTCTime
moduleLoadedAt' name (_, _, modh)
= do mpm <- HT.lookup modh name
pm <- maybe (fail $ "Module " ++ name ++ " not loaded")
return mpm
return (pm_time pm)
loadedModules :: IO [String]
loadedModules = withPathEnvNB env loadedModules'
loadedModules' :: PathEnvData -> IO [String]
loadedModules' (_, _, modh) = HT.toList modh >>= (\lst -> return (map fst lst))
functions to handle HashTables in a better way
-- it seems like it doesn't replace the old value on insert
insertHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> val -> IO ()
insertHT ht key val
= do HT.delete ht key
HT.insert ht key val
insertHT_C :: (Eq key, Hashable key) => (val -> val -> val) -> HT.BasicHashTable key val -> key -> val -> IO ()
insertHT_C func ht key val
= do mval <- HT.lookup ht key
case mval of
Just val' -> insertHT ht key (func val val')
Nothing -> insertHT ht key val
modifyHT :: (Eq key, Hashable key) => (val -> val) -> HT.BasicHashTable key val -> key -> IO ()
modifyHT func ht key
= do mval <- HT.lookup ht key
case mval of
Just val -> insertHT ht key (func val)
Nothing -> return ()
lookupHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> IO (Maybe val)
lookupHT ht key = HT.lookup ht key
deleteHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> IO ()
deleteHT ht key = HT.delete ht key
lookupDefHT :: (Eq key, Hashable key) => HT.BasicHashTable key b -> b -> key -> IO b
lookupDefHT ht val key
= do mval <- HT.lookup ht key
case mval of
Just val -> return val
Nothing -> return val
| null | https://raw.githubusercontent.com/ggreif/dynamic-loader/9f3c8b6136d1902ab68ac37ff0182bb2bf1e9eae/System/Plugins/PathLoader.hs | haskell | --------------------------------------------------------------------------
|
Module : PathLoader
License : BSD-style (see LICENSE)
Maintainer : ggreif+
Stability : experimental
A module that implements dynamic loading.
Has smart handling of dependencies and
is thread safe.
--------------------------------------------------------------------------
# LANGUAGE ScopedTypeVariables, ConstraintKinds #
PM reference_count type time module
base_path dependency_map modules
|
Set all dependencies. All previous dependencies are removed.
|
Delete a module dependency.
|
Delete all dependencies for a module. Same behaviour as
@setDependencies path []@.
|
Do something with the current dependencies of a module. You can't use
(blocking) functions from this module in the function given to
withDependencies. If you do so, a deadlock will occur.
|
Unload a module and all modules it depends on. This unloading only
occurs if the module isn't needed by any other libraries or hasn't
been loaded more than once. An exception is thrown in case of error.
|
Same as @unloadModule@ just doesn't trow any exceptions on error.
|
Load a function from a module. It cannot load functions from packages
and will throw an exception if one tries to do so. Also throws if an
error occurs.
It seems (but I'm unsure) like any functions loaded will continue to
be valid even after the module it resides in is unloaded. It will also
still be valid if a new version of that module is loaded (it will thus
still call the old function).
|
Give the modification time for a loded module. Will throw an exception
if the module isn't loaded.
it seems like it doesn't replace the old value on insert | Copyright : ( c ) Hampus Ram 2004 , 2012
Portability : non - portable ( ghc > = 7.6 only )
module System.Plugins.PathLoader (LoadedModule,
ModuleType (..),
setBasePath,
addDependency,
setDependencies,
delDependency,
delAllDeps,
withDependencies,
loadModule,
unloadModule,
unloadModuleQuiet,
loadFunction,
loadQualifiedFunction,
moduleLoadedAt,
loadedModules,
DL.addDLL) where
import Control.Concurrent.MVar
import Data.List
import qualified Data.HashTable.IO as HT
import Data.Hashable
import Data.IORef
import System.IO.Unsafe
import System.Directory
import Data.Time
import Control.Exception (catch, SomeException)
import System.Plugins.Criteria.LoadCriterion
import System.Plugins.Criteria.UnsafeCriterion
import qualified System.Plugins.DynamicLoader as DL
type Loadable c t t' = (LoadCriterion c t, Effective c t ~ IO t')
data LoadedModule = LM FilePath ModuleType
data ModuleType = MT_Module
| MT_Package
deriving (Eq, Ord, Show)
type ModuleWT = (ModuleType, FilePath)
type PathDynamics = Either DL.DynamicModule DL.DynamicPackage
type PathDep = [ModuleWT]
data PathModule = PM { pm_refc :: !Int,
pm_time :: UTCTime,
pm_deps :: PathDep,
pm_module :: PathDynamics }
type PathEnvData = (Maybe FilePath,
HT.BasicHashTable String [ModuleWT],
HT.BasicHashTable String PathModule)
New PathEnv that uses both an IORef and a MVar
to make it possible to have non blocking functions
that inspect the state .
New PathEnv that uses both an IORef and a MVar
to make it possible to have non blocking functions
that inspect the state.
-}
type PathEnv = (MVar (), IORef PathEnvData)
withPathEnv :: Loadable c t t' => Criterion c t -> PathEnv -> (PathEnvData -> Effective c t) -> Effective c t
withPathEnv _ (mvar, ioref) f
= withMVar mvar (\_ -> readIORef ioref >>= f)
withPathEnvNB :: PathEnv -> (PathEnvData -> IO b) -> IO b
withPathEnvNB (_, ioref) f = readIORef ioref >>= f
modifyPathEnv_ :: PathEnv -> (PathEnvData -> IO PathEnvData) -> IO ()
modifyPathEnv_ (mvar, ioref) f
= withMVar mvar (\_ -> readIORef ioref >>= f >>= writeIORef ioref)
# NOINLINE env #
env :: PathEnv
env = unsafePerformIO (do modh <- HT.new
deph <- HT.new
mvar <- newMVar ()
ioref <- newIORef (Nothing, deph, modh)
return (mvar, ioref))
|
Set the base path used in figuring out module names . If not set the default
( i.e. currentDirectory ) will be used .
Set the base path used in figuring out module names. If not set the default
(i.e. currentDirectory) will be used.
-}
setBasePath :: Maybe FilePath -> IO ()
setBasePath mpath
= modifyPathEnv_ env (\(_, deph, modh) -> return (mpath, deph, modh))
|
Add a module dependency . Any dependencies must be added /before/ any
calls to loadModule\/loadPackage or symbols will not be resolved with a
crash as result .
Add a module dependency. Any dependencies must be added /before/ any
calls to loadModule\/loadPackage or symbols will not be resolved with a
crash as result.
-}
addDependency :: FilePath -> (ModuleType, FilePath) -> IO ()
addDependency from to = withPathEnv UnsafeCriterion env (addDependency' from to)
addDependency' :: FilePath -> (ModuleType, FilePath) -> PathEnvData -> IO ()
addDependency' from to (_, deph, _)
= insertHT_C union deph from [to]
setDependencies :: FilePath -> [(ModuleType, FilePath)] -> IO ()
setDependencies from to = withPathEnv UnsafeCriterion env (setDependencies' from to)
setDependencies' :: FilePath -> [(ModuleType, FilePath)] ->
PathEnvData -> IO ()
setDependencies' from to (_, deph, _)
= insertHT deph from to
delDependency :: FilePath -> (ModuleType, FilePath) -> IO ()
delDependency from to = withPathEnv UnsafeCriterion env (delDependency' from to)
delDependency' :: FilePath -> (ModuleType, FilePath) -> PathEnvData -> IO ()
delDependency' from to (_, deph, _)
= modifyHT (\\[to]) deph from
delAllDeps :: FilePath -> IO ()
delAllDeps from = withPathEnv UnsafeCriterion env (delAllDeps' from)
delAllDeps' :: FilePath -> PathEnvData -> IO ()
delAllDeps' from (_, deph, _)
= deleteHT deph from
withDependencies :: Loadable c t t' => Criterion c t -> FilePath
-> (Maybe [(ModuleType, FilePath)] -> Effective c t) -> Effective c t
withDependencies crit from f
= withPathEnv crit env (\(_,deph,_) -> lookupHT deph from >>= f)
|
Load a module ( or package ) and modules ( or packages ) it depends on . It
is possible to load a module many times without any error
occuring . However to unload a module one needs to call @unloadModule@
the same number of times .
Before loading any modules you should add wich dependencies it has
with ( and which dependencies the modules upon which it
depends have ) .
If the module already has been loaded nothing will be done except
updating the reference count . I.e. if dependencies have been updated
they will be ignored until the module has been completely unloaded and
loaded again .
If any error occurs an exception is thrown .
Load a module (or package) and modules (or packages) it depends on. It
is possible to load a module many times without any error
occuring. However to unload a module one needs to call @unloadModule@
the same number of times.
Before loading any modules you should add wich dependencies it has
with addDependency (and which dependencies the modules upon which it
depends have).
If the module already has been loaded nothing will be done except
updating the reference count. I.e. if dependencies have been updated
they will be ignored until the module has been completely unloaded and
loaded again.
If any error occurs an exception is thrown.
-}
loadModule :: FilePath -> ModuleType -> IO LoadedModule
loadModule m mt
= do withPathEnv UnsafeCriterion env (\env -> do loadModuleWithDep (mt, m) env
DL.resolveFunctions
return (LM m mt))
loadModuleWithDep :: (ModuleType, FilePath) -> PathEnvData -> IO ()
loadModuleWithDep nwt@(_, name) env@(_, _, modh)
= do mpm <- lookupHT modh name
(pm, depmods) <- midLoadModule mpm nwt env
insertHT modh name pm
mapM_ (\modwt -> loadModuleWithDep modwt env) depmods
midLoadModule :: Maybe PathModule -> (ModuleType, FilePath) ->
PathEnvData -> IO (PathModule, PathDep)
midLoadModule (Just pm) _ _ = return $ (pm { pm_refc = pm_refc pm + 1 },
pm_deps pm)
midLoadModule Nothing nwt@(_, name) env@(_, deph, _)
= do (sd, time) <- lowLoadModule nwt env
depmods <- lookupDefHT deph [] name
return (PM 1 time depmods sd, depmods)
lowLoadModule :: ModuleWT -> PathEnvData -> IO (PathDynamics, UTCTime)
lowLoadModule (MT_Package, name) (_, _, _)
= do lp <- DL.loadPackageFromPath name
time <- getModificationTime (DL.dp_path lp)
return (Right lp, time)
lowLoadModule (MT_Module, name) (mpath, _, _)
= do lm <- DL.loadModuleFromPath name mpath
time <- getModificationTime (DL.dm_path lm)
return (Left lm, time)
unloadModule :: LoadedModule -> IO ()
unloadModule (LM name _)
= withPathEnv UnsafeCriterion env (unloadModuleWithDep name)
unloadModuleQuiet :: LoadedModule -> IO ()
unloadModuleQuiet (LM name _)
= withPathEnv UnsafeCriterion env (\env -> catch (unloadModuleWithDep name env)
(\(_ :: SomeException) -> return ()))
unloadModuleWithDep :: FilePath -> PathEnvData -> IO ()
unloadModuleWithDep name env@(_, _, modh)
= do mpm <- lookupHT modh name
pm <- maybe (fail $ "Module " ++ name ++ " not loaded")
return mpm
if pm_refc pm > 1
then do insertHT modh name (pm { pm_refc = pm_refc pm - 1 })
else do lowUnloadModule (pm_module pm)
deleteHT modh name
mapM_ (\(_, m) -> unloadModuleWithDep m env) (pm_deps pm)
lowUnloadModule :: PathDynamics -> IO ()
lowUnloadModule (Left lm) = DL.unloadModule lm
lowUnloadModule (Right lp) = DL.unloadPackage lp
loadFunction :: Loadable c t t' => Criterion c t -> LoadedModule -> String -> Effective c t
loadFunction crit (LM m MT_Module) name
= withPathEnv crit env (loadFunction' m name)
where loadFunction' mname fname (_, _, modh)
= do mpm <- HT.lookup modh mname
pm <- maybe (fail $ "Module " ++ mname ++ " isn't loaded")
return mpm
let Left dm = pm_module pm
DL.loadFunction dm fname
loadFunction _ _ _ = fail "You cannot load functions from a package."
|
Load a qualified function from a module or package . It will throw an
exception if an error occurs . Same restriction as for
DynamicLinker.loadQualifiedFunction applies here too .
Load a qualified function from a module or package. It will throw an
exception if an error occurs. Same restriction as for
DynamicLinker.loadQualifiedFunction applies here too.
-}
loadQualifiedFunction :: Loadable c t t' => Criterion c t -> String -> Effective c t
loadQualifiedFunction crit name
= withPathEnv crit env (loadQualifiedFunction' name)
where loadQualifiedFunction' qname _ = DL.loadQualifiedFunction qname
moduleLoadedAt :: LoadedModule -> IO UTCTime
moduleLoadedAt (LM m _)
= withPathEnvNB env (moduleLoadedAt' m)
moduleLoadedAt' :: FilePath -> PathEnvData -> IO UTCTime
moduleLoadedAt' name (_, _, modh)
= do mpm <- HT.lookup modh name
pm <- maybe (fail $ "Module " ++ name ++ " not loaded")
return mpm
return (pm_time pm)
loadedModules :: IO [String]
loadedModules = withPathEnvNB env loadedModules'
loadedModules' :: PathEnvData -> IO [String]
loadedModules' (_, _, modh) = HT.toList modh >>= (\lst -> return (map fst lst))
functions to handle HashTables in a better way
insertHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> val -> IO ()
insertHT ht key val
= do HT.delete ht key
HT.insert ht key val
insertHT_C :: (Eq key, Hashable key) => (val -> val -> val) -> HT.BasicHashTable key val -> key -> val -> IO ()
insertHT_C func ht key val
= do mval <- HT.lookup ht key
case mval of
Just val' -> insertHT ht key (func val val')
Nothing -> insertHT ht key val
modifyHT :: (Eq key, Hashable key) => (val -> val) -> HT.BasicHashTable key val -> key -> IO ()
modifyHT func ht key
= do mval <- HT.lookup ht key
case mval of
Just val -> insertHT ht key (func val)
Nothing -> return ()
lookupHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> IO (Maybe val)
lookupHT ht key = HT.lookup ht key
deleteHT :: (Eq key, Hashable key) => HT.BasicHashTable key val -> key -> IO ()
deleteHT ht key = HT.delete ht key
lookupDefHT :: (Eq key, Hashable key) => HT.BasicHashTable key b -> b -> key -> IO b
lookupDefHT ht val key
= do mval <- HT.lookup ht key
case mval of
Just val -> return val
Nothing -> return val
|
e729c348b63d5acfd24daddf16930daf120946c5b20d7958097aad354d168340 | processone/xmpp | flex_offline.erl | Created automatically by xdata generator ( xdata_codec.erl )
%% Source: flex_offline.xdata
%% Form type:
Document :
-module(flex_offline).
-compile({nowarn_unused_function,
[{dec_int, 3},
{dec_int, 1},
{dec_enum, 2},
{dec_enum_int, 2},
{dec_enum_int, 4},
{enc_int, 1},
{enc_enum, 1},
{enc_enum_int, 1},
{not_empty, 1},
{dec_bool, 1},
{enc_bool, 1},
{dec_ip, 1},
{enc_ip, 1}]}).
-compile(nowarn_unused_vars).
-dialyzer({nowarn_function, {dec_int, 3}}).
-export([encode/1, encode/2, encode/3]).
-export([decode/1,
decode/2,
decode/3,
format_error/1,
io_format_error/1]).
-include("xmpp_codec.hrl").
-include("flex_offline.hrl").
-export_type([property/0,
result/0,
form/0,
error_reason/0]).
-define(T(S), <<S>>).
-spec format_error(error_reason()) -> binary().
-spec io_format_error(error_reason()) -> {binary(),
[binary()]}.
-spec decode([xdata_field()]) -> result().
-spec decode([xdata_field()],
[binary(), ...]) -> result().
-spec decode([xdata_field()], [binary(), ...],
[binary()]) -> result().
-spec decode([xdata_field()], [binary(), ...],
[binary()], result()) -> result().
-spec do_decode([xdata_field()], binary(), [binary()],
result()) -> result().
-spec encode(form()) -> [xdata_field()].
-spec encode(form(), binary()) -> [xdata_field()].
-spec encode(form(), binary(),
[number_of_messages]) -> [xdata_field()].
dec_int(Val) -> dec_int(Val, infinity, infinity).
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.
enc_int(Int) -> integer_to_binary(Int).
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
dec_enum_int(Val, Enums) ->
try dec_int(Val) catch _:_ -> dec_enum(Val, Enums) end.
dec_enum_int(Val, Enums, Min, Max) ->
try dec_int(Val, Min, Max) catch
_:_ -> dec_enum(Val, Enums)
end.
enc_enum_int(Int) when is_integer(Int) -> enc_int(Int);
enc_enum_int(Atom) -> enc_enum(Atom).
dec_bool(<<"1">>) -> true;
dec_bool(<<"0">>) -> false;
dec_bool(<<"true">>) -> true;
dec_bool(<<"false">>) -> false.
enc_bool(true) -> <<"1">>;
enc_bool(false) -> <<"0">>.
not_empty(<<_, _/binary>> = Val) -> Val.
dec_ip(Val) ->
{ok, Addr} = inet_parse:address(binary_to_list(Val)),
Addr.
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)).
format_error({form_type_mismatch, Type}) ->
<<"FORM_TYPE doesn't match '", Type/binary, "'">>;
format_error({bad_var_value, Var, Type}) ->
<<"Bad value of field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({missing_value, Var, Type}) ->
<<"Missing value of field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({too_many_values, Var, Type}) ->
<<"Too many values for field '", Var/binary,
"' of type '", Type/binary, "'">>;
format_error({unknown_var, Var, Type}) ->
<<"Unknown field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({missing_required_var, Var, Type}) ->
<<"Missing required field '", Var/binary, "' of type '",
Type/binary, "'">>.
io_format_error({form_type_mismatch, Type}) ->
{<<"FORM_TYPE doesn't match '~s'">>, [Type]};
io_format_error({bad_var_value, Var, Type}) ->
{<<"Bad value of field '~s' of type '~s'">>,
[Var, Type]};
io_format_error({missing_value, Var, Type}) ->
{<<"Missing value of field '~s' of type "
"'~s'">>,
[Var, Type]};
io_format_error({too_many_values, Var, Type}) ->
{<<"Too many values for field '~s' of type "
"'~s'">>,
[Var, Type]};
io_format_error({unknown_var, Var, Type}) ->
{<<"Unknown field '~s' of type '~s'">>, [Var, Type]};
io_format_error({missing_required_var, Var, Type}) ->
{<<"Missing required field '~s' of type "
"'~s'">>,
[Var, Type]}.
decode(Fs) ->
decode(Fs,
[<<"">>],
[],
[]).
decode(Fs, XMLNSList) -> decode(Fs, XMLNSList, [], []).
decode(Fs, XMLNSList, Required) ->
decode(Fs, XMLNSList, Required, []).
decode(Fs, [_ | _] = XMLNSList, Required, Acc) ->
case lists:keyfind(<<"FORM_TYPE">>,
#xdata_field.var,
Fs)
of
false -> do_decode(Fs, hd(XMLNSList), Required, Acc);
#xdata_field{values = [XMLNS]} ->
case lists:member(XMLNS, XMLNSList) of
true -> do_decode(Fs, XMLNS, Required, Acc);
false ->
erlang:error({?MODULE, {form_type_mismatch, XMLNS}})
end
end.
encode(Cfg) -> encode(Cfg, <<"en">>, []).
encode(Cfg, Lang) -> encode(Cfg, Lang, []).
encode(List, Lang, Required) ->
Fs = [case Opt of
{number_of_messages, Val} ->
[encode_number_of_messages(Val,
Lang,
lists:member(number_of_messages,
Required))];
#xdata_field{} -> [Opt]
end
|| Opt <- List],
FormType = #xdata_field{var = <<"FORM_TYPE">>,
type = hidden,
values =
[<<"">>]},
[FormType | lists:flatten(Fs)].
do_decode([#xdata_field{var = <<"number_of_messages">>,
values = [Value]}
| Fs],
XMLNS, Required, Acc) ->
try dec_int(Value, 0, infinity) of
Result ->
do_decode(Fs,
XMLNS,
lists:delete(<<"number_of_messages">>, Required),
[{number_of_messages, Result} | Acc])
catch
_:_ ->
erlang:error({?MODULE,
{bad_var_value, <<"number_of_messages">>, XMLNS}})
end;
do_decode([#xdata_field{var = <<"number_of_messages">>,
values = []} =
F
| Fs],
XMLNS, Required, Acc) ->
do_decode([F#xdata_field{var = <<"number_of_messages">>,
values = [<<>>]}
| Fs],
XMLNS,
Required,
Acc);
do_decode([#xdata_field{var = <<"number_of_messages">>}
| _],
XMLNS, _, _) ->
erlang:error({?MODULE,
{too_many_values, <<"number_of_messages">>, XMLNS}});
do_decode([#xdata_field{var = Var} | Fs], XMLNS,
Required, Acc) ->
if Var /= <<"FORM_TYPE">> ->
erlang:error({?MODULE, {unknown_var, Var, XMLNS}});
true -> do_decode(Fs, XMLNS, Required, Acc)
end;
do_decode([], XMLNS, [Var | _], _) ->
erlang:error({?MODULE,
{missing_required_var, Var, XMLNS}});
do_decode([], _, [], Acc) -> Acc.
-spec encode_number_of_messages(non_neg_integer() |
undefined,
binary(), boolean()) -> xdata_field().
encode_number_of_messages(Value, Lang, IsRequired) ->
Values = case Value of
undefined -> [];
Value -> [enc_int(Value)]
end,
Opts = [],
#xdata_field{var = <<"number_of_messages">>,
values = Values, required = IsRequired,
type = 'text-single', options = Opts, desc = <<>>,
label =
xmpp_tr:tr(Lang, ?T("Number of Offline Messages"))}.
| null | https://raw.githubusercontent.com/processone/xmpp/6705a6e5dbe8c8dc9cc70cba9c442c6da61de716/src/flex_offline.erl | erlang | Source: flex_offline.xdata
Form type: | Created automatically by xdata generator ( xdata_codec.erl )
Document :
-module(flex_offline).
-compile({nowarn_unused_function,
[{dec_int, 3},
{dec_int, 1},
{dec_enum, 2},
{dec_enum_int, 2},
{dec_enum_int, 4},
{enc_int, 1},
{enc_enum, 1},
{enc_enum_int, 1},
{not_empty, 1},
{dec_bool, 1},
{enc_bool, 1},
{dec_ip, 1},
{enc_ip, 1}]}).
-compile(nowarn_unused_vars).
-dialyzer({nowarn_function, {dec_int, 3}}).
-export([encode/1, encode/2, encode/3]).
-export([decode/1,
decode/2,
decode/3,
format_error/1,
io_format_error/1]).
-include("xmpp_codec.hrl").
-include("flex_offline.hrl").
-export_type([property/0,
result/0,
form/0,
error_reason/0]).
-define(T(S), <<S>>).
-spec format_error(error_reason()) -> binary().
-spec io_format_error(error_reason()) -> {binary(),
[binary()]}.
-spec decode([xdata_field()]) -> result().
-spec decode([xdata_field()],
[binary(), ...]) -> result().
-spec decode([xdata_field()], [binary(), ...],
[binary()]) -> result().
-spec decode([xdata_field()], [binary(), ...],
[binary()], result()) -> result().
-spec do_decode([xdata_field()], binary(), [binary()],
result()) -> result().
-spec encode(form()) -> [xdata_field()].
-spec encode(form(), binary()) -> [xdata_field()].
-spec encode(form(), binary(),
[number_of_messages]) -> [xdata_field()].
dec_int(Val) -> dec_int(Val, infinity, infinity).
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.
enc_int(Int) -> integer_to_binary(Int).
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true -> AtomVal
end.
enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8).
dec_enum_int(Val, Enums) ->
try dec_int(Val) catch _:_ -> dec_enum(Val, Enums) end.
dec_enum_int(Val, Enums, Min, Max) ->
try dec_int(Val, Min, Max) catch
_:_ -> dec_enum(Val, Enums)
end.
enc_enum_int(Int) when is_integer(Int) -> enc_int(Int);
enc_enum_int(Atom) -> enc_enum(Atom).
dec_bool(<<"1">>) -> true;
dec_bool(<<"0">>) -> false;
dec_bool(<<"true">>) -> true;
dec_bool(<<"false">>) -> false.
enc_bool(true) -> <<"1">>;
enc_bool(false) -> <<"0">>.
not_empty(<<_, _/binary>> = Val) -> Val.
dec_ip(Val) ->
{ok, Addr} = inet_parse:address(binary_to_list(Val)),
Addr.
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)).
format_error({form_type_mismatch, Type}) ->
<<"FORM_TYPE doesn't match '", Type/binary, "'">>;
format_error({bad_var_value, Var, Type}) ->
<<"Bad value of field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({missing_value, Var, Type}) ->
<<"Missing value of field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({too_many_values, Var, Type}) ->
<<"Too many values for field '", Var/binary,
"' of type '", Type/binary, "'">>;
format_error({unknown_var, Var, Type}) ->
<<"Unknown field '", Var/binary, "' of type '",
Type/binary, "'">>;
format_error({missing_required_var, Var, Type}) ->
<<"Missing required field '", Var/binary, "' of type '",
Type/binary, "'">>.
io_format_error({form_type_mismatch, Type}) ->
{<<"FORM_TYPE doesn't match '~s'">>, [Type]};
io_format_error({bad_var_value, Var, Type}) ->
{<<"Bad value of field '~s' of type '~s'">>,
[Var, Type]};
io_format_error({missing_value, Var, Type}) ->
{<<"Missing value of field '~s' of type "
"'~s'">>,
[Var, Type]};
io_format_error({too_many_values, Var, Type}) ->
{<<"Too many values for field '~s' of type "
"'~s'">>,
[Var, Type]};
io_format_error({unknown_var, Var, Type}) ->
{<<"Unknown field '~s' of type '~s'">>, [Var, Type]};
io_format_error({missing_required_var, Var, Type}) ->
{<<"Missing required field '~s' of type "
"'~s'">>,
[Var, Type]}.
decode(Fs) ->
decode(Fs,
[<<"">>],
[],
[]).
decode(Fs, XMLNSList) -> decode(Fs, XMLNSList, [], []).
decode(Fs, XMLNSList, Required) ->
decode(Fs, XMLNSList, Required, []).
decode(Fs, [_ | _] = XMLNSList, Required, Acc) ->
case lists:keyfind(<<"FORM_TYPE">>,
#xdata_field.var,
Fs)
of
false -> do_decode(Fs, hd(XMLNSList), Required, Acc);
#xdata_field{values = [XMLNS]} ->
case lists:member(XMLNS, XMLNSList) of
true -> do_decode(Fs, XMLNS, Required, Acc);
false ->
erlang:error({?MODULE, {form_type_mismatch, XMLNS}})
end
end.
encode(Cfg) -> encode(Cfg, <<"en">>, []).
encode(Cfg, Lang) -> encode(Cfg, Lang, []).
encode(List, Lang, Required) ->
Fs = [case Opt of
{number_of_messages, Val} ->
[encode_number_of_messages(Val,
Lang,
lists:member(number_of_messages,
Required))];
#xdata_field{} -> [Opt]
end
|| Opt <- List],
FormType = #xdata_field{var = <<"FORM_TYPE">>,
type = hidden,
values =
[<<"">>]},
[FormType | lists:flatten(Fs)].
do_decode([#xdata_field{var = <<"number_of_messages">>,
values = [Value]}
| Fs],
XMLNS, Required, Acc) ->
try dec_int(Value, 0, infinity) of
Result ->
do_decode(Fs,
XMLNS,
lists:delete(<<"number_of_messages">>, Required),
[{number_of_messages, Result} | Acc])
catch
_:_ ->
erlang:error({?MODULE,
{bad_var_value, <<"number_of_messages">>, XMLNS}})
end;
do_decode([#xdata_field{var = <<"number_of_messages">>,
values = []} =
F
| Fs],
XMLNS, Required, Acc) ->
do_decode([F#xdata_field{var = <<"number_of_messages">>,
values = [<<>>]}
| Fs],
XMLNS,
Required,
Acc);
do_decode([#xdata_field{var = <<"number_of_messages">>}
| _],
XMLNS, _, _) ->
erlang:error({?MODULE,
{too_many_values, <<"number_of_messages">>, XMLNS}});
do_decode([#xdata_field{var = Var} | Fs], XMLNS,
Required, Acc) ->
if Var /= <<"FORM_TYPE">> ->
erlang:error({?MODULE, {unknown_var, Var, XMLNS}});
true -> do_decode(Fs, XMLNS, Required, Acc)
end;
do_decode([], XMLNS, [Var | _], _) ->
erlang:error({?MODULE,
{missing_required_var, Var, XMLNS}});
do_decode([], _, [], Acc) -> Acc.
-spec encode_number_of_messages(non_neg_integer() |
undefined,
binary(), boolean()) -> xdata_field().
encode_number_of_messages(Value, Lang, IsRequired) ->
Values = case Value of
undefined -> [];
Value -> [enc_int(Value)]
end,
Opts = [],
#xdata_field{var = <<"number_of_messages">>,
values = Values, required = IsRequired,
type = 'text-single', options = Opts, desc = <<>>,
label =
xmpp_tr:tr(Lang, ?T("Number of Offline Messages"))}.
|
74083c82c519cefe907a4efbca2c8f5d7fd31c6c2e9e0de83e83770be59b3b66 | LexiFi/menhir | MyMap.mli | (******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
(* file LICENSE. *)
(* *)
(******************************************************************************)
This is a stripped - down copy of the [ Map ] module from 's standard
library . The only difference is that [ add x d f m ] takes both a datum
[ default ] and a function [ f ] of data to data . If the key [ x ] is absent in the
map [ m ] , then a mapping of [ x ] to [ f default ] is added . If the key [ x ] is
present , then the existing datum if passed to [ f ] , which produces a new
datum . If the old and new data are physically the same , then the map [ m ] is
returned , physically unchanged . Otherwise , an updated map is returned . This
yields fewer memory allocations and an easy way of testing whether the
binding was already present in the set before it was added .
library. The only difference is that [add x d f m] takes both a datum
[default] and a function [f] of data to data. If the key [x] is absent in the
map [m], then a mapping of [x] to [f default] is added. If the key [x] is
present, then the existing datum if passed to [f], which produces a new
datum. If the old and new data are physically the same, then the map [m] is
returned, physically unchanged. Otherwise, an updated map is returned. This
yields fewer memory allocations and an easy way of testing whether the
binding was already present in the set before it was added. *)
module Make (Ord: Map.OrderedType) : sig
type key = Ord.t
type 'a t
val empty: 'a t
val add: key -> 'a -> ('a -> 'a) -> 'a t -> 'a t
val find: key -> 'a t -> 'a (* may raise [Not_found] *)
val iter: (key -> 'a -> unit) -> 'a t -> unit
end
| null | https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/attic/src/MyMap.mli | ocaml | ****************************************************************************
file LICENSE.
****************************************************************************
may raise [Not_found] |
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
This is a stripped - down copy of the [ Map ] module from 's standard
library . The only difference is that [ add x d f m ] takes both a datum
[ default ] and a function [ f ] of data to data . If the key [ x ] is absent in the
map [ m ] , then a mapping of [ x ] to [ f default ] is added . If the key [ x ] is
present , then the existing datum if passed to [ f ] , which produces a new
datum . If the old and new data are physically the same , then the map [ m ] is
returned , physically unchanged . Otherwise , an updated map is returned . This
yields fewer memory allocations and an easy way of testing whether the
binding was already present in the set before it was added .
library. The only difference is that [add x d f m] takes both a datum
[default] and a function [f] of data to data. If the key [x] is absent in the
map [m], then a mapping of [x] to [f default] is added. If the key [x] is
present, then the existing datum if passed to [f], which produces a new
datum. If the old and new data are physically the same, then the map [m] is
returned, physically unchanged. Otherwise, an updated map is returned. This
yields fewer memory allocations and an easy way of testing whether the
binding was already present in the set before it was added. *)
module Make (Ord: Map.OrderedType) : sig
type key = Ord.t
type 'a t
val empty: 'a t
val add: key -> 'a -> ('a -> 'a) -> 'a t -> 'a t
val iter: (key -> 'a -> unit) -> 'a t -> unit
end
|
87b55b3aa6f03f43d49ae985533a49658e6899d7cf35f3f92848760713b09c66 | Verites/verigraph | Semantics.hs | module Logic.Ctl.Semantics
( satisfyExpr
, satisfyExpr'
) where
import Data.List
import Logic.Ctl.Base
import Logic.Model
| Obtain all states that satisfy the given CTL expression .
satisfyExpr :: KripkeStructure String -> Expr -> [State String]
satisfyExpr model expr =
statesByIds model (satisfyExpr' model expr)
| Obtain the identifiers of all states that satisfy the given CTL expression .
satisfyExpr' :: KripkeStructure String -> Expr -> [Int]
satisfyExpr' _ (Literal False) =
[]
satisfyExpr' model (Literal True) =
stateIds model
satisfyExpr' model (Atom v) =
let
goodStates = filter (stateSatisfies v) (states model)
in
map elementId goodStates
satisfyExpr' model (Not p) =
let
badStates = satisfyExpr' model p
in
stateIds model \\ badStates
satisfyExpr' model (And p q) =
satisfyExpr' model p `intersect` satisfyExpr' model q
satisfyExpr' model (Or p q) =
satisfyExpr' model p `union` satisfyExpr' model q
satisfyExpr' model (Implies p q) =
satisfyExpr' model (q `Or` Not p)
satisfyExpr' model (Equiv p q) =
satisfyExpr' model ((p `And` q) `Or` (Not p `And` Not q))
satisfyExpr' model (Temporal p) =
satisfyTemporal model p
stateSatisfies :: String -> State String -> Bool
stateSatisfies p st =
p `elem` values st
satisfyTemporal :: KripkeStructure String -> PathQuantified Expr -> [Int]
satisfyTemporal model (A (X p)) =
satisfyExpr' model (Not$ Temporal$E$X$ Not p)
satisfyTemporal model (A (F p)) =
satisfyAllFuture model p
satisfyTemporal model (A (G p)) =
satisfyExpr' model (Not$ Temporal$E$F$ Not p)
satisfyTemporal model (A (U p q)) =
satisfyExpr' model (Not$ Or (Temporal$E$U (Not q) (Not p `And` Not q))
(Temporal$E$G$ Not q))
satisfyTemporal model (E (X p)) =
satisfySomeNext model p
satisfyTemporal model (E (F p)) =
satisfyTemporal model (E$U (Literal True) p)
satisfyTemporal model (E (G p)) =
satisfyExpr' model (Not$ Temporal$A$F$ Not p)
satisfyTemporal model (E (U p q)) =
satisfySomeUntil model p q
satisfyAllFuture :: KripkeStructure String -> Expr -> [Int]
satisfyAllFuture model p =
recursivelyAddPredecessors statesWherePHolds
where
statesWherePHolds =
satisfyExpr' model p
recursivelyAddPredecessors reachable =
let
reachable' =
reachable `union` predecessorsA model reachable
in
if reachable == reachable' then
reachable'
else
recursivelyAddPredecessors reachable'
satisfySomeNext :: KripkeStructure String -> Expr -> [Int]
satisfySomeNext model p =
let
statesWherePHolds =
satisfyExpr' model p
predecessorSets =
[ prevStates model st | st <- statesWherePHolds ]
in
foldl' union [] predecessorSets
satisfySomeUntil :: KripkeStructure String -> Expr -> Expr -> [Int]
satisfySomeUntil model p q =
recursivelyAddPredecessors statesWhereQHolds
where
statesWherePHolds =
satisfyExpr' model p
statesWhereQHolds =
satisfyExpr' model q
recursivelyAddPredecessors reachable =
let
predecessorsWherePHolds =
statesWherePHolds `intersect` predecessorsE model reachable
reachable' =
reachable `union` predecessorsWherePHolds
in
if reachable == reachable' then
reachable'
else
recursivelyAddPredecessors reachable'
-- | Obtain the states that are predecessors _only_ to states in the given set.
predecessorsA :: KripkeStructure a -> [Int] -> [Int]
predecessorsA model states =
let
allPredecessors =
predecessorsE model states
onlyHasCorrectSuccessors state =
nextStates model state `subsetOf` states
in
filter onlyHasCorrectSuccessors allPredecessors
-- | Obtain the states that are predecessors to _some_ state in the given set.
predecessorsE :: KripkeStructure a -> [Int] -> [Int]
predecessorsE model ids =
let
predecessorSets =
map (prevStates model) ids
in
foldl union [] predecessorSets
subsetOf :: Eq a => [a] -> [a] -> Bool
subsetOf as bs =
all (`elem` bs) as
statesByIds :: KripkeStructure a -> [Int] -> [State a]
statesByIds model =
map (`getState` model)
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/library/Logic/Ctl/Semantics.hs | haskell | | Obtain the states that are predecessors _only_ to states in the given set.
| Obtain the states that are predecessors to _some_ state in the given set. | module Logic.Ctl.Semantics
( satisfyExpr
, satisfyExpr'
) where
import Data.List
import Logic.Ctl.Base
import Logic.Model
| Obtain all states that satisfy the given CTL expression .
satisfyExpr :: KripkeStructure String -> Expr -> [State String]
satisfyExpr model expr =
statesByIds model (satisfyExpr' model expr)
| Obtain the identifiers of all states that satisfy the given CTL expression .
satisfyExpr' :: KripkeStructure String -> Expr -> [Int]
satisfyExpr' _ (Literal False) =
[]
satisfyExpr' model (Literal True) =
stateIds model
satisfyExpr' model (Atom v) =
let
goodStates = filter (stateSatisfies v) (states model)
in
map elementId goodStates
satisfyExpr' model (Not p) =
let
badStates = satisfyExpr' model p
in
stateIds model \\ badStates
satisfyExpr' model (And p q) =
satisfyExpr' model p `intersect` satisfyExpr' model q
satisfyExpr' model (Or p q) =
satisfyExpr' model p `union` satisfyExpr' model q
satisfyExpr' model (Implies p q) =
satisfyExpr' model (q `Or` Not p)
satisfyExpr' model (Equiv p q) =
satisfyExpr' model ((p `And` q) `Or` (Not p `And` Not q))
satisfyExpr' model (Temporal p) =
satisfyTemporal model p
stateSatisfies :: String -> State String -> Bool
stateSatisfies p st =
p `elem` values st
satisfyTemporal :: KripkeStructure String -> PathQuantified Expr -> [Int]
satisfyTemporal model (A (X p)) =
satisfyExpr' model (Not$ Temporal$E$X$ Not p)
satisfyTemporal model (A (F p)) =
satisfyAllFuture model p
satisfyTemporal model (A (G p)) =
satisfyExpr' model (Not$ Temporal$E$F$ Not p)
satisfyTemporal model (A (U p q)) =
satisfyExpr' model (Not$ Or (Temporal$E$U (Not q) (Not p `And` Not q))
(Temporal$E$G$ Not q))
satisfyTemporal model (E (X p)) =
satisfySomeNext model p
satisfyTemporal model (E (F p)) =
satisfyTemporal model (E$U (Literal True) p)
satisfyTemporal model (E (G p)) =
satisfyExpr' model (Not$ Temporal$A$F$ Not p)
satisfyTemporal model (E (U p q)) =
satisfySomeUntil model p q
satisfyAllFuture :: KripkeStructure String -> Expr -> [Int]
satisfyAllFuture model p =
recursivelyAddPredecessors statesWherePHolds
where
statesWherePHolds =
satisfyExpr' model p
recursivelyAddPredecessors reachable =
let
reachable' =
reachable `union` predecessorsA model reachable
in
if reachable == reachable' then
reachable'
else
recursivelyAddPredecessors reachable'
satisfySomeNext :: KripkeStructure String -> Expr -> [Int]
satisfySomeNext model p =
let
statesWherePHolds =
satisfyExpr' model p
predecessorSets =
[ prevStates model st | st <- statesWherePHolds ]
in
foldl' union [] predecessorSets
satisfySomeUntil :: KripkeStructure String -> Expr -> Expr -> [Int]
satisfySomeUntil model p q =
recursivelyAddPredecessors statesWhereQHolds
where
statesWherePHolds =
satisfyExpr' model p
statesWhereQHolds =
satisfyExpr' model q
recursivelyAddPredecessors reachable =
let
predecessorsWherePHolds =
statesWherePHolds `intersect` predecessorsE model reachable
reachable' =
reachable `union` predecessorsWherePHolds
in
if reachable == reachable' then
reachable'
else
recursivelyAddPredecessors reachable'
predecessorsA :: KripkeStructure a -> [Int] -> [Int]
predecessorsA model states =
let
allPredecessors =
predecessorsE model states
onlyHasCorrectSuccessors state =
nextStates model state `subsetOf` states
in
filter onlyHasCorrectSuccessors allPredecessors
predecessorsE :: KripkeStructure a -> [Int] -> [Int]
predecessorsE model ids =
let
predecessorSets =
map (prevStates model) ids
in
foldl union [] predecessorSets
subsetOf :: Eq a => [a] -> [a] -> Bool
subsetOf as bs =
all (`elem` bs) as
statesByIds :: KripkeStructure a -> [Int] -> [State a]
statesByIds model =
map (`getState` model)
|
0a95a85742a24b6be56486f738851ee09f35dd6135c8ab991362e70bfba9003c | atlas-engineer/nyxt | inspector.lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt)
(defvar *inspected-values* (tg:make-weak-hash-table :test 'equal :weakness :value))
(export-always 'sequence-p)
(defun sequence-p (object)
"Return true if OBJECT is a sequence that's not a string."
(typep object '(and sequence (not string))))
(export-always 'scalar-p)
(defun scalar-p (object)
;; REVIEW: List direct T subclasses instead?
"Return true if OBJECT is of one of the following types:
- symbol,
- character,
- string,
- non-complex number."
(funcall (alex:disjoin
'symbolp
'characterp
'stringp
(rcurry 'typep '(and number (not complex))))
object))
(export-always 'inspected-value)
(defmethod inspected-value (id)
(gethash id *inspected-values*))
(defmethod (setf inspected-value) (new-value id)
(setf (gethash id *inspected-values*) new-value))
(defun ensure-inspected-id (value)
(maphash
(lambda (id object)
(when (equal value object)
(return-from ensure-inspected-id id)))
*inspected-values*)
(sera:lret ((id (new-id)))
(setf (inspected-value id) value)))
(export-always '*inspector-print-length*)
(defvar *inspector-print-length* 20
"The size of the structure after which to collapse this structure into a link.
Can cause a renderer to choke when set to a high value. Use with caution!")
(defun escaped-literal-print (value)
(spinneret:with-html-string
(:code (:raw (spinneret::escape-string
(let ((*print-lines* 2)
(*print-length* *inspector-print-length*))
(prini-to-string value)))))))
(defun link-to (object)
(if (scalar-p object)
(spinneret:with-html-string
(:raw (escaped-literal-print object)))
(spinneret:with-html-string
(:a :href (nyxt-url 'describe-value :id (ensure-inspected-id object))
(:raw (escaped-literal-print object))))))
(defun compact-listing (sequence &key table-p)
(let ((length (min (length sequence) *inspector-print-length*)))
(spinneret:with-html-string
(cond
(table-p
(:table
(:tbody
(:tr
(dotimes (i length)
(:td (:raw (value->html (elt sequence i) t))))
(:td "More: " (:raw (link-to sequence)))))))))))
(export-always 'value->html)
(defgeneric value->html (value &optional compact-p)
(:method :around (value &optional compact-p)
(let ((spinneret:*html-style* :tree))
(call-next-method value compact-p)))
(:method (value &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:method ((value null) &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:method ((value string) &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:documentation "Produce HTML showing the structure of the VALUE.
If it's COMPACT-P, compress the output.
Specialize this generic function if you want to have a different markup for Lisp
values in help buffers, REPL and elsewhere."))
(defmethod value->html ((value function) &optional compact-p)
(spinneret:with-html-string
(let ((name (first (alex:ensure-list (swank-backend:function-name value)))))
(cond
((and name (eq name 'lambda) compact-p)
(:raw (link-to value)))
((and name (eq name 'lambda))
(multiple-value-bind (expression closure-p name)
(function-lambda-expression value)
(:dl
(:dt "name")
(:dd (:raw (escaped-literal-print name)))
(:dt "code")
(:dd (:raw (escaped-literal-print expression)))
(:dt "closure-p")
(:dd (:raw (value->html closure-p))))))
(name
(:a :href (nyxt-url 'describe-function :fn name)
(:raw (escaped-literal-print value))))
(t (:raw (escaped-literal-print value)))))))
(defmethod value->html ((value list) &optional compact-p)
(spinneret:with-html-string
(:div
:style "overflow-x: auto"
(cond
(compact-p
(:raw (compact-listing value :table-p t)))
((types:association-list-p value)
(:table
(unless compact-p
(:caption "Association list"))
(:thead
(dolist (e value)
(:th (:raw (value->html (car e) t)))))
(:tbody
(:tr
(dolist (e value)
(:td (:raw (value->html (rest e) t))))))))
((and (types:property-list-p value)
;; Stricter understanding of property lists:
;; -- Even length.
;; -- Keys are strictly keywords.
-- At least one value should be a non - keyword .
(evenp (length value))
(loop with all-values-keywords? = t
for (key val) on value by #'cddr
unless (keywordp key)
do (return nil)
unless (keywordp val)
do (setf all-values-keywords? nil)
finally (return (not all-values-keywords?))))
(:table
(unless compact-p
(:caption "Property list"))
(:thead (loop for key in value by #'cddr
collect (:th (:raw (escaped-literal-print key)))))
(:tbody
(:tr
(loop for val in (rest value) by #'cddr
collect (:td (:raw (value->html val t))))))))
((and (types:proper-list-p value)
(not (alexandria:circular-list-p value))
(not (alexandria:circular-tree-p value)))
(:ul
(dotimes (i (length value))
(:li (:raw (value->html (elt value i) t))))))
(t (:raw (escaped-literal-print value)))))))
(defmethod value->html ((value array) &optional compact-p)
(spinneret:with-html-string
(cond
((uiop:emptyp value)
(:raw (call-next-method)))
(compact-p
(:raw (compact-listing value :table-p t)))
(t (:div
:style "overflow-x: auto"
(case (length (array-dimensions value))
(1 (:table
(unless compact-p
(:caption "Array")
(:thead
(:th :colspan (alex:lastcar (array-dimensions value))
"Elements (" (princ-to-string (array-dimension value 0)) ")")))
(:tbody
(:tr
(loop for e across value
collect (:td (:raw (value->html e t))))))))
(2 (:table
(:tbody
(loop with height = (array-dimension value 0)
and width = (array-dimension value 1)
for y below height
collect (:tr (loop for x below width
collect (:td (:raw (value->html (aref value y x) t)))))))))
(otherwise (:raw (call-next-method)))))))))
(defmethod value->html ((value sequence) &optional compact-p)
(spinneret:with-html-string
(cond
((uiop:emptyp value)
(:raw (escaped-literal-print value)))
(compact-p
(:raw (compact-listing value :table-p compact-p)))
(t (:ul
(dotimes (i (length value))
(:li (:raw (value->html (elt value i) t)))))))))
(defmethod value->html ((value hash-table) &optional compact-p)
(spinneret:with-html-string
(:div
:style "overflow-x: auto"
(let ((keys (alex:hash-table-keys value)))
(cond
((uiop:emptyp keys)
(:raw (call-next-method)))
((and compact-p (> (hash-table-count value) *inspector-print-length*))
(:raw (link-to value)))
(t (:table
(unless compact-p
(:caption "Hash-table"))
(:thead (dolist (key keys)
(:th (:raw (escaped-literal-print key)))))
(:tbody
(:tr
(dolist (key keys)
(:td (:raw (value->html (gethash key value) t)))))))))))))
(defmethod value->html ((value pathname) &optional compact-p)
(let* ((namestring (uiop:native-namestring value))
(mime (mimes:mime namestring)))
(spinneret:with-html-string
(if compact-p
(:raw (link-to value))
(:a :href (quri.uri.file:make-uri-file :path namestring)
:title (if (uiop:directory-pathname-p value)
"directory"
mime)
(cond
((and (uiop:directory-pathname-p value)
(not compact-p))
;; REVIEW: This should use
;; `nyxt/file-manager-mode:directory-elements' (not accessible
;; at the time this is loaded) or an NFiles equivalent (should
we abstract most of File Manager to Nfiles ? )
(dolist (element (append (uiop:subdirectories value)
(uiop:directory-files value)))
(:li (:raw (value->html element t)))))
((and (str:starts-with-p "image/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:img :src (quri.uri.file:make-uri-file :path namestring)
:alt namestring)))
((and (str:starts-with-p "audio/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:audio :src (quri.uri.file:make-uri-file :path namestring)
:controls t)))
((and (str:starts-with-p "video/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:video :src (quri.uri.file:make-uri-file :path namestring)
:controls t)))
(t namestring)))))))
(defun print-complex-object (value compact-p)
(if compact-p
(link-to value)
(spinneret:with-html-string
(alex:if-let ((slot-names (mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots (class-of value)))))
(:dl
(dolist (slot-name slot-names)
(:dt (prini-to-string slot-name)
" "
(:button
:class "button"
:onclick (ps:ps (nyxt/ps:lisp-eval
(:title "change value")
(handler-case
(setf (slot-value value slot-name)
(first
(evaluate
(prompt1
:prompt (format nil "Set ~a to" slot-name)
:sources 'prompter:raw-source))))
(prompt-buffer-canceled nil))))
"change "))
(:dd (:raw (value->html (slot-value value slot-name) t)))))
(:raw (escaped-literal-print value))))))
(defmethod value->html ((value standard-object) &optional compact-p)
(print-complex-object value compact-p))
(defmethod value->html ((value structure-object) &optional compact-p)
(print-complex-object value compact-p))
| null | https://raw.githubusercontent.com/atlas-engineer/nyxt/4dfdcfaf54a1da0ccc7ce4dcda74e2c2d54a48c2/source/inspector.lisp | lisp | REVIEW: List direct T subclasses instead?
Stricter understanding of property lists:
-- Even length.
-- Keys are strictly keywords.
REVIEW: This should use
`nyxt/file-manager-mode:directory-elements' (not accessible
at the time this is loaded) or an NFiles equivalent (should | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt)
(defvar *inspected-values* (tg:make-weak-hash-table :test 'equal :weakness :value))
(export-always 'sequence-p)
(defun sequence-p (object)
"Return true if OBJECT is a sequence that's not a string."
(typep object '(and sequence (not string))))
(export-always 'scalar-p)
(defun scalar-p (object)
"Return true if OBJECT is of one of the following types:
- symbol,
- character,
- string,
- non-complex number."
(funcall (alex:disjoin
'symbolp
'characterp
'stringp
(rcurry 'typep '(and number (not complex))))
object))
(export-always 'inspected-value)
(defmethod inspected-value (id)
(gethash id *inspected-values*))
(defmethod (setf inspected-value) (new-value id)
(setf (gethash id *inspected-values*) new-value))
(defun ensure-inspected-id (value)
(maphash
(lambda (id object)
(when (equal value object)
(return-from ensure-inspected-id id)))
*inspected-values*)
(sera:lret ((id (new-id)))
(setf (inspected-value id) value)))
(export-always '*inspector-print-length*)
(defvar *inspector-print-length* 20
"The size of the structure after which to collapse this structure into a link.
Can cause a renderer to choke when set to a high value. Use with caution!")
(defun escaped-literal-print (value)
(spinneret:with-html-string
(:code (:raw (spinneret::escape-string
(let ((*print-lines* 2)
(*print-length* *inspector-print-length*))
(prini-to-string value)))))))
(defun link-to (object)
(if (scalar-p object)
(spinneret:with-html-string
(:raw (escaped-literal-print object)))
(spinneret:with-html-string
(:a :href (nyxt-url 'describe-value :id (ensure-inspected-id object))
(:raw (escaped-literal-print object))))))
(defun compact-listing (sequence &key table-p)
(let ((length (min (length sequence) *inspector-print-length*)))
(spinneret:with-html-string
(cond
(table-p
(:table
(:tbody
(:tr
(dotimes (i length)
(:td (:raw (value->html (elt sequence i) t))))
(:td "More: " (:raw (link-to sequence)))))))))))
(export-always 'value->html)
(defgeneric value->html (value &optional compact-p)
(:method :around (value &optional compact-p)
(let ((spinneret:*html-style* :tree))
(call-next-method value compact-p)))
(:method (value &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:method ((value null) &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:method ((value string) &optional compact-p)
(declare (ignore compact-p))
(escaped-literal-print value))
(:documentation "Produce HTML showing the structure of the VALUE.
If it's COMPACT-P, compress the output.
Specialize this generic function if you want to have a different markup for Lisp
values in help buffers, REPL and elsewhere."))
(defmethod value->html ((value function) &optional compact-p)
(spinneret:with-html-string
(let ((name (first (alex:ensure-list (swank-backend:function-name value)))))
(cond
((and name (eq name 'lambda) compact-p)
(:raw (link-to value)))
((and name (eq name 'lambda))
(multiple-value-bind (expression closure-p name)
(function-lambda-expression value)
(:dl
(:dt "name")
(:dd (:raw (escaped-literal-print name)))
(:dt "code")
(:dd (:raw (escaped-literal-print expression)))
(:dt "closure-p")
(:dd (:raw (value->html closure-p))))))
(name
(:a :href (nyxt-url 'describe-function :fn name)
(:raw (escaped-literal-print value))))
(t (:raw (escaped-literal-print value)))))))
(defmethod value->html ((value list) &optional compact-p)
(spinneret:with-html-string
(:div
:style "overflow-x: auto"
(cond
(compact-p
(:raw (compact-listing value :table-p t)))
((types:association-list-p value)
(:table
(unless compact-p
(:caption "Association list"))
(:thead
(dolist (e value)
(:th (:raw (value->html (car e) t)))))
(:tbody
(:tr
(dolist (e value)
(:td (:raw (value->html (rest e) t))))))))
((and (types:property-list-p value)
-- At least one value should be a non - keyword .
(evenp (length value))
(loop with all-values-keywords? = t
for (key val) on value by #'cddr
unless (keywordp key)
do (return nil)
unless (keywordp val)
do (setf all-values-keywords? nil)
finally (return (not all-values-keywords?))))
(:table
(unless compact-p
(:caption "Property list"))
(:thead (loop for key in value by #'cddr
collect (:th (:raw (escaped-literal-print key)))))
(:tbody
(:tr
(loop for val in (rest value) by #'cddr
collect (:td (:raw (value->html val t))))))))
((and (types:proper-list-p value)
(not (alexandria:circular-list-p value))
(not (alexandria:circular-tree-p value)))
(:ul
(dotimes (i (length value))
(:li (:raw (value->html (elt value i) t))))))
(t (:raw (escaped-literal-print value)))))))
(defmethod value->html ((value array) &optional compact-p)
(spinneret:with-html-string
(cond
((uiop:emptyp value)
(:raw (call-next-method)))
(compact-p
(:raw (compact-listing value :table-p t)))
(t (:div
:style "overflow-x: auto"
(case (length (array-dimensions value))
(1 (:table
(unless compact-p
(:caption "Array")
(:thead
(:th :colspan (alex:lastcar (array-dimensions value))
"Elements (" (princ-to-string (array-dimension value 0)) ")")))
(:tbody
(:tr
(loop for e across value
collect (:td (:raw (value->html e t))))))))
(2 (:table
(:tbody
(loop with height = (array-dimension value 0)
and width = (array-dimension value 1)
for y below height
collect (:tr (loop for x below width
collect (:td (:raw (value->html (aref value y x) t)))))))))
(otherwise (:raw (call-next-method)))))))))
(defmethod value->html ((value sequence) &optional compact-p)
(spinneret:with-html-string
(cond
((uiop:emptyp value)
(:raw (escaped-literal-print value)))
(compact-p
(:raw (compact-listing value :table-p compact-p)))
(t (:ul
(dotimes (i (length value))
(:li (:raw (value->html (elt value i) t)))))))))
(defmethod value->html ((value hash-table) &optional compact-p)
(spinneret:with-html-string
(:div
:style "overflow-x: auto"
(let ((keys (alex:hash-table-keys value)))
(cond
((uiop:emptyp keys)
(:raw (call-next-method)))
((and compact-p (> (hash-table-count value) *inspector-print-length*))
(:raw (link-to value)))
(t (:table
(unless compact-p
(:caption "Hash-table"))
(:thead (dolist (key keys)
(:th (:raw (escaped-literal-print key)))))
(:tbody
(:tr
(dolist (key keys)
(:td (:raw (value->html (gethash key value) t)))))))))))))
(defmethod value->html ((value pathname) &optional compact-p)
(let* ((namestring (uiop:native-namestring value))
(mime (mimes:mime namestring)))
(spinneret:with-html-string
(if compact-p
(:raw (link-to value))
(:a :href (quri.uri.file:make-uri-file :path namestring)
:title (if (uiop:directory-pathname-p value)
"directory"
mime)
(cond
((and (uiop:directory-pathname-p value)
(not compact-p))
we abstract most of File Manager to Nfiles ? )
(dolist (element (append (uiop:subdirectories value)
(uiop:directory-files value)))
(:li (:raw (value->html element t)))))
((and (str:starts-with-p "image/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:img :src (quri.uri.file:make-uri-file :path namestring)
:alt namestring)))
((and (str:starts-with-p "audio/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:audio :src (quri.uri.file:make-uri-file :path namestring)
:controls t)))
((and (str:starts-with-p "video/" mime)
(not compact-p))
(:figure
(:figcaption namestring)
(:video :src (quri.uri.file:make-uri-file :path namestring)
:controls t)))
(t namestring)))))))
(defun print-complex-object (value compact-p)
(if compact-p
(link-to value)
(spinneret:with-html-string
(alex:if-let ((slot-names (mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots (class-of value)))))
(:dl
(dolist (slot-name slot-names)
(:dt (prini-to-string slot-name)
" "
(:button
:class "button"
:onclick (ps:ps (nyxt/ps:lisp-eval
(:title "change value")
(handler-case
(setf (slot-value value slot-name)
(first
(evaluate
(prompt1
:prompt (format nil "Set ~a to" slot-name)
:sources 'prompter:raw-source))))
(prompt-buffer-canceled nil))))
"change "))
(:dd (:raw (value->html (slot-value value slot-name) t)))))
(:raw (escaped-literal-print value))))))
(defmethod value->html ((value standard-object) &optional compact-p)
(print-complex-object value compact-p))
(defmethod value->html ((value structure-object) &optional compact-p)
(print-complex-object value compact-p))
|
7d373b7ae08c58c95c62be0d0d8c9e7543cf528bc222618ea04afe8cd37fa50c | sigscale/snmp-collector | snmp_collector_trap_rfc3877.erl | %%% snmp_collector_trap_rfc3877.erl
%%% vim: ts=3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2016 - 2020 SigScale Global Inc.
%%% @end
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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
@doc This module normalizes RFC3877 traps received on NBI .
%%
%% Varbinds are mapped to alarm attributes, using the MIBs avaialable,
%% and to VES attributes.
%%
The following table shows the mapping between RFC3877 MIB attributes
%% and VES attributes.
%%
%% <h3> MIB Values and VNF Event Stream (VES) </h3>
%%
%% <p><table id="mt">
%% <thead>
%% <tr id="mt">
%% <th id="mt">MIB Values</th>
%% <th id="mt">VNF Event Stream (VES)</th>
%% <th id="mt">VES Value Type</th>
%% </tr>
%% </thead>
%% <tbody>
%% <tr id="mt">
%% <td id="mt">ituAlarmEventType</td>
%% <td id="mt">commonEventheader.eventType</td>
< td id="mt">e.g . " Quality of Service Alarm"</td >
%% </tr>
%% <tr id="mt">
%% <td id="mt">ituAlarmProbableCause</td>
%% <td id="mt">faultsFields.alarmAdditionalInformation.probableCause</td>
< td id="mt">3GPP 32.111 - 2 Annex B e.g. " Alarm Indication Signal ( AIS)</td >
%% </tr>
%% <tr id="mt">
%% <td id="mt">alarmDescription</td>
%% <td id="mt">faultFields.specificProblem</td>
%% <td id="mt"></td>
%% </tr>
%% <tr id="mt">
%% <td id="mt">ituAlarmAdditionalText</td>
%% <td id="mt">additionalText</td>
%% <td id="mt"></td>
%% </tr>
%% <tr id="mt">
%% <td id="mt">alarmActiveIndex/alarmClearIndex</td>
%% <td id="mt">faultFields.alarmAdditionalInformation.alarmId</td>
%% <td id="mt">Unique identifier of an alarm</td>
%% </tr>
%% <tr id="mt">
%% <td id="mt">ituAlarmPerceivedSeverity</td>
%% <td id="mt">faultFields.eventSeverity</td>
%% <td id="mt">CRITICAL | MAJOR | MINOR | WARNING | INDETERMINATE | CLEARED</td>
%% </tr>
%% <tr id="mt">
%% <td id="mt">snmpTrapOID</td>
%% <td id="mt">commonEventHeader.eventName</td>
%% <td id="mt">notifyNewAlarm | notifyChangedAlarm | notifyClearedAlarm</td>
%% </tr>
%% <tr id="mt">
%% <td id="mt">alarmActiveDateAndTime/alarmClearDateAndTime</td>
%% <td id="mt">commonEventHeader.startEpochMicrosec</td>
%% <td id="mt"></td>
%% </tr>
%% </tbody>
%% </table></p>
-module(snmp_collector_trap_rfc3877).
-copyright('Copyright (c) 2016 - 2020 SigScale Global Inc.').
-include("snmp_collector.hrl").
-behaviour(snmpm_user).
%% export snmpm_user call backs.
-export([handle_error/3, handle_agent/5,
handle_pdu/4, handle_trap/3, handle_inform/3,
handle_report/3]).
%% support deprecated_time_unit()
-define(MILLISECOND, milli_seconds).
%-define(MILLISECOND, millisecond).
-define(MICROSECOND, micro_seconds).
-define(MICROSECOND , microsecond ) .
% calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}})
-define(EPOCH, 62167219200).
%%----------------------------------------------------------------------
%% The snmp_collector_trap_rfc3877 public API
%%----------------------------------------------------------------------
-spec handle_error(ReqId, Reason, UserData) -> snmp:void()
when
ReqId :: integer(),
Reason :: {unexpected_pdu, SnmpInfo} |
{invalid_sec_info, SecInfo, SnmpInfo} |
{empty_message, Addr, Port} | term(),
SnmpInfo :: snmpm:snmp_gen_info(),
SecInfo :: term(),
Addr :: inet:ip_address(),
Port :: integer(),
UserData :: term().
%% @doc Handle sending an "asynchronous" error to the user.
@private
handle_error(ReqId, Reason, UserData) ->
snmp_collector_snmpm_user_default:handle_error(ReqId, Reason, UserData).
-spec handle_agent(Domain, Address, Type, SnmpInfo, UserData) -> Reply
when
Domain :: transportDomainUdpIpv4 | transportDomainUdpIpv6,
Address :: {inet:ip_address(), inet:port_number()},
Type :: pdu | trap | report | inform,
SnmpInfo :: SnmpPduInfo | SnmpTrapInfo |
SnmpReportInfo | SnmpInformInfo,
SnmpPduInfo :: snmpm:snmp_gen_info(),
SnmpTrapInfo :: snmpm:snmp_v1_trap_info(),
SnmpReportInfo :: snmpm:snmp_gen_info(),
SnmpInformInfo :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
%% @doc Handle messages received from an unknown agent.
@private
handle_agent(Domain, Address, Type, {ErrorStatus, ErrorIndex, Varbind}, UserData) ->
snmp_collector_snmpm_user_default:handle_agent(Domain,
Address , Type, {ErrorStatus, ErrorIndex, Varbind},
UserData);
handle_agent(Domain, Address, Type, {Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData) ->
snmp_collector_snmpm_user_default:handle_agent(Domain, Address, Type,
{Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData).
-spec handle_pdu(TargetName, ReqId, SnmpPduInfo, UserData) -> snmp:void()
when
TargetName :: snmpm:target_name(),
ReqId :: term(),
SnmpPduInfo :: snmpm:snmp_gen_info(),
UserData :: term().
%% @doc Handle the reply to a asynchronous request.
@private
handle_pdu(TargetName, ReqId, SnmpResponse, UserData) ->
snmp_collector_snmpm_user_default:handle_pdu(TargetName, ReqId, SnmpResponse, UserData).
-spec handle_trap(TargetName, SnmpTrapInfo, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpTrapInfo :: snmpm:snmp_v1_trap_info() | snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
%% @doc Handle a trap/notification message from an agent.
@private
handle_trap(TargetName, {ErrorStatus, ErrorIndex, Varbinds}, UserData) ->
case domain(Varbinds) of
other ->
snmp_collector_trap_generic:handle_trap(TargetName, {ErrorStatus,
ErrorIndex, Varbinds}, UserData);
fault ->
handle_fault(TargetName, Varbinds)
end;
handle_trap(TargetName, {Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData) ->
case domain(Varbinds) of
other ->
snmp_collector_trap_generic:handle_trap(TargetName,
{Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData);
fault ->
handle_fault(TargetName, Varbinds)
end.
-spec handle_inform(TargetName, SnmpInformInfo, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpInformInfo :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
%% @doc Handle a inform message.
@private
handle_inform(TargetName, SnmpInform, UserData) ->
snmp_collector_snmpm_user_default:handle_inform(TargetName, SnmpInform, UserData),
ignore.
-spec handle_report(TargetName, SnmpReport, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpReport :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
%% @doc Handle a report message.
@private
handle_report(TargetName, SnmpReport, UserData) ->
snmp_collector_snmpm_user_default:handle_report(TargetName, SnmpReport, UserData),
ignore.
%%----------------------------------------------------------------------
%% The internal functions
%%----------------------------------------------------------------------
-spec handle_fault(TargetName, Varbinds) -> Result
when
TargetName :: string(),
Varbinds :: snmp:varbinds(),
Result :: ignore | {error, Reason},
Reason :: term().
%% @doc Handle a fault event.
handle_fault(TargetName, Varbinds) ->
try
{ok, Pairs} = snmp_collector_utils:arrange_list(Varbinds),
{ok, NamesValues} = snmp_collector_utils:oids_to_names(Pairs, []),
AlarmDetails = fault(NamesValues),
snmp_collector_utils:update_counters(rfc3877, TargetName, AlarmDetails),
Event = snmp_collector_utils:create_event(TargetName, AlarmDetails, fault),
snmp_collector_utils:send_event(Event)
of
ok ->
ignore;
{error, Reason} ->
{error, Reason}
catch
_:Reason ->
{error, Reason}
end.
-spec fault(OidNameValuePair) -> VesNameValuePair
when
OidNameValuePair :: [{OidName, OidValue}],
OidName :: string(),
OidValue :: string(),
VesNameValuePair :: [{VesName, VesValue}],
VesName :: string(),
VesValue :: string ().
%% @doc CODEC for event.
fault([{"snmpTrapOID", "alarmActiveState"} | T] = _OldNameValuePair) ->
fault(T, "alarmNew", [{"eventName", ?EN_NEW},
{"alarmCondition", "alarmNew"}]);
fault([{"snmpTrapOID", "alarmClearState"} | T]) ->
fault(T, "alarmCleared", [{"eventName", ?EN_CLEARED},
{"alarmCondition", "alarmCleared"},
{"eventSeverity", ?ES_CLEARED}]).
%% @hidden
fault([{"alarmActiveIndex", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"alarmId", Value} | Acc]);
fault([{"alarmClearIndex", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"alarmId", Value} | Acc]);
fault([{"alarmActiveDateAndTime", Value} | T], EN, Acc)
when EN == "alarmNew", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"raisedTime", Value} | Acc]);
fault([{"alarmActiveDateAndTime", Value} | T], EN, Acc)
when EN == "alarmSeverityChange", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"changedTime", Value} | Acc]);
fault([{"alarmClearDateAndTime", Value} | T], EN, Acc)
when EN == "alarmCleared", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"clearedTime", Value} | Acc]);
fault([{"alarmActiveResourceId", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"sourceId", Value} | Acc]);
fault([{"alarmClearResourceId", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"sourceId", Value} | Acc]);
fault([{"alarmActiveEngineID", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"reportingEntityId", Value} | Acc]);
fault([{"alarmClearEngineID", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"reportingEntityId", Value} | Acc]);
fault([{"ituAlarmProbableCause", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"probableCause", probable_cause(Value)} | Acc]);
fault([{"alarmActiveDescription", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"specificProblem", Value} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "1"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_CLEARED} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "2"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_INDETERMINATE} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "3"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_CRITICAL} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "4"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_MAJOR} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "5"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_MINOR} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "6"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_WARNING} | Acc]);
fault([{"ituAlarmEventType", "2"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Communication_System} | Acc]);
fault([{"ituAlarmEventType", "3"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Quality_Of_Service_Alarm} | Acc]);
fault([{"ituAlarmEventType", "4"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Processing_Error} | Acc]);
fault([{"ituAlarmEventType", "5"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Equipment_Alarm} | Acc]);
fault([{"ituAlarmEventType", "6"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Environmental_Alarm} | Acc]);
fault([{"ituAlarmEventType", "7"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Integrity_Violation} | Acc]);
fault([{"ituAlarmEventType", "8"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Operational_Violation} | Acc]);
fault([{"ituAlarmEventType", "9"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Physical_Violation} | Acc]);
fault([{"ituAlarmEventType", "10"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Security_Service_Or_Mechanism_Violation} | Acc]);
fault([{"ituAlarmEventType", "11"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Time_Domain_Violation} | Acc]);
fault([{"ituAlarmAdditionalText", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"additionalText", Value} | Acc]);
fault([{_, [$ ]} | T], EN, Acc) ->
fault(T, EN, Acc);
fault([{_, []} | T], EN, Acc) ->
fault(T, EN, Acc);
fault([{Name, Value} | T], EN, Acc) ->
fault(T, EN, [{Name, Value} | Acc]);
fault([], _, Acc) ->
Acc.
-spec domain(Varbinds) -> Result
when
Varbinds :: [Varbinds],
Result :: fault | other.
%% @doc Check the domain of the event.
domain([_TimeTicks, {varbind, [1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0] , _, TrapName, _} | _T]) ->
domain1(snmp_collector_utils:oid_to_name(TrapName)).
%% @hidden
domain1("alarmActiveState") ->
fault;
domain1("alarmClearState") ->
fault;
domain1(_Other) ->
other.
-spec probable_cause(ProbableCauseCode) -> Result
when
ProbableCauseCode :: string(),
Result :: ProbableCause | ok,
ProbableCause :: string().
%% @doc Look up a probable cause.
probable_cause("1") ->
?PC_Alarm_Indication_Signal;
probable_cause("2") ->
?PC_Call_Setup_Failure;
probable_cause("3") ->
?PC_Degraded_Signal;
probable_cause("4") ->
?PC_FERF;
probable_cause("5") ->
?PC_Framing_Error;
probable_cause("6") ->
?PC_LOF;
probable_cause("7") ->
?PC_LOP;
probable_cause("8") ->
?PC_LOS;
probable_cause("9") ->
?PC_Payload_Type_Mismatch;
probable_cause("10") ->
?PC_Transmission_Error;
probable_cause("11") ->
?PC_Remote_Alarm_Interface;
probable_cause("12") ->
?PC_Excessive_Error_Rate;
probable_cause("13") ->
?PC_Path_Trace_Mismatch;
probable_cause("14") ->
?PC_Unavailable;
probable_cause("15") ->
?PC_Signal_Label_Mismatch;
probable_cause("16") ->
?PC_Loss_Of_Multi_Frame;
probable_cause("17") ->
?PC_Communications_Receive_Failure;
probable_cause("18") ->
?PC_Communications_Transmit_Failure;
probable_cause("19") ->
?PC_Modulaion_Failure;
probable_cause("20") ->
?PC_Demodulation_Failure;
probable_cause("21") ->
?PC_Broadcast_Channel_Failure;
probable_cause("22") ->
?PC_Connection_Establishment_Error;
probable_cause("23") ->
?PC_Invalid_Message_Received;
probable_cause("24") ->
?PC_Local_Node_Transmission_Error;
probable_cause("25") ->
?PC_Remote_Node_Transmission_Error;
probable_cause("26") ->
?PC_Routing_Failure;
probable_cause("51") ->
?PC_Back_Plane_Failure;
probable_cause("52") ->
?PC_Data_Set_Problem;
probable_cause("53") ->
?PC_Equipment_Identifier_Duplication;
probable_cause("54") ->
?PC_External_If_Device_Problem;
probable_cause("55") ->
?PC_Line_Card_Problem;
probable_cause("56") ->
?PC_Multiplexer_Problem;
probable_cause("57") ->
?PC_NE_Identifier_Duplication;
probable_cause("58") ->
?PC_Power_Problem;
probable_cause("59") ->
?PC_Processor_Problem;
probable_cause("60") ->
?PC_Protection_Path_Failure;
probable_cause("61") ->
?PC_Receiver_Failure;
probable_cause("62") ->
?PC_Replaceable_Unit_Missing;
probable_cause("63") ->
?PC_Replaceable_Unit_Type_Mismatch;
probable_cause("64") ->
?PC_Synchronization_Source_Mismatch;
probable_cause("65") ->
?PC_Terminal_Problem;
probable_cause("66") ->
?PC_Timing_Problem;
probable_cause("67") ->
?PC_Transmitter_Failure;
probable_cause("68") ->
?PC_Trunk_Card_Problem;
probable_cause("69") ->
?PC_Replaceable_Unit_Problem;
probable_cause("70") ->
?PC_Real_Time_Clock_Failure;
probable_cause("71") ->
?PC_Antenna_Failure;
probable_cause("72") ->
?PC_Battery_Charging_Failure;
probable_cause("73") ->
?PC_Disk_Failure;
probable_cause("74") ->
?PC_Frequency_Hopping_Failure;
probable_cause("75") ->
?PC_Input_Output_Device_Error;
probable_cause("76") ->
?PC_Loss_Of_Synchronization;
probable_cause("77") ->
?PC_Loss_Of_Redundancy;
probable_cause("78") ->
?PC_Power_Supply_Failure;
probable_cause("79") ->
?PC_Signal_Quality_Evaluation_Failure;
probable_cause("80") ->
?PC_Transceiver_Failure;
probable_cause("81") ->
?PC_Protection_Mechanism_Failure;
probable_cause("82") ->
?PC_Protecting_Resource_Failure;
probable_cause("101") ->
?PC_Air_Compressor_Failure;
probable_cause("102") ->
?PC_Air_Conditioning_Failure;
probable_cause("103") ->
?PC_Air_Dryer_Failure;
probable_cause("104") ->
?PC_Battery_Discharging;
probable_cause("105") ->
?PC_Battery_Failure;
probable_cause("106") ->
?PC_Commercial_Power_Failure;
probable_cause("107") ->
?PC_Cooling_Fan_Failure;
probable_cause("108") ->
?PC_Engine_Failure;
probable_cause("109") ->
?PC_Fire_Detector_Failure;
probable_cause("110") ->
?PC_Fuse_Failure;
probable_cause("111") ->
?PC_Generator_Failure;
probable_cause("112") ->
?PC_Low_Battery_Threshold;
probable_cause("113") ->
?PC_Pump_Failure;
probable_cause("114") ->
?PC_Rectifier_Failure;
probable_cause("115") ->
?PC_Rectifier_High_Voltage;
probable_cause("116") ->
?PC_Rectifier_Low_Voltage;
probable_cause("117") ->
?PC_Ventilation_System_Failure;
probable_cause("118") ->
?PC_Enclosure_Door_Open;
probable_cause("119") ->
?PC_Explosive_Gas;
probable_cause("120") ->
?PC_Fire;
probable_cause("121") ->
?PC_Flood;
probable_cause("122") ->
?PC_High_Humidity;
probable_cause("123") ->
?PC_High_Temperature;
probable_cause("124") ->
?PC_High_Wind;
probable_cause("125") ->
?PC_Ice_Build_Up;
probable_cause("126") ->
?PC_Intrusion_Detection;
probable_cause("127") ->
?PC_Low_Fuel;
probable_cause("128") ->
?PC_Low_Humidity;
probable_cause("129") ->
?PC_Low_Cable_Pressure;
probable_cause("130") ->
?PC_Low_Temperature;
probable_cause("131") ->
?PC_Low_Water;
probable_cause("132") ->
?PC_Smoke;
probable_cause("133") ->
?PC_Toxic_Gas;
probable_cause("134") ->
?PC_Cooling_System_Failure;
probable_cause("135") ->
?PC_External_Equipment_Failure;
probable_cause("136") ->
?PC_External_Point_Failure;
probable_cause("151") ->
?PC_Storage_Capacity_Problem;
probable_cause("152") ->
?PC_Memory_Mismatch;
probable_cause("153") ->
?PC_Corrupt_Data;
probable_cause("154") ->
?PC_Out_Of_CPU_Cycles;
probable_cause("155") ->
?PC_Software_Environment_Problem;
probable_cause("156") ->
?PC_Software_Download_Failure;
probable_cause("157") ->
?PC_Loss_Of_Real_Time;
probable_cause("158") ->
?PC_Reinitialized;
probable_cause("159") ->
?PC_Application_Subsystem_Failure;
probable_cause("160") ->
?PC_Configuration_Or_Customization_Error;
probable_cause("161") ->
?PC_Database_Inconsistency;
probable_cause("162") ->
?PC_File_Error;
probable_cause("163") ->
?PC_Out_Of_Memory;
probable_cause("164") ->
?PC_Software_Error;
probable_cause("165") ->
?PC_Timeout_Expired;
probable_cause("166") ->
?PC_Underlying_Resource_Unavailable;
probable_cause("167") ->
?PC_Version_Mismatch;
probable_cause("201") ->
?PC_Bandwidth_Reduced;
probable_cause("202") ->
?PC_Congestion;
probable_cause("203") ->
?PC_Excessive_Error_Rate;
probable_cause("204") ->
?PC_Excessive_Rresponse_Time;
probable_cause("205") ->
?PC_Excessive_Retransmission_Rate;
probable_cause("206") ->
?PC_Reduced_Logging_Capability;
probable_cause("207") ->
?PC_System_Resources_Overload;
probable_cause("500") ->
?PC_Adapter_Error;
probable_cause("501") ->
?PC_Application_Subsystem_Failure;
probable_cause("502") ->
?PC_Bandwidth_Reduced;
probable_cause("503") ->
?PC_Call_Establishment_Error;
probable_cause("504") ->
?PC_Communication_Protocol_Error;
probable_cause("505") ->
?PC_Communication_Subsystem_Failure;
probable_cause("506") ->
?PC_Configuration_Or_Customization_Error;
probable_cause("507") ->
?PC_Congestion;
probable_cause("508") ->
?PC_Corrupt_Data;
probable_cause("509") ->
?PC_CPU_Cycles_Limit_Exceeded;
probable_cause("510") ->
?PC_Data_Set_Or_Modem_Error;
probable_cause("511") ->
?PC_Degraded_Signal;
probable_cause("512") ->
?PC_DTE_DCE_Interface_Error;
probable_cause("513") ->
?PC_Enclosure_Door_Open;
probable_cause("514") ->
?PC_Equipment_Malfunction;
probable_cause("515") ->
?PC_Excessive_Vibration;
probable_cause("516") ->
?PC_File_Error;
probable_cause("517") ->
?PC_Fire_Detected;
probable_cause("518") ->
?PC_Framing_Error;
probable_cause("519") ->
?PC_HOVOCP;
probable_cause("520") ->
?PC_Humidity_Unacceptable;
probable_cause("521") ->
?PC_Input_Output_Device_Error;
probable_cause("522") ->
?PC_Input_Device_Error;
probable_cause("523") ->
?PC_LAN_Error;
probable_cause("524") ->
?PC_Leak_Detection;
probable_cause("525") ->
?PC_Local_Node_Transmission_Error;
probable_cause("526") ->
?PC_LOF;
probable_cause("527") ->
?PC_LOS;
probable_cause("528") ->
?PC_Material_Supply_Exhausted;
probable_cause("529") ->
?PC_Multiplexer_Problem;
probable_cause("530") ->
?PC_Out_Of_Memory;
probable_cause("531") ->
?PC_Output_Device_Error;
probable_cause("532") ->
?PC_Performance_Degraded;
probable_cause("533") ->
?PC_Power_Problem;
probable_cause("534") ->
?PC_Pressure_Unacceptable;
probable_cause("535") ->
?PC_Processor_Problem;
probable_cause("536") ->
?PC_Pump_Failure;
probable_cause("537") ->
?PC_Queue_Size_Exceeded;
probable_cause("538") ->
?PC_Receive_Failure;
probable_cause("539") ->
?PC_Receiver_Failure;
probable_cause("540") ->
?PC_Remote_Node_Transmission_Error;
probable_cause("541") ->
?PC_Resource_at_or_Nearing_Capacity;
probable_cause("542") ->
?PC_Excessive_Rresponse_Time;
probable_cause("543") ->
?PC_Excessive_Retransmission_Rate;
probable_cause("544") ->
?PC_Software_Error;
probable_cause("545") ->
?PC_Software_Program_Abnormally_Terminated;
probable_cause("546") ->
?PC_Software_Program_Error;
probable_cause("547") ->
?PC_Storage_Capacity_Problem;
probable_cause("548") ->
?PC_Temperature_Unacceptable;
probable_cause("549") ->
?PC_Threshold_Crossed;
probable_cause("550") ->
?PC_Timing_Problem;
probable_cause("551") ->
?PC_Toxic_Leak_Detected;
probable_cause("552") ->
?PC_Transmit_Failure;
probable_cause("553") ->
?PC_Transmitter_Failure;
probable_cause("554") ->
?PC_Underlying_Resource_Unavailable;
probable_cause("555") ->
?PC_Version_Mismatch;
probable_cause("600") ->
?PC_Authentication_Failure;
probable_cause("601") ->
?PC_Breach_Of_Confidentiality;
probable_cause("602") ->
?PC_Cable_Tamper;
probable_cause("603") ->
?PC_Delayed_Information;
probable_cause("604") ->
?PC_Denial_Of_Service;
probable_cause("605") ->
?PC_Duplicate_Information;
probable_cause("606") ->
?PC_Info_Missing;
probable_cause("607") ->
?PC_Info_Mod_Detected;
probable_cause("608") ->
?PC_Info_Out_Of_Sequence;
probable_cause("609") ->
?PC_Key_Expired;
probable_cause("610") ->
?PC_Non_Repudiation_Failure;
probable_cause("611") ->
?PC_Out_Of_Hours_Activity;
probable_cause("612") ->
?PC_Out_Of_Service;
probable_cause("613") ->
?PC_Procedural_Error;
probable_cause("614") ->
?PC_Unauthorized_Access_Attempt;
probable_cause("615") ->
?PC_Unexpected_Info;
probable_cause("1024") ->
?PC_Indeterminate;
probable_cause(ProbableCauseCode) ->
error_logger:info_report(["SNMP Manager Unrecognized Probable Cause",
{probableCause, ProbableCauseCode},
{module, ?MODULE}]),
ProbableCauseCode.
| null | https://raw.githubusercontent.com/sigscale/snmp-collector/cb6b95ed331abd6f258d8ea55bf34c57f2992444/src/snmp_collector_trap_rfc3877.erl | erlang | snmp_collector_trap_rfc3877.erl
vim: ts=3
@end
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.
Varbinds are mapped to alarm attributes, using the MIBs avaialable,
and to VES attributes.
and VES attributes.
<h3> MIB Values and VNF Event Stream (VES) </h3>
<p><table id="mt">
<thead>
<tr id="mt">
<th id="mt">MIB Values</th>
<th id="mt">VNF Event Stream (VES)</th>
<th id="mt">VES Value Type</th>
</tr>
</thead>
<tbody>
<tr id="mt">
<td id="mt">ituAlarmEventType</td>
<td id="mt">commonEventheader.eventType</td>
</tr>
<tr id="mt">
<td id="mt">ituAlarmProbableCause</td>
<td id="mt">faultsFields.alarmAdditionalInformation.probableCause</td>
</tr>
<tr id="mt">
<td id="mt">alarmDescription</td>
<td id="mt">faultFields.specificProblem</td>
<td id="mt"></td>
</tr>
<tr id="mt">
<td id="mt">ituAlarmAdditionalText</td>
<td id="mt">additionalText</td>
<td id="mt"></td>
</tr>
<tr id="mt">
<td id="mt">alarmActiveIndex/alarmClearIndex</td>
<td id="mt">faultFields.alarmAdditionalInformation.alarmId</td>
<td id="mt">Unique identifier of an alarm</td>
</tr>
<tr id="mt">
<td id="mt">ituAlarmPerceivedSeverity</td>
<td id="mt">faultFields.eventSeverity</td>
<td id="mt">CRITICAL | MAJOR | MINOR | WARNING | INDETERMINATE | CLEARED</td>
</tr>
<tr id="mt">
<td id="mt">snmpTrapOID</td>
<td id="mt">commonEventHeader.eventName</td>
<td id="mt">notifyNewAlarm | notifyChangedAlarm | notifyClearedAlarm</td>
</tr>
<tr id="mt">
<td id="mt">alarmActiveDateAndTime/alarmClearDateAndTime</td>
<td id="mt">commonEventHeader.startEpochMicrosec</td>
<td id="mt"></td>
</tr>
</tbody>
</table></p>
export snmpm_user call backs.
support deprecated_time_unit()
-define(MILLISECOND, millisecond).
calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}})
----------------------------------------------------------------------
The snmp_collector_trap_rfc3877 public API
----------------------------------------------------------------------
@doc Handle sending an "asynchronous" error to the user.
@doc Handle messages received from an unknown agent.
@doc Handle the reply to a asynchronous request.
@doc Handle a trap/notification message from an agent.
@doc Handle a inform message.
@doc Handle a report message.
----------------------------------------------------------------------
The internal functions
----------------------------------------------------------------------
@doc Handle a fault event.
@doc CODEC for event.
@hidden
@doc Check the domain of the event.
@hidden
@doc Look up a probable cause. | 2016 - 2020 SigScale Global Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@doc This module normalizes RFC3877 traps received on NBI .
The following table shows the mapping between RFC3877 MIB attributes
< td id="mt">e.g . " Quality of Service Alarm"</td >
< td id="mt">3GPP 32.111 - 2 Annex B e.g. " Alarm Indication Signal ( AIS)</td >
-module(snmp_collector_trap_rfc3877).
-copyright('Copyright (c) 2016 - 2020 SigScale Global Inc.').
-include("snmp_collector.hrl").
-behaviour(snmpm_user).
-export([handle_error/3, handle_agent/5,
handle_pdu/4, handle_trap/3, handle_inform/3,
handle_report/3]).
-define(MILLISECOND, milli_seconds).
-define(MICROSECOND, micro_seconds).
-define(MICROSECOND , microsecond ) .
-define(EPOCH, 62167219200).
-spec handle_error(ReqId, Reason, UserData) -> snmp:void()
when
ReqId :: integer(),
Reason :: {unexpected_pdu, SnmpInfo} |
{invalid_sec_info, SecInfo, SnmpInfo} |
{empty_message, Addr, Port} | term(),
SnmpInfo :: snmpm:snmp_gen_info(),
SecInfo :: term(),
Addr :: inet:ip_address(),
Port :: integer(),
UserData :: term().
@private
handle_error(ReqId, Reason, UserData) ->
snmp_collector_snmpm_user_default:handle_error(ReqId, Reason, UserData).
-spec handle_agent(Domain, Address, Type, SnmpInfo, UserData) -> Reply
when
Domain :: transportDomainUdpIpv4 | transportDomainUdpIpv6,
Address :: {inet:ip_address(), inet:port_number()},
Type :: pdu | trap | report | inform,
SnmpInfo :: SnmpPduInfo | SnmpTrapInfo |
SnmpReportInfo | SnmpInformInfo,
SnmpPduInfo :: snmpm:snmp_gen_info(),
SnmpTrapInfo :: snmpm:snmp_v1_trap_info(),
SnmpReportInfo :: snmpm:snmp_gen_info(),
SnmpInformInfo :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
@private
handle_agent(Domain, Address, Type, {ErrorStatus, ErrorIndex, Varbind}, UserData) ->
snmp_collector_snmpm_user_default:handle_agent(Domain,
Address , Type, {ErrorStatus, ErrorIndex, Varbind},
UserData);
handle_agent(Domain, Address, Type, {Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData) ->
snmp_collector_snmpm_user_default:handle_agent(Domain, Address, Type,
{Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData).
-spec handle_pdu(TargetName, ReqId, SnmpPduInfo, UserData) -> snmp:void()
when
TargetName :: snmpm:target_name(),
ReqId :: term(),
SnmpPduInfo :: snmpm:snmp_gen_info(),
UserData :: term().
@private
handle_pdu(TargetName, ReqId, SnmpResponse, UserData) ->
snmp_collector_snmpm_user_default:handle_pdu(TargetName, ReqId, SnmpResponse, UserData).
-spec handle_trap(TargetName, SnmpTrapInfo, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpTrapInfo :: snmpm:snmp_v1_trap_info() | snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
@private
handle_trap(TargetName, {ErrorStatus, ErrorIndex, Varbinds}, UserData) ->
case domain(Varbinds) of
other ->
snmp_collector_trap_generic:handle_trap(TargetName, {ErrorStatus,
ErrorIndex, Varbinds}, UserData);
fault ->
handle_fault(TargetName, Varbinds)
end;
handle_trap(TargetName, {Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData) ->
case domain(Varbinds) of
other ->
snmp_collector_trap_generic:handle_trap(TargetName,
{Enteprise, Generic, Spec, Timestamp, Varbinds}, UserData);
fault ->
handle_fault(TargetName, Varbinds)
end.
-spec handle_inform(TargetName, SnmpInformInfo, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpInformInfo :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
@private
handle_inform(TargetName, SnmpInform, UserData) ->
snmp_collector_snmpm_user_default:handle_inform(TargetName, SnmpInform, UserData),
ignore.
-spec handle_report(TargetName, SnmpReport, UserData) -> Reply
when
TargetName :: snmpm:target_name(),
SnmpReport :: snmpm:snmp_gen_info(),
UserData :: term(),
Reply :: ignore.
@private
handle_report(TargetName, SnmpReport, UserData) ->
snmp_collector_snmpm_user_default:handle_report(TargetName, SnmpReport, UserData),
ignore.
-spec handle_fault(TargetName, Varbinds) -> Result
when
TargetName :: string(),
Varbinds :: snmp:varbinds(),
Result :: ignore | {error, Reason},
Reason :: term().
handle_fault(TargetName, Varbinds) ->
try
{ok, Pairs} = snmp_collector_utils:arrange_list(Varbinds),
{ok, NamesValues} = snmp_collector_utils:oids_to_names(Pairs, []),
AlarmDetails = fault(NamesValues),
snmp_collector_utils:update_counters(rfc3877, TargetName, AlarmDetails),
Event = snmp_collector_utils:create_event(TargetName, AlarmDetails, fault),
snmp_collector_utils:send_event(Event)
of
ok ->
ignore;
{error, Reason} ->
{error, Reason}
catch
_:Reason ->
{error, Reason}
end.
-spec fault(OidNameValuePair) -> VesNameValuePair
when
OidNameValuePair :: [{OidName, OidValue}],
OidName :: string(),
OidValue :: string(),
VesNameValuePair :: [{VesName, VesValue}],
VesName :: string(),
VesValue :: string ().
fault([{"snmpTrapOID", "alarmActiveState"} | T] = _OldNameValuePair) ->
fault(T, "alarmNew", [{"eventName", ?EN_NEW},
{"alarmCondition", "alarmNew"}]);
fault([{"snmpTrapOID", "alarmClearState"} | T]) ->
fault(T, "alarmCleared", [{"eventName", ?EN_CLEARED},
{"alarmCondition", "alarmCleared"},
{"eventSeverity", ?ES_CLEARED}]).
fault([{"alarmActiveIndex", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"alarmId", Value} | Acc]);
fault([{"alarmClearIndex", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"alarmId", Value} | Acc]);
fault([{"alarmActiveDateAndTime", Value} | T], EN, Acc)
when EN == "alarmNew", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"raisedTime", Value} | Acc]);
fault([{"alarmActiveDateAndTime", Value} | T], EN, Acc)
when EN == "alarmSeverityChange", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"changedTime", Value} | Acc]);
fault([{"alarmClearDateAndTime", Value} | T], EN, Acc)
when EN == "alarmCleared", is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"clearedTime", Value} | Acc]);
fault([{"alarmActiveResourceId", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"sourceId", Value} | Acc]);
fault([{"alarmClearResourceId", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"sourceId", Value} | Acc]);
fault([{"alarmActiveEngineID", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"reportingEntityId", Value} | Acc]);
fault([{"alarmClearEngineID", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"reportingEntityId", Value} | Acc]);
fault([{"ituAlarmProbableCause", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"probableCause", probable_cause(Value)} | Acc]);
fault([{"alarmActiveDescription", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"specificProblem", Value} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "1"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_CLEARED} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "2"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_INDETERMINATE} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "3"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_CRITICAL} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "4"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_MAJOR} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "5"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_MINOR} | Acc]);
fault([{"ituAlarmPerceivedSeverity", "6"} | T], EN, Acc) ->
fault(T, EN, [{"eventSeverity", ?ES_WARNING} | Acc]);
fault([{"ituAlarmEventType", "2"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Communication_System} | Acc]);
fault([{"ituAlarmEventType", "3"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Quality_Of_Service_Alarm} | Acc]);
fault([{"ituAlarmEventType", "4"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Processing_Error} | Acc]);
fault([{"ituAlarmEventType", "5"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Equipment_Alarm} | Acc]);
fault([{"ituAlarmEventType", "6"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Environmental_Alarm} | Acc]);
fault([{"ituAlarmEventType", "7"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Integrity_Violation} | Acc]);
fault([{"ituAlarmEventType", "8"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Operational_Violation} | Acc]);
fault([{"ituAlarmEventType", "9"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Physical_Violation} | Acc]);
fault([{"ituAlarmEventType", "10"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Security_Service_Or_Mechanism_Violation} | Acc]);
fault([{"ituAlarmEventType", "11"} | T], EN, Acc) ->
fault(T, EN, [{"eventType", ?ET_Time_Domain_Violation} | Acc]);
fault([{"ituAlarmAdditionalText", Value} | T], EN, Acc)
when is_list(Value), length(Value) > 0 ->
fault(T, EN, [{"additionalText", Value} | Acc]);
fault([{_, [$ ]} | T], EN, Acc) ->
fault(T, EN, Acc);
fault([{_, []} | T], EN, Acc) ->
fault(T, EN, Acc);
fault([{Name, Value} | T], EN, Acc) ->
fault(T, EN, [{Name, Value} | Acc]);
fault([], _, Acc) ->
Acc.
-spec domain(Varbinds) -> Result
when
Varbinds :: [Varbinds],
Result :: fault | other.
domain([_TimeTicks, {varbind, [1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0] , _, TrapName, _} | _T]) ->
domain1(snmp_collector_utils:oid_to_name(TrapName)).
domain1("alarmActiveState") ->
fault;
domain1("alarmClearState") ->
fault;
domain1(_Other) ->
other.
-spec probable_cause(ProbableCauseCode) -> Result
when
ProbableCauseCode :: string(),
Result :: ProbableCause | ok,
ProbableCause :: string().
probable_cause("1") ->
?PC_Alarm_Indication_Signal;
probable_cause("2") ->
?PC_Call_Setup_Failure;
probable_cause("3") ->
?PC_Degraded_Signal;
probable_cause("4") ->
?PC_FERF;
probable_cause("5") ->
?PC_Framing_Error;
probable_cause("6") ->
?PC_LOF;
probable_cause("7") ->
?PC_LOP;
probable_cause("8") ->
?PC_LOS;
probable_cause("9") ->
?PC_Payload_Type_Mismatch;
probable_cause("10") ->
?PC_Transmission_Error;
probable_cause("11") ->
?PC_Remote_Alarm_Interface;
probable_cause("12") ->
?PC_Excessive_Error_Rate;
probable_cause("13") ->
?PC_Path_Trace_Mismatch;
probable_cause("14") ->
?PC_Unavailable;
probable_cause("15") ->
?PC_Signal_Label_Mismatch;
probable_cause("16") ->
?PC_Loss_Of_Multi_Frame;
probable_cause("17") ->
?PC_Communications_Receive_Failure;
probable_cause("18") ->
?PC_Communications_Transmit_Failure;
probable_cause("19") ->
?PC_Modulaion_Failure;
probable_cause("20") ->
?PC_Demodulation_Failure;
probable_cause("21") ->
?PC_Broadcast_Channel_Failure;
probable_cause("22") ->
?PC_Connection_Establishment_Error;
probable_cause("23") ->
?PC_Invalid_Message_Received;
probable_cause("24") ->
?PC_Local_Node_Transmission_Error;
probable_cause("25") ->
?PC_Remote_Node_Transmission_Error;
probable_cause("26") ->
?PC_Routing_Failure;
probable_cause("51") ->
?PC_Back_Plane_Failure;
probable_cause("52") ->
?PC_Data_Set_Problem;
probable_cause("53") ->
?PC_Equipment_Identifier_Duplication;
probable_cause("54") ->
?PC_External_If_Device_Problem;
probable_cause("55") ->
?PC_Line_Card_Problem;
probable_cause("56") ->
?PC_Multiplexer_Problem;
probable_cause("57") ->
?PC_NE_Identifier_Duplication;
probable_cause("58") ->
?PC_Power_Problem;
probable_cause("59") ->
?PC_Processor_Problem;
probable_cause("60") ->
?PC_Protection_Path_Failure;
probable_cause("61") ->
?PC_Receiver_Failure;
probable_cause("62") ->
?PC_Replaceable_Unit_Missing;
probable_cause("63") ->
?PC_Replaceable_Unit_Type_Mismatch;
probable_cause("64") ->
?PC_Synchronization_Source_Mismatch;
probable_cause("65") ->
?PC_Terminal_Problem;
probable_cause("66") ->
?PC_Timing_Problem;
probable_cause("67") ->
?PC_Transmitter_Failure;
probable_cause("68") ->
?PC_Trunk_Card_Problem;
probable_cause("69") ->
?PC_Replaceable_Unit_Problem;
probable_cause("70") ->
?PC_Real_Time_Clock_Failure;
probable_cause("71") ->
?PC_Antenna_Failure;
probable_cause("72") ->
?PC_Battery_Charging_Failure;
probable_cause("73") ->
?PC_Disk_Failure;
probable_cause("74") ->
?PC_Frequency_Hopping_Failure;
probable_cause("75") ->
?PC_Input_Output_Device_Error;
probable_cause("76") ->
?PC_Loss_Of_Synchronization;
probable_cause("77") ->
?PC_Loss_Of_Redundancy;
probable_cause("78") ->
?PC_Power_Supply_Failure;
probable_cause("79") ->
?PC_Signal_Quality_Evaluation_Failure;
probable_cause("80") ->
?PC_Transceiver_Failure;
probable_cause("81") ->
?PC_Protection_Mechanism_Failure;
probable_cause("82") ->
?PC_Protecting_Resource_Failure;
probable_cause("101") ->
?PC_Air_Compressor_Failure;
probable_cause("102") ->
?PC_Air_Conditioning_Failure;
probable_cause("103") ->
?PC_Air_Dryer_Failure;
probable_cause("104") ->
?PC_Battery_Discharging;
probable_cause("105") ->
?PC_Battery_Failure;
probable_cause("106") ->
?PC_Commercial_Power_Failure;
probable_cause("107") ->
?PC_Cooling_Fan_Failure;
probable_cause("108") ->
?PC_Engine_Failure;
probable_cause("109") ->
?PC_Fire_Detector_Failure;
probable_cause("110") ->
?PC_Fuse_Failure;
probable_cause("111") ->
?PC_Generator_Failure;
probable_cause("112") ->
?PC_Low_Battery_Threshold;
probable_cause("113") ->
?PC_Pump_Failure;
probable_cause("114") ->
?PC_Rectifier_Failure;
probable_cause("115") ->
?PC_Rectifier_High_Voltage;
probable_cause("116") ->
?PC_Rectifier_Low_Voltage;
probable_cause("117") ->
?PC_Ventilation_System_Failure;
probable_cause("118") ->
?PC_Enclosure_Door_Open;
probable_cause("119") ->
?PC_Explosive_Gas;
probable_cause("120") ->
?PC_Fire;
probable_cause("121") ->
?PC_Flood;
probable_cause("122") ->
?PC_High_Humidity;
probable_cause("123") ->
?PC_High_Temperature;
probable_cause("124") ->
?PC_High_Wind;
probable_cause("125") ->
?PC_Ice_Build_Up;
probable_cause("126") ->
?PC_Intrusion_Detection;
probable_cause("127") ->
?PC_Low_Fuel;
probable_cause("128") ->
?PC_Low_Humidity;
probable_cause("129") ->
?PC_Low_Cable_Pressure;
probable_cause("130") ->
?PC_Low_Temperature;
probable_cause("131") ->
?PC_Low_Water;
probable_cause("132") ->
?PC_Smoke;
probable_cause("133") ->
?PC_Toxic_Gas;
probable_cause("134") ->
?PC_Cooling_System_Failure;
probable_cause("135") ->
?PC_External_Equipment_Failure;
probable_cause("136") ->
?PC_External_Point_Failure;
probable_cause("151") ->
?PC_Storage_Capacity_Problem;
probable_cause("152") ->
?PC_Memory_Mismatch;
probable_cause("153") ->
?PC_Corrupt_Data;
probable_cause("154") ->
?PC_Out_Of_CPU_Cycles;
probable_cause("155") ->
?PC_Software_Environment_Problem;
probable_cause("156") ->
?PC_Software_Download_Failure;
probable_cause("157") ->
?PC_Loss_Of_Real_Time;
probable_cause("158") ->
?PC_Reinitialized;
probable_cause("159") ->
?PC_Application_Subsystem_Failure;
probable_cause("160") ->
?PC_Configuration_Or_Customization_Error;
probable_cause("161") ->
?PC_Database_Inconsistency;
probable_cause("162") ->
?PC_File_Error;
probable_cause("163") ->
?PC_Out_Of_Memory;
probable_cause("164") ->
?PC_Software_Error;
probable_cause("165") ->
?PC_Timeout_Expired;
probable_cause("166") ->
?PC_Underlying_Resource_Unavailable;
probable_cause("167") ->
?PC_Version_Mismatch;
probable_cause("201") ->
?PC_Bandwidth_Reduced;
probable_cause("202") ->
?PC_Congestion;
probable_cause("203") ->
?PC_Excessive_Error_Rate;
probable_cause("204") ->
?PC_Excessive_Rresponse_Time;
probable_cause("205") ->
?PC_Excessive_Retransmission_Rate;
probable_cause("206") ->
?PC_Reduced_Logging_Capability;
probable_cause("207") ->
?PC_System_Resources_Overload;
probable_cause("500") ->
?PC_Adapter_Error;
probable_cause("501") ->
?PC_Application_Subsystem_Failure;
probable_cause("502") ->
?PC_Bandwidth_Reduced;
probable_cause("503") ->
?PC_Call_Establishment_Error;
probable_cause("504") ->
?PC_Communication_Protocol_Error;
probable_cause("505") ->
?PC_Communication_Subsystem_Failure;
probable_cause("506") ->
?PC_Configuration_Or_Customization_Error;
probable_cause("507") ->
?PC_Congestion;
probable_cause("508") ->
?PC_Corrupt_Data;
probable_cause("509") ->
?PC_CPU_Cycles_Limit_Exceeded;
probable_cause("510") ->
?PC_Data_Set_Or_Modem_Error;
probable_cause("511") ->
?PC_Degraded_Signal;
probable_cause("512") ->
?PC_DTE_DCE_Interface_Error;
probable_cause("513") ->
?PC_Enclosure_Door_Open;
probable_cause("514") ->
?PC_Equipment_Malfunction;
probable_cause("515") ->
?PC_Excessive_Vibration;
probable_cause("516") ->
?PC_File_Error;
probable_cause("517") ->
?PC_Fire_Detected;
probable_cause("518") ->
?PC_Framing_Error;
probable_cause("519") ->
?PC_HOVOCP;
probable_cause("520") ->
?PC_Humidity_Unacceptable;
probable_cause("521") ->
?PC_Input_Output_Device_Error;
probable_cause("522") ->
?PC_Input_Device_Error;
probable_cause("523") ->
?PC_LAN_Error;
probable_cause("524") ->
?PC_Leak_Detection;
probable_cause("525") ->
?PC_Local_Node_Transmission_Error;
probable_cause("526") ->
?PC_LOF;
probable_cause("527") ->
?PC_LOS;
probable_cause("528") ->
?PC_Material_Supply_Exhausted;
probable_cause("529") ->
?PC_Multiplexer_Problem;
probable_cause("530") ->
?PC_Out_Of_Memory;
probable_cause("531") ->
?PC_Output_Device_Error;
probable_cause("532") ->
?PC_Performance_Degraded;
probable_cause("533") ->
?PC_Power_Problem;
probable_cause("534") ->
?PC_Pressure_Unacceptable;
probable_cause("535") ->
?PC_Processor_Problem;
probable_cause("536") ->
?PC_Pump_Failure;
probable_cause("537") ->
?PC_Queue_Size_Exceeded;
probable_cause("538") ->
?PC_Receive_Failure;
probable_cause("539") ->
?PC_Receiver_Failure;
probable_cause("540") ->
?PC_Remote_Node_Transmission_Error;
probable_cause("541") ->
?PC_Resource_at_or_Nearing_Capacity;
probable_cause("542") ->
?PC_Excessive_Rresponse_Time;
probable_cause("543") ->
?PC_Excessive_Retransmission_Rate;
probable_cause("544") ->
?PC_Software_Error;
probable_cause("545") ->
?PC_Software_Program_Abnormally_Terminated;
probable_cause("546") ->
?PC_Software_Program_Error;
probable_cause("547") ->
?PC_Storage_Capacity_Problem;
probable_cause("548") ->
?PC_Temperature_Unacceptable;
probable_cause("549") ->
?PC_Threshold_Crossed;
probable_cause("550") ->
?PC_Timing_Problem;
probable_cause("551") ->
?PC_Toxic_Leak_Detected;
probable_cause("552") ->
?PC_Transmit_Failure;
probable_cause("553") ->
?PC_Transmitter_Failure;
probable_cause("554") ->
?PC_Underlying_Resource_Unavailable;
probable_cause("555") ->
?PC_Version_Mismatch;
probable_cause("600") ->
?PC_Authentication_Failure;
probable_cause("601") ->
?PC_Breach_Of_Confidentiality;
probable_cause("602") ->
?PC_Cable_Tamper;
probable_cause("603") ->
?PC_Delayed_Information;
probable_cause("604") ->
?PC_Denial_Of_Service;
probable_cause("605") ->
?PC_Duplicate_Information;
probable_cause("606") ->
?PC_Info_Missing;
probable_cause("607") ->
?PC_Info_Mod_Detected;
probable_cause("608") ->
?PC_Info_Out_Of_Sequence;
probable_cause("609") ->
?PC_Key_Expired;
probable_cause("610") ->
?PC_Non_Repudiation_Failure;
probable_cause("611") ->
?PC_Out_Of_Hours_Activity;
probable_cause("612") ->
?PC_Out_Of_Service;
probable_cause("613") ->
?PC_Procedural_Error;
probable_cause("614") ->
?PC_Unauthorized_Access_Attempt;
probable_cause("615") ->
?PC_Unexpected_Info;
probable_cause("1024") ->
?PC_Indeterminate;
probable_cause(ProbableCauseCode) ->
error_logger:info_report(["SNMP Manager Unrecognized Probable Cause",
{probableCause, ProbableCauseCode},
{module, ?MODULE}]),
ProbableCauseCode.
|
9735598530b1bb06fa7e8fdd4f86e4995c6f5a9957683670ccc3ca77f81f75ff | aws-beam/aws-erlang | aws_appsync.erl | %% WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
See -beam/aws-codegen for more details .
%% @doc AppSync provides API actions for creating and interacting with data
sources using GraphQL from your application .
-module(aws_appsync).
-export([associate_api/3,
associate_api/4,
create_api_cache/3,
create_api_cache/4,
create_api_key/3,
create_api_key/4,
create_data_source/3,
create_data_source/4,
create_domain_name/2,
create_domain_name/3,
create_function/3,
create_function/4,
create_graphql_api/2,
create_graphql_api/3,
create_resolver/4,
create_resolver/5,
create_type/3,
create_type/4,
delete_api_cache/3,
delete_api_cache/4,
delete_api_key/4,
delete_api_key/5,
delete_data_source/4,
delete_data_source/5,
delete_domain_name/3,
delete_domain_name/4,
delete_function/4,
delete_function/5,
delete_graphql_api/3,
delete_graphql_api/4,
delete_resolver/5,
delete_resolver/6,
delete_type/4,
delete_type/5,
disassociate_api/3,
disassociate_api/4,
evaluate_code/2,
evaluate_code/3,
evaluate_mapping_template/2,
evaluate_mapping_template/3,
flush_api_cache/3,
flush_api_cache/4,
get_api_association/2,
get_api_association/4,
get_api_association/5,
get_api_cache/2,
get_api_cache/4,
get_api_cache/5,
get_data_source/3,
get_data_source/5,
get_data_source/6,
get_domain_name/2,
get_domain_name/4,
get_domain_name/5,
get_function/3,
get_function/5,
get_function/6,
get_graphql_api/2,
get_graphql_api/4,
get_graphql_api/5,
get_introspection_schema/3,
get_introspection_schema/5,
get_introspection_schema/6,
get_resolver/4,
get_resolver/6,
get_resolver/7,
get_schema_creation_status/2,
get_schema_creation_status/4,
get_schema_creation_status/5,
get_type/4,
get_type/6,
get_type/7,
list_api_keys/2,
list_api_keys/4,
list_api_keys/5,
list_data_sources/2,
list_data_sources/4,
list_data_sources/5,
list_domain_names/1,
list_domain_names/3,
list_domain_names/4,
list_functions/2,
list_functions/4,
list_functions/5,
list_graphql_apis/1,
list_graphql_apis/3,
list_graphql_apis/4,
list_resolvers/3,
list_resolvers/5,
list_resolvers/6,
list_resolvers_by_function/3,
list_resolvers_by_function/5,
list_resolvers_by_function/6,
list_tags_for_resource/2,
list_tags_for_resource/4,
list_tags_for_resource/5,
list_types/3,
list_types/5,
list_types/6,
start_schema_creation/3,
start_schema_creation/4,
tag_resource/3,
tag_resource/4,
untag_resource/3,
untag_resource/4,
update_api_cache/3,
update_api_cache/4,
update_api_key/4,
update_api_key/5,
update_data_source/4,
update_data_source/5,
update_domain_name/3,
update_domain_name/4,
update_function/4,
update_function/5,
update_graphql_api/3,
update_graphql_api/4,
update_resolver/5,
update_resolver/6,
update_type/4,
update_type/5]).
-include_lib("hackney/include/hackney_lib.hrl").
%%====================================================================
%% API
%%====================================================================
%% @doc Maps an endpoint to your custom domain.
associate_api(Client, DomainName, Input) ->
associate_api(Client, DomainName, Input, []).
associate_api(Client, DomainName, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Creates a cache for the GraphQL API.
create_api_cache(Client, ApiId, Input) ->
create_api_cache(Client, ApiId, Input, []).
create_api_cache(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Creates a unique key that you can distribute to clients who invoke
%% your API.
create_api_key(Client, ApiId, Input) ->
create_api_key(Client, ApiId, Input, []).
create_api_key(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a ` DataSource ' object .
create_data_source(Client, ApiId, Input) ->
create_data_source(Client, ApiId, Input, []).
create_data_source(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a custom ` ' object .
create_domain_name(Client, Input) ->
create_domain_name(Client, Input, []).
create_domain_name(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Creates a `Function' object.
%%
%% A function is a reusable entity. You can use multiple functions to compose
%% the resolver logic.
create_function(Client, ApiId, Input) ->
create_function(Client, ApiId, Input, []).
create_function(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a ` GraphqlApi ' object .
create_graphql_api(Client, Input) ->
create_graphql_api(Client, Input, []).
create_graphql_api(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/apis"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Creates a `Resolver' object.
%%
%% A resolver converts incoming requests into a format that a data source can
understand , and converts the data source 's responses into GraphQL .
create_resolver(Client, ApiId, TypeName, Input) ->
create_resolver(Client, ApiId, TypeName, Input, []).
create_resolver(Client, ApiId, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Creates a `Type' object.
create_type(Client, ApiId, Input) ->
create_type(Client, ApiId, Input, []).
create_type(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes an ` ApiCache ' object .
delete_api_cache(Client, ApiId, Input) ->
delete_api_cache(Client, ApiId, Input, []).
delete_api_cache(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Deletes an API key.
delete_api_key(Client, ApiId, Id, Input) ->
delete_api_key(Client, ApiId, Id, Input, []).
delete_api_key(Client, ApiId, Id, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys/", aws_util:encode_uri(Id), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a ` DataSource ' object .
delete_data_source(Client, ApiId, Name, Input) ->
delete_data_source(Client, ApiId, Name, Input, []).
delete_data_source(Client, ApiId, Name, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a custom ` ' object .
delete_domain_name(Client, DomainName, Input) ->
delete_domain_name(Client, DomainName, Input, []).
delete_domain_name(Client, DomainName, Input0, Options0) ->
Method = delete,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Deletes a `Function'.
delete_function(Client, ApiId, FunctionId, Input) ->
delete_function(Client, ApiId, FunctionId, Input, []).
delete_function(Client, ApiId, FunctionId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a ` GraphqlApi ' object .
delete_graphql_api(Client, ApiId, Input) ->
delete_graphql_api(Client, ApiId, Input, []).
delete_graphql_api(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Deletes a `Resolver' object.
delete_resolver(Client, ApiId, FieldName, TypeName, Input) ->
delete_resolver(Client, ApiId, FieldName, TypeName, Input, []).
delete_resolver(Client, ApiId, FieldName, TypeName, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Deletes a `Type' object.
delete_type(Client, ApiId, TypeName, Input) ->
delete_type(Client, ApiId, TypeName, Input, []).
delete_type(Client, ApiId, TypeName, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Removes an ` ApiAssociation ' object from a custom domain .
disassociate_api(Client, DomainName, Input) ->
disassociate_api(Client, DomainName, Input, []).
disassociate_api(Client, DomainName, Input0, Options0) ->
Method = delete,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Evaluates the given code and returns the response.
%%
%% The code definition requirements depend on the specified runtime. For
%% `APPSYNC_JS' runtimes, the code defines the request and response
functions . The request function takes the incoming request after a GraphQL
%% operation is parsed and converts it into a request configuration for the
%% selected data source operation. The response function interprets responses
from the data source and maps it to the shape of the GraphQL field output
%% type.
evaluate_code(Client, Input) ->
evaluate_code(Client, Input, []).
evaluate_code(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/dataplane-evaluatecode"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Evaluates a given template and returns the response.
%%
%% The mapping template can be a request or response template.
%%
Request templates take the incoming request after a GraphQL operation is
%% parsed and convert it into a request configuration for the selected data
%% source operation. Response templates interpret responses from the data
source and map it to the shape of the GraphQL field output type .
%%
Mapping templates are written in the Apache Velocity Template Language
( VTL ) .
evaluate_mapping_template(Client, Input) ->
evaluate_mapping_template(Client, Input, []).
evaluate_mapping_template(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/dataplane-evaluatetemplate"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Flushes an ` ApiCache ' object .
flush_api_cache(Client, ApiId, Input) ->
flush_api_cache(Client, ApiId, Input, []).
flush_api_cache(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/FlushCache"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Retrieves an ` ApiAssociation ' object .
get_api_association(Client, DomainName)
when is_map(Client) ->
get_api_association(Client, DomainName, #{}, #{}).
get_api_association(Client, DomainName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_api_association(Client, DomainName, QueryMap, HeadersMap, []).
get_api_association(Client, DomainName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves an ` ApiCache ' object .
get_api_cache(Client, ApiId)
when is_map(Client) ->
get_api_cache(Client, ApiId, #{}, #{}).
get_api_cache(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_api_cache(Client, ApiId, QueryMap, HeadersMap, []).
get_api_cache(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a ` DataSource ' object .
get_data_source(Client, ApiId, Name)
when is_map(Client) ->
get_data_source(Client, ApiId, Name, #{}, #{}).
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap, []).
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a custom ` ' object .
get_domain_name(Client, DomainName)
when is_map(Client) ->
get_domain_name(Client, DomainName, #{}, #{}).
get_domain_name(Client, DomainName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_domain_name(Client, DomainName, QueryMap, HeadersMap, []).
get_domain_name(Client, DomainName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Get a `Function'.
get_function(Client, ApiId, FunctionId)
when is_map(Client) ->
get_function(Client, ApiId, FunctionId, #{}, #{}).
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, []).
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a ` GraphqlApi ' object .
get_graphql_api(Client, ApiId)
when is_map(Client) ->
get_graphql_api(Client, ApiId, #{}, #{}).
get_graphql_api(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_graphql_api(Client, ApiId, QueryMap, HeadersMap, []).
get_graphql_api(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Retrieves the introspection schema for a GraphQL API.
get_introspection_schema(Client, ApiId, Format)
when is_map(Client) ->
get_introspection_schema(Client, ApiId, Format, #{}, #{}).
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap, []).
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schema"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format},
{<<"includeDirectives">>, maps:get(<<"includeDirectives">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Retrieves a `Resolver' object.
get_resolver(Client, ApiId, FieldName, TypeName)
when is_map(Client) ->
get_resolver(Client, ApiId, FieldName, TypeName, #{}, #{}).
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap, []).
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Retrieves the current status of a schema creation operation.
get_schema_creation_status(Client, ApiId)
when is_map(Client) ->
get_schema_creation_status(Client, ApiId, #{}, #{}).
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap, []).
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schemacreation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Retrieves a `Type' object.
get_type(Client, ApiId, TypeName, Format)
when is_map(Client) ->
get_type(Client, ApiId, TypeName, Format, #{}, #{}).
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap, []).
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists the API keys for a given API.
%%
API keys are deleted automatically 60 days after they expire . However ,
%% they may still be included in the response until they have actually been
deleted . You can safely call ` DeleteApiKey ' to manually delete a key
%% before it's automatically deleted.
list_api_keys(Client, ApiId)
when is_map(Client) ->
list_api_keys(Client, ApiId, #{}, #{}).
list_api_keys(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_api_keys(Client, ApiId, QueryMap, HeadersMap, []).
list_api_keys(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists the data sources for a given API.
list_data_sources(Client, ApiId)
when is_map(Client) ->
list_data_sources(Client, ApiId, #{}, #{}).
list_data_sources(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_data_sources(Client, ApiId, QueryMap, HeadersMap, []).
list_data_sources(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists multiple custom domain names.
list_domain_names(Client)
when is_map(Client) ->
list_domain_names(Client, #{}, #{}).
list_domain_names(Client, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_domain_names(Client, QueryMap, HeadersMap, []).
list_domain_names(Client, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc List multiple functions.
list_functions(Client, ApiId)
when is_map(Client) ->
list_functions(Client, ApiId, #{}, #{}).
list_functions(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_functions(Client, ApiId, QueryMap, HeadersMap, []).
list_functions(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists your GraphQL APIs.
list_graphql_apis(Client)
when is_map(Client) ->
list_graphql_apis(Client, #{}, #{}).
list_graphql_apis(Client, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_graphql_apis(Client, QueryMap, HeadersMap, []).
list_graphql_apis(Client, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists the resolvers for a given API and type.
list_resolvers(Client, ApiId, TypeName)
when is_map(Client) ->
list_resolvers(Client, ApiId, TypeName, #{}, #{}).
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap, []).
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc List the resolvers that are associated with a specific function.
list_resolvers_by_function(Client, ApiId, FunctionId)
when is_map(Client) ->
list_resolvers_by_function(Client, ApiId, FunctionId, #{}, #{}).
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, []).
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists the tags for a resource.
list_tags_for_resource(Client, ResourceArn)
when is_map(Client) ->
list_tags_for_resource(Client, ResourceArn, #{}, #{}).
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []).
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Lists the types for a given API.
list_types(Client, ApiId, Format)
when is_map(Client) ->
list_types(Client, ApiId, Format, #{}, #{}).
list_types(Client, ApiId, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_types(Client, ApiId, Format, QueryMap, HeadersMap, []).
list_types(Client, ApiId, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format},
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
%% @doc Adds a new schema to your GraphQL API.
%%
%% This operation is asynchronous. Use to determine when it has completed.
start_schema_creation(Client, ApiId, Input) ->
start_schema_creation(Client, ApiId, Input, []).
start_schema_creation(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schemacreation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Tags a resource with user-supplied tags.
tag_resource(Client, ResourceArn, Input) ->
tag_resource(Client, ResourceArn, Input, []).
tag_resource(Client, ResourceArn, Input0, Options0) ->
Method = post,
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Untags a resource .
untag_resource(Client, ResourceArn, Input) ->
untag_resource(Client, ResourceArn, Input, []).
untag_resource(Client, ResourceArn, Input0, Options0) ->
Method = delete,
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
QueryMapping = [
{<<"tagKeys">>, <<"tagKeys">>}
],
{Query_, Input} = aws_request:build_headers(QueryMapping, Input2),
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Updates the cache for the GraphQL API.
update_api_cache(Client, ApiId, Input) ->
update_api_cache(Client, ApiId, Input, []).
update_api_cache(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches/update"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Updates an API key.
%%
%% You can update the key as long as it's not deleted.
update_api_key(Client, ApiId, Id, Input) ->
update_api_key(Client, ApiId, Id, Input, []).
update_api_key(Client, ApiId, Id, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys/", aws_util:encode_uri(Id), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a ` DataSource ' object .
update_data_source(Client, ApiId, Name, Input) ->
update_data_source(Client, ApiId, Name, Input, []).
update_data_source(Client, ApiId, Name, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a custom ` ' object .
update_domain_name(Client, DomainName, Input) ->
update_domain_name(Client, DomainName, Input, []).
update_domain_name(Client, DomainName, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Updates a `Function' object.
update_function(Client, ApiId, FunctionId, Input) ->
update_function(Client, ApiId, FunctionId, Input, []).
update_function(Client, ApiId, FunctionId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a ` GraphqlApi ' object .
update_graphql_api(Client, ApiId, Input) ->
update_graphql_api(Client, ApiId, Input, []).
update_graphql_api(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Updates a `Resolver' object.
update_resolver(Client, ApiId, FieldName, TypeName, Input) ->
update_resolver(Client, ApiId, FieldName, TypeName, Input, []).
update_resolver(Client, ApiId, FieldName, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%% @doc Updates a `Type' object.
update_type(Client, ApiId, TypeName, Input) ->
update_type(Client, ApiId, TypeName, Input, []).
update_type(Client, ApiId, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%%====================================================================
Internal functions
%%====================================================================
-spec request(aws_client:aws_client(), atom(), iolist(), list(),
list(), map() | undefined, list(), pos_integer() | undefined) ->
{ok, {integer(), list()}} |
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map(),
Error :: map().
request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end,
aws_request:request(RequestFun, Options).
do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
Client1 = Client#{service => <<"appsync">>},
Host = build_host(<<"appsync">>, Client1),
URL0 = build_url(Host, Path, Client1),
URL = aws_request:add_query(URL0, Query),
AdditionalHeaders1 = [ {<<"Host">>, Host}
, {<<"Content-Type">>, <<"application/x-amz-json-1.1">>}
],
Payload =
case proplists:get_value(send_body_as_binary, Options) of
true ->
maps:get(<<"Body">>, Input, <<"">>);
false ->
encode_payload(Input)
end,
AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of
true ->
add_checksum_hash_header(AdditionalHeaders1, Payload);
false ->
AdditionalHeaders1
end,
Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0),
MethodBin = aws_request:method_to_binary(Method),
SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload),
Response = hackney:request(Method, URL, SignedHeaders, Payload, Options),
DecodeBody = not proplists:get_value(receive_body_as_binary, Options),
handle_response(Response, SuccessStatusCode, DecodeBody).
add_checksum_hash_header(Headers, Body) ->
[ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))}
| Headers
].
handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
{ok, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) ->
{error, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
case hackney:body(Client) of
{ok, <<>>} when StatusCode =:= 200;
StatusCode =:= SuccessStatusCode ->
{ok, #{}, {StatusCode, ResponseHeaders, Client}};
{ok, Body} ->
Result = case DecodeBody of
true ->
try
jsx:decode(Body)
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
false -> #{<<"Body">> => Body}
end,
{ok, Result, {StatusCode, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody)
when StatusCode =:= 503 ->
Retriable error if retries are enabled
{error, service_unavailable};
handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) ->
{ok, Body} = hackney:body(Client),
try
DecodedError = jsx:decode(Body),
{error, DecodedError, {StatusCode, ResponseHeaders, Client}}
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
handle_response({error, Reason}, _, _DecodeBody) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Path0, Client) ->
Proto = aws_client:proto(Client),
Path = erlang:iolist_to_binary(Path0),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>).
-spec encode_payload(undefined | map()) -> binary().
encode_payload(undefined) ->
<<>>;
encode_payload(Input) ->
jsx:encode(Input).
| null | https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_appsync.erl | erlang | WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
@doc AppSync provides API actions for creating and interacting with data
====================================================================
API
====================================================================
@doc Maps an endpoint to your custom domain.
@doc Creates a cache for the GraphQL API.
@doc Creates a unique key that you can distribute to clients who invoke
your API.
@doc Creates a `Function' object.
A function is a reusable entity. You can use multiple functions to compose
the resolver logic.
@doc Creates a `Resolver' object.
A resolver converts incoming requests into a format that a data source can
@doc Creates a `Type' object.
@doc Deletes an API key.
@doc Deletes a `Function'.
@doc Deletes a `Resolver' object.
@doc Deletes a `Type' object.
@doc Evaluates the given code and returns the response.
The code definition requirements depend on the specified runtime. For
`APPSYNC_JS' runtimes, the code defines the request and response
operation is parsed and converts it into a request configuration for the
selected data source operation. The response function interprets responses
type.
@doc Evaluates a given template and returns the response.
The mapping template can be a request or response template.
parsed and convert it into a request configuration for the selected data
source operation. Response templates interpret responses from the data
@doc Get a `Function'.
@doc Retrieves the introspection schema for a GraphQL API.
@doc Retrieves a `Resolver' object.
@doc Retrieves the current status of a schema creation operation.
@doc Retrieves a `Type' object.
@doc Lists the API keys for a given API.
they may still be included in the response until they have actually been
before it's automatically deleted.
@doc Lists the data sources for a given API.
@doc Lists multiple custom domain names.
@doc List multiple functions.
@doc Lists your GraphQL APIs.
@doc Lists the resolvers for a given API and type.
@doc List the resolvers that are associated with a specific function.
@doc Lists the tags for a resource.
@doc Lists the types for a given API.
@doc Adds a new schema to your GraphQL API.
This operation is asynchronous. Use to determine when it has completed.
@doc Tags a resource with user-supplied tags.
@doc Updates the cache for the GraphQL API.
@doc Updates an API key.
You can update the key as long as it's not deleted.
@doc Updates a `Function' object.
@doc Updates a `Resolver' object.
@doc Updates a `Type' object.
====================================================================
==================================================================== | See -beam/aws-codegen for more details .
sources using GraphQL from your application .
-module(aws_appsync).
-export([associate_api/3,
associate_api/4,
create_api_cache/3,
create_api_cache/4,
create_api_key/3,
create_api_key/4,
create_data_source/3,
create_data_source/4,
create_domain_name/2,
create_domain_name/3,
create_function/3,
create_function/4,
create_graphql_api/2,
create_graphql_api/3,
create_resolver/4,
create_resolver/5,
create_type/3,
create_type/4,
delete_api_cache/3,
delete_api_cache/4,
delete_api_key/4,
delete_api_key/5,
delete_data_source/4,
delete_data_source/5,
delete_domain_name/3,
delete_domain_name/4,
delete_function/4,
delete_function/5,
delete_graphql_api/3,
delete_graphql_api/4,
delete_resolver/5,
delete_resolver/6,
delete_type/4,
delete_type/5,
disassociate_api/3,
disassociate_api/4,
evaluate_code/2,
evaluate_code/3,
evaluate_mapping_template/2,
evaluate_mapping_template/3,
flush_api_cache/3,
flush_api_cache/4,
get_api_association/2,
get_api_association/4,
get_api_association/5,
get_api_cache/2,
get_api_cache/4,
get_api_cache/5,
get_data_source/3,
get_data_source/5,
get_data_source/6,
get_domain_name/2,
get_domain_name/4,
get_domain_name/5,
get_function/3,
get_function/5,
get_function/6,
get_graphql_api/2,
get_graphql_api/4,
get_graphql_api/5,
get_introspection_schema/3,
get_introspection_schema/5,
get_introspection_schema/6,
get_resolver/4,
get_resolver/6,
get_resolver/7,
get_schema_creation_status/2,
get_schema_creation_status/4,
get_schema_creation_status/5,
get_type/4,
get_type/6,
get_type/7,
list_api_keys/2,
list_api_keys/4,
list_api_keys/5,
list_data_sources/2,
list_data_sources/4,
list_data_sources/5,
list_domain_names/1,
list_domain_names/3,
list_domain_names/4,
list_functions/2,
list_functions/4,
list_functions/5,
list_graphql_apis/1,
list_graphql_apis/3,
list_graphql_apis/4,
list_resolvers/3,
list_resolvers/5,
list_resolvers/6,
list_resolvers_by_function/3,
list_resolvers_by_function/5,
list_resolvers_by_function/6,
list_tags_for_resource/2,
list_tags_for_resource/4,
list_tags_for_resource/5,
list_types/3,
list_types/5,
list_types/6,
start_schema_creation/3,
start_schema_creation/4,
tag_resource/3,
tag_resource/4,
untag_resource/3,
untag_resource/4,
update_api_cache/3,
update_api_cache/4,
update_api_key/4,
update_api_key/5,
update_data_source/4,
update_data_source/5,
update_domain_name/3,
update_domain_name/4,
update_function/4,
update_function/5,
update_graphql_api/3,
update_graphql_api/4,
update_resolver/5,
update_resolver/6,
update_type/4,
update_type/5]).
-include_lib("hackney/include/hackney_lib.hrl").
associate_api(Client, DomainName, Input) ->
associate_api(Client, DomainName, Input, []).
associate_api(Client, DomainName, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
create_api_cache(Client, ApiId, Input) ->
create_api_cache(Client, ApiId, Input, []).
create_api_cache(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
create_api_key(Client, ApiId, Input) ->
create_api_key(Client, ApiId, Input, []).
create_api_key(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a ` DataSource ' object .
create_data_source(Client, ApiId, Input) ->
create_data_source(Client, ApiId, Input, []).
create_data_source(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a custom ` ' object .
create_domain_name(Client, Input) ->
create_domain_name(Client, Input, []).
create_domain_name(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
create_function(Client, ApiId, Input) ->
create_function(Client, ApiId, Input, []).
create_function(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Creates a ` GraphqlApi ' object .
create_graphql_api(Client, Input) ->
create_graphql_api(Client, Input, []).
create_graphql_api(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/apis"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
understand , and converts the data source 's responses into GraphQL .
create_resolver(Client, ApiId, TypeName, Input) ->
create_resolver(Client, ApiId, TypeName, Input, []).
create_resolver(Client, ApiId, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
create_type(Client, ApiId, Input) ->
create_type(Client, ApiId, Input, []).
create_type(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes an ` ApiCache ' object .
delete_api_cache(Client, ApiId, Input) ->
delete_api_cache(Client, ApiId, Input, []).
delete_api_cache(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
delete_api_key(Client, ApiId, Id, Input) ->
delete_api_key(Client, ApiId, Id, Input, []).
delete_api_key(Client, ApiId, Id, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys/", aws_util:encode_uri(Id), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a ` DataSource ' object .
delete_data_source(Client, ApiId, Name, Input) ->
delete_data_source(Client, ApiId, Name, Input, []).
delete_data_source(Client, ApiId, Name, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a custom ` ' object .
delete_domain_name(Client, DomainName, Input) ->
delete_domain_name(Client, DomainName, Input, []).
delete_domain_name(Client, DomainName, Input0, Options0) ->
Method = delete,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
delete_function(Client, ApiId, FunctionId, Input) ->
delete_function(Client, ApiId, FunctionId, Input, []).
delete_function(Client, ApiId, FunctionId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Deletes a ` GraphqlApi ' object .
delete_graphql_api(Client, ApiId, Input) ->
delete_graphql_api(Client, ApiId, Input, []).
delete_graphql_api(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
delete_resolver(Client, ApiId, FieldName, TypeName, Input) ->
delete_resolver(Client, ApiId, FieldName, TypeName, Input, []).
delete_resolver(Client, ApiId, FieldName, TypeName, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
delete_type(Client, ApiId, TypeName, Input) ->
delete_type(Client, ApiId, TypeName, Input, []).
delete_type(Client, ApiId, TypeName, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Removes an ` ApiAssociation ' object from a custom domain .
disassociate_api(Client, DomainName, Input) ->
disassociate_api(Client, DomainName, Input, []).
disassociate_api(Client, DomainName, Input0, Options0) ->
Method = delete,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
functions . The request function takes the incoming request after a GraphQL
from the data source and maps it to the shape of the GraphQL field output
evaluate_code(Client, Input) ->
evaluate_code(Client, Input, []).
evaluate_code(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/dataplane-evaluatecode"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
Request templates take the incoming request after a GraphQL operation is
source and map it to the shape of the GraphQL field output type .
Mapping templates are written in the Apache Velocity Template Language
( VTL ) .
evaluate_mapping_template(Client, Input) ->
evaluate_mapping_template(Client, Input, []).
evaluate_mapping_template(Client, Input0, Options0) ->
Method = post,
Path = ["/v1/dataplane-evaluatetemplate"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Flushes an ` ApiCache ' object .
flush_api_cache(Client, ApiId, Input) ->
flush_api_cache(Client, ApiId, Input, []).
flush_api_cache(Client, ApiId, Input0, Options0) ->
Method = delete,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/FlushCache"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Retrieves an ` ApiAssociation ' object .
get_api_association(Client, DomainName)
when is_map(Client) ->
get_api_association(Client, DomainName, #{}, #{}).
get_api_association(Client, DomainName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_api_association(Client, DomainName, QueryMap, HeadersMap, []).
get_api_association(Client, DomainName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), "/apiassociation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves an ` ApiCache ' object .
get_api_cache(Client, ApiId)
when is_map(Client) ->
get_api_cache(Client, ApiId, #{}, #{}).
get_api_cache(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_api_cache(Client, ApiId, QueryMap, HeadersMap, []).
get_api_cache(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a ` DataSource ' object .
get_data_source(Client, ApiId, Name)
when is_map(Client) ->
get_data_source(Client, ApiId, Name, #{}, #{}).
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap, []).
get_data_source(Client, ApiId, Name, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a custom ` ' object .
get_domain_name(Client, DomainName)
when is_map(Client) ->
get_domain_name(Client, DomainName, #{}, #{}).
get_domain_name(Client, DomainName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_domain_name(Client, DomainName, QueryMap, HeadersMap, []).
get_domain_name(Client, DomainName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
get_function(Client, ApiId, FunctionId)
when is_map(Client) ->
get_function(Client, ApiId, FunctionId, #{}, #{}).
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, []).
get_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
@doc Retrieves a ` GraphqlApi ' object .
get_graphql_api(Client, ApiId)
when is_map(Client) ->
get_graphql_api(Client, ApiId, #{}, #{}).
get_graphql_api(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_graphql_api(Client, ApiId, QueryMap, HeadersMap, []).
get_graphql_api(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
get_introspection_schema(Client, ApiId, Format)
when is_map(Client) ->
get_introspection_schema(Client, ApiId, Format, #{}, #{}).
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap, []).
get_introspection_schema(Client, ApiId, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schema"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format},
{<<"includeDirectives">>, maps:get(<<"includeDirectives">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
get_resolver(Client, ApiId, FieldName, TypeName)
when is_map(Client) ->
get_resolver(Client, ApiId, FieldName, TypeName, #{}, #{}).
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap, []).
get_resolver(Client, ApiId, FieldName, TypeName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
get_schema_creation_status(Client, ApiId)
when is_map(Client) ->
get_schema_creation_status(Client, ApiId, #{}, #{}).
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap, []).
get_schema_creation_status(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schemacreation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
get_type(Client, ApiId, TypeName, Format)
when is_map(Client) ->
get_type(Client, ApiId, TypeName, Format, #{}, #{}).
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap, []).
get_type(Client, ApiId, TypeName, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
API keys are deleted automatically 60 days after they expire . However ,
deleted . You can safely call ` DeleteApiKey ' to manually delete a key
list_api_keys(Client, ApiId)
when is_map(Client) ->
list_api_keys(Client, ApiId, #{}, #{}).
list_api_keys(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_api_keys(Client, ApiId, QueryMap, HeadersMap, []).
list_api_keys(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_data_sources(Client, ApiId)
when is_map(Client) ->
list_data_sources(Client, ApiId, #{}, #{}).
list_data_sources(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_data_sources(Client, ApiId, QueryMap, HeadersMap, []).
list_data_sources(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_domain_names(Client)
when is_map(Client) ->
list_domain_names(Client, #{}, #{}).
list_domain_names(Client, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_domain_names(Client, QueryMap, HeadersMap, []).
list_domain_names(Client, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/domainnames"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_functions(Client, ApiId)
when is_map(Client) ->
list_functions(Client, ApiId, #{}, #{}).
list_functions(Client, ApiId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_functions(Client, ApiId, QueryMap, HeadersMap, []).
list_functions(Client, ApiId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_graphql_apis(Client)
when is_map(Client) ->
list_graphql_apis(Client, #{}, #{}).
list_graphql_apis(Client, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_graphql_apis(Client, QueryMap, HeadersMap, []).
list_graphql_apis(Client, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_resolvers(Client, ApiId, TypeName)
when is_map(Client) ->
list_resolvers(Client, ApiId, TypeName, #{}, #{}).
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap, []).
list_resolvers(Client, ApiId, TypeName, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_resolvers_by_function(Client, ApiId, FunctionId)
when is_map(Client) ->
list_resolvers_by_function(Client, ApiId, FunctionId, #{}, #{}).
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, []).
list_resolvers_by_function(Client, ApiId, FunctionId, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), "/resolvers"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_tags_for_resource(Client, ResourceArn)
when is_map(Client) ->
list_tags_for_resource(Client, ResourceArn, #{}, #{}).
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, []).
list_tags_for_resource(Client, ResourceArn, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query_ = [],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
list_types(Client, ApiId, Format)
when is_map(Client) ->
list_types(Client, ApiId, Format, #{}, #{}).
list_types(Client, ApiId, Format, QueryMap, HeadersMap)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap) ->
list_types(Client, ApiId, Format, QueryMap, HeadersMap, []).
list_types(Client, ApiId, Format, QueryMap, HeadersMap, Options0)
when is_map(Client), is_map(QueryMap), is_map(HeadersMap), is_list(Options0) ->
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false}
| Options0],
Headers = [],
Query0_ =
[
{<<"format">>, Format},
{<<"maxResults">>, maps:get(<<"maxResults">>, QueryMap, undefined)},
{<<"nextToken">>, maps:get(<<"nextToken">>, QueryMap, undefined)}
],
Query_ = [H || {_, V} = H <- Query0_, V =/= undefined],
request(Client, get, Path, Query_, Headers, undefined, Options, SuccessStatusCode).
start_schema_creation(Client, ApiId, Input) ->
start_schema_creation(Client, ApiId, Input, []).
start_schema_creation(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/schemacreation"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
tag_resource(Client, ResourceArn, Input) ->
tag_resource(Client, ResourceArn, Input, []).
tag_resource(Client, ResourceArn, Input0, Options0) ->
Method = post,
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Untags a resource .
untag_resource(Client, ResourceArn, Input) ->
untag_resource(Client, ResourceArn, Input, []).
untag_resource(Client, ResourceArn, Input0, Options0) ->
Method = delete,
Path = ["/v1/tags/", aws_util:encode_uri(ResourceArn), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
QueryMapping = [
{<<"tagKeys">>, <<"tagKeys">>}
],
{Query_, Input} = aws_request:build_headers(QueryMapping, Input2),
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
update_api_cache(Client, ApiId, Input) ->
update_api_cache(Client, ApiId, Input, []).
update_api_cache(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/ApiCaches/update"],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
update_api_key(Client, ApiId, Id, Input) ->
update_api_key(Client, ApiId, Id, Input, []).
update_api_key(Client, ApiId, Id, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/apikeys/", aws_util:encode_uri(Id), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a ` DataSource ' object .
update_data_source(Client, ApiId, Name, Input) ->
update_data_source(Client, ApiId, Name, Input, []).
update_data_source(Client, ApiId, Name, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/datasources/", aws_util:encode_uri(Name), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a custom ` ' object .
update_domain_name(Client, DomainName, Input) ->
update_domain_name(Client, DomainName, Input, []).
update_domain_name(Client, DomainName, Input0, Options0) ->
Method = post,
Path = ["/v1/domainnames/", aws_util:encode_uri(DomainName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
update_function(Client, ApiId, FunctionId, Input) ->
update_function(Client, ApiId, FunctionId, Input, []).
update_function(Client, ApiId, FunctionId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/functions/", aws_util:encode_uri(FunctionId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
@doc Updates a ` GraphqlApi ' object .
update_graphql_api(Client, ApiId, Input) ->
update_graphql_api(Client, ApiId, Input, []).
update_graphql_api(Client, ApiId, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
update_resolver(Client, ApiId, FieldName, TypeName, Input) ->
update_resolver(Client, ApiId, FieldName, TypeName, Input, []).
update_resolver(Client, ApiId, FieldName, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), "/resolvers/", aws_util:encode_uri(FieldName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
update_type(Client, ApiId, TypeName, Input) ->
update_type(Client, ApiId, TypeName, Input, []).
update_type(Client, ApiId, TypeName, Input0, Options0) ->
Method = post,
Path = ["/v1/apis/", aws_util:encode_uri(ApiId), "/types/", aws_util:encode_uri(TypeName), ""],
SuccessStatusCode = undefined,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
Headers = [],
Input1 = Input0,
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
Internal functions
-spec request(aws_client:aws_client(), atom(), iolist(), list(),
list(), map() | undefined, list(), pos_integer() | undefined) ->
{ok, {integer(), list()}} |
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map(),
Error :: map().
request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end,
aws_request:request(RequestFun, Options).
do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
Client1 = Client#{service => <<"appsync">>},
Host = build_host(<<"appsync">>, Client1),
URL0 = build_url(Host, Path, Client1),
URL = aws_request:add_query(URL0, Query),
AdditionalHeaders1 = [ {<<"Host">>, Host}
, {<<"Content-Type">>, <<"application/x-amz-json-1.1">>}
],
Payload =
case proplists:get_value(send_body_as_binary, Options) of
true ->
maps:get(<<"Body">>, Input, <<"">>);
false ->
encode_payload(Input)
end,
AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of
true ->
add_checksum_hash_header(AdditionalHeaders1, Payload);
false ->
AdditionalHeaders1
end,
Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0),
MethodBin = aws_request:method_to_binary(Method),
SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload),
Response = hackney:request(Method, URL, SignedHeaders, Payload, Options),
DecodeBody = not proplists:get_value(receive_body_as_binary, Options),
handle_response(Response, SuccessStatusCode, DecodeBody).
add_checksum_hash_header(Headers, Body) ->
[ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))}
| Headers
].
handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
{ok, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) ->
{error, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
case hackney:body(Client) of
{ok, <<>>} when StatusCode =:= 200;
StatusCode =:= SuccessStatusCode ->
{ok, #{}, {StatusCode, ResponseHeaders, Client}};
{ok, Body} ->
Result = case DecodeBody of
true ->
try
jsx:decode(Body)
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
false -> #{<<"Body">> => Body}
end,
{ok, Result, {StatusCode, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody)
when StatusCode =:= 503 ->
Retriable error if retries are enabled
{error, service_unavailable};
handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) ->
{ok, Body} = hackney:body(Client),
try
DecodedError = jsx:decode(Body),
{error, DecodedError, {StatusCode, ResponseHeaders, Client}}
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
handle_response({error, Reason}, _, _DecodeBody) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Path0, Client) ->
Proto = aws_client:proto(Client),
Path = erlang:iolist_to_binary(Path0),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>).
-spec encode_payload(undefined | map()) -> binary().
encode_payload(undefined) ->
<<>>;
encode_payload(Input) ->
jsx:encode(Input).
|
131374383cc823aad672a6f5f1f9db6fa8c1858e45e644ce1d043a068ab0e4b5 | braidchat/braid | styles.cljs | (ns braid.page-subscriptions.styles
(:require
[braid.core.client.ui.styles.mixins :as mixins]
[braid.core.client.ui.styles.vars :as vars]
[garden.units :refer [px rem em]]))
(def tags-page
[:>.page.tags
[:>.title
{:font-size "large"}]
[:>.content
(mixins/settings-container-style)
[:>.new-tag
(mixins/settings-item-style)
[:input.error
{:color "red"}]]
[:>.tag-list
(mixins/settings-item-style)
[:>.tags
{:margin-top (em 1)
:color vars/grey-text}
[:>.tag-info
{:margin-bottom (em 1)}
[:.description-edit
[:textarea
{:display "block"
:width "100%"}]]
[:>.button
mixins/pill-button
{:margin-left (em 1)}]
[:button
{:margin-right (rem 0.5)}
[:&.delete
{:color "red"}
(mixins/fontawesome nil)]]
[:>.count
{:margin-right (em 0.5)}
[:&::after
{:margin-left (em 0.25)}]
[:&.threads-count
[:&::after
(mixins/fontawesome \uf181)]]
[:&.subscribers-count
[:&::after
(mixins/fontawesome \uf0c0)]]]]]]]])
| null | https://raw.githubusercontent.com/braidchat/braid/d94d94cd82b573809e0a6a93527ac3d66ef35202/src/braid/page_subscriptions/styles.cljs | clojure | (ns braid.page-subscriptions.styles
(:require
[braid.core.client.ui.styles.mixins :as mixins]
[braid.core.client.ui.styles.vars :as vars]
[garden.units :refer [px rem em]]))
(def tags-page
[:>.page.tags
[:>.title
{:font-size "large"}]
[:>.content
(mixins/settings-container-style)
[:>.new-tag
(mixins/settings-item-style)
[:input.error
{:color "red"}]]
[:>.tag-list
(mixins/settings-item-style)
[:>.tags
{:margin-top (em 1)
:color vars/grey-text}
[:>.tag-info
{:margin-bottom (em 1)}
[:.description-edit
[:textarea
{:display "block"
:width "100%"}]]
[:>.button
mixins/pill-button
{:margin-left (em 1)}]
[:button
{:margin-right (rem 0.5)}
[:&.delete
{:color "red"}
(mixins/fontawesome nil)]]
[:>.count
{:margin-right (em 0.5)}
[:&::after
{:margin-left (em 0.25)}]
[:&.threads-count
[:&::after
(mixins/fontawesome \uf181)]]
[:&.subscribers-count
[:&::after
(mixins/fontawesome \uf0c0)]]]]]]]])
| |
092bd1151d1122d4dee84684af17d0538fa0ad3ea9c294c8eb082010c9e58de6 | e-bigmoon/haskell-blog | JSON_conveniences3.hs | #!/usr/bin/env stack
{- stack repl --resolver lts-15.4
--package text
--package yesod
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeFamilies #-}
import Data.Text (Text)
import Yesod
data Person = Person
{ name :: Text
, age :: Int
}
instance ToJSON Person where
toJSON Person {..} = object
[ "name" .= name
, "age" .= age
]
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
getHomeR :: Handler TypedContent
getHomeR = selectRep $ do
provideRep $ return
[shamlet|
<p>Hello, my name is #{name} and I am #{age} years old.
|]
provideJson person
where
person@Person {..} = Person "Michael" 28
main :: IO ()
main = warp 3000 App
| null | https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/ch12/JSON_conveniences3.hs | haskell | stack repl --resolver lts-15.4
--package text
--package yesod
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeFamilies # | #!/usr/bin/env stack
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
import Data.Text (Text)
import Yesod
data Person = Person
{ name :: Text
, age :: Int
}
instance ToJSON Person where
toJSON Person {..} = object
[ "name" .= name
, "age" .= age
]
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
instance Yesod App
getHomeR :: Handler TypedContent
getHomeR = selectRep $ do
provideRep $ return
[shamlet|
<p>Hello, my name is #{name} and I am #{age} years old.
|]
provideJson person
where
person@Person {..} = Person "Michael" 28
main :: IO ()
main = warp 3000 App
|
a89230a15803507d639191b0e525524f96ac7c91b6056ac3b3e6a040cc507ad7 | roglo/mlrogue | rogbotio.mli | $ I d : rogbotio.mli , v 1.3 2010/05/04 07:55:17 deraugla Exp $
value socket : string -> Unix.file_descr;
value getchar : int -> int -> Unix.file_descr -> char;
| null | https://raw.githubusercontent.com/roglo/mlrogue/b73238bbbc8cd88c83579c3b72772a8c418020e5/rogbotio.mli | ocaml | $ I d : rogbotio.mli , v 1.3 2010/05/04 07:55:17 deraugla Exp $
value socket : string -> Unix.file_descr;
value getchar : int -> int -> Unix.file_descr -> char;
| |
80bfcfa1b45a9e1ccd441f406768e84c0eeaa949270dde01d8bd410b03743d7a | jeroanan/rkt-coreutils | realpath.rkt | #lang s-exp "util/frontend-program.rkt"
(simple-file-handler-program2 "repl/realpath.rkt" realpath)
| null | https://raw.githubusercontent.com/jeroanan/rkt-coreutils/571629d1e2562c557ba258b31ce454add2e93dd9/src/realpath.rkt | racket | #lang s-exp "util/frontend-program.rkt"
(simple-file-handler-program2 "repl/realpath.rkt" realpath)
| |
a568400ff89dcc17d6ae78ab147f03e19dd0d549017e0d14eb93b44b17f72607 | RedPRL/redtt | ResEnv.mli | open RedTT_Core
* This module has two responsibilities :
1 . maintain the mapping from strings to names .
2 . keep track of items to be serialized .
1. maintain the mapping from strings to names.
2. keep track of items to be serialized. *)
type resolution =
[ `Ix of int
| `Name of Name.t
]
type visibility =
[ `Private | `Public ]
type t
val init : unit -> t
val bind : string -> t -> t
val bindn : string list -> t -> t
val bind_opt : string option -> t -> t
val add_native_global : visibility:visibility -> Name.t -> t -> t
val import_global : visibility:visibility -> Name.t -> t -> t
val import_public : visibility:visibility -> t -> t -> t
val get : string -> t -> resolution
val get_name : string -> t -> Name.t
val native_of_name : Name.t -> t -> int option
val name_of_native : int -> t -> Name.t option
type exported_natives = (string option * Name.t) list
type exported_foreigners = Name.t list
val export_native_globals : t -> exported_natives
val export_foreign_globals : t -> exported_foreigners
val pp_visibility : visibility Pp.t0
| null | https://raw.githubusercontent.com/RedPRL/redtt/50689559ff970e33013b8cf8a3bbc8be18ec4e09/src/frontend/ResEnv.mli | ocaml | open RedTT_Core
* This module has two responsibilities :
1 . maintain the mapping from strings to names .
2 . keep track of items to be serialized .
1. maintain the mapping from strings to names.
2. keep track of items to be serialized. *)
type resolution =
[ `Ix of int
| `Name of Name.t
]
type visibility =
[ `Private | `Public ]
type t
val init : unit -> t
val bind : string -> t -> t
val bindn : string list -> t -> t
val bind_opt : string option -> t -> t
val add_native_global : visibility:visibility -> Name.t -> t -> t
val import_global : visibility:visibility -> Name.t -> t -> t
val import_public : visibility:visibility -> t -> t -> t
val get : string -> t -> resolution
val get_name : string -> t -> Name.t
val native_of_name : Name.t -> t -> int option
val name_of_native : int -> t -> Name.t option
type exported_natives = (string option * Name.t) list
type exported_foreigners = Name.t list
val export_native_globals : t -> exported_natives
val export_foreign_globals : t -> exported_foreigners
val pp_visibility : visibility Pp.t0
| |
6f009161e9d4a3ec1da843a3663de7b78fbaae6bf7ed7cc811297f4ec250f7dc | Eventuria/demonstration-gsd | Wrapper.hs | {-# LANGUAGE OverloadedStrings #-}
module Eventuria.Adapters.ByLine.Wrapper where
import qualified System.Console.Byline as ByLine (askWithMenuRepeatedly)
import System.Console.Byline hiding (askWithMenuRepeatedly)
import Control.Monad.IO.Class
import qualified Data.Text as Text
import Text.Printf (printf)
type ErrorDescription = String
askWithMenuRepeatedly :: (MonadIO m)
=> Menu availableActions -- ^ The 'Menu' to display.
-> Stylized -- ^ The prompt.
-> Stylized -- ^ Error message.
-> Byline m availableActions
askWithMenuRepeatedly m prompt errprompt = do
answer <- ByLine.askWithMenuRepeatedly m prompt errprompt
case answer of
Match action -> return action
NoItems -> error "unexpected NoItems returned"
Other x -> error "unexpected Other returned"
renderPrefixAndSuffixForDynamicGsdMenu :: Menu a -> Menu a
renderPrefixAndSuffixForDynamicGsdMenu menu =
prefix (\menuIndex -> fg white <> (text . Text.pack . printf "%2d") menuIndex)
$ suffix (fg white <> text "- ") menu
| null | https://raw.githubusercontent.com/Eventuria/demonstration-gsd/5c7692b310086bc172d3fd4e1eaf09ae51ea468f/src/Eventuria/Adapters/ByLine/Wrapper.hs | haskell | # LANGUAGE OverloadedStrings #
^ The 'Menu' to display.
^ The prompt.
^ Error message. | module Eventuria.Adapters.ByLine.Wrapper where
import qualified System.Console.Byline as ByLine (askWithMenuRepeatedly)
import System.Console.Byline hiding (askWithMenuRepeatedly)
import Control.Monad.IO.Class
import qualified Data.Text as Text
import Text.Printf (printf)
type ErrorDescription = String
askWithMenuRepeatedly :: (MonadIO m)
-> Byline m availableActions
askWithMenuRepeatedly m prompt errprompt = do
answer <- ByLine.askWithMenuRepeatedly m prompt errprompt
case answer of
Match action -> return action
NoItems -> error "unexpected NoItems returned"
Other x -> error "unexpected Other returned"
renderPrefixAndSuffixForDynamicGsdMenu :: Menu a -> Menu a
renderPrefixAndSuffixForDynamicGsdMenu menu =
prefix (\menuIndex -> fg white <> (text . Text.pack . printf "%2d") menuIndex)
$ suffix (fg white <> text "- ") menu
|
91a1cc54c0fb68f3598bddff58bf9814aa49c73a27a370ad8dc68042f64c9a95 | tategakibunko/jingoo | jg_types.mli |
jg_types.mli
Copyright ( c ) 2011- by
License : see LICENSE
jg_types.mli
Copyright (c) 2011- by Masaki WATANABE
License: see LICENSE
*)
exception SyntaxError of string
type environment = {
autoescape : bool;
(** If true, template variables are auto escaped when output. *)
strict_mode : bool;
* If true , strict type cheking is enabled .
If false , some kind of invalid type usages are just ignored .
for example , following expression throws exception if [ strict_mode = true ] ,
but is skipped if [ strict_mode = false ] .
{ [
{ # 3(Tint ) is not iterable # }
{ % for item in 3 % }
{ { item } }
{ % endfor % }
] }
If false, some kind of invalid type usages are just ignored.
for example, following expression throws exception if [strict_mode = true],
but is skipped if [strict_mode = false].
{[
{# 3(Tint) is not iterable #}
{% for item in 3 %}
{{ item }}
{% endfor %}
]}
*)
template_dirs : string list;
(** Template search path list used by [{% include %}] statements.
Jingoo will always search in current directory in last resort.
*)
filters : (string * tvalue) list;
(** User-defined filters. *)
extensions : string list;
(** Path list of shared library modules ([.cms] or [.cmxs] files)
which are dynamically loaded.
*)
}
* See { ! : std_env }
and context = {
frame_stack : frame list;
macro_table : (string, macro) Hashtbl.t;
namespace_table : (string, (string, tvalue) Hashtbl.t) Hashtbl.t;
active_filters : string list;
serialize: bool;
output : tvalue -> unit;
}
and frame = (string -> tvalue)
and macro = Macro of macro_arg_names * macro_defaults * macro_code
and macro_arg_names = string list
and macro_defaults = kwargs
and macro_code = statement list
and tvalue =
Tnull
| Tint of int
| Tbool of bool
| Tfloat of float
| Tstr of string
| Tobj of (string * tvalue) list
| Thash of (string, tvalue) Hashtbl.t
| Tpat of (string -> tvalue)
| Tlist of tvalue list
| Tset of tvalue list
| Tfun of (?kwargs:kwargs -> tvalue -> tvalue)
| Tarray of tvalue array
| Tlazy of tvalue Lazy.t
| Tvolatile of (unit -> tvalue)
| Tsafe of string
and kwargs = (string * tvalue) list
(**/**)
and ast = statement list
[@@deriving show { with_path = false }]
and statement =
TextStatement of string
| ExpandStatement of expression
| IfStatement of branch list
| ForStatement of string list * expression * ast
| IncludeStatement of expression * with_context
| RawIncludeStatement of expression
| ExtendsStatement of string
| ImportStatement of string * string option
| FromImportStatement of string * (string * string option) list
| SetStatement of expression * expression
| SetBlockStatement of string * ast
| BlockStatement of string * ast
| MacroStatement of string * arguments * ast
| FilterStatement of string * ast
| CallStatement of string * arguments * (string option * expression) list * ast
| WithStatement of (string * expression) list * ast
| AutoEscapeStatement of expression * ast
| NamespaceStatement of string * (string * expression) list
| Statements of ast
| FunctionStatement of string * arguments * ast
| SwitchStatement of expression * (expression list * ast) list
and expression =
IdentExpr of string
| LiteralExpr of tvalue
| NotOpExpr of expression
| NegativeOpExpr of expression
| PlusOpExpr of expression * expression
| MinusOpExpr of expression * expression
| TimesOpExpr of expression * expression
| PowerOpExpr of expression * expression
| DivOpExpr of expression * expression
| ModOpExpr of expression * expression
| AndOpExpr of expression * expression
| OrOpExpr of expression * expression
| NotEqOpExpr of expression * expression
| EqEqOpExpr of expression * expression
| LtOpExpr of expression * expression
| GtOpExpr of expression * expression
| LtEqOpExpr of expression * expression
| GtEqOpExpr of expression * expression
| DotExpr of expression * string
| BracketExpr of expression * expression
| ApplyExpr of expression * (string option * expression) list
| ListExpr of expression list
| SetExpr of expression list
| ObjExpr of (string * expression) list
| TestOpExpr of expression * expression
| InOpExpr of expression * expression
| FunctionExpression of string list * expression
| TernaryOpExpr of expression * expression * expression
and with_context = bool
and branch = expression option * ast
and arguments = (string * expression option) list
(**/**)
* { [
let std_env = {
= true ;
strict_mode = false ;
template_dirs = [ ] ;
filters = [ ] ;
extensions = [ ] ;
}
] }
let std_env = {
autoescape = true;
strict_mode = false;
template_dirs = [];
filters = [];
extensions = [];
}
]}
*)
val std_env : environment
* { 2 Boxing OCaml values }
val box_int : int -> tvalue
val box_float : float -> tvalue
val box_string : string -> tvalue
val box_bool : bool -> tvalue
val box_list : tvalue list -> tvalue
val box_set : tvalue list -> tvalue
val box_obj : (string * tvalue) list -> tvalue
val box_hash : (string, tvalue) Hashtbl.t -> tvalue
val box_array : tvalue array -> tvalue
val box_pat : (string -> tvalue) -> tvalue
val box_lazy : tvalue Lazy.t -> tvalue
val box_fun : (?kwargs:kwargs -> tvalue -> tvalue) -> tvalue
(** {2 Unboxing OCaml values}
Unboxing operations raise [Invalid_argument] in case of type error.
*)
val unbox_int : tvalue -> int
val unbox_float : tvalue -> float
val unbox_string : tvalue -> string
val unbox_bool : tvalue -> bool
val unbox_list : tvalue -> tvalue list
val unbox_set : tvalue -> tvalue list
val unbox_array : tvalue -> tvalue array
val unbox_obj : tvalue -> (string * tvalue) list
val unbox_hash : tvalue -> (string, tvalue) Hashtbl.t
val unbox_pat : tvalue -> (string -> tvalue)
val unbox_lazy : tvalue -> tvalue Lazy.t
val unbox_fun : tvalue -> (?kwargs:kwargs -> tvalue -> tvalue)
* { 2 Helpers for function writing }
val func : (?kwargs:kwargs -> tvalue list -> tvalue) -> int -> tvalue
val func_arg1 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue) -> tvalue
val func_arg2 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue -> tvalue) -> tvalue
val func_arg3 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue -> tvalue -> tvalue) -> tvalue
val func_no_kw : ?name:string -> (tvalue list -> tvalue) -> int -> tvalue
val func_arg1_no_kw : ?name:string -> (tvalue -> tvalue) -> tvalue
val func_arg2_no_kw : ?name:string -> (tvalue -> tvalue -> tvalue) -> tvalue
val func_arg3_no_kw : ?name:string -> (tvalue -> tvalue -> tvalue -> tvalue) -> tvalue
* { 2 : notes - tvalue Notes about some data types }
{ ! type - tvalue . Tobj }
Key / value object using an associative list .
{ ! type - tvalue . }
Key / value objects using a hash table .
{ ! type - tvalue . Tpat }
Key / value object using a function to map [ " key " ] to [ value ] .
Faster than { ! type - tvalue . Tobj } and { ! type - tvalue . } ,
but not iterable nor testable .
{ ! type - tvalue . Tset }
Tuples
{ ! type - tvalue . Tlazy }
Lazy values are actually computed only when needed .
Useful for recursive some data structure .
In the following example , your app would throw a stack overflow without lazyness .
{ [
let rec lazy_model n =
let prev = lazy_model ( n - 1 ) in
let next = lazy_model ( n + 1 ) in
let cur = Tint n in
( lazy ( Tobj [ ( " cur " , cur ) ; ( " prev " , prev ) ; ( " next " , next ) ] ) )
] }
{ ! type - tvalue . Tvolatile }
You can use volatile values for variables that can not be defined at model 's
definition time or if it is subject to changes over time on 's side
{!type-tvalue.Tobj}
Key/value object using an associative list.
{!type-tvalue.Thash}
Key/value objects using a hash table.
{!type-tvalue.Tpat}
Key/value object using a function to map ["key"] to [value].
Faster than {!type-tvalue.Tobj} and {!type-tvalue.Thash},
but not iterable nor testable.
{!type-tvalue.Tset}
Tuples
{!type-tvalue.Tlazy}
Lazy values are actually computed only when needed.
Useful for recursive some data structure.
In the following example, your app would throw a stack overflow without lazyness.
{[
let rec lazy_model n =
let prev = lazy_model (n - 1) in
let next = lazy_model (n + 1) in
let cur = Tint n in
Tlazy (lazy (Tobj [ ("cur", cur) ; ("prev", prev) ; ("next", next) ]) )
]}
{!type-tvalue.Tvolatile}
You can use volatile values for variables that can not be defined at model's
definition time or if it is subject to changes over time on ocaml's side
*)
*
{ 2 : function - calls Function calls }
Built - in functions ( aka filters ) expect the { b TARGET } value to be the { b LAST } argument , in
order to be usable with the pipe notation . You are encouraged to do the same while defining your
own functions .
[ { { x | foo ( 10,20 ) } } ] is equivalent too [ { { foo ( 10,20,x ) } } ] .
Functions support partial application . e.g. [ { { list | map ( foo ( 10,20 ) ) } } ]
There is two kind of arguments : { { : # type - args } unnamed arguments } and { { : # type - kwargs } keyword arguments } .
When defining a { b keyword argument } , { b label ca n't be omitted } .
You { b ca n't } use [ slice(4 , [ 1,2,3,4,5 ] , 0 ) ] , because you need to explicitly bind [ 0 ] with the [ fill_with ] label .
A correct usage of the [ slice ] function would be [ slice(4 , [ 1,2,3,4,5 ] , fill_with=0 ) ] .
Note that kwargs may be defined at any place : [ slice(4 , fill_with=0 , [ 1,2,3,4,5 ] ) ] .
{2:function-calls Function calls}
Built-in functions (aka filters) expect the {b TARGET} value to be the {b LAST} argument, in
order to be usable with the pipe notation. You are encouraged to do the same while defining your
own functions.
[{{ x | foo (10,20) }}] is equivalent too [{{ foo (10,20,x) }}].
Functions support partial application. e.g. [{{ list | map (foo (10,20)) }}]
There is two kind of arguments: {{:#type-args} unnamed arguments} and {{:#type-kwargs} keyword arguments}.
When defining a {b keyword argument}, {b label can't be omitted}.
You {b can't} use [slice(4, [1,2,3,4,5], 0)], because you need to explicitly bind [0] with the [fill_with] label.
A correct usage of the [slice] function would be [slice(4, [1,2,3,4,5], fill_with=0)].
Note that kwargs may be defined at any place: [slice(4, fill_with=0, [1,2,3,4,5])].
*)
(**/**)
(** Function exported for internal usage but not documented *)
val type_string_of_tvalue : tvalue -> string
val failwith_type_error : string -> (string * tvalue) list -> 'a
val failwith_type_error_1 : string -> tvalue -> 'a
val failwith_type_error_2 : string -> tvalue -> tvalue -> 'a
val failwith_type_error_3 : string -> tvalue -> tvalue -> tvalue -> 'a
val merge_kwargs : kwargs option -> kwargs option -> kwargs option
val func_failure : ?name:string -> ?kwargs:kwargs -> tvalue list -> 'a
| null | https://raw.githubusercontent.com/tategakibunko/jingoo/1ed8f036c8f37294f282fe147f767bbd11a5386d/src/jg_types.mli | ocaml | * If true, template variables are auto escaped when output.
* Template search path list used by [{% include %}] statements.
Jingoo will always search in current directory in last resort.
* User-defined filters.
* Path list of shared library modules ([.cms] or [.cmxs] files)
which are dynamically loaded.
*/*
*/*
* {2 Unboxing OCaml values}
Unboxing operations raise [Invalid_argument] in case of type error.
*/*
* Function exported for internal usage but not documented |
jg_types.mli
Copyright ( c ) 2011- by
License : see LICENSE
jg_types.mli
Copyright (c) 2011- by Masaki WATANABE
License: see LICENSE
*)
exception SyntaxError of string
type environment = {
autoescape : bool;
strict_mode : bool;
* If true , strict type cheking is enabled .
If false , some kind of invalid type usages are just ignored .
for example , following expression throws exception if [ strict_mode = true ] ,
but is skipped if [ strict_mode = false ] .
{ [
{ # 3(Tint ) is not iterable # }
{ % for item in 3 % }
{ { item } }
{ % endfor % }
] }
If false, some kind of invalid type usages are just ignored.
for example, following expression throws exception if [strict_mode = true],
but is skipped if [strict_mode = false].
{[
{# 3(Tint) is not iterable #}
{% for item in 3 %}
{{ item }}
{% endfor %}
]}
*)
template_dirs : string list;
filters : (string * tvalue) list;
extensions : string list;
}
* See { ! : std_env }
and context = {
frame_stack : frame list;
macro_table : (string, macro) Hashtbl.t;
namespace_table : (string, (string, tvalue) Hashtbl.t) Hashtbl.t;
active_filters : string list;
serialize: bool;
output : tvalue -> unit;
}
and frame = (string -> tvalue)
and macro = Macro of macro_arg_names * macro_defaults * macro_code
and macro_arg_names = string list
and macro_defaults = kwargs
and macro_code = statement list
and tvalue =
Tnull
| Tint of int
| Tbool of bool
| Tfloat of float
| Tstr of string
| Tobj of (string * tvalue) list
| Thash of (string, tvalue) Hashtbl.t
| Tpat of (string -> tvalue)
| Tlist of tvalue list
| Tset of tvalue list
| Tfun of (?kwargs:kwargs -> tvalue -> tvalue)
| Tarray of tvalue array
| Tlazy of tvalue Lazy.t
| Tvolatile of (unit -> tvalue)
| Tsafe of string
and kwargs = (string * tvalue) list
and ast = statement list
[@@deriving show { with_path = false }]
and statement =
TextStatement of string
| ExpandStatement of expression
| IfStatement of branch list
| ForStatement of string list * expression * ast
| IncludeStatement of expression * with_context
| RawIncludeStatement of expression
| ExtendsStatement of string
| ImportStatement of string * string option
| FromImportStatement of string * (string * string option) list
| SetStatement of expression * expression
| SetBlockStatement of string * ast
| BlockStatement of string * ast
| MacroStatement of string * arguments * ast
| FilterStatement of string * ast
| CallStatement of string * arguments * (string option * expression) list * ast
| WithStatement of (string * expression) list * ast
| AutoEscapeStatement of expression * ast
| NamespaceStatement of string * (string * expression) list
| Statements of ast
| FunctionStatement of string * arguments * ast
| SwitchStatement of expression * (expression list * ast) list
and expression =
IdentExpr of string
| LiteralExpr of tvalue
| NotOpExpr of expression
| NegativeOpExpr of expression
| PlusOpExpr of expression * expression
| MinusOpExpr of expression * expression
| TimesOpExpr of expression * expression
| PowerOpExpr of expression * expression
| DivOpExpr of expression * expression
| ModOpExpr of expression * expression
| AndOpExpr of expression * expression
| OrOpExpr of expression * expression
| NotEqOpExpr of expression * expression
| EqEqOpExpr of expression * expression
| LtOpExpr of expression * expression
| GtOpExpr of expression * expression
| LtEqOpExpr of expression * expression
| GtEqOpExpr of expression * expression
| DotExpr of expression * string
| BracketExpr of expression * expression
| ApplyExpr of expression * (string option * expression) list
| ListExpr of expression list
| SetExpr of expression list
| ObjExpr of (string * expression) list
| TestOpExpr of expression * expression
| InOpExpr of expression * expression
| FunctionExpression of string list * expression
| TernaryOpExpr of expression * expression * expression
and with_context = bool
and branch = expression option * ast
and arguments = (string * expression option) list
* { [
let std_env = {
= true ;
strict_mode = false ;
template_dirs = [ ] ;
filters = [ ] ;
extensions = [ ] ;
}
] }
let std_env = {
autoescape = true;
strict_mode = false;
template_dirs = [];
filters = [];
extensions = [];
}
]}
*)
val std_env : environment
* { 2 Boxing OCaml values }
val box_int : int -> tvalue
val box_float : float -> tvalue
val box_string : string -> tvalue
val box_bool : bool -> tvalue
val box_list : tvalue list -> tvalue
val box_set : tvalue list -> tvalue
val box_obj : (string * tvalue) list -> tvalue
val box_hash : (string, tvalue) Hashtbl.t -> tvalue
val box_array : tvalue array -> tvalue
val box_pat : (string -> tvalue) -> tvalue
val box_lazy : tvalue Lazy.t -> tvalue
val box_fun : (?kwargs:kwargs -> tvalue -> tvalue) -> tvalue
val unbox_int : tvalue -> int
val unbox_float : tvalue -> float
val unbox_string : tvalue -> string
val unbox_bool : tvalue -> bool
val unbox_list : tvalue -> tvalue list
val unbox_set : tvalue -> tvalue list
val unbox_array : tvalue -> tvalue array
val unbox_obj : tvalue -> (string * tvalue) list
val unbox_hash : tvalue -> (string, tvalue) Hashtbl.t
val unbox_pat : tvalue -> (string -> tvalue)
val unbox_lazy : tvalue -> tvalue Lazy.t
val unbox_fun : tvalue -> (?kwargs:kwargs -> tvalue -> tvalue)
* { 2 Helpers for function writing }
val func : (?kwargs:kwargs -> tvalue list -> tvalue) -> int -> tvalue
val func_arg1 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue) -> tvalue
val func_arg2 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue -> tvalue) -> tvalue
val func_arg3 : ?name:string -> (?kwargs:kwargs -> tvalue -> tvalue -> tvalue -> tvalue) -> tvalue
val func_no_kw : ?name:string -> (tvalue list -> tvalue) -> int -> tvalue
val func_arg1_no_kw : ?name:string -> (tvalue -> tvalue) -> tvalue
val func_arg2_no_kw : ?name:string -> (tvalue -> tvalue -> tvalue) -> tvalue
val func_arg3_no_kw : ?name:string -> (tvalue -> tvalue -> tvalue -> tvalue) -> tvalue
* { 2 : notes - tvalue Notes about some data types }
{ ! type - tvalue . Tobj }
Key / value object using an associative list .
{ ! type - tvalue . }
Key / value objects using a hash table .
{ ! type - tvalue . Tpat }
Key / value object using a function to map [ " key " ] to [ value ] .
Faster than { ! type - tvalue . Tobj } and { ! type - tvalue . } ,
but not iterable nor testable .
{ ! type - tvalue . Tset }
Tuples
{ ! type - tvalue . Tlazy }
Lazy values are actually computed only when needed .
Useful for recursive some data structure .
In the following example , your app would throw a stack overflow without lazyness .
{ [
let rec lazy_model n =
let prev = lazy_model ( n - 1 ) in
let next = lazy_model ( n + 1 ) in
let cur = Tint n in
( lazy ( Tobj [ ( " cur " , cur ) ; ( " prev " , prev ) ; ( " next " , next ) ] ) )
] }
{ ! type - tvalue . Tvolatile }
You can use volatile values for variables that can not be defined at model 's
definition time or if it is subject to changes over time on 's side
{!type-tvalue.Tobj}
Key/value object using an associative list.
{!type-tvalue.Thash}
Key/value objects using a hash table.
{!type-tvalue.Tpat}
Key/value object using a function to map ["key"] to [value].
Faster than {!type-tvalue.Tobj} and {!type-tvalue.Thash},
but not iterable nor testable.
{!type-tvalue.Tset}
Tuples
{!type-tvalue.Tlazy}
Lazy values are actually computed only when needed.
Useful for recursive some data structure.
In the following example, your app would throw a stack overflow without lazyness.
{[
let rec lazy_model n =
let prev = lazy_model (n - 1) in
let next = lazy_model (n + 1) in
let cur = Tint n in
Tlazy (lazy (Tobj [ ("cur", cur) ; ("prev", prev) ; ("next", next) ]) )
]}
{!type-tvalue.Tvolatile}
You can use volatile values for variables that can not be defined at model's
definition time or if it is subject to changes over time on ocaml's side
*)
*
{ 2 : function - calls Function calls }
Built - in functions ( aka filters ) expect the { b TARGET } value to be the { b LAST } argument , in
order to be usable with the pipe notation . You are encouraged to do the same while defining your
own functions .
[ { { x | foo ( 10,20 ) } } ] is equivalent too [ { { foo ( 10,20,x ) } } ] .
Functions support partial application . e.g. [ { { list | map ( foo ( 10,20 ) ) } } ]
There is two kind of arguments : { { : # type - args } unnamed arguments } and { { : # type - kwargs } keyword arguments } .
When defining a { b keyword argument } , { b label ca n't be omitted } .
You { b ca n't } use [ slice(4 , [ 1,2,3,4,5 ] , 0 ) ] , because you need to explicitly bind [ 0 ] with the [ fill_with ] label .
A correct usage of the [ slice ] function would be [ slice(4 , [ 1,2,3,4,5 ] , fill_with=0 ) ] .
Note that kwargs may be defined at any place : [ slice(4 , fill_with=0 , [ 1,2,3,4,5 ] ) ] .
{2:function-calls Function calls}
Built-in functions (aka filters) expect the {b TARGET} value to be the {b LAST} argument, in
order to be usable with the pipe notation. You are encouraged to do the same while defining your
own functions.
[{{ x | foo (10,20) }}] is equivalent too [{{ foo (10,20,x) }}].
Functions support partial application. e.g. [{{ list | map (foo (10,20)) }}]
There is two kind of arguments: {{:#type-args} unnamed arguments} and {{:#type-kwargs} keyword arguments}.
When defining a {b keyword argument}, {b label can't be omitted}.
You {b can't} use [slice(4, [1,2,3,4,5], 0)], because you need to explicitly bind [0] with the [fill_with] label.
A correct usage of the [slice] function would be [slice(4, [1,2,3,4,5], fill_with=0)].
Note that kwargs may be defined at any place: [slice(4, fill_with=0, [1,2,3,4,5])].
*)
val type_string_of_tvalue : tvalue -> string
val failwith_type_error : string -> (string * tvalue) list -> 'a
val failwith_type_error_1 : string -> tvalue -> 'a
val failwith_type_error_2 : string -> tvalue -> tvalue -> 'a
val failwith_type_error_3 : string -> tvalue -> tvalue -> tvalue -> 'a
val merge_kwargs : kwargs option -> kwargs option -> kwargs option
val func_failure : ?name:string -> ?kwargs:kwargs -> tvalue list -> 'a
|
9b0ada2b467c920f65028ddf298d7cc18e1a45c6ddbc1860ef5fecd9a5948ec7 | synduce/Synduce | nested_min_sum_max_mts.ml | * @synduce --no - lifting -NB -n 30
type list =
| Elt of int
| Cons of int * list
type nested_list =
| Line of list
| NCons of list * nested_list
type cnlist =
| Sglt of list
| Cat of cnlist * cnlist
let rec clist_to_list = function
| Sglt a -> Line a
| Cat (x, y) -> dec y x
and dec l1 = function
| Sglt a -> NCons (a, clist_to_list l1)
| Cat (x, y) -> dec (Cat (y, l1)) x
;;
let rec spec = function
| Line a -> bmts a
| NCons (hd, tl) ->
let hi, lo = spec tl in
let line_lo, line_hi = bmts hd in
min line_lo lo, max line_hi hi
and bmts = function
| Elt x -> x, max x 0
| Cons (hd, tl) ->
let asum, amts = bmts tl in
asum + hd, max (amts + hd) 0
;;
let rec target = function
| Sglt x -> inner x
| Cat (l, r) -> [%synt s1] (target r) (target l)
and inner = function
| Elt x -> [%synt inner0] x
| Cons (hd, tl) -> [%synt inner1] hd (inner tl)
;;
assert (target = clist_to_list @@ spec)
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/unrealizable/nested_min_sum_max_mts.ml | ocaml | * @synduce --no - lifting -NB -n 30
type list =
| Elt of int
| Cons of int * list
type nested_list =
| Line of list
| NCons of list * nested_list
type cnlist =
| Sglt of list
| Cat of cnlist * cnlist
let rec clist_to_list = function
| Sglt a -> Line a
| Cat (x, y) -> dec y x
and dec l1 = function
| Sglt a -> NCons (a, clist_to_list l1)
| Cat (x, y) -> dec (Cat (y, l1)) x
;;
let rec spec = function
| Line a -> bmts a
| NCons (hd, tl) ->
let hi, lo = spec tl in
let line_lo, line_hi = bmts hd in
min line_lo lo, max line_hi hi
and bmts = function
| Elt x -> x, max x 0
| Cons (hd, tl) ->
let asum, amts = bmts tl in
asum + hd, max (amts + hd) 0
;;
let rec target = function
| Sglt x -> inner x
| Cat (l, r) -> [%synt s1] (target r) (target l)
and inner = function
| Elt x -> [%synt inner0] x
| Cons (hd, tl) -> [%synt inner1] hd (inner tl)
;;
assert (target = clist_to_list @@ spec)
| |
138afc4376d26f8136e12d3f36ca63c365aa3da3c5c335646dfa0195efc5cd0b | samee/netlist | Queue.hs | module Circuit.Queue
( Queue
, Circuit.Queue.empty
, fromList
, capLength
, front
, Circuit.Queue.null
, condPush, condPop) where
import Control.Monad
import Util
import Circuit.NetList
We can simply use gblIsNothing bits and avoid headPtr and tailPtr ops TODO
data Queue a = Queue { buffer :: [NetMaybe a]
, headPtr :: NetUInt
, tailPtr :: NetUInt
, parent :: Maybe (Queue (a,a))
, headAdjusted :: Bool -- pop-side
, tailAdjusted :: Bool -- push-side
, maxLength :: Int
}
-- Internal configs
By the way things are set up , pop only chooses from the first 5 buffer slots
push only writes into one of the last 3
ptrWidth = 3
buffSize = 6
bufferHead q = take 3 $ buffer q
bufferTail q = drop 3 $ buffer q
empty = Queue { buffer = replicate buffSize netNoth
, headPtr = constIntW ptrWidth 3
, tailPtr = constIntW ptrWidth 3
, parent = Nothing
, headAdjusted = True
, tailAdjusted = True
, maxLength = maxBound
}
fromList :: [g] -> Queue g
fromList [] = empty
fromList [x] = empty { buffer = [netNoth,netNoth,netNoth
,netJust x,netNoth,netNoth]
, tailPtr = constIntW ptrWidth 4
, tailAdjusted = False
}
fromList (x1:x2:l)
| even $ length l = (twoItems x1 x2) { parent = parentList l }
| otherwise = (threeItems x1 x2 (last l)) { parent = parentList $ init l }
where
twoItems x1 x2 = empty { buffer = [netNoth,netJust x1,netJust x2
,netNoth,netNoth,netNoth]
, headPtr = constIntW ptrWidth 1
}
threeItems x1 x2 x3 = empty { buffer = [netNoth,netJust x1,netJust x2
,netJust x3,netNoth,netNoth]
, headPtr = constIntW ptrWidth 1
, tailPtr = constIntW ptrWidth 4
, tailAdjusted = False
}
parentList [] = Nothing
parentList l = Just $ fromList $ pairUp l
front q = muxList (headPtr q) $ take 5 $ buffer q
-- Apparently I do not need to check parent
null q = equal (headPtr q) (tailPtr q)
Internal use unambiguous aliases
gqnull = Circuit.Queue.null
gqempty = Circuit.Queue.empty
parentLength len = (len-2) `div` 2
capLength :: Int -> Queue a -> Queue a
capLength len q = q { maxLength = len
, parent = cappedParent
}
where
cappedParent = case parent q of
Nothing -> Nothing
Just p -> Just $ capLength (parentLength len) p
-- If this changes significantly, fromList may also have to change
condPush :: Swappable a => NetBool -> a -> Queue a -> NetWriter (Queue a)
condPush c v q = do
dec <- hackeyDecoder c $ tailPtr q
newtail <- forM (zip dec $ bufferTail q) $ \(write,oldv) ->
mux write oldv (netJust v)
tptr <- condAdd c (tailPtr q) (constInt 1)
adjustTail $ q { buffer = bufferHead q++newtail
, tailPtr = tptr }
-- Internal use by condPush
case i of 00 - > [ 0,1,0 ] ; 01 - > [ 0,0,1 ] ; 11 - > [ 1,0,0 ]
hackeyDecoder en i = do
(i0,i') <- splitLsb =<< bitify i
i1 <- lsb i'
(ab,c) <- decoderUnit en i1
(a,b) <- decoderUnit ab i0
return [c,a,b]
condPop :: Swappable a => NetBool -> Queue a -> NetWriter (Queue a)
condPop c q = do
c <- netAnd c =<< netNot =<< gqnull q
dec <- decoderEn c $ headPtr q
newbuff <- liftM (++[last $ buffer q]) $ forM (zip dec $ init $ buffer q)
$ \(erase,oldv) -> condZap erase oldv
newhead <- condAdd c (headPtr q) (constInt 1)
adjustHead >=> resetIfEmpty $ q { buffer = newbuff
, headPtr = newhead
}
resetIfEmpty q = do
eq <- equal (headPtr q) (tailPtr q)
pnull <- parentNull q
emp <- netAnd pnull eq
tptr <- mux emp (tailPtr q) (constInt 3)
hptr <- mux emp (headPtr q) (constInt 3)
return $ q { headPtr = hptr, tailPtr = tptr }
Internal use
parentNull q = case parent q of
Nothing -> return netTrue
Just par -> gqnull par
adjustTail q | tailAdjusted q = return $ q { tailAdjusted = False }
| knownNothing (buff!!4) = return $ q { tailAdjusted = True }
| knownNothing (buff!!3) = error "Queue tail problem"
| otherwise = do
let parentPayload = (assumeJust 3, assumeJust 4)
tailSlide <- greaterThan (tailPtr q) (constInt 4)
tptr <- condSub tailSlide (tailPtr q) (constInt 2)
pnull <- parentNull q
headFull <- greaterThan (constInt 2) (headPtr q)
slideToParent <- netAnd tailSlide
=<< netOr headFull =<< netNot pnull
slideToHead <- netXor slideToParent tailSlide
newhead <- zipMux slideToHead (bufferHead q)
(take 3 $ drop 2 buff)
hptr <- condSub slideToHead (headPtr q) (constInt 2)
newtail <- mux tailSlide (head$bufferTail q) (last buff)
>>= return.(:[netNoth,netNoth])
newPar <- if maxlen <= 3 then return Nothing
else liftM Just $ condPush slideToParent
parentPayload oldparent
return $ q { buffer = newhead++newtail
, headPtr = hptr
, tailPtr = tptr
, parent = newPar
, tailAdjusted = True
}
where
oldparent = case parent q of
Nothing -> capLength (parentLength maxlen) empty
Just p -> p
buff = buffer q
maxlen = maxLength q
assumeJust i = netFromJust (buff!!i)
adjustHead :: Swappable g => Queue g -> NetWriter (Queue g)
adjustHead q | headAdjusted q = return $ q { headAdjusted = False }
| otherwise = do
headSlide <- greaterThan (headPtr q) (constInt 1)
(parentPayload,newPar) <- slideFromParent headSlide
noPayload <- netIsNothing (head parentPayload)
tailFull <- greaterThan (tailPtr q) (constInt 4)
slideFromTail <- netAnd tailFull =<< netXor headSlide noPayload
finalPayload <- zipMux noPayload parentPayload tailPayload
tailNotStuck <- netAnd headSlide tailFull
slideSuccess <- netOr tailNotStuck =<< netNot noPayload
tailUsed <- netAnd tailNotStuck noPayload
hptr <- condSub slideSuccess (headPtr q) (constInt 2)
tptr <- condSub tailUsed (tailPtr q) (constInt 2)
newHead <- zipMux slideSuccess (bufferHead q)
((buffer q!!2):finalPayload)
newTail <- zipMux tailUsed (bufferTail q)
((buffer q!!5):[netNoth,netNoth])
return $ q { buffer = newHead++newTail
, headPtr = hptr
, tailPtr = tptr
, parent = newPar
, headAdjusted = True
}
where
nothpair = [netNoth,netNoth] -- well, list actually
tailPayload = take 2 $ bufferTail q
slideFromParent headSlide = case parent q of
Nothing -> return (nothpair,Nothing)
Just par -> do mb <- front par
par' <- condPop headSlide par
payload <- mux headSlide netNoth mb
mbpl <- distrJust payload
return (mbpl,Just par')
distrJust mbp | knownNothing mbp = return nothpair
| otherwise = do p <- netIsNothing mbp
let (a,b) = netFromJust mbp
mapM (condZap p.netJust) [a,b]
head _ _ _ X _ _ tail
over first 5 ,
over last 3
A ' slide ' is simply a left shift by 2 places
pushAdjust : : = Make sure the next two push operations work , and so does
however many pops left before popAdjust
if tailPtr > 4 then , tailSlide = True , tailPtr-=2
-- Check where the outgoing elements should go : head or parent
if parent is not null then slideToParent
else if headPtr < 2 then slideToParent
else slideToHead
reset ptrs if size = = 0
popAdjust : : = Make sure the next two pop operations work , making room for
the 1 or two pushes left
if headPtr > 1 then headSlide = True
-- Check where the incoming elements are coming from : tail or parent
if parent is not null then slideFromParent , headPtr -= 2
-- Two different tailPtr conditions . Why ? TODO
else if tailPtr > 4 then slideFromTail , headPtr -= 2
-- else if size = = 1 then slideFromTail , headPtr -= 2 -- Re check TODO
else do nothing , even if headSlide is True
reset ptrs if size = = 0
head ___X__ tail
Pop muxes over first 5,
Push muxes over last 3
A 'slide' is simply a left shift by 2 places
pushAdjust ::= Make sure the next two push operations work, and so does
however many pops left before popAdjust
if tailPtr > 4 then, tailSlide = True, tailPtr-=2
-- Check where the outgoing elements should go: head or parent
if parent is not null then slideToParent
else if headPtr < 2 then slideToParent
else slideToHead
reset ptrs if size == 0
popAdjust ::= Make sure the next two pop operations work, making room for
the 1 or two pushes left
if headPtr > 1 then headSlide = True
-- Check where the incoming elements are coming from: tail or parent
if parent is not null then slideFromParent, headPtr -= 2
-- Two different tailPtr conditions. Why? TODO
else if tailPtr > 4 then slideFromTail, headPtr -= 2
-- else if size == 1 then slideFromTail, headPtr -= 2 -- Re check TODO
else do nothing, even if headSlide is True
reset ptrs if size == 0
-}
| null | https://raw.githubusercontent.com/samee/netlist/9fc20829f29724dc1148e54bd64fefd7e70af5ba/Circuit/Queue.hs | haskell | pop-side
push-side
Internal configs
Apparently I do not need to check parent
If this changes significantly, fromList may also have to change
Internal use by condPush
well, list actually
Check where the outgoing elements should go : head or parent
Check where the incoming elements are coming from : tail or parent
Two different tailPtr conditions . Why ? TODO
else if size = = 1 then slideFromTail , headPtr -= 2 -- Re check TODO
Check where the outgoing elements should go: head or parent
Check where the incoming elements are coming from: tail or parent
Two different tailPtr conditions. Why? TODO
else if size == 1 then slideFromTail, headPtr -= 2 -- Re check TODO | module Circuit.Queue
( Queue
, Circuit.Queue.empty
, fromList
, capLength
, front
, Circuit.Queue.null
, condPush, condPop) where
import Control.Monad
import Util
import Circuit.NetList
We can simply use gblIsNothing bits and avoid headPtr and tailPtr ops TODO
data Queue a = Queue { buffer :: [NetMaybe a]
, headPtr :: NetUInt
, tailPtr :: NetUInt
, parent :: Maybe (Queue (a,a))
, maxLength :: Int
}
By the way things are set up , pop only chooses from the first 5 buffer slots
push only writes into one of the last 3
ptrWidth = 3
buffSize = 6
bufferHead q = take 3 $ buffer q
bufferTail q = drop 3 $ buffer q
empty = Queue { buffer = replicate buffSize netNoth
, headPtr = constIntW ptrWidth 3
, tailPtr = constIntW ptrWidth 3
, parent = Nothing
, headAdjusted = True
, tailAdjusted = True
, maxLength = maxBound
}
fromList :: [g] -> Queue g
fromList [] = empty
fromList [x] = empty { buffer = [netNoth,netNoth,netNoth
,netJust x,netNoth,netNoth]
, tailPtr = constIntW ptrWidth 4
, tailAdjusted = False
}
fromList (x1:x2:l)
| even $ length l = (twoItems x1 x2) { parent = parentList l }
| otherwise = (threeItems x1 x2 (last l)) { parent = parentList $ init l }
where
twoItems x1 x2 = empty { buffer = [netNoth,netJust x1,netJust x2
,netNoth,netNoth,netNoth]
, headPtr = constIntW ptrWidth 1
}
threeItems x1 x2 x3 = empty { buffer = [netNoth,netJust x1,netJust x2
,netJust x3,netNoth,netNoth]
, headPtr = constIntW ptrWidth 1
, tailPtr = constIntW ptrWidth 4
, tailAdjusted = False
}
parentList [] = Nothing
parentList l = Just $ fromList $ pairUp l
front q = muxList (headPtr q) $ take 5 $ buffer q
null q = equal (headPtr q) (tailPtr q)
Internal use unambiguous aliases
gqnull = Circuit.Queue.null
gqempty = Circuit.Queue.empty
parentLength len = (len-2) `div` 2
capLength :: Int -> Queue a -> Queue a
capLength len q = q { maxLength = len
, parent = cappedParent
}
where
cappedParent = case parent q of
Nothing -> Nothing
Just p -> Just $ capLength (parentLength len) p
condPush :: Swappable a => NetBool -> a -> Queue a -> NetWriter (Queue a)
condPush c v q = do
dec <- hackeyDecoder c $ tailPtr q
newtail <- forM (zip dec $ bufferTail q) $ \(write,oldv) ->
mux write oldv (netJust v)
tptr <- condAdd c (tailPtr q) (constInt 1)
adjustTail $ q { buffer = bufferHead q++newtail
, tailPtr = tptr }
case i of 00 - > [ 0,1,0 ] ; 01 - > [ 0,0,1 ] ; 11 - > [ 1,0,0 ]
hackeyDecoder en i = do
(i0,i') <- splitLsb =<< bitify i
i1 <- lsb i'
(ab,c) <- decoderUnit en i1
(a,b) <- decoderUnit ab i0
return [c,a,b]
condPop :: Swappable a => NetBool -> Queue a -> NetWriter (Queue a)
condPop c q = do
c <- netAnd c =<< netNot =<< gqnull q
dec <- decoderEn c $ headPtr q
newbuff <- liftM (++[last $ buffer q]) $ forM (zip dec $ init $ buffer q)
$ \(erase,oldv) -> condZap erase oldv
newhead <- condAdd c (headPtr q) (constInt 1)
adjustHead >=> resetIfEmpty $ q { buffer = newbuff
, headPtr = newhead
}
resetIfEmpty q = do
eq <- equal (headPtr q) (tailPtr q)
pnull <- parentNull q
emp <- netAnd pnull eq
tptr <- mux emp (tailPtr q) (constInt 3)
hptr <- mux emp (headPtr q) (constInt 3)
return $ q { headPtr = hptr, tailPtr = tptr }
Internal use
parentNull q = case parent q of
Nothing -> return netTrue
Just par -> gqnull par
adjustTail q | tailAdjusted q = return $ q { tailAdjusted = False }
| knownNothing (buff!!4) = return $ q { tailAdjusted = True }
| knownNothing (buff!!3) = error "Queue tail problem"
| otherwise = do
let parentPayload = (assumeJust 3, assumeJust 4)
tailSlide <- greaterThan (tailPtr q) (constInt 4)
tptr <- condSub tailSlide (tailPtr q) (constInt 2)
pnull <- parentNull q
headFull <- greaterThan (constInt 2) (headPtr q)
slideToParent <- netAnd tailSlide
=<< netOr headFull =<< netNot pnull
slideToHead <- netXor slideToParent tailSlide
newhead <- zipMux slideToHead (bufferHead q)
(take 3 $ drop 2 buff)
hptr <- condSub slideToHead (headPtr q) (constInt 2)
newtail <- mux tailSlide (head$bufferTail q) (last buff)
>>= return.(:[netNoth,netNoth])
newPar <- if maxlen <= 3 then return Nothing
else liftM Just $ condPush slideToParent
parentPayload oldparent
return $ q { buffer = newhead++newtail
, headPtr = hptr
, tailPtr = tptr
, parent = newPar
, tailAdjusted = True
}
where
oldparent = case parent q of
Nothing -> capLength (parentLength maxlen) empty
Just p -> p
buff = buffer q
maxlen = maxLength q
assumeJust i = netFromJust (buff!!i)
adjustHead :: Swappable g => Queue g -> NetWriter (Queue g)
adjustHead q | headAdjusted q = return $ q { headAdjusted = False }
| otherwise = do
headSlide <- greaterThan (headPtr q) (constInt 1)
(parentPayload,newPar) <- slideFromParent headSlide
noPayload <- netIsNothing (head parentPayload)
tailFull <- greaterThan (tailPtr q) (constInt 4)
slideFromTail <- netAnd tailFull =<< netXor headSlide noPayload
finalPayload <- zipMux noPayload parentPayload tailPayload
tailNotStuck <- netAnd headSlide tailFull
slideSuccess <- netOr tailNotStuck =<< netNot noPayload
tailUsed <- netAnd tailNotStuck noPayload
hptr <- condSub slideSuccess (headPtr q) (constInt 2)
tptr <- condSub tailUsed (tailPtr q) (constInt 2)
newHead <- zipMux slideSuccess (bufferHead q)
((buffer q!!2):finalPayload)
newTail <- zipMux tailUsed (bufferTail q)
((buffer q!!5):[netNoth,netNoth])
return $ q { buffer = newHead++newTail
, headPtr = hptr
, tailPtr = tptr
, parent = newPar
, headAdjusted = True
}
where
tailPayload = take 2 $ bufferTail q
slideFromParent headSlide = case parent q of
Nothing -> return (nothpair,Nothing)
Just par -> do mb <- front par
par' <- condPop headSlide par
payload <- mux headSlide netNoth mb
mbpl <- distrJust payload
return (mbpl,Just par')
distrJust mbp | knownNothing mbp = return nothpair
| otherwise = do p <- netIsNothing mbp
let (a,b) = netFromJust mbp
mapM (condZap p.netJust) [a,b]
head _ _ _ X _ _ tail
over first 5 ,
over last 3
A ' slide ' is simply a left shift by 2 places
pushAdjust : : = Make sure the next two push operations work , and so does
however many pops left before popAdjust
if tailPtr > 4 then , tailSlide = True , tailPtr-=2
if parent is not null then slideToParent
else if headPtr < 2 then slideToParent
else slideToHead
reset ptrs if size = = 0
popAdjust : : = Make sure the next two pop operations work , making room for
the 1 or two pushes left
if headPtr > 1 then headSlide = True
if parent is not null then slideFromParent , headPtr -= 2
else if tailPtr > 4 then slideFromTail , headPtr -= 2
else do nothing , even if headSlide is True
reset ptrs if size = = 0
head ___X__ tail
Pop muxes over first 5,
Push muxes over last 3
A 'slide' is simply a left shift by 2 places
pushAdjust ::= Make sure the next two push operations work, and so does
however many pops left before popAdjust
if tailPtr > 4 then, tailSlide = True, tailPtr-=2
if parent is not null then slideToParent
else if headPtr < 2 then slideToParent
else slideToHead
reset ptrs if size == 0
popAdjust ::= Make sure the next two pop operations work, making room for
the 1 or two pushes left
if headPtr > 1 then headSlide = True
if parent is not null then slideFromParent, headPtr -= 2
else if tailPtr > 4 then slideFromTail, headPtr -= 2
else do nothing, even if headSlide is True
reset ptrs if size == 0
-}
|
6ba27fbfecd0849d7485790e5e94f80544b06f1cbbbf3cfe84a5f4dade965c93 | NobbZ/rebar3_autotest | rebar3_autotest_prv.erl | -module(rebar3_autotest_prv).
-behaviour(provider).
-export([init/1, do/1, format_error/1]).
-define(DESCRIPTION, "A rebar3 plugin to run tests automatically when there are changes.").
-define(PROVIDER, autotest).
-define(DEPS, [app_discovery]).
-define(OPTS, []).
-define(INCLUDE_FILE_PATTERNS, [
"\\A.+\\.erl\\z",
"\\A.+\\.hrl\\z",
"\\A.+\\.app\\.src\\z",
"\\A.+\\.app\\z",
"\\A.+\\.ex\\z",
"\\A.+\\.exs\\z",
"\\A.+\\.yaws\\z",
"\\A.+\\.xrl\\z"
]).
%% ===================================================================
%% Public API
%% ===================================================================
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{name, ?PROVIDER}, % The 'user friendly' name of the task
{module, ?MODULE}, % The module implementation of the task
{bare, true}, % The task can be run by the user, always true
{deps, ?DEPS}, % The list of dependencies
{example, "rebar3 autotest"}, % How to use the plugin
{opts, ?OPTS}, % list of options understood by the plugin
{short_desc, ?DESCRIPTION},
{desc, ?DESCRIPTION},
{profiles, [test]}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
State1 = remove_from_plugin_paths(State),
spawn_link(fun() ->
listen_on_project_apps(State1),
auto_first()
end),
rebar_prv_shell:do(State1). % pesky shell. Looks like rebar_agent can't currently start itself. :(
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
%% ===================================================================
%% Private stuff
%% ===================================================================
listen_on_project_apps(State) ->
ProjectApps = rebar_state:project_apps(State),
lists:foreach(fun(AppInfo) ->
SrcDir = filename:join(rebar_app_info:dir(AppInfo), "src"),
IncDir = filename:join(rebar_app_info:dir(AppInfo), "include"),
TstDir = filename:join(rebar_app_info:dir(AppInfo), "test"),
PrvDir = filename:join(rebar_app_info:dir(AppInfo), "priv"),
enotify:start_link(SrcDir),
enotify:start_link(IncDir),
enotify:start_link(TstDir),
enotify:start_link(PrvDir)
end, ProjectApps).
remove_from_plugin_paths(State) ->
PluginPaths = rebar_state:code_paths(State, all_plugin_deps),
PluginsMinusAutotest = lists:filter(fun(Path) ->
Name = filename:basename(Path, "/ebin"),
AtomName = list_to_atom(Name),
not ((rebar3_autotest =:= AtomName)
or (enotify =:= AtomName))
end, PluginPaths),
rebar_state:code_paths(State, all_plugin_deps, PluginsMinusAutotest).
substr(String, {Offset, Length}) ->
string:substr(String, Offset+1, Length).
eunit_output_to_notification_message(Output) ->
case re:run(Output, "^Finished in (\\d+\\.\\d+) seconds$", [global, multiline]) of
{match, TimeMatches} ->
Time = substr(Output, lists:last(lists:last(TimeMatches))),
{match, ResultMatches} = case re:run(Output, "\\d+ tests, \\d+ failures, \\d+ skips$", [global, multiline]) of
M = {match, _} -> M;
nomatch ->
re:run(Output, "\\d+ tests, \\d+ failures$", [global, multiline])
end,
Results = substr(Output, hd(lists:last(ResultMatches))),
io_lib:format("~s in ~s seconds", [Results, Time]);
nomatch ->
"Compilation error(s)"
end.
run_eunit() ->
Rebar3AbsPath = os:find_executable("rebar3"),
Port = open_port({spawn_executable, Rebar3AbsPath}, [
binary,
{line, 1024},
exit_status,
hide,
stderr_to_stdout,
{arg0, "rebar3"},
{args, ["eunit"]}
]),
{ExitCode, Output} = capture_eunit_output(Port, <<>>),
Icon = if
ExitCode =:= 0 -> "ok";
true -> "error"
end,
Msg = eunit_output_to_notification_message(Output),
notify(Icon, Msg).
capture_eunit_output(Port, Output) ->
receive
{Port, {data, {noeol, NewOutput}}} ->
file:write(standard_error, NewOutput),
capture_eunit_output(Port, <<Output/binary, NewOutput/binary>>);
{Port, {data, {eol, NewOutput}}} ->
file:write(standard_error, NewOutput),
io:format(standard_error, "~n", []),
capture_eunit_output(Port, <<Output/binary, NewOutput/binary, "\n">>);
{Port, {exit_status, Status}} ->
{Status, unicode:characters_to_list(Output)}
end.
-spec
should_check(Event) -> boolean() when
Event :: {AbsPathFile, Attributes},
AbsPathFile :: string(),
Attributes :: [atom()].
should_check({AbsPathFile, _Attributes}) ->
IncludeREs = lists:map(fun(S) -> {ok, MP} = re:compile(S), MP end, ?INCLUDE_FILE_PATTERNS),
FileName = filename:basename(AbsPathFile),
lists:any(fun(RE) -> re:run(FileName, RE) =/= nomatch end, IncludeREs).
auto_first() ->
case whereis(rebar_agent) of
undefined ->
timer:sleep(25),
auto_first();
_ ->
run_eunit(),
auto()
end.
auto() ->
receive
Event = {AbsPathFile, Attributes} when is_list(AbsPathFile) and is_list(Attributes) ->
case should_check(Event) of
true -> run_eunit();
_Else -> skip
end,
auto()
end.
notify(IconName, Message) ->
case os:find_executable("terminal-notifier") of
false ->
skipped;
Exe ->
PluginPrivDir = code:priv_dir(rebar3_autotest),
IconPath = filename:join([PluginPrivDir, "icons", IconName]) ++ ".icns",
Cmd = io_lib:format("'~s' '-title' 'EUnit' '-message' '~s' '-appIcon' '~s'", [Exe, Message, IconPath]),
os:cmd(Cmd),
ok
end.
| null | https://raw.githubusercontent.com/NobbZ/rebar3_autotest/fe1ee4444437e974c40d7be9ae1a99b7e2944a4c/src/rebar3_autotest_prv.erl | erlang | ===================================================================
Public API
===================================================================
The 'user friendly' name of the task
The module implementation of the task
The task can be run by the user, always true
The list of dependencies
How to use the plugin
list of options understood by the plugin
pesky shell. Looks like rebar_agent can't currently start itself. :(
===================================================================
Private stuff
=================================================================== | -module(rebar3_autotest_prv).
-behaviour(provider).
-export([init/1, do/1, format_error/1]).
-define(DESCRIPTION, "A rebar3 plugin to run tests automatically when there are changes.").
-define(PROVIDER, autotest).
-define(DEPS, [app_discovery]).
-define(OPTS, []).
-define(INCLUDE_FILE_PATTERNS, [
"\\A.+\\.erl\\z",
"\\A.+\\.hrl\\z",
"\\A.+\\.app\\.src\\z",
"\\A.+\\.app\\z",
"\\A.+\\.ex\\z",
"\\A.+\\.exs\\z",
"\\A.+\\.yaws\\z",
"\\A.+\\.xrl\\z"
]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{short_desc, ?DESCRIPTION},
{desc, ?DESCRIPTION},
{profiles, [test]}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
State1 = remove_from_plugin_paths(State),
spawn_link(fun() ->
listen_on_project_apps(State1),
auto_first()
end),
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
listen_on_project_apps(State) ->
ProjectApps = rebar_state:project_apps(State),
lists:foreach(fun(AppInfo) ->
SrcDir = filename:join(rebar_app_info:dir(AppInfo), "src"),
IncDir = filename:join(rebar_app_info:dir(AppInfo), "include"),
TstDir = filename:join(rebar_app_info:dir(AppInfo), "test"),
PrvDir = filename:join(rebar_app_info:dir(AppInfo), "priv"),
enotify:start_link(SrcDir),
enotify:start_link(IncDir),
enotify:start_link(TstDir),
enotify:start_link(PrvDir)
end, ProjectApps).
remove_from_plugin_paths(State) ->
PluginPaths = rebar_state:code_paths(State, all_plugin_deps),
PluginsMinusAutotest = lists:filter(fun(Path) ->
Name = filename:basename(Path, "/ebin"),
AtomName = list_to_atom(Name),
not ((rebar3_autotest =:= AtomName)
or (enotify =:= AtomName))
end, PluginPaths),
rebar_state:code_paths(State, all_plugin_deps, PluginsMinusAutotest).
substr(String, {Offset, Length}) ->
string:substr(String, Offset+1, Length).
eunit_output_to_notification_message(Output) ->
case re:run(Output, "^Finished in (\\d+\\.\\d+) seconds$", [global, multiline]) of
{match, TimeMatches} ->
Time = substr(Output, lists:last(lists:last(TimeMatches))),
{match, ResultMatches} = case re:run(Output, "\\d+ tests, \\d+ failures, \\d+ skips$", [global, multiline]) of
M = {match, _} -> M;
nomatch ->
re:run(Output, "\\d+ tests, \\d+ failures$", [global, multiline])
end,
Results = substr(Output, hd(lists:last(ResultMatches))),
io_lib:format("~s in ~s seconds", [Results, Time]);
nomatch ->
"Compilation error(s)"
end.
run_eunit() ->
Rebar3AbsPath = os:find_executable("rebar3"),
Port = open_port({spawn_executable, Rebar3AbsPath}, [
binary,
{line, 1024},
exit_status,
hide,
stderr_to_stdout,
{arg0, "rebar3"},
{args, ["eunit"]}
]),
{ExitCode, Output} = capture_eunit_output(Port, <<>>),
Icon = if
ExitCode =:= 0 -> "ok";
true -> "error"
end,
Msg = eunit_output_to_notification_message(Output),
notify(Icon, Msg).
capture_eunit_output(Port, Output) ->
receive
{Port, {data, {noeol, NewOutput}}} ->
file:write(standard_error, NewOutput),
capture_eunit_output(Port, <<Output/binary, NewOutput/binary>>);
{Port, {data, {eol, NewOutput}}} ->
file:write(standard_error, NewOutput),
io:format(standard_error, "~n", []),
capture_eunit_output(Port, <<Output/binary, NewOutput/binary, "\n">>);
{Port, {exit_status, Status}} ->
{Status, unicode:characters_to_list(Output)}
end.
-spec
should_check(Event) -> boolean() when
Event :: {AbsPathFile, Attributes},
AbsPathFile :: string(),
Attributes :: [atom()].
should_check({AbsPathFile, _Attributes}) ->
IncludeREs = lists:map(fun(S) -> {ok, MP} = re:compile(S), MP end, ?INCLUDE_FILE_PATTERNS),
FileName = filename:basename(AbsPathFile),
lists:any(fun(RE) -> re:run(FileName, RE) =/= nomatch end, IncludeREs).
auto_first() ->
case whereis(rebar_agent) of
undefined ->
timer:sleep(25),
auto_first();
_ ->
run_eunit(),
auto()
end.
auto() ->
receive
Event = {AbsPathFile, Attributes} when is_list(AbsPathFile) and is_list(Attributes) ->
case should_check(Event) of
true -> run_eunit();
_Else -> skip
end,
auto()
end.
notify(IconName, Message) ->
case os:find_executable("terminal-notifier") of
false ->
skipped;
Exe ->
PluginPrivDir = code:priv_dir(rebar3_autotest),
IconPath = filename:join([PluginPrivDir, "icons", IconName]) ++ ".icns",
Cmd = io_lib:format("'~s' '-title' 'EUnit' '-message' '~s' '-appIcon' '~s'", [Exe, Message, IconPath]),
os:cmd(Cmd),
ok
end.
|
2e0f36247a78c2c0fa9a5105ce89d5376f4db9644c828baef2746aef17fefde9 | PeterDWhite/Osker | SystemHalfMessage.hs | Copyright ( C ) , 2001 , 2002 , 2003
Copyright ( c ) OHSU , 2001 , 2002 , 2003
module SystemHalfMessage
Types of Osker messages in system half
) where
----------------------------------------------------------------------
The definitions that localize the message to the system
-- half instantiation of the executive.
----------------------------------------------------------------------
imports
import qualified SystemCall as SC
Osker imports
import qualified OskerMessage as OM
data SystemHalfMessageType
From the user half , via the trap handler .
= FromTrapHandlerType
Commands from the system half
| ToSystemHalfType
deriving (Eq, Ord, Enum, Show)
-- Convert the incoming payload to the system half to a message type.
systemHalfPayloadType :: OM.OskerPay -> SystemHalfMessageType
systemHalfPayloadType sp =
case sp of
OM.FromTrapHandler _sysreq -> FromTrapHandlerType
OM.ToSystemHalf _kcc -> ToSystemHalfType
_otherwise -> error ("systemHalfPayloadType: " ++ show sp)
Get the message type from the incoming message to the system half
systemHalfMessageType :: OM.OskerPay -> Int
systemHalfMessageType = fromEnum . systemHalfPayloadType
Get the activity index from the incoming message to the system half .
systemHalfMessageIndex :: OM.OskerPay -> Int
systemHalfMessageIndex sp =
case sp of
OM.FromTrapHandler sysreq -> SC.systemRequest2Int sysreq
OM.ToSystemHalf kcc -> OM.kernelCoreCommand2Int kcc
_otherwise ->
error ("systemHalfPayloadIndex: " ++ show sp)
Generate the call table index from the incoming message
to the system half .
getCallTableIndex :: CTI.ToCallTableIndex OM.OskerPay
getCallTableIndex sp =
CTI.CallTableIndex
(systemHalfMessageType sp) -- Message type
(systemHalfMessageIndex sp) -- Message index
| null | https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Kernel/SystemHalf/SystemHalfMessage.hs | haskell | --------------------------------------------------------------------
half instantiation of the executive.
--------------------------------------------------------------------
Convert the incoming payload to the system half to a message type.
Message type
Message index | Copyright ( C ) , 2001 , 2002 , 2003
Copyright ( c ) OHSU , 2001 , 2002 , 2003
module SystemHalfMessage
Types of Osker messages in system half
) where
The definitions that localize the message to the system
imports
import qualified SystemCall as SC
Osker imports
import qualified OskerMessage as OM
data SystemHalfMessageType
From the user half , via the trap handler .
= FromTrapHandlerType
Commands from the system half
| ToSystemHalfType
deriving (Eq, Ord, Enum, Show)
systemHalfPayloadType :: OM.OskerPay -> SystemHalfMessageType
systemHalfPayloadType sp =
case sp of
OM.FromTrapHandler _sysreq -> FromTrapHandlerType
OM.ToSystemHalf _kcc -> ToSystemHalfType
_otherwise -> error ("systemHalfPayloadType: " ++ show sp)
Get the message type from the incoming message to the system half
systemHalfMessageType :: OM.OskerPay -> Int
systemHalfMessageType = fromEnum . systemHalfPayloadType
Get the activity index from the incoming message to the system half .
systemHalfMessageIndex :: OM.OskerPay -> Int
systemHalfMessageIndex sp =
case sp of
OM.FromTrapHandler sysreq -> SC.systemRequest2Int sysreq
OM.ToSystemHalf kcc -> OM.kernelCoreCommand2Int kcc
_otherwise ->
error ("systemHalfPayloadIndex: " ++ show sp)
Generate the call table index from the incoming message
to the system half .
getCallTableIndex :: CTI.ToCallTableIndex OM.OskerPay
getCallTableIndex sp =
CTI.CallTableIndex
|
bd221cee2f9eeb123f06dcdf97bc0195218a09a4dada972e9006bb47b59d8b95 | yutopp/rill | codegen_llvm.ml |
* Copyright yutopp 2015 - .
*
* Distributed under the Boost Software License , Version 1.0 .
* ( See accompanying file LICENSE_1_0.txt or copy at
* )
* Copyright yutopp 2015 - .
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* )
*)
open Batteries
open Stdint
module FI = Codegen_flowinfo
module L = Llvm
module TAst = Tagged_ast
type env_t = TAst.t Env.env_t
type type_info_t = env_t Type.info_t
type ctfe_val_t = type_info_t Ctfe_value.t
type type_gen_t = env_t Type.Generator.t
type value_form_t = bool (* is_address or not *)
type builtin_func_params_t =
(type_info_t * value_form_t) list
type builtin_func_ret_t =
(type_info_t * value_form_t)
type 'ctx builtin_func_def_t =
builtin_func_params_t -> builtin_func_ret_t -> L.llvalue array -> 'ctx -> L.llvalue
type ('ty, 'ctx) builtin_template_func_def_t =
'ty Ctfe_value.t list ->
builtin_func_params_t -> builtin_func_ret_t -> L.llvalue array -> 'ctx -> L.llvalue
type ('ty, 'ctx) record_value_t =
| LLValue of (L.llvalue * value_form_t)
| LLType of L.lltype
| LLTypeGen of ('ty Ctfe_value.t list -> L.lltype)
| ElemIndex of int
| BuiltinFunc of 'ctx builtin_func_def_t
| BuiltinFuncGen of ('ty, 'ctx) builtin_template_func_def_t
| TrivialAction
type 'ty generated_value_t =
L.llvalue * 'ty * value_form_t * Codegen_flowinfo.t
module CodeGeneratorType =
struct
type ir_context_t = L.llcontext
type ir_builder_t = L.llbuilder
type ir_module_t = L.llmodule
type ir_value_t = L.llvalue
type ir_intrinsics = Codegen_llvm_intrinsics.t
type 'ty ir_cache_value_t = 'ty generated_value_t
type ('ty, 'ctx) value_t = ('ty, 'ctx) record_value_t
end
module Ctx = Codegen_context.Make(CodeGeneratorType)
type ctx_t = (env_t, Nodes.CachedNodeCounter.t, type_info_t, ctfe_val_t) Ctx.t
exception Meta_var_un_evaluatable of Unification.id_t
let agg_recever_name = "agg.receiver"
let initialize_llvm_backends =
let is_initialized = ref false in
let initialize () =
match !is_initialized with
| false ->
Llvm_X86.initialize ();
is_initialized := true
| true ->
()
in
initialize
let make_default_context ~type_sets ~uni_map ~target_module =
initialize_llvm_backends();
let ir_context = L.global_context () in
let ir_module = L.create_module ir_context "Rill" in
let ir_builder = L.builder ir_context in
let ir_intrinsics =
Codegen_llvm_intrinsics.declare_intrinsics ir_context ir_module
in
Ctx.init
~ir_context:ir_context
~ir_builder:ir_builder
~ir_module:ir_module
~ir_intrinsics:ir_intrinsics
~type_sets:type_sets
~uni_map:uni_map
~target_module:target_module
let llval_i1 v ctx =
let open Ctx in
L.const_int (L.i1_type ctx.ir_context) (if v then 1 else 0)
let llval_i32 v ctx =
let open Ctx in
L.const_int_of_string (L.i32_type ctx.ir_context) (Int32.to_string v) 10
let llval_u32 v ctx =
let open Ctx in
L.const_int_of_string (L.i32_type ctx.ir_context) (Uint32.to_string v) 10
let llval_string v ctx =
let open Ctx in
(* null terminated *)
L.const_stringz ctx.ir_context v
let do_debug_print_flag = not Config.is_release (*&& false*)
let debug_dump_value v =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_llvalue v)
let debug_dump_module m =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_llmodule m)
let debug_dump_type t =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_lltype t)
let debug_params_and_args param_tys_and_addrs args =
if not Config.is_release then
List.iter2 (fun (ty, is_addr) llval ->
Debug.printf "type: %s / is_addr: %b"
(Type.to_string ty)
is_addr;
debug_dump_value llval
) param_tys_and_addrs (Array.to_list args);
exception Discontinue_code_generation of FI.t
let discontinue_when_expr_terminated fi =
if FI.has_terminator fi then
raise (Discontinue_code_generation fi)
let rec generate_code ?(storage=None) node prev_fi ctx : 'ty generated_value_t =
let open Ctx in
let void_v = L.undef (L.void_type ctx.ir_context) in
let void_ty = ctx.type_sets.Type_sets.ts_void_type in
let void_val fi = (void_v, void_ty, false, fi) in
if FI.has_terminator prev_fi then void_val prev_fi else
match TAst.kind_of node with
| TAst.Module (inner, pkg_names, mod_name, base_dir, _) ->
generate_code inner prev_fi ctx
| TAst.StatementList (nodes) ->
let rec gen nx (v, t, p, fi) = match nx with
| [] -> (v, t, p, fi)
| x :: xs ->
let l =
try
generate_code x fi ctx
with
| Discontinue_code_generation nfi ->
void_val nfi
in
gen xs l
in
gen nodes (void_val prev_fi)
| TAst.ExprStmt e ->
generate_code e prev_fi ctx
| TAst.VoidExprStmt e ->
let (_, _, _, fi) = generate_code e prev_fi ctx in
void_val fi
| TAst.ReturnStmt (opt_e) ->
begin
Debug.printf "ReturnStmt!!!!!!!!";
let (llval, fi) = match opt_e with
| Some e ->
let (llval, ty, is_addr, fi) = generate_code e prev_fi ctx in
discontinue_when_expr_terminated fi;
if is_heavy_object ty || ty == void_ty then
(L.build_ret_void ctx.ir_builder, fi)
else
let llval = adjust_addr_val llval ty is_addr ctx in
(L.build_ret llval ctx.ir_builder, fi)
| None ->
(L.build_ret_void ctx.ir_builder, prev_fi)
in
(llval, void_ty, false, fi |> FI.set_has_terminator true)
end
| TAst.GenericFuncDef (opt_body, Some env) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let fenv_r = Env.FunctionOp.get_record env in
Debug.printf "<><><><> Define Function: %s (%s)"
(env.Env.mangled_name |> Option.get)
(Env_system.EnvId.to_string env.Env.env_id);
let declare_current_function name =
declare_function name env ctx
in
let define_current_function kind fn_spec =
define_function kind fn_spec opt_body env prev_fi ctx
in
match fenv_r.Env.fn_detail with
| Env.FnRecordNormal (def, kind, fenv_spec) ->
begin
define_current_function kind fenv_spec;
void_val prev_fi
end
| Env.FnRecordImplicit (def, kind, fenv_spec) ->
begin
match def with
(* implicit & trivial *)
| Env.FnDefDefaulted true ->
begin
assert(List.length fenv_spec.Env.fn_spec_param_envs = 0);
let r_value = match kind with
| Env.FnKindDefaultConstructor None
| Env.FnKindCopyConstructor None
| Env.FnKindMoveConstructor None
| Env.FnKindConstructor None -> TrivialAction
| _ -> failwith "[ICE]"
in
Ctx.bind_val_to_env ctx r_value env;
void_val prev_fi
end
(* implicit & non-trivial *)
| Env.FnDefDefaulted false ->
begin
define_current_function kind fenv_spec;
void_val prev_fi
end
| _ -> failwith "[ICE] define implicit function"
end
| Env.FnRecordExternal (def, kind, extern_fname) ->
begin
let f = declare_current_function extern_fname in
Ctx.bind_external_function ctx extern_fname f;
void_val prev_fi
end
| Env.FnRecordBuiltin (def, kind, name) ->
begin
(* DO NOTHING *)
void_val prev_fi
end
| _ -> failwith "[ICE]"
end
| TAst.ClassDefStmt (
name, _, body, opt_attr, Some env
) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let cenv_r = Env.ClassOp.get_record env in
let member_lltypes =
(* define member variables *)
let get_member_type index env =
Ctx.bind_val_to_env ctx (ElemIndex index) env;
let r = Env.VariableOp.get_record env in
let llty = lltype_of_typeinfo r.Env.var_type ctx in
llty
in
List.mapi get_member_type cenv_r.Env.cls_member_vars
in
let struct_ty =
L.named_struct_type ctx.Ctx.ir_context
(env.Env.mangled_name |> Option.get)
in
L.struct_set_body struct_ty (Array.of_list member_lltypes)
false (* not packed *);
Ctx.bind_val_to_env ctx (LLType struct_ty) env;
debug_dump_type struct_ty;
(* body *)
let _ = generate_code body prev_fi ctx in
void_val prev_fi
end
| TAst.ExternClassDefStmt (
name, _, extern_cname, _, _, Some env
) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let b_value = try Ctx.find_val_by_name ctx extern_cname with
| Not_found ->
failwith (Printf.sprintf "[ICE] builtin class \"%s\" is not found"
extern_cname)
in
let ty = match b_value with
| LLType ty -> ty
| LLTypeGen f ->
let cenv_r = Env.ClassOp.get_record env in
f cenv_r.Env.cls_template_vals
| _ -> failwith ""
in
Ctx.bind_val_to_env ctx (LLType ty) env;
void_val prev_fi
end
| TAst.VariableDefStmt (_, TAst.{kind = TAst.VarInit (var_init); _}, Some env) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
let venv = Env.VariableOp.get_record env in
let var_type = venv.Env.var_type in
let (_, _, (_, opt_init_expr)) = var_init in
let init_expr = Option.get opt_init_expr in
let (llval, expr_ty, is_addr, cg) = generate_code init_expr prev_fi ctx in
Debug.printf "<><><>\nDefine variable: %s / is_addr: %b\n<><><>\n"
(Id_string.to_string venv.Env.var_name)
is_addr;
Type.debug_print var_type;
let var_name = Id_string.to_string venv.Env.var_name in
L.set_value_name var_name llval;
Ctx.bind_val_to_env ctx (LLValue (llval, is_addr)) env;
Ctx.mark_env_as_defined ctx env;
void_val cg
end
| TAst.MemberVariableDefStmt _ -> void_val prev_fi
| TAst.EmptyStmt -> void_val prev_fi
| TAst.GenericCallExpr (storage_ref, args, Some caller_env, Some env) ->
begin
let f_er = Env.FunctionOp.get_record env in
let {
Env.fn_detail = detail;
Env.fn_param_kinds = param_kinds;
Env.fn_return_type = ret_ty;
} = f_er in
let analyze_func_and_eval_args kind =
let (param_tys, evaled_args) = normalize_params_and_args param_kinds args in
eval_args_for_func kind storage_ref param_tys ret_ty evaled_args
caller_env prev_fi ctx
in
let call_llfunc kind f =
let (_, llargs, _, returns_addr) = analyze_func_and_eval_args kind in
let returns_heavy_obj = is_heavy_object ret_ty in
match returns_heavy_obj with
| false ->
let llval = L.build_call f llargs "" ctx.ir_builder in
(llval, returns_addr)
| true ->
let _ = L.build_call f llargs "" ctx.ir_builder in
assert (Array.length llargs > 0);
let llval = llargs.(0) in
(llval, returns_addr)
in
let fn_s_name = Env.get_name env |> Id_string.to_string in
let (llval, returns_addr) = match detail with
(* normal function *)
| Env.FnRecordNormal (_, kind, _) ->
begin
Debug.printf "gen value: debug / function normal %s / kind: %s"
fn_s_name
(Env.FunctionOp.string_of_kind kind);
let r_value = force_target_generation ctx env in
match r_value with
| LLValue (f, true) -> call_llfunc kind f
| _ -> failwith "[ICE] unexpected value"
end
| Env.FnRecordImplicit (def, kind, _) ->
begin
let open Codegen_llvm_intrinsics in
Debug.printf "gen value: debug / function implicit %s / kind: %s"
fn_s_name
(Env.FunctionOp.string_of_kind kind);
let r_value = force_target_generation ctx env in
match r_value with
(* trivial function *)
| TrivialAction ->
begin
let (new_obj, is_addr) = match storage_ref with
| TAst.StoStack _
| TAst.StoAgg _
| TAst.StoArrayElem _
| TAst.StoMemberVar _ ->
let (v, _, is_addr) =
setup_storage storage_ref caller_env ctx
in
(v, is_addr)
| _ ->
TAst.debug_print_storage storage_ref;
failwith "[ICE]"
in
match kind with
| Env.FnKindDefaultConstructor None ->
begin
TODO : zero - fill
(new_obj, is_addr)
end
| Env.FnKindCopyConstructor None
| Env.FnKindMoveConstructor None ->
begin
assert (List.length args = 1);
let rhs = List.hd args in
let (llrhs, rhs_ty, is_ptr, cg) = generate_code rhs prev_fi ctx in
assert (is_ptr);
let sl = Type.size_of rhs_ty in
let al = Type.align_of rhs_ty in
let _ = ctx.intrinsics.memcpy_i32 new_obj llrhs
sl al false ctx.ir_builder
in
(new_obj, is_addr)
end
| _ -> failwith "[ICE]"
end
(* non-trivial function *)
| LLValue (f, true) -> call_llfunc kind f
| _ -> failwith "[ICE] unexpected"
end
(* external function *)
| Env.FnRecordExternal (def, kind, extern_name) ->
begin
Debug.printf "CALL FUNC / extern %s = \"%s\" / kind: %s\n"
fn_s_name
extern_name
(Env.FunctionOp.string_of_kind kind);
let (_, llargs, _, returns_addr) =
analyze_func_and_eval_args kind
in
let (extern_f, is_addr) =
find_llval_by_env_with_force_generation ctx env
in
assert (is_addr);
let llval = L.build_call extern_f llargs "" ctx.ir_builder in
(llval, returns_addr)
end
| Env.FnRecordBuiltin (def, kind, extern_name) ->
begin
Debug.printf "CALL FUNC / builtin %s = \"%s\" / kind: %s\n"
fn_s_name
extern_name
(Env.FunctionOp.string_of_kind kind);
TAst.debug_print_storage (storage_ref);
let (param_tys, llargs, is_addrs, returns_addr) =
analyze_func_and_eval_args kind
in
Debug.printf "== Args\n";
Array.iter debug_dump_value llargs;
Debug.printf "== %b\n" returns_addr;
let v_record = Ctx.find_val_by_name ctx extern_name in
let builtin_gen_f = match v_record with
| BuiltinFunc f -> f
| BuiltinFuncGen f ->
let fenv_r = Env.FunctionOp.get_record env in
f fenv_r.Env.fn_template_vals
| _ -> failwith "[ICE]"
in
let param_ty_and_addrs = List.combine param_tys is_addrs in
let ret_ty_and_addrs = (ret_ty, returns_addr) in
let llval = builtin_gen_f param_ty_and_addrs ret_ty_and_addrs llargs ctx in
(llval, returns_addr)
end
| Env.FnUndef -> failwith "[ICE] codegen: undefined function record"
in
Debug.printf "is_addr: %b" returns_addr;
TODO
end
| TAst.NestedExpr (lhs_node, _, rhs_ty, Some rhs_env) ->
begin
let (ll_lhs, _, is_addr, cg) = generate_code lhs_node prev_fi ctx in
assert (is_addr);
let v_record = try Ctx.find_val_by_env ctx rhs_env with
| Not_found -> failwith "[ICE] member env is not found"
in
let index = match v_record with
| ElemIndex i -> i
| _ -> failwith "[ICE]"
in
let llelem = L.build_struct_gep ll_lhs index "" ctx.ir_builder in
TODO
end
| TAst.FinalyzeExpr (opt_act_node, final_exprs) ->
let (ll_lhs, ty, is_addr, cg) = match opt_act_node with
| Some act_node -> generate_code act_node prev_fi ctx
| None -> void_val prev_fi
in
List.iter (fun n -> let _ = generate_code n prev_fi ctx in ()) final_exprs;
TODO
| TAst.SetCacheExpr (id, node) ->
let values = generate_code node prev_fi ctx in
Ctx.bind_values_to_cache_id ctx values id;
values
| TAst.GetCacheExpr id ->
Ctx.find_values_by_cache_id ctx id
| TAst.BoolLit (v, lit_ty) ->
begin
let llty = L.i1_type ctx.ir_context in
let llval = L.const_int llty (if v then 1 else 0) in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.IntLit (v, bits, signed, lit_ty) ->
begin
let llty = match bits with
| 8 -> L.i8_type ctx.ir_context
| 32 -> L.i32_type ctx.ir_context
| _ -> failwith "[ICE]"
in
let llval = L.const_int llty v in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.StringLit (str, lit_ty) ->
begin
let llty = L.pointer_type (L.i8_type ctx.ir_context) in
let llval = L.build_global_stringptr str "" ctx.ir_builder in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.ArrayLit (elems, static_constructable, arr_ty) ->
begin
let arr_llty = lltype_of_typeinfo arr_ty ctx in
let ll_array_sto = build_alloca_to_entry arr_llty ctx in
if static_constructable then
begin
let (ll_elems, tys, _, _) =
generate_codes elems prev_fi ctx
in
let lit_ty = List.hd tys in
let llty = lltype_of_typeinfo lit_ty ctx in
let lit_ptr_ty = L.pointer_type llty in
let ll_array = L.const_array llty (Array.of_list ll_elems) in
let ll_array = L.define_global "" ll_array ctx.ir_module in
L.set_linkage L.Linkage.Private ll_array;
L.set_unnamed_addr true ll_array;
let llsrc = L.build_bitcast ll_array lit_ptr_ty "" ctx.ir_builder in
let lltrg = L.build_bitcast ll_array_sto lit_ptr_ty "" ctx.ir_builder in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let open Codegen_llvm_intrinsics in
let _ =
ctx.intrinsics.memcpy_i32 lltrg llsrc
size_of align_of false ctx.ir_builder
in
TODO
end
else
begin
Ctx.push_array_storage ctx (LLValue (ll_array_sto, true));
let _ = elems |> List.map (fun n -> generate_code n prev_fi ctx) in
let _ = Ctx.pop_array_storage ctx in
TODO
end
end
| TAst.GenericId (name, lt_args, Some rel_env) ->
begin
let { Env.er = er; _ } = rel_env in
match er with
| Env.Function (_, r) ->
begin
assert(List.length lt_args = 0);
(* *)
Env.debug_print rel_env;
failwith @@ "[ICE] TAst.Id: function "
^ (Id_string.to_string name)
^ " // "
^ (Id_string.to_string (Env.get_name rel_env))
end
| Env.Variable (r) ->
begin
assert(List.length lt_args = 0);
Debug.printf "variable %s / type => %s\n"
(Id_string.to_string name)
(Type.to_string r.Env.var_type);
let var_llr =
try Ctx.find_val_by_env ctx rel_env with
| Not_found ->
try Ctx.find_metaval_by_env ctx rel_env with
| Not_found ->
failwith (Printf.sprintf "[ICE] variable(meta) env is not found: %s, %s"
(Meta_level.to_string rel_env.Env.meta_level)
(Type.to_string r.Env.var_type))
in
let (llval, is_addr) = match var_llr with
| LLValue v -> v
| _ -> failwith "[ICE]"
in
let ty = r.Env.var_type in
TODO
end
| Env.Class (_, r) ->
begin
let ty_attr_val_default = {
Type_attr.ta_ref_val = Type_attr.Val;
Type_attr.ta_mut = Type_attr.Const;
} in
(* generics *)
assert (List.length r.Env.cls_generics_vals >= List.length lt_args);
let generics_args =
let rec f pl al acc =
match (pl, al) with
| ([], []) -> acc
| ([], _) -> failwith ""
| (_::px, []) -> f px [] (Lifetime.LtUndef :: acc) (* TODO: check undef *)
| (p::px, a::ax) -> f px ax (a :: acc)
in
f r.Env.cls_generics_vals lt_args [] |> List.rev
in
(* type *)
let ty =
Type.Generator.generate_type ctx.type_sets.Type_sets.ts_type_gen
(Type_info.UniqueTy rel_env)
r.Env.cls_template_vals
generics_args
ty_attr_val_default
in
let itype_id = Option.get ty.Type_info.ti_id in
Debug.printf "#### LLVM: eval class: type_id = %s / %s\n"
(Int64.to_string itype_id)
(Type.to_string ty);
(* return the internal typeid as a type *)
let llval = L.const_of_int64 (L.i64_type ctx.ir_context)
itype_id
Type_info.is_type_id_signed
in
let ty = ctx.type_sets.Type_sets.ts_type_type in
TODO
end
(* regards all values are NOT references *)
| Env.MetaVariable (uni_id) ->
begin
assert(List.length lt_args = 0);
let uni_map = ctx.uni_map in
Debug.printf "LLVM codegen Env.MetaVariable = %d\n" uni_id;
let (_, c) = Unification.search_value_until_terminal uni_map uni_id in
match c with
| Unification.Val v -> ctfe_val_to_llval v prev_fi ctx
| _ -> raise @@ Meta_var_un_evaluatable uni_id
end
| _ ->
begin
Env.debug_print rel_env;
failwith @@ "codegen; id " ^ (Id_string.to_string name)
end
end
| TAst.ScopeExpr (block) ->
generate_code block prev_fi ctx
| TAst.IfExpr (cond_expr, then_expr, opt_else_expr, if_ty) ->
begin
let (llcond, _, is_cond_addr, fi) = generate_code cond_expr prev_fi ctx in
discontinue_when_expr_terminated fi;
let llcond = if is_cond_addr then
L.build_load llcond "" ctx.ir_builder
else
llcond
in
let ibb = L.insertion_block ctx.ir_builder in
let tbb = L.insert_block ctx.ir_context "then" ibb in (* then *)
let ebb = L.insert_block ctx.ir_context "else" ibb in (* else *)
let fbb = L.insert_block ctx.ir_context "term" ibb in (* final *)
L.move_block_after ibb tbb;
L.move_block_after tbb ebb;
L.move_block_after ebb fbb;
(* make jump entry *)
let _ = match Option.is_some opt_else_expr with
| true ->
(* true -> true block, false -> else block *)
L.build_cond_br llcond tbb ebb ctx.ir_builder
| false ->
(* true -> true block, false -> final block *)
L.build_cond_br llcond tbb fbb ctx.ir_builder
in
(* then node *)
let then_branch =
L.position_at_end tbb ctx.Ctx.ir_builder;
let (then_llval, then_ty, is_then_addr, then_fi) =
generate_code then_expr fi ctx
in
if not (FI.has_terminator then_fi) then
let then_llval = adjust_llval_form if_ty then_ty then_llval ctx in
let then_llval =
adjust_addr_val then_llval then_ty is_then_addr ctx
in
let _ = L.build_br fbb ctx.ir_builder in
let cip = L.insertion_block ctx.ir_builder in
[(then_llval, cip)]
else
[]
in
(* else node *)
let else_branch =
match opt_else_expr with
| Some else_expr ->
L.position_at_end ebb ctx.Ctx.ir_builder;
let (else_llval, else_ty, is_else_addr, else_fi) =
generate_code else_expr fi ctx
in
if not (FI.has_terminator else_fi) then
let else_llval = adjust_llval_form if_ty else_ty else_llval ctx in
let else_llval =
adjust_addr_val else_llval else_ty is_else_addr ctx
in
let _ = L.build_br fbb ctx.ir_builder in
let cip = L.insertion_block ctx.ir_builder in
[(else_llval, cip)]
else
[]
| None ->
L.remove_block ebb;
[(void_v, ibb)] (* pass through *)
in
(* make term *)
let branchs = then_branch @ else_branch in
Debug.printf "IF EXPR / branchs %d" (List.length branchs);
match branchs with
| [] ->
L.remove_block fbb;
void_val (fi |> FI.set_has_terminator true)
| _ ->
L.position_at_end fbb ctx.Ctx.ir_builder;
if Type.has_same_class ctx.type_sets.Type_sets.ts_void_type if_ty then
void_val fi
else
let llret = L.build_phi branchs "" ctx.ir_builder in
let is_addr = is_address_representation if_ty in
(llret, if_ty, is_addr, fi)
end
(* FIX: is_addr *)
| TAst.ForExpr (opt_decl, opt_cond, opt_step, body) ->
begin
let ip = L.insertion_block ctx.Ctx.ir_builder in
let bip = L.insert_block ctx.ir_context "loop_begin" ip in
let sip = L.insert_block ctx.ir_context "loop_step" ip in
let eip = L.insert_block ctx.ir_context "loop_end" ip in
L.move_block_after ip bip;
L.move_block_after bip sip;
L.move_block_after sip eip;
let _ = match opt_decl with
| Some decl -> ignore @@ generate_code decl prev_fi ctx
| None -> ()
in
let _ = L.build_br bip ctx.ir_builder in
L.position_at_end bip ctx.Ctx.ir_builder;
let _ = match opt_cond with
| Some cond ->
begin
let (llcond, _, _, _) = generate_code cond prev_fi ctx in
ignore @@ L.build_cond_br llcond sip eip ctx.ir_builder;
L.position_at_end sip ctx.Ctx.ir_builder;
end
| None -> L.remove_block sip;
in
ignore @@ generate_code body prev_fi ctx;
let _ = match opt_step with
| Some step ->
begin
ignore @@ generate_code step prev_fi ctx
end
| None -> ();
in
ignore @@ L.build_br bip ctx.ir_builder;
L.position_at_end eip ctx.Ctx.ir_builder;
void_val prev_fi
end
| TAst.CtxNode ty ->
begin
let itype_id = Option.get ty.Type_info.ti_id in
Debug.printf "##### type_id = %s\n" (Int64.to_string itype_id);
(* return the internal typeid as a type *)
let llval = L.const_of_int64 (L.i64_type ctx.ir_context)
itype_id
Type_info.is_type_id_signed
in
let ty = ctx.type_sets.Type_sets.ts_type_type in
(llval, ty, false, prev_fi)
end
| TAst.StorageWrapperExpr (sto, e) ->
Debug.printf "STORAGE CHANGED\n";
TAst.debug_print_storage (!sto);
generate_code ~storage:(Some !sto) e prev_fi ctx
| TAst.Undef ty ->
let llty = lltype_of_typeinfo ty ctx in
(L.undef llty, ty, false, prev_fi)
| _ ->
failwith "cannot generate : node"
and ctfe_val_to_llval ctfe_val prev_fi ctx =
let open Ctx in
let tsets = ctx.type_sets in
match ctfe_val with
| Ctfe_value.Type (ty) ->
begin
let {
Type_info.ti_id = opt_tid;
Type_info.ti_sort = ty_sort;
} = ty in
match ty_sort with
| Type_info.UniqueTy _
| Type_info.NotDetermined _ ->
begin
match opt_tid with
| Some tid ->
(* return the internal typeid as a type *)
let llval =
L.const_of_int64 (L.i64_type ctx.ir_context)
tid
Type_info.is_type_id_signed
in
let ty = tsets.Type_sets.ts_type_type in
(llval, ty, false, prev_fi)
| None -> failwith "[ICE] codegen_llvm : has no type_id"
end
| _-> failwith "[ICE] codegen_llvm : type"
end
| Ctfe_value.Bool b ->
let llval =
L.const_of_int64 (L.i1_type ctx.ir_context)
(Int64.of_int (Bool.to_int b))
false (* not signed *)
in
let ty = !(tsets.Type_sets.ts_bool_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Int32 i32 ->
let llval =
L.const_of_int64 (L.i32_type ctx.ir_context)
(Int32.to_int64 i32)
true (* signed *)
in
let ty = !(tsets.Type_sets.ts_int32_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Uint32 i32 ->
let llval =
L.const_of_int64 (L.i32_type ctx.ir_context)
(Uint32.to_int64 i32)
false (* unsigned *)
in
let ty = !(tsets.Type_sets.ts_int32_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Undef ud_uni_id ->
raise @@ Meta_var_un_evaluatable ud_uni_id
| _ -> failwith "[ICE]"
and is_in_other_module ctx env =
let open Ctx in
match Ctx.target_module ctx with
| None -> false
| Some target_module ->
let target_module_id = Env.get_id target_module in
let module_env_id = match Env.get_module_env_id env with
| Some e -> e
| None -> failwith "[ICE]"
in
if target_module_id = module_env_id then
false
else
not env.Env.is_instantiated
and generate_code_by_interrupt node ctx =
(* save current position *)
let opt_ip = match L.insertion_block ctx.Ctx.ir_builder with
| exception Not_found -> None
| x -> Some x
in
(* generate code independently *)
let _ = generate_code node FI.empty ctx in
(* resume position *)
opt_ip |> Option.may (fun ip -> L.position_at_end ip ctx.Ctx.ir_builder)
and force_target_generation ctx env =
try Ctx.find_val_by_env ctx env with
| Not_found ->
begin
let { Env.rel_node = rel_node; _ } = env in
let node = match rel_node with
| Some v -> v
| None ->
begin
Env.debug_print env;
failwith "[ICE] force_target_generation: there is no rel node"
end
in
generate_code_by_interrupt node ctx;
(* retry *)
try Ctx.find_val_by_env ctx env with
| Not_found ->
begin
Env.debug_print env;
failwith "[ICE] force_target_generation: couldn't find target"
end
end
| _ -> failwith "yo"
and find_llval_by_env_with_force_generation ctx env =
let v_record = force_target_generation ctx env in
match v_record with
| LLValue v -> v
| _ -> failwith "[ICE] / find_llval_by_env_with_force_generation"
and find_lltype_by_env_with_force_generation ctx env =
let v_record = force_target_generation ctx env in
match v_record with
| LLType t -> t
| _ -> failwith "[ICE] / find_lltype_by_env_with_force_generation"
and register_metaval value env ctx =
let (llval, _, _, _) = ctfe_val_to_llval value FI.empty ctx in
let cv = LLValue (llval, false) in
Ctx.bind_metaval_to_env ctx cv env
and lltype_of_typeinfo ty ctx =
let open Ctx in
let cenv = Type.as_unique ty in
let ll_ty = find_lltype_by_env_with_force_generation ctx cenv in
ll_ty
and lltype_of_typeinfo_param ty ctx =
let ll_ty = lltype_of_typeinfo ty ctx in
if is_address_representation_param ty then
L.pointer_type ll_ty
else
ll_ty
and lltype_of_typeinfo_ret ty ctx =
let ll_ty = lltype_of_typeinfo ty ctx in
if is_address_representation ty then
L.pointer_type ll_ty
else
ll_ty
and is_primitive ty =
let cenv = Type.as_unique ty in
let cr = Env.ClassOp.get_record cenv in
cr.Env.cls_traits.Env.cls_traits_is_primitive
and is_always_value ty =
let cenv = Type.as_unique ty in
let cr = Env.ClassOp.get_record cenv in
cr.Env.cls_traits.Env.cls_traits_is_always_value
and is_heavy_object ty =
let {
Type_attr.ta_ref_val = rv;
Type_attr.ta_mut = mut;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Ref _ -> false
| Type_attr.Val -> is_address_representation ty
| _ -> failwith "[ICE] Unexpected : rv"
(**)
and is_address_representation ty =
let {
Type_attr.ta_ref_val = rv;
Type_attr.ta_mut = mut;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Ref _ -> not (is_always_value ty)
| Type_attr.Val ->
begin
match mut with
| Type_attr.Mutable -> true
| Type_attr.Const
| Type_attr.Immutable ->
begin
(* if type is NOT primitive, it will be represented by address *)
not (is_primitive ty)
end
| _ -> failwith "[ICE] Unexpected : mut"
end
| _ -> failwith "[ICE] Unexpected : rv"
(* address representation of function interface *)
and is_address_representation_param ty =
let {
Type_attr.ta_ref_val = rv;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Val when is_primitive ty -> false
| _ -> is_address_representation ty
and adjust_llval_form' trg_ty trg_chkf src_ty src_chkf skip_alloca llval ctx =
let open Ctx in
match (trg_chkf trg_ty, src_chkf src_ty) with
| (true, true)
| (false, false) -> llval
| (true, false) ->
if skip_alloca then
llval
else
let llty = lltype_of_typeinfo trg_ty ctx in
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.ir_builder in
v
| (false, true) ->
if skip_alloca then
llval
else
L.build_load llval "" ctx.ir_builder
and adjust_llval_form trg_ty src_ty llval ctx =
Debug.printf "is_pointer rep? trg: %b(%s), src: %b(%s)"
(is_address_representation trg_ty)
(Type.to_string trg_ty)
(is_address_representation src_ty)
(Type.to_string src_ty);
debug_dump_value llval;
let trg_check_f = is_address_representation in
let src_check_f = is_address_representation in
adjust_llval_form' trg_ty trg_check_f src_ty src_check_f false llval ctx
and adjust_arg_llval_form trg_ty src_ty src_is_addr skip_alloca llval ctx =
if is_primitive trg_ty then
begin
Debug.printf "ARG: is_pointer_arg rep? trg: [%b](%s), src: [%b]<%b>(%s) ->"
(is_address_representation_param trg_ty)
(Type.to_string trg_ty)
src_is_addr
(is_address_representation src_ty)
(Type.to_string src_ty);
debug_dump_value llval;
Debug.printf "<-";
let trg_check_f = is_address_representation_param in
let src_check_f = fun _ -> src_is_addr in
adjust_llval_form' trg_ty trg_check_f src_ty src_check_f skip_alloca llval ctx
end
else
adjust_llval_form trg_ty src_ty llval ctx
and adjust_addr_val v ty is_addr ctx =
if is_address_representation ty then
v
else
if is_addr then
L.build_load v "" ctx.Ctx.ir_builder
else
v
(* allocate storage for primitve i*)
and adjust_primitive_value storage llty llval ctx =
match storage with
| Some (TAst.StoStack _) ->
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.Ctx.ir_builder in
(v, true)
| Some TAst.StoImm
| None -> (llval, false)
| _ -> failwith "[ICE]"
and paramkinds_to_llparams params ret_ty ctx =
let returns_heavy_obj = is_heavy_object ret_ty in
let f (is_vargs, rev_tys) tp =
match tp with
| Env.FnParamKindType ty -> (is_vargs, ty :: rev_tys)
in
let (is_vargs, rev_tys) =
List.fold_left f (false, []) params
in
let param_types = rev_tys |> List.rev in
let llparams =
(if returns_heavy_obj then [ret_ty] else []) @ param_types
|> List.map (fun t -> lltype_of_typeinfo_param t ctx)
|> Array.of_list
in
(is_vargs, llparams)
(* move to elsewhere *)
and typeinfo_of_paramkind pk =
match pk with
| Env.FnParamKindType ty -> ty
and normalize_params_and_args params_info args =
adjust_param_types' params_info args []
|> List.rev |> List.split
and adjust_param_types' params_info args acc =
match (params_info, args) with
| (param_info :: px, arg :: ax) ->
begin
match param_info with
| Env.FnParamKindType ty ->
adjust_param_types' px ax ((ty, arg) :: acc)
end
| (_, []) -> acc
| ([], _) -> failwith "[ICE]"
and setup_storage sto caller_env ctx =
let open Ctx in
match sto with
| TAst.StoStack (ty) ->
begin
Debug.printf "setup_storage: StoStack ty=%s\n"
(Type.to_string ty);
let llty = lltype_of_typeinfo ty ctx in
let v = build_alloca_to_entry llty ctx in
(v, ty, true)
end
| TAst.StoAgg (ty) ->
begin
Debug.printf "setup_storage: StoAgg ty=%s\n"
(Type.to_string ty);
let ctx_env = caller_env.Env.context_env in
let (ll_fval, is_f_addr) =
find_llval_by_env_with_force_generation ctx ctx_env
in
assert (is_f_addr);
let agg = L.param ll_fval 0 in
assert (L.value_name agg = agg_recever_name);
(agg, ty, true)
end
| TAst.StoArrayElem (ty, index) ->
Debug.printf "setup_storage: StoArrayElem ty=%s\n"
(Type.to_string ty);
let array_sto = match Ctx.current_array_storage ctx with
| LLValue (v, true) -> v
| _ -> failwith "[ICE]"
in
let zero = L.const_int (L.i32_type ctx.ir_context) 0 in
let llindex = L.const_int (L.i32_type ctx.ir_context) index in
let array_elem_ptr =
L.build_in_bounds_gep array_sto
[|zero; llindex|]
""
ctx.Ctx.ir_builder
in
(array_elem_ptr, ty, true)
| TAst.StoArrayElemFromThis (ty, Some this_env, index) ->
Debug.printf "setup_storage: StoArrayElemFromThis ty=%s\n"
(Type.to_string ty);
let (array_sto, is_f_addr) =
find_llval_by_env_with_force_generation ctx this_env
in
assert (is_f_addr);
let zero = L.const_int (L.i32_type ctx.ir_context) 0 in
let llindex = L.const_int (L.i32_type ctx.ir_context) index in
let array_elem_ptr =
L.build_in_bounds_gep array_sto
[|zero; llindex|]
""
ctx.Ctx.ir_builder
in
(array_elem_ptr, ty, true)
| TAst.StoMemberVar (ty, Some venv, Some parent_fenv) ->
Debug.printf "setup_storage: StoMemberVar ty=%s\n"
(Type.to_string ty);
let (reciever_llval, is_addr) =
match Env.FunctionOp.get_kind parent_fenv with
| Env.FnKindConstructor (Some rvenv)
| Env.FnKindCopyConstructor (Some rvenv)
| Env.FnKindMoveConstructor (Some rvenv)
| Env.FnKindDefaultConstructor (Some rvenv)
| Env.FnKindDestructor (Some rvenv) ->
find_llval_by_env_with_force_generation ctx rvenv
| _ -> failwith "[ICE] no reciever"
in
assert (is_addr);
let member_index = match Ctx.find_val_by_env ctx venv with
| ElemIndex idx -> idx
| _ -> failwith "[ICE] a member variable is not found"
in
let elem_llval =
debug_dump_value reciever_llval;
Debug.printf "index = %d\n" member_index;
L.build_struct_gep reciever_llval member_index "" ctx.ir_builder
in
(elem_llval, ty, true)
| _ -> failwith "[ICE] cannot setup storage"
and generate_codes nodes fi ctx =
let (llvals, tys, is_addrs, fi) =
let f (llvals, tys, is_addrs, fi) node =
let (llval, ty, is_addr, nfi) = generate_code node fi ctx in
(llval::llvals, ty::tys, is_addr::is_addrs, nfi)
in
List.fold_left f ([], [], [], fi) nodes
in
(llvals |> List.rev, tys |> List.rev, is_addrs |> List.rev, fi)
and eval_args_for_func kind ret_sto param_types ret_ty args caller_env prev_fi ctx =
Debug.printf "eval_args_for_func: storage %s"
(TAst.string_of_stirage ret_sto);
(* normal arguments *)
let (llvals, arg_tys, is_addrs, fi) =
generate_codes args prev_fi ctx
in
discontinue_when_expr_terminated fi;
(* special arguments *)
let (opt_head, (returns_addr, skip_alloca)) =
match ret_sto with
| TAst.StoStack _
| TAst.StoAgg _
| TAst.StoArrayElem _
| TAst.StoArrayElemFromThis _
| TAst.StoMemberVar _ ->
let (v, ty, is_addr) = setup_storage ret_sto caller_env ctx in
let sa = is_primitive ty in
(Some (v, ty, is_addr), (true, sa))
| TAst.StoImm ->
let (returns_addr, sa) =
match kind with
| Env.FnKindFree ->
(is_address_representation ret_ty, false)
| Env.FnKindMember ->
let returns_addr =
is_address_representation ret_ty
in
let skip_alloca = match param_types with
| [] -> false
| x :: _ -> is_primitive x
in
(returns_addr, skip_alloca)
(* for special functions with immediate(primitive) *)
| _ ->
let returns_addr = match is_addrs with
| [] -> false
| hp :: _ -> hp
in
let skip_alloca = match param_types with
| [] -> false
| x :: _ -> is_primitive x
in
(returns_addr, skip_alloca)
in
(None, (returns_addr, sa))
| _ ->
failwith (Printf.sprintf "[ICE] special arguments %s"
(TAst.string_of_stirage ret_sto))
in
let (llvals, arg_tys, is_addrs, param_types) = match opt_head with
| Some (v, ty, is_addr) ->
(v::llvals, ty::arg_tys, is_addr::is_addrs, ty::param_types)
| None ->
(llvals, arg_tys, is_addrs, param_types)
in
let llargs =
Debug.printf "conv funcs skip_alloca = %b\n" skip_alloca;
let rec make param_tys arg_tys is_addrs llvals sa =
match (param_tys, arg_tys, is_addrs, llvals) with
| ([], [], [], []) -> []
| (pt::pts, at::ats, ia::ias, lv::lvs) ->
let llarg = adjust_arg_llval_form pt at ia sa lv ctx in
llarg::(make pts ats ias lvs sa)
| _ -> failwith ""
in
make param_types arg_tys is_addrs llvals skip_alloca
in
let llargs = llargs |> Array.of_list in
(param_types, llargs, is_addrs, returns_addr)
and declare_function name fenv ctx =
let open Ctx in
let fenv_r = Env.FunctionOp.get_record fenv in
(* if this class returns non primitive object,
* add a parameter to receive the object *)
let returns_heavy_obj = is_heavy_object fenv_r.Env.fn_return_type in
let func_ret_ty =
if returns_heavy_obj then
ctx.type_sets.Type_sets.ts_void_type
else
fenv_r.Env.fn_return_type
in
let llret_ty = lltype_of_typeinfo_ret func_ret_ty ctx in
let (_, llparam_tys) =
paramkinds_to_llparams fenv_r.Env.fn_param_kinds
fenv_r.Env.fn_return_type
ctx
in
(* type of function *)
let f_ty = L.function_type llret_ty llparam_tys in
(* declare function *)
let f = L.declare_function name f_ty ctx.ir_module in
Ctx.bind_val_to_env ctx (LLValue (f, true)) fenv;
f
and setup_function_entry f ctx =
let open Ctx in
(* entry block (for alloca and runtime initialize) *)
let ebb = L.append_block ctx.ir_context "entry" f in
(* program block *)
let pbb = L.append_block ctx.ir_context "program" f in
L.position_at_end pbb ctx.ir_builder;
(* push function block *)
Ctx.push_processing_function ctx f;
(ebb, pbb)
and connect_function_entry f (ebb, pbb) ctx =
let open Ctx in
(* connect entry and program block *)
L.position_at_end ebb ctx.ir_builder;
let _ = L.build_br pbb ctx.ir_builder in
L.move_block_after ebb pbb;
(* pop function *)
let _ = Ctx.pop_processing_function ctx in
()
and define_function kind fn_spec opt_body fenv fi ctx =
let open Ctx in
let fenv_r = Env.FunctionOp.get_record fenv in
let body = Option.get opt_body in
let param_envs = fn_spec.Env.fn_spec_param_envs in
let force_inline = fn_spec.Env.fn_spec_force_inline in
let name = fenv.Env.mangled_name |> Option.get in
let f = declare_function name fenv ctx in
if force_inline then
begin
let always_inline = L.create_enum_attr ctx.ir_context "alwaysinline" 0L in
L.add_function_attr f always_inline L.AttrIndex.Function;
let no_unwind = L.create_enum_attr ctx.ir_context "nounwind" 0L in
L.add_function_attr f no_unwind L.AttrIndex.Function;
L.set_linkage L.Linkage.Private f;
()
end;
if is_in_other_module ctx fenv && not force_inline then
begin
Ctx.bind_external_function ctx name f;
()
end
else
begin
let (ebb, pbb) = setup_function_entry f ctx in
(* setup parameters *)
let param_envs = param_envs |> List.enum in
let raw_ll_params = L.params f |> Array.enum in
let returns_heavy_obj = is_heavy_object fenv_r.Env.fn_return_type in
if returns_heavy_obj then
begin
(* set name of receiver *)
let opt_agg = Enum.peek raw_ll_params in
assert (Option.is_some opt_agg);
let agg = Option.get opt_agg in
let _ = match kind with
| Env.FnKindConstructor (Some venv)
| Env.FnKindCopyConstructor (Some venv)
| Env.FnKindMoveConstructor (Some venv)
| Env.FnKindDefaultConstructor (Some venv)
| Env.FnKindDestructor (Some venv) ->
let venv_r = Env.VariableOp.get_record venv in
let var_name = Id_string.to_string venv_r.Env.var_name in
L.set_value_name var_name agg;
Ctx.bind_val_to_env ctx (LLValue (agg, true)) venv
| _ ->
L.set_value_name agg_recever_name agg;
in
remove the implicit parameter from ENUM
Enum.drop 1 raw_ll_params;
end;
(* adjust type specialized by params to normal type forms *)
let adjust_param_type (ty, llval) =
let should_param_be_address = is_address_representation ty in
let actual_param_rep = is_address_representation_param ty in
match (should_param_be_address, actual_param_rep) with
| (true, false) ->
let llty = lltype_of_typeinfo ty ctx in
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.ir_builder in
(v, should_param_be_address)
| (true, true)
| (false, false) -> (llval, should_param_be_address)
| _ -> failwith "[ICE]"
in
let ll_params =
let param_types =
fenv_r.Env.fn_param_kinds
|> List.map typeinfo_of_paramkind
|> List.enum
in
Enum.combine (param_types, raw_ll_params)
|> Enum.map adjust_param_type
in
let declare_param_var optenv (llvar, is_addr) =
match optenv with
| Some env ->
begin
let venv = Env.VariableOp.get_record env in
let var_name = Id_string.to_string venv.Env.var_name in
L.set_value_name var_name llvar;
Ctx.bind_val_to_env ctx (LLValue (llvar, is_addr)) env
end
| None -> ()
in
Enum.iter2 declare_param_var param_envs ll_params;
(* reset position for program block *)
L.position_at_end pbb ctx.ir_builder;
(**)
let _ = generate_code body fi ctx in
connect_function_entry f (ebb, pbb) ctx;
debug_dump_value f;
Debug.printf "generated genric function(%b): %s [%s]\n"
fenv.Env.closed
name
(fenv.Env.env_id |> Env_system.EnvId.to_string);
Llvm_analysis.assert_valid_function f
end
and build_alloca_to_entry llty ctx =
(* save current position *)
let ip =
try L.insertion_block ctx.Ctx.ir_builder with
| Not_found ->
failwith "[ICE] unexpected alloca call"
in
(* move to entry block of the function *)
let current_f = Ctx.current_processing_function ctx in
let entry_block = L.entry_block current_f in
L.position_at_end entry_block ctx.Ctx.ir_builder;
(**)
let llval = L.build_alloca llty "" ctx.Ctx.ir_builder in
(* resume position *)
L.position_at_end ip ctx.Ctx.ir_builder;
llval
let regenerate_module ctx =
let ir_module = L.create_module ctx.Ctx.ir_context "Rill" in
ctx.Ctx.ir_module <- ir_module
let inject_builtins ctx =
let open Ctx in
let register_builtin_type name record =
Ctx.bind_val_to_name ctx record name;
Debug.printf " debug / \"%s\"\n " name
in
let register_builtin_func name f =
Ctx.bind_val_to_name ctx (BuiltinFunc f) name;
Debug.printf " debug / func = \"%s\"\n " name
in
let register_builtin_template_func name f =
Ctx.bind_val_to_name ctx (BuiltinFuncGen f) name;
Debug.printf " debug / func = \"%s\"\n " name
in
type is represented as int64 in this context .
* It donates ID of type in the type generator
* It donates ID of type in the type generator
*)
begin
let open Builtin_info in
* Builtin types
* Builtin types
*)
register_builtin_type type_type_i.internal_name
(LLType (L.i64_type ctx.ir_context));
register_builtin_type void_type_i.internal_name
(LLType (L.void_type ctx.ir_context));
register_builtin_type bool_type_i.internal_name
(LLType (L.i1_type ctx.ir_context));
register_builtin_type uint8_type_i.internal_name
(LLType (L.i8_type ctx.ir_context));
register_builtin_type int32_type_i.internal_name
(LLType (L.i32_type ctx.ir_context));
register_builtin_type uint32_type_i.internal_name
(LLType (L.i32_type ctx.ir_context));
register_builtin_type raw_ptr_type_i.internal_name
(LLTypeGen (
fun template_args ->
begin
assert (List.length template_args = 1);
let ty_ct_val = List.nth template_args 0 in
let ty_val = match ty_ct_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let elem_ty = lltype_of_typeinfo ty_val ctx in
L.pointer_type elem_ty
end
));
register_builtin_type untyped_raw_ptr_type_i.internal_name
(LLType (L.pointer_type (L.i8_type ctx.ir_context)));
register_builtin_type array_type_i.internal_name
(LLTypeGen (
fun template_args ->
begin
assert (List.length template_args = 2);
let ty_ct_val = List.nth template_args 0 in
let len_ct_val = List.nth template_args 1 in
let ty_val = match ty_ct_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let len_val = match len_ct_val with
| Ctfe_value.Uint32 i32 -> i32
| _ -> failwith "[ICE]"
in
(* TODO: fix *)
let llty = lltype_of_typeinfo ty_val ctx in
let len = Uint32.to_int len_val in
L.array_type llty len
end
));
end;
* Builtin functions
* Builtin functions
*)
let () =
(* sizeof is onlymeta function *)
let f template_args _ _ _args ctx =
assert (List.length template_args = 1);
assert (Array.length _args = 0);
let ty = match List.nth template_args 0 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
llval_u32 (Type.size_of ty) ctx
in
register_builtin_template_func "__builtin_sizeof" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let type_s = Type.to_string ty in
L.build_global_stringptr type_s "" ctx.ir_builder
in
register_builtin_template_func "__builtin_stringof" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let llty = lltype_of_typeinfo ty ctx in
let llptrty = L.pointer_type llty in
assert (Array.length args = 1);
L.build_bitcast args.(0) llptrty "" ctx.ir_builder
in
register_builtin_template_func "__builtin_unsafe_ptr_cast" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 2);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let llty = lltype_of_typeinfo ty ctx in
let llptrty = L.pointer_type llty in
assert (Array.length args = 1);
L.build_pointercast args.(0) llptrty "" ctx.ir_builder
in
register_builtin_template_func "__builtin_take_address_from_array" f
in
let () =
let f param_tys_and_addrs _ args ctx =
let open Codegen_llvm_intrinsics in
assert (Array.length args = 1);
assert (List.length param_tys_and_addrs = 1);
let (arr_ty, _) = List.hd param_tys_and_addrs in
let to_obj = args.(0) in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let _ =
ctx.intrinsics.memset_i32 to_obj (Int8.of_int 0)
size_of align_of false ctx.ir_builder
in
to_obj
in
let open Builtin_info in
register_builtin_func
(make_builtin_default_ctor_name array_type_i.internal_name) f
in
let () =
let f param_tys_and_addrs _ args ctx =
let open Codegen_llvm_intrinsics in
assert (Array.length args = 2);
assert (List.length param_tys_and_addrs = 2);
let (arr_ty, _) = List.hd param_tys_and_addrs in
let to_obj = args.(0) in
let from_obj = args.(1) in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let _ =
ctx.intrinsics.memcpy_i32 to_obj from_obj
size_of align_of false ctx.ir_builder
in
to_obj
in
let open Builtin_info in
register_builtin_func
(make_builtin_copy_ctor_name array_type_i.internal_name) f
in
let define_special_members builtin_info init_val_gen =
let open Builtin_info in
let normalize_store_value param_tys_and_addrs args =
assert (List.length param_tys_and_addrs = Array.length args);
let (_, rhs_is_addr) = List.at param_tys_and_addrs 1 in
Debug.printf "is_addr? => %b" rhs_is_addr;
debug_dump_value args.(1);
if rhs_is_addr then
L.build_load args.(1) "" ctx.ir_builder
else
args.(1)
in
let () = (* default constructor *)
let f param_tys_and_addrs ret_ty_and_addr args ctx =
assert (List.length param_tys_and_addrs = Array.length args);
let v = init_val_gen ret_ty_and_addr in
match Array.length args with
| 1 ->
let _ = L.build_store v args.(0) ctx.ir_builder in args.(0)
| 0 -> v
| _ -> failwith ""
in
register_builtin_func
(make_builtin_default_ctor_name builtin_info.internal_name) f
in
let () = (* copy constructor *)
let f param_tys_and_addrs _ args ctx =
assert (List.length param_tys_and_addrs = Array.length args);
Debug.printf "copy ctor: %s (%d)"
(builtin_info.internal_name)
(Array.length args);
List.iter (fun (ty, is_addr) -> Debug.printf "ty %s: %b"
(Type.to_string ty)
is_addr)
param_tys_and_addrs;
Array.iter debug_dump_value args;
match Array.length args with
| 2 ->
let store_val = normalize_store_value param_tys_and_addrs args in
let _ = L.build_store store_val args.(0) ctx.ir_builder in
args.(0)
| 1 -> args.(0)
| _ -> failwith ""
in
register_builtin_func
(make_builtin_copy_ctor_name builtin_info.internal_name) f
in
let () = (* copy assign *)
let f param_tys_and_addrs _ args ctx =
assert (Array.length args = 2);
Debug.printf "copy assign: %s (args length = %d)"
(builtin_info.internal_name)
(Array.length args);
debug_params_and_args param_tys_and_addrs args;
let store_val = normalize_store_value param_tys_and_addrs args in
L.build_store store_val args.(0) ctx.Ctx.ir_builder
in
register_builtin_func
(make_builtin_copy_assign_name builtin_info.internal_name) f
in
()
in
(*let _ =
(* defaulted but not trivial *)
let f args ctx =
assert (Array.length args = 2);
failwith ""
in
register_builtin_func "__builtin_array_type_copy_ctor" f
in*)
(* for type *)
let () =
let open Builtin_info in
(* TODO: fix *)
let init _ = L.const_int (L.i64_type ctx.ir_context) 0 in
define_special_members type_type_i init;
let () = (* ==(:type, :type) onlymeta: bool *)
let f template_args _ _ _args ctx =
assert (List.length template_args = 2);
assert (Array.length _args = 0);
let lhs_ty = match List.nth template_args 0 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
let rhs_ty = match List.nth template_args 1 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
let _ = lhs_ty in
let _ = rhs_ty in
(* TODO: IMPLEMENT! *)
llval_i1 (true) ctx
in
register_builtin_template_func "__builtin_op_binary_==_type_type" f
in
()
in
(* for int8 *)
let () =
let open Builtin_info in
let init _ = L.const_int (L.i8_type ctx.ir_context) 0 in
define_special_members uint8_type_i init;
()
in
let () =
let open Builtin_info in
let () = (* identity *)
let f _ _ args ctx =
assert (Array.length args = 1);
args.(0)
in
register_builtin_func "__builtin_identity" f
in
+ (: ):
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i8_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_uint32_to_uint8" f
in
let () = (* +(:int32): uint8 *)
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i8_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_int32_to_uint8" f
in
+ (: ): int32
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_uint8_to_int32" f
in
let () = (* +(:int32): uint32 *)
let f _ _ args ctx =
assert (Array.length args = 1);
unsigned , use zext
L.build_zext_or_bitcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_int32_to_uint32" f
in
+ (: ): uint32
let f _ _ args ctx =
assert (Array.length args = 1);
unsigned , use zext
L.build_zext_or_bitcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_bool_to_uint32" f
in
()
in
(* for int32 *)
let () =
let open Builtin_info in
let init _ = L.const_int (L.i32_type ctx.ir_context) 0 in
define_special_members int32_type_i init;
let () = (* unary- (:int); int *)
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_neg args.(0) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_unary_pre_-_int" f
in
let () = (* +(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_add args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_+_int_int" f
in
let () = (* -(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sub args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_-_int_int" f
in
let () = (* *(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_mul args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_*_int_int" f
in
let () = (* /(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sdiv args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_/_int_int" f
in
let () = (* %(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_srem args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_%_int_int" f
in
let () = (* <(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Slt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<_int_int" f
in
let () = (* >(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sgt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_>_int_int" f
in
let () = (* |(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_or args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_|_int_int" f
in
let () = (* ^(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_xor args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_^_int_int" f
in
let () = (* &(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_&_int_int" f
in
let () = (* <=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sle args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<=_int_int" f
in
let () = (* >=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sge args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_>=_int_int" f
in
let () = (* <<(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_shl args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<<_int_int" f
in
let () = (* >>(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_ashr args.(0) args.(1) "" ctx.Ctx.ir_builder (* sign ext(arithmetic) *)
in
register_builtin_func "__builtin_op_binary_>>_int_int" f
in
let () = (* >>>(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func "__builtin_op_binary_>>>_int_int" f
in
let () = (* ==(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Eq args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_==_int_int" f
in
let () = (* !=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ne args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_!=_int_int" f
in
()
in
for uint32
let () =
let open Builtin_info in
let basename = "uint" in
let init _ = L.const_int (L.i32_type ctx.ir_context) 0 in
define_special_members uint32_type_i init;
+ (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_add args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_+_%s_%s" basename basename) f
in
-(:INT , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sub args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_-_%s_%s" basename basename) f
in
* (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_mul args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_*_%s_%s" basename basename) f
in
/(:INT , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_udiv args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_/_%s_%s" basename basename) f
in
% (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_urem args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_%%_%s_%s" basename basename) f
in
let () = (* <(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ult args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<_%s_%s" basename basename) f
in
let () = (* >(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ugt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>_%s_%s" basename basename) f
in
let () = (* |(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_or args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_|_%s_%s" basename basename) f
in
let () = (* ^(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_xor args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_^_%s_%s" basename basename) f
in
let () = (* &(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_&_%s_%s" basename basename) f
in
let () = (* <=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ule args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<=_%s_%s" basename basename) f
in
let () = (* >=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Uge args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>=_%s_%s" basename basename) f
in
let () = (* <<(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_shl args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<<_%s_%s" basename basename) f
in
let () = (* >>(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>>_%s_%s" basename basename) f
in
let () = (* >>>(:int, :int): int *)
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>>>_%s_%s" basename basename) f
in
let () = (* ==(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Eq args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_==_%s_%s" basename basename) f
in
let () = (* !=(:int, :int): bool *)
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ne args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_!=_%s_%s" basename basename) f
in
()
in
(* for bool *)
let () =
let open Builtin_info in
let init _ = L.const_int (L.i1_type ctx.ir_context) 0 in
define_special_members bool_type_i init;
let () = (* pre!(:bool): bool *)
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_not args.(0) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_unary_pre_!_bool" f
in
& & (: , : bool ): bool
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_&&_bool_bool" f
in
()
in
let () = (* *)
let f _ _ args ctx =
assert (Array.length args = 1);
args.(0)
in
register_builtin_func "__builtin_make_ptr_from_ref" f
in
for ptr
let () =
let open Builtin_info in
let init (ty, is_addr) =
let llty = lltype_of_typeinfo ty ctx in
L.const_pointer_null llty
in
define_special_members raw_ptr_type_i init;
()
in
for ptr
let () =
let open Builtin_info in
let init (ty, is_addr) =
let llty = lltype_of_typeinfo ty ctx in
L.const_pointer_null llty
in
define_special_members untyped_raw_ptr_type_i init;
+ (: ) , : int ): )
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_in_bounds_gep args.(0) [|args.(1)|] "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_+_raw_ptr_int" f
in
pre * (: ) ): ref(T )
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value . Type ty - > ty
| _ - > failwith " [ ICE ] "
in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in*)
assert (Array.length args = 1);
args.(0)
in
register_builtin_template_func "__builtin_op_unary_pre_*_raw_ptr" f
in
= =( : raw_ptr!(T ) , : ) ): bool
let f _ _ _ args ctx =
assert (Array.length args = 2);
let res = L.build_ptrdiff args.(0) args.(1) "" ctx.Ctx.ir_builder in
let zero = L.const_int (L.i64_type ctx.ir_context) 0 in
L.build_icmp L.Icmp.Eq res zero "" ctx.Ctx.ir_builder
in
register_builtin_template_func "__builtin_op_binary_==_ptr_ptr" f
in
()
in
()
exception FailedToWriteBitcode
exception FailedToBuildBytecode
let create_object_from_ctx ctx options out_filepath =
let open Ctx in
Debug.reportf "= GENERATE_OBJECT(%s)" out_filepath;
let basic_name =
try
Filename.chop_extension out_filepath
with
| Invalid_argument _ -> out_filepath
in
(* TODO: support '-emit-llvm' option *)
output object file from module
let bin_name = basic_name ^ ".o" in
Codegen_llvm_object.emit_file bin_name ctx.ir_module Codegen_format.OfObject;
bin_name
let emit ~type_sets ~uni_map ~target_module
triple format out_filepath =
let ctx =
make_default_context ~type_sets:type_sets
~uni_map:uni_map
~target_module:(Some target_module)
in
inject_builtins ctx;
let node = target_module.Env.rel_node |> Option.get in
let _ =
let timer = Debug.Timer.create () in
Debug.reportf "= GENERATE_CODE(%s)"
out_filepath;
let _ = generate_code node FI.empty ctx in
Debug.reportf "= GENERATE_CODE(%s) %s"
out_filepath
(Debug.Timer.string_of_elapsed timer)
in
(* TODO: fix *)
let _ =
(*let triple = LT.Target.default_triple () in*)
L.set_target_triple triple ctx.Ctx.ir_module
in
let _ =
let timer = Debug.Timer.create () in
Debug.reportf "= GENERATE_OBJECT(%s)" out_filepath;
let () = Codegen_llvm_object.emit_file out_filepath ctx.Ctx.ir_module format in
Debug.reportf "= GENERATE_OBJECT(%s) %s"
out_filepath
(Debug.Timer.string_of_elapsed timer)
in
Ok out_filepath
let create_object node out_filepath ctx =
inject_builtins ctx;
debug_dump_module ctx.Ctx.ir_module;
create_object_from_ctx ctx [] out_filepath
| null | https://raw.githubusercontent.com/yutopp/rill/375b67c03ab2087d0a2a833bd9e80f3e51e2694f/rillc/_migrating/codegen_llvm.ml | ocaml | is_address or not
null terminated
&& false
implicit & trivial
implicit & non-trivial
DO NOTHING
define member variables
not packed
body
normal function
trivial function
non-trivial function
external function
generics
TODO: check undef
type
return the internal typeid as a type
regards all values are NOT references
then
else
final
make jump entry
true -> true block, false -> else block
true -> true block, false -> final block
then node
else node
pass through
make term
FIX: is_addr
return the internal typeid as a type
return the internal typeid as a type
not signed
signed
unsigned
save current position
generate code independently
resume position
retry
if type is NOT primitive, it will be represented by address
address representation of function interface
allocate storage for primitve i
move to elsewhere
normal arguments
special arguments
for special functions with immediate(primitive)
if this class returns non primitive object,
* add a parameter to receive the object
type of function
declare function
entry block (for alloca and runtime initialize)
program block
push function block
connect entry and program block
pop function
setup parameters
set name of receiver
adjust type specialized by params to normal type forms
reset position for program block
save current position
move to entry block of the function
resume position
TODO: fix
sizeof is onlymeta function
default constructor
copy constructor
copy assign
let _ =
(* defaulted but not trivial
for type
TODO: fix
==(:type, :type) onlymeta: bool
TODO: IMPLEMENT!
for int8
identity
+(:int32): uint8
+(:int32): uint32
for int32
unary- (:int); int
+(:int, :int): int
-(:int, :int): int
*(:int, :int): int
/(:int, :int): int
%(:int, :int): int
<(:int, :int): bool
>(:int, :int): bool
|(:int, :int): int
^(:int, :int): int
&(:int, :int): int
<=(:int, :int): bool
>=(:int, :int): bool
<<(:int, :int): int
>>(:int, :int): int
sign ext(arithmetic)
>>>(:int, :int): int
==(:int, :int): bool
!=(:int, :int): bool
<(:int, :int): bool
>(:int, :int): bool
|(:int, :int): int
^(:int, :int): int
&(:int, :int): int
<=(:int, :int): bool
>=(:int, :int): bool
<<(:int, :int): int
>>(:int, :int): int
>>>(:int, :int): int
==(:int, :int): bool
!=(:int, :int): bool
for bool
pre!(:bool): bool
TODO: support '-emit-llvm' option
TODO: fix
let triple = LT.Target.default_triple () in |
* Copyright yutopp 2015 - .
*
* Distributed under the Boost Software License , Version 1.0 .
* ( See accompanying file LICENSE_1_0.txt or copy at
* )
* Copyright yutopp 2015 - .
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* )
*)
open Batteries
open Stdint
module FI = Codegen_flowinfo
module L = Llvm
module TAst = Tagged_ast
type env_t = TAst.t Env.env_t
type type_info_t = env_t Type.info_t
type ctfe_val_t = type_info_t Ctfe_value.t
type type_gen_t = env_t Type.Generator.t
type builtin_func_params_t =
(type_info_t * value_form_t) list
type builtin_func_ret_t =
(type_info_t * value_form_t)
type 'ctx builtin_func_def_t =
builtin_func_params_t -> builtin_func_ret_t -> L.llvalue array -> 'ctx -> L.llvalue
type ('ty, 'ctx) builtin_template_func_def_t =
'ty Ctfe_value.t list ->
builtin_func_params_t -> builtin_func_ret_t -> L.llvalue array -> 'ctx -> L.llvalue
type ('ty, 'ctx) record_value_t =
| LLValue of (L.llvalue * value_form_t)
| LLType of L.lltype
| LLTypeGen of ('ty Ctfe_value.t list -> L.lltype)
| ElemIndex of int
| BuiltinFunc of 'ctx builtin_func_def_t
| BuiltinFuncGen of ('ty, 'ctx) builtin_template_func_def_t
| TrivialAction
type 'ty generated_value_t =
L.llvalue * 'ty * value_form_t * Codegen_flowinfo.t
module CodeGeneratorType =
struct
type ir_context_t = L.llcontext
type ir_builder_t = L.llbuilder
type ir_module_t = L.llmodule
type ir_value_t = L.llvalue
type ir_intrinsics = Codegen_llvm_intrinsics.t
type 'ty ir_cache_value_t = 'ty generated_value_t
type ('ty, 'ctx) value_t = ('ty, 'ctx) record_value_t
end
module Ctx = Codegen_context.Make(CodeGeneratorType)
type ctx_t = (env_t, Nodes.CachedNodeCounter.t, type_info_t, ctfe_val_t) Ctx.t
exception Meta_var_un_evaluatable of Unification.id_t
let agg_recever_name = "agg.receiver"
let initialize_llvm_backends =
let is_initialized = ref false in
let initialize () =
match !is_initialized with
| false ->
Llvm_X86.initialize ();
is_initialized := true
| true ->
()
in
initialize
let make_default_context ~type_sets ~uni_map ~target_module =
initialize_llvm_backends();
let ir_context = L.global_context () in
let ir_module = L.create_module ir_context "Rill" in
let ir_builder = L.builder ir_context in
let ir_intrinsics =
Codegen_llvm_intrinsics.declare_intrinsics ir_context ir_module
in
Ctx.init
~ir_context:ir_context
~ir_builder:ir_builder
~ir_module:ir_module
~ir_intrinsics:ir_intrinsics
~type_sets:type_sets
~uni_map:uni_map
~target_module:target_module
let llval_i1 v ctx =
let open Ctx in
L.const_int (L.i1_type ctx.ir_context) (if v then 1 else 0)
let llval_i32 v ctx =
let open Ctx in
L.const_int_of_string (L.i32_type ctx.ir_context) (Int32.to_string v) 10
let llval_u32 v ctx =
let open Ctx in
L.const_int_of_string (L.i32_type ctx.ir_context) (Uint32.to_string v) 10
let llval_string v ctx =
let open Ctx in
L.const_stringz ctx.ir_context v
let debug_dump_value v =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_llvalue v)
let debug_dump_module m =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_llmodule m)
let debug_dump_type t =
if do_debug_print_flag then
Debug.printf "%s" (L.string_of_lltype t)
let debug_params_and_args param_tys_and_addrs args =
if not Config.is_release then
List.iter2 (fun (ty, is_addr) llval ->
Debug.printf "type: %s / is_addr: %b"
(Type.to_string ty)
is_addr;
debug_dump_value llval
) param_tys_and_addrs (Array.to_list args);
exception Discontinue_code_generation of FI.t
let discontinue_when_expr_terminated fi =
if FI.has_terminator fi then
raise (Discontinue_code_generation fi)
let rec generate_code ?(storage=None) node prev_fi ctx : 'ty generated_value_t =
let open Ctx in
let void_v = L.undef (L.void_type ctx.ir_context) in
let void_ty = ctx.type_sets.Type_sets.ts_void_type in
let void_val fi = (void_v, void_ty, false, fi) in
if FI.has_terminator prev_fi then void_val prev_fi else
match TAst.kind_of node with
| TAst.Module (inner, pkg_names, mod_name, base_dir, _) ->
generate_code inner prev_fi ctx
| TAst.StatementList (nodes) ->
let rec gen nx (v, t, p, fi) = match nx with
| [] -> (v, t, p, fi)
| x :: xs ->
let l =
try
generate_code x fi ctx
with
| Discontinue_code_generation nfi ->
void_val nfi
in
gen xs l
in
gen nodes (void_val prev_fi)
| TAst.ExprStmt e ->
generate_code e prev_fi ctx
| TAst.VoidExprStmt e ->
let (_, _, _, fi) = generate_code e prev_fi ctx in
void_val fi
| TAst.ReturnStmt (opt_e) ->
begin
Debug.printf "ReturnStmt!!!!!!!!";
let (llval, fi) = match opt_e with
| Some e ->
let (llval, ty, is_addr, fi) = generate_code e prev_fi ctx in
discontinue_when_expr_terminated fi;
if is_heavy_object ty || ty == void_ty then
(L.build_ret_void ctx.ir_builder, fi)
else
let llval = adjust_addr_val llval ty is_addr ctx in
(L.build_ret llval ctx.ir_builder, fi)
| None ->
(L.build_ret_void ctx.ir_builder, prev_fi)
in
(llval, void_ty, false, fi |> FI.set_has_terminator true)
end
| TAst.GenericFuncDef (opt_body, Some env) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let fenv_r = Env.FunctionOp.get_record env in
Debug.printf "<><><><> Define Function: %s (%s)"
(env.Env.mangled_name |> Option.get)
(Env_system.EnvId.to_string env.Env.env_id);
let declare_current_function name =
declare_function name env ctx
in
let define_current_function kind fn_spec =
define_function kind fn_spec opt_body env prev_fi ctx
in
match fenv_r.Env.fn_detail with
| Env.FnRecordNormal (def, kind, fenv_spec) ->
begin
define_current_function kind fenv_spec;
void_val prev_fi
end
| Env.FnRecordImplicit (def, kind, fenv_spec) ->
begin
match def with
| Env.FnDefDefaulted true ->
begin
assert(List.length fenv_spec.Env.fn_spec_param_envs = 0);
let r_value = match kind with
| Env.FnKindDefaultConstructor None
| Env.FnKindCopyConstructor None
| Env.FnKindMoveConstructor None
| Env.FnKindConstructor None -> TrivialAction
| _ -> failwith "[ICE]"
in
Ctx.bind_val_to_env ctx r_value env;
void_val prev_fi
end
| Env.FnDefDefaulted false ->
begin
define_current_function kind fenv_spec;
void_val prev_fi
end
| _ -> failwith "[ICE] define implicit function"
end
| Env.FnRecordExternal (def, kind, extern_fname) ->
begin
let f = declare_current_function extern_fname in
Ctx.bind_external_function ctx extern_fname f;
void_val prev_fi
end
| Env.FnRecordBuiltin (def, kind, name) ->
begin
void_val prev_fi
end
| _ -> failwith "[ICE]"
end
| TAst.ClassDefStmt (
name, _, body, opt_attr, Some env
) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let cenv_r = Env.ClassOp.get_record env in
let member_lltypes =
let get_member_type index env =
Ctx.bind_val_to_env ctx (ElemIndex index) env;
let r = Env.VariableOp.get_record env in
let llty = lltype_of_typeinfo r.Env.var_type ctx in
llty
in
List.mapi get_member_type cenv_r.Env.cls_member_vars
in
let struct_ty =
L.named_struct_type ctx.Ctx.ir_context
(env.Env.mangled_name |> Option.get)
in
L.struct_set_body struct_ty (Array.of_list member_lltypes)
Ctx.bind_val_to_env ctx (LLType struct_ty) env;
debug_dump_type struct_ty;
let _ = generate_code body prev_fi ctx in
void_val prev_fi
end
| TAst.ExternClassDefStmt (
name, _, extern_cname, _, _, Some env
) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
Ctx.mark_env_as_defined ctx env;
let b_value = try Ctx.find_val_by_name ctx extern_cname with
| Not_found ->
failwith (Printf.sprintf "[ICE] builtin class \"%s\" is not found"
extern_cname)
in
let ty = match b_value with
| LLType ty -> ty
| LLTypeGen f ->
let cenv_r = Env.ClassOp.get_record env in
f cenv_r.Env.cls_template_vals
| _ -> failwith ""
in
Ctx.bind_val_to_env ctx (LLType ty) env;
void_val prev_fi
end
| TAst.VariableDefStmt (_, TAst.{kind = TAst.VarInit (var_init); _}, Some env) ->
if Ctx.is_env_defined ctx env then void_val prev_fi else
begin
let venv = Env.VariableOp.get_record env in
let var_type = venv.Env.var_type in
let (_, _, (_, opt_init_expr)) = var_init in
let init_expr = Option.get opt_init_expr in
let (llval, expr_ty, is_addr, cg) = generate_code init_expr prev_fi ctx in
Debug.printf "<><><>\nDefine variable: %s / is_addr: %b\n<><><>\n"
(Id_string.to_string venv.Env.var_name)
is_addr;
Type.debug_print var_type;
let var_name = Id_string.to_string venv.Env.var_name in
L.set_value_name var_name llval;
Ctx.bind_val_to_env ctx (LLValue (llval, is_addr)) env;
Ctx.mark_env_as_defined ctx env;
void_val cg
end
| TAst.MemberVariableDefStmt _ -> void_val prev_fi
| TAst.EmptyStmt -> void_val prev_fi
| TAst.GenericCallExpr (storage_ref, args, Some caller_env, Some env) ->
begin
let f_er = Env.FunctionOp.get_record env in
let {
Env.fn_detail = detail;
Env.fn_param_kinds = param_kinds;
Env.fn_return_type = ret_ty;
} = f_er in
let analyze_func_and_eval_args kind =
let (param_tys, evaled_args) = normalize_params_and_args param_kinds args in
eval_args_for_func kind storage_ref param_tys ret_ty evaled_args
caller_env prev_fi ctx
in
let call_llfunc kind f =
let (_, llargs, _, returns_addr) = analyze_func_and_eval_args kind in
let returns_heavy_obj = is_heavy_object ret_ty in
match returns_heavy_obj with
| false ->
let llval = L.build_call f llargs "" ctx.ir_builder in
(llval, returns_addr)
| true ->
let _ = L.build_call f llargs "" ctx.ir_builder in
assert (Array.length llargs > 0);
let llval = llargs.(0) in
(llval, returns_addr)
in
let fn_s_name = Env.get_name env |> Id_string.to_string in
let (llval, returns_addr) = match detail with
| Env.FnRecordNormal (_, kind, _) ->
begin
Debug.printf "gen value: debug / function normal %s / kind: %s"
fn_s_name
(Env.FunctionOp.string_of_kind kind);
let r_value = force_target_generation ctx env in
match r_value with
| LLValue (f, true) -> call_llfunc kind f
| _ -> failwith "[ICE] unexpected value"
end
| Env.FnRecordImplicit (def, kind, _) ->
begin
let open Codegen_llvm_intrinsics in
Debug.printf "gen value: debug / function implicit %s / kind: %s"
fn_s_name
(Env.FunctionOp.string_of_kind kind);
let r_value = force_target_generation ctx env in
match r_value with
| TrivialAction ->
begin
let (new_obj, is_addr) = match storage_ref with
| TAst.StoStack _
| TAst.StoAgg _
| TAst.StoArrayElem _
| TAst.StoMemberVar _ ->
let (v, _, is_addr) =
setup_storage storage_ref caller_env ctx
in
(v, is_addr)
| _ ->
TAst.debug_print_storage storage_ref;
failwith "[ICE]"
in
match kind with
| Env.FnKindDefaultConstructor None ->
begin
TODO : zero - fill
(new_obj, is_addr)
end
| Env.FnKindCopyConstructor None
| Env.FnKindMoveConstructor None ->
begin
assert (List.length args = 1);
let rhs = List.hd args in
let (llrhs, rhs_ty, is_ptr, cg) = generate_code rhs prev_fi ctx in
assert (is_ptr);
let sl = Type.size_of rhs_ty in
let al = Type.align_of rhs_ty in
let _ = ctx.intrinsics.memcpy_i32 new_obj llrhs
sl al false ctx.ir_builder
in
(new_obj, is_addr)
end
| _ -> failwith "[ICE]"
end
| LLValue (f, true) -> call_llfunc kind f
| _ -> failwith "[ICE] unexpected"
end
| Env.FnRecordExternal (def, kind, extern_name) ->
begin
Debug.printf "CALL FUNC / extern %s = \"%s\" / kind: %s\n"
fn_s_name
extern_name
(Env.FunctionOp.string_of_kind kind);
let (_, llargs, _, returns_addr) =
analyze_func_and_eval_args kind
in
let (extern_f, is_addr) =
find_llval_by_env_with_force_generation ctx env
in
assert (is_addr);
let llval = L.build_call extern_f llargs "" ctx.ir_builder in
(llval, returns_addr)
end
| Env.FnRecordBuiltin (def, kind, extern_name) ->
begin
Debug.printf "CALL FUNC / builtin %s = \"%s\" / kind: %s\n"
fn_s_name
extern_name
(Env.FunctionOp.string_of_kind kind);
TAst.debug_print_storage (storage_ref);
let (param_tys, llargs, is_addrs, returns_addr) =
analyze_func_and_eval_args kind
in
Debug.printf "== Args\n";
Array.iter debug_dump_value llargs;
Debug.printf "== %b\n" returns_addr;
let v_record = Ctx.find_val_by_name ctx extern_name in
let builtin_gen_f = match v_record with
| BuiltinFunc f -> f
| BuiltinFuncGen f ->
let fenv_r = Env.FunctionOp.get_record env in
f fenv_r.Env.fn_template_vals
| _ -> failwith "[ICE]"
in
let param_ty_and_addrs = List.combine param_tys is_addrs in
let ret_ty_and_addrs = (ret_ty, returns_addr) in
let llval = builtin_gen_f param_ty_and_addrs ret_ty_and_addrs llargs ctx in
(llval, returns_addr)
end
| Env.FnUndef -> failwith "[ICE] codegen: undefined function record"
in
Debug.printf "is_addr: %b" returns_addr;
TODO
end
| TAst.NestedExpr (lhs_node, _, rhs_ty, Some rhs_env) ->
begin
let (ll_lhs, _, is_addr, cg) = generate_code lhs_node prev_fi ctx in
assert (is_addr);
let v_record = try Ctx.find_val_by_env ctx rhs_env with
| Not_found -> failwith "[ICE] member env is not found"
in
let index = match v_record with
| ElemIndex i -> i
| _ -> failwith "[ICE]"
in
let llelem = L.build_struct_gep ll_lhs index "" ctx.ir_builder in
TODO
end
| TAst.FinalyzeExpr (opt_act_node, final_exprs) ->
let (ll_lhs, ty, is_addr, cg) = match opt_act_node with
| Some act_node -> generate_code act_node prev_fi ctx
| None -> void_val prev_fi
in
List.iter (fun n -> let _ = generate_code n prev_fi ctx in ()) final_exprs;
TODO
| TAst.SetCacheExpr (id, node) ->
let values = generate_code node prev_fi ctx in
Ctx.bind_values_to_cache_id ctx values id;
values
| TAst.GetCacheExpr id ->
Ctx.find_values_by_cache_id ctx id
| TAst.BoolLit (v, lit_ty) ->
begin
let llty = L.i1_type ctx.ir_context in
let llval = L.const_int llty (if v then 1 else 0) in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.IntLit (v, bits, signed, lit_ty) ->
begin
let llty = match bits with
| 8 -> L.i8_type ctx.ir_context
| 32 -> L.i32_type ctx.ir_context
| _ -> failwith "[ICE]"
in
let llval = L.const_int llty v in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.StringLit (str, lit_ty) ->
begin
let llty = L.pointer_type (L.i8_type ctx.ir_context) in
let llval = L.build_global_stringptr str "" ctx.ir_builder in
let (llval, is_addr) = adjust_primitive_value storage llty llval ctx in
(llval, lit_ty, is_addr, prev_fi)
end
| TAst.ArrayLit (elems, static_constructable, arr_ty) ->
begin
let arr_llty = lltype_of_typeinfo arr_ty ctx in
let ll_array_sto = build_alloca_to_entry arr_llty ctx in
if static_constructable then
begin
let (ll_elems, tys, _, _) =
generate_codes elems prev_fi ctx
in
let lit_ty = List.hd tys in
let llty = lltype_of_typeinfo lit_ty ctx in
let lit_ptr_ty = L.pointer_type llty in
let ll_array = L.const_array llty (Array.of_list ll_elems) in
let ll_array = L.define_global "" ll_array ctx.ir_module in
L.set_linkage L.Linkage.Private ll_array;
L.set_unnamed_addr true ll_array;
let llsrc = L.build_bitcast ll_array lit_ptr_ty "" ctx.ir_builder in
let lltrg = L.build_bitcast ll_array_sto lit_ptr_ty "" ctx.ir_builder in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let open Codegen_llvm_intrinsics in
let _ =
ctx.intrinsics.memcpy_i32 lltrg llsrc
size_of align_of false ctx.ir_builder
in
TODO
end
else
begin
Ctx.push_array_storage ctx (LLValue (ll_array_sto, true));
let _ = elems |> List.map (fun n -> generate_code n prev_fi ctx) in
let _ = Ctx.pop_array_storage ctx in
TODO
end
end
| TAst.GenericId (name, lt_args, Some rel_env) ->
begin
let { Env.er = er; _ } = rel_env in
match er with
| Env.Function (_, r) ->
begin
assert(List.length lt_args = 0);
Env.debug_print rel_env;
failwith @@ "[ICE] TAst.Id: function "
^ (Id_string.to_string name)
^ " // "
^ (Id_string.to_string (Env.get_name rel_env))
end
| Env.Variable (r) ->
begin
assert(List.length lt_args = 0);
Debug.printf "variable %s / type => %s\n"
(Id_string.to_string name)
(Type.to_string r.Env.var_type);
let var_llr =
try Ctx.find_val_by_env ctx rel_env with
| Not_found ->
try Ctx.find_metaval_by_env ctx rel_env with
| Not_found ->
failwith (Printf.sprintf "[ICE] variable(meta) env is not found: %s, %s"
(Meta_level.to_string rel_env.Env.meta_level)
(Type.to_string r.Env.var_type))
in
let (llval, is_addr) = match var_llr with
| LLValue v -> v
| _ -> failwith "[ICE]"
in
let ty = r.Env.var_type in
TODO
end
| Env.Class (_, r) ->
begin
let ty_attr_val_default = {
Type_attr.ta_ref_val = Type_attr.Val;
Type_attr.ta_mut = Type_attr.Const;
} in
assert (List.length r.Env.cls_generics_vals >= List.length lt_args);
let generics_args =
let rec f pl al acc =
match (pl, al) with
| ([], []) -> acc
| ([], _) -> failwith ""
| (p::px, a::ax) -> f px ax (a :: acc)
in
f r.Env.cls_generics_vals lt_args [] |> List.rev
in
let ty =
Type.Generator.generate_type ctx.type_sets.Type_sets.ts_type_gen
(Type_info.UniqueTy rel_env)
r.Env.cls_template_vals
generics_args
ty_attr_val_default
in
let itype_id = Option.get ty.Type_info.ti_id in
Debug.printf "#### LLVM: eval class: type_id = %s / %s\n"
(Int64.to_string itype_id)
(Type.to_string ty);
let llval = L.const_of_int64 (L.i64_type ctx.ir_context)
itype_id
Type_info.is_type_id_signed
in
let ty = ctx.type_sets.Type_sets.ts_type_type in
TODO
end
| Env.MetaVariable (uni_id) ->
begin
assert(List.length lt_args = 0);
let uni_map = ctx.uni_map in
Debug.printf "LLVM codegen Env.MetaVariable = %d\n" uni_id;
let (_, c) = Unification.search_value_until_terminal uni_map uni_id in
match c with
| Unification.Val v -> ctfe_val_to_llval v prev_fi ctx
| _ -> raise @@ Meta_var_un_evaluatable uni_id
end
| _ ->
begin
Env.debug_print rel_env;
failwith @@ "codegen; id " ^ (Id_string.to_string name)
end
end
| TAst.ScopeExpr (block) ->
generate_code block prev_fi ctx
| TAst.IfExpr (cond_expr, then_expr, opt_else_expr, if_ty) ->
begin
let (llcond, _, is_cond_addr, fi) = generate_code cond_expr prev_fi ctx in
discontinue_when_expr_terminated fi;
let llcond = if is_cond_addr then
L.build_load llcond "" ctx.ir_builder
else
llcond
in
let ibb = L.insertion_block ctx.ir_builder in
L.move_block_after ibb tbb;
L.move_block_after tbb ebb;
L.move_block_after ebb fbb;
let _ = match Option.is_some opt_else_expr with
| true ->
L.build_cond_br llcond tbb ebb ctx.ir_builder
| false ->
L.build_cond_br llcond tbb fbb ctx.ir_builder
in
let then_branch =
L.position_at_end tbb ctx.Ctx.ir_builder;
let (then_llval, then_ty, is_then_addr, then_fi) =
generate_code then_expr fi ctx
in
if not (FI.has_terminator then_fi) then
let then_llval = adjust_llval_form if_ty then_ty then_llval ctx in
let then_llval =
adjust_addr_val then_llval then_ty is_then_addr ctx
in
let _ = L.build_br fbb ctx.ir_builder in
let cip = L.insertion_block ctx.ir_builder in
[(then_llval, cip)]
else
[]
in
let else_branch =
match opt_else_expr with
| Some else_expr ->
L.position_at_end ebb ctx.Ctx.ir_builder;
let (else_llval, else_ty, is_else_addr, else_fi) =
generate_code else_expr fi ctx
in
if not (FI.has_terminator else_fi) then
let else_llval = adjust_llval_form if_ty else_ty else_llval ctx in
let else_llval =
adjust_addr_val else_llval else_ty is_else_addr ctx
in
let _ = L.build_br fbb ctx.ir_builder in
let cip = L.insertion_block ctx.ir_builder in
[(else_llval, cip)]
else
[]
| None ->
L.remove_block ebb;
in
let branchs = then_branch @ else_branch in
Debug.printf "IF EXPR / branchs %d" (List.length branchs);
match branchs with
| [] ->
L.remove_block fbb;
void_val (fi |> FI.set_has_terminator true)
| _ ->
L.position_at_end fbb ctx.Ctx.ir_builder;
if Type.has_same_class ctx.type_sets.Type_sets.ts_void_type if_ty then
void_val fi
else
let llret = L.build_phi branchs "" ctx.ir_builder in
let is_addr = is_address_representation if_ty in
(llret, if_ty, is_addr, fi)
end
| TAst.ForExpr (opt_decl, opt_cond, opt_step, body) ->
begin
let ip = L.insertion_block ctx.Ctx.ir_builder in
let bip = L.insert_block ctx.ir_context "loop_begin" ip in
let sip = L.insert_block ctx.ir_context "loop_step" ip in
let eip = L.insert_block ctx.ir_context "loop_end" ip in
L.move_block_after ip bip;
L.move_block_after bip sip;
L.move_block_after sip eip;
let _ = match opt_decl with
| Some decl -> ignore @@ generate_code decl prev_fi ctx
| None -> ()
in
let _ = L.build_br bip ctx.ir_builder in
L.position_at_end bip ctx.Ctx.ir_builder;
let _ = match opt_cond with
| Some cond ->
begin
let (llcond, _, _, _) = generate_code cond prev_fi ctx in
ignore @@ L.build_cond_br llcond sip eip ctx.ir_builder;
L.position_at_end sip ctx.Ctx.ir_builder;
end
| None -> L.remove_block sip;
in
ignore @@ generate_code body prev_fi ctx;
let _ = match opt_step with
| Some step ->
begin
ignore @@ generate_code step prev_fi ctx
end
| None -> ();
in
ignore @@ L.build_br bip ctx.ir_builder;
L.position_at_end eip ctx.Ctx.ir_builder;
void_val prev_fi
end
| TAst.CtxNode ty ->
begin
let itype_id = Option.get ty.Type_info.ti_id in
Debug.printf "##### type_id = %s\n" (Int64.to_string itype_id);
let llval = L.const_of_int64 (L.i64_type ctx.ir_context)
itype_id
Type_info.is_type_id_signed
in
let ty = ctx.type_sets.Type_sets.ts_type_type in
(llval, ty, false, prev_fi)
end
| TAst.StorageWrapperExpr (sto, e) ->
Debug.printf "STORAGE CHANGED\n";
TAst.debug_print_storage (!sto);
generate_code ~storage:(Some !sto) e prev_fi ctx
| TAst.Undef ty ->
let llty = lltype_of_typeinfo ty ctx in
(L.undef llty, ty, false, prev_fi)
| _ ->
failwith "cannot generate : node"
and ctfe_val_to_llval ctfe_val prev_fi ctx =
let open Ctx in
let tsets = ctx.type_sets in
match ctfe_val with
| Ctfe_value.Type (ty) ->
begin
let {
Type_info.ti_id = opt_tid;
Type_info.ti_sort = ty_sort;
} = ty in
match ty_sort with
| Type_info.UniqueTy _
| Type_info.NotDetermined _ ->
begin
match opt_tid with
| Some tid ->
let llval =
L.const_of_int64 (L.i64_type ctx.ir_context)
tid
Type_info.is_type_id_signed
in
let ty = tsets.Type_sets.ts_type_type in
(llval, ty, false, prev_fi)
| None -> failwith "[ICE] codegen_llvm : has no type_id"
end
| _-> failwith "[ICE] codegen_llvm : type"
end
| Ctfe_value.Bool b ->
let llval =
L.const_of_int64 (L.i1_type ctx.ir_context)
(Int64.of_int (Bool.to_int b))
in
let ty = !(tsets.Type_sets.ts_bool_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Int32 i32 ->
let llval =
L.const_of_int64 (L.i32_type ctx.ir_context)
(Int32.to_int64 i32)
in
let ty = !(tsets.Type_sets.ts_int32_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Uint32 i32 ->
let llval =
L.const_of_int64 (L.i32_type ctx.ir_context)
(Uint32.to_int64 i32)
in
let ty = !(tsets.Type_sets.ts_int32_type_holder) in
(llval, ty, false, prev_fi)
| Ctfe_value.Undef ud_uni_id ->
raise @@ Meta_var_un_evaluatable ud_uni_id
| _ -> failwith "[ICE]"
and is_in_other_module ctx env =
let open Ctx in
match Ctx.target_module ctx with
| None -> false
| Some target_module ->
let target_module_id = Env.get_id target_module in
let module_env_id = match Env.get_module_env_id env with
| Some e -> e
| None -> failwith "[ICE]"
in
if target_module_id = module_env_id then
false
else
not env.Env.is_instantiated
and generate_code_by_interrupt node ctx =
let opt_ip = match L.insertion_block ctx.Ctx.ir_builder with
| exception Not_found -> None
| x -> Some x
in
let _ = generate_code node FI.empty ctx in
opt_ip |> Option.may (fun ip -> L.position_at_end ip ctx.Ctx.ir_builder)
and force_target_generation ctx env =
try Ctx.find_val_by_env ctx env with
| Not_found ->
begin
let { Env.rel_node = rel_node; _ } = env in
let node = match rel_node with
| Some v -> v
| None ->
begin
Env.debug_print env;
failwith "[ICE] force_target_generation: there is no rel node"
end
in
generate_code_by_interrupt node ctx;
try Ctx.find_val_by_env ctx env with
| Not_found ->
begin
Env.debug_print env;
failwith "[ICE] force_target_generation: couldn't find target"
end
end
| _ -> failwith "yo"
and find_llval_by_env_with_force_generation ctx env =
let v_record = force_target_generation ctx env in
match v_record with
| LLValue v -> v
| _ -> failwith "[ICE] / find_llval_by_env_with_force_generation"
and find_lltype_by_env_with_force_generation ctx env =
let v_record = force_target_generation ctx env in
match v_record with
| LLType t -> t
| _ -> failwith "[ICE] / find_lltype_by_env_with_force_generation"
and register_metaval value env ctx =
let (llval, _, _, _) = ctfe_val_to_llval value FI.empty ctx in
let cv = LLValue (llval, false) in
Ctx.bind_metaval_to_env ctx cv env
and lltype_of_typeinfo ty ctx =
let open Ctx in
let cenv = Type.as_unique ty in
let ll_ty = find_lltype_by_env_with_force_generation ctx cenv in
ll_ty
and lltype_of_typeinfo_param ty ctx =
let ll_ty = lltype_of_typeinfo ty ctx in
if is_address_representation_param ty then
L.pointer_type ll_ty
else
ll_ty
and lltype_of_typeinfo_ret ty ctx =
let ll_ty = lltype_of_typeinfo ty ctx in
if is_address_representation ty then
L.pointer_type ll_ty
else
ll_ty
and is_primitive ty =
let cenv = Type.as_unique ty in
let cr = Env.ClassOp.get_record cenv in
cr.Env.cls_traits.Env.cls_traits_is_primitive
and is_always_value ty =
let cenv = Type.as_unique ty in
let cr = Env.ClassOp.get_record cenv in
cr.Env.cls_traits.Env.cls_traits_is_always_value
and is_heavy_object ty =
let {
Type_attr.ta_ref_val = rv;
Type_attr.ta_mut = mut;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Ref _ -> false
| Type_attr.Val -> is_address_representation ty
| _ -> failwith "[ICE] Unexpected : rv"
and is_address_representation ty =
let {
Type_attr.ta_ref_val = rv;
Type_attr.ta_mut = mut;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Ref _ -> not (is_always_value ty)
| Type_attr.Val ->
begin
match mut with
| Type_attr.Mutable -> true
| Type_attr.Const
| Type_attr.Immutable ->
begin
not (is_primitive ty)
end
| _ -> failwith "[ICE] Unexpected : mut"
end
| _ -> failwith "[ICE] Unexpected : rv"
and is_address_representation_param ty =
let {
Type_attr.ta_ref_val = rv;
} = ty.Type_info.ti_attr in
match rv with
| Type_attr.Val when is_primitive ty -> false
| _ -> is_address_representation ty
and adjust_llval_form' trg_ty trg_chkf src_ty src_chkf skip_alloca llval ctx =
let open Ctx in
match (trg_chkf trg_ty, src_chkf src_ty) with
| (true, true)
| (false, false) -> llval
| (true, false) ->
if skip_alloca then
llval
else
let llty = lltype_of_typeinfo trg_ty ctx in
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.ir_builder in
v
| (false, true) ->
if skip_alloca then
llval
else
L.build_load llval "" ctx.ir_builder
and adjust_llval_form trg_ty src_ty llval ctx =
Debug.printf "is_pointer rep? trg: %b(%s), src: %b(%s)"
(is_address_representation trg_ty)
(Type.to_string trg_ty)
(is_address_representation src_ty)
(Type.to_string src_ty);
debug_dump_value llval;
let trg_check_f = is_address_representation in
let src_check_f = is_address_representation in
adjust_llval_form' trg_ty trg_check_f src_ty src_check_f false llval ctx
and adjust_arg_llval_form trg_ty src_ty src_is_addr skip_alloca llval ctx =
if is_primitive trg_ty then
begin
Debug.printf "ARG: is_pointer_arg rep? trg: [%b](%s), src: [%b]<%b>(%s) ->"
(is_address_representation_param trg_ty)
(Type.to_string trg_ty)
src_is_addr
(is_address_representation src_ty)
(Type.to_string src_ty);
debug_dump_value llval;
Debug.printf "<-";
let trg_check_f = is_address_representation_param in
let src_check_f = fun _ -> src_is_addr in
adjust_llval_form' trg_ty trg_check_f src_ty src_check_f skip_alloca llval ctx
end
else
adjust_llval_form trg_ty src_ty llval ctx
and adjust_addr_val v ty is_addr ctx =
if is_address_representation ty then
v
else
if is_addr then
L.build_load v "" ctx.Ctx.ir_builder
else
v
and adjust_primitive_value storage llty llval ctx =
match storage with
| Some (TAst.StoStack _) ->
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.Ctx.ir_builder in
(v, true)
| Some TAst.StoImm
| None -> (llval, false)
| _ -> failwith "[ICE]"
and paramkinds_to_llparams params ret_ty ctx =
let returns_heavy_obj = is_heavy_object ret_ty in
let f (is_vargs, rev_tys) tp =
match tp with
| Env.FnParamKindType ty -> (is_vargs, ty :: rev_tys)
in
let (is_vargs, rev_tys) =
List.fold_left f (false, []) params
in
let param_types = rev_tys |> List.rev in
let llparams =
(if returns_heavy_obj then [ret_ty] else []) @ param_types
|> List.map (fun t -> lltype_of_typeinfo_param t ctx)
|> Array.of_list
in
(is_vargs, llparams)
and typeinfo_of_paramkind pk =
match pk with
| Env.FnParamKindType ty -> ty
and normalize_params_and_args params_info args =
adjust_param_types' params_info args []
|> List.rev |> List.split
and adjust_param_types' params_info args acc =
match (params_info, args) with
| (param_info :: px, arg :: ax) ->
begin
match param_info with
| Env.FnParamKindType ty ->
adjust_param_types' px ax ((ty, arg) :: acc)
end
| (_, []) -> acc
| ([], _) -> failwith "[ICE]"
and setup_storage sto caller_env ctx =
let open Ctx in
match sto with
| TAst.StoStack (ty) ->
begin
Debug.printf "setup_storage: StoStack ty=%s\n"
(Type.to_string ty);
let llty = lltype_of_typeinfo ty ctx in
let v = build_alloca_to_entry llty ctx in
(v, ty, true)
end
| TAst.StoAgg (ty) ->
begin
Debug.printf "setup_storage: StoAgg ty=%s\n"
(Type.to_string ty);
let ctx_env = caller_env.Env.context_env in
let (ll_fval, is_f_addr) =
find_llval_by_env_with_force_generation ctx ctx_env
in
assert (is_f_addr);
let agg = L.param ll_fval 0 in
assert (L.value_name agg = agg_recever_name);
(agg, ty, true)
end
| TAst.StoArrayElem (ty, index) ->
Debug.printf "setup_storage: StoArrayElem ty=%s\n"
(Type.to_string ty);
let array_sto = match Ctx.current_array_storage ctx with
| LLValue (v, true) -> v
| _ -> failwith "[ICE]"
in
let zero = L.const_int (L.i32_type ctx.ir_context) 0 in
let llindex = L.const_int (L.i32_type ctx.ir_context) index in
let array_elem_ptr =
L.build_in_bounds_gep array_sto
[|zero; llindex|]
""
ctx.Ctx.ir_builder
in
(array_elem_ptr, ty, true)
| TAst.StoArrayElemFromThis (ty, Some this_env, index) ->
Debug.printf "setup_storage: StoArrayElemFromThis ty=%s\n"
(Type.to_string ty);
let (array_sto, is_f_addr) =
find_llval_by_env_with_force_generation ctx this_env
in
assert (is_f_addr);
let zero = L.const_int (L.i32_type ctx.ir_context) 0 in
let llindex = L.const_int (L.i32_type ctx.ir_context) index in
let array_elem_ptr =
L.build_in_bounds_gep array_sto
[|zero; llindex|]
""
ctx.Ctx.ir_builder
in
(array_elem_ptr, ty, true)
| TAst.StoMemberVar (ty, Some venv, Some parent_fenv) ->
Debug.printf "setup_storage: StoMemberVar ty=%s\n"
(Type.to_string ty);
let (reciever_llval, is_addr) =
match Env.FunctionOp.get_kind parent_fenv with
| Env.FnKindConstructor (Some rvenv)
| Env.FnKindCopyConstructor (Some rvenv)
| Env.FnKindMoveConstructor (Some rvenv)
| Env.FnKindDefaultConstructor (Some rvenv)
| Env.FnKindDestructor (Some rvenv) ->
find_llval_by_env_with_force_generation ctx rvenv
| _ -> failwith "[ICE] no reciever"
in
assert (is_addr);
let member_index = match Ctx.find_val_by_env ctx venv with
| ElemIndex idx -> idx
| _ -> failwith "[ICE] a member variable is not found"
in
let elem_llval =
debug_dump_value reciever_llval;
Debug.printf "index = %d\n" member_index;
L.build_struct_gep reciever_llval member_index "" ctx.ir_builder
in
(elem_llval, ty, true)
| _ -> failwith "[ICE] cannot setup storage"
and generate_codes nodes fi ctx =
let (llvals, tys, is_addrs, fi) =
let f (llvals, tys, is_addrs, fi) node =
let (llval, ty, is_addr, nfi) = generate_code node fi ctx in
(llval::llvals, ty::tys, is_addr::is_addrs, nfi)
in
List.fold_left f ([], [], [], fi) nodes
in
(llvals |> List.rev, tys |> List.rev, is_addrs |> List.rev, fi)
and eval_args_for_func kind ret_sto param_types ret_ty args caller_env prev_fi ctx =
Debug.printf "eval_args_for_func: storage %s"
(TAst.string_of_stirage ret_sto);
let (llvals, arg_tys, is_addrs, fi) =
generate_codes args prev_fi ctx
in
discontinue_when_expr_terminated fi;
let (opt_head, (returns_addr, skip_alloca)) =
match ret_sto with
| TAst.StoStack _
| TAst.StoAgg _
| TAst.StoArrayElem _
| TAst.StoArrayElemFromThis _
| TAst.StoMemberVar _ ->
let (v, ty, is_addr) = setup_storage ret_sto caller_env ctx in
let sa = is_primitive ty in
(Some (v, ty, is_addr), (true, sa))
| TAst.StoImm ->
let (returns_addr, sa) =
match kind with
| Env.FnKindFree ->
(is_address_representation ret_ty, false)
| Env.FnKindMember ->
let returns_addr =
is_address_representation ret_ty
in
let skip_alloca = match param_types with
| [] -> false
| x :: _ -> is_primitive x
in
(returns_addr, skip_alloca)
| _ ->
let returns_addr = match is_addrs with
| [] -> false
| hp :: _ -> hp
in
let skip_alloca = match param_types with
| [] -> false
| x :: _ -> is_primitive x
in
(returns_addr, skip_alloca)
in
(None, (returns_addr, sa))
| _ ->
failwith (Printf.sprintf "[ICE] special arguments %s"
(TAst.string_of_stirage ret_sto))
in
let (llvals, arg_tys, is_addrs, param_types) = match opt_head with
| Some (v, ty, is_addr) ->
(v::llvals, ty::arg_tys, is_addr::is_addrs, ty::param_types)
| None ->
(llvals, arg_tys, is_addrs, param_types)
in
let llargs =
Debug.printf "conv funcs skip_alloca = %b\n" skip_alloca;
let rec make param_tys arg_tys is_addrs llvals sa =
match (param_tys, arg_tys, is_addrs, llvals) with
| ([], [], [], []) -> []
| (pt::pts, at::ats, ia::ias, lv::lvs) ->
let llarg = adjust_arg_llval_form pt at ia sa lv ctx in
llarg::(make pts ats ias lvs sa)
| _ -> failwith ""
in
make param_types arg_tys is_addrs llvals skip_alloca
in
let llargs = llargs |> Array.of_list in
(param_types, llargs, is_addrs, returns_addr)
and declare_function name fenv ctx =
let open Ctx in
let fenv_r = Env.FunctionOp.get_record fenv in
let returns_heavy_obj = is_heavy_object fenv_r.Env.fn_return_type in
let func_ret_ty =
if returns_heavy_obj then
ctx.type_sets.Type_sets.ts_void_type
else
fenv_r.Env.fn_return_type
in
let llret_ty = lltype_of_typeinfo_ret func_ret_ty ctx in
let (_, llparam_tys) =
paramkinds_to_llparams fenv_r.Env.fn_param_kinds
fenv_r.Env.fn_return_type
ctx
in
let f_ty = L.function_type llret_ty llparam_tys in
let f = L.declare_function name f_ty ctx.ir_module in
Ctx.bind_val_to_env ctx (LLValue (f, true)) fenv;
f
and setup_function_entry f ctx =
let open Ctx in
let ebb = L.append_block ctx.ir_context "entry" f in
let pbb = L.append_block ctx.ir_context "program" f in
L.position_at_end pbb ctx.ir_builder;
Ctx.push_processing_function ctx f;
(ebb, pbb)
and connect_function_entry f (ebb, pbb) ctx =
let open Ctx in
L.position_at_end ebb ctx.ir_builder;
let _ = L.build_br pbb ctx.ir_builder in
L.move_block_after ebb pbb;
let _ = Ctx.pop_processing_function ctx in
()
and define_function kind fn_spec opt_body fenv fi ctx =
let open Ctx in
let fenv_r = Env.FunctionOp.get_record fenv in
let body = Option.get opt_body in
let param_envs = fn_spec.Env.fn_spec_param_envs in
let force_inline = fn_spec.Env.fn_spec_force_inline in
let name = fenv.Env.mangled_name |> Option.get in
let f = declare_function name fenv ctx in
if force_inline then
begin
let always_inline = L.create_enum_attr ctx.ir_context "alwaysinline" 0L in
L.add_function_attr f always_inline L.AttrIndex.Function;
let no_unwind = L.create_enum_attr ctx.ir_context "nounwind" 0L in
L.add_function_attr f no_unwind L.AttrIndex.Function;
L.set_linkage L.Linkage.Private f;
()
end;
if is_in_other_module ctx fenv && not force_inline then
begin
Ctx.bind_external_function ctx name f;
()
end
else
begin
let (ebb, pbb) = setup_function_entry f ctx in
let param_envs = param_envs |> List.enum in
let raw_ll_params = L.params f |> Array.enum in
let returns_heavy_obj = is_heavy_object fenv_r.Env.fn_return_type in
if returns_heavy_obj then
begin
let opt_agg = Enum.peek raw_ll_params in
assert (Option.is_some opt_agg);
let agg = Option.get opt_agg in
let _ = match kind with
| Env.FnKindConstructor (Some venv)
| Env.FnKindCopyConstructor (Some venv)
| Env.FnKindMoveConstructor (Some venv)
| Env.FnKindDefaultConstructor (Some venv)
| Env.FnKindDestructor (Some venv) ->
let venv_r = Env.VariableOp.get_record venv in
let var_name = Id_string.to_string venv_r.Env.var_name in
L.set_value_name var_name agg;
Ctx.bind_val_to_env ctx (LLValue (agg, true)) venv
| _ ->
L.set_value_name agg_recever_name agg;
in
remove the implicit parameter from ENUM
Enum.drop 1 raw_ll_params;
end;
let adjust_param_type (ty, llval) =
let should_param_be_address = is_address_representation ty in
let actual_param_rep = is_address_representation_param ty in
match (should_param_be_address, actual_param_rep) with
| (true, false) ->
let llty = lltype_of_typeinfo ty ctx in
let v = build_alloca_to_entry llty ctx in
let _ = L.build_store llval v ctx.ir_builder in
(v, should_param_be_address)
| (true, true)
| (false, false) -> (llval, should_param_be_address)
| _ -> failwith "[ICE]"
in
let ll_params =
let param_types =
fenv_r.Env.fn_param_kinds
|> List.map typeinfo_of_paramkind
|> List.enum
in
Enum.combine (param_types, raw_ll_params)
|> Enum.map adjust_param_type
in
let declare_param_var optenv (llvar, is_addr) =
match optenv with
| Some env ->
begin
let venv = Env.VariableOp.get_record env in
let var_name = Id_string.to_string venv.Env.var_name in
L.set_value_name var_name llvar;
Ctx.bind_val_to_env ctx (LLValue (llvar, is_addr)) env
end
| None -> ()
in
Enum.iter2 declare_param_var param_envs ll_params;
L.position_at_end pbb ctx.ir_builder;
let _ = generate_code body fi ctx in
connect_function_entry f (ebb, pbb) ctx;
debug_dump_value f;
Debug.printf "generated genric function(%b): %s [%s]\n"
fenv.Env.closed
name
(fenv.Env.env_id |> Env_system.EnvId.to_string);
Llvm_analysis.assert_valid_function f
end
and build_alloca_to_entry llty ctx =
let ip =
try L.insertion_block ctx.Ctx.ir_builder with
| Not_found ->
failwith "[ICE] unexpected alloca call"
in
let current_f = Ctx.current_processing_function ctx in
let entry_block = L.entry_block current_f in
L.position_at_end entry_block ctx.Ctx.ir_builder;
let llval = L.build_alloca llty "" ctx.Ctx.ir_builder in
L.position_at_end ip ctx.Ctx.ir_builder;
llval
let regenerate_module ctx =
let ir_module = L.create_module ctx.Ctx.ir_context "Rill" in
ctx.Ctx.ir_module <- ir_module
let inject_builtins ctx =
let open Ctx in
let register_builtin_type name record =
Ctx.bind_val_to_name ctx record name;
Debug.printf " debug / \"%s\"\n " name
in
let register_builtin_func name f =
Ctx.bind_val_to_name ctx (BuiltinFunc f) name;
Debug.printf " debug / func = \"%s\"\n " name
in
let register_builtin_template_func name f =
Ctx.bind_val_to_name ctx (BuiltinFuncGen f) name;
Debug.printf " debug / func = \"%s\"\n " name
in
type is represented as int64 in this context .
* It donates ID of type in the type generator
* It donates ID of type in the type generator
*)
begin
let open Builtin_info in
* Builtin types
* Builtin types
*)
register_builtin_type type_type_i.internal_name
(LLType (L.i64_type ctx.ir_context));
register_builtin_type void_type_i.internal_name
(LLType (L.void_type ctx.ir_context));
register_builtin_type bool_type_i.internal_name
(LLType (L.i1_type ctx.ir_context));
register_builtin_type uint8_type_i.internal_name
(LLType (L.i8_type ctx.ir_context));
register_builtin_type int32_type_i.internal_name
(LLType (L.i32_type ctx.ir_context));
register_builtin_type uint32_type_i.internal_name
(LLType (L.i32_type ctx.ir_context));
register_builtin_type raw_ptr_type_i.internal_name
(LLTypeGen (
fun template_args ->
begin
assert (List.length template_args = 1);
let ty_ct_val = List.nth template_args 0 in
let ty_val = match ty_ct_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let elem_ty = lltype_of_typeinfo ty_val ctx in
L.pointer_type elem_ty
end
));
register_builtin_type untyped_raw_ptr_type_i.internal_name
(LLType (L.pointer_type (L.i8_type ctx.ir_context)));
register_builtin_type array_type_i.internal_name
(LLTypeGen (
fun template_args ->
begin
assert (List.length template_args = 2);
let ty_ct_val = List.nth template_args 0 in
let len_ct_val = List.nth template_args 1 in
let ty_val = match ty_ct_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let len_val = match len_ct_val with
| Ctfe_value.Uint32 i32 -> i32
| _ -> failwith "[ICE]"
in
let llty = lltype_of_typeinfo ty_val ctx in
let len = Uint32.to_int len_val in
L.array_type llty len
end
));
end;
* Builtin functions
* Builtin functions
*)
let () =
let f template_args _ _ _args ctx =
assert (List.length template_args = 1);
assert (Array.length _args = 0);
let ty = match List.nth template_args 0 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
llval_u32 (Type.size_of ty) ctx
in
register_builtin_template_func "__builtin_sizeof" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let type_s = Type.to_string ty in
L.build_global_stringptr type_s "" ctx.ir_builder
in
register_builtin_template_func "__builtin_stringof" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let llty = lltype_of_typeinfo ty ctx in
let llptrty = L.pointer_type llty in
assert (Array.length args = 1);
L.build_bitcast args.(0) llptrty "" ctx.ir_builder
in
register_builtin_template_func "__builtin_unsafe_ptr_cast" f
in
let () =
let f template_args _ _ args ctx =
assert (List.length template_args = 2);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in
let llty = lltype_of_typeinfo ty ctx in
let llptrty = L.pointer_type llty in
assert (Array.length args = 1);
L.build_pointercast args.(0) llptrty "" ctx.ir_builder
in
register_builtin_template_func "__builtin_take_address_from_array" f
in
let () =
let f param_tys_and_addrs _ args ctx =
let open Codegen_llvm_intrinsics in
assert (Array.length args = 1);
assert (List.length param_tys_and_addrs = 1);
let (arr_ty, _) = List.hd param_tys_and_addrs in
let to_obj = args.(0) in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let _ =
ctx.intrinsics.memset_i32 to_obj (Int8.of_int 0)
size_of align_of false ctx.ir_builder
in
to_obj
in
let open Builtin_info in
register_builtin_func
(make_builtin_default_ctor_name array_type_i.internal_name) f
in
let () =
let f param_tys_and_addrs _ args ctx =
let open Codegen_llvm_intrinsics in
assert (Array.length args = 2);
assert (List.length param_tys_and_addrs = 2);
let (arr_ty, _) = List.hd param_tys_and_addrs in
let to_obj = args.(0) in
let from_obj = args.(1) in
let size_of = Type.size_of arr_ty in
let align_of = Type.align_of arr_ty in
let _ =
ctx.intrinsics.memcpy_i32 to_obj from_obj
size_of align_of false ctx.ir_builder
in
to_obj
in
let open Builtin_info in
register_builtin_func
(make_builtin_copy_ctor_name array_type_i.internal_name) f
in
let define_special_members builtin_info init_val_gen =
let open Builtin_info in
let normalize_store_value param_tys_and_addrs args =
assert (List.length param_tys_and_addrs = Array.length args);
let (_, rhs_is_addr) = List.at param_tys_and_addrs 1 in
Debug.printf "is_addr? => %b" rhs_is_addr;
debug_dump_value args.(1);
if rhs_is_addr then
L.build_load args.(1) "" ctx.ir_builder
else
args.(1)
in
let f param_tys_and_addrs ret_ty_and_addr args ctx =
assert (List.length param_tys_and_addrs = Array.length args);
let v = init_val_gen ret_ty_and_addr in
match Array.length args with
| 1 ->
let _ = L.build_store v args.(0) ctx.ir_builder in args.(0)
| 0 -> v
| _ -> failwith ""
in
register_builtin_func
(make_builtin_default_ctor_name builtin_info.internal_name) f
in
let f param_tys_and_addrs _ args ctx =
assert (List.length param_tys_and_addrs = Array.length args);
Debug.printf "copy ctor: %s (%d)"
(builtin_info.internal_name)
(Array.length args);
List.iter (fun (ty, is_addr) -> Debug.printf "ty %s: %b"
(Type.to_string ty)
is_addr)
param_tys_and_addrs;
Array.iter debug_dump_value args;
match Array.length args with
| 2 ->
let store_val = normalize_store_value param_tys_and_addrs args in
let _ = L.build_store store_val args.(0) ctx.ir_builder in
args.(0)
| 1 -> args.(0)
| _ -> failwith ""
in
register_builtin_func
(make_builtin_copy_ctor_name builtin_info.internal_name) f
in
let f param_tys_and_addrs _ args ctx =
assert (Array.length args = 2);
Debug.printf "copy assign: %s (args length = %d)"
(builtin_info.internal_name)
(Array.length args);
debug_params_and_args param_tys_and_addrs args;
let store_val = normalize_store_value param_tys_and_addrs args in
L.build_store store_val args.(0) ctx.Ctx.ir_builder
in
register_builtin_func
(make_builtin_copy_assign_name builtin_info.internal_name) f
in
()
in
let f args ctx =
assert (Array.length args = 2);
failwith ""
in
register_builtin_func "__builtin_array_type_copy_ctor" f
in*)
let () =
let open Builtin_info in
let init _ = L.const_int (L.i64_type ctx.ir_context) 0 in
define_special_members type_type_i init;
let f template_args _ _ _args ctx =
assert (List.length template_args = 2);
assert (Array.length _args = 0);
let lhs_ty = match List.nth template_args 0 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
let rhs_ty = match List.nth template_args 1 with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE] failed to get a ctfed value"
in
let _ = lhs_ty in
let _ = rhs_ty in
llval_i1 (true) ctx
in
register_builtin_template_func "__builtin_op_binary_==_type_type" f
in
()
in
let () =
let open Builtin_info in
let init _ = L.const_int (L.i8_type ctx.ir_context) 0 in
define_special_members uint8_type_i init;
()
in
let () =
let open Builtin_info in
let f _ _ args ctx =
assert (Array.length args = 1);
args.(0)
in
register_builtin_func "__builtin_identity" f
in
+ (: ):
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i8_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_uint32_to_uint8" f
in
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i8_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_int32_to_uint8" f
in
+ (: ): int32
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_intcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_uint8_to_int32" f
in
let f _ _ args ctx =
assert (Array.length args = 1);
unsigned , use zext
L.build_zext_or_bitcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_int32_to_uint32" f
in
+ (: ): uint32
let f _ _ args ctx =
assert (Array.length args = 1);
unsigned , use zext
L.build_zext_or_bitcast args.(0) (L.i32_type ctx.ir_context) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_cast_from_bool_to_uint32" f
in
()
in
let () =
let open Builtin_info in
let init _ = L.const_int (L.i32_type ctx.ir_context) 0 in
define_special_members int32_type_i init;
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_neg args.(0) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_unary_pre_-_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_add args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_+_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sub args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_-_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_mul args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_*_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sdiv args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_/_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_srem args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_%_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Slt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sgt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_>_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_or args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_|_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_xor args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_^_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_&_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sle args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<=_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Sge args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_>=_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_shl args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_<<_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
in
register_builtin_func "__builtin_op_binary_>>_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func "__builtin_op_binary_>>>_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Eq args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_==_int_int" f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ne args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_!=_int_int" f
in
()
in
for uint32
let () =
let open Builtin_info in
let basename = "uint" in
let init _ = L.const_int (L.i32_type ctx.ir_context) 0 in
define_special_members uint32_type_i init;
+ (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_add args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_+_%s_%s" basename basename) f
in
-(:INT , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_sub args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_-_%s_%s" basename basename) f
in
* (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_mul args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_*_%s_%s" basename basename) f
in
/(:INT , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_udiv args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_/_%s_%s" basename basename) f
in
% (: , : ): INT
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_urem args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_%%_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ult args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ugt args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_or args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_|_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_xor args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_^_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_&_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ule args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<=_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Uge args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>=_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_shl args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_<<_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>>_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
zero ext(logical )
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_>>>_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Eq args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_==_%s_%s" basename basename) f
in
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_icmp L.Icmp.Ne args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func
(Printf.sprintf "__builtin_op_binary_!=_%s_%s" basename basename) f
in
()
in
let () =
let open Builtin_info in
let init _ = L.const_int (L.i1_type ctx.ir_context) 0 in
define_special_members bool_type_i init;
let f _ _ args ctx =
assert (Array.length args = 1);
L.build_not args.(0) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_unary_pre_!_bool" f
in
& & (: , : bool ): bool
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_and args.(0) args.(1) "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_&&_bool_bool" f
in
()
in
let f _ _ args ctx =
assert (Array.length args = 1);
args.(0)
in
register_builtin_func "__builtin_make_ptr_from_ref" f
in
for ptr
let () =
let open Builtin_info in
let init (ty, is_addr) =
let llty = lltype_of_typeinfo ty ctx in
L.const_pointer_null llty
in
define_special_members raw_ptr_type_i init;
()
in
for ptr
let () =
let open Builtin_info in
let init (ty, is_addr) =
let llty = lltype_of_typeinfo ty ctx in
L.const_pointer_null llty
in
define_special_members untyped_raw_ptr_type_i init;
+ (: ) , : int ): )
let f _ _ args ctx =
assert (Array.length args = 2);
L.build_in_bounds_gep args.(0) [|args.(1)|] "" ctx.Ctx.ir_builder
in
register_builtin_func "__builtin_op_binary_+_raw_ptr_int" f
in
pre * (: ) ): ref(T )
let f template_args _ _ args ctx =
assert (List.length template_args = 1);
let ty_val = List.nth template_args 0 in
let ty = match ty_val with
| Ctfe_value . Type ty - > ty
| _ - > failwith " [ ICE ] "
in
let ty = match ty_val with
| Ctfe_value.Type ty -> ty
| _ -> failwith "[ICE]"
in*)
assert (Array.length args = 1);
args.(0)
in
register_builtin_template_func "__builtin_op_unary_pre_*_raw_ptr" f
in
= =( : raw_ptr!(T ) , : ) ): bool
let f _ _ _ args ctx =
assert (Array.length args = 2);
let res = L.build_ptrdiff args.(0) args.(1) "" ctx.Ctx.ir_builder in
let zero = L.const_int (L.i64_type ctx.ir_context) 0 in
L.build_icmp L.Icmp.Eq res zero "" ctx.Ctx.ir_builder
in
register_builtin_template_func "__builtin_op_binary_==_ptr_ptr" f
in
()
in
()
exception FailedToWriteBitcode
exception FailedToBuildBytecode
let create_object_from_ctx ctx options out_filepath =
let open Ctx in
Debug.reportf "= GENERATE_OBJECT(%s)" out_filepath;
let basic_name =
try
Filename.chop_extension out_filepath
with
| Invalid_argument _ -> out_filepath
in
output object file from module
let bin_name = basic_name ^ ".o" in
Codegen_llvm_object.emit_file bin_name ctx.ir_module Codegen_format.OfObject;
bin_name
let emit ~type_sets ~uni_map ~target_module
triple format out_filepath =
let ctx =
make_default_context ~type_sets:type_sets
~uni_map:uni_map
~target_module:(Some target_module)
in
inject_builtins ctx;
let node = target_module.Env.rel_node |> Option.get in
let _ =
let timer = Debug.Timer.create () in
Debug.reportf "= GENERATE_CODE(%s)"
out_filepath;
let _ = generate_code node FI.empty ctx in
Debug.reportf "= GENERATE_CODE(%s) %s"
out_filepath
(Debug.Timer.string_of_elapsed timer)
in
let _ =
L.set_target_triple triple ctx.Ctx.ir_module
in
let _ =
let timer = Debug.Timer.create () in
Debug.reportf "= GENERATE_OBJECT(%s)" out_filepath;
let () = Codegen_llvm_object.emit_file out_filepath ctx.Ctx.ir_module format in
Debug.reportf "= GENERATE_OBJECT(%s) %s"
out_filepath
(Debug.Timer.string_of_elapsed timer)
in
Ok out_filepath
let create_object node out_filepath ctx =
inject_builtins ctx;
debug_dump_module ctx.Ctx.ir_module;
create_object_from_ctx ctx [] out_filepath
|
6ab39621c0b08fadabe5c1afecb214b4b91164c55598dd3ec5dc545dc5eea537 | hiroshi-unno/coar | treeAutomaton.ml | open Core
open Common.Ext
(** Tree automata *)
type ('sym, 'lab) t =
| Leaf
| Label of 'sym * 'lab * 'lab
| Alter of ('sym, 'lab) t * ('sym, 'lab) t
| Emp
let rec pr ppf = function
| Leaf ->
Format.fprintf ppf "()"
| Label (id1, id2, id3) ->
Format.fprintf ppf "%a(%a, %a)" String.pr id1 String.pr id2 String.pr id3
| Alter (u1, u2) ->
Format.fprintf ppf "(%a | %a)" pr u1 pr u2
| Emp ->
()
let rec rename rn = function
| Leaf -> Leaf
| Label (id1, id2, id3) ->
Label (id1,
(try List.Assoc.find_exn ~equal:String.equal rn id2 with Not_found_s _ -> id2),
(try List.Assoc.find_exn ~equal:String.equal rn id3 with Not_found_s _ -> id3))
| Alter (u1, u2) -> Alter (rename rn u1, rename rn u2)
| Emp -> Emp
let rec next_ids = function
| Leaf -> []
| Label (_id1, id2, id3) -> [id2; id3]
| Alter (u1, u2) -> (*List.unique*) (next_ids u1 @ next_ids u2)
| Emp -> []
let set_reachable ids next =
let diff l1 l2 =
List.filter ~f:(fun x -> not @@ List.mem ~equal:Stdlib.(=) l2 x) l1
in
let rec loop ids nids =
let ids' = ids @ nids in
let nids' = diff (List.unique (List.concat_map ~f:next nids)) ids' in
if List.is_empty nids' then ids' else loop ids' nids'
in
loop [] ids
let assoc id rs =
try List.Assoc.find_exn ~equal:String.equal rs id with Not_found_s _ ->
failwith ("state " ^ id ^ " not found")
(* without changing order*)
let remove_unreachable ids rs =
let reachable_ids =
set_reachable (List.unique ids) (fun id -> next_ids (assoc id rs))
in
List.filter ~f:(fun (id, _) -> List.mem ~equal:String.equal reachable_ids id) rs
let reachable id rs =
List.map ~f:(fun id -> id, assoc id rs)
(set_reachable [id] (fun id -> next_ids (assoc id rs)))
let rec minimize rs =
let rec f rs nece =
match rs with
| [] -> nece
| (id, u) :: rs ->
try
let (id', _) =
List.find_exn
~f:(fun (id', u') -> Stdlib.(rename [id, id'] u = rename [id, id'] u'))
nece
in
(* Format.printf "= %a@," pr u; *)
let rn = [id, id'] in
f (List.map ~f:(fun (id, u) -> id, rename rn u) rs)
(List.map ~f:(fun (id, u) -> id, rename rn u) nece)
with Not_found_s _ ->
Format.printf " < > % a@ , " pr u ;
f rs ((id, u) :: nece)
in
let rs' = List.rev (f rs []) in
if List.length rs' < List.length rs then minimize rs' else rs'
let canonize u =
let rec aux u =
match u with
| Leaf | Label (_, _, _) -> [u]
| Alter (u1, u2) ->
let x = aux u1 @ aux u2 in
let x' = List.unique x in
(*let _ = assert (x = x') in*)
x'
| Emp -> []
in
let xs = List.sort ~compare:Stdlib.compare @@ aux u in
match xs with
| [] -> failwith "canonize"
| [x] -> x
| x :: xs -> List.fold_left ~init:x xs ~f:(fun x y -> Alter (x, y))
let rec of_table_aux = function
| Leaf -> ["leaf", []]
| Label (id1, id2, id3) -> [id1, [id2; id3]]
| Alter (u1, u2) -> of_table_aux u1 @ of_table_aux u2
| Emp -> failwith "TreeAutomaton.of_table_aux"
let of_table rs = List.map ~f:(fun (id, u) -> id, of_table_aux u) rs
let make_table xs = List.classify xs
let pr_table ppf trs =
List.iter trs ~f:(fun (id1, xs) ->
List.iter xs ~f:(fun (id2, ids) ->
Format.fprintf ppf "%a %a -> %a.@\n"
String.pr id1 String.pr id2 (List.pr String.pr " ") ids))
let next_ids_table = List.concat_map ~f:snd
(* without changing order*)
let remove_unreachable_table ids trs =
let reachable_ids =
set_reachable (List.unique ids) (fun id -> next_ids_table (assoc id trs))
in
List.filter ~f:(fun (id, _) -> List.mem ~equal:String.equal reachable_ids id) trs
let reachable_table id trs =
List.map ~f:(fun id -> id, assoc id trs)
(set_reachable [id] (fun id -> next_ids_table (assoc id trs)))
let number_of_states trs =
List.length @@ List.unique @@ List.map ~f:fst trs
let parse_file filename =
let inchan = open_in filename in
let lb = in
let _ = lb . Lexing.lex_curr_p < -
{ Lexing.pos_fname = Filename.basename filename ; Lexing.pos_lnum = 1 ; = 0 ; Lexing.pos_bol = 0 } in
let tl = Parser.xmltypedefs Lexer.token lb in
let _ = in
tl
let parse_string str =
let lb = in
let _ = lb . Lexing.lex_curr_p < -
{ Lexing.pos_fname = " " ; Lexing.pos_lnum = 1 ; = 0 ; Lexing.pos_bol = 0 } in
Parser.xmltypedefs Lexer.token lb
let _ =
let filename =
if Array.length Sys.argv = 2 then
Sys.argv.(1 )
else
failwith " invalid arguments "
in
let env = parse_file filename in
Format.printf " @[<v > " ;
let env = RegTreeExp.elim_kleene_env env in
let env = RegTreeExp.elim_option_env env in
( *
List.iter ( fun ( i d , t ) - > Format.printf " type % s = % a@ , " i d RegTreeExp.pr t ) env ;
Format.printf " @ , " ;
let parse_file filename =
let inchan = open_in filename in
let lb = Lexing.from_channel inchan in
let _ = lb.Lexing.lex_curr_p <-
{ Lexing.pos_fname = Filename.basename filename; Lexing.pos_lnum = 1; Lexing.pos_cnum = 0; Lexing.pos_bol = 0 } in
let tl = Parser.xmltypedefs Lexer.token lb in
let _ = close_in inchan in
tl
let parse_string str =
let lb = Lexing.from_string str in
let _ = lb.Lexing.lex_curr_p <-
{ Lexing.pos_fname = ""; Lexing.pos_lnum = 1; Lexing.pos_cnum = 0; Lexing.pos_bol = 0 } in
Parser.xmltypedefs Lexer.token lb
let _ =
let filename =
if Array.length Sys.argv = 2 then
Sys.argv.(1)
else
failwith "invalid arguments"
in
let env = parse_file filename in
Format.printf "@[<v>";
let env = RegTreeExp.elim_kleene_env env in
let env = RegTreeExp.elim_option_env env in
(*
List.iter (fun (id, t) -> Format.printf "type %s = %a@," id RegTreeExp.pr t) env;
Format.printf "@,";
*)
let rs = RegTreeExp.to_ta_env env env [] [] in
let rs = List.map (fun (id, u) -> id, TreeAutomaton.canonize u) rs in
let (id, _) = List.hd rs in
let rs = TreeAutomaton.remove_unreachable [id] rs in
(*
List.iter (fun (id, u) -> Format.printf "%s -> %a@," id TreeAutomaton.pr u) rs;
*)
let rs = TreeAutomaton.minimize rs in
let rn = List.mapi (fun i (id, _) -> id, "q" ^ (string_of_int i)) rs in
let rs = List.map (fun (id, u) -> List.assoc id rn, TreeAutomaton.rename rn u) rs in
(*
List.iter (fun (id, u) -> Format.printf "%s -> %a@," id TreeAutomaton.pr u) rs;
*)
let trs = TreeAutomaton.of_table rs in
let trs_out = trs in
Format.printf "%%BEGINA@,";
Format.printf "%a" TreeAutomaton.pr_table trs_out;
Format.printf "%%ENDA@,";
Format.printf "@]"
*)
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/automata/treeAutomaton.ml | ocaml | * Tree automata
List.unique
without changing order
Format.printf "= %a@," pr u;
let _ = assert (x = x') in
without changing order
List.iter (fun (id, t) -> Format.printf "type %s = %a@," id RegTreeExp.pr t) env;
Format.printf "@,";
List.iter (fun (id, u) -> Format.printf "%s -> %a@," id TreeAutomaton.pr u) rs;
List.iter (fun (id, u) -> Format.printf "%s -> %a@," id TreeAutomaton.pr u) rs;
| open Core
open Common.Ext
type ('sym, 'lab) t =
| Leaf
| Label of 'sym * 'lab * 'lab
| Alter of ('sym, 'lab) t * ('sym, 'lab) t
| Emp
let rec pr ppf = function
| Leaf ->
Format.fprintf ppf "()"
| Label (id1, id2, id3) ->
Format.fprintf ppf "%a(%a, %a)" String.pr id1 String.pr id2 String.pr id3
| Alter (u1, u2) ->
Format.fprintf ppf "(%a | %a)" pr u1 pr u2
| Emp ->
()
let rec rename rn = function
| Leaf -> Leaf
| Label (id1, id2, id3) ->
Label (id1,
(try List.Assoc.find_exn ~equal:String.equal rn id2 with Not_found_s _ -> id2),
(try List.Assoc.find_exn ~equal:String.equal rn id3 with Not_found_s _ -> id3))
| Alter (u1, u2) -> Alter (rename rn u1, rename rn u2)
| Emp -> Emp
let rec next_ids = function
| Leaf -> []
| Label (_id1, id2, id3) -> [id2; id3]
| Emp -> []
let set_reachable ids next =
let diff l1 l2 =
List.filter ~f:(fun x -> not @@ List.mem ~equal:Stdlib.(=) l2 x) l1
in
let rec loop ids nids =
let ids' = ids @ nids in
let nids' = diff (List.unique (List.concat_map ~f:next nids)) ids' in
if List.is_empty nids' then ids' else loop ids' nids'
in
loop [] ids
let assoc id rs =
try List.Assoc.find_exn ~equal:String.equal rs id with Not_found_s _ ->
failwith ("state " ^ id ^ " not found")
let remove_unreachable ids rs =
let reachable_ids =
set_reachable (List.unique ids) (fun id -> next_ids (assoc id rs))
in
List.filter ~f:(fun (id, _) -> List.mem ~equal:String.equal reachable_ids id) rs
let reachable id rs =
List.map ~f:(fun id -> id, assoc id rs)
(set_reachable [id] (fun id -> next_ids (assoc id rs)))
let rec minimize rs =
let rec f rs nece =
match rs with
| [] -> nece
| (id, u) :: rs ->
try
let (id', _) =
List.find_exn
~f:(fun (id', u') -> Stdlib.(rename [id, id'] u = rename [id, id'] u'))
nece
in
let rn = [id, id'] in
f (List.map ~f:(fun (id, u) -> id, rename rn u) rs)
(List.map ~f:(fun (id, u) -> id, rename rn u) nece)
with Not_found_s _ ->
Format.printf " < > % a@ , " pr u ;
f rs ((id, u) :: nece)
in
let rs' = List.rev (f rs []) in
if List.length rs' < List.length rs then minimize rs' else rs'
let canonize u =
let rec aux u =
match u with
| Leaf | Label (_, _, _) -> [u]
| Alter (u1, u2) ->
let x = aux u1 @ aux u2 in
let x' = List.unique x in
x'
| Emp -> []
in
let xs = List.sort ~compare:Stdlib.compare @@ aux u in
match xs with
| [] -> failwith "canonize"
| [x] -> x
| x :: xs -> List.fold_left ~init:x xs ~f:(fun x y -> Alter (x, y))
let rec of_table_aux = function
| Leaf -> ["leaf", []]
| Label (id1, id2, id3) -> [id1, [id2; id3]]
| Alter (u1, u2) -> of_table_aux u1 @ of_table_aux u2
| Emp -> failwith "TreeAutomaton.of_table_aux"
let of_table rs = List.map ~f:(fun (id, u) -> id, of_table_aux u) rs
let make_table xs = List.classify xs
let pr_table ppf trs =
List.iter trs ~f:(fun (id1, xs) ->
List.iter xs ~f:(fun (id2, ids) ->
Format.fprintf ppf "%a %a -> %a.@\n"
String.pr id1 String.pr id2 (List.pr String.pr " ") ids))
let next_ids_table = List.concat_map ~f:snd
let remove_unreachable_table ids trs =
let reachable_ids =
set_reachable (List.unique ids) (fun id -> next_ids_table (assoc id trs))
in
List.filter ~f:(fun (id, _) -> List.mem ~equal:String.equal reachable_ids id) trs
let reachable_table id trs =
List.map ~f:(fun id -> id, assoc id trs)
(set_reachable [id] (fun id -> next_ids_table (assoc id trs)))
let number_of_states trs =
List.length @@ List.unique @@ List.map ~f:fst trs
let parse_file filename =
let inchan = open_in filename in
let lb = in
let _ = lb . Lexing.lex_curr_p < -
{ Lexing.pos_fname = Filename.basename filename ; Lexing.pos_lnum = 1 ; = 0 ; Lexing.pos_bol = 0 } in
let tl = Parser.xmltypedefs Lexer.token lb in
let _ = in
tl
let parse_string str =
let lb = in
let _ = lb . Lexing.lex_curr_p < -
{ Lexing.pos_fname = " " ; Lexing.pos_lnum = 1 ; = 0 ; Lexing.pos_bol = 0 } in
Parser.xmltypedefs Lexer.token lb
let _ =
let filename =
if Array.length Sys.argv = 2 then
Sys.argv.(1 )
else
failwith " invalid arguments "
in
let env = parse_file filename in
Format.printf " @[<v > " ;
let env = RegTreeExp.elim_kleene_env env in
let env = RegTreeExp.elim_option_env env in
( *
List.iter ( fun ( i d , t ) - > Format.printf " type % s = % a@ , " i d RegTreeExp.pr t ) env ;
Format.printf " @ , " ;
let parse_file filename =
let inchan = open_in filename in
let lb = Lexing.from_channel inchan in
let _ = lb.Lexing.lex_curr_p <-
{ Lexing.pos_fname = Filename.basename filename; Lexing.pos_lnum = 1; Lexing.pos_cnum = 0; Lexing.pos_bol = 0 } in
let tl = Parser.xmltypedefs Lexer.token lb in
let _ = close_in inchan in
tl
let parse_string str =
let lb = Lexing.from_string str in
let _ = lb.Lexing.lex_curr_p <-
{ Lexing.pos_fname = ""; Lexing.pos_lnum = 1; Lexing.pos_cnum = 0; Lexing.pos_bol = 0 } in
Parser.xmltypedefs Lexer.token lb
let _ =
let filename =
if Array.length Sys.argv = 2 then
Sys.argv.(1)
else
failwith "invalid arguments"
in
let env = parse_file filename in
Format.printf "@[<v>";
let env = RegTreeExp.elim_kleene_env env in
let env = RegTreeExp.elim_option_env env in
let rs = RegTreeExp.to_ta_env env env [] [] in
let rs = List.map (fun (id, u) -> id, TreeAutomaton.canonize u) rs in
let (id, _) = List.hd rs in
let rs = TreeAutomaton.remove_unreachable [id] rs in
let rs = TreeAutomaton.minimize rs in
let rn = List.mapi (fun i (id, _) -> id, "q" ^ (string_of_int i)) rs in
let rs = List.map (fun (id, u) -> List.assoc id rn, TreeAutomaton.rename rn u) rs in
let trs = TreeAutomaton.of_table rs in
let trs_out = trs in
Format.printf "%%BEGINA@,";
Format.printf "%a" TreeAutomaton.pr_table trs_out;
Format.printf "%%ENDA@,";
Format.printf "@]"
*)
|
6e98ec049def29cc45cd6cd2ea59620f07be7910e4639aa53502b7aba5dd6a57 | soegaard/racket-cas | diff.rkt | #lang racket/base
(provide diff ; (diff u x) differentiate the expression u with respect to the variable x
Diff)
;;;
;;; Differentiation
;;;
(require racket/format racket/match
(for-syntax racket/base racket/syntax syntax/parse)
"core.rkt" "math-match.rkt" "relational-operators.rkt" "trig.rkt")
(module+ test
(require rackunit math/bigfloat)
(define x 'x) (define y 'y) (define z 'z))
(define (1/sqrt:1-u^2 u)
(⊘ 1 (Sqrt (⊖ 1 (Sqr u)))))
(define (diff u x)
(define (d u) (diff u x))
(define (products us)
; example: (products '(a b c)) = '((* a b c) (* b c) c)
(match us
['() '()]
[(list u) (list u)]
[(cons u us) (define ps (products us))
(cons (⊗ u (car ps)) ps)]))
(math-match u
[r 0]
[y #:when (eq? x y) 1]
[y 0]
[(⊕ v w) (⊕ (d v) (d w))]
[(⊗ v w) (match u
[(list '* v w) (⊕ (⊗ (d v) w) (⊗ v (d w)))]
[(list '* vs ...)
(let loop ([sum 0]
[us '()]
[us⊗ 1]
[ws vs]
[ws⊗s (products vs)])
; invariant: (append us ws) = vs
invariant : ( ⊗ us⊗ ( first ws⊗s ) ) = u
(match ws
['() sum]
[(list w) (⊕ (⊗ (d w) us⊗) sum)]
[(cons w ws) (loop (⊕ (⊗ (d w) (⊗ us⊗ (cadr ws⊗s))) sum)
(cons u w) (⊗ us⊗ w) ws (cdr ws⊗s))]))])]
[(Expt u r) (⊗ r (Expt u (- r 1)) (d u))]
[(Expt @e u) (⊗ (Exp u) (d u))]
[(Expt r y) #:when (and (positive? r) (equal? y x)) (⊗ (Expt r x) (Ln r))]
[(Expt u v) (diff (Exp (⊗ v (Ln u))) x)] ; assumes u positive
; [(Exp u) (⊗ (Exp u) (d u))]
[(Ln u) (⊗ (⊘ 1 u) (d u))]
[(Cos u) (⊗ (⊖ 0 (Sin u)) (d u))]
[(Sin u) (⊗ (Cos u) (d u))]
[(Asin u) (1/sqrt:1-u^2 u)]
[(Acos u) (⊖ (1/sqrt:1-u^2 u))]
[(Atan u) (⊘ 1 (⊕ (Sqr x) 1))]
[(Si x) (Sinc x)]
[(Ci x) (⊘ (Cos x) x)]
[(app: f us) #:when (symbol? f)
(match us
[(list u) (cond [(eq? u x) (Diff `(,f ,x) x)]
[else (⊗ `(app (derivative ,f ,x) ,u) (d u))])] ; xxx
[_ `(diff (,f ,@us) ,x)])] ; xxx
[_ (error 'diff (~a "got: " u " wrt " x))]))
(define (Diff: u [x 'x])
(define D Diff:)
(math-match u
[(Equal u1 u2) (Equal (D u1 x) (D u2 x))]
[_ (list 'diff u x)]))
(define-match-expander Diff
(λ (stx) (syntax-parse stx [(_ u x) #'(list 'diff u x)]))
(λ (stx) (syntax-parse stx [(_ u x) #'(Diff: u)] [_ (identifier? stx) #'Diff:])))
(module+ test
(displayln "TEST - diff")
(check-equal? (diff 1 x) 0)
(check-equal? (diff x x) 1)
(check-equal? (diff y x) 0)
(check-equal? (diff (⊗ x x) x) '(* 2 x))
(check-equal? (diff (⊗ x x x) x) '(* 3 (expt x 2)))
(check-equal? (diff (⊗ x x x x) x) '(* 4 (expt x 3)))
(check-equal? (diff (⊕ (⊗ 5 x) (⊗ x x)) x) '(+ 5 (* 2 x)))
(check-equal? (diff (Exp x) x) (Exp x))
(check-equal? (diff (Exp (⊗ x x)) x) (⊗ 2 x (Exp (⊗ x x))))
(check-equal? (diff (Expt x 1) x) 1)
(check-equal? (diff (Expt x 2) x) (⊗ 2 x))
(check-equal? (diff (Expt x 3) x) (⊗ 3 (Expt x 2)))
(check-equal? (diff (Ln x) x) (⊘ 1 x))
(check-equal? (diff (Ln (⊗ x x)) x) (⊘ (⊗ 2 x) (⊗ x x)))
(check-equal? (diff (Cos x) x) (⊖ (Sin x)))
(check-equal? (diff (Cos (⊗ x x)) x) (⊗ (⊖ (Sin (⊗ x x))) 2 x))
(check-equal? (diff (Sin x) x) (Cos x))
(check-equal? (diff (Sin (⊗ x x)) x) (⊗ 2 (Cos (Expt x 2)) x))
TODO : ASE should rewrite the result to ( * ' ( x ) ( + 1 ( ln x ) ) )
(check-equal? (diff (Expt x x) x) '(* (expt @e (* x (ln x))) (+ 1 (ln x))))
(check-equal? (diff (Si x) x) (Sinc x))
(check-equal? (diff (Ci x) x) (⊘ (Cos x) x))
)
| null | https://raw.githubusercontent.com/soegaard/racket-cas/c61c7a11697bb2cfbb710594daa276f1071fb48f/racket-cas/diff.rkt | racket | (diff u x) differentiate the expression u with respect to the variable x
Differentiation
example: (products '(a b c)) = '((* a b c) (* b c) c)
invariant: (append us ws) = vs
assumes u positive
[(Exp u) (⊗ (Exp u) (d u))]
xxx
xxx | #lang racket/base
Diff)
(require racket/format racket/match
(for-syntax racket/base racket/syntax syntax/parse)
"core.rkt" "math-match.rkt" "relational-operators.rkt" "trig.rkt")
(module+ test
(require rackunit math/bigfloat)
(define x 'x) (define y 'y) (define z 'z))
(define (1/sqrt:1-u^2 u)
(⊘ 1 (Sqrt (⊖ 1 (Sqr u)))))
(define (diff u x)
(define (d u) (diff u x))
(define (products us)
(match us
['() '()]
[(list u) (list u)]
[(cons u us) (define ps (products us))
(cons (⊗ u (car ps)) ps)]))
(math-match u
[r 0]
[y #:when (eq? x y) 1]
[y 0]
[(⊕ v w) (⊕ (d v) (d w))]
[(⊗ v w) (match u
[(list '* v w) (⊕ (⊗ (d v) w) (⊗ v (d w)))]
[(list '* vs ...)
(let loop ([sum 0]
[us '()]
[us⊗ 1]
[ws vs]
[ws⊗s (products vs)])
invariant : ( ⊗ us⊗ ( first ws⊗s ) ) = u
(match ws
['() sum]
[(list w) (⊕ (⊗ (d w) us⊗) sum)]
[(cons w ws) (loop (⊕ (⊗ (d w) (⊗ us⊗ (cadr ws⊗s))) sum)
(cons u w) (⊗ us⊗ w) ws (cdr ws⊗s))]))])]
[(Expt u r) (⊗ r (Expt u (- r 1)) (d u))]
[(Expt @e u) (⊗ (Exp u) (d u))]
[(Expt r y) #:when (and (positive? r) (equal? y x)) (⊗ (Expt r x) (Ln r))]
[(Ln u) (⊗ (⊘ 1 u) (d u))]
[(Cos u) (⊗ (⊖ 0 (Sin u)) (d u))]
[(Sin u) (⊗ (Cos u) (d u))]
[(Asin u) (1/sqrt:1-u^2 u)]
[(Acos u) (⊖ (1/sqrt:1-u^2 u))]
[(Atan u) (⊘ 1 (⊕ (Sqr x) 1))]
[(Si x) (Sinc x)]
[(Ci x) (⊘ (Cos x) x)]
[(app: f us) #:when (symbol? f)
(match us
[(list u) (cond [(eq? u x) (Diff `(,f ,x) x)]
[_ (error 'diff (~a "got: " u " wrt " x))]))
(define (Diff: u [x 'x])
(define D Diff:)
(math-match u
[(Equal u1 u2) (Equal (D u1 x) (D u2 x))]
[_ (list 'diff u x)]))
(define-match-expander Diff
(λ (stx) (syntax-parse stx [(_ u x) #'(list 'diff u x)]))
(λ (stx) (syntax-parse stx [(_ u x) #'(Diff: u)] [_ (identifier? stx) #'Diff:])))
(module+ test
(displayln "TEST - diff")
(check-equal? (diff 1 x) 0)
(check-equal? (diff x x) 1)
(check-equal? (diff y x) 0)
(check-equal? (diff (⊗ x x) x) '(* 2 x))
(check-equal? (diff (⊗ x x x) x) '(* 3 (expt x 2)))
(check-equal? (diff (⊗ x x x x) x) '(* 4 (expt x 3)))
(check-equal? (diff (⊕ (⊗ 5 x) (⊗ x x)) x) '(+ 5 (* 2 x)))
(check-equal? (diff (Exp x) x) (Exp x))
(check-equal? (diff (Exp (⊗ x x)) x) (⊗ 2 x (Exp (⊗ x x))))
(check-equal? (diff (Expt x 1) x) 1)
(check-equal? (diff (Expt x 2) x) (⊗ 2 x))
(check-equal? (diff (Expt x 3) x) (⊗ 3 (Expt x 2)))
(check-equal? (diff (Ln x) x) (⊘ 1 x))
(check-equal? (diff (Ln (⊗ x x)) x) (⊘ (⊗ 2 x) (⊗ x x)))
(check-equal? (diff (Cos x) x) (⊖ (Sin x)))
(check-equal? (diff (Cos (⊗ x x)) x) (⊗ (⊖ (Sin (⊗ x x))) 2 x))
(check-equal? (diff (Sin x) x) (Cos x))
(check-equal? (diff (Sin (⊗ x x)) x) (⊗ 2 (Cos (Expt x 2)) x))
TODO : ASE should rewrite the result to ( * ' ( x ) ( + 1 ( ln x ) ) )
(check-equal? (diff (Expt x x) x) '(* (expt @e (* x (ln x))) (+ 1 (ln x))))
(check-equal? (diff (Si x) x) (Sinc x))
(check-equal? (diff (Ci x) x) (⊘ (Cos x) x))
)
|
43ad1e3df268c84e826ed7600cf57983e921a3f4f5219eecaeb1c45b860137dc | markhibberd/postmark | Postmark.hs | -- |
Module : Network . Api . Postmark
Copyright : ( c ) 2012
License : BSD3
Maintainer : < >
-- Portability: portable
--
-- Library for postmarkapp.com HTTP Api.
--
To get start see some examples in the " Network . Api . Postmark . Tutorial " module .
--
-- Source and more information can be found at <>.
--
-- To experiment with a live demo try:
--
-- > $ git clone
-- > $ cd postmark
> $ cabal install --only - dependencies & & cabal configure -f demo & & cabal build
> $ ./dist / build / postmark - demo / postmark - demo
--
-- Issues can be reported at <>.
--
module Network.Api.Postmark (
-- * Settings
PostmarkSettings (..), PostmarkApiToken, postmarkHttp, postmarkHttps,
-- ** Using the test token
postmarkTestToken, postmarkHttpTest, postmarkHttpsTest,
-- * Sending email
email, emails, Email (..), defaultEmail,
-- ** Using a template
emailWithTemplate, EmailWithTemplate (..), defaultEmailWithTemplate,
-- ** Tracking links
TrackLinks (..),
-- ** Attachments
Attachment (..),
-- ** Response type
Sent (..),
-- * Error types
PostmarkError (..), PostmarkErrorType (..),
-- * Lower-level API
-- ** Request
request, PostmarkRequest (..), PostmarkRequest',
-- ** Response
PostmarkResponse (..), PostmarkUnexpectedType (..),
PostmarkResponse', syntaxErr, formatErr,
) where
import Network.Api.Postmark.Core
import Network.Api.Postmark.Data
import Network.Api.Postmark.Error
import Network.Api.Postmark.Request
import Network.Api.Postmark.Response
import Network.Api.Postmark.Settings
| null | https://raw.githubusercontent.com/markhibberd/postmark/2eb6087bbb19421f1dd765b973702f37c1d386e9/src/Network/Api/Postmark.hs | haskell | |
Portability: portable
Library for postmarkapp.com HTTP Api.
Source and more information can be found at <>.
To experiment with a live demo try:
> $ git clone
> $ cd postmark
only - dependencies & & cabal configure -f demo & & cabal build
Issues can be reported at <>.
* Settings
** Using the test token
* Sending email
** Using a template
** Tracking links
** Attachments
** Response type
* Error types
* Lower-level API
** Request
** Response | Module : Network . Api . Postmark
Copyright : ( c ) 2012
License : BSD3
Maintainer : < >
To get start see some examples in the " Network . Api . Postmark . Tutorial " module .
> $ ./dist / build / postmark - demo / postmark - demo
module Network.Api.Postmark (
PostmarkSettings (..), PostmarkApiToken, postmarkHttp, postmarkHttps,
postmarkTestToken, postmarkHttpTest, postmarkHttpsTest,
email, emails, Email (..), defaultEmail,
emailWithTemplate, EmailWithTemplate (..), defaultEmailWithTemplate,
TrackLinks (..),
Attachment (..),
Sent (..),
PostmarkError (..), PostmarkErrorType (..),
request, PostmarkRequest (..), PostmarkRequest',
PostmarkResponse (..), PostmarkUnexpectedType (..),
PostmarkResponse', syntaxErr, formatErr,
) where
import Network.Api.Postmark.Core
import Network.Api.Postmark.Data
import Network.Api.Postmark.Error
import Network.Api.Postmark.Request
import Network.Api.Postmark.Response
import Network.Api.Postmark.Settings
|
7cc6f812a78c98228762000f9ea5a9101a0e76033ab5d0722963752d0a8d4e43 | RyanGlScott/text-show | OldTypeableSpec.hs | # LANGUAGE CPP #
#if !(MIN_VERSION_base(4,8,0))
# OPTIONS_GHC -fno - warn - warnings - deprecations #
#endif
|
Module : Spec . Data . OldTypeableSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for data types in the " Data . OldTypeable " module .
Module: Spec.Data.OldTypeableSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for data types in the "Data.OldTypeable" module.
-}
module Spec.Data.OldTypeableSpec (main, spec) where
import Instances.Data.OldTypeable ()
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if !(MIN_VERSION_base(4,8,0))
import Data.OldTypeable (TyCon, TypeRep)
import Data.Proxy.Compat (Proxy(..))
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
#if !(MIN_VERSION_base(4,8,0))
describe "TypeRep" $
matchesTextShowSpec (Proxy :: Proxy TypeRep)
describe "TyCon" $
matchesTextShowSpec (Proxy :: Proxy TyCon)
#else
pure ()
#endif
| null | https://raw.githubusercontent.com/RyanGlScott/text-show/cede44e2bc357db54a7e2ad17de200708b9331cc/tests/Spec/Data/OldTypeableSpec.hs | haskell | # LANGUAGE CPP #
#if !(MIN_VERSION_base(4,8,0))
# OPTIONS_GHC -fno - warn - warnings - deprecations #
#endif
|
Module : Spec . Data . OldTypeableSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for data types in the " Data . OldTypeable " module .
Module: Spec.Data.OldTypeableSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for data types in the "Data.OldTypeable" module.
-}
module Spec.Data.OldTypeableSpec (main, spec) where
import Instances.Data.OldTypeable ()
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if !(MIN_VERSION_base(4,8,0))
import Data.OldTypeable (TyCon, TypeRep)
import Data.Proxy.Compat (Proxy(..))
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
#if !(MIN_VERSION_base(4,8,0))
describe "TypeRep" $
matchesTextShowSpec (Proxy :: Proxy TypeRep)
describe "TyCon" $
matchesTextShowSpec (Proxy :: Proxy TyCon)
#else
pure ()
#endif
| |
1f3d812fd19ea8a28d92ed59a0ac6f2b5eb91bb72f2c5ed85aff49bc2b94597c | asdr/easyweb | _initialize.lisp | (defpackage :(% TMPL_VAR APPLICATION_NAME %)
(:use #:cl #:easyweb))
(in-package :(% TMPL_VAR APPLICATION_NAME %))
;;load template files
;;once you load a template file it's created and
;;changes wont affect by other loads
;; | null | https://raw.githubusercontent.com/asdr/easyweb/b259358a5f5e146b233b38d5e5df5b85a5a479cd/template-app/_initialize.lisp | lisp | load template files
once you load a template file it's created and
changes wont affect by other loads
| (defpackage :(% TMPL_VAR APPLICATION_NAME %)
(:use #:cl #:easyweb))
(in-package :(% TMPL_VAR APPLICATION_NAME %))
|
61e783e472ac14bc766bf9825211f87fa1508df2fabb5643682ee3ae146f64a7 | wdebeaum/DeepSemLex | mathematician.lisp | ;;;;
;;;; W::mathematician
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::mathematician
(SENSES
((meta-data :origin calo :entry-date 20060503 :change-date nil :wn ("mathematician%1:18:00") :comments nil)
(LF-PARENT ONT::scholar) ;professional)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/DeepSemLex/ce0e7523dd2b1ebd42b9e88ffbcfdb0fd339aaee/trips/src/LexiconManager/Data/new/mathematician.lisp | lisp |
W::mathematician
professional) |
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::mathematician
(SENSES
((meta-data :origin calo :entry-date 20060503 :change-date nil :wn ("mathematician%1:18:00") :comments nil)
)
)
)
))
|
c111af39b60e61be3d6755f5733af0ff30655b4ae2d60d9da4b3e8fbc2377ddf | tweag/asterius | genconstants.hs | import Asterius.JSGen.Constants
import Data.ByteString.Builder
import System.IO
main :: IO ()
main = hPutBuilder stdout rtsConstants
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/app/genconstants.hs | haskell | import Asterius.JSGen.Constants
import Data.ByteString.Builder
import System.IO
main :: IO ()
main = hPutBuilder stdout rtsConstants
| |
967747356157abcfd3bb6a357f2647c0a945b3f019e4ba015d59fc0f031ebfa5 | mentat-collective/Mafs.cljs | user.clj | (ns user
(:require [mentat.clerk-utils.build :as b]
[mentat.clerk-utils.css :as css]))
(css/set-css!
"-modern@0.1.2/cmu-serif.css"
"@0.15.2/core.css"
"@0.15.2/font.css")
(def index
"dev/mafs/notebook.clj")
(def defaults
{:index index
:browse? true
:watch-paths ["dev"]
:cljs-namespaces '[mafs.sci-extensions]})
(def static-defaults
(assoc defaults
:browse? false
:cname "mafs.mentat.org"
:git/url "-collective/mafs.cljs"))
(defn serve!
([] (serve! {}))
([opts]
(b/serve!
(merge defaults opts))))
(def halt! b/halt!)
(defn build! [opts]
(b/build!
(merge static-defaults opts)))
| null | https://raw.githubusercontent.com/mentat-collective/Mafs.cljs/a429c31ae2585fa89a62d16823893dd97b07c267/dev/user.clj | clojure | (ns user
(:require [mentat.clerk-utils.build :as b]
[mentat.clerk-utils.css :as css]))
(css/set-css!
"-modern@0.1.2/cmu-serif.css"
"@0.15.2/core.css"
"@0.15.2/font.css")
(def index
"dev/mafs/notebook.clj")
(def defaults
{:index index
:browse? true
:watch-paths ["dev"]
:cljs-namespaces '[mafs.sci-extensions]})
(def static-defaults
(assoc defaults
:browse? false
:cname "mafs.mentat.org"
:git/url "-collective/mafs.cljs"))
(defn serve!
([] (serve! {}))
([opts]
(b/serve!
(merge defaults opts))))
(def halt! b/halt!)
(defn build! [opts]
(b/build!
(merge static-defaults opts)))
| |
4257a0727b8a553705a5e703ac9168216debb26f908f210a8bb1a1ea40703358 | mhuebert/maria | edit.cljs | (ns lark.structure.edit
(:refer-clojure :exclude [char])
(:require [lark.tree.core :as tree]
[lark.tree.range :as range]
[lark.tree.util :as util]
[lark.tree.cursor :as cursor]
[lark.editors.codemirror :as cm]
[fast-zip.core :as z]
[goog.dom :as dom]
[goog.dom.Range :as Range]
[clojure.string :as string]
[lark.tree.nav :as nav]
[lark.tree.parse :as parse]
[lark.tree.node :as node]
[clojure.string :as str]
[lark.tree.format :as format]
[lark.tree.node :as n]
[lark.tree.emit :as emit]
[lark.tree.reader :as r])
(:require-macros [lark.structure.edit :as edit :refer [operation]]))
(defn format!
([editor] (format! editor {}))
([editor {:keys [preserve-cursor-space?]}]
(let [pre-val (.getValue editor)
pre-zipper (tree/string-zip pre-val)
pre-pos (cm/pos->boundary (cm/get-cursor editor))
cursor-loc (when preserve-cursor-space?
(nav/cursor-space-loc pre-zipper pre-pos))
post-val (binding [r/*active-cursor-node* (some-> cursor-loc
(z/node))]
(tree/format pre-zipper))
post-zipper (tree/string-zip post-val)]
(when (not= pre-val post-val) ;; only mutate editor if value has changed
(.setValue editor post-val))
(->> (cursor/path pre-zipper pre-pos cursor-loc) ;; cursor path from pre-format zipper, ignoring whitespace
(cursor/position post-zipper) ;; returns position in post-format zipper for path
(cm/range->Pos)
(.setCursor editor))
(cm/set-zipper! editor post-zipper))))
(def other-bracket {\( \) \[ \] \{ \} \" \"})
(defn spaces [n] (apply str (take n (repeat " "))))
(def clipboard-helper-element
(memoize (fn []
(let [textarea (doto (dom/createElement "pre")
(dom/setProperties #js {:id "lark-tree-pasteHelper"
:contentEditable true
:className "fixed o-0 z-0 bottom-0 right-0"}))]
(dom/appendChild js/document.body textarea)
textarea))))
(defn copy
"Copy text to clipboard using a hidden input element."
[text]
(let [hadFocus (.-activeElement js/document)
text (string/replace text #"[\n\r]" "<br/>")
_ (aset (clipboard-helper-element) "innerHTML" text)]
(doto (Range/createFromNodeContents (clipboard-helper-element))
(.select))
(try (.execCommand js/document "copy")
(catch js/Error e (.error js/console "Copy command didn't work. Maybe a browser incompatibility?")))
(.focus hadFocus)))
(defn copy-range!
"Copy a {:line .. :column ..} range from a CodeMirror instance."
[cm range]
(copy (cm/range-text cm range))
true)
(defn cut-range!
"Cut a {:line .. :column ..} range from a CodeMirror instance."
[cm range]
(copy (cm/range-text cm range))
(cm/replace-range! cm "" range)
true)
(defn cursor-skip-pos
[{{:keys [pos loc]} :magic/cursor} side]
(let [move (case side :left nav/left-up
:right nav/right-up)
nodes (->> (iterate move (nav/include-prefix-parents loc))
(take-while identity)
(map z/node)
(filter (fn [node]
(and (not (node/whitespace? node))
(not (range/pos= pos (range/bounds node side)))))))]
(some-> (first nodes)
(range/bounds side))))
(defn cursor-skip!
"Returns function for moving cursor left or right, touching only node boundaries."
[cm side]
(some->> (cursor-skip-pos cm side)
(cm/set-cursor! cm)))
(defn move-char [cm pos amount]
(.findPosH cm pos amount "char" false))
(defn char-at [cm pos]
(.getRange cm pos (move-char cm pos 1)))
(defprotocol IPointer
(get-range [this i])
(move [this amount])
(move-while! [this i pred])
(move-while [this i pred])
(insert! [this s] [this replace-i s])
(set-editor-cursor! [this])
(adjust-for-changes! [this changes]))
(def ^:dynamic *changes* nil)
(defn log-editor-changes [cm changes]
(when *changes*
(.apply (.-push *changes*) *changes* changes)))
(defn adjust-for-change [pos change]
(cond (<= (compare pos (.-from change)) 0) pos
(<= (compare pos (.-to change)) 0) (cm/changeEnd change)
:else
(let [line (-> (.-line pos)
(+ (-> change .-text .-length))
(- (-> (.. change -to -line)
(- (.. change -from -line))))
(- 1))
ch (cond-> (.-ch pos)
(= (.-line pos) (.. change -to -line)) (+ (-> (.-ch (cm/changeEnd change))
(- (.. change -to -ch)))))]
(cm/Pos line ch))))
(defn adjust-for-changes [pos changes]
(loop [pos pos
i 0]
(if (= i (.-length changes))
pos
(recur (adjust-for-change pos (aget changes i))
(inc i)))))
(defn move-while-pos [pos editor i pred]
(loop [the-pos pos]
(let [next-pos (move-char editor the-pos i)
char (if (pos? i) (.getRange editor the-pos (move-char editor the-pos i))
(char-at editor next-pos))]
(if (and (pred char) (not (.-hitSide next-pos)))
(recur next-pos)
the-pos))))
(defrecord Pointer [editor ^:mutable pos]
IPointer
(get-range [this i]
(if (neg? i)
(.getRange editor (:pos (move this i)) pos)
(.getRange editor pos (:pos (move this i)))))
(move [this amount]
(assoc this :pos (move-char editor pos amount)))
(insert! [this text]
(.replaceRange editor text pos pos)
this)
(insert! [this amount text]
(.replaceRange editor text pos (move-char editor pos amount))
this)
(set-editor-cursor! [this]
(.setCursor editor pos nil #js {:scroll false})
this)
(adjust-for-changes! [this changes]
(set! pos (adjust-for-changes pos changes))
this)
(move-while! [this i pred]
(set! pos (move-while-pos pos editor i pred))
this)
(move-while [this i pred]
(assoc this :pos (move-while-pos pos editor i pred))))
(defn pointer
([editor] (pointer editor (cm/get-cursor editor)))
([editor pos] (->Pointer editor pos)))
(defn chars-around [the-pointer]
(mapv (fn [i]
(util/some-str (get-range the-pointer i))) [-1 1]))
(defn uneval! [{{:keys [loc]} :magic/cursor
:as cm}]
(when-let [loc (->> (cons (nav/include-prefix-parents loc) (nav/left-locs loc))
(remove (comp node/whitespace? z/node))
(first))]
(let [node (z/node loc)]
(let [a-pointer (pointer cm)
changes (operation cm
(or (when-let [uneval-loc (first (filter (comp (partial = :uneval) :tag z/node)
[loc (z/up loc)]))]
(-> (pointer cm (cm/range->Pos (range/bounds (z/node uneval-loc) :left)))
(insert! 2 "")))
(-> (pointer cm (cm/range->Pos (range/bounds node :left)))
(insert! "#_"))))]
(adjust-for-changes! a-pointer changes)
(set-editor-cursor! a-pointer))))
true)
(range/within? {:line 0, :column 1, :end-line 0, :end-column 22}
{:line 0, :column 13})
(def kill!
(fn [{{pos :pos} :magic/cursor
zipper :zipper :as editor}]
(edit/with-formatting editor
(let [loc (nav/navigate zipper pos)
node (z/node loc)
loc (cond-> loc
(or (not (range/within-inner? node pos))
(node/whitespace? node)) (z/up))
node (z/node loc)
in-edge? (when (node/has-edges? node)
(let [inner (range/inner-range node)]
(not (range/within? inner pos))))
end-node (cond in-edge? nil ;; ignore kill when cursor is inside an edge structure, eg. #|""
(not (node/may-contain-children? node)) (range/inner-range node)
:else (->> (z/children loc)
(drop-while #(range/lt (range/bounds % :right) pos))
(take-while #(<= (:line %) (:line pos)))
(last)))]
(when end-node
(->> (merge pos (select-keys end-node [:end-line :end-column]))
(cut-range! editor)))))
true))
(defn boundary? [s]
(some->> (last s)
(.indexOf "\"()[]{} ")
(pos?)))
(defn unwrap! [{{:keys [pos loc bracket-node]} :magic/cursor :as editor}]
(when (and loc (not (cm/selection? editor)))
(when-let [edge-node (loop [loc (cond-> loc
(not (range/within-inner? bracket-node pos)) (z/up))]
(cond (not loc) nil
(node/has-edges? (z/node loc)) (z/node loc)
:else (recur (z/up loc))))]
(edit/with-formatting editor
(let [[l r] (node/edges edge-node)
[left-r right-r] (range/edge-ranges edge-node)]
(doseq [[n range] [[(count l) left-r]
[(count r) right-r]]]
(cm/replace-range! editor (format/spaces n) range))))))
true)
(defn raise! [{{:keys [pos bracket-loc bracket-node]} :magic/cursor :as editor}]
(when (and bracket-loc (z/up bracket-loc))
(let [outer-node (z/node (z/up bracket-loc))]
(edit/with-formatting editor
(cm/replace-range! editor "" (range/end bracket-node) outer-node)
(cm/replace-range! editor "" outer-node bracket-node))))
true)
(def copy-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(copy-range! cm (get-in cm [:magic/cursor :bracket-node])))))
(def cut-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(cut-range! cm (get-in cm [:magic/cursor :bracket-node])))))
(def delete-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(cm/replace-range! cm "" (get-in cm [:magic/cursor :bracket-node])))))
(defn pop-stack! [cm]
(when-let [stack (get-in cm [:magic/cursor :stack])]
(let [stack (cond-> stack
(or (:base (first stack))
(= (cm/current-selection-bounds cm) (first stack))) rest)
item (first stack)]
(swap! cm update-in [:magic/cursor :stack] (if (range/empty-range? item)
empty rest))
item)))
(defn push-stack! [cm node]
(when (range/empty-range? node)
(swap! cm update-in [:magic/cursor :stack] empty))
(when-not (= node (first (get-in cm [:magic/cursor :stack])))
(swap! cm update-in [:magic/cursor :stack] conj (range/bounds node)))
true)
(defn tracked-select [cm node]
(when node
(cm/select-range cm node)
(push-stack! cm (range/bounds node))))
(defn push-cursor! [cm]
(push-stack! cm (cm/Pos->range (cm/get-cursor cm)))
(cm/unset-temp-marker! cm))
(def expand-selection
(fn [{zipper :zipper
:as cm}]
(let [sel (cm/current-selection-bounds cm)
loc (nav/navigate zipper sel)
select! (partial tracked-select cm)
cursor-root (cm/temp-marker-cursor-pos cm)
selection? (cm/selection? cm)]
(when (or cursor-root (not selection?))
(push-cursor! cm)
(push-stack! cm (cm/current-selection-bounds cm)))
(loop [loc loc]
(if-not loc
sel
(let [node (z/node loc)
inner-range (when (node/has-edges? node)
(let [range (range/inner-range node)]
(when-not (range/empty-range? range)
range)))]
(cond (range/range= sel inner-range) (select! node)
(some-> inner-range
(range/within? sel)) (select! inner-range)
(range/range= sel node) (recur (z/up loc))
(range/within? node sel) (select! node)
:else (recur (z/up loc)))))))
true))
(def shrink-selection
(fn [cm]
(some->> (pop-stack! cm)
(cm/select-range cm))
true))
(defn expand-selection-x [{zipper :zipper
:as cm} direction]
(let [selection-bounds (cm/current-selection-bounds cm)
selection-loc (nav/navigate zipper (range/bounds selection-bounds direction))
selection-node (z/node selection-loc)
cursor-root (cm/temp-marker-cursor-pos cm)]
(when cursor-root
(push-cursor! cm)
(push-stack! cm selection-bounds))
(if (and (node/has-edges? selection-node)
(= (range/bounds selection-bounds direction)
(range/bounds (range/inner-range selection-node) direction)))
(expand-selection cm)
(if-let [adjacent-loc (first (filter (comp (complement node/whitespace?) z/node) ((case direction :right nav/right-locs
:left nav/left-locs) selection-loc)))]
(tracked-select cm (merge (range/bounds (z/node adjacent-loc))
(case direction :right (range/bounds selection-bounds :left)
:left (range/->end (range/bounds selection-bounds :right)))))
(expand-selection cm))))
true)
(def backspace! #(.execCommand % "delCharBefore"))
(defn comment-line
([cm]
(operation
cm
(if (cm/selection? cm)
(let [sel (aget (.listSelections cm) 0)
[start end] (sort [(.. sel -anchor -line)
(.. sel -head -line)])]
(doseq [line-n (range start (inc end))]
(comment-line cm line-n)))
(comment-line cm (.-line (cm/get-cursor cm))))))
([cm line-n]
(let [[spaces semicolons] (rest (re-find #"^(\s*)(;+)?" (.getLine cm line-n)))
[space-n semicolon-n] (map count [spaces semicolons])]
(if (> semicolon-n 0)
(cm/replace-range! cm "" {:line line-n
:column space-n
:end-column (+ space-n semicolon-n)})
(cm/replace-range! cm ";;" {:line line-n
:column space-n
:end-column space-n})))
true))
TODO
;; slurp/unslurp strings
;; - pad with space
;; - unslurp last spaced element
(defn slurp-parent? [node pos]
(and (or #_(= :string (:tag node))
(node/may-contain-children? node))
(range/within-inner? node pos)))
(defn slurp-parent [loc pos]
(loop [loc loc]
(when loc
(if (slurp-parent? (z/node loc) pos)
loc
(recur (z/up loc))))))
(def slurp-forward
(fn [{{:keys [loc pos]} :magic/cursor
:as cm}]
(let [end-edge-loc (slurp-parent loc pos)
start-edge-loc (nav/include-prefix-parents end-edge-loc)
{:keys [tag] :as node} (z/node start-edge-loc)]
(when (and node (not= :base tag))
(let [right-bracket (second (node/edges (z/node end-edge-loc)))
last-child (some->> (z/children end-edge-loc)
(remove node/whitespace?)
(last))]
(when-let [next-form (some->> (z/rights start-edge-loc)
(remove node/whitespace?)
first)]
(let [form-content (emit/string next-form)
replace-start (if last-child (range/bounds last-child :right)
(-> (z/node end-edge-loc)
(range/inner-range)
(range/bounds :right)))
replace-end (select-keys next-form [:end-line :end-column])
pad-start (and last-child
(or (not (boundary? (first form-content)))
(not (boundary? (last (emit/string last-child))))))
cur (.getCursor cm)]
(cm/replace-range! cm (str
(when pad-start " ")
form-content
right-bracket)
(merge replace-start replace-end))
(.setCursor cm cur))))))
true))
(def unslurp-forward
(fn [{{:keys [loc pos]} :magic/cursor
:as editor}]
(let [end-edge-loc (slurp-parent loc pos)
end-edge-node (some-> end-edge-loc z/node)]
(when (and end-edge-node (not= :base (:tag end-edge-node)))
(when-let [last-child (->> (z/children end-edge-loc)
(remove node/whitespace?)
(last))]
(edit/with-formatting editor
(-> (pointer editor (cm/range->Pos (range/end end-edge-node)))
(insert! (str " " (emit/string last-child) " ")))
(cm/replace-range! editor (-> (cm/range-text editor last-child)
(str/replace #"[^\n]" " ")) last-child)
(cm/set-cursor! editor (first (sort [(cm/range->Pos pos)
(-> (range/inner-range end-edge-node)
(range/end)
(cm/range->Pos))])))))))
true))
(defn cursor-selection-edge [editor side]
(cm/set-cursor! editor (-> (cm/current-selection-bounds editor)
(range/bounds side)))
true)
(defn cursor-line-edge [editor side]
(let [cursor (cm/get-cursor editor)
line-i (.-line cursor)
line (.getLine editor line-i)
padding (count (second (re-find (case side :left #"^(\s+).*"
:right #".*?(\s+)$") line)))]
(cm/set-cursor! editor (cm/Pos line-i (case side :left padding
:right (- (count line) padding)))))
true)
(defn node-symbol [node]
(when (= :token (.-tag node))
(-> (emit/sexp node)
(util/guard-> symbol?))))
(defn eldoc-symbol
([loc pos]
(eldoc-symbol (cond-> loc
(= (range/bounds pos :left)
(some-> loc (z/node) (range/bounds :left))) (z/up))))
([loc]
(some->> loc
(nav/closest #(#{:list :fn} (.-tag (z/node %))))
(z/children)
(first)
(node-symbol)))) | null | https://raw.githubusercontent.com/mhuebert/maria/15586564796bc9273ace3101b21662d0c66b4d22/editor/vendor/lark/structure/edit.cljs | clojure | only mutate editor if value has changed
cursor path from pre-format zipper, ignoring whitespace
returns position in post-format zipper for path
ignore kill when cursor is inside an edge structure, eg. #|""
slurp/unslurp strings
- pad with space
- unslurp last spaced element | (ns lark.structure.edit
(:refer-clojure :exclude [char])
(:require [lark.tree.core :as tree]
[lark.tree.range :as range]
[lark.tree.util :as util]
[lark.tree.cursor :as cursor]
[lark.editors.codemirror :as cm]
[fast-zip.core :as z]
[goog.dom :as dom]
[goog.dom.Range :as Range]
[clojure.string :as string]
[lark.tree.nav :as nav]
[lark.tree.parse :as parse]
[lark.tree.node :as node]
[clojure.string :as str]
[lark.tree.format :as format]
[lark.tree.node :as n]
[lark.tree.emit :as emit]
[lark.tree.reader :as r])
(:require-macros [lark.structure.edit :as edit :refer [operation]]))
(defn format!
([editor] (format! editor {}))
([editor {:keys [preserve-cursor-space?]}]
(let [pre-val (.getValue editor)
pre-zipper (tree/string-zip pre-val)
pre-pos (cm/pos->boundary (cm/get-cursor editor))
cursor-loc (when preserve-cursor-space?
(nav/cursor-space-loc pre-zipper pre-pos))
post-val (binding [r/*active-cursor-node* (some-> cursor-loc
(z/node))]
(tree/format pre-zipper))
post-zipper (tree/string-zip post-val)]
(.setValue editor post-val))
(cm/range->Pos)
(.setCursor editor))
(cm/set-zipper! editor post-zipper))))
(def other-bracket {\( \) \[ \] \{ \} \" \"})
(defn spaces [n] (apply str (take n (repeat " "))))
(def clipboard-helper-element
(memoize (fn []
(let [textarea (doto (dom/createElement "pre")
(dom/setProperties #js {:id "lark-tree-pasteHelper"
:contentEditable true
:className "fixed o-0 z-0 bottom-0 right-0"}))]
(dom/appendChild js/document.body textarea)
textarea))))
(defn copy
"Copy text to clipboard using a hidden input element."
[text]
(let [hadFocus (.-activeElement js/document)
text (string/replace text #"[\n\r]" "<br/>")
_ (aset (clipboard-helper-element) "innerHTML" text)]
(doto (Range/createFromNodeContents (clipboard-helper-element))
(.select))
(try (.execCommand js/document "copy")
(catch js/Error e (.error js/console "Copy command didn't work. Maybe a browser incompatibility?")))
(.focus hadFocus)))
(defn copy-range!
"Copy a {:line .. :column ..} range from a CodeMirror instance."
[cm range]
(copy (cm/range-text cm range))
true)
(defn cut-range!
"Cut a {:line .. :column ..} range from a CodeMirror instance."
[cm range]
(copy (cm/range-text cm range))
(cm/replace-range! cm "" range)
true)
(defn cursor-skip-pos
[{{:keys [pos loc]} :magic/cursor} side]
(let [move (case side :left nav/left-up
:right nav/right-up)
nodes (->> (iterate move (nav/include-prefix-parents loc))
(take-while identity)
(map z/node)
(filter (fn [node]
(and (not (node/whitespace? node))
(not (range/pos= pos (range/bounds node side)))))))]
(some-> (first nodes)
(range/bounds side))))
(defn cursor-skip!
"Returns function for moving cursor left or right, touching only node boundaries."
[cm side]
(some->> (cursor-skip-pos cm side)
(cm/set-cursor! cm)))
(defn move-char [cm pos amount]
(.findPosH cm pos amount "char" false))
(defn char-at [cm pos]
(.getRange cm pos (move-char cm pos 1)))
(defprotocol IPointer
(get-range [this i])
(move [this amount])
(move-while! [this i pred])
(move-while [this i pred])
(insert! [this s] [this replace-i s])
(set-editor-cursor! [this])
(adjust-for-changes! [this changes]))
(def ^:dynamic *changes* nil)
(defn log-editor-changes [cm changes]
(when *changes*
(.apply (.-push *changes*) *changes* changes)))
(defn adjust-for-change [pos change]
(cond (<= (compare pos (.-from change)) 0) pos
(<= (compare pos (.-to change)) 0) (cm/changeEnd change)
:else
(let [line (-> (.-line pos)
(+ (-> change .-text .-length))
(- (-> (.. change -to -line)
(- (.. change -from -line))))
(- 1))
ch (cond-> (.-ch pos)
(= (.-line pos) (.. change -to -line)) (+ (-> (.-ch (cm/changeEnd change))
(- (.. change -to -ch)))))]
(cm/Pos line ch))))
(defn adjust-for-changes [pos changes]
(loop [pos pos
i 0]
(if (= i (.-length changes))
pos
(recur (adjust-for-change pos (aget changes i))
(inc i)))))
(defn move-while-pos [pos editor i pred]
(loop [the-pos pos]
(let [next-pos (move-char editor the-pos i)
char (if (pos? i) (.getRange editor the-pos (move-char editor the-pos i))
(char-at editor next-pos))]
(if (and (pred char) (not (.-hitSide next-pos)))
(recur next-pos)
the-pos))))
(defrecord Pointer [editor ^:mutable pos]
IPointer
(get-range [this i]
(if (neg? i)
(.getRange editor (:pos (move this i)) pos)
(.getRange editor pos (:pos (move this i)))))
(move [this amount]
(assoc this :pos (move-char editor pos amount)))
(insert! [this text]
(.replaceRange editor text pos pos)
this)
(insert! [this amount text]
(.replaceRange editor text pos (move-char editor pos amount))
this)
(set-editor-cursor! [this]
(.setCursor editor pos nil #js {:scroll false})
this)
(adjust-for-changes! [this changes]
(set! pos (adjust-for-changes pos changes))
this)
(move-while! [this i pred]
(set! pos (move-while-pos pos editor i pred))
this)
(move-while [this i pred]
(assoc this :pos (move-while-pos pos editor i pred))))
(defn pointer
([editor] (pointer editor (cm/get-cursor editor)))
([editor pos] (->Pointer editor pos)))
(defn chars-around [the-pointer]
(mapv (fn [i]
(util/some-str (get-range the-pointer i))) [-1 1]))
(defn uneval! [{{:keys [loc]} :magic/cursor
:as cm}]
(when-let [loc (->> (cons (nav/include-prefix-parents loc) (nav/left-locs loc))
(remove (comp node/whitespace? z/node))
(first))]
(let [node (z/node loc)]
(let [a-pointer (pointer cm)
changes (operation cm
(or (when-let [uneval-loc (first (filter (comp (partial = :uneval) :tag z/node)
[loc (z/up loc)]))]
(-> (pointer cm (cm/range->Pos (range/bounds (z/node uneval-loc) :left)))
(insert! 2 "")))
(-> (pointer cm (cm/range->Pos (range/bounds node :left)))
(insert! "#_"))))]
(adjust-for-changes! a-pointer changes)
(set-editor-cursor! a-pointer))))
true)
(range/within? {:line 0, :column 1, :end-line 0, :end-column 22}
{:line 0, :column 13})
(def kill!
(fn [{{pos :pos} :magic/cursor
zipper :zipper :as editor}]
(edit/with-formatting editor
(let [loc (nav/navigate zipper pos)
node (z/node loc)
loc (cond-> loc
(or (not (range/within-inner? node pos))
(node/whitespace? node)) (z/up))
node (z/node loc)
in-edge? (when (node/has-edges? node)
(let [inner (range/inner-range node)]
(not (range/within? inner pos))))
(not (node/may-contain-children? node)) (range/inner-range node)
:else (->> (z/children loc)
(drop-while #(range/lt (range/bounds % :right) pos))
(take-while #(<= (:line %) (:line pos)))
(last)))]
(when end-node
(->> (merge pos (select-keys end-node [:end-line :end-column]))
(cut-range! editor)))))
true))
(defn boundary? [s]
(some->> (last s)
(.indexOf "\"()[]{} ")
(pos?)))
(defn unwrap! [{{:keys [pos loc bracket-node]} :magic/cursor :as editor}]
(when (and loc (not (cm/selection? editor)))
(when-let [edge-node (loop [loc (cond-> loc
(not (range/within-inner? bracket-node pos)) (z/up))]
(cond (not loc) nil
(node/has-edges? (z/node loc)) (z/node loc)
:else (recur (z/up loc))))]
(edit/with-formatting editor
(let [[l r] (node/edges edge-node)
[left-r right-r] (range/edge-ranges edge-node)]
(doseq [[n range] [[(count l) left-r]
[(count r) right-r]]]
(cm/replace-range! editor (format/spaces n) range))))))
true)
(defn raise! [{{:keys [pos bracket-loc bracket-node]} :magic/cursor :as editor}]
(when (and bracket-loc (z/up bracket-loc))
(let [outer-node (z/node (z/up bracket-loc))]
(edit/with-formatting editor
(cm/replace-range! editor "" (range/end bracket-node) outer-node)
(cm/replace-range! editor "" outer-node bracket-node))))
true)
(def copy-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(copy-range! cm (get-in cm [:magic/cursor :bracket-node])))))
(def cut-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(cut-range! cm (get-in cm [:magic/cursor :bracket-node])))))
(def delete-form
(fn [cm] (if (cm/selection? cm)
:lark.commands/Pass
(cm/replace-range! cm "" (get-in cm [:magic/cursor :bracket-node])))))
(defn pop-stack! [cm]
(when-let [stack (get-in cm [:magic/cursor :stack])]
(let [stack (cond-> stack
(or (:base (first stack))
(= (cm/current-selection-bounds cm) (first stack))) rest)
item (first stack)]
(swap! cm update-in [:magic/cursor :stack] (if (range/empty-range? item)
empty rest))
item)))
(defn push-stack! [cm node]
(when (range/empty-range? node)
(swap! cm update-in [:magic/cursor :stack] empty))
(when-not (= node (first (get-in cm [:magic/cursor :stack])))
(swap! cm update-in [:magic/cursor :stack] conj (range/bounds node)))
true)
(defn tracked-select [cm node]
(when node
(cm/select-range cm node)
(push-stack! cm (range/bounds node))))
(defn push-cursor! [cm]
(push-stack! cm (cm/Pos->range (cm/get-cursor cm)))
(cm/unset-temp-marker! cm))
(def expand-selection
(fn [{zipper :zipper
:as cm}]
(let [sel (cm/current-selection-bounds cm)
loc (nav/navigate zipper sel)
select! (partial tracked-select cm)
cursor-root (cm/temp-marker-cursor-pos cm)
selection? (cm/selection? cm)]
(when (or cursor-root (not selection?))
(push-cursor! cm)
(push-stack! cm (cm/current-selection-bounds cm)))
(loop [loc loc]
(if-not loc
sel
(let [node (z/node loc)
inner-range (when (node/has-edges? node)
(let [range (range/inner-range node)]
(when-not (range/empty-range? range)
range)))]
(cond (range/range= sel inner-range) (select! node)
(some-> inner-range
(range/within? sel)) (select! inner-range)
(range/range= sel node) (recur (z/up loc))
(range/within? node sel) (select! node)
:else (recur (z/up loc)))))))
true))
(def shrink-selection
(fn [cm]
(some->> (pop-stack! cm)
(cm/select-range cm))
true))
(defn expand-selection-x [{zipper :zipper
:as cm} direction]
(let [selection-bounds (cm/current-selection-bounds cm)
selection-loc (nav/navigate zipper (range/bounds selection-bounds direction))
selection-node (z/node selection-loc)
cursor-root (cm/temp-marker-cursor-pos cm)]
(when cursor-root
(push-cursor! cm)
(push-stack! cm selection-bounds))
(if (and (node/has-edges? selection-node)
(= (range/bounds selection-bounds direction)
(range/bounds (range/inner-range selection-node) direction)))
(expand-selection cm)
(if-let [adjacent-loc (first (filter (comp (complement node/whitespace?) z/node) ((case direction :right nav/right-locs
:left nav/left-locs) selection-loc)))]
(tracked-select cm (merge (range/bounds (z/node adjacent-loc))
(case direction :right (range/bounds selection-bounds :left)
:left (range/->end (range/bounds selection-bounds :right)))))
(expand-selection cm))))
true)
(def backspace! #(.execCommand % "delCharBefore"))
(defn comment-line
([cm]
(operation
cm
(if (cm/selection? cm)
(let [sel (aget (.listSelections cm) 0)
[start end] (sort [(.. sel -anchor -line)
(.. sel -head -line)])]
(doseq [line-n (range start (inc end))]
(comment-line cm line-n)))
(comment-line cm (.-line (cm/get-cursor cm))))))
([cm line-n]
(let [[spaces semicolons] (rest (re-find #"^(\s*)(;+)?" (.getLine cm line-n)))
[space-n semicolon-n] (map count [spaces semicolons])]
(if (> semicolon-n 0)
(cm/replace-range! cm "" {:line line-n
:column space-n
:end-column (+ space-n semicolon-n)})
(cm/replace-range! cm ";;" {:line line-n
:column space-n
:end-column space-n})))
true))
TODO
(defn slurp-parent? [node pos]
(and (or #_(= :string (:tag node))
(node/may-contain-children? node))
(range/within-inner? node pos)))
(defn slurp-parent [loc pos]
(loop [loc loc]
(when loc
(if (slurp-parent? (z/node loc) pos)
loc
(recur (z/up loc))))))
(def slurp-forward
(fn [{{:keys [loc pos]} :magic/cursor
:as cm}]
(let [end-edge-loc (slurp-parent loc pos)
start-edge-loc (nav/include-prefix-parents end-edge-loc)
{:keys [tag] :as node} (z/node start-edge-loc)]
(when (and node (not= :base tag))
(let [right-bracket (second (node/edges (z/node end-edge-loc)))
last-child (some->> (z/children end-edge-loc)
(remove node/whitespace?)
(last))]
(when-let [next-form (some->> (z/rights start-edge-loc)
(remove node/whitespace?)
first)]
(let [form-content (emit/string next-form)
replace-start (if last-child (range/bounds last-child :right)
(-> (z/node end-edge-loc)
(range/inner-range)
(range/bounds :right)))
replace-end (select-keys next-form [:end-line :end-column])
pad-start (and last-child
(or (not (boundary? (first form-content)))
(not (boundary? (last (emit/string last-child))))))
cur (.getCursor cm)]
(cm/replace-range! cm (str
(when pad-start " ")
form-content
right-bracket)
(merge replace-start replace-end))
(.setCursor cm cur))))))
true))
(def unslurp-forward
(fn [{{:keys [loc pos]} :magic/cursor
:as editor}]
(let [end-edge-loc (slurp-parent loc pos)
end-edge-node (some-> end-edge-loc z/node)]
(when (and end-edge-node (not= :base (:tag end-edge-node)))
(when-let [last-child (->> (z/children end-edge-loc)
(remove node/whitespace?)
(last))]
(edit/with-formatting editor
(-> (pointer editor (cm/range->Pos (range/end end-edge-node)))
(insert! (str " " (emit/string last-child) " ")))
(cm/replace-range! editor (-> (cm/range-text editor last-child)
(str/replace #"[^\n]" " ")) last-child)
(cm/set-cursor! editor (first (sort [(cm/range->Pos pos)
(-> (range/inner-range end-edge-node)
(range/end)
(cm/range->Pos))])))))))
true))
(defn cursor-selection-edge [editor side]
(cm/set-cursor! editor (-> (cm/current-selection-bounds editor)
(range/bounds side)))
true)
(defn cursor-line-edge [editor side]
(let [cursor (cm/get-cursor editor)
line-i (.-line cursor)
line (.getLine editor line-i)
padding (count (second (re-find (case side :left #"^(\s+).*"
:right #".*?(\s+)$") line)))]
(cm/set-cursor! editor (cm/Pos line-i (case side :left padding
:right (- (count line) padding)))))
true)
(defn node-symbol [node]
(when (= :token (.-tag node))
(-> (emit/sexp node)
(util/guard-> symbol?))))
(defn eldoc-symbol
([loc pos]
(eldoc-symbol (cond-> loc
(= (range/bounds pos :left)
(some-> loc (z/node) (range/bounds :left))) (z/up))))
([loc]
(some->> loc
(nav/closest #(#{:list :fn} (.-tag (z/node %))))
(z/children)
(first)
(node-symbol)))) |
2421f2d8142c64153630b60b490d440c9746dae4c8c42fcd3ae2ff44b1c13f69 | Commonfare-net/macao-social-wallet | transaction_form.clj | Freecoin - digital social currency toolkit
part of Decentralized Citizen Engagement Technologies ( D - CENT )
R&D funded by the European Commission ( FP7 / CAPS 610349 )
Copyright ( C ) 2015 Dyne.org foundation
Copyright ( C ) 2015 Thoughtworks , Inc.
designed , written and maintained by
< >
;; With contributions by
< >
< >
< >
;; 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 </>.
(ns freecoin.handlers.transaction-form
(:require [liberator.core :as lc]
[liberator.representation :as lr]
[ring.util.response :as r]
[freecoin-lib.db
[wallet :as wallet]
[uuid :as uuid]
[confirmation :as confirmation]]
[just-auth.db.account :as account]
[freecoin.context-helpers :as ch]
[freecoin.routes :as routes]
[freecoin-lib.core :as blockchain]
[freecoin.auth :as auth]
[freecoin-lib.config :as config]
[freecoin.views :as fv]
[freecoin.form_helpers :as fh]
[freecoin.views.transaction-form :as transaction-form]
[taoensso.timbre :as log]))
(lc/defresource get-transaction-to [wallet-store]
:allowed-methods [:get]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:handle-ok (fn [ctx]
(if-let [email (get-in ctx [:request :params :email])]
(-> (transaction-form/build-transaction-to ctx)
(fv/render-page)))))
(lc/defresource get-transaction-form [wallet-store]
:allowed-methods [:get]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:handle-ok (fn [ctx]
(->> (:request ctx)
transaction-form/build
fv/render-page)))
(lc/defresource post-transaction-form [blockchain wallet-store confirmation-store account-store]
:allowed-methods [:post]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:allowed?
(fn [ctx]
(let [{:keys [status data problems]}
(fh/validate-form (transaction-form/transaction-form-spec)
(ch/context->params ctx))
amount (:amount data)
sender-email (ch/context->signed-in-email ctx)
sender-balance (blockchain/get-balance blockchain sender-email)]
(if (= :ok status)
(if-let [recipient-wallet
(wallet/fetch wallet-store (:recipient data))]
;; Check that the balance aftter the transaction would be above 0 unless it is made by the admin
(if (or
(>= (- sender-balance amount) 0)
(some #{:admin} (:flags (account/fetch account-store sender-email))))
{::form-data data
::recipient-wallet recipient-wallet}
[false (fh/form-problem :amount "Balance is not sufficient to perform this transaction")])
[false (fh/form-problem :recipient "Not found")])
[false (fh/form-problem problems)])))
:post!
(fn [ctx]
(let [amount (get-in ctx [::form-data :amount])
tags (get-in ctx [::form-data :tags] #{})
sender-email (ch/context->signed-in-email ctx)
recipient (::recipient-wallet ctx)]
(when-let [confirmation (confirmation/new-transaction-confirmation!
confirmation-store uuid/uuid
sender-email (:email recipient) amount tags)]
{::confirmation confirmation})))
:post-redirect?
(fn [ctx]
{:location (routes/absolute-path
:get-confirm-transaction-form
:confirmation-uid (:uid (::confirmation ctx)))})
:handle-forbidden
(fn [ctx]
(-> (routes/absolute-path :get-transaction-form)
r/redirect
(fh/flash-form-problem ctx)
lr/ring-response)))
| null | https://raw.githubusercontent.com/Commonfare-net/macao-social-wallet/d3724d6c706cdaa669c59da439fe48b0373e17b7/src/freecoin/handlers/transaction_form.clj | clojure | With contributions by
This program is free software: you can redistribute it and/or modify
(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.
along with this program. If not, see </>.
Check that the balance aftter the transaction would be above 0 unless it is made by the admin | Freecoin - digital social currency toolkit
part of Decentralized Citizen Engagement Technologies ( D - CENT )
R&D funded by the European Commission ( FP7 / CAPS 610349 )
Copyright ( C ) 2015 Dyne.org foundation
Copyright ( C ) 2015 Thoughtworks , Inc.
designed , written and maintained by
< >
< >
< >
< >
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
You should have received a copy of the GNU Affero General Public License
(ns freecoin.handlers.transaction-form
(:require [liberator.core :as lc]
[liberator.representation :as lr]
[ring.util.response :as r]
[freecoin-lib.db
[wallet :as wallet]
[uuid :as uuid]
[confirmation :as confirmation]]
[just-auth.db.account :as account]
[freecoin.context-helpers :as ch]
[freecoin.routes :as routes]
[freecoin-lib.core :as blockchain]
[freecoin.auth :as auth]
[freecoin-lib.config :as config]
[freecoin.views :as fv]
[freecoin.form_helpers :as fh]
[freecoin.views.transaction-form :as transaction-form]
[taoensso.timbre :as log]))
(lc/defresource get-transaction-to [wallet-store]
:allowed-methods [:get]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:handle-ok (fn [ctx]
(if-let [email (get-in ctx [:request :params :email])]
(-> (transaction-form/build-transaction-to ctx)
(fv/render-page)))))
(lc/defresource get-transaction-form [wallet-store]
:allowed-methods [:get]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:handle-ok (fn [ctx]
(->> (:request ctx)
transaction-form/build
fv/render-page)))
(lc/defresource post-transaction-form [blockchain wallet-store confirmation-store account-store]
:allowed-methods [:post]
:available-media-types ["text/html"]
:authorized? #(auth/is-signed-in %)
:allowed?
(fn [ctx]
(let [{:keys [status data problems]}
(fh/validate-form (transaction-form/transaction-form-spec)
(ch/context->params ctx))
amount (:amount data)
sender-email (ch/context->signed-in-email ctx)
sender-balance (blockchain/get-balance blockchain sender-email)]
(if (= :ok status)
(if-let [recipient-wallet
(wallet/fetch wallet-store (:recipient data))]
(if (or
(>= (- sender-balance amount) 0)
(some #{:admin} (:flags (account/fetch account-store sender-email))))
{::form-data data
::recipient-wallet recipient-wallet}
[false (fh/form-problem :amount "Balance is not sufficient to perform this transaction")])
[false (fh/form-problem :recipient "Not found")])
[false (fh/form-problem problems)])))
:post!
(fn [ctx]
(let [amount (get-in ctx [::form-data :amount])
tags (get-in ctx [::form-data :tags] #{})
sender-email (ch/context->signed-in-email ctx)
recipient (::recipient-wallet ctx)]
(when-let [confirmation (confirmation/new-transaction-confirmation!
confirmation-store uuid/uuid
sender-email (:email recipient) amount tags)]
{::confirmation confirmation})))
:post-redirect?
(fn [ctx]
{:location (routes/absolute-path
:get-confirm-transaction-form
:confirmation-uid (:uid (::confirmation ctx)))})
:handle-forbidden
(fn [ctx]
(-> (routes/absolute-path :get-transaction-form)
r/redirect
(fh/flash-form-problem ctx)
lr/ring-response)))
|
f9b6f2fb6f6f86be94f985739f1e1617967721fb57cf9f3f714d9398cf883514 | monadbobo/ocaml-core | bitarray.ml | open Core.Std
a single 63 bit chunk of the array , bounds checking is left to the main module . We can
only use 62 bits , because of the sign bit
only use 62 bits, because of the sign bit *)
module Int63_chunk : sig
type t
val empty : t
val get : t -> int -> bool
val set : t -> int -> bool -> t
end = struct
open Int63
type t = Int63.t
let empty = zero
let get t i = bit_and t (shift_left one i) > zero
let set t i v =
if v then bit_or t (shift_left one i)
else bit_and t (bit_xor minus_one (shift_left one i))
end
type t = {
data: Int63_chunk.t Array.t;
length: int
}
We ca n't use the sign bit , so we only get to use 62 bits
let bits_per_bucket = 62
let create sz =
if sz < 0 || sz > (Array.max_length * bits_per_bucket) then
invalid_argf "invalid size" ();
{ data = Array.create (1 + (sz / bits_per_bucket)) Int63_chunk.empty;
length = sz }
;;
let bucket i = i / bits_per_bucket
let index i = i mod bits_per_bucket
let bounds_check t i =
if i < 0 || i >= t.length then
invalid_argf "Bitarray: out of bounds" ();
;;
let get t i =
bounds_check t i;
Int63_chunk.get t.data.(bucket i) (index i)
;;
let set t i v =
bounds_check t i;
let bucket = bucket i in
t.data.(bucket) <- Int63_chunk.set t.data.(bucket) (index i) v
;;
let clear t =
Array.fill t.data ~pos:0 ~len:(Array.length t.data) Int63_chunk.empty
;;
let fold =
let rec loop t n ~init ~f =
if n < t.length then
loop t (n + 1) ~init:(f init (get t n)) ~f
else
init
in
fun t ~init ~f -> loop t 0 ~init ~f
;;
let iter t ~f = fold t ~init:() ~f:(fun _ v -> f v)
let sexp_of_t t =
Array.sexp_of_t Bool.sexp_of_t
(Array.init t.length ~f:(fun i -> get t i))
;;
let t_of_sexp sexp =
let a = Array.t_of_sexp Bool.t_of_sexp sexp in
let t = create (Array.length a) in
Array.iteri a ~f:(fun i v -> set t i v);
t
;;
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/bitarray.ml | ocaml | open Core.Std
a single 63 bit chunk of the array , bounds checking is left to the main module . We can
only use 62 bits , because of the sign bit
only use 62 bits, because of the sign bit *)
module Int63_chunk : sig
type t
val empty : t
val get : t -> int -> bool
val set : t -> int -> bool -> t
end = struct
open Int63
type t = Int63.t
let empty = zero
let get t i = bit_and t (shift_left one i) > zero
let set t i v =
if v then bit_or t (shift_left one i)
else bit_and t (bit_xor minus_one (shift_left one i))
end
type t = {
data: Int63_chunk.t Array.t;
length: int
}
We ca n't use the sign bit , so we only get to use 62 bits
let bits_per_bucket = 62
let create sz =
if sz < 0 || sz > (Array.max_length * bits_per_bucket) then
invalid_argf "invalid size" ();
{ data = Array.create (1 + (sz / bits_per_bucket)) Int63_chunk.empty;
length = sz }
;;
let bucket i = i / bits_per_bucket
let index i = i mod bits_per_bucket
let bounds_check t i =
if i < 0 || i >= t.length then
invalid_argf "Bitarray: out of bounds" ();
;;
let get t i =
bounds_check t i;
Int63_chunk.get t.data.(bucket i) (index i)
;;
let set t i v =
bounds_check t i;
let bucket = bucket i in
t.data.(bucket) <- Int63_chunk.set t.data.(bucket) (index i) v
;;
let clear t =
Array.fill t.data ~pos:0 ~len:(Array.length t.data) Int63_chunk.empty
;;
let fold =
let rec loop t n ~init ~f =
if n < t.length then
loop t (n + 1) ~init:(f init (get t n)) ~f
else
init
in
fun t ~init ~f -> loop t 0 ~init ~f
;;
let iter t ~f = fold t ~init:() ~f:(fun _ v -> f v)
let sexp_of_t t =
Array.sexp_of_t Bool.sexp_of_t
(Array.init t.length ~f:(fun i -> get t i))
;;
let t_of_sexp sexp =
let a = Array.t_of_sexp Bool.t_of_sexp sexp in
let t = create (Array.length a) in
Array.iteri a ~f:(fun i v -> set t i v);
t
;;
| |
2f7356336e51d090f24c23402e57acb99a4b6800654e055aeed51c6a33fc30f1 | softwarelanguageslab/maf | R5RS_various_regex-2.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 0
* negated predicates : 5
* swapped branches : 3
* calls to i d fun : 4
(letrec ((debug-trace (lambda ()
(<change>
'do-nothing
((lambda (x) x) 'do-nothing))))
(regex-NULL #f)
(regex-BLANK #t)
(regex-alt? (lambda (re)
(if (pair? re) (eq? (car re) 'alt) #f)))
(regex-seq? (lambda (re)
(if (pair? re) (eq? (car re) 'seq) #f)))
(regex-rep? (lambda (re)
(if (pair? re) (eq? (car re) 'rep) #f)))
(regex-null? (lambda (re)
(eq? re #f)))
(regex-empty? (lambda (re)
(eq? re #t)))
(regex-atom? (lambda (re)
(let ((__or_res (char? re)))
(if (<change> __or_res (not __or_res))
__or_res
(symbol? re)))))
(match-seq (lambda (re f)
(if (regex-seq? re) (f (cadr re) (caddr re)) #f)))
(match-alt (lambda (re f)
(if (regex-alt? re) (f (cadr re) (caddr re)) #f)))
(match-rep (lambda (re f)
(if (regex-rep? re)
(<change>
(f (cadr re))
#f)
(<change>
#f
(f (cadr re))))))
(seq (lambda (pat1 pat2)
(if (<change> (regex-null? pat1) (not (regex-null? pat1)))
regex-NULL
(if (regex-null? pat2)
(<change>
regex-NULL
(if (not (regex-empty? pat1))
pat2
(if (regex-empty? pat2)
pat1
(cons 'seq (cons pat1 (cons pat2 ()))))))
(<change>
(if (regex-empty? pat1)
pat2
(if (regex-empty? pat2)
pat1
(cons 'seq (cons pat1 (cons pat2 ())))))
regex-NULL)))))
(alt (lambda (pat1 pat2)
(if (regex-null? pat1)
pat2
(if (regex-null? pat2)
pat1
(cons 'alt (cons pat1 (cons pat2 ())))))))
(rep (lambda (pat)
(if (regex-null? pat)
regex-BLANK
(if (regex-empty? pat)
regex-BLANK
(cons 'rep (cons pat ()))))))
(regex-empty (lambda (re)
(<change>
(if (regex-empty? re)
#t
(if (regex-null? re)
#f
(if (regex-atom? re)
#f
(let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(if (regex-rep? re) #t #f))))))))
((lambda (x) x)
(if (regex-empty? re)
#t
(if (regex-null? re)
#f
(if (<change> (regex-atom? re) (not (regex-atom? re)))
#f
(let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (regex-empty pat1) (regex-empty pat2))))))
(if (<change> __cond-empty-body (not __cond-empty-body))
__cond-empty-body
(if (regex-rep? re) #t #f))))))))))))
(regex-derivative (lambda (re c)
(debug-trace)
(if (regex-empty? re)
regex-NULL
(if (regex-null? re)
regex-NULL
(if (eq? c re)
(<change>
regex-BLANK
(if (regex-atom? re)
regex-NULL
(let ((__cond-empty-body (match-seq
re
(lambda (pat1 pat2)
regex-empty
(alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c)))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat))))))
((lambda (x) x) (if __cond-empty-body __cond-empty-body regex-NULL)))))))))
(<change>
(if (regex-atom? re)
regex-NULL
(let ((__cond-empty-body (match-seq
re
(lambda (pat1 pat2)
(alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c)))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat))))))
(if __cond-empty-body
__cond-empty-body
regex-NULL)))))))
regex-BLANK))))))
(d/dc regex-derivative)
(regex-match (lambda (pattern data)
(if (null? data)
(regex-empty? (regex-empty pattern))
(regex-match (d/dc pattern (car data)) (cdr data)))))
(check-expect (lambda (check expect)
(<change>
(equal? check expect)
((lambda (x) x) (equal? check expect)))))
(res (check-expect
(regex-match
(__toplevel_cons
'seq
(__toplevel_cons 'foo (__toplevel_cons (__toplevel_cons 'rep (__toplevel_cons 'bar ())) ())))
(__toplevel_cons 'foo (__toplevel_cons 'bar ())))
#t)))
res) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_various_regex-2.scm | scheme | Changes: | * removed : 0
* added : 1
* swaps : 0
* negated predicates : 5
* swapped branches : 3
* calls to i d fun : 4
(letrec ((debug-trace (lambda ()
(<change>
'do-nothing
((lambda (x) x) 'do-nothing))))
(regex-NULL #f)
(regex-BLANK #t)
(regex-alt? (lambda (re)
(if (pair? re) (eq? (car re) 'alt) #f)))
(regex-seq? (lambda (re)
(if (pair? re) (eq? (car re) 'seq) #f)))
(regex-rep? (lambda (re)
(if (pair? re) (eq? (car re) 'rep) #f)))
(regex-null? (lambda (re)
(eq? re #f)))
(regex-empty? (lambda (re)
(eq? re #t)))
(regex-atom? (lambda (re)
(let ((__or_res (char? re)))
(if (<change> __or_res (not __or_res))
__or_res
(symbol? re)))))
(match-seq (lambda (re f)
(if (regex-seq? re) (f (cadr re) (caddr re)) #f)))
(match-alt (lambda (re f)
(if (regex-alt? re) (f (cadr re) (caddr re)) #f)))
(match-rep (lambda (re f)
(if (regex-rep? re)
(<change>
(f (cadr re))
#f)
(<change>
#f
(f (cadr re))))))
(seq (lambda (pat1 pat2)
(if (<change> (regex-null? pat1) (not (regex-null? pat1)))
regex-NULL
(if (regex-null? pat2)
(<change>
regex-NULL
(if (not (regex-empty? pat1))
pat2
(if (regex-empty? pat2)
pat1
(cons 'seq (cons pat1 (cons pat2 ()))))))
(<change>
(if (regex-empty? pat1)
pat2
(if (regex-empty? pat2)
pat1
(cons 'seq (cons pat1 (cons pat2 ())))))
regex-NULL)))))
(alt (lambda (pat1 pat2)
(if (regex-null? pat1)
pat2
(if (regex-null? pat2)
pat1
(cons 'alt (cons pat1 (cons pat2 ())))))))
(rep (lambda (pat)
(if (regex-null? pat)
regex-BLANK
(if (regex-empty? pat)
regex-BLANK
(cons 'rep (cons pat ()))))))
(regex-empty (lambda (re)
(<change>
(if (regex-empty? re)
#t
(if (regex-null? re)
#f
(if (regex-atom? re)
#f
(let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(if (regex-rep? re) #t #f))))))))
((lambda (x) x)
(if (regex-empty? re)
#t
(if (regex-null? re)
#f
(if (<change> (regex-atom? re) (not (regex-atom? re)))
#f
(let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (regex-empty pat1) (regex-empty pat2))))))
(if (<change> __cond-empty-body (not __cond-empty-body))
__cond-empty-body
(if (regex-rep? re) #t #f))))))))))))
(regex-derivative (lambda (re c)
(debug-trace)
(if (regex-empty? re)
regex-NULL
(if (regex-null? re)
regex-NULL
(if (eq? c re)
(<change>
regex-BLANK
(if (regex-atom? re)
regex-NULL
(let ((__cond-empty-body (match-seq
re
(lambda (pat1 pat2)
regex-empty
(alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c)))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat))))))
((lambda (x) x) (if __cond-empty-body __cond-empty-body regex-NULL)))))))))
(<change>
(if (regex-atom? re)
regex-NULL
(let ((__cond-empty-body (match-seq
re
(lambda (pat1 pat2)
(alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c)))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c))))))
(if __cond-empty-body
__cond-empty-body
(let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat))))))
(if __cond-empty-body
__cond-empty-body
regex-NULL)))))))
regex-BLANK))))))
(d/dc regex-derivative)
(regex-match (lambda (pattern data)
(if (null? data)
(regex-empty? (regex-empty pattern))
(regex-match (d/dc pattern (car data)) (cdr data)))))
(check-expect (lambda (check expect)
(<change>
(equal? check expect)
((lambda (x) x) (equal? check expect)))))
(res (check-expect
(regex-match
(__toplevel_cons
'seq
(__toplevel_cons 'foo (__toplevel_cons (__toplevel_cons 'rep (__toplevel_cons 'bar ())) ())))
(__toplevel_cons 'foo (__toplevel_cons 'bar ())))
#t)))
res) |
fb656e4083382314dbd086617847fd20503faa358a2a9df4329866a62f246492 | MinaProtocol/mina | events_blocks_request.ml |
* This file has been generated by the OCamlClientCodegen generator for openapi - generator .
*
* Generated by : -generator.tech
*
* Schema Events_blocks_request.t : EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state .
* This file has been generated by the OCamlClientCodegen generator for openapi-generator.
*
* Generated by: -generator.tech
*
* Schema Events_blocks_request.t : EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state.
*)
type t =
{ network_identifier : Network_identifier.t
; (* offset is the offset into the event stream to sync events from. If this field is not populated, we return the limit events backwards from tip. If this is set to 0, we start from the beginning. *)
offset : int64 option [@default None]
; (* limit is the maximum number of events to fetch in one call. The implementation may return <= limit events. *)
limit : int64 option [@default None]
}
[@@deriving yojson { strict = false }, show, eq]
* EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state .
let create (network_identifier : Network_identifier.t) : t =
{ network_identifier; offset = None; limit = None }
| null | https://raw.githubusercontent.com/MinaProtocol/mina/a80b00221953c26ff158e7375a948b5fa9e7bd8b/src/lib/rosetta_models/events_blocks_request.ml | ocaml | offset is the offset into the event stream to sync events from. If this field is not populated, we return the limit events backwards from tip. If this is set to 0, we start from the beginning.
limit is the maximum number of events to fetch in one call. The implementation may return <= limit events. |
* This file has been generated by the OCamlClientCodegen generator for openapi - generator .
*
* Generated by : -generator.tech
*
* Schema Events_blocks_request.t : EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state .
* This file has been generated by the OCamlClientCodegen generator for openapi-generator.
*
* Generated by: -generator.tech
*
* Schema Events_blocks_request.t : EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state.
*)
type t =
{ network_identifier : Network_identifier.t
offset : int64 option [@default None]
limit : int64 option [@default None]
}
[@@deriving yojson { strict = false }, show, eq]
* EventsBlocksRequest is utilized to fetch a sequence of BlockEvents indicating which blocks were added and removed from storage to reach the current state .
let create (network_identifier : Network_identifier.t) : t =
{ network_identifier; offset = None; limit = None }
|
66d5cf2ba4d88f58c8b366bfaf7955be5ad77edadc301edd453defeac3a362a3 | CloudI/CloudI | command_props.erl | -*- coding : utf-8 -*-
-*- erlang - indent - level : 2 -*-
%%% -------------------------------------------------------------------
Copyright 2010 - 2016 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr 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.
%%%
%%% PropEr 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 PropEr. If not, see </>.
2010 - 2016 , and
%%% @version {@version}
@author
-module(command_props).
-include_lib("proper/include/proper.hrl").
-define(MOD, ets_counter).
-define(MOD1, pdict_statem).
ne_nd_list(ElemType) ->
?LET(L, non_empty(list(ElemType)), lists:usort(L)).
short_ne_nd_list(ElemType) ->
?LET(L, resize(8, non_empty(list(ElemType))), lists:usort(L)).
no_duplicates(L) ->
length(L) =:= length(lists:usort(L)).
prop_index() ->
?FORALL(List, ne_nd_list(integer()),
?FORALL(X, union(List),
lists:nth(proper_statem:index(X, List), List) =:= X)).
prop_all_insertions() ->
?FORALL(List, list(integer()),
begin
Len = length(List),
?FORALL(Limit, range(1,Len+1),
?FORALL(X, integer(),
begin
AllIns = proper_statem:all_insertions(X, Limit, List),
length(AllIns) =:= Limit
end))
end).
prop_insert_all() ->
?FORALL(List, short_ne_nd_list(integer()),
begin
Len = length(List),
{L1, L2} = lists:split(Len div 2, List),
AllIns = proper_statem:insert_all(L1, L2),
?WHENFAIL(io:format("~nList: ~w, L1: ~w, L2: ~w~nAllIns: ~w~n",
[List,L1,L2,AllIns]),
lists:all(fun(L) ->
length(L) =:= Len andalso
no_duplicates(L) andalso
lists:subtract(L,L2) =:= L1
end, AllIns))
end).
prop_zip() ->
?FORALL({X, Y}, {list(), list()},
begin
LenX = length(X),
LenY = length(Y),
Res = if LenX < LenY ->
lists:zip(X, lists:sublist(Y, LenX));
LenX =:= LenY ->
lists:zip(X, Y);
LenX > LenY ->
lists:zip(lists:sublist(X, LenY), Y)
end,
equals(zip(X, Y), Res)
end).
prop_state_after() ->
?FORALL(Cmds, proper_statem:commands(?MOD1),
begin
SymbState = proper_statem:state_after(?MOD1, Cmds),
{_, S, ok} = proper_statem:run_commands(?MOD1, Cmds),
?MOD1:clean_up(),
equals(proper_symb:eval(SymbState), S)
end).
prop_parallel_ets_counter() ->
?FORALL({_Seq, [P1, P2]}, proper_statem:parallel_commands(?MOD),
begin
Len1 = length(P1),
Len2 = length(P2),
Len1 =:= Len2 orelse (Len1 + 1) =:= Len2
end).
prop_check_true() ->
?FORALL({Seq, Par}, proper_statem:parallel_commands(?MOD),
begin
?MOD:clean_up(),
?MOD:set_up(),
{{_, State, ok}, Env} = proper_statem:run(?MOD, Seq, []),
Res = [proper_statem:execute(C, Env, ?MOD) || C <- Par],
V = proper_statem:check(?MOD, State, Env, false, [], Res),
equals(V, true)
end).
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/proper/test/command_props.erl | erlang | -------------------------------------------------------------------
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with PropEr. If not, see </>.
@version {@version} | -*- coding : utf-8 -*-
-*- erlang - indent - level : 2 -*-
Copyright 2010 - 2016 < > ,
< >
and < >
This file is part of PropEr .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
2010 - 2016 , and
@author
-module(command_props).
-include_lib("proper/include/proper.hrl").
-define(MOD, ets_counter).
-define(MOD1, pdict_statem).
ne_nd_list(ElemType) ->
?LET(L, non_empty(list(ElemType)), lists:usort(L)).
short_ne_nd_list(ElemType) ->
?LET(L, resize(8, non_empty(list(ElemType))), lists:usort(L)).
no_duplicates(L) ->
length(L) =:= length(lists:usort(L)).
prop_index() ->
?FORALL(List, ne_nd_list(integer()),
?FORALL(X, union(List),
lists:nth(proper_statem:index(X, List), List) =:= X)).
prop_all_insertions() ->
?FORALL(List, list(integer()),
begin
Len = length(List),
?FORALL(Limit, range(1,Len+1),
?FORALL(X, integer(),
begin
AllIns = proper_statem:all_insertions(X, Limit, List),
length(AllIns) =:= Limit
end))
end).
prop_insert_all() ->
?FORALL(List, short_ne_nd_list(integer()),
begin
Len = length(List),
{L1, L2} = lists:split(Len div 2, List),
AllIns = proper_statem:insert_all(L1, L2),
?WHENFAIL(io:format("~nList: ~w, L1: ~w, L2: ~w~nAllIns: ~w~n",
[List,L1,L2,AllIns]),
lists:all(fun(L) ->
length(L) =:= Len andalso
no_duplicates(L) andalso
lists:subtract(L,L2) =:= L1
end, AllIns))
end).
prop_zip() ->
?FORALL({X, Y}, {list(), list()},
begin
LenX = length(X),
LenY = length(Y),
Res = if LenX < LenY ->
lists:zip(X, lists:sublist(Y, LenX));
LenX =:= LenY ->
lists:zip(X, Y);
LenX > LenY ->
lists:zip(lists:sublist(X, LenY), Y)
end,
equals(zip(X, Y), Res)
end).
prop_state_after() ->
?FORALL(Cmds, proper_statem:commands(?MOD1),
begin
SymbState = proper_statem:state_after(?MOD1, Cmds),
{_, S, ok} = proper_statem:run_commands(?MOD1, Cmds),
?MOD1:clean_up(),
equals(proper_symb:eval(SymbState), S)
end).
prop_parallel_ets_counter() ->
?FORALL({_Seq, [P1, P2]}, proper_statem:parallel_commands(?MOD),
begin
Len1 = length(P1),
Len2 = length(P2),
Len1 =:= Len2 orelse (Len1 + 1) =:= Len2
end).
prop_check_true() ->
?FORALL({Seq, Par}, proper_statem:parallel_commands(?MOD),
begin
?MOD:clean_up(),
?MOD:set_up(),
{{_, State, ok}, Env} = proper_statem:run(?MOD, Seq, []),
Res = [proper_statem:execute(C, Env, ?MOD) || C <- Par],
V = proper_statem:check(?MOD, State, Env, false, [], Res),
equals(V, true)
end).
|
ac88fee4c32e3ed8fc7833eda5c79ede8d05417737dd4e672304653c92d408aa | janestreet/virtual_dom | vdom_keyboard.ml | module Grouped_help_text = Grouped_help_text
module Help_text = Help_text
module Keyboard_event_handler = Keyboard_event_handler
module Keystroke = Keystroke
module Variable_keyboard_event_handler = Variable_keyboard_event_handler
module Keyboard_event = Keyboard_event
let with_keyboard_handler node keyboard_handler =
let open Virtual_dom.Vdom in
Node.div
~attr:
(Attr.on_keydown (fun event ->
Keyboard_event_handler.handle_or_ignore_event keyboard_handler event))
[ node ]
;;
| null | https://raw.githubusercontent.com/janestreet/virtual_dom/53466b0f06875cafd30ee2d22536e494e7237b3a/keyboard/src/vdom_keyboard.ml | ocaml | module Grouped_help_text = Grouped_help_text
module Help_text = Help_text
module Keyboard_event_handler = Keyboard_event_handler
module Keystroke = Keystroke
module Variable_keyboard_event_handler = Variable_keyboard_event_handler
module Keyboard_event = Keyboard_event
let with_keyboard_handler node keyboard_handler =
let open Virtual_dom.Vdom in
Node.div
~attr:
(Attr.on_keydown (fun event ->
Keyboard_event_handler.handle_or_ignore_event keyboard_handler event))
[ node ]
;;
| |
485014d4e4e3bdb967512177f0adb75b8596bd14e1da648a7f9f09012a31b039 | titola/incudine | error.lisp | Copyright ( c ) 2013 - 2019
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
;;;
;;; This library is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Lesser General Public License for more details.
;;;
You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
(in-package :portmidi)
(define-condition portmidi-error (cl:error) ()
(:documentation "All types of PortMidi error conditions inherit from
this condition."))
(define-condition allocation-error (portmidi-error storage-condition)
((object-type :reader object-type-of :initarg :object-type))
(:report (lambda (condition stream)
(format stream "Failed object allocation for ~A."
(object-type-of condition))))
(:documentation "Signaled if an object allocation fails.
Subtype of PORTMIDI-ERROR and STORAGE-CONDITION."))
(define-condition error-generic (portmidi-error)
((error :reader error :initarg :error))
(:report (lambda (condition stream)
(princ (get-error-text (error condition))
stream)))
(:documentation "Signaled if there is a generic PortMidi error."))
(defun allocation-error (object-type)
"Signal a PORTMIDI:ALLOCATION-ERROR for OBJECT-TYPE."
(cl:error 'allocation-error :object-type object-type))
(defun error-generic (error)
"Signal a PORTMIDI:ERROR-GENERIC."
(cl:error 'error-generic :error error))
| null | https://raw.githubusercontent.com/titola/incudine/325174a54a540f4daa67bcbb29780073c35b7b80/contrib/cl-portmidi/error.lisp | lisp |
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software | Copyright ( c ) 2013 - 2019
version 2.1 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
(in-package :portmidi)
(define-condition portmidi-error (cl:error) ()
(:documentation "All types of PortMidi error conditions inherit from
this condition."))
(define-condition allocation-error (portmidi-error storage-condition)
((object-type :reader object-type-of :initarg :object-type))
(:report (lambda (condition stream)
(format stream "Failed object allocation for ~A."
(object-type-of condition))))
(:documentation "Signaled if an object allocation fails.
Subtype of PORTMIDI-ERROR and STORAGE-CONDITION."))
(define-condition error-generic (portmidi-error)
((error :reader error :initarg :error))
(:report (lambda (condition stream)
(princ (get-error-text (error condition))
stream)))
(:documentation "Signaled if there is a generic PortMidi error."))
(defun allocation-error (object-type)
"Signal a PORTMIDI:ALLOCATION-ERROR for OBJECT-TYPE."
(cl:error 'allocation-error :object-type object-type))
(defun error-generic (error)
"Signal a PORTMIDI:ERROR-GENERIC."
(cl:error 'error-generic :error error))
|
a1f7ae269247ffb22f77f69875d8a3f4057e6f255edbbefb7db7643feeae0aff | EFanZh/EOPL-Exercises | exercise-1.22.rkt | #lang eopl
Exercise 1.22 [ ★ ★ ] ( filter - in pred lst ) returns the list of those elements in lst that satisfy the predicate pred .
;;
> ( filter - in number ? ' ( a 2 ( 1 3 ) b 7 ) )
( 2 7 )
> ( filter - in symbol ? ' ( a ( b c ) 17 foo ) )
;; (a foo)
(define filter-in
(lambda (pred lst)
(if (null? lst)
'()
(let ([element (car lst)]
[tail (filter-in pred (cdr lst))])
(if (pred element)
(cons element tail)
tail)))))
(provide filter-in)
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-1.22.rkt | racket |
(a foo) | #lang eopl
Exercise 1.22 [ ★ ★ ] ( filter - in pred lst ) returns the list of those elements in lst that satisfy the predicate pred .
> ( filter - in number ? ' ( a 2 ( 1 3 ) b 7 ) )
( 2 7 )
> ( filter - in symbol ? ' ( a ( b c ) 17 foo ) )
(define filter-in
(lambda (pred lst)
(if (null? lst)
'()
(let ([element (car lst)]
[tail (filter-in pred (cdr lst))])
(if (pred element)
(cons element tail)
tail)))))
(provide filter-in)
|
821281fcc7832d2b7514dbf5727d33ac42c1797aa27ccb05d0d1bed4f0d6374b | hdgarrood/qq-literals | Example.hs | # LANGUAGE TemplateHaskell #
module Spec.Example where
import Network.URI (URI, parseURI)
import Language.Haskell.TH.Quote (QuasiQuoter)
import QQLiterals (qqLiteral)
eitherParseURI :: String -> Either String URI
eitherParseURI str =
maybe (Left ("Failed to parse URI: " ++ str)) Right (parseURI str)
uri :: QuasiQuoter
uri = qqLiteral eitherParseURI 'eitherParseURI
| null | https://raw.githubusercontent.com/hdgarrood/qq-literals/19f3dfae03623b6ea6898096c1e6fa4cf1e749bb/test/Spec/Example.hs | haskell | # LANGUAGE TemplateHaskell #
module Spec.Example where
import Network.URI (URI, parseURI)
import Language.Haskell.TH.Quote (QuasiQuoter)
import QQLiterals (qqLiteral)
eitherParseURI :: String -> Either String URI
eitherParseURI str =
maybe (Left ("Failed to parse URI: " ++ str)) Right (parseURI str)
uri :: QuasiQuoter
uri = qqLiteral eitherParseURI 'eitherParseURI
| |
8f9510c88ad41f5c022c2fab15834f03f0d9fb256f28ba74332e624c633a08df | namin/logically | tp.clj | (ns logically.abs.tp
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l]
[clojure.core.logic.nominal :exclude [fresh hash] :as nom])
(:use [logically.abs.db]
[logically.abs.lub]))
(defn prove [db flag goals]
(conde
[(fresh [b bs]
(conso b bs goals)
(db-get-fact db b)
(prove db flag bs))]
[(== goals ())]))
(defn operatoro [db flag c]
(fresh [head body]
(c head body)
(prove db flag body)
(set-union db flag head)))
(defn iterateo [db flag c]
(conda
[(all (operatoro db flag c) fail)]
[(all (flag-retract! flag) (iterateo db flag c))]
[succeed]))
(defn go [c q]
(let [db (db-new)
flag (flag-new)]
(all
(iterateo db flag c)
(db-get-fact db q))))
| null | https://raw.githubusercontent.com/namin/logically/49e814e04ff0f5f20efa75122c0b869e400487ac/src/logically/abs/tp.clj | clojure | (ns logically.abs.tp
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l]
[clojure.core.logic.nominal :exclude [fresh hash] :as nom])
(:use [logically.abs.db]
[logically.abs.lub]))
(defn prove [db flag goals]
(conde
[(fresh [b bs]
(conso b bs goals)
(db-get-fact db b)
(prove db flag bs))]
[(== goals ())]))
(defn operatoro [db flag c]
(fresh [head body]
(c head body)
(prove db flag body)
(set-union db flag head)))
(defn iterateo [db flag c]
(conda
[(all (operatoro db flag c) fail)]
[(all (flag-retract! flag) (iterateo db flag c))]
[succeed]))
(defn go [c q]
(let [db (db-new)
flag (flag-new)]
(all
(iterateo db flag c)
(db-get-fact db q))))
| |
ed6bc6cbdfd71f9c02bbeb9973a78a089bac21326c941772b12c3a7edd42381f | alanz/ghc-exactprint | TH2.hs | Bloc comment
-}
# LANGUAGE PolyKinds #
module Language.Grammars.AspectAG.TH where
import Data.GenRec
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/309efa8689e1ce2407523ba2ebe058b97757ba8b/tests/examples/ghc92/TH2.hs | haskell | Bloc comment
-}
# LANGUAGE PolyKinds #
module Language.Grammars.AspectAG.TH where
import Data.GenRec
| |
5971c7e3cc5bd3437d0642d03d7956a162fa94b0e52ee0e96659341f27e6e57c | leonoel/clope | impl.clj | (ns ^:no-doc clope.impl
(:import (clope.impl Rope) (java.io Writer)))
(defmethod print-method Rope [^Rope r ^Writer w]
(.write w "#rope")
(print-method {:hash (.hashCode r) :size (.size r)} w))
(defn wrap [^bytes bytes]
(when (pos? (alength bytes)) (Rope/wrap bytes)))
(defn join [^Rope l ^Rope r]
(Rope/join l r))
(defn size [^Rope r]
(.size r))
(defn subr [^Rope r ^long s ^long e]
(.subr r s e)) | null | https://raw.githubusercontent.com/leonoel/clope/1980656d4be72040a9b2007a64f93c9ff2c6ee43/src/clope/impl.clj | clojure | (ns ^:no-doc clope.impl
(:import (clope.impl Rope) (java.io Writer)))
(defmethod print-method Rope [^Rope r ^Writer w]
(.write w "#rope")
(print-method {:hash (.hashCode r) :size (.size r)} w))
(defn wrap [^bytes bytes]
(when (pos? (alength bytes)) (Rope/wrap bytes)))
(defn join [^Rope l ^Rope r]
(Rope/join l r))
(defn size [^Rope r]
(.size r))
(defn subr [^Rope r ^long s ^long e]
(.subr r s e)) | |
b8decad146adbdd23cb816759d68ae328fc39e584c11247969d89ae60389ebed | racket/redex | enum.rkt | #lang racket/base
(require racket/bool
racket/contract
racket/function
racket/list
racket/math
racket/match
racket/promise
racket/set
data/enumerate/lib/unsafe
"env.rkt"
"error.rkt"
"lang-struct.rkt"
"match-a-pattern.rkt"
"preprocess-pat.rkt"
"preprocess-lang.rkt"
"ambiguous.rkt")
(provide
enum-test-support
enum-count
finite-enum?
(contract-out
[lang-enumerators (-> (listof nt?)
(hash/c symbol? (listof any/c)) ;; any/c is compiled-pattern
(promise/c (listof nt?))
procedure? ;; this works around a circularity at the module level
lang-enum?)]
[pat-enumerator (-> lang-enum?
any/c ;; pattern
ambiguity-cache?
flat-contract?
(or/c #f enum?))]
[term-index (-> lang-enum?
any/c ;; pattern
any/c ;; term
(or/c exact-nonnegative-integer? #f))]
[enum-ith (-> enum? exact-nonnegative-integer? any/c)]
[lang-enum? (-> any/c boolean?)]
[enum? (-> any/c boolean?)]))
(define enum-test-support (make-parameter #f))
;; nt-enums : hash[sym -o> (or/c #f enum)]
;; cc-enums : promise/c (hash[sym -o> (or/c #f enum)])
;; unused-var/e : enum
(struct lang-enum (nt-enums delayed-cc-enums unused-var/e unparse-term+pat-nt-ht))
(struct production (n term) #:transparent)
(struct repeat (n terms) #:transparent)
(struct name-ref (name) #:transparent)
(struct misname-ref (name tag) #:transparent)
(struct nrep-ref (name subpat) #:transparent)
(struct decomp (ctx term) #:transparent)
(struct hide-hole (term) #:transparent)
;; Top level exports
(define (enum-ith e x) (from-nat e x))
(define (lang-enumerators lang orig-clang-all-ht cc-lang call-nt-proc/bool)
(define clang-all-ht (hash-copy orig-clang-all-ht))
(define unused-var/e
(apply except/e
symbol/e
(used-vars lang)))
(cond
;; when the language itself has a `(cross ...) pattern, then we
;; cannot assume that there are no references from the main language
;; to the compatible closure language, so we just combine them here
;; and process them and then separate them back out later, giving up
;; on the laziness in computing the compatible closure-related stuff
[(or (enum-test-support) (has-cross? lang))
(define forced-cc-lang (force cc-lang))
;; do a check that might not actually be necessary but if this
;; were to fail, things would be go wrong in a confusing way later
(let ()
(define all-nts (make-hash))
(for ([nt (in-list lang)])
(hash-set! all-nts (nt-name nt) #t))
(for ([nt (in-list forced-cc-lang)])
(when (hash-ref all-nts (nt-name nt) #f)
(error 'enum.rkt
"cannot cope with the non-terminal ~s, as it collides with on from the compatible closure language"
(nt-name nt)))))
;; we combine everything here and dump all enums into `all-enums`
(define all-enums (make-hash))
(define-values (fin-lang rec-lang cant-enumerate-table)
(sep-lang (append lang forced-cc-lang)
clang-all-ht))
(define unparse-term+pat-nt-ht
(build-nt-unparse-term+pat (append fin-lang rec-lang)
;; recombine the productions to make sure they are in
;; the same order as they are in the forwards enumeration
clang-all-ht
call-nt-proc/bool))
(define l-enum
;; here we just use `all-enums` in both places
(lang-enum all-enums (delay all-enums) unused-var/e unparse-term+pat-nt-ht))
(make-lang-table! l-enum all-enums fin-lang rec-lang cant-enumerate-table)
l-enum]
[else
(define nt-enums (make-hash))
(define cc-enums (make-hash))
(define filled-cc-enums
(delay (let-values ([(fin-cc-lang rec-cc-lang cant-enumerate-cc-table)
(sep-lang (force cc-lang) #f)])
(make-lang-table! l-enum cc-enums fin-cc-lang rec-cc-lang cant-enumerate-cc-table
#:i-am-cross? #t)
cc-enums)))
(define-values (fin-lang rec-lang cant-enumerate-table) (sep-lang lang clang-all-ht))
(define unparse-term+pat-nt-ht
(build-nt-unparse-term+pat (append fin-lang rec-lang)
;; recombine the productions to make sure they are in
;; the same order as they are in the forwards enumeration
clang-all-ht
call-nt-proc/bool))
(define l-enum
(lang-enum nt-enums filled-cc-enums unused-var/e unparse-term+pat-nt-ht))
(make-lang-table! l-enum nt-enums fin-lang rec-lang cant-enumerate-table)
l-enum]))
(define (make-lang-table! l-enum ht fin-lang rec-lang cant-enumerate-table
#:i-am-cross? [i-am-cross? #f])
(define (enumerate-lang! cur-lang enum-f)
(for ([nt (in-list cur-lang)])
(hash-set! ht
(nt-name nt)
(if (hash-ref cant-enumerate-table (nt-name nt))
#f
(enum-f (nt-rhs nt) ht)))))
(enumerate-lang! fin-lang
(λ (rhs enums)
(enumerate-rhss rhs l-enum
#:cross-table (and i-am-cross? enums))))
(define rec-lang-base-i (length fin-lang))
(enumerate-lang! rec-lang
(λ (rhs enums)
(delay/e (enumerate-rhss rhs l-enum
#:cross-table (and i-am-cross? enums))
#:count +inf.f))))
(define (build-nt-unparse-term+pat lang clang-all-ht call-nt-proc/bool)
(define init-unparse-term+pat (make-hash))
(define unparse-term+pat-nt-ht (make-hash))
(for ([nt (in-list lang)])
(define name (nt-name nt))
(hash-set! unparse-term+pat-nt-ht name
(λ (term)
(error 'lang-enumerators "knot for ~s not tied" nt)))
(hash-set! init-unparse-term+pat
name
(λ (term)
((hash-ref unparse-term+pat-nt-ht name) term))))
(define empty-t-env (t-env #hash() #hash() #hash()))
(for ([nt (in-list lang)])
(define name (nt-name nt))
(define prod-procs
(for/list ([rhs (in-list (nt-rhs nt))])
(unparse-term+pat (rhs-pattern rhs) init-unparse-term+pat)))
(cond
[(andmap values prod-procs)
(define (unparse-nt-term+pat term)
(let/ec k
(for ([rhs (in-list (hash-ref clang-all-ht name))]
[prod-proc (in-list prod-procs)]
[i (in-naturals)])
(when (call-nt-proc/bool (compiled-pattern-cp rhs)
term
;; is it okay to use equal? here
;; and not the language's α-equal function?
equal?)
(k (production i (ann-pat empty-t-env (prod-proc term))))))
(error 'unparse-term+pat "ack: failure ~s ~s" nt term)))
(hash-set! unparse-term+pat-nt-ht name unparse-nt-term+pat)]
[else (hash-set! unparse-term+pat-nt-ht name #f)]))
unparse-term+pat-nt-ht)
(define (pat-enumerator l-enum pat the-ambiguity-cache pat-matches/c)
(cond
[(can-enumerate? pat (lang-enum-nt-enums l-enum) (lang-enum-delayed-cc-enums l-enum))
(define from-term (and (not (ambiguous-pattern? pat the-ambiguity-cache))
(top-level-unparse-term+pat pat l-enum)))
(define raw-enumerator (pat/e pat l-enum))
(cond
[from-term
(map/e to-term from-term raw-enumerator #:contract pat-matches/c)]
[else
(pam/e to-term raw-enumerator #:contract pat-matches/c)])]
[else #f]))
(define (term-index l-enum pat term)
(define raw-enumerator (pat/e pat l-enum))
(cond
[raw-enumerator
(define from-term (top-level-unparse-term+pat pat l-enum))
(to-nat raw-enumerator (from-term term))]
[else #f]))
(define (enumerate-rhss rhss l-enum
#:cross-table [cross-table #f])
(define (with-index i e)
(map/e (λ (x) (production i x))
production-term
e
#:contract
(struct/c production i any/c)))
(apply or/e
(for/list ([i (in-naturals)]
[production (in-list rhss)])
(with-index i
(pat/e (rhs-pattern production) l-enum
#:cross-table cross-table)))))
(define (pat/e pat l-enum
#:cross-table [cross-table #f])
(match-define (ann-pat nv pp-pat) (preprocess pat))
(map/e
(λ (l) (apply ann-pat l))
(λ (ap)
(list (ann-pat-ann ap)
(ann-pat-pat ap)))
(list/e (env/e nv l-enum)
(pat-refs/e pp-pat l-enum
#:cross-table cross-table))
#:contract any/c))
(: pat - refs / e : # : cross - table [ ( or / c # f ( symbol ? enum ? ) ] - > )
(define (pat-refs/e pat l-enum
#:cross-table [cross-table #f])
(define (loop pat)
(match-a-pattern
pat
[`any any/e]
[`number two-way-number/e]
[`string string/e]
[`natural natural/e]
[`integer integer/e]
[`real two-way-real/e]
[`boolean bool/e]
[`variable symbol/e]
[`(variable-except ,s ...)
(apply except/e symbol/e s)]
[`(variable-prefix ,s)
(var-prefix/e s)]
[`variable-not-otherwise-mentioned
(lang-enum-unused-var/e l-enum)]
;; not sure this is the right equality function,
;; but it matches the plug-hole function (above)
[`hole (single/e the-hole #:equal? eq?)]
[`(nt ,id)
(lang-enum-get-nt-enum l-enum id)]
[`(name ,n ,pat)
(single/e (name-ref n))]
[`(mismatch-name ,n ,tag)
(single/e (misname-ref n tag))]
[`(in-hole ,p1 ,p2)
(define p1/e (loop p1))
(define p2/e (loop p2))
(map/e (λ (l) (apply decomp l))
(λ (d)
(match d
[(decomp ctx term)
(list ctx term)]))
(list/e p1/e p2/e)
#:contract
(struct/c decomp
(enum-contract p1/e)
(enum-contract p2/e)))]
[`(hide-hole ,p)
(define p/e (loop p))
(map/e hide-hole
hide-hole-term
p/e
#:contract
(struct/c hide-hole
(enum-contract p/e)))]
[`(side-condition ,p ,g ,e)
(unsupported pat)]
[`(cross ,s)
(if cross-table
(hash-ref cross-table s)
(lang-enum-get-cross-enum l-enum s))]
[`(list ,sub-pats ...)
(apply list/e
(for/list ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat #f #f)
(define pats/e (listof/e (loop pat)))
(map/e
(λ (ts) (repeat (length ts) ts))
(λ (rep) (repeat-terms rep))
pats/e
#:contract (struct/c repeat
exact-nonnegative-integer?
(enum-contract pats/e)))]
[`(repeat ,tag ,n #f)
(single/e (nrep-ref n tag))]
[`(repeat ,pat ,n ,m)
(unimplemented "mismatch repeats (..._!_)")]
[else (loop sub-pat)])))]
[(? (compose not pair?))
(single/e pat)]))
(loop pat))
(define (has-cross? lang)
(for/or ([nt (in-list lang)])
(for/or ([pat (in-list (nt-rhs nt))])
(let loop ([pat (rhs-pattern pat)])
(match-a-pattern
pat
[`any #f]
[`number #f]
[`string #f]
[`natural #f]
[`integer #f]
[`real #f]
[`boolean #f]
[`variable #f]
[`(variable-except ,s ...) #f]
[`(variable-prefix ,s) #f]
[`variable-not-otherwise-mentioned #f]
[`hole #f]
[`(nt ,id) #f]
[`(name ,n ,pat) #f]
[`(mismatch-name ,n ,tag) #f]
[`(in-hole ,p1 ,p2) (or (loop p1) (loop p2))]
[`(hide-hole ,p) (loop p)]
[`(side-condition ,p ,g ,e) (loop p)]
[`(cross ,s) #t]
[`(list ,sub-pats ...)
(for/or ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat ,_ ,_) (loop pat)]
[pat (loop pat)]))]
[(? (compose not pair?)) #f])))))
(define/match (env/e nv l-enum)
[((env names misnames nreps) _)
(define (val/e p)
(pat-refs/e p l-enum))
(define/match (misvals/e p-ts)
[((cons p ts))
(define p/e (val/e p))
(fold-enum (λ (ts-excepts tag)
(define excepts
(map cdr ts-excepts))
(cons/e (fin/e tag)
(apply except/e p/e excepts
#:contract any/c)))
(set->list ts)
#:f-range-finite? (finite-enum? p/e))])
(define/match (reprec/e nv-t)
[((cons nv tpats))
(define tpats/e
(hash-traverse/e val/e tpats #:contract any/c))
(listof/e
(cons/e (env/e nv l-enum)
tpats/e))])
(define names-env
(hash-traverse/e val/e names #:contract any/c))
(define misnames-env
(hash-traverse/e misvals/e misnames #:contract any/c))
(define nreps-env
(hash-traverse/e reprec/e nreps #:contract any/c))
(map/e
(λ (v) (apply t-env v))
(λ (t-e)
(match t-e
[(t-env names misnames nreps)
(list names misnames nreps)]))
(list/e names-env
misnames-env
nreps-env)
#:contract t-env?)])
;; to-term : (ann-pat t-env pat-with-refs) -> redex term
(define (to-term ap)
(match ap
[(ann-pat nv term)
(strip-hide-holes (refs-to-fn term nv))]))
refs - to - fn : > Term
(define (refs-to-fn refpat nv)
(match refpat
[(ann-pat nv term)
(refs-to-fn term nv)]
[(production _ term)
(refs-to-fn term nv)]
[(decomp ctx-refs termpat-refs)
(define ctx (refs-to-fn ctx-refs nv))
(define term (refs-to-fn termpat-refs nv))
(plug-hole ctx term)]
[(hide-hole p)
(hide-hole (refs-to-fn p nv))]
[(name-ref n)
(refs-to-fn (t-env-name-ref nv n) nv)]
[(misname-ref n tag)
(refs-to-fn (t-env-misname-ref nv n tag) nv)]
[(list subrefpats ...)
(append*
(for/list ([subrefpat (in-list subrefpats)])
(match subrefpat
[(repeat _ subs)
(for/list ([sub (in-list subs)])
(refs-to-fn sub nv))]
[(nrep-ref n tag)
(define env-ts (t-env-nrep-ref nv n))
(for/list ([nv-t (in-list env-ts)])
(match nv-t
[(cons nv tterms)
(refs-to-fn (hash-ref tterms tag) nv)]))]
[_ (list (refs-to-fn subrefpat nv))])))]
[else refpat]))
(define (strip-hide-holes term)
(match term
[(hide-hole t) (strip-hide-holes t)]
[(list ts ...) (map strip-hide-holes ts)]
[_ term]))
(define (plug-hole ctx term)
(define (plug ctx)
(match ctx
[(? (curry eq? the-hole)) term]
[(list ctxs ...) (map plug ctxs)]
[_ ctx]))
(define (unhide term)
(match term
[(list ctxs ...) (map unhide ctxs)]
[(hide-hole term) (unhide term)]
[_ term]))
(unhide (plug ctx)))
;; lang-enum-get-nt-enum : lang-enum Symbol -> (or/c Enum #f)
(define (lang-enum-get-nt-enum l-enum s)
(hash-ref (lang-enum-nt-enums l-enum) s))
;; lang-enum-get-cross-enum : lang-enum Symbol -> (or/c Enum #f)
(define (lang-enum-get-cross-enum l-enum s)
(hash-ref (force (lang-enum-delayed-cc-enums l-enum)) s))
(define (var-prefix/e s)
(define as-str (symbol->string s))
(define ((flip f) x y) (f y x))
(map/e (compose string->symbol
(curry string-append as-str)
symbol->string)
(compose string->symbol
list->string
(curry (flip drop) (string-length as-str))
string->list
symbol->string)
symbol/e
#:contract (and/c symbol?
(let ([reg (regexp (format "^~a" (regexp-quote as-str)))])
(λ (x)
(regexp-match? reg (symbol->string x)))))))
(define base/e
(or/e (fin/e '())
(cons two-way-number/e number?)
string/e
bool/e
symbol/e))
(define any/e
(delay/e
(or/e (cons base/e (negate pair?))
(cons (cons/e any/e any/e) pair?))
#:count +inf.0))
;; this function turns a term back into a parsed
;; term to be used with an enumerator produced by pat-refs/e
;; also: the pat should be unambiguous ...?
( if so , we can invert ; if not , we can maybe just get the first one ? )
;; PRE: term matches pat.
;;
;; this variant can be used with non-terminals in a language; the function
top - level - unparse - term+pat is used with raw patterns that appear
;; outside of a language
(define (unparse-term+pat pat unparse-nt-hash)
(define names-encountered (make-hash))
(let/ec k
(define (fail) (k #f))
(let loop ([pat pat])
(match-a-pattern
pat
[`any values]
[`number values]
[`string values]
[`natural values]
[`integer values]
[`real values]
[`boolean values]
[`variable values]
[`(variable-except ,s ...) values]
[`(variable-prefix ,s) values]
[`variable-not-otherwise-mentioned values]
[`hole values]
[`(nt ,id) (or (hash-ref unparse-nt-hash id) (fail))]
[`(name ,n ,pat)
(when (hash-ref names-encountered n #f) (fail))
(hash-set! names-encountered n #t)
(loop pat)]
[`(mismatch-name ,n ,tag) (fail)]
[`(in-hole ,p1 ,p2) (fail)]
[`(hide-hole ,p) (fail)]
[`(side-condition ,p ,g ,e) (fail)]
[`(cross ,s) (fail)]
[`(list ,sub-pats ...)
(define repeat-count 0)
(define to-terms
( listof ( cons / c boolean?[repeat ] term - parser ) )
(for/list ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat #f #f)
(cond
[(zero? repeat-count)
(set! repeat-count 1)
(cons #t (loop pat))]
[else
(fail)])]
[`(repeat ,pat ,_1 ,_2) (fail)]
[pat (cons #f (loop pat))])))
(λ (term)
(define times-to-repeat (- (length term) (- (length sub-pats) 1)))
(for/list ([bool+to-term (in-list to-terms)])
(match bool+to-term
[(cons #t to-term) ;; repeat
(repeat
times-to-repeat
(for/list ([i (in-range times-to-repeat)])
(define this-term (car term))
(set! term (cdr term))
(to-term this-term)))]
[(cons #f to-term) ;; not a repeat
(define this-term (car term))
(set! term (cdr term))
(to-term this-term)])))]
[(? (compose not pair?)) values]))))
(define (top-level-unparse-term+pat pat l-enum)
(define unparse-nt-hash (lang-enum-unparse-term+pat-nt-ht l-enum))
(define unparser (unparse-term+pat pat (lang-enum-unparse-term+pat-nt-ht l-enum)))
(and unparser
(λ (term)
(ann-pat (t-env #hash() #hash() #hash()) (unparser term)))))
| null | https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-lib/redex/private/enum.rkt | racket | any/c is compiled-pattern
this works around a circularity at the module level
pattern
pattern
term
nt-enums : hash[sym -o> (or/c #f enum)]
cc-enums : promise/c (hash[sym -o> (or/c #f enum)])
unused-var/e : enum
Top level exports
when the language itself has a `(cross ...) pattern, then we
cannot assume that there are no references from the main language
to the compatible closure language, so we just combine them here
and process them and then separate them back out later, giving up
on the laziness in computing the compatible closure-related stuff
do a check that might not actually be necessary but if this
were to fail, things would be go wrong in a confusing way later
we combine everything here and dump all enums into `all-enums`
recombine the productions to make sure they are in
the same order as they are in the forwards enumeration
here we just use `all-enums` in both places
recombine the productions to make sure they are in
the same order as they are in the forwards enumeration
is it okay to use equal? here
and not the language's α-equal function?
not sure this is the right equality function,
but it matches the plug-hole function (above)
to-term : (ann-pat t-env pat-with-refs) -> redex term
lang-enum-get-nt-enum : lang-enum Symbol -> (or/c Enum #f)
lang-enum-get-cross-enum : lang-enum Symbol -> (or/c Enum #f)
this function turns a term back into a parsed
term to be used with an enumerator produced by pat-refs/e
also: the pat should be unambiguous ...?
if not , we can maybe just get the first one ? )
PRE: term matches pat.
this variant can be used with non-terminals in a language; the function
outside of a language
repeat
not a repeat | #lang racket/base
(require racket/bool
racket/contract
racket/function
racket/list
racket/math
racket/match
racket/promise
racket/set
data/enumerate/lib/unsafe
"env.rkt"
"error.rkt"
"lang-struct.rkt"
"match-a-pattern.rkt"
"preprocess-pat.rkt"
"preprocess-lang.rkt"
"ambiguous.rkt")
(provide
enum-test-support
enum-count
finite-enum?
(contract-out
[lang-enumerators (-> (listof nt?)
(promise/c (listof nt?))
lang-enum?)]
[pat-enumerator (-> lang-enum?
ambiguity-cache?
flat-contract?
(or/c #f enum?))]
[term-index (-> lang-enum?
(or/c exact-nonnegative-integer? #f))]
[enum-ith (-> enum? exact-nonnegative-integer? any/c)]
[lang-enum? (-> any/c boolean?)]
[enum? (-> any/c boolean?)]))
(define enum-test-support (make-parameter #f))
(struct lang-enum (nt-enums delayed-cc-enums unused-var/e unparse-term+pat-nt-ht))
(struct production (n term) #:transparent)
(struct repeat (n terms) #:transparent)
(struct name-ref (name) #:transparent)
(struct misname-ref (name tag) #:transparent)
(struct nrep-ref (name subpat) #:transparent)
(struct decomp (ctx term) #:transparent)
(struct hide-hole (term) #:transparent)
(define (enum-ith e x) (from-nat e x))
(define (lang-enumerators lang orig-clang-all-ht cc-lang call-nt-proc/bool)
(define clang-all-ht (hash-copy orig-clang-all-ht))
(define unused-var/e
(apply except/e
symbol/e
(used-vars lang)))
(cond
[(or (enum-test-support) (has-cross? lang))
(define forced-cc-lang (force cc-lang))
(let ()
(define all-nts (make-hash))
(for ([nt (in-list lang)])
(hash-set! all-nts (nt-name nt) #t))
(for ([nt (in-list forced-cc-lang)])
(when (hash-ref all-nts (nt-name nt) #f)
(error 'enum.rkt
"cannot cope with the non-terminal ~s, as it collides with on from the compatible closure language"
(nt-name nt)))))
(define all-enums (make-hash))
(define-values (fin-lang rec-lang cant-enumerate-table)
(sep-lang (append lang forced-cc-lang)
clang-all-ht))
(define unparse-term+pat-nt-ht
(build-nt-unparse-term+pat (append fin-lang rec-lang)
clang-all-ht
call-nt-proc/bool))
(define l-enum
(lang-enum all-enums (delay all-enums) unused-var/e unparse-term+pat-nt-ht))
(make-lang-table! l-enum all-enums fin-lang rec-lang cant-enumerate-table)
l-enum]
[else
(define nt-enums (make-hash))
(define cc-enums (make-hash))
(define filled-cc-enums
(delay (let-values ([(fin-cc-lang rec-cc-lang cant-enumerate-cc-table)
(sep-lang (force cc-lang) #f)])
(make-lang-table! l-enum cc-enums fin-cc-lang rec-cc-lang cant-enumerate-cc-table
#:i-am-cross? #t)
cc-enums)))
(define-values (fin-lang rec-lang cant-enumerate-table) (sep-lang lang clang-all-ht))
(define unparse-term+pat-nt-ht
(build-nt-unparse-term+pat (append fin-lang rec-lang)
clang-all-ht
call-nt-proc/bool))
(define l-enum
(lang-enum nt-enums filled-cc-enums unused-var/e unparse-term+pat-nt-ht))
(make-lang-table! l-enum nt-enums fin-lang rec-lang cant-enumerate-table)
l-enum]))
(define (make-lang-table! l-enum ht fin-lang rec-lang cant-enumerate-table
#:i-am-cross? [i-am-cross? #f])
(define (enumerate-lang! cur-lang enum-f)
(for ([nt (in-list cur-lang)])
(hash-set! ht
(nt-name nt)
(if (hash-ref cant-enumerate-table (nt-name nt))
#f
(enum-f (nt-rhs nt) ht)))))
(enumerate-lang! fin-lang
(λ (rhs enums)
(enumerate-rhss rhs l-enum
#:cross-table (and i-am-cross? enums))))
(define rec-lang-base-i (length fin-lang))
(enumerate-lang! rec-lang
(λ (rhs enums)
(delay/e (enumerate-rhss rhs l-enum
#:cross-table (and i-am-cross? enums))
#:count +inf.f))))
(define (build-nt-unparse-term+pat lang clang-all-ht call-nt-proc/bool)
(define init-unparse-term+pat (make-hash))
(define unparse-term+pat-nt-ht (make-hash))
(for ([nt (in-list lang)])
(define name (nt-name nt))
(hash-set! unparse-term+pat-nt-ht name
(λ (term)
(error 'lang-enumerators "knot for ~s not tied" nt)))
(hash-set! init-unparse-term+pat
name
(λ (term)
((hash-ref unparse-term+pat-nt-ht name) term))))
(define empty-t-env (t-env #hash() #hash() #hash()))
(for ([nt (in-list lang)])
(define name (nt-name nt))
(define prod-procs
(for/list ([rhs (in-list (nt-rhs nt))])
(unparse-term+pat (rhs-pattern rhs) init-unparse-term+pat)))
(cond
[(andmap values prod-procs)
(define (unparse-nt-term+pat term)
(let/ec k
(for ([rhs (in-list (hash-ref clang-all-ht name))]
[prod-proc (in-list prod-procs)]
[i (in-naturals)])
(when (call-nt-proc/bool (compiled-pattern-cp rhs)
term
equal?)
(k (production i (ann-pat empty-t-env (prod-proc term))))))
(error 'unparse-term+pat "ack: failure ~s ~s" nt term)))
(hash-set! unparse-term+pat-nt-ht name unparse-nt-term+pat)]
[else (hash-set! unparse-term+pat-nt-ht name #f)]))
unparse-term+pat-nt-ht)
(define (pat-enumerator l-enum pat the-ambiguity-cache pat-matches/c)
(cond
[(can-enumerate? pat (lang-enum-nt-enums l-enum) (lang-enum-delayed-cc-enums l-enum))
(define from-term (and (not (ambiguous-pattern? pat the-ambiguity-cache))
(top-level-unparse-term+pat pat l-enum)))
(define raw-enumerator (pat/e pat l-enum))
(cond
[from-term
(map/e to-term from-term raw-enumerator #:contract pat-matches/c)]
[else
(pam/e to-term raw-enumerator #:contract pat-matches/c)])]
[else #f]))
(define (term-index l-enum pat term)
(define raw-enumerator (pat/e pat l-enum))
(cond
[raw-enumerator
(define from-term (top-level-unparse-term+pat pat l-enum))
(to-nat raw-enumerator (from-term term))]
[else #f]))
(define (enumerate-rhss rhss l-enum
#:cross-table [cross-table #f])
(define (with-index i e)
(map/e (λ (x) (production i x))
production-term
e
#:contract
(struct/c production i any/c)))
(apply or/e
(for/list ([i (in-naturals)]
[production (in-list rhss)])
(with-index i
(pat/e (rhs-pattern production) l-enum
#:cross-table cross-table)))))
(define (pat/e pat l-enum
#:cross-table [cross-table #f])
(match-define (ann-pat nv pp-pat) (preprocess pat))
(map/e
(λ (l) (apply ann-pat l))
(λ (ap)
(list (ann-pat-ann ap)
(ann-pat-pat ap)))
(list/e (env/e nv l-enum)
(pat-refs/e pp-pat l-enum
#:cross-table cross-table))
#:contract any/c))
(: pat - refs / e : # : cross - table [ ( or / c # f ( symbol ? enum ? ) ] - > )
(define (pat-refs/e pat l-enum
#:cross-table [cross-table #f])
(define (loop pat)
(match-a-pattern
pat
[`any any/e]
[`number two-way-number/e]
[`string string/e]
[`natural natural/e]
[`integer integer/e]
[`real two-way-real/e]
[`boolean bool/e]
[`variable symbol/e]
[`(variable-except ,s ...)
(apply except/e symbol/e s)]
[`(variable-prefix ,s)
(var-prefix/e s)]
[`variable-not-otherwise-mentioned
(lang-enum-unused-var/e l-enum)]
[`hole (single/e the-hole #:equal? eq?)]
[`(nt ,id)
(lang-enum-get-nt-enum l-enum id)]
[`(name ,n ,pat)
(single/e (name-ref n))]
[`(mismatch-name ,n ,tag)
(single/e (misname-ref n tag))]
[`(in-hole ,p1 ,p2)
(define p1/e (loop p1))
(define p2/e (loop p2))
(map/e (λ (l) (apply decomp l))
(λ (d)
(match d
[(decomp ctx term)
(list ctx term)]))
(list/e p1/e p2/e)
#:contract
(struct/c decomp
(enum-contract p1/e)
(enum-contract p2/e)))]
[`(hide-hole ,p)
(define p/e (loop p))
(map/e hide-hole
hide-hole-term
p/e
#:contract
(struct/c hide-hole
(enum-contract p/e)))]
[`(side-condition ,p ,g ,e)
(unsupported pat)]
[`(cross ,s)
(if cross-table
(hash-ref cross-table s)
(lang-enum-get-cross-enum l-enum s))]
[`(list ,sub-pats ...)
(apply list/e
(for/list ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat #f #f)
(define pats/e (listof/e (loop pat)))
(map/e
(λ (ts) (repeat (length ts) ts))
(λ (rep) (repeat-terms rep))
pats/e
#:contract (struct/c repeat
exact-nonnegative-integer?
(enum-contract pats/e)))]
[`(repeat ,tag ,n #f)
(single/e (nrep-ref n tag))]
[`(repeat ,pat ,n ,m)
(unimplemented "mismatch repeats (..._!_)")]
[else (loop sub-pat)])))]
[(? (compose not pair?))
(single/e pat)]))
(loop pat))
(define (has-cross? lang)
(for/or ([nt (in-list lang)])
(for/or ([pat (in-list (nt-rhs nt))])
(let loop ([pat (rhs-pattern pat)])
(match-a-pattern
pat
[`any #f]
[`number #f]
[`string #f]
[`natural #f]
[`integer #f]
[`real #f]
[`boolean #f]
[`variable #f]
[`(variable-except ,s ...) #f]
[`(variable-prefix ,s) #f]
[`variable-not-otherwise-mentioned #f]
[`hole #f]
[`(nt ,id) #f]
[`(name ,n ,pat) #f]
[`(mismatch-name ,n ,tag) #f]
[`(in-hole ,p1 ,p2) (or (loop p1) (loop p2))]
[`(hide-hole ,p) (loop p)]
[`(side-condition ,p ,g ,e) (loop p)]
[`(cross ,s) #t]
[`(list ,sub-pats ...)
(for/or ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat ,_ ,_) (loop pat)]
[pat (loop pat)]))]
[(? (compose not pair?)) #f])))))
(define/match (env/e nv l-enum)
[((env names misnames nreps) _)
(define (val/e p)
(pat-refs/e p l-enum))
(define/match (misvals/e p-ts)
[((cons p ts))
(define p/e (val/e p))
(fold-enum (λ (ts-excepts tag)
(define excepts
(map cdr ts-excepts))
(cons/e (fin/e tag)
(apply except/e p/e excepts
#:contract any/c)))
(set->list ts)
#:f-range-finite? (finite-enum? p/e))])
(define/match (reprec/e nv-t)
[((cons nv tpats))
(define tpats/e
(hash-traverse/e val/e tpats #:contract any/c))
(listof/e
(cons/e (env/e nv l-enum)
tpats/e))])
(define names-env
(hash-traverse/e val/e names #:contract any/c))
(define misnames-env
(hash-traverse/e misvals/e misnames #:contract any/c))
(define nreps-env
(hash-traverse/e reprec/e nreps #:contract any/c))
(map/e
(λ (v) (apply t-env v))
(λ (t-e)
(match t-e
[(t-env names misnames nreps)
(list names misnames nreps)]))
(list/e names-env
misnames-env
nreps-env)
#:contract t-env?)])
(define (to-term ap)
(match ap
[(ann-pat nv term)
(strip-hide-holes (refs-to-fn term nv))]))
refs - to - fn : > Term
(define (refs-to-fn refpat nv)
(match refpat
[(ann-pat nv term)
(refs-to-fn term nv)]
[(production _ term)
(refs-to-fn term nv)]
[(decomp ctx-refs termpat-refs)
(define ctx (refs-to-fn ctx-refs nv))
(define term (refs-to-fn termpat-refs nv))
(plug-hole ctx term)]
[(hide-hole p)
(hide-hole (refs-to-fn p nv))]
[(name-ref n)
(refs-to-fn (t-env-name-ref nv n) nv)]
[(misname-ref n tag)
(refs-to-fn (t-env-misname-ref nv n tag) nv)]
[(list subrefpats ...)
(append*
(for/list ([subrefpat (in-list subrefpats)])
(match subrefpat
[(repeat _ subs)
(for/list ([sub (in-list subs)])
(refs-to-fn sub nv))]
[(nrep-ref n tag)
(define env-ts (t-env-nrep-ref nv n))
(for/list ([nv-t (in-list env-ts)])
(match nv-t
[(cons nv tterms)
(refs-to-fn (hash-ref tterms tag) nv)]))]
[_ (list (refs-to-fn subrefpat nv))])))]
[else refpat]))
(define (strip-hide-holes term)
(match term
[(hide-hole t) (strip-hide-holes t)]
[(list ts ...) (map strip-hide-holes ts)]
[_ term]))
(define (plug-hole ctx term)
(define (plug ctx)
(match ctx
[(? (curry eq? the-hole)) term]
[(list ctxs ...) (map plug ctxs)]
[_ ctx]))
(define (unhide term)
(match term
[(list ctxs ...) (map unhide ctxs)]
[(hide-hole term) (unhide term)]
[_ term]))
(unhide (plug ctx)))
(define (lang-enum-get-nt-enum l-enum s)
(hash-ref (lang-enum-nt-enums l-enum) s))
(define (lang-enum-get-cross-enum l-enum s)
(hash-ref (force (lang-enum-delayed-cc-enums l-enum)) s))
(define (var-prefix/e s)
(define as-str (symbol->string s))
(define ((flip f) x y) (f y x))
(map/e (compose string->symbol
(curry string-append as-str)
symbol->string)
(compose string->symbol
list->string
(curry (flip drop) (string-length as-str))
string->list
symbol->string)
symbol/e
#:contract (and/c symbol?
(let ([reg (regexp (format "^~a" (regexp-quote as-str)))])
(λ (x)
(regexp-match? reg (symbol->string x)))))))
(define base/e
(or/e (fin/e '())
(cons two-way-number/e number?)
string/e
bool/e
symbol/e))
(define any/e
(delay/e
(or/e (cons base/e (negate pair?))
(cons (cons/e any/e any/e) pair?))
#:count +inf.0))
top - level - unparse - term+pat is used with raw patterns that appear
(define (unparse-term+pat pat unparse-nt-hash)
(define names-encountered (make-hash))
(let/ec k
(define (fail) (k #f))
(let loop ([pat pat])
(match-a-pattern
pat
[`any values]
[`number values]
[`string values]
[`natural values]
[`integer values]
[`real values]
[`boolean values]
[`variable values]
[`(variable-except ,s ...) values]
[`(variable-prefix ,s) values]
[`variable-not-otherwise-mentioned values]
[`hole values]
[`(nt ,id) (or (hash-ref unparse-nt-hash id) (fail))]
[`(name ,n ,pat)
(when (hash-ref names-encountered n #f) (fail))
(hash-set! names-encountered n #t)
(loop pat)]
[`(mismatch-name ,n ,tag) (fail)]
[`(in-hole ,p1 ,p2) (fail)]
[`(hide-hole ,p) (fail)]
[`(side-condition ,p ,g ,e) (fail)]
[`(cross ,s) (fail)]
[`(list ,sub-pats ...)
(define repeat-count 0)
(define to-terms
( listof ( cons / c boolean?[repeat ] term - parser ) )
(for/list ([sub-pat (in-list sub-pats)])
(match sub-pat
[`(repeat ,pat #f #f)
(cond
[(zero? repeat-count)
(set! repeat-count 1)
(cons #t (loop pat))]
[else
(fail)])]
[`(repeat ,pat ,_1 ,_2) (fail)]
[pat (cons #f (loop pat))])))
(λ (term)
(define times-to-repeat (- (length term) (- (length sub-pats) 1)))
(for/list ([bool+to-term (in-list to-terms)])
(match bool+to-term
(repeat
times-to-repeat
(for/list ([i (in-range times-to-repeat)])
(define this-term (car term))
(set! term (cdr term))
(to-term this-term)))]
(define this-term (car term))
(set! term (cdr term))
(to-term this-term)])))]
[(? (compose not pair?)) values]))))
(define (top-level-unparse-term+pat pat l-enum)
(define unparse-nt-hash (lang-enum-unparse-term+pat-nt-ht l-enum))
(define unparser (unparse-term+pat pat (lang-enum-unparse-term+pat-nt-ht l-enum)))
(and unparser
(λ (term)
(ann-pat (t-env #hash() #hash() #hash()) (unparser term)))))
|
0510970f780ffc99d80ff34b441be65de37aeba8d428994eeafc019443146fa8 | tomprimozic/type-systems | infer.ml | open Expr
type settings = {
mutable dynamic_parameters : bool;
mutable freeze_dynamic : bool
}
let settings = {
dynamic_parameters = true;
freeze_dynamic = true;
}
let current_id = ref 0
let next_id () =
let id = !current_id in
current_id := id + 1 ;
id
let reset_id () = current_id := 0
let new_var level is_dynamic = TVar (ref (Unbound(next_id (), level, is_dynamic)))
let new_gen_var () = TVar (ref (Generic (next_id ())))
exception Error of string
let error msg = raise (Error msg)
module Env = struct
module StringMap = Map.Make (String)
type env = ty StringMap.t
let empty : env = StringMap.empty
let extend env name ty = StringMap.add name ty env
let lookup env name = StringMap.find name env
end
let occurs_check_adjust_levels_make_vars_dynamic tvar_id tvar_level tvar_is_dynamic ty =
let rec f = function
| TVar {contents = Link ty} -> f ty
| TVar {contents = Generic _} -> assert false
| TVar ({contents = Unbound(other_id, other_level, other_is_dynamic)} as other_tvar) ->
if other_id = tvar_id then
error "recursive types"
else
let new_level = min tvar_level other_level in
let new_is_dynamic = tvar_is_dynamic || other_is_dynamic in
other_tvar := Unbound(other_id, new_level, new_is_dynamic)
| TApp(ty, ty_arg_list) ->
f ty ;
List.iter f ty_arg_list
| TArrow(param_ty_list, return_ty) ->
List.iter f param_ty_list ;
f return_ty
| TConst _ -> ()
| TDynamic -> assert false
in
f ty
let rec unify ty1 ty2 =
if ty1 == ty2 then () else
match (ty1, ty2) with
| TConst name1, TConst name2 when name1 = name2 -> ()
| TDynamic, _ | _, TDynamic -> assert false
| TApp(ty1, ty_arg_list1), TApp(ty2, ty_arg_list2) ->
unify ty1 ty2 ;
List.iter2 unify ty_arg_list1 ty_arg_list2
| TArrow(param_ty_list1, return_ty1), TArrow(param_ty_list2, return_ty2) ->
List.iter2 unify param_ty_list1 param_ty_list2 ;
unify return_ty1 return_ty2
| TVar {contents = Link ty1}, ty2 | ty1, TVar {contents = Link ty2} -> unify ty1 ty2
| TVar {contents = Unbound(id1, _, _)}, TVar {contents = Unbound(id2, _, _)} when id1 = id2 ->
assert false (* There is only a single instance of a particular type variable. *)
| TVar ({contents = Unbound(id, level, is_dynamic)} as tvar), ty
| ty, TVar ({contents = Unbound(id, level, is_dynamic)} as tvar) ->
occurs_check_adjust_levels_make_vars_dynamic id level is_dynamic ty ;
tvar := Link ty
| _, _ -> error ("cannot unify types " ^ string_of_ty ty1 ^ " and " ^ string_of_ty ty2)
let rec generalize level = function
| TDynamic -> assert false
| TVar {contents = Unbound(id, other_level, is_dynamic)} when other_level > level ->
if is_dynamic then
if settings.freeze_dynamic then
TDynamic
else
TVar (ref (Unbound(id, level, true)))
else
TVar (ref (Generic id))
| TApp(ty, ty_arg_list) ->
TApp(generalize level ty, List.map (generalize level) ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map (generalize level) param_ty_list, generalize level return_ty)
| TVar {contents = Link ty} -> generalize level ty
| TVar {contents = Generic _} | TVar {contents = Unbound _} | TConst _ as ty -> ty
let instantiate_helper instantiate_dynamic level ty =
let id_var_map = Hashtbl.create 10 in
let rec f ty = match ty with
| TConst _ -> ty
| TVar {contents = Link ty} -> f ty
| TVar {contents = Generic id} -> begin
try
Hashtbl.find id_var_map id
with Not_found ->
let var = new_var level false in
Hashtbl.add id_var_map id var ;
var
end
| TVar {contents = Unbound _} -> ty
| TDynamic ->
if instantiate_dynamic then
new_var level true
else
TDynamic
| TApp(ty, ty_arg_list) ->
TApp(f ty, List.map f ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map f param_ty_list, f return_ty)
in
f ty
let instantiate level ty = instantiate_helper true level ty
let instantiate_ty_ann level ty = instantiate_helper false level ty
let rec match_fun_ty num_params = function
| TArrow(param_ty_list, return_ty) ->
if List.length param_ty_list <> num_params then
error "unexpected number of arguments"
else
param_ty_list, return_ty
| TVar {contents = Link ty} -> match_fun_ty num_params ty
| TVar ({contents = Unbound(id, level, is_dynamic)} as tvar) ->
let param_ty_list =
let rec f = function
| 0 -> []
| n -> new_var level is_dynamic :: f (n - 1)
in
f num_params
in
let return_ty = new_var level is_dynamic in
tvar := Link (TArrow(param_ty_list, return_ty)) ;
param_ty_list, return_ty
| TDynamic -> assert false
| _ -> error "expected a function"
let rec duplicate_dynamic level = function
| TDynamic -> assert false
| TVar {contents = Unbound(id, other_level, true)} when other_level > level ->
new_var level true
| TApp(ty, ty_arg_list) ->
TApp(duplicate_dynamic level ty, List.map (duplicate_dynamic level) ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map (duplicate_dynamic level) param_ty_list, duplicate_dynamic level return_ty)
| TVar {contents = Link ty} -> duplicate_dynamic level ty
| TVar {contents = Generic _} | TVar {contents = Unbound _} | TConst _ as ty -> ty
let rec infer env level = function
| Var name -> begin
try
instantiate level (Env.lookup env name)
with Not_found -> error ("variable " ^ name ^ " not found")
end
| Fun(param_list, body_expr) ->
let fn_env_ref = ref env in
let param_ty_list = List.map
(fun (param_name, maybe_param_ty_ann) ->
let param_ty = match maybe_param_ty_ann with
| None ->
if settings.dynamic_parameters
then TDynamic
else new_var level false
| Some ty_ann ->
instantiate_ty_ann level ty_ann
in
fn_env_ref := Env.extend !fn_env_ref param_name param_ty ;
param_ty)
param_list in
let return_ty = infer !fn_env_ref level body_expr in
TArrow(List.map (instantiate level) param_ty_list, return_ty)
| Let(var_name, None, value_expr, body_expr) ->
let var_ty = infer env (level + 1) value_expr in
let generalized_ty = generalize level var_ty in
infer (Env.extend env var_name generalized_ty) level body_expr
| Let(var_name, Some ty_ann, value_expr, body_expr) ->
equivalent to ` let = ( value_expr : ty_ann ) in body_expr `
infer env level (Let(var_name, None, Ann(value_expr, ty_ann), body_expr))
| Call(fn_expr, arg_list) ->
let param_ty_list, return_ty =
match_fun_ty (List.length arg_list) (infer env (level + 1) fn_expr)
in
List.iter2
(fun param_ty arg_expr -> unify param_ty (infer env (level + 1) arg_expr))
param_ty_list arg_list
;
duplicate_dynamic level return_ty
| Ann(expr, ty_ann) ->
(* equivalent to `(fun (x : ty_ann) -> x)(expr)` *)
infer env level (Call(Fun([("x", Some ty_ann)], Var "x"), [expr]))
| null | https://raw.githubusercontent.com/tomprimozic/type-systems/4403586a897ee94cb8f0de039aeee8ef1ecef968/gradual_typing/infer.ml | ocaml | There is only a single instance of a particular type variable.
equivalent to `(fun (x : ty_ann) -> x)(expr)` | open Expr
type settings = {
mutable dynamic_parameters : bool;
mutable freeze_dynamic : bool
}
let settings = {
dynamic_parameters = true;
freeze_dynamic = true;
}
let current_id = ref 0
let next_id () =
let id = !current_id in
current_id := id + 1 ;
id
let reset_id () = current_id := 0
let new_var level is_dynamic = TVar (ref (Unbound(next_id (), level, is_dynamic)))
let new_gen_var () = TVar (ref (Generic (next_id ())))
exception Error of string
let error msg = raise (Error msg)
module Env = struct
module StringMap = Map.Make (String)
type env = ty StringMap.t
let empty : env = StringMap.empty
let extend env name ty = StringMap.add name ty env
let lookup env name = StringMap.find name env
end
let occurs_check_adjust_levels_make_vars_dynamic tvar_id tvar_level tvar_is_dynamic ty =
let rec f = function
| TVar {contents = Link ty} -> f ty
| TVar {contents = Generic _} -> assert false
| TVar ({contents = Unbound(other_id, other_level, other_is_dynamic)} as other_tvar) ->
if other_id = tvar_id then
error "recursive types"
else
let new_level = min tvar_level other_level in
let new_is_dynamic = tvar_is_dynamic || other_is_dynamic in
other_tvar := Unbound(other_id, new_level, new_is_dynamic)
| TApp(ty, ty_arg_list) ->
f ty ;
List.iter f ty_arg_list
| TArrow(param_ty_list, return_ty) ->
List.iter f param_ty_list ;
f return_ty
| TConst _ -> ()
| TDynamic -> assert false
in
f ty
let rec unify ty1 ty2 =
if ty1 == ty2 then () else
match (ty1, ty2) with
| TConst name1, TConst name2 when name1 = name2 -> ()
| TDynamic, _ | _, TDynamic -> assert false
| TApp(ty1, ty_arg_list1), TApp(ty2, ty_arg_list2) ->
unify ty1 ty2 ;
List.iter2 unify ty_arg_list1 ty_arg_list2
| TArrow(param_ty_list1, return_ty1), TArrow(param_ty_list2, return_ty2) ->
List.iter2 unify param_ty_list1 param_ty_list2 ;
unify return_ty1 return_ty2
| TVar {contents = Link ty1}, ty2 | ty1, TVar {contents = Link ty2} -> unify ty1 ty2
| TVar {contents = Unbound(id1, _, _)}, TVar {contents = Unbound(id2, _, _)} when id1 = id2 ->
| TVar ({contents = Unbound(id, level, is_dynamic)} as tvar), ty
| ty, TVar ({contents = Unbound(id, level, is_dynamic)} as tvar) ->
occurs_check_adjust_levels_make_vars_dynamic id level is_dynamic ty ;
tvar := Link ty
| _, _ -> error ("cannot unify types " ^ string_of_ty ty1 ^ " and " ^ string_of_ty ty2)
let rec generalize level = function
| TDynamic -> assert false
| TVar {contents = Unbound(id, other_level, is_dynamic)} when other_level > level ->
if is_dynamic then
if settings.freeze_dynamic then
TDynamic
else
TVar (ref (Unbound(id, level, true)))
else
TVar (ref (Generic id))
| TApp(ty, ty_arg_list) ->
TApp(generalize level ty, List.map (generalize level) ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map (generalize level) param_ty_list, generalize level return_ty)
| TVar {contents = Link ty} -> generalize level ty
| TVar {contents = Generic _} | TVar {contents = Unbound _} | TConst _ as ty -> ty
let instantiate_helper instantiate_dynamic level ty =
let id_var_map = Hashtbl.create 10 in
let rec f ty = match ty with
| TConst _ -> ty
| TVar {contents = Link ty} -> f ty
| TVar {contents = Generic id} -> begin
try
Hashtbl.find id_var_map id
with Not_found ->
let var = new_var level false in
Hashtbl.add id_var_map id var ;
var
end
| TVar {contents = Unbound _} -> ty
| TDynamic ->
if instantiate_dynamic then
new_var level true
else
TDynamic
| TApp(ty, ty_arg_list) ->
TApp(f ty, List.map f ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map f param_ty_list, f return_ty)
in
f ty
let instantiate level ty = instantiate_helper true level ty
let instantiate_ty_ann level ty = instantiate_helper false level ty
let rec match_fun_ty num_params = function
| TArrow(param_ty_list, return_ty) ->
if List.length param_ty_list <> num_params then
error "unexpected number of arguments"
else
param_ty_list, return_ty
| TVar {contents = Link ty} -> match_fun_ty num_params ty
| TVar ({contents = Unbound(id, level, is_dynamic)} as tvar) ->
let param_ty_list =
let rec f = function
| 0 -> []
| n -> new_var level is_dynamic :: f (n - 1)
in
f num_params
in
let return_ty = new_var level is_dynamic in
tvar := Link (TArrow(param_ty_list, return_ty)) ;
param_ty_list, return_ty
| TDynamic -> assert false
| _ -> error "expected a function"
let rec duplicate_dynamic level = function
| TDynamic -> assert false
| TVar {contents = Unbound(id, other_level, true)} when other_level > level ->
new_var level true
| TApp(ty, ty_arg_list) ->
TApp(duplicate_dynamic level ty, List.map (duplicate_dynamic level) ty_arg_list)
| TArrow(param_ty_list, return_ty) ->
TArrow(List.map (duplicate_dynamic level) param_ty_list, duplicate_dynamic level return_ty)
| TVar {contents = Link ty} -> duplicate_dynamic level ty
| TVar {contents = Generic _} | TVar {contents = Unbound _} | TConst _ as ty -> ty
let rec infer env level = function
| Var name -> begin
try
instantiate level (Env.lookup env name)
with Not_found -> error ("variable " ^ name ^ " not found")
end
| Fun(param_list, body_expr) ->
let fn_env_ref = ref env in
let param_ty_list = List.map
(fun (param_name, maybe_param_ty_ann) ->
let param_ty = match maybe_param_ty_ann with
| None ->
if settings.dynamic_parameters
then TDynamic
else new_var level false
| Some ty_ann ->
instantiate_ty_ann level ty_ann
in
fn_env_ref := Env.extend !fn_env_ref param_name param_ty ;
param_ty)
param_list in
let return_ty = infer !fn_env_ref level body_expr in
TArrow(List.map (instantiate level) param_ty_list, return_ty)
| Let(var_name, None, value_expr, body_expr) ->
let var_ty = infer env (level + 1) value_expr in
let generalized_ty = generalize level var_ty in
infer (Env.extend env var_name generalized_ty) level body_expr
| Let(var_name, Some ty_ann, value_expr, body_expr) ->
equivalent to ` let = ( value_expr : ty_ann ) in body_expr `
infer env level (Let(var_name, None, Ann(value_expr, ty_ann), body_expr))
| Call(fn_expr, arg_list) ->
let param_ty_list, return_ty =
match_fun_ty (List.length arg_list) (infer env (level + 1) fn_expr)
in
List.iter2
(fun param_ty arg_expr -> unify param_ty (infer env (level + 1) arg_expr))
param_ty_list arg_list
;
duplicate_dynamic level return_ty
| Ann(expr, ty_ann) ->
infer env level (Call(Fun([("x", Some ty_ann)], Var "x"), [expr]))
|
e4558fe1a73029aac50a3da3242f603ad3f5006b5ff19cc50960d6e48a55735e | momohatt/hscaml | Syntax.hs | module Syntax
( Command(..)
, Decl(..)
, Expr(..)
, Pattern(..)
, Binop(..)
, Value(..)
, Env
, nameOfDecl
) where
data Command
= CExpr Expr
| CDecl Decl
deriving (Show)
data Decl
= DLet String Expr
| DLetRec String Expr
deriving (Show)
data Expr
= EConstInt Integer
| EConstBool Bool
| EVar String
| ETuple [Expr]
| ENil
| ECons Expr Expr
| ENot Expr
| ENeg Expr
| EBinop Binop Expr Expr
| EIf Expr Expr Expr
| ELetIn Decl Expr
| EFun String Expr
| EApp Expr Expr
| EMatch Expr [(Pattern, Expr)]
deriving (Show)
data Pattern
= PInt Integer
| PBool Bool
| PVar String
| PTuple [Pattern]
| PNil
| PCons Pattern Pattern
deriving (Show)
data Binop
= BAnd
| BOr
| BAdd
| BSub
| BMul
| BDiv
| BEq
| BGT
| BLT
| BGE
| BLE
deriving (Show, Eq)
data Value
= VInt Integer
| VBool Bool
| VFun String Expr Env
| VTuple [Value]
| VNil
| VCons Value Value
type Env = [(String, Value)]
instance Show Value where
show (VInt n) = show n
show (VBool True) = "true"
show (VBool False) = "false"
show (VFun {}) = "<fun>"
show (VTuple vs) = "(" ++ show (head vs) ++ concatMap (\v -> ", " ++ show v) (tail vs) ++ ")"
show VNil = "[]"
show (VCons v1 v2) = "[" ++ show v1 ++ listToStr' v2
where listToStr' v = case v of
VNil -> "]"
VCons v1 v2 -> "; " ++ show v1 ++ listToStr' v2
nameOfDecl :: Decl -> String
nameOfDecl d =
case d of
DLet x _ -> x
DLetRec x _ -> x
| null | https://raw.githubusercontent.com/momohatt/hscaml/00a2251d6f247dfd63bdd9252d6bc248dafac2af/src/Syntax.hs | haskell | module Syntax
( Command(..)
, Decl(..)
, Expr(..)
, Pattern(..)
, Binop(..)
, Value(..)
, Env
, nameOfDecl
) where
data Command
= CExpr Expr
| CDecl Decl
deriving (Show)
data Decl
= DLet String Expr
| DLetRec String Expr
deriving (Show)
data Expr
= EConstInt Integer
| EConstBool Bool
| EVar String
| ETuple [Expr]
| ENil
| ECons Expr Expr
| ENot Expr
| ENeg Expr
| EBinop Binop Expr Expr
| EIf Expr Expr Expr
| ELetIn Decl Expr
| EFun String Expr
| EApp Expr Expr
| EMatch Expr [(Pattern, Expr)]
deriving (Show)
data Pattern
= PInt Integer
| PBool Bool
| PVar String
| PTuple [Pattern]
| PNil
| PCons Pattern Pattern
deriving (Show)
data Binop
= BAnd
| BOr
| BAdd
| BSub
| BMul
| BDiv
| BEq
| BGT
| BLT
| BGE
| BLE
deriving (Show, Eq)
data Value
= VInt Integer
| VBool Bool
| VFun String Expr Env
| VTuple [Value]
| VNil
| VCons Value Value
type Env = [(String, Value)]
instance Show Value where
show (VInt n) = show n
show (VBool True) = "true"
show (VBool False) = "false"
show (VFun {}) = "<fun>"
show (VTuple vs) = "(" ++ show (head vs) ++ concatMap (\v -> ", " ++ show v) (tail vs) ++ ")"
show VNil = "[]"
show (VCons v1 v2) = "[" ++ show v1 ++ listToStr' v2
where listToStr' v = case v of
VNil -> "]"
VCons v1 v2 -> "; " ++ show v1 ++ listToStr' v2
nameOfDecl :: Decl -> String
nameOfDecl d =
case d of
DLet x _ -> x
DLetRec x _ -> x
| |
56007d6c81542e41cc48842f69040cd3f74a230623ce44ca5a901abc42d8c2bb | goldfirere/units | Simulator.hs | Copyright ( c ) 2013 - 4
This file demonstrates some of ` units ` 's capabilities by building up a simple
physics simulator .
This file demonstrates some of `units`'s capabilities by building up a simple
physics simulator.
-}
# LANGUAGE TypeOperators , TypeFamilies , QuasiQuotes #
module Tests.Compile.Simulator where
import Data.Metrology.SI
import Data.Metrology.Show ()
import Data.Metrology.Vector
-- We never want to add positions! QPoint protects us from this.
type Position = QPoint Length
-- +x = right
-- +y = up
We still want the " outer " type to be , not the pair . So push the pairing
operation down to the 's representation .
type family Vec2D x where
Vec2D (Qu d l n) = Qu d l (n, n)
-- An object in our little simulation
data Object = Object { mass :: Mass
, rad :: Length
, pos :: Vec2D Position
, vel :: Vec2D Velocity }
deriving Show
type Universe = [Object]
updating takes two passes : move everything according to their own positions
-- and gravity (ignoring pulls between objects), and then look for collisions
-- and update collided objects' positions and velocities accordingly. This might
fail if three objects were to collide in a row all at once .
g :: Vec2D Acceleration
could also be :/ ( Second : ^ sTwo )
g_universe :: Force %* Length %^ Two %/ (Mass %^ Two)
g_universe = 6.67e-11 % [si| N m^2 / kg^2 |]
update :: Time -> Universe -> Universe
update dt objs
= let objs1 = map (updateNoColls dt objs) objs in
updateColls objs1
-- update without taking collisions into account
updateNoColls :: Time -> Universe -> Object -> Object
updateNoColls dt univ obj@(Object { mass = m, pos = x, vel = dx })
= let new_pos = x |.+^| dx |^*| dt -- new position
v1 = dx |+| g |^*| dt -- new velocity w.r.t. downward gravity
f = gravityAt univ x m
a = f |^/| m
v2 = v1 |+| a |^*| dt -- new velocity also with mutual gravity
in obj { pos = new_pos, vel = v2 }
-- calculate the gravity at a point from all other masses
gravityAt :: Universe -> Vec2D Position -> Mass -> Vec2D Force
gravityAt univ p m = qSum (map gravity_at_1 univ)
where
gravity caused by just one point
gravity_at_1 (Object { mass = m1, pos = pos1 })
= let r = p |.-.| pos1
f = g_universe |*| m1 |*| m |*^| r |^/| (qMagnitude r |^ sThree)
in
if qMagnitude r |>| (zero :: Length) -- exclude the point itself!
then redim f
else zero
-- update by collisions
updateColls :: Universe -> Universe
updateColls objs
= let collisions = findCollisions objs in
map resolveCollision collisions
-- returns a list of collisions, as pairs of an object with, perhaps,
-- a collision partner
findCollisions :: Universe -> [(Object, Maybe Object)]
findCollisions objs
= map (findCollision objs) objs
check for collisions for one particular Object
findCollision :: Universe -> Object -> (Object, Maybe Object)
findCollision [] obj = (obj, Nothing)
findCollision (other : rest) obj
| colliding other obj
= (obj, Just other)
| otherwise
= findCollision rest obj
are two objects in contact ?
colliding :: Object -> Object -> Bool
colliding (Object { pos = x1, rad = rad1 })
(Object { pos = x2, rad = rad2 })
= let distance = qDistance x1 x2 in
distance |>| (zero :: Length) && distance |<=| (rad1 |+| rad2)
resolve the collision between two objects , updating only the first
object in the pair . The second object will be updated in a separate
-- (symmetric) call.
resolveCollision :: (Object, Maybe Object) -> Object
resolveCollision (obj, Nothing) = obj
resolveCollision (obj@Object { mass = m1, rad = rad1
, pos = z1, vel = v1 },
Just (Object { mass = m2, rad = rad2
, pos = z2, vel = v2 }))
= let -- c :: Vec2D Length
c = z2 |.-.| z1 -- vector from z1 to z2
vc1 , vc2 , vd1 , vc1 ' , v1 ' : : Vec2D Velocity
vc1 = c `qProject` v1 -- component of v1 along c
vc2 = c `qProject` v2 -- component of v2 along c
vd1 = v1 |-| vc1 -- component of v1 orthogonal to c
vc1' = (m1 |*^| vc1 |-| m2 |*^| vc2 |+| 2 *| m2 |*^| vc2) |^/| (m1 |+| m2)
-- new component of v1 along c
v1' = vc1' |+| vd1 -- new v1
also , move object 1 to be out of contact with object 2
z1' = z2 |.-^| (rad1 |+| rad2) |*^| qNormalized c
in
obj { pos = z1', vel = v1' }
| null | https://raw.githubusercontent.com/goldfirere/units/0ffc07627bb6c1eacd60469fd9366346cbfde334/units-test/Tests/Compile/Simulator.hs | haskell | We never want to add positions! QPoint protects us from this.
+x = right
+y = up
An object in our little simulation
and gravity (ignoring pulls between objects), and then look for collisions
and update collided objects' positions and velocities accordingly. This might
update without taking collisions into account
new position
new velocity w.r.t. downward gravity
new velocity also with mutual gravity
calculate the gravity at a point from all other masses
exclude the point itself!
update by collisions
returns a list of collisions, as pairs of an object with, perhaps,
a collision partner
(symmetric) call.
c :: Vec2D Length
vector from z1 to z2
component of v1 along c
component of v2 along c
component of v1 orthogonal to c
new component of v1 along c
new v1 | Copyright ( c ) 2013 - 4
This file demonstrates some of ` units ` 's capabilities by building up a simple
physics simulator .
This file demonstrates some of `units`'s capabilities by building up a simple
physics simulator.
-}
# LANGUAGE TypeOperators , TypeFamilies , QuasiQuotes #
module Tests.Compile.Simulator where
import Data.Metrology.SI
import Data.Metrology.Show ()
import Data.Metrology.Vector
type Position = QPoint Length
We still want the " outer " type to be , not the pair . So push the pairing
operation down to the 's representation .
type family Vec2D x where
Vec2D (Qu d l n) = Qu d l (n, n)
data Object = Object { mass :: Mass
, rad :: Length
, pos :: Vec2D Position
, vel :: Vec2D Velocity }
deriving Show
type Universe = [Object]
updating takes two passes : move everything according to their own positions
fail if three objects were to collide in a row all at once .
g :: Vec2D Acceleration
could also be :/ ( Second : ^ sTwo )
g_universe :: Force %* Length %^ Two %/ (Mass %^ Two)
g_universe = 6.67e-11 % [si| N m^2 / kg^2 |]
update :: Time -> Universe -> Universe
update dt objs
= let objs1 = map (updateNoColls dt objs) objs in
updateColls objs1
updateNoColls :: Time -> Universe -> Object -> Object
updateNoColls dt univ obj@(Object { mass = m, pos = x, vel = dx })
f = gravityAt univ x m
a = f |^/| m
in obj { pos = new_pos, vel = v2 }
gravityAt :: Universe -> Vec2D Position -> Mass -> Vec2D Force
gravityAt univ p m = qSum (map gravity_at_1 univ)
where
gravity caused by just one point
gravity_at_1 (Object { mass = m1, pos = pos1 })
= let r = p |.-.| pos1
f = g_universe |*| m1 |*| m |*^| r |^/| (qMagnitude r |^ sThree)
in
then redim f
else zero
updateColls :: Universe -> Universe
updateColls objs
= let collisions = findCollisions objs in
map resolveCollision collisions
findCollisions :: Universe -> [(Object, Maybe Object)]
findCollisions objs
= map (findCollision objs) objs
check for collisions for one particular Object
findCollision :: Universe -> Object -> (Object, Maybe Object)
findCollision [] obj = (obj, Nothing)
findCollision (other : rest) obj
| colliding other obj
= (obj, Just other)
| otherwise
= findCollision rest obj
are two objects in contact ?
colliding :: Object -> Object -> Bool
colliding (Object { pos = x1, rad = rad1 })
(Object { pos = x2, rad = rad2 })
= let distance = qDistance x1 x2 in
distance |>| (zero :: Length) && distance |<=| (rad1 |+| rad2)
resolve the collision between two objects , updating only the first
object in the pair . The second object will be updated in a separate
resolveCollision :: (Object, Maybe Object) -> Object
resolveCollision (obj, Nothing) = obj
resolveCollision (obj@Object { mass = m1, rad = rad1
, pos = z1, vel = v1 },
Just (Object { mass = m2, rad = rad2
, pos = z2, vel = v2 }))
vc1 , vc2 , vd1 , vc1 ' , v1 ' : : Vec2D Velocity
vc1' = (m1 |*^| vc1 |-| m2 |*^| vc2 |+| 2 *| m2 |*^| vc2) |^/| (m1 |+| m2)
also , move object 1 to be out of contact with object 2
z1' = z2 |.-^| (rad1 |+| rad2) |*^| qNormalized c
in
obj { pos = z1', vel = v1' }
|
b8e136b0b25772155246dd9b90832158a7b76dbece208a5aeb30246efbef4e75 | janestreet/universe | constants.mli | (* nil format *)
val nil : char
(* bool format family *)
val true_ : char
val false_ : char
(* int format family *)
val positive_fixint_unmask : int
val negative_fixint_mask : int
val uint8_header : char
val uint16_header : char
val uint32_header : char
val uint64_header : char
val int8_header : char
val int16_header : char
val int32_header : char
val int64_header : char
(* float format family *)
val float32_header : char
val float64_header : char
(* string format family *)
val fixstr_mask : int
val str8_header : char
val str16_header : char
val str32_header : char
(* binary format family *)
val bin8_header : char
val bin16_header : char
val bin32_header : char
(* array format family *)
val fixarray_mask : int
val array16_header : char
val array32_header : char
(* map format family *)
val fixmap_mask : int
val map16_header : char
val map32_header : char
(* ext format family *)
val fixext1_header : char
val fixext2_header : char
val fixext4_header : char
val fixext8_header : char
val fixext16_header : char
val ext8_header : char
val ext16_header : char
val ext32_header : char
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/vcaml/msgpack/src/constants.mli | ocaml | nil format
bool format family
int format family
float format family
string format family
binary format family
array format family
map format family
ext format family | val nil : char
val true_ : char
val false_ : char
val positive_fixint_unmask : int
val negative_fixint_mask : int
val uint8_header : char
val uint16_header : char
val uint32_header : char
val uint64_header : char
val int8_header : char
val int16_header : char
val int32_header : char
val int64_header : char
val float32_header : char
val float64_header : char
val fixstr_mask : int
val str8_header : char
val str16_header : char
val str32_header : char
val bin8_header : char
val bin16_header : char
val bin32_header : char
val fixarray_mask : int
val array16_header : char
val array32_header : char
val fixmap_mask : int
val map16_header : char
val map32_header : char
val fixext1_header : char
val fixext2_header : char
val fixext4_header : char
val fixext8_header : char
val fixext16_header : char
val ext8_header : char
val ext16_header : char
val ext32_header : char
|
e0380b61ffbad7f8cd59b36c3bc56f809da64148af29e7aaadd7e132f0bdb27f | jellelicht/guix | pk-crypto.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (guix pk-crypto)
#:use-module ((guix utils)
#:select (bytevector->base16-string
base16-string->bytevector))
#:use-module (guix gcrypt)
#:use-module (system foreign)
#:use-module (rnrs bytevectors)
#:use-module (ice-9 match)
#:export (canonical-sexp?
error-source
error-string
string->canonical-sexp
canonical-sexp->string
number->canonical-sexp
canonical-sexp-car
canonical-sexp-cdr
canonical-sexp-nth
canonical-sexp-nth-data
canonical-sexp-length
canonical-sexp-null?
canonical-sexp-list?
bytevector->hash-data
hash-data->bytevector
key-type
sign
verify
generate-key
find-sexp-token
canonical-sexp->sexp
sexp->canonical-sexp)
#:re-export (gcrypt-version))
;;; Commentary:
;;;
Public key cryptographic routines from GNU Libgcrypt .
;;;;
Libgcrypt uses " canonical s - expressions " to represent key material ,
;;; parameters, and data. We keep it as an opaque object to map them to
Scheme s - expressions because ( 1 ) Libgcrypt sexps may be stored in secure
memory , and ( 2 ) the read syntax is different .
;;;
;;; A 'canonical-sexp->sexp' procedure is provided nevertheless, for use in
cases where it is safe to move data out of Libgcrypt --- e.g. , when
;;; processing ACL entries, public keys, etc.
;;;
Canonical sexps were defined by Rivest et al . in the IETF draft at
;;; <> for the purposes of SPKI
;;; (see <>.)
;;;
;;; Code:
Libgcrypt " s - expressions " .
(define-wrapped-pointer-type <canonical-sexp>
canonical-sexp?
naked-pointer->canonical-sexp
canonical-sexp->pointer
(lambda (obj port)
;; Don't print OBJ's external representation: we don't want key material
;; to leak in backtraces and such.
(format port "#<canonical-sexp ~a | ~a>"
(number->string (object-address obj) 16)
(number->string (pointer-address (canonical-sexp->pointer obj))
16))))
(define finalize-canonical-sexp!
(libgcrypt-func "gcry_sexp_release"))
(define-inlinable (pointer->canonical-sexp ptr)
"Return a <canonical-sexp> that wraps PTR."
(let* ((sexp (naked-pointer->canonical-sexp ptr))
(ptr* (canonical-sexp->pointer sexp)))
Did we already have a < canonical - sexp > object for PTR ?
(when (equal? ptr ptr*)
No , so we can safely add a finalizer ( in 2.0.9
;; 'set-pointer-finalizer!' *adds* a finalizer rather than replacing the
;; existing one.)
(set-pointer-finalizer! ptr finalize-canonical-sexp!))
sexp))
(define error-source
(let* ((ptr (libgcrypt-func "gcry_strsource"))
(proc (pointer->procedure '* ptr (list int))))
(lambda (err)
"Return the error source (a string) for ERR, an error code as thrown
along with 'gcry-error'."
(pointer->string (proc err)))))
(define error-string
(let* ((ptr (libgcrypt-func "gcry_strerror"))
(proc (pointer->procedure '* ptr (list int))))
(lambda (err)
"Return the error description (a string) for ERR, an error code as
thrown along with 'gcry-error'."
(pointer->string (proc err)))))
(define string->canonical-sexp
(let* ((ptr (libgcrypt-func "gcry_sexp_new"))
(proc (pointer->procedure int ptr `(* * ,size_t ,int))))
(lambda (str)
"Parse STR and return the corresponding gcrypt s-expression."
When STR comes from ' canonical - sexp->string ' , it may contain
;; characters that are really meant to be interpreted as bytes as in a C
' char * ' . Thus , convert STR to ISO-8859 - 1 so the byte values of the
;; characters are preserved.
(let* ((sexp (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc sexp (string->pointer str "ISO-8859-1") 0 1)))
(if (= 0 err)
(pointer->canonical-sexp (dereference-pointer sexp))
(throw 'gcry-error 'string->canonical-sexp err))))))
(define-syntax GCRYSEXP_FMT_ADVANCED
(identifier-syntax 3))
(define canonical-sexp->string
(let* ((ptr (libgcrypt-func "gcry_sexp_sprint"))
(proc (pointer->procedure size_t ptr `(* ,int * ,size_t))))
(lambda (sexp)
"Return a textual representation of SEXP."
(let loop ((len 1024))
(let* ((buf (bytevector->pointer (make-bytevector len)))
(size (proc (canonical-sexp->pointer sexp)
GCRYSEXP_FMT_ADVANCED buf len)))
(if (zero? size)
(loop (* len 2))
(pointer->string buf size "ISO-8859-1")))))))
(define canonical-sexp-car
(let* ((ptr (libgcrypt-func "gcry_sexp_car"))
(proc (pointer->procedure '* ptr '(*))))
(lambda (lst)
"Return the first element of LST, an sexp, if that element is a list;
return #f if LST or its first element is not a list (this is different from
the usual Lisp 'car'.)"
(let ((result (proc (canonical-sexp->pointer lst))))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define canonical-sexp-cdr
(let* ((ptr (libgcrypt-func "gcry_sexp_cdr"))
(proc (pointer->procedure '* ptr '(*))))
(lambda (lst)
"Return the tail of LST, an sexp, or #f if LST is not a list."
(let ((result (proc (canonical-sexp->pointer lst))))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define canonical-sexp-nth
(let* ((ptr (libgcrypt-func "gcry_sexp_nth"))
(proc (pointer->procedure '* ptr `(* ,int))))
(lambda (lst index)
"Return the INDEXth nested element of LST, an s-expression. Return #f
if that element does not exist, or if it's an atom. (Note: this is obviously
different from Scheme's 'list-ref'.)"
(let ((result (proc (canonical-sexp->pointer lst) index)))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define (dereference-size_t p)
"Return the size_t value pointed to by P."
(bytevector-uint-ref (pointer->bytevector p (sizeof size_t))
0 (native-endianness)
(sizeof size_t)))
(define canonical-sexp-length
(let* ((ptr (libgcrypt-func "gcry_sexp_length"))
(proc (pointer->procedure int ptr '(*))))
(lambda (sexp)
"Return the length of SEXP if it's a list (including the empty list);
return zero if SEXP is an atom."
(proc (canonical-sexp->pointer sexp)))))
(define token-string?
(let ((token-cs (char-set-union char-set:digit
char-set:letter
(char-set #\- #\. #\/ #\_
#\: #\* #\+ #\=))))
(lambda (str)
"Return #t if STR is a token as per Section 4.3 of
<>."
(and (not (string-null? str))
(string-every token-cs str)
(not (char-set-contains? char-set:digit (string-ref str 0)))))))
(define canonical-sexp-nth-data
(let* ((ptr (libgcrypt-func "gcry_sexp_nth_data"))
(proc (pointer->procedure '* ptr `(* ,int *))))
(lambda (lst index)
"Return as a symbol (for \"sexp tokens\") or a bytevector (for any other
\"octet string\") the INDEXth data element (atom) of LST, an s-expression.
Return #f if that element does not exist, or if it's a list."
(let* ((size* (bytevector->pointer (make-bytevector (sizeof '*))))
(result (proc (canonical-sexp->pointer lst) index size*)))
(if (null-pointer? result)
#f
(let* ((len (dereference-size_t size*))
(str (pointer->string result len "ISO-8859-1")))
;; The sexp spec speaks of "tokens" and "octet strings".
;; Sometimes these octet strings are actual strings (text),
;; sometimes they're bytevectors, and sometimes they're
;; multi-precision integers (MPIs). Only the application knows.
;; However, for convenience, we return a symbol when a token is
;; encountered since tokens are frequent (at least in the 'car'
;; of each sexp.)
(if (token-string? str)
(string->symbol str) ; an sexp "token"
(bytevector-copy ; application data, textual or binary
(pointer->bytevector result len)))))))))
(define (number->canonical-sexp number)
"Return an s-expression representing NUMBER."
(string->canonical-sexp (string-append "#" (number->string number 16) "#")))
(define* (bytevector->hash-data bv
#:optional
(hash-algo "sha256")
#:key (key-type 'ecc))
"Given BV, a bytevector containing a hash of type HASH-ALGO, return an
s-expression suitable for use as the 'data' argument for 'sign'. KEY-TYPE
must be a symbol: 'dsa, 'ecc, or 'rsa."
(string->canonical-sexp
(format #f "(data (flags ~a) (hash \"~a\" #~a#))"
(case key-type
((ecc dsa) "rfc6979")
((rsa) "pkcs1")
(else (error "unknown key type" key-type)))
hash-algo
(bytevector->base16-string bv))))
(define (key-type sexp)
"Return a symbol denoting the type of public or private key represented by
SEXP--e.g., 'rsa', 'ecc'--or #f if SEXP does not denote a valid key."
(case (canonical-sexp-nth-data sexp 0)
((public-key private-key)
(canonical-sexp-nth-data (canonical-sexp-nth sexp 1) 0))
(else #f)))
(define* (hash-data->bytevector data)
"Return two values: the hash value (a bytevector), and the hash algorithm (a
string) extracted from DATA, an sexp as returned by 'bytevector->hash-data'.
Return #f if DATA does not conform."
(let ((hash (find-sexp-token data 'hash)))
(if hash
(let ((algo (canonical-sexp-nth-data hash 1))
(value (canonical-sexp-nth-data hash 2)))
(values value (symbol->string algo)))
(values #f #f))))
(define sign
(let* ((ptr (libgcrypt-func "gcry_pk_sign"))
(proc (pointer->procedure int ptr '(* * *))))
(lambda (data secret-key)
"Sign DATA, a canonical s-expression representing a suitable hash, with
SECRET-KEY (a canonical s-expression whose car is 'private-key'.) Note that
DATA must be a 'data' s-expression, as returned by
'bytevector->hash-data' (info \"(gcrypt) Cryptographic Functions\")."
(let* ((sig (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc sig (canonical-sexp->pointer data)
(canonical-sexp->pointer secret-key))))
(if (= 0 err)
(pointer->canonical-sexp (dereference-pointer sig))
(throw 'gcry-error 'sign err))))))
(define verify
(let* ((ptr (libgcrypt-func "gcry_pk_verify"))
(proc (pointer->procedure int ptr '(* * *))))
(lambda (signature data public-key)
"Verify that SIGNATURE is a signature of DATA with PUBLIC-KEY, all of
which are gcrypt s-expressions."
(zero? (proc (canonical-sexp->pointer signature)
(canonical-sexp->pointer data)
(canonical-sexp->pointer public-key))))))
(define generate-key
(let* ((ptr (libgcrypt-func "gcry_pk_genkey"))
(proc (pointer->procedure int ptr '(* *))))
(lambda (params)
"Return as an s-expression a new key pair for PARAMS. PARAMS must be an
s-expression like: (genkey (rsa (nbits 4:2048)))."
(let* ((key (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc key (canonical-sexp->pointer params))))
(if (zero? err)
(pointer->canonical-sexp (dereference-pointer key))
(throw 'gcry-error 'generate-key err))))))
(define find-sexp-token
(let* ((ptr (libgcrypt-func "gcry_sexp_find_token"))
(proc (pointer->procedure '* ptr `(* * ,size_t))))
(lambda (sexp token)
"Find in SEXP the first element whose 'car' is TOKEN and return it;
return #f if not found."
(let* ((token (string->pointer (symbol->string token)))
(res (proc (canonical-sexp->pointer sexp) token 0)))
(if (null-pointer? res)
#f
(pointer->canonical-sexp res))))))
(define-inlinable (canonical-sexp-null? sexp)
"Return #t if SEXP is the empty-list sexp."
(null-pointer? (canonical-sexp->pointer sexp)))
(define (canonical-sexp-list? sexp)
"Return #t if SEXP is a list."
(or (canonical-sexp-null? sexp)
(> (canonical-sexp-length sexp) 0)))
(define (canonical-sexp-fold proc seed sexp)
"Fold PROC (as per SRFI-1) over SEXP, a canonical sexp."
(if (canonical-sexp-list? sexp)
(let ((len (canonical-sexp-length sexp)))
(let loop ((index 0)
(result seed))
(if (= index len)
result
(loop (+ 1 index)
;; XXX: Call 'nth-data' *before* 'nth' to work around
;; <>, which
affects 1.6.0 and earlier versions .
(proc (or (canonical-sexp-nth-data sexp index)
(canonical-sexp-nth sexp index))
result)))))
(error "sexp is not a list" sexp)))
(define (canonical-sexp->sexp sexp)
"Return a Scheme sexp corresponding to SEXP. This is particularly useful to
compare sexps (since Libgcrypt does not provide an 'equal?' procedure), or to
use pattern matching."
(if (canonical-sexp-list? sexp)
(reverse
(canonical-sexp-fold (lambda (item result)
(cons (if (canonical-sexp? item)
(canonical-sexp->sexp item)
item)
result))
'()
sexp))
As of Libgcrypt 1.6.0 , there 's no function to extract the buffer of a
non - list sexp ( ! ) , so we first enlist SEXP , then get at its buffer .
(let ((sexp (string->canonical-sexp
(string-append "(" (canonical-sexp->string sexp)
")"))))
(or (canonical-sexp-nth-data sexp 0)
(canonical-sexp-nth sexp 0)))))
(define (sexp->canonical-sexp sexp)
"Return a canonical sexp equivalent to SEXP, a Scheme sexp as returned by
'canonical-sexp->sexp'."
XXX : This is inefficient , but the Libgcrypt API does n't allow us to do
;; much better.
(string->canonical-sexp
(call-with-output-string
(lambda (port)
(define (write item)
(cond ((list? item)
(display "(" port)
(for-each write item)
(display ")" port))
((symbol? item)
(format port " ~a" item))
((bytevector? item)
(format port " #~a#"
(bytevector->base16-string item)))
(else
(error "unsupported sexp item type" item))))
(write sexp)))))
(define (gcrypt-error-printer port key args default-printer)
"Print the gcrypt error specified by ARGS."
(match args
((proc err)
(format port "In procedure ~a: ~a: ~a"
proc (error-source err) (error-string err)))))
(set-exception-printer! 'gcry-error gcrypt-error-printer)
;;; pk-crypto.scm ends here
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/pk-crypto.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Commentary:
parameters, and data. We keep it as an opaque object to map them to
A 'canonical-sexp->sexp' procedure is provided nevertheless, for use in
processing ACL entries, public keys, etc.
<> for the purposes of SPKI
(see <>.)
Code:
Don't print OBJ's external representation: we don't want key material
to leak in backtraces and such.
'set-pointer-finalizer!' *adds* a finalizer rather than replacing the
existing one.)
characters that are really meant to be interpreted as bytes as in a C
characters are preserved.
The sexp spec speaks of "tokens" and "octet strings".
Sometimes these octet strings are actual strings (text),
sometimes they're bytevectors, and sometimes they're
multi-precision integers (MPIs). Only the application knows.
However, for convenience, we return a symbol when a token is
encountered since tokens are frequent (at least in the 'car'
of each sexp.)
an sexp "token"
application data, textual or binary
XXX: Call 'nth-data' *before* 'nth' to work around
<>, which
much better.
pk-crypto.scm ends here | Copyright © 2013 , 2014 , 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix pk-crypto)
#:use-module ((guix utils)
#:select (bytevector->base16-string
base16-string->bytevector))
#:use-module (guix gcrypt)
#:use-module (system foreign)
#:use-module (rnrs bytevectors)
#:use-module (ice-9 match)
#:export (canonical-sexp?
error-source
error-string
string->canonical-sexp
canonical-sexp->string
number->canonical-sexp
canonical-sexp-car
canonical-sexp-cdr
canonical-sexp-nth
canonical-sexp-nth-data
canonical-sexp-length
canonical-sexp-null?
canonical-sexp-list?
bytevector->hash-data
hash-data->bytevector
key-type
sign
verify
generate-key
find-sexp-token
canonical-sexp->sexp
sexp->canonical-sexp)
#:re-export (gcrypt-version))
Public key cryptographic routines from GNU Libgcrypt .
Libgcrypt uses " canonical s - expressions " to represent key material ,
Scheme s - expressions because ( 1 ) Libgcrypt sexps may be stored in secure
memory , and ( 2 ) the read syntax is different .
cases where it is safe to move data out of Libgcrypt --- e.g. , when
Canonical sexps were defined by Rivest et al . in the IETF draft at
Libgcrypt " s - expressions " .
(define-wrapped-pointer-type <canonical-sexp>
canonical-sexp?
naked-pointer->canonical-sexp
canonical-sexp->pointer
(lambda (obj port)
(format port "#<canonical-sexp ~a | ~a>"
(number->string (object-address obj) 16)
(number->string (pointer-address (canonical-sexp->pointer obj))
16))))
(define finalize-canonical-sexp!
(libgcrypt-func "gcry_sexp_release"))
(define-inlinable (pointer->canonical-sexp ptr)
"Return a <canonical-sexp> that wraps PTR."
(let* ((sexp (naked-pointer->canonical-sexp ptr))
(ptr* (canonical-sexp->pointer sexp)))
Did we already have a < canonical - sexp > object for PTR ?
(when (equal? ptr ptr*)
No , so we can safely add a finalizer ( in 2.0.9
(set-pointer-finalizer! ptr finalize-canonical-sexp!))
sexp))
(define error-source
(let* ((ptr (libgcrypt-func "gcry_strsource"))
(proc (pointer->procedure '* ptr (list int))))
(lambda (err)
"Return the error source (a string) for ERR, an error code as thrown
along with 'gcry-error'."
(pointer->string (proc err)))))
(define error-string
(let* ((ptr (libgcrypt-func "gcry_strerror"))
(proc (pointer->procedure '* ptr (list int))))
(lambda (err)
"Return the error description (a string) for ERR, an error code as
thrown along with 'gcry-error'."
(pointer->string (proc err)))))
(define string->canonical-sexp
(let* ((ptr (libgcrypt-func "gcry_sexp_new"))
(proc (pointer->procedure int ptr `(* * ,size_t ,int))))
(lambda (str)
"Parse STR and return the corresponding gcrypt s-expression."
When STR comes from ' canonical - sexp->string ' , it may contain
' char * ' . Thus , convert STR to ISO-8859 - 1 so the byte values of the
(let* ((sexp (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc sexp (string->pointer str "ISO-8859-1") 0 1)))
(if (= 0 err)
(pointer->canonical-sexp (dereference-pointer sexp))
(throw 'gcry-error 'string->canonical-sexp err))))))
(define-syntax GCRYSEXP_FMT_ADVANCED
(identifier-syntax 3))
(define canonical-sexp->string
(let* ((ptr (libgcrypt-func "gcry_sexp_sprint"))
(proc (pointer->procedure size_t ptr `(* ,int * ,size_t))))
(lambda (sexp)
"Return a textual representation of SEXP."
(let loop ((len 1024))
(let* ((buf (bytevector->pointer (make-bytevector len)))
(size (proc (canonical-sexp->pointer sexp)
GCRYSEXP_FMT_ADVANCED buf len)))
(if (zero? size)
(loop (* len 2))
(pointer->string buf size "ISO-8859-1")))))))
(define canonical-sexp-car
(let* ((ptr (libgcrypt-func "gcry_sexp_car"))
(proc (pointer->procedure '* ptr '(*))))
(lambda (lst)
return #f if LST or its first element is not a list (this is different from
the usual Lisp 'car'.)"
(let ((result (proc (canonical-sexp->pointer lst))))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define canonical-sexp-cdr
(let* ((ptr (libgcrypt-func "gcry_sexp_cdr"))
(proc (pointer->procedure '* ptr '(*))))
(lambda (lst)
"Return the tail of LST, an sexp, or #f if LST is not a list."
(let ((result (proc (canonical-sexp->pointer lst))))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define canonical-sexp-nth
(let* ((ptr (libgcrypt-func "gcry_sexp_nth"))
(proc (pointer->procedure '* ptr `(* ,int))))
(lambda (lst index)
"Return the INDEXth nested element of LST, an s-expression. Return #f
if that element does not exist, or if it's an atom. (Note: this is obviously
different from Scheme's 'list-ref'.)"
(let ((result (proc (canonical-sexp->pointer lst) index)))
(if (null-pointer? result)
#f
(pointer->canonical-sexp result))))))
(define (dereference-size_t p)
"Return the size_t value pointed to by P."
(bytevector-uint-ref (pointer->bytevector p (sizeof size_t))
0 (native-endianness)
(sizeof size_t)))
(define canonical-sexp-length
(let* ((ptr (libgcrypt-func "gcry_sexp_length"))
(proc (pointer->procedure int ptr '(*))))
(lambda (sexp)
return zero if SEXP is an atom."
(proc (canonical-sexp->pointer sexp)))))
(define token-string?
(let ((token-cs (char-set-union char-set:digit
char-set:letter
(char-set #\- #\. #\/ #\_
#\: #\* #\+ #\=))))
(lambda (str)
"Return #t if STR is a token as per Section 4.3 of
<>."
(and (not (string-null? str))
(string-every token-cs str)
(not (char-set-contains? char-set:digit (string-ref str 0)))))))
(define canonical-sexp-nth-data
(let* ((ptr (libgcrypt-func "gcry_sexp_nth_data"))
(proc (pointer->procedure '* ptr `(* ,int *))))
(lambda (lst index)
"Return as a symbol (for \"sexp tokens\") or a bytevector (for any other
\"octet string\") the INDEXth data element (atom) of LST, an s-expression.
Return #f if that element does not exist, or if it's a list."
(let* ((size* (bytevector->pointer (make-bytevector (sizeof '*))))
(result (proc (canonical-sexp->pointer lst) index size*)))
(if (null-pointer? result)
#f
(let* ((len (dereference-size_t size*))
(str (pointer->string result len "ISO-8859-1")))
(if (token-string? str)
(pointer->bytevector result len)))))))))
(define (number->canonical-sexp number)
"Return an s-expression representing NUMBER."
(string->canonical-sexp (string-append "#" (number->string number 16) "#")))
(define* (bytevector->hash-data bv
#:optional
(hash-algo "sha256")
#:key (key-type 'ecc))
"Given BV, a bytevector containing a hash of type HASH-ALGO, return an
s-expression suitable for use as the 'data' argument for 'sign'. KEY-TYPE
must be a symbol: 'dsa, 'ecc, or 'rsa."
(string->canonical-sexp
(format #f "(data (flags ~a) (hash \"~a\" #~a#))"
(case key-type
((ecc dsa) "rfc6979")
((rsa) "pkcs1")
(else (error "unknown key type" key-type)))
hash-algo
(bytevector->base16-string bv))))
(define (key-type sexp)
"Return a symbol denoting the type of public or private key represented by
SEXP--e.g., 'rsa', 'ecc'--or #f if SEXP does not denote a valid key."
(case (canonical-sexp-nth-data sexp 0)
((public-key private-key)
(canonical-sexp-nth-data (canonical-sexp-nth sexp 1) 0))
(else #f)))
(define* (hash-data->bytevector data)
"Return two values: the hash value (a bytevector), and the hash algorithm (a
string) extracted from DATA, an sexp as returned by 'bytevector->hash-data'.
Return #f if DATA does not conform."
(let ((hash (find-sexp-token data 'hash)))
(if hash
(let ((algo (canonical-sexp-nth-data hash 1))
(value (canonical-sexp-nth-data hash 2)))
(values value (symbol->string algo)))
(values #f #f))))
(define sign
(let* ((ptr (libgcrypt-func "gcry_pk_sign"))
(proc (pointer->procedure int ptr '(* * *))))
(lambda (data secret-key)
"Sign DATA, a canonical s-expression representing a suitable hash, with
SECRET-KEY (a canonical s-expression whose car is 'private-key'.) Note that
DATA must be a 'data' s-expression, as returned by
'bytevector->hash-data' (info \"(gcrypt) Cryptographic Functions\")."
(let* ((sig (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc sig (canonical-sexp->pointer data)
(canonical-sexp->pointer secret-key))))
(if (= 0 err)
(pointer->canonical-sexp (dereference-pointer sig))
(throw 'gcry-error 'sign err))))))
(define verify
(let* ((ptr (libgcrypt-func "gcry_pk_verify"))
(proc (pointer->procedure int ptr '(* * *))))
(lambda (signature data public-key)
"Verify that SIGNATURE is a signature of DATA with PUBLIC-KEY, all of
which are gcrypt s-expressions."
(zero? (proc (canonical-sexp->pointer signature)
(canonical-sexp->pointer data)
(canonical-sexp->pointer public-key))))))
(define generate-key
(let* ((ptr (libgcrypt-func "gcry_pk_genkey"))
(proc (pointer->procedure int ptr '(* *))))
(lambda (params)
"Return as an s-expression a new key pair for PARAMS. PARAMS must be an
s-expression like: (genkey (rsa (nbits 4:2048)))."
(let* ((key (bytevector->pointer (make-bytevector (sizeof '*))))
(err (proc key (canonical-sexp->pointer params))))
(if (zero? err)
(pointer->canonical-sexp (dereference-pointer key))
(throw 'gcry-error 'generate-key err))))))
(define find-sexp-token
(let* ((ptr (libgcrypt-func "gcry_sexp_find_token"))
(proc (pointer->procedure '* ptr `(* * ,size_t))))
(lambda (sexp token)
return #f if not found."
(let* ((token (string->pointer (symbol->string token)))
(res (proc (canonical-sexp->pointer sexp) token 0)))
(if (null-pointer? res)
#f
(pointer->canonical-sexp res))))))
(define-inlinable (canonical-sexp-null? sexp)
"Return #t if SEXP is the empty-list sexp."
(null-pointer? (canonical-sexp->pointer sexp)))
(define (canonical-sexp-list? sexp)
"Return #t if SEXP is a list."
(or (canonical-sexp-null? sexp)
(> (canonical-sexp-length sexp) 0)))
(define (canonical-sexp-fold proc seed sexp)
"Fold PROC (as per SRFI-1) over SEXP, a canonical sexp."
(if (canonical-sexp-list? sexp)
(let ((len (canonical-sexp-length sexp)))
(let loop ((index 0)
(result seed))
(if (= index len)
result
(loop (+ 1 index)
affects 1.6.0 and earlier versions .
(proc (or (canonical-sexp-nth-data sexp index)
(canonical-sexp-nth sexp index))
result)))))
(error "sexp is not a list" sexp)))
(define (canonical-sexp->sexp sexp)
"Return a Scheme sexp corresponding to SEXP. This is particularly useful to
compare sexps (since Libgcrypt does not provide an 'equal?' procedure), or to
use pattern matching."
(if (canonical-sexp-list? sexp)
(reverse
(canonical-sexp-fold (lambda (item result)
(cons (if (canonical-sexp? item)
(canonical-sexp->sexp item)
item)
result))
'()
sexp))
As of Libgcrypt 1.6.0 , there 's no function to extract the buffer of a
non - list sexp ( ! ) , so we first enlist SEXP , then get at its buffer .
(let ((sexp (string->canonical-sexp
(string-append "(" (canonical-sexp->string sexp)
")"))))
(or (canonical-sexp-nth-data sexp 0)
(canonical-sexp-nth sexp 0)))))
(define (sexp->canonical-sexp sexp)
"Return a canonical sexp equivalent to SEXP, a Scheme sexp as returned by
'canonical-sexp->sexp'."
XXX : This is inefficient , but the Libgcrypt API does n't allow us to do
(string->canonical-sexp
(call-with-output-string
(lambda (port)
(define (write item)
(cond ((list? item)
(display "(" port)
(for-each write item)
(display ")" port))
((symbol? item)
(format port " ~a" item))
((bytevector? item)
(format port " #~a#"
(bytevector->base16-string item)))
(else
(error "unsupported sexp item type" item))))
(write sexp)))))
(define (gcrypt-error-printer port key args default-printer)
"Print the gcrypt error specified by ARGS."
(match args
((proc err)
(format port "In procedure ~a: ~a: ~a"
proc (error-source err) (error-string err)))))
(set-exception-printer! 'gcry-error gcrypt-error-printer)
|
780b1d1fea94bf2afb415ea64368f7204549587cb121cb4ed81d6e0b2ac9355c | thheller/shadow-cljs | client.cljs | (ns shadow.cljs.npm.client
(:require [cljs.reader :as reader]
["readline" :as rl]
["net" :as node-net]
["fs" :as fs]
[shadow.cljs.npm.util :as util]
[clojure.string :as str]))
(defn socket-data [data exit-token error-token]
(let [txt (.toString data)]
(cond
(str/includes? txt exit-token)
[:close (-> (str/replace txt exit-token "")
(str/trimr))]
(str/includes? txt error-token)
[:exit (-> (str/replace txt error-token "")
(str/trimr))]
:else
[:continue txt])))
(defn repl-client
"readline client that tries to maintain a prompt. not quite smart yet."
[^js socket args]
(let [last-prompt-ref
(volatile! nil)
rl
(rl/createInterface
#js {:input js/process.stdin
:output js/process.stdout
:completer
(fn [prefix callback]
(let [last-prompt @last-prompt-ref]
;; without a prompt we can't autocomplete
(if-not last-prompt
(callback nil (clj->js [[] prefix]))
FIXME : hook this up properly
(callback nil (clj->js [[] prefix])))))})
write
(fn [text]
;; assume that everything we send is (read) which reads something
;; we can never autocomplete
;; and only a new prompt enables it
(vreset! last-prompt-ref nil)
(.write socket text))
repl-mode?
false
exit-token
(str (random-uuid))
error-token
(str (random-uuid))
stop!
(fn []
(.close rl)
(.end socket)
(println))]
(println "shadow-cljs - connected to server")
;; FIXME: this is an ugly hack that will be removed soon
;; its just a quick way to interact with the server without a proper API protocol
(write (str "(do (require 'shadow.cljs.devtools.cli) (shadow.cljs.devtools.cli/from-remote " (pr-str exit-token) " " (pr-str error-token) " " (pr-str (into [] args)) "))\n"))
(.on rl "line"
(fn [line]
(write (str line "\n"))))
CTRL+D closes the rl
(.on rl "close"
(fn []
(stop!)))
(.on socket "data"
(fn [data]
(let [[action txt]
(socket-data data exit-token error-token)]
(js/process.stdout.write txt)
(case action
:close
(stop!)
:exit
(js/process.exit 1)
:continue
(let [prompts
(re-seq #"\[(\d+):(\d+)\]\~([^=> \n]+)=> " txt)]
(doseq [[prompt root-id level-id ns :as m] prompts]
(vreset! last-prompt-ref {:text prompt
:ns (symbol ns)
:level (js/parseInt level-id 10)
:root (js/parseInt root-id 10)})
(.setPrompt rl prompt))
(when @last-prompt-ref
(.prompt rl true)))))))
(.on socket "end" #(.close rl))
))
(defn socket-pipe
"client that just pipes everything through the socket without any processing"
[^js socket args]
(let [write
(fn [text]
(.write socket text))
exit-token
(str (random-uuid))
error-token
(str (random-uuid))
stop!
(fn []
(.end socket))
stdin-read
(fn [buffer]
(write (.toString buffer)))]
(write (str "(do (require 'shadow.cljs.devtools.cli) (shadow.cljs.devtools.cli/from-remote " (pr-str exit-token) " " (pr-str error-token) " " (pr-str (into [] args)) "))\n"))
(js/process.stdin.on "data" stdin-read)
(js/process.stdin.on "close" stop!)
(.on socket "data"
(fn [data]
(let [[action txt]
(socket-data data exit-token error-token)]
(js/process.stdout.write txt)
(case action
:close
(stop!)
:exit
(js/process.exit 1)
:continue
nil))))
(.on socket "end"
(fn []
(js/process.stdin.removeListener "data" stdin-read)
(js/process.stdin.removeListener "close" stop!)
))))
(defn run
"attempts to connect to running server. if the connect fails calls callback"
[project-root config server-port-file opts args fallback]
(let [cli-repl
(-> (util/slurp server-port-file)
(js/parseInt 10))]
(if-not (pos-int? cli-repl)
(prn [:no-socket-repl-port server-port-file cli-repl])
(let [connect-listener
(fn [err]
(this-as socket
(if (get-in opts [:options :stdin])
(socket-pipe socket args)
(repl-client socket args))))
socket
(node-net/connect
#js {:port cli-repl
:host "127.0.0.1"
:timeout 1000}
connect-listener)]
(.on socket "error"
(fn [err]
(println "shadow-cljs - socket connect failed, server process dead?")
(fallback err)
))))))
| null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/main/shadow/cljs/npm/client.cljs | clojure | without a prompt we can't autocomplete
assume that everything we send is (read) which reads something
we can never autocomplete
and only a new prompt enables it
FIXME: this is an ugly hack that will be removed soon
its just a quick way to interact with the server without a proper API protocol | (ns shadow.cljs.npm.client
(:require [cljs.reader :as reader]
["readline" :as rl]
["net" :as node-net]
["fs" :as fs]
[shadow.cljs.npm.util :as util]
[clojure.string :as str]))
(defn socket-data [data exit-token error-token]
(let [txt (.toString data)]
(cond
(str/includes? txt exit-token)
[:close (-> (str/replace txt exit-token "")
(str/trimr))]
(str/includes? txt error-token)
[:exit (-> (str/replace txt error-token "")
(str/trimr))]
:else
[:continue txt])))
(defn repl-client
"readline client that tries to maintain a prompt. not quite smart yet."
[^js socket args]
(let [last-prompt-ref
(volatile! nil)
rl
(rl/createInterface
#js {:input js/process.stdin
:output js/process.stdout
:completer
(fn [prefix callback]
(let [last-prompt @last-prompt-ref]
(if-not last-prompt
(callback nil (clj->js [[] prefix]))
FIXME : hook this up properly
(callback nil (clj->js [[] prefix])))))})
write
(fn [text]
(vreset! last-prompt-ref nil)
(.write socket text))
repl-mode?
false
exit-token
(str (random-uuid))
error-token
(str (random-uuid))
stop!
(fn []
(.close rl)
(.end socket)
(println))]
(println "shadow-cljs - connected to server")
(write (str "(do (require 'shadow.cljs.devtools.cli) (shadow.cljs.devtools.cli/from-remote " (pr-str exit-token) " " (pr-str error-token) " " (pr-str (into [] args)) "))\n"))
(.on rl "line"
(fn [line]
(write (str line "\n"))))
CTRL+D closes the rl
(.on rl "close"
(fn []
(stop!)))
(.on socket "data"
(fn [data]
(let [[action txt]
(socket-data data exit-token error-token)]
(js/process.stdout.write txt)
(case action
:close
(stop!)
:exit
(js/process.exit 1)
:continue
(let [prompts
(re-seq #"\[(\d+):(\d+)\]\~([^=> \n]+)=> " txt)]
(doseq [[prompt root-id level-id ns :as m] prompts]
(vreset! last-prompt-ref {:text prompt
:ns (symbol ns)
:level (js/parseInt level-id 10)
:root (js/parseInt root-id 10)})
(.setPrompt rl prompt))
(when @last-prompt-ref
(.prompt rl true)))))))
(.on socket "end" #(.close rl))
))
(defn socket-pipe
"client that just pipes everything through the socket without any processing"
[^js socket args]
(let [write
(fn [text]
(.write socket text))
exit-token
(str (random-uuid))
error-token
(str (random-uuid))
stop!
(fn []
(.end socket))
stdin-read
(fn [buffer]
(write (.toString buffer)))]
(write (str "(do (require 'shadow.cljs.devtools.cli) (shadow.cljs.devtools.cli/from-remote " (pr-str exit-token) " " (pr-str error-token) " " (pr-str (into [] args)) "))\n"))
(js/process.stdin.on "data" stdin-read)
(js/process.stdin.on "close" stop!)
(.on socket "data"
(fn [data]
(let [[action txt]
(socket-data data exit-token error-token)]
(js/process.stdout.write txt)
(case action
:close
(stop!)
:exit
(js/process.exit 1)
:continue
nil))))
(.on socket "end"
(fn []
(js/process.stdin.removeListener "data" stdin-read)
(js/process.stdin.removeListener "close" stop!)
))))
(defn run
"attempts to connect to running server. if the connect fails calls callback"
[project-root config server-port-file opts args fallback]
(let [cli-repl
(-> (util/slurp server-port-file)
(js/parseInt 10))]
(if-not (pos-int? cli-repl)
(prn [:no-socket-repl-port server-port-file cli-repl])
(let [connect-listener
(fn [err]
(this-as socket
(if (get-in opts [:options :stdin])
(socket-pipe socket args)
(repl-client socket args))))
socket
(node-net/connect
#js {:port cli-repl
:host "127.0.0.1"
:timeout 1000}
connect-listener)]
(.on socket "error"
(fn [err]
(println "shadow-cljs - socket connect failed, server process dead?")
(fallback err)
))))))
|
e7b7146b53678e67f1375cc8c4c3b6aeb3c71f7589ad791cdb96dd14fe83e7c3 | janestreet/base_quickcheck | observer.mli | * Observers create random functions . { ! } creates a random function
using an observer for the input type and a generator for the output type .
using an observer for the input type and a generator for the output type. *)
open! Base
type -'a t = 'a Observer0.t
* { 2 Basic Observers }
(** Produces an observer that treats all values as equivalent. Random functions generated
using this observer will be constant with respect to the value(s) it observes. *)
val opaque : _ t
* @inline
(** Produces an observer that generates random inputs for a given function, calls the
function on them, then observes the corresponding outputs. *)
val fn : 'a Generator.t -> 'b t -> ('a -> 'b) t
val map_t : 'key t -> 'data t -> ('key, 'data, 'cmp) Map.t t
val set_t : 'elt t -> ('elt, 'cmp) Set.t t
val map_tree : 'key t -> 'data t -> ('key, 'data, 'cmp) Map.Using_comparator.Tree.t t
val set_tree : 'elt t -> ('elt, 'cmp) Set.Using_comparator.Tree.t t
(** {2 Observers Based on Hash Functions} *)
(** Creates an observer that just calls a hash function. This is a good default for most
hashable types not covered by the basic observers above. *)
val of_hash_fold : (Hash.state -> 'a -> Hash.state) -> 'a t
* { 2 Modifying Observers }
val unmap : 'a t -> f:('b -> 'a) -> 'b t
(** {2 Observers for Recursive Types} *)
* Ties the recursive knot to observe recursive types .
For example , here is an observer for binary trees :
{ [
let tree_observer leaf_observer =
fixed_point ( fun self - >
either leaf_observer ( both self self )
| > unmap ~f:(function
| ` Leaf leaf - > First leaf
| ` Node ( l , r ) - > Second ( l , r ) ) )
] }
For example, here is an observer for binary trees:
{[
let tree_observer leaf_observer =
fixed_point (fun self ->
either leaf_observer (both self self)
|> unmap ~f:(function
| `Leaf leaf -> First leaf
| `Node (l, r) -> Second (l, r)))
]}
*)
val fixed_point : ('a t -> 'a t) -> 'a t
(** Creates a [t] that forces the lazy argument as necessary. Can be used to tie
(mutually) recursive knots. *)
val of_lazy : 'a t Lazy.t -> 'a t
* { 2 Low - Level functions }
Most users do not need to call these functions .
Most users do not need to call these functions.
*)
val create : ('a -> size:int -> hash:Hash.state -> Hash.state) -> 'a t
val observe : 'a t -> 'a -> size:int -> hash:Hash.state -> Hash.state
| null | https://raw.githubusercontent.com/janestreet/base_quickcheck/b3dc5bda5084253f62362293977e451a6c4257de/src/observer.mli | ocaml | * Produces an observer that treats all values as equivalent. Random functions generated
using this observer will be constant with respect to the value(s) it observes.
* Produces an observer that generates random inputs for a given function, calls the
function on them, then observes the corresponding outputs.
* {2 Observers Based on Hash Functions}
* Creates an observer that just calls a hash function. This is a good default for most
hashable types not covered by the basic observers above.
* {2 Observers for Recursive Types}
* Creates a [t] that forces the lazy argument as necessary. Can be used to tie
(mutually) recursive knots. | * Observers create random functions . { ! } creates a random function
using an observer for the input type and a generator for the output type .
using an observer for the input type and a generator for the output type. *)
open! Base
type -'a t = 'a Observer0.t
* { 2 Basic Observers }
val opaque : _ t
* @inline
val fn : 'a Generator.t -> 'b t -> ('a -> 'b) t
val map_t : 'key t -> 'data t -> ('key, 'data, 'cmp) Map.t t
val set_t : 'elt t -> ('elt, 'cmp) Set.t t
val map_tree : 'key t -> 'data t -> ('key, 'data, 'cmp) Map.Using_comparator.Tree.t t
val set_tree : 'elt t -> ('elt, 'cmp) Set.Using_comparator.Tree.t t
val of_hash_fold : (Hash.state -> 'a -> Hash.state) -> 'a t
* { 2 Modifying Observers }
val unmap : 'a t -> f:('b -> 'a) -> 'b t
* Ties the recursive knot to observe recursive types .
For example , here is an observer for binary trees :
{ [
let tree_observer leaf_observer =
fixed_point ( fun self - >
either leaf_observer ( both self self )
| > unmap ~f:(function
| ` Leaf leaf - > First leaf
| ` Node ( l , r ) - > Second ( l , r ) ) )
] }
For example, here is an observer for binary trees:
{[
let tree_observer leaf_observer =
fixed_point (fun self ->
either leaf_observer (both self self)
|> unmap ~f:(function
| `Leaf leaf -> First leaf
| `Node (l, r) -> Second (l, r)))
]}
*)
val fixed_point : ('a t -> 'a t) -> 'a t
val of_lazy : 'a t Lazy.t -> 'a t
* { 2 Low - Level functions }
Most users do not need to call these functions .
Most users do not need to call these functions.
*)
val create : ('a -> size:int -> hash:Hash.state -> Hash.state) -> 'a t
val observe : 'a t -> 'a -> size:int -> hash:Hash.state -> Hash.state
|
b232ffe46f6694cc74c8510cf64deee421d4ada8d36038c873225fb52cd638f1 | dktr0/Punctual | Test.hs | module Sound.Punctual.Test where
import Data.Time
import Data.Tempo
import Data.Map as Map
import Data.IntMap as IntMap
import Data.Text
import Data.Text.IO as T
import Sound.Punctual.Program
import Sound.Punctual.Parser
import Sound.Punctual.FragmentShader
testFragmentShader :: Text -> IO ()
testFragmentShader x = do
now <- getCurrentTime
case parse now x of
Left err -> Prelude.putStrLn $ "parse error: " ++ err
Right p -> do
Prelude.putStrLn ""
Prelude.putStrLn $ show p
Prelude.putStrLn ""
let testTempo = Tempo 1.0 now 0
T.putStrLn $ fragmentShader testTempo Map.empty (emptyProgram now) p
| null | https://raw.githubusercontent.com/dktr0/Punctual/3ded56b274e59ba99b620cd534e029fad6328218/library-src/Sound/Punctual/Test.hs | haskell | module Sound.Punctual.Test where
import Data.Time
import Data.Tempo
import Data.Map as Map
import Data.IntMap as IntMap
import Data.Text
import Data.Text.IO as T
import Sound.Punctual.Program
import Sound.Punctual.Parser
import Sound.Punctual.FragmentShader
testFragmentShader :: Text -> IO ()
testFragmentShader x = do
now <- getCurrentTime
case parse now x of
Left err -> Prelude.putStrLn $ "parse error: " ++ err
Right p -> do
Prelude.putStrLn ""
Prelude.putStrLn $ show p
Prelude.putStrLn ""
let testTempo = Tempo 1.0 now 0
T.putStrLn $ fragmentShader testTempo Map.empty (emptyProgram now) p
| |
b8203117391f52ac037229003f6baf5f0be80883c22c67c9534da228ee8bc656 | patrickt/bracer | Internal.hs | {-# LANGUAGE RankNTypes #-}
module Language.Bracer.Backends.C.Parser.Internal where
import Prelude ()
import Overture hiding (try)
import Language.Bracer.Syntax.Names
import Control.Monad.State
import Data.Default
import Data.HashMap.Lazy (HashMap)
import Text.Trifecta
import Text.Parser.Token.Style
newtype CParser a = CParser (StateT Environment Parser a)
deriving ( Functor
, Applicative
, Alternative
, Monad
, MonadPlus
, CharParsing
, DeltaParsing
, MonadState Environment
)
deriving instance Parsing CParser
data Environment = Environment
{ _typedefTable :: forall f . HashMap Name (Term f)
}
instance Default Environment where
def = Environment mempty
unCParser :: CParser a -> Parser a
unCParser (CParser p) = evalStateT p def
runCParser :: CParser a -> String -> Result a
runCParser p = parseString (unCParser (whiteSpace *> p <* eof)) mempty
testCParser :: (Show a) => CParser a -> String -> IO ()
testCParser p = parseTest (unCParser (whiteSpace *> p <* eof))
instance TokenParsing CParser where
someSpace = buildSomeSpaceParser (CParser someSpace) javaCommentStyle
| null | https://raw.githubusercontent.com/patrickt/bracer/ebad062d421f7678ddafc442245e361c0423cb1b/Language/Bracer/Backends/C/Parser/Internal.hs | haskell | # LANGUAGE RankNTypes # |
module Language.Bracer.Backends.C.Parser.Internal where
import Prelude ()
import Overture hiding (try)
import Language.Bracer.Syntax.Names
import Control.Monad.State
import Data.Default
import Data.HashMap.Lazy (HashMap)
import Text.Trifecta
import Text.Parser.Token.Style
newtype CParser a = CParser (StateT Environment Parser a)
deriving ( Functor
, Applicative
, Alternative
, Monad
, MonadPlus
, CharParsing
, DeltaParsing
, MonadState Environment
)
deriving instance Parsing CParser
data Environment = Environment
{ _typedefTable :: forall f . HashMap Name (Term f)
}
instance Default Environment where
def = Environment mempty
unCParser :: CParser a -> Parser a
unCParser (CParser p) = evalStateT p def
runCParser :: CParser a -> String -> Result a
runCParser p = parseString (unCParser (whiteSpace *> p <* eof)) mempty
testCParser :: (Show a) => CParser a -> String -> IO ()
testCParser p = parseTest (unCParser (whiteSpace *> p <* eof))
instance TokenParsing CParser where
someSpace = buildSomeSpaceParser (CParser someSpace) javaCommentStyle
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.