_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
2cd87f134dfb14b109b08e4d3cb7236d3b10377f88f575e08d8cae7ab7f40b6e
suhdonghwi/nuri
Decl.hs
module Nuri.Parse.Decl where import qualified Data.Text as T import Nuri.Expr ( Decl (..), DeclType (..), Expr, FuncKind (..), FuncVariation (Antonym, Synonym), ) import Nuri.Parse ( MonadParser, lexeme, reserved, sc, scn, symbol, ) import Nuri.Parse.PartTable (MonadPartTable, addDecl) import Nuri.Parse.Term (parseIdentifier) import Nuri.Parse.Util (parseFuncIdentifier, parseJosa, parseStructIdentifier) import qualified Text.Megaparsec as P parseDecl :: (MonadParser m) => m Expr -> m Decl parseDecl e = parseConstDecl e <|> parseFuncDecl e <|> parseStructDecl parseDeclKind :: (MonadParser m) => m FuncKind parseDeclKind = (pure Normal <* reserved "함수") <|> (pure Verb <* reserved "동사") <|> (pure Adjective <* reserved "형용사") checkValidIdentifier :: (MonadParser m) => Int -> FuncKind -> Text -> m () checkValidIdentifier offset kind name = do if kind `elem` [Verb, Adjective] then unless (T.last name == '다') $ do P.setOffset offset fail "용언을 선언할 때는 식별자가 ~(하)다 꼴이어야 합니다." else pass parseFuncDecl :: (MonadParser m) => m Expr -> m Decl parseFuncDecl parseExpr = do pos <- P.getSourcePos declKind <- parseDeclKind args <- parseArgList [] offset <- P.getOffset funcName <- parseFuncIdentifier synAnts <- if declKind == Adjective then parseSynAnt <|> pure [] else pure [] let addVariation (Synonym t) = addDecl t Adjective addVariation (Antonym t) = addDecl t Adjective checkValidIdentifier offset declKind funcName addDecl funcName declKind sequence_ $ addVariation <$> synAnts colon <- P.observing (symbol ":") let funcDecl body = Decl pos funcName $ case declKind of Normal -> FuncDecl args body Verb -> VerbDecl args body Adjective -> AdjectiveDecl args synAnts body case colon of Left _ -> return $ funcDecl Nothing Right _ -> do scn body <- Just <$> parseExpr return $ funcDecl body where parseSynonym :: (MonadParser m) => m FuncVariation parseSynonym = symbol "=" >> Synonym <$> parseAdjectiveIdentifier parseAntonym :: (MonadParser m) => m FuncVariation parseAntonym = symbol "<->" >> Antonym <$> parseAdjectiveIdentifier parseAdjectiveIdentifier :: (MonadParser m) => m Text parseAdjectiveIdentifier = do offset <- P.getOffset funcName <- parseFuncIdentifier checkValidIdentifier offset Adjective funcName return funcName parseSynAnt :: (MonadParser m) => m [FuncVariation] parseSynAnt = P.between (symbol "(") (symbol ")") ((parseSynonym <|> parseAntonym) `P.sepBy1` symbol ",") parseArgList :: (MonadParser m) => [(Text, Text)] -> m [(Text, Text)] parseArgList l = do identPos <- P.getOffset identResult <- P.observing parseIdentifier case identResult of Left _ -> return l Right ident -> do josaPos <- P.getOffset josa <- parseJosa sc when (ident `elem` (fst <$> l)) ( do P.setOffset (identPos + 1) fail "함수 인자의 이름이 중복됩니다." ) when (josa `elem` (snd <$> l)) ( do P.setOffset josaPos fail "조사는 중복되게 사용할 수 없습니다." ) parseArgList (l ++ [(ident, josa)]) parseConstDecl :: (MonadParser m) => m Expr -> m Decl parseConstDecl parseExpr = do pos <- P.getSourcePos reserved "상수" identifier <- lexeme parseIdentifier <* symbol ":" Decl pos identifier . ConstDecl <$> parseExpr parseStructDecl :: (MonadParser m, MonadPartTable m) => m Decl parseStructDecl = do pos <- P.getSourcePos reserved "구조체" identifier <- lexeme parseStructIdentifier <* symbol ":" fields <- parseFuncIdentifier `P.sepBy1` symbol "," sequence_ $ (`addDecl` Normal) <$> fields return $ Decl pos identifier (StructDecl fields)
null
https://raw.githubusercontent.com/suhdonghwi/nuri/337550e3d50c290144df905ea3f189e9af6123c2/src/Nuri/Parse/Decl.hs
haskell
module Nuri.Parse.Decl where import qualified Data.Text as T import Nuri.Expr ( Decl (..), DeclType (..), Expr, FuncKind (..), FuncVariation (Antonym, Synonym), ) import Nuri.Parse ( MonadParser, lexeme, reserved, sc, scn, symbol, ) import Nuri.Parse.PartTable (MonadPartTable, addDecl) import Nuri.Parse.Term (parseIdentifier) import Nuri.Parse.Util (parseFuncIdentifier, parseJosa, parseStructIdentifier) import qualified Text.Megaparsec as P parseDecl :: (MonadParser m) => m Expr -> m Decl parseDecl e = parseConstDecl e <|> parseFuncDecl e <|> parseStructDecl parseDeclKind :: (MonadParser m) => m FuncKind parseDeclKind = (pure Normal <* reserved "함수") <|> (pure Verb <* reserved "동사") <|> (pure Adjective <* reserved "형용사") checkValidIdentifier :: (MonadParser m) => Int -> FuncKind -> Text -> m () checkValidIdentifier offset kind name = do if kind `elem` [Verb, Adjective] then unless (T.last name == '다') $ do P.setOffset offset fail "용언을 선언할 때는 식별자가 ~(하)다 꼴이어야 합니다." else pass parseFuncDecl :: (MonadParser m) => m Expr -> m Decl parseFuncDecl parseExpr = do pos <- P.getSourcePos declKind <- parseDeclKind args <- parseArgList [] offset <- P.getOffset funcName <- parseFuncIdentifier synAnts <- if declKind == Adjective then parseSynAnt <|> pure [] else pure [] let addVariation (Synonym t) = addDecl t Adjective addVariation (Antonym t) = addDecl t Adjective checkValidIdentifier offset declKind funcName addDecl funcName declKind sequence_ $ addVariation <$> synAnts colon <- P.observing (symbol ":") let funcDecl body = Decl pos funcName $ case declKind of Normal -> FuncDecl args body Verb -> VerbDecl args body Adjective -> AdjectiveDecl args synAnts body case colon of Left _ -> return $ funcDecl Nothing Right _ -> do scn body <- Just <$> parseExpr return $ funcDecl body where parseSynonym :: (MonadParser m) => m FuncVariation parseSynonym = symbol "=" >> Synonym <$> parseAdjectiveIdentifier parseAntonym :: (MonadParser m) => m FuncVariation parseAntonym = symbol "<->" >> Antonym <$> parseAdjectiveIdentifier parseAdjectiveIdentifier :: (MonadParser m) => m Text parseAdjectiveIdentifier = do offset <- P.getOffset funcName <- parseFuncIdentifier checkValidIdentifier offset Adjective funcName return funcName parseSynAnt :: (MonadParser m) => m [FuncVariation] parseSynAnt = P.between (symbol "(") (symbol ")") ((parseSynonym <|> parseAntonym) `P.sepBy1` symbol ",") parseArgList :: (MonadParser m) => [(Text, Text)] -> m [(Text, Text)] parseArgList l = do identPos <- P.getOffset identResult <- P.observing parseIdentifier case identResult of Left _ -> return l Right ident -> do josaPos <- P.getOffset josa <- parseJosa sc when (ident `elem` (fst <$> l)) ( do P.setOffset (identPos + 1) fail "함수 인자의 이름이 중복됩니다." ) when (josa `elem` (snd <$> l)) ( do P.setOffset josaPos fail "조사는 중복되게 사용할 수 없습니다." ) parseArgList (l ++ [(ident, josa)]) parseConstDecl :: (MonadParser m) => m Expr -> m Decl parseConstDecl parseExpr = do pos <- P.getSourcePos reserved "상수" identifier <- lexeme parseIdentifier <* symbol ":" Decl pos identifier . ConstDecl <$> parseExpr parseStructDecl :: (MonadParser m, MonadPartTable m) => m Decl parseStructDecl = do pos <- P.getSourcePos reserved "구조체" identifier <- lexeme parseStructIdentifier <* symbol ":" fields <- parseFuncIdentifier `P.sepBy1` symbol "," sequence_ $ (`addDecl` Normal) <$> fields return $ Decl pos identifier (StructDecl fields)
e12fdca1a92f8b06f40494707158b1f69375786dbaa11d56107e8e1642ebca57
robert-strandh/CLIMatis
polygon-rendering.lisp
(cl:in-package #:clim3-rendering) (defun render-polygons (polygons) (render-trapezoids (trapezoids-from-polygons polygons))) (defun print-mask (mask) (loop for c from 0 below (array-dimension mask 0) do (loop for r from 0 below (array-dimension mask 1) do (format t "~5,3f " (aref mask c r))) (format t "~%"))) (defparameter *b-outer* '((1 . 1) (4 . 1) (5.5 . 2) (6 . 3.5) (5.5 . 5) (4.5 . 5.5) (5.5 . 6) (6 . 7.5) (5.5 . 9) (4 . 10) (1 . 10))) (defparameter *b-inner-upper* '((2 . 2) (3.5 . 2) (4.5 . 2.5) (5 . 3.5) (4.5 . 4.5) (3.5 . 5) (2 . 5))) (defparameter *b-inner-lower* '((2 . 6) (3.5 . 6) (4.5 . 6.5) (5 . 7.5) (4.5 . 8.5) (3.5 . 9) (2 . 9)))
null
https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Drawing/polygon-rendering.lisp
lisp
(cl:in-package #:clim3-rendering) (defun render-polygons (polygons) (render-trapezoids (trapezoids-from-polygons polygons))) (defun print-mask (mask) (loop for c from 0 below (array-dimension mask 0) do (loop for r from 0 below (array-dimension mask 1) do (format t "~5,3f " (aref mask c r))) (format t "~%"))) (defparameter *b-outer* '((1 . 1) (4 . 1) (5.5 . 2) (6 . 3.5) (5.5 . 5) (4.5 . 5.5) (5.5 . 6) (6 . 7.5) (5.5 . 9) (4 . 10) (1 . 10))) (defparameter *b-inner-upper* '((2 . 2) (3.5 . 2) (4.5 . 2.5) (5 . 3.5) (4.5 . 4.5) (3.5 . 5) (2 . 5))) (defparameter *b-inner-lower* '((2 . 6) (3.5 . 6) (4.5 . 6.5) (5 . 7.5) (4.5 . 8.5) (3.5 . 9) (2 . 9)))
02c43b126bc1fb0aaaacfa2175791dbeed81d41531e7b5c34cb3d8cbad00aeb2
symbiont-io/detsys-testkit
Worker.hs
{-# LANGUAGE OverloadedStrings #-} module Dumblog.ZeroCopy.Worker where import Control.Concurrent (threadDelay) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Int (Int32, Int64) import Foreign (sizeOf) import Foreign.C.Types (CInt(CInt)) import Network.Socket (mkSocket) import Network.Socket.ByteString (sendAll) import Journal.Internal.ByteBufferPtr import Journal.MP import Journal.Types (Journal, Subscriber(Sub1)) import Dumblog.ZeroCopy.State ------------------------------------------------------------------------ worker :: Journal -> State -> IO () worker jour = go where go :: State -> IO () go state = do mFdAndReq <- readJournal jour Sub1 case mFdAndReq of Nothing -> threadDelay 10 >> go state Just fdAndReq -> do -- XXX: We should probably add a variant of readJournal that returns a -- bytebuffer instead of converting the bytestring to a bytebuffer... let bb = unsafeFromBS fdAndReq fd <- readInt32OffAddr bb 0 offset <- readInt64OffAddr bb (sizeOf (4 :: Int32)) let req = BS.drop (sizeOf (4 :: Int32) + sizeOf (8 :: Int64)) fdAndReq case parseCommand req of Just (Write offset' len) -> do (ix, state') <- writeLocation state offset (Location (fromIntegral offset') (fromIntegral len)) conn <- mkSocket (CInt fd) sendAll conn (response (BS.pack (show ix))) go state' Just (Read ix) -> do conn <- mkSocket (CInt fd) readSendfile state conn ix go state Nothing -> go state response :: ByteString -> ByteString response body = BS.pack "HTTP/1.0 200 OK\r\nContent-Length: " <> BS.pack (show (BS.length body)) <> "\r\n\r\n" <> body data Command = Write Int Int | Read Int deriving Show parseCommand :: ByteString -> Maybe Command parseCommand bs = let (method, rest) = BS.break (== ' ') bs in case method of "GET" -> Read <$> parseIndex rest "POST" -> uncurry Write <$> parseOffsetLength rest _otherwise -> Nothing parseIndex :: ByteString -> Maybe Int parseIndex = fmap fst . BS.readInt . BS.dropWhile (\c -> c == ' ' || c == '/') parseOffsetLength :: ByteString -> Maybe (Int, Int) parseOffsetLength bs = do let (_before, match) = BS.breakSubstring "Content-Length: " bs rest = BS.drop (BS.length "Content-Length: ") match (len, _rest) <- BS.readInt rest let (headers, _match) = BS.breakSubstring "\r\n\r\n" bs return (BS.length headers + BS.length "POST" + BS.length "\r\n\r\n", len)
null
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/0c46216b1aadef5a65537b6ed7c7c21efb66ab72/src/sut/dumblog/src/zero-copy/Dumblog/ZeroCopy/Worker.hs
haskell
# LANGUAGE OverloadedStrings # ---------------------------------------------------------------------- XXX: We should probably add a variant of readJournal that returns a bytebuffer instead of converting the bytestring to a bytebuffer...
module Dumblog.ZeroCopy.Worker where import Control.Concurrent (threadDelay) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Int (Int32, Int64) import Foreign (sizeOf) import Foreign.C.Types (CInt(CInt)) import Network.Socket (mkSocket) import Network.Socket.ByteString (sendAll) import Journal.Internal.ByteBufferPtr import Journal.MP import Journal.Types (Journal, Subscriber(Sub1)) import Dumblog.ZeroCopy.State worker :: Journal -> State -> IO () worker jour = go where go :: State -> IO () go state = do mFdAndReq <- readJournal jour Sub1 case mFdAndReq of Nothing -> threadDelay 10 >> go state Just fdAndReq -> do let bb = unsafeFromBS fdAndReq fd <- readInt32OffAddr bb 0 offset <- readInt64OffAddr bb (sizeOf (4 :: Int32)) let req = BS.drop (sizeOf (4 :: Int32) + sizeOf (8 :: Int64)) fdAndReq case parseCommand req of Just (Write offset' len) -> do (ix, state') <- writeLocation state offset (Location (fromIntegral offset') (fromIntegral len)) conn <- mkSocket (CInt fd) sendAll conn (response (BS.pack (show ix))) go state' Just (Read ix) -> do conn <- mkSocket (CInt fd) readSendfile state conn ix go state Nothing -> go state response :: ByteString -> ByteString response body = BS.pack "HTTP/1.0 200 OK\r\nContent-Length: " <> BS.pack (show (BS.length body)) <> "\r\n\r\n" <> body data Command = Write Int Int | Read Int deriving Show parseCommand :: ByteString -> Maybe Command parseCommand bs = let (method, rest) = BS.break (== ' ') bs in case method of "GET" -> Read <$> parseIndex rest "POST" -> uncurry Write <$> parseOffsetLength rest _otherwise -> Nothing parseIndex :: ByteString -> Maybe Int parseIndex = fmap fst . BS.readInt . BS.dropWhile (\c -> c == ' ' || c == '/') parseOffsetLength :: ByteString -> Maybe (Int, Int) parseOffsetLength bs = do let (_before, match) = BS.breakSubstring "Content-Length: " bs rest = BS.drop (BS.length "Content-Length: ") match (len, _rest) <- BS.readInt rest let (headers, _match) = BS.breakSubstring "\r\n\r\n" bs return (BS.length headers + BS.length "POST" + BS.length "\r\n\r\n", len)
46eae8a7b32885e8160b0c14dbc6ec13f6b6de2ca1186ee545223a885b5bad39
alexander-yakushev/defprecated
core.clj
(ns defprecated.core (:refer-clojure :exclude [defn defmacro]) (:require [clojure.core :as core])) (core/defn- make-warning-msg [sym ns depr-map] (format "WARNING: %s is deprecated%s." (str "#'" ns "/" sym) (if-let [instead (:use-instead depr-map)] (format ", use %s instead" (if-let [instead-var (ns-resolve ns instead)] instead-var instead)) ""))) (core/defn println-stderr [s] (binding [*out* *err*] (println s))) (core/defmacro def "Sames as `def` but defines a deprecated var." {:forms '([symbol docstring? init?])} [symbol & args] (let [[m init?] (if (string? (first args)) [{:doc (first args)} (next args)] [{} args]) m (conj (if (meta symbol) (meta symbol) {}) m) depr-map (:deprecated m) depr-map (if (map? depr-map) depr-map {:in depr-map}) m (update-in m [:doc] #(str (make-warning-msg symbol *ns* depr-map) "\n " %)) m (assoc m :deprecated (:in depr-map "current version"))] (list* 'def (with-meta symbol m) init?))) (core/defn- make-invokable "Produces code for defining deprecated functions or macros." [original name fdecl] (let [[m fdecl] (if (string? (first fdecl)) [{:doc (first fdecl)} (next fdecl)] [{} fdecl]) [m fdecl] (if (map? (first fdecl)) [(conj m (first fdecl)) (next fdecl)] [m fdecl]) fdecl (if (vector? (first fdecl)) (list fdecl) fdecl) [m fdecl] (if (map? (last fdecl)) [(conj m (last fdecl)) (butlast fdecl)] [m fdecl]) m (conj (if (meta name) (meta name) {}) m) [good-arities depr-arities] ((juxt remove filter) #(:deprecated (meta %)) (map first fdecl)) has-depr-arities (not (empty? depr-arities)) depr-map (:deprecated m) depr-map (conj {:print-warning :once} (if (map? depr-map) depr-map {:in depr-map})) warn-msg (make-warning-msg name *ns* depr-map) arity-warn-fmt (str "WARNING: #'" *ns* "/" name " arit%s %s %s deprecated, use one of " (seq good-arities) " instead.") print-fn (:print-function depr-map `println-stderr) warning-sym (gensym "warning") m (if has-depr-arities (-> m (assoc :deprecated nil) (assoc :forms (list `quote good-arities))) (-> m (assoc :deprecated (:in depr-map "current version")) (update-in [:doc] #(str warn-msg "\n " %))))] (case (:print-warning depr-map) :always (list* original name m (for [[params & body] fdecl] `(~params ~@(if has-depr-arities (when (:deprecated (meta params)) `((~print-fn ~(format arity-warn-fmt "y" params "is")))) `((~print-fn ~warn-msg))) ~@body))) :once `(let [~warning-sym (delay (~print-fn ~(if has-depr-arities (format arity-warn-fmt "ies" (seq depr-arities) "are") warn-msg)))] ~(list* original name m (for [[params & body] fdecl] `(~params ~@(when (or (not has-depr-arities) (:deprecated (meta params))) `((force ~warning-sym))) ~@body)))) :never (list* original name m fdecl)))) (core/defmacro defn "Sames as `clojure.core/defn` but defines a deprecated funcion. " [name & fdecl] (make-invokable 'clojure.core/defn name fdecl)) (core/defmacro defmacro "Sames as `clojure.core/defmacro` but defines a deprecated macro. " [name & fdecl] (make-invokable 'clojure.core/defmacro name fdecl))
null
https://raw.githubusercontent.com/alexander-yakushev/defprecated/90627f896ba745fa0bd3079fcedce26091fc68b8/src/defprecated/core.clj
clojure
(ns defprecated.core (:refer-clojure :exclude [defn defmacro]) (:require [clojure.core :as core])) (core/defn- make-warning-msg [sym ns depr-map] (format "WARNING: %s is deprecated%s." (str "#'" ns "/" sym) (if-let [instead (:use-instead depr-map)] (format ", use %s instead" (if-let [instead-var (ns-resolve ns instead)] instead-var instead)) ""))) (core/defn println-stderr [s] (binding [*out* *err*] (println s))) (core/defmacro def "Sames as `def` but defines a deprecated var." {:forms '([symbol docstring? init?])} [symbol & args] (let [[m init?] (if (string? (first args)) [{:doc (first args)} (next args)] [{} args]) m (conj (if (meta symbol) (meta symbol) {}) m) depr-map (:deprecated m) depr-map (if (map? depr-map) depr-map {:in depr-map}) m (update-in m [:doc] #(str (make-warning-msg symbol *ns* depr-map) "\n " %)) m (assoc m :deprecated (:in depr-map "current version"))] (list* 'def (with-meta symbol m) init?))) (core/defn- make-invokable "Produces code for defining deprecated functions or macros." [original name fdecl] (let [[m fdecl] (if (string? (first fdecl)) [{:doc (first fdecl)} (next fdecl)] [{} fdecl]) [m fdecl] (if (map? (first fdecl)) [(conj m (first fdecl)) (next fdecl)] [m fdecl]) fdecl (if (vector? (first fdecl)) (list fdecl) fdecl) [m fdecl] (if (map? (last fdecl)) [(conj m (last fdecl)) (butlast fdecl)] [m fdecl]) m (conj (if (meta name) (meta name) {}) m) [good-arities depr-arities] ((juxt remove filter) #(:deprecated (meta %)) (map first fdecl)) has-depr-arities (not (empty? depr-arities)) depr-map (:deprecated m) depr-map (conj {:print-warning :once} (if (map? depr-map) depr-map {:in depr-map})) warn-msg (make-warning-msg name *ns* depr-map) arity-warn-fmt (str "WARNING: #'" *ns* "/" name " arit%s %s %s deprecated, use one of " (seq good-arities) " instead.") print-fn (:print-function depr-map `println-stderr) warning-sym (gensym "warning") m (if has-depr-arities (-> m (assoc :deprecated nil) (assoc :forms (list `quote good-arities))) (-> m (assoc :deprecated (:in depr-map "current version")) (update-in [:doc] #(str warn-msg "\n " %))))] (case (:print-warning depr-map) :always (list* original name m (for [[params & body] fdecl] `(~params ~@(if has-depr-arities (when (:deprecated (meta params)) `((~print-fn ~(format arity-warn-fmt "y" params "is")))) `((~print-fn ~warn-msg))) ~@body))) :once `(let [~warning-sym (delay (~print-fn ~(if has-depr-arities (format arity-warn-fmt "ies" (seq depr-arities) "are") warn-msg)))] ~(list* original name m (for [[params & body] fdecl] `(~params ~@(when (or (not has-depr-arities) (:deprecated (meta params))) `((force ~warning-sym))) ~@body)))) :never (list* original name m fdecl)))) (core/defmacro defn "Sames as `clojure.core/defn` but defines a deprecated funcion. " [name & fdecl] (make-invokable 'clojure.core/defn name fdecl)) (core/defmacro defmacro "Sames as `clojure.core/defmacro` but defines a deprecated macro. " [name & fdecl] (make-invokable 'clojure.core/defmacro name fdecl))
6c958d0e47cad85756af6c0623e5de180d61302be44cf97ef5f86fc95ff42430
theodormoroianu/SecondYearCourses
LambdaChurch_20210415165505.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda ------------ --BOOLEANS-- ------------ A boolean is any way to choose between two alternatives ( t - > t - > t ) The boolean constant true always chooses the first alternative cTrue :: Term cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: Term cFalse = undefined --If is not really needed because we can use the booleans themselves, but... cIf :: Term cIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") --The boolean negation switches the alternatives cNot :: Term cNot = lam "b" (v "b" $$ cFalse $$ cTrue) --The boolean conjunction can be built as a conditional cAnd :: Term cAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ cFalse) --The boolean disjunction can be built as a conditional cOr :: Term cOr = lams ["b1", "b2"] (v "b1" $$ cTrue $$ v "b2") ---------- -- PAIRS-- ---------- -- a pair with components of type a and b is a way to compute something based -- on the values contained within the pair (a -> b -> c) -> c builds a pair out of two values as an object which , when given --a function to be applied on the values, it will apply it on them. cPair :: Term cPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") first projection uses the function selecting first component on a pair cFst :: Term cFst = lam "pair" (v "pair" $$ cTrue) second projection cSnd :: Term cSnd = lam "pair" (v "pair" $$ cFalse) c0 :: Term c0 = lams ["s", "z"] (v "z") -- note that it's the same as cFalse c1 :: Term c1 = lams ["s", "z"] (v "s" $$ v "z") c2 :: Term c2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) cS :: Term cS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) cNat :: Integer -> Term cNat = undefined cPlus :: Term cPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) cPlus' :: Term cPlus' = lams ["n", "m"] (v "n" $$ cS $$ v "m") cMul :: Term cMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) cMul' :: Term cMul' = lams ["n", "m"] (v "n" $$ (cPlus' $$ v "m") $$ c0) cPow :: Term cPow = lams ["m", "n"] (v "n" $$ v "m") cPow' :: Term cPow' = lams ["m", "n"] (v "n" $$ (cMul' $$ v "m") $$ c1) cIs0 :: Term cIs0 = lam "n" (v "n" $$ (cAnd $$ cFalse) $$ cTrue) cS' :: Term cS' = lam "n" (v "n" $$ cS $$ c1) cS'Rev0 :: Term cS'Rev0 = lams ["s","z"] c0 cPred :: Term cPred = lam "n" (cIf $$ (cIs0 $$ v "n") $$ c0 $$ (v "n" $$ cS' $$ cS'Rev0)) cSub :: Term cSub = lams ["m", "n"] (v "n" $$ cPred $$ v "m") cLte :: Term cLte = lams ["m", "n"] (cIs0 $$ (cSub $$ v "m" $$ v "n")) cGte :: Term cGte = lams ["m", "n"] (cLte $$ v "n" $$ v "m") cLt :: Term cLt = lams ["m", "n"] (cNot $$ (cGte $$ v "m" $$ v "n")) cGt :: Term cGt = lams ["m", "n"] (cLt $$ v "n" $$ v "m") cEq :: Term cEq = lams ["m", "n"] (cAnd $$ (cLte $$ v "m" $$ v "n") $$ (cLte $$ v "n" $$ v "m")) cPred' :: Term cPred' = lam "n" (cFst $$ (v "n" $$ lam "p" (lam "x" (cPair $$ v "x" $$ (cS $$ v "x")) $$ (cSnd $$ v "p")) $$ (cPair $$ c0 $$ c0) )) cFactorial :: Term cFactorial = lam "n" (cSnd $$ (v "n" $$ lam "p" (cPair $$ (cS $$ (cFst $$ v "p")) $$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p")) ) $$ (cPair $$ c1 $$ c1) )) cFibonacci :: Term cFibonacci = lam "n" (cFst $$ (v "n" $$ lam "p" (cPair $$ (cSnd $$ v "p") $$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p")) ) $$ (cPair $$ c0 $$ c1) )) cDivMod :: Term cDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (cIf $$ (cLte $$ v "n" $$ (cSnd $$ v "pair")) $$ (cPair $$ (cS $$ (cFst $$ v "pair")) $$ (cSub $$ (cSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (cPair $$ c0 $$ v "m") ) cNil :: Term cNil = lams ["agg", "init"] (v "init") cCons :: Term cCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) cList :: [Term] -> Term cList = foldr (\x l -> cCons $$ x $$ l) cNil cNatList :: [Integer] -> Term cNatList = cList . map cNat cSum :: Term cSum = lam "l" (v "l" $$ cPlus $$ c0) cIsNil :: Term cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue) cHead :: Term cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cTail :: Term cTail = lam "l" (cFst $$ (v "l" $$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t")) $$ (cSnd $$ v "p")) $$ (cPair $$ cNil $$ cNil) )) fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) cDivMod' :: Term cDivMod' = lams ["m", "n"] (cIs0 $$ v "n" $$ (cPair $$ c0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (cIs0 $$ v "x" $$ (cLte $$ v "n" $$ (cSnd $$ v "p") $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0) $$ v "p" ) $$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x")) ) $$ (cSub $$ (cSnd $$ v "p") $$ v "n") ) $$ (cPair $$ c0 $$ v "m") ) ) cSudan :: Term cSudan = fix $$ lam "f" (lams ["n", "x", "y"] (cIs0 $$ v "n" $$ (cPlus $$ v "x" $$ v "y") $$ (cIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (cPred $$ v "n") $$ v "fnpy" $$ (cPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y")) ) ) )) cAckermann :: Term cAckermann = fix $$ lam "A" (lams ["m", "n"] (cIs0 $$ v "m" $$ (cS $$ v "n") $$ (cIs0 $$ v "n" $$ (v "A" $$ (cPred $$ v "m") $$ c1) $$ (v "A" $$ (cPred $$ v "m") $$ (v "A" $$ v "m" $$ (cPred $$ v "n"))) ) ))
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415165505.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda ---------- BOOLEANS-- ---------- If is not really needed because we can use the booleans themselves, but... The boolean negation switches the alternatives The boolean conjunction can be built as a conditional The boolean disjunction can be built as a conditional -------- PAIRS-- -------- a pair with components of type a and b is a way to compute something based on the values contained within the pair (a -> b -> c) -> c a function to be applied on the values, it will apply it on them. note that it's the same as cFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s A boolean is any way to choose between two alternatives ( t - > t - > t ) The boolean constant true always chooses the first alternative cTrue :: Term cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: Term cFalse = undefined cIf :: Term cIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") cNot :: Term cNot = lam "b" (v "b" $$ cFalse $$ cTrue) cAnd :: Term cAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ cFalse) cOr :: Term cOr = lams ["b1", "b2"] (v "b1" $$ cTrue $$ v "b2") builds a pair out of two values as an object which , when given cPair :: Term cPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") first projection uses the function selecting first component on a pair cFst :: Term cFst = lam "pair" (v "pair" $$ cTrue) second projection cSnd :: Term cSnd = lam "pair" (v "pair" $$ cFalse) c0 :: Term c1 :: Term c1 = lams ["s", "z"] (v "s" $$ v "z") c2 :: Term c2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) cS :: Term cS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) cNat :: Integer -> Term cNat = undefined cPlus :: Term cPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) cPlus' :: Term cPlus' = lams ["n", "m"] (v "n" $$ cS $$ v "m") cMul :: Term cMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) cMul' :: Term cMul' = lams ["n", "m"] (v "n" $$ (cPlus' $$ v "m") $$ c0) cPow :: Term cPow = lams ["m", "n"] (v "n" $$ v "m") cPow' :: Term cPow' = lams ["m", "n"] (v "n" $$ (cMul' $$ v "m") $$ c1) cIs0 :: Term cIs0 = lam "n" (v "n" $$ (cAnd $$ cFalse) $$ cTrue) cS' :: Term cS' = lam "n" (v "n" $$ cS $$ c1) cS'Rev0 :: Term cS'Rev0 = lams ["s","z"] c0 cPred :: Term cPred = lam "n" (cIf $$ (cIs0 $$ v "n") $$ c0 $$ (v "n" $$ cS' $$ cS'Rev0)) cSub :: Term cSub = lams ["m", "n"] (v "n" $$ cPred $$ v "m") cLte :: Term cLte = lams ["m", "n"] (cIs0 $$ (cSub $$ v "m" $$ v "n")) cGte :: Term cGte = lams ["m", "n"] (cLte $$ v "n" $$ v "m") cLt :: Term cLt = lams ["m", "n"] (cNot $$ (cGte $$ v "m" $$ v "n")) cGt :: Term cGt = lams ["m", "n"] (cLt $$ v "n" $$ v "m") cEq :: Term cEq = lams ["m", "n"] (cAnd $$ (cLte $$ v "m" $$ v "n") $$ (cLte $$ v "n" $$ v "m")) cPred' :: Term cPred' = lam "n" (cFst $$ (v "n" $$ lam "p" (lam "x" (cPair $$ v "x" $$ (cS $$ v "x")) $$ (cSnd $$ v "p")) $$ (cPair $$ c0 $$ c0) )) cFactorial :: Term cFactorial = lam "n" (cSnd $$ (v "n" $$ lam "p" (cPair $$ (cS $$ (cFst $$ v "p")) $$ (cMul $$ (cFst $$ v "p") $$ (cSnd $$ v "p")) ) $$ (cPair $$ c1 $$ c1) )) cFibonacci :: Term cFibonacci = lam "n" (cFst $$ (v "n" $$ lam "p" (cPair $$ (cSnd $$ v "p") $$ (cPlus $$ (cFst $$ v "p") $$ (cSnd $$ v "p")) ) $$ (cPair $$ c0 $$ c1) )) cDivMod :: Term cDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (cIf $$ (cLte $$ v "n" $$ (cSnd $$ v "pair")) $$ (cPair $$ (cS $$ (cFst $$ v "pair")) $$ (cSub $$ (cSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (cPair $$ c0 $$ v "m") ) cNil :: Term cNil = lams ["agg", "init"] (v "init") cCons :: Term cCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) cList :: [Term] -> Term cList = foldr (\x l -> cCons $$ x $$ l) cNil cNatList :: [Integer] -> Term cNatList = cList . map cNat cSum :: Term cSum = lam "l" (v "l" $$ cPlus $$ c0) cIsNil :: Term cIsNil = lam "l" (v "l" $$ lams ["x", "a"] cFalse $$ cTrue) cHead :: Term cHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cTail :: Term cTail = lam "l" (cFst $$ (v "l" $$ lams ["x","p"] (lam "t" (cPair $$ v "t" $$ (cCons $$ v "x" $$ v "t")) $$ (cSnd $$ v "p")) $$ (cPair $$ cNil $$ cNil) )) fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) cDivMod' :: Term cDivMod' = lams ["m", "n"] (cIs0 $$ v "n" $$ (cPair $$ c0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (cIs0 $$ v "x" $$ (cLte $$ v "n" $$ (cSnd $$ v "p") $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0) $$ v "p" ) $$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x")) ) $$ (cSub $$ (cSnd $$ v "p") $$ v "n") ) $$ (cPair $$ c0 $$ v "m") ) ) cSudan :: Term cSudan = fix $$ lam "f" (lams ["n", "x", "y"] (cIs0 $$ v "n" $$ (cPlus $$ v "x" $$ v "y") $$ (cIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (cPred $$ v "n") $$ v "fnpy" $$ (cPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y")) ) ) )) cAckermann :: Term cAckermann = fix $$ lam "A" (lams ["m", "n"] (cIs0 $$ v "m" $$ (cS $$ v "n") $$ (cIs0 $$ v "n" $$ (v "A" $$ (cPred $$ v "m") $$ c1) $$ (v "A" $$ (cPred $$ v "m") $$ (v "A" $$ v "m" $$ (cPred $$ v "n"))) ) ))
5f7862e7ab7e71d4ebb8d37febe8aed0b23752284ee5f09a7fd9f70201ab90d2
yallop/ocaml-ctypes
test_roots.ml
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes open Foreign let testlib = Dl.(dlopen ~filename:"clib/libtest_functions.so" ~flags:[RTLD_NOW]) (* Test root lifetime. *) let test_root_lifetime _ = (* Check that values not registered as roots are collected. *) let alive = ref true in let () = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; in Gc.full_major (); assert_equal false !alive ~msg:"values not registered as roots are collected"; (* Check that values registered as roots are not collected. *) let alive = ref true in let _r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Gc.full_major (); assert_equal true !alive ~msg:"registered roots are not collected"; (* Check that values unregistered as roots are collected. *) let alive = ref true in let r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Root.release r; Gc.full_major (); assert_equal false !alive ~msg:"released roots are collected"; (* Check that values assigned to roots are not collected. *) let alive = ref true in let () = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; let r = Root.create () in Root.set r v; in Gc.full_major (); assert_equal true !alive ~msg:"values assigned to roots are not collected"; (* Check that values registered as roots and then overwritten are collected. *) let alive = ref true in let r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Root.set r (); Gc.full_major (); assert_equal false !alive ~msg:"overwritten roots are collected"; () (* Test passing roots to C functions. *) let test_passing_roots _ = let save = foreign ~from:testlib "save_ocaml_value" (ptr void @-> returning void) and retrieve = foreign ~from:testlib "retrieve_ocaml_value" (void @-> returning (ptr void)) in let r = Root.create [| ( + ) 1; ( * ) 2 |] in begin save r; Gc.full_major (); let fs : (int -> int) array = Root.get (retrieve ()) in assert_equal 11 (fs.(0) 10); assert_equal 20 (fs.(1) 10) end let suite = "Root tests" >::: ["root lifetime" >:: test_root_lifetime; "passing roots" >:: test_passing_roots; ] let _ = run_test_tt_main suite
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/cc3ccdd574b0deeec1dc20850a6515881db0f1ae/tests/test-roots/test_roots.ml
ocaml
Test root lifetime. Check that values not registered as roots are collected. Check that values registered as roots are not collected. Check that values unregistered as roots are collected. Check that values assigned to roots are not collected. Check that values registered as roots and then overwritten are collected. Test passing roots to C functions.
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes open Foreign let testlib = Dl.(dlopen ~filename:"clib/libtest_functions.so" ~flags:[RTLD_NOW]) let test_root_lifetime _ = let alive = ref true in let () = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; in Gc.full_major (); assert_equal false !alive ~msg:"values not registered as roots are collected"; let alive = ref true in let _r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Gc.full_major (); assert_equal true !alive ~msg:"registered roots are not collected"; let alive = ref true in let r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Root.release r; Gc.full_major (); assert_equal false !alive ~msg:"released roots are collected"; let alive = ref true in let () = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; let r = Root.create () in Root.set r v; in Gc.full_major (); assert_equal true !alive ~msg:"values assigned to roots are not collected"; let alive = ref true in let r = let v = [| 1; 2; 3 |] in Gc.finalise (fun _ -> alive := false) v; Root.create v in Root.set r (); Gc.full_major (); assert_equal false !alive ~msg:"overwritten roots are collected"; () let test_passing_roots _ = let save = foreign ~from:testlib "save_ocaml_value" (ptr void @-> returning void) and retrieve = foreign ~from:testlib "retrieve_ocaml_value" (void @-> returning (ptr void)) in let r = Root.create [| ( + ) 1; ( * ) 2 |] in begin save r; Gc.full_major (); let fs : (int -> int) array = Root.get (retrieve ()) in assert_equal 11 (fs.(0) 10); assert_equal 20 (fs.(1) 10) end let suite = "Root tests" >::: ["root lifetime" >:: test_root_lifetime; "passing roots" >:: test_passing_roots; ] let _ = run_test_tt_main suite
0239849570d37d145ca93a98088f4d7b178984b6825141d4842a17a443b257a6
VictorNicollet/Ohm
action_Server.ml
Ohm is © 2012 open Util open BatPervasives module BS = BatString open Action_Common class type ['param] server = object method protocol : 'param -> [`HTTP|`HTTPS] method domain : 'param -> string method port : 'param -> int method cookie_domain : 'param -> string option method matches : [`HTTP|`HTTPS] -> string -> int -> 'param option end let server_root server param = let protocol = server # protocol param in String.concat "" ( (match protocol with `HTTP -> "http://" | `HTTPS -> "https://") :: (server # domain param) :: (match protocol, server # port param with | `HTTPS, 443 | `HTTP, 80 -> [] | _, port -> [ ":" ; string_of_int port ]))
null
https://raw.githubusercontent.com/VictorNicollet/Ohm/ca90c162f6c49927c893114491f29d44aaf71feb/src/action_Server.ml
ocaml
Ohm is © 2012 open Util open BatPervasives module BS = BatString open Action_Common class type ['param] server = object method protocol : 'param -> [`HTTP|`HTTPS] method domain : 'param -> string method port : 'param -> int method cookie_domain : 'param -> string option method matches : [`HTTP|`HTTPS] -> string -> int -> 'param option end let server_root server param = let protocol = server # protocol param in String.concat "" ( (match protocol with `HTTP -> "http://" | `HTTPS -> "https://") :: (server # domain param) :: (match protocol, server # port param with | `HTTPS, 443 | `HTTP, 80 -> [] | _, port -> [ ":" ; string_of_int port ]))
aea50aec3085bd825c584210bb93c5b8bf7fcec8823dd1fce07edcad7cd8cb7e
vrnithinkumar/ETC
stlc.erl
-module(stlc). -compile(export_all). -type lterm() :: tuple(). Term Constructors ident (Name) -> {ident, Name}. int (N) -> {int, N}. lam (X, Exp) -> {lam, ident (X), Exp}. app (E1, E2) -> {app, E1, E2}. lets (X, E1, E2) -> {lets, ident (X), E1, E2}. % Example idtype ( A ) - > funt(A , A ) . idterm (X) -> lam (X, ident (X)). idapp(X) -> app(idterm(X),idterm(X)). sample() -> F = ident(f), lets(f,idterm(x),app(F,app(F,int(5)))). -spec infer(lterm()) -> hm:type(). infer (Term) -> try inferE([],Term) of {T,Cs} -> S = hm:prettify([],T), io:fwrite("~nGenerated constraints are:~n"), S_ = hm:prettyCs(Cs,S), Sub = hm:solve(Cs), io:fwrite("Inferred type: "), hm:prettify(S_, hm:subT(T,Sub)), io:fwrite("~n"), ok catch error:{type_error,Reason} -> erlang:error("Type Error: " ++ Reason) end. %%%%%%%%%%%% Inference algorithm -spec inferE(hm:env(), lterm()) -> {hm:type(), [hm:constraint()]}. inferE (Env, {ident, X}) -> T = env:lookup(X,Env), case T of undefined -> erlang:error({type_error,"Unbound variable " ++ util:to_string(X)}); _ -> {hm:freshen(T),[]} end; inferE (_, {int, _}) -> {hm:bt(int), []}; inferE (Env, {lam, {ident, X}, B}) -> A = env:fresh(), Env_ = env:extend (X,A,Env), {T,Cs_} = inferE (Env_, B), {hm:funt([A],T), Cs_ }; inferE (Env, {app, F, A}) -> {T1,Cs1} = inferE(Env, F), {T2,Cs2} = inferE(Env, A), V = env:fresh(), {V, Cs1 ++ Cs2 ++ [{T1, hm:funt([T2],V)}]}; inferE (Env, {lets, {ident, X}, E1, E2}) -> {T1, Cs1} = inferE(Env, E1), Sub = hm:solve(Cs1), T1_ = hm:subT(T1, Sub), % principal type for X Env_ = hm:subE(Env, Sub), Env__ = env:extend (X, hm:generalize(T1_, Env_), Env_), {T2, Cs2} = inferE(Env__, E2), {T2, Cs1 ++ Cs2}.
null
https://raw.githubusercontent.com/vrnithinkumar/ETC/5e5806975fe96a902dab830a0c8caadc5d61e62b/src/stlc.erl
erlang
Example Inference algorithm principal type for X
-module(stlc). -compile(export_all). -type lterm() :: tuple(). Term Constructors ident (Name) -> {ident, Name}. int (N) -> {int, N}. lam (X, Exp) -> {lam, ident (X), Exp}. app (E1, E2) -> {app, E1, E2}. lets (X, E1, E2) -> {lets, ident (X), E1, E2}. idtype ( A ) - > funt(A , A ) . idterm (X) -> lam (X, ident (X)). idapp(X) -> app(idterm(X),idterm(X)). sample() -> F = ident(f), lets(f,idterm(x),app(F,app(F,int(5)))). -spec infer(lterm()) -> hm:type(). infer (Term) -> try inferE([],Term) of {T,Cs} -> S = hm:prettify([],T), io:fwrite("~nGenerated constraints are:~n"), S_ = hm:prettyCs(Cs,S), Sub = hm:solve(Cs), io:fwrite("Inferred type: "), hm:prettify(S_, hm:subT(T,Sub)), io:fwrite("~n"), ok catch error:{type_error,Reason} -> erlang:error("Type Error: " ++ Reason) end. -spec inferE(hm:env(), lterm()) -> {hm:type(), [hm:constraint()]}. inferE (Env, {ident, X}) -> T = env:lookup(X,Env), case T of undefined -> erlang:error({type_error,"Unbound variable " ++ util:to_string(X)}); _ -> {hm:freshen(T),[]} end; inferE (_, {int, _}) -> {hm:bt(int), []}; inferE (Env, {lam, {ident, X}, B}) -> A = env:fresh(), Env_ = env:extend (X,A,Env), {T,Cs_} = inferE (Env_, B), {hm:funt([A],T), Cs_ }; inferE (Env, {app, F, A}) -> {T1,Cs1} = inferE(Env, F), {T2,Cs2} = inferE(Env, A), V = env:fresh(), {V, Cs1 ++ Cs2 ++ [{T1, hm:funt([T2],V)}]}; inferE (Env, {lets, {ident, X}, E1, E2}) -> {T1, Cs1} = inferE(Env, E1), Sub = hm:solve(Cs1), Env_ = hm:subE(Env, Sub), Env__ = env:extend (X, hm:generalize(T1_, Env_), Env_), {T2, Cs2} = inferE(Env__, E2), {T2, Cs1 ++ Cs2}.
4a01e5ebc15a802834c25eaa1f4db1124cbb55f918b66dd41213777aeb9a2fa2
langston-barrett/CoverTranslator
Main.hs
import System import System.Cmd import System.Console.GetOpt import System.Posix.Files import Data.Maybe ( fromMaybe ) import qualified Text.PrettyPrint.HughesPJ as Pretty(Doc, render) import Control.Monad import Prelude hiding (catch) import Control.Exception (catch) import IO (writeFile, hPutStr, stderr) import Char import ExternalCore (Module) import ParserExternalCore(parseCore, ParseResult(OkP,FailP)) --import PprExternalCore() import LambdaLifting (lambdaLift) import CaseAbstraction (caseAbstract, KeepKind(AllTopLevel, VarTopLevel)) import BNFC_Show_Doc () import Cl.Abs as Cl (Module) import Core2Cl (core2cl) import qualified Cl.Print(printTree, prt) import Cl2Fol (cl2fol) import Fol (ProofObl, Id(Qname), Library, Def, Prop) import FolPP (otterPrinter, tptpPrinter, debugPrinter) import FoFrontEnd (splitAndSlice) import Core2Agda (core2agda) import AgdaProp2Goal (agdaProp2Goal) import AbsAlfa as Agda (Module) import PrintAlfa (printTree) import UnObfusc(unObfusc) dump :: Show a => String -> a -> IO () dump label x = writeFile (label++".debug_CoverTranslator") (show x) `catch` \err-> hPutStr stderr ("Ignoring this problem: "++show err) data Options = Options { optVerbosity :: Int, optPrintOtter :: Bool, optPrintTptp :: Bool, optPrintAgda :: Bool, optLoadFiles :: [String], optIncFiles :: [String] } defaultOptions :: Options defaultOptions = Options { optVerbosity = 0, optPrintOtter = False, optPrintTptp = False, optPrintAgda = False, optLoadFiles = [], optIncFiles = [] } options :: [ OptDescr (Options -> IO Options) ] options = [ Option "v" ["verbose"] (ReqArg (\d -> \opt -> return opt { optVerbosity = read d }) "VERBOSITY") "set VERBOSITY level" , Option "l" ["load"] (ReqArg (\f -> \opt -> return opt { optLoadFiles = f:(optLoadFiles opt) }) "FILE") "load FILE as library" , Option "i" ["include"] (ReqArg (\f -> \opt -> return opt { optIncFiles = f:(optIncFiles opt) }) "FILE") "include FILE as library" , Option "o" ["otter"] (NoArg (\opt -> return opt { optPrintOtter = True })) "output Otter code" , Option "t" ["tptp"] (NoArg (\opt -> return opt { optPrintTptp = True })) "output tptp code" , Option "a" ["agda"] (NoArg (\opt -> return opt { optPrintAgda = True })) "output Agda code" ] -- | Parse input flags, do main job (using loadFile), -- splitAndSlice, write output files main :: IO () main = do args <- getArgs let (actions, nonOptions, errors) = getOpt RequireOrder options args filename <- case nonOptions of [x] -> return x [] -> do putStrLn (usageInfo "cfop [options] file" options) error "No input file specified" _ -> do putStrLn (usageInfo "cfop [options] file" options) error "Only one input file allowed" opts <- foldl (>>=) (return defaultOptions) actions let prAgda = optPrintAgda opts if prAgda then agda_main opts filename else fol_main opts filename agda_main opts filename = do (name, agda) <- loadFile2Agda opts filename when (optPrintAgda opts) (writeFile (name++".agda") (printTree agda)) shoule catch IO errors fol_main opts filename = do let Options { optPrintOtter = prOtter, optPrintTptp = prTptp, optLoadFiles = files2load, optIncFiles = files2inc } = opts (name, b, fCode, fProp) <- loadFile opts True filename loadLibraries <- mapM (loadFile opts False) files2load incLibraries <- mapM (loadFile opts True) files2inc let libraries = loadLibraries ++ incLibraries mName = toUpper (head name) : tail name lProofOb = splitAndSlice libraries (mName, b, fCode, fProp) when prOtter (outputProofObligations otterPrinter name lProofOb) when prTptp (outputProofObligations tptpPrinter name lProofOb) outputProofObligations :: (ProofObl -> Pretty.Doc) -> String -> [ProofObl] -> IO () outputProofObligations printer baseName lProofOb = mapM_ outputOne lProofOb where filename v = baseName ++ "_" ++ (unObfusc v) ++ ".otter" outputOne proofOb@(Qname _m v, _code, _prop) = writeFile (filename v) (Pretty.render (printer proofOb)) -- | parseCore, caseAbstract, lambdaLift, core2cl, cl2fol loadFile :: Options -> Bool -> String -> IO Fol.Library loadFile opts useDef filename = do (name, lifted) <- loadFile_ opts filename let cl :: Cl.Module cl = core2cl lifted let verbose :: Int verbose = optVerbosity opts when (verbose>3) (dump (name++".cl") (Cl.Print.prt 0 cl)) let fCode :: [Fol.Def] fProp :: [Fol.Prop] fol@(fCode, fProp) = cl2fol cl when ( verbose>0 ) ( dump ( name++".fol " ) ( fol ) ) return (name, useDef, fCode, fProp) -- | parseCore, caseAbstract, lambdaLift loadFile_ :: Options -> String -> IO (String, ExternalCore.Module) loadFile_ opts filename = do s <- readFile filename let (name, _ext) = splitName filename let core :: ExternalCore.Module core = case parseCore s 1 of OkP m -> m FailP s -> error ("Parse error: " ++ s) caseA :: ExternalCore.Module -- caseA = caseAbstract AllTopLevel core caseA = caseAbstract VarTopLevel core let verbose :: Int verbose = optVerbosity opts when (verbose>0) (dump (name++".caseA.hcr") caseA) let lifted :: ExternalCore.Module lifted = lambdaLift caseA when (verbose>0) (dump (name++".lifted.hcr") lifted) return (name, lifted) loadFile2Agda :: Options -> String -> IO (String, Agda.Module) loadFile2Agda opts filename = do (name, lifted) <- loadFile_ opts filename let agda = agdaProp2Goal $ core2agda lifted return (name, agda) splitName :: String -> (String, String) splitName filename = splitN filename where splitN s = searchDot ([],[]) (reverse filename) searchDot (f,e) [] = (e, []) searchDot (f,e) (x:xs) | x == '.' = (reverse xs, e) | x == '/' = (reverse (x:xs) ++ e, []) | otherwise = searchDot (f, x:e) xs
null
https://raw.githubusercontent.com/langston-barrett/CoverTranslator/4172bef9f4eede7e45dc002a70bf8c6dd9a56b5c/src/Main.hs
haskell
import PprExternalCore() | Parse input flags, do main job (using loadFile), splitAndSlice, write output files | parseCore, caseAbstract, lambdaLift, core2cl, cl2fol | parseCore, caseAbstract, lambdaLift caseA = caseAbstract AllTopLevel core
import System import System.Cmd import System.Console.GetOpt import System.Posix.Files import Data.Maybe ( fromMaybe ) import qualified Text.PrettyPrint.HughesPJ as Pretty(Doc, render) import Control.Monad import Prelude hiding (catch) import Control.Exception (catch) import IO (writeFile, hPutStr, stderr) import Char import ExternalCore (Module) import ParserExternalCore(parseCore, ParseResult(OkP,FailP)) import LambdaLifting (lambdaLift) import CaseAbstraction (caseAbstract, KeepKind(AllTopLevel, VarTopLevel)) import BNFC_Show_Doc () import Cl.Abs as Cl (Module) import Core2Cl (core2cl) import qualified Cl.Print(printTree, prt) import Cl2Fol (cl2fol) import Fol (ProofObl, Id(Qname), Library, Def, Prop) import FolPP (otterPrinter, tptpPrinter, debugPrinter) import FoFrontEnd (splitAndSlice) import Core2Agda (core2agda) import AgdaProp2Goal (agdaProp2Goal) import AbsAlfa as Agda (Module) import PrintAlfa (printTree) import UnObfusc(unObfusc) dump :: Show a => String -> a -> IO () dump label x = writeFile (label++".debug_CoverTranslator") (show x) `catch` \err-> hPutStr stderr ("Ignoring this problem: "++show err) data Options = Options { optVerbosity :: Int, optPrintOtter :: Bool, optPrintTptp :: Bool, optPrintAgda :: Bool, optLoadFiles :: [String], optIncFiles :: [String] } defaultOptions :: Options defaultOptions = Options { optVerbosity = 0, optPrintOtter = False, optPrintTptp = False, optPrintAgda = False, optLoadFiles = [], optIncFiles = [] } options :: [ OptDescr (Options -> IO Options) ] options = [ Option "v" ["verbose"] (ReqArg (\d -> \opt -> return opt { optVerbosity = read d }) "VERBOSITY") "set VERBOSITY level" , Option "l" ["load"] (ReqArg (\f -> \opt -> return opt { optLoadFiles = f:(optLoadFiles opt) }) "FILE") "load FILE as library" , Option "i" ["include"] (ReqArg (\f -> \opt -> return opt { optIncFiles = f:(optIncFiles opt) }) "FILE") "include FILE as library" , Option "o" ["otter"] (NoArg (\opt -> return opt { optPrintOtter = True })) "output Otter code" , Option "t" ["tptp"] (NoArg (\opt -> return opt { optPrintTptp = True })) "output tptp code" , Option "a" ["agda"] (NoArg (\opt -> return opt { optPrintAgda = True })) "output Agda code" ] main :: IO () main = do args <- getArgs let (actions, nonOptions, errors) = getOpt RequireOrder options args filename <- case nonOptions of [x] -> return x [] -> do putStrLn (usageInfo "cfop [options] file" options) error "No input file specified" _ -> do putStrLn (usageInfo "cfop [options] file" options) error "Only one input file allowed" opts <- foldl (>>=) (return defaultOptions) actions let prAgda = optPrintAgda opts if prAgda then agda_main opts filename else fol_main opts filename agda_main opts filename = do (name, agda) <- loadFile2Agda opts filename when (optPrintAgda opts) (writeFile (name++".agda") (printTree agda)) shoule catch IO errors fol_main opts filename = do let Options { optPrintOtter = prOtter, optPrintTptp = prTptp, optLoadFiles = files2load, optIncFiles = files2inc } = opts (name, b, fCode, fProp) <- loadFile opts True filename loadLibraries <- mapM (loadFile opts False) files2load incLibraries <- mapM (loadFile opts True) files2inc let libraries = loadLibraries ++ incLibraries mName = toUpper (head name) : tail name lProofOb = splitAndSlice libraries (mName, b, fCode, fProp) when prOtter (outputProofObligations otterPrinter name lProofOb) when prTptp (outputProofObligations tptpPrinter name lProofOb) outputProofObligations :: (ProofObl -> Pretty.Doc) -> String -> [ProofObl] -> IO () outputProofObligations printer baseName lProofOb = mapM_ outputOne lProofOb where filename v = baseName ++ "_" ++ (unObfusc v) ++ ".otter" outputOne proofOb@(Qname _m v, _code, _prop) = writeFile (filename v) (Pretty.render (printer proofOb)) loadFile :: Options -> Bool -> String -> IO Fol.Library loadFile opts useDef filename = do (name, lifted) <- loadFile_ opts filename let cl :: Cl.Module cl = core2cl lifted let verbose :: Int verbose = optVerbosity opts when (verbose>3) (dump (name++".cl") (Cl.Print.prt 0 cl)) let fCode :: [Fol.Def] fProp :: [Fol.Prop] fol@(fCode, fProp) = cl2fol cl when ( verbose>0 ) ( dump ( name++".fol " ) ( fol ) ) return (name, useDef, fCode, fProp) loadFile_ :: Options -> String -> IO (String, ExternalCore.Module) loadFile_ opts filename = do s <- readFile filename let (name, _ext) = splitName filename let core :: ExternalCore.Module core = case parseCore s 1 of OkP m -> m FailP s -> error ("Parse error: " ++ s) caseA :: ExternalCore.Module caseA = caseAbstract VarTopLevel core let verbose :: Int verbose = optVerbosity opts when (verbose>0) (dump (name++".caseA.hcr") caseA) let lifted :: ExternalCore.Module lifted = lambdaLift caseA when (verbose>0) (dump (name++".lifted.hcr") lifted) return (name, lifted) loadFile2Agda :: Options -> String -> IO (String, Agda.Module) loadFile2Agda opts filename = do (name, lifted) <- loadFile_ opts filename let agda = agdaProp2Goal $ core2agda lifted return (name, agda) splitName :: String -> (String, String) splitName filename = splitN filename where splitN s = searchDot ([],[]) (reverse filename) searchDot (f,e) [] = (e, []) searchDot (f,e) (x:xs) | x == '.' = (reverse xs, e) | x == '/' = (reverse (x:xs) ++ e, []) | otherwise = searchDot (f, x:e) xs
06d62d0a4371814f0bb96f9d35d28b37114a2aefbf4fce9acc81ee3c624656ae
erlyaws/yaws
throwtest.erl
-module(throwtest). -export([out/1]). out(_Arg) -> throw({status, 200}).
null
https://raw.githubusercontent.com/erlyaws/yaws/da198c828e9d95ca2137da7884cddadd73941d13/testsuite/main_SUITE_data/throwtest.erl
erlang
-module(throwtest). -export([out/1]). out(_Arg) -> throw({status, 200}).
c6bc9b34c1146392973de6ffa050cad1b9fce49317c4746c534138fe1746e42c
tanakh/ICFP2011
KRYHomu.hs
# LANGUAGE CPP # {-# OPTIONS -Wall #-} import Control.Applicative import qualified Control.Exception.Control as E import Control.Monad import Control.Monad.State import Data.Maybe import LTG getFirstWorthEnemy :: Int -> LTG (Maybe Int) getFirstWorthEnemy dmg = do alives <- filterM (\ix -> do al <- isAlive False ix vt <- getVital False ix return (al && vt >= dmg)) [0..255] return $ listToMaybe alives getAnySlot :: LTG (Maybe Int) getAnySlot = do aliveidents <- filterM (\ix -> do al <- isAlive True ix fn <- getField True ix return (al && fn == VFun "I")) [0..255] return $ listToMaybe aliveidents ensureZombieDead :: LTG () ensureZombieDead = do zombieReady <- isDead False 255 if zombieReady then do return () oops ! They revived 255 ! vit <- getVital False 255 aliveslot <- getAnySlot lprint $ "GG2 " ++ show vit ++ " " ++ show aliveslot case (vit, aliveslot) of (1, Just slot) -> do -- dec slot $< Zero Dec $> slot ensureZombieDead _ -> return () zombieLoop :: Int -> Int -> LTG () zombieLoop f2 dmg = do elms <- getFirstWorthEnemy dmg case elms of Nothing -> return () Just n -> do num 7 n copyTo f2 0 ensureZombieDead f2 $< I zombieLoop f2 dmg ofN :: Int -> Value ofN x = VInt x ofC :: Card -> Value ofC x = VFun (cardName x) infixl 1 $| ($|) :: Value -> Value -> Value x $| y = VApp x y lazyApplyIntermediate :: Value -> Value -> Value lazyApplyIntermediate f g = -- S (K f) (K g) (ofC S) $| (ofC K $| f) $| (ofC K $| g) makeFieldUnlessConstructed :: Int -> Value -> LTG() -> LTG() makeFieldUnlessConstructed f lval procedure = do ff <- getField True f if ff == lval then do {-lprint $ "Reusing " ++ show f-} return () else do {- lprint $ "Failed reusing " ++ show f ++ " [expected " ++ show lval ++ " but was " ++ show ff ++ "]"-} procedure kyokoAnAn :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> LTG () kyokoAnAn f1 f2 f3 f4 f5 f7 target dmg = do -- f1, f2, f3: temp -- f4, f5 -- target: zombie target \x - > ( copy f4 ) ( succ x ) -- next = v[f2] <- S (lazy_apply Copy f4) succ let lazyCopy4 = lazyApplyIntermediate (ofC Copy) (ofN 4) makeFieldUnlessConstructed f2 (ofC S $| lazyCopy4 $| ofC Succ) $ do clear f2 f2 $< Copy num 0 f4 lazyApply f2 0 S $> f2 f2 $< Succ True f2 ; -- f = v[f4] <- S (lazy_apply Copy f5) I -- S (S help I) (S (K copy) (K 6)) S ( S(S help I)(S(K copy)(K 6 ) ) ) ( S ( S(K copy)(K 4 ) ) succ ) \x - > help x x ( ( \ _ - > ( copy 6 ) ) x ) ; ( copy 4 ) ( succ x ) let lazyCopy6 = lazyApplyIntermediate (ofC Copy) (ofN 6) let loopCode = ofC S $| lazyCopy4 $| ofC Succ let helpBody = ofC S $| (ofC S $| ofC Help $| ofC I) $| lazyCopy6 makeFieldUnlessConstructed f4 (ofC S $| helpBody $| loopCode) $ do -- S (S Help I) clear f4 f4 $< S f4 $< Help f4 $< I S $> f4 clear f3 lazy ( Copy 6 ) f3 $< Copy num 0 6 lazyApply f3 0 copyTo 0 f3 apply0 f4 -- S (S Help I) (S (K copy) (K 6)) -- v[f4] <- S f4 f2 S $> f4 copyTo 0 f2 apply0 f4 --x1 <- getField True f4; lprint x1 -- v[f1] <- S (lazyApply Copy f4) (lazyApply Copy f7) -- this is zombie! let lazyCopy7 = lazyApplyIntermediate (ofC Copy) (ofN 7) makeFieldUnlessConstructed f1 (ofC S $| lazyCopy4 $| lazyCopy7) $ do clear f1 f1 $< Copy num 0 f4 lazyApply f1 0 S $> f1 clear f2 f2 $< Copy num 0 f7 lazyApply f2 0 copyTo 0 f2 apply0 f1 --x2 <- getField True f1; lprint x2 num f2 (255-target) Zombie $> f2 lazyApply f2 f1 copyTo 0 f2 zombieLoop f2 dmg sittingDuck :: LTG() sittingDuck = do I $> 0 sittingDuck get 3 * 2^n or 2^n smaller than x getEasyInt :: Int -> Int getEasyInt x | (x <= 3) = x getEasyInt x = max (head $ filter (\y -> y * 2 > x) twos) (head $ filter (\y -> y * 2 > x) threep) where twos = map (2^) [(0::Int)..] threep = 1 : map (\n -> 3*(2^n)) [(0::Int)..] #ifdef KAMIJO Iize , omae wo , ! ! speedo :: Int -> Double speedo x | x == 0 = 0 | odd x = 1 + speedo (x-1) | even x = 1 + speedo (div x 2) getMaxEnemy :: LTG Int getMaxEnemy = do oppAlives <- filterM (isAlive False) [0..255] vitals <- mapM (getVital False) oppAlives let targets = zip oppAlives vitals umami (i, v) = (fromIntegral v * 2 ** (0-speedo i) , v) return $ snd $ maximum $ map umami targets #else debugTag::String debugTag = "kyoko" getMaxEnemy :: LTG Int getMaxEnemy = do oppAlives <- filterM (isAlive False) [0..255] vitals <- mapM (getVital False) oppAlives return $ maximum vitals #endif kyoukoMain :: LTG() kyoukoMain = do dmg <- getEasyInt <$> getMaxEnemy zombifySlotVital <- getVital False 255 let zombifySlotV = getEasyInt zombifySlotVital alives <- filterM (\x -> do v <- getVital True x return $ v > zombifySlotV) [1..255] -- TODO: raise error to increase vitality if length alives < 2 then lerror "there are no vital" else do -- dmg > 2 -> attack is issued " dec " is issued if = 1 when (zombifySlotV > 1) $ do attack2 (alives !! 1) (alives !! 4) 0 zombifySlotV attack ( ! ! 0 ) 0 zombifySlotV attack ( ! ! 1 ) 0 zombifySlotV attack (alives !! 0) 0 zombifySlotV attack (alives !! 1) 0 zombifySlotV -} v[5 ] < - S ( S help I ) ( lazyApply Copy 6 ) clear 5 5 $ < S 5 $ < Help 5 $ < I S $ > 5 clear 6 6 $ < Copy num 7 6 lazyApply 6 7 copyTo 0 6 apply0 5 clear 5 5 $< S 5 $< Help 5 $< I S $> 5 clear 6 6 $< Copy num 7 6 lazyApply 6 7 copyTo 0 6 apply0 5 -} num 6 dmg kyokoAnAn 1 2 3 4 5 7 255 dmg attackFA 1 2 18 3 5 6 8192 attackLoopFA 1 2 18 5 0 0 -- sittingDuck keepAlive :: Int -> LTG () keepAlive ix = do d <- isDead True ix when d $ do _ <- revive ix keepAlive ix ignExc :: LTG a -> LTG () ignExc m = do mb <- E.try m case mb of Left (LTGError _) -> return () Right _ -> return () yose :: LTG () yose = do forever $ ignExc $ do keepAlive 0 num 0 0 forM_ [(0::Int)..255] $ \_ -> do keepAlive 0 keepAlive 1 copyTo 1 0 Dec $> 1 Succ $> 0 waruagaki :: LTG () waruagaki = do keepAlive 0 keepAlive 1 keepAlive 2 num 0 1 Inc $> 0 num 0 2 Inc $> 0 main :: IO () main = runLTG $ do lprint debugTag forever $ do ds <- filterM (isDead True) [0..255] if null ds then do turn <- turnCnt <$> get if turn >= 100000 - 1536 then do lprint "yose mode" yose else do lprint "normal mode" mb <- E.try kyoukoMain case mb of Left (LTGError e) -> do case e of "there are no vital" -> do lprint "waruagaki mode" waruagaki _ -> do lprint e return () Right _ -> do return () return () else do lprint $ "Revive mode: " ++ show (head ds) ignExc $ revive (head ds) lprint "Revive done" return () futureApply 1 2 18 3
null
https://raw.githubusercontent.com/tanakh/ICFP2011/db0d670cdbe12e9cef4242d6ab202a98c254412e/ai/KRYHomu.hs
haskell
# OPTIONS -Wall # dec S (K f) (K g) lprint $ "Reusing " ++ show f lprint $ "Failed reusing " ++ show f ++ " [expected " ++ show lval ++ " but was " ++ show ff ++ "]" f1, f2, f3: temp f4, f5 target: zombie target next = v[f2] <- S (lazy_apply Copy f4) succ f = v[f4] <- S (lazy_apply Copy f5) I S (S help I) (S (K copy) (K 6)) S (S Help I) S (S Help I) (S (K copy) (K 6)) v[f4] <- S f4 f2 x1 <- getField True f4; lprint x1 v[f1] <- S (lazyApply Copy f4) (lazyApply Copy f7) this is zombie! x2 <- getField True f1; lprint x2 TODO: raise error to increase vitality dmg > 2 -> attack is issued sittingDuck
# LANGUAGE CPP # import Control.Applicative import qualified Control.Exception.Control as E import Control.Monad import Control.Monad.State import Data.Maybe import LTG getFirstWorthEnemy :: Int -> LTG (Maybe Int) getFirstWorthEnemy dmg = do alives <- filterM (\ix -> do al <- isAlive False ix vt <- getVital False ix return (al && vt >= dmg)) [0..255] return $ listToMaybe alives getAnySlot :: LTG (Maybe Int) getAnySlot = do aliveidents <- filterM (\ix -> do al <- isAlive True ix fn <- getField True ix return (al && fn == VFun "I")) [0..255] return $ listToMaybe aliveidents ensureZombieDead :: LTG () ensureZombieDead = do zombieReady <- isDead False 255 if zombieReady then do return () oops ! They revived 255 ! vit <- getVital False 255 aliveslot <- getAnySlot lprint $ "GG2 " ++ show vit ++ " " ++ show aliveslot case (vit, aliveslot) of (1, Just slot) -> do slot $< Zero Dec $> slot ensureZombieDead _ -> return () zombieLoop :: Int -> Int -> LTG () zombieLoop f2 dmg = do elms <- getFirstWorthEnemy dmg case elms of Nothing -> return () Just n -> do num 7 n copyTo f2 0 ensureZombieDead f2 $< I zombieLoop f2 dmg ofN :: Int -> Value ofN x = VInt x ofC :: Card -> Value ofC x = VFun (cardName x) infixl 1 $| ($|) :: Value -> Value -> Value x $| y = VApp x y lazyApplyIntermediate :: Value -> Value -> Value lazyApplyIntermediate f g = (ofC S) $| (ofC K $| f) $| (ofC K $| g) makeFieldUnlessConstructed :: Int -> Value -> LTG() -> LTG() makeFieldUnlessConstructed f lval procedure = do ff <- getField True f if ff == lval then do return () else do procedure kyokoAnAn :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> LTG () kyokoAnAn f1 f2 f3 f4 f5 f7 target dmg = do \x - > ( copy f4 ) ( succ x ) let lazyCopy4 = lazyApplyIntermediate (ofC Copy) (ofN 4) makeFieldUnlessConstructed f2 (ofC S $| lazyCopy4 $| ofC Succ) $ do clear f2 f2 $< Copy num 0 f4 lazyApply f2 0 S $> f2 f2 $< Succ True f2 ; S ( S(S help I)(S(K copy)(K 6 ) ) ) ( S ( S(K copy)(K 4 ) ) succ ) \x - > help x x ( ( \ _ - > ( copy 6 ) ) x ) ; ( copy 4 ) ( succ x ) let lazyCopy6 = lazyApplyIntermediate (ofC Copy) (ofN 6) let loopCode = ofC S $| lazyCopy4 $| ofC Succ let helpBody = ofC S $| (ofC S $| ofC Help $| ofC I) $| lazyCopy6 makeFieldUnlessConstructed f4 (ofC S $| helpBody $| loopCode) $ do clear f4 f4 $< S f4 $< Help f4 $< I S $> f4 clear f3 lazy ( Copy 6 ) f3 $< Copy num 0 6 lazyApply f3 0 copyTo 0 f3 S $> f4 copyTo 0 f2 apply0 f4 let lazyCopy7 = lazyApplyIntermediate (ofC Copy) (ofN 7) makeFieldUnlessConstructed f1 (ofC S $| lazyCopy4 $| lazyCopy7) $ do clear f1 f1 $< Copy num 0 f4 lazyApply f1 0 S $> f1 clear f2 f2 $< Copy num 0 f7 lazyApply f2 0 copyTo 0 f2 apply0 f1 num f2 (255-target) Zombie $> f2 lazyApply f2 f1 copyTo 0 f2 zombieLoop f2 dmg sittingDuck :: LTG() sittingDuck = do I $> 0 sittingDuck get 3 * 2^n or 2^n smaller than x getEasyInt :: Int -> Int getEasyInt x | (x <= 3) = x getEasyInt x = max (head $ filter (\y -> y * 2 > x) twos) (head $ filter (\y -> y * 2 > x) threep) where twos = map (2^) [(0::Int)..] threep = 1 : map (\n -> 3*(2^n)) [(0::Int)..] #ifdef KAMIJO Iize , omae wo , ! ! speedo :: Int -> Double speedo x | x == 0 = 0 | odd x = 1 + speedo (x-1) | even x = 1 + speedo (div x 2) getMaxEnemy :: LTG Int getMaxEnemy = do oppAlives <- filterM (isAlive False) [0..255] vitals <- mapM (getVital False) oppAlives let targets = zip oppAlives vitals umami (i, v) = (fromIntegral v * 2 ** (0-speedo i) , v) return $ snd $ maximum $ map umami targets #else debugTag::String debugTag = "kyoko" getMaxEnemy :: LTG Int getMaxEnemy = do oppAlives <- filterM (isAlive False) [0..255] vitals <- mapM (getVital False) oppAlives return $ maximum vitals #endif kyoukoMain :: LTG() kyoukoMain = do dmg <- getEasyInt <$> getMaxEnemy zombifySlotVital <- getVital False 255 let zombifySlotV = getEasyInt zombifySlotVital alives <- filterM (\x -> do v <- getVital True x return $ v > zombifySlotV) [1..255] if length alives < 2 then lerror "there are no vital" else do " dec " is issued if = 1 when (zombifySlotV > 1) $ do attack2 (alives !! 1) (alives !! 4) 0 zombifySlotV attack ( ! ! 0 ) 0 zombifySlotV attack ( ! ! 1 ) 0 zombifySlotV attack (alives !! 0) 0 zombifySlotV attack (alives !! 1) 0 zombifySlotV -} v[5 ] < - S ( S help I ) ( lazyApply Copy 6 ) clear 5 5 $ < S 5 $ < Help 5 $ < I S $ > 5 clear 6 6 $ < Copy num 7 6 lazyApply 6 7 copyTo 0 6 apply0 5 clear 5 5 $< S 5 $< Help 5 $< I S $> 5 clear 6 6 $< Copy num 7 6 lazyApply 6 7 copyTo 0 6 apply0 5 -} num 6 dmg kyokoAnAn 1 2 3 4 5 7 255 dmg attackFA 1 2 18 3 5 6 8192 attackLoopFA 1 2 18 5 0 0 keepAlive :: Int -> LTG () keepAlive ix = do d <- isDead True ix when d $ do _ <- revive ix keepAlive ix ignExc :: LTG a -> LTG () ignExc m = do mb <- E.try m case mb of Left (LTGError _) -> return () Right _ -> return () yose :: LTG () yose = do forever $ ignExc $ do keepAlive 0 num 0 0 forM_ [(0::Int)..255] $ \_ -> do keepAlive 0 keepAlive 1 copyTo 1 0 Dec $> 1 Succ $> 0 waruagaki :: LTG () waruagaki = do keepAlive 0 keepAlive 1 keepAlive 2 num 0 1 Inc $> 0 num 0 2 Inc $> 0 main :: IO () main = runLTG $ do lprint debugTag forever $ do ds <- filterM (isDead True) [0..255] if null ds then do turn <- turnCnt <$> get if turn >= 100000 - 1536 then do lprint "yose mode" yose else do lprint "normal mode" mb <- E.try kyoukoMain case mb of Left (LTGError e) -> do case e of "there are no vital" -> do lprint "waruagaki mode" waruagaki _ -> do lprint e return () Right _ -> do return () return () else do lprint $ "Revive mode: " ++ show (head ds) ignExc $ revive (head ds) lprint "Revive done" return () futureApply 1 2 18 3
6828b656f8bb6f872ea139f9878f447f79663a41abf1c001ac030d75f2984e28
erlang/otp
my_behaviour.erl
-module(my_behaviour). -callback foo() -> #{ {{{f,f}, f}, f} => x }.
null
https://raw.githubusercontent.com/erlang/otp/de2a455b752258236eb764cb4c8368c6d9f20114/lib/dialyzer/test/behaviour_SUITE_data/src/otp_6221/my_behaviour.erl
erlang
-module(my_behaviour). -callback foo() -> #{ {{{f,f}, f}, f} => x }.
1c036a0d52ddb0b2a164f4bb4405218cbb20d6b7520086e7b6f558118cc02a84
m4dc4p/haskelldb
hardcoded-layout-simple-query.hs
import Database.HaskellDB import Database.HaskellDB.DBLayout import TestConnect import Random create table test_tb1 ( c11 int not null , c12 int null ) ; --------------------------------------------------------------------------- -- Tables --------------------------------------------------------------------------- ------------------------------------- -- Table test_tb1 ------------------------------------- test_tb1 :: Table (RecCons C11 (Expr Int) (RecCons C12 (Expr (Maybe Int)) RecNil)) test_tb1 = baseTable "test_tb1" $ hdbMakeEntry C11 # hdbMakeEntry C12 --------------------------------------------------------------------------- -- Fields --------------------------------------------------------------------------- ------------------------------------- C11 Field ------------------------------------- data C11 = C11 instance FieldTag C11 where fieldName _ = "c11" c11 :: Attr C11 Int c11 = mkAttr C11 ------------------------------------- C12 Field ------------------------------------- data C12 = C12 instance FieldTag C12 where fieldName _ = "c12" c12 :: Attr C12 (Maybe Int) c12 = mkAttr C12 -- -- A simple query -- q = do tb1 <- table test_tb1 project (c11 << tb1!c11 # c12 << tb1!c12) newRec x y = c11 << constant x # c12 << constant y printResults rs = mapM_ (\row -> putStrLn (show (row!c11) ++ " " ++ show (row!c12))) rs -- -- Testing db layout functions -- listTables db = tables db >>= putStr . unlines -- run 'describe' describeTable table db = describe db table >>= putStr . unlines . map show bigTest db = do putStrLn "Tables:" listTables db cols <- describe db "test_tb1" putStrLn "Columns in test_tb1" putStrLn (unlines (map show cols)) putStrLn "Contents of test_tb1" res <- query db q printResults res (x::Int) <- randomIO (y::Int) <- randomIO let my = if even y then Just y else Nothing -- insertNew db test_tb1 (newRec x my) insert db test_tb1 ( project ( x my ) ) -- putStrLn $ "Contents of test_tb1 after inserting " ++ show (x,my) putStrLn "Contents of test_tb1" res <- query db q printResults res main = argConnect bigTest
null
https://raw.githubusercontent.com/m4dc4p/haskelldb/a1fbc8a2eca8c70ebe382bf4c022275836d9d510/test/old/hardcoded-layout-simple-query.hs
haskell
------------------------------------------------------------------------- Tables ------------------------------------------------------------------------- ----------------------------------- Table test_tb1 ----------------------------------- ------------------------------------------------------------------------- Fields ------------------------------------------------------------------------- ----------------------------------- ----------------------------------- ----------------------------------- ----------------------------------- A simple query Testing db layout functions run 'describe' insertNew db test_tb1 (newRec x my) putStrLn $ "Contents of test_tb1 after inserting " ++ show (x,my)
import Database.HaskellDB import Database.HaskellDB.DBLayout import TestConnect import Random create table test_tb1 ( c11 int not null , c12 int null ) ; test_tb1 :: Table (RecCons C11 (Expr Int) (RecCons C12 (Expr (Maybe Int)) RecNil)) test_tb1 = baseTable "test_tb1" $ hdbMakeEntry C11 # hdbMakeEntry C12 C11 Field data C11 = C11 instance FieldTag C11 where fieldName _ = "c11" c11 :: Attr C11 Int c11 = mkAttr C11 C12 Field data C12 = C12 instance FieldTag C12 where fieldName _ = "c12" c12 :: Attr C12 (Maybe Int) c12 = mkAttr C12 q = do tb1 <- table test_tb1 project (c11 << tb1!c11 # c12 << tb1!c12) newRec x y = c11 << constant x # c12 << constant y printResults rs = mapM_ (\row -> putStrLn (show (row!c11) ++ " " ++ show (row!c12))) rs listTables db = tables db >>= putStr . unlines describeTable table db = describe db table >>= putStr . unlines . map show bigTest db = do putStrLn "Tables:" listTables db cols <- describe db "test_tb1" putStrLn "Columns in test_tb1" putStrLn (unlines (map show cols)) putStrLn "Contents of test_tb1" res <- query db q printResults res (x::Int) <- randomIO (y::Int) <- randomIO let my = if even y then Just y else Nothing insert db test_tb1 ( project ( x my ) ) putStrLn "Contents of test_tb1" res <- query db q printResults res main = argConnect bigTest
88ff2f3a9e223db4fd5d2d6fd992142a6b133d8bd89d24c5d6aab04709b9c2a8
alexbiehl/postie
Postie.hs
# LANGUAGE ScopedTypeVariables # module Network.Mail.Postie ( run, -- | Runs server with a given application on a specified port runSettings, -- | Runs server with a given application and settings runSettingsSocket, -- * Application module Network.Mail.Postie.Types, -- * Settings module Network.Mail.Postie.Settings, -- * Address module Network.Mail.Postie.Address, -- * Exceptions UnexpectedEndOfInputException, TooMuchDataException, -- * Re-exports P.Producer, P.Consumer, P.runEffect, (P.>->), ) where import Control.Concurrent import Control.Exception as E import Control.Monad (forever, void) import Network.Socket import Network.TLS (ServerParams) import qualified Pipes as P import System.Timeout import Network.Mail.Postie.Address import Network.Mail.Postie.Connection import Network.Mail.Postie.Pipes (TooMuchDataException, UnexpectedEndOfInputException) import Network.Mail.Postie.Session import Network.Mail.Postie.Settings import Network.Mail.Postie.Types run :: Int -> Application -> IO () run port = runSettings (def {settingsPort = fromIntegral port}) runSettings :: Settings -> Application -> IO () runSettings settings app = withSocketsDo $ bracket (listenOn port) close $ \sock -> runSettingsSocket settings sock app where port = settingsPort settings listenOn portNum = bracketOnError (socket AF_INET6 Stream defaultProtocol) close ( \sock -> do setSocketOption sock ReuseAddr 1 bind sock (SockAddrInet6 portNum 0 (0, 0, 0, 0) 0) listen sock maxListenQueue return sock ) runSettingsSocket :: Settings -> Socket -> Application -> IO () runSettingsSocket settings sock = runSettingsConnection settings getConn where getConn = do (s, sa) <- accept sock conn <- mkSocketConnection s return (conn, sa) runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO () runSettingsConnection settings getConn app = do serverParams <- mkServerParams' runSettingsConnectionMaker settings (getConnMaker serverParams) serverParams app where getConnMaker serverParams = do (conn, sa) <- getConn let mkConn = do case settingsStartTLSPolicy settings of Just ConnectWithTLS -> do let (Just sp) = serverParams connSetSecure conn sp _ -> return () return conn return (mkConn, sa) mkServerParams' = case settingsTLS settings of Just tls -> do serverParams <- mkServerParams tls return (Just serverParams) _ -> return Nothing runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Maybe ServerParams -> Application -> IO () runSettingsConnectionMaker settings getConnMaker serverParams app = do settingsBeforeMainLoop settings void $ forever $ do (mkConn, sockAddr) <- getConnLoop void $ forkIOWithUnmask $ \unmask -> do sessionID <- mkSessionID bracket mkConn connClose $ \conn -> void $ timeout maxDuration $ unmask . handle (onE $ Just sessionID) . bracket_ (onOpen sessionID sockAddr) (onClose sessionID) $ runSession (mkSessionEnv sessionID app settings conn serverParams) where getConnLoop = getConnMaker `E.catch` \(e :: IOException) -> do onE Nothing (toException e) threadDelay 1000000 getConnLoop onE = settingsOnException settings onOpen = settingsOnOpen settings onClose = settingsOnClose settings maxDuration = settingsTimeout settings * 1000000
null
https://raw.githubusercontent.com/alexbiehl/postie/6a4edf104e09940e8df8a559dfbc827ba2c4dde0/src/Network/Mail/Postie.hs
haskell
| Runs server with a given application on a specified port | Runs server with a given application and settings * Application * Settings * Address * Exceptions * Re-exports
# LANGUAGE ScopedTypeVariables # module Network.Mail.Postie ( run, runSettings, runSettingsSocket, module Network.Mail.Postie.Types, module Network.Mail.Postie.Settings, module Network.Mail.Postie.Address, UnexpectedEndOfInputException, TooMuchDataException, P.Producer, P.Consumer, P.runEffect, (P.>->), ) where import Control.Concurrent import Control.Exception as E import Control.Monad (forever, void) import Network.Socket import Network.TLS (ServerParams) import qualified Pipes as P import System.Timeout import Network.Mail.Postie.Address import Network.Mail.Postie.Connection import Network.Mail.Postie.Pipes (TooMuchDataException, UnexpectedEndOfInputException) import Network.Mail.Postie.Session import Network.Mail.Postie.Settings import Network.Mail.Postie.Types run :: Int -> Application -> IO () run port = runSettings (def {settingsPort = fromIntegral port}) runSettings :: Settings -> Application -> IO () runSettings settings app = withSocketsDo $ bracket (listenOn port) close $ \sock -> runSettingsSocket settings sock app where port = settingsPort settings listenOn portNum = bracketOnError (socket AF_INET6 Stream defaultProtocol) close ( \sock -> do setSocketOption sock ReuseAddr 1 bind sock (SockAddrInet6 portNum 0 (0, 0, 0, 0) 0) listen sock maxListenQueue return sock ) runSettingsSocket :: Settings -> Socket -> Application -> IO () runSettingsSocket settings sock = runSettingsConnection settings getConn where getConn = do (s, sa) <- accept sock conn <- mkSocketConnection s return (conn, sa) runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO () runSettingsConnection settings getConn app = do serverParams <- mkServerParams' runSettingsConnectionMaker settings (getConnMaker serverParams) serverParams app where getConnMaker serverParams = do (conn, sa) <- getConn let mkConn = do case settingsStartTLSPolicy settings of Just ConnectWithTLS -> do let (Just sp) = serverParams connSetSecure conn sp _ -> return () return conn return (mkConn, sa) mkServerParams' = case settingsTLS settings of Just tls -> do serverParams <- mkServerParams tls return (Just serverParams) _ -> return Nothing runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Maybe ServerParams -> Application -> IO () runSettingsConnectionMaker settings getConnMaker serverParams app = do settingsBeforeMainLoop settings void $ forever $ do (mkConn, sockAddr) <- getConnLoop void $ forkIOWithUnmask $ \unmask -> do sessionID <- mkSessionID bracket mkConn connClose $ \conn -> void $ timeout maxDuration $ unmask . handle (onE $ Just sessionID) . bracket_ (onOpen sessionID sockAddr) (onClose sessionID) $ runSession (mkSessionEnv sessionID app settings conn serverParams) where getConnLoop = getConnMaker `E.catch` \(e :: IOException) -> do onE Nothing (toException e) threadDelay 1000000 getConnLoop onE = settingsOnException settings onOpen = settingsOnOpen settings onClose = settingsOnClose settings maxDuration = settingsTimeout settings * 1000000
9e25ba8cfdd3ca56621be52984fd075f2aed938a91382928148d6d3386a10c60
juspay/atlas
App.hs
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : App Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : App Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module App ( runPublicTransportSearchConsumer, ) where import Beckn.Exit import Beckn.Prelude import Beckn.Storage.Esqueleto.Migration (migrateIfNeeded) import Beckn.Types.Flow (runFlowR) import Beckn.Utils.App import Beckn.Utils.Dhall (readDhallConfigDefault) import Beckn.Utils.Servant.Server (runHealthCheckServerWithService) import Beckn.Utils.Servant.SignatureAuth (modFlowRtWithAuthManagers) import Environment import Servant import qualified Service.Runner as Runner runPublicTransportSearchConsumer :: (AppCfg -> AppCfg) -> IO () runPublicTransportSearchConsumer configModifier = do appCfg <- configModifier <$> readDhallConfigDefault "public-transport-search-consumer" appEnv <- try (buildAppEnv appCfg) >>= handleLeftIO @SomeException exitBuildingAppEnvFailure "Couldn't build AppEnv: " runHealthCheckServerWithService appEnv identity identity EmptyContext (runService appEnv) releaseAppEnv $ \flowRt -> do migrateIfNeeded appCfg.migrationPath appCfg.autoMigrate appCfg.esqDBCfg >>= handleLeft exitDBMigrationFailure "Couldn't migrate database: " modFlowRtWithAuthManagers flowRt appEnv [(appCfg.bapId, appCfg.authEntity.uniqueKeyId)] where runService appEnv flowRt = runFlowR flowRt appEnv Runner.run
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/public-transport-search-consumer/src/App.hs
haskell
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : App Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : App Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module App ( runPublicTransportSearchConsumer, ) where import Beckn.Exit import Beckn.Prelude import Beckn.Storage.Esqueleto.Migration (migrateIfNeeded) import Beckn.Types.Flow (runFlowR) import Beckn.Utils.App import Beckn.Utils.Dhall (readDhallConfigDefault) import Beckn.Utils.Servant.Server (runHealthCheckServerWithService) import Beckn.Utils.Servant.SignatureAuth (modFlowRtWithAuthManagers) import Environment import Servant import qualified Service.Runner as Runner runPublicTransportSearchConsumer :: (AppCfg -> AppCfg) -> IO () runPublicTransportSearchConsumer configModifier = do appCfg <- configModifier <$> readDhallConfigDefault "public-transport-search-consumer" appEnv <- try (buildAppEnv appCfg) >>= handleLeftIO @SomeException exitBuildingAppEnvFailure "Couldn't build AppEnv: " runHealthCheckServerWithService appEnv identity identity EmptyContext (runService appEnv) releaseAppEnv $ \flowRt -> do migrateIfNeeded appCfg.migrationPath appCfg.autoMigrate appCfg.esqDBCfg >>= handleLeft exitDBMigrationFailure "Couldn't migrate database: " modFlowRtWithAuthManagers flowRt appEnv [(appCfg.bapId, appCfg.authEntity.uniqueKeyId)] where runService appEnv flowRt = runFlowR flowRt appEnv Runner.run
c07b342c6159142101738ee00b7880757511ae03c40120a16d05b37ccc77be71
bobeff/playground
017.rkt
Exercise 17 . Define the function image - classify , which consumes an image and ; conditionally produces "tall" if the image is taller than wide, "wide" if it ; is wider than tall, or "square" if its width and height are the same. #lang racket (require 2htdp/image rackunit) (include "../data/cat-image.rkt") (define (image-classify image) (let ((width (image-width image)) (height (image-height image))) (cond ((< width height) "tall") ((> width height) "wide") ((= width height) "square")))) (define tall-rectangle (rectangle 10 20 "solid" "red")) (define wide-rectangle (rectangle 20 10 "solid" "green")) (define square (rectangle 20 20 "solid" "blue")) (check-equal? (image-classify cat) "tall") (check-equal? (image-classify tall-rectangle) "tall") (check-equal? (image-classify wide-rectangle) "wide") (check-equal? (image-classify square) "square")
null
https://raw.githubusercontent.com/bobeff/playground/7072dbd7e0acd690749abe1498dd5f247cc21637/htdp-second-edition/exercises/017.rkt
racket
conditionally produces "tall" if the image is taller than wide, "wide" if it is wider than tall, or "square" if its width and height are the same.
Exercise 17 . Define the function image - classify , which consumes an image and #lang racket (require 2htdp/image rackunit) (include "../data/cat-image.rkt") (define (image-classify image) (let ((width (image-width image)) (height (image-height image))) (cond ((< width height) "tall") ((> width height) "wide") ((= width height) "square")))) (define tall-rectangle (rectangle 10 20 "solid" "red")) (define wide-rectangle (rectangle 20 10 "solid" "green")) (define square (rectangle 20 20 "solid" "blue")) (check-equal? (image-classify cat) "tall") (check-equal? (image-classify tall-rectangle) "tall") (check-equal? (image-classify wide-rectangle) "wide") (check-equal? (image-classify square) "square")
334cffe7d99bf2f915c2cb55a9f8cdbb1ece760f421b98991513f26c43f26a6b
Decentralized-Pictures/T4L3NT
client_proto_programs.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Protocol open Alpha_context open Tezos_micheline open Michelson_v1_printer module Program = Client_aliases.Alias (struct type t = Michelson_v1_parser.parsed Micheline_parser.parsing_result include Compare.Make (struct type nonrec t = t let compare = Micheline_parser.compare Michelson_v1_parser.compare_parsed end) let encoding = Data_encoding.conv (fun ({Michelson_v1_parser.source; _}, _) -> source) (fun source -> Michelson_v1_parser.parse_toplevel source) Data_encoding.string let of_source source = return (Michelson_v1_parser.parse_toplevel source) let to_source ({Michelson_v1_parser.source; _}, _) = return source let name = "script" end) let print_errors ?parsed (cctxt : #Protocol_client_context.full) errs ~show_source = Michelson_v1_error_reporter.enrich_runtime_errors cctxt ~chain:cctxt#chain ~block:cctxt#block ~parsed errs >>= fun errs -> cctxt#warning "%a" (Michelson_v1_error_reporter.report_errors ~details:false ?parsed ~show_source) errs >>= fun () -> cctxt#error "error running script" >>= fun () -> return_unit let print_view_result (cctxt : #Protocol_client_context.full) = function | Ok expr -> cctxt#message "%a" print_expr expr >>= fun () -> return_unit | Error errs -> print_errors cctxt ~show_source:false errs let print_run_result (cctxt : #Client_context.printer) ~show_source ~parsed = function | Ok (storage, operations, maybe_lazy_storage_diff) -> cctxt#message "@[<v 0>@[<v 2>storage@,\ %a@]@,\ @[<v 2>emitted operations@,\ %a@]@,\ @[<v 2>big_map diff@,\ %a@]@]@." print_expr storage (Format.pp_print_list Operation_result.pp_internal_operation) operations (fun ppf -> function | None -> () | Some diff -> print_big_map_diff ppf diff) maybe_lazy_storage_diff >>= fun () -> return_unit | Error errs -> print_errors cctxt errs ~show_source ~parsed let print_trace_result (cctxt : #Client_context.printer) ~show_source ~parsed = function | Ok (storage, operations, trace, maybe_lazy_storage_diff) -> cctxt#message "@[<v 0>@[<v 2>storage@,\ %a@]@,\ @[<v 2>emitted operations@,\ %a@]@,\ @[<v 2>big_map diff@,\ %a@]@,\ @[<v 2>trace@,\ %a@]@]@." print_expr storage (Format.pp_print_list Operation_result.pp_internal_operation) operations (fun ppf -> function | None -> () | Some diff -> print_big_map_diff ppf diff) maybe_lazy_storage_diff print_execution_trace trace >>= fun () -> return_unit | Error errs -> print_errors cctxt errs ~show_source ~parsed type simulation_params = { input : Michelson_v1_parser.parsed; unparsing_mode : Script_ir_translator.unparsing_mode; now : Script_timestamp.t option; level : Script_int.n Script_int.num option; source : Contract.t option; payer : Contract.t option; gas : Gas.Arith.integral option; } type run_view_params = { shared_params : simulation_params; contract : Contract.t; entrypoint : string; } type run_params = { shared_params : simulation_params; amount : Tez.t option; balance : Tez.t; program : Michelson_v1_parser.parsed; storage : Michelson_v1_parser.parsed; entrypoint : string option; } let run_view (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_view_params) = let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; contract; entrypoint; } = params in Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> Plugin.RPC.Scripts.run_view cctxt (chain, block) ?gas ~contract ~entrypoint ~input:input.expanded ~chain_id ?source ?payer ~unparsing_mode ~now ~level let run (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_params) = Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; program; amount; balance; storage; entrypoint; } = params in let amount = Option.value ~default:Tez.fifty_cents amount in Plugin.RPC.Scripts.run_code cctxt (chain, block) ?gas ?entrypoint ~unparsing_mode ~script:program.expanded ~storage:storage.expanded ~input:input.expanded ~amount ~balance ~chain_id ~source ~payer ~now ~level let trace (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_params) = Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; program; amount; balance; storage; entrypoint; } = params in let amount = Option.value ~default:Tez.fifty_cents amount in Plugin.RPC.Scripts.trace_code cctxt (chain, block) ?gas ?entrypoint ~unparsing_mode ~script:program.expanded ~storage:storage.expanded ~input:input.expanded ~amount ~balance ~chain_id ~source ~payer ~now ~level let typecheck_data cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~(data : Michelson_v1_parser.parsed) ~(ty : Michelson_v1_parser.parsed) () = Plugin.RPC.Scripts.typecheck_data cctxt (chain, block) ?gas ?legacy ~data:data.expanded ~ty:ty.expanded let typecheck_program cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~show_types (program : Michelson_v1_parser.parsed) = Plugin.RPC.Scripts.typecheck_code cctxt (chain, block) ?gas ?legacy ~script:program.expanded ~show_types let script_size cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~(program : Michelson_v1_parser.parsed) ~(storage : Michelson_v1_parser.parsed) () = Plugin.RPC.Scripts.script_size cctxt (chain, block) ?gas ?legacy ~script:program.expanded ~storage:storage.expanded let print_typecheck_result ~emacs ~show_types ~print_source_on_error program res (cctxt : #Client_context.printer) = if emacs then let (type_map, errs, _gas) = match res with | Ok (type_map, gas) -> (type_map, [], Some gas) | Error (Environment.Ecoproto_error (Script_tc_errors.Ill_typed_contract (_, type_map)) :: _ as errs) -> (type_map, errs, None) | Error errs -> ([], errs, None) in cctxt#message "(@[<v 0>(types . %a)@ (errors . %a)@])" Michelson_v1_emacs.print_type_map (program, type_map) Michelson_v1_emacs.report_errors (program, errs) >>= fun () -> return_unit else match res with | Ok (type_map, gas) -> let program = Michelson_v1_printer.inject_types type_map program in cctxt#message "@[<v 0>Well typed@,Gas remaining: %a@]" Gas.pp gas >>= fun () -> if show_types then cctxt#message "%a" Micheline_printer.print_expr program >>= fun () -> return_unit else return_unit | Error errs -> cctxt#warning "%a" (Michelson_v1_error_reporter.report_errors ~details:show_types ~show_source:print_source_on_error ~parsed:program) errs >>= fun () -> cctxt#error "ill-typed script" let entrypoint_type cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) ~entrypoint = Michelson_v1_entrypoints.script_entrypoint_type cctxt ~chain ~block program.expanded ~entrypoint let print_entrypoint_type (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ~entrypoint ty = Michelson_v1_entrypoints.print_entrypoint_type cctxt ~entrypoint ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty let list_entrypoints cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) = Michelson_v1_entrypoints.list_entrypoints cctxt ~chain ~block program.expanded let print_entrypoints_list (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ty = Michelson_v1_entrypoints.print_entrypoints_list cctxt ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty let list_unreachables cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) = Michelson_v1_entrypoints.list_unreachables cctxt ~chain ~block program.expanded let print_unreachables (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ty = Michelson_v1_entrypoints.print_unreachables cctxt ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_012_Psithaca/lib_client/client_proto_programs.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2019 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol open Alpha_context open Tezos_micheline open Michelson_v1_printer module Program = Client_aliases.Alias (struct type t = Michelson_v1_parser.parsed Micheline_parser.parsing_result include Compare.Make (struct type nonrec t = t let compare = Micheline_parser.compare Michelson_v1_parser.compare_parsed end) let encoding = Data_encoding.conv (fun ({Michelson_v1_parser.source; _}, _) -> source) (fun source -> Michelson_v1_parser.parse_toplevel source) Data_encoding.string let of_source source = return (Michelson_v1_parser.parse_toplevel source) let to_source ({Michelson_v1_parser.source; _}, _) = return source let name = "script" end) let print_errors ?parsed (cctxt : #Protocol_client_context.full) errs ~show_source = Michelson_v1_error_reporter.enrich_runtime_errors cctxt ~chain:cctxt#chain ~block:cctxt#block ~parsed errs >>= fun errs -> cctxt#warning "%a" (Michelson_v1_error_reporter.report_errors ~details:false ?parsed ~show_source) errs >>= fun () -> cctxt#error "error running script" >>= fun () -> return_unit let print_view_result (cctxt : #Protocol_client_context.full) = function | Ok expr -> cctxt#message "%a" print_expr expr >>= fun () -> return_unit | Error errs -> print_errors cctxt ~show_source:false errs let print_run_result (cctxt : #Client_context.printer) ~show_source ~parsed = function | Ok (storage, operations, maybe_lazy_storage_diff) -> cctxt#message "@[<v 0>@[<v 2>storage@,\ %a@]@,\ @[<v 2>emitted operations@,\ %a@]@,\ @[<v 2>big_map diff@,\ %a@]@]@." print_expr storage (Format.pp_print_list Operation_result.pp_internal_operation) operations (fun ppf -> function | None -> () | Some diff -> print_big_map_diff ppf diff) maybe_lazy_storage_diff >>= fun () -> return_unit | Error errs -> print_errors cctxt errs ~show_source ~parsed let print_trace_result (cctxt : #Client_context.printer) ~show_source ~parsed = function | Ok (storage, operations, trace, maybe_lazy_storage_diff) -> cctxt#message "@[<v 0>@[<v 2>storage@,\ %a@]@,\ @[<v 2>emitted operations@,\ %a@]@,\ @[<v 2>big_map diff@,\ %a@]@,\ @[<v 2>trace@,\ %a@]@]@." print_expr storage (Format.pp_print_list Operation_result.pp_internal_operation) operations (fun ppf -> function | None -> () | Some diff -> print_big_map_diff ppf diff) maybe_lazy_storage_diff print_execution_trace trace >>= fun () -> return_unit | Error errs -> print_errors cctxt errs ~show_source ~parsed type simulation_params = { input : Michelson_v1_parser.parsed; unparsing_mode : Script_ir_translator.unparsing_mode; now : Script_timestamp.t option; level : Script_int.n Script_int.num option; source : Contract.t option; payer : Contract.t option; gas : Gas.Arith.integral option; } type run_view_params = { shared_params : simulation_params; contract : Contract.t; entrypoint : string; } type run_params = { shared_params : simulation_params; amount : Tez.t option; balance : Tez.t; program : Michelson_v1_parser.parsed; storage : Michelson_v1_parser.parsed; entrypoint : string option; } let run_view (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_view_params) = let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; contract; entrypoint; } = params in Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> Plugin.RPC.Scripts.run_view cctxt (chain, block) ?gas ~contract ~entrypoint ~input:input.expanded ~chain_id ?source ?payer ~unparsing_mode ~now ~level let run (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_params) = Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; program; amount; balance; storage; entrypoint; } = params in let amount = Option.value ~default:Tez.fifty_cents amount in Plugin.RPC.Scripts.run_code cctxt (chain, block) ?gas ?entrypoint ~unparsing_mode ~script:program.expanded ~storage:storage.expanded ~input:input.expanded ~amount ~balance ~chain_id ~source ~payer ~now ~level let trace (cctxt : #Protocol_client_context.rpc_context) ~(chain : Chain_services.chain) ~block (params : run_params) = Chain_services.chain_id cctxt ~chain () >>=? fun chain_id -> let { shared_params = {input; unparsing_mode; now; level; source; payer; gas}; program; amount; balance; storage; entrypoint; } = params in let amount = Option.value ~default:Tez.fifty_cents amount in Plugin.RPC.Scripts.trace_code cctxt (chain, block) ?gas ?entrypoint ~unparsing_mode ~script:program.expanded ~storage:storage.expanded ~input:input.expanded ~amount ~balance ~chain_id ~source ~payer ~now ~level let typecheck_data cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~(data : Michelson_v1_parser.parsed) ~(ty : Michelson_v1_parser.parsed) () = Plugin.RPC.Scripts.typecheck_data cctxt (chain, block) ?gas ?legacy ~data:data.expanded ~ty:ty.expanded let typecheck_program cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~show_types (program : Michelson_v1_parser.parsed) = Plugin.RPC.Scripts.typecheck_code cctxt (chain, block) ?gas ?legacy ~script:program.expanded ~show_types let script_size cctxt ~(chain : Chain_services.chain) ~block ?gas ?legacy ~(program : Michelson_v1_parser.parsed) ~(storage : Michelson_v1_parser.parsed) () = Plugin.RPC.Scripts.script_size cctxt (chain, block) ?gas ?legacy ~script:program.expanded ~storage:storage.expanded let print_typecheck_result ~emacs ~show_types ~print_source_on_error program res (cctxt : #Client_context.printer) = if emacs then let (type_map, errs, _gas) = match res with | Ok (type_map, gas) -> (type_map, [], Some gas) | Error (Environment.Ecoproto_error (Script_tc_errors.Ill_typed_contract (_, type_map)) :: _ as errs) -> (type_map, errs, None) | Error errs -> ([], errs, None) in cctxt#message "(@[<v 0>(types . %a)@ (errors . %a)@])" Michelson_v1_emacs.print_type_map (program, type_map) Michelson_v1_emacs.report_errors (program, errs) >>= fun () -> return_unit else match res with | Ok (type_map, gas) -> let program = Michelson_v1_printer.inject_types type_map program in cctxt#message "@[<v 0>Well typed@,Gas remaining: %a@]" Gas.pp gas >>= fun () -> if show_types then cctxt#message "%a" Micheline_printer.print_expr program >>= fun () -> return_unit else return_unit | Error errs -> cctxt#warning "%a" (Michelson_v1_error_reporter.report_errors ~details:show_types ~show_source:print_source_on_error ~parsed:program) errs >>= fun () -> cctxt#error "ill-typed script" let entrypoint_type cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) ~entrypoint = Michelson_v1_entrypoints.script_entrypoint_type cctxt ~chain ~block program.expanded ~entrypoint let print_entrypoint_type (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ~entrypoint ty = Michelson_v1_entrypoints.print_entrypoint_type cctxt ~entrypoint ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty let list_entrypoints cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) = Michelson_v1_entrypoints.list_entrypoints cctxt ~chain ~block program.expanded let print_entrypoints_list (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ty = Michelson_v1_entrypoints.print_entrypoints_list cctxt ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty let list_unreachables cctxt ~(chain : Chain_services.chain) ~block (program : Michelson_v1_parser.parsed) = Michelson_v1_entrypoints.list_unreachables cctxt ~chain ~block program.expanded let print_unreachables (cctxt : #Client_context.printer) ~emacs ?script_name ~show_source ~parsed ty = Michelson_v1_entrypoints.print_unreachables cctxt ~emacs ?script_name ~on_errors:(print_errors cctxt ~show_source ~parsed) ty
bdf17fcd555de5dc1c226a7fda95d58081039086a0ff840af0df609c56194553
mirage/shared-block-ring
journal.mli
* Copyright ( C ) 2013 - 2015 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (C) 2013-2015 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Make (Log: S.LOG) (Block: S.BLOCK) (Time: S.TIME) (Clock: S.CLOCK) (Operation: S.CSTRUCTABLE): S.JOURNAL with type disk := Block.t and type operation := Operation.t (** Create a journal from a block device. Descriptions of idempotent operations may be pushed to the journal, and we guarantee to perform them at-least-once in the order they were pushed provided the block device is available. If the program crashes, the journal replay will be started when the program restarts. *)
null
https://raw.githubusercontent.com/mirage/shared-block-ring/e780fd9ed2186c14dd49f9e8d00211be648aa762/lib/journal.mli
ocaml
* Create a journal from a block device. Descriptions of idempotent operations may be pushed to the journal, and we guarantee to perform them at-least-once in the order they were pushed provided the block device is available. If the program crashes, the journal replay will be started when the program restarts.
* Copyright ( C ) 2013 - 2015 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (C) 2013-2015 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) module Make (Log: S.LOG) (Block: S.BLOCK) (Time: S.TIME) (Clock: S.CLOCK) (Operation: S.CSTRUCTABLE): S.JOURNAL with type disk := Block.t and type operation := Operation.t
71ef64ba268a972d801fc76140fddc47651d3dde3826757a8a2ba092dc2b27a8
lemmaandrew/CodingBatHaskell
endUp.hs
From Given a string , return a new string where the last 3 chars are now in upper case . If the string has less than 3 chars , uppercase whatever is there . Note that str.toUpperCase ( ) returns the uppercase version of a string . Given a string, return a new string where the last 3 chars are now in upper case. If the string has less than 3 chars, uppercase whatever is there. Note that str.toUpperCase() returns the uppercase version of a string. -} import Test.Hspec ( hspec, describe, it, shouldBe ) endUp :: String -> String endUp str = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "\"HeLLO\"" $ endUp "Hello" `shouldBe` "HeLLO" it "\"hi thERE\"" $ endUp "hi there" `shouldBe` "hi thERE" it "\"HI\"" $ endUp "hi" `shouldBe` "HI" it "\"woo HOO\"" $ endUp "woo hoo" `shouldBe` "woo HOO" it "\"xyZ12\"" $ endUp "xyz12" `shouldBe` "xyZ12" it "\"X\"" $ endUp "x" `shouldBe` "X" it "\"\"" $ endUp "" `shouldBe` ""
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Warmup-1/endUp.hs
haskell
From Given a string , return a new string where the last 3 chars are now in upper case . If the string has less than 3 chars , uppercase whatever is there . Note that str.toUpperCase ( ) returns the uppercase version of a string . Given a string, return a new string where the last 3 chars are now in upper case. If the string has less than 3 chars, uppercase whatever is there. Note that str.toUpperCase() returns the uppercase version of a string. -} import Test.Hspec ( hspec, describe, it, shouldBe ) endUp :: String -> String endUp str = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "\"HeLLO\"" $ endUp "Hello" `shouldBe` "HeLLO" it "\"hi thERE\"" $ endUp "hi there" `shouldBe` "hi thERE" it "\"HI\"" $ endUp "hi" `shouldBe` "HI" it "\"woo HOO\"" $ endUp "woo hoo" `shouldBe` "woo HOO" it "\"xyZ12\"" $ endUp "xyz12" `shouldBe` "xyZ12" it "\"X\"" $ endUp "x" `shouldBe` "X" it "\"\"" $ endUp "" `shouldBe` ""
5ed6fb4bc67b31ef0ca7fe4530b102c47b5a03a825af5d7a19eb19c487ebc188
korya/efuns
env.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : env.mli , v 1.1 2001/03/09 13:23:51 lefessan Exp $ (* Environment handling *) open Types type t val empty: t val initial: t (* Lookup by paths *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_module: Path.t -> t -> module_type val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> cltype_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr val find_modtype_expansion: Path.t -> t -> Types.module_type (* Lookup by long identifiers *) val lookup_value: Longident.t -> t -> Path.t * value_description val lookup_constructor: Longident.t -> t -> constructor_description val lookup_label: Longident.t -> t -> label_description val lookup_type: Longident.t -> t -> Path.t * type_declaration val lookup_module: Longident.t -> t -> Path.t * module_type val lookup_modtype: Longident.t -> t -> Path.t * modtype_declaration val lookup_class: Longident.t -> t -> Path.t * class_declaration val lookup_cltype: Longident.t -> t -> Path.t * cltype_declaration (* Insertion by identifier *) val add_value: Ident.t -> value_description -> t -> t val add_type: Ident.t -> type_declaration -> t -> t val add_exception: Ident.t -> exception_declaration -> t -> t val add_module: Ident.t -> module_type -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> cltype_declaration -> t -> t (* Insertion of all fields of a signature. *) val add_item: signature_item -> t -> t val add_signature: signature -> t -> t (* Insertion of all fields of a signature, relative to the given path. Used to implement open. *) val open_signature: Path.t -> signature -> t -> t val open_pers_signature: string -> t -> t (* Insertion by name *) val enter_value: string -> value_description -> t -> Ident.t * t val enter_type: string -> type_declaration -> t -> Ident.t * t val enter_exception: string -> exception_declaration -> t -> Ident.t * t val enter_module: string -> module_type -> t -> Ident.t * t val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t val enter_class: string -> class_declaration -> t -> Ident.t * t val enter_cltype: string -> cltype_declaration -> t -> Ident.t * t (* Reset the cache of in-core module interfaces. To be called in particular when load_path changes. *) val reset_cache: unit -> unit (* Read, save a signature to/from a file *) val read_signature: string -> string -> signature (* Arguments: module name, file name. Results: signature. *) val save_signature: signature -> string -> string -> unit (* Arguments: signature, module name, file name. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imported_units: unit -> (string * Digest.t) list (* Summaries -- compact representation of an environment, to be exported in debugging information. *) type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_exception of summary * Ident.t * exception_declaration | Env_module of summary * Ident.t * module_type | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * cltype_declaration | Env_open of summary * Path.t val summary: t -> summary (* Error report *) type error = Not_an_interface of string | Corrupted_interface of string | Illegal_renaming of string * string | Inconsistent_import of string * string * string exception Error of error open Format val report_error: formatter -> error -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (t -> module_type -> module_type -> unit) ref
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/ocamlsrc/compat/3.01/include/env.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Environment handling Lookup by paths Lookup by long identifiers Insertion by identifier Insertion of all fields of a signature. Insertion of all fields of a signature, relative to the given path. Used to implement open. Insertion by name Reset the cache of in-core module interfaces. To be called in particular when load_path changes. Read, save a signature to/from a file Arguments: module name, file name. Results: signature. Arguments: signature, module name, file name. Summaries -- compact representation of an environment, to be exported in debugging information. Error report
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : env.mli , v 1.1 2001/03/09 13:23:51 lefessan Exp $ open Types type t val empty: t val initial: t val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_module: Path.t -> t -> module_type val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> cltype_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr val find_modtype_expansion: Path.t -> t -> Types.module_type val lookup_value: Longident.t -> t -> Path.t * value_description val lookup_constructor: Longident.t -> t -> constructor_description val lookup_label: Longident.t -> t -> label_description val lookup_type: Longident.t -> t -> Path.t * type_declaration val lookup_module: Longident.t -> t -> Path.t * module_type val lookup_modtype: Longident.t -> t -> Path.t * modtype_declaration val lookup_class: Longident.t -> t -> Path.t * class_declaration val lookup_cltype: Longident.t -> t -> Path.t * cltype_declaration val add_value: Ident.t -> value_description -> t -> t val add_type: Ident.t -> type_declaration -> t -> t val add_exception: Ident.t -> exception_declaration -> t -> t val add_module: Ident.t -> module_type -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> cltype_declaration -> t -> t val add_item: signature_item -> t -> t val add_signature: signature -> t -> t val open_signature: Path.t -> signature -> t -> t val open_pers_signature: string -> t -> t val enter_value: string -> value_description -> t -> Ident.t * t val enter_type: string -> type_declaration -> t -> Ident.t * t val enter_exception: string -> exception_declaration -> t -> Ident.t * t val enter_module: string -> module_type -> t -> Ident.t * t val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t val enter_class: string -> class_declaration -> t -> Ident.t * t val enter_cltype: string -> cltype_declaration -> t -> Ident.t * t val reset_cache: unit -> unit val read_signature: string -> string -> signature val save_signature: signature -> string -> string -> unit Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imported_units: unit -> (string * Digest.t) list type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_exception of summary * Ident.t * exception_declaration | Env_module of summary * Ident.t * module_type | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * cltype_declaration | Env_open of summary * Path.t val summary: t -> summary type error = Not_an_interface of string | Corrupted_interface of string | Illegal_renaming of string * string | Inconsistent_import of string * string * string exception Error of error open Format val report_error: formatter -> error -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (t -> module_type -> module_type -> unit) ref
87fcb5ecd36737257304972be59747961a610aa30b7a7a02fc6815be43d792df
seckcoder/course-compiler
r4_17.rkt
(define (big [a : Integer] [b : Integer] [c : Integer] [d : Integer] [e : Integer] [f : Integer] [g : Integer] [h : Integer] [i : Integer] [j : Integer]) : Integer (+ d j)) (big 1 2 3 20 5 6 7 8 9 22)
null
https://raw.githubusercontent.com/seckcoder/course-compiler/4363e5b3e15eaa7553902c3850b6452de80b2ef6/tests/student-tests/r4_17.rkt
racket
(define (big [a : Integer] [b : Integer] [c : Integer] [d : Integer] [e : Integer] [f : Integer] [g : Integer] [h : Integer] [i : Integer] [j : Integer]) : Integer (+ d j)) (big 1 2 3 20 5 6 7 8 9 22)
b48e056b21011562d82c16817b776d25ae0e9b56d5d3f833b878967a7ad9f324
cyverse-archive/DiscoveryEnvironmentBackend
privileges.clj
(ns iplant_groups.routes.domain.privileges (:use [common-swagger-api.schema :only [describe]]) (:require [iplant_groups.routes.domain.subject :as subject] [iplant_groups.routes.domain.group :as group] [iplant_groups.routes.domain.folder :as folder] [schema.core :as s])) (s/defschema Privilege {:type (describe String "The general type of privilege.") :name (describe String "The privilege name, under the type") (s/optional-key :allowed) (describe Boolean "Whether the privilege is marked allowed.") (s/optional-key :revokable) (describe Boolean "Whether the privilege is marked revokable.") :subject (describe subject/Subject "The subject/user with the privilege.")}) (s/defschema GroupPrivilege (assoc Privilege :group (describe group/Group "The group the permission applies to."))) (s/defschema FolderPrivilege (assoc Privilege :folder (describe folder/Folder "The folder the permission applies to."))) (s/defschema GroupPrivileges {:privileges (describe [GroupPrivilege] "A list of group-centric privileges")}) (s/defschema FolderPrivileges {:privileges (describe [FolderPrivilege] "A list of folder-centric privileges")})
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/iplant-groups/src/iplant_groups/routes/domain/privileges.clj
clojure
(ns iplant_groups.routes.domain.privileges (:use [common-swagger-api.schema :only [describe]]) (:require [iplant_groups.routes.domain.subject :as subject] [iplant_groups.routes.domain.group :as group] [iplant_groups.routes.domain.folder :as folder] [schema.core :as s])) (s/defschema Privilege {:type (describe String "The general type of privilege.") :name (describe String "The privilege name, under the type") (s/optional-key :allowed) (describe Boolean "Whether the privilege is marked allowed.") (s/optional-key :revokable) (describe Boolean "Whether the privilege is marked revokable.") :subject (describe subject/Subject "The subject/user with the privilege.")}) (s/defschema GroupPrivilege (assoc Privilege :group (describe group/Group "The group the permission applies to."))) (s/defschema FolderPrivilege (assoc Privilege :folder (describe folder/Folder "The folder the permission applies to."))) (s/defschema GroupPrivileges {:privileges (describe [GroupPrivilege] "A list of group-centric privileges")}) (s/defschema FolderPrivileges {:privileges (describe [FolderPrivilege] "A list of folder-centric privileges")})
c793f32d513223e811ca55694f9d3addda00c7bed906d801dd78d6753abe38f0
wasamasa/libui
calculator.scm
(use (prefix libui ui:)) (ui:margined? #t) (ui:padded? #t) (ui:init!) (define out #f) (define cur-val 0) (define cur-op #f) (define last-op #f) (define (do-operation button) (let ((op (car (string->list (ui:button-text button))))) (if (and (char<=? #\0 op) (char<=? op #\9)) (begin (if (and last-op (char<=? #\0 last-op) (char<=? last-op #\9) (not (equal? (ui:entry-text out) "0"))) (set! (ui:entry-text out) (format "~a~c" (ui:entry-text out) op)) (set! (ui:entry-text out) (format "~c" op))) (set! last-op op)) (begin (set! last-op op) (case cur-op ((#\+) (set! (ui:entry-text out) (number->string (+ cur-val (string->number (ui:entry-text out)))))) ((#\-) (set! (ui:entry-text out) (number->string (- cur-val (string->number (ui:entry-text out)))))) ((#\*) (set! (ui:entry-text out) (number->string (* cur-val (string->number (ui:entry-text out)))))) ((#\/) (set! (ui:entry-text out) (number->string (/ cur-val (string->number (ui:entry-text out)))))) ((#\=) #f)) (if (memv op '(#\+ #\- #\* #\/)) (begin (set! cur-op op) (set! cur-val (string->number (ui:entry-text out)))) (begin (set! cur-val 0) (set! cur-op #f) (when (eqv? op #\C) (set! (ui:entry-text out) "0")))))))) (ui:widgets `(window (@ (id main) (title "Calculator") (width 240) (height 240) (closing ,(lambda (_window) (ui:quit!)))) (grid (item (@ (left 0) (top 0) (xspan 4)) (entry (@ (id out) (text "0") (read-only? #t)))) (item (@ (left 0) (top 1)) (button (@ (text "7") (clicked ,do-operation)))) (item (@ (left 1) (top 1)) (button (@ (text "8") (clicked ,do-operation)))) (item (@ (left 2) (top 1)) (button (@ (text "9") (clicked ,do-operation)))) (item (@ (left 3) (top 1)) (button (@ (text "/") (clicked ,do-operation)))) (item (@ (left 0) (top 2)) (button (@ (text "4") (clicked ,do-operation)))) (item (@ (left 1) (top 2)) (button (@ (text "5") (clicked ,do-operation)))) (item (@ (left 2) (top 2)) (button (@ (text "6") (clicked ,do-operation)))) (item (@ (left 3) (top 2)) (button (@ (text "*") (clicked ,do-operation)))) (item (@ (left 0) (top 3)) (button (@ (text "1") (clicked ,do-operation)))) (item (@ (left 1) (top 3)) (button (@ (text "2") (clicked ,do-operation)))) (item (@ (left 2) (top 3)) (button (@ (text "3") (clicked ,do-operation)))) (item (@ (left 3) (top 3)) (button (@ (text "-") (clicked ,do-operation)))) (item (@ (left 0) (top 4)) (button (@ (text "C") (clicked ,do-operation)))) (item (@ (left 1) (top 4)) (button (@ (text "0") (clicked ,do-operation)))) (item (@ (left 2) (top 4)) (button (@ (text "=") (clicked ,do-operation)))) (item (@ (left 3) (top 4)) (button (@ (text "+") (clicked ,do-operation))))))) (set! out (ui:widget-by-id 'out)) (ui:control-show! (ui:->control (ui:widget-by-id 'main))) (ui:main)
null
https://raw.githubusercontent.com/wasamasa/libui/d9b61bc650e5ee5981e78dedfca345466a9f5fe6/examples/calculator/calculator.scm
scheme
(use (prefix libui ui:)) (ui:margined? #t) (ui:padded? #t) (ui:init!) (define out #f) (define cur-val 0) (define cur-op #f) (define last-op #f) (define (do-operation button) (let ((op (car (string->list (ui:button-text button))))) (if (and (char<=? #\0 op) (char<=? op #\9)) (begin (if (and last-op (char<=? #\0 last-op) (char<=? last-op #\9) (not (equal? (ui:entry-text out) "0"))) (set! (ui:entry-text out) (format "~a~c" (ui:entry-text out) op)) (set! (ui:entry-text out) (format "~c" op))) (set! last-op op)) (begin (set! last-op op) (case cur-op ((#\+) (set! (ui:entry-text out) (number->string (+ cur-val (string->number (ui:entry-text out)))))) ((#\-) (set! (ui:entry-text out) (number->string (- cur-val (string->number (ui:entry-text out)))))) ((#\*) (set! (ui:entry-text out) (number->string (* cur-val (string->number (ui:entry-text out)))))) ((#\/) (set! (ui:entry-text out) (number->string (/ cur-val (string->number (ui:entry-text out)))))) ((#\=) #f)) (if (memv op '(#\+ #\- #\* #\/)) (begin (set! cur-op op) (set! cur-val (string->number (ui:entry-text out)))) (begin (set! cur-val 0) (set! cur-op #f) (when (eqv? op #\C) (set! (ui:entry-text out) "0")))))))) (ui:widgets `(window (@ (id main) (title "Calculator") (width 240) (height 240) (closing ,(lambda (_window) (ui:quit!)))) (grid (item (@ (left 0) (top 0) (xspan 4)) (entry (@ (id out) (text "0") (read-only? #t)))) (item (@ (left 0) (top 1)) (button (@ (text "7") (clicked ,do-operation)))) (item (@ (left 1) (top 1)) (button (@ (text "8") (clicked ,do-operation)))) (item (@ (left 2) (top 1)) (button (@ (text "9") (clicked ,do-operation)))) (item (@ (left 3) (top 1)) (button (@ (text "/") (clicked ,do-operation)))) (item (@ (left 0) (top 2)) (button (@ (text "4") (clicked ,do-operation)))) (item (@ (left 1) (top 2)) (button (@ (text "5") (clicked ,do-operation)))) (item (@ (left 2) (top 2)) (button (@ (text "6") (clicked ,do-operation)))) (item (@ (left 3) (top 2)) (button (@ (text "*") (clicked ,do-operation)))) (item (@ (left 0) (top 3)) (button (@ (text "1") (clicked ,do-operation)))) (item (@ (left 1) (top 3)) (button (@ (text "2") (clicked ,do-operation)))) (item (@ (left 2) (top 3)) (button (@ (text "3") (clicked ,do-operation)))) (item (@ (left 3) (top 3)) (button (@ (text "-") (clicked ,do-operation)))) (item (@ (left 0) (top 4)) (button (@ (text "C") (clicked ,do-operation)))) (item (@ (left 1) (top 4)) (button (@ (text "0") (clicked ,do-operation)))) (item (@ (left 2) (top 4)) (button (@ (text "=") (clicked ,do-operation)))) (item (@ (left 3) (top 4)) (button (@ (text "+") (clicked ,do-operation))))))) (set! out (ui:widget-by-id 'out)) (ui:control-show! (ui:->control (ui:widget-by-id 'main))) (ui:main)
05a25e9339a1627416583afa6f355532eb1af8155769dad3dda30c9ccd71a136
ndmitchell/neil
Todo.hs
module Paper.Todo(todo) where import Control.Monad import Data.Char import Data.List.Extra import Paper.Util.Error todo :: [FilePath] -> IO () todo files = do errs <- liftM concat $ mapM readTodos files sequence_ errs when (not $ null errs) $ error $ "Error: " ++ show (length errs) ++ " todo commands found" putStrLn "No todo commands found" readTodos :: FilePath -> IO [IO ()] readTodos file = liftM (f 1) $ readFile file where f n ('\n':xs) = f (n+1) xs f n ('\\':t:'o':'d':'o':x:xs) | toLower t == 't' && not (isAlpha x) && x /= '}' = errorMsg file n "\\todo" msg : f n xs where msg = g $ trimStart (x:xs) f n (x:xs) = f n xs f n [] = [] g ('{':xs) = "{" ++ takeWhile (`notElem` "\n}") xs ++ "}" g _ = ""
null
https://raw.githubusercontent.com/ndmitchell/neil/b06624fe697c23375222856d538cb974e96da048/src/Paper/Todo.hs
haskell
module Paper.Todo(todo) where import Control.Monad import Data.Char import Data.List.Extra import Paper.Util.Error todo :: [FilePath] -> IO () todo files = do errs <- liftM concat $ mapM readTodos files sequence_ errs when (not $ null errs) $ error $ "Error: " ++ show (length errs) ++ " todo commands found" putStrLn "No todo commands found" readTodos :: FilePath -> IO [IO ()] readTodos file = liftM (f 1) $ readFile file where f n ('\n':xs) = f (n+1) xs f n ('\\':t:'o':'d':'o':x:xs) | toLower t == 't' && not (isAlpha x) && x /= '}' = errorMsg file n "\\todo" msg : f n xs where msg = g $ trimStart (x:xs) f n (x:xs) = f n xs f n [] = [] g ('{':xs) = "{" ++ takeWhile (`notElem` "\n}") xs ++ "}" g _ = ""
d6aa0f722f372d486d1df9f92bd79b2fe667be6a83debaf077bd76f1d5ac212e
digital-asset/ghc
T9999.hs
# LANGUAGE PolyKinds , TypeFamilies , StandaloneDeriving # module T9999 where import Data.Typeable data family F a class C a where data F1 a type F2 a main = typeRep (Proxy :: Proxy F) == typeRep (Proxy :: Proxy F1)
null
https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/typecheck/should_fail/T9999.hs
haskell
# LANGUAGE PolyKinds , TypeFamilies , StandaloneDeriving # module T9999 where import Data.Typeable data family F a class C a where data F1 a type F2 a main = typeRep (Proxy :: Proxy F) == typeRep (Proxy :: Proxy F1)
160e8adc880f49681c9a94d16afdf34753aaf71866cb97bc93bb8eea57fa196e
JohnnyJayJay/ring-discord-auth
core_test.clj
(ns ring-discord-auth.core-test (:require [clojure.test :refer [deftest is testing]] [ring-discord-auth.core :as core] [ring-discord-auth.test-helpers :as test-helpers]) (:import (org.bouncycastle.crypto.params Ed25519PublicKeyParameters) (org.bouncycastle.crypto.signers Ed25519Signer))) (deftest public-key-verifier-test (let [public-key-str "e421dceefff3a9d008b7898fcc0974813201800419d72f36d51e010d6a0acb71"] (testing "public-key->verifier should convert all possible types or return nil" (is (instance? Ed25519Signer (core/public-key->signer-verifier public-key-str))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (core/hex->bytes public-key-str)))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (-> public-key-str core/hex->bytes (Ed25519PublicKeyParameters. 0))))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (-> public-key-str core/hex->bytes (Ed25519PublicKeyParameters. 0) core/new-verifier)))) (is (nil? (core/public-key->signer-verifier 1))) (is (nil? (core/public-key->signer-verifier nil)))))) (deftest authentic-test (let [key-pair (test-helpers/generate-keypair) signer (test-helpers/new-signer (:private key-pair)) public-key (.getEncoded (:public key-pair)) timestamp "1625603592" body "this should be a json." signature (->> (str timestamp body) .getBytes (test-helpers/sign signer))] (testing "authentic? should check signature vs public-key, timestamp and body" (is (= true (core/authentic? (test-helpers/bytes->hex signature) body timestamp (test-helpers/bytes->hex public-key) "utf8")) "checks with conversions.") (is (= true (core/authentic? signature (.getBytes body) (.getBytes timestamp) public-key "utf8")) "checks without conversions.") (is (= false (core/authentic? (test-helpers/bytes->hex signature) (str body "hacks-to-fail") timestamp (test-helpers/bytes->hex public-key) "utf8")) "checks with conversions.") (is (= false (core/authentic? signature (.getBytes (str body "hacks-to-fail")) (.getBytes timestamp) public-key "utf8")) "checks without conversions."))))
null
https://raw.githubusercontent.com/JohnnyJayJay/ring-discord-auth/4a050f6ba6b7a9f6a08c79819f5260f836ee36d6/test/ring_discord_auth/core_test.clj
clojure
(ns ring-discord-auth.core-test (:require [clojure.test :refer [deftest is testing]] [ring-discord-auth.core :as core] [ring-discord-auth.test-helpers :as test-helpers]) (:import (org.bouncycastle.crypto.params Ed25519PublicKeyParameters) (org.bouncycastle.crypto.signers Ed25519Signer))) (deftest public-key-verifier-test (let [public-key-str "e421dceefff3a9d008b7898fcc0974813201800419d72f36d51e010d6a0acb71"] (testing "public-key->verifier should convert all possible types or return nil" (is (instance? Ed25519Signer (core/public-key->signer-verifier public-key-str))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (core/hex->bytes public-key-str)))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (-> public-key-str core/hex->bytes (Ed25519PublicKeyParameters. 0))))) (is (instance? Ed25519Signer (core/public-key->signer-verifier (-> public-key-str core/hex->bytes (Ed25519PublicKeyParameters. 0) core/new-verifier)))) (is (nil? (core/public-key->signer-verifier 1))) (is (nil? (core/public-key->signer-verifier nil)))))) (deftest authentic-test (let [key-pair (test-helpers/generate-keypair) signer (test-helpers/new-signer (:private key-pair)) public-key (.getEncoded (:public key-pair)) timestamp "1625603592" body "this should be a json." signature (->> (str timestamp body) .getBytes (test-helpers/sign signer))] (testing "authentic? should check signature vs public-key, timestamp and body" (is (= true (core/authentic? (test-helpers/bytes->hex signature) body timestamp (test-helpers/bytes->hex public-key) "utf8")) "checks with conversions.") (is (= true (core/authentic? signature (.getBytes body) (.getBytes timestamp) public-key "utf8")) "checks without conversions.") (is (= false (core/authentic? (test-helpers/bytes->hex signature) (str body "hacks-to-fail") timestamp (test-helpers/bytes->hex public-key) "utf8")) "checks with conversions.") (is (= false (core/authentic? signature (.getBytes (str body "hacks-to-fail")) (.getBytes timestamp) public-key "utf8")) "checks without conversions."))))
f808d4866a9ff6edd1008588d808d8d056ea6b69b1cef074940c86c979221e79
jesperes/aoc_erlang
aoc2018_day21.erl
-module(aoc2018_day21). %% %% We are given a program (input.txt) in ElfCode (see days 16 and 19 ) , and we are to determine certain properties of it . I %% started out by "emulating" it only to discover that it was far to %% inefficient to get anything done. I then translated the program %% more or less directly to C and got the solution that %% way. %% The code below ( outer_loop/3 ) is roughly this C program translated to erlang . %% -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2018, day = 21, name = "Chronal Conversion", expected = {4682012, 5363733}, has_input_file = false}. -type input_type() :: none. -type result_type() :: integer(). -spec parse(Input :: binary()) -> input_type(). parse(_Input) -> %% The program was the input, and it has been hand-converted into Erlang . none. -spec solve1(Input :: input_type()) -> result_type(). solve1(_) -> For part 1 , we are only interested in finding out the value of %% R0 which causes the program to terminate in as few steps as possible . This means finding the R1 value after running through %% the program once (there is an "outer" outer loop in the %% original program which is basically "do ... while (R1 != R0)".) %% So , for part 1 , we simply need to know the value of R1 after one pass through outer_loop . If R0 is set to this value , the %% program will terminate after as few steps as possible. {R1, _, _} = outer_loop(0), R1. -spec solve2(Input :: input_type()) -> result_type(). solve2(_) -> For part 2 , we are told that we want to figure out the smallest %% value of R0 which causes the program to terminate in as many %% steps as possible. I did not understand this part until a %% colleague explained it to me, but basically we can observe that as we set R0 to { 1 , 2 , 3 , ... } , the resulting R1 values will %% eventually repeat, and we want to know the last of the R0 values used before we observe a repetition in the R1 values . This is the %% (smallest) R0 value which causes the program to run in as many %% cycles as possible. %% We solve this by putting all the R1 values in a set , and terminate once we get a R1 value we have already seen . part2_loop(0, sets:new()). part2_loop(R1, Vals) -> {R1_new, _, _} = outer_loop(R1), case sets:is_element(R1_new, Vals) of true -> R1; false -> part2_loop(R1_new, sets:add_element(R1_new, Vals)) end. %% The outer loop runs a single pass through the computation, producing new values for the registers R1 , R2 , R3 , and R5 . The %% code doesn't really do anything useful. %% %% In the original program, there is an additional loop outside this %% one which terminates once R1 == R0. outer_loop(R1) -> inner_loop1(8725355, R1 bor 65536). inner_loop1(R1, R2) -> R5 = R2 band 255, R1_1 = ((R1 + R5) * 65899) band 16#ffffff, inner_loop2(R1_1, R2, R5). inner_loop2(R1, R2, _) when R2 >= 256 -> R5 = inner_loop3(R2, 0), inner_loop1(R1, R5); inner_loop2(R1, R2, R5) -> {R1, R2, R5}. Computes a new value for R5 . The program spends 99 % of all its time %% here. inner_loop3(R2, R5) -> if (R5 + 1) bsl 8 > R2 -> R5; true -> inner_loop3(R2, R5 + 1) end.
null
https://raw.githubusercontent.com/jesperes/aoc_erlang/ec0786088fb9ab886ee57e17ea0149ba3e91810a/src/2018/aoc2018_day21.erl
erlang
We are given a program (input.txt) in ElfCode (see days 16 started out by "emulating" it only to discover that it was far to inefficient to get anything done. I then translated the program more or less directly to C and got the solution that way. The program was the input, and it has been hand-converted into R0 which causes the program to terminate in as few steps as the program once (there is an "outer" outer loop in the original program which is basically "do ... while (R1 != R0)".) program will terminate after as few steps as possible. value of R0 which causes the program to terminate in as many steps as possible. I did not understand this part until a colleague explained it to me, but basically we can observe that eventually repeat, and we want to know the last of the R0 values (smallest) R0 value which causes the program to run in as many cycles as possible. The outer loop runs a single pass through the computation, code doesn't really do anything useful. In the original program, there is an additional loop outside this one which terminates once R1 == R0. of all its time here.
-module(aoc2018_day21). and 19 ) , and we are to determine certain properties of it . I The code below ( outer_loop/3 ) is roughly this C program translated to erlang . -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2018, day = 21, name = "Chronal Conversion", expected = {4682012, 5363733}, has_input_file = false}. -type input_type() :: none. -type result_type() :: integer(). -spec parse(Input :: binary()) -> input_type(). parse(_Input) -> Erlang . none. -spec solve1(Input :: input_type()) -> result_type(). solve1(_) -> For part 1 , we are only interested in finding out the value of possible . This means finding the R1 value after running through So , for part 1 , we simply need to know the value of R1 after one pass through outer_loop . If R0 is set to this value , the {R1, _, _} = outer_loop(0), R1. -spec solve2(Input :: input_type()) -> result_type(). solve2(_) -> For part 2 , we are told that we want to figure out the smallest as we set R0 to { 1 , 2 , 3 , ... } , the resulting R1 values will used before we observe a repetition in the R1 values . This is the We solve this by putting all the R1 values in a set , and terminate once we get a R1 value we have already seen . part2_loop(0, sets:new()). part2_loop(R1, Vals) -> {R1_new, _, _} = outer_loop(R1), case sets:is_element(R1_new, Vals) of true -> R1; false -> part2_loop(R1_new, sets:add_element(R1_new, Vals)) end. producing new values for the registers R1 , R2 , R3 , and R5 . The outer_loop(R1) -> inner_loop1(8725355, R1 bor 65536). inner_loop1(R1, R2) -> R5 = R2 band 255, R1_1 = ((R1 + R5) * 65899) band 16#ffffff, inner_loop2(R1_1, R2, R5). inner_loop2(R1, R2, _) when R2 >= 256 -> R5 = inner_loop3(R2, 0), inner_loop1(R1, R5); inner_loop2(R1, R2, R5) -> {R1, R2, R5}. inner_loop3(R2, R5) -> if (R5 + 1) bsl 8 > R2 -> R5; true -> inner_loop3(R2, R5 + 1) end.
68ccd86270873fee0c04ae3addcedf9af8922bae208ec268d2144393dc56c7e7
jesperes/aoc_erlang
aoc2019_day06.erl
Advent of Code solution for 2019 day 06 . Created : 2019 - 12 - 06T06:41:22 + 00:00 -module(aoc2019_day06). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 6, name = "Universal Orbit Map", expected = {300598, 520}, has_input_file = true}. -type input_type() :: [string()]. -type result_type() :: integer(). -spec parse(Binary :: binary()) -> input_type(). parse(Binary) -> string:tokens( string:trim(binary_to_list(Binary)), "\n\r"). -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> Graph = make_digraph(Input, [acyclic]), sum_of_orbits(Graph). -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> Graph = make_digraph(Input, [cyclic]), orbital_dist(Graph). -spec make_digraph(input_type(), [acyclic | cyclic]) -> digraph:graph(). make_digraph(Input, DigraphOpts) -> Atom = fun list_to_atom/1, Graph = digraph:new(DigraphOpts), lists:map(fun(Line) -> [A, B] = lists:map(Atom, string:tokens(Line, ")")), digraph:add_vertex(Graph, A), digraph:add_vertex(Graph, B), digraph:add_edge(Graph, B, A, {B, A}), digraph:add_edge(Graph, A, B, {A, B}) end, Input), Graph. -spec sum_of_orbits(digraph:graph()) -> number(). sum_of_orbits(Graph) -> lists:sum( lists:map(fun ('COM') -> 0; (V) -> length(digraph:get_path(Graph, V, 'COM')) - 1 end, digraph:vertices(Graph))). -spec orbital_dist(digraph:graph()) -> integer(). orbital_dist(Graph) -> length(digraph:get_path(Graph, 'YOU', 'SAN')) - 3.
null
https://raw.githubusercontent.com/jesperes/aoc_erlang/ec0786088fb9ab886ee57e17ea0149ba3e91810a/src/2019/aoc2019_day06.erl
erlang
Advent of Code solution for 2019 day 06 . Created : 2019 - 12 - 06T06:41:22 + 00:00 -module(aoc2019_day06). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 6, name = "Universal Orbit Map", expected = {300598, 520}, has_input_file = true}. -type input_type() :: [string()]. -type result_type() :: integer(). -spec parse(Binary :: binary()) -> input_type(). parse(Binary) -> string:tokens( string:trim(binary_to_list(Binary)), "\n\r"). -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> Graph = make_digraph(Input, [acyclic]), sum_of_orbits(Graph). -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> Graph = make_digraph(Input, [cyclic]), orbital_dist(Graph). -spec make_digraph(input_type(), [acyclic | cyclic]) -> digraph:graph(). make_digraph(Input, DigraphOpts) -> Atom = fun list_to_atom/1, Graph = digraph:new(DigraphOpts), lists:map(fun(Line) -> [A, B] = lists:map(Atom, string:tokens(Line, ")")), digraph:add_vertex(Graph, A), digraph:add_vertex(Graph, B), digraph:add_edge(Graph, B, A, {B, A}), digraph:add_edge(Graph, A, B, {A, B}) end, Input), Graph. -spec sum_of_orbits(digraph:graph()) -> number(). sum_of_orbits(Graph) -> lists:sum( lists:map(fun ('COM') -> 0; (V) -> length(digraph:get_path(Graph, V, 'COM')) - 1 end, digraph:vertices(Graph))). -spec orbital_dist(digraph:graph()) -> integer(). orbital_dist(Graph) -> length(digraph:get_path(Graph, 'YOU', 'SAN')) - 3.
365cd49107d030fbc2c0cf98ee006ef10f3257d60b9a848afeea72a71e8888c5
I3ck/HGE2D
Example3.hs
module Main where import HGE2D.Types import HGE2D.Datas import HGE2D.Colors import HGE2D.Classes import HGE2D.Instances () import HGE2D.Shapes import HGE2D.Render import HGE2D.Engine {- Example showing dynamic changes by moving the rectanlge -} -------------------------------------------------------------------------------- --in here we are going to store all data of the game data GameState = GameState { gsSize :: (Double, Double) -- current size of the entire game in pixels , time :: Millisecond -- current time of the game , isClicked :: Bool -- whether the rectangle has been clicked , moveUp :: Bool -- whether the rectangle is moving up , pos :: RealPosition -- the position of the rectangle } --define our initial state gs3 = GameState { time = 0 , gsSize = (0, 0) , pos = (0, 0) , isClicked = False , moveUp = False } --define all functions of the engine for usage of our state es3 = EngineState { getTitle = myGetTitle , getTime = myGetTime , setTime = mySetTime , moveTime = myMoveTime , click = myClick , mUp = myMouseUp , hover = myHover , drag = myDrag , kDown = myKeyDown , kUp = myKeyUp , resize = myResize , getSize = myGetSize , toGlInstr = myToGlInstr } :: EngineState GameState where myGetTitle _ = "Welcome to Example3" --title of the games window myGetTime = time -- how to retrieve the games time mySetTime ms gs = gs { time = ms } -- how to set the games time myMoveTime ms gs = gs { pos = newPos, moveUp = newMoveUp } -- react to changes in time by moving the position where newMoveUp | snd oldPos < 1 && moveUp gs = False | snd oldPos > (snd $ gsSize gs) && (not (moveUp gs)) = True | otherwise = moveUp gs newPos | moveUp gs = ((fst oldPos), (snd oldPos - realToFrac ms / 30)) | otherwise = ((fst oldPos), (snd oldPos + realToFrac ms / 10)) oldPos = pos gs myClick _ _ gs = gs { isClicked = not $ isClicked gs } -- toggle the isClicked Bool on click myMouseUp _ _ = id --nor mouse up myHover x y gs = gs { pos = (x, y) } -- store the hover position myDrag _ _ gs = gs -- don't react to draging myKeyDown _ _ _ = id -- nor key presses myKeyUp _ _ _ = id --nor key releases myResize (w, h) gs = gs { gsSize = (realToFrac w, realToFrac h) } -- how to resize our game myGetSize = gsSize -- and get its size myToGlInstr gs = withCamera es3 gs $ RenderPreserve $ RenderMany -- render with a camera and while preserving changes [ RenderColorize color -- a colored , RenderTranslate (realToFrac $ getX $ pos gs) (realToFrac $ getY $ pos gs) -- moved to pos , rectangle 30 30 -- rectangle of 30px with and height ] where -- the color of the rectangle depends on the click state color | isClicked gs = colorWhite | otherwise = colorGreen -------------------------------------------------------------------------------- main = runEngine es3 gs3
null
https://raw.githubusercontent.com/I3ck/HGE2D/7ab789964013d8f24cd0be9fbad967d41d00a4bb/src/examples/Example3.hs
haskell
Example showing dynamic changes by moving the rectanlge ------------------------------------------------------------------------------ in here we are going to store all data of the game current size of the entire game in pixels current time of the game whether the rectangle has been clicked whether the rectangle is moving up the position of the rectangle define our initial state define all functions of the engine for usage of our state title of the games window how to retrieve the games time how to set the games time react to changes in time by moving the position toggle the isClicked Bool on click nor mouse up store the hover position don't react to draging nor key presses nor key releases how to resize our game and get its size render with a camera and while preserving changes a colored moved to pos rectangle of 30px with and height the color of the rectangle depends on the click state ------------------------------------------------------------------------------
module Main where import HGE2D.Types import HGE2D.Datas import HGE2D.Colors import HGE2D.Classes import HGE2D.Instances () import HGE2D.Shapes import HGE2D.Render import HGE2D.Engine data GameState = GameState } gs3 = GameState { time = 0 , gsSize = (0, 0) , pos = (0, 0) , isClicked = False , moveUp = False } es3 = EngineState { getTitle = myGetTitle , getTime = myGetTime , setTime = mySetTime , moveTime = myMoveTime , click = myClick , mUp = myMouseUp , hover = myHover , drag = myDrag , kDown = myKeyDown , kUp = myKeyUp , resize = myResize , getSize = myGetSize , toGlInstr = myToGlInstr } :: EngineState GameState where where newMoveUp | snd oldPos < 1 && moveUp gs = False | snd oldPos > (snd $ gsSize gs) && (not (moveUp gs)) = True | otherwise = moveUp gs newPos | moveUp gs = ((fst oldPos), (snd oldPos - realToFrac ms / 30)) | otherwise = ((fst oldPos), (snd oldPos + realToFrac ms / 10)) oldPos = pos gs ] color | isClicked gs = colorWhite | otherwise = colorGreen main = runEngine es3 gs3
3741a3df6dbdcce0f883e4c2e3458397dcef3ac48b49c6ce18a75b7eef7fdea8
SergeTupchiy/socks_er
socks_er.erl
-module(socks_er). -behaviour(application). -behaviour(supervisor). api for starting with erl -s socks_er -export([start/2, stop/1]). %% application -export([start_link/0, init/1]). %% supervisor dev / testing defaults to be used with upstream server run locally via -define(UNAME, <<"test">>). -define(PASSWD, <<"test1">>). -define(DEFAULT_UPSTREAM_HOST, "localhost"). -define(DEFAULT_UPSTREAM_PORT, "1080"). -define(DEFAULT_LISTEN_PORT, "1081"). -define(DEFAULT_NUM_ACCEPTORS, "100"). -define(DEFAULT_MAX_CONNECTIONS, "1024"). %% the same as ranch default value 5 minutes start() -> {ok, _} = application:ensure_all_started(socks_er, permanent), ok. %% application start(_StartType, _StartArgs) -> ok = application:ensure_started(ranch), ProxyHost = os:getenv("U_HOST", ?DEFAULT_UPSTREAM_HOST), ProxyPort = erlang:list_to_integer(os:getenv("U_PORT", ?DEFAULT_UPSTREAM_PORT)), ProxyUname = erlang:iolist_to_binary(os:getenv("U_UNAME", ?UNAME)), ProxyPasswd = erlang:iolist_to_binary(os:getenv("U_PASSWD", ?PASSWD)), ListenPort = erlang:list_to_integer(os:getenv("LISTEN_PORT", ?DEFAULT_LISTEN_PORT)), NumAcceptors = erlang:list_to_integer(os:getenv("NUM_ACCEPTORS", ?DEFAULT_NUM_ACCEPTORS)), MaxConnections = erlang:list_to_integer(os:getenv("MAX_CONNECTIONS", ?DEFAULT_MAX_CONNECTIONS)), ConnTimeout = erlang:list_to_integer(os:getenv("CONN_TIMEOUT", ?DEFAULT_CONN_TIMEOUT_MS)), {ok, _} = ranch:start_listener(socks_server, ranch_tcp, #{socket_opts => [{port, ListenPort}], max_connections => MaxConnections, num_acceptors => NumAcceptors}, socks_server, [ProxyHost, ProxyPort, ProxyUname, ProxyPasswd, ConnTimeout]), start_link(). stop(_State) -> ranch:stop_listener(socks_server), ok. %% supervisor start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, { {one_for_all, 0, 1}, []} }.
null
https://raw.githubusercontent.com/SergeTupchiy/socks_er/254d84ead928b02bd345054d7af1dacfa9a4ee97/src/socks_er.erl
erlang
application supervisor the same as ranch default value application supervisor
-module(socks_er). -behaviour(application). -behaviour(supervisor). api for starting with erl -s socks_er dev / testing defaults to be used with upstream server run locally via -define(UNAME, <<"test">>). -define(PASSWD, <<"test1">>). -define(DEFAULT_UPSTREAM_HOST, "localhost"). -define(DEFAULT_UPSTREAM_PORT, "1080"). -define(DEFAULT_LISTEN_PORT, "1081"). -define(DEFAULT_NUM_ACCEPTORS, "100"). 5 minutes start() -> {ok, _} = application:ensure_all_started(socks_er, permanent), ok. start(_StartType, _StartArgs) -> ok = application:ensure_started(ranch), ProxyHost = os:getenv("U_HOST", ?DEFAULT_UPSTREAM_HOST), ProxyPort = erlang:list_to_integer(os:getenv("U_PORT", ?DEFAULT_UPSTREAM_PORT)), ProxyUname = erlang:iolist_to_binary(os:getenv("U_UNAME", ?UNAME)), ProxyPasswd = erlang:iolist_to_binary(os:getenv("U_PASSWD", ?PASSWD)), ListenPort = erlang:list_to_integer(os:getenv("LISTEN_PORT", ?DEFAULT_LISTEN_PORT)), NumAcceptors = erlang:list_to_integer(os:getenv("NUM_ACCEPTORS", ?DEFAULT_NUM_ACCEPTORS)), MaxConnections = erlang:list_to_integer(os:getenv("MAX_CONNECTIONS", ?DEFAULT_MAX_CONNECTIONS)), ConnTimeout = erlang:list_to_integer(os:getenv("CONN_TIMEOUT", ?DEFAULT_CONN_TIMEOUT_MS)), {ok, _} = ranch:start_listener(socks_server, ranch_tcp, #{socket_opts => [{port, ListenPort}], max_connections => MaxConnections, num_acceptors => NumAcceptors}, socks_server, [ProxyHost, ProxyPort, ProxyUname, ProxyPasswd, ConnTimeout]), start_link(). stop(_State) -> ranch:stop_listener(socks_server), ok. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, { {one_for_all, 0, 1}, []} }.
91aef44b0b76309bd541e13e70a3bc2296ed0db7cf1b6b542d7e42668a9050e0
Soostone/instrument
Counter.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # {-# OPTIONS_GHC -Wno-name-shadowing #-} module Instrument.Tests.Counter ( tests, ) where import Instrument.Counter import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import Control.Monad tests :: TestTree tests = testGroup "Instrument.Counter" [ testCase "is zero after initialized" $ do c <- newCounter val <- readCounter c assertEqual "should be zero after initialized" 0 val, testProperty "registers arbitrary number of hits: increment" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter forM_ [1..n] (\_ -> increment c) val <- readCounter c pure $ fromIntegral n === val, testProperty "registers arbitrary number of hits: add" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter add (fromIntegral n) c val <- readCounter c pure $ fromIntegral n === val, testProperty "reset brings back to zero" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter add (fromIntegral n) c val <- resetCounter c assertEqual "should match" (fromIntegral n) val val <- readCounter c pure $ 0 === val, testProperty "registers arbitrary number of hits close to rollover" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter let offset = maxBound - 5 add offset c val <- resetCounter c assertEqual "offset should match" (fromIntegral offset) val val <- readCounter c assertEqual "should be zero after reset" 0 val forM_ [1..n] (\_ -> increment c) val <- readCounter c pure $ fromIntegral n === val ]
null
https://raw.githubusercontent.com/Soostone/instrument/9be4002ddd035b960f2f7439e876e268308db89c/instrument/test/src/Instrument/Tests/Counter.hs
haskell
# LANGUAGE OverloadedStrings # # OPTIONS_GHC -Wno-name-shadowing #
# LANGUAGE ScopedTypeVariables # module Instrument.Tests.Counter ( tests, ) where import Instrument.Counter import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck import Control.Monad tests :: TestTree tests = testGroup "Instrument.Counter" [ testCase "is zero after initialized" $ do c <- newCounter val <- readCounter c assertEqual "should be zero after initialized" 0 val, testProperty "registers arbitrary number of hits: increment" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter forM_ [1..n] (\_ -> increment c) val <- readCounter c pure $ fromIntegral n === val, testProperty "registers arbitrary number of hits: add" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter add (fromIntegral n) c val <- readCounter c pure $ fromIntegral n === val, testProperty "reset brings back to zero" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter add (fromIntegral n) c val <- resetCounter c assertEqual "should match" (fromIntegral n) val val <- readCounter c pure $ 0 === val, testProperty "registers arbitrary number of hits close to rollover" $ \(NonNegative (n :: Integer)) -> ioProperty $ do c <- newCounter let offset = maxBound - 5 add offset c val <- resetCounter c assertEqual "offset should match" (fromIntegral offset) val val <- readCounter c assertEqual "should be zero after reset" 0 val forM_ [1..n] (\_ -> increment c) val <- readCounter c pure $ fromIntegral n === val ]
f76bd37087eadf09fc8e540cd38c030e9478a0b65156f2b5c0e7d5a48d643082
lamdu/lamdu
Codec.hs
| JSON encoder / decoder for types # LANGUAGE TemplateHaskell , TypeFamilies , TypeApplications , FlexibleInstances # module Lamdu.Data.Export.JSON.Codec ( TagOrder , Version(..) , Entity(..), _EntitySchemaVersion, _EntityDef, _EntityTag, _EntityNominal, _EntityLamVar ) where import qualified Control.Lens as Lens import Control.Lens.Extended ((~~>)) import Control.Monad ((>=>)) import Data.Aeson ((.:)) import qualified Data.Aeson as Aeson import Data.Aeson.Key (Key) import qualified Data.Aeson.Key as Aeson.Key import Data.Aeson.Lens (_Object) import qualified Data.Aeson.Types as AesonTypes import Data.Bitraversable (Bitraversable(..)) import qualified Data.ByteString.Base16 as Hex import qualified Data.ByteString.Char8 as BS import qualified Data.Map as Map import qualified Data.Set as Set import Data.UUID.Types (UUID) import qualified Data.Vector as Vector import Hyper import Hyper.Syntax (FuncType(..)) import Hyper.Syntax.Nominal (ToNom(..), NominalDecl(..), NominalInst(..)) import Hyper.Syntax.Row (RowExtend(..)) import Hyper.Syntax.Scheme (Scheme(..), QVars(..), QVarInstances(..), _QVarInstances) import Hyper.Type.Prune (Prune(..), _Unpruned) import Lamdu.Calc.Definition import Lamdu.Calc.Identifier (Identifier, identHex, identFromHex) import Lamdu.Calc.Term (Val) import qualified Lamdu.Calc.Term as V import qualified Lamdu.Calc.Type as T import qualified Lamdu.Data.Anchors as Anchors import Lamdu.Data.Definition (Definition(..)) import qualified Lamdu.Data.Definition as Definition import qualified Lamdu.Data.Meta as Meta import Lamdu.Data.Tag (Tag(..)) import qualified Lamdu.Data.Tag as Tag import Lamdu.Prelude hiding ((.=)) type Encoder a = a -> Aeson.Value type Decoder a = Aeson.Value -> AesonTypes.Parser a type TagOrder = Int newtype Version = Version Int deriving stock (Eq, Ord, Show) data Entity = EntitySchemaVersion Version | EntityDef (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) | EntityTag T.Tag Tag | EntityNominal T.Tag T.NominalId (Either (T.Types # QVars) (Pure # NominalDecl T.Type)) | EntityLamVar T.Tag V.Var | EntityOpenDefPane V.Var Lens.makePrisms ''Entity instance Aeson.ToJSON Entity where toJSON (EntitySchemaVersion ver) = encodeSchemaVersion ver toJSON (EntityDef def) = encodeDef def toJSON (EntityTag tid tdata) = encodeNamedTag (tid, tdata) toJSON (EntityNominal tag nomId nom) = encodeTaggedNominal ((tag, nomId), nom) toJSON (EntityLamVar tag var) = encodeTaggedLamVar (tag, var) toJSON (EntityOpenDefPane (V.Var v)) = "openDefPane" ~~> encodeIdent v & Aeson.Object instance Aeson.FromJSON Entity where parseJSON = decodeVariant "entity" [ ("def", fmap EntityDef . decodeDef) , ("tagOrder", fmap (uncurry EntityTag) . decodeNamedTag) , ("nom", fmap (\((tag, nomId), nom) -> EntityNominal tag nomId nom) . decodeTaggedNominal) , ("lamVar", fmap (uncurry EntityLamVar) . decodeTaggedLamVar) , ("openDefPane", fmap (EntityOpenDefPane . V.Var) . ((.: "openDefPane") >=> decodeIdent)) , ("schemaVersion", fmap EntitySchemaVersion . decodeSchemaVersion) ] array :: [Aeson.Value] -> Aeson.Value array = Aeson.Array . Vector.fromList encodePresentationMode :: Encoder Meta.PresentationMode encodePresentationMode Meta.Verbose = Aeson.String "Verbose" encodePresentationMode (Meta.Operator l r) = Aeson.object [("Operator", array [encodeTagId l, encodeTagId r])] decodePresentationMode :: Decoder Meta.PresentationMode decodePresentationMode (Aeson.String "Verbose") = pure Meta.Verbose decodePresentationMode x = decodeVariant "Type" [ ("Operator", \o -> o .: "Operator" >>= decodeOperator) ] x where decodeOperator = Aeson.withArray "array of Operator tags" $ \arr -> case Vector.toList arr of [l, r] -> Meta.Operator <$> decodeTagId l <*> decodeTagId r _ -> fail "Expecting two operator tags" encodeFFIName :: Encoder Definition.FFIName encodeFFIName (Definition.FFIName modulePath name) = modulePath ++ [name] & Aeson.toJSON decodeFFIName :: Decoder Definition.FFIName decodeFFIName = Aeson.withArray "array of FFIName components" $ \arr -> case Vector.toList arr of [] -> fail "Expecting at least one FFIName component" xs -> Definition.FFIName <$> traverse Aeson.parseJSON (init xs) <*> Aeson.parseJSON (last xs) encodeIdent :: Encoder Identifier encodeIdent = Aeson.toJSON . identHex toEither :: AesonTypes.Parser a -> Either String a toEither parser = AesonTypes.parseEither (\() -> parser) () fromEither :: Either String a -> AesonTypes.Parser a fromEither = either fail pure decodeIdent :: Decoder Identifier decodeIdent json = Aeson.parseJSON json <&> identFromHex >>= fromEither encodeIdentMap :: Aeson.ToJSON b => (k -> Identifier) -> (a -> b) -> Encoder (Map k a) encodeIdentMap getIdent encode m = m & Map.map encode & Map.mapKeys (identHex . getIdent) & Aeson.toJSON # ANN decodeIdentMap ( " HLint : ignore Use ^@ .. " : : String ) # decodeIdentMap :: (Aeson.FromJSON j, Ord k) => (Identifier -> k) -> (j -> AesonTypes.Parser a) -> Decoder (Map k a) decodeIdentMap fromIdent decode json = Aeson.parseJSON json <&> Map.toList >>= traverse (bitraverse (fmap fromIdent . fromEither . identFromHex) decode) <&> Map.fromList encodeSquash :: (Eq a, Monoid a, Aeson.ToJSON j) => Text -> (a -> j) -> a -> Aeson.Object encodeSquash name encode x | x == mempty = mempty | otherwise = Aeson.Key.fromText name ~~> Aeson.toJSON (encode x) -- | Parse object based on containing some traversal decodeVariantObj :: String -> [(Text, Aeson.Object -> AesonTypes.Parser r)] -> Aeson.Object -> AesonTypes.Parser r decodeVariantObj msg [] _ = "parseVariantObj of " <> msg <> " failed!" & fail decodeVariantObj msg ((field, parser):rest) obj | Lens.has (Lens.ix (Aeson.Key.fromText field)) obj = parser obj | otherwise = decodeVariantObj msg rest obj decodeVariant :: String -> [(Text, Aeson.Object -> AesonTypes.Parser r)] -> Aeson.Value -> AesonTypes.Parser r decodeVariant msg options (Aeson.Object obj) = decodeVariantObj msg options obj decodeVariant msg _ _ = "parseVariant of " <> msg <> " expected object!" & fail decodeSquashed :: (Aeson.FromJSON j, Monoid a) => Text -> (j -> AesonTypes.Parser a) -> Aeson.Object -> AesonTypes.Parser a decodeSquashed name decode o | Lens.has (Lens.ix (Aeson.Key.fromText name)) o = o .: Aeson.Key.fromText name >>= decode | otherwise = pure mempty encodeTagId :: Encoder T.Tag encodeTagId tag | tag == Anchors.anonTag = Aeson.Null | otherwise = T.tagName tag & encodeIdent decodeTagId :: Decoder T.Tag decodeTagId Aeson.Null = pure Anchors.anonTag decodeTagId json = decodeIdent json <&> T.Tag jsum :: [AesonTypes.Parser a] -> AesonTypes.Parser a jsum parsers = parsers <&> toEither <&> swapEither & sequence <&> unlines & swapEither & fromEither where swapEither (Left x) = Right x swapEither (Right x) = Left x encodeComposite :: Encoder (Pure # T.Row) encodeComposite = array . go where go (Pure T.REmpty) = [] go (Pure (T.RVar (T.Var name))) = [Aeson.object [("rowVar", encodeIdent name)]] go (Pure (T.RExtend (RowExtend t v r))) = (encodeType v & _Object . Lens.at "rowTag" ?~ encodeTagId t) : go r decodeComposite :: Decoder (Pure # T.Row) decodeComposite (Aeson.Array vec) = case items ^? Lens._Snoc >>= _2 (^? _Object . Lens.ix "rowVar") of Just (elems, restVar) -> foldr field (decodeIdent restVar <&> Pure . T.RVar . T.Var) elems _ -> foldr field (Pure T.REmpty & pure) items where items = Vector.toList vec field x rest = Aeson.withObject "RowField" ?? x $ \o -> RowExtend <$> (o .: "rowTag" >>= decodeTagId) <*> decodeType x <*> rest <&> Pure . T.RExtend decodeComposite x = fail ("malformed row" <> show x) encodeType :: Encoder (Pure # T.Type) encodeType t = case t ^. _Pure of T.TFun (FuncType a b) -> "funcParam" ~~> encodeType a <> "funcResult" ~~> encodeType b T.TRecord composite -> "record" ~~> encodeComposite composite T.TVariant composite -> "variant" ~~> encodeComposite composite T.TVar (T.Var name) -> "typeVar" ~~> encodeIdent name T.TInst (NominalInst tId params) -> "nomId" ~~> encodeIdent (T.nomId tId) <> encodeSquash "nomTypeArgs" (encodeIdentMap T.tvName encodeType) (params ^. T.tType . _QVarInstances) <> encodeSquash "nomRowArgs" (encodeIdentMap T.tvName encodeComposite) (params ^. T.tRow . _QVarInstances) & Aeson.Object decodeType :: Decoder (Pure # T.Type) decodeType json = Aeson.withObject "Type" ?? json $ \o -> jsum [ FuncType <$> (o .: "funcParam" >>= decodeType) <*> (o .: "funcResult" >>= decodeType) <&> T.TFun , o .: "record" >>= decodeComposite <&> T.TRecord , o .: "variant" >>= decodeComposite <&> T.TVariant , o .: "typeVar" >>= decodeIdent <&> T.Var <&> T.TVar , NominalInst <$> (o .: "nomId" >>= decodeIdent <&> T.NominalId) <*> (T.Types <$> (decodeSquashed "nomTypeArgs" (decodeIdentMap T.Var decodeType) o <&> QVarInstances) <*> (decodeSquashed "nomRowArgs" (decodeIdentMap T.Var decodeComposite) o <&> QVarInstances) ) <&> T.TInst ] <&> (_Pure #) encodeCompositeVarConstraints :: T.RConstraints -> [Aeson.Value] encodeCompositeVarConstraints (T.RowConstraints forbidden scopeLevel) | scopeLevel == mempty = forbidden ^.. Lens.folded <&> T.tagName <&> encodeIdent | otherwise = -- We only encode top-level types, no skolem escape considerations... error "encodeCompositeVarConstraints does not support inner-scoped types" decodeCompositeConstraints :: [Aeson.Value] -> AesonTypes.Parser T.RConstraints decodeCompositeConstraints json = traverse decodeIdent json <&> map T.Tag <&> Set.fromList <&> (`T.RowConstraints` mempty) encodeTypeVars :: T.Types # QVars -> Aeson.Object encodeTypeVars (T.Types (QVars tvs) (QVars rvs)) = encodeSquash "typeVars" (Aeson.toJSON . map (encodeIdent . T.tvName)) (tvs ^.. Lens.itraversed . Lens.asIndex) <> encodeSquash "rowVars" (encodeIdentMap T.tvName encodeCompositeVarConstraints) rvs decodeTypeVars :: Aeson.Object -> AesonTypes.Parser (T.Types # QVars) decodeTypeVars obj = T.Types <$> ( decodeSquashed "typeVars" ( \tvs -> Aeson.parseJSON tvs >>= traverse decodeIdent <&> map (\name -> (T.Var name, mempty)) <&> Map.fromList ) obj <&> QVars ) <*> (decodeSquashed "rowVars" (decodeIdentMap T.Var decodeCompositeConstraints) obj <&> QVars) encodeScheme :: Encoder (Pure # T.Scheme) encodeScheme (Pure (Scheme tvs typ)) = "schemeType" ~~> encodeType typ <> encodeTypeVars tvs & Aeson.Object decodeScheme :: Decoder (Pure # T.Scheme) decodeScheme = Aeson.withObject "scheme" $ \obj -> do tvs <- decodeTypeVars obj typ <- obj .: "schemeType" >>= decodeType _Pure # Scheme tvs typ & pure encodeLeaf :: V.Leaf -> Aeson.Object encodeLeaf = \case V.LHole -> l "hole" V.LRecEmpty -> l "recEmpty" V.LAbsurd -> l "absurd" V.LVar (V.Var var) -> "var" ~~> encodeIdent var V.LLiteral (V.PrimVal (T.NominalId primId) primBytes) -> "primId" ~~> encodeIdent primId <> "primBytes" ~~> Aeson.toJSON (BS.unpack (Hex.encode primBytes)) V.LFromNom (T.NominalId nomId) -> "fromNomId" ~~> encodeIdent nomId V.LGetField tag -> "getField" ~~> encodeTagId tag V.LInject tag -> "inject" ~~> encodeTagId tag where l x = x ~~> Aeson.object [] decodeLeaf :: Aeson.Object -> AesonTypes.Parser V.Leaf decodeLeaf = decodeVariantObj "leaf" [ l "hole" V.LHole , l "recEmpty" V.LRecEmpty , l "absurd" V.LAbsurd , f "var" (fmap (V.LVar . V.Var) . decodeIdent) , f "fromNomId" (fmap (V.LFromNom . T.NominalId) . decodeIdent) , f "getField" (fmap V.LGetField . decodeTagId) , f "inject" (fmap V.LInject . decodeTagId) , ("primId", \obj -> do primId <- obj .: "primId" >>= decodeIdent <&> T.NominalId bytesHex <- obj .: "primBytes" primBytes <- Hex.decode (BS.pack bytesHex) & fromEither V.PrimVal primId primBytes & pure <&> V.LLiteral ) ] where l key v = ( key , \obj -> obj .: Aeson.Key.fromText key >>= \case Aeson.Object x | x == mempty -> pure v x -> fail ("bad val for leaf " ++ show x) ) f key v = (key, \o -> o .: Aeson.Key.fromText key >>= v) encodeVal :: Codec h => Encoder (Ann (Const UUID) # h) encodeVal (Ann uuid body) = encodeBody body & insertField "id" uuid & Aeson.Object class Codec h where decodeBody :: Aeson.Object -> AesonTypes.Parser (h # Annotated UUID) encodeBody :: h # Annotated UUID -> Aeson.Object decodeVal :: Codec h => Decoder (Ann (Const UUID) # h) decodeVal = Aeson.withObject "val" $ \obj -> Ann <$> (obj .: "id") <*> decodeBody obj instance Codec V.Term where encodeBody body = case encBody of V.BApp (V.App func arg) -> "applyFunc" ~~> c func <> "applyArg" ~~> c arg V.BLam (V.TypedLam (V.Var varId) paramType res) -> "lamVar" ~~> encodeIdent varId <> "lamParamType" ~~> c paramType <> "lamBody" ~~> c res V.BRecExtend (RowExtend tag x rest) -> "extendTag" ~~> encodeTagId tag <> "extendVal" ~~> c x <> "extendRest" ~~> c rest V.BCase (RowExtend tag handler restHandler) -> "caseTag" ~~> encodeTagId tag <> "caseHandler" ~~> c handler <> "caseRest" ~~> c restHandler V.BToNom (ToNom (T.NominalId nomId) x) -> "toNomId" ~~> encodeIdent nomId <> "toNomVal" ~~> c x V.BLeaf x -> encodeLeaf x where encBody :: V.Term # Const Aeson.Value encBody = hmap (Proxy @Codec #> Const . encodeVal) body c x = x ^. Lens._Wrapped decodeBody obj = jsum [ V.App <$> (obj .: "applyFunc" <&> c) <*> (obj .: "applyArg" <&> c) <&> V.BApp , V.TypedLam <$> (obj .: "lamVar" >>= decodeIdent <&> V.Var) <*> (obj .: "lamParamType" <&> c) <*> (obj .: "lamBody" <&> c) <&> V.BLam , RowExtend <$> (obj .: "extendTag" >>= decodeTagId) <*> (obj .: "extendVal" <&> c) <*> (obj .: "extendRest" <&> c) <&> V.BRecExtend , RowExtend <$> (obj .: "caseTag" >>= decodeTagId) <*> (obj .: "caseHandler" <&> c) <*> (obj .: "caseRest" <&> c) <&> V.BCase , ToNom <$> (obj .: "toNomId" >>= decodeIdent <&> T.NominalId) <*> (obj .: "toNomVal" <&> c) <&> V.BToNom , decodeLeaf obj <&> V.BLeaf ] >>= htraverse (Proxy @Codec #> decodeVal . (^. Lens._Wrapped)) where c :: Aeson.Value -> Const Aeson.Value # n c = Const instance Codec (HCompose Prune T.Type) where decodeBody obj | (obj & Lens.at "id" .~ Nothing) == mempty = _HCompose # Pruned & pure | otherwise = obj .: "record" >>= \case Aeson.Array objs -> case traverse (^? _Object) objs >>= (^? Lens._Snoc) of Nothing -> fail "Malformed row fields" Just (fields, rTail) -> foldr extend (rTail .: "rowId" <&> Const <&> (`Ann` (hcomposed _Unpruned # T.REmpty))) fields where extend field rest = Ann <$> (field .: "rowId" <&> Const) <*> ( RowExtend <$> (field .: "rowTag" >>= decodeTagId) <*> (field .: "id" <&> Const <&> (`Ann` (_HCompose # Pruned)) <&> (_HCompose #)) <*> (rest <&> (_HCompose #)) <&> (hcomposed _Unpruned . T._RExtend #) ) _ -> fail "Malformed params record" <&> (hcomposed _Unpruned . T._TRecord . _HCompose #) encodeBody (HCompose Pruned) = mempty encodeBody (HCompose (Unpruned (HCompose (T.TRecord (HCompose row))))) = "record" ~~> array (go row) where go (Ann uuid (HCompose b)) = Aeson.Object (insertField "rowId" uuid x) : xs where (x, xs) = case b of Pruned -> (mempty, []) Unpruned (HCompose T.REmpty) -> (mempty, []) Unpruned (HCompose (T.RExtend (RowExtend t (HCompose (Ann fId (HCompose Pruned))) (HCompose r)))) -> ( "rowTag" ~~> encodeTagId t & insertField "id" fId , go r ) Unpruned _ -> error "TODO" encodeBody (HCompose (Unpruned _)) = error "TODO" encodeDefExpr :: Definition.Expr (Val UUID) -> Aeson.Object encodeDefExpr (Definition.Expr x frozenDeps) = "val" ~~> encodeVal x <> encodeSquash "frozenDeps" id encodedDeps where encodedDeps = encodeSquash "defTypes" (encodeIdentMap V.vvName encodeScheme) (frozenDeps ^. depsGlobalTypes) <> encodeSquash "nominals" (encodeIdentMap T.nomId encodeNominal) (frozenDeps ^. depsNominals) encodeDefBody :: Definition.Body (Val UUID) -> Aeson.Object encodeDefBody (Definition.BodyBuiltin name) = "builtin" ~~> encodeFFIName name encodeDefBody (Definition.BodyExpr defExpr) = encodeDefExpr defExpr decodeDefExpr :: Aeson.Object -> AesonTypes.Parser (Definition.Expr (Val UUID)) decodeDefExpr obj = Definition.Expr <$> (obj .: "val" >>= decodeVal) <*> decodeSquashed "frozenDeps" (Aeson.withObject "deps" decodeDeps) obj where decodeDeps o = Deps <$> decodeSquashed "defTypes" (decodeIdentMap V.Var decodeScheme) o <*> decodeSquashed "nominals" (decodeIdentMap T.NominalId decodeNominal) o decodeDefBody :: Aeson.Object -> AesonTypes.Parser (Definition.Body (Val UUID)) decodeDefBody obj = jsum [ obj .: "builtin" >>= decodeFFIName <&> Definition.BodyBuiltin , decodeDefExpr obj <&> Definition.BodyExpr ] insertField :: Aeson.ToJSON a => Key -> a -> Aeson.Object -> Aeson.Object insertField k v = Lens.at k ?~ Aeson.toJSON v encodeNominal :: Pure # NominalDecl T.Type -> Aeson.Object encodeNominal (Pure (NominalDecl params nominalType)) = "nomType" ~~> encodeScheme (_Pure # nominalType) <> encodeTypeVars params decodeNominal :: Aeson.Object -> AesonTypes.Parser (Pure # NominalDecl T.Type) decodeNominal obj = NominalDecl <$> decodeTypeVars obj <*> (obj .: "nomType" >>= decodeScheme <&> (^. _Pure)) <&> (_Pure #) encodeTagged :: Key -> (a -> Aeson.Object) -> ((T.Tag, Identifier), a) -> Aeson.Object encodeTagged idAttrName encoder ((tag, ident), x) = encoder x & insertField idAttrName (encodeIdent ident) & insertField "tag" (encodeTagId tag) decodeTagged :: Key -> (Aeson.Object -> AesonTypes.Parser a) -> Aeson.Object -> AesonTypes.Parser ((T.Tag, Identifier), a) decodeTagged idAttrName decoder obj = (,) <$> ( (,) <$> (obj .: "tag" >>= decodeTagId) <*> (obj .: idAttrName >>= decodeIdent) ) <*> decoder obj encodeDef :: Encoder (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) encodeDef (Definition body scheme (presentationMode, tag, V.Var globalId)) = encodeTagged "def" encodeDefBody ((tag, globalId), body) & insertField "typ" (encodeScheme scheme) & insertField "defPresentationMode" (encodePresentationMode presentationMode) & Aeson.Object decodeDef :: Aeson.Object -> AesonTypes.Parser (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) decodeDef obj = do ((tag, globalId), body) <- decodeTagged "def" decodeDefBody obj presentationMode <- obj .: "defPresentationMode" >>= decodePresentationMode scheme <- obj .: "typ" >>= decodeScheme Definition body scheme (presentationMode, tag, V.Var globalId) & pure encodeTagOrder :: TagOrder -> Aeson.Object encodeTagOrder tagOrder = "tagOrder" ~~> Aeson.toJSON tagOrder encodeSymbol :: Tag.Symbol -> Aeson.Object encodeSymbol Tag.NoSymbol = mempty encodeSymbol (Tag.UniversalSymbol x) = "op" ~~> Aeson.String x encodeSymbol (Tag.DirectionalSymbol (Tag.DirOp l r)) = "op" ~~> array [Aeson.String l, Aeson.String r] encodeNamedTag :: Encoder (T.Tag, Tag) encodeNamedTag (T.Tag ident, Tag order op names) = (encodeTagOrder order & insertField "tag" (encodeIdent ident)) <> encodeSquash "names" id names <> encodeSymbol op & Aeson.Object decodeSymbol :: Maybe Aeson.Value -> AesonTypes.Parser Tag.Symbol decodeSymbol Nothing = pure Tag.NoSymbol decodeSymbol (Just (Aeson.String x)) = Tag.UniversalSymbol x & pure decodeSymbol (Just (Aeson.Array x)) = case x ^.. traverse of [Aeson.String l, Aeson.String r] -> Tag.DirOp l r & Tag.DirectionalSymbol & pure _ -> fail ("unexpected op names:" <> show x) decodeSymbol x = fail ("unexpected op name: " <> show x) decodeNamedTag :: Aeson.Object -> AesonTypes.Parser (T.Tag, Tag) decodeNamedTag obj = (,) <$> (obj .: "tag" >>= decodeIdent <&> T.Tag) <*> ( Tag <$> (obj .: "tagOrder") <*> decodeSymbol (obj ^. Lens.at "op") <*> decodeSquashed "names" Aeson.parseJSON obj ) encodeTaggedLamVar :: Encoder (T.Tag, V.Var) encodeTaggedLamVar (tag, V.Var ident) = encodeTagged "lamVar" mempty ((tag, ident), ()) & Aeson.Object decodeTaggedLamVar :: Aeson.Object -> AesonTypes.Parser (T.Tag, V.Var) decodeTaggedLamVar json = decodeTagged "lamVar" (\_ -> pure ()) json <&> \((tag, ident), ()) -> (tag, V.Var ident) encodeTaggedNominal :: Encoder ((T.Tag, T.NominalId), Either (T.Types # QVars) (Pure # NominalDecl T.Type)) encodeTaggedNominal ((tag, T.NominalId nomId), nom) = either encodeTypeVars encodeNominal nom & Lens.at "nom" ?~ encodeIdent nomId & Lens.at "tag" ?~ encodeTagId tag & Aeson.Object decodeTaggedNominal :: Aeson.Object -> AesonTypes.Parser ((T.Tag, T.NominalId), Either (T.Types # QVars) (Pure # NominalDecl T.Type)) decodeTaggedNominal json = decodeTagged "nom" decodeMNom json <&> _1 . _2 %~ T.NominalId where decodeMNom x = jsum [ decodeNominal x <&> Right , decodeTypeVars x <&> Left ] encodeSchemaVersion :: Encoder Version encodeSchemaVersion (Version ver) = "schemaVersion" ~~> Aeson.toJSON ver & Aeson.Object decodeSchemaVersion :: Aeson.Object -> AesonTypes.Parser Version decodeSchemaVersion = (.: "schemaVersion") <&> fmap Version
null
https://raw.githubusercontent.com/lamdu/lamdu/e9e54b0e37cb121fe4bd761ba555b841011fd60b/src/Lamdu/Data/Export/JSON/Codec.hs
haskell
| Parse object based on containing some traversal We only encode top-level types, no skolem escape considerations...
| JSON encoder / decoder for types # LANGUAGE TemplateHaskell , TypeFamilies , TypeApplications , FlexibleInstances # module Lamdu.Data.Export.JSON.Codec ( TagOrder , Version(..) , Entity(..), _EntitySchemaVersion, _EntityDef, _EntityTag, _EntityNominal, _EntityLamVar ) where import qualified Control.Lens as Lens import Control.Lens.Extended ((~~>)) import Control.Monad ((>=>)) import Data.Aeson ((.:)) import qualified Data.Aeson as Aeson import Data.Aeson.Key (Key) import qualified Data.Aeson.Key as Aeson.Key import Data.Aeson.Lens (_Object) import qualified Data.Aeson.Types as AesonTypes import Data.Bitraversable (Bitraversable(..)) import qualified Data.ByteString.Base16 as Hex import qualified Data.ByteString.Char8 as BS import qualified Data.Map as Map import qualified Data.Set as Set import Data.UUID.Types (UUID) import qualified Data.Vector as Vector import Hyper import Hyper.Syntax (FuncType(..)) import Hyper.Syntax.Nominal (ToNom(..), NominalDecl(..), NominalInst(..)) import Hyper.Syntax.Row (RowExtend(..)) import Hyper.Syntax.Scheme (Scheme(..), QVars(..), QVarInstances(..), _QVarInstances) import Hyper.Type.Prune (Prune(..), _Unpruned) import Lamdu.Calc.Definition import Lamdu.Calc.Identifier (Identifier, identHex, identFromHex) import Lamdu.Calc.Term (Val) import qualified Lamdu.Calc.Term as V import qualified Lamdu.Calc.Type as T import qualified Lamdu.Data.Anchors as Anchors import Lamdu.Data.Definition (Definition(..)) import qualified Lamdu.Data.Definition as Definition import qualified Lamdu.Data.Meta as Meta import Lamdu.Data.Tag (Tag(..)) import qualified Lamdu.Data.Tag as Tag import Lamdu.Prelude hiding ((.=)) type Encoder a = a -> Aeson.Value type Decoder a = Aeson.Value -> AesonTypes.Parser a type TagOrder = Int newtype Version = Version Int deriving stock (Eq, Ord, Show) data Entity = EntitySchemaVersion Version | EntityDef (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) | EntityTag T.Tag Tag | EntityNominal T.Tag T.NominalId (Either (T.Types # QVars) (Pure # NominalDecl T.Type)) | EntityLamVar T.Tag V.Var | EntityOpenDefPane V.Var Lens.makePrisms ''Entity instance Aeson.ToJSON Entity where toJSON (EntitySchemaVersion ver) = encodeSchemaVersion ver toJSON (EntityDef def) = encodeDef def toJSON (EntityTag tid tdata) = encodeNamedTag (tid, tdata) toJSON (EntityNominal tag nomId nom) = encodeTaggedNominal ((tag, nomId), nom) toJSON (EntityLamVar tag var) = encodeTaggedLamVar (tag, var) toJSON (EntityOpenDefPane (V.Var v)) = "openDefPane" ~~> encodeIdent v & Aeson.Object instance Aeson.FromJSON Entity where parseJSON = decodeVariant "entity" [ ("def", fmap EntityDef . decodeDef) , ("tagOrder", fmap (uncurry EntityTag) . decodeNamedTag) , ("nom", fmap (\((tag, nomId), nom) -> EntityNominal tag nomId nom) . decodeTaggedNominal) , ("lamVar", fmap (uncurry EntityLamVar) . decodeTaggedLamVar) , ("openDefPane", fmap (EntityOpenDefPane . V.Var) . ((.: "openDefPane") >=> decodeIdent)) , ("schemaVersion", fmap EntitySchemaVersion . decodeSchemaVersion) ] array :: [Aeson.Value] -> Aeson.Value array = Aeson.Array . Vector.fromList encodePresentationMode :: Encoder Meta.PresentationMode encodePresentationMode Meta.Verbose = Aeson.String "Verbose" encodePresentationMode (Meta.Operator l r) = Aeson.object [("Operator", array [encodeTagId l, encodeTagId r])] decodePresentationMode :: Decoder Meta.PresentationMode decodePresentationMode (Aeson.String "Verbose") = pure Meta.Verbose decodePresentationMode x = decodeVariant "Type" [ ("Operator", \o -> o .: "Operator" >>= decodeOperator) ] x where decodeOperator = Aeson.withArray "array of Operator tags" $ \arr -> case Vector.toList arr of [l, r] -> Meta.Operator <$> decodeTagId l <*> decodeTagId r _ -> fail "Expecting two operator tags" encodeFFIName :: Encoder Definition.FFIName encodeFFIName (Definition.FFIName modulePath name) = modulePath ++ [name] & Aeson.toJSON decodeFFIName :: Decoder Definition.FFIName decodeFFIName = Aeson.withArray "array of FFIName components" $ \arr -> case Vector.toList arr of [] -> fail "Expecting at least one FFIName component" xs -> Definition.FFIName <$> traverse Aeson.parseJSON (init xs) <*> Aeson.parseJSON (last xs) encodeIdent :: Encoder Identifier encodeIdent = Aeson.toJSON . identHex toEither :: AesonTypes.Parser a -> Either String a toEither parser = AesonTypes.parseEither (\() -> parser) () fromEither :: Either String a -> AesonTypes.Parser a fromEither = either fail pure decodeIdent :: Decoder Identifier decodeIdent json = Aeson.parseJSON json <&> identFromHex >>= fromEither encodeIdentMap :: Aeson.ToJSON b => (k -> Identifier) -> (a -> b) -> Encoder (Map k a) encodeIdentMap getIdent encode m = m & Map.map encode & Map.mapKeys (identHex . getIdent) & Aeson.toJSON # ANN decodeIdentMap ( " HLint : ignore Use ^@ .. " : : String ) # decodeIdentMap :: (Aeson.FromJSON j, Ord k) => (Identifier -> k) -> (j -> AesonTypes.Parser a) -> Decoder (Map k a) decodeIdentMap fromIdent decode json = Aeson.parseJSON json <&> Map.toList >>= traverse (bitraverse (fmap fromIdent . fromEither . identFromHex) decode) <&> Map.fromList encodeSquash :: (Eq a, Monoid a, Aeson.ToJSON j) => Text -> (a -> j) -> a -> Aeson.Object encodeSquash name encode x | x == mempty = mempty | otherwise = Aeson.Key.fromText name ~~> Aeson.toJSON (encode x) decodeVariantObj :: String -> [(Text, Aeson.Object -> AesonTypes.Parser r)] -> Aeson.Object -> AesonTypes.Parser r decodeVariantObj msg [] _ = "parseVariantObj of " <> msg <> " failed!" & fail decodeVariantObj msg ((field, parser):rest) obj | Lens.has (Lens.ix (Aeson.Key.fromText field)) obj = parser obj | otherwise = decodeVariantObj msg rest obj decodeVariant :: String -> [(Text, Aeson.Object -> AesonTypes.Parser r)] -> Aeson.Value -> AesonTypes.Parser r decodeVariant msg options (Aeson.Object obj) = decodeVariantObj msg options obj decodeVariant msg _ _ = "parseVariant of " <> msg <> " expected object!" & fail decodeSquashed :: (Aeson.FromJSON j, Monoid a) => Text -> (j -> AesonTypes.Parser a) -> Aeson.Object -> AesonTypes.Parser a decodeSquashed name decode o | Lens.has (Lens.ix (Aeson.Key.fromText name)) o = o .: Aeson.Key.fromText name >>= decode | otherwise = pure mempty encodeTagId :: Encoder T.Tag encodeTagId tag | tag == Anchors.anonTag = Aeson.Null | otherwise = T.tagName tag & encodeIdent decodeTagId :: Decoder T.Tag decodeTagId Aeson.Null = pure Anchors.anonTag decodeTagId json = decodeIdent json <&> T.Tag jsum :: [AesonTypes.Parser a] -> AesonTypes.Parser a jsum parsers = parsers <&> toEither <&> swapEither & sequence <&> unlines & swapEither & fromEither where swapEither (Left x) = Right x swapEither (Right x) = Left x encodeComposite :: Encoder (Pure # T.Row) encodeComposite = array . go where go (Pure T.REmpty) = [] go (Pure (T.RVar (T.Var name))) = [Aeson.object [("rowVar", encodeIdent name)]] go (Pure (T.RExtend (RowExtend t v r))) = (encodeType v & _Object . Lens.at "rowTag" ?~ encodeTagId t) : go r decodeComposite :: Decoder (Pure # T.Row) decodeComposite (Aeson.Array vec) = case items ^? Lens._Snoc >>= _2 (^? _Object . Lens.ix "rowVar") of Just (elems, restVar) -> foldr field (decodeIdent restVar <&> Pure . T.RVar . T.Var) elems _ -> foldr field (Pure T.REmpty & pure) items where items = Vector.toList vec field x rest = Aeson.withObject "RowField" ?? x $ \o -> RowExtend <$> (o .: "rowTag" >>= decodeTagId) <*> decodeType x <*> rest <&> Pure . T.RExtend decodeComposite x = fail ("malformed row" <> show x) encodeType :: Encoder (Pure # T.Type) encodeType t = case t ^. _Pure of T.TFun (FuncType a b) -> "funcParam" ~~> encodeType a <> "funcResult" ~~> encodeType b T.TRecord composite -> "record" ~~> encodeComposite composite T.TVariant composite -> "variant" ~~> encodeComposite composite T.TVar (T.Var name) -> "typeVar" ~~> encodeIdent name T.TInst (NominalInst tId params) -> "nomId" ~~> encodeIdent (T.nomId tId) <> encodeSquash "nomTypeArgs" (encodeIdentMap T.tvName encodeType) (params ^. T.tType . _QVarInstances) <> encodeSquash "nomRowArgs" (encodeIdentMap T.tvName encodeComposite) (params ^. T.tRow . _QVarInstances) & Aeson.Object decodeType :: Decoder (Pure # T.Type) decodeType json = Aeson.withObject "Type" ?? json $ \o -> jsum [ FuncType <$> (o .: "funcParam" >>= decodeType) <*> (o .: "funcResult" >>= decodeType) <&> T.TFun , o .: "record" >>= decodeComposite <&> T.TRecord , o .: "variant" >>= decodeComposite <&> T.TVariant , o .: "typeVar" >>= decodeIdent <&> T.Var <&> T.TVar , NominalInst <$> (o .: "nomId" >>= decodeIdent <&> T.NominalId) <*> (T.Types <$> (decodeSquashed "nomTypeArgs" (decodeIdentMap T.Var decodeType) o <&> QVarInstances) <*> (decodeSquashed "nomRowArgs" (decodeIdentMap T.Var decodeComposite) o <&> QVarInstances) ) <&> T.TInst ] <&> (_Pure #) encodeCompositeVarConstraints :: T.RConstraints -> [Aeson.Value] encodeCompositeVarConstraints (T.RowConstraints forbidden scopeLevel) | scopeLevel == mempty = forbidden ^.. Lens.folded <&> T.tagName <&> encodeIdent | otherwise = error "encodeCompositeVarConstraints does not support inner-scoped types" decodeCompositeConstraints :: [Aeson.Value] -> AesonTypes.Parser T.RConstraints decodeCompositeConstraints json = traverse decodeIdent json <&> map T.Tag <&> Set.fromList <&> (`T.RowConstraints` mempty) encodeTypeVars :: T.Types # QVars -> Aeson.Object encodeTypeVars (T.Types (QVars tvs) (QVars rvs)) = encodeSquash "typeVars" (Aeson.toJSON . map (encodeIdent . T.tvName)) (tvs ^.. Lens.itraversed . Lens.asIndex) <> encodeSquash "rowVars" (encodeIdentMap T.tvName encodeCompositeVarConstraints) rvs decodeTypeVars :: Aeson.Object -> AesonTypes.Parser (T.Types # QVars) decodeTypeVars obj = T.Types <$> ( decodeSquashed "typeVars" ( \tvs -> Aeson.parseJSON tvs >>= traverse decodeIdent <&> map (\name -> (T.Var name, mempty)) <&> Map.fromList ) obj <&> QVars ) <*> (decodeSquashed "rowVars" (decodeIdentMap T.Var decodeCompositeConstraints) obj <&> QVars) encodeScheme :: Encoder (Pure # T.Scheme) encodeScheme (Pure (Scheme tvs typ)) = "schemeType" ~~> encodeType typ <> encodeTypeVars tvs & Aeson.Object decodeScheme :: Decoder (Pure # T.Scheme) decodeScheme = Aeson.withObject "scheme" $ \obj -> do tvs <- decodeTypeVars obj typ <- obj .: "schemeType" >>= decodeType _Pure # Scheme tvs typ & pure encodeLeaf :: V.Leaf -> Aeson.Object encodeLeaf = \case V.LHole -> l "hole" V.LRecEmpty -> l "recEmpty" V.LAbsurd -> l "absurd" V.LVar (V.Var var) -> "var" ~~> encodeIdent var V.LLiteral (V.PrimVal (T.NominalId primId) primBytes) -> "primId" ~~> encodeIdent primId <> "primBytes" ~~> Aeson.toJSON (BS.unpack (Hex.encode primBytes)) V.LFromNom (T.NominalId nomId) -> "fromNomId" ~~> encodeIdent nomId V.LGetField tag -> "getField" ~~> encodeTagId tag V.LInject tag -> "inject" ~~> encodeTagId tag where l x = x ~~> Aeson.object [] decodeLeaf :: Aeson.Object -> AesonTypes.Parser V.Leaf decodeLeaf = decodeVariantObj "leaf" [ l "hole" V.LHole , l "recEmpty" V.LRecEmpty , l "absurd" V.LAbsurd , f "var" (fmap (V.LVar . V.Var) . decodeIdent) , f "fromNomId" (fmap (V.LFromNom . T.NominalId) . decodeIdent) , f "getField" (fmap V.LGetField . decodeTagId) , f "inject" (fmap V.LInject . decodeTagId) , ("primId", \obj -> do primId <- obj .: "primId" >>= decodeIdent <&> T.NominalId bytesHex <- obj .: "primBytes" primBytes <- Hex.decode (BS.pack bytesHex) & fromEither V.PrimVal primId primBytes & pure <&> V.LLiteral ) ] where l key v = ( key , \obj -> obj .: Aeson.Key.fromText key >>= \case Aeson.Object x | x == mempty -> pure v x -> fail ("bad val for leaf " ++ show x) ) f key v = (key, \o -> o .: Aeson.Key.fromText key >>= v) encodeVal :: Codec h => Encoder (Ann (Const UUID) # h) encodeVal (Ann uuid body) = encodeBody body & insertField "id" uuid & Aeson.Object class Codec h where decodeBody :: Aeson.Object -> AesonTypes.Parser (h # Annotated UUID) encodeBody :: h # Annotated UUID -> Aeson.Object decodeVal :: Codec h => Decoder (Ann (Const UUID) # h) decodeVal = Aeson.withObject "val" $ \obj -> Ann <$> (obj .: "id") <*> decodeBody obj instance Codec V.Term where encodeBody body = case encBody of V.BApp (V.App func arg) -> "applyFunc" ~~> c func <> "applyArg" ~~> c arg V.BLam (V.TypedLam (V.Var varId) paramType res) -> "lamVar" ~~> encodeIdent varId <> "lamParamType" ~~> c paramType <> "lamBody" ~~> c res V.BRecExtend (RowExtend tag x rest) -> "extendTag" ~~> encodeTagId tag <> "extendVal" ~~> c x <> "extendRest" ~~> c rest V.BCase (RowExtend tag handler restHandler) -> "caseTag" ~~> encodeTagId tag <> "caseHandler" ~~> c handler <> "caseRest" ~~> c restHandler V.BToNom (ToNom (T.NominalId nomId) x) -> "toNomId" ~~> encodeIdent nomId <> "toNomVal" ~~> c x V.BLeaf x -> encodeLeaf x where encBody :: V.Term # Const Aeson.Value encBody = hmap (Proxy @Codec #> Const . encodeVal) body c x = x ^. Lens._Wrapped decodeBody obj = jsum [ V.App <$> (obj .: "applyFunc" <&> c) <*> (obj .: "applyArg" <&> c) <&> V.BApp , V.TypedLam <$> (obj .: "lamVar" >>= decodeIdent <&> V.Var) <*> (obj .: "lamParamType" <&> c) <*> (obj .: "lamBody" <&> c) <&> V.BLam , RowExtend <$> (obj .: "extendTag" >>= decodeTagId) <*> (obj .: "extendVal" <&> c) <*> (obj .: "extendRest" <&> c) <&> V.BRecExtend , RowExtend <$> (obj .: "caseTag" >>= decodeTagId) <*> (obj .: "caseHandler" <&> c) <*> (obj .: "caseRest" <&> c) <&> V.BCase , ToNom <$> (obj .: "toNomId" >>= decodeIdent <&> T.NominalId) <*> (obj .: "toNomVal" <&> c) <&> V.BToNom , decodeLeaf obj <&> V.BLeaf ] >>= htraverse (Proxy @Codec #> decodeVal . (^. Lens._Wrapped)) where c :: Aeson.Value -> Const Aeson.Value # n c = Const instance Codec (HCompose Prune T.Type) where decodeBody obj | (obj & Lens.at "id" .~ Nothing) == mempty = _HCompose # Pruned & pure | otherwise = obj .: "record" >>= \case Aeson.Array objs -> case traverse (^? _Object) objs >>= (^? Lens._Snoc) of Nothing -> fail "Malformed row fields" Just (fields, rTail) -> foldr extend (rTail .: "rowId" <&> Const <&> (`Ann` (hcomposed _Unpruned # T.REmpty))) fields where extend field rest = Ann <$> (field .: "rowId" <&> Const) <*> ( RowExtend <$> (field .: "rowTag" >>= decodeTagId) <*> (field .: "id" <&> Const <&> (`Ann` (_HCompose # Pruned)) <&> (_HCompose #)) <*> (rest <&> (_HCompose #)) <&> (hcomposed _Unpruned . T._RExtend #) ) _ -> fail "Malformed params record" <&> (hcomposed _Unpruned . T._TRecord . _HCompose #) encodeBody (HCompose Pruned) = mempty encodeBody (HCompose (Unpruned (HCompose (T.TRecord (HCompose row))))) = "record" ~~> array (go row) where go (Ann uuid (HCompose b)) = Aeson.Object (insertField "rowId" uuid x) : xs where (x, xs) = case b of Pruned -> (mempty, []) Unpruned (HCompose T.REmpty) -> (mempty, []) Unpruned (HCompose (T.RExtend (RowExtend t (HCompose (Ann fId (HCompose Pruned))) (HCompose r)))) -> ( "rowTag" ~~> encodeTagId t & insertField "id" fId , go r ) Unpruned _ -> error "TODO" encodeBody (HCompose (Unpruned _)) = error "TODO" encodeDefExpr :: Definition.Expr (Val UUID) -> Aeson.Object encodeDefExpr (Definition.Expr x frozenDeps) = "val" ~~> encodeVal x <> encodeSquash "frozenDeps" id encodedDeps where encodedDeps = encodeSquash "defTypes" (encodeIdentMap V.vvName encodeScheme) (frozenDeps ^. depsGlobalTypes) <> encodeSquash "nominals" (encodeIdentMap T.nomId encodeNominal) (frozenDeps ^. depsNominals) encodeDefBody :: Definition.Body (Val UUID) -> Aeson.Object encodeDefBody (Definition.BodyBuiltin name) = "builtin" ~~> encodeFFIName name encodeDefBody (Definition.BodyExpr defExpr) = encodeDefExpr defExpr decodeDefExpr :: Aeson.Object -> AesonTypes.Parser (Definition.Expr (Val UUID)) decodeDefExpr obj = Definition.Expr <$> (obj .: "val" >>= decodeVal) <*> decodeSquashed "frozenDeps" (Aeson.withObject "deps" decodeDeps) obj where decodeDeps o = Deps <$> decodeSquashed "defTypes" (decodeIdentMap V.Var decodeScheme) o <*> decodeSquashed "nominals" (decodeIdentMap T.NominalId decodeNominal) o decodeDefBody :: Aeson.Object -> AesonTypes.Parser (Definition.Body (Val UUID)) decodeDefBody obj = jsum [ obj .: "builtin" >>= decodeFFIName <&> Definition.BodyBuiltin , decodeDefExpr obj <&> Definition.BodyExpr ] insertField :: Aeson.ToJSON a => Key -> a -> Aeson.Object -> Aeson.Object insertField k v = Lens.at k ?~ Aeson.toJSON v encodeNominal :: Pure # NominalDecl T.Type -> Aeson.Object encodeNominal (Pure (NominalDecl params nominalType)) = "nomType" ~~> encodeScheme (_Pure # nominalType) <> encodeTypeVars params decodeNominal :: Aeson.Object -> AesonTypes.Parser (Pure # NominalDecl T.Type) decodeNominal obj = NominalDecl <$> decodeTypeVars obj <*> (obj .: "nomType" >>= decodeScheme <&> (^. _Pure)) <&> (_Pure #) encodeTagged :: Key -> (a -> Aeson.Object) -> ((T.Tag, Identifier), a) -> Aeson.Object encodeTagged idAttrName encoder ((tag, ident), x) = encoder x & insertField idAttrName (encodeIdent ident) & insertField "tag" (encodeTagId tag) decodeTagged :: Key -> (Aeson.Object -> AesonTypes.Parser a) -> Aeson.Object -> AesonTypes.Parser ((T.Tag, Identifier), a) decodeTagged idAttrName decoder obj = (,) <$> ( (,) <$> (obj .: "tag" >>= decodeTagId) <*> (obj .: idAttrName >>= decodeIdent) ) <*> decoder obj encodeDef :: Encoder (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) encodeDef (Definition body scheme (presentationMode, tag, V.Var globalId)) = encodeTagged "def" encodeDefBody ((tag, globalId), body) & insertField "typ" (encodeScheme scheme) & insertField "defPresentationMode" (encodePresentationMode presentationMode) & Aeson.Object decodeDef :: Aeson.Object -> AesonTypes.Parser (Definition (Val UUID) (Meta.PresentationMode, T.Tag, V.Var)) decodeDef obj = do ((tag, globalId), body) <- decodeTagged "def" decodeDefBody obj presentationMode <- obj .: "defPresentationMode" >>= decodePresentationMode scheme <- obj .: "typ" >>= decodeScheme Definition body scheme (presentationMode, tag, V.Var globalId) & pure encodeTagOrder :: TagOrder -> Aeson.Object encodeTagOrder tagOrder = "tagOrder" ~~> Aeson.toJSON tagOrder encodeSymbol :: Tag.Symbol -> Aeson.Object encodeSymbol Tag.NoSymbol = mempty encodeSymbol (Tag.UniversalSymbol x) = "op" ~~> Aeson.String x encodeSymbol (Tag.DirectionalSymbol (Tag.DirOp l r)) = "op" ~~> array [Aeson.String l, Aeson.String r] encodeNamedTag :: Encoder (T.Tag, Tag) encodeNamedTag (T.Tag ident, Tag order op names) = (encodeTagOrder order & insertField "tag" (encodeIdent ident)) <> encodeSquash "names" id names <> encodeSymbol op & Aeson.Object decodeSymbol :: Maybe Aeson.Value -> AesonTypes.Parser Tag.Symbol decodeSymbol Nothing = pure Tag.NoSymbol decodeSymbol (Just (Aeson.String x)) = Tag.UniversalSymbol x & pure decodeSymbol (Just (Aeson.Array x)) = case x ^.. traverse of [Aeson.String l, Aeson.String r] -> Tag.DirOp l r & Tag.DirectionalSymbol & pure _ -> fail ("unexpected op names:" <> show x) decodeSymbol x = fail ("unexpected op name: " <> show x) decodeNamedTag :: Aeson.Object -> AesonTypes.Parser (T.Tag, Tag) decodeNamedTag obj = (,) <$> (obj .: "tag" >>= decodeIdent <&> T.Tag) <*> ( Tag <$> (obj .: "tagOrder") <*> decodeSymbol (obj ^. Lens.at "op") <*> decodeSquashed "names" Aeson.parseJSON obj ) encodeTaggedLamVar :: Encoder (T.Tag, V.Var) encodeTaggedLamVar (tag, V.Var ident) = encodeTagged "lamVar" mempty ((tag, ident), ()) & Aeson.Object decodeTaggedLamVar :: Aeson.Object -> AesonTypes.Parser (T.Tag, V.Var) decodeTaggedLamVar json = decodeTagged "lamVar" (\_ -> pure ()) json <&> \((tag, ident), ()) -> (tag, V.Var ident) encodeTaggedNominal :: Encoder ((T.Tag, T.NominalId), Either (T.Types # QVars) (Pure # NominalDecl T.Type)) encodeTaggedNominal ((tag, T.NominalId nomId), nom) = either encodeTypeVars encodeNominal nom & Lens.at "nom" ?~ encodeIdent nomId & Lens.at "tag" ?~ encodeTagId tag & Aeson.Object decodeTaggedNominal :: Aeson.Object -> AesonTypes.Parser ((T.Tag, T.NominalId), Either (T.Types # QVars) (Pure # NominalDecl T.Type)) decodeTaggedNominal json = decodeTagged "nom" decodeMNom json <&> _1 . _2 %~ T.NominalId where decodeMNom x = jsum [ decodeNominal x <&> Right , decodeTypeVars x <&> Left ] encodeSchemaVersion :: Encoder Version encodeSchemaVersion (Version ver) = "schemaVersion" ~~> Aeson.toJSON ver & Aeson.Object decodeSchemaVersion :: Aeson.Object -> AesonTypes.Parser Version decodeSchemaVersion = (.: "schemaVersion") <&> fmap Version
c7e9a607bd3381fedf27680b9b20ef2662245e567884b153d745f2027125cd16
imrehg/ypsilon
tree.scm
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk tree) (export gtk_tree_drag_dest_drag_data_received gtk_tree_drag_dest_get_type gtk_tree_drag_dest_row_drop_possible gtk_tree_drag_source_drag_data_delete gtk_tree_drag_source_drag_data_get gtk_tree_drag_source_get_type gtk_tree_drag_source_row_draggable gtk_tree_get_row_drag_data gtk_tree_iter_copy gtk_tree_iter_free gtk_tree_iter_get_type gtk_tree_model_filter_clear_cache gtk_tree_model_filter_convert_child_iter_to_iter gtk_tree_model_filter_convert_child_path_to_path gtk_tree_model_filter_convert_iter_to_child_iter gtk_tree_model_filter_convert_path_to_child_path gtk_tree_model_filter_get_model gtk_tree_model_filter_get_type gtk_tree_model_filter_new gtk_tree_model_filter_refilter gtk_tree_model_filter_set_modify_func gtk_tree_model_filter_set_visible_column gtk_tree_model_filter_set_visible_func gtk_tree_model_flags_get_type gtk_tree_model_foreach gtk_tree_model_get gtk_tree_model_get_column_type gtk_tree_model_get_flags gtk_tree_model_get_iter gtk_tree_model_get_iter_first gtk_tree_model_get_iter_from_string gtk_tree_model_get_n_columns gtk_tree_model_get_path gtk_tree_model_get_string_from_iter gtk_tree_model_get_type gtk_tree_model_get_valist gtk_tree_model_get_value gtk_tree_model_iter_children gtk_tree_model_iter_has_child gtk_tree_model_iter_n_children gtk_tree_model_iter_next gtk_tree_model_iter_nth_child gtk_tree_model_iter_parent gtk_tree_model_ref_node gtk_tree_model_row_changed gtk_tree_model_row_deleted gtk_tree_model_row_has_child_toggled gtk_tree_model_row_inserted gtk_tree_model_rows_reordered gtk_tree_model_sort_clear_cache gtk_tree_model_sort_convert_child_iter_to_iter gtk_tree_model_sort_convert_child_path_to_path gtk_tree_model_sort_convert_iter_to_child_iter gtk_tree_model_sort_convert_path_to_child_path gtk_tree_model_sort_get_model gtk_tree_model_sort_get_type gtk_tree_model_sort_iter_is_valid gtk_tree_model_sort_new_with_model gtk_tree_model_sort_reset_default_sort_func gtk_tree_model_unref_node gtk_tree_path_append_index gtk_tree_path_compare gtk_tree_path_copy gtk_tree_path_down gtk_tree_path_free gtk_tree_path_get_depth gtk_tree_path_get_indices gtk_tree_path_get_type gtk_tree_path_is_ancestor gtk_tree_path_is_descendant gtk_tree_path_new gtk_tree_path_new_first gtk_tree_path_new_from_indices gtk_tree_path_new_from_string gtk_tree_path_next gtk_tree_path_prepend_index gtk_tree_path_prev gtk_tree_path_to_string gtk_tree_path_up gtk_tree_row_reference_copy gtk_tree_row_reference_deleted gtk_tree_row_reference_free gtk_tree_row_reference_get_model gtk_tree_row_reference_get_path gtk_tree_row_reference_get_type gtk_tree_row_reference_inserted gtk_tree_row_reference_new gtk_tree_row_reference_new_proxy gtk_tree_row_reference_reordered gtk_tree_row_reference_valid gtk_tree_selection_count_selected_rows gtk_tree_selection_get_mode gtk_tree_selection_get_select_function gtk_tree_selection_get_selected gtk_tree_selection_get_selected_rows gtk_tree_selection_get_tree_view gtk_tree_selection_get_type gtk_tree_selection_get_user_data gtk_tree_selection_iter_is_selected gtk_tree_selection_path_is_selected gtk_tree_selection_select_all gtk_tree_selection_select_iter gtk_tree_selection_select_path gtk_tree_selection_select_range gtk_tree_selection_selected_foreach gtk_tree_selection_set_mode gtk_tree_selection_set_select_function gtk_tree_selection_unselect_all gtk_tree_selection_unselect_iter gtk_tree_selection_unselect_path gtk_tree_selection_unselect_range gtk_tree_set_row_drag_data gtk_tree_sortable_get_sort_column_id gtk_tree_sortable_get_type gtk_tree_sortable_has_default_sort_func gtk_tree_sortable_set_default_sort_func gtk_tree_sortable_set_sort_column_id gtk_tree_sortable_set_sort_func gtk_tree_sortable_sort_column_changed gtk_tree_store_append gtk_tree_store_clear gtk_tree_store_get_type gtk_tree_store_insert gtk_tree_store_insert_after gtk_tree_store_insert_before gtk_tree_store_insert_with_values gtk_tree_store_insert_with_valuesv gtk_tree_store_is_ancestor gtk_tree_store_iter_depth gtk_tree_store_iter_is_valid gtk_tree_store_move_after gtk_tree_store_move_before gtk_tree_store_new gtk_tree_store_newv gtk_tree_store_prepend gtk_tree_store_remove gtk_tree_store_reorder gtk_tree_store_set gtk_tree_store_set_column_types gtk_tree_store_set_valist gtk_tree_store_set_value gtk_tree_store_set_valuesv gtk_tree_store_swap gtk_tree_view_append_column gtk_tree_view_collapse_all gtk_tree_view_collapse_row gtk_tree_view_column_add_attribute gtk_tree_view_column_cell_get_position gtk_tree_view_column_cell_get_size gtk_tree_view_column_cell_is_visible gtk_tree_view_column_cell_set_cell_data gtk_tree_view_column_clear gtk_tree_view_column_clear_attributes gtk_tree_view_column_clicked gtk_tree_view_column_focus_cell gtk_tree_view_column_get_alignment gtk_tree_view_column_get_cell_renderers gtk_tree_view_column_get_clickable gtk_tree_view_column_get_expand gtk_tree_view_column_get_fixed_width gtk_tree_view_column_get_max_width gtk_tree_view_column_get_min_width gtk_tree_view_column_get_reorderable gtk_tree_view_column_get_resizable gtk_tree_view_column_get_sizing gtk_tree_view_column_get_sort_column_id gtk_tree_view_column_get_sort_indicator gtk_tree_view_column_get_sort_order gtk_tree_view_column_get_spacing gtk_tree_view_column_get_title gtk_tree_view_column_get_tree_view gtk_tree_view_column_get_type gtk_tree_view_column_get_visible gtk_tree_view_column_get_widget gtk_tree_view_column_get_width gtk_tree_view_column_new gtk_tree_view_column_new_with_attributes gtk_tree_view_column_pack_end gtk_tree_view_column_pack_start gtk_tree_view_column_queue_resize gtk_tree_view_column_set_alignment gtk_tree_view_column_set_attributes gtk_tree_view_column_set_cell_data_func gtk_tree_view_column_set_clickable gtk_tree_view_column_set_expand gtk_tree_view_column_set_fixed_width gtk_tree_view_column_set_max_width gtk_tree_view_column_set_min_width gtk_tree_view_column_set_reorderable gtk_tree_view_column_set_resizable gtk_tree_view_column_set_sizing gtk_tree_view_column_set_sort_column_id gtk_tree_view_column_set_sort_indicator gtk_tree_view_column_set_sort_order gtk_tree_view_column_set_spacing gtk_tree_view_column_set_title gtk_tree_view_column_set_visible gtk_tree_view_column_set_widget gtk_tree_view_column_sizing_get_type gtk_tree_view_columns_autosize gtk_tree_view_convert_bin_window_to_tree_coords gtk_tree_view_convert_bin_window_to_widget_coords gtk_tree_view_convert_tree_to_bin_window_coords gtk_tree_view_convert_tree_to_widget_coords gtk_tree_view_convert_widget_to_bin_window_coords gtk_tree_view_convert_widget_to_tree_coords gtk_tree_view_create_row_drag_icon gtk_tree_view_drop_position_get_type gtk_tree_view_enable_model_drag_dest gtk_tree_view_enable_model_drag_source gtk_tree_view_expand_all gtk_tree_view_expand_row gtk_tree_view_expand_to_path gtk_tree_view_get_background_area gtk_tree_view_get_bin_window gtk_tree_view_get_cell_area gtk_tree_view_get_column gtk_tree_view_get_columns gtk_tree_view_get_cursor gtk_tree_view_get_dest_row_at_pos gtk_tree_view_get_drag_dest_row gtk_tree_view_get_enable_search gtk_tree_view_get_enable_tree_lines gtk_tree_view_get_expander_column gtk_tree_view_get_fixed_height_mode gtk_tree_view_get_grid_lines gtk_tree_view_get_hadjustment gtk_tree_view_get_headers_clickable gtk_tree_view_get_headers_visible gtk_tree_view_get_hover_expand gtk_tree_view_get_hover_selection gtk_tree_view_get_level_indentation gtk_tree_view_get_model gtk_tree_view_get_path_at_pos gtk_tree_view_get_reorderable gtk_tree_view_get_row_separator_func gtk_tree_view_get_rubber_banding gtk_tree_view_get_rules_hint gtk_tree_view_get_search_column gtk_tree_view_get_search_entry gtk_tree_view_get_search_equal_func gtk_tree_view_get_search_position_func gtk_tree_view_get_selection gtk_tree_view_get_show_expanders gtk_tree_view_get_tooltip_column gtk_tree_view_get_tooltip_context gtk_tree_view_get_type gtk_tree_view_get_vadjustment gtk_tree_view_get_visible_range gtk_tree_view_get_visible_rect gtk_tree_view_grid_lines_get_type gtk_tree_view_insert_column gtk_tree_view_insert_column_with_attributes gtk_tree_view_insert_column_with_data_func gtk_tree_view_is_rubber_banding_active gtk_tree_view_map_expanded_rows gtk_tree_view_mode_get_type gtk_tree_view_move_column_after gtk_tree_view_new gtk_tree_view_new_with_model gtk_tree_view_remove_column gtk_tree_view_row_activated gtk_tree_view_row_expanded gtk_tree_view_scroll_to_cell gtk_tree_view_scroll_to_point gtk_tree_view_set_column_drag_function gtk_tree_view_set_cursor gtk_tree_view_set_cursor_on_cell gtk_tree_view_set_destroy_count_func gtk_tree_view_set_drag_dest_row gtk_tree_view_set_enable_search gtk_tree_view_set_enable_tree_lines gtk_tree_view_set_expander_column gtk_tree_view_set_fixed_height_mode gtk_tree_view_set_grid_lines gtk_tree_view_set_hadjustment gtk_tree_view_set_headers_clickable gtk_tree_view_set_headers_visible gtk_tree_view_set_hover_expand gtk_tree_view_set_hover_selection gtk_tree_view_set_level_indentation gtk_tree_view_set_model gtk_tree_view_set_reorderable gtk_tree_view_set_row_separator_func gtk_tree_view_set_rubber_banding gtk_tree_view_set_rules_hint gtk_tree_view_set_search_column gtk_tree_view_set_search_entry gtk_tree_view_set_search_equal_func gtk_tree_view_set_search_position_func gtk_tree_view_set_show_expanders gtk_tree_view_set_tooltip_cell gtk_tree_view_set_tooltip_column gtk_tree_view_set_tooltip_row gtk_tree_view_set_vadjustment gtk_tree_view_unset_rows_drag_dest gtk_tree_view_unset_rows_drag_source) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) ;; gboolean gtk_tree_drag_dest_drag_data_received (GtkTreeDragDest* drag_dest, GtkTreePath* dest, GtkSelectionData* selection_data) (define-function int gtk_tree_drag_dest_drag_data_received (void* void* void*)) GType gtk_tree_drag_dest_get_type ( void ) (define-function unsigned-long gtk_tree_drag_dest_get_type ()) ;; gboolean gtk_tree_drag_dest_row_drop_possible (GtkTreeDragDest* drag_dest, GtkTreePath* dest_path, GtkSelectionData* selection_data) (define-function int gtk_tree_drag_dest_row_drop_possible (void* void* void*)) ( GtkTreeDragSource * drag_source , GtkTreePath * path ) (define-function int gtk_tree_drag_source_drag_data_delete (void* void*)) ;; gboolean gtk_tree_drag_source_drag_data_get (GtkTreeDragSource* drag_source, GtkTreePath* path, GtkSelectionData* selection_data) (define-function int gtk_tree_drag_source_drag_data_get (void* void* void*)) GType gtk_tree_drag_source_get_type ( void ) (define-function unsigned-long gtk_tree_drag_source_get_type ()) ;; gboolean gtk_tree_drag_source_row_draggable (GtkTreeDragSource* drag_source, GtkTreePath* path) (define-function int gtk_tree_drag_source_row_draggable (void* void*)) ( GtkSelectionData * selection_data , GtkTreeModel * * tree_model , GtkTreePath * * path ) (define-function int gtk_tree_get_row_drag_data (void* void* void*)) ;; GtkTreeIter* gtk_tree_iter_copy (GtkTreeIter* iter) (define-function void* gtk_tree_iter_copy (void*)) ;; void gtk_tree_iter_free (GtkTreeIter* iter) (define-function void gtk_tree_iter_free (void*)) GType gtk_tree_iter_get_type ( void ) (define-function unsigned-long gtk_tree_iter_get_type ()) ;; void gtk_tree_model_filter_clear_cache (GtkTreeModelFilter* filter) (define-function void gtk_tree_model_filter_clear_cache (void*)) ;; gboolean gtk_tree_model_filter_convert_child_iter_to_iter (GtkTreeModelFilter* filter, GtkTreeIter* filter_iter, GtkTreeIter* child_iter) (define-function int gtk_tree_model_filter_convert_child_iter_to_iter (void* void* void*)) ;; GtkTreePath* gtk_tree_model_filter_convert_child_path_to_path (GtkTreeModelFilter* filter, GtkTreePath* child_path) (define-function void* gtk_tree_model_filter_convert_child_path_to_path (void* void*)) void ( GtkTreeModelFilter * filter , GtkTreeIter * child_iter , GtkTreeIter * filter_iter ) (define-function void gtk_tree_model_filter_convert_iter_to_child_iter (void* void* void*)) ;; GtkTreePath* gtk_tree_model_filter_convert_path_to_child_path (GtkTreeModelFilter* filter, GtkTreePath* filter_path) (define-function void* gtk_tree_model_filter_convert_path_to_child_path (void* void*)) ;; GtkTreeModel* gtk_tree_model_filter_get_model (GtkTreeModelFilter* filter) (define-function void* gtk_tree_model_filter_get_model (void*)) GType gtk_tree_model_filter_get_type ( void ) (define-function unsigned-long gtk_tree_model_filter_get_type ()) ;; GtkTreeModel* gtk_tree_model_filter_new (GtkTreeModel* child_model, GtkTreePath* root) (define-function void* gtk_tree_model_filter_new (void* void*)) ;; void gtk_tree_model_filter_refilter (GtkTreeModelFilter* filter) (define-function void gtk_tree_model_filter_refilter (void*)) void gtk_tree_model_filter_set_modify_func ( GtkTreeModelFilter * filter , gint n_columns , GType * types , GtkTreeModelFilterModifyFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_model_filter_set_modify_func (void* int void* (c-callback void (void* void* void* int void*)) void* (c-callback void (void*)))) ;; void gtk_tree_model_filter_set_visible_column (GtkTreeModelFilter* filter, gint column) (define-function void gtk_tree_model_filter_set_visible_column (void* int)) void gtk_tree_model_filter_set_visible_func ( GtkTreeModelFilter * filter , func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_model_filter_set_visible_func (void* (c-callback int (void* void* void*)) void* (c-callback void (void*)))) GType gtk_tree_model_flags_get_type ( void ) (define-function unsigned-long gtk_tree_model_flags_get_type ()) void ( GtkTreeModel * model , GtkTreeModelForeachFunc func , gpointer user_data ) (define-function void gtk_tree_model_foreach (void* (c-callback int (void* void* void* void*)) void*)) ;; void gtk_tree_model_get (GtkTreeModel* tree_model, GtkTreeIter* iter, ...) (define-function void gtk_tree_model_get (void* void* ...)) ;; GType gtk_tree_model_get_column_type (GtkTreeModel* tree_model, gint index_) (define-function unsigned-long gtk_tree_model_get_column_type (void* int)) ;; GtkTreeModelFlags gtk_tree_model_get_flags (GtkTreeModel* tree_model) (define-function int gtk_tree_model_get_flags (void*)) ;; gboolean gtk_tree_model_get_iter (GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) (define-function int gtk_tree_model_get_iter (void* void* void*)) ;; gboolean gtk_tree_model_get_iter_first (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function int gtk_tree_model_get_iter_first (void* void*)) ;; gboolean gtk_tree_model_get_iter_from_string (GtkTreeModel* tree_model, GtkTreeIter* iter, const gchar* path_string) (define-function int gtk_tree_model_get_iter_from_string (void* void* char*)) ;; gint gtk_tree_model_get_n_columns (GtkTreeModel* tree_model) (define-function int gtk_tree_model_get_n_columns (void*)) ;; GtkTreePath* gtk_tree_model_get_path (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function void* gtk_tree_model_get_path (void* void*)) gchar * gtk_tree_model_get_string_from_iter ( GtkTreeModel * tree_model , GtkTreeIter * iter ) (define-function char* gtk_tree_model_get_string_from_iter (void* void*)) GType gtk_tree_model_get_type ( void ) (define-function unsigned-long gtk_tree_model_get_type ()) void gtk_tree_model_get_valist ( GtkTreeModel * tree_model , GtkTreeIter * iter , va_list ) (define-function/va_list void gtk_tree_model_get_valist (void* void* va_list)) ;; void gtk_tree_model_get_value (GtkTreeModel* tree_model, GtkTreeIter* iter, gint column, GValue* value) (define-function void gtk_tree_model_get_value (void* void* int void*)) ;; gboolean gtk_tree_model_iter_children (GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreeIter* parent) (define-function int gtk_tree_model_iter_children (void* void* void*)) ;; gboolean gtk_tree_model_iter_has_child (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function int gtk_tree_model_iter_has_child (void* void*)) ( GtkTreeModel * tree_model , GtkTreeIter * iter ) (define-function int gtk_tree_model_iter_n_children (void* void*)) ;; gboolean gtk_tree_model_iter_next (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function int gtk_tree_model_iter_next (void* void*)) gboolean gtk_tree_model_iter_nth_child ( GtkTreeModel * tree_model , GtkTreeIter * iter , GtkTreeIter * parent , gint n ) (define-function int gtk_tree_model_iter_nth_child (void* void* void* int)) ( GtkTreeModel * tree_model , GtkTreeIter * iter , GtkTreeIter * child ) (define-function int gtk_tree_model_iter_parent (void* void* void*)) ;; void gtk_tree_model_ref_node (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function void gtk_tree_model_ref_node (void* void*)) ;; void gtk_tree_model_row_changed (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) (define-function void gtk_tree_model_row_changed (void* void* void*)) ;; void gtk_tree_model_row_deleted (GtkTreeModel* tree_model, GtkTreePath* path) (define-function void gtk_tree_model_row_deleted (void* void*)) ;; void gtk_tree_model_row_has_child_toggled (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) (define-function void gtk_tree_model_row_has_child_toggled (void* void* void*)) ;; void gtk_tree_model_row_inserted (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) (define-function void gtk_tree_model_row_inserted (void* void* void*)) ;; void gtk_tree_model_rows_reordered (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter, gint* new_order) (define-function void gtk_tree_model_rows_reordered (void* void* void* void*)) void gtk_tree_model_sort_clear_cache ( GtkTreeModelSort * tree_model_sort ) (define-function void gtk_tree_model_sort_clear_cache (void*)) ;; gboolean gtk_tree_model_sort_convert_child_iter_to_iter (GtkTreeModelSort* tree_model_sort, GtkTreeIter* sort_iter, GtkTreeIter* child_iter) (define-function int gtk_tree_model_sort_convert_child_iter_to_iter (void* void* void*)) ;; GtkTreePath* gtk_tree_model_sort_convert_child_path_to_path (GtkTreeModelSort* tree_model_sort, GtkTreePath* child_path) (define-function void* gtk_tree_model_sort_convert_child_path_to_path (void* void*)) ;; void gtk_tree_model_sort_convert_iter_to_child_iter (GtkTreeModelSort* tree_model_sort, GtkTreeIter* child_iter, GtkTreeIter* sorted_iter) (define-function void gtk_tree_model_sort_convert_iter_to_child_iter (void* void* void*)) ;; GtkTreePath* gtk_tree_model_sort_convert_path_to_child_path (GtkTreeModelSort* tree_model_sort, GtkTreePath* sorted_path) (define-function void* gtk_tree_model_sort_convert_path_to_child_path (void* void*)) ;; GtkTreeModel* gtk_tree_model_sort_get_model (GtkTreeModelSort* tree_model) (define-function void* gtk_tree_model_sort_get_model (void*)) GType gtk_tree_model_sort_get_type ( void ) (define-function unsigned-long gtk_tree_model_sort_get_type ()) ;; gboolean gtk_tree_model_sort_iter_is_valid (GtkTreeModelSort* tree_model_sort, GtkTreeIter* iter) (define-function int gtk_tree_model_sort_iter_is_valid (void* void*)) ;; GtkTreeModel* gtk_tree_model_sort_new_with_model (GtkTreeModel* child_model) (define-function void* gtk_tree_model_sort_new_with_model (void*)) ;; void gtk_tree_model_sort_reset_default_sort_func (GtkTreeModelSort* tree_model_sort) (define-function void gtk_tree_model_sort_reset_default_sort_func (void*)) ;; void gtk_tree_model_unref_node (GtkTreeModel* tree_model, GtkTreeIter* iter) (define-function void gtk_tree_model_unref_node (void* void*)) ;; void gtk_tree_path_append_index (GtkTreePath* path, gint index_) (define-function void gtk_tree_path_append_index (void* int)) ( const GtkTreePath * a , const GtkTreePath * b ) (define-function int gtk_tree_path_compare (void* void*)) ;; GtkTreePath* gtk_tree_path_copy (const GtkTreePath* path) (define-function void* gtk_tree_path_copy (void*)) ;; void gtk_tree_path_down (GtkTreePath* path) (define-function void gtk_tree_path_down (void*)) ;; void gtk_tree_path_free (GtkTreePath* path) (define-function void gtk_tree_path_free (void*)) ;; gint gtk_tree_path_get_depth (GtkTreePath* path) (define-function int gtk_tree_path_get_depth (void*)) ;; gint* gtk_tree_path_get_indices (GtkTreePath* path) (define-function void* gtk_tree_path_get_indices (void*)) GType gtk_tree_path_get_type ( void ) (define-function unsigned-long gtk_tree_path_get_type ()) ( GtkTreePath * path , GtkTreePath * descendant ) (define-function int gtk_tree_path_is_ancestor (void* void*)) ;; gboolean gtk_tree_path_is_descendant (GtkTreePath* path, GtkTreePath* ancestor) (define-function int gtk_tree_path_is_descendant (void* void*)) ;; GtkTreePath* gtk_tree_path_new (void) (define-function void* gtk_tree_path_new ()) ;; GtkTreePath* gtk_tree_path_new_first (void) (define-function void* gtk_tree_path_new_first ()) ;; GtkTreePath* gtk_tree_path_new_from_indices (gint first_index, ...) (define-function void* gtk_tree_path_new_from_indices (int ...)) ;; GtkTreePath* gtk_tree_path_new_from_string (const gchar* path) (define-function void* gtk_tree_path_new_from_string (char*)) void ( GtkTreePath * path ) (define-function void gtk_tree_path_next (void*)) ;; void gtk_tree_path_prepend_index (GtkTreePath* path, gint index_) (define-function void gtk_tree_path_prepend_index (void* int)) ( GtkTreePath * path ) (define-function int gtk_tree_path_prev (void*)) ;; gchar* gtk_tree_path_to_string (GtkTreePath* path) (define-function char* gtk_tree_path_to_string (void*)) ;; gboolean gtk_tree_path_up (GtkTreePath* path) (define-function int gtk_tree_path_up (void*)) ;; GtkTreeRowReference* gtk_tree_row_reference_copy (GtkTreeRowReference* reference) (define-function void* gtk_tree_row_reference_copy (void*)) ;; void gtk_tree_row_reference_deleted (GObject* proxy, GtkTreePath* path) (define-function void gtk_tree_row_reference_deleted (void* void*)) ;; void gtk_tree_row_reference_free (GtkTreeRowReference* reference) (define-function void gtk_tree_row_reference_free (void*)) ;; GtkTreeModel* gtk_tree_row_reference_get_model (GtkTreeRowReference* reference) (define-function void* gtk_tree_row_reference_get_model (void*)) ;; GtkTreePath* gtk_tree_row_reference_get_path (GtkTreeRowReference* reference) (define-function void* gtk_tree_row_reference_get_path (void*)) GType gtk_tree_row_reference_get_type ( void ) (define-function unsigned-long gtk_tree_row_reference_get_type ()) ;; void gtk_tree_row_reference_inserted (GObject* proxy, GtkTreePath* path) (define-function void gtk_tree_row_reference_inserted (void* void*)) ;; GtkTreeRowReference* gtk_tree_row_reference_new (GtkTreeModel* model, GtkTreePath* path) (define-function void* gtk_tree_row_reference_new (void* void*)) ;; GtkTreeRowReference* gtk_tree_row_reference_new_proxy (GObject* proxy, GtkTreeModel* model, GtkTreePath* path) (define-function void* gtk_tree_row_reference_new_proxy (void* void* void*)) ;; void gtk_tree_row_reference_reordered (GObject* proxy, GtkTreePath* path, GtkTreeIter* iter, gint* new_order) (define-function void gtk_tree_row_reference_reordered (void* void* void* void*)) ( GtkTreeRowReference * reference ) (define-function int gtk_tree_row_reference_valid (void*)) ( GtkTreeSelection * selection ) (define-function int gtk_tree_selection_count_selected_rows (void*)) ;; GtkSelectionMode gtk_tree_selection_get_mode (GtkTreeSelection* selection) (define-function int gtk_tree_selection_get_mode (void*)) GtkTreeSelectionFunc gtk_tree_selection_get_select_function ( GtkTreeSelection * selection ) (define-function void* gtk_tree_selection_get_select_function (void*)) ;; gboolean gtk_tree_selection_get_selected (GtkTreeSelection* selection, GtkTreeModel** model, GtkTreeIter* iter) (define-function int gtk_tree_selection_get_selected (void* void* void*)) ;; GList* gtk_tree_selection_get_selected_rows (GtkTreeSelection* selection, GtkTreeModel** model) (define-function void* gtk_tree_selection_get_selected_rows (void* void*)) ;; GtkTreeView* gtk_tree_selection_get_tree_view (GtkTreeSelection* selection) (define-function void* gtk_tree_selection_get_tree_view (void*)) GType gtk_tree_selection_get_type ( void ) (define-function unsigned-long gtk_tree_selection_get_type ()) ;; gpointer gtk_tree_selection_get_user_data (GtkTreeSelection* selection) (define-function void* gtk_tree_selection_get_user_data (void*)) ;; gboolean gtk_tree_selection_iter_is_selected (GtkTreeSelection* selection, GtkTreeIter* iter) (define-function int gtk_tree_selection_iter_is_selected (void* void*)) ;; gboolean gtk_tree_selection_path_is_selected (GtkTreeSelection* selection, GtkTreePath* path) (define-function int gtk_tree_selection_path_is_selected (void* void*)) ;; void gtk_tree_selection_select_all (GtkTreeSelection* selection) (define-function void gtk_tree_selection_select_all (void*)) ;; void gtk_tree_selection_select_iter (GtkTreeSelection* selection, GtkTreeIter* iter) (define-function void gtk_tree_selection_select_iter (void* void*)) ;; void gtk_tree_selection_select_path (GtkTreeSelection* selection, GtkTreePath* path) (define-function void gtk_tree_selection_select_path (void* void*)) ;; void gtk_tree_selection_select_range (GtkTreeSelection* selection, GtkTreePath* start_path, GtkTreePath* end_path) (define-function void gtk_tree_selection_select_range (void* void* void*)) void ( GtkTreeSelection * selection , GtkTreeSelectionForeachFunc func , gpointer data ) (define-function void gtk_tree_selection_selected_foreach (void* (c-callback void (void* void* void* void*)) void*)) ;; void gtk_tree_selection_set_mode (GtkTreeSelection* selection, GtkSelectionMode type) (define-function void gtk_tree_selection_set_mode (void* int)) void gtk_tree_selection_set_select_function ( GtkTreeSelection * selection , GtkTreeSelectionFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_selection_set_select_function (void* void* void* (c-callback void (void*)))) ;; void gtk_tree_selection_unselect_all (GtkTreeSelection* selection) (define-function void gtk_tree_selection_unselect_all (void*)) ;; void gtk_tree_selection_unselect_iter (GtkTreeSelection* selection, GtkTreeIter* iter) (define-function void gtk_tree_selection_unselect_iter (void* void*)) ;; void gtk_tree_selection_unselect_path (GtkTreeSelection* selection, GtkTreePath* path) (define-function void gtk_tree_selection_unselect_path (void* void*)) ;; void gtk_tree_selection_unselect_range (GtkTreeSelection* selection, GtkTreePath* start_path, GtkTreePath* end_path) (define-function void gtk_tree_selection_unselect_range (void* void* void*)) ( GtkSelectionData * selection_data , GtkTreeModel * tree_model , GtkTreePath * path ) (define-function int gtk_tree_set_row_drag_data (void* void* void*)) ;; gboolean gtk_tree_sortable_get_sort_column_id (GtkTreeSortable* sortable, gint* sort_column_id, GtkSortType* order) (define-function int gtk_tree_sortable_get_sort_column_id (void* void* void*)) GType gtk_tree_sortable_get_type ( void ) (define-function unsigned-long gtk_tree_sortable_get_type ()) ;; gboolean gtk_tree_sortable_has_default_sort_func (GtkTreeSortable* sortable) (define-function int gtk_tree_sortable_has_default_sort_func (void*)) void gtk_tree_sortable_set_default_sort_func ( GtkTreeSortable * sortable , GtkTreeIterCompareFunc sort_func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_sortable_set_default_sort_func (void* (c-callback int (void* void* void* void*)) void* (c-callback void (void*)))) ;; void gtk_tree_sortable_set_sort_column_id (GtkTreeSortable* sortable, gint sort_column_id, GtkSortType order) (define-function void gtk_tree_sortable_set_sort_column_id (void* int int)) void gtk_tree_sortable_set_sort_func ( GtkTreeSortable * sortable , gint sort_column_id , GtkTreeIterCompareFunc sort_func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_sortable_set_sort_func (void* int (c-callback int (void* void* void* void*)) void* (c-callback void (void*)))) ;; void gtk_tree_sortable_sort_column_changed (GtkTreeSortable* sortable) (define-function void gtk_tree_sortable_sort_column_changed (void*)) ;; void gtk_tree_store_append (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent) (define-function void gtk_tree_store_append (void* void* void*)) void ( GtkTreeStore * tree_store ) (define-function void gtk_tree_store_clear (void*)) GType gtk_tree_store_get_type ( void ) (define-function unsigned-long gtk_tree_store_get_type ()) void ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position ) (define-function void gtk_tree_store_insert (void* void* void* int)) ;; void gtk_tree_store_insert_after (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent, GtkTreeIter* sibling) (define-function void gtk_tree_store_insert_after (void* void* void* void*)) ;; void gtk_tree_store_insert_before (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent, GtkTreeIter* sibling) (define-function void gtk_tree_store_insert_before (void* void* void* void*)) void gtk_tree_store_insert_with_values ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position , ... ) (define-function void gtk_tree_store_insert_with_values (void* void* void* int ...)) void gtk_tree_store_insert_with_valuesv ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position , gint * columns , GValue * values , ) (define-function void gtk_tree_store_insert_with_valuesv (void* void* void* int void* void* int)) ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * descendant ) (define-function int gtk_tree_store_is_ancestor (void* void* void*)) ;; gint gtk_tree_store_iter_depth (GtkTreeStore* tree_store, GtkTreeIter* iter) (define-function int gtk_tree_store_iter_depth (void* void*)) ( GtkTreeStore * tree_store , GtkTreeIter * iter ) (define-function int gtk_tree_store_iter_is_valid (void* void*)) ;; void gtk_tree_store_move_after (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* position) (define-function void gtk_tree_store_move_after (void* void* void*)) void ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * position ) (define-function void gtk_tree_store_move_before (void* void* void*)) GtkTreeStore * gtk_tree_store_new ( gint n_columns , ... ) (define-function void* gtk_tree_store_new (int ...)) GtkTreeStore * gtk_tree_store_newv ( gint n_columns , GType * types ) (define-function void* gtk_tree_store_newv (int void*)) ;; void gtk_tree_store_prepend (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent) (define-function void gtk_tree_store_prepend (void* void* void*)) ;; gboolean gtk_tree_store_remove (GtkTreeStore* tree_store, GtkTreeIter* iter) (define-function int gtk_tree_store_remove (void* void*)) void gtk_tree_store_reorder ( GtkTreeStore * tree_store , GtkTreeIter * parent , gint * new_order ) (define-function void gtk_tree_store_reorder (void* void* void*)) ;; void gtk_tree_store_set (GtkTreeStore* tree_store, GtkTreeIter* iter, ...) (define-function void gtk_tree_store_set (void* void* ...)) void gtk_tree_store_set_column_types ( GtkTreeStore * tree_store , gint n_columns , GType * types ) (define-function void gtk_tree_store_set_column_types (void* int void*)) void gtk_tree_store_set_valist ( GtkTreeStore * tree_store , GtkTreeIter * iter , va_list ) (define-function/va_list void gtk_tree_store_set_valist (void* void* va_list)) ;; void gtk_tree_store_set_value (GtkTreeStore* tree_store, GtkTreeIter* iter, gint column, GValue* value) (define-function void gtk_tree_store_set_value (void* void* int void*)) void gtk_tree_store_set_valuesv ( GtkTreeStore * tree_store , GtkTreeIter * iter , gint * columns , GValue * values , ) (define-function void gtk_tree_store_set_valuesv (void* void* void* void* int)) ;; void gtk_tree_store_swap (GtkTreeStore* tree_store, GtkTreeIter* a, GtkTreeIter* b) (define-function void gtk_tree_store_swap (void* void* void*)) ;; gint gtk_tree_view_append_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) (define-function int gtk_tree_view_append_column (void* void*)) ;; void gtk_tree_view_collapse_all (GtkTreeView* tree_view) (define-function void gtk_tree_view_collapse_all (void*)) gboolean gtk_tree_view_collapse_row ( GtkTreeView * tree_view , GtkTreePath * path ) (define-function int gtk_tree_view_collapse_row (void* void*)) void ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , const gchar * attribute , gint column ) (define-function void gtk_tree_view_column_add_attribute (void* void* char* int)) ;; gboolean gtk_tree_view_column_cell_get_position (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell_renderer, gint* start_pos, gint* width) (define-function int gtk_tree_view_column_cell_get_position (void* void* void* void*)) void gtk_tree_view_column_cell_get_size ( GtkTreeViewColumn * tree_column , const GdkRectangle * cell_area , gint * x_offset , gint * y_offset , gint * width , gint * height ) (define-function void gtk_tree_view_column_cell_get_size (void* void* void* void* void* void*)) ;; gboolean gtk_tree_view_column_cell_is_visible (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_cell_is_visible (void*)) void gtk_tree_view_column_cell_set_cell_data ( GtkTreeViewColumn * tree_column , GtkTreeModel * tree_model , GtkTreeIter * iter , , is_expanded ) (define-function void gtk_tree_view_column_cell_set_cell_data (void* void* void* int int)) void gtk_tree_view_column_clear ( GtkTreeViewColumn * tree_column ) (define-function void gtk_tree_view_column_clear (void*)) ;; void gtk_tree_view_column_clear_attributes (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell_renderer) (define-function void gtk_tree_view_column_clear_attributes (void* void*)) ;; void gtk_tree_view_column_clicked (GtkTreeViewColumn* tree_column) (define-function void gtk_tree_view_column_clicked (void*)) ;; void gtk_tree_view_column_focus_cell (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell) (define-function void gtk_tree_view_column_focus_cell (void* void*)) ;; gfloat gtk_tree_view_column_get_alignment (GtkTreeViewColumn* tree_column) (define-function float gtk_tree_view_column_get_alignment (void*)) ;; GList* gtk_tree_view_column_get_cell_renderers (GtkTreeViewColumn* tree_column) (define-function void* gtk_tree_view_column_get_cell_renderers (void*)) ;; gboolean gtk_tree_view_column_get_clickable (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_clickable (void*)) ;; gboolean gtk_tree_view_column_get_expand (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_expand (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_fixed_width (void*)) ;; gint gtk_tree_view_column_get_max_width (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_max_width (void*)) gint gtk_tree_view_column_get_min_width ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_min_width (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_reorderable (void*)) ;; gboolean gtk_tree_view_column_get_resizable (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_resizable (void*)) ;; GtkTreeViewColumnSizing gtk_tree_view_column_get_sizing (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_sizing (void*)) ;; gint gtk_tree_view_column_get_sort_column_id (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_sort_column_id (void*)) ;; gboolean gtk_tree_view_column_get_sort_indicator (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_sort_indicator (void*)) ;; GtkSortType gtk_tree_view_column_get_sort_order (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_sort_order (void*)) ;; gint gtk_tree_view_column_get_spacing (GtkTreeViewColumn* tree_column) (define-function int gtk_tree_view_column_get_spacing (void*)) const gchar * ( GtkTreeViewColumn * tree_column ) (define-function char* gtk_tree_view_column_get_title (void*)) GtkWidget * gtk_tree_view_column_get_tree_view ( GtkTreeViewColumn * tree_column ) (define-function void* gtk_tree_view_column_get_tree_view (void*)) GType gtk_tree_view_column_get_type ( void ) (define-function unsigned-long gtk_tree_view_column_get_type ()) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_visible (void*)) ;; GtkWidget* gtk_tree_view_column_get_widget (GtkTreeViewColumn* tree_column) (define-function void* gtk_tree_view_column_get_widget (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_width (void*)) ;; GtkTreeViewColumn* gtk_tree_view_column_new (void) (define-function void* gtk_tree_view_column_new ()) ;; GtkTreeViewColumn* gtk_tree_view_column_new_with_attributes (const gchar* title, GtkCellRenderer* cell, ...) (define-function void* gtk_tree_view_column_new_with_attributes (char* void* ...)) void gtk_tree_view_column_pack_end ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell , expand ) (define-function void gtk_tree_view_column_pack_end (void* void* int)) void gtk_tree_view_column_pack_start ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell , expand ) (define-function void gtk_tree_view_column_pack_start (void* void* int)) ;; void gtk_tree_view_column_queue_resize (GtkTreeViewColumn* tree_column) (define-function void gtk_tree_view_column_queue_resize (void*)) void gtk_tree_view_column_set_alignment ( GtkTreeViewColumn * tree_column , xalign ) (define-function void gtk_tree_view_column_set_alignment (void* float)) void gtk_tree_view_column_set_attributes ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , ... ) (define-function void gtk_tree_view_column_set_attributes (void* void* ...)) void gtk_tree_view_column_set_cell_data_func ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , GtkTreeCellDataFunc func , , GDestroyNotify destroy ) (define-function void gtk_tree_view_column_set_cell_data_func (void* void* (c-callback void (void* void* void* void* void*)) void* (c-callback void (void*)))) void ( GtkTreeViewColumn * tree_column , clickable ) (define-function void gtk_tree_view_column_set_clickable (void* int)) void gtk_tree_view_column_set_expand ( GtkTreeViewColumn * tree_column , expand ) (define-function void gtk_tree_view_column_set_expand (void* int)) void gtk_tree_view_column_set_fixed_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_fixed_width (void* int)) void gtk_tree_view_column_set_max_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_max_width (void* int)) void gtk_tree_view_column_set_min_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_min_width (void* int)) void gtk_tree_view_column_set_reorderable ( GtkTreeViewColumn * tree_column , reorderable ) (define-function void gtk_tree_view_column_set_reorderable (void* int)) void gtk_tree_view_column_set_resizable ( GtkTreeViewColumn * tree_column , resizable ) (define-function void gtk_tree_view_column_set_resizable (void* int)) ;; void gtk_tree_view_column_set_sizing (GtkTreeViewColumn* tree_column, GtkTreeViewColumnSizing type) (define-function void gtk_tree_view_column_set_sizing (void* int)) void gtk_tree_view_column_set_sort_column_id ( GtkTreeViewColumn * tree_column , sort_column_id ) (define-function void gtk_tree_view_column_set_sort_column_id (void* int)) void gtk_tree_view_column_set_sort_indicator ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_sort_indicator (void* int)) ;; void gtk_tree_view_column_set_sort_order (GtkTreeViewColumn* tree_column, GtkSortType order) (define-function void gtk_tree_view_column_set_sort_order (void* int)) ;; void gtk_tree_view_column_set_spacing (GtkTreeViewColumn* tree_column, gint spacing) (define-function void gtk_tree_view_column_set_spacing (void* int)) ;; void gtk_tree_view_column_set_title (GtkTreeViewColumn* tree_column, const gchar* title) (define-function void gtk_tree_view_column_set_title (void* char*)) void gtk_tree_view_column_set_visible ( GtkTreeViewColumn * tree_column , visible ) (define-function void gtk_tree_view_column_set_visible (void* int)) void gtk_tree_view_column_set_widget ( GtkTreeViewColumn * tree_column , GtkWidget * widget ) (define-function void gtk_tree_view_column_set_widget (void* void*)) GType gtk_tree_view_column_sizing_get_type ( void ) (define-function unsigned-long gtk_tree_view_column_sizing_get_type ()) ;; void gtk_tree_view_columns_autosize (GtkTreeView* tree_view) (define-function void gtk_tree_view_columns_autosize (void*)) void gtk_tree_view_convert_bin_window_to_tree_coords ( GtkTreeView * tree_view , bx , by , gint * tx , gint * ty ) (define-function void gtk_tree_view_convert_bin_window_to_tree_coords (void* int int void* void*)) void gtk_tree_view_convert_bin_window_to_widget_coords ( GtkTreeView * tree_view , bx , by , gint * wx , gint * wy ) (define-function void gtk_tree_view_convert_bin_window_to_widget_coords (void* int int void* void*)) void gtk_tree_view_convert_tree_to_bin_window_coords ( GtkTreeView * tree_view , , , * bx , gint * by ) (define-function void gtk_tree_view_convert_tree_to_bin_window_coords (void* int int void* void*)) void gtk_tree_view_convert_tree_to_widget_coords ( GtkTreeView * tree_view , , , * wx , gint * wy ) (define-function void gtk_tree_view_convert_tree_to_widget_coords (void* int int void* void*)) void gtk_tree_view_convert_widget_to_bin_window_coords ( GtkTreeView * tree_view , , gint wy , gint * bx , gint * by ) (define-function void gtk_tree_view_convert_widget_to_bin_window_coords (void* int int void* void*)) void gtk_tree_view_convert_widget_to_tree_coords ( GtkTreeView * tree_view , , gint wy , gint * tx , gint * ty ) (define-function void gtk_tree_view_convert_widget_to_tree_coords (void* int int void* void*)) ;; GdkPixmap* gtk_tree_view_create_row_drag_icon (GtkTreeView* tree_view, GtkTreePath* path) (define-function void* gtk_tree_view_create_row_drag_icon (void* void*)) GType gtk_tree_view_drop_position_get_type ( void ) (define-function unsigned-long gtk_tree_view_drop_position_get_type ()) void gtk_tree_view_enable_model_drag_dest ( GtkTreeView * tree_view , const GtkTargetEntry * targets , gint n_targets , GdkDragAction actions ) (define-function void gtk_tree_view_enable_model_drag_dest (void* void* int int)) void gtk_tree_view_enable_model_drag_source ( GtkTreeView * tree_view , GdkModifierType start_button_mask , const GtkTargetEntry * targets , gint n_targets , GdkDragAction actions ) (define-function void gtk_tree_view_enable_model_drag_source (void* int void* int int)) void gtk_tree_view_expand_all ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_expand_all (void*)) gboolean gtk_tree_view_expand_row ( GtkTreeView * tree_view , GtkTreePath * path , ) (define-function int gtk_tree_view_expand_row (void* void* int)) ;; void gtk_tree_view_expand_to_path (GtkTreeView* tree_view, GtkTreePath* path) (define-function void gtk_tree_view_expand_to_path (void* void*)) void gtk_tree_view_get_background_area ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , GdkRectangle * rect ) (define-function void gtk_tree_view_get_background_area (void* void* void* void*)) GdkWindow * gtk_tree_view_get_bin_window ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_bin_window (void*)) void gtk_tree_view_get_cell_area ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , GdkRectangle * rect ) (define-function void gtk_tree_view_get_cell_area (void* void* void* void*)) ;; GtkTreeViewColumn* gtk_tree_view_get_column (GtkTreeView* tree_view, gint n) (define-function void* gtk_tree_view_get_column (void* int)) GList * ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_columns (void*)) ;; void gtk_tree_view_get_cursor (GtkTreeView* tree_view, GtkTreePath** path, GtkTreeViewColumn** focus_column) (define-function void gtk_tree_view_get_cursor (void* void* void*)) gboolean gtk_tree_view_get_dest_row_at_pos ( GtkTreeView * tree_view , , , GtkTreePath * * path , GtkTreeViewDropPosition * pos ) (define-function int gtk_tree_view_get_dest_row_at_pos (void* int int void* void*)) void ( GtkTreeView * tree_view , GtkTreePath * * path , GtkTreeViewDropPosition * pos ) (define-function void gtk_tree_view_get_drag_dest_row (void* void* void*)) ;; gboolean gtk_tree_view_get_enable_search (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_enable_search (void*)) ;; gboolean gtk_tree_view_get_enable_tree_lines (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_enable_tree_lines (void*)) ;; GtkTreeViewColumn* gtk_tree_view_get_expander_column (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_expander_column (void*)) ;; gboolean gtk_tree_view_get_fixed_height_mode (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_fixed_height_mode (void*)) ;; GtkTreeViewGridLines gtk_tree_view_get_grid_lines (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_grid_lines (void*)) ;; GtkAdjustment* gtk_tree_view_get_hadjustment (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_hadjustment (void*)) ;; gboolean gtk_tree_view_get_headers_clickable (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_headers_clickable (void*)) ;; gboolean gtk_tree_view_get_headers_visible (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_headers_visible (void*)) ;; gboolean gtk_tree_view_get_hover_expand (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_hover_expand (void*)) ;; gboolean gtk_tree_view_get_hover_selection (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_hover_selection (void*)) gint gtk_tree_view_get_level_indentation ( GtkTreeView * tree_view ) (define-function int gtk_tree_view_get_level_indentation (void*)) ;; GtkTreeModel* gtk_tree_view_get_model (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_model (void*)) gboolean gtk_tree_view_get_path_at_pos ( GtkTreeView * tree_view , , gint y , GtkTreePath * * path , GtkTreeViewColumn * * column , gint * cell_x , gint * cell_y ) (define-function int gtk_tree_view_get_path_at_pos (void* int int void* void* void* void*)) ;; gboolean gtk_tree_view_get_reorderable (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_reorderable (void*)) ;; GtkTreeViewRowSeparatorFunc gtk_tree_view_get_row_separator_func (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_row_separator_func (void*)) ;; gboolean gtk_tree_view_get_rubber_banding (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_rubber_banding (void*)) ;; gboolean gtk_tree_view_get_rules_hint (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_rules_hint (void*)) ;; gint gtk_tree_view_get_search_column (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_search_column (void*)) GtkEntry * gtk_tree_view_get_search_entry ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_search_entry (void*)) GtkTreeViewSearchEqualFunc gtk_tree_view_get_search_equal_func ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_search_equal_func (void*)) ;; GtkTreeViewSearchPositionFunc gtk_tree_view_get_search_position_func (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_search_position_func (void*)) ;; GtkTreeSelection* gtk_tree_view_get_selection (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_selection (void*)) ;; gboolean gtk_tree_view_get_show_expanders (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_show_expanders (void*)) ;; gint gtk_tree_view_get_tooltip_column (GtkTreeView* tree_view) (define-function int gtk_tree_view_get_tooltip_column (void*)) gboolean gtk_tree_view_get_tooltip_context(GtkTreeView * tree_view , gint * x , gint * y , , GtkTreeModel * * model , GtkTreePath * * path , GtkTreeIter * iter ) (define-function int gtk_tree_view_get_tooltip_context (void* void* void* int void* void* void*)) GType gtk_tree_view_get_type ( void ) (define-function unsigned-long gtk_tree_view_get_type ()) ;; GtkAdjustment* gtk_tree_view_get_vadjustment (GtkTreeView* tree_view) (define-function void* gtk_tree_view_get_vadjustment (void*)) ;; gboolean gtk_tree_view_get_visible_range (GtkTreeView* tree_view, GtkTreePath** start_path, GtkTreePath** end_path) (define-function int gtk_tree_view_get_visible_range (void* void* void*)) void gtk_tree_view_get_visible_rect ( GtkTreeView * tree_view , GdkRectangle * visible_rect ) (define-function void gtk_tree_view_get_visible_rect (void* void*)) GType gtk_tree_view_grid_lines_get_type ( void ) (define-function unsigned-long gtk_tree_view_grid_lines_get_type ()) ;; gint gtk_tree_view_insert_column (GtkTreeView* tree_view, GtkTreeViewColumn* column, gint position) (define-function int gtk_tree_view_insert_column (void* void* int)) ;; gint gtk_tree_view_insert_column_with_attributes (GtkTreeView* tree_view, gint position, const gchar* title, GtkCellRenderer* cell, ...) (define-function int gtk_tree_view_insert_column_with_attributes (void* int char* void* ...)) gint gtk_tree_view_insert_column_with_data_func ( GtkTreeView * tree_view , gint position , const gchar * title , GtkCellRenderer * cell , GtkTreeCellDataFunc func , gpointer data , ) (define-function int gtk_tree_view_insert_column_with_data_func (void* int char* void* (c-callback void (void* void* void* void* void*)) void* (c-callback void (void*)))) ;; gboolean gtk_tree_view_is_rubber_banding_active (GtkTreeView* tree_view) (define-function int gtk_tree_view_is_rubber_banding_active (void*)) void gtk_tree_view_map_expanded_rows ( GtkTreeView * tree_view , GtkTreeViewMappingFunc func , gpointer data ) (define-function void gtk_tree_view_map_expanded_rows (void* (c-callback void (void* void* void*)) void*)) GType gtk_tree_view_mode_get_type ( void ) (define-function unsigned-long gtk_tree_view_mode_get_type ()) void ( GtkTreeView * tree_view , GtkTreeViewColumn * column , GtkTreeViewColumn * base_column ) (define-function void gtk_tree_view_move_column_after (void* void* void*)) GtkWidget * gtk_tree_view_new ( void ) (define-function void* gtk_tree_view_new ()) GtkWidget * gtk_tree_view_new_with_model ( GtkTreeModel * model ) (define-function void* gtk_tree_view_new_with_model (void*)) ;; gint gtk_tree_view_remove_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) (define-function int gtk_tree_view_remove_column (void* void*)) ;; void gtk_tree_view_row_activated (GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* column) (define-function void gtk_tree_view_row_activated (void* void* void*)) ;; gboolean gtk_tree_view_row_expanded (GtkTreeView* tree_view, GtkTreePath* path) (define-function int gtk_tree_view_row_expanded (void* void*)) void gtk_tree_view_scroll_to_cell ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , , row_align , ) (define-function void gtk_tree_view_scroll_to_cell (void* void* void* int float float)) void gtk_tree_view_scroll_to_point ( GtkTreeView * tree_view , gint tree_x , ) (define-function void gtk_tree_view_scroll_to_point (void* int int)) void gtk_tree_view_set_column_drag_function ( GtkTreeView * tree_view , GtkTreeViewColumnDropFunc func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_column_drag_function (void* (c-callback int (void* void* void* void* void*)) void* (c-callback void (void*)))) ;; void gtk_tree_view_set_cursor (GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* focus_column, gboolean start_editing) (define-function void gtk_tree_view_set_cursor (void* void* void* int)) void gtk_tree_view_set_cursor_on_cell ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * focus_column , GtkCellRenderer * focus_cell , ) (define-function void gtk_tree_view_set_cursor_on_cell (void* void* void* void* int)) void gtk_tree_view_set_destroy_count_func ( GtkTreeView * tree_view , GtkTreeDestroyCountFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_destroy_count_func (void* (c-callback void (void* void* int void*)) void* (c-callback void (void*)))) void gtk_tree_view_set_drag_dest_row ( GtkTreeView * tree_view , GtkTreePath * path , ) (define-function void gtk_tree_view_set_drag_dest_row (void* void* int)) ;; void gtk_tree_view_set_enable_search (GtkTreeView* tree_view, gboolean enable_search) (define-function void gtk_tree_view_set_enable_search (void* int)) void gtk_tree_view_set_enable_tree_lines ( GtkTreeView * tree_view , enabled ) (define-function void gtk_tree_view_set_enable_tree_lines (void* int)) ;; void gtk_tree_view_set_expander_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) (define-function void gtk_tree_view_set_expander_column (void* void*)) void gtk_tree_view_set_fixed_height_mode ( GtkTreeView * tree_view , enable ) (define-function void gtk_tree_view_set_fixed_height_mode (void* int)) void gtk_tree_view_set_grid_lines ( GtkTreeView * tree_view , GtkTreeViewGridLines grid_lines ) (define-function void gtk_tree_view_set_grid_lines (void* int)) ;; void gtk_tree_view_set_hadjustment (GtkTreeView* tree_view, GtkAdjustment* adjustment) (define-function void gtk_tree_view_set_hadjustment (void* void*)) ;; void gtk_tree_view_set_headers_clickable (GtkTreeView* tree_view, gboolean setting) (define-function void gtk_tree_view_set_headers_clickable (void* int)) void gtk_tree_view_set_headers_visible ( GtkTreeView * tree_view , headers_visible ) (define-function void gtk_tree_view_set_headers_visible (void* int)) void gtk_tree_view_set_hover_expand ( GtkTreeView * tree_view , expand ) (define-function void gtk_tree_view_set_hover_expand (void* int)) void gtk_tree_view_set_hover_selection ( GtkTreeView * tree_view , ) (define-function void gtk_tree_view_set_hover_selection (void* int)) ;; void gtk_tree_view_set_level_indentation (GtkTreeView* tree_view, gint indentation) (define-function void gtk_tree_view_set_level_indentation (void* int)) ;; void gtk_tree_view_set_model (GtkTreeView* tree_view, GtkTreeModel* model) (define-function void gtk_tree_view_set_model (void* void*)) void gtk_tree_view_set_reorderable ( GtkTreeView * tree_view , reorderable ) (define-function void gtk_tree_view_set_reorderable (void* int)) void gtk_tree_view_set_row_separator_func ( GtkTreeView * tree_view , GtkTreeViewRowSeparatorFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_row_separator_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_rubber_banding ( GtkTreeView * tree_view , enable ) (define-function void gtk_tree_view_set_rubber_banding (void* int)) ;; void gtk_tree_view_set_rules_hint (GtkTreeView* tree_view, gboolean setting) (define-function void gtk_tree_view_set_rules_hint (void* int)) ;; void gtk_tree_view_set_search_column (GtkTreeView* tree_view, gint column) (define-function void gtk_tree_view_set_search_column (void* int)) ;; void gtk_tree_view_set_search_entry (GtkTreeView* tree_view, GtkEntry* entry) (define-function void gtk_tree_view_set_search_entry (void* void*)) void gtk_tree_view_set_search_equal_func ( GtkTreeView * tree_view , GtkTreeViewSearchEqualFunc search_equal_func , gpointer search_user_data , GDestroyNotify search_destroy ) (define-function void gtk_tree_view_set_search_equal_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_search_position_func ( GtkTreeView * tree_view , GtkTreeViewSearchPositionFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_search_position_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_show_expanders ( GtkTreeView * tree_view , enabled ) (define-function void gtk_tree_view_set_show_expanders (void* int)) ;; void gtk_tree_view_set_tooltip_cell (GtkTreeView* tree_view, GtkTooltip* tooltip, GtkTreePath* path, GtkTreeViewColumn* column, GtkCellRenderer* cell) (define-function void gtk_tree_view_set_tooltip_cell (void* void* void* void* void*)) ;; void gtk_tree_view_set_tooltip_column (GtkTreeView* tree_view, gint column) (define-function void gtk_tree_view_set_tooltip_column (void* int)) void gtk_tree_view_set_tooltip_row ( GtkTreeView * tree_view , GtkTooltip * tooltip , GtkTreePath * path ) (define-function void gtk_tree_view_set_tooltip_row (void* void* void*)) ;; void gtk_tree_view_set_vadjustment (GtkTreeView* tree_view, GtkAdjustment* adjustment) (define-function void gtk_tree_view_set_vadjustment (void* void*)) void gtk_tree_view_unset_rows_drag_dest ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_unset_rows_drag_dest (void*)) void gtk_tree_view_unset_rows_drag_source ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_unset_rows_drag_source (void*)) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/sitelib/ypsilon/gtk/tree.scm
scheme
gboolean gtk_tree_drag_dest_drag_data_received (GtkTreeDragDest* drag_dest, GtkTreePath* dest, GtkSelectionData* selection_data) gboolean gtk_tree_drag_dest_row_drop_possible (GtkTreeDragDest* drag_dest, GtkTreePath* dest_path, GtkSelectionData* selection_data) gboolean gtk_tree_drag_source_drag_data_get (GtkTreeDragSource* drag_source, GtkTreePath* path, GtkSelectionData* selection_data) gboolean gtk_tree_drag_source_row_draggable (GtkTreeDragSource* drag_source, GtkTreePath* path) GtkTreeIter* gtk_tree_iter_copy (GtkTreeIter* iter) void gtk_tree_iter_free (GtkTreeIter* iter) void gtk_tree_model_filter_clear_cache (GtkTreeModelFilter* filter) gboolean gtk_tree_model_filter_convert_child_iter_to_iter (GtkTreeModelFilter* filter, GtkTreeIter* filter_iter, GtkTreeIter* child_iter) GtkTreePath* gtk_tree_model_filter_convert_child_path_to_path (GtkTreeModelFilter* filter, GtkTreePath* child_path) GtkTreePath* gtk_tree_model_filter_convert_path_to_child_path (GtkTreeModelFilter* filter, GtkTreePath* filter_path) GtkTreeModel* gtk_tree_model_filter_get_model (GtkTreeModelFilter* filter) GtkTreeModel* gtk_tree_model_filter_new (GtkTreeModel* child_model, GtkTreePath* root) void gtk_tree_model_filter_refilter (GtkTreeModelFilter* filter) void gtk_tree_model_filter_set_visible_column (GtkTreeModelFilter* filter, gint column) void gtk_tree_model_get (GtkTreeModel* tree_model, GtkTreeIter* iter, ...) GType gtk_tree_model_get_column_type (GtkTreeModel* tree_model, gint index_) GtkTreeModelFlags gtk_tree_model_get_flags (GtkTreeModel* tree_model) gboolean gtk_tree_model_get_iter (GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) gboolean gtk_tree_model_get_iter_first (GtkTreeModel* tree_model, GtkTreeIter* iter) gboolean gtk_tree_model_get_iter_from_string (GtkTreeModel* tree_model, GtkTreeIter* iter, const gchar* path_string) gint gtk_tree_model_get_n_columns (GtkTreeModel* tree_model) GtkTreePath* gtk_tree_model_get_path (GtkTreeModel* tree_model, GtkTreeIter* iter) void gtk_tree_model_get_value (GtkTreeModel* tree_model, GtkTreeIter* iter, gint column, GValue* value) gboolean gtk_tree_model_iter_children (GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreeIter* parent) gboolean gtk_tree_model_iter_has_child (GtkTreeModel* tree_model, GtkTreeIter* iter) gboolean gtk_tree_model_iter_next (GtkTreeModel* tree_model, GtkTreeIter* iter) void gtk_tree_model_ref_node (GtkTreeModel* tree_model, GtkTreeIter* iter) void gtk_tree_model_row_changed (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) void gtk_tree_model_row_deleted (GtkTreeModel* tree_model, GtkTreePath* path) void gtk_tree_model_row_has_child_toggled (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) void gtk_tree_model_row_inserted (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter) void gtk_tree_model_rows_reordered (GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter, gint* new_order) gboolean gtk_tree_model_sort_convert_child_iter_to_iter (GtkTreeModelSort* tree_model_sort, GtkTreeIter* sort_iter, GtkTreeIter* child_iter) GtkTreePath* gtk_tree_model_sort_convert_child_path_to_path (GtkTreeModelSort* tree_model_sort, GtkTreePath* child_path) void gtk_tree_model_sort_convert_iter_to_child_iter (GtkTreeModelSort* tree_model_sort, GtkTreeIter* child_iter, GtkTreeIter* sorted_iter) GtkTreePath* gtk_tree_model_sort_convert_path_to_child_path (GtkTreeModelSort* tree_model_sort, GtkTreePath* sorted_path) GtkTreeModel* gtk_tree_model_sort_get_model (GtkTreeModelSort* tree_model) gboolean gtk_tree_model_sort_iter_is_valid (GtkTreeModelSort* tree_model_sort, GtkTreeIter* iter) GtkTreeModel* gtk_tree_model_sort_new_with_model (GtkTreeModel* child_model) void gtk_tree_model_sort_reset_default_sort_func (GtkTreeModelSort* tree_model_sort) void gtk_tree_model_unref_node (GtkTreeModel* tree_model, GtkTreeIter* iter) void gtk_tree_path_append_index (GtkTreePath* path, gint index_) GtkTreePath* gtk_tree_path_copy (const GtkTreePath* path) void gtk_tree_path_down (GtkTreePath* path) void gtk_tree_path_free (GtkTreePath* path) gint gtk_tree_path_get_depth (GtkTreePath* path) gint* gtk_tree_path_get_indices (GtkTreePath* path) gboolean gtk_tree_path_is_descendant (GtkTreePath* path, GtkTreePath* ancestor) GtkTreePath* gtk_tree_path_new (void) GtkTreePath* gtk_tree_path_new_first (void) GtkTreePath* gtk_tree_path_new_from_indices (gint first_index, ...) GtkTreePath* gtk_tree_path_new_from_string (const gchar* path) void gtk_tree_path_prepend_index (GtkTreePath* path, gint index_) gchar* gtk_tree_path_to_string (GtkTreePath* path) gboolean gtk_tree_path_up (GtkTreePath* path) GtkTreeRowReference* gtk_tree_row_reference_copy (GtkTreeRowReference* reference) void gtk_tree_row_reference_deleted (GObject* proxy, GtkTreePath* path) void gtk_tree_row_reference_free (GtkTreeRowReference* reference) GtkTreeModel* gtk_tree_row_reference_get_model (GtkTreeRowReference* reference) GtkTreePath* gtk_tree_row_reference_get_path (GtkTreeRowReference* reference) void gtk_tree_row_reference_inserted (GObject* proxy, GtkTreePath* path) GtkTreeRowReference* gtk_tree_row_reference_new (GtkTreeModel* model, GtkTreePath* path) GtkTreeRowReference* gtk_tree_row_reference_new_proxy (GObject* proxy, GtkTreeModel* model, GtkTreePath* path) void gtk_tree_row_reference_reordered (GObject* proxy, GtkTreePath* path, GtkTreeIter* iter, gint* new_order) GtkSelectionMode gtk_tree_selection_get_mode (GtkTreeSelection* selection) gboolean gtk_tree_selection_get_selected (GtkTreeSelection* selection, GtkTreeModel** model, GtkTreeIter* iter) GList* gtk_tree_selection_get_selected_rows (GtkTreeSelection* selection, GtkTreeModel** model) GtkTreeView* gtk_tree_selection_get_tree_view (GtkTreeSelection* selection) gpointer gtk_tree_selection_get_user_data (GtkTreeSelection* selection) gboolean gtk_tree_selection_iter_is_selected (GtkTreeSelection* selection, GtkTreeIter* iter) gboolean gtk_tree_selection_path_is_selected (GtkTreeSelection* selection, GtkTreePath* path) void gtk_tree_selection_select_all (GtkTreeSelection* selection) void gtk_tree_selection_select_iter (GtkTreeSelection* selection, GtkTreeIter* iter) void gtk_tree_selection_select_path (GtkTreeSelection* selection, GtkTreePath* path) void gtk_tree_selection_select_range (GtkTreeSelection* selection, GtkTreePath* start_path, GtkTreePath* end_path) void gtk_tree_selection_set_mode (GtkTreeSelection* selection, GtkSelectionMode type) void gtk_tree_selection_unselect_all (GtkTreeSelection* selection) void gtk_tree_selection_unselect_iter (GtkTreeSelection* selection, GtkTreeIter* iter) void gtk_tree_selection_unselect_path (GtkTreeSelection* selection, GtkTreePath* path) void gtk_tree_selection_unselect_range (GtkTreeSelection* selection, GtkTreePath* start_path, GtkTreePath* end_path) gboolean gtk_tree_sortable_get_sort_column_id (GtkTreeSortable* sortable, gint* sort_column_id, GtkSortType* order) gboolean gtk_tree_sortable_has_default_sort_func (GtkTreeSortable* sortable) void gtk_tree_sortable_set_sort_column_id (GtkTreeSortable* sortable, gint sort_column_id, GtkSortType order) void gtk_tree_sortable_sort_column_changed (GtkTreeSortable* sortable) void gtk_tree_store_append (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent) void gtk_tree_store_insert_after (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent, GtkTreeIter* sibling) void gtk_tree_store_insert_before (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent, GtkTreeIter* sibling) gint gtk_tree_store_iter_depth (GtkTreeStore* tree_store, GtkTreeIter* iter) void gtk_tree_store_move_after (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* position) void gtk_tree_store_prepend (GtkTreeStore* tree_store, GtkTreeIter* iter, GtkTreeIter* parent) gboolean gtk_tree_store_remove (GtkTreeStore* tree_store, GtkTreeIter* iter) void gtk_tree_store_set (GtkTreeStore* tree_store, GtkTreeIter* iter, ...) void gtk_tree_store_set_value (GtkTreeStore* tree_store, GtkTreeIter* iter, gint column, GValue* value) void gtk_tree_store_swap (GtkTreeStore* tree_store, GtkTreeIter* a, GtkTreeIter* b) gint gtk_tree_view_append_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) void gtk_tree_view_collapse_all (GtkTreeView* tree_view) gboolean gtk_tree_view_column_cell_get_position (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell_renderer, gint* start_pos, gint* width) gboolean gtk_tree_view_column_cell_is_visible (GtkTreeViewColumn* tree_column) void gtk_tree_view_column_clear_attributes (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell_renderer) void gtk_tree_view_column_clicked (GtkTreeViewColumn* tree_column) void gtk_tree_view_column_focus_cell (GtkTreeViewColumn* tree_column, GtkCellRenderer* cell) gfloat gtk_tree_view_column_get_alignment (GtkTreeViewColumn* tree_column) GList* gtk_tree_view_column_get_cell_renderers (GtkTreeViewColumn* tree_column) gboolean gtk_tree_view_column_get_clickable (GtkTreeViewColumn* tree_column) gboolean gtk_tree_view_column_get_expand (GtkTreeViewColumn* tree_column) gint gtk_tree_view_column_get_max_width (GtkTreeViewColumn* tree_column) gboolean gtk_tree_view_column_get_resizable (GtkTreeViewColumn* tree_column) GtkTreeViewColumnSizing gtk_tree_view_column_get_sizing (GtkTreeViewColumn* tree_column) gint gtk_tree_view_column_get_sort_column_id (GtkTreeViewColumn* tree_column) gboolean gtk_tree_view_column_get_sort_indicator (GtkTreeViewColumn* tree_column) GtkSortType gtk_tree_view_column_get_sort_order (GtkTreeViewColumn* tree_column) gint gtk_tree_view_column_get_spacing (GtkTreeViewColumn* tree_column) GtkWidget* gtk_tree_view_column_get_widget (GtkTreeViewColumn* tree_column) GtkTreeViewColumn* gtk_tree_view_column_new (void) GtkTreeViewColumn* gtk_tree_view_column_new_with_attributes (const gchar* title, GtkCellRenderer* cell, ...) void gtk_tree_view_column_queue_resize (GtkTreeViewColumn* tree_column) void gtk_tree_view_column_set_sizing (GtkTreeViewColumn* tree_column, GtkTreeViewColumnSizing type) void gtk_tree_view_column_set_sort_order (GtkTreeViewColumn* tree_column, GtkSortType order) void gtk_tree_view_column_set_spacing (GtkTreeViewColumn* tree_column, gint spacing) void gtk_tree_view_column_set_title (GtkTreeViewColumn* tree_column, const gchar* title) void gtk_tree_view_columns_autosize (GtkTreeView* tree_view) GdkPixmap* gtk_tree_view_create_row_drag_icon (GtkTreeView* tree_view, GtkTreePath* path) void gtk_tree_view_expand_to_path (GtkTreeView* tree_view, GtkTreePath* path) GtkTreeViewColumn* gtk_tree_view_get_column (GtkTreeView* tree_view, gint n) void gtk_tree_view_get_cursor (GtkTreeView* tree_view, GtkTreePath** path, GtkTreeViewColumn** focus_column) gboolean gtk_tree_view_get_enable_search (GtkTreeView* tree_view) gboolean gtk_tree_view_get_enable_tree_lines (GtkTreeView* tree_view) GtkTreeViewColumn* gtk_tree_view_get_expander_column (GtkTreeView* tree_view) gboolean gtk_tree_view_get_fixed_height_mode (GtkTreeView* tree_view) GtkTreeViewGridLines gtk_tree_view_get_grid_lines (GtkTreeView* tree_view) GtkAdjustment* gtk_tree_view_get_hadjustment (GtkTreeView* tree_view) gboolean gtk_tree_view_get_headers_clickable (GtkTreeView* tree_view) gboolean gtk_tree_view_get_headers_visible (GtkTreeView* tree_view) gboolean gtk_tree_view_get_hover_expand (GtkTreeView* tree_view) gboolean gtk_tree_view_get_hover_selection (GtkTreeView* tree_view) GtkTreeModel* gtk_tree_view_get_model (GtkTreeView* tree_view) gboolean gtk_tree_view_get_reorderable (GtkTreeView* tree_view) GtkTreeViewRowSeparatorFunc gtk_tree_view_get_row_separator_func (GtkTreeView* tree_view) gboolean gtk_tree_view_get_rubber_banding (GtkTreeView* tree_view) gboolean gtk_tree_view_get_rules_hint (GtkTreeView* tree_view) gint gtk_tree_view_get_search_column (GtkTreeView* tree_view) GtkTreeViewSearchPositionFunc gtk_tree_view_get_search_position_func (GtkTreeView* tree_view) GtkTreeSelection* gtk_tree_view_get_selection (GtkTreeView* tree_view) gboolean gtk_tree_view_get_show_expanders (GtkTreeView* tree_view) gint gtk_tree_view_get_tooltip_column (GtkTreeView* tree_view) GtkAdjustment* gtk_tree_view_get_vadjustment (GtkTreeView* tree_view) gboolean gtk_tree_view_get_visible_range (GtkTreeView* tree_view, GtkTreePath** start_path, GtkTreePath** end_path) gint gtk_tree_view_insert_column (GtkTreeView* tree_view, GtkTreeViewColumn* column, gint position) gint gtk_tree_view_insert_column_with_attributes (GtkTreeView* tree_view, gint position, const gchar* title, GtkCellRenderer* cell, ...) gboolean gtk_tree_view_is_rubber_banding_active (GtkTreeView* tree_view) gint gtk_tree_view_remove_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) void gtk_tree_view_row_activated (GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* column) gboolean gtk_tree_view_row_expanded (GtkTreeView* tree_view, GtkTreePath* path) void gtk_tree_view_set_cursor (GtkTreeView* tree_view, GtkTreePath* path, GtkTreeViewColumn* focus_column, gboolean start_editing) void gtk_tree_view_set_enable_search (GtkTreeView* tree_view, gboolean enable_search) void gtk_tree_view_set_expander_column (GtkTreeView* tree_view, GtkTreeViewColumn* column) void gtk_tree_view_set_hadjustment (GtkTreeView* tree_view, GtkAdjustment* adjustment) void gtk_tree_view_set_headers_clickable (GtkTreeView* tree_view, gboolean setting) void gtk_tree_view_set_level_indentation (GtkTreeView* tree_view, gint indentation) void gtk_tree_view_set_model (GtkTreeView* tree_view, GtkTreeModel* model) void gtk_tree_view_set_rules_hint (GtkTreeView* tree_view, gboolean setting) void gtk_tree_view_set_search_column (GtkTreeView* tree_view, gint column) void gtk_tree_view_set_search_entry (GtkTreeView* tree_view, GtkEntry* entry) void gtk_tree_view_set_tooltip_cell (GtkTreeView* tree_view, GtkTooltip* tooltip, GtkTreePath* path, GtkTreeViewColumn* column, GtkCellRenderer* cell) void gtk_tree_view_set_tooltip_column (GtkTreeView* tree_view, gint column) void gtk_tree_view_set_vadjustment (GtkTreeView* tree_view, GtkAdjustment* adjustment) [end]
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk tree) (export gtk_tree_drag_dest_drag_data_received gtk_tree_drag_dest_get_type gtk_tree_drag_dest_row_drop_possible gtk_tree_drag_source_drag_data_delete gtk_tree_drag_source_drag_data_get gtk_tree_drag_source_get_type gtk_tree_drag_source_row_draggable gtk_tree_get_row_drag_data gtk_tree_iter_copy gtk_tree_iter_free gtk_tree_iter_get_type gtk_tree_model_filter_clear_cache gtk_tree_model_filter_convert_child_iter_to_iter gtk_tree_model_filter_convert_child_path_to_path gtk_tree_model_filter_convert_iter_to_child_iter gtk_tree_model_filter_convert_path_to_child_path gtk_tree_model_filter_get_model gtk_tree_model_filter_get_type gtk_tree_model_filter_new gtk_tree_model_filter_refilter gtk_tree_model_filter_set_modify_func gtk_tree_model_filter_set_visible_column gtk_tree_model_filter_set_visible_func gtk_tree_model_flags_get_type gtk_tree_model_foreach gtk_tree_model_get gtk_tree_model_get_column_type gtk_tree_model_get_flags gtk_tree_model_get_iter gtk_tree_model_get_iter_first gtk_tree_model_get_iter_from_string gtk_tree_model_get_n_columns gtk_tree_model_get_path gtk_tree_model_get_string_from_iter gtk_tree_model_get_type gtk_tree_model_get_valist gtk_tree_model_get_value gtk_tree_model_iter_children gtk_tree_model_iter_has_child gtk_tree_model_iter_n_children gtk_tree_model_iter_next gtk_tree_model_iter_nth_child gtk_tree_model_iter_parent gtk_tree_model_ref_node gtk_tree_model_row_changed gtk_tree_model_row_deleted gtk_tree_model_row_has_child_toggled gtk_tree_model_row_inserted gtk_tree_model_rows_reordered gtk_tree_model_sort_clear_cache gtk_tree_model_sort_convert_child_iter_to_iter gtk_tree_model_sort_convert_child_path_to_path gtk_tree_model_sort_convert_iter_to_child_iter gtk_tree_model_sort_convert_path_to_child_path gtk_tree_model_sort_get_model gtk_tree_model_sort_get_type gtk_tree_model_sort_iter_is_valid gtk_tree_model_sort_new_with_model gtk_tree_model_sort_reset_default_sort_func gtk_tree_model_unref_node gtk_tree_path_append_index gtk_tree_path_compare gtk_tree_path_copy gtk_tree_path_down gtk_tree_path_free gtk_tree_path_get_depth gtk_tree_path_get_indices gtk_tree_path_get_type gtk_tree_path_is_ancestor gtk_tree_path_is_descendant gtk_tree_path_new gtk_tree_path_new_first gtk_tree_path_new_from_indices gtk_tree_path_new_from_string gtk_tree_path_next gtk_tree_path_prepend_index gtk_tree_path_prev gtk_tree_path_to_string gtk_tree_path_up gtk_tree_row_reference_copy gtk_tree_row_reference_deleted gtk_tree_row_reference_free gtk_tree_row_reference_get_model gtk_tree_row_reference_get_path gtk_tree_row_reference_get_type gtk_tree_row_reference_inserted gtk_tree_row_reference_new gtk_tree_row_reference_new_proxy gtk_tree_row_reference_reordered gtk_tree_row_reference_valid gtk_tree_selection_count_selected_rows gtk_tree_selection_get_mode gtk_tree_selection_get_select_function gtk_tree_selection_get_selected gtk_tree_selection_get_selected_rows gtk_tree_selection_get_tree_view gtk_tree_selection_get_type gtk_tree_selection_get_user_data gtk_tree_selection_iter_is_selected gtk_tree_selection_path_is_selected gtk_tree_selection_select_all gtk_tree_selection_select_iter gtk_tree_selection_select_path gtk_tree_selection_select_range gtk_tree_selection_selected_foreach gtk_tree_selection_set_mode gtk_tree_selection_set_select_function gtk_tree_selection_unselect_all gtk_tree_selection_unselect_iter gtk_tree_selection_unselect_path gtk_tree_selection_unselect_range gtk_tree_set_row_drag_data gtk_tree_sortable_get_sort_column_id gtk_tree_sortable_get_type gtk_tree_sortable_has_default_sort_func gtk_tree_sortable_set_default_sort_func gtk_tree_sortable_set_sort_column_id gtk_tree_sortable_set_sort_func gtk_tree_sortable_sort_column_changed gtk_tree_store_append gtk_tree_store_clear gtk_tree_store_get_type gtk_tree_store_insert gtk_tree_store_insert_after gtk_tree_store_insert_before gtk_tree_store_insert_with_values gtk_tree_store_insert_with_valuesv gtk_tree_store_is_ancestor gtk_tree_store_iter_depth gtk_tree_store_iter_is_valid gtk_tree_store_move_after gtk_tree_store_move_before gtk_tree_store_new gtk_tree_store_newv gtk_tree_store_prepend gtk_tree_store_remove gtk_tree_store_reorder gtk_tree_store_set gtk_tree_store_set_column_types gtk_tree_store_set_valist gtk_tree_store_set_value gtk_tree_store_set_valuesv gtk_tree_store_swap gtk_tree_view_append_column gtk_tree_view_collapse_all gtk_tree_view_collapse_row gtk_tree_view_column_add_attribute gtk_tree_view_column_cell_get_position gtk_tree_view_column_cell_get_size gtk_tree_view_column_cell_is_visible gtk_tree_view_column_cell_set_cell_data gtk_tree_view_column_clear gtk_tree_view_column_clear_attributes gtk_tree_view_column_clicked gtk_tree_view_column_focus_cell gtk_tree_view_column_get_alignment gtk_tree_view_column_get_cell_renderers gtk_tree_view_column_get_clickable gtk_tree_view_column_get_expand gtk_tree_view_column_get_fixed_width gtk_tree_view_column_get_max_width gtk_tree_view_column_get_min_width gtk_tree_view_column_get_reorderable gtk_tree_view_column_get_resizable gtk_tree_view_column_get_sizing gtk_tree_view_column_get_sort_column_id gtk_tree_view_column_get_sort_indicator gtk_tree_view_column_get_sort_order gtk_tree_view_column_get_spacing gtk_tree_view_column_get_title gtk_tree_view_column_get_tree_view gtk_tree_view_column_get_type gtk_tree_view_column_get_visible gtk_tree_view_column_get_widget gtk_tree_view_column_get_width gtk_tree_view_column_new gtk_tree_view_column_new_with_attributes gtk_tree_view_column_pack_end gtk_tree_view_column_pack_start gtk_tree_view_column_queue_resize gtk_tree_view_column_set_alignment gtk_tree_view_column_set_attributes gtk_tree_view_column_set_cell_data_func gtk_tree_view_column_set_clickable gtk_tree_view_column_set_expand gtk_tree_view_column_set_fixed_width gtk_tree_view_column_set_max_width gtk_tree_view_column_set_min_width gtk_tree_view_column_set_reorderable gtk_tree_view_column_set_resizable gtk_tree_view_column_set_sizing gtk_tree_view_column_set_sort_column_id gtk_tree_view_column_set_sort_indicator gtk_tree_view_column_set_sort_order gtk_tree_view_column_set_spacing gtk_tree_view_column_set_title gtk_tree_view_column_set_visible gtk_tree_view_column_set_widget gtk_tree_view_column_sizing_get_type gtk_tree_view_columns_autosize gtk_tree_view_convert_bin_window_to_tree_coords gtk_tree_view_convert_bin_window_to_widget_coords gtk_tree_view_convert_tree_to_bin_window_coords gtk_tree_view_convert_tree_to_widget_coords gtk_tree_view_convert_widget_to_bin_window_coords gtk_tree_view_convert_widget_to_tree_coords gtk_tree_view_create_row_drag_icon gtk_tree_view_drop_position_get_type gtk_tree_view_enable_model_drag_dest gtk_tree_view_enable_model_drag_source gtk_tree_view_expand_all gtk_tree_view_expand_row gtk_tree_view_expand_to_path gtk_tree_view_get_background_area gtk_tree_view_get_bin_window gtk_tree_view_get_cell_area gtk_tree_view_get_column gtk_tree_view_get_columns gtk_tree_view_get_cursor gtk_tree_view_get_dest_row_at_pos gtk_tree_view_get_drag_dest_row gtk_tree_view_get_enable_search gtk_tree_view_get_enable_tree_lines gtk_tree_view_get_expander_column gtk_tree_view_get_fixed_height_mode gtk_tree_view_get_grid_lines gtk_tree_view_get_hadjustment gtk_tree_view_get_headers_clickable gtk_tree_view_get_headers_visible gtk_tree_view_get_hover_expand gtk_tree_view_get_hover_selection gtk_tree_view_get_level_indentation gtk_tree_view_get_model gtk_tree_view_get_path_at_pos gtk_tree_view_get_reorderable gtk_tree_view_get_row_separator_func gtk_tree_view_get_rubber_banding gtk_tree_view_get_rules_hint gtk_tree_view_get_search_column gtk_tree_view_get_search_entry gtk_tree_view_get_search_equal_func gtk_tree_view_get_search_position_func gtk_tree_view_get_selection gtk_tree_view_get_show_expanders gtk_tree_view_get_tooltip_column gtk_tree_view_get_tooltip_context gtk_tree_view_get_type gtk_tree_view_get_vadjustment gtk_tree_view_get_visible_range gtk_tree_view_get_visible_rect gtk_tree_view_grid_lines_get_type gtk_tree_view_insert_column gtk_tree_view_insert_column_with_attributes gtk_tree_view_insert_column_with_data_func gtk_tree_view_is_rubber_banding_active gtk_tree_view_map_expanded_rows gtk_tree_view_mode_get_type gtk_tree_view_move_column_after gtk_tree_view_new gtk_tree_view_new_with_model gtk_tree_view_remove_column gtk_tree_view_row_activated gtk_tree_view_row_expanded gtk_tree_view_scroll_to_cell gtk_tree_view_scroll_to_point gtk_tree_view_set_column_drag_function gtk_tree_view_set_cursor gtk_tree_view_set_cursor_on_cell gtk_tree_view_set_destroy_count_func gtk_tree_view_set_drag_dest_row gtk_tree_view_set_enable_search gtk_tree_view_set_enable_tree_lines gtk_tree_view_set_expander_column gtk_tree_view_set_fixed_height_mode gtk_tree_view_set_grid_lines gtk_tree_view_set_hadjustment gtk_tree_view_set_headers_clickable gtk_tree_view_set_headers_visible gtk_tree_view_set_hover_expand gtk_tree_view_set_hover_selection gtk_tree_view_set_level_indentation gtk_tree_view_set_model gtk_tree_view_set_reorderable gtk_tree_view_set_row_separator_func gtk_tree_view_set_rubber_banding gtk_tree_view_set_rules_hint gtk_tree_view_set_search_column gtk_tree_view_set_search_entry gtk_tree_view_set_search_equal_func gtk_tree_view_set_search_position_func gtk_tree_view_set_show_expanders gtk_tree_view_set_tooltip_cell gtk_tree_view_set_tooltip_column gtk_tree_view_set_tooltip_row gtk_tree_view_set_vadjustment gtk_tree_view_unset_rows_drag_dest gtk_tree_view_unset_rows_drag_source) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) (define-function int gtk_tree_drag_dest_drag_data_received (void* void* void*)) GType gtk_tree_drag_dest_get_type ( void ) (define-function unsigned-long gtk_tree_drag_dest_get_type ()) (define-function int gtk_tree_drag_dest_row_drop_possible (void* void* void*)) ( GtkTreeDragSource * drag_source , GtkTreePath * path ) (define-function int gtk_tree_drag_source_drag_data_delete (void* void*)) (define-function int gtk_tree_drag_source_drag_data_get (void* void* void*)) GType gtk_tree_drag_source_get_type ( void ) (define-function unsigned-long gtk_tree_drag_source_get_type ()) (define-function int gtk_tree_drag_source_row_draggable (void* void*)) ( GtkSelectionData * selection_data , GtkTreeModel * * tree_model , GtkTreePath * * path ) (define-function int gtk_tree_get_row_drag_data (void* void* void*)) (define-function void* gtk_tree_iter_copy (void*)) (define-function void gtk_tree_iter_free (void*)) GType gtk_tree_iter_get_type ( void ) (define-function unsigned-long gtk_tree_iter_get_type ()) (define-function void gtk_tree_model_filter_clear_cache (void*)) (define-function int gtk_tree_model_filter_convert_child_iter_to_iter (void* void* void*)) (define-function void* gtk_tree_model_filter_convert_child_path_to_path (void* void*)) void ( GtkTreeModelFilter * filter , GtkTreeIter * child_iter , GtkTreeIter * filter_iter ) (define-function void gtk_tree_model_filter_convert_iter_to_child_iter (void* void* void*)) (define-function void* gtk_tree_model_filter_convert_path_to_child_path (void* void*)) (define-function void* gtk_tree_model_filter_get_model (void*)) GType gtk_tree_model_filter_get_type ( void ) (define-function unsigned-long gtk_tree_model_filter_get_type ()) (define-function void* gtk_tree_model_filter_new (void* void*)) (define-function void gtk_tree_model_filter_refilter (void*)) void gtk_tree_model_filter_set_modify_func ( GtkTreeModelFilter * filter , gint n_columns , GType * types , GtkTreeModelFilterModifyFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_model_filter_set_modify_func (void* int void* (c-callback void (void* void* void* int void*)) void* (c-callback void (void*)))) (define-function void gtk_tree_model_filter_set_visible_column (void* int)) void gtk_tree_model_filter_set_visible_func ( GtkTreeModelFilter * filter , func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_model_filter_set_visible_func (void* (c-callback int (void* void* void*)) void* (c-callback void (void*)))) GType gtk_tree_model_flags_get_type ( void ) (define-function unsigned-long gtk_tree_model_flags_get_type ()) void ( GtkTreeModel * model , GtkTreeModelForeachFunc func , gpointer user_data ) (define-function void gtk_tree_model_foreach (void* (c-callback int (void* void* void* void*)) void*)) (define-function void gtk_tree_model_get (void* void* ...)) (define-function unsigned-long gtk_tree_model_get_column_type (void* int)) (define-function int gtk_tree_model_get_flags (void*)) (define-function int gtk_tree_model_get_iter (void* void* void*)) (define-function int gtk_tree_model_get_iter_first (void* void*)) (define-function int gtk_tree_model_get_iter_from_string (void* void* char*)) (define-function int gtk_tree_model_get_n_columns (void*)) (define-function void* gtk_tree_model_get_path (void* void*)) gchar * gtk_tree_model_get_string_from_iter ( GtkTreeModel * tree_model , GtkTreeIter * iter ) (define-function char* gtk_tree_model_get_string_from_iter (void* void*)) GType gtk_tree_model_get_type ( void ) (define-function unsigned-long gtk_tree_model_get_type ()) void gtk_tree_model_get_valist ( GtkTreeModel * tree_model , GtkTreeIter * iter , va_list ) (define-function/va_list void gtk_tree_model_get_valist (void* void* va_list)) (define-function void gtk_tree_model_get_value (void* void* int void*)) (define-function int gtk_tree_model_iter_children (void* void* void*)) (define-function int gtk_tree_model_iter_has_child (void* void*)) ( GtkTreeModel * tree_model , GtkTreeIter * iter ) (define-function int gtk_tree_model_iter_n_children (void* void*)) (define-function int gtk_tree_model_iter_next (void* void*)) gboolean gtk_tree_model_iter_nth_child ( GtkTreeModel * tree_model , GtkTreeIter * iter , GtkTreeIter * parent , gint n ) (define-function int gtk_tree_model_iter_nth_child (void* void* void* int)) ( GtkTreeModel * tree_model , GtkTreeIter * iter , GtkTreeIter * child ) (define-function int gtk_tree_model_iter_parent (void* void* void*)) (define-function void gtk_tree_model_ref_node (void* void*)) (define-function void gtk_tree_model_row_changed (void* void* void*)) (define-function void gtk_tree_model_row_deleted (void* void*)) (define-function void gtk_tree_model_row_has_child_toggled (void* void* void*)) (define-function void gtk_tree_model_row_inserted (void* void* void*)) (define-function void gtk_tree_model_rows_reordered (void* void* void* void*)) void gtk_tree_model_sort_clear_cache ( GtkTreeModelSort * tree_model_sort ) (define-function void gtk_tree_model_sort_clear_cache (void*)) (define-function int gtk_tree_model_sort_convert_child_iter_to_iter (void* void* void*)) (define-function void* gtk_tree_model_sort_convert_child_path_to_path (void* void*)) (define-function void gtk_tree_model_sort_convert_iter_to_child_iter (void* void* void*)) (define-function void* gtk_tree_model_sort_convert_path_to_child_path (void* void*)) (define-function void* gtk_tree_model_sort_get_model (void*)) GType gtk_tree_model_sort_get_type ( void ) (define-function unsigned-long gtk_tree_model_sort_get_type ()) (define-function int gtk_tree_model_sort_iter_is_valid (void* void*)) (define-function void* gtk_tree_model_sort_new_with_model (void*)) (define-function void gtk_tree_model_sort_reset_default_sort_func (void*)) (define-function void gtk_tree_model_unref_node (void* void*)) (define-function void gtk_tree_path_append_index (void* int)) ( const GtkTreePath * a , const GtkTreePath * b ) (define-function int gtk_tree_path_compare (void* void*)) (define-function void* gtk_tree_path_copy (void*)) (define-function void gtk_tree_path_down (void*)) (define-function void gtk_tree_path_free (void*)) (define-function int gtk_tree_path_get_depth (void*)) (define-function void* gtk_tree_path_get_indices (void*)) GType gtk_tree_path_get_type ( void ) (define-function unsigned-long gtk_tree_path_get_type ()) ( GtkTreePath * path , GtkTreePath * descendant ) (define-function int gtk_tree_path_is_ancestor (void* void*)) (define-function int gtk_tree_path_is_descendant (void* void*)) (define-function void* gtk_tree_path_new ()) (define-function void* gtk_tree_path_new_first ()) (define-function void* gtk_tree_path_new_from_indices (int ...)) (define-function void* gtk_tree_path_new_from_string (char*)) void ( GtkTreePath * path ) (define-function void gtk_tree_path_next (void*)) (define-function void gtk_tree_path_prepend_index (void* int)) ( GtkTreePath * path ) (define-function int gtk_tree_path_prev (void*)) (define-function char* gtk_tree_path_to_string (void*)) (define-function int gtk_tree_path_up (void*)) (define-function void* gtk_tree_row_reference_copy (void*)) (define-function void gtk_tree_row_reference_deleted (void* void*)) (define-function void gtk_tree_row_reference_free (void*)) (define-function void* gtk_tree_row_reference_get_model (void*)) (define-function void* gtk_tree_row_reference_get_path (void*)) GType gtk_tree_row_reference_get_type ( void ) (define-function unsigned-long gtk_tree_row_reference_get_type ()) (define-function void gtk_tree_row_reference_inserted (void* void*)) (define-function void* gtk_tree_row_reference_new (void* void*)) (define-function void* gtk_tree_row_reference_new_proxy (void* void* void*)) (define-function void gtk_tree_row_reference_reordered (void* void* void* void*)) ( GtkTreeRowReference * reference ) (define-function int gtk_tree_row_reference_valid (void*)) ( GtkTreeSelection * selection ) (define-function int gtk_tree_selection_count_selected_rows (void*)) (define-function int gtk_tree_selection_get_mode (void*)) GtkTreeSelectionFunc gtk_tree_selection_get_select_function ( GtkTreeSelection * selection ) (define-function void* gtk_tree_selection_get_select_function (void*)) (define-function int gtk_tree_selection_get_selected (void* void* void*)) (define-function void* gtk_tree_selection_get_selected_rows (void* void*)) (define-function void* gtk_tree_selection_get_tree_view (void*)) GType gtk_tree_selection_get_type ( void ) (define-function unsigned-long gtk_tree_selection_get_type ()) (define-function void* gtk_tree_selection_get_user_data (void*)) (define-function int gtk_tree_selection_iter_is_selected (void* void*)) (define-function int gtk_tree_selection_path_is_selected (void* void*)) (define-function void gtk_tree_selection_select_all (void*)) (define-function void gtk_tree_selection_select_iter (void* void*)) (define-function void gtk_tree_selection_select_path (void* void*)) (define-function void gtk_tree_selection_select_range (void* void* void*)) void ( GtkTreeSelection * selection , GtkTreeSelectionForeachFunc func , gpointer data ) (define-function void gtk_tree_selection_selected_foreach (void* (c-callback void (void* void* void* void*)) void*)) (define-function void gtk_tree_selection_set_mode (void* int)) void gtk_tree_selection_set_select_function ( GtkTreeSelection * selection , GtkTreeSelectionFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_selection_set_select_function (void* void* void* (c-callback void (void*)))) (define-function void gtk_tree_selection_unselect_all (void*)) (define-function void gtk_tree_selection_unselect_iter (void* void*)) (define-function void gtk_tree_selection_unselect_path (void* void*)) (define-function void gtk_tree_selection_unselect_range (void* void* void*)) ( GtkSelectionData * selection_data , GtkTreeModel * tree_model , GtkTreePath * path ) (define-function int gtk_tree_set_row_drag_data (void* void* void*)) (define-function int gtk_tree_sortable_get_sort_column_id (void* void* void*)) GType gtk_tree_sortable_get_type ( void ) (define-function unsigned-long gtk_tree_sortable_get_type ()) (define-function int gtk_tree_sortable_has_default_sort_func (void*)) void gtk_tree_sortable_set_default_sort_func ( GtkTreeSortable * sortable , GtkTreeIterCompareFunc sort_func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_sortable_set_default_sort_func (void* (c-callback int (void* void* void* void*)) void* (c-callback void (void*)))) (define-function void gtk_tree_sortable_set_sort_column_id (void* int int)) void gtk_tree_sortable_set_sort_func ( GtkTreeSortable * sortable , gint sort_column_id , GtkTreeIterCompareFunc sort_func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_sortable_set_sort_func (void* int (c-callback int (void* void* void* void*)) void* (c-callback void (void*)))) (define-function void gtk_tree_sortable_sort_column_changed (void*)) (define-function void gtk_tree_store_append (void* void* void*)) void ( GtkTreeStore * tree_store ) (define-function void gtk_tree_store_clear (void*)) GType gtk_tree_store_get_type ( void ) (define-function unsigned-long gtk_tree_store_get_type ()) void ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position ) (define-function void gtk_tree_store_insert (void* void* void* int)) (define-function void gtk_tree_store_insert_after (void* void* void* void*)) (define-function void gtk_tree_store_insert_before (void* void* void* void*)) void gtk_tree_store_insert_with_values ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position , ... ) (define-function void gtk_tree_store_insert_with_values (void* void* void* int ...)) void gtk_tree_store_insert_with_valuesv ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * parent , gint position , gint * columns , GValue * values , ) (define-function void gtk_tree_store_insert_with_valuesv (void* void* void* int void* void* int)) ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * descendant ) (define-function int gtk_tree_store_is_ancestor (void* void* void*)) (define-function int gtk_tree_store_iter_depth (void* void*)) ( GtkTreeStore * tree_store , GtkTreeIter * iter ) (define-function int gtk_tree_store_iter_is_valid (void* void*)) (define-function void gtk_tree_store_move_after (void* void* void*)) void ( GtkTreeStore * tree_store , GtkTreeIter * iter , GtkTreeIter * position ) (define-function void gtk_tree_store_move_before (void* void* void*)) GtkTreeStore * gtk_tree_store_new ( gint n_columns , ... ) (define-function void* gtk_tree_store_new (int ...)) GtkTreeStore * gtk_tree_store_newv ( gint n_columns , GType * types ) (define-function void* gtk_tree_store_newv (int void*)) (define-function void gtk_tree_store_prepend (void* void* void*)) (define-function int gtk_tree_store_remove (void* void*)) void gtk_tree_store_reorder ( GtkTreeStore * tree_store , GtkTreeIter * parent , gint * new_order ) (define-function void gtk_tree_store_reorder (void* void* void*)) (define-function void gtk_tree_store_set (void* void* ...)) void gtk_tree_store_set_column_types ( GtkTreeStore * tree_store , gint n_columns , GType * types ) (define-function void gtk_tree_store_set_column_types (void* int void*)) void gtk_tree_store_set_valist ( GtkTreeStore * tree_store , GtkTreeIter * iter , va_list ) (define-function/va_list void gtk_tree_store_set_valist (void* void* va_list)) (define-function void gtk_tree_store_set_value (void* void* int void*)) void gtk_tree_store_set_valuesv ( GtkTreeStore * tree_store , GtkTreeIter * iter , gint * columns , GValue * values , ) (define-function void gtk_tree_store_set_valuesv (void* void* void* void* int)) (define-function void gtk_tree_store_swap (void* void* void*)) (define-function int gtk_tree_view_append_column (void* void*)) (define-function void gtk_tree_view_collapse_all (void*)) gboolean gtk_tree_view_collapse_row ( GtkTreeView * tree_view , GtkTreePath * path ) (define-function int gtk_tree_view_collapse_row (void* void*)) void ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , const gchar * attribute , gint column ) (define-function void gtk_tree_view_column_add_attribute (void* void* char* int)) (define-function int gtk_tree_view_column_cell_get_position (void* void* void* void*)) void gtk_tree_view_column_cell_get_size ( GtkTreeViewColumn * tree_column , const GdkRectangle * cell_area , gint * x_offset , gint * y_offset , gint * width , gint * height ) (define-function void gtk_tree_view_column_cell_get_size (void* void* void* void* void* void*)) (define-function int gtk_tree_view_column_cell_is_visible (void*)) void gtk_tree_view_column_cell_set_cell_data ( GtkTreeViewColumn * tree_column , GtkTreeModel * tree_model , GtkTreeIter * iter , , is_expanded ) (define-function void gtk_tree_view_column_cell_set_cell_data (void* void* void* int int)) void gtk_tree_view_column_clear ( GtkTreeViewColumn * tree_column ) (define-function void gtk_tree_view_column_clear (void*)) (define-function void gtk_tree_view_column_clear_attributes (void* void*)) (define-function void gtk_tree_view_column_clicked (void*)) (define-function void gtk_tree_view_column_focus_cell (void* void*)) (define-function float gtk_tree_view_column_get_alignment (void*)) (define-function void* gtk_tree_view_column_get_cell_renderers (void*)) (define-function int gtk_tree_view_column_get_clickable (void*)) (define-function int gtk_tree_view_column_get_expand (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_fixed_width (void*)) (define-function int gtk_tree_view_column_get_max_width (void*)) gint gtk_tree_view_column_get_min_width ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_min_width (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_reorderable (void*)) (define-function int gtk_tree_view_column_get_resizable (void*)) (define-function int gtk_tree_view_column_get_sizing (void*)) (define-function int gtk_tree_view_column_get_sort_column_id (void*)) (define-function int gtk_tree_view_column_get_sort_indicator (void*)) (define-function int gtk_tree_view_column_get_sort_order (void*)) (define-function int gtk_tree_view_column_get_spacing (void*)) const gchar * ( GtkTreeViewColumn * tree_column ) (define-function char* gtk_tree_view_column_get_title (void*)) GtkWidget * gtk_tree_view_column_get_tree_view ( GtkTreeViewColumn * tree_column ) (define-function void* gtk_tree_view_column_get_tree_view (void*)) GType gtk_tree_view_column_get_type ( void ) (define-function unsigned-long gtk_tree_view_column_get_type ()) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_visible (void*)) (define-function void* gtk_tree_view_column_get_widget (void*)) ( GtkTreeViewColumn * tree_column ) (define-function int gtk_tree_view_column_get_width (void*)) (define-function void* gtk_tree_view_column_new ()) (define-function void* gtk_tree_view_column_new_with_attributes (char* void* ...)) void gtk_tree_view_column_pack_end ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell , expand ) (define-function void gtk_tree_view_column_pack_end (void* void* int)) void gtk_tree_view_column_pack_start ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell , expand ) (define-function void gtk_tree_view_column_pack_start (void* void* int)) (define-function void gtk_tree_view_column_queue_resize (void*)) void gtk_tree_view_column_set_alignment ( GtkTreeViewColumn * tree_column , xalign ) (define-function void gtk_tree_view_column_set_alignment (void* float)) void gtk_tree_view_column_set_attributes ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , ... ) (define-function void gtk_tree_view_column_set_attributes (void* void* ...)) void gtk_tree_view_column_set_cell_data_func ( GtkTreeViewColumn * tree_column , GtkCellRenderer * cell_renderer , GtkTreeCellDataFunc func , , GDestroyNotify destroy ) (define-function void gtk_tree_view_column_set_cell_data_func (void* void* (c-callback void (void* void* void* void* void*)) void* (c-callback void (void*)))) void ( GtkTreeViewColumn * tree_column , clickable ) (define-function void gtk_tree_view_column_set_clickable (void* int)) void gtk_tree_view_column_set_expand ( GtkTreeViewColumn * tree_column , expand ) (define-function void gtk_tree_view_column_set_expand (void* int)) void gtk_tree_view_column_set_fixed_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_fixed_width (void* int)) void gtk_tree_view_column_set_max_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_max_width (void* int)) void gtk_tree_view_column_set_min_width ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_min_width (void* int)) void gtk_tree_view_column_set_reorderable ( GtkTreeViewColumn * tree_column , reorderable ) (define-function void gtk_tree_view_column_set_reorderable (void* int)) void gtk_tree_view_column_set_resizable ( GtkTreeViewColumn * tree_column , resizable ) (define-function void gtk_tree_view_column_set_resizable (void* int)) (define-function void gtk_tree_view_column_set_sizing (void* int)) void gtk_tree_view_column_set_sort_column_id ( GtkTreeViewColumn * tree_column , sort_column_id ) (define-function void gtk_tree_view_column_set_sort_column_id (void* int)) void gtk_tree_view_column_set_sort_indicator ( GtkTreeViewColumn * tree_column , ) (define-function void gtk_tree_view_column_set_sort_indicator (void* int)) (define-function void gtk_tree_view_column_set_sort_order (void* int)) (define-function void gtk_tree_view_column_set_spacing (void* int)) (define-function void gtk_tree_view_column_set_title (void* char*)) void gtk_tree_view_column_set_visible ( GtkTreeViewColumn * tree_column , visible ) (define-function void gtk_tree_view_column_set_visible (void* int)) void gtk_tree_view_column_set_widget ( GtkTreeViewColumn * tree_column , GtkWidget * widget ) (define-function void gtk_tree_view_column_set_widget (void* void*)) GType gtk_tree_view_column_sizing_get_type ( void ) (define-function unsigned-long gtk_tree_view_column_sizing_get_type ()) (define-function void gtk_tree_view_columns_autosize (void*)) void gtk_tree_view_convert_bin_window_to_tree_coords ( GtkTreeView * tree_view , bx , by , gint * tx , gint * ty ) (define-function void gtk_tree_view_convert_bin_window_to_tree_coords (void* int int void* void*)) void gtk_tree_view_convert_bin_window_to_widget_coords ( GtkTreeView * tree_view , bx , by , gint * wx , gint * wy ) (define-function void gtk_tree_view_convert_bin_window_to_widget_coords (void* int int void* void*)) void gtk_tree_view_convert_tree_to_bin_window_coords ( GtkTreeView * tree_view , , , * bx , gint * by ) (define-function void gtk_tree_view_convert_tree_to_bin_window_coords (void* int int void* void*)) void gtk_tree_view_convert_tree_to_widget_coords ( GtkTreeView * tree_view , , , * wx , gint * wy ) (define-function void gtk_tree_view_convert_tree_to_widget_coords (void* int int void* void*)) void gtk_tree_view_convert_widget_to_bin_window_coords ( GtkTreeView * tree_view , , gint wy , gint * bx , gint * by ) (define-function void gtk_tree_view_convert_widget_to_bin_window_coords (void* int int void* void*)) void gtk_tree_view_convert_widget_to_tree_coords ( GtkTreeView * tree_view , , gint wy , gint * tx , gint * ty ) (define-function void gtk_tree_view_convert_widget_to_tree_coords (void* int int void* void*)) (define-function void* gtk_tree_view_create_row_drag_icon (void* void*)) GType gtk_tree_view_drop_position_get_type ( void ) (define-function unsigned-long gtk_tree_view_drop_position_get_type ()) void gtk_tree_view_enable_model_drag_dest ( GtkTreeView * tree_view , const GtkTargetEntry * targets , gint n_targets , GdkDragAction actions ) (define-function void gtk_tree_view_enable_model_drag_dest (void* void* int int)) void gtk_tree_view_enable_model_drag_source ( GtkTreeView * tree_view , GdkModifierType start_button_mask , const GtkTargetEntry * targets , gint n_targets , GdkDragAction actions ) (define-function void gtk_tree_view_enable_model_drag_source (void* int void* int int)) void gtk_tree_view_expand_all ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_expand_all (void*)) gboolean gtk_tree_view_expand_row ( GtkTreeView * tree_view , GtkTreePath * path , ) (define-function int gtk_tree_view_expand_row (void* void* int)) (define-function void gtk_tree_view_expand_to_path (void* void*)) void gtk_tree_view_get_background_area ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , GdkRectangle * rect ) (define-function void gtk_tree_view_get_background_area (void* void* void* void*)) GdkWindow * gtk_tree_view_get_bin_window ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_bin_window (void*)) void gtk_tree_view_get_cell_area ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , GdkRectangle * rect ) (define-function void gtk_tree_view_get_cell_area (void* void* void* void*)) (define-function void* gtk_tree_view_get_column (void* int)) GList * ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_columns (void*)) (define-function void gtk_tree_view_get_cursor (void* void* void*)) gboolean gtk_tree_view_get_dest_row_at_pos ( GtkTreeView * tree_view , , , GtkTreePath * * path , GtkTreeViewDropPosition * pos ) (define-function int gtk_tree_view_get_dest_row_at_pos (void* int int void* void*)) void ( GtkTreeView * tree_view , GtkTreePath * * path , GtkTreeViewDropPosition * pos ) (define-function void gtk_tree_view_get_drag_dest_row (void* void* void*)) (define-function int gtk_tree_view_get_enable_search (void*)) (define-function int gtk_tree_view_get_enable_tree_lines (void*)) (define-function void* gtk_tree_view_get_expander_column (void*)) (define-function int gtk_tree_view_get_fixed_height_mode (void*)) (define-function int gtk_tree_view_get_grid_lines (void*)) (define-function void* gtk_tree_view_get_hadjustment (void*)) (define-function int gtk_tree_view_get_headers_clickable (void*)) (define-function int gtk_tree_view_get_headers_visible (void*)) (define-function int gtk_tree_view_get_hover_expand (void*)) (define-function int gtk_tree_view_get_hover_selection (void*)) gint gtk_tree_view_get_level_indentation ( GtkTreeView * tree_view ) (define-function int gtk_tree_view_get_level_indentation (void*)) (define-function void* gtk_tree_view_get_model (void*)) gboolean gtk_tree_view_get_path_at_pos ( GtkTreeView * tree_view , , gint y , GtkTreePath * * path , GtkTreeViewColumn * * column , gint * cell_x , gint * cell_y ) (define-function int gtk_tree_view_get_path_at_pos (void* int int void* void* void* void*)) (define-function int gtk_tree_view_get_reorderable (void*)) (define-function void* gtk_tree_view_get_row_separator_func (void*)) (define-function int gtk_tree_view_get_rubber_banding (void*)) (define-function int gtk_tree_view_get_rules_hint (void*)) (define-function int gtk_tree_view_get_search_column (void*)) GtkEntry * gtk_tree_view_get_search_entry ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_search_entry (void*)) GtkTreeViewSearchEqualFunc gtk_tree_view_get_search_equal_func ( GtkTreeView * tree_view ) (define-function void* gtk_tree_view_get_search_equal_func (void*)) (define-function void* gtk_tree_view_get_search_position_func (void*)) (define-function void* gtk_tree_view_get_selection (void*)) (define-function int gtk_tree_view_get_show_expanders (void*)) (define-function int gtk_tree_view_get_tooltip_column (void*)) gboolean gtk_tree_view_get_tooltip_context(GtkTreeView * tree_view , gint * x , gint * y , , GtkTreeModel * * model , GtkTreePath * * path , GtkTreeIter * iter ) (define-function int gtk_tree_view_get_tooltip_context (void* void* void* int void* void* void*)) GType gtk_tree_view_get_type ( void ) (define-function unsigned-long gtk_tree_view_get_type ()) (define-function void* gtk_tree_view_get_vadjustment (void*)) (define-function int gtk_tree_view_get_visible_range (void* void* void*)) void gtk_tree_view_get_visible_rect ( GtkTreeView * tree_view , GdkRectangle * visible_rect ) (define-function void gtk_tree_view_get_visible_rect (void* void*)) GType gtk_tree_view_grid_lines_get_type ( void ) (define-function unsigned-long gtk_tree_view_grid_lines_get_type ()) (define-function int gtk_tree_view_insert_column (void* void* int)) (define-function int gtk_tree_view_insert_column_with_attributes (void* int char* void* ...)) gint gtk_tree_view_insert_column_with_data_func ( GtkTreeView * tree_view , gint position , const gchar * title , GtkCellRenderer * cell , GtkTreeCellDataFunc func , gpointer data , ) (define-function int gtk_tree_view_insert_column_with_data_func (void* int char* void* (c-callback void (void* void* void* void* void*)) void* (c-callback void (void*)))) (define-function int gtk_tree_view_is_rubber_banding_active (void*)) void gtk_tree_view_map_expanded_rows ( GtkTreeView * tree_view , GtkTreeViewMappingFunc func , gpointer data ) (define-function void gtk_tree_view_map_expanded_rows (void* (c-callback void (void* void* void*)) void*)) GType gtk_tree_view_mode_get_type ( void ) (define-function unsigned-long gtk_tree_view_mode_get_type ()) void ( GtkTreeView * tree_view , GtkTreeViewColumn * column , GtkTreeViewColumn * base_column ) (define-function void gtk_tree_view_move_column_after (void* void* void*)) GtkWidget * gtk_tree_view_new ( void ) (define-function void* gtk_tree_view_new ()) GtkWidget * gtk_tree_view_new_with_model ( GtkTreeModel * model ) (define-function void* gtk_tree_view_new_with_model (void*)) (define-function int gtk_tree_view_remove_column (void* void*)) (define-function void gtk_tree_view_row_activated (void* void* void*)) (define-function int gtk_tree_view_row_expanded (void* void*)) void gtk_tree_view_scroll_to_cell ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * column , , row_align , ) (define-function void gtk_tree_view_scroll_to_cell (void* void* void* int float float)) void gtk_tree_view_scroll_to_point ( GtkTreeView * tree_view , gint tree_x , ) (define-function void gtk_tree_view_scroll_to_point (void* int int)) void gtk_tree_view_set_column_drag_function ( GtkTreeView * tree_view , GtkTreeViewColumnDropFunc func , gpointer user_data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_column_drag_function (void* (c-callback int (void* void* void* void* void*)) void* (c-callback void (void*)))) (define-function void gtk_tree_view_set_cursor (void* void* void* int)) void gtk_tree_view_set_cursor_on_cell ( GtkTreeView * tree_view , GtkTreePath * path , GtkTreeViewColumn * focus_column , GtkCellRenderer * focus_cell , ) (define-function void gtk_tree_view_set_cursor_on_cell (void* void* void* void* int)) void gtk_tree_view_set_destroy_count_func ( GtkTreeView * tree_view , GtkTreeDestroyCountFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_destroy_count_func (void* (c-callback void (void* void* int void*)) void* (c-callback void (void*)))) void gtk_tree_view_set_drag_dest_row ( GtkTreeView * tree_view , GtkTreePath * path , ) (define-function void gtk_tree_view_set_drag_dest_row (void* void* int)) (define-function void gtk_tree_view_set_enable_search (void* int)) void gtk_tree_view_set_enable_tree_lines ( GtkTreeView * tree_view , enabled ) (define-function void gtk_tree_view_set_enable_tree_lines (void* int)) (define-function void gtk_tree_view_set_expander_column (void* void*)) void gtk_tree_view_set_fixed_height_mode ( GtkTreeView * tree_view , enable ) (define-function void gtk_tree_view_set_fixed_height_mode (void* int)) void gtk_tree_view_set_grid_lines ( GtkTreeView * tree_view , GtkTreeViewGridLines grid_lines ) (define-function void gtk_tree_view_set_grid_lines (void* int)) (define-function void gtk_tree_view_set_hadjustment (void* void*)) (define-function void gtk_tree_view_set_headers_clickable (void* int)) void gtk_tree_view_set_headers_visible ( GtkTreeView * tree_view , headers_visible ) (define-function void gtk_tree_view_set_headers_visible (void* int)) void gtk_tree_view_set_hover_expand ( GtkTreeView * tree_view , expand ) (define-function void gtk_tree_view_set_hover_expand (void* int)) void gtk_tree_view_set_hover_selection ( GtkTreeView * tree_view , ) (define-function void gtk_tree_view_set_hover_selection (void* int)) (define-function void gtk_tree_view_set_level_indentation (void* int)) (define-function void gtk_tree_view_set_model (void* void*)) void gtk_tree_view_set_reorderable ( GtkTreeView * tree_view , reorderable ) (define-function void gtk_tree_view_set_reorderable (void* int)) void gtk_tree_view_set_row_separator_func ( GtkTreeView * tree_view , GtkTreeViewRowSeparatorFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_row_separator_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_rubber_banding ( GtkTreeView * tree_view , enable ) (define-function void gtk_tree_view_set_rubber_banding (void* int)) (define-function void gtk_tree_view_set_rules_hint (void* int)) (define-function void gtk_tree_view_set_search_column (void* int)) (define-function void gtk_tree_view_set_search_entry (void* void*)) void gtk_tree_view_set_search_equal_func ( GtkTreeView * tree_view , GtkTreeViewSearchEqualFunc search_equal_func , gpointer search_user_data , GDestroyNotify search_destroy ) (define-function void gtk_tree_view_set_search_equal_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_search_position_func ( GtkTreeView * tree_view , GtkTreeViewSearchPositionFunc func , gpointer data , GDestroyNotify destroy ) (define-function void gtk_tree_view_set_search_position_func (void* void* void* (c-callback void (void*)))) void gtk_tree_view_set_show_expanders ( GtkTreeView * tree_view , enabled ) (define-function void gtk_tree_view_set_show_expanders (void* int)) (define-function void gtk_tree_view_set_tooltip_cell (void* void* void* void* void*)) (define-function void gtk_tree_view_set_tooltip_column (void* int)) void gtk_tree_view_set_tooltip_row ( GtkTreeView * tree_view , GtkTooltip * tooltip , GtkTreePath * path ) (define-function void gtk_tree_view_set_tooltip_row (void* void* void*)) (define-function void gtk_tree_view_set_vadjustment (void* void*)) void gtk_tree_view_unset_rows_drag_dest ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_unset_rows_drag_dest (void*)) void gtk_tree_view_unset_rows_drag_source ( GtkTreeView * tree_view ) (define-function void gtk_tree_view_unset_rows_drag_source (void*))
0ebd37d80d2811a2ec22d17553f7ff2462c438bc0e8a815946aa0deae0025a5a
mokus0/junkbox
CodeMetric.hs
module CodeMetric where import Data.List class CodeMetric a where measure :: a -> String -> Int data SymbolCount = SymbolCount [Char] deriving (Read, Show) instance Eq SymbolCount where (SymbolCount l1) == (SymbolCount l2) = (sort l1) == (sort l2) a /= b = not (a == b) instance CodeMetric SymbolCount where measure (SymbolCount symbols) string = length (filter (`elem` symbols) string) data LineCount = LineCount deriving (Eq, Show, Read) instance CodeMetric LineCount where measure LineCount = measure (SymbolCount "\n")
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Projects/one-offs/CodeMetric.hs
haskell
module CodeMetric where import Data.List class CodeMetric a where measure :: a -> String -> Int data SymbolCount = SymbolCount [Char] deriving (Read, Show) instance Eq SymbolCount where (SymbolCount l1) == (SymbolCount l2) = (sort l1) == (sort l2) a /= b = not (a == b) instance CodeMetric SymbolCount where measure (SymbolCount symbols) string = length (filter (`elem` symbols) string) data LineCount = LineCount deriving (Eq, Show, Read) instance CodeMetric LineCount where measure LineCount = measure (SymbolCount "\n")
75096f188ed46aa9b0f70ab3206fadc86a5d0eefbc86930659f2e32c3b150550
bos/rwh
Overlap.hs
# LANGUAGE FlexibleInstances # {-- snippet Borked --} class Borked a where bork :: a -> String instance Borked Int where bork = show instance Borked (Int, Int) where bork (a, b) = bork a ++ ", " ++ bork b instance (Borked a, Borked b) => Borked (a, b) where bork (a, b) = ">>" ++ bork a ++ " " ++ bork b ++ "<<" {-- /snippet Borked --} {-- snippet wimply --} instance Borked a => Borked (Int, a) where bork (a, b) = bork a ++ ", " ++ bork b instance Borked a => Borked (a, Int) where bork (a, b) = bork a ++ ", " ++ bork b {-- /snippet wimply --}
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch06/Overlap.hs
haskell
- snippet Borked - - /snippet Borked - - snippet wimply - - /snippet wimply -
# LANGUAGE FlexibleInstances # class Borked a where bork :: a -> String instance Borked Int where bork = show instance Borked (Int, Int) where bork (a, b) = bork a ++ ", " ++ bork b instance (Borked a, Borked b) => Borked (a, b) where bork (a, b) = ">>" ++ bork a ++ " " ++ bork b ++ "<<" instance Borked a => Borked (Int, a) where bork (a, b) = bork a ++ ", " ++ bork b instance Borked a => Borked (a, Int) where bork (a, b) = bork a ++ ", " ++ bork b
e445fe4d5ea13b5bf4cccf4eab0c7a51a59ee8352b20495ab9f2794e28984588
klutometis/clrs
section.scm
(require-extension syntax-case foof-loop array-lib array-lib-sub) (module section-15.1 (fastest-way stations stations/recursive fastest-way/compact) (include "../15.1/fastest-way.scm"))
null
https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/15.1/section.scm
scheme
(require-extension syntax-case foof-loop array-lib array-lib-sub) (module section-15.1 (fastest-way stations stations/recursive fastest-way/compact) (include "../15.1/fastest-way.scm"))
506cf1bc89a6e3d226674d12484e80f1b24a7415dc1e56251e9d59332e1cf93d
haskellfoundation/error-message-index
NoHeader.hs
module NoHeader where f = $(static)
null
https://raw.githubusercontent.com/haskellfoundation/error-message-index/26c5c12c279eb4a997b1ff17eea46f1e86b046ab/message-index/messages/GHC-58481/example3/before/NoHeader.hs
haskell
module NoHeader where f = $(static)
35aad6820248350db5da90900b72f505f634655cb94934929fb6b6695d7ffed5
jordwalke/rehp
url.ml
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Raphaël Proust * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (* Url tampering. *) let split c s = Js.str_array (s##split (Js.string (String.make 1 c))) let split_2 c s = let index = s##indexOf (Js.string (String.make 1 c)) in if index < 0 then Js.undefined else Js.def (s##slice 0 index, s##slice_end (index + 1)) exception Local_exn let interrupt () = raise Local_exn (* url (AKA percent) encoding/decoding *) let plus_re = Regexp.regexp_string "+" let escape_plus s = Regexp.global_replace plus_re s "%2B" let unescape_plus s = Regexp.global_replace plus_re s " " let plus_re_js_string = new%js Js.regExp_withFlags (Js.string "\\+") (Js.string "g") let unescape_plus_js_string s = plus_re_js_string##.lastIndex := 0; s##replace plus_re_js_string (Js.string " ") let urldecode_js_string_string s = Js.to_bytestring (Js.unescape (unescape_plus_js_string s)) let urldecode s = Js.to_bytestring (Js.unescape (Js.bytestring (unescape_plus s))) let urlencode_js_string_string s = Js.to_bytestring ( Js.escape s ) Js.to_bytestring (Js.escape s)*) let urlencode ?(with_plus = true) s = if with_plus then escape_plus (Js.to_bytestring (Js.escape (Js.bytestring s))) else Js.to_bytestring (Js.escape (Js.bytestring s)) (** The type for HTTP url. *) type http_url = { hu_host : string (** The host part of the url. *) ; hu_port : int (** The port for the connection if any. *) ; hu_path : string list (** The path splitted on ['/'] characters. *) ; hu_path_string : string (** The original entire path. *) ; hu_arguments : (string * string) list (** Arguments as a field-value association list.*) ; hu_fragment : string (** The fragment part (after the ['#'] character). *) } (** The type for local file urls. *) type file_url = { fu_path : string list ; fu_path_string : string ; fu_arguments : (string * string) list ; fu_fragment : string } type url = | Http of http_url | Https of http_url | File of file_url * The type for urls . [ File ] is for local files and [ Exotic s ] is for unknown / unsupported protocols . unknown/unsupported protocols. *) exception Not_an_http_protocol let is_secure prot_string = match Js.to_bytestring prot_string##toLowerCase with | "https:" | "https" -> true | "http:" | "http" -> false | "file:" | "file" | _ -> raise Not_an_http_protocol (* port number *) let default_http_port = 80 let default_https_port = 443 (* path *) let path_of_path_string s = let l = String.length s in let rec aux i = let j = try String.index_from s i '/' with Not_found -> l in let word = String.sub s i (j - i) in if j >= l then [word] else word :: aux (j + 1) in match aux 0 with [""] -> [] | [""; ""] -> [""] | a -> a (* Arguments *) let encode_arguments l = String.concat "&" (List.map (fun (n, v) -> urlencode n ^ "=" ^ urlencode v) l) let decode_arguments_js_string s = let arr = split '&' s in let len = arr##.length in let name_value_split s = split_2 '=' s in let rec aux acc idx = if idx < 0 then acc else try aux ( Js.Optdef.case (Js.array_get arr idx) interrupt (fun s -> Js.Optdef.case (name_value_split s) interrupt (fun (x, y) -> let get = urldecode_js_string_string in get x, get y ) ) :: acc ) (pred idx) with Local_exn -> aux acc (pred idx) in aux [] (len - 1) let decode_arguments s = decode_arguments_js_string (Js.bytestring s) let url_re = new%js Js.regExp (Js.bytestring "^([Hh][Tt][Tt][Pp][Ss]?)://([0-9a-zA-Z.-]+|\\[[0-9a-zA-Z.-]+\\]|\\[[0-9A-Fa-f:.]+\\])?(:([0-9]+))?(/([^\\?#]*)(\\?([^#]*))?(#(.*))?)?$") let file_re = new%js Js.regExp (Js.bytestring "^([Ff][Ii][Ll][Ee])://([^\\?#]*)(\\?([^#]*))?(#(.*))?$") let url_of_js_string s = Js.Opt.case (url_re##exec s) (fun () -> Js.Opt.case (file_re##exec s) (fun () -> None) (fun handle -> let res = Js.match_result handle in let path_str = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 2) interrupt) in Some (File { fu_path = path_of_path_string path_str ; fu_path_string = path_str ; fu_arguments = decode_arguments_js_string (Js.Optdef.get (Js.array_get res 4) (fun () -> Js.bytestring "")) ; fu_fragment = Js.to_bytestring (Js.Optdef.get (Js.array_get res 6) (fun () -> Js.bytestring "")) }) ) ) (fun handle -> let res = Js.match_result handle in let ssl = is_secure (Js.Optdef.get (Js.array_get res 1) interrupt) in let port_of_string = function | "" -> if ssl then 443 else 80 | s -> int_of_string s in let path_str = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 6) (fun () -> Js.bytestring "")) in let url = { hu_host = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 2) interrupt) ; hu_port = port_of_string (Js.to_bytestring (Js.Optdef.get (Js.array_get res 4) (fun () -> Js.bytestring ""))) ; hu_path = path_of_path_string path_str ; hu_path_string = path_str ; hu_arguments = decode_arguments_js_string (Js.Optdef.get (Js.array_get res 8) (fun () -> Js.bytestring "")) ; hu_fragment = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 10) (fun () -> Js.bytestring "")) } in Some (if ssl then Https url else Http url) ) let url_of_string s = url_of_js_string (Js.bytestring s) let string_of_url = function | File {fu_path = path; fu_arguments = args; fu_fragment = frag; _} -> ( "file://" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) | Http { hu_host = host ; hu_port = port ; hu_path = path ; hu_arguments = args ; hu_fragment = frag; _ } -> ( "http://" ^ urlencode host ^ (match port with 80 -> "" | n -> ":" ^ string_of_int n) ^ "/" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) | Https { hu_host = host ; hu_port = port ; hu_path = path ; hu_arguments = args ; hu_fragment = frag; _ } -> ( "https://" ^ urlencode host ^ (match port with 443 -> "" | n -> ":" ^ string_of_int n) ^ "/" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) module Current = struct let l = if Js.Optdef.test (Js.Optdef.return Dom_html.window##.location) then Dom_html.window##.location else let empty = Js.string "" in object%js val mutable href = empty val mutable protocol = empty val mutable host = empty val mutable hostname = empty val mutable port = empty val mutable pathname = empty val mutable search = empty val mutable hash = empty val origin = Js.undefined method reload = () method replace _ = () method assign _ = () end let host = urldecode_js_string_string l##.hostname let protocol = urldecode_js_string_string l##.protocol let port = (fun () -> try Some (int_of_string (Js.to_bytestring l##.port)) with Failure _ -> None ) () let path_string = urldecode_js_string_string l##.pathname let path = path_of_path_string path_string let arguments = decode_arguments_js_string ( if l##.search##charAt 0 == Js.string "?" then l##.search##slice_end 1 else l##.search ) let get_fragment () = (* location.hash doesn't have the same behavior depending on the browser Firefox bug : *) (* let s = Js.to_bytestring (l##hash) in *) if String.length s > 0 & & s.[0 ] = ' # ' then String.sub s 1 ( String.length s - 1 ) (* else s; *) Js.Opt.case (l##.href##_match (new%js Js.regExp (Js.string "#(.*)"))) (fun () -> "") (fun res -> let res = Js.match_result res in Js.to_string (Js.Unsafe.get res 1) ) let set_fragment s = l##.hash := Js.bytestring (urlencode s) let get () = url_of_js_string l##.href let set u = l##.href := Js.bytestring (string_of_url u) let as_string = urldecode_js_string_string l##.href end
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/lib/js_of_ocaml/url.ml
ocaml
Url tampering. url (AKA percent) encoding/decoding * The type for HTTP url. * The host part of the url. * The port for the connection if any. * The path splitted on ['/'] characters. * The original entire path. * Arguments as a field-value association list. * The fragment part (after the ['#'] character). * The type for local file urls. port number path Arguments location.hash doesn't have the same behavior depending on the browser Firefox bug : let s = Js.to_bytestring (l##hash) in else s;
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Raphaël Proust * Laboratoire PPS - CNRS Université Paris Diderot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let split c s = Js.str_array (s##split (Js.string (String.make 1 c))) let split_2 c s = let index = s##indexOf (Js.string (String.make 1 c)) in if index < 0 then Js.undefined else Js.def (s##slice 0 index, s##slice_end (index + 1)) exception Local_exn let interrupt () = raise Local_exn let plus_re = Regexp.regexp_string "+" let escape_plus s = Regexp.global_replace plus_re s "%2B" let unescape_plus s = Regexp.global_replace plus_re s " " let plus_re_js_string = new%js Js.regExp_withFlags (Js.string "\\+") (Js.string "g") let unescape_plus_js_string s = plus_re_js_string##.lastIndex := 0; s##replace plus_re_js_string (Js.string " ") let urldecode_js_string_string s = Js.to_bytestring (Js.unescape (unescape_plus_js_string s)) let urldecode s = Js.to_bytestring (Js.unescape (Js.bytestring (unescape_plus s))) let urlencode_js_string_string s = Js.to_bytestring ( Js.escape s ) Js.to_bytestring (Js.escape s)*) let urlencode ?(with_plus = true) s = if with_plus then escape_plus (Js.to_bytestring (Js.escape (Js.bytestring s))) else Js.to_bytestring (Js.escape (Js.bytestring s)) type http_url = ; hu_arguments : (string * string) list type file_url = { fu_path : string list ; fu_path_string : string ; fu_arguments : (string * string) list ; fu_fragment : string } type url = | Http of http_url | Https of http_url | File of file_url * The type for urls . [ File ] is for local files and [ Exotic s ] is for unknown / unsupported protocols . unknown/unsupported protocols. *) exception Not_an_http_protocol let is_secure prot_string = match Js.to_bytestring prot_string##toLowerCase with | "https:" | "https" -> true | "http:" | "http" -> false | "file:" | "file" | _ -> raise Not_an_http_protocol let default_http_port = 80 let default_https_port = 443 let path_of_path_string s = let l = String.length s in let rec aux i = let j = try String.index_from s i '/' with Not_found -> l in let word = String.sub s i (j - i) in if j >= l then [word] else word :: aux (j + 1) in match aux 0 with [""] -> [] | [""; ""] -> [""] | a -> a let encode_arguments l = String.concat "&" (List.map (fun (n, v) -> urlencode n ^ "=" ^ urlencode v) l) let decode_arguments_js_string s = let arr = split '&' s in let len = arr##.length in let name_value_split s = split_2 '=' s in let rec aux acc idx = if idx < 0 then acc else try aux ( Js.Optdef.case (Js.array_get arr idx) interrupt (fun s -> Js.Optdef.case (name_value_split s) interrupt (fun (x, y) -> let get = urldecode_js_string_string in get x, get y ) ) :: acc ) (pred idx) with Local_exn -> aux acc (pred idx) in aux [] (len - 1) let decode_arguments s = decode_arguments_js_string (Js.bytestring s) let url_re = new%js Js.regExp (Js.bytestring "^([Hh][Tt][Tt][Pp][Ss]?)://([0-9a-zA-Z.-]+|\\[[0-9a-zA-Z.-]+\\]|\\[[0-9A-Fa-f:.]+\\])?(:([0-9]+))?(/([^\\?#]*)(\\?([^#]*))?(#(.*))?)?$") let file_re = new%js Js.regExp (Js.bytestring "^([Ff][Ii][Ll][Ee])://([^\\?#]*)(\\?([^#]*))?(#(.*))?$") let url_of_js_string s = Js.Opt.case (url_re##exec s) (fun () -> Js.Opt.case (file_re##exec s) (fun () -> None) (fun handle -> let res = Js.match_result handle in let path_str = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 2) interrupt) in Some (File { fu_path = path_of_path_string path_str ; fu_path_string = path_str ; fu_arguments = decode_arguments_js_string (Js.Optdef.get (Js.array_get res 4) (fun () -> Js.bytestring "")) ; fu_fragment = Js.to_bytestring (Js.Optdef.get (Js.array_get res 6) (fun () -> Js.bytestring "")) }) ) ) (fun handle -> let res = Js.match_result handle in let ssl = is_secure (Js.Optdef.get (Js.array_get res 1) interrupt) in let port_of_string = function | "" -> if ssl then 443 else 80 | s -> int_of_string s in let path_str = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 6) (fun () -> Js.bytestring "")) in let url = { hu_host = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 2) interrupt) ; hu_port = port_of_string (Js.to_bytestring (Js.Optdef.get (Js.array_get res 4) (fun () -> Js.bytestring ""))) ; hu_path = path_of_path_string path_str ; hu_path_string = path_str ; hu_arguments = decode_arguments_js_string (Js.Optdef.get (Js.array_get res 8) (fun () -> Js.bytestring "")) ; hu_fragment = urldecode_js_string_string (Js.Optdef.get (Js.array_get res 10) (fun () -> Js.bytestring "")) } in Some (if ssl then Https url else Http url) ) let url_of_string s = url_of_js_string (Js.bytestring s) let string_of_url = function | File {fu_path = path; fu_arguments = args; fu_fragment = frag; _} -> ( "file://" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) | Http { hu_host = host ; hu_port = port ; hu_path = path ; hu_arguments = args ; hu_fragment = frag; _ } -> ( "http://" ^ urlencode host ^ (match port with 80 -> "" | n -> ":" ^ string_of_int n) ^ "/" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) | Https { hu_host = host ; hu_port = port ; hu_path = path ; hu_arguments = args ; hu_fragment = frag; _ } -> ( "https://" ^ urlencode host ^ (match port with 443 -> "" | n -> ":" ^ string_of_int n) ^ "/" ^ String.concat "/" (List.map (fun x -> urlencode x) path) ^ (match args with [] -> "" | l -> "?" ^ encode_arguments l) ^ match frag with "" -> "" | s -> "#" ^ urlencode s ) module Current = struct let l = if Js.Optdef.test (Js.Optdef.return Dom_html.window##.location) then Dom_html.window##.location else let empty = Js.string "" in object%js val mutable href = empty val mutable protocol = empty val mutable host = empty val mutable hostname = empty val mutable port = empty val mutable pathname = empty val mutable search = empty val mutable hash = empty val origin = Js.undefined method reload = () method replace _ = () method assign _ = () end let host = urldecode_js_string_string l##.hostname let protocol = urldecode_js_string_string l##.protocol let port = (fun () -> try Some (int_of_string (Js.to_bytestring l##.port)) with Failure _ -> None ) () let path_string = urldecode_js_string_string l##.pathname let path = path_of_path_string path_string let arguments = decode_arguments_js_string ( if l##.search##charAt 0 == Js.string "?" then l##.search##slice_end 1 else l##.search ) let get_fragment () = if String.length s > 0 & & s.[0 ] = ' # ' then String.sub s 1 ( String.length s - 1 ) Js.Opt.case (l##.href##_match (new%js Js.regExp (Js.string "#(.*)"))) (fun () -> "") (fun res -> let res = Js.match_result res in Js.to_string (Js.Unsafe.get res 1) ) let set_fragment s = l##.hash := Js.bytestring (urlencode s) let get () = url_of_js_string l##.href let set u = l##.href := Js.bytestring (string_of_url u) let as_string = urldecode_js_string_string l##.href end
85ec75360bdb09773cf9264816e4159b37608ea12b58c372b63e8a1dae2b6cb5
incanter/incanter
cubic_spline.clj
(ns ^{:skip-wiki true} incanter.interp.cubic-spline (:require [incanter.interp.utils :refer (find-segment)])) (defn- map-pairs [fn coll] (mapv #(apply fn %) (partition 2 1 coll))) (defn- get-hs [xs] (map-pairs #(- %2 %1) xs)) (defn- transpose [grid] (apply map vector grid)) (defn- calc-coefs [hs ys type] (let [alphas ys gammas (cond (= type :natural) (incanter.interpolation.Utils/calcNaturalGammas ys hs) (= type :closed) (incanter.interpolation.Utils/calcClosedGammas ys hs) :default (throw (IllegalArgumentException. (str "Unknown type " type)))) deltas (map / (get-hs gammas) hs) betas (map + (map / (get-hs ys) hs) (map #(* %1 (/ %2 6)) (map-pairs #(+ (* 2 %2) %1) gammas) hs))] (mapv vector (rest alphas) betas (map #(/ % 2) (rest gammas)) (map #(/ % 6) deltas)))) (defn- calc-polynom [coefs x] (reduce #(+ (* %1 x) %2) 0 (reverse coefs))) (defn- polynom "Takes coefficients of 3-order polynom and builds a function that calculates it in given point. It's ~3 times faster than calc-polynom function. " [coefs] (let [d (double (nth coefs 0)) c (double (nth coefs 1)) b (double (nth coefs 2)) a (double (nth coefs 3))] (fn [^double x] (+ d (* x (+ c (* x (+ b (* a x))))))))) (defn interpolate "Interpolates set of points using cubic splines. " [points options] (let [xs (mapv #(double (first %)) points) ys (mapv #(double (second %)) points) hs (get-hs xs) type (:boundaries options :natural) all-coefs (calc-coefs hs ys type) polynoms (mapv polynom all-coefs)] (fn [x] (let [ind (find-segment xs x) x-i (xs (inc ind)) polynom (polynoms ind)] (polynom (- x x-i)))))) (defn- interpolate-parametric [points options] (let [point-groups (->> points (map (fn [[t value]] (map #(vector t %) value))) (transpose)) interpolators (map #(interpolate % options) point-groups)] (fn [t] (map #(% t) interpolators)))) (defn interpolate-grid "Interpolates grid using bicubic splines." [grid xs ys options] (let [type (:boundaries options :natural) xs (mapv double xs) hs (get-hs xs) grid (map #(mapv double %) grid) coefs (pmap #(calc-coefs hs % type) grid) trans-coefs (transpose coefs) strip-points (map #(map vector ys %) trans-coefs) strip-interpolators (vec (pmap #(interpolate-parametric % options) strip-points))] (fn [x y] (let [ind-x (find-segment xs x) x-i (xs (inc ind-x)) coefs ((strip-interpolators ind-x) y)] (calc-polynom coefs (- x x-i)))))) (defn- difference [ys hs ind] (let [n (dec (count ys))] (cond (zero? ind) (/ (- (ys 1) (ys 0)) (hs 0)) (= ind n) (/ (- (ys n) (ys (dec n))) (hs (dec n))) :default (/ (+ (/ (- (ys (inc ind)) (ys ind)) (hs ind)) (/ (- (ys ind) (ys (dec ind))) (hs (dec ind)))) 2)))) (defn- differences [ys hs] (map #(difference ys hs %) (range (count ys)))) (defn- get-alphas ([[y0 y1] [yd0 yd1] h] (get-alphas [y0 yd0 y1 yd1] h)) ([[y0 yd0 y1 yd1] h] [y0 yd0 (/ (- y1 y0 (* h yd0)) h h) (/ (+ (* 2 (- y0 y1)) (* h (+ yd0 yd1))) h h h)])) (defn- hermite-polynom [alphas [a b]] (let [a0 (double (nth alphas 0)) a1 (double (nth alphas 1)) a2 (double (nth alphas 2)) a3 (double (nth alphas 3)) a (double a) b (double b)] (fn [^double x] (+ a0 (* (- x a) (+ a1 (* (- x a) (+ a2 (* (- x b) a3))))))))) (defn interpolate-hermite "Interpolates set of points using cubic hermite splines. " [points options] (let [xs (mapv #(first %) points) ys (mapv #(second %) points) hs (get-hs xs) yds (:derivatives options (differences ys hs)) all-alphas (map get-alphas (partition 2 1 ys) (partition 2 1 yds) hs) polynoms (mapv hermite-polynom all-alphas (partition 2 1 xs))] (fn [x] (let [ind (find-segment xs x) x-i (xs (inc ind)) polynom (polynoms ind)] (polynom x))))) (defn- add-partial-derivatives [grid xs ys] (let [hs-x (get-hs xs) hs-y (get-hs ys) grid-dx (map #(differences % hs-x) grid) grid-dy (->> (transpose grid) (map #(differences % hs-y)) transpose) grid-dxdy (->> (transpose grid-dx) (map #(differences % hs-y)) transpose)] (interleave (map interleave grid grid-dx) (map interleave grid-dy grid-dxdy)))) (defn- get-alphas-grid [grid h-x h-y] (->> grid (map #(get-alphas % h-x)) transpose (map #(get-alphas % h-y)) transpose)) (defn- hermite-rect-interpolator [square [a b] [c d]] (let [alphas (get-alphas-grid square (- b a) (- d c)) [a0 a1 a2 a3] (map #(hermite-polynom % [a b]) alphas)] (fn [x y] (+ (a0 x) (* (- y c) (+ (a1 x) (* (- y c) (+ (a2 x) (* (- y d) (a3 x)))))))))) (defn interpolate-grid-hermite "Interpolates grid using bicubic hermite splines." [grid xs ys options] (let [xs (mapv double xs) ys (mapv double ys) grid (map #(mapv double %) grid) grid-ex (add-partial-derivatives grid xs ys) interpolators (mapv (fn [strip ys] (mapv #(hermite-rect-interpolator %1 %2 ys) (transpose (map #(partition 4 2 %) strip)) (partition 2 1 xs))) (partition 4 2 grid-ex) (partition 2 1 ys))] (fn [x y] (let [ind-x (find-segment xs x) ind-y (find-segment ys y)] ((get-in interpolators [ind-y ind-x]) x y)))))
null
https://raw.githubusercontent.com/incanter/incanter/e0a03aac237fcc60587278a36bd2e76266fc6356/modules/incanter-core/src/incanter/interp/cubic_spline.clj
clojure
(ns ^{:skip-wiki true} incanter.interp.cubic-spline (:require [incanter.interp.utils :refer (find-segment)])) (defn- map-pairs [fn coll] (mapv #(apply fn %) (partition 2 1 coll))) (defn- get-hs [xs] (map-pairs #(- %2 %1) xs)) (defn- transpose [grid] (apply map vector grid)) (defn- calc-coefs [hs ys type] (let [alphas ys gammas (cond (= type :natural) (incanter.interpolation.Utils/calcNaturalGammas ys hs) (= type :closed) (incanter.interpolation.Utils/calcClosedGammas ys hs) :default (throw (IllegalArgumentException. (str "Unknown type " type)))) deltas (map / (get-hs gammas) hs) betas (map + (map / (get-hs ys) hs) (map #(* %1 (/ %2 6)) (map-pairs #(+ (* 2 %2) %1) gammas) hs))] (mapv vector (rest alphas) betas (map #(/ % 2) (rest gammas)) (map #(/ % 6) deltas)))) (defn- calc-polynom [coefs x] (reduce #(+ (* %1 x) %2) 0 (reverse coefs))) (defn- polynom "Takes coefficients of 3-order polynom and builds a function that calculates it in given point. It's ~3 times faster than calc-polynom function. " [coefs] (let [d (double (nth coefs 0)) c (double (nth coefs 1)) b (double (nth coefs 2)) a (double (nth coefs 3))] (fn [^double x] (+ d (* x (+ c (* x (+ b (* a x))))))))) (defn interpolate "Interpolates set of points using cubic splines. " [points options] (let [xs (mapv #(double (first %)) points) ys (mapv #(double (second %)) points) hs (get-hs xs) type (:boundaries options :natural) all-coefs (calc-coefs hs ys type) polynoms (mapv polynom all-coefs)] (fn [x] (let [ind (find-segment xs x) x-i (xs (inc ind)) polynom (polynoms ind)] (polynom (- x x-i)))))) (defn- interpolate-parametric [points options] (let [point-groups (->> points (map (fn [[t value]] (map #(vector t %) value))) (transpose)) interpolators (map #(interpolate % options) point-groups)] (fn [t] (map #(% t) interpolators)))) (defn interpolate-grid "Interpolates grid using bicubic splines." [grid xs ys options] (let [type (:boundaries options :natural) xs (mapv double xs) hs (get-hs xs) grid (map #(mapv double %) grid) coefs (pmap #(calc-coefs hs % type) grid) trans-coefs (transpose coefs) strip-points (map #(map vector ys %) trans-coefs) strip-interpolators (vec (pmap #(interpolate-parametric % options) strip-points))] (fn [x y] (let [ind-x (find-segment xs x) x-i (xs (inc ind-x)) coefs ((strip-interpolators ind-x) y)] (calc-polynom coefs (- x x-i)))))) (defn- difference [ys hs ind] (let [n (dec (count ys))] (cond (zero? ind) (/ (- (ys 1) (ys 0)) (hs 0)) (= ind n) (/ (- (ys n) (ys (dec n))) (hs (dec n))) :default (/ (+ (/ (- (ys (inc ind)) (ys ind)) (hs ind)) (/ (- (ys ind) (ys (dec ind))) (hs (dec ind)))) 2)))) (defn- differences [ys hs] (map #(difference ys hs %) (range (count ys)))) (defn- get-alphas ([[y0 y1] [yd0 yd1] h] (get-alphas [y0 yd0 y1 yd1] h)) ([[y0 yd0 y1 yd1] h] [y0 yd0 (/ (- y1 y0 (* h yd0)) h h) (/ (+ (* 2 (- y0 y1)) (* h (+ yd0 yd1))) h h h)])) (defn- hermite-polynom [alphas [a b]] (let [a0 (double (nth alphas 0)) a1 (double (nth alphas 1)) a2 (double (nth alphas 2)) a3 (double (nth alphas 3)) a (double a) b (double b)] (fn [^double x] (+ a0 (* (- x a) (+ a1 (* (- x a) (+ a2 (* (- x b) a3))))))))) (defn interpolate-hermite "Interpolates set of points using cubic hermite splines. " [points options] (let [xs (mapv #(first %) points) ys (mapv #(second %) points) hs (get-hs xs) yds (:derivatives options (differences ys hs)) all-alphas (map get-alphas (partition 2 1 ys) (partition 2 1 yds) hs) polynoms (mapv hermite-polynom all-alphas (partition 2 1 xs))] (fn [x] (let [ind (find-segment xs x) x-i (xs (inc ind)) polynom (polynoms ind)] (polynom x))))) (defn- add-partial-derivatives [grid xs ys] (let [hs-x (get-hs xs) hs-y (get-hs ys) grid-dx (map #(differences % hs-x) grid) grid-dy (->> (transpose grid) (map #(differences % hs-y)) transpose) grid-dxdy (->> (transpose grid-dx) (map #(differences % hs-y)) transpose)] (interleave (map interleave grid grid-dx) (map interleave grid-dy grid-dxdy)))) (defn- get-alphas-grid [grid h-x h-y] (->> grid (map #(get-alphas % h-x)) transpose (map #(get-alphas % h-y)) transpose)) (defn- hermite-rect-interpolator [square [a b] [c d]] (let [alphas (get-alphas-grid square (- b a) (- d c)) [a0 a1 a2 a3] (map #(hermite-polynom % [a b]) alphas)] (fn [x y] (+ (a0 x) (* (- y c) (+ (a1 x) (* (- y c) (+ (a2 x) (* (- y d) (a3 x)))))))))) (defn interpolate-grid-hermite "Interpolates grid using bicubic hermite splines." [grid xs ys options] (let [xs (mapv double xs) ys (mapv double ys) grid (map #(mapv double %) grid) grid-ex (add-partial-derivatives grid xs ys) interpolators (mapv (fn [strip ys] (mapv #(hermite-rect-interpolator %1 %2 ys) (transpose (map #(partition 4 2 %) strip)) (partition 2 1 xs))) (partition 4 2 grid-ex) (partition 2 1 ys))] (fn [x y] (let [ind-x (find-segment xs x) ind-y (find-segment ys y)] ((get-in interpolators [ind-y ind-x]) x y)))))
6a5df811f6ca06c3ea8a80e1a45a73c28c1ff89031f01fe74efde27af5900458
plewto/Cadejo
envelope_panel.clj
(ns cadejo.instruments.algo.editor.envelope-panel (:use [cadejo.instruments.algo.algo-constants]) (:require [cadejo.ui.util.lnf :as lnf]) (:require [cadejo.ui.util.sgwr-factory :as sfactory]) (:require [cadejo.util.math :as math]) (:require [sgwr.components.drawing :as drw]) (:require [sgwr.components.line :as line]) (:require [sgwr.components.point :as point]) (:require [sgwr.components.text :as text]) (:require [sgwr.tools.multistate-button :as msb]) (:require [sgwr.util.color :as uc]) (:require [sgwr.util.math :as sgwr-math]) (:require [seesaw.core :as ss]) (:import javax.swing.Box java.awt.event.MouseMotionListener java.awt.event.MouseListener)) ;; buttons: ;; gate preset ;; percussion preset ADSSR preset ;; dice ;; copy ;; paste ;; zoom-in ;; zoom-out ;; zoom-restore op - operator number [ 1,2,3, ... ,8 ] or : pitch for pitch env (def width 580) (def height 400) (def toolbar-height 60) (def ^:private current-view* (atom default-envelope-view)) (defn- invertable? [op] (or (= op 2)(= op 3)(= op 5)(= op 6)(= op 8))) (defn- param-key [n param] (if (keyword? n) (keyword (format "env1-%s" param)) (keyword (format "op%d-%s" n param)))) (defn- get-data-map [performance] (.current-data (.bank performance))) (defn- preset-gate-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.0 param-decay1 0.2 param-decay2 0.2 param-release 0.0 param-breakpoint 1.0 param-sustain 1.0 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- preset-percussion-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.0 param-decay1 0.1 param-decay2 1.0 param-release 2.0 param-breakpoint 0.8 param-sustain 0.0 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- preset-adsr-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.05 param-decay1 0.25 param-decay2 1.4 param-release 0.2 param-breakpoint 0.9 param-sustain 0.85 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- env-dice [op ied] (let [time-scale (math/pick '[1.0 1.0 1.0 1.0 2.0 2.0 4.0 8.0]) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") att (rand time-scale) dcy1 (rand time-scale) dcy2 (rand time-scale) rel (rand time-scale) bp (math/coin 0.5 (math/rand-range 0.5 1.0)(rand)) sus (math/coin 0.5 (math/rand-range 0.5 1.0)(rand)) dmap {param-attack att param-decay1 dcy1 param-decay2 dcy2 param-release rel param-breakpoint bp param-sustain sus}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (def ^:private clipboard* (atom {:attack 0.0 :decay1 0.2 :decay2 0.2 :release 0.0 :breakpoint 1.0 :sustain 1.0})) (defn- copy-env [op ied] (let [dmap (get-data-map (.parent-performance ied)) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain")] (reset! clipboard* {:attack (param-attack dmap) :decay1 (param-decay1 dmap) :decay2 (param-decay2 dmap) :release (param-release dmap) :breakpoint (param-breakpoint dmap) :sustain (param-sustain dmap)}))) (defn- paste-env [op ied] (let [clip @clipboard* param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain")] (.set-param! ied param-attack (:attack clip)) (.set-param! ied param-decay1 (:decay1 clip)) (.set-param! ied param-decay2 (:decay2 clip)) (.set-param! ied param-release (:release clip)) (.set-param! ied param-breakpoint (:breakpoint clip)) (.set-param! ied param-sustain (:sustain clip)))) (defn- env-toolbar [op ied callback] (let [param-bias (if (= op :pitch) :env1-bias (param-key op "env-bias")) param-scale (if (= op :pitch) :env1-scale (param-key op "env-scale")) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") drw (let [d (drw/native-drawing width toolbar-height)] (.background! d (lnf/envelope-background)) d) root (.root drw) tools (.tool-root drw) [x0 y0][0 toolbar-height] x-gap 30 x-space 50 x-gate (+ x0 x-gap) x-percussion (+ x-gate x-space) x-adsr (+ x-percussion x-space) x-dice (+ x-adsr x-space) x-copy (+ x-dice x-space) x-paste (+ x-copy x-space) x-zoom-in (+ x-paste x-space) x-zoom-out (+ x-zoom-in x-space) x-zoom-restore (+ x-zoom-out x-space) x-invert (+ x-zoom-restore x-space) y-buttons (- y0 50) pan-main (ss/vertical-panel :items [(.canvas drw)] :background (lnf/background)) invert-action (fn [cb _] (if (msb/checkbox-selected? cb) (do (.set-param! ied param-bias 1.0) (.set-param! ied param-scale -1.0) (.status! ied (format "Invert envelope %s" op))) (do (.set-param! ied param-bias 0.0) (.set-param! ied param-scale 1.0) (.status! ied (format "Envelope %s normal" op))))) cb-invert (if (invertable? op) (sfactory/checkbox drw [x-invert (+ y-buttons 15)] :invert-env "Invert" invert-action)) sync-fn (fn [dmap] (if cb-invert (let [bias (get dmap param-bias 0.0)] (msb/select-checkbox! cb-invert (pos? bias) false) (.render drw))))] (sfactory/env-button drw [x-gate y-buttons] :gate callback) (sfactory/env-button drw [x-percussion y-buttons] :percussion callback) (sfactory/env-button drw [x-adsr y-buttons] :adsr callback) (sfactory/dice-button drw [x-dice y-buttons] :env-dice callback) (sfactory/copy-button drw [x-copy y-buttons] :env-copy callback) (sfactory/paste-button drw [x-paste y-buttons] :env-paste callback) (sfactory/zoom-in-button drw [x-zoom-in y-buttons] :env-zoom-in callback) (sfactory/zoom-out-button drw [x-zoom-out y-buttons] :env-zoom-out callback) (sfactory/zoom-restore-button drw [x-zoom-restore y-buttons] :env-zoom-restore callback) (.background! drw (lnf/background)) (.render drw) {:pan-main pan-main :drawing drw :sync-fn sync-fn})) (defn envelope-panel [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") zoom-ratio 1.5 performance (.parent-performance ied) drw (let [d (drw/cartesian-drawing width height (first default-envelope-view)(second default-envelope-view))] (.background! d (lnf/envelope-background)) d) root (.root drw) tools (.tool-root drw) major (fn [p0 p1] (line/line root p0 p1 :id :env-axis :color (lnf/major-tick) :style :solid)) minor (fn [p0 p1] (line/line root p0 p1 :id :env-axis :color (lnf/minor-tick) :style :dotted)) segment (fn [id p0 p1 sty] (let [seg (line/line root p0 p1 :id id :style sty :width 1.0 :color (lnf/envelope-segment))] (.color! seg :selected (lnf/envelope-selected)) (.color! seg :default (lnf/envelope-segment)) seg)) seg-a (segment :a [0 0] [1 1] :solid) seg-b (segment :b [1 1][2 0.7] :solid) seg-c (segment :c [2 0.7][4 0.5] :solid) seg-d (segment :d [4 0.5][6 0.5] :dash) seg-e (segment :e [6 0.5][7 0.0] :solid) segments [seg-a seg-b seg-c seg-d seg-e] point (fn [id pos adjacent] (let [c1 (uc/color (lnf/envelope-handle)) c2 (uc/inversion c1) p (point/point root pos :id id :color c1 :style [:dot] :size 3)] (.put-property! p :adjacent adjacent) (.color! p :default c1) (.color! p :selected c2) p)) p1 (point :p1 [1 1] [seg-a seg-b]) p2 (point :p2 [2 0.7] [seg-b seg-c]) p3 (point :p3 [4 0.5] [seg-c seg-d]) p4 (point :p4 [6 0.5] [seg-d seg-e]) p5 (point :p5 [7 0.0] [seg-e]) points [p1 p2 p3 p4 p5] current-point* (atom nil) disable-fn (fn [] ) enable-fn (fn [] ) toolbar* (atom nil) txt-view (text/text root [0.1 -0.04] "View: xxx" :lock-size true :color (lnf/text) :style :mono :size 6) sync-fn (fn [] (let [dmap (get-data-map performance) att (param-attack dmap) dcy1 (param-decay1 dmap) dcy2 (param-decay2 dmap) rel (param-release dmap) bp (param-breakpoint dmap) sus (param-sustain dmap) t0 0.0 t1 (+ t0 att) t2 (+ t1 dcy1) t3 (+ t2 dcy2) t4 (+ t3 2) t5 (+ t4 rel)] (.set-points! p1 [[t1 1.0]]) (.set-points! p2 [[t2 bp]]) (.set-points! p3 [[t3 sus]]) (.set-points! p4 [[t4 sus]]) (.set-points! p5 [[t5 0.0]]) (.put-property! p1 :adjacent [seg-a seg-b]) (.put-property! p2 :adjacent [seg-b seg-c]) (.put-property! p3 :adjacent [seg-c seg-d]) (.put-property! p4 :adjacent [seg-d seg-e]) (.set-points! seg-a [[0 0][t1 1.0]]) (.set-points! seg-b [[t1 1.0][t2 bp]]) (.set-points! seg-c [[t2 bp ][t3 sus]]) (.set-points! seg-d [[t3 sus][t4 sus]]) (.set-points! seg-e [[t4 sus][t5 0]]) (.put-property! txt-view :text (format "View: %6.3f seconds" (first (second @current-view*)))) ((:sync-fn @toolbar*) dmap) (.set-view drw @current-view*))) toolbar-callback (fn [b _] (let [id (.get-property b :id)] (cond (= id :gate) (do (preset-gate-env op ied) (sync-fn) (.status! ied (format "Using gate preset, Envelope %s" op))) (= id :percussion) (do (preset-percussion-env op ied) (sync-fn) (.status! ied (format "Using percussion preset, Envelope %s" op))) (= id :adsr) (do (preset-adsr-env op ied) (sync-fn) (.status! ied (format "Using ADSR preset, Envelope %s" op))) (= id :env-dice) (do (env-dice op ied) (sync-fn) (.status! ied (format "Randomized Envelope %s" op))) (= id :env-copy) (do (copy-env op ied) (.status! ied (format "Envelope %s copied to clipboard" op))) (= id :env-paste) (do (paste-env op ied) (sync-fn) (.status! ied (format "Clipboard pasted to Envelope %s" op))) (= id :env-zoom-in) (let [[p0 p1] @current-view* [x1 y1] p1 x2 (/ x1 zoom-ratio)] (reset! current-view* [p0 [x2 y1]]) (sync-fn) (.status! ied (format "Env %s zoom-in %s seconds" op x2))) (= id :env-zoom-out) (let [[p0 p1] @current-view* [x1 y1] p1 x2 (* x1 zoom-ratio)] (reset! current-view* [p0 [x2 y1]]) (sync-fn) (.status! ied (format "Env %s zoom-out %s seconds" op x2))) (= id :env-zoom-restore) (do (reset! current-view* default-envelope-view) (sync-fn) (.status! ied (format "Env %s restore-view %s seconds" op (first (second default-envelope-view))))) :default (println "env-toolbar calllback id is " id)))) toolbar (env-toolbar op ied toolbar-callback) pan-main (let [tb (env-toolbar op ied toolbar-callback)] (reset! toolbar* tb) (ss/border-panel :north (Box/createVerticalStrut 170) :center (ss/vertical-panel :items [(.canvas drw) (:pan-main tb)]) :east (Box/createHorizontalStrut 100) :south (Box/createVerticalStrut 16) :background (lnf/background)))] (.add-mouse-listener drw (proxy [MouseListener][] (mouseExited [_] (.use-attributes! root :default) (.render drw)) (mouseEntered [_]) (mouseClicked [_]) (mousePressed [_]) (mouseReleased [_]))) (.add-mouse-motion-listener drw (proxy [MouseMotionListener][] (mouseMoved [ev] (let [[x y](.mouse-where drw) d* (atom 1e6)] (reset! current-point* nil) (doseq [s segments](.use-attributes! s :default)) (doseq [p points] (.use-attributes! p :default) (let [pos (first (.points p)) dp (sgwr-math/distance [x y] pos)] (if (< dp @d*) (do (reset! d* dp) (reset! current-point* p))))) (doseq [p (cons @current-point* (.get-property @current-point* :adjacent ))] (.use-attributes! p :selected)) (.render drw) (.status! ied (format "env [time %5.3f amp %5.3f]" x y)))) (mouseDragged [ev] (let [cp @current-point* dmap (get-data-map performance) att (param-attack dmap) dcy1 (param-decay1 dmap) dcy2 (param-decay2 dmap) rel (param-release dmap) bp (param-breakpoint dmap) sus (param-sustain dmap) t0 0.0 t1* (atom (+ t0 att)) t2* (atom (+ @t1* dcy1)) t3* (atom (+ @t2* dcy2)) t4* (atom (+ @t3* 2)) t5* (atom (+ @t4* rel)) bp* (atom bp) sus* (atom sus) update-curve (fn [] (.set-points! p1 [[@t1* 1.0]]) (.set-points! p2 [[@t2* @bp*]]) (.set-points! p3 [[@t3* @sus*]]) (.set-points! p4 [[@t4* @sus*]]) (.set-points! p5 [[@t5* 0.0]]) (.set-points! seg-a [[0 0][@t1* 1.0]]) (.set-points! seg-b [[@t1* 1.0][@t2* @bp*]]) (.set-points! seg-c [[@t2* @bp*][@t3* @sus*]]) (.set-points! seg-d [[@t3* @sus*][@t4* @sus*]]) (.set-points! seg-e [[@t4* sus][@t5* 0.0]]) (.render drw))] (cond (= cp p1) ; attack time p1 (let [[att _](.mouse-where drw)] (reset! t1* (float (max 0 att))) (reset! t2* (+ @t1* dcy1)) (reset! t3* (+ @t2* dcy2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (.set-param! ied param-attack @t1*) (update-curve)) decay1 , breakpoint (let [[x y](.mouse-where drw) att @t1* dcy-1 (float (max 0 (- x att))) bp (float (sgwr-math/clamp y 0.0 1.0))] (reset! t2* (+ @t1* dcy1)) (reset! t3* (+ @t2* dcy2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (reset! bp* bp) (.set-param! ied param-decay1 dcy-1) (.set-param! ied param-breakpoint bp) (.status! ied (format "[%s] -> %5.3f [%s] -> %5.3f" param-decay1 dcy1 param-breakpoint bp)) (update-curve)) (= cp p3) ; decay2, sustain (let [[x y](.mouse-where drw) dcy-2 (float (max 0 (- x @t2*))) sus (float (sgwr-math/clamp y 0.0 1.0))] (reset! t3* (+ @t2* dcy-2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (reset! sus* sus) (.set-param! ied param-decay2 dcy-2) (.set-param! ied param-sustain sus) (.status! ied (format "[%s] -> %5.3f [%s] -> %5.3f" param-decay2 dcy-2 param-sustain sus)) (update-curve)) (= cp p4) ; sustain (let [[_ y](.mouse-where drw) sus (float (sgwr-math/clamp y 0.0 1.0))] (reset! sus* sus) (.set-param! ied param-sustain sus) (update-curve)) (= cp p5) ; release time (let [[x _](.mouse-where drw) rel (float (max 0 (- x @t4*)))] (reset! t5* (+ @t4* rel)) (.set-param! ied param-release rel) (update-curve)) :default (.warning! ied "Internal ERROR envelope-panel mouse-motion-listener") ))))) ;; rules (point/point root [0 0] :id :env-p0 :color (lnf/envelope-handle) :style [:diag :diag2] :size 3) (major [0.0 -0.05][0.0 1.05]) (major [-0.1 0.00][100 0.00]) (major [-0.1 1.0][100 1.0]) (doseq [db (range -3 -36 -3)] (let [y (math/db->amp db)] (minor [-0.1 y][100 y]))) {:pan-main pan-main :sync-fn sync-fn :disable-fn disable-fn :enable-fn enable-fn}))
null
https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/instruments/algo/editor/envelope_panel.clj
clojure
buttons: gate preset percussion preset dice copy paste zoom-in zoom-out zoom-restore attack time p1 decay2, sustain sustain release time rules
(ns cadejo.instruments.algo.editor.envelope-panel (:use [cadejo.instruments.algo.algo-constants]) (:require [cadejo.ui.util.lnf :as lnf]) (:require [cadejo.ui.util.sgwr-factory :as sfactory]) (:require [cadejo.util.math :as math]) (:require [sgwr.components.drawing :as drw]) (:require [sgwr.components.line :as line]) (:require [sgwr.components.point :as point]) (:require [sgwr.components.text :as text]) (:require [sgwr.tools.multistate-button :as msb]) (:require [sgwr.util.color :as uc]) (:require [sgwr.util.math :as sgwr-math]) (:require [seesaw.core :as ss]) (:import javax.swing.Box java.awt.event.MouseMotionListener java.awt.event.MouseListener)) ADSSR preset op - operator number [ 1,2,3, ... ,8 ] or : pitch for pitch env (def width 580) (def height 400) (def toolbar-height 60) (def ^:private current-view* (atom default-envelope-view)) (defn- invertable? [op] (or (= op 2)(= op 3)(= op 5)(= op 6)(= op 8))) (defn- param-key [n param] (if (keyword? n) (keyword (format "env1-%s" param)) (keyword (format "op%d-%s" n param)))) (defn- get-data-map [performance] (.current-data (.bank performance))) (defn- preset-gate-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.0 param-decay1 0.2 param-decay2 0.2 param-release 0.0 param-breakpoint 1.0 param-sustain 1.0 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- preset-percussion-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.0 param-decay1 0.1 param-decay2 1.0 param-release 2.0 param-breakpoint 0.8 param-sustain 0.0 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- preset-adsr-env [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") dmap {param-attack 0.05 param-decay1 0.25 param-decay2 1.4 param-release 0.2 param-breakpoint 0.9 param-sustain 0.85 param-bias 0.0 param-scale 1.0}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (defn- env-dice [op ied] (let [time-scale (math/pick '[1.0 1.0 1.0 1.0 2.0 2.0 4.0 8.0]) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") param-bias (param-key op "bias") param-scale (param-key op "scale") att (rand time-scale) dcy1 (rand time-scale) dcy2 (rand time-scale) rel (rand time-scale) bp (math/coin 0.5 (math/rand-range 0.5 1.0)(rand)) sus (math/coin 0.5 (math/rand-range 0.5 1.0)(rand)) dmap {param-attack att param-decay1 dcy1 param-decay2 dcy2 param-release rel param-breakpoint bp param-sustain sus}] (doseq [[p v](seq dmap)] (.set-param! ied p v)))) (def ^:private clipboard* (atom {:attack 0.0 :decay1 0.2 :decay2 0.2 :release 0.0 :breakpoint 1.0 :sustain 1.0})) (defn- copy-env [op ied] (let [dmap (get-data-map (.parent-performance ied)) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain")] (reset! clipboard* {:attack (param-attack dmap) :decay1 (param-decay1 dmap) :decay2 (param-decay2 dmap) :release (param-release dmap) :breakpoint (param-breakpoint dmap) :sustain (param-sustain dmap)}))) (defn- paste-env [op ied] (let [clip @clipboard* param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain")] (.set-param! ied param-attack (:attack clip)) (.set-param! ied param-decay1 (:decay1 clip)) (.set-param! ied param-decay2 (:decay2 clip)) (.set-param! ied param-release (:release clip)) (.set-param! ied param-breakpoint (:breakpoint clip)) (.set-param! ied param-sustain (:sustain clip)))) (defn- env-toolbar [op ied callback] (let [param-bias (if (= op :pitch) :env1-bias (param-key op "env-bias")) param-scale (if (= op :pitch) :env1-scale (param-key op "env-scale")) param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") drw (let [d (drw/native-drawing width toolbar-height)] (.background! d (lnf/envelope-background)) d) root (.root drw) tools (.tool-root drw) [x0 y0][0 toolbar-height] x-gap 30 x-space 50 x-gate (+ x0 x-gap) x-percussion (+ x-gate x-space) x-adsr (+ x-percussion x-space) x-dice (+ x-adsr x-space) x-copy (+ x-dice x-space) x-paste (+ x-copy x-space) x-zoom-in (+ x-paste x-space) x-zoom-out (+ x-zoom-in x-space) x-zoom-restore (+ x-zoom-out x-space) x-invert (+ x-zoom-restore x-space) y-buttons (- y0 50) pan-main (ss/vertical-panel :items [(.canvas drw)] :background (lnf/background)) invert-action (fn [cb _] (if (msb/checkbox-selected? cb) (do (.set-param! ied param-bias 1.0) (.set-param! ied param-scale -1.0) (.status! ied (format "Invert envelope %s" op))) (do (.set-param! ied param-bias 0.0) (.set-param! ied param-scale 1.0) (.status! ied (format "Envelope %s normal" op))))) cb-invert (if (invertable? op) (sfactory/checkbox drw [x-invert (+ y-buttons 15)] :invert-env "Invert" invert-action)) sync-fn (fn [dmap] (if cb-invert (let [bias (get dmap param-bias 0.0)] (msb/select-checkbox! cb-invert (pos? bias) false) (.render drw))))] (sfactory/env-button drw [x-gate y-buttons] :gate callback) (sfactory/env-button drw [x-percussion y-buttons] :percussion callback) (sfactory/env-button drw [x-adsr y-buttons] :adsr callback) (sfactory/dice-button drw [x-dice y-buttons] :env-dice callback) (sfactory/copy-button drw [x-copy y-buttons] :env-copy callback) (sfactory/paste-button drw [x-paste y-buttons] :env-paste callback) (sfactory/zoom-in-button drw [x-zoom-in y-buttons] :env-zoom-in callback) (sfactory/zoom-out-button drw [x-zoom-out y-buttons] :env-zoom-out callback) (sfactory/zoom-restore-button drw [x-zoom-restore y-buttons] :env-zoom-restore callback) (.background! drw (lnf/background)) (.render drw) {:pan-main pan-main :drawing drw :sync-fn sync-fn})) (defn envelope-panel [op ied] (let [param-attack (param-key op "attack") param-decay1 (param-key op "decay1") param-decay2 (param-key op "decay2") param-release (param-key op "release") param-breakpoint (param-key op "breakpoint") param-sustain (param-key op "sustain") zoom-ratio 1.5 performance (.parent-performance ied) drw (let [d (drw/cartesian-drawing width height (first default-envelope-view)(second default-envelope-view))] (.background! d (lnf/envelope-background)) d) root (.root drw) tools (.tool-root drw) major (fn [p0 p1] (line/line root p0 p1 :id :env-axis :color (lnf/major-tick) :style :solid)) minor (fn [p0 p1] (line/line root p0 p1 :id :env-axis :color (lnf/minor-tick) :style :dotted)) segment (fn [id p0 p1 sty] (let [seg (line/line root p0 p1 :id id :style sty :width 1.0 :color (lnf/envelope-segment))] (.color! seg :selected (lnf/envelope-selected)) (.color! seg :default (lnf/envelope-segment)) seg)) seg-a (segment :a [0 0] [1 1] :solid) seg-b (segment :b [1 1][2 0.7] :solid) seg-c (segment :c [2 0.7][4 0.5] :solid) seg-d (segment :d [4 0.5][6 0.5] :dash) seg-e (segment :e [6 0.5][7 0.0] :solid) segments [seg-a seg-b seg-c seg-d seg-e] point (fn [id pos adjacent] (let [c1 (uc/color (lnf/envelope-handle)) c2 (uc/inversion c1) p (point/point root pos :id id :color c1 :style [:dot] :size 3)] (.put-property! p :adjacent adjacent) (.color! p :default c1) (.color! p :selected c2) p)) p1 (point :p1 [1 1] [seg-a seg-b]) p2 (point :p2 [2 0.7] [seg-b seg-c]) p3 (point :p3 [4 0.5] [seg-c seg-d]) p4 (point :p4 [6 0.5] [seg-d seg-e]) p5 (point :p5 [7 0.0] [seg-e]) points [p1 p2 p3 p4 p5] current-point* (atom nil) disable-fn (fn [] ) enable-fn (fn [] ) toolbar* (atom nil) txt-view (text/text root [0.1 -0.04] "View: xxx" :lock-size true :color (lnf/text) :style :mono :size 6) sync-fn (fn [] (let [dmap (get-data-map performance) att (param-attack dmap) dcy1 (param-decay1 dmap) dcy2 (param-decay2 dmap) rel (param-release dmap) bp (param-breakpoint dmap) sus (param-sustain dmap) t0 0.0 t1 (+ t0 att) t2 (+ t1 dcy1) t3 (+ t2 dcy2) t4 (+ t3 2) t5 (+ t4 rel)] (.set-points! p1 [[t1 1.0]]) (.set-points! p2 [[t2 bp]]) (.set-points! p3 [[t3 sus]]) (.set-points! p4 [[t4 sus]]) (.set-points! p5 [[t5 0.0]]) (.put-property! p1 :adjacent [seg-a seg-b]) (.put-property! p2 :adjacent [seg-b seg-c]) (.put-property! p3 :adjacent [seg-c seg-d]) (.put-property! p4 :adjacent [seg-d seg-e]) (.set-points! seg-a [[0 0][t1 1.0]]) (.set-points! seg-b [[t1 1.0][t2 bp]]) (.set-points! seg-c [[t2 bp ][t3 sus]]) (.set-points! seg-d [[t3 sus][t4 sus]]) (.set-points! seg-e [[t4 sus][t5 0]]) (.put-property! txt-view :text (format "View: %6.3f seconds" (first (second @current-view*)))) ((:sync-fn @toolbar*) dmap) (.set-view drw @current-view*))) toolbar-callback (fn [b _] (let [id (.get-property b :id)] (cond (= id :gate) (do (preset-gate-env op ied) (sync-fn) (.status! ied (format "Using gate preset, Envelope %s" op))) (= id :percussion) (do (preset-percussion-env op ied) (sync-fn) (.status! ied (format "Using percussion preset, Envelope %s" op))) (= id :adsr) (do (preset-adsr-env op ied) (sync-fn) (.status! ied (format "Using ADSR preset, Envelope %s" op))) (= id :env-dice) (do (env-dice op ied) (sync-fn) (.status! ied (format "Randomized Envelope %s" op))) (= id :env-copy) (do (copy-env op ied) (.status! ied (format "Envelope %s copied to clipboard" op))) (= id :env-paste) (do (paste-env op ied) (sync-fn) (.status! ied (format "Clipboard pasted to Envelope %s" op))) (= id :env-zoom-in) (let [[p0 p1] @current-view* [x1 y1] p1 x2 (/ x1 zoom-ratio)] (reset! current-view* [p0 [x2 y1]]) (sync-fn) (.status! ied (format "Env %s zoom-in %s seconds" op x2))) (= id :env-zoom-out) (let [[p0 p1] @current-view* [x1 y1] p1 x2 (* x1 zoom-ratio)] (reset! current-view* [p0 [x2 y1]]) (sync-fn) (.status! ied (format "Env %s zoom-out %s seconds" op x2))) (= id :env-zoom-restore) (do (reset! current-view* default-envelope-view) (sync-fn) (.status! ied (format "Env %s restore-view %s seconds" op (first (second default-envelope-view))))) :default (println "env-toolbar calllback id is " id)))) toolbar (env-toolbar op ied toolbar-callback) pan-main (let [tb (env-toolbar op ied toolbar-callback)] (reset! toolbar* tb) (ss/border-panel :north (Box/createVerticalStrut 170) :center (ss/vertical-panel :items [(.canvas drw) (:pan-main tb)]) :east (Box/createHorizontalStrut 100) :south (Box/createVerticalStrut 16) :background (lnf/background)))] (.add-mouse-listener drw (proxy [MouseListener][] (mouseExited [_] (.use-attributes! root :default) (.render drw)) (mouseEntered [_]) (mouseClicked [_]) (mousePressed [_]) (mouseReleased [_]))) (.add-mouse-motion-listener drw (proxy [MouseMotionListener][] (mouseMoved [ev] (let [[x y](.mouse-where drw) d* (atom 1e6)] (reset! current-point* nil) (doseq [s segments](.use-attributes! s :default)) (doseq [p points] (.use-attributes! p :default) (let [pos (first (.points p)) dp (sgwr-math/distance [x y] pos)] (if (< dp @d*) (do (reset! d* dp) (reset! current-point* p))))) (doseq [p (cons @current-point* (.get-property @current-point* :adjacent ))] (.use-attributes! p :selected)) (.render drw) (.status! ied (format "env [time %5.3f amp %5.3f]" x y)))) (mouseDragged [ev] (let [cp @current-point* dmap (get-data-map performance) att (param-attack dmap) dcy1 (param-decay1 dmap) dcy2 (param-decay2 dmap) rel (param-release dmap) bp (param-breakpoint dmap) sus (param-sustain dmap) t0 0.0 t1* (atom (+ t0 att)) t2* (atom (+ @t1* dcy1)) t3* (atom (+ @t2* dcy2)) t4* (atom (+ @t3* 2)) t5* (atom (+ @t4* rel)) bp* (atom bp) sus* (atom sus) update-curve (fn [] (.set-points! p1 [[@t1* 1.0]]) (.set-points! p2 [[@t2* @bp*]]) (.set-points! p3 [[@t3* @sus*]]) (.set-points! p4 [[@t4* @sus*]]) (.set-points! p5 [[@t5* 0.0]]) (.set-points! seg-a [[0 0][@t1* 1.0]]) (.set-points! seg-b [[@t1* 1.0][@t2* @bp*]]) (.set-points! seg-c [[@t2* @bp*][@t3* @sus*]]) (.set-points! seg-d [[@t3* @sus*][@t4* @sus*]]) (.set-points! seg-e [[@t4* sus][@t5* 0.0]]) (.render drw))] (let [[att _](.mouse-where drw)] (reset! t1* (float (max 0 att))) (reset! t2* (+ @t1* dcy1)) (reset! t3* (+ @t2* dcy2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (.set-param! ied param-attack @t1*) (update-curve)) decay1 , breakpoint (let [[x y](.mouse-where drw) att @t1* dcy-1 (float (max 0 (- x att))) bp (float (sgwr-math/clamp y 0.0 1.0))] (reset! t2* (+ @t1* dcy1)) (reset! t3* (+ @t2* dcy2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (reset! bp* bp) (.set-param! ied param-decay1 dcy-1) (.set-param! ied param-breakpoint bp) (.status! ied (format "[%s] -> %5.3f [%s] -> %5.3f" param-decay1 dcy1 param-breakpoint bp)) (update-curve)) (let [[x y](.mouse-where drw) dcy-2 (float (max 0 (- x @t2*))) sus (float (sgwr-math/clamp y 0.0 1.0))] (reset! t3* (+ @t2* dcy-2)) (reset! t4* (+ @t3* 2)) (reset! t5* (+ @t4* rel)) (reset! sus* sus) (.set-param! ied param-decay2 dcy-2) (.set-param! ied param-sustain sus) (.status! ied (format "[%s] -> %5.3f [%s] -> %5.3f" param-decay2 dcy-2 param-sustain sus)) (update-curve)) (let [[_ y](.mouse-where drw) sus (float (sgwr-math/clamp y 0.0 1.0))] (reset! sus* sus) (.set-param! ied param-sustain sus) (update-curve)) (let [[x _](.mouse-where drw) rel (float (max 0 (- x @t4*)))] (reset! t5* (+ @t4* rel)) (.set-param! ied param-release rel) (update-curve)) :default (.warning! ied "Internal ERROR envelope-panel mouse-motion-listener") ))))) (point/point root [0 0] :id :env-p0 :color (lnf/envelope-handle) :style [:diag :diag2] :size 3) (major [0.0 -0.05][0.0 1.05]) (major [-0.1 0.00][100 0.00]) (major [-0.1 1.0][100 1.0]) (doseq [db (range -3 -36 -3)] (let [y (math/db->amp db)] (minor [-0.1 y][100 y]))) {:pan-main pan-main :sync-fn sync-fn :disable-fn disable-fn :enable-fn enable-fn}))
fea12a3cb487891b8316d789e077d5044f923b5b38222ae275a882034be693db
techwhizbang/bluecollar
redis_test.clj
(ns bluecollar.redis-test (:use clojure.test bluecollar.test-helper) (:require [bluecollar.redis :as redis] [bluecollar.keys-and-queues :as keys-qs])) (use-fixtures :each (fn [f] (redis-setup) (keys-qs/register-keys) (keys-qs/register-queues nil) (f))) (deftest redis-conn-test (testing "returns a new RedisConnection with the default pool-size" (let [conn (redis/new-connection redis/config) pool (:pool (:pool conn))] (is (= 10 (.getMaxActive pool))))) (testing "returns a new RedisConnection with the given pool-size" (let [conn (redis/new-connection redis/config 50) pool (:pool (:pool conn))] (is (= 50 (.getMaxActive pool)))))) (deftest failure-retry-cnt-test (testing "returns zero when there are no failures" (is (= 0 (redis/failure-retry-cnt "no-failures")))) (testing "increments an entry that does not exist yet by one" (redis/failure-retry-inc "burger") (is (= 1 (redis/failure-retry-cnt "burger")))) (testing "increments an entry that already exists by one" (redis/failure-retry-inc "cheese") (redis/failure-retry-inc "cheese") (is (= 2 (redis/failure-retry-cnt "cheese"))))) (deftest failure-retry-del-test (testing "it removes a key from the failures hash" (redis/failure-retry-inc "pizza") (is (= 1 (redis/failure-retry-cnt "pizza"))) (redis/failure-retry-del "pizza") (is (= 0 (redis/failure-retry-cnt "pizza")))) (testing "it doesn't complain if the key doesn't exist in the failures hash" (redis/failure-retry-del "mushroom frittata") (is (= 0 (redis/failure-retry-cnt "mushroom frittata"))))) (deftest failure-total-test (testing "returns zero when there are no failures" (is (= 0 (redis/failure-total-cnt)))) (testing "increments the count by one" (dorun (repeatedly 2 #(redis/failure-total-inc))) (is (= 2 (redis/failure-total-cnt))))) (deftest failure-total-del-test (redis/failure-total-inc) (is (= 1 (redis/failure-total-cnt))) (redis/failure-total-del) (is (= 0 (redis/failure-total-cnt)))) (deftest success-total-test (testing "returns zero when there are no successes" (is (= 0 (redis/success-total-cnt)))) (testing "increments the count by one" (dorun (repeatedly 2 #(redis/success-total-inc))) (is (= 2 (redis/success-total-cnt))))) (deftest success-total-del-test (redis/success-total-inc) (is (= 1 (redis/success-total-cnt))) (redis/success-total-del) (is (= 0 (redis/success-total-cnt)))) (deftest get-set-key-test (redis/setex "belgian" "tripel" 1) (is (= "tripel" (redis/get-value "belgian"))) (Thread/sleep 2500) (is (nil? (redis/get-value "belgian")))) (deftest delete-a-key-test (redis/setex "belgian" "dubbel" 2) (redis/del "belgian") (is (nil? (redis/get-value"belgian")))) (deftest sadd-srem-item-test (redis/sadd "beers" "ipa") (is (redis/smember? "beers" "ipa")) (redis/srem "beers" "ipa") (is (not (redis/smember? "beers" "ipa")))) (deftest push-value-onto-queue-test (testing "pushes a String value onto a named queued" (is (= (redis/push "bacon" "eggs") 1))) (testing "uses a separate RedisConnection to push a String value" (let [redis-conn (redis/new-connection redis-test-settings)] (is (= (redis/push "pancakes" "syrup" redis-conn) 1)) ))) (deftest rpush-value-onto-queue-test (testing "pushes a String value onto the tail of the named queue" (is (= (redis/rpush "chicken" "tacos") 1)) (is (= "tacos" (redis/pop-to-processing "chicken")))) (testing "pushes a String value ahead of something already in the queue" (let [_ (redis/push "chicken" "fajitas") _ (redis/rpush "chicken" "pot pie")] (is (= "pot pie" (redis/pop-to-processing "chicken"))) (is (= "fajitas" (redis/pop-to-processing "chicken"))) ))) (deftest pop-value-from-queue-test (testing "consumes a value from a named queue" (let [_ (redis/push "mocha" "latte") value (redis/pop-to-processing "mocha")] (is (= value "latte")))) (testing "places the pop valued into the processing queue" (let [_ (redis/push "deep dish" "pizza") _ (redis/pop-to-processing "deep dish") values (redis/lrange "processing" 0 0)] (is (= (first values) "pizza"))) ) (testing "uses a separate RedisConnection to pop a value" (let [redis-conn (redis/new-connection redis-test-settings) _ (redis/push "salt" "pepper" redis-conn)] (is (= (redis/pop-to-processing "salt" redis-conn) "pepper")) ))) (deftest blocking-pop-value-test (testing "consumes a value from a named queue" (let [_ (redis/push "mocha" "latte") value (redis/blocking-pop "mocha")] (is (= value "latte")))) (testing "places the value from the queue into the named processing queue" (let [_ (redis/push "basil" "pesto") value (redis/blocking-pop "basil" "basil-processing" 2) value-from-processing (redis/processing-pop "basil-processing")] (is (= value value-from-processing))))) (deftest remove-from-processing-test (testing "it removes the value from the processing queue" (let [original-value "latte" _ (redis/push "caramel" original-value) popped-value (redis/blocking-pop "caramel") _ (redis/remove-from-processing original-value) remaining-vals (redis/lrange "processing" 0 0)] (is (= popped-value "latte")) (is (empty? remaining-vals)) ))) (deftest processing-pop-test (testing "it removes the next item off of the processing queue" (let [original-value "blintzes" _ (redis/push "cheese" original-value) popped-value (redis/blocking-pop "cheese") processing-pop-val (redis/processing-pop)] (is (= processing-pop-val original-value)))) (testing "when there are multiple values on the processing queue" (let [first-value "blintzes" _ (redis/push "cheese" first-value) second-value "pierogies" _ (redis/push "cheese" second-value) _ (dorun (repeatedly 2 #(redis/blocking-pop "cheese"))) processing-first-val (redis/processing-pop) processing-sec-val (redis/processing-pop)] (is (= processing-first-val first-value)) (is (= processing-sec-val second-value))) )) (deftest push-worker-runtime-test (testing "it prepends the latest runtime to the front of the list" (redis/push-worker-runtime "worker-1" 20) (redis/push-worker-runtime "worker-1" 21) (is (= [21 20] (redis/get-worker-runtimes "worker-1")))))
null
https://raw.githubusercontent.com/techwhizbang/bluecollar/10269249a686c4e92daefd7cecd6c7c5934db81c/test/bluecollar/redis_test.clj
clojure
(ns bluecollar.redis-test (:use clojure.test bluecollar.test-helper) (:require [bluecollar.redis :as redis] [bluecollar.keys-and-queues :as keys-qs])) (use-fixtures :each (fn [f] (redis-setup) (keys-qs/register-keys) (keys-qs/register-queues nil) (f))) (deftest redis-conn-test (testing "returns a new RedisConnection with the default pool-size" (let [conn (redis/new-connection redis/config) pool (:pool (:pool conn))] (is (= 10 (.getMaxActive pool))))) (testing "returns a new RedisConnection with the given pool-size" (let [conn (redis/new-connection redis/config 50) pool (:pool (:pool conn))] (is (= 50 (.getMaxActive pool)))))) (deftest failure-retry-cnt-test (testing "returns zero when there are no failures" (is (= 0 (redis/failure-retry-cnt "no-failures")))) (testing "increments an entry that does not exist yet by one" (redis/failure-retry-inc "burger") (is (= 1 (redis/failure-retry-cnt "burger")))) (testing "increments an entry that already exists by one" (redis/failure-retry-inc "cheese") (redis/failure-retry-inc "cheese") (is (= 2 (redis/failure-retry-cnt "cheese"))))) (deftest failure-retry-del-test (testing "it removes a key from the failures hash" (redis/failure-retry-inc "pizza") (is (= 1 (redis/failure-retry-cnt "pizza"))) (redis/failure-retry-del "pizza") (is (= 0 (redis/failure-retry-cnt "pizza")))) (testing "it doesn't complain if the key doesn't exist in the failures hash" (redis/failure-retry-del "mushroom frittata") (is (= 0 (redis/failure-retry-cnt "mushroom frittata"))))) (deftest failure-total-test (testing "returns zero when there are no failures" (is (= 0 (redis/failure-total-cnt)))) (testing "increments the count by one" (dorun (repeatedly 2 #(redis/failure-total-inc))) (is (= 2 (redis/failure-total-cnt))))) (deftest failure-total-del-test (redis/failure-total-inc) (is (= 1 (redis/failure-total-cnt))) (redis/failure-total-del) (is (= 0 (redis/failure-total-cnt)))) (deftest success-total-test (testing "returns zero when there are no successes" (is (= 0 (redis/success-total-cnt)))) (testing "increments the count by one" (dorun (repeatedly 2 #(redis/success-total-inc))) (is (= 2 (redis/success-total-cnt))))) (deftest success-total-del-test (redis/success-total-inc) (is (= 1 (redis/success-total-cnt))) (redis/success-total-del) (is (= 0 (redis/success-total-cnt)))) (deftest get-set-key-test (redis/setex "belgian" "tripel" 1) (is (= "tripel" (redis/get-value "belgian"))) (Thread/sleep 2500) (is (nil? (redis/get-value "belgian")))) (deftest delete-a-key-test (redis/setex "belgian" "dubbel" 2) (redis/del "belgian") (is (nil? (redis/get-value"belgian")))) (deftest sadd-srem-item-test (redis/sadd "beers" "ipa") (is (redis/smember? "beers" "ipa")) (redis/srem "beers" "ipa") (is (not (redis/smember? "beers" "ipa")))) (deftest push-value-onto-queue-test (testing "pushes a String value onto a named queued" (is (= (redis/push "bacon" "eggs") 1))) (testing "uses a separate RedisConnection to push a String value" (let [redis-conn (redis/new-connection redis-test-settings)] (is (= (redis/push "pancakes" "syrup" redis-conn) 1)) ))) (deftest rpush-value-onto-queue-test (testing "pushes a String value onto the tail of the named queue" (is (= (redis/rpush "chicken" "tacos") 1)) (is (= "tacos" (redis/pop-to-processing "chicken")))) (testing "pushes a String value ahead of something already in the queue" (let [_ (redis/push "chicken" "fajitas") _ (redis/rpush "chicken" "pot pie")] (is (= "pot pie" (redis/pop-to-processing "chicken"))) (is (= "fajitas" (redis/pop-to-processing "chicken"))) ))) (deftest pop-value-from-queue-test (testing "consumes a value from a named queue" (let [_ (redis/push "mocha" "latte") value (redis/pop-to-processing "mocha")] (is (= value "latte")))) (testing "places the pop valued into the processing queue" (let [_ (redis/push "deep dish" "pizza") _ (redis/pop-to-processing "deep dish") values (redis/lrange "processing" 0 0)] (is (= (first values) "pizza"))) ) (testing "uses a separate RedisConnection to pop a value" (let [redis-conn (redis/new-connection redis-test-settings) _ (redis/push "salt" "pepper" redis-conn)] (is (= (redis/pop-to-processing "salt" redis-conn) "pepper")) ))) (deftest blocking-pop-value-test (testing "consumes a value from a named queue" (let [_ (redis/push "mocha" "latte") value (redis/blocking-pop "mocha")] (is (= value "latte")))) (testing "places the value from the queue into the named processing queue" (let [_ (redis/push "basil" "pesto") value (redis/blocking-pop "basil" "basil-processing" 2) value-from-processing (redis/processing-pop "basil-processing")] (is (= value value-from-processing))))) (deftest remove-from-processing-test (testing "it removes the value from the processing queue" (let [original-value "latte" _ (redis/push "caramel" original-value) popped-value (redis/blocking-pop "caramel") _ (redis/remove-from-processing original-value) remaining-vals (redis/lrange "processing" 0 0)] (is (= popped-value "latte")) (is (empty? remaining-vals)) ))) (deftest processing-pop-test (testing "it removes the next item off of the processing queue" (let [original-value "blintzes" _ (redis/push "cheese" original-value) popped-value (redis/blocking-pop "cheese") processing-pop-val (redis/processing-pop)] (is (= processing-pop-val original-value)))) (testing "when there are multiple values on the processing queue" (let [first-value "blintzes" _ (redis/push "cheese" first-value) second-value "pierogies" _ (redis/push "cheese" second-value) _ (dorun (repeatedly 2 #(redis/blocking-pop "cheese"))) processing-first-val (redis/processing-pop) processing-sec-val (redis/processing-pop)] (is (= processing-first-val first-value)) (is (= processing-sec-val second-value))) )) (deftest push-worker-runtime-test (testing "it prepends the latest runtime to the front of the list" (redis/push-worker-runtime "worker-1" 20) (redis/push-worker-runtime "worker-1" 21) (is (= [21 20] (redis/get-worker-runtimes "worker-1")))))
2887485c7922f02549255db6388937f3b7369411ebd7a6f0d65ffed99e5fee02
tek/ribosome
Scratch.hs
-- |Interpreters for 'Scratch' module Ribosome.Interpreter.Scratch where import Conc (interpretAtomic) import qualified Data.Map.Strict as Map import Exon (exon) import Ribosome.Data.PluginName (PluginName) import Ribosome.Data.ScratchId (ScratchId (ScratchId)) import Ribosome.Data.ScratchState (ScratchState) import Ribosome.Effect.Scratch (Scratch (Delete, Find, Get, Show, Update)) import qualified Ribosome.Host.Data.RpcError as RpcError import Ribosome.Host.Data.RpcError (RpcError) import Ribosome.Host.Effect.Rpc (Rpc) import Ribosome.Internal.Scratch (killScratch, lookupScratch, setScratchContent, showInScratch) |Interpret ' Scratch ' by storing the Neovim UI handles in ' AtomicState ' . This uses ' ' , see [ Errors]("Ribosome#g : errors " ) . interpretScratchAtomic :: Members [Rpc !! RpcError, AtomicState (Map ScratchId ScratchState), Reader PluginName, Log, Resource] r => InterpreterFor (Scratch !! RpcError) r interpretScratchAtomic = interpretResumable \case Show text options -> restop (showInScratch text options) Update i text -> do s <- stopNote (RpcError.Unexpected [exon|No scratch buffer named '#{coerce i}' exists|]) =<< lookupScratch i s <$ restop @_ @Rpc (setScratchContent s text) Delete i -> traverse_ killScratch =<< lookupScratch i Get -> atomicGets Map.elems Find i -> atomicGets (Map.lookup i) |Interpret ' Scratch ' by storing the Neovim UI handles in ' AtomicState ' . This uses ' ' , see [ Errors]("Ribosome#g : errors " ) . interpretScratch :: Members [Rpc !! RpcError, Reader PluginName, Log, Resource, Embed IO] r => InterpreterFor (Scratch !! RpcError) r interpretScratch = interpretAtomic mempty . interpretScratchAtomic . raiseUnder
null
https://raw.githubusercontent.com/tek/ribosome/f801aca3a7ff9a178e05a03d7874a06e88f4ac2b/packages/ribosome/lib/Ribosome/Interpreter/Scratch.hs
haskell
|Interpreters for 'Scratch'
module Ribosome.Interpreter.Scratch where import Conc (interpretAtomic) import qualified Data.Map.Strict as Map import Exon (exon) import Ribosome.Data.PluginName (PluginName) import Ribosome.Data.ScratchId (ScratchId (ScratchId)) import Ribosome.Data.ScratchState (ScratchState) import Ribosome.Effect.Scratch (Scratch (Delete, Find, Get, Show, Update)) import qualified Ribosome.Host.Data.RpcError as RpcError import Ribosome.Host.Data.RpcError (RpcError) import Ribosome.Host.Effect.Rpc (Rpc) import Ribosome.Internal.Scratch (killScratch, lookupScratch, setScratchContent, showInScratch) |Interpret ' Scratch ' by storing the Neovim UI handles in ' AtomicState ' . This uses ' ' , see [ Errors]("Ribosome#g : errors " ) . interpretScratchAtomic :: Members [Rpc !! RpcError, AtomicState (Map ScratchId ScratchState), Reader PluginName, Log, Resource] r => InterpreterFor (Scratch !! RpcError) r interpretScratchAtomic = interpretResumable \case Show text options -> restop (showInScratch text options) Update i text -> do s <- stopNote (RpcError.Unexpected [exon|No scratch buffer named '#{coerce i}' exists|]) =<< lookupScratch i s <$ restop @_ @Rpc (setScratchContent s text) Delete i -> traverse_ killScratch =<< lookupScratch i Get -> atomicGets Map.elems Find i -> atomicGets (Map.lookup i) |Interpret ' Scratch ' by storing the Neovim UI handles in ' AtomicState ' . This uses ' ' , see [ Errors]("Ribosome#g : errors " ) . interpretScratch :: Members [Rpc !! RpcError, Reader PluginName, Log, Resource, Embed IO] r => InterpreterFor (Scratch !! RpcError) r interpretScratch = interpretAtomic mempty . interpretScratchAtomic . raiseUnder
2f36176e631e0183e2d631c6ca59101a707b1be18b49129269e50f5a5d609656
s-expressionists/Eclector
package.lisp
(cl:defpackage #:eclector.readtable.simple (:use #:common-lisp) (:shadow . #1=(#:readtable)) (:import-from #:eclector.base #:recovery-description-using-language) (:export . #1#))
null
https://raw.githubusercontent.com/s-expressionists/Eclector/0469fef9bde28ac16f5de6964b189534c152fafa/code/readtable/simple/package.lisp
lisp
(cl:defpackage #:eclector.readtable.simple (:use #:common-lisp) (:shadow . #1=(#:readtable)) (:import-from #:eclector.base #:recovery-description-using-language) (:export . #1#))
0c73148c2b436dc0cfb78c8013c3f60fce37ed0572b6997626d890c8410bfff8
montelibero-org/veche
ApiSpec.hs
# LANGUAGE BlockArguments # # LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedRecordDot # {-# LANGUAGE OverloadedStrings #-} module ApiSpec (spec) where -- prelude import TestImport -- global import Data.ByteString (breakSubstring) import Data.ByteString.Base64 qualified as Base64 import Network.Stellar.Keypair (KeyPair, encodePublicKey, fromPrivateKey') import Network.Stellar.Keypair qualified import Network.Stellar.Signature (signBlob) mmwbR :: [Text] -> Route App mmwbR = AuthR . PluginR "mymtlwalletbot" kp :: KeyPair kp = fromPrivateKey' "SDHDJTXDM6IILXA3SPT357QJ2MJCH6WWWLZDVZI2HHSIR3V2E4AOMG4B" account :: Text account = encodePublicKey kp.kpPublicKey spec :: Spec spec = withApp $ describe "verification key" do it "taken from /start command" do get' $ AuthR LoginR statusIs 200 a <- htmlQuery ".mymtlwalletbot-authn-start" <&> toStrict . headEx let verifier = between "?start=veche_" "\"" a let signature = signBlob kp $ encodeUtf8 account <> verifier get' ( mmwbR [] , [ ("account", account) , ("signature", decodeUtf8Throw $ Base64.encode signature) ] ) statusIs 303 -- successful authentication it "is created on request" do post' (mmwbR ["verifier"], [("account", account)]) [] statusIs 200 verifier <- getResponseBody let signature = signBlob kp $ encodeUtf8 account <> toStrict verifier testClearCookies -- important! clear session get' ( mmwbR [] , [ ("account", account) , ("signature", decodeUtf8Throw $ Base64.encode signature) , ("verifier", decodeUtf8Throw $ toStrict verifier) ] ) statusIs 303 -- successful authentication between :: ByteString -> ByteString -> ByteString -> ByteString between start end = fst . breakSubstring end . drop (length start) . snd . breakSubstring start
null
https://raw.githubusercontent.com/montelibero-org/veche/60f79ef4afba55475196a86a26b3ea0a972a4b17/veche-web/test/ApiSpec.hs
haskell
# LANGUAGE OverloadedStrings # prelude global successful authentication important! clear session successful authentication
# LANGUAGE BlockArguments # # LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # # LANGUAGE OverloadedRecordDot # module ApiSpec (spec) where import TestImport import Data.ByteString (breakSubstring) import Data.ByteString.Base64 qualified as Base64 import Network.Stellar.Keypair (KeyPair, encodePublicKey, fromPrivateKey') import Network.Stellar.Keypair qualified import Network.Stellar.Signature (signBlob) mmwbR :: [Text] -> Route App mmwbR = AuthR . PluginR "mymtlwalletbot" kp :: KeyPair kp = fromPrivateKey' "SDHDJTXDM6IILXA3SPT357QJ2MJCH6WWWLZDVZI2HHSIR3V2E4AOMG4B" account :: Text account = encodePublicKey kp.kpPublicKey spec :: Spec spec = withApp $ describe "verification key" do it "taken from /start command" do get' $ AuthR LoginR statusIs 200 a <- htmlQuery ".mymtlwalletbot-authn-start" <&> toStrict . headEx let verifier = between "?start=veche_" "\"" a let signature = signBlob kp $ encodeUtf8 account <> verifier get' ( mmwbR [] , [ ("account", account) , ("signature", decodeUtf8Throw $ Base64.encode signature) ] ) it "is created on request" do post' (mmwbR ["verifier"], [("account", account)]) [] statusIs 200 verifier <- getResponseBody let signature = signBlob kp $ encodeUtf8 account <> toStrict verifier get' ( mmwbR [] , [ ("account", account) , ("signature", decodeUtf8Throw $ Base64.encode signature) , ("verifier", decodeUtf8Throw $ toStrict verifier) ] ) between :: ByteString -> ByteString -> ByteString -> ByteString between start end = fst . breakSubstring end . drop (length start) . snd . breakSubstring start
ac15b4d9b16162c8fe7fa366708c8a41c62b188e5dec840208d364170495a057
edbutler/nonograms-rule-synthesis
bindings.rkt
#lang rosette/safe (provide gaps-of-line blocks-of-line) (require (only-in racket error) "../core/core.rkt" "symbolic.rkt" "rules.rkt") ( cell ? - > bool ? ) , line ? - > ( listof segment ? ) (define (segments-of-concrete-line partition-fn ctx) (when (symbolic? ctx) (error "only concrete lines supported")) (define cells (line-cells ctx)) (define (foldfn i c acc) (define segs (first acc)) (define last-start (second acc)) (define last-len (third acc)) (cond [(partition-fn c) (list segs last-start (add1 last-len))] [(> last-len 0) (list (cons (segment last-start (+ last-len last-start) #t) segs) (add1 i) 0)] [else (list segs (add1 i) 0)])) (define res (foldl foldfn (list '() 0 0) (range/s 0 (add1 (line-length ctx))) (append cells (list #f)))) (reverse (first res))) (define (segments-of-symbolic-line partition-fn ctx) (define len (line-length ctx)) (define max-segments (quotient (add1 len) 2)) (define cells (line-cells ctx)) (define-values (segments seg-count) (symbolic-segments ctx max-segments)) (for-each (λ (i c) (define (in-seg? s) (&& (segment-used? s) (<= (segment-start s) i) (< i (segment-end s)))) (define in-any? (lormap in-seg? segments)) (assert (<=> (partition-fn c) in-any?))) (range/s 0 len) cells) (take segments seg-count)) (define (segments-of-line partition-fn ctx #:symbolic? [symb? 'detect]) (cond [(or (equal? symb? #t) (and (equal? symb? 'detect) (symbolic? ctx))) (segments-of-symbolic-line partition-fn ctx)] [else (segments-of-concrete-line partition-fn ctx)])) line ? - > ( listof segment ? ) (define (gaps-of-line ctx #:symbolic? [s? 'detect]) (define (in-gap? c) (|| (true-cell? c) (empty-cell? c))) (segments-of-line in-gap? ctx #:symbolic? s?)) line ? - > ( listof segment ? ) (define (blocks-of-line ctx #:symbolic? [s? 'detect]) (segments-of-line true-cell? ctx #:symbolic? s?))
null
https://raw.githubusercontent.com/edbutler/nonograms-rule-synthesis/16f8dacb17bd77c9d927ab9fa0b8c1678dc68088/src/nonograms/bindings.rkt
racket
#lang rosette/safe (provide gaps-of-line blocks-of-line) (require (only-in racket error) "../core/core.rkt" "symbolic.rkt" "rules.rkt") ( cell ? - > bool ? ) , line ? - > ( listof segment ? ) (define (segments-of-concrete-line partition-fn ctx) (when (symbolic? ctx) (error "only concrete lines supported")) (define cells (line-cells ctx)) (define (foldfn i c acc) (define segs (first acc)) (define last-start (second acc)) (define last-len (third acc)) (cond [(partition-fn c) (list segs last-start (add1 last-len))] [(> last-len 0) (list (cons (segment last-start (+ last-len last-start) #t) segs) (add1 i) 0)] [else (list segs (add1 i) 0)])) (define res (foldl foldfn (list '() 0 0) (range/s 0 (add1 (line-length ctx))) (append cells (list #f)))) (reverse (first res))) (define (segments-of-symbolic-line partition-fn ctx) (define len (line-length ctx)) (define max-segments (quotient (add1 len) 2)) (define cells (line-cells ctx)) (define-values (segments seg-count) (symbolic-segments ctx max-segments)) (for-each (λ (i c) (define (in-seg? s) (&& (segment-used? s) (<= (segment-start s) i) (< i (segment-end s)))) (define in-any? (lormap in-seg? segments)) (assert (<=> (partition-fn c) in-any?))) (range/s 0 len) cells) (take segments seg-count)) (define (segments-of-line partition-fn ctx #:symbolic? [symb? 'detect]) (cond [(or (equal? symb? #t) (and (equal? symb? 'detect) (symbolic? ctx))) (segments-of-symbolic-line partition-fn ctx)] [else (segments-of-concrete-line partition-fn ctx)])) line ? - > ( listof segment ? ) (define (gaps-of-line ctx #:symbolic? [s? 'detect]) (define (in-gap? c) (|| (true-cell? c) (empty-cell? c))) (segments-of-line in-gap? ctx #:symbolic? s?)) line ? - > ( listof segment ? ) (define (blocks-of-line ctx #:symbolic? [s? 'detect]) (segments-of-line true-cell? ctx #:symbolic? s?))
e0e21b9754ed8320d9176ae533090993b7ddb02fe6622ee5ae4a51ca8a7b6575
mbj/stratosphere
StoppingConditionProperty.hs
module Stratosphere.SageMaker.MonitoringSchedule.StoppingConditionProperty ( StoppingConditionProperty(..), mkStoppingConditionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StoppingConditionProperty = StoppingConditionProperty {maxRuntimeInSeconds :: (Value Prelude.Integer)} mkStoppingConditionProperty :: Value Prelude.Integer -> StoppingConditionProperty mkStoppingConditionProperty maxRuntimeInSeconds = StoppingConditionProperty {maxRuntimeInSeconds = maxRuntimeInSeconds} instance ToResourceProperties StoppingConditionProperty where toResourceProperties StoppingConditionProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::MonitoringSchedule.StoppingCondition", supportsTags = Prelude.False, properties = ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]} instance JSON.ToJSON StoppingConditionProperty where toJSON StoppingConditionProperty {..} = JSON.object ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds] instance Property "MaxRuntimeInSeconds" StoppingConditionProperty where type PropertyType "MaxRuntimeInSeconds" StoppingConditionProperty = Value Prelude.Integer set newValue StoppingConditionProperty {} = StoppingConditionProperty {maxRuntimeInSeconds = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/MonitoringSchedule/StoppingConditionProperty.hs
haskell
module Stratosphere.SageMaker.MonitoringSchedule.StoppingConditionProperty ( StoppingConditionProperty(..), mkStoppingConditionProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StoppingConditionProperty = StoppingConditionProperty {maxRuntimeInSeconds :: (Value Prelude.Integer)} mkStoppingConditionProperty :: Value Prelude.Integer -> StoppingConditionProperty mkStoppingConditionProperty maxRuntimeInSeconds = StoppingConditionProperty {maxRuntimeInSeconds = maxRuntimeInSeconds} instance ToResourceProperties StoppingConditionProperty where toResourceProperties StoppingConditionProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::MonitoringSchedule.StoppingCondition", supportsTags = Prelude.False, properties = ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds]} instance JSON.ToJSON StoppingConditionProperty where toJSON StoppingConditionProperty {..} = JSON.object ["MaxRuntimeInSeconds" JSON..= maxRuntimeInSeconds] instance Property "MaxRuntimeInSeconds" StoppingConditionProperty where type PropertyType "MaxRuntimeInSeconds" StoppingConditionProperty = Value Prelude.Integer set newValue StoppingConditionProperty {} = StoppingConditionProperty {maxRuntimeInSeconds = newValue, ..}
39a4eb1b5811f6431ad402d8013f5e7aa240f9a930a3866b3ca62ac2d575cbd2
leksah/leksah
Setup.hs
{-# LANGUAGE OverloadedStrings #-} import Data.GI.CodeGen.CabalHooks (setupBinding, TaggedOverride(..)) import qualified GI.GLib.Config as GLib main :: IO () main = setupBinding name version pkgName pkgVersion verbose overridesFile inheritedOverrides outputDir where name = "GObject" version = "2.0" pkgName = "gi-gobject" pkgVersion = "2.0.26" overridesFile = Just "GObject.overrides" verbose = False outputDir = Nothing inheritedOverrides = [TaggedOverride "inherited:GLib" GLib.overrides]
null
https://raw.githubusercontent.com/leksah/leksah/fd9c1d80993fb1ee5fd299a16bf373d8c789e737/vendor/gi-gobject/Setup.hs
haskell
# LANGUAGE OverloadedStrings #
import Data.GI.CodeGen.CabalHooks (setupBinding, TaggedOverride(..)) import qualified GI.GLib.Config as GLib main :: IO () main = setupBinding name version pkgName pkgVersion verbose overridesFile inheritedOverrides outputDir where name = "GObject" version = "2.0" pkgName = "gi-gobject" pkgVersion = "2.0.26" overridesFile = Just "GObject.overrides" verbose = False outputDir = Nothing inheritedOverrides = [TaggedOverride "inherited:GLib" GLib.overrides]
7bd5ca35c6a6f89743af96f8efb8a018bb10460f4a47f3f2350b09fac532c323
informatimago/lisp
dll.lisp
-*- coding : utf-8 -*- ;;;;**************************************************************************** FILE : dll.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp USER - INTERFACE : ;;;;DESCRIPTION ;;;; ;;;; A doubly-linked list. ;;;; < PJB > < > MODIFICATIONS 2011 - 06 - 22 < PJB > Corrected a bug in DLL . 2005 - 04 - 28 < PJB > Clean - up . 2004 - 03 - 01 < PJB > Created . ;;;;LEGAL AGPL3 ;;;; Copyright 2004 - 2016 ;;;; ;;;; 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 </> ;;;;**************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DLL" (:use "COMMON-LISP") (:export "DLL-DELETE" "DLL-INSERT" "DLL-NODE-POSITION" "DLL-NODE-NTH" "DLL-NODE-ITEM" "DLL-NODE-PREVIOUS" "DLL-NODE-NEXT" "DLL-NODE" "DLL-LAST" "DLL-FIRST" "DLL-POSITION" "DLL-NTH" "DLL-CONTENTS" "DLL-NCONC" "DLL-APPEND" "DLL-COPY" "DLL-EQUAL" "DLL-LENGTH" "DLL-EMPTY-P" "DLL-LAST-NODE" "DLL-FIRST-NODE" "DLL") (:documentation " This module exports a double-linked list type. This is a structure optimized for insertions and deletions in any place, each node keeping a pointer to both the previous and the next node. The stub keeps a pointer to the head of the list, and the list is circularly closed \(the tail points to the head). License: AGPL3 Copyright Pascal J. Bourguignon 2001 - 2012 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 </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DLL") (defstruct (dll (:conc-name %dll-)) "A Doubly-Linked List. A DLL keeps a reference to the first node and to the last node." (first nil) (last nil)) (defstruct dll-node "A node in a Doubly-Linked List. Each node is linked to the previous and to the next node in the list, and keeps a reference to its item." (previous nil) (next nil) (item nil)) (setf (documentation 'dll-node-previous 'function) "The previous node." (documentation 'dll-node-next 'function) "The next node." (documentation 'dll-node-item 'function) "The item of the node.") (defun dll (&rest list) " RETURN: A new DLL containing the elements passed as arguments. " (loop :with dlist = (make-dll) :for element :in list :for last-node = (dll-insert dlist nil element) :then (dll-insert dlist last-node element) :finally (return dlist))) (defun dll-first-node (dlist) " RETURN: The first node of the DLIST. " (%dll-first dlist)) (defun dll-last-node (dlist) " RETURN: The last node of the DLIST. " (%dll-last dlist)) (defun dll-empty-p (dlist) " RETURN: Whether the DLL DLIST is empty. ie. (zerop (dll-length dlist)) " (null (%dll-first dlist))) (defun dll-length (dlist) " RETURN: The number of elements in the DLL DLIST. " (do ((len 0 (1+ len)) (current (%dll-last dlist) (dll-node-previous current))) ((null current) len))) (defun dll-nth (index dlist) " RETURN: The INDEXth element in the DLL DLIST. " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (= i index)) (when current (dll-node-item current))))) (defun dll-position (item dlist &key (test (function eql))) " RETURN: The INDEX of the first element in the DLL DLIST that satisfies the test (TEST element ITEM). " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (funcall test (dll-node-item current) item)) (when current i)))) (defun dll-node-position (node dlist &key (test (function eql))) " RETURN: The INDEX of the first node in the DLL DLIST that satisfies the test (TEST element NODE). " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (funcall test current node)) (when current i)))) (defun dll-equal (&rest dlls) " RETURN: Whether all the DLLS contain the same elements in the same order. " (or (null dlls) (null (cdr dlls)) (and (let ((left (first dlls)) (right (second dlls))) (and (equal (dll-node-item (%dll-first left)) (dll-node-item (%dll-first right))) (equal (dll-node-item (%dll-last left)) (dll-node-item (%dll-last right))) (do ((lnodes (dll-node-next (%dll-first left)) (dll-node-next lnodes)) (rnodes (dll-node-next (%dll-first right)) (dll-node-next rnodes))) ((or (eq lnodes (%dll-last left)) (eq rnodes (%dll-last right)) (not (equal (dll-node-item lnodes) (dll-node-item rnodes)))) (and (eq lnodes (%dll-last left)) (eq rnodes (%dll-last right))))) (dll-equal (cdr dlls))))))) (defun dll-copy (dlist) " RETURN: A copy of the DLL DLIST. " (do ((new-dll (make-dll)) (src (%dll-first dlist) (dll-node-next src)) (dst nil)) ((null src) new-dll) (setf dst (dll-insert new-dll dst (dll-node-item src))))) (defun dll-append (&rest dlls) " DO: Appends the elements in all the DLLS into a single dll. The DLLs are not modified. RETURN: A new dll with all the elements in DLLS. " (if (null dlls) (make-dll) (apply (function dll-nconc) (mapcar (function dll-copy) dlls)))) (defun dll-nconc (first-dll &rest dlls) " PRE: No dll appears twice in (CONS FIRST-DLL DLLS). DO: Extract the nodes from all but the FIRST-DLL, and append them all to that FIRST-DLL. POST: ∀l∈dlls, (dll-empty-p l) (dll-length first-dll) = Σ (dll-length old l) l∈dlls " (if (null dlls) first-dll (dolist (dll (rest dlls) first-dll) (let ((first (%dll-first dll))) (unless (null first) (setf (dll-node-previous first) (%dll-last first-dll) (dll-node-next (%dll-last first-dll)) first (%dll-last first-dll) (%dll-last dll) (%dll-first dll) nil (%dll-last dll) nil)))))) (defun dll-contents (dlist) " RETURN: A new list containing the items of the dll. " (do ((current (%dll-last dlist) (dll-node-previous current)) (result ())) ((null current) result) (push (dll-node-item current) result))) (defun dll-first (dlist) " RETURN: The first element in the DLL DLIST, or NIL if it's empty. " (unless (dll-empty-p dlist) (dll-node-item (%dll-first dlist)))) (defun dll-last (dlist) " RETURN: The last element in the DLL DLIST, or NIL if it's empty. " (unless (dll-empty-p dlist) (dll-node-item (%dll-last dlist)))) (defun dll-node-nth (index dlist) " RETURN: The INDEXth node of the DLL DLIST, or NIL if it's empty. " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (= i index)) current))) (defun dll-insert (dlist node item) " DO: Insert a new node after NODE, or before first position when (NULL NODE). RETURN: The new node. " (let ((new-node nil)) (cond first item (setf new-node (make-dll-node :item item)) (setf (%dll-first dlist) new-node (%dll-last dlist) (%dll-first dlist))) insert before first (setf new-node (make-dll-node :previous nil :next (dll-first-node dlist) :item item)) (setf (dll-node-previous (%dll-first dlist)) new-node (%dll-first dlist) new-node)) ((not (dll-node-position node dlist)) (error "Node not in doubly-linked list.")) (t (setf new-node (make-dll-node :previous node :next (dll-node-next node) :item item)) (if (dll-node-next node) (setf (dll-node-previous (dll-node-next node)) new-node) (setf (%dll-last dlist) new-node)) (setf (dll-node-next node) new-node))) new-node)) (defun dll-extract-node (dlist node) (if (eq (dll-first-node dlist) node) (setf (%dll-first dlist) (dll-node-next node)) (setf (dll-node-next (dll-node-previous node)) (dll-node-next node))) (if (eq (dll-last-node dlist) node) (setf (%dll-last dlist) (dll-node-previous node)) (setf (dll-node-previous (dll-node-next node)) (dll-node-previous node))) dlist) (defun dll-delete (node dlist) " DO: Delete the NODE from the DLL DLIST. RETURN: DLIST " (unless (or (null node) (dll-empty-p dlist) (not (dll-node-position node dlist))) ;; Note O(N)! (dll-extract-node dlist node)) dlist) (defun dll-delete-nth (index dlist) " DO: Delete the INDEXth element of the DLL DLIST. RETURN: DLIST " (dll-extract-node dlist (dll-node-nth index dlist))) ;;;; THE END ;;;;
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/cesarum/dll.lisp
lisp
**************************************************************************** LANGUAGE: Common-Lisp SYSTEM: Common-Lisp DESCRIPTION A doubly-linked list. LEGAL 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 along with this program. If not, see </> **************************************************************************** without even the implied warranty of Note O(N)! THE END ;;;;
-*- coding : utf-8 -*- FILE : dll.lisp USER - INTERFACE : < PJB > < > MODIFICATIONS 2011 - 06 - 22 < PJB > Corrected a bug in DLL . 2005 - 04 - 28 < PJB > Clean - up . 2004 - 03 - 01 < PJB > Created . AGPL3 Copyright 2004 - 2016 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 GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DLL" (:use "COMMON-LISP") (:export "DLL-DELETE" "DLL-INSERT" "DLL-NODE-POSITION" "DLL-NODE-NTH" "DLL-NODE-ITEM" "DLL-NODE-PREVIOUS" "DLL-NODE-NEXT" "DLL-NODE" "DLL-LAST" "DLL-FIRST" "DLL-POSITION" "DLL-NTH" "DLL-CONTENTS" "DLL-NCONC" "DLL-APPEND" "DLL-COPY" "DLL-EQUAL" "DLL-LENGTH" "DLL-EMPTY-P" "DLL-LAST-NODE" "DLL-FIRST-NODE" "DLL") (:documentation " This module exports a double-linked list type. This is a structure optimized for insertions and deletions in any place, each node keeping a pointer to both the previous and the next node. The stub keeps a pointer to the head of the list, and the list is circularly closed \(the tail points to the head). License: AGPL3 Copyright Pascal J. Bourguignon 2001 - 2012 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, 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 </> ")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DLL") (defstruct (dll (:conc-name %dll-)) "A Doubly-Linked List. A DLL keeps a reference to the first node and to the last node." (first nil) (last nil)) (defstruct dll-node "A node in a Doubly-Linked List. Each node is linked to the previous and to the next node in the list, and keeps a reference to its item." (previous nil) (next nil) (item nil)) (setf (documentation 'dll-node-previous 'function) "The previous node." (documentation 'dll-node-next 'function) "The next node." (documentation 'dll-node-item 'function) "The item of the node.") (defun dll (&rest list) " RETURN: A new DLL containing the elements passed as arguments. " (loop :with dlist = (make-dll) :for element :in list :for last-node = (dll-insert dlist nil element) :then (dll-insert dlist last-node element) :finally (return dlist))) (defun dll-first-node (dlist) " RETURN: The first node of the DLIST. " (%dll-first dlist)) (defun dll-last-node (dlist) " RETURN: The last node of the DLIST. " (%dll-last dlist)) (defun dll-empty-p (dlist) " RETURN: Whether the DLL DLIST is empty. ie. (zerop (dll-length dlist)) " (null (%dll-first dlist))) (defun dll-length (dlist) " RETURN: The number of elements in the DLL DLIST. " (do ((len 0 (1+ len)) (current (%dll-last dlist) (dll-node-previous current))) ((null current) len))) (defun dll-nth (index dlist) " RETURN: The INDEXth element in the DLL DLIST. " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (= i index)) (when current (dll-node-item current))))) (defun dll-position (item dlist &key (test (function eql))) " RETURN: The INDEX of the first element in the DLL DLIST that satisfies the test (TEST element ITEM). " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (funcall test (dll-node-item current) item)) (when current i)))) (defun dll-node-position (node dlist &key (test (function eql))) " RETURN: The INDEX of the first node in the DLL DLIST that satisfies the test (TEST element NODE). " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (funcall test current node)) (when current i)))) (defun dll-equal (&rest dlls) " RETURN: Whether all the DLLS contain the same elements in the same order. " (or (null dlls) (null (cdr dlls)) (and (let ((left (first dlls)) (right (second dlls))) (and (equal (dll-node-item (%dll-first left)) (dll-node-item (%dll-first right))) (equal (dll-node-item (%dll-last left)) (dll-node-item (%dll-last right))) (do ((lnodes (dll-node-next (%dll-first left)) (dll-node-next lnodes)) (rnodes (dll-node-next (%dll-first right)) (dll-node-next rnodes))) ((or (eq lnodes (%dll-last left)) (eq rnodes (%dll-last right)) (not (equal (dll-node-item lnodes) (dll-node-item rnodes)))) (and (eq lnodes (%dll-last left)) (eq rnodes (%dll-last right))))) (dll-equal (cdr dlls))))))) (defun dll-copy (dlist) " RETURN: A copy of the DLL DLIST. " (do ((new-dll (make-dll)) (src (%dll-first dlist) (dll-node-next src)) (dst nil)) ((null src) new-dll) (setf dst (dll-insert new-dll dst (dll-node-item src))))) (defun dll-append (&rest dlls) " DO: Appends the elements in all the DLLS into a single dll. The DLLs are not modified. RETURN: A new dll with all the elements in DLLS. " (if (null dlls) (make-dll) (apply (function dll-nconc) (mapcar (function dll-copy) dlls)))) (defun dll-nconc (first-dll &rest dlls) " PRE: No dll appears twice in (CONS FIRST-DLL DLLS). DO: Extract the nodes from all but the FIRST-DLL, and append them all to that FIRST-DLL. POST: ∀l∈dlls, (dll-empty-p l) (dll-length first-dll) = Σ (dll-length old l) l∈dlls " (if (null dlls) first-dll (dolist (dll (rest dlls) first-dll) (let ((first (%dll-first dll))) (unless (null first) (setf (dll-node-previous first) (%dll-last first-dll) (dll-node-next (%dll-last first-dll)) first (%dll-last first-dll) (%dll-last dll) (%dll-first dll) nil (%dll-last dll) nil)))))) (defun dll-contents (dlist) " RETURN: A new list containing the items of the dll. " (do ((current (%dll-last dlist) (dll-node-previous current)) (result ())) ((null current) result) (push (dll-node-item current) result))) (defun dll-first (dlist) " RETURN: The first element in the DLL DLIST, or NIL if it's empty. " (unless (dll-empty-p dlist) (dll-node-item (%dll-first dlist)))) (defun dll-last (dlist) " RETURN: The last element in the DLL DLIST, or NIL if it's empty. " (unless (dll-empty-p dlist) (dll-node-item (%dll-last dlist)))) (defun dll-node-nth (index dlist) " RETURN: The INDEXth node of the DLL DLIST, or NIL if it's empty. " (do ((i 0 (1+ i)) (current (%dll-first dlist) (dll-node-next current))) ((or (null current) (= i index)) current))) (defun dll-insert (dlist node item) " DO: Insert a new node after NODE, or before first position when (NULL NODE). RETURN: The new node. " (let ((new-node nil)) (cond first item (setf new-node (make-dll-node :item item)) (setf (%dll-first dlist) new-node (%dll-last dlist) (%dll-first dlist))) insert before first (setf new-node (make-dll-node :previous nil :next (dll-first-node dlist) :item item)) (setf (dll-node-previous (%dll-first dlist)) new-node (%dll-first dlist) new-node)) ((not (dll-node-position node dlist)) (error "Node not in doubly-linked list.")) (t (setf new-node (make-dll-node :previous node :next (dll-node-next node) :item item)) (if (dll-node-next node) (setf (dll-node-previous (dll-node-next node)) new-node) (setf (%dll-last dlist) new-node)) (setf (dll-node-next node) new-node))) new-node)) (defun dll-extract-node (dlist node) (if (eq (dll-first-node dlist) node) (setf (%dll-first dlist) (dll-node-next node)) (setf (dll-node-next (dll-node-previous node)) (dll-node-next node))) (if (eq (dll-last-node dlist) node) (setf (%dll-last dlist) (dll-node-previous node)) (setf (dll-node-previous (dll-node-next node)) (dll-node-previous node))) dlist) (defun dll-delete (node dlist) " DO: Delete the NODE from the DLL DLIST. RETURN: DLIST " (unless (or (null node) (dll-empty-p dlist) (dll-extract-node dlist node)) dlist) (defun dll-delete-nth (index dlist) " DO: Delete the INDEXth element of the DLL DLIST. RETURN: DLIST " (dll-extract-node dlist (dll-node-nth index dlist)))
89b960d066bbba1c23a48bd29cd02938eadbdfe26950f323196343436998893d
jgertm/lang
typeclasses_test.clj
(ns lang.desugar.typeclasses-test (:require [clojure.test :refer [deftest is testing]] [lang.test-prelude :refer :all] matcher-combinators.test)) (deftest desugar-simple-typeclass (let [[class instance is-it-true? nope] (-> (run :desugar (defmodule lang.desugar.typeclasses-test.simple-definitions (:skip-implicits)) (defclass (Veracious T) (true? :$ (-> T Bool))) (definstance (Veracious Bool) (true? [bool] bool)) (defn is-it-true? [x] (true? x)) (def nope (is-it-true? false))) :definitions) module {:reference :module :name ["lang" "desugar" "typeclasses-test" "simple-definitions"]} Bool {:ast/type :named :name {:reference :type :name "Bool"}}] (is (match? {:ast/definition :type :name {:reference :type :name "D:Veracious"} :params [{:name "T"}] :body {:ast/type :forall :variable {:ast/type :universal-variable :reference {:name "T"}} :body {:ast/type :record :fields {{:reference :field :name "true?" :in module} {:ast/type :function :domain {:ast/type :universal-variable :reference {:reference :type :name "T"}} :return Bool}}}}} class)) (is (match? {:ast/definition :constant :name {:reference :constant :name "I:Veracious:Bool"} :body {:ast/term :record :fields {{:reference :field :name "true?" :in module} {:ast/term :lambda :arguments [{:reference :constant :name "bool"}] :body {:ast/term :symbol :symbol {:reference :constant :name "bool"} :type-checker.term/type {:ast/type :named :name {:name "Bool"}}} :type-checker.term/type {:ast/type :function :domain Bool :return Bool}}}}} instance)) (let [dictionary {:reference :dictionary :name #(->> % (name) (re-find #"Veracious"))} argument {:reference :constant :name "x"}] (is (match? {:ast/definition :constant :name {:name "is-it-true?"} :body {:ast/term :recur :body {:ast/term :lambda :arguments [dictionary argument] :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :symbol :symbol dictionary} :field {:reference :field :name "true?"}} :arguments [{:ast/term :symbol :symbol argument}]}}}} is-it-true?))) (is (match? {:ast/definition :constant :name {:name "nope"} :body {:ast/term :application :function {:ast/term :symbol :symbol {:name "is-it-true?"}} :arguments [{:ast/term :symbol :symbol {:reference :constant :in module :name "I:Veracious:Bool"}} {:ast/term :atom :atom {:atom :boolean :value false}}]}} nope)))) (deftest desugar-chained-typeclasses (let [module (run :desugar (defmodule lang.desugar.typeclasses-test.chained-definitions (:skip-implicits)) (defclass (Show T) (show :$ (-> T String))) (deftype (Identity T) (| [:value T])) (definstance (Show Integer) (show [i] (. i (java.math.BigInteger/toString)))) (definstance (Show (Identity T)) :when (Show T) (show [identity] (match identity [:value val] (show val)))) (def just-a-number (show [:value 42])) (defn wrap-and-show [value] (show [:value value]))) [class type integer-instance identity-instance just-a-number wrap-and-show] (:definitions module)] (is (match? {:ast/definition :constant :body {:ast/term :lambda :arguments [{:reference :dictionary}] :body {:ast/term :record :fields {{:reference :field :name "show" :in {:reference :module :name ["lang" "desugar" "typeclasses-test" "chained-definitions"]}} {:ast/term :lambda :body {:ast/term :match :branches [{:action {:ast/term :application :function {:ast/term :extract :record {:ast/term :symbol :symbol {:reference :dictionary}}} :arguments [{:ast/term :symbol}]}}]}}}}}} identity-instance)) (is (match? {:ast/definition :constant :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :application :function {:ast/term :symbol :symbol {:name "I:Show:(Identity α)"}} :arguments [{:ast/term :symbol :symbol {:name "I:Show:Integer"}}]}}}} just-a-number)) (is (match? {:ast/definition :constant :body {:ast/term :recur :body {:ast/term :lambda :arguments [{:reference :dictionary} {:reference :constant}] :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :application :function {:ast/term :symbol :symbol {:name "I:Show:(Identity α)"}} :arguments [{:ast/term :symbol :symbol {:reference :dictionary}}]}} :arguments [{:ast/term :variant}]}}}} wrap-and-show))))
null
https://raw.githubusercontent.com/jgertm/lang/5a4d73f01d93d7615e44f8ce2dfe8a237dd80766/test/lang/desugar/typeclasses_test.clj
clojure
(ns lang.desugar.typeclasses-test (:require [clojure.test :refer [deftest is testing]] [lang.test-prelude :refer :all] matcher-combinators.test)) (deftest desugar-simple-typeclass (let [[class instance is-it-true? nope] (-> (run :desugar (defmodule lang.desugar.typeclasses-test.simple-definitions (:skip-implicits)) (defclass (Veracious T) (true? :$ (-> T Bool))) (definstance (Veracious Bool) (true? [bool] bool)) (defn is-it-true? [x] (true? x)) (def nope (is-it-true? false))) :definitions) module {:reference :module :name ["lang" "desugar" "typeclasses-test" "simple-definitions"]} Bool {:ast/type :named :name {:reference :type :name "Bool"}}] (is (match? {:ast/definition :type :name {:reference :type :name "D:Veracious"} :params [{:name "T"}] :body {:ast/type :forall :variable {:ast/type :universal-variable :reference {:name "T"}} :body {:ast/type :record :fields {{:reference :field :name "true?" :in module} {:ast/type :function :domain {:ast/type :universal-variable :reference {:reference :type :name "T"}} :return Bool}}}}} class)) (is (match? {:ast/definition :constant :name {:reference :constant :name "I:Veracious:Bool"} :body {:ast/term :record :fields {{:reference :field :name "true?" :in module} {:ast/term :lambda :arguments [{:reference :constant :name "bool"}] :body {:ast/term :symbol :symbol {:reference :constant :name "bool"} :type-checker.term/type {:ast/type :named :name {:name "Bool"}}} :type-checker.term/type {:ast/type :function :domain Bool :return Bool}}}}} instance)) (let [dictionary {:reference :dictionary :name #(->> % (name) (re-find #"Veracious"))} argument {:reference :constant :name "x"}] (is (match? {:ast/definition :constant :name {:name "is-it-true?"} :body {:ast/term :recur :body {:ast/term :lambda :arguments [dictionary argument] :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :symbol :symbol dictionary} :field {:reference :field :name "true?"}} :arguments [{:ast/term :symbol :symbol argument}]}}}} is-it-true?))) (is (match? {:ast/definition :constant :name {:name "nope"} :body {:ast/term :application :function {:ast/term :symbol :symbol {:name "is-it-true?"}} :arguments [{:ast/term :symbol :symbol {:reference :constant :in module :name "I:Veracious:Bool"}} {:ast/term :atom :atom {:atom :boolean :value false}}]}} nope)))) (deftest desugar-chained-typeclasses (let [module (run :desugar (defmodule lang.desugar.typeclasses-test.chained-definitions (:skip-implicits)) (defclass (Show T) (show :$ (-> T String))) (deftype (Identity T) (| [:value T])) (definstance (Show Integer) (show [i] (. i (java.math.BigInteger/toString)))) (definstance (Show (Identity T)) :when (Show T) (show [identity] (match identity [:value val] (show val)))) (def just-a-number (show [:value 42])) (defn wrap-and-show [value] (show [:value value]))) [class type integer-instance identity-instance just-a-number wrap-and-show] (:definitions module)] (is (match? {:ast/definition :constant :body {:ast/term :lambda :arguments [{:reference :dictionary}] :body {:ast/term :record :fields {{:reference :field :name "show" :in {:reference :module :name ["lang" "desugar" "typeclasses-test" "chained-definitions"]}} {:ast/term :lambda :body {:ast/term :match :branches [{:action {:ast/term :application :function {:ast/term :extract :record {:ast/term :symbol :symbol {:reference :dictionary}}} :arguments [{:ast/term :symbol}]}}]}}}}}} identity-instance)) (is (match? {:ast/definition :constant :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :application :function {:ast/term :symbol :symbol {:name "I:Show:(Identity α)"}} :arguments [{:ast/term :symbol :symbol {:name "I:Show:Integer"}}]}}}} just-a-number)) (is (match? {:ast/definition :constant :body {:ast/term :recur :body {:ast/term :lambda :arguments [{:reference :dictionary} {:reference :constant}] :body {:ast/term :application :function {:ast/term :extract :record {:ast/term :application :function {:ast/term :symbol :symbol {:name "I:Show:(Identity α)"}} :arguments [{:ast/term :symbol :symbol {:reference :dictionary}}]}} :arguments [{:ast/term :variant}]}}}} wrap-and-show))))
dbb11b2138e9624129508b4da9ae40c3fb5cdb68ce44d25f0c1deebcff3014a8
hurryabit/pukeko
Dict.hs
# LANGUAGE TemplateHaskell # module Pukeko.AST.Dict ( NoDict (..) , Dict (..) , DxBinder , dict2type ) where import Pukeko.Prelude import Pukeko.Pretty import Data.Aeson.TH import Pukeko.AST.Name import Pukeko.AST.Type data NoDict = NoDict data Dict = DVar DxVar | DDer DxVar [Type] [Dict] | DSub DxVar Class Type Dict type DxBinder ty = (DxVar, (Class, ty)) dict2type :: Traversal' Dict Type dict2type f = \case DVar x -> pure (DVar x) DDer z ts ds -> DDer z <$> traverse f ts <*> (traverse . dict2type) f ds DSub z c t d -> DSub z c <$> f t <*> dict2type f d instance Pretty Dict instance PrettyPrec Dict where prettyPrec _prec _dict = "{Dict}" deriving instance Show Dict deriveToJSON defaultOptions ''Dict
null
https://raw.githubusercontent.com/hurryabit/pukeko/d11a101a41123c5151bcdd7dd2d0ef53c65483c2/src/Pukeko/AST/Dict.hs
haskell
# LANGUAGE TemplateHaskell # module Pukeko.AST.Dict ( NoDict (..) , Dict (..) , DxBinder , dict2type ) where import Pukeko.Prelude import Pukeko.Pretty import Data.Aeson.TH import Pukeko.AST.Name import Pukeko.AST.Type data NoDict = NoDict data Dict = DVar DxVar | DDer DxVar [Type] [Dict] | DSub DxVar Class Type Dict type DxBinder ty = (DxVar, (Class, ty)) dict2type :: Traversal' Dict Type dict2type f = \case DVar x -> pure (DVar x) DDer z ts ds -> DDer z <$> traverse f ts <*> (traverse . dict2type) f ds DSub z c t d -> DSub z c <$> f t <*> dict2type f d instance Pretty Dict instance PrettyPrec Dict where prettyPrec _prec _dict = "{Dict}" deriving instance Show Dict deriveToJSON defaultOptions ''Dict
36df360444113afea643102e3667c8e8a5143fb36aa57a627c377bcdde7bd684
ryukzak/nitta
Types.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE FunctionalDependencies # {-# LANGUAGE GADTs #-} # LANGUAGE QuasiQuotes # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # | Module : NITTA.Model . ProcessorUnits . Types Description : Set of types for process unit description Copyright : ( c ) , 2021 License : : Stability : experimental Module : NITTA.Model.ProcessorUnits.Types Description : Set of types for process unit description Copyright : (c) Aleksandr Penskoi, 2021 License : BSD3 Maintainer : Stability : experimental -} module NITTA.Model.ProcessorUnits.Types ( -- * Processor unit UnitTag (..), ProcessorUnit (..), bind, allowToProcess, NextTick (..), ParallelismType (..), -- * Process description Process (..), ProcessStepID, Step (..), StepInfo (..), Relation (..), isVertical, isHorizontal, descent, whatsHappen, extractInstructionAt, withShift, isRefactorStep, isAllocationStep, -- * Control Controllable (..), SignalTag (..), UnambiguouslyDecode (..), Connected (..), ByTime (..), SignalValue (..), (+++), -- * IO IOConnected (..), InputPortTag (..), OutputPortTag (..), InoutPortTag (..), ) where import Data.Aeson (ToJSON) import Data.Default import Data.Either import Data.Kind import Data.List qualified as L import Data.List.Utils (replace) import Data.Maybe import Data.Set qualified as S import Data.String import Data.String.Interpolate import Data.String.ToString import Data.Text qualified as T import Data.Typeable import GHC.Generics (Generic) import NITTA.Intermediate.Types import NITTA.Model.Problems.Endpoint import NITTA.Model.Time import Numeric.Interval.NonEmpty import Numeric.Interval.NonEmpty qualified as I import Prettyprinter -- | Class for processor unit tag or "name" class (Typeable tag, Ord tag, ToString tag, IsString tag, Semigroup tag) => UnitTag tag where -- | Whether the value can be used as a template or not isTemplate :: tag -> Bool -- | Create tag from the template and index fromTemplate :: tag -> String -> tag instance UnitTag T.Text where isTemplate tag = T.isInfixOf (T.pack "{x}") tag fromTemplate tag index = T.replace (T.pack "{x}") (T.pack index) tag instance UnitTag String where isTemplate tag = "{x}" `L.isInfixOf` tag fromTemplate tag index = replace "{x}" index tag -- | Processor unit parallelism type data ParallelismType = -- | All operations can be performed in parallel mode Full | -- | All operations can be performed in pipeline mode Pipeline | -- | Other processor units None deriving (Show, Generic, Eq) instance ToJSON ParallelismType | Process unit - part of NITTA process with can execute a function from intermediate representation : 1 . get function for execution ( ' tryBind ' ) ; 2 . store computational process description ( ' process ' ) ; 3 . other features implemented by different type classes ( see above and in " NITTA.Model . Problems " ) . intermediate representation: 1. get function for execution ('tryBind'); 2. store computational process description ('process'); 3. other features implemented by different type classes (see above and in "NITTA.Model.Problems"). -} class (VarValTime v x t) => ProcessorUnit u v x t | u -> v x t where If the processor unit can execute a function , then it will return the PU -- model with already bound function (only registeration, actual scheduling -- will be happening later). If not, it will return @Left@ value with a -- specific reason (e.g., not support or all internal resources is over). tryBind :: F v x -> u -> Either String u -- Get a computational process description. If the processor unit embedded another PUs ( like " NITTA.Model . Networks . Bus " ) , the description should -- contain process steps for all PUs. -- -- 'ProcessStepID' may change from one call to another. process :: u -> Process t (StepInfo v x t) | Indicates what type of parallelism is supported by ' ProcessorUnit ' parallelismType :: u -> ParallelismType parallelismType _ = None | Provide the processor unit size . At the moment it 's just the number of puSize :: u -> Float puSize _ = 1 bind f pu = case tryBind f pu of Right pu' -> pu' Left err -> error $ "can't bind function: " <> err allowToProcess f pu = isRight $ tryBind f pu class NextTick u t | u -> t where nextTick :: u -> t instance (ProcessorUnit u v x t) => NextTick u t where nextTick = nextTick . process --------------------------------------------------------------------- | Computational process description . It was designed in ISO 15926 style , with separated data and relations storage . separated data and relations storage. -} data Process t i = Process { steps :: [Step t i] -- ^ All process steps desctiption. , relations :: [Relation] -- ^ List of relationships between process steps (see 'Relation'). , nextTick_ :: t -- ^ Next tick for instruction. Note: instruction /= endpoint. , nextUid :: ProcessStepID -- ^ Next process step ID } deriving (Generic) instance (Time t, Show i) => Pretty (Process t i) where pretty p = [__i| Process: steps: #{ showList' $ reverse $ steps p } relations: #{ showList' $ relations p } nextTick: #{ nextTick p } nextUid: #{ nextUid p } |] where showList' [] = pretty "" showList' xs = line <> indent 8 (vsep lst) where lst = map (pretty . (\(ix, value) -> [i|#{ ix }) #{ value }|] :: T.Text)) $ zip [0 :: Int ..] xs instance (ToJSON t, ToJSON i) => ToJSON (Process t i) instance (Default t) => Default (Process t i) where def = Process{steps = [], relations = [], nextTick_ = def, nextUid = def} instance {-# OVERLAPS #-} NextTick (Process t si) t where nextTick = nextTick_ instance (Ord t) => WithFunctions (Process t (StepInfo v x t)) (F v x) where functions Process{steps} = mapMaybe get $ L.sortOn (I.inf . pInterval) steps where get Step{pDesc} | IntermediateStep f <- descent pDesc = Just f get _ = Nothing | Unique ID of a process step . Uniquity presented only inside PU . type ProcessStepID = Int -- | Process step representation data Step t i = Step { pID :: ProcessStepID -- ^ uniq (inside single the process unit) step ID , pInterval :: Interval t -- ^ step time , pDesc :: i -- ^ step description } deriving (Show, Generic) instance (ToJSON t, ToJSON i) => ToJSON (Step t i) instance (Ord v) => Patch (Step t (StepInfo v x t)) (Changeset v) where patch diff step@Step{pDesc} = step{pDesc = patch diff pDesc} -- | Informative process step description at a specific process level. data StepInfo v x t where -- | CAD level step CADStep :: String -> StepInfo v x t -- | Apply refactoring RefactorStep :: (Typeable ref, Show ref, Eq ref) => ref -> StepInfo v x t -- | intermidiate level step (function execution) IntermediateStep :: F v x -> StepInfo v x t -- | endpoint level step (source or target) EndpointRoleStep :: EndpointRole v -> StepInfo v x t -- | process unit instruction (depends on process unit type) InstructionStep :: (Show (Instruction pu), Typeable (Instruction pu)) => Instruction pu -> StepInfo v x t -- | wrapper for nested process unit step (used for networks) NestedStep :: (UnitTag tag) => {nTitle :: tag, nStep :: Step t (StepInfo v x t)} -> StepInfo v x t -- | Process unit allocation step AllocationStep :: (Typeable a, Show a, Eq a) => a -> StepInfo v x t descent (NestedStep _ step) = descent $ pDesc step descent desc = desc isRefactorStep RefactorStep{} = True isRefactorStep _ = False isAllocationStep AllocationStep{} = True isAllocationStep _ = False instance (Var v, Show (Step t (StepInfo v x t))) => Show (StepInfo v x t) where show (CADStep msg) = "CAD: " <> msg show (AllocationStep alloc) = "Allocation: " <> show alloc show (RefactorStep ref) = "Refactor: " <> show ref show (IntermediateStep F{fun}) = "Intermediate: " <> show fun show (EndpointRoleStep eff) = "Endpoint: " <> show eff show (InstructionStep instr) = "Instruction: " <> show instr show NestedStep{nTitle, nStep = Step{pDesc}} = "@" <> toString nTitle <> " " <> show pDesc instance (Ord v) => Patch (StepInfo v x t) (Changeset v) where patch diff (IntermediateStep f) = IntermediateStep $ patch diff f patch diff (EndpointRoleStep ep) = EndpointRoleStep $ patch diff ep patch diff (NestedStep tag nStep) = NestedStep tag $ patch diff nStep patch _ instr = instr -- | Relations between process steps. data Relation = -- | Vertical relationships (up and down). For example, the intermediate -- step (function execution) can be translated to a sequence of endpoint -- steps (receiving and sending variable), and process unit instructions. Vertical {vUp, vDown :: ProcessStepID} | Horizontal relationships ( on one level ) . For example , we bind the -- function and apply the refactoring. The binding step should be -- connected to refactoring steps, including new binding steps. Horizontal {hPrev, hNext :: ProcessStepID} deriving (Show, Generic, Ord, Eq) isVertical Vertical{} = True isVertical _ = False isHorizontal Horizontal{} = True isHorizontal _ = False instance ToJSON Relation whatsHappen t Process{steps} = filter (atSameTime t . pInterval) steps where atSameTime a ti = a `member` ti extractInstructionAt pu t = mapMaybe (inst pu) $ whatsHappen t $ process pu where inst :: (Typeable (Instruction pu)) => pu -> Step t (StepInfo v x t) -> Maybe (Instruction pu) inst _ Step{pDesc = InstructionStep instr} = cast instr inst _ _ = Nothing | Shift @nextTick@ value if it is not zero on a specific offset . Use case : The processor unit has buffered output , so we should provide @oe@ signal for one tick before data actually send to the bus . That raises the following cases : 1 . First usage . We can receive value immediately on nextTick @ tick | Endpoint | Instruction | 0 | Target " c " | WR | < - nextTick @ 2 . Not first usage . We need to wait for one tick from the last instruction due to the offset between instruction and data transfers . @ tick | Endpoint | Instruction | 8 | | OE | 9 | Source [ " b " ] | | < - nextTick 10 | Target " c " | WR | @ processor unit has buffered output, so we should provide @oe@ signal for one tick before data actually send to the bus. That raises the following cases: 1. First usage. We can receive value immediately on nextTick @ tick | Endpoint | Instruction | 0 | Target "c" | WR | <- nextTick @ 2. Not first usage. We need to wait for one tick from the last instruction due to the offset between instruction and data transfers. @ tick | Endpoint | Instruction | 8 | | OE | 9 | Source ["b"] | | <- nextTick 10 | Target "c" | WR | @ -} 0 `withShift` _offset = 0 tick `withShift` offset = tick + offset --------------------------------------------------------------------- | Type class for controllable units . Defines two level of a unit behaviour representation ( see ahead ) . representation (see ahead). -} class Controllable pu where Instruction describe unit behaviour on each mUnit cycle . If instruction not defined for some cycles - it should be interpreted as NOP . data Instruction pu :: Type | controll signals on each mUnit cycle ( without exclusion ) . data Microcode pu :: Type -- | Zip port signal tags and value. zipSignalTagsAndValues :: Ports pu -> Microcode pu -> [(SignalTag, SignalValue)] -- | Get list of used control signal tags. usedPortTags :: Ports pu -> [SignalTag] -- | Take signal tags from inifinite list of tags. takePortTags :: [SignalTag] -> pu -> Ports pu -- | Getting microcode value at a specific time. class ByTime pu t | pu -> t where microcodeAt :: pu -> t -> Microcode pu instance ( Show (Instruction pu) , Default (Microcode pu) , ProcessorUnit pu v x t , UnambiguouslyDecode pu , Time t , Typeable pu ) => ByTime pu t where microcodeAt pu t = case extractInstructionAt pu t of [] -> def [instr] -> decodeInstruction instr is -> error [i|instruction collision at #{ t } tick: #{ is } #{ pretty $ process pu }|] newtype SignalTag = SignalTag {signalTag :: T.Text} deriving (Eq, Ord) instance Show SignalTag where show = toString . signalTag -- | Type class of processor units with control ports. class Connected pu where -- | A processor unit control ports (signals, flags). data Ports pu :: Type | Decoding microcode from a simple instruction ( microcode do n't change over time ) . TODO : that class for all process units , including networks . time). TODO: Generalize that class for all process units, including networks. -} class UnambiguouslyDecode pu where decodeInstruction :: Instruction pu -> Microcode pu -- | Control line value. data SignalValue = -- | undefined by design (`x`) Undef | -- | boolean (`0` or `1`) Bool Bool | -- | broken value (`x`) by data colision BrokenSignal deriving (Eq) instance Default SignalValue where def = Undef instance Show SignalValue where show Undef = "x" show (Bool True) = "1" show (Bool False) = "0" show BrokenSignal = "B" Undef +++ v = v v +++ Undef = v _ +++ _ = BrokenSignal ------------------------------------------------------------ | Type class of processor units with IO ports . class IOConnected pu where data IOPorts pu :: Type | External input ports , which go outside of NITTA mUnit . inputPorts :: IOPorts pu -> S.Set InputPortTag inputPorts _ = S.empty | External output ports , which go outside of NITTA mUnit . outputPorts :: IOPorts pu -> S.Set OutputPortTag outputPorts _ = S.empty | External output ports , which go outside of NITTA mUnit . inoutPorts :: IOPorts pu -> S.Set InoutPortTag inoutPorts _ = S.empty newtype InputPortTag = InputPortTag {inputPortTag :: T.Text} deriving (Eq, Ord) instance Show InputPortTag where show = toString . inputPortTag newtype OutputPortTag = OutputPortTag {outputPortTag :: T.Text} deriving (Eq, Ord) instance Show OutputPortTag where show = toString . outputPortTag newtype InoutPortTag = InoutPortTag {inoutPortTag :: T.Text} deriving (Eq, Ord) instance Show InoutPortTag where show = toString . inoutPortTag
null
https://raw.githubusercontent.com/ryukzak/nitta/1e1e571fd73b2cb9bea4e5781bf658e7edd264c0/src/NITTA/Model/ProcessorUnits/Types.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # * Processor unit * Process description * Control * IO | Class for processor unit tag or "name" | Whether the value can be used as a template or not | Create tag from the template and index | Processor unit parallelism type | All operations can be performed in parallel mode | All operations can be performed in pipeline mode | Other processor units model with already bound function (only registeration, actual scheduling will be happening later). If not, it will return @Left@ value with a specific reason (e.g., not support or all internal resources is over). Get a computational process description. If the processor unit embedded contain process steps for all PUs. 'ProcessStepID' may change from one call to another. ------------------------------------------------------------------- ^ All process steps desctiption. ^ List of relationships between process steps (see 'Relation'). ^ Next tick for instruction. Note: instruction /= endpoint. ^ Next process step ID # OVERLAPS # | Process step representation ^ uniq (inside single the process unit) step ID ^ step time ^ step description | Informative process step description at a specific process level. | CAD level step | Apply refactoring | intermidiate level step (function execution) | endpoint level step (source or target) | process unit instruction (depends on process unit type) | wrapper for nested process unit step (used for networks) | Process unit allocation step | Relations between process steps. | Vertical relationships (up and down). For example, the intermediate step (function execution) can be translated to a sequence of endpoint steps (receiving and sending variable), and process unit instructions. function and apply the refactoring. The binding step should be connected to refactoring steps, including new binding steps. ------------------------------------------------------------------- | Zip port signal tags and value. | Get list of used control signal tags. | Take signal tags from inifinite list of tags. | Getting microcode value at a specific time. | Type class of processor units with control ports. | A processor unit control ports (signals, flags). | Control line value. | undefined by design (`x`) | boolean (`0` or `1`) | broken value (`x`) by data colision ----------------------------------------------------------
# LANGUAGE FunctionalDependencies # # LANGUAGE QuasiQuotes # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # | Module : NITTA.Model . ProcessorUnits . Types Description : Set of types for process unit description Copyright : ( c ) , 2021 License : : Stability : experimental Module : NITTA.Model.ProcessorUnits.Types Description : Set of types for process unit description Copyright : (c) Aleksandr Penskoi, 2021 License : BSD3 Maintainer : Stability : experimental -} module NITTA.Model.ProcessorUnits.Types ( UnitTag (..), ProcessorUnit (..), bind, allowToProcess, NextTick (..), ParallelismType (..), Process (..), ProcessStepID, Step (..), StepInfo (..), Relation (..), isVertical, isHorizontal, descent, whatsHappen, extractInstructionAt, withShift, isRefactorStep, isAllocationStep, Controllable (..), SignalTag (..), UnambiguouslyDecode (..), Connected (..), ByTime (..), SignalValue (..), (+++), IOConnected (..), InputPortTag (..), OutputPortTag (..), InoutPortTag (..), ) where import Data.Aeson (ToJSON) import Data.Default import Data.Either import Data.Kind import Data.List qualified as L import Data.List.Utils (replace) import Data.Maybe import Data.Set qualified as S import Data.String import Data.String.Interpolate import Data.String.ToString import Data.Text qualified as T import Data.Typeable import GHC.Generics (Generic) import NITTA.Intermediate.Types import NITTA.Model.Problems.Endpoint import NITTA.Model.Time import Numeric.Interval.NonEmpty import Numeric.Interval.NonEmpty qualified as I import Prettyprinter class (Typeable tag, Ord tag, ToString tag, IsString tag, Semigroup tag) => UnitTag tag where isTemplate :: tag -> Bool fromTemplate :: tag -> String -> tag instance UnitTag T.Text where isTemplate tag = T.isInfixOf (T.pack "{x}") tag fromTemplate tag index = T.replace (T.pack "{x}") (T.pack index) tag instance UnitTag String where isTemplate tag = "{x}" `L.isInfixOf` tag fromTemplate tag index = replace "{x}" index tag data ParallelismType Full Pipeline None deriving (Show, Generic, Eq) instance ToJSON ParallelismType | Process unit - part of NITTA process with can execute a function from intermediate representation : 1 . get function for execution ( ' tryBind ' ) ; 2 . store computational process description ( ' process ' ) ; 3 . other features implemented by different type classes ( see above and in " NITTA.Model . Problems " ) . intermediate representation: 1. get function for execution ('tryBind'); 2. store computational process description ('process'); 3. other features implemented by different type classes (see above and in "NITTA.Model.Problems"). -} class (VarValTime v x t) => ProcessorUnit u v x t | u -> v x t where If the processor unit can execute a function , then it will return the PU tryBind :: F v x -> u -> Either String u another PUs ( like " NITTA.Model . Networks . Bus " ) , the description should process :: u -> Process t (StepInfo v x t) | Indicates what type of parallelism is supported by ' ProcessorUnit ' parallelismType :: u -> ParallelismType parallelismType _ = None | Provide the processor unit size . At the moment it 's just the number of puSize :: u -> Float puSize _ = 1 bind f pu = case tryBind f pu of Right pu' -> pu' Left err -> error $ "can't bind function: " <> err allowToProcess f pu = isRight $ tryBind f pu class NextTick u t | u -> t where nextTick :: u -> t instance (ProcessorUnit u v x t) => NextTick u t where nextTick = nextTick . process | Computational process description . It was designed in ISO 15926 style , with separated data and relations storage . separated data and relations storage. -} data Process t i = Process { steps :: [Step t i] , relations :: [Relation] , nextTick_ :: t , nextUid :: ProcessStepID } deriving (Generic) instance (Time t, Show i) => Pretty (Process t i) where pretty p = [__i| Process: steps: #{ showList' $ reverse $ steps p } relations: #{ showList' $ relations p } nextTick: #{ nextTick p } nextUid: #{ nextUid p } |] where showList' [] = pretty "" showList' xs = line <> indent 8 (vsep lst) where lst = map (pretty . (\(ix, value) -> [i|#{ ix }) #{ value }|] :: T.Text)) $ zip [0 :: Int ..] xs instance (ToJSON t, ToJSON i) => ToJSON (Process t i) instance (Default t) => Default (Process t i) where def = Process{steps = [], relations = [], nextTick_ = def, nextUid = def} nextTick = nextTick_ instance (Ord t) => WithFunctions (Process t (StepInfo v x t)) (F v x) where functions Process{steps} = mapMaybe get $ L.sortOn (I.inf . pInterval) steps where get Step{pDesc} | IntermediateStep f <- descent pDesc = Just f get _ = Nothing | Unique ID of a process step . Uniquity presented only inside PU . type ProcessStepID = Int data Step t i = Step { pID :: ProcessStepID , pInterval :: Interval t , pDesc :: i } deriving (Show, Generic) instance (ToJSON t, ToJSON i) => ToJSON (Step t i) instance (Ord v) => Patch (Step t (StepInfo v x t)) (Changeset v) where patch diff step@Step{pDesc} = step{pDesc = patch diff pDesc} data StepInfo v x t where CADStep :: String -> StepInfo v x t RefactorStep :: (Typeable ref, Show ref, Eq ref) => ref -> StepInfo v x t IntermediateStep :: F v x -> StepInfo v x t EndpointRoleStep :: EndpointRole v -> StepInfo v x t InstructionStep :: (Show (Instruction pu), Typeable (Instruction pu)) => Instruction pu -> StepInfo v x t NestedStep :: (UnitTag tag) => {nTitle :: tag, nStep :: Step t (StepInfo v x t)} -> StepInfo v x t AllocationStep :: (Typeable a, Show a, Eq a) => a -> StepInfo v x t descent (NestedStep _ step) = descent $ pDesc step descent desc = desc isRefactorStep RefactorStep{} = True isRefactorStep _ = False isAllocationStep AllocationStep{} = True isAllocationStep _ = False instance (Var v, Show (Step t (StepInfo v x t))) => Show (StepInfo v x t) where show (CADStep msg) = "CAD: " <> msg show (AllocationStep alloc) = "Allocation: " <> show alloc show (RefactorStep ref) = "Refactor: " <> show ref show (IntermediateStep F{fun}) = "Intermediate: " <> show fun show (EndpointRoleStep eff) = "Endpoint: " <> show eff show (InstructionStep instr) = "Instruction: " <> show instr show NestedStep{nTitle, nStep = Step{pDesc}} = "@" <> toString nTitle <> " " <> show pDesc instance (Ord v) => Patch (StepInfo v x t) (Changeset v) where patch diff (IntermediateStep f) = IntermediateStep $ patch diff f patch diff (EndpointRoleStep ep) = EndpointRoleStep $ patch diff ep patch diff (NestedStep tag nStep) = NestedStep tag $ patch diff nStep patch _ instr = instr data Relation Vertical {vUp, vDown :: ProcessStepID} | Horizontal relationships ( on one level ) . For example , we bind the Horizontal {hPrev, hNext :: ProcessStepID} deriving (Show, Generic, Ord, Eq) isVertical Vertical{} = True isVertical _ = False isHorizontal Horizontal{} = True isHorizontal _ = False instance ToJSON Relation whatsHappen t Process{steps} = filter (atSameTime t . pInterval) steps where atSameTime a ti = a `member` ti extractInstructionAt pu t = mapMaybe (inst pu) $ whatsHappen t $ process pu where inst :: (Typeable (Instruction pu)) => pu -> Step t (StepInfo v x t) -> Maybe (Instruction pu) inst _ Step{pDesc = InstructionStep instr} = cast instr inst _ _ = Nothing | Shift @nextTick@ value if it is not zero on a specific offset . Use case : The processor unit has buffered output , so we should provide @oe@ signal for one tick before data actually send to the bus . That raises the following cases : 1 . First usage . We can receive value immediately on nextTick @ tick | Endpoint | Instruction | 0 | Target " c " | WR | < - nextTick @ 2 . Not first usage . We need to wait for one tick from the last instruction due to the offset between instruction and data transfers . @ tick | Endpoint | Instruction | 8 | | OE | 9 | Source [ " b " ] | | < - nextTick 10 | Target " c " | WR | @ processor unit has buffered output, so we should provide @oe@ signal for one tick before data actually send to the bus. That raises the following cases: 1. First usage. We can receive value immediately on nextTick @ tick | Endpoint | Instruction | 0 | Target "c" | WR | <- nextTick @ 2. Not first usage. We need to wait for one tick from the last instruction due to the offset between instruction and data transfers. @ tick | Endpoint | Instruction | 8 | | OE | 9 | Source ["b"] | | <- nextTick 10 | Target "c" | WR | @ -} 0 `withShift` _offset = 0 tick `withShift` offset = tick + offset | Type class for controllable units . Defines two level of a unit behaviour representation ( see ahead ) . representation (see ahead). -} class Controllable pu where Instruction describe unit behaviour on each mUnit cycle . If instruction not defined for some cycles - it should be interpreted as NOP . data Instruction pu :: Type | controll signals on each mUnit cycle ( without exclusion ) . data Microcode pu :: Type zipSignalTagsAndValues :: Ports pu -> Microcode pu -> [(SignalTag, SignalValue)] usedPortTags :: Ports pu -> [SignalTag] takePortTags :: [SignalTag] -> pu -> Ports pu class ByTime pu t | pu -> t where microcodeAt :: pu -> t -> Microcode pu instance ( Show (Instruction pu) , Default (Microcode pu) , ProcessorUnit pu v x t , UnambiguouslyDecode pu , Time t , Typeable pu ) => ByTime pu t where microcodeAt pu t = case extractInstructionAt pu t of [] -> def [instr] -> decodeInstruction instr is -> error [i|instruction collision at #{ t } tick: #{ is } #{ pretty $ process pu }|] newtype SignalTag = SignalTag {signalTag :: T.Text} deriving (Eq, Ord) instance Show SignalTag where show = toString . signalTag class Connected pu where data Ports pu :: Type | Decoding microcode from a simple instruction ( microcode do n't change over time ) . TODO : that class for all process units , including networks . time). TODO: Generalize that class for all process units, including networks. -} class UnambiguouslyDecode pu where decodeInstruction :: Instruction pu -> Microcode pu data SignalValue Undef Bool Bool BrokenSignal deriving (Eq) instance Default SignalValue where def = Undef instance Show SignalValue where show Undef = "x" show (Bool True) = "1" show (Bool False) = "0" show BrokenSignal = "B" Undef +++ v = v v +++ Undef = v _ +++ _ = BrokenSignal | Type class of processor units with IO ports . class IOConnected pu where data IOPorts pu :: Type | External input ports , which go outside of NITTA mUnit . inputPorts :: IOPorts pu -> S.Set InputPortTag inputPorts _ = S.empty | External output ports , which go outside of NITTA mUnit . outputPorts :: IOPorts pu -> S.Set OutputPortTag outputPorts _ = S.empty | External output ports , which go outside of NITTA mUnit . inoutPorts :: IOPorts pu -> S.Set InoutPortTag inoutPorts _ = S.empty newtype InputPortTag = InputPortTag {inputPortTag :: T.Text} deriving (Eq, Ord) instance Show InputPortTag where show = toString . inputPortTag newtype OutputPortTag = OutputPortTag {outputPortTag :: T.Text} deriving (Eq, Ord) instance Show OutputPortTag where show = toString . outputPortTag newtype InoutPortTag = InoutPortTag {inoutPortTag :: T.Text} deriving (Eq, Ord) instance Show InoutPortTag where show = toString . inoutPortTag
966bf37e9161863274729b84a526172632e812e12fd7e8b19d59047d959f3f6a
thma/PolysemyCleanArchitecture
AppServer.hs
# LANGUAGE TemplateHaskell # module ExternalInterfaces.AppServer where import InterfaceAdapters.Config import Network.Wai (Application) import Polysemy (makeSem) This module defines an AppServer effect that allows to host a WAI Application . This module defines an AppServer effect that allows to host a WAI Application. -} data AppServer m a where ^ serve a WAI Application ServeApp :: Application -> AppServer m () -- ^ create a WAI Application from Config and then serve it ServeAppFromConfig :: Config -> AppServer m () makeSem ''AppServer
null
https://raw.githubusercontent.com/thma/PolysemyCleanArchitecture/3bb375a30bcbf35c9df62802902e0faa03e3f03d/src/ExternalInterfaces/AppServer.hs
haskell
^ create a WAI Application from Config and then serve it
# LANGUAGE TemplateHaskell # module ExternalInterfaces.AppServer where import InterfaceAdapters.Config import Network.Wai (Application) import Polysemy (makeSem) This module defines an AppServer effect that allows to host a WAI Application . This module defines an AppServer effect that allows to host a WAI Application. -} data AppServer m a where ^ serve a WAI Application ServeApp :: Application -> AppServer m () ServeAppFromConfig :: Config -> AppServer m () makeSem ''AppServer
e37948a9fb6faa95f9ab538cff04603e9bb7465a089cf3c872e6ff27da354a18
input-output-hk/project-icarus-importer
Types.hs
-- | Module containing blockchainImporter-specific datatypes module Pos.BlockchainImporter.Core.Types ( TxExtra (..) ) where import Universum import Pos.Core (Timestamp) import Pos.Core.Txp (TxUndo) data TxExtra = TxExtra { teTimestamp :: !(Maybe Timestamp) non - strict on purpose , see comment in ` processTxDo ` in Pos . . Txp . Local , teInputOutputs :: TxUndo } deriving (Show, Generic, Eq)
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/blockchain-importer/src/Pos/BlockchainImporter/Core/Types.hs
haskell
| Module containing blockchainImporter-specific datatypes
module Pos.BlockchainImporter.Core.Types ( TxExtra (..) ) where import Universum import Pos.Core (Timestamp) import Pos.Core.Txp (TxUndo) data TxExtra = TxExtra { teTimestamp :: !(Maybe Timestamp) non - strict on purpose , see comment in ` processTxDo ` in Pos . . Txp . Local , teInputOutputs :: TxUndo } deriving (Show, Generic, Eq)
6ce5df9693ffaf1bf19f00702f462045555b6e4a50ee878db5a726c30712d17a
objectionary/try-phi
Main.hs
# LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Main(main) where import Test(test, test') main :: IO () main = do test' test "./test/data/snippet.eo" print "ok"
null
https://raw.githubusercontent.com/objectionary/try-phi/9eb9879c46decc4eb1e6f34beaa6a2736224b649/back/language-utils/app/Main.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE CPP # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Main(main) where import Test(test, test') main :: IO () main = do test' test "./test/data/snippet.eo" print "ok"
7fa42b7378661bf23ccf4c148702a0c7cfe9239047be773b9fd09b302562fea3
replikativ/replikativ
meta.cljc
(ns replikativ.crdt.cdvcs.meta "Operation on metadata and commit-graph (directed acyclic graph) of a CDVCS. Metadata CDVCS-format for automatic server-side synching (p2p-web). Have a look at the documentation for more information." (:require [clojure.set :as set] [replikativ.environ :refer [*date-fn*]])) ;; adapted from clojure.set, but is faster if the intersection is small ;; where intersection in clojure.set is faster when the intersection is large (defn intersection [s1 s2] (if (< (count s2) (count s1)) (recur s2 s1) (reduce (fn [result item] (if (contains? s2 item) (conj result item) result)) #{} s1))) (defn consistent-graph? [graph] (let [parents (->> graph vals (map set) (apply set/union)) commits (->> graph keys set)] (set/superset? commits parents))) (defn lowest-common-ancestors "Online BFS implementation with O(n) complexity. Assumes no cycles exist." ([graph-a heads-a graph-b heads-b] (cond ;; already done (= (set heads-a) (set heads-b)) {:lcas (set heads-a) :visited-a (set heads-a) :visited-b (set heads-b)} :else (lowest-common-ancestors graph-a heads-a heads-a heads-a graph-b heads-b heads-b heads-b))) ([graph-a heads-a visited-a start-heads-a graph-b heads-b visited-b start-heads-b] (let [new-heads-a (set (mapcat graph-a heads-a)) new-heads-b (set (mapcat graph-b heads-b)) visited-a (set/union visited-a new-heads-a) visited-b (set/union visited-b new-heads-b)] ;; short circuit intersection ;; as long as we don't match any new heads-b in visited-a TODO it is possible to use this as recursion condition only ;; count new-heads = count intersection new-heads-b visited-a (if (and (not-empty new-heads-b) (empty? (intersection visited-a new-heads-b))) (recur graph-a new-heads-a visited-a start-heads-a graph-b new-heads-b visited-b start-heads-b) ;; this intersection is expensive (let [lcas (intersection visited-a visited-b)] (if (and (not (empty? lcas)) ;; keep going until all paths of b are in graph-a to ;; complete visited-b. (= (count (select-keys graph-a new-heads-b)) (count new-heads-b))) {:lcas lcas :visited-a visited-a :visited-b visited-b} (do (when (and (empty? new-heads-a) (empty? new-heads-b)) (throw (ex-info "Graph is not connected, LCA failed." {;:graph-a graph-a ;:graph-b graph-b :dangling-heads-a heads-a :dangling-heads-b heads-b :start-heads-a start-heads-a :start-heads-b start-heads-b :visited-a visited-a :visited-b visited-b}))) (recur graph-a new-heads-a visited-a start-heads-a graph-b new-heads-b visited-b start-heads-b)))))))) (defn- pairwise-lcas [new-graph graph-a heads-a heads-b] (cond ;; if heads-b is already in graph-a, then they are the lcas (= (count heads-b) (count (select-keys graph-a (seq heads-b)))) (set/difference heads-b heads-a) :else (apply set/union (for [a heads-a b heads-b :when (not= a b)] (let [{:keys [lcas]} (lowest-common-ancestors new-graph #{a} new-graph #{b})] lcas))))) (defn remove-ancestors [new-graph graph-a heads-a heads-b] (let [to-remove (pairwise-lcas new-graph graph-a heads-a heads-b)] (set/difference (set/union heads-a heads-b) to-remove))) (defn downstream "Applies downstream updates from op to state. Idempotent and commutative." [{bs :heads cg :commit-graph :as cdvcs} {obs :heads ocg :commit-graph :as op}] (try (let [;; faster, but safer was not to overwrite parts of the graph new-graph (if (> (count cg) (count ocg)) (merge cg ocg) (merge ocg cg)) new-heads (remove-ancestors new-graph cg bs obs)] TODO disable debug checks in releases automatically #_(when-not (consistent-graph? new-graph) (throw (ex-info "Inconsistent graph created." {:cdvcs cdvcs :op op}))) (assoc cdvcs :heads new-heads :commit-graph new-graph)) (catch #?(:clj Exception :cljs js/Error) e (throw (ex-info "Cannot apply downstream operation." {:error e :op op}))))) (comment ;; lca benchmarking... (def giant-graph (->> (interleave (range 1 (inc 1e6)) (range 0 1e6)) (partition 2) (mapv (fn [[k v]] [k (if (= v 0) [] [v])])) (into {}))) (time (do (lowest-common-ancestors giant-graph #{100} giant-graph #{1}) nil)) (time (let [{:keys [lcas visited-a visited-b] :as lca} (lowest-common-ancestors giant-graph #{1000000} {1 [] 2 [1]} #{2})] [lcas (count visited-a) (count visited-b)] #_(select-keys giant-graph visited-b))) )
null
https://raw.githubusercontent.com/replikativ/replikativ/1533a7e43e46bfb70e8c8eb34dc5708e611a478d/src/replikativ/crdt/cdvcs/meta.cljc
clojure
adapted from clojure.set, but is faster if the intersection is small where intersection in clojure.set is faster when the intersection is large already done short circuit intersection as long as we don't match any new heads-b in visited-a count new-heads = count intersection new-heads-b visited-a this intersection is expensive keep going until all paths of b are in graph-a to complete visited-b. :graph-a graph-a :graph-b graph-b if heads-b is already in graph-a, then they are the lcas faster, but safer was not to overwrite parts of the graph lca benchmarking...
(ns replikativ.crdt.cdvcs.meta "Operation on metadata and commit-graph (directed acyclic graph) of a CDVCS. Metadata CDVCS-format for automatic server-side synching (p2p-web). Have a look at the documentation for more information." (:require [clojure.set :as set] [replikativ.environ :refer [*date-fn*]])) (defn intersection [s1 s2] (if (< (count s2) (count s1)) (recur s2 s1) (reduce (fn [result item] (if (contains? s2 item) (conj result item) result)) #{} s1))) (defn consistent-graph? [graph] (let [parents (->> graph vals (map set) (apply set/union)) commits (->> graph keys set)] (set/superset? commits parents))) (defn lowest-common-ancestors "Online BFS implementation with O(n) complexity. Assumes no cycles exist." ([graph-a heads-a graph-b heads-b] (cond (= (set heads-a) (set heads-b)) {:lcas (set heads-a) :visited-a (set heads-a) :visited-b (set heads-b)} :else (lowest-common-ancestors graph-a heads-a heads-a heads-a graph-b heads-b heads-b heads-b))) ([graph-a heads-a visited-a start-heads-a graph-b heads-b visited-b start-heads-b] (let [new-heads-a (set (mapcat graph-a heads-a)) new-heads-b (set (mapcat graph-b heads-b)) visited-a (set/union visited-a new-heads-a) visited-b (set/union visited-b new-heads-b)] TODO it is possible to use this as recursion condition only (if (and (not-empty new-heads-b) (empty? (intersection visited-a new-heads-b))) (recur graph-a new-heads-a visited-a start-heads-a graph-b new-heads-b visited-b start-heads-b) (let [lcas (intersection visited-a visited-b)] (if (and (not (empty? lcas)) (= (count (select-keys graph-a new-heads-b)) (count new-heads-b))) {:lcas lcas :visited-a visited-a :visited-b visited-b} (do (when (and (empty? new-heads-a) (empty? new-heads-b)) (throw (ex-info "Graph is not connected, LCA failed." :dangling-heads-a heads-a :dangling-heads-b heads-b :start-heads-a start-heads-a :start-heads-b start-heads-b :visited-a visited-a :visited-b visited-b}))) (recur graph-a new-heads-a visited-a start-heads-a graph-b new-heads-b visited-b start-heads-b)))))))) (defn- pairwise-lcas [new-graph graph-a heads-a heads-b] (cond (= (count heads-b) (count (select-keys graph-a (seq heads-b)))) (set/difference heads-b heads-a) :else (apply set/union (for [a heads-a b heads-b :when (not= a b)] (let [{:keys [lcas]} (lowest-common-ancestors new-graph #{a} new-graph #{b})] lcas))))) (defn remove-ancestors [new-graph graph-a heads-a heads-b] (let [to-remove (pairwise-lcas new-graph graph-a heads-a heads-b)] (set/difference (set/union heads-a heads-b) to-remove))) (defn downstream "Applies downstream updates from op to state. Idempotent and commutative." [{bs :heads cg :commit-graph :as cdvcs} {obs :heads ocg :commit-graph :as op}] (try new-graph (if (> (count cg) (count ocg)) (merge cg ocg) (merge ocg cg)) new-heads (remove-ancestors new-graph cg bs obs)] TODO disable debug checks in releases automatically #_(when-not (consistent-graph? new-graph) (throw (ex-info "Inconsistent graph created." {:cdvcs cdvcs :op op}))) (assoc cdvcs :heads new-heads :commit-graph new-graph)) (catch #?(:clj Exception :cljs js/Error) e (throw (ex-info "Cannot apply downstream operation." {:error e :op op}))))) (comment (def giant-graph (->> (interleave (range 1 (inc 1e6)) (range 0 1e6)) (partition 2) (mapv (fn [[k v]] [k (if (= v 0) [] [v])])) (into {}))) (time (do (lowest-common-ancestors giant-graph #{100} giant-graph #{1}) nil)) (time (let [{:keys [lcas visited-a visited-b] :as lca} (lowest-common-ancestors giant-graph #{1000000} {1 [] 2 [1]} #{2})] [lcas (count visited-a) (count visited-b)] #_(select-keys giant-graph visited-b))) )
704085e57ef1ef8e2536617822a76701816a5cd11454245363d2bd99e40e81cf
skanev/playground
38.scm
EOPL exercise 3.38 ; ; Extend the lexical address translator and interpreter to handle cond from exercise 3.12 . (load-relative "cases/nameless/env.scm") ; The parser (define-datatype expression expression? (const-exp (num number?)) (diff-exp (minuend expression?) (subtrahend expression?)) (zero?-exp (expr expression?)) (if-exp (predicate expression?) (consequent expression?) (alternative expression?)) (var-exp (var symbol?)) (let-exp (var symbol?) (value expression?) (body expression?)) (proc-exp (var symbol?) (body expression?)) (call-exp (rator expression?) (rand expression?)) (nameless-var-exp (num integer?)) (nameless-let-exp (exp1 expression?) (body expression?)) (nameless-proc-exp (body expression?)) (cond-exp (conditions (list-of expression?)) (actions (list-of expression?)))) (define scanner-spec '((white-sp (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit))) symbol) (number (digit (arbno digit)) number))) (define grammar '((expression (number) const-exp) (expression ("cond" (arbno expression "==>" expression) "end") cond-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression (identifier) var-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("(" expression expression ")") call-exp))) (define scan&parse (sllgen:make-string-parser scanner-spec grammar)) ; The evaluator (define-datatype proc proc? (procedure (body expression?) (saved-nameless-env nameless-environment?))) (define (apply-procedure proc1 val) (cases proc proc1 (procedure (body saved-nameless-env) (value-of body (extend-nameless-env val saved-nameless-env))))) (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?)) (proc-val (proc proc?))) (define (expval->num val) (cases expval val (num-val (num) num) (else (eopl:error 'expval->num "Invalid number: ~s" val)))) (define (expval->bool val) (cases expval val (bool-val (bool) bool) (else (eopl:error 'expval->bool "Invalid boolean: ~s" val)))) (define (expval->proc val) (cases expval val (proc-val (proc) proc) (else (eopl:error 'expval->proc "Invalid procedure: ~s" val)))) (define (translation-of expr senv) (cases expression expr (const-exp (num) (const-exp num)) (diff-exp (minuend subtrahend) (diff-exp (translation-of minuend senv) (translation-of subtrahend senv))) (zero?-exp (arg) (zero?-exp (translation-of arg senv))) (if-exp (predicate consequent alternative) (if-exp (translation-of predicate senv) (translation-of consequent senv) (translation-of alternative senv))) (var-exp (var) (nameless-var-exp (apply-senv senv var))) (let-exp (var value-exp body) (nameless-let-exp (translation-of value-exp senv) (translation-of body (extend-senv var senv)))) (proc-exp (var body) (nameless-proc-exp (translation-of body (extend-senv var senv)))) (call-exp (rator rand) (call-exp (translation-of rator senv) (translation-of rand senv))) (cond-exp (conditions actions) (cond-exp (map (lambda (e) (translation-of e senv)) conditions) (map (lambda (e) (translation-of e senv)) actions))) (else (eopl:error 'translation-of "Cannot translate ~a" expr)))) (define (eval-cond conditions actions nenv) (cond ((null? conditions) (bool-val #f)) ((expval->bool (value-of (car conditions) nenv)) (value-of (car actions) nenv)) (else (eval-cond (cdr conditions) (cdr actions) nenv)))) (define (value-of expr nenv) (cases expression expr (const-exp (num) (num-val num)) (diff-exp (minuend subtrahend) (let ((minuend-val (value-of minuend nenv)) (subtrahend-val (value-of subtrahend nenv))) (let ((minuend-num (expval->num minuend-val)) (subtrahend-num (expval->num subtrahend-val))) (num-val (- minuend-num subtrahend-num))))) (zero?-exp (arg) (let ((value (value-of arg nenv))) (let ((number (expval->num value))) (if (zero? number) (bool-val #t) (bool-val #f))))) (if-exp (predicate consequent alternative) (let ((value (value-of predicate nenv))) (if (expval->bool value) (value-of consequent nenv) (value-of alternative nenv)))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator nenv))) (arg (value-of rand nenv))) (apply-procedure proc arg))) (nameless-var-exp (n) (apply-nameless-env nenv n)) (nameless-let-exp (value-exp body) (let ((val (value-of value-exp nenv))) (value-of body (extend-nameless-env val nenv)))) (nameless-proc-exp (body) (proc-val (procedure body nenv))) (cond-exp (conditions actions) (eval-cond conditions actions nenv)) (else (eopl:error 'value-of "Cannot evaluate ~a" expr))))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/38.scm
scheme
Extend the lexical address translator and interpreter to handle cond from The parser The evaluator
EOPL exercise 3.38 exercise 3.12 . (load-relative "cases/nameless/env.scm") (define-datatype expression expression? (const-exp (num number?)) (diff-exp (minuend expression?) (subtrahend expression?)) (zero?-exp (expr expression?)) (if-exp (predicate expression?) (consequent expression?) (alternative expression?)) (var-exp (var symbol?)) (let-exp (var symbol?) (value expression?) (body expression?)) (proc-exp (var symbol?) (body expression?)) (call-exp (rator expression?) (rand expression?)) (nameless-var-exp (num integer?)) (nameless-let-exp (exp1 expression?) (body expression?)) (nameless-proc-exp (body expression?)) (cond-exp (conditions (list-of expression?)) (actions (list-of expression?)))) (define scanner-spec '((white-sp (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit))) symbol) (number (digit (arbno digit)) number))) (define grammar '((expression (number) const-exp) (expression ("cond" (arbno expression "==>" expression) "end") cond-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression (identifier) var-exp) (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) (expression ("(" expression expression ")") call-exp))) (define scan&parse (sllgen:make-string-parser scanner-spec grammar)) (define-datatype proc proc? (procedure (body expression?) (saved-nameless-env nameless-environment?))) (define (apply-procedure proc1 val) (cases proc proc1 (procedure (body saved-nameless-env) (value-of body (extend-nameless-env val saved-nameless-env))))) (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?)) (proc-val (proc proc?))) (define (expval->num val) (cases expval val (num-val (num) num) (else (eopl:error 'expval->num "Invalid number: ~s" val)))) (define (expval->bool val) (cases expval val (bool-val (bool) bool) (else (eopl:error 'expval->bool "Invalid boolean: ~s" val)))) (define (expval->proc val) (cases expval val (proc-val (proc) proc) (else (eopl:error 'expval->proc "Invalid procedure: ~s" val)))) (define (translation-of expr senv) (cases expression expr (const-exp (num) (const-exp num)) (diff-exp (minuend subtrahend) (diff-exp (translation-of minuend senv) (translation-of subtrahend senv))) (zero?-exp (arg) (zero?-exp (translation-of arg senv))) (if-exp (predicate consequent alternative) (if-exp (translation-of predicate senv) (translation-of consequent senv) (translation-of alternative senv))) (var-exp (var) (nameless-var-exp (apply-senv senv var))) (let-exp (var value-exp body) (nameless-let-exp (translation-of value-exp senv) (translation-of body (extend-senv var senv)))) (proc-exp (var body) (nameless-proc-exp (translation-of body (extend-senv var senv)))) (call-exp (rator rand) (call-exp (translation-of rator senv) (translation-of rand senv))) (cond-exp (conditions actions) (cond-exp (map (lambda (e) (translation-of e senv)) conditions) (map (lambda (e) (translation-of e senv)) actions))) (else (eopl:error 'translation-of "Cannot translate ~a" expr)))) (define (eval-cond conditions actions nenv) (cond ((null? conditions) (bool-val #f)) ((expval->bool (value-of (car conditions) nenv)) (value-of (car actions) nenv)) (else (eval-cond (cdr conditions) (cdr actions) nenv)))) (define (value-of expr nenv) (cases expression expr (const-exp (num) (num-val num)) (diff-exp (minuend subtrahend) (let ((minuend-val (value-of minuend nenv)) (subtrahend-val (value-of subtrahend nenv))) (let ((minuend-num (expval->num minuend-val)) (subtrahend-num (expval->num subtrahend-val))) (num-val (- minuend-num subtrahend-num))))) (zero?-exp (arg) (let ((value (value-of arg nenv))) (let ((number (expval->num value))) (if (zero? number) (bool-val #t) (bool-val #f))))) (if-exp (predicate consequent alternative) (let ((value (value-of predicate nenv))) (if (expval->bool value) (value-of consequent nenv) (value-of alternative nenv)))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator nenv))) (arg (value-of rand nenv))) (apply-procedure proc arg))) (nameless-var-exp (n) (apply-nameless-env nenv n)) (nameless-let-exp (value-exp body) (let ((val (value-of value-exp nenv))) (value-of body (extend-nameless-env val nenv)))) (nameless-proc-exp (body) (proc-val (procedure body nenv))) (cond-exp (conditions actions) (eval-cond conditions actions nenv)) (else (eopl:error 'value-of "Cannot evaluate ~a" expr))))
0f3cbf7c922737668c92e7d6263221fa614a96f88a9a98cee19d9a374c765130
tokenmill/timewords
core.clj
(ns timewords.core (:require [clojure.string :as s] [clj-time.core :as joda] [clj-time.coerce :as jco] [timewords.standard.standard :as standard] [timewords.fuzzy.fuzzy :as fuzzy]) (:import (java.util Date) (org.joda.time DateTime)) (:gen-class :name lt.tokenmill.timewords.Timewords :methods [[parse [java.lang.String] java.util.Date] [parse [java.lang.String java.util.Date] java.util.Date] [parse [java.lang.String java.util.Date java.lang.String] java.util.Date]])) (defn parse "Given a string that represents date, returns a java.util.Date object. Cases that are not handled return nil. Second (optional) parameter must be a language code, e.g. `en`. Third (optional) parameter is a document-time which must be nil or java.util.Date. `document-time` is used to parse relative timewords like 'yesterday'." ^Date [^String date-string & [^Date document-time ^String language]] (try (when-not (or (nil? document-time) (instance? Date document-time)) (throw (Exception. "document-time is not either nil or java.util.Date."))) (when-not (or (nil? language) (string? language)) (throw (Exception. "language parameter is not either nil or java.lang.String."))) (let [date-string (.replaceAll date-string "[\\u00A0\\u202F\\uFEFF\\u2007\\u180E]" " ") ^String language (or language "en") ^DateTime document-time (or (DateTime. document-time) (joda/now))] (when (not (s/blank? date-string)) (jco/to-date (or (standard/to-date date-string language document-time) (fuzzy/to-date date-string language document-time))))) (catch Exception e (prn (str "Caught exception: '" (.getMessage e) "', while parsing timeword '" date-string "' with language '" language "' and with document-time '" document-time "'.")) nil))) (defn -parse ^Date [_ ^String date-string & [^Date document-time ^String language]] (parse date-string document-time language))
null
https://raw.githubusercontent.com/tokenmill/timewords/431ef3aa9eb899f2abd47cebc20a232f8c226b4a/src/timewords/core.clj
clojure
(ns timewords.core (:require [clojure.string :as s] [clj-time.core :as joda] [clj-time.coerce :as jco] [timewords.standard.standard :as standard] [timewords.fuzzy.fuzzy :as fuzzy]) (:import (java.util Date) (org.joda.time DateTime)) (:gen-class :name lt.tokenmill.timewords.Timewords :methods [[parse [java.lang.String] java.util.Date] [parse [java.lang.String java.util.Date] java.util.Date] [parse [java.lang.String java.util.Date java.lang.String] java.util.Date]])) (defn parse "Given a string that represents date, returns a java.util.Date object. Cases that are not handled return nil. Second (optional) parameter must be a language code, e.g. `en`. Third (optional) parameter is a document-time which must be nil or java.util.Date. `document-time` is used to parse relative timewords like 'yesterday'." ^Date [^String date-string & [^Date document-time ^String language]] (try (when-not (or (nil? document-time) (instance? Date document-time)) (throw (Exception. "document-time is not either nil or java.util.Date."))) (when-not (or (nil? language) (string? language)) (throw (Exception. "language parameter is not either nil or java.lang.String."))) (let [date-string (.replaceAll date-string "[\\u00A0\\u202F\\uFEFF\\u2007\\u180E]" " ") ^String language (or language "en") ^DateTime document-time (or (DateTime. document-time) (joda/now))] (when (not (s/blank? date-string)) (jco/to-date (or (standard/to-date date-string language document-time) (fuzzy/to-date date-string language document-time))))) (catch Exception e (prn (str "Caught exception: '" (.getMessage e) "', while parsing timeword '" date-string "' with language '" language "' and with document-time '" document-time "'.")) nil))) (defn -parse ^Date [_ ^String date-string & [^Date document-time ^String language]] (parse date-string document-time language))
53ebeb497b3486e48073ce4c1e5910b7498a3a32038b20a67fa9fa280857c410
rwmjones/guestfs-tools
resize.mli
virt - resize * Copyright ( C ) 2010 - 2023 Red Hat Inc. * * 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. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2010-2023 Red Hat Inc. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) (* Nothing is exported. *)
null
https://raw.githubusercontent.com/rwmjones/guestfs-tools/57423d907270526ea664ff15601cce956353820e/resize/resize.mli
ocaml
Nothing is exported.
virt - resize * Copyright ( C ) 2010 - 2023 Red Hat Inc. * * 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. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2010-2023 Red Hat Inc. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *)
54204cd45c59485b42926ce04785f4487a0527b6c3284e4c7e38b1e30b0e296e
ejgallego/coq-lsp
stats.ml
(************************************************************************) (* Coq Language Server Protocol *) Copyright 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Copyright 2022 -- Dual License LGPL 2.1 / GPL3 + Written by : (************************************************************************) (* Status: Experimental *) (************************************************************************) module Kind = struct type t = | Hashing | Parsing | Exec end let stats = Hashtbl.create 1000 let find kind = Hashtbl.find_opt stats kind |> Option.default 0.0 type t = float * float * float let zero () = (0.0, 0.0, 0.0) let dump () = (find Kind.Hashing, find Kind.Parsing, find Kind.Exec) let restore (h, p, e) = Hashtbl.replace stats Kind.Hashing h; Hashtbl.replace stats Kind.Parsing p; Hashtbl.replace stats Kind.Exec e let get_f (h, p, e) ~kind = match kind with | Kind.Hashing -> h | Parsing -> p | Exec -> e let bump kind time = let acc = find kind in Hashtbl.replace stats kind (acc +. time) let time f x = let before = Unix.gettimeofday () in let res = f x in let after = Unix.gettimeofday () in (res, after -. before) let record ~kind ~f x = let res, time = time f x in bump kind time; (res, time) let get ~kind = find kind let to_string () = Format.asprintf "hashing: %f | parsing: %f | exec: %f" (find Kind.Hashing) (find Kind.Parsing) (find Kind.Exec) let reset () = Hashtbl.remove stats Kind.Hashing; Hashtbl.remove stats Kind.Parsing; Hashtbl.remove stats Kind.Exec; ()
null
https://raw.githubusercontent.com/ejgallego/coq-lsp/f72982922d55689f9397283c525485ad26e952de/fleche/stats.ml
ocaml
********************************************************************** Coq Language Server Protocol ********************************************************************** Status: Experimental **********************************************************************
Copyright 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 + Copyright 2022 -- Dual License LGPL 2.1 / GPL3 + Written by : module Kind = struct type t = | Hashing | Parsing | Exec end let stats = Hashtbl.create 1000 let find kind = Hashtbl.find_opt stats kind |> Option.default 0.0 type t = float * float * float let zero () = (0.0, 0.0, 0.0) let dump () = (find Kind.Hashing, find Kind.Parsing, find Kind.Exec) let restore (h, p, e) = Hashtbl.replace stats Kind.Hashing h; Hashtbl.replace stats Kind.Parsing p; Hashtbl.replace stats Kind.Exec e let get_f (h, p, e) ~kind = match kind with | Kind.Hashing -> h | Parsing -> p | Exec -> e let bump kind time = let acc = find kind in Hashtbl.replace stats kind (acc +. time) let time f x = let before = Unix.gettimeofday () in let res = f x in let after = Unix.gettimeofday () in (res, after -. before) let record ~kind ~f x = let res, time = time f x in bump kind time; (res, time) let get ~kind = find kind let to_string () = Format.asprintf "hashing: %f | parsing: %f | exec: %f" (find Kind.Hashing) (find Kind.Parsing) (find Kind.Exec) let reset () = Hashtbl.remove stats Kind.Hashing; Hashtbl.remove stats Kind.Parsing; Hashtbl.remove stats Kind.Exec; ()
73444676ae838994aa09e2161639d1fc3c59b6cdc3ccebfed9a7fd38507d7d21
mzp/coq-ide-for-ios
ratio.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../../LICENSE. *) (* *) (***********************************************************************) $ I d : ratio.mli 9547 2010 - 01 - 22 12:48:24Z doligez $ (* Module [Ratio]: operations on rational numbers *) open Nat open Big_int Rationals ( type [ ratio ] ) are arbitrary - precision rational numbers , plus the special elements [ 1/0 ] ( infinity ) and [ 0/0 ] ( undefined ) . In constrast with numbers ( type [ num ] ) , the special cases of small integers and big integers are not optimized specially . plus the special elements [1/0] (infinity) and [0/0] (undefined). In constrast with numbers (type [num]), the special cases of small integers and big integers are not optimized specially. *) type ratio val null_denominator : ratio -> bool val numerator_ratio : ratio -> big_int val denominator_ratio : ratio -> big_int val sign_ratio : ratio -> int val normalize_ratio : ratio -> ratio val cautious_normalize_ratio : ratio -> ratio val cautious_normalize_ratio_when_printing : ratio -> ratio val create_ratio : big_int -> big_int -> ratio val create_normalized_ratio : big_int -> big_int -> ratio val is_normalized_ratio : ratio -> bool val report_sign_ratio : ratio -> big_int -> big_int val abs_ratio : ratio -> ratio val is_integer_ratio : ratio -> bool val add_ratio : ratio -> ratio -> ratio val minus_ratio : ratio -> ratio val add_int_ratio : int -> ratio -> ratio val add_big_int_ratio : big_int -> ratio -> ratio val sub_ratio : ratio -> ratio -> ratio val mult_ratio : ratio -> ratio -> ratio val mult_int_ratio : int -> ratio -> ratio val mult_big_int_ratio : big_int -> ratio -> ratio val square_ratio : ratio -> ratio val inverse_ratio : ratio -> ratio val div_ratio : ratio -> ratio -> ratio val integer_ratio : ratio -> big_int val floor_ratio : ratio -> big_int val round_ratio : ratio -> big_int val ceiling_ratio : ratio -> big_int val eq_ratio : ratio -> ratio -> bool val compare_ratio : ratio -> ratio -> int val lt_ratio : ratio -> ratio -> bool val le_ratio : ratio -> ratio -> bool val gt_ratio : ratio -> ratio -> bool val ge_ratio : ratio -> ratio -> bool val max_ratio : ratio -> ratio -> ratio val min_ratio : ratio -> ratio -> ratio val eq_big_int_ratio : big_int -> ratio -> bool val compare_big_int_ratio : big_int -> ratio -> int val lt_big_int_ratio : big_int -> ratio -> bool val le_big_int_ratio : big_int -> ratio -> bool val gt_big_int_ratio : big_int -> ratio -> bool val ge_big_int_ratio : big_int -> ratio -> bool val int_of_ratio : ratio -> int val ratio_of_int : int -> ratio val ratio_of_nat : nat -> ratio val nat_of_ratio : ratio -> nat val ratio_of_big_int : big_int -> ratio val big_int_of_ratio : ratio -> big_int val div_int_ratio : int -> ratio -> ratio val div_ratio_int : ratio -> int -> ratio val div_big_int_ratio : big_int -> ratio -> ratio val div_ratio_big_int : ratio -> big_int -> ratio val approx_ratio_fix : int -> ratio -> string val approx_ratio_exp : int -> ratio -> string val float_of_rational_string : ratio -> string val string_of_ratio : ratio -> string val ratio_of_string : string -> ratio val float_of_ratio : ratio -> float val power_ratio_positive_int : ratio -> int -> ratio val power_ratio_positive_big_int : ratio -> big_int -> ratio
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/ocaml-3.12.0/lib/ocaml/ratio.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../../LICENSE. ********************************************************************* Module [Ratio]: operations on rational numbers
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ I d : ratio.mli 9547 2010 - 01 - 22 12:48:24Z doligez $ open Nat open Big_int Rationals ( type [ ratio ] ) are arbitrary - precision rational numbers , plus the special elements [ 1/0 ] ( infinity ) and [ 0/0 ] ( undefined ) . In constrast with numbers ( type [ num ] ) , the special cases of small integers and big integers are not optimized specially . plus the special elements [1/0] (infinity) and [0/0] (undefined). In constrast with numbers (type [num]), the special cases of small integers and big integers are not optimized specially. *) type ratio val null_denominator : ratio -> bool val numerator_ratio : ratio -> big_int val denominator_ratio : ratio -> big_int val sign_ratio : ratio -> int val normalize_ratio : ratio -> ratio val cautious_normalize_ratio : ratio -> ratio val cautious_normalize_ratio_when_printing : ratio -> ratio val create_ratio : big_int -> big_int -> ratio val create_normalized_ratio : big_int -> big_int -> ratio val is_normalized_ratio : ratio -> bool val report_sign_ratio : ratio -> big_int -> big_int val abs_ratio : ratio -> ratio val is_integer_ratio : ratio -> bool val add_ratio : ratio -> ratio -> ratio val minus_ratio : ratio -> ratio val add_int_ratio : int -> ratio -> ratio val add_big_int_ratio : big_int -> ratio -> ratio val sub_ratio : ratio -> ratio -> ratio val mult_ratio : ratio -> ratio -> ratio val mult_int_ratio : int -> ratio -> ratio val mult_big_int_ratio : big_int -> ratio -> ratio val square_ratio : ratio -> ratio val inverse_ratio : ratio -> ratio val div_ratio : ratio -> ratio -> ratio val integer_ratio : ratio -> big_int val floor_ratio : ratio -> big_int val round_ratio : ratio -> big_int val ceiling_ratio : ratio -> big_int val eq_ratio : ratio -> ratio -> bool val compare_ratio : ratio -> ratio -> int val lt_ratio : ratio -> ratio -> bool val le_ratio : ratio -> ratio -> bool val gt_ratio : ratio -> ratio -> bool val ge_ratio : ratio -> ratio -> bool val max_ratio : ratio -> ratio -> ratio val min_ratio : ratio -> ratio -> ratio val eq_big_int_ratio : big_int -> ratio -> bool val compare_big_int_ratio : big_int -> ratio -> int val lt_big_int_ratio : big_int -> ratio -> bool val le_big_int_ratio : big_int -> ratio -> bool val gt_big_int_ratio : big_int -> ratio -> bool val ge_big_int_ratio : big_int -> ratio -> bool val int_of_ratio : ratio -> int val ratio_of_int : int -> ratio val ratio_of_nat : nat -> ratio val nat_of_ratio : ratio -> nat val ratio_of_big_int : big_int -> ratio val big_int_of_ratio : ratio -> big_int val div_int_ratio : int -> ratio -> ratio val div_ratio_int : ratio -> int -> ratio val div_big_int_ratio : big_int -> ratio -> ratio val div_ratio_big_int : ratio -> big_int -> ratio val approx_ratio_fix : int -> ratio -> string val approx_ratio_exp : int -> ratio -> string val float_of_rational_string : ratio -> string val string_of_ratio : ratio -> string val ratio_of_string : string -> ratio val float_of_ratio : ratio -> float val power_ratio_positive_int : ratio -> int -> ratio val power_ratio_positive_big_int : ratio -> big_int -> ratio
f9e60921fd76f31fbc16ecabc896ef555cfbe05d055d269713b48b5180ea0ec8
kdltr/chicken-core
embedded4.scm
;;; x.scm (import (chicken gc) (chicken platform)) (define (bar x) (gc) (* x x)) (define-external (baz (int i)) double (sqrt i)) (return-to-host)
null
https://raw.githubusercontent.com/kdltr/chicken-core/b2e6c5243dd469064bec947cb3b49dafaa1514e5/tests/embedded4.scm
scheme
x.scm
(import (chicken gc) (chicken platform)) (define (bar x) (gc) (* x x)) (define-external (baz (int i)) double (sqrt i)) (return-to-host)
f4decd191a75e46fff8f1a4659e30151d578cbf1c2386f9b497c6b5ce6069960
svdm/ClojureGP
test_breeding.clj
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (-1.0.php) which ;; can be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, from ;; this software. (ns test.cljgp.test-breeding (:use clojure.test cljgp.generate cljgp.breeding cljgp.evaluation cljgp.util) (:refer test.helpers)) (deftest test-parent-arg-type (let [p (fn [s t] (with-meta s {:gp-arg-types t})) tree-orig [(p '+ [:+1 :+2]) [(p '* [:*1 :*2]) (p 'x []) (p 'y [])] [(p '- [:-1 :-2]) [(p 'div [:div1 :div2]) (p 'a []) (p 'b [])] (p 'c [])]]] (is (= [:root :+1 :*1 :*2 :+2 :-1 :div1 :div2 :-2] (map #(parent-arg-type % :root (make-tree-seq tree-orig)) (range (count (make-tree-seq tree-orig)))))))) (deftest test-tree-replace (let [tree-orig `(+ (* (+ _1 _2) (- _3 _4)) (/ (/ _5 _1) (+ _2 _3)))] (doseq [i (range (count (make-tree-seq tree-orig)))] (is (= :test (nth (make-tree-seq (tree-replace i :test tree-orig)) i)) "Replace should work correctly in any tree node.")))) Two manually created trees for testing a specific type situation (def typetest-tree-a (list (with-meta `count {:gp-type Number :gp-arg-types [:test.helpers/seq]}) (with-meta `TEXT {:gp-type :test.helpers/string}))) (def typetest-tree-b (list (with-meta `safe-nth {:gp-type Number :gp-arg-types [:test.helpers/vector Number]}) (with-meta `VECT {:gp-type :test.helpers/vector}) (with-meta `_1 {:gp-type Number}))) (deftest test-crossover-uniform (let [trees (crossover-uniform [(my-gen 6 :full rtype) (my-gen 6 :grow rtype)] rtype)] (is (or (= (count trees) 2) (= trees nil))) (doseq [tree trees] (full-tree-test tree))) ;;; test for a regression in typed crossover, where types with a common parent type could be picked for crossover even though the type of the first node could not satisfy the parent - arg - type of the second node , leading to ;;; invalidly typed trees (dotimes [_ 10] (let [typetrees (crossover-uniform [typetest-tree-a typetest-tree-b] Number)] (testing "Invalid types after crossover, possible regression" (doseq [tree typetrees] (full-tree-test tree)))))) These breeder fns that may validly return nil depending on rand , should ;;; really be tested multiple times... (deftest test-mutate (let [tree (mutate (my-gen 4 :full rtype) 17 func-set-maths term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree)))) (deftest test-hoist-mutate (let [parent (my-gen 4 :full rtype) tree (hoist-mutate parent rtype)] (full-tree-test tree) (is (some #{tree} (make-tree-seq parent)) "Hoisted tree must be subtree of parent."))) (deftest test-point-mutate (let [parent (my-gen 6 :full rtype) tree (point-mutate parent func-set-maths term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree) (is (not= parent tree) "New tree must differ from parent.") (is (== (tree-size parent) (tree-size tree)) "New tree must have the same structure as parent, and therefore be of the same size.")))) (deftest test-shrink-mutate (let [parent (my-gen 6 :full rtype) tree (shrink-mutate parent term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree) (is (not= parent tree) "New tree must differ from parent.") (is (> (tree-size parent) (tree-size tree)) "New tree must be smaller than parent.")))) (defn test-inds [inds gen-old num-expected] (let [trees (map #(get-fn-body (:func %)) inds)] (is (seq inds)) (is (= (count inds) num-expected)) (is (every? valid-ind? inds) "All individuals should be maps with the required keys") (is (every? #(= (:gen %) (inc gen-old)) inds) "New individuals should have incremented :gen.") (doseq [tree trees] (full-tree-test tree)))) (deftest test-crossover-individuals (let [gen-old 0 inds (crossover-individuals crossover-uniform [(make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) (make-individual (my-tpl (my-gen 4 :grow rtype)) gen-old)] config-maths)] (test-inds inds gen-old 2))) (deftest test-mutate-ind (let [gen-old 0 ind (mutate-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) 17 config-maths)] (test-inds ind gen-old 1))) (deftest test-hoist-ind (let [gen-old 0 ind (hoist-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-point-mutate-ind (let [gen-old 0 ind (point-mutate-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-shrink-ind (let [gen-old 0 ind (shrink-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-reproduce-ind (let [gen-old 0 ind-old (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) ind (reproduce-individual ind-old config-maths)] (test-inds ind gen-old 1) (is (= (dissoc (into {} ind-old) :gen) (dissoc (into {} (first ind)) :gen)) "Reproduced individuals should be identical apart from :gen"))) ; *-breeder functions not tested currently as they are very basic compositions ; of a selection function and the *-ind functions perhaps TODO #_(defn fake-evaluation [pop] (map #(assoc % :fitness (rand)) pop)) (deftest test-breed-new-pop (let [target-size (:population-size config-maths) pop-evaluated (evaluate-pop (generate-pop config-maths) config-maths) pop-new (breed-new-pop pop-evaluated config-maths)] (is (seq (doall pop-new))) (is (= (count pop-new) target-size))))
null
https://raw.githubusercontent.com/svdm/ClojureGP/266e501411b37297bdeb082913df63ececa8515c/test/cljgp/test_breeding.clj
clojure
Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. test for a regression in typed crossover, where types with a common parent invalidly typed trees really be tested multiple times... *-breeder functions not tested currently as they are very basic compositions of a selection function and the *-ind functions
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse (ns test.cljgp.test-breeding (:use clojure.test cljgp.generate cljgp.breeding cljgp.evaluation cljgp.util) (:refer test.helpers)) (deftest test-parent-arg-type (let [p (fn [s t] (with-meta s {:gp-arg-types t})) tree-orig [(p '+ [:+1 :+2]) [(p '* [:*1 :*2]) (p 'x []) (p 'y [])] [(p '- [:-1 :-2]) [(p 'div [:div1 :div2]) (p 'a []) (p 'b [])] (p 'c [])]]] (is (= [:root :+1 :*1 :*2 :+2 :-1 :div1 :div2 :-2] (map #(parent-arg-type % :root (make-tree-seq tree-orig)) (range (count (make-tree-seq tree-orig)))))))) (deftest test-tree-replace (let [tree-orig `(+ (* (+ _1 _2) (- _3 _4)) (/ (/ _5 _1) (+ _2 _3)))] (doseq [i (range (count (make-tree-seq tree-orig)))] (is (= :test (nth (make-tree-seq (tree-replace i :test tree-orig)) i)) "Replace should work correctly in any tree node.")))) Two manually created trees for testing a specific type situation (def typetest-tree-a (list (with-meta `count {:gp-type Number :gp-arg-types [:test.helpers/seq]}) (with-meta `TEXT {:gp-type :test.helpers/string}))) (def typetest-tree-b (list (with-meta `safe-nth {:gp-type Number :gp-arg-types [:test.helpers/vector Number]}) (with-meta `VECT {:gp-type :test.helpers/vector}) (with-meta `_1 {:gp-type Number}))) (deftest test-crossover-uniform (let [trees (crossover-uniform [(my-gen 6 :full rtype) (my-gen 6 :grow rtype)] rtype)] (is (or (= (count trees) 2) (= trees nil))) (doseq [tree trees] (full-tree-test tree))) type could be picked for crossover even though the type of the first node could not satisfy the parent - arg - type of the second node , leading to (dotimes [_ 10] (let [typetrees (crossover-uniform [typetest-tree-a typetest-tree-b] Number)] (testing "Invalid types after crossover, possible regression" (doseq [tree typetrees] (full-tree-test tree)))))) These breeder fns that may validly return nil depending on rand , should (deftest test-mutate (let [tree (mutate (my-gen 4 :full rtype) 17 func-set-maths term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree)))) (deftest test-hoist-mutate (let [parent (my-gen 4 :full rtype) tree (hoist-mutate parent rtype)] (full-tree-test tree) (is (some #{tree} (make-tree-seq parent)) "Hoisted tree must be subtree of parent."))) (deftest test-point-mutate (let [parent (my-gen 6 :full rtype) tree (point-mutate parent func-set-maths term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree) (is (not= parent tree) "New tree must differ from parent.") (is (== (tree-size parent) (tree-size tree)) "New tree must have the same structure as parent, and therefore be of the same size.")))) (deftest test-shrink-mutate (let [parent (my-gen 6 :full rtype) tree (shrink-mutate parent term-set-maths rtype)] (when (not (nil? tree)) (full-tree-test tree) (is (not= parent tree) "New tree must differ from parent.") (is (> (tree-size parent) (tree-size tree)) "New tree must be smaller than parent.")))) (defn test-inds [inds gen-old num-expected] (let [trees (map #(get-fn-body (:func %)) inds)] (is (seq inds)) (is (= (count inds) num-expected)) (is (every? valid-ind? inds) "All individuals should be maps with the required keys") (is (every? #(= (:gen %) (inc gen-old)) inds) "New individuals should have incremented :gen.") (doseq [tree trees] (full-tree-test tree)))) (deftest test-crossover-individuals (let [gen-old 0 inds (crossover-individuals crossover-uniform [(make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) (make-individual (my-tpl (my-gen 4 :grow rtype)) gen-old)] config-maths)] (test-inds inds gen-old 2))) (deftest test-mutate-ind (let [gen-old 0 ind (mutate-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) 17 config-maths)] (test-inds ind gen-old 1))) (deftest test-hoist-ind (let [gen-old 0 ind (hoist-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-point-mutate-ind (let [gen-old 0 ind (point-mutate-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-shrink-ind (let [gen-old 0 ind (shrink-individual (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) config-maths)] (test-inds ind gen-old 1))) (deftest test-reproduce-ind (let [gen-old 0 ind-old (make-individual (my-tpl (my-gen 4 :full rtype)) gen-old) ind (reproduce-individual ind-old config-maths)] (test-inds ind gen-old 1) (is (= (dissoc (into {} ind-old) :gen) (dissoc (into {} (first ind)) :gen)) "Reproduced individuals should be identical apart from :gen"))) perhaps TODO #_(defn fake-evaluation [pop] (map #(assoc % :fitness (rand)) pop)) (deftest test-breed-new-pop (let [target-size (:population-size config-maths) pop-evaluated (evaluate-pop (generate-pop config-maths) config-maths) pop-new (breed-new-pop pop-evaluated config-maths)] (is (seq (doall pop-new))) (is (= (count pop-new) target-size))))
7681a74aadfad55b6e33ce9ed072597e1c74b5d092a99e9242fee59c57c45732
pstephens/kingjames.bible
unittests.cljs
Copyright 2015 . All Rights Reserved . ;;;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . ;;;; You may obtain a copy of the License at ;;;; ;;;; -2.0 ;;;; ;;;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the License for the specific language governing permissions and ;;;; limitations under the License. (ns test.node.unittests (:require [cljs.nodejs :as nodejs] [cljs.test :refer-macros [run-tests] :refer [successful?]] [test.node.common.bible.coretests] [test.node.common.bible.iotests] [test.node.common.normalizer.coretests])) (nodejs/enable-util-print!) (def process nodejs/process) (defn runtests [] (run-tests 'test.node.common.normalizer.coretests 'test.node.common.bible.coretests 'test.node.common.bible.iotests)) (defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m] (if (successful? m) (do (println "Success!") (.exit process 0)) (do (println "FAIL") (.exit process 1))))
null
https://raw.githubusercontent.com/pstephens/kingjames.bible/a2c2a7324176a829df6ebf50976d81c65c35eb02/src/test/node/unittests.cljs
clojure
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 2015 . All Rights Reserved . you may not use this file except in compliance with the License . distributed under the License is distributed on an " AS IS " BASIS , (ns test.node.unittests (:require [cljs.nodejs :as nodejs] [cljs.test :refer-macros [run-tests] :refer [successful?]] [test.node.common.bible.coretests] [test.node.common.bible.iotests] [test.node.common.normalizer.coretests])) (nodejs/enable-util-print!) (def process nodejs/process) (defn runtests [] (run-tests 'test.node.common.normalizer.coretests 'test.node.common.bible.coretests 'test.node.common.bible.iotests)) (defmethod cljs.test/report [:cljs.test/default :end-run-tests] [m] (if (successful? m) (do (println "Success!") (.exit process 0)) (do (println "FAIL") (.exit process 1))))
d56c4e3d14a84fa99460af3cf2fc539c53aee6e73611d1daf6e8eab74d1d5fb0
typelead/eta
tc073.hs
module ShouldSucceed where f [] = [] f (x:xs) = x : (f xs)
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc073.hs
haskell
module ShouldSucceed where f [] = [] f (x:xs) = x : (f xs)
f932e51d25beb301bfe186ed4a190f905a26f5102314d0e36b65ff96908462d5
ygrek/ocaml-extlib
extHashtbl.ml
* , extra functions over hashtables . * Copyright ( C ) 2003 * * 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 , * with the special exception on linking described in file LICENSE . * * 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * ExtHashtbl, extra functions over hashtables. * Copyright (C) 2003 Nicolas Cannasse * * 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, * with the special exception on linking described in file LICENSE. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) module Hashtbl = struct #if OCAML >= 400 && OCAML < 412 external old_hash_param : int -> int -> 'a -> int = "caml_hash_univ_param" "noalloc" #endif type ('a, 'b) h_bucketlist = | Empty | Cons of 'a * 'b * ('a, 'b) h_bucketlist #if OCAML >= 400 type ('a, 'b) h_t = { mutable size: int; mutable data: ('a, 'b) h_bucketlist array; mutable seed: int; initial_size: int; } #else type ('a, 'b) h_t = { mutable size: int; mutable data: ('a, 'b) h_bucketlist array } #endif include Hashtbl #if OCAML < 400 let create ?random:_ n = Hashtbl.create (* no seed *) n #endif external h_conv : ('a, 'b) t -> ('a, 'b) h_t = "%identity" external h_make : ('a, 'b) h_t -> ('a, 'b) t = "%identity" let exists = mem let enum h = let rec make ipos ibuck idata icount = let pos = ref ipos in let buck = ref ibuck in let hdata = ref idata in let hcount = ref icount in let force() = (** this is a hack in order to keep an O(1) enum constructor **) if !hcount = -1 then begin hcount := (h_conv h).size; hdata := Array.copy (h_conv h).data; end; in let rec next() = force(); match !buck with | Empty -> if !hcount = 0 then raise Enum.No_more_elements; incr pos; buck := Array.unsafe_get !hdata !pos; next() | Cons (k,i,next_buck) -> buck := next_buck; decr hcount; (k,i) in let count() = if !hcount = -1 then (h_conv h).size else !hcount in let clone() = force(); make !pos !buck !hdata !hcount in Enum.make ~next ~count ~clone in make (-1) Empty (Obj.magic()) (-1) let keys h = Enum.map (fun (k,_) -> k) (enum h) let values h = Enum.map (fun (_,v) -> v) (enum h) let map f h = let rec loop = function | Empty -> Empty | Cons (k,v,next) -> Cons (k,f v,loop next) in h_make { (h_conv h) with data = Array.map loop (h_conv h).data; } #if OCAML >= 400 (* copied from stdlib :( *) let key_index h key = (* compatibility with old hash tables *) if Obj.size (Obj.repr h) >= 3 then (seeded_hash_param 10 100 (h_conv h).seed key) land (Array.length (h_conv h).data - 1) #if OCAML >= 412 else failwith "Old hash function not supported anymore" #else else (old_hash_param 10 100 key) mod (Array.length (h_conv h).data) #endif #else let key_index h key = (hash key) mod (Array.length (h_conv h).data) #endif let remove_all h key = let hc = h_conv h in let rec loop = function | Empty -> Empty | Cons(k,v,next) -> if k = key then begin hc.size <- pred hc.size; loop next end else Cons(k,v,loop next) in let pos = key_index h key in Array.unsafe_set hc.data pos (loop (Array.unsafe_get hc.data pos)) let find_default h key defval = let rec loop = function | Empty -> defval | Cons (k,v,next) -> if k = key then v else loop next in let pos = key_index h key in loop (Array.unsafe_get (h_conv h).data pos) #if OCAML < 405 let find_opt h key = let rec loop = function | Empty -> None | Cons (k,v,next) -> if k = key then Some v else loop next in let pos = key_index h key in loop (Array.unsafe_get (h_conv h).data pos) #endif let find_option = find_opt let of_enum e = let h = create (if Enum.fast_count e then Enum.count e else 0) in Enum.iter (fun (k,v) -> add h k v) e; h let length h = (h_conv h).size end
null
https://raw.githubusercontent.com/ygrek/ocaml-extlib/69b77f0f0500c98371aea9a6f2abb56c946cdab0/src/extHashtbl.ml
ocaml
no seed * this is a hack in order to keep an O(1) enum constructor * copied from stdlib :( compatibility with old hash tables
* , extra functions over hashtables . * Copyright ( C ) 2003 * * 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 , * with the special exception on linking described in file LICENSE . * * 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * ExtHashtbl, extra functions over hashtables. * Copyright (C) 2003 Nicolas Cannasse * * 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, * with the special exception on linking described in file LICENSE. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) module Hashtbl = struct #if OCAML >= 400 && OCAML < 412 external old_hash_param : int -> int -> 'a -> int = "caml_hash_univ_param" "noalloc" #endif type ('a, 'b) h_bucketlist = | Empty | Cons of 'a * 'b * ('a, 'b) h_bucketlist #if OCAML >= 400 type ('a, 'b) h_t = { mutable size: int; mutable data: ('a, 'b) h_bucketlist array; mutable seed: int; initial_size: int; } #else type ('a, 'b) h_t = { mutable size: int; mutable data: ('a, 'b) h_bucketlist array } #endif include Hashtbl #if OCAML < 400 #endif external h_conv : ('a, 'b) t -> ('a, 'b) h_t = "%identity" external h_make : ('a, 'b) h_t -> ('a, 'b) t = "%identity" let exists = mem let enum h = let rec make ipos ibuck idata icount = let pos = ref ipos in let buck = ref ibuck in let hdata = ref idata in let hcount = ref icount in let force() = if !hcount = -1 then begin hcount := (h_conv h).size; hdata := Array.copy (h_conv h).data; end; in let rec next() = force(); match !buck with | Empty -> if !hcount = 0 then raise Enum.No_more_elements; incr pos; buck := Array.unsafe_get !hdata !pos; next() | Cons (k,i,next_buck) -> buck := next_buck; decr hcount; (k,i) in let count() = if !hcount = -1 then (h_conv h).size else !hcount in let clone() = force(); make !pos !buck !hdata !hcount in Enum.make ~next ~count ~clone in make (-1) Empty (Obj.magic()) (-1) let keys h = Enum.map (fun (k,_) -> k) (enum h) let values h = Enum.map (fun (_,v) -> v) (enum h) let map f h = let rec loop = function | Empty -> Empty | Cons (k,v,next) -> Cons (k,f v,loop next) in h_make { (h_conv h) with data = Array.map loop (h_conv h).data; } #if OCAML >= 400 let key_index h key = if Obj.size (Obj.repr h) >= 3 then (seeded_hash_param 10 100 (h_conv h).seed key) land (Array.length (h_conv h).data - 1) #if OCAML >= 412 else failwith "Old hash function not supported anymore" #else else (old_hash_param 10 100 key) mod (Array.length (h_conv h).data) #endif #else let key_index h key = (hash key) mod (Array.length (h_conv h).data) #endif let remove_all h key = let hc = h_conv h in let rec loop = function | Empty -> Empty | Cons(k,v,next) -> if k = key then begin hc.size <- pred hc.size; loop next end else Cons(k,v,loop next) in let pos = key_index h key in Array.unsafe_set hc.data pos (loop (Array.unsafe_get hc.data pos)) let find_default h key defval = let rec loop = function | Empty -> defval | Cons (k,v,next) -> if k = key then v else loop next in let pos = key_index h key in loop (Array.unsafe_get (h_conv h).data pos) #if OCAML < 405 let find_opt h key = let rec loop = function | Empty -> None | Cons (k,v,next) -> if k = key then Some v else loop next in let pos = key_index h key in loop (Array.unsafe_get (h_conv h).data pos) #endif let find_option = find_opt let of_enum e = let h = create (if Enum.fast_count e then Enum.count e else 0) in Enum.iter (fun (k,v) -> add h k v) e; h let length h = (h_conv h).size end
d649e53c987b46a877531e1965ef00f300c9e2c5ae4e380ff5b309aaa569ce77
GaloisInc/ivory
Array.hs
# LANGUAGE MultiParamTypeClasses # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # module Ivory.Language.Array ( Ix(), IxRep, ixRep, fromIx, toIx, ixSize, arrayLen, (!), ) where import Ivory.Language.IBool import Ivory.Language.Area import Ivory.Language.Proxy import Ivory.Language.Ref import Ivory.Language.Sint import Ivory.Language.IIntegral import Ivory.Language.Type import Ivory.Language.Cast import qualified Ivory.Language.Syntax as I import GHC.TypeLits (Nat) -------------------------------------------------------------------------------- -- Indexes -- Note: it is assumed in ivory-opts and the ivory-backend that the associated type is an Sint32 , so this should not be changed in the front - end without -- modifying the other packages. type IxRep = Sint32 -- | The representation type of a @TyIndex@, this is fixed to @Int32@ for the -- time being. ixRep :: I.Type ixRep = ivoryType (Proxy :: Proxy IxRep) -- | Values in the range @0 .. n-1@. newtype Ix (n :: Nat) = Ix { getIx :: I.Expr } instance (ANat n) => IvoryType (Ix n) where ivoryType _ = I.TyIndex (fromTypeNat (aNat :: NatType n)) instance (ANat n) => IvoryVar (Ix n) where wrapVar = wrapVarExpr unwrapExpr = getIx instance (ANat n) => IvoryExpr (Ix n) where wrapExpr e | 0 /= fromTypeNat (aNat :: NatType n) = Ix e | otherwise = error "cannot have an index with width 0" instance (ANat n) => IvoryStore (Ix n) instance (ANat n) => Num (Ix n) where (*) = ixBinop (*) (-) = ixBinop (-) (+) = ixBinop (+) abs = ixUnary abs signum = ixUnary signum fromInteger = mkIx . fromInteger instance ANat n => Bounded (Ix n) where minBound = 0 maxBound = fromInteger (n - 1) where n = fromTypeNat (aNat :: NatType n) instance (ANat n) => IvoryEq (Ix n) instance (ANat n) => IvoryOrd (Ix n) fromIx :: ANat n => Ix n -> IxRep fromIx = wrapExpr . unwrapExpr -- | Casting from a bounded Ivory expression to an index. This is safe, -- although the value may be truncated. Furthermore, indexes are always -- positive. toIx :: forall a n. (SafeCast a IxRep, ANat n) => a -> Ix n toIx = mkIx . unwrapExpr . (safeCast :: a -> IxRep) -- | The number of elements that an index covers. ixSize :: forall n. (ANat n) => Ix n -> Integer ixSize _ = fromTypeNat (aNat :: NatType n) instance ( ANat n, IvoryIntegral to, Default to ) => SafeCast (Ix n) to where safeCast ix | Just s <- toMaxSize (ivoryType (Proxy :: Proxy to)) , ixSize ix <= s = ivoryCast (fromIx ix) | otherwise = error ixCastError -- -- It doesn't make sense to case an index downwards dynamically. -- inBounds _ _ = error ixCastError ixCastError :: String ixCastError = "Idx cast : cannot cast index: result type is too small." -- XXX don't export mkIx :: forall n. (ANat n) => I.Expr -> Ix n mkIx e = wrapExpr (I.ExpToIx e base) where base = ixSize (undefined :: Ix n) -- XXX don't export ixBinop :: (ANat n) => (I.Expr -> I.Expr -> I.Expr) -> (Ix n -> Ix n -> Ix n) ixBinop f x y = mkIx $ f (rawIxVal x) (rawIxVal y) -- XXX don't export ixUnary :: (ANat n) => (I.Expr -> I.Expr) -> (Ix n -> Ix n) ixUnary f = mkIx . f . rawIxVal -- XXX don't export rawIxVal :: ANat n => Ix n -> I.Expr rawIxVal n = case unwrapExpr n of I.ExpToIx e _ -> e e@(I.ExpVar _) -> e e -> error $ "Front-end: can't unwrap ixVal: " ++ show e -- Arrays ---------------------------------------------------------------------- arrayLen :: forall s len area n ref. (Num n, ANat len, IvoryArea area, IvoryRef ref) => ref s ('Array len area) -> n arrayLen _ = fromInteger (fromTypeNat (aNat :: NatType len)) -- | Array indexing. (!) :: forall s len area ref. ( ANat len, IvoryArea area, IvoryRef ref , IvoryExpr (ref s ('Array len area)), IvoryExpr (ref s area)) => ref s ('Array len area) -> Ix len -> ref s area arr ! ix = wrapExpr (I.ExpIndex ty (unwrapExpr arr) ixRep (getIx ix)) where ty = ivoryArea (Proxy :: Proxy ('Array len area))
null
https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory/src/Ivory/Language/Array.hs
haskell
------------------------------------------------------------------------------ Indexes Note: it is assumed in ivory-opts and the ivory-backend that the associated modifying the other packages. | The representation type of a @TyIndex@, this is fixed to @Int32@ for the time being. | Values in the range @0 .. n-1@. | Casting from a bounded Ivory expression to an index. This is safe, although the value may be truncated. Furthermore, indexes are always positive. | The number of elements that an index covers. -- It doesn't make sense to case an index downwards dynamically. inBounds _ _ = error ixCastError XXX don't export XXX don't export XXX don't export XXX don't export Arrays ---------------------------------------------------------------------- | Array indexing.
# LANGUAGE MultiParamTypeClasses # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # module Ivory.Language.Array ( Ix(), IxRep, ixRep, fromIx, toIx, ixSize, arrayLen, (!), ) where import Ivory.Language.IBool import Ivory.Language.Area import Ivory.Language.Proxy import Ivory.Language.Ref import Ivory.Language.Sint import Ivory.Language.IIntegral import Ivory.Language.Type import Ivory.Language.Cast import qualified Ivory.Language.Syntax as I import GHC.TypeLits (Nat) type is an Sint32 , so this should not be changed in the front - end without type IxRep = Sint32 ixRep :: I.Type ixRep = ivoryType (Proxy :: Proxy IxRep) newtype Ix (n :: Nat) = Ix { getIx :: I.Expr } instance (ANat n) => IvoryType (Ix n) where ivoryType _ = I.TyIndex (fromTypeNat (aNat :: NatType n)) instance (ANat n) => IvoryVar (Ix n) where wrapVar = wrapVarExpr unwrapExpr = getIx instance (ANat n) => IvoryExpr (Ix n) where wrapExpr e | 0 /= fromTypeNat (aNat :: NatType n) = Ix e | otherwise = error "cannot have an index with width 0" instance (ANat n) => IvoryStore (Ix n) instance (ANat n) => Num (Ix n) where (*) = ixBinop (*) (-) = ixBinop (-) (+) = ixBinop (+) abs = ixUnary abs signum = ixUnary signum fromInteger = mkIx . fromInteger instance ANat n => Bounded (Ix n) where minBound = 0 maxBound = fromInteger (n - 1) where n = fromTypeNat (aNat :: NatType n) instance (ANat n) => IvoryEq (Ix n) instance (ANat n) => IvoryOrd (Ix n) fromIx :: ANat n => Ix n -> IxRep fromIx = wrapExpr . unwrapExpr toIx :: forall a n. (SafeCast a IxRep, ANat n) => a -> Ix n toIx = mkIx . unwrapExpr . (safeCast :: a -> IxRep) ixSize :: forall n. (ANat n) => Ix n -> Integer ixSize _ = fromTypeNat (aNat :: NatType n) instance ( ANat n, IvoryIntegral to, Default to ) => SafeCast (Ix n) to where safeCast ix | Just s <- toMaxSize (ivoryType (Proxy :: Proxy to)) , ixSize ix <= s = ivoryCast (fromIx ix) | otherwise = error ixCastError ixCastError :: String ixCastError = "Idx cast : cannot cast index: result type is too small." mkIx :: forall n. (ANat n) => I.Expr -> Ix n mkIx e = wrapExpr (I.ExpToIx e base) where base = ixSize (undefined :: Ix n) ixBinop :: (ANat n) => (I.Expr -> I.Expr -> I.Expr) -> (Ix n -> Ix n -> Ix n) ixBinop f x y = mkIx $ f (rawIxVal x) (rawIxVal y) ixUnary :: (ANat n) => (I.Expr -> I.Expr) -> (Ix n -> Ix n) ixUnary f = mkIx . f . rawIxVal rawIxVal :: ANat n => Ix n -> I.Expr rawIxVal n = case unwrapExpr n of I.ExpToIx e _ -> e e@(I.ExpVar _) -> e e -> error $ "Front-end: can't unwrap ixVal: " ++ show e arrayLen :: forall s len area n ref. (Num n, ANat len, IvoryArea area, IvoryRef ref) => ref s ('Array len area) -> n arrayLen _ = fromInteger (fromTypeNat (aNat :: NatType len)) (!) :: forall s len area ref. ( ANat len, IvoryArea area, IvoryRef ref , IvoryExpr (ref s ('Array len area)), IvoryExpr (ref s area)) => ref s ('Array len area) -> Ix len -> ref s area arr ! ix = wrapExpr (I.ExpIndex ty (unwrapExpr arr) ixRep (getIx ix)) where ty = ivoryArea (Proxy :: Proxy ('Array len area))
5a522d13ca1c65c5400b917c5cb9c1f3e926b96c77d1536deb899cff57caffb9
ocaml/oasis
Main.ml
(******************************************************************************) OASIS : architecture for building OCaml libraries and applications (* *) Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL (* *) (* 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, with the OCaml static compilation *) (* exception. *) (* *) (* This library is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *) (* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING 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 St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) * Main for OASIS open OASISTypes open OASISUtils open OASISPlugin open OASISBuiltinPlugins open BaseMessage open CLISubCommand open Format open FormatExt open Setup open SetupDev open SetupClean open Quickstart open Manual open Check open Query open Version open Help let () = (* Run subcommand *) try OASISBuiltinPlugins.init (); CLIArgExt.parse_and_run () with e -> begin if Printexc.backtrace_status () then Printexc.print_backtrace stderr; begin match e with | Failure str -> error "%s" str | e -> begin error "%s" (Printexc.to_string e); if Printexc.backtrace_status () then List.iter (debug "%s") (OASISString.nsplit (Printexc.get_backtrace ()) '\n') end end; exit 1 end
null
https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/cli/Main.ml
ocaml
**************************************************************************** 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 your option) any later version, with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more details. **************************************************************************** Run subcommand
OASIS : architecture for building OCaml libraries and applications Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL the Free Software Foundation ; either version 2.1 of the License , or ( at 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 St , Fifth Floor , Boston , MA 02110 - 1301 USA * Main for OASIS open OASISTypes open OASISUtils open OASISPlugin open OASISBuiltinPlugins open BaseMessage open CLISubCommand open Format open FormatExt open Setup open SetupDev open SetupClean open Quickstart open Manual open Check open Query open Version open Help let () = try OASISBuiltinPlugins.init (); CLIArgExt.parse_and_run () with e -> begin if Printexc.backtrace_status () then Printexc.print_backtrace stderr; begin match e with | Failure str -> error "%s" str | e -> begin error "%s" (Printexc.to_string e); if Printexc.backtrace_status () then List.iter (debug "%s") (OASISString.nsplit (Printexc.get_backtrace ()) '\n') end end; exit 1 end
aabad1152dc3b6d0350a2e158246cd24deb4c6e7891b223a2c34b16eec425133
Martoon-00/toy-compiler
Util.hs
| Some utility functions on SM instructions analysis module Toy.SM.Util where import Data.Foldable (Foldable, foldMap) import qualified Data.Set as S import Universum hiding (Foldable, foldMap) import Toy.Base (Var) import Toy.SM.Data (Inst (..)) gatherLocals :: Foldable t => t Inst -> S.Set Var gatherLocals = foldMap gather where gather :: Inst -> S.Set Var gather (Store v) = one v gather _ = mempty
null
https://raw.githubusercontent.com/Martoon-00/toy-compiler/a325d56c367bbb673608d283197fcd51cf5960fa/src/Toy/SM/Util.hs
haskell
| Some utility functions on SM instructions analysis module Toy.SM.Util where import Data.Foldable (Foldable, foldMap) import qualified Data.Set as S import Universum hiding (Foldable, foldMap) import Toy.Base (Var) import Toy.SM.Data (Inst (..)) gatherLocals :: Foldable t => t Inst -> S.Set Var gatherLocals = foldMap gather where gather :: Inst -> S.Set Var gather (Store v) = one v gather _ = mempty
652311fe1283c339a05b6f38d6a5520a9c838a1b5a229ed0d4e87ff6692ab3b6
monadfix/ormolu-live
ForeignSrcLang.hs
# OPTIONS_GHC -fno - warn - orphans # -- | See @GHC.LanguageExtensions@ for an explanation -- on why this is needed module GHC.ForeignSrcLang ( module GHC.ForeignSrcLang.Type ) where import Data.Binary import GHC.ForeignSrcLang.Type instance Binary ForeignSrcLang
null
https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/libraries/ghc-boot/GHC/ForeignSrcLang.hs
haskell
| See @GHC.LanguageExtensions@ for an explanation on why this is needed
# OPTIONS_GHC -fno - warn - orphans # module GHC.ForeignSrcLang ( module GHC.ForeignSrcLang.Type ) where import Data.Binary import GHC.ForeignSrcLang.Type instance Binary ForeignSrcLang
d7292de9030d66d27534fd23216251d14aed6a52d218cdc8fe48e3070e6cc45e
litxio/ptghci
PtgResponse.hs
module Language.Haskell.PtGhci.PtgResponse where import Language.Haskell.PtGhci.Prelude import GHC.Generics import Data.Aeson import Data.Text import Language.Haskell.Ghcid.Types import Language.Haskell.PtGhci.Orphans data PtgResponse = ExecCaptureResponse { success :: Bool , content :: Text } | ExecStreamResponse { success :: Bool , errorMessage :: Maybe Text , syncVal :: Int } | LoadMessagesResponse { success :: Bool , messages :: [Load] } | CompletionResponse { success :: Bool , startChars :: Text , candidates :: [Text] } deriving (Show, Generic) instance ToJSON PtgResponse
null
https://raw.githubusercontent.com/litxio/ptghci/bbb3c5fdf2e73a557864b6b1e26833fffb34fc84/src/Language/Haskell/PtGhci/PtgResponse.hs
haskell
module Language.Haskell.PtGhci.PtgResponse where import Language.Haskell.PtGhci.Prelude import GHC.Generics import Data.Aeson import Data.Text import Language.Haskell.Ghcid.Types import Language.Haskell.PtGhci.Orphans data PtgResponse = ExecCaptureResponse { success :: Bool , content :: Text } | ExecStreamResponse { success :: Bool , errorMessage :: Maybe Text , syncVal :: Int } | LoadMessagesResponse { success :: Bool , messages :: [Load] } | CompletionResponse { success :: Bool , startChars :: Text , candidates :: [Text] } deriving (Show, Generic) instance ToJSON PtgResponse
3fad363221eb7ddd901c999a4170889dd81fb1ddccda48b78fc4a1ded5605eaa
jrm-code-project/LISP-Machine
command-loop.lisp
-*- Mode : LISP ; Package:(SUBDEBUG USE GLOBAL ) ; : CL ; -*- (defvar *command-prefix*) (defvar *get-next-command-unget* nil) (defun unget-command (blip) (setq *get-next-command-unget* (append *get-next-command-unget* (list blip)))) (defconst *activation-list* '(#\/ #\tab #\space #\: #\altmode #\@ #\linefeed #\^ #\= #\page #\: #\. #\_ #\( )) (defun get-next-command () (cond ((null *get-next-command-unget*) (labels ((act-fun (char) (or (ldb-test %%kbd-super char) (member char *activation-list* :test 'char-equal)))) (do (command blip error-p) (()) (multiple-value (command blip) (with-input-editing (terminal-io `((:activation ,#'act-fun) (:preemptable) (:full-rubout :full-rubout) ) ) (do ((out-string (make-string 10. :fill-pointer 0)) (char (send terminal-io :any-tyi) (send terminal-io :any-tyi))) ((or (not (integerp char) (characterp char))) (values out-string char)) (array-push-extend out-string char)))) (cond ((eq blip :full-rubout) (return :full-rubout)) ((consp command) (case (car command) (:typeout-execute (case (cadr command) (lam:force-object-kbd-input (funcall (cadr command) (caddr command) terminal-io)))))) (t (multiple-value (*command-prefix* error-p) (ignore-errors (read-from-string command nil))) (cond (error-p (format t "?? error reading ")) (t (when (not (member (cadr blip) '(#\linefeed #\( ) :test 'char-equal)) (format t "~c" (cadr blip))) (return blip)))))))) (t (pop *get-next-command-unget*)))) (defvar *accumulator*) (defvar *last-command*) (defvar *update-display*) (defvar *current-address*) (defun sd () (let ((*accumulator* nil) (*command-prefix* nil) (*update-display* t) (*read-base* 8) (*print-base* 8) (*last-command* nil) (*current-address* 0) ) (command-loop) )) (defsignal bad-reg-adr error ()) (defsignal sd error ()) (defun command-loop () (format t "~&") (catch 'exit (do-forever (catch-error-restart ((sys:abort error) "Return to top level in SD") (condition-case (error) (do-forever (when *update-display* ;(update-display) (setq *update-display* nil)) (let ((blip (get-next-command))) (cond ((eq blip :full-rubout) (format t " ?? ")) (t (let ((val (sd-eval *command-prefix*))) (when (numberp val) (if (null *accumulator*) (setq *accumulator* 0)) (incf *accumulator* val))) (when (consp blip) (case (car blip) (:activation (let* ((fun-name (format nil "SD-~@:(~:C~)" (cadr blip))) (fun (intern-soft fun-name 'subdebug))) (cond ((fboundp fun) (funcall fun) (setq *last-command* fun) (when (not (memq fun '(sd-@ sd-space sd-.))) (setq *accumulator* nil))) (t (format t "?? ~s " fun-name))))))))))) ((bad-reg-adr sd) (format t "~&Error: ") (send error :report terminal-io) (format t "~&") (setq *accumulator* nil)))) (format t "~&Back to SD top level.~&")))) (defun sd-eval (exp) (cond ((numberp exp) exp) (t nil))) (defun sd-space () )
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/pace/command-loop.lisp
lisp
Package:(SUBDEBUG USE GLOBAL ) ; : CL ; -*- (update-display)
(defvar *command-prefix*) (defvar *get-next-command-unget* nil) (defun unget-command (blip) (setq *get-next-command-unget* (append *get-next-command-unget* (list blip)))) (defconst *activation-list* '(#\/ #\tab #\space #\: #\altmode #\@ #\linefeed #\^ #\= #\page #\: #\. #\_ #\( )) (defun get-next-command () (cond ((null *get-next-command-unget*) (labels ((act-fun (char) (or (ldb-test %%kbd-super char) (member char *activation-list* :test 'char-equal)))) (do (command blip error-p) (()) (multiple-value (command blip) (with-input-editing (terminal-io `((:activation ,#'act-fun) (:preemptable) (:full-rubout :full-rubout) ) ) (do ((out-string (make-string 10. :fill-pointer 0)) (char (send terminal-io :any-tyi) (send terminal-io :any-tyi))) ((or (not (integerp char) (characterp char))) (values out-string char)) (array-push-extend out-string char)))) (cond ((eq blip :full-rubout) (return :full-rubout)) ((consp command) (case (car command) (:typeout-execute (case (cadr command) (lam:force-object-kbd-input (funcall (cadr command) (caddr command) terminal-io)))))) (t (multiple-value (*command-prefix* error-p) (ignore-errors (read-from-string command nil))) (cond (error-p (format t "?? error reading ")) (t (when (not (member (cadr blip) '(#\linefeed #\( ) :test 'char-equal)) (format t "~c" (cadr blip))) (return blip)))))))) (t (pop *get-next-command-unget*)))) (defvar *accumulator*) (defvar *last-command*) (defvar *update-display*) (defvar *current-address*) (defun sd () (let ((*accumulator* nil) (*command-prefix* nil) (*update-display* t) (*read-base* 8) (*print-base* 8) (*last-command* nil) (*current-address* 0) ) (command-loop) )) (defsignal bad-reg-adr error ()) (defsignal sd error ()) (defun command-loop () (format t "~&") (catch 'exit (do-forever (catch-error-restart ((sys:abort error) "Return to top level in SD") (condition-case (error) (do-forever (when *update-display* (setq *update-display* nil)) (let ((blip (get-next-command))) (cond ((eq blip :full-rubout) (format t " ?? ")) (t (let ((val (sd-eval *command-prefix*))) (when (numberp val) (if (null *accumulator*) (setq *accumulator* 0)) (incf *accumulator* val))) (when (consp blip) (case (car blip) (:activation (let* ((fun-name (format nil "SD-~@:(~:C~)" (cadr blip))) (fun (intern-soft fun-name 'subdebug))) (cond ((fboundp fun) (funcall fun) (setq *last-command* fun) (when (not (memq fun '(sd-@ sd-space sd-.))) (setq *accumulator* nil))) (t (format t "?? ~s " fun-name))))))))))) ((bad-reg-adr sd) (format t "~&Error: ") (send error :report terminal-io) (format t "~&") (setq *accumulator* nil)))) (format t "~&Back to SD top level.~&")))) (defun sd-eval (exp) (cond ((numberp exp) exp) (t nil))) (defun sd-space () )
582d1e52c45b0e4421917afe6e6260c74ac46424592df7aac0c22c624392733c
dannypsnl/racket-llvm
info.rkt
#lang info (define collection "racket-llvm") (define deps '("base" "scribble-lib")) (define build-deps '("scribble-lib" "racket-doc" "rackunit-lib" "at-exp-lib")) (define scribblings '(("scribblings/racket-llvm.scrbl" (multi-page)))) (define pkg-desc "LLVM C-API bindings for Racket") (define version "0.0") (define license '(Apache-2.0 OR MIT)) (define pkg-authors '(dannypsnl)) (define test-omit-paths '("examples"))
null
https://raw.githubusercontent.com/dannypsnl/racket-llvm/37392dcf7a48744eceac700c89d7dffb4122a36a/info.rkt
racket
#lang info (define collection "racket-llvm") (define deps '("base" "scribble-lib")) (define build-deps '("scribble-lib" "racket-doc" "rackunit-lib" "at-exp-lib")) (define scribblings '(("scribblings/racket-llvm.scrbl" (multi-page)))) (define pkg-desc "LLVM C-API bindings for Racket") (define version "0.0") (define license '(Apache-2.0 OR MIT)) (define pkg-authors '(dannypsnl)) (define test-omit-paths '("examples"))
5715f84b49d4e8d7c38ea1dce6e284f934f98859ba3792f329b7a9021c857190
coccinelle/coccinelle
pycaml.ml
type pyobject = Py.Object.t type pyobject_type = | TupleType | BytesType | UnicodeType | BoolType | IntType | FloatType | ListType | NoneType | CallableType | ModuleType | ClassType | TypeType | DictType | NullType | CamlpillType | OtherType Signifies that either of BytesType or UnicodeType is allowed . Signifies that only the particular Camlpill variety is allowed . | AnyType let pytype_name t = match t with | TupleType -> "Python-Tuple" | BytesType -> "Python-Bytes" | UnicodeType -> "Python-Unicode" | BoolType -> "Python-Bool" | IntType -> "Python-Int" | FloatType -> "Python-Float" | ListType -> "Python-List" | NoneType -> "Python-None" | CallableType -> "Python-Callable" | ModuleType -> "Python-Module" | ClassType -> "Python-Class" | NullType -> "Python-Null" | TypeType -> "Python-Type" | DictType -> "Python-Dict" | CamlpillType -> "Python-Camlpill" | OtherType -> "Python-Other" | EitherStringType -> "Python-EitherString" | CamlpillSubtype sym -> "Python-Camlpill-" ^ sym | AnyType -> "Python-Any" let _py_type_of_pyobject_type t = match t with | BoolType -> Py.Type.Bool | BytesType -> Py.Type.Bytes | CallableType -> Py.Type.Callable | CamlpillType | CamlpillSubtype _ -> Py.Type.Capsule | DictType -> Py.Type.Dict | FloatType -> Py.Type.Float | ListType -> Py.Type.List | IntType -> Py.Type.Long | ModuleType -> Py.Type.Module | NoneType -> Py.Type.None | NullType -> Py.Type.Null | TupleType -> Py.Type.Tuple | TypeType -> Py.Type.Type | EitherStringType | UnicodeType -> Py.Type.Unicode | AnyType | ClassType | OtherType -> Py.Type.Unknown let pyobject_type_of_py_type t = match t with Py.Type.Unknown | Py.Type.Iter | Py.Type.Set -> OtherType | Py.Type.Bool -> BoolType | Py.Type.Bytes -> BytesType | Py.Type.Callable -> CallableType | Py.Type.Capsule -> CamlpillType | Py.Type.Closure -> CallableType | Py.Type.Dict -> DictType | Py.Type.Float -> FloatType | Py.Type.List -> ListType | Py.Type.Int | Py.Type.Long -> IntType | Py.Type.Module -> ModuleType | Py.Type.None -> NoneType | Py.Type.Null -> NullType | Py.Type.Tuple -> TupleType | Py.Type.Type -> TypeType | Py.Type.Unicode -> UnicodeType type pyerror_type = Pyerr_Exception | Pyerr_StandardError | Pyerr_ArithmeticError | Pyerr_LookupError | Pyerr_AssertionError | Pyerr_AttributeError | Pyerr_EOFError | Pyerr_EnvironmentError | Pyerr_FloatingPointError | Pyerr_IOError | Pyerr_ImportError | Pyerr_IndexError | Pyerr_KeyError | Pyerr_KeyboardInterrupt | Pyerr_MemoryError | Pyerr_NameError | Pyerr_NotImplementedError | Pyerr_OSError | Pyerr_OverflowError | Pyerr_ReferenceError | Pyerr_RuntimeError | Pyerr_SyntaxError | Pyerr_SystemExit | Pyerr_TypeError | Pyerr_ValueError | Pyerr_ZeroDivisionError include Pywrappers.Pycaml exception Pycaml_exn of (pyerror_type * string) let make_pill_wrapping name _instance = Py.Capsule.make name let py_false () = Py.Bool.f let py_finalize = Py.finalize let py_initialize () = Py.initialize () let py_is_true = Py.Object.is_true let py_isinitialized () = if Py.is_initialized () then 1 else 0 let py_setprogramname = Py.set_program_name let py_setpythonhome = Py.set_python_home let py_getprogramname = Py.get_program_name let py_getpythonhome = Py.get_python_home let py_getprogramfullpath = Py.get_program_full_path let py_getprefix = Py.get_prefix let py_getexecprefix = Py.get_exec_prefix let py_getpath = Py.get_path let py_true () = Py.Bool.t let _pycaml_seterror error msg = let error' = match error with Pyerr_Exception -> Py.Err.Exception | Pyerr_StandardError -> Py.Err.StandardError | Pyerr_ArithmeticError -> Py.Err.ArithmeticError | Pyerr_LookupError -> Py.Err.LookupError | Pyerr_AssertionError -> Py.Err.AssertionError | Pyerr_AttributeError -> Py.Err.AttributeError | Pyerr_EOFError -> Py.Err.EOFError | Pyerr_EnvironmentError -> Py.Err.EnvironmentError | Pyerr_FloatingPointError -> Py.Err.FloatingPointError | Pyerr_IOError -> Py.Err.IOError | Pyerr_ImportError -> Py.Err.ImportError | Pyerr_IndexError -> Py.Err.IndexError | Pyerr_KeyError -> Py.Err.KeyError | Pyerr_KeyboardInterrupt -> Py.Err.KeyboardInterrupt | Pyerr_MemoryError -> Py.Err.MemoryError | Pyerr_NameError -> Py.Err.NameError | Pyerr_NotImplementedError -> Py.Err.NotImplementedError | Pyerr_OSError -> Py.Err.OSError | Pyerr_OverflowError -> Py.Err.OverflowError | Pyerr_ReferenceError -> Py.Err.ReferenceError | Pyerr_RuntimeError -> Py.Err.RuntimeError | Pyerr_SyntaxError -> Py.Err.SyntaxError | Pyerr_SystemExit -> Py.Err.SystemExit | Pyerr_TypeError -> Py.Err.TypeError | Pyerr_ValueError -> Py.Err.ValueError | Pyerr_ZeroDivisionError -> Py.Err.ZeroDivisionError in Py.Err.set_error error' msg let int_of_bool b = if b then -1 else 0 let _pybytes_check v = int_of_bool (Py.Type.get v = Py.Type.Bytes) let pybytes_asstring = Py.String.to_string let pybytes_format (fmt, args) = Py.String.format fmt args let pyiter_check v = int_of_bool (Py.Type.get v = Py.Type.Iter) let pymodule_getfilename = Py.Module.get_filename let pymodule_getname = Py.Module.get_name let _pyunicode_check v = int_of_bool (Py.Type.get v = Py.Type.Unicode) let pyerr_fetch _ = match Py.Err.fetch () with None -> (Py.null, Py.null, Py.null) | Some e -> e let pyerr_normalizeexception e = e let pylist_toarray = Py.Sequence.to_array let pyint_asint = Py.Long.to_int let pyint_fromint = Py.Long.of_int let pynone () = Py.none let pynull () = Py.null let pystring_asstring = Py.String.to_string let pystring_fromstring = Py.String.of_string let pytuple_fromarray = Py.Tuple.of_array let pytuple_fromsingle = Py.Tuple.singleton let pytuple_toarray = Py.Tuple.to_array let pytype v = pyobject_type_of_py_type (Py.Type.get v) let register_ocamlpill_types _array = () let pyeval_callobject (func, arg) = Pywrappers.pyeval_callobjectwithkeywords func arg Py.null let pyimport_execcodemodule (obj, s) = Pywrappers.pyimport_execcodemodule s obj let pyimport_importmoduleex (name, globals, locals, fromlist) = Pywrappers.pyimport_importmodulelevel name globals locals fromlist (-1) let py_compilestringflags (str, filename, start, flags) = if Py.version_major () <= 2 then py_compilestringflags (str, filename, start, flags) else py_compilestringexflags (str, filename, start, flags, -1) let py_compilestring (str, filename, start) = py_compilestringflags (str, filename, start, None) let pyrun_anyfile (fd, filename) = pyrun_anyfileexflags (fd, filename, 0, None) let pyrun_anyfileex (fd, filename, closeit) = pyrun_anyfileexflags (fd, filename, closeit, None) let pyrun_file (fd, filename, start, globals, locals) = pyrun_fileexflags (fd, filename, start, globals, locals, 0, None) let pyrun_fileex (fd, filename, start, globals, locals, closeit) = pyrun_fileexflags (fd, filename, start, globals, locals, closeit, None) let pyrun_interactiveone (fd, filename) = pyrun_interactiveoneflags (fd, filename, None) let pyrun_interactiveloop (fd, filename) = pyrun_interactiveloopflags (fd, filename, None) let pyrun_simplefile (fd, filename) = pyrun_simplefileexflags (fd, filename, 0, None) let pyrun_simplefileex (fd, filename, closeit) = pyrun_simplefileexflags (fd, filename, closeit, None) let pyrun_simplestring s = pyrun_simplestringflags (s, None) let pyrun_string (s, start, globals, locals) = pyrun_stringflags (s, start, globals, locals, None) let pywrap_closure f = Py.Callable.of_function_as_tuple f let pytuple_empty = Py.Tuple.empty let pytuple2 = Py.Tuple.of_tuple2 let pytuple3 = Py.Tuple.of_tuple3 let pytuple4 = Py.Tuple.of_tuple4 let pytuple5 = Py.Tuple.of_tuple5 let set_python_argv = Py.set_argv let py_optionally unwrapper py_value = if not (Py.List.check py_value) then Py.Type.mismatch "List" py_value; match Py.List.size py_value with 0 -> None | 1 -> Some (unwrapper (Py.List.get_item py_value 0)) | _ -> Py.Type.mismatch "List of size 0 or 1" py_value let pycallable_asfun = Py.Callable.to_function let guarded_pytuple_toarray = Py.Tuple.to_array let guarded_pylist_toarray = Py.List.to_array let guarded_pybytes_asstring = Py.String.to_string let guarded_pynumber_asfloat = Py.Number.to_float let guarded_pyfloat_asfloat = Py.Float.to_float let guarded_pyint_asint = Py.Long.to_int let ocamlpill_hard_unwrap v = snd (Py.Capsule.unsafe_unwrap_value v) let python_eval = pyrun_simplestring let python_load filename = ignore (Py.Run.load (Py.Filename filename) filename) let pybytes_asstringandsize = Py.String.to_string let pystring_asstringandsize = Py.String.to_string let pyunicode_decodeutf8 (s, errors) = Py.String.decode_UTF8 s ?errors let byteorder_of_int_option byteorder_int = match byteorder_int with None -> None | Some (-1) -> Some Py.LittleEndian | Some 1 -> Some Py.BigEndian | _ -> failwith "pyunicode_decodeutf: invalid byteorder" let pyunicode_decodeutf16 (s, errors, byteorder_int) = let byteorder = byteorder_of_int_option byteorder_int in fst (Py.String.decode_UTF16 s ?errors ?byteorder) let pyunicode_decodeutf32 (s, errors, byteorder_int) = let byteorder = byteorder_of_int_option byteorder_int in fst (Py.String.decode_UTF32 s ?errors ?byteorder) let pyunicode_fromunicode f size = Py.String.of_unicode (Array.init size f) let pyunicode_asunicode = Py.String.to_unicode let pyunicode_getsize = Py.String.length let pyobject_ascharbuffer = Py.Object.as_char_buffer let pyobject_asreadbuffer = Py.Object.as_read_buffer let pyobject_aswritebuffer = Py.Object.as_write_buffer let python () = Py.Run.interactive (); 0 let ipython () = Py.Run.ipython (); 0 let make_ocamlpill_wrapper_unwrapper = make_pill_wrapping let ocamlpill_type_of = Py.Capsule.type_of let type_mismatch_exception type_wanted type_here pos exn_name = Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "Argument %d: Type wanted: %s -- Type provided: %s%s." (pos + 1) (pytype_name type_wanted) (pytype_name type_here) exn_name)) let pill_type_mismatch_exception ?position ?exn_name wanted gotten = let arg_no = match position with None -> "" | Some _p -> "Argument %d: " in let en = match exn_name with None -> "" | Some n -> n in Pycaml_exn (Pyerr_TypeError, Printf.sprintf "%sPython-Ocaml Pill Type mismatch: wanted: '%s' - got: '%s'%s" arg_no wanted gotten en) let check_pill_type ?position ?exn_name wanted pill = let gotten = ocamlpill_type_of pill in if not (gotten = wanted) then raise (pill_type_mismatch_exception ?position:position ?exn_name:exn_name wanted gotten) let unpythonizing_function ?name ?(catch_weird_exceptions = true) ?extra_guards ?(expect_tuple = false) wanted_types function_body = ignore catch_weird_exceptions; let exn_name = match name with None -> "" | Some s -> Printf.sprintf " (%s)" s in let work_fun python_args = let body () = let nr_args_given = if expect_tuple then pytuple_size python_args else 1 in let nr_args_wanted = Array.length wanted_types in let () = if nr_args_given <> nr_args_wanted then raise (Pycaml_exn (Pyerr_IndexError, (Printf.sprintf "Args given: %d Wanted: %d%s" nr_args_given nr_args_wanted exn_name))) in let arr_args = if expect_tuple then Py.Tuple.to_array python_args else [| python_args |] in let rec check_types pos = if pos = nr_args_given then function_body arr_args else let arg = arr_args.(pos) in let type_wanted = wanted_types.(pos) in let () = match type_wanted with | AnyType -> () | EitherStringType -> if not (Py.String.check arg) then raise (type_mismatch_exception type_wanted (pytype arg) pos exn_name) | CamlpillSubtype sym -> check_pill_type ~position:pos ~exn_name:exn_name sym arg | _ -> let type_here = pytype arg in if type_here <> type_wanted then raise (type_mismatch_exception type_wanted type_here pos exn_name) in begin match extra_guards with None -> () | Some guards -> let guard = guards.(pos) in let guard_error = guard arr_args.(pos) in match guard_error with None -> () | Some msg -> raise (Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "Check for argument %d failed: %s%s" (pos + 1) msg exn_name))) end; check_types (pos+1) in check_types 0 in body () in work_fun let py_profiling_active = ref false let py_profile_hash = Stdcompat.Lazy.from_fun (fun () -> Hashtbl.create 100) let py_activate_profiling () = let old_value = !py_profiling_active in py_profiling_active := true; old_value let py_deactivate_profiling () = let old_value = !py_profiling_active in py_profiling_active := false; old_value let py_profile_report () = let add_entry name time_and_calls list = (name, time_and_calls.(0), time_and_calls.(1)) :: list in let items = Hashtbl.fold add_entry (Lazy.force py_profile_hash) [] in let array = Array.of_list items in let order (_, time_a, _) (_, time_b, _) = compare time_b time_a in Array.sort order array; array let py_profile_reset () = Hashtbl.clear (Lazy.force py_profile_hash) let python_interfaced_function ?name ?(catch_weird_exceptions = true) ?doc ?extra_guards wanted_types function_body = let exn_name = match name with None -> "" | Some s -> Printf.sprintf " (%s)" s in let closure = unpythonizing_function ?name ~catch_weird_exceptions ?extra_guards wanted_types function_body in let closure' args = try closure args with Not_found -> let msg = Printf.sprintf "OCaml exception 'Not_found'%s" exn_name in raise (Py.Err (Py.Err.LookupError, msg)) | Division_by_zero -> let msg = Printf.sprintf "OCaml exception 'Division_by_zero'%s" exn_name in raise (Py.Err (Py.Err.ZeroDivisionError, msg)) | Failure s -> let msg = Printf.sprintf "OCaml exception 'Failure: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Invalid_argument s -> let msg = Printf.sprintf "OCaml exception 'Invalid_argument: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Out_of_memory -> let msg = Printf.sprintf "OCaml exception 'Out_of_memory'%s" exn_name in raise (Py.Err (Py.Err.MemoryError, msg)) | Stack_overflow -> let msg = Printf.sprintf "OCaml exception 'Stack_overflow'%s" exn_name in raise (Py.Err (Py.Err.OverflowError, msg)) | Sys_error s -> let msg = Printf.sprintf "OCaml exception 'Sys_error: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | End_of_file -> let msg = Printf.sprintf "OCaml exception 'End_of_file'%s" exn_name in raise (Py.Err (Py.Err.IOError, msg)) | Match_failure (filename, line, column) -> let msg = Printf.sprintf "OCaml exception 'Match_faiure file=%s line=%d(c. %d)'%s" filename line column exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Assert_failure (filename, line, column) -> let msg = Printf.sprintf "OCaml exception 'Assert_faiure file=%s line=%d(c. %d)'%s" filename line column exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Py.E (_, _) | Py.Err (_, _) as e -> raise e | something_else when catch_weird_exceptions -> let msg = Printf.sprintf "OCaml weird low-level exception '%s'%s" (Printexc.to_string something_else) exn_name in raise (Py.Err (Py.Err.StandardError, msg)) in let closure'' = match name with Some s when !py_profiling_active -> let closure'' args = let t0 = Unix.gettimeofday () in let stop_timer () = let t1 = Unix.gettimeofday () in let time_and_calls = let py_profile_hash' = Lazy.force py_profile_hash in try Hashtbl.find py_profile_hash' s with Not_found -> let x = [| 0.; 0. |] in Hashtbl.add py_profile_hash' s x; x in time_and_calls.(0) <- time_and_calls.(0) +. t1 -. t0; time_and_calls.(1) <- time_and_calls.(1) +. 1. in try let result = closure' args in stop_timer (); result with e -> stop_timer (); raise e in closure'' | _ -> closure' in Py.Callable.of_function_as_tuple ?docstring:doc closure'' let python_pre_interfaced_function ?catch_weird_exceptions ?doc ?extra_guards wanted_types function_body name = python_interfaced_function ~name ?catch_weird_exceptions ?doc ?extra_guards wanted_types function_body let pythonize_string = Py.String.of_string let unpythonize_string = Py.String.to_string let py_homogeneous_list_as_array ?error_label ?length type_name type_checker unwrapper list = let the_error_label = match error_label with None -> "" | Some x -> Printf.sprintf "%s: " x in let list_size = Py.List.size list in let () = match length with None -> () | Some length' -> if list_size <> length' then raise (Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "%sExpected list of length %d, got length: %d" the_error_label length' list_size))) in for i = 0 to list_size - 1 do let item = Py.List.get list i in if not (type_checker item) then raise (Pycaml_exn (Pyerr_TypeError, Printf.sprintf "%sExpected homogeneous list of %s. Entry %d is of type %s (%s)!" the_error_label type_name (1 + i) (Py.Type.name (Py.Type.get item)) (Py.Object.string_of_repr item))) done; Py.List.to_array_map unwrapper list let py_float_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "float" Py.Float.check pyfloat_asdouble arr let py_int_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "int" Py.Long.check pyint_asint arr let py_number_list_as_float_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "number" Py.Number.check Py.Number.to_float arr let py_string_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "string" Py.String.check Py.String.to_string arr let py_list_list_as_array_map ?error_label ?length map arr = py_homogeneous_list_as_array ?error_label ?length "<Python List>" Py.List.check map arr let py_list_list_as_array ?error_label ?length arr = py_list_list_as_array_map ?error_label ?length (fun x -> x) arr let py_list_list_as_array2 ?error_label ?length arr = py_list_list_as_array_map ?error_label ?length Py.List.to_array arr let py_float_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_float_list_as_array ?error_label ?length:length_inner) arr let py_number_list_list_as_float_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_number_list_as_float_array ?error_label ?length:length_inner) arr let py_int_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_int_list_as_array ?error_label ?length:length_inner) arr let py_string_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_string_list_as_array ?error_label ?length:length_inner) arr let py_float_tensor ?(init=(fun _ -> 0.0)) index_ranges = let nr_indices = Array.length index_ranges in let v_indices = Array.make nr_indices 0 in if nr_indices = 0 then (pyfloat_fromdouble (init v_indices), fun _ -> failwith "Cannot set rank-0 python float tensor!") else let rec build pos = let range = index_ranges.(pos) in Py.List.init range (fun ix_here -> let () = v_indices.(pos) <- ix_here in if pos = nr_indices-1 then pyfloat_fromdouble (init v_indices) else build (succ pos)) in let structure = build 0 in let setter indices value = let rec walk sub_structure pos = let i = indices.(pos) in if pos = nr_indices-1 then Py.List.set sub_structure i value else walk (Py.List.get sub_structure i) (succ pos) in walk structure 0 in (structure,setter) let int_array_to_python = Py.List.of_array_map Py.Long.of_int let float_array_to_python = Py.List.of_array_map Py.Float.of_float let register_for_python stuff = let ocaml_module = Py.Import.add_module "ocaml" in let register (python_name, value) = Py.Object.set_attr_string ocaml_module python_name value in Array.iter register stuff let register_pre_functions_for_python stuff = let prepare (python_name, pre_fun) = (python_name, pre_fun python_name) in register_for_python (Array.map prepare stuff) let python_last_value = Py.last_value let pywrap_closure_docstring docstring f = Py.Callable.of_function_as_tuple ~docstring f let pyrefcount = Py.Object.reference_count let pylist_get = Py.List.get let pylist_set = Py.List.set let pylist_fromarray = Py.List.of_array let py_repr obj = Py.Object.string_of_repr obj let pyunwrap_value = Py.Capsule.unsafe_unwrap_value let pywrap_value = Py.Capsule.unsafe_wrap_value type funcptr type funcent = funcptr * int * int * bool type pymodule_func = { pyml_name : string ; pyml_func : (pyobject -> pyobject) ; pyml_flags : int ; pyml_doc : string; }
null
https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/bundles/pyml/pyml-current/pycaml.ml
ocaml
type pyobject = Py.Object.t type pyobject_type = | TupleType | BytesType | UnicodeType | BoolType | IntType | FloatType | ListType | NoneType | CallableType | ModuleType | ClassType | TypeType | DictType | NullType | CamlpillType | OtherType Signifies that either of BytesType or UnicodeType is allowed . Signifies that only the particular Camlpill variety is allowed . | AnyType let pytype_name t = match t with | TupleType -> "Python-Tuple" | BytesType -> "Python-Bytes" | UnicodeType -> "Python-Unicode" | BoolType -> "Python-Bool" | IntType -> "Python-Int" | FloatType -> "Python-Float" | ListType -> "Python-List" | NoneType -> "Python-None" | CallableType -> "Python-Callable" | ModuleType -> "Python-Module" | ClassType -> "Python-Class" | NullType -> "Python-Null" | TypeType -> "Python-Type" | DictType -> "Python-Dict" | CamlpillType -> "Python-Camlpill" | OtherType -> "Python-Other" | EitherStringType -> "Python-EitherString" | CamlpillSubtype sym -> "Python-Camlpill-" ^ sym | AnyType -> "Python-Any" let _py_type_of_pyobject_type t = match t with | BoolType -> Py.Type.Bool | BytesType -> Py.Type.Bytes | CallableType -> Py.Type.Callable | CamlpillType | CamlpillSubtype _ -> Py.Type.Capsule | DictType -> Py.Type.Dict | FloatType -> Py.Type.Float | ListType -> Py.Type.List | IntType -> Py.Type.Long | ModuleType -> Py.Type.Module | NoneType -> Py.Type.None | NullType -> Py.Type.Null | TupleType -> Py.Type.Tuple | TypeType -> Py.Type.Type | EitherStringType | UnicodeType -> Py.Type.Unicode | AnyType | ClassType | OtherType -> Py.Type.Unknown let pyobject_type_of_py_type t = match t with Py.Type.Unknown | Py.Type.Iter | Py.Type.Set -> OtherType | Py.Type.Bool -> BoolType | Py.Type.Bytes -> BytesType | Py.Type.Callable -> CallableType | Py.Type.Capsule -> CamlpillType | Py.Type.Closure -> CallableType | Py.Type.Dict -> DictType | Py.Type.Float -> FloatType | Py.Type.List -> ListType | Py.Type.Int | Py.Type.Long -> IntType | Py.Type.Module -> ModuleType | Py.Type.None -> NoneType | Py.Type.Null -> NullType | Py.Type.Tuple -> TupleType | Py.Type.Type -> TypeType | Py.Type.Unicode -> UnicodeType type pyerror_type = Pyerr_Exception | Pyerr_StandardError | Pyerr_ArithmeticError | Pyerr_LookupError | Pyerr_AssertionError | Pyerr_AttributeError | Pyerr_EOFError | Pyerr_EnvironmentError | Pyerr_FloatingPointError | Pyerr_IOError | Pyerr_ImportError | Pyerr_IndexError | Pyerr_KeyError | Pyerr_KeyboardInterrupt | Pyerr_MemoryError | Pyerr_NameError | Pyerr_NotImplementedError | Pyerr_OSError | Pyerr_OverflowError | Pyerr_ReferenceError | Pyerr_RuntimeError | Pyerr_SyntaxError | Pyerr_SystemExit | Pyerr_TypeError | Pyerr_ValueError | Pyerr_ZeroDivisionError include Pywrappers.Pycaml exception Pycaml_exn of (pyerror_type * string) let make_pill_wrapping name _instance = Py.Capsule.make name let py_false () = Py.Bool.f let py_finalize = Py.finalize let py_initialize () = Py.initialize () let py_is_true = Py.Object.is_true let py_isinitialized () = if Py.is_initialized () then 1 else 0 let py_setprogramname = Py.set_program_name let py_setpythonhome = Py.set_python_home let py_getprogramname = Py.get_program_name let py_getpythonhome = Py.get_python_home let py_getprogramfullpath = Py.get_program_full_path let py_getprefix = Py.get_prefix let py_getexecprefix = Py.get_exec_prefix let py_getpath = Py.get_path let py_true () = Py.Bool.t let _pycaml_seterror error msg = let error' = match error with Pyerr_Exception -> Py.Err.Exception | Pyerr_StandardError -> Py.Err.StandardError | Pyerr_ArithmeticError -> Py.Err.ArithmeticError | Pyerr_LookupError -> Py.Err.LookupError | Pyerr_AssertionError -> Py.Err.AssertionError | Pyerr_AttributeError -> Py.Err.AttributeError | Pyerr_EOFError -> Py.Err.EOFError | Pyerr_EnvironmentError -> Py.Err.EnvironmentError | Pyerr_FloatingPointError -> Py.Err.FloatingPointError | Pyerr_IOError -> Py.Err.IOError | Pyerr_ImportError -> Py.Err.ImportError | Pyerr_IndexError -> Py.Err.IndexError | Pyerr_KeyError -> Py.Err.KeyError | Pyerr_KeyboardInterrupt -> Py.Err.KeyboardInterrupt | Pyerr_MemoryError -> Py.Err.MemoryError | Pyerr_NameError -> Py.Err.NameError | Pyerr_NotImplementedError -> Py.Err.NotImplementedError | Pyerr_OSError -> Py.Err.OSError | Pyerr_OverflowError -> Py.Err.OverflowError | Pyerr_ReferenceError -> Py.Err.ReferenceError | Pyerr_RuntimeError -> Py.Err.RuntimeError | Pyerr_SyntaxError -> Py.Err.SyntaxError | Pyerr_SystemExit -> Py.Err.SystemExit | Pyerr_TypeError -> Py.Err.TypeError | Pyerr_ValueError -> Py.Err.ValueError | Pyerr_ZeroDivisionError -> Py.Err.ZeroDivisionError in Py.Err.set_error error' msg let int_of_bool b = if b then -1 else 0 let _pybytes_check v = int_of_bool (Py.Type.get v = Py.Type.Bytes) let pybytes_asstring = Py.String.to_string let pybytes_format (fmt, args) = Py.String.format fmt args let pyiter_check v = int_of_bool (Py.Type.get v = Py.Type.Iter) let pymodule_getfilename = Py.Module.get_filename let pymodule_getname = Py.Module.get_name let _pyunicode_check v = int_of_bool (Py.Type.get v = Py.Type.Unicode) let pyerr_fetch _ = match Py.Err.fetch () with None -> (Py.null, Py.null, Py.null) | Some e -> e let pyerr_normalizeexception e = e let pylist_toarray = Py.Sequence.to_array let pyint_asint = Py.Long.to_int let pyint_fromint = Py.Long.of_int let pynone () = Py.none let pynull () = Py.null let pystring_asstring = Py.String.to_string let pystring_fromstring = Py.String.of_string let pytuple_fromarray = Py.Tuple.of_array let pytuple_fromsingle = Py.Tuple.singleton let pytuple_toarray = Py.Tuple.to_array let pytype v = pyobject_type_of_py_type (Py.Type.get v) let register_ocamlpill_types _array = () let pyeval_callobject (func, arg) = Pywrappers.pyeval_callobjectwithkeywords func arg Py.null let pyimport_execcodemodule (obj, s) = Pywrappers.pyimport_execcodemodule s obj let pyimport_importmoduleex (name, globals, locals, fromlist) = Pywrappers.pyimport_importmodulelevel name globals locals fromlist (-1) let py_compilestringflags (str, filename, start, flags) = if Py.version_major () <= 2 then py_compilestringflags (str, filename, start, flags) else py_compilestringexflags (str, filename, start, flags, -1) let py_compilestring (str, filename, start) = py_compilestringflags (str, filename, start, None) let pyrun_anyfile (fd, filename) = pyrun_anyfileexflags (fd, filename, 0, None) let pyrun_anyfileex (fd, filename, closeit) = pyrun_anyfileexflags (fd, filename, closeit, None) let pyrun_file (fd, filename, start, globals, locals) = pyrun_fileexflags (fd, filename, start, globals, locals, 0, None) let pyrun_fileex (fd, filename, start, globals, locals, closeit) = pyrun_fileexflags (fd, filename, start, globals, locals, closeit, None) let pyrun_interactiveone (fd, filename) = pyrun_interactiveoneflags (fd, filename, None) let pyrun_interactiveloop (fd, filename) = pyrun_interactiveloopflags (fd, filename, None) let pyrun_simplefile (fd, filename) = pyrun_simplefileexflags (fd, filename, 0, None) let pyrun_simplefileex (fd, filename, closeit) = pyrun_simplefileexflags (fd, filename, closeit, None) let pyrun_simplestring s = pyrun_simplestringflags (s, None) let pyrun_string (s, start, globals, locals) = pyrun_stringflags (s, start, globals, locals, None) let pywrap_closure f = Py.Callable.of_function_as_tuple f let pytuple_empty = Py.Tuple.empty let pytuple2 = Py.Tuple.of_tuple2 let pytuple3 = Py.Tuple.of_tuple3 let pytuple4 = Py.Tuple.of_tuple4 let pytuple5 = Py.Tuple.of_tuple5 let set_python_argv = Py.set_argv let py_optionally unwrapper py_value = if not (Py.List.check py_value) then Py.Type.mismatch "List" py_value; match Py.List.size py_value with 0 -> None | 1 -> Some (unwrapper (Py.List.get_item py_value 0)) | _ -> Py.Type.mismatch "List of size 0 or 1" py_value let pycallable_asfun = Py.Callable.to_function let guarded_pytuple_toarray = Py.Tuple.to_array let guarded_pylist_toarray = Py.List.to_array let guarded_pybytes_asstring = Py.String.to_string let guarded_pynumber_asfloat = Py.Number.to_float let guarded_pyfloat_asfloat = Py.Float.to_float let guarded_pyint_asint = Py.Long.to_int let ocamlpill_hard_unwrap v = snd (Py.Capsule.unsafe_unwrap_value v) let python_eval = pyrun_simplestring let python_load filename = ignore (Py.Run.load (Py.Filename filename) filename) let pybytes_asstringandsize = Py.String.to_string let pystring_asstringandsize = Py.String.to_string let pyunicode_decodeutf8 (s, errors) = Py.String.decode_UTF8 s ?errors let byteorder_of_int_option byteorder_int = match byteorder_int with None -> None | Some (-1) -> Some Py.LittleEndian | Some 1 -> Some Py.BigEndian | _ -> failwith "pyunicode_decodeutf: invalid byteorder" let pyunicode_decodeutf16 (s, errors, byteorder_int) = let byteorder = byteorder_of_int_option byteorder_int in fst (Py.String.decode_UTF16 s ?errors ?byteorder) let pyunicode_decodeutf32 (s, errors, byteorder_int) = let byteorder = byteorder_of_int_option byteorder_int in fst (Py.String.decode_UTF32 s ?errors ?byteorder) let pyunicode_fromunicode f size = Py.String.of_unicode (Array.init size f) let pyunicode_asunicode = Py.String.to_unicode let pyunicode_getsize = Py.String.length let pyobject_ascharbuffer = Py.Object.as_char_buffer let pyobject_asreadbuffer = Py.Object.as_read_buffer let pyobject_aswritebuffer = Py.Object.as_write_buffer let python () = Py.Run.interactive (); 0 let ipython () = Py.Run.ipython (); 0 let make_ocamlpill_wrapper_unwrapper = make_pill_wrapping let ocamlpill_type_of = Py.Capsule.type_of let type_mismatch_exception type_wanted type_here pos exn_name = Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "Argument %d: Type wanted: %s -- Type provided: %s%s." (pos + 1) (pytype_name type_wanted) (pytype_name type_here) exn_name)) let pill_type_mismatch_exception ?position ?exn_name wanted gotten = let arg_no = match position with None -> "" | Some _p -> "Argument %d: " in let en = match exn_name with None -> "" | Some n -> n in Pycaml_exn (Pyerr_TypeError, Printf.sprintf "%sPython-Ocaml Pill Type mismatch: wanted: '%s' - got: '%s'%s" arg_no wanted gotten en) let check_pill_type ?position ?exn_name wanted pill = let gotten = ocamlpill_type_of pill in if not (gotten = wanted) then raise (pill_type_mismatch_exception ?position:position ?exn_name:exn_name wanted gotten) let unpythonizing_function ?name ?(catch_weird_exceptions = true) ?extra_guards ?(expect_tuple = false) wanted_types function_body = ignore catch_weird_exceptions; let exn_name = match name with None -> "" | Some s -> Printf.sprintf " (%s)" s in let work_fun python_args = let body () = let nr_args_given = if expect_tuple then pytuple_size python_args else 1 in let nr_args_wanted = Array.length wanted_types in let () = if nr_args_given <> nr_args_wanted then raise (Pycaml_exn (Pyerr_IndexError, (Printf.sprintf "Args given: %d Wanted: %d%s" nr_args_given nr_args_wanted exn_name))) in let arr_args = if expect_tuple then Py.Tuple.to_array python_args else [| python_args |] in let rec check_types pos = if pos = nr_args_given then function_body arr_args else let arg = arr_args.(pos) in let type_wanted = wanted_types.(pos) in let () = match type_wanted with | AnyType -> () | EitherStringType -> if not (Py.String.check arg) then raise (type_mismatch_exception type_wanted (pytype arg) pos exn_name) | CamlpillSubtype sym -> check_pill_type ~position:pos ~exn_name:exn_name sym arg | _ -> let type_here = pytype arg in if type_here <> type_wanted then raise (type_mismatch_exception type_wanted type_here pos exn_name) in begin match extra_guards with None -> () | Some guards -> let guard = guards.(pos) in let guard_error = guard arr_args.(pos) in match guard_error with None -> () | Some msg -> raise (Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "Check for argument %d failed: %s%s" (pos + 1) msg exn_name))) end; check_types (pos+1) in check_types 0 in body () in work_fun let py_profiling_active = ref false let py_profile_hash = Stdcompat.Lazy.from_fun (fun () -> Hashtbl.create 100) let py_activate_profiling () = let old_value = !py_profiling_active in py_profiling_active := true; old_value let py_deactivate_profiling () = let old_value = !py_profiling_active in py_profiling_active := false; old_value let py_profile_report () = let add_entry name time_and_calls list = (name, time_and_calls.(0), time_and_calls.(1)) :: list in let items = Hashtbl.fold add_entry (Lazy.force py_profile_hash) [] in let array = Array.of_list items in let order (_, time_a, _) (_, time_b, _) = compare time_b time_a in Array.sort order array; array let py_profile_reset () = Hashtbl.clear (Lazy.force py_profile_hash) let python_interfaced_function ?name ?(catch_weird_exceptions = true) ?doc ?extra_guards wanted_types function_body = let exn_name = match name with None -> "" | Some s -> Printf.sprintf " (%s)" s in let closure = unpythonizing_function ?name ~catch_weird_exceptions ?extra_guards wanted_types function_body in let closure' args = try closure args with Not_found -> let msg = Printf.sprintf "OCaml exception 'Not_found'%s" exn_name in raise (Py.Err (Py.Err.LookupError, msg)) | Division_by_zero -> let msg = Printf.sprintf "OCaml exception 'Division_by_zero'%s" exn_name in raise (Py.Err (Py.Err.ZeroDivisionError, msg)) | Failure s -> let msg = Printf.sprintf "OCaml exception 'Failure: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Invalid_argument s -> let msg = Printf.sprintf "OCaml exception 'Invalid_argument: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Out_of_memory -> let msg = Printf.sprintf "OCaml exception 'Out_of_memory'%s" exn_name in raise (Py.Err (Py.Err.MemoryError, msg)) | Stack_overflow -> let msg = Printf.sprintf "OCaml exception 'Stack_overflow'%s" exn_name in raise (Py.Err (Py.Err.OverflowError, msg)) | Sys_error s -> let msg = Printf.sprintf "OCaml exception 'Sys_error: %s'%s" s exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | End_of_file -> let msg = Printf.sprintf "OCaml exception 'End_of_file'%s" exn_name in raise (Py.Err (Py.Err.IOError, msg)) | Match_failure (filename, line, column) -> let msg = Printf.sprintf "OCaml exception 'Match_faiure file=%s line=%d(c. %d)'%s" filename line column exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Assert_failure (filename, line, column) -> let msg = Printf.sprintf "OCaml exception 'Assert_faiure file=%s line=%d(c. %d)'%s" filename line column exn_name in raise (Py.Err (Py.Err.StandardError, msg)) | Py.E (_, _) | Py.Err (_, _) as e -> raise e | something_else when catch_weird_exceptions -> let msg = Printf.sprintf "OCaml weird low-level exception '%s'%s" (Printexc.to_string something_else) exn_name in raise (Py.Err (Py.Err.StandardError, msg)) in let closure'' = match name with Some s when !py_profiling_active -> let closure'' args = let t0 = Unix.gettimeofday () in let stop_timer () = let t1 = Unix.gettimeofday () in let time_and_calls = let py_profile_hash' = Lazy.force py_profile_hash in try Hashtbl.find py_profile_hash' s with Not_found -> let x = [| 0.; 0. |] in Hashtbl.add py_profile_hash' s x; x in time_and_calls.(0) <- time_and_calls.(0) +. t1 -. t0; time_and_calls.(1) <- time_and_calls.(1) +. 1. in try let result = closure' args in stop_timer (); result with e -> stop_timer (); raise e in closure'' | _ -> closure' in Py.Callable.of_function_as_tuple ?docstring:doc closure'' let python_pre_interfaced_function ?catch_weird_exceptions ?doc ?extra_guards wanted_types function_body name = python_interfaced_function ~name ?catch_weird_exceptions ?doc ?extra_guards wanted_types function_body let pythonize_string = Py.String.of_string let unpythonize_string = Py.String.to_string let py_homogeneous_list_as_array ?error_label ?length type_name type_checker unwrapper list = let the_error_label = match error_label with None -> "" | Some x -> Printf.sprintf "%s: " x in let list_size = Py.List.size list in let () = match length with None -> () | Some length' -> if list_size <> length' then raise (Pycaml_exn (Pyerr_TypeError, (Printf.sprintf "%sExpected list of length %d, got length: %d" the_error_label length' list_size))) in for i = 0 to list_size - 1 do let item = Py.List.get list i in if not (type_checker item) then raise (Pycaml_exn (Pyerr_TypeError, Printf.sprintf "%sExpected homogeneous list of %s. Entry %d is of type %s (%s)!" the_error_label type_name (1 + i) (Py.Type.name (Py.Type.get item)) (Py.Object.string_of_repr item))) done; Py.List.to_array_map unwrapper list let py_float_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "float" Py.Float.check pyfloat_asdouble arr let py_int_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "int" Py.Long.check pyint_asint arr let py_number_list_as_float_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "number" Py.Number.check Py.Number.to_float arr let py_string_list_as_array ?error_label ?length arr = py_homogeneous_list_as_array ?error_label ?length "string" Py.String.check Py.String.to_string arr let py_list_list_as_array_map ?error_label ?length map arr = py_homogeneous_list_as_array ?error_label ?length "<Python List>" Py.List.check map arr let py_list_list_as_array ?error_label ?length arr = py_list_list_as_array_map ?error_label ?length (fun x -> x) arr let py_list_list_as_array2 ?error_label ?length arr = py_list_list_as_array_map ?error_label ?length Py.List.to_array arr let py_float_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_float_list_as_array ?error_label ?length:length_inner) arr let py_number_list_list_as_float_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_number_list_as_float_array ?error_label ?length:length_inner) arr let py_int_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_int_list_as_array ?error_label ?length:length_inner) arr let py_string_list_list_as_array ?error_label ?length_outer ?length_inner arr = py_list_list_as_array_map ?error_label ?length:length_outer (py_string_list_as_array ?error_label ?length:length_inner) arr let py_float_tensor ?(init=(fun _ -> 0.0)) index_ranges = let nr_indices = Array.length index_ranges in let v_indices = Array.make nr_indices 0 in if nr_indices = 0 then (pyfloat_fromdouble (init v_indices), fun _ -> failwith "Cannot set rank-0 python float tensor!") else let rec build pos = let range = index_ranges.(pos) in Py.List.init range (fun ix_here -> let () = v_indices.(pos) <- ix_here in if pos = nr_indices-1 then pyfloat_fromdouble (init v_indices) else build (succ pos)) in let structure = build 0 in let setter indices value = let rec walk sub_structure pos = let i = indices.(pos) in if pos = nr_indices-1 then Py.List.set sub_structure i value else walk (Py.List.get sub_structure i) (succ pos) in walk structure 0 in (structure,setter) let int_array_to_python = Py.List.of_array_map Py.Long.of_int let float_array_to_python = Py.List.of_array_map Py.Float.of_float let register_for_python stuff = let ocaml_module = Py.Import.add_module "ocaml" in let register (python_name, value) = Py.Object.set_attr_string ocaml_module python_name value in Array.iter register stuff let register_pre_functions_for_python stuff = let prepare (python_name, pre_fun) = (python_name, pre_fun python_name) in register_for_python (Array.map prepare stuff) let python_last_value = Py.last_value let pywrap_closure_docstring docstring f = Py.Callable.of_function_as_tuple ~docstring f let pyrefcount = Py.Object.reference_count let pylist_get = Py.List.get let pylist_set = Py.List.set let pylist_fromarray = Py.List.of_array let py_repr obj = Py.Object.string_of_repr obj let pyunwrap_value = Py.Capsule.unsafe_unwrap_value let pywrap_value = Py.Capsule.unsafe_wrap_value type funcptr type funcent = funcptr * int * int * bool type pymodule_func = { pyml_name : string ; pyml_func : (pyobject -> pyobject) ; pyml_flags : int ; pyml_doc : string; }
14cbcf4da5a139dd75687182143c451d2d7be705ad0e4899465ecf26095f2070
emillon/ocaml-zeit
scale.ml
type t = { current : int ; min : int ; max : int } [@@deriving eq, show, of_yojson]
null
https://raw.githubusercontent.com/emillon/ocaml-zeit/cdcdd0b155d406d1b8c8947e3c620527c3c9ecf7/lib/scale.ml
ocaml
type t = { current : int ; min : int ; max : int } [@@deriving eq, show, of_yojson]
966b545de8df789a696b67d3863c3ad769dc32b172184bcbd1b9f4e91cced85f
nibbula/yew
options.lisp
;;; ;;; options.lisp - Options “pattern”. ;;; ;;; I'm not sure this is actually useful. ;;; ;;; Why would I want some fake Javascript/Smalltalk like prototyping? ;;; Perhaps it's just paranoia about having to reboot my nonexistent Lisp ;;; machine when class versioning somehow fails? ;;; ;;; Options look like a slot, but you're not supposed to really give a damn if ;;; they're there or not. And they don't change the type graph or method ;;; dispatching. (defpackage :options (:documentation "Options “pattern”. For when you might want a new slot in your class, but maybe you don't really want to commit to it, or you'd like it to fail in a different way when you change your mind. To use this, define a subclass of options-mixin, then define your options with: (defoption class option-name type &rest args) For example: (defclass lorry (vehicle options-mixin) ((chassis) (wheels) (motor))) (defoption lorry winch option :load-capacity '(2000 kg)) (defoption lorry plow option :height '(125 cm))") (:use :cl :dlib) (:export #:option #:option-name #:option-value #:options-mixin #:options #:options-prototypes #:find-option #:set-option #:get-option #:defoption)) (in-package :options) (defclass option () ((name :initarg :name :accessor option-name :documentation "Name of the option.") (value :initarg :value :accessor option-value :documentation "Value of the option.") (documentation :initarg :documentation :accessor option-documentation :documentation "Documentation for the option.")) (:documentation "Something like a slot, but more malleable.")) (defclass options-mixin () ((options :initarg :options :accessor options :initform nil :documentation "Optional properties.") ;; (option-prototypes ;; :allocation :class ;; :initarg :option-prototypes ;; :accessor options-prototypes : initform nil : type list ;; :documentation "List of options to be created on a new object.") ) (:documentation "Options mixin.")) (defvar *prototypes* (make-hash-table :test #'equal) "A table of prototypes for classes. The key is a class-name. The value is a list of options.") (defun class-prototype (class) "Return the prototype for ‘class’, or NIL if there isn't one." (gethash (class-name class) *prototypes*)) (defun add-option (class name type args) "Add an option named ‘name’ with the given ‘type’ and other properties in ‘args’ to the prototype for ‘class’." (push (nconc (list type :name name) args) (gethash (class-name (find-class class)) *prototypes*))) (defun class-options (class) "Return a list of the options for ‘class’." (loop :with p :for c :in (mop:compute-class-precedence-list class) :when (setf p (class-prototype c)) :nconc (if (atom p) (list p) p))) (defmethod initialize-options ((o options-mixin)) (let* ((options (class-options (class-of o)))) ;; This isn't useful. The whole point is we can add options later. ;; (when (not options) ;; (warn "There are no options for ~s." (class-name (class-of o)))) (loop :for option :in options :do (when (not (find (getf (cdr option) :name) (options o) :key #'option-name :test #'equalp)) (push (apply #'make-instance (first option) (cdr option)) (options o)))))) (defmethod initialize-instance :after ((o options-mixin) &rest initargs &key &allow-other-keys) "Initialize a options-mixin." (declare (ignore initargs)) ;; Instantiate options from the defined option list. (initialize-options o)) (defgeneric find-option (obj name) (:documentation "Find the option of the object OBJ, named NAME. Error if there is none.") (:method ((obj options-mixin) name) (when (not (options obj)) (initialize-options obj)) (or (find name (options obj) :key #'option-name :test #'equalp) (progn Initialize and try again . (initialize-options obj) (or (find name (options obj) :key #'option-name :test #'equalp) (error "No such option ~s" name)))))) (defgeneric set-option (obj name value) (:documentation "Set the option named NAME, for OBJ, to VALUE.") (:method ((obj options-mixin) name value) (when (not (options obj)) (initialize-options obj)) (setf (option-value (find-option obj name)) value))) (defgeneric get-option (obj name) (:documentation "Get the option named NAME, for OBJ.") (:method ((obj options-mixin) name) (when (not (options obj)) (initialize-options obj)) (option-value (find-option obj name)))) ;; This is pretty messed up. ;; ;; When we define an option we squirrel away it's details in a *global* ;; hashtable keyed by class. Then, when we create an object with options, we ;; look up the prototype in the hash table and instantiate the options, with ;; the initargs given here. ;; ;; It might be nice to hang these on a class allocated slot, but there's no ;; instance around at the time we're defining them. ;; ;; The stupid thing is this: if the defoption is done after the object is ;; created, then the object doesn't have the options, so we have to make them, when we first try to access them . (defmacro defoption (class name type &rest args) "Define an option of ‘type’, named ‘name’ for ‘class’, with the initargs ‘args’." (let* ((sym (symbolify (s+ class "-" name))) (name-string (string-downcase name))) `(progn ;; Access options as if they were in the containing object. (defgeneric ,sym (obj) (:documentation ,(s+ "Return the value of " name-string "."))) (defmethod ,sym ((obj ,class)) (get-option obj ,name-string)) (defgeneric (setf ,sym) (value obj) (:documentation ,(s+ "Set the value of " name-string "."))) (defmethod (setf ,sym) (value (obj ,class)) (set-option obj ,name-string value)) (add-option ',class ,name-string ',type ',args)))) ;; “I have run out of options patterns.” EOF
null
https://raw.githubusercontent.com/nibbula/yew/1a6c0e950574048838ec416a828a0e37c762be6f/lib/options.lisp
lisp
options.lisp - Options “pattern”. I'm not sure this is actually useful. Why would I want some fake Javascript/Smalltalk like prototyping? Perhaps it's just paranoia about having to reboot my nonexistent Lisp machine when class versioning somehow fails? Options look like a slot, but you're not supposed to really give a damn if they're there or not. And they don't change the type graph or method dispatching. (option-prototypes :allocation :class :initarg :option-prototypes :accessor options-prototypes :documentation "List of options to be created on a new object.") This isn't useful. The whole point is we can add options later. (when (not options) (warn "There are no options for ~s." (class-name (class-of o)))) Instantiate options from the defined option list. This is pretty messed up. When we define an option we squirrel away it's details in a *global* hashtable keyed by class. Then, when we create an object with options, we look up the prototype in the hash table and instantiate the options, with the initargs given here. It might be nice to hang these on a class allocated slot, but there's no instance around at the time we're defining them. The stupid thing is this: if the defoption is done after the object is created, then the object doesn't have the options, so we have to make them, Access options as if they were in the containing object. “I have run out of options patterns.”
(defpackage :options (:documentation "Options “pattern”. For when you might want a new slot in your class, but maybe you don't really want to commit to it, or you'd like it to fail in a different way when you change your mind. To use this, define a subclass of options-mixin, then define your options with: (defoption class option-name type &rest args) For example: (defclass lorry (vehicle options-mixin) ((chassis) (wheels) (motor))) (defoption lorry winch option :load-capacity '(2000 kg)) (defoption lorry plow option :height '(125 cm))") (:use :cl :dlib) (:export #:option #:option-name #:option-value #:options-mixin #:options #:options-prototypes #:find-option #:set-option #:get-option #:defoption)) (in-package :options) (defclass option () ((name :initarg :name :accessor option-name :documentation "Name of the option.") (value :initarg :value :accessor option-value :documentation "Value of the option.") (documentation :initarg :documentation :accessor option-documentation :documentation "Documentation for the option.")) (:documentation "Something like a slot, but more malleable.")) (defclass options-mixin () ((options :initarg :options :accessor options :initform nil :documentation "Optional properties.") : initform nil : type list ) (:documentation "Options mixin.")) (defvar *prototypes* (make-hash-table :test #'equal) "A table of prototypes for classes. The key is a class-name. The value is a list of options.") (defun class-prototype (class) "Return the prototype for ‘class’, or NIL if there isn't one." (gethash (class-name class) *prototypes*)) (defun add-option (class name type args) "Add an option named ‘name’ with the given ‘type’ and other properties in ‘args’ to the prototype for ‘class’." (push (nconc (list type :name name) args) (gethash (class-name (find-class class)) *prototypes*))) (defun class-options (class) "Return a list of the options for ‘class’." (loop :with p :for c :in (mop:compute-class-precedence-list class) :when (setf p (class-prototype c)) :nconc (if (atom p) (list p) p))) (defmethod initialize-options ((o options-mixin)) (let* ((options (class-options (class-of o)))) (loop :for option :in options :do (when (not (find (getf (cdr option) :name) (options o) :key #'option-name :test #'equalp)) (push (apply #'make-instance (first option) (cdr option)) (options o)))))) (defmethod initialize-instance :after ((o options-mixin) &rest initargs &key &allow-other-keys) "Initialize a options-mixin." (declare (ignore initargs)) (initialize-options o)) (defgeneric find-option (obj name) (:documentation "Find the option of the object OBJ, named NAME. Error if there is none.") (:method ((obj options-mixin) name) (when (not (options obj)) (initialize-options obj)) (or (find name (options obj) :key #'option-name :test #'equalp) (progn Initialize and try again . (initialize-options obj) (or (find name (options obj) :key #'option-name :test #'equalp) (error "No such option ~s" name)))))) (defgeneric set-option (obj name value) (:documentation "Set the option named NAME, for OBJ, to VALUE.") (:method ((obj options-mixin) name value) (when (not (options obj)) (initialize-options obj)) (setf (option-value (find-option obj name)) value))) (defgeneric get-option (obj name) (:documentation "Get the option named NAME, for OBJ.") (:method ((obj options-mixin) name) (when (not (options obj)) (initialize-options obj)) (option-value (find-option obj name)))) when we first try to access them . (defmacro defoption (class name type &rest args) "Define an option of ‘type’, named ‘name’ for ‘class’, with the initargs ‘args’." (let* ((sym (symbolify (s+ class "-" name))) (name-string (string-downcase name))) `(progn (defgeneric ,sym (obj) (:documentation ,(s+ "Return the value of " name-string "."))) (defmethod ,sym ((obj ,class)) (get-option obj ,name-string)) (defgeneric (setf ,sym) (value obj) (:documentation ,(s+ "Set the value of " name-string "."))) (defmethod (setf ,sym) (value (obj ,class)) (set-option obj ,name-string value)) (add-option ',class ,name-string ',type ',args)))) EOF
2a550265cd2b035b7d7cd594da5f46c7bfa03e3b9df98fe494960c6a77e7da97
esb-lwb/lwb
feature_model.clj
(ns lwb.prop.examples.feature-model (:require [lwb.prop :refer :all] [lwb.prop.cardinality :refer :all] [lwb.prop.sat :refer (sat sat? valid?)] [lwb.prop.cardinality :refer (max-kof)])) ;; Feature Modeling ;; Feature Modeling is a technique to analyze and manage the variability in a ;; product line. In a product line concrete products share certain properties (or features) ;; and differ in other properties. ;; ;; A feature model comprises a feature diagram together with additional constraints. ;; The feature diagram is a tree of features, where subfeatures are properties that realize ;; their super feature. ;; For groups of subfeatures there are four types of relationships : 1 . The subfeatures are mandatory to get the super feature 2 . The subfeatures are optional to get the super feature 3 . At least one of the subfeatures is needed to realize the super feature 4 . Exactly one of the subfeatures realizes the super feature ;; ;; The additional constraints are cross tree constraints, that define integrity conditions ;; for features across the structure of the feature tree. ;; Example: In the book " Mastering Software Variability with FeatureIDE the authors ( , , , Fabian Bendhuhn , , and ) have the example of a software ;; controlling an elevator as running example. The feature model for this software product line is Fig . 5.7 on page 52 of the book . ;; From a feature model is quite straight forward to build a propositional formula that represents ;; the feature model: The features are the variables of the formula, a feature is part of a concrete ;; product if the value of the variable is true, and it is not part of the product if its truth ;; value is false. ;; SAT solvers that solve the satisfiability problem of propositional logic can therefore be ;; used to check whether a configuration of features is valid. They can also determine all possible configurations of products from a given feature model . Tools like the FeatureIDE from the book above use SAT solving for analyzing and managing feature models . Definition of the syntax for a feature model in lwb A feature is denoted by a Clojure symbol , e.g. elevator ;; ;; There are reserved keywords that are used in the head position of lists in the notation of a feature model in lwb . They are : ;; ;; fm (feature model) ;; fm is followed by the name of the root feature as well as feature definitions and cross tree ;; constraints ;; ;; ft (feature) ;; ft is followed by the name of the feature together with all its groups of subfeatures ;; ;; These groups are: ;; man (mandatory) - a group of mandatory subfeatures ;; opt (optional) - a group of optional subfeatures some - of - a group of subfeatures where at least one is mandatory for a valid configuration one - of - a group of subfeatures where exactly one appears in a valid configuration ;; ctc ( cross tree constraint ) ctc is followed by a propositional formula that defines an integrity condition on the ;; features. ;; The example of the feature model for the elevator: (def elevator-model '(fm elevator (ft elevator (man behavior) (opt voice-output call-buttons security safety)) (ft behavior (man modes) (opt service priorities)) (ft call-buttons (one-of directed-call undirected-call)) (ft security (man permission)) (ft safety (opt overloaded)) (ft modes (one-of sabbath fifo shortest-path)) (ft priorities (some-of rush-hour floor-priority person-priority)) (ft permission (some-of floor-permission permission-control)) (ctc (or call-buttons sabbath)) (ctc (impl directed-call shortest-path)) (ctc (impl undirected-call (or fifo shortest-path))))) Functions and Macro for generating the propositional formula for the model (defn opts "Parts of the formula for a group of optional features" [ft opt-expr] (loop [o (next opt-expr) result '()] (if o (recur (next o) (conj result (list 'impl (first o) ft))) result))) (comment (opts 'safety '(opt overloaded onemore)) ) (defn mans "Parts of the formula for a group of mandatory features" [ft man-expr] (loop [m (next man-expr) result '()] (if m (recur (next m) (conj result (list 'equiv ft (first m)))) result))) (comment (mans 'safety '(man overloaded onemore)) ) (defn some-ofs "Parts of the formula for a group of features, where at least one is mandatory" [ft some-of-expr] (list 'equiv ft (concat (list 'or) (next some-of-expr)))) (defn some-ofs' [ft some-of-expr] (list (some-ofs ft some-of-expr))) (comment (some-ofs 'safety '(some-of overloaded onemore x y z)) (some-ofs' 'safety '(some-of overloaded onemore x y z)) ) (defn one-ofs "Parts of the formula for a group of features, where at exactly one is mandatory" [ft one-of-expr] (conj (max-kof 1 (next one-of-expr)) (some-ofs ft one-of-expr))) (comment (one-ofs 'safety '(one-of overloaded onemore x y z)) ) (defn fts "Parts of the formula from a feature definition" [[_ ftname & defs]] (let [fts' (fn [ft & ftgroups] (loop [g ftgroups result '()] (if g (let [func (case (ffirst g) opt opts man mans some-of some-ofs' one-of one-ofs (constantly nil))] (recur (next g) (concat result (func ft (first g))))) result)))] (apply fts' ftname defs))) (comment (fts '(ft renovation-factory (man source-lang impl-lang) (opt x y z))) (fts '(ft size (one-of s5-8 s6-1 s6-5))) ) (defn ctcs "Part of the formula from a cross tree constraint" [[_ fml]] (list fml)) (comment (ctcs '(ctc (or call-buttons sabbath))) ) (defmacro fm "Returns formula according to the given feature model" [rootname & defs] (let [gen-fml (fn [rootname & defs] (loop [d (first defs), result (list 'and rootname)] (if d (let [def (first d) func (case (first def) ft fts ctc ctcs (constantly nil))] (recur (next d) (concat result (func (first d))))) result)))] `(~gen-fml '~rootname '~defs))) (comment (eval elevator-model) ) ;; Using the formula (comment (def elevator-phi (eval elevator-model)) elevator-phi (sat elevator-phi) ; => {rush-hour false, sabbath true, service false, floor-priority false, permission false, priorities false, fifo false, shortest-path false, undirected-call false, security false, modes true, behavior true, directed-call false, floor-permission false, voice-output false, safety false, call-buttons false, elevator true, person-priority false, permission-control false, overloaded false} (eval-phi elevator-phi '{rush-hour false, sabbath true, service false, floor-priority false, permission false, priorities false, fifo false, shortest-path false, undirected-call false, security false, modes true, behavior true, directed-call false, floor-permission false, voice-output false, safety false, call-buttons false, elevator true, person-priority false, permission-control false, overloaded false}) ;=> true ) One more example : the Graph Library from , , , : Feature - oriented Software Product Lines (def gl '(fm graph-library (ft graph-library (man edge-type) (opt search weighted algorithm)) (ft edge-type (one-of directed undirected)) (ft search (one-of bfs dfs)) (ft algorithm (some-of cycle shortest-path mst transpose)) (ft mst (one-of prim kruskal)) (ctc (impl mst (and undirected weighted))) (ctc (impl cycle directed)))) (comment (def gl-phi (eval gl)) gl-phi Compare this with the formula in the book of et al . p.34 (sat gl-phi) ; => {directed true, prim false, kruskal false, cycle false, algorithm false, shortest-path false, edge-type true, transpose false, undirected false, search true, bfs false, graph-library true, dfs true, mst false, weighted false} (eval-phi gl-phi '{directed false, prim true, kruskal false, cycle false, algorithm true, shortest-path false, edge-type true, transpose false, undirected true, search true, bfs true, graph-library true, dfs false, mst true, weighted true}) ; => true (eval-phi gl-phi '{directed false, prim true, kruskal false, cycle true, ;; made true, contradicts ctc algorithm true, shortest-path false, edge-type true, transpose false, undirected true, search true, bfs true, graph-library true, dfs false, mst true, weighted true}) ; => false ) Example iPhone 2019 (def iphone2019 '(fm iphone (ft iphone (man size camera memory color) (opt service)) (ft size (one-of s5-8 s6-1 s6-5)) (ft camera (one-of c3 c2)) (ft memory (one-of m64 m128 m256 m512)) (ft color (one-of cg1 cg2)) (ft cg1 (one-of red purple yellow green black white)) (ft cg2 (one-of spacegrey midnightgreen gold silver)) (ctc (impl (or s5-8 s6-5) c3)) (ctc (impl s6-1 c2)) (ctc (impl c3 cg2)) (ctc (impl c2 cg1)) (ctc (impl c3 (or m64 m256 m512))) (ctc (impl c2 (or m64 m128 m256))))) (comment (def iphone2019-phi (eval iphone2019)) iphone2019-phi (sat iphone2019-phi) ; => {s6-1 false, midnightgreen true, s5-8 false, purple false, silver false, black false, m512 true, service false, color true, m256 false, spacegrey false, c3 true, white false, iphone true, yellow false, green false, memory true, cg2 true, m64 false, m128 false, c2 false, cg1 false, size true, gold false, red false, s6-5 true, camera true} (eval-phi iphone2019-phi '{iphone true size true s5-8 true s6-1 false s6-5 false camera true c3 true c2 false memory true m64 false m128 false m256 true m512 false color true cg1 false red false purple false yellow false green false black false white false cg2 true spacegrey true midnightgreen false gold false silver false service false}) ; => true (eval-phi iphone2019-phi '{iphone true size true s5-8 true s6-1 false s6-5 false camera true c3 true c2 false memory true m64 false m128 false m256 true m512 false color true cg1 true iPhone 11 Pro in red ? ? purple false yellow false green false black false white false cg2 false spacegrey false midnightgreen false gold false silver false service false}) ; => false )
null
https://raw.githubusercontent.com/esb-lwb/lwb/bba51ada7f7316341733d37b0dc4848c4891ef3a/src/lwb/prop/examples/feature_model.clj
clojure
Feature Modeling Feature Modeling is a technique to analyze and manage the variability in a product line. In a product line concrete products share certain properties (or features) and differ in other properties. A feature model comprises a feature diagram together with additional constraints. The feature diagram is a tree of features, where subfeatures are properties that realize their super feature. The additional constraints are cross tree constraints, that define integrity conditions for features across the structure of the feature tree. Example: controlling an elevator as running example. The feature model for this software product line is From a feature model is quite straight forward to build a propositional formula that represents the feature model: The features are the variables of the formula, a feature is part of a concrete product if the value of the variable is true, and it is not part of the product if its truth value is false. used to check whether a configuration of features is valid. They can also determine all There are reserved keywords that are used in the head position of lists in the notation fm (feature model) fm is followed by the name of the root feature as well as feature definitions and cross tree constraints ft (feature) ft is followed by the name of the feature together with all its groups of subfeatures These groups are: man (mandatory) - a group of mandatory subfeatures opt (optional) - a group of optional subfeatures features. The example of the feature model for the elevator: Using the formula => => true => => true made true, contradicts ctc => false => => true => false
(ns lwb.prop.examples.feature-model (:require [lwb.prop :refer :all] [lwb.prop.cardinality :refer :all] [lwb.prop.sat :refer (sat sat? valid?)] [lwb.prop.cardinality :refer (max-kof)])) For groups of subfeatures there are four types of relationships : 1 . The subfeatures are mandatory to get the super feature 2 . The subfeatures are optional to get the super feature 3 . At least one of the subfeatures is needed to realize the super feature 4 . Exactly one of the subfeatures realizes the super feature In the book " Mastering Software Variability with FeatureIDE the authors ( , , , Fabian Bendhuhn , , and ) have the example of a software Fig . 5.7 on page 52 of the book . SAT solvers that solve the satisfiability problem of propositional logic can therefore be possible configurations of products from a given feature model . Tools like the FeatureIDE from the book above use SAT solving for analyzing and managing feature models . Definition of the syntax for a feature model in lwb A feature is denoted by a Clojure symbol , e.g. elevator of a feature model in lwb . They are : some - of - a group of subfeatures where at least one is mandatory for a valid configuration one - of - a group of subfeatures where exactly one appears in a valid configuration ctc ( cross tree constraint ) ctc is followed by a propositional formula that defines an integrity condition on the (def elevator-model '(fm elevator (ft elevator (man behavior) (opt voice-output call-buttons security safety)) (ft behavior (man modes) (opt service priorities)) (ft call-buttons (one-of directed-call undirected-call)) (ft security (man permission)) (ft safety (opt overloaded)) (ft modes (one-of sabbath fifo shortest-path)) (ft priorities (some-of rush-hour floor-priority person-priority)) (ft permission (some-of floor-permission permission-control)) (ctc (or call-buttons sabbath)) (ctc (impl directed-call shortest-path)) (ctc (impl undirected-call (or fifo shortest-path))))) Functions and Macro for generating the propositional formula for the model (defn opts "Parts of the formula for a group of optional features" [ft opt-expr] (loop [o (next opt-expr) result '()] (if o (recur (next o) (conj result (list 'impl (first o) ft))) result))) (comment (opts 'safety '(opt overloaded onemore)) ) (defn mans "Parts of the formula for a group of mandatory features" [ft man-expr] (loop [m (next man-expr) result '()] (if m (recur (next m) (conj result (list 'equiv ft (first m)))) result))) (comment (mans 'safety '(man overloaded onemore)) ) (defn some-ofs "Parts of the formula for a group of features, where at least one is mandatory" [ft some-of-expr] (list 'equiv ft (concat (list 'or) (next some-of-expr)))) (defn some-ofs' [ft some-of-expr] (list (some-ofs ft some-of-expr))) (comment (some-ofs 'safety '(some-of overloaded onemore x y z)) (some-ofs' 'safety '(some-of overloaded onemore x y z)) ) (defn one-ofs "Parts of the formula for a group of features, where at exactly one is mandatory" [ft one-of-expr] (conj (max-kof 1 (next one-of-expr)) (some-ofs ft one-of-expr))) (comment (one-ofs 'safety '(one-of overloaded onemore x y z)) ) (defn fts "Parts of the formula from a feature definition" [[_ ftname & defs]] (let [fts' (fn [ft & ftgroups] (loop [g ftgroups result '()] (if g (let [func (case (ffirst g) opt opts man mans some-of some-ofs' one-of one-ofs (constantly nil))] (recur (next g) (concat result (func ft (first g))))) result)))] (apply fts' ftname defs))) (comment (fts '(ft renovation-factory (man source-lang impl-lang) (opt x y z))) (fts '(ft size (one-of s5-8 s6-1 s6-5))) ) (defn ctcs "Part of the formula from a cross tree constraint" [[_ fml]] (list fml)) (comment (ctcs '(ctc (or call-buttons sabbath))) ) (defmacro fm "Returns formula according to the given feature model" [rootname & defs] (let [gen-fml (fn [rootname & defs] (loop [d (first defs), result (list 'and rootname)] (if d (let [def (first d) func (case (first def) ft fts ctc ctcs (constantly nil))] (recur (next d) (concat result (func (first d))))) result)))] `(~gen-fml '~rootname '~defs))) (comment (eval elevator-model) ) (comment (def elevator-phi (eval elevator-model)) elevator-phi (sat elevator-phi) {rush-hour false, sabbath true, service false, floor-priority false, permission false, priorities false, fifo false, shortest-path false, undirected-call false, security false, modes true, behavior true, directed-call false, floor-permission false, voice-output false, safety false, call-buttons false, elevator true, person-priority false, permission-control false, overloaded false} (eval-phi elevator-phi '{rush-hour false, sabbath true, service false, floor-priority false, permission false, priorities false, fifo false, shortest-path false, undirected-call false, security false, modes true, behavior true, directed-call false, floor-permission false, voice-output false, safety false, call-buttons false, elevator true, person-priority false, permission-control false, overloaded false}) ) One more example : the Graph Library from , , , : Feature - oriented Software Product Lines (def gl '(fm graph-library (ft graph-library (man edge-type) (opt search weighted algorithm)) (ft edge-type (one-of directed undirected)) (ft search (one-of bfs dfs)) (ft algorithm (some-of cycle shortest-path mst transpose)) (ft mst (one-of prim kruskal)) (ctc (impl mst (and undirected weighted))) (ctc (impl cycle directed)))) (comment (def gl-phi (eval gl)) gl-phi Compare this with the formula in the book of et al . p.34 (sat gl-phi) {directed true, prim false, kruskal false, cycle false, algorithm false, shortest-path false, edge-type true, transpose false, undirected false, search true, bfs false, graph-library true, dfs true, mst false, weighted false} (eval-phi gl-phi '{directed false, prim true, kruskal false, cycle false, algorithm true, shortest-path false, edge-type true, transpose false, undirected true, search true, bfs true, graph-library true, dfs false, mst true, weighted true}) (eval-phi gl-phi '{directed false, prim true, kruskal false, algorithm true, shortest-path false, edge-type true, transpose false, undirected true, search true, bfs true, graph-library true, dfs false, mst true, weighted true}) ) Example iPhone 2019 (def iphone2019 '(fm iphone (ft iphone (man size camera memory color) (opt service)) (ft size (one-of s5-8 s6-1 s6-5)) (ft camera (one-of c3 c2)) (ft memory (one-of m64 m128 m256 m512)) (ft color (one-of cg1 cg2)) (ft cg1 (one-of red purple yellow green black white)) (ft cg2 (one-of spacegrey midnightgreen gold silver)) (ctc (impl (or s5-8 s6-5) c3)) (ctc (impl s6-1 c2)) (ctc (impl c3 cg2)) (ctc (impl c2 cg1)) (ctc (impl c3 (or m64 m256 m512))) (ctc (impl c2 (or m64 m128 m256))))) (comment (def iphone2019-phi (eval iphone2019)) iphone2019-phi (sat iphone2019-phi) {s6-1 false, midnightgreen true, s5-8 false, purple false, silver false, black false, m512 true, service false, color true, m256 false, spacegrey false, c3 true, white false, iphone true, yellow false, green false, memory true, cg2 true, m64 false, m128 false, c2 false, cg1 false, size true, gold false, red false, s6-5 true, camera true} (eval-phi iphone2019-phi '{iphone true size true s5-8 true s6-1 false s6-5 false camera true c3 true c2 false memory true m64 false m128 false m256 true m512 false color true cg1 false red false purple false yellow false green false black false white false cg2 true spacegrey true midnightgreen false gold false silver false service false}) (eval-phi iphone2019-phi '{iphone true size true s5-8 true s6-1 false s6-5 false camera true c3 true c2 false memory true m64 false m128 false m256 true m512 false color true cg1 true iPhone 11 Pro in red ? ? purple false yellow false green false black false white false cg2 false spacegrey false midnightgreen false gold false silver false service false}) )
160c01784620321be56e9216465be350bebfdd2cf9eddf1296637f2051e71d90
avsm/platform
comment_in_empty.ml
module M = struct (* this module is empty *) end module type M = sig (* this module type is empty *) end class type m = object (* this class type is empty *) end let x = object (* this object is empty *) end let _ = [ (* this list is empty *) ] let _ = (* this list is empty2 *) [] let _ = (* this list is empty2 *) [] let _ = [| (* this array is empty *) |] let _ = f ( (* comment in unit *) ) te""st let x = function | [ (* empty list pat *) ] |[| (* empty array pat *) |] |( (* unit pat *) ) | "" (* comment *) -> () let x = object method x () = {< (* this override is empty *) >} end type t = private [> (*this variant is empty *) ] type t = < (* this object type is empty *) > type t = < .. (* this object type is empty *) > let x = ipsum dolor sit amet , adipiscing elit . risus . Suspendisse lectus tortor , dignissim sit amet , adipiscing nec , ultricies sed , dolor . risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. *) ) let x = ipsum dolor sit amet , adipiscing elit . risus . Suspendisse lectus tortor , dignissim sit amet , adipiscing nec , ultricies sed , dolor . risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. *) ]
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/ocamlformat.0.12/test/passing/comment_in_empty.ml
ocaml
this module is empty this module type is empty this class type is empty this object is empty this list is empty this list is empty2 this list is empty2 this array is empty comment in unit empty list pat empty array pat unit pat comment this override is empty this variant is empty this object type is empty this object type is empty
module M = struct end module type M = sig end te""st let x = function () let x = object end let x = ipsum dolor sit amet , adipiscing elit . risus . Suspendisse lectus tortor , dignissim sit amet , adipiscing nec , ultricies sed , dolor . risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. *) ) let x = ipsum dolor sit amet , adipiscing elit . risus . Suspendisse lectus tortor , dignissim sit amet , adipiscing nec , ultricies sed , dolor . risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. *) ]
8c55c21a1814240b10160544c664f401cae5fb9d3821edfd50ca82624c9fb535
dannywillems/RML
typer.mli
(** [type_of context term] returns the type of terms with the typing derivation tree. *) val type_of : ?context:ContextType.context -> Grammar.nominal_term -> DerivationTree.typing_node DerivationTree.t * Grammar.nominal_typ
null
https://raw.githubusercontent.com/dannywillems/RML/357be3ddac1f6d38b638248d37a877b4f6f802ea/src/typing/typer.mli
ocaml
* [type_of context term] returns the type of terms with the typing derivation tree.
val type_of : ?context:ContextType.context -> Grammar.nominal_term -> DerivationTree.typing_node DerivationTree.t * Grammar.nominal_typ
ef310abdc051896e150db2b78fbe6d20abcd5454a5b7a9602115a4e82b1c1da6
tebello-thejane/bitx.hs
LensSpec.hs
# LANGUAGE OverloadedStrings , module Network.Bitcoin.BitX.Spec.Specs.LensSpec ( spec ) where import Test.Hspec import Lens.Micro import qualified Network.Bitcoin.BitX as BitX import Network.Bitcoin.BitX.Types import Data.Time.Clock.POSIX # ANN module ( " HLint : ignore Reduce duplication " : : String ) # spec :: Spec spec = describe "Lens functionality test" $ it "This file should just compile" $ True `shouldBe` True -- If this file compiles, then (hopefully) all the Has* classes have been created and exported properly _bitXError :: Maybe Int _bitXError = do let x = BitX.BitXError "" "" let _ = x ^. BitX.error let _ = x ^. BitX.errorCode Nothing _ticker :: Maybe Int _ticker = do let x = BitX.Ticker (posixSecondsToUTCTime 0) Nothing Nothing Nothing 0 XBTZAR let _ = x ^. BitX.timestamp let _ = x ^. BitX.bid let _ = x ^. BitX.ask let _ = x ^. BitX.lastTrade let _ = x ^. BitX.rolling24HourVolume let _ = x ^. BitX.pair Nothing _order :: Maybe Int _order = do let x = BitX.Order 0 0 let _ = x ^. BitX.volume let _ = x ^. BitX.price Nothing _orderbook :: Maybe Int _orderbook = do let x = BitX.Orderbook (posixSecondsToUTCTime 0) [BitX.Order 0 0] [BitX.Order 0 0] let _ = x ^. BitX.timestamp let _ = x ^. BitX.asks let _ = x ^. BitX.bids Nothing _trade :: Maybe Int _trade = do let x = BitX.Trade (posixSecondsToUTCTime 0) 0 0 False let _ = x ^. BitX.timestamp let _ = x ^. BitX.volume let _ = x ^. BitX.price let _ = x ^. BitX.isBuy Nothing _bitXAuth :: Maybe Int _bitXAuth = do let x = BitX.BitXAuth "" "" let _ = x ^. BitX.id let _ = x ^. BitX.secret Nothing _privateOrder :: Maybe Int _privateOrder = do let x = BitX.PrivateOrder 0 0 (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) 0 0 0 0 "" XBTZAR PENDING ASK let _ = x ^. BitX.base let _ = x ^. BitX.counter let _ = x ^. BitX.creationTimestamp let _ = x ^. BitX.feeBase let _ = x ^. BitX.feeCounter let _ = x ^. BitX.limitPrice let _ = x ^. BitX.limitVolume let _ = x ^. BitX.id let _ = x ^. BitX.pair let _ = x ^. BitX.state let _ = x ^. BitX.orderType let _ = x ^. BitX.expirationTimestamp let _ = x ^. BitX.completedTimestamp Nothing _transaction :: Maybe Int _transaction = do let x = BitX.Transaction 0 (posixSecondsToUTCTime 0) 0 0 0 0 ZAR "" let _ = x ^. BitX.rowIndex let _ = x ^. BitX.timestamp let _ = x ^. BitX.balance let _ = x ^. BitX.available let _ = x ^. BitX.balanceDelta let _ = x ^. BitX.availableDelta let _ = x ^. BitX.currency let _ = x ^. BitX.description Nothing _balance :: Maybe Int _balance = do let x = BitX.Balance "" ZAR 0 0 0 let _ = x ^. BitX.id let _ = x ^. BitX.asset let _ = x ^. BitX.balance let _ = x ^. BitX.reserved let _ = x ^. BitX.unconfirmed Nothing _fundingAddress :: Maybe Int _fundingAddress = do let x = BitX.FundingAddress ZAR "" 0 0 let _ = x ^. BitX.asset let _ = x ^. BitX.address let _ = x ^. BitX.totalReceived let _ = x ^. BitX.totalUnconfirmed Nothing _newWithdrawal :: Maybe Int _newWithdrawal = do let x = BitX.NewWithdrawal ZAR_EFT 0 Nothing let _ = x ^. BitX.withdrawalType let _ = x ^. BitX.amount let _ = x ^. BitX.beneficiaryId Nothing _bitcoinSendRequest :: Maybe Int _bitcoinSendRequest = do let x = BitX.BitcoinSendRequest 0 ZAR "" (Just "") (Just "") let _ = x ^. BitX.amount let _ = x ^. BitX.currency let _ = x ^. BitX.address let _ = x ^. BitX.description let _ = x ^. BitX.message Nothing _orderQuote :: Maybe Int _orderQuote = do let x = BitX.OrderQuote "" BUY XBTZAR 0 0 (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) False False let _ = x ^. BitX.id let _ = x ^. BitX.quoteType let _ = x ^. BitX.pair let _ = x ^. BitX.baseAmount let _ = x ^. BitX.counterAmount let _ = x ^. BitX.createdAt let _ = x ^. BitX.expiresAt let _ = x ^. BitX.discarded let _ = x ^. BitX.exercised Nothing _account :: Maybe Int _account = do let x = BitX.Account "" "" ZAR let _ = x ^. BitX.id let _ = x ^. BitX.name let _ = x ^. BitX.currency Nothing _marketOrderRequest :: Maybe Int _marketOrderRequest = do let x = BitX.MarketOrderRequest XBTZAR BID 0 let _ = x ^. BitX.pair let _ = x ^. BitX.orderType let _ = x ^. BitX.volume Nothing _withdrawalRequest :: Maybe Int _withdrawalRequest = do let x = BitX.WithdrawalRequest PENDING "" let _ = x ^. BitX.status let _ = x ^. BitX.id Nothing _privateTrade :: Maybe Int _privateTrade = do let x = BitX.PrivateTrade 0 0 0 0 True "" XBTZAR 0 (posixSecondsToUTCTime 0) BID 0 let _ = x ^. BitX.base let _ = x ^. BitX.counter let _ = x ^. BitX.feeBase let _ = x ^. BitX.feeCounter let _ = x ^. BitX.isBuy let _ = x ^. BitX.orderId let _ = x ^. BitX.pair let _ = x ^. BitX.price let _ = x ^. BitX.timestamp let _ = x ^. BitX.orderType let _ = x ^. BitX.volume Nothing _feeInfo :: Maybe Int _feeInfo = do let x = BitX.FeeInfo 0 0 0 let _ = x ^. BitX.makerFee let _ = x ^. BitX.takerFee let _ = x ^. BitX.thirtyDayVolume Nothing
null
https://raw.githubusercontent.com/tebello-thejane/bitx.hs/d5b1211656192b90381732ee31ca631e5031041b/test/Network/Bitcoin/BitX/Spec/Specs/LensSpec.hs
haskell
If this file compiles, then (hopefully) all the Has* classes have been created and exported properly
# LANGUAGE OverloadedStrings , module Network.Bitcoin.BitX.Spec.Specs.LensSpec ( spec ) where import Test.Hspec import Lens.Micro import qualified Network.Bitcoin.BitX as BitX import Network.Bitcoin.BitX.Types import Data.Time.Clock.POSIX # ANN module ( " HLint : ignore Reduce duplication " : : String ) # spec :: Spec spec = describe "Lens functionality test" $ it "This file should just compile" $ True `shouldBe` True _bitXError :: Maybe Int _bitXError = do let x = BitX.BitXError "" "" let _ = x ^. BitX.error let _ = x ^. BitX.errorCode Nothing _ticker :: Maybe Int _ticker = do let x = BitX.Ticker (posixSecondsToUTCTime 0) Nothing Nothing Nothing 0 XBTZAR let _ = x ^. BitX.timestamp let _ = x ^. BitX.bid let _ = x ^. BitX.ask let _ = x ^. BitX.lastTrade let _ = x ^. BitX.rolling24HourVolume let _ = x ^. BitX.pair Nothing _order :: Maybe Int _order = do let x = BitX.Order 0 0 let _ = x ^. BitX.volume let _ = x ^. BitX.price Nothing _orderbook :: Maybe Int _orderbook = do let x = BitX.Orderbook (posixSecondsToUTCTime 0) [BitX.Order 0 0] [BitX.Order 0 0] let _ = x ^. BitX.timestamp let _ = x ^. BitX.asks let _ = x ^. BitX.bids Nothing _trade :: Maybe Int _trade = do let x = BitX.Trade (posixSecondsToUTCTime 0) 0 0 False let _ = x ^. BitX.timestamp let _ = x ^. BitX.volume let _ = x ^. BitX.price let _ = x ^. BitX.isBuy Nothing _bitXAuth :: Maybe Int _bitXAuth = do let x = BitX.BitXAuth "" "" let _ = x ^. BitX.id let _ = x ^. BitX.secret Nothing _privateOrder :: Maybe Int _privateOrder = do let x = BitX.PrivateOrder 0 0 (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) 0 0 0 0 "" XBTZAR PENDING ASK let _ = x ^. BitX.base let _ = x ^. BitX.counter let _ = x ^. BitX.creationTimestamp let _ = x ^. BitX.feeBase let _ = x ^. BitX.feeCounter let _ = x ^. BitX.limitPrice let _ = x ^. BitX.limitVolume let _ = x ^. BitX.id let _ = x ^. BitX.pair let _ = x ^. BitX.state let _ = x ^. BitX.orderType let _ = x ^. BitX.expirationTimestamp let _ = x ^. BitX.completedTimestamp Nothing _transaction :: Maybe Int _transaction = do let x = BitX.Transaction 0 (posixSecondsToUTCTime 0) 0 0 0 0 ZAR "" let _ = x ^. BitX.rowIndex let _ = x ^. BitX.timestamp let _ = x ^. BitX.balance let _ = x ^. BitX.available let _ = x ^. BitX.balanceDelta let _ = x ^. BitX.availableDelta let _ = x ^. BitX.currency let _ = x ^. BitX.description Nothing _balance :: Maybe Int _balance = do let x = BitX.Balance "" ZAR 0 0 0 let _ = x ^. BitX.id let _ = x ^. BitX.asset let _ = x ^. BitX.balance let _ = x ^. BitX.reserved let _ = x ^. BitX.unconfirmed Nothing _fundingAddress :: Maybe Int _fundingAddress = do let x = BitX.FundingAddress ZAR "" 0 0 let _ = x ^. BitX.asset let _ = x ^. BitX.address let _ = x ^. BitX.totalReceived let _ = x ^. BitX.totalUnconfirmed Nothing _newWithdrawal :: Maybe Int _newWithdrawal = do let x = BitX.NewWithdrawal ZAR_EFT 0 Nothing let _ = x ^. BitX.withdrawalType let _ = x ^. BitX.amount let _ = x ^. BitX.beneficiaryId Nothing _bitcoinSendRequest :: Maybe Int _bitcoinSendRequest = do let x = BitX.BitcoinSendRequest 0 ZAR "" (Just "") (Just "") let _ = x ^. BitX.amount let _ = x ^. BitX.currency let _ = x ^. BitX.address let _ = x ^. BitX.description let _ = x ^. BitX.message Nothing _orderQuote :: Maybe Int _orderQuote = do let x = BitX.OrderQuote "" BUY XBTZAR 0 0 (posixSecondsToUTCTime 0) (posixSecondsToUTCTime 0) False False let _ = x ^. BitX.id let _ = x ^. BitX.quoteType let _ = x ^. BitX.pair let _ = x ^. BitX.baseAmount let _ = x ^. BitX.counterAmount let _ = x ^. BitX.createdAt let _ = x ^. BitX.expiresAt let _ = x ^. BitX.discarded let _ = x ^. BitX.exercised Nothing _account :: Maybe Int _account = do let x = BitX.Account "" "" ZAR let _ = x ^. BitX.id let _ = x ^. BitX.name let _ = x ^. BitX.currency Nothing _marketOrderRequest :: Maybe Int _marketOrderRequest = do let x = BitX.MarketOrderRequest XBTZAR BID 0 let _ = x ^. BitX.pair let _ = x ^. BitX.orderType let _ = x ^. BitX.volume Nothing _withdrawalRequest :: Maybe Int _withdrawalRequest = do let x = BitX.WithdrawalRequest PENDING "" let _ = x ^. BitX.status let _ = x ^. BitX.id Nothing _privateTrade :: Maybe Int _privateTrade = do let x = BitX.PrivateTrade 0 0 0 0 True "" XBTZAR 0 (posixSecondsToUTCTime 0) BID 0 let _ = x ^. BitX.base let _ = x ^. BitX.counter let _ = x ^. BitX.feeBase let _ = x ^. BitX.feeCounter let _ = x ^. BitX.isBuy let _ = x ^. BitX.orderId let _ = x ^. BitX.pair let _ = x ^. BitX.price let _ = x ^. BitX.timestamp let _ = x ^. BitX.orderType let _ = x ^. BitX.volume Nothing _feeInfo :: Maybe Int _feeInfo = do let x = BitX.FeeInfo 0 0 0 let _ = x ^. BitX.makerFee let _ = x ^. BitX.takerFee let _ = x ^. BitX.thirtyDayVolume Nothing
b04f55707cf61b0c7e8df066b1593f58f763ffff739db542628983e7c751534f
fpco/ide-backend
TestPkgE.hs
module Testing.TestPkgE where testPkgE :: String testPkgE = "This is test package E-0.2"
null
https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/test-packages/testpkg-E-0.2/Testing/TestPkgE.hs
haskell
module Testing.TestPkgE where testPkgE :: String testPkgE = "This is test package E-0.2"
181134f96d57d03d7f46f16f23322efdb6e7ba3f94eb84e3b8e284e1985f77b5
LonoCloud/step.async
pschema.clj
(ns lonocloud.step.async.pschema (:refer-clojure :exclude [defn defn- fn]) (:require [clojure.pprint :as pprint :refer [pprint]] [schema.core :as s] [schema.utils :as schema-utils]) (:import [schema.core OptionalKey])) (def eq s/eq) (def enum s/enum) (def Int s/Int) (ns-unmap *ns* 'Number) (def Num s/Num) (def maybe s/maybe) (def Any s/Any) (def Map {s/Any s/Any}) (def Keyword s/Keyword) (def Fn (s/pred fn?)) (def Ref clojure.lang.Ref) (def Atom clojure.lang.Atom) (def either s/either) (def Schema s/Schema) (def one s/one) (def required-key s/required-key) (def optional-key s/optional-key) (def optional-key? s/optional-key?) (def Inst s/Inst) (def check s/check) (def explain s/explain) (def validate s/validate) (def optional s/optional) ;; (def error "helper when writing custom type checkers" schema-utils/error) (defmacro satisfies-protocol [t p] `(deftype ~t [] s/Schema (walker [this#] (clojure.core/fn [x#] (if (satisfies? ~p x#) x# (schema-utils/error [x# 'not (str (:on ~p))])))) (explain [this#] (str (:on ~p))))) (clojure.core/defn analyze-defn-params "Produce [type comment params body]" [[a1 a2 a3 a4 :as params]] (if (= :- a1) (if (string? a3) (let [[_ _ _ _ & body] params] [a2 a3 a4 body]) (let [[_ _ _ & body] params] [a2 nil a3 body])) (if (string? a1) (let [[_ _ & body] params] [nil a1 a2 body]) (let [[_ & body] params] [nil nil a1 body])))) (defmacro defn [name & more] (let [[type comment-str params body] (analyze-defn-params more)] (if type (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) :- ~type ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) :- ~type ~params ~@body)) (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) ~params ~@body))))) (defmacro defn- [name & more] (let [[type comment-str params body] (analyze-defn-params more)] (if type (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) :- ~type ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) :- ~type ~params ~@body)) (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) ~params ~@body))))) (defmulti to-key class) (defmethod to-key clojure.lang.Keyword ;; NOTE: Keyword is shadowed above, so must fully qualify here [k] k) (defmethod to-key OptionalKey [k] (:k k)) (defn get-type-keys [m] (map to-key (keys m))) (comment (pprint (defnx foo :- String "this is " [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo :- String [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo "this is " [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo [a] (+ 1 2) {:a 10})) ) ;; typed functions (defn simplify-schema "Convert a function schema to a simpler representation containing only what must be checked" [schema] (let [{:keys [input-schemas output-schema]} schema] {:output-schema (when output-schema (s/explain output-schema)) :input-schemas (vec (map (comp vec s/explain-input-schema) input-schemas))})) (defn- get-schema-of "Lookup the schema type of a function." [f] (simplify-schema (schema-utils/class-schema (class f)))) (defn- vararg-type "Check a single input schema and if it contains a varargs, return the element type of the vararg" [schema] (let [n (count schema) start-n (max (- n 2) 0) [l1 l2] (drop start-n schema)] (when (= '& l1) (first l2)))) (defn- expand-var-arg-to "'Unroll' part of a vararg (if present) in the source to make the source input schema the same length as the target schema. Note: the schemas in this case are individual arities." [source target] (let [target-count (count target) n (count source) start-n (max (- n 2) 0) start (take start-n source)] (if-let [source-vararg-type (vararg-type source)] (if-let [target-vararg-type (vararg-type target)] (if (and (= source-vararg-type target-vararg-type) (< n target-count)) (reduce into (vec start) [(repeat (max (- target-count start-n 2) 0) source-vararg-type) ['& [source-vararg-type]]]) source) (into (vec start) (repeat (max (- target-count start-n) 0) source-vararg-type))) source))) (defn- arg-matches [schema-field target-field] (or (= schema-field target-field) (if (or (= schema-field '&) (= target-field '&)) false (and (= target-field {'Any 'Any}) (map? schema-field))))) (defn- matches? [schema target] (and (= (count schema) (count target)) (->> (map arg-matches schema target) (every? identity)))) (defn- is-matching-schema? "Determine if there are any schemas in the choices that matches the target schema." [choices target] (->> choices (map #(expand-var-arg-to % target)) (some #(matches? % target)))) (defn is-schema-a? "Determine if the child function schema is a sub-type of the parent function schema." [child parent] (let [parent-out (:output-schema parent) parent-ins (:input-schemas parent) child-out (:output-schema child) child-ins (:input-schemas child)] (or (and (nil? child-out) (empty? child-ins)) (and (= child-out parent-out) (->> (map #(is-matching-schema? child-ins %) parent-ins) (every? identity)))))) (defprotocol TypedFunctionProtocol (get-schema [this]) (print-typed-function [this])) (deftype TypedFunctionType [schema] TypedFunctionProtocol (get-schema [this] schema) (print-typed-function [this] schema) s/Schema (walker [this] (clojure.core/fn [x] (if (is-schema-a? (if (= identity x) (let [out-schema (:output-schema schema)] {:output-schema out-schema :input-schemas [[out-schema]]}) (get-schema-of x)) schema) x (schema-utils/error [x 'not (str "typed function " schema)])))) (explain [this] schema)) (defmethod print-method TypedFunctionType [x ^java.io.Writer writer] (print-method (print-typed-function x) writer)) (defmethod pprint/simple-dispatch TypedFunctionType [x] (pprint/pprint (print-typed-function x))) (defmacro fn [& args] `(TypedFunctionType. (simplify-schema (s/=>* ~@args))))
null
https://raw.githubusercontent.com/LonoCloud/step.async/31dc58f72cb9719a11a97dc36992c67cf3efb766/src/lonocloud/step/async/pschema.clj
clojure
NOTE: Keyword is shadowed above, so must fully qualify here typed functions
(ns lonocloud.step.async.pschema (:refer-clojure :exclude [defn defn- fn]) (:require [clojure.pprint :as pprint :refer [pprint]] [schema.core :as s] [schema.utils :as schema-utils]) (:import [schema.core OptionalKey])) (def eq s/eq) (def enum s/enum) (def Int s/Int) (ns-unmap *ns* 'Number) (def Num s/Num) (def maybe s/maybe) (def Any s/Any) (def Map {s/Any s/Any}) (def Keyword s/Keyword) (def Fn (s/pred fn?)) (def Ref clojure.lang.Ref) (def Atom clojure.lang.Atom) (def either s/either) (def Schema s/Schema) (def one s/one) (def required-key s/required-key) (def optional-key s/optional-key) (def optional-key? s/optional-key?) (def Inst s/Inst) (def check s/check) (def explain s/explain) (def validate s/validate) (def optional s/optional) (def error "helper when writing custom type checkers" schema-utils/error) (defmacro satisfies-protocol [t p] `(deftype ~t [] s/Schema (walker [this#] (clojure.core/fn [x#] (if (satisfies? ~p x#) x# (schema-utils/error [x# 'not (str (:on ~p))])))) (explain [this#] (str (:on ~p))))) (clojure.core/defn analyze-defn-params "Produce [type comment params body]" [[a1 a2 a3 a4 :as params]] (if (= :- a1) (if (string? a3) (let [[_ _ _ _ & body] params] [a2 a3 a4 body]) (let [[_ _ _ & body] params] [a2 nil a3 body])) (if (string? a1) (let [[_ _ & body] params] [nil a1 a2 body]) (let [[_ & body] params] [nil nil a1 body])))) (defmacro defn [name & more] (let [[type comment-str params body] (analyze-defn-params more)] (if type (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) :- ~type ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) :- ~type ~params ~@body)) (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :always-validate true)) ~params ~@body))))) (defmacro defn- [name & more] (let [[type comment-str params body] (analyze-defn-params more)] (if type (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) :- ~type ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) :- ~type ~params ~@body)) (if comment-str `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) ~comment-str ~params ~@body) `(s/defn ~(with-meta name (assoc (meta name) :private true :always-validate true)) ~params ~@body))))) (defmulti to-key class) [k] k) (defmethod to-key OptionalKey [k] (:k k)) (defn get-type-keys [m] (map to-key (keys m))) (comment (pprint (defnx foo :- String "this is " [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo :- String [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo "this is " [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo [a :- String] (+ 1 2) {:a 10})) (pprint (defnx foo [a] (+ 1 2) {:a 10})) ) (defn simplify-schema "Convert a function schema to a simpler representation containing only what must be checked" [schema] (let [{:keys [input-schemas output-schema]} schema] {:output-schema (when output-schema (s/explain output-schema)) :input-schemas (vec (map (comp vec s/explain-input-schema) input-schemas))})) (defn- get-schema-of "Lookup the schema type of a function." [f] (simplify-schema (schema-utils/class-schema (class f)))) (defn- vararg-type "Check a single input schema and if it contains a varargs, return the element type of the vararg" [schema] (let [n (count schema) start-n (max (- n 2) 0) [l1 l2] (drop start-n schema)] (when (= '& l1) (first l2)))) (defn- expand-var-arg-to "'Unroll' part of a vararg (if present) in the source to make the source input schema the same length as the target schema. Note: the schemas in this case are individual arities." [source target] (let [target-count (count target) n (count source) start-n (max (- n 2) 0) start (take start-n source)] (if-let [source-vararg-type (vararg-type source)] (if-let [target-vararg-type (vararg-type target)] (if (and (= source-vararg-type target-vararg-type) (< n target-count)) (reduce into (vec start) [(repeat (max (- target-count start-n 2) 0) source-vararg-type) ['& [source-vararg-type]]]) source) (into (vec start) (repeat (max (- target-count start-n) 0) source-vararg-type))) source))) (defn- arg-matches [schema-field target-field] (or (= schema-field target-field) (if (or (= schema-field '&) (= target-field '&)) false (and (= target-field {'Any 'Any}) (map? schema-field))))) (defn- matches? [schema target] (and (= (count schema) (count target)) (->> (map arg-matches schema target) (every? identity)))) (defn- is-matching-schema? "Determine if there are any schemas in the choices that matches the target schema." [choices target] (->> choices (map #(expand-var-arg-to % target)) (some #(matches? % target)))) (defn is-schema-a? "Determine if the child function schema is a sub-type of the parent function schema." [child parent] (let [parent-out (:output-schema parent) parent-ins (:input-schemas parent) child-out (:output-schema child) child-ins (:input-schemas child)] (or (and (nil? child-out) (empty? child-ins)) (and (= child-out parent-out) (->> (map #(is-matching-schema? child-ins %) parent-ins) (every? identity)))))) (defprotocol TypedFunctionProtocol (get-schema [this]) (print-typed-function [this])) (deftype TypedFunctionType [schema] TypedFunctionProtocol (get-schema [this] schema) (print-typed-function [this] schema) s/Schema (walker [this] (clojure.core/fn [x] (if (is-schema-a? (if (= identity x) (let [out-schema (:output-schema schema)] {:output-schema out-schema :input-schemas [[out-schema]]}) (get-schema-of x)) schema) x (schema-utils/error [x 'not (str "typed function " schema)])))) (explain [this] schema)) (defmethod print-method TypedFunctionType [x ^java.io.Writer writer] (print-method (print-typed-function x) writer)) (defmethod pprint/simple-dispatch TypedFunctionType [x] (pprint/pprint (print-typed-function x))) (defmacro fn [& args] `(TypedFunctionType. (simplify-schema (s/=>* ~@args))))
a1641af477df5a3acf7cd71ed2fb94358726a92ec6c42c6d863584c0fe9138a5
michaelballantyne/multiscope
main.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse) (for-meta 2 racket/base syntax/parse syntax/id-table)) ; because we want to add scopes to absolutely everything we import, ; we don't provide any initial bindings through the module language ; other than #%module-begin and forms for require. The forms for require ; will unfortunately be accessible to all the scopes, but may be overridden. (provide (rename-out [module-begin #%module-begin]) #%top-interaction #%top #%app #%datum ; for require require only-in except-in prefix-in rename-in combine-in relative-in only-meta-in for-syntax for-template for-label for-meta submod quote lib file planet) (begin-for-syntax (define expanding-module1? #f) (define (set-expanding-module1!) (set! expanding-module1? #t))) (begin-for-syntax (begin-for-syntax (define expanding-module2? #f) (define (set-expanding-module2!) (set! expanding-module2? #t)))) (module multi-phase-helpers racket/base (require (for-syntax racket/base)) (define-syntax-rule (transient-effect statements ...) (begin (define-syntax (m stx) (begin statements ...) #'(void)) (m))) (define-syntax-rule (define-syntax/no-provide var expr) (begin (define-syntax tmp expr) (define-syntax var (make-rename-transformer (syntax-property #'tmp 'not-provide-all-defined #t))))) (define-for-syntax (apply-scope this-introducer all-introducers stx) (this-introducer (for/fold ([stx stx]) ([introducer all-introducers]) (introducer stx 'remove)) 'add)) (provide transient-effect define-syntax/no-provide (for-syntax apply-scope))) (require 'multi-phase-helpers (for-syntax 'multi-phase-helpers)) (begin-for-syntax (define (make-phase0-scope-macro this-introducer other-introducers) (lambda (stx) (syntax-parse stx [(_ body ...) (when (not expanding-module1?) (raise-syntax-error 'multiscope "scope-application macro used outside of defining module (likely through an exported macro). This is unsupported. Use the phase 1 syntax-quote-like macros instead." stx)) ; don't add any scopes to begin; it needs to resolve ; to the definition available to the macro (not the use-site) ; lest the reference be ambiguous. (define/syntax-parse (scoped-body ...) (apply-scope this-introducer other-introducers #'(body ...))) #'(begin scoped-body ...)]))) (begin-for-syntax (define (make-phase1-scope-macro scope-ids this-introducer other-introducers) (define table (make-immutable-free-id-table ; Not sure why, but this only works if #:phase is 0. Seems like it should be 1 , as we 'd want to change behavior if the phase 1 macro had been shadowed . (map cons scope-ids other-introducers) #:phase 0)) (define (scoped-syntax this-introducer stx) (syntax-parse stx [(scope body) #:when (and (identifier? #'scope) (free-id-table-ref table #'scope #f)) (scoped-syntax (free-id-table-ref table #'scope) #'body)] [(list-element ...) (datum->syntax #'(list-element ...) (for/list ([el (syntax->list #'(list-element ...))]) (scoped-syntax this-introducer el)))] [pattern-var #:when (and (identifier? #'pattern-var) (syntax-pattern-variable? (syntax-local-value #'pattern-var (lambda () #f)))) #'pattern-var] [other (apply-scope this-introducer other-introducers #'other)])) (syntax-parser [(_ body ...) (when (not expanding-module2?) (raise-syntax-error 'multiscope "scoped syntax-quoting phase 1 macro used outside of defining module (likely through an exported macro). This is unsupported. Apply scopes at a higher phase but within the originating module instead.")) (with-syntax ([(scoped-body ...) (scoped-syntax this-introducer #'(body ...))]) #'(syntax scoped-body ...))])))) (define-syntax (define-scopes stx) (syntax-parse stx [(_ scope ...) (define/syntax-parse (scope-introducer ...) (generate-temporaries #'(scope ...))) ; We create the identifying syntax object scopes for each scope during the ; define-scopes exapansion rather than in the resulting module to ; ensure they are the same for every instantiation of the module, ; so that things like top-interaction apply the same scope and thus work. (define/syntax-parse (scoped-ids ...) (for/list ([id (syntax->list #'(scope ...))]) ((make-syntax-introducer #t) id))) #'(begin ; For phase 0 macro (begin-for-syntax (define scope-introducer (make-syntax-delta-introducer #'scoped-ids #'scope)) ...) For phase 1 syntax quoting macro (begin-for-syntax (begin-for-syntax (define scope-introducer (make-syntax-delta-introducer #'scoped-ids #'scope)) ... )) ; phase 0 macro; produces a scoped version of the argument syntax. (define-syntax/no-provide scope (make-phase0-scope-macro scope-introducer (list scope-introducer ...))) ... phase 1 macro ; quasisyntax - like . (begin-for-syntax (define-syntax/no-provide scope (make-phase1-scope-macro (list #'scope ...) scope-introducer (list scope-introducer ...))) ...))])) (begin-for-syntax (define-syntax-class scope-spec (pattern [name:id require-specs ...])) (define (make-top-interaction default-scope) (lambda (stx) (set-expanding-module1!) (syntax-case stx () [(_ . form) #`(#,default-scope form)])))) (define-syntax (module-begin stx) (syntax-parse stx #:datum-literals (scopes) [(_ (scopes default-scope:scope-spec other-scope:scope-spec ...) forms ...) #:with (scope:scope-spec ...) #'(default-scope other-scope ...) #:with #%top-interaction (datum->syntax stx '#%top-interaction) #'(#%module-begin (transient-effect (set-expanding-module1!)) (begin-for-syntax (transient-effect (set-expanding-module2!))) (define-scopes scope.name ...) ; Applying the appropriate scope macro to the require-spec causes ; the imported identifier to have that scope (and thus only be referenced ; when the referring identifier also has the scope). We also happen to apply ; the scope to `require` itself, but this has no impact as require is ; a reference and resolution is by scope subset. (scope.name (require scope.require-specs ...)) ... ; Forms in the remainder of the module body and entered at the REPL are ; resolved in the default scope. (define-syntax #%top-interaction (make-top-interaction #'default-scope.name)) (default-scope.name forms) ...)])) (module reader syntax/module-reader #:language 'multiscope)
null
https://raw.githubusercontent.com/michaelballantyne/multiscope/58af714ee263b3a34006b0aa810d0c6e34ba93f7/main.rkt
racket
because we want to add scopes to absolutely everything we import, we don't provide any initial bindings through the module language other than #%module-begin and forms for require. The forms for require will unfortunately be accessible to all the scopes, but may be overridden. for require don't add any scopes to begin; it needs to resolve to the definition available to the macro (not the use-site) lest the reference be ambiguous. Not sure why, but this only works if #:phase is 0. We create the identifying syntax object scopes for each scope during the define-scopes exapansion rather than in the resulting module to ensure they are the same for every instantiation of the module, so that things like top-interaction apply the same scope and thus work. For phase 0 macro phase 0 macro; produces a scoped version of the argument syntax. quasisyntax - like . Applying the appropriate scope macro to the require-spec causes the imported identifier to have that scope (and thus only be referenced when the referring identifier also has the scope). We also happen to apply the scope to `require` itself, but this has no impact as require is a reference and resolution is by scope subset. Forms in the remainder of the module body and entered at the REPL are resolved in the default scope.
#lang racket/base (require (for-syntax racket/base syntax/parse) (for-meta 2 racket/base syntax/parse syntax/id-table)) (provide (rename-out [module-begin #%module-begin]) #%top-interaction #%top #%app #%datum require only-in except-in prefix-in rename-in combine-in relative-in only-meta-in for-syntax for-template for-label for-meta submod quote lib file planet) (begin-for-syntax (define expanding-module1? #f) (define (set-expanding-module1!) (set! expanding-module1? #t))) (begin-for-syntax (begin-for-syntax (define expanding-module2? #f) (define (set-expanding-module2!) (set! expanding-module2? #t)))) (module multi-phase-helpers racket/base (require (for-syntax racket/base)) (define-syntax-rule (transient-effect statements ...) (begin (define-syntax (m stx) (begin statements ...) #'(void)) (m))) (define-syntax-rule (define-syntax/no-provide var expr) (begin (define-syntax tmp expr) (define-syntax var (make-rename-transformer (syntax-property #'tmp 'not-provide-all-defined #t))))) (define-for-syntax (apply-scope this-introducer all-introducers stx) (this-introducer (for/fold ([stx stx]) ([introducer all-introducers]) (introducer stx 'remove)) 'add)) (provide transient-effect define-syntax/no-provide (for-syntax apply-scope))) (require 'multi-phase-helpers (for-syntax 'multi-phase-helpers)) (begin-for-syntax (define (make-phase0-scope-macro this-introducer other-introducers) (lambda (stx) (syntax-parse stx [(_ body ...) (when (not expanding-module1?) (raise-syntax-error 'multiscope "scope-application macro used outside of defining module (likely through an exported macro). This is unsupported. Use the phase 1 syntax-quote-like macros instead." stx)) (define/syntax-parse (scoped-body ...) (apply-scope this-introducer other-introducers #'(body ...))) #'(begin scoped-body ...)]))) (begin-for-syntax (define (make-phase1-scope-macro scope-ids this-introducer other-introducers) (define table (make-immutable-free-id-table Seems like it should be 1 , as we 'd want to change behavior if the phase 1 macro had been shadowed . (map cons scope-ids other-introducers) #:phase 0)) (define (scoped-syntax this-introducer stx) (syntax-parse stx [(scope body) #:when (and (identifier? #'scope) (free-id-table-ref table #'scope #f)) (scoped-syntax (free-id-table-ref table #'scope) #'body)] [(list-element ...) (datum->syntax #'(list-element ...) (for/list ([el (syntax->list #'(list-element ...))]) (scoped-syntax this-introducer el)))] [pattern-var #:when (and (identifier? #'pattern-var) (syntax-pattern-variable? (syntax-local-value #'pattern-var (lambda () #f)))) #'pattern-var] [other (apply-scope this-introducer other-introducers #'other)])) (syntax-parser [(_ body ...) (when (not expanding-module2?) (raise-syntax-error 'multiscope "scoped syntax-quoting phase 1 macro used outside of defining module (likely through an exported macro). This is unsupported. Apply scopes at a higher phase but within the originating module instead.")) (with-syntax ([(scoped-body ...) (scoped-syntax this-introducer #'(body ...))]) #'(syntax scoped-body ...))])))) (define-syntax (define-scopes stx) (syntax-parse stx [(_ scope ...) (define/syntax-parse (scope-introducer ...) (generate-temporaries #'(scope ...))) (define/syntax-parse (scoped-ids ...) (for/list ([id (syntax->list #'(scope ...))]) ((make-syntax-introducer #t) id))) #'(begin (begin-for-syntax (define scope-introducer (make-syntax-delta-introducer #'scoped-ids #'scope)) ...) For phase 1 syntax quoting macro (begin-for-syntax (begin-for-syntax (define scope-introducer (make-syntax-delta-introducer #'scoped-ids #'scope)) ... )) (define-syntax/no-provide scope (make-phase0-scope-macro scope-introducer (list scope-introducer ...))) ... (begin-for-syntax (define-syntax/no-provide scope (make-phase1-scope-macro (list #'scope ...) scope-introducer (list scope-introducer ...))) ...))])) (begin-for-syntax (define-syntax-class scope-spec (pattern [name:id require-specs ...])) (define (make-top-interaction default-scope) (lambda (stx) (set-expanding-module1!) (syntax-case stx () [(_ . form) #`(#,default-scope form)])))) (define-syntax (module-begin stx) (syntax-parse stx #:datum-literals (scopes) [(_ (scopes default-scope:scope-spec other-scope:scope-spec ...) forms ...) #:with (scope:scope-spec ...) #'(default-scope other-scope ...) #:with #%top-interaction (datum->syntax stx '#%top-interaction) #'(#%module-begin (transient-effect (set-expanding-module1!)) (begin-for-syntax (transient-effect (set-expanding-module2!))) (define-scopes scope.name ...) (scope.name (require scope.require-specs ...)) ... (define-syntax #%top-interaction (make-top-interaction #'default-scope.name)) (default-scope.name forms) ...)])) (module reader syntax/module-reader #:language 'multiscope)
79b96fb5db9b53a200879c9a157eef1f0781bb831934910874ee981e3ed48c9c
acl2/acl2
smtp@useless-runes.lsp
(ABNF::UNTRANSLATE-PREPROCESS-*SMTP-GRAMMAR-RULES*) (ABNF::RULELIST-WFP-OF-*SMTP-GRAMMAR-RULES*) (ABNF::SMTP-CST-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-MATCHP$) (ABNF::SMTP-CST-MATCHP$-OF-TREE-FIX-TREE (12 1 (:REWRITE ABNF::TREE-FIX-WHEN-TREEP)) (6 6 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP)) (5 1 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP)) (4 4 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P)) (3 3 (:TYPE-PRESCRIPTION ABNF::TREEP)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP)) (2 1 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP)) (1 1 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP)) (1 1 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X)) ) (ABNF::SMTP-CST-MATCHP$-TREE-EQUIV-CONGRUENCE-ON-TREE) (ABNF::SMTP-CST-MATCHP$-OF-ELEMENT-FIX-ELEM (4 4 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P)) (3 1 (:REWRITE ABNF::ELEMENT-FIX-WHEN-ELEMENTP)) (2 2 (:TYPE-PRESCRIPTION ABNF::ELEMENTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) ) (ABNF::SMTP-CST-MATCHP$-ELEMENT-EQUIV-CONGRUENCE-ON-ELEM) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-ELEM-MATCHP$) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-OF-TREE-LIST-FIX-TREES (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-FIX)) (16 1 (:REWRITE ABNF::TREE-LIST-FIX-WHEN-TREE-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP)) ) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-TREE-LIST-EQUIV-CONGRUENCE-ON-TREES) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-OF-ELEMENT-FIX-ELEM (18 2 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (3 1 (:REWRITE ABNF::ELEMENT-FIX-WHEN-ELEMENTP)) (2 2 (:TYPE-PRESCRIPTION ABNF::ELEMENTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) ) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-ELEMENT-EQUIV-CONGRUENCE-ON-ELEM) (ABNF::SMTP-CST-LIST-REP-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-REP-MATCHP$) (ABNF::SMTP-CST-LIST-REP-MATCHP$-OF-TREE-LIST-FIX-TREES (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-FIX)) (16 1 (:REWRITE ABNF::TREE-LIST-FIX-WHEN-TREE-LISTP)) (9 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (7 7 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (7 7 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP)) ) (ABNF::SMTP-CST-LIST-REP-MATCHP$-TREE-LIST-EQUIV-CONGRUENCE-ON-TREES) (ABNF::SMTP-CST-LIST-REP-MATCHP$-OF-REPETITION-FIX-REP (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (5 1 (:REWRITE ABNF::REPETITION-FIX-WHEN-REPETITIONP)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (2 2 (:TYPE-PRESCRIPTION ABNF::REPETITIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::REPETITIONP-WHEN-MEMBER-EQUAL-OF-CONCATENATIONP)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) ) (ABNF::SMTP-CST-LIST-REP-MATCHP$-REPETITION-EQUIV-CONGRUENCE-ON-REP) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-LIST-CONC-MATCHP$) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-OF-TREE-LIST-LIST-FIX-TREESS (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-CONCATENATION-P-WHEN-ATOM-CONCATENATION)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-LIST-FIX)) (14 1 (:REWRITE ABNF::TREE-LIST-LIST-FIX-WHEN-TREE-LIST-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-TREE-LIST-LIST-EQUIV-CONGRUENCE-ON-TREESS) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-OF-CONCATENATION-FIX-CONC (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-CONCATENATION-P-WHEN-ATOM-CONCATENATION)) (16 1 (:REWRITE ABNF::CONCATENATION-FIX-WHEN-CONCATENATIONP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (9 1 (:REWRITE ABNF::CONCATENATIONP-WHEN-NOT-CONSP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::CONCATENATIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::CONCATENATIONP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::CONCATENATIONP-WHEN-MEMBER-EQUAL-OF-ALTERNATIONP)) ) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-CONCATENATION-EQUIV-CONGRUENCE-ON-CONC) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-LIST-ALT-MATCHP$) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-OF-TREE-LIST-LIST-FIX-TREESS (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-ALTERNATION-P-WHEN-ATOM-ALTERNATION)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-LIST-FIX)) (14 1 (:REWRITE ABNF::TREE-LIST-LIST-FIX-WHEN-TREE-LIST-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-TREE-LIST-LIST-EQUIV-CONGRUENCE-ON-TREESS) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-OF-ALTERNATION-FIX-ALT (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-ALTERNATION-P-WHEN-ATOM-ALTERNATION)) (14 1 (:REWRITE ABNF::ALTERNATION-FIX-WHEN-ALTERNATIONP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (9 1 (:REWRITE ABNF::ALTERNATIONP-WHEN-NOT-CONSP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::ALTERNATIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::ALTERNATIONP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-ALTERNATION-EQUIV-CONGRUENCE-ON-ALT) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO) (ABNF::SMTP-CST-NONLEAF-WHEN-HELO) (ABNF::SMTP-CST-RULENAME-WHEN-HELO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-HELO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-HELO) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT2-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-EHLO-OK-RSP) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-GREET) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-GREET) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-GREET) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-GREET) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-GREET) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-PARAM) (ABNF::SMTP-CST-NONLEAF-WHEN-MAIL) (ABNF::SMTP-CST-RULENAME-WHEN-MAIL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAIL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAIL) (ABNF::SMTP-CST-NONLEAF-WHEN-RCPT) (ABNF::SMTP-CST-RULENAME-WHEN-RCPT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RCPT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RCPT) (ABNF::SMTP-CST-NONLEAF-WHEN-DATA) (ABNF::SMTP-CST-RULENAME-WHEN-DATA) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DATA) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DATA) (ABNF::SMTP-CST-NONLEAF-WHEN-RSET) (ABNF::SMTP-CST-RULENAME-WHEN-RSET) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RSET) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RSET) (ABNF::SMTP-CST-NONLEAF-WHEN-VRFY) (ABNF::SMTP-CST-RULENAME-WHEN-VRFY) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-VRFY) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-VRFY) (ABNF::SMTP-CST-NONLEAF-WHEN-EXPN) (ABNF::SMTP-CST-RULENAME-WHEN-EXPN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EXPN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EXPN) (ABNF::SMTP-CST-NONLEAF-WHEN-HELP) (ABNF::SMTP-CST-RULENAME-WHEN-HELP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-HELP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-HELP) (ABNF::SMTP-CST-NONLEAF-WHEN-NOOP) (ABNF::SMTP-CST-RULENAME-WHEN-NOOP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-NOOP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-NOOP) (ABNF::SMTP-CST-NONLEAF-WHEN-QUIT) (ABNF::SMTP-CST-RULENAME-WHEN-QUIT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUIT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUIT) (ABNF::SMTP-CST-NONLEAF-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REP1-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT2-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT2-REP1-REVERSE-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-MATCH-ALT1-FORWARD-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REP1-FORWARD-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-A-D-L) (ABNF::SMTP-CST-RULENAME-WHEN-A-D-L) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-A-D-L) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-A-D-L) (ABNF::SMTP-CST-NONLEAF-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-RULENAME-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-NONLEAF-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-RULENAME-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-MATCH-ALT1-ESMTP-VALUE) (ABNF::SMTP-CST-NONLEAF-WHEN-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-KEYWORD) (ABNF::SMTP-CST-MATCH-ALT1-KEYWORD) (ABNF::SMTP-CST-MATCH-ALT1-REP1-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-ARGUMENT) (ABNF::SMTP-CST-RULENAME-WHEN-ARGUMENT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ARGUMENT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ARGUMENT) (ABNF::SMTP-CST-MATCH-ALT1-ARGUMENT) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ARGUMENT) (ABNF::SMTP-CST-NONLEAF-WHEN-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-LET-DIG) (ABNF::SMTP-CST-RULENAME-WHEN-LET-DIG) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LET-DIG) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT1-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT2-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LET-DIG) (ABNF::SMTP-CST-NONLEAF-WHEN-LDH-STR) (ABNF::SMTP-CST-RULENAME-WHEN-LDH-STR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LDH-STR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LDH-STR) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-MAILBOX) (ABNF::SMTP-CST-RULENAME-WHEN-MAILBOX) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAILBOX) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAILBOX) (ABNF::SMTP-CST-NONLEAF-WHEN-LOCAL-PART) (ABNF::SMTP-CST-RULENAME-WHEN-LOCAL-PART) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LOCAL-PART) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT1-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT2-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LOCAL-PART) (ABNF::SMTP-CST-NONLEAF-WHEN-DOT-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-DOT-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DOT-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DOT-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-ATOM) (ABNF::SMTP-CST-RULENAME-WHEN-ATOM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ATOM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ATOM) (ABNF::SMTP-CST-MATCH-ALT1-ATOM) (ABNF::SMTP-CST-NONLEAF-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-QCONTENTSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT3-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT3-REP1-QTEXTSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STRING) (ABNF::SMTP-CST-MATCH-ALT1-STRING) (ABNF::SMTP-CST-MATCH-ALT1-REP1-STRING) (ABNF::SMTP-CST-MATCH-ALT2-STRING) (ABNF::SMTP-CST-MATCH-ALT2-REP1-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-RULENAME-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-MATCH-ALT1-STANDARDIZED-TAG) (ABNF::SMTP-CST-MATCH-ALT1-REP1-STANDARDIZED-TAG) (ABNF::SMTP-CST-NONLEAF-WHEN-DCONTENT) (ABNF::SMTP-CST-RULENAME-WHEN-DCONTENT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DCONTENT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT1-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT1-REP1-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT2-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT2-REP1-DCONTENT) (ABNF::SMTP-CST-NONLEAF-WHEN-SNUM) (ABNF::SMTP-CST-RULENAME-WHEN-SNUM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-SNUM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-SNUM) (ABNF::SMTP-CST-MATCH-ALT1-SNUM) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT1-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT2-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT2-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT3-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT3-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT4-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT4-REP1-IPV6-ADDR) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-HEX) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-HEX) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-HEX) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-HEX) (ABNF::SMTP-CST-MATCH-ALT1-IPV6-HEX) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-FULL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-FULL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-FULL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-FULL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-COMP) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-COMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-COMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-COMP) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-NONLEAF-WHEN-GREETING) (ABNF::SMTP-CST-RULENAME-WHEN-GREETING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-GREETING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-GREETING) (ABNF::SMTP-CST-MATCH-ALT1-GREETING) (ABNF::SMTP-CST-MATCH-ALT1-REP1-GREETING) (ABNF::SMTP-CST-MATCH-ALT2-GREETING) (ABNF::SMTP-CST-MATCH-ALT2-REP1-GREETING) (ABNF::SMTP-CST-NONLEAF-WHEN-TEXTSTRING) (ABNF::SMTP-CST-RULENAME-WHEN-TEXTSTRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TEXTSTRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TEXTSTRING) (ABNF::SMTP-CST-MATCH-ALT1-TEXTSTRING) (ABNF::SMTP-CST-NONLEAF-WHEN-REPLY-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-REPLY-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REPLY-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REPLY-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-REPLY-CODE) (ABNF::SMTP-CST-RULENAME-WHEN-REPLY-CODE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REPLY-CODE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REPLY-CODE) (ABNF::SMTP-CST-NONLEAF-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-STAMP) (ABNF::SMTP-CST-RULENAME-WHEN-STAMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STAMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STAMP) (ABNF::SMTP-CST-NONLEAF-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT1-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT2-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT2-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT3-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT3-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-TCP-INFO) (ABNF::SMTP-CST-RULENAME-WHEN-TCP-INFO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TCP-INFO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT1-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT1-REP1-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT2-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT2-REP1-TCP-INFO) (ABNF::SMTP-CST-NONLEAF-WHEN-OPT-INFO) (ABNF::SMTP-CST-RULENAME-WHEN-OPT-INFO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-OPT-INFO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-OPT-INFO) (ABNF::SMTP-CST-NONLEAF-WHEN-VIA) (ABNF::SMTP-CST-RULENAME-WHEN-VIA) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-VIA) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-VIA) (ABNF::SMTP-CST-NONLEAF-WHEN-WITH) (ABNF::SMTP-CST-RULENAME-WHEN-WITH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-WITH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-WITH) (ABNF::SMTP-CST-NONLEAF-WHEN-ID) (ABNF::SMTP-CST-RULENAME-WHEN-ID) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ID) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ID) (ABNF::SMTP-CST-NONLEAF-WHEN-FOR) (ABNF::SMTP-CST-RULENAME-WHEN-FOR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FOR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FOR) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-RULENAME-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-NONLEAF-WHEN-LINK) (ABNF::SMTP-CST-RULENAME-WHEN-LINK) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LINK) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LINK) (ABNF::SMTP-CST-MATCH-ALT1-LINK) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LINK) (ABNF::SMTP-CST-MATCH-ALT2-LINK) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LINK) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-RULENAME-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-MATCH-ALT1-ADDTL-LINK) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ADDTL-LINK) (ABNF::SMTP-CST-NONLEAF-WHEN-PROTOCOL) (ABNF::SMTP-CST-RULENAME-WHEN-PROTOCOL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-PROTOCOL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-REP1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT2-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT2-REP1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT3-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT3-REP1-PROTOCOL) (ABNF::SMTP-CST-NONLEAF-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-RULENAME-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-ATTDL-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ATTDL-PROTOCOL)
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/abnf/examples/.sys/smtp%40useless-runes.lsp
lisp
(ABNF::UNTRANSLATE-PREPROCESS-*SMTP-GRAMMAR-RULES*) (ABNF::RULELIST-WFP-OF-*SMTP-GRAMMAR-RULES*) (ABNF::SMTP-CST-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-MATCHP$) (ABNF::SMTP-CST-MATCHP$-OF-TREE-FIX-TREE (12 1 (:REWRITE ABNF::TREE-FIX-WHEN-TREEP)) (6 6 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP)) (5 1 (:REWRITE ABNF::TREEP-WHEN-TREE-OPTIONP)) (4 4 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P)) (3 3 (:TYPE-PRESCRIPTION ABNF::TREEP)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-OPTIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREEP-WHEN-MEMBER-EQUAL-OF-TREE-LISTP)) (2 1 (:REWRITE ABNF::TREE-OPTIONP-WHEN-TREEP)) (1 1 (:REWRITE ABNF::TREEP-WHEN-PARSE-TREEP)) (1 1 (:REWRITE ABNF::TREEP-WHEN-IN-TREE-SETP-BINDS-FREE-X)) ) (ABNF::SMTP-CST-MATCHP$-TREE-EQUIV-CONGRUENCE-ON-TREE) (ABNF::SMTP-CST-MATCHP$-OF-ELEMENT-FIX-ELEM (4 4 (:REWRITE ABNF::TREE-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-MATCH-ELEMENT-P-WHEN-MEMBER-EQUAL-OF-TREE-LIST-MATCH-ELEMENT-P)) (3 1 (:REWRITE ABNF::ELEMENT-FIX-WHEN-ELEMENTP)) (2 2 (:TYPE-PRESCRIPTION ABNF::ELEMENTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) ) (ABNF::SMTP-CST-MATCHP$-ELEMENT-EQUIV-CONGRUENCE-ON-ELEM) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-ELEM-MATCHP$) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-OF-TREE-LIST-FIX-TREES (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-FIX)) (16 1 (:REWRITE ABNF::TREE-LIST-FIX-WHEN-TREE-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP)) ) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-TREE-LIST-EQUIV-CONGRUENCE-ON-TREES) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-OF-ELEMENT-FIX-ELEM (18 2 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (4 4 (:REWRITE ABNF::TREE-LIST-MATCH-ELEMENT-P-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (4 4 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (4 4 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (3 1 (:REWRITE ABNF::ELEMENT-FIX-WHEN-ELEMENTP)) (2 2 (:TYPE-PRESCRIPTION ABNF::ELEMENTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) ) (ABNF::SMTP-CST-LIST-ELEM-MATCHP$-ELEMENT-EQUIV-CONGRUENCE-ON-ELEM) (ABNF::SMTP-CST-LIST-REP-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-REP-MATCHP$) (ABNF::SMTP-CST-LIST-REP-MATCHP$-OF-TREE-LIST-FIX-TREES (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-FIX)) (16 1 (:REWRITE ABNF::TREE-LIST-FIX-WHEN-TREE-LISTP)) (9 1 (:REWRITE ABNF::TREE-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (7 7 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (7 7 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (6 6 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::TREE-LISTP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LISTP)) ) (ABNF::SMTP-CST-LIST-REP-MATCHP$-TREE-LIST-EQUIV-CONGRUENCE-ON-TREES) (ABNF::SMTP-CST-LIST-REP-MATCHP$-OF-REPETITION-FIX-REP (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-ATOM)) (5 1 (:REWRITE ABNF::REPETITION-FIX-WHEN-REPETITIONP)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (4 4 (:REWRITE ABNF::TREE-LIST-TERMINATEDP-WHEN-MEMBER-EQUAL-OF-TREE-LIST-LIST-TERMINATEDP)) (2 2 (:TYPE-PRESCRIPTION ABNF::REPETITIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::REPETITIONP-WHEN-MEMBER-EQUAL-OF-CONCATENATIONP)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (2 2 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (2 2 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) ) (ABNF::SMTP-CST-LIST-REP-MATCHP$-REPETITION-EQUIV-CONGRUENCE-ON-REP) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-LIST-CONC-MATCHP$) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-OF-TREE-LIST-LIST-FIX-TREESS (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-CONCATENATION-P-WHEN-ATOM-CONCATENATION)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-LIST-FIX)) (14 1 (:REWRITE ABNF::TREE-LIST-LIST-FIX-WHEN-TREE-LIST-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-TREE-LIST-LIST-EQUIV-CONGRUENCE-ON-TREESS) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-OF-CONCATENATION-FIX-CONC (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-CONCATENATION-P-WHEN-ATOM-CONCATENATION)) (16 1 (:REWRITE ABNF::CONCATENATION-FIX-WHEN-CONCATENATIONP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (9 1 (:REWRITE ABNF::CONCATENATIONP-WHEN-NOT-CONSP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::CONCATENATIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::CONCATENATIONP-WHEN-SUBSETP-EQUAL)) (2 2 (:REWRITE ABNF::CONCATENATIONP-WHEN-MEMBER-EQUAL-OF-ALTERNATIONP)) ) (ABNF::SMTP-CST-LIST-LIST-CONC-MATCHP$-CONCATENATION-EQUIV-CONGRUENCE-ON-CONC) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$) (ABNF::BOOLEANP-OF-SMTP-CST-LIST-LIST-ALT-MATCHP$) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-OF-TREE-LIST-LIST-FIX-TREESS (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (28 3 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-ALTERNATION-P-WHEN-ATOM-ALTERNATION)) (18 2 (:REWRITE ABNF::CONSP-OF-TREE-LIST-LIST-FIX)) (14 1 (:REWRITE ABNF::TREE-LIST-LIST-FIX-WHEN-TREE-LIST-LISTP)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (9 9 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (9 9 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (9 1 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-NOT-CONSP)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (7 7 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (6 6 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::TREE-LIST-LISTP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::TREE-LIST-LISTP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-TREE-LIST-LIST-EQUIV-CONGRUENCE-ON-TREESS) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-OF-ALTERNATION-FIX-ALT (18 2 (:REWRITE ABNF::TREE-LIST-LIST-MATCH-ALTERNATION-P-WHEN-ATOM-ALTERNATION)) (14 1 (:REWRITE ABNF::ALTERNATION-FIX-WHEN-ALTERNATIONP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-NOT-CONSP)) (10 2 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-ATOM)) (9 1 (:REWRITE ABNF::ALTERNATIONP-WHEN-NOT-CONSP)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2)) (5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2)) (5 5 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1)) (4 4 (:REWRITE ABNF::TREE-LIST-LIST-TERMINATEDP-WHEN-SUBSETP-EQUAL)) (2 2 (:TYPE-PRESCRIPTION ABNF::ALTERNATIONP)) (2 2 (:REWRITE-QUOTED-CONSTANT ABNF::RULELIST-FIX-UNDER-RULELIST-EQUIV)) (2 2 (:REWRITE ABNF::ALTERNATIONP-WHEN-SUBSETP-EQUAL)) ) (ABNF::SMTP-CST-LIST-LIST-ALT-MATCHP$-ALTERNATION-EQUIV-CONGRUENCE-ON-ALT) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO) (ABNF::SMTP-CST-NONLEAF-WHEN-HELO) (ABNF::SMTP-CST-RULENAME-WHEN-HELO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-HELO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-HELO) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT2-EHLO-OK-RSP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-EHLO-OK-RSP) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-GREET) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-GREET) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-GREET) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-GREET) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-GREET) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-RULENAME-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EHLO-PARAM) (ABNF::SMTP-CST-MATCH-ALT1-EHLO-PARAM) (ABNF::SMTP-CST-NONLEAF-WHEN-MAIL) (ABNF::SMTP-CST-RULENAME-WHEN-MAIL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAIL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAIL) (ABNF::SMTP-CST-NONLEAF-WHEN-RCPT) (ABNF::SMTP-CST-RULENAME-WHEN-RCPT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RCPT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RCPT) (ABNF::SMTP-CST-NONLEAF-WHEN-DATA) (ABNF::SMTP-CST-RULENAME-WHEN-DATA) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DATA) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DATA) (ABNF::SMTP-CST-NONLEAF-WHEN-RSET) (ABNF::SMTP-CST-RULENAME-WHEN-RSET) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RSET) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RSET) (ABNF::SMTP-CST-NONLEAF-WHEN-VRFY) (ABNF::SMTP-CST-RULENAME-WHEN-VRFY) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-VRFY) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-VRFY) (ABNF::SMTP-CST-NONLEAF-WHEN-EXPN) (ABNF::SMTP-CST-RULENAME-WHEN-EXPN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EXPN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EXPN) (ABNF::SMTP-CST-NONLEAF-WHEN-HELP) (ABNF::SMTP-CST-RULENAME-WHEN-HELP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-HELP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-HELP) (ABNF::SMTP-CST-NONLEAF-WHEN-NOOP) (ABNF::SMTP-CST-RULENAME-WHEN-NOOP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-NOOP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-NOOP) (ABNF::SMTP-CST-NONLEAF-WHEN-QUIT) (ABNF::SMTP-CST-RULENAME-WHEN-QUIT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUIT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUIT) (ABNF::SMTP-CST-NONLEAF-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REP1-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT2-REVERSE-PATH) (ABNF::SMTP-CST-MATCH-ALT2-REP1-REVERSE-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FORWARD-PATH) (ABNF::SMTP-CST-MATCH-ALT1-FORWARD-PATH) (ABNF::SMTP-CST-MATCH-ALT1-REP1-FORWARD-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-PATH) (ABNF::SMTP-CST-RULENAME-WHEN-PATH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-PATH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-PATH) (ABNF::SMTP-CST-NONLEAF-WHEN-A-D-L) (ABNF::SMTP-CST-RULENAME-WHEN-A-D-L) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-A-D-L) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-A-D-L) (ABNF::SMTP-CST-NONLEAF-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-AT-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-RULENAME-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAIL-PARAMETERS) (ABNF::SMTP-CST-NONLEAF-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-RULENAME-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RCPT-PARAMETERS) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-PARAM) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-RULENAME-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ESMTP-VALUE) (ABNF::SMTP-CST-MATCH-ALT1-ESMTP-VALUE) (ABNF::SMTP-CST-NONLEAF-WHEN-KEYWORD) (ABNF::SMTP-CST-RULENAME-WHEN-KEYWORD) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-KEYWORD) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-KEYWORD) (ABNF::SMTP-CST-MATCH-ALT1-KEYWORD) (ABNF::SMTP-CST-MATCH-ALT1-REP1-KEYWORD) (ABNF::SMTP-CST-NONLEAF-WHEN-ARGUMENT) (ABNF::SMTP-CST-RULENAME-WHEN-ARGUMENT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ARGUMENT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ARGUMENT) (ABNF::SMTP-CST-MATCH-ALT1-ARGUMENT) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ARGUMENT) (ABNF::SMTP-CST-NONLEAF-WHEN-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-SUB-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-LET-DIG) (ABNF::SMTP-CST-RULENAME-WHEN-LET-DIG) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LET-DIG) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT1-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT2-LET-DIG) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LET-DIG) (ABNF::SMTP-CST-NONLEAF-WHEN-LDH-STR) (ABNF::SMTP-CST-RULENAME-WHEN-LDH-STR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LDH-STR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LDH-STR) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-MAILBOX) (ABNF::SMTP-CST-RULENAME-WHEN-MAILBOX) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-MAILBOX) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-MAILBOX) (ABNF::SMTP-CST-NONLEAF-WHEN-LOCAL-PART) (ABNF::SMTP-CST-RULENAME-WHEN-LOCAL-PART) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LOCAL-PART) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT1-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT2-LOCAL-PART) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LOCAL-PART) (ABNF::SMTP-CST-NONLEAF-WHEN-DOT-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-DOT-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DOT-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DOT-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-ATOM) (ABNF::SMTP-CST-RULENAME-WHEN-ATOM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ATOM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ATOM) (ABNF::SMTP-CST-MATCH-ALT1-ATOM) (ABNF::SMTP-CST-NONLEAF-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUOTED-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-QCONTENTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-QCONTENTSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QUOTED-PAIRSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-RULENAME-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT1-REP1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT2-REP1-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT3-QTEXTSMTP) (ABNF::SMTP-CST-MATCH-ALT3-REP1-QTEXTSMTP) (ABNF::SMTP-CST-NONLEAF-WHEN-STRING) (ABNF::SMTP-CST-RULENAME-WHEN-STRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STRING) (ABNF::SMTP-CST-MATCH-ALT1-STRING) (ABNF::SMTP-CST-MATCH-ALT1-REP1-STRING) (ABNF::SMTP-CST-MATCH-ALT2-STRING) (ABNF::SMTP-CST-MATCH-ALT2-REP1-STRING) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV4-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-RULENAME-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-GENERAL-ADDRESS-LITERAL) (ABNF::SMTP-CST-NONLEAF-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-RULENAME-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STANDARDIZED-TAG) (ABNF::SMTP-CST-MATCH-ALT1-STANDARDIZED-TAG) (ABNF::SMTP-CST-MATCH-ALT1-REP1-STANDARDIZED-TAG) (ABNF::SMTP-CST-NONLEAF-WHEN-DCONTENT) (ABNF::SMTP-CST-RULENAME-WHEN-DCONTENT) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-DCONTENT) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT1-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT1-REP1-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT2-DCONTENT) (ABNF::SMTP-CST-MATCH-ALT2-REP1-DCONTENT) (ABNF::SMTP-CST-NONLEAF-WHEN-SNUM) (ABNF::SMTP-CST-RULENAME-WHEN-SNUM) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-SNUM) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-SNUM) (ABNF::SMTP-CST-MATCH-ALT1-SNUM) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT1-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT2-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT2-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT3-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT3-REP1-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT4-IPV6-ADDR) (ABNF::SMTP-CST-MATCH-ALT4-REP1-IPV6-ADDR) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-HEX) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-HEX) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-HEX) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-HEX) (ABNF::SMTP-CST-MATCH-ALT1-IPV6-HEX) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-FULL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-FULL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-FULL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-FULL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6-COMP) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6-COMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6-COMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6-COMP) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6V4-FULL) (ABNF::SMTP-CST-NONLEAF-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-RULENAME-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-IPV6V4-COMP) (ABNF::SMTP-CST-NONLEAF-WHEN-GREETING) (ABNF::SMTP-CST-RULENAME-WHEN-GREETING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-GREETING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-GREETING) (ABNF::SMTP-CST-MATCH-ALT1-GREETING) (ABNF::SMTP-CST-MATCH-ALT1-REP1-GREETING) (ABNF::SMTP-CST-MATCH-ALT2-GREETING) (ABNF::SMTP-CST-MATCH-ALT2-REP1-GREETING) (ABNF::SMTP-CST-NONLEAF-WHEN-TEXTSTRING) (ABNF::SMTP-CST-RULENAME-WHEN-TEXTSTRING) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TEXTSTRING) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TEXTSTRING) (ABNF::SMTP-CST-MATCH-ALT1-TEXTSTRING) (ABNF::SMTP-CST-NONLEAF-WHEN-REPLY-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-REPLY-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REPLY-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REPLY-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-REPLY-CODE) (ABNF::SMTP-CST-RULENAME-WHEN-REPLY-CODE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-REPLY-CODE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-REPLY-CODE) (ABNF::SMTP-CST-NONLEAF-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-RETURN-PATH-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-RULENAME-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TIME-STAMP-LINE) (ABNF::SMTP-CST-NONLEAF-WHEN-STAMP) (ABNF::SMTP-CST-RULENAME-WHEN-STAMP) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-STAMP) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-STAMP) (ABNF::SMTP-CST-NONLEAF-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FROM-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-BY-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-RULENAME-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT1-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT2-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT2-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT3-EXTENDED-DOMAIN) (ABNF::SMTP-CST-MATCH-ALT3-REP1-EXTENDED-DOMAIN) (ABNF::SMTP-CST-NONLEAF-WHEN-TCP-INFO) (ABNF::SMTP-CST-RULENAME-WHEN-TCP-INFO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-TCP-INFO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT1-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT1-REP1-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT2-TCP-INFO) (ABNF::SMTP-CST-MATCH-ALT2-REP1-TCP-INFO) (ABNF::SMTP-CST-NONLEAF-WHEN-OPT-INFO) (ABNF::SMTP-CST-RULENAME-WHEN-OPT-INFO) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-OPT-INFO) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-OPT-INFO) (ABNF::SMTP-CST-NONLEAF-WHEN-VIA) (ABNF::SMTP-CST-RULENAME-WHEN-VIA) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-VIA) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-VIA) (ABNF::SMTP-CST-NONLEAF-WHEN-WITH) (ABNF::SMTP-CST-RULENAME-WHEN-WITH) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-WITH) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-WITH) (ABNF::SMTP-CST-NONLEAF-WHEN-ID) (ABNF::SMTP-CST-RULENAME-WHEN-ID) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ID) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ID) (ABNF::SMTP-CST-NONLEAF-WHEN-FOR) (ABNF::SMTP-CST-RULENAME-WHEN-FOR) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-FOR) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-FOR) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-RULENAME-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDITIONAL-REGISTERED-CLAUSES) (ABNF::SMTP-CST-NONLEAF-WHEN-LINK) (ABNF::SMTP-CST-RULENAME-WHEN-LINK) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-LINK) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-LINK) (ABNF::SMTP-CST-MATCH-ALT1-LINK) (ABNF::SMTP-CST-MATCH-ALT1-REP1-LINK) (ABNF::SMTP-CST-MATCH-ALT2-LINK) (ABNF::SMTP-CST-MATCH-ALT2-REP1-LINK) (ABNF::SMTP-CST-NONLEAF-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-RULENAME-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ADDTL-LINK) (ABNF::SMTP-CST-MATCH-ALT1-ADDTL-LINK) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ADDTL-LINK) (ABNF::SMTP-CST-NONLEAF-WHEN-PROTOCOL) (ABNF::SMTP-CST-RULENAME-WHEN-PROTOCOL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-PROTOCOL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-REP1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT2-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT2-REP1-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT3-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT3-REP1-PROTOCOL) (ABNF::SMTP-CST-NONLEAF-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-RULENAME-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-BRANCHES-MATCH-ALT-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-ALTERNATIVES-WHEN-ATTDL-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-ATTDL-PROTOCOL) (ABNF::SMTP-CST-MATCH-ALT1-REP1-ATTDL-PROTOCOL)
cbb3cfb6566299fc08bc8edf9f37406b724851d2e5c47523f53f1dbfd98ae605
funimagej/fun.imagej
filters.clj
(ns fun.imagej.filters (:require [clojure.string :as string]) (:import [net.imglib2.img ImagePlusAdapter Img] [net.imglib2.img.display.imagej ImageJFunctions] [net.imglib2.type NativeType] [net.imglib2.type.numeric NumericType] [net.imglib2.type.numeric.real FloatType] [net.imglib2.algorithm.gauss3 Gauss3] [net.imglib2.algorithm.dog DifferenceOfGaussian] [net.imglib2.view Views] [net.imglib2 Cursor] [java.util.concurrent Executors])) (defn gaussian-3d "Perform a 3D guassian convolution." [img sx sy sz] (let [sigma (double-array [sx sy sz]) infiniteImg (Views/extendValue img (FloatType.))] (Gauss3/gauss sigma infiniteImg img ) img)) (defn dog-3d "Perform a 3D DoG." [img sx1 sy1 sz1 sx2 sy2 sz2] (let [sigma1 (double-array [sx1 sy1 sz1]) sigma2 (double-array [sx2 sy2 sz2]) infiniteImg (Views/extendValue img (FloatType.)) es (Executors/newFixedThreadPool 1000)] (DifferenceOfGaussian/DoG sigma1 sigma2 infiniteImg img es) img)) #_(defn convolve-3d "Perform a 3D convolution with an arbitrary kernel." [img kernel] (FFTConvolution. (copy-image img) kernel)) #_(defn convolve "Perform a FFT convolution with an arbitrary kernel." [img kernel] (FFTConvolution. (copy-image img) kernel))
null
https://raw.githubusercontent.com/funimagej/fun.imagej/dcbe14581ba9394d8ecc6e254e02fac8130a942d/src/fun/imagej/filters.clj
clojure
(ns fun.imagej.filters (:require [clojure.string :as string]) (:import [net.imglib2.img ImagePlusAdapter Img] [net.imglib2.img.display.imagej ImageJFunctions] [net.imglib2.type NativeType] [net.imglib2.type.numeric NumericType] [net.imglib2.type.numeric.real FloatType] [net.imglib2.algorithm.gauss3 Gauss3] [net.imglib2.algorithm.dog DifferenceOfGaussian] [net.imglib2.view Views] [net.imglib2 Cursor] [java.util.concurrent Executors])) (defn gaussian-3d "Perform a 3D guassian convolution." [img sx sy sz] (let [sigma (double-array [sx sy sz]) infiniteImg (Views/extendValue img (FloatType.))] (Gauss3/gauss sigma infiniteImg img ) img)) (defn dog-3d "Perform a 3D DoG." [img sx1 sy1 sz1 sx2 sy2 sz2] (let [sigma1 (double-array [sx1 sy1 sz1]) sigma2 (double-array [sx2 sy2 sz2]) infiniteImg (Views/extendValue img (FloatType.)) es (Executors/newFixedThreadPool 1000)] (DifferenceOfGaussian/DoG sigma1 sigma2 infiniteImg img es) img)) #_(defn convolve-3d "Perform a 3D convolution with an arbitrary kernel." [img kernel] (FFTConvolution. (copy-image img) kernel)) #_(defn convolve "Perform a FFT convolution with an arbitrary kernel." [img kernel] (FFTConvolution. (copy-image img) kernel))
849b3f6842cfa5bca4ca40686c47dbafef02f557e155454f1c76c65b10665c5d
metabase/metabase
security.clj
(ns metabase.server.middleware.security "Ring middleware for adding security-related headers to API responses." (:require [clojure.java.io :as io] [clojure.string :as str] [java-time :as t] [metabase.analytics.snowplow :as snowplow] [metabase.config :as config] [metabase.models.setting :refer [defsetting]] [metabase.public-settings :as public-settings] [metabase.server.request.util :as request.u] [metabase.util.i18n :refer [deferred-tru]] [ring.util.codec :refer [base64-encode]]) (:import (java.security MessageDigest))) (set! *warn-on-reflection* true) (defonce ^:private ^:const inline-js-hashes (letfn [(file-hash [resource-filename] (base64-encode (.digest (doto (MessageDigest/getInstance "SHA-256") (.update (.getBytes (slurp (io/resource resource-filename))))))))] inline script in index.html that sets ` MetabaseBootstrap ` and the like "frontend_client/inline_js/index_bootstrap.js" inline script in index.html that loads Google Analytics "frontend_client/inline_js/index_ganalytics.js" ;; inline script in init.html "frontend_client/inline_js/init.js"]))) (defn- cache-prevention-headers "Headers that tell browsers not to cache a response." [] {"Cache-Control" "max-age=0, no-cache, must-revalidate, proxy-revalidate" "Expires" "Tue, 03 Jul 2001 06:00:00 GMT" "Last-Modified" (t/format :rfc-1123-date-time (t/zoned-date-time))}) (defn- cache-far-future-headers "Headers that tell browsers to cache a static resource for a long time." [] {"Cache-Control" "public, max-age=31536000"}) (def ^:private ^:const strict-transport-security-header "Tell browsers to only access this resource over HTTPS for the next year (prevent MTM attacks). (This only applies if the original request was HTTPS; if sent in response to an HTTP request, this is simply ignored)" {"Strict-Transport-Security" "max-age=31536000"}) (defn- content-security-policy-header "`Content-Security-Policy` header. See -security-policy.com for more details." [] {"Content-Security-Policy" (str/join (for [[k vs] {:default-src ["'none'"] :script-src (concat ["'self'" "'unsafe-eval'" ; TODO - we keep working towards removing this entirely "" "" (when (public-settings/anon-tracking-enabled) "-analytics.com") ;; for webpack hot reloading (when config/is-dev? "*:8080") for react dev tools to work in Firefox until resolution of ;; (when config/is-dev? "'unsafe-inline'")] (when-not config/is-dev? (map (partial format "'sha256-%s'") inline-js-hashes))) :child-src ["'self'" TODO - double check that we actually need this for Google Auth ""] :style-src ["'self'" "'unsafe-inline'" ""] :font-src ["*"] :img-src ["*" "'self' data:"] :connect-src ["'self'" Google Identity Services "" MailChimp . So people can sign up for the Metabase mailing list in the sign up process "metabase.us10.list-manage.com" Google analytics (when (public-settings/anon-tracking-enabled) "www.google-analytics.com") Snowplow analytics (when (public-settings/anon-tracking-enabled) (snowplow/snowplow-url)) ;; Webpack dev server (when config/is-dev? "*:8080 ws://*:8080")] :manifest-src ["'self'"]}] (format "%s %s; " (name k) (str/join " " vs))))}) (defn- embedding-app-origin [] (when (and (public-settings/enable-embedding) (public-settings/embedding-app-origin)) (public-settings/embedding-app-origin))) (defn- content-security-policy-header-with-frame-ancestors [allow-iframes?] (update (content-security-policy-header) "Content-Security-Policy" #(format "%s frame-ancestors %s;" % (if allow-iframes? "*" (or (embedding-app-origin) "'none'"))))) (defsetting ssl-certificate-public-key (deferred-tru (str "Base-64 encoded public key for this site''s SSL certificate. " "Specify this to enable HTTP Public Key Pinning. " "See {0} for more information.") "")) ;; TODO - it would be nice if we could make this a proper link in the UI; consider enabling markdown parsing (defn- first-embedding-app-origin "Return only the first embedding app origin." [] (some-> (embedding-app-origin) (str/split #" ") first)) (defn security-headers "Fetch a map of security headers that should be added to a response based on the passed options." [& {:keys [allow-iframes? allow-cache?] :or {allow-iframes? false, allow-cache? false}}] (merge (if allow-cache? (cache-far-future-headers) (cache-prevention-headers)) strict-transport-security-header (content-security-policy-header-with-frame-ancestors allow-iframes?) (when-not allow-iframes? ;; Tell browsers not to render our site as an iframe (prevent clickjacking) {"X-Frame-Options" (if (embedding-app-origin) (format "ALLOW-FROM %s" (first-embedding-app-origin)) "DENY")}) { ;; Tell browser to block suspected XSS attacks "X-XSS-Protection" "1; mode=block" ;; Prevent Flash / PDF files from including content from site. "X-Permitted-Cross-Domain-Policies" "none" ;; Tell browser not to use MIME sniffing to guess types of files -- protect against MIME type confusion attacks "X-Content-Type-Options" "nosniff"})) (defn- add-security-headers* [request response] (update response :headers merge (security-headers :allow-iframes? ((some-fn request.u/public? request.u/embed?) request) :allow-cache? (request.u/cacheable? request)))) (defn add-security-headers "Add HTTP security and cache-busting headers." [handler] (fn [request respond raise] (handler request (comp respond (partial add-security-headers* request)) raise)))
null
https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/src/metabase/server/middleware/security.clj
clojure
inline script in init.html if sent in response to an HTTP request, this is simply ignored)" TODO - we keep working towards removing this entirely for webpack hot reloading Webpack dev server TODO - it would be nice if we could make this a proper link in the UI; consider enabling markdown parsing Tell browsers not to render our site as an iframe (prevent clickjacking) Tell browser to block suspected XSS attacks Prevent Flash / PDF files from including content from site. Tell browser not to use MIME sniffing to guess types of files -- protect against MIME type confusion attacks
(ns metabase.server.middleware.security "Ring middleware for adding security-related headers to API responses." (:require [clojure.java.io :as io] [clojure.string :as str] [java-time :as t] [metabase.analytics.snowplow :as snowplow] [metabase.config :as config] [metabase.models.setting :refer [defsetting]] [metabase.public-settings :as public-settings] [metabase.server.request.util :as request.u] [metabase.util.i18n :refer [deferred-tru]] [ring.util.codec :refer [base64-encode]]) (:import (java.security MessageDigest))) (set! *warn-on-reflection* true) (defonce ^:private ^:const inline-js-hashes (letfn [(file-hash [resource-filename] (base64-encode (.digest (doto (MessageDigest/getInstance "SHA-256") (.update (.getBytes (slurp (io/resource resource-filename))))))))] inline script in index.html that sets ` MetabaseBootstrap ` and the like "frontend_client/inline_js/index_bootstrap.js" inline script in index.html that loads Google Analytics "frontend_client/inline_js/index_ganalytics.js" "frontend_client/inline_js/init.js"]))) (defn- cache-prevention-headers "Headers that tell browsers not to cache a response." [] {"Cache-Control" "max-age=0, no-cache, must-revalidate, proxy-revalidate" "Expires" "Tue, 03 Jul 2001 06:00:00 GMT" "Last-Modified" (t/format :rfc-1123-date-time (t/zoned-date-time))}) (defn- cache-far-future-headers "Headers that tell browsers to cache a static resource for a long time." [] {"Cache-Control" "public, max-age=31536000"}) (def ^:private ^:const strict-transport-security-header "Tell browsers to only access this resource over HTTPS for the next year (prevent MTM attacks). (This only applies if {"Strict-Transport-Security" "max-age=31536000"}) (defn- content-security-policy-header "`Content-Security-Policy` header. See -security-policy.com for more details." [] {"Content-Security-Policy" (str/join (for [[k vs] {:default-src ["'none'"] :script-src (concat ["'self'" "" "" (when (public-settings/anon-tracking-enabled) "-analytics.com") (when config/is-dev? "*:8080") for react dev tools to work in Firefox until resolution of (when config/is-dev? "'unsafe-inline'")] (when-not config/is-dev? (map (partial format "'sha256-%s'") inline-js-hashes))) :child-src ["'self'" TODO - double check that we actually need this for Google Auth ""] :style-src ["'self'" "'unsafe-inline'" ""] :font-src ["*"] :img-src ["*" "'self' data:"] :connect-src ["'self'" Google Identity Services "" MailChimp . So people can sign up for the Metabase mailing list in the sign up process "metabase.us10.list-manage.com" Google analytics (when (public-settings/anon-tracking-enabled) "www.google-analytics.com") Snowplow analytics (when (public-settings/anon-tracking-enabled) (snowplow/snowplow-url)) (when config/is-dev? "*:8080 ws://*:8080")] :manifest-src ["'self'"]}] (format "%s %s; " (name k) (str/join " " vs))))}) (defn- embedding-app-origin [] (when (and (public-settings/enable-embedding) (public-settings/embedding-app-origin)) (public-settings/embedding-app-origin))) (defn- content-security-policy-header-with-frame-ancestors [allow-iframes?] (update (content-security-policy-header) "Content-Security-Policy" #(format "%s frame-ancestors %s;" % (if allow-iframes? "*" (or (embedding-app-origin) "'none'"))))) (defsetting ssl-certificate-public-key (deferred-tru (str "Base-64 encoded public key for this site''s SSL certificate. " "Specify this to enable HTTP Public Key Pinning. " "See {0} for more information.") "")) (defn- first-embedding-app-origin "Return only the first embedding app origin." [] (some-> (embedding-app-origin) (str/split #" ") first)) (defn security-headers "Fetch a map of security headers that should be added to a response based on the passed options." [& {:keys [allow-iframes? allow-cache?] :or {allow-iframes? false, allow-cache? false}}] (merge (if allow-cache? (cache-far-future-headers) (cache-prevention-headers)) strict-transport-security-header (content-security-policy-header-with-frame-ancestors allow-iframes?) (when-not allow-iframes? {"X-Frame-Options" (if (embedding-app-origin) (format "ALLOW-FROM %s" (first-embedding-app-origin)) "DENY")}) "X-XSS-Protection" "1; mode=block" "X-Permitted-Cross-Domain-Policies" "none" "X-Content-Type-Options" "nosniff"})) (defn- add-security-headers* [request response] (update response :headers merge (security-headers :allow-iframes? ((some-fn request.u/public? request.u/embed?) request) :allow-cache? (request.u/cacheable? request)))) (defn add-security-headers "Add HTTP security and cache-busting headers." [handler] (fn [request respond raise] (handler request (comp respond (partial add-security-headers* request)) raise)))
948ee1408aec5673249fb84d39306c04168b4fe2fb33d580ea72d567ab19e3a2
mpenet/commons
jvm.clj
(ns qbits.commons.jvm) (defn add-shutdown-hook! [f] (.addShutdownHook (Runtime/getRuntime) (Thread. ^Runnable f))) (defn set-uncaught-ex-handler! [f] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (f thread ex))))) (defmacro compile-if "Evaluate `exp` and if it returns logical true and doesn't error, expand to `then`. Else expand to `else`. (compile-if (Class/forName \"java.util.concurrent.ForkJoinTask\") (do-cool-stuff-with-fork-join) (fall-back-to-executor-services)) Taken from #L24" [exp then & [else]] (if (try (eval exp) (catch Throwable _ false)) `(do ~then) `(do ~else))) (defmacro compile-if-ns-exists [n then & [else]] `(compile-if (try (require (quote ~n)) true (catch Exception _# nil)) ~then ~else)) (defmacro compile-if-class-exists [k then & [else]] `(compile-if (Class/forName ~(str k)) ~then ~else))
null
https://raw.githubusercontent.com/mpenet/commons/a377fed3a5ef00ba26f704e39ca60ad4039870cb/src/clj/qbits/commons/jvm.clj
clojure
(ns qbits.commons.jvm) (defn add-shutdown-hook! [f] (.addShutdownHook (Runtime/getRuntime) (Thread. ^Runnable f))) (defn set-uncaught-ex-handler! [f] (Thread/setDefaultUncaughtExceptionHandler (reify Thread$UncaughtExceptionHandler (uncaughtException [_ thread ex] (f thread ex))))) (defmacro compile-if "Evaluate `exp` and if it returns logical true and doesn't error, expand to `then`. Else expand to `else`. (compile-if (Class/forName \"java.util.concurrent.ForkJoinTask\") (do-cool-stuff-with-fork-join) (fall-back-to-executor-services)) Taken from #L24" [exp then & [else]] (if (try (eval exp) (catch Throwable _ false)) `(do ~then) `(do ~else))) (defmacro compile-if-ns-exists [n then & [else]] `(compile-if (try (require (quote ~n)) true (catch Exception _# nil)) ~then ~else)) (defmacro compile-if-class-exists [k then & [else]] `(compile-if (Class/forName ~(str k)) ~then ~else))
e463a2a2f30c118daf1dd4c96643eae55acbb7331d45b192261cdfafb3c25908
input-output-hk/plutus-apps
Server.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} module Plutus.ChainIndex.Emulator.Server( serveChainIndexQueryServer, serveChainIndex) where import Control.Concurrent.STM (TVar) import Control.Concurrent.STM qualified as STM import Control.Monad.Except qualified as E import Control.Monad.Freer (Eff, interpret, run, type (~>)) import Control.Monad.Freer.Error (Error, runError) import Control.Monad.Freer.Extras.Log (handleLogIgnore) import Control.Monad.Freer.Extras.Modify (raiseEnd) import Control.Monad.Freer.State (evalState) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.ByteString.Lazy qualified as BSL import Data.Proxy (Proxy (..)) import Data.Text qualified as Text import Data.Text.Encoding qualified as Text import Network.Wai.Handler.Warp qualified as Warp import Plutus.ChainIndex (ChainIndexError, ChainIndexLog) import Plutus.ChainIndex.Api (API, FullAPI, swagger) import Plutus.ChainIndex.Effects (ChainIndexControlEffect, ChainIndexQueryEffect) import Plutus.ChainIndex.Emulator.Handlers (ChainIndexEmulatorState (..), handleControl, handleQuery) import Plutus.ChainIndex.Server hiding (serveChainIndexQueryServer) import Servant.API ((:<|>) (..)) import Servant.Server (Handler, ServerError, err500, errBody, hoistServer, serve) serveChainIndexQueryServer :: Int -- ^ Port ^ Chain index state ( TODO : When the disk state is stored in a DB , replace this with DB connection info ) -> IO () serveChainIndexQueryServer port diskState = do let server = hoistServer (Proxy @API) (runChainIndexQuery diskState) serveChainIndex Warp.run port (serve (Proxy @FullAPI) (server :<|> swagger)) runChainIndexQuery :: TVar ChainIndexEmulatorState -> Eff '[ChainIndexQueryEffect, ChainIndexControlEffect, Error ServerError] ~> Handler runChainIndexQuery emState_ action = do emState <- liftIO (STM.readTVarIO emState_) let result = run $ evalState emState $ runError @ChainIndexError $ handleLogIgnore @ChainIndexLog $ runError $ interpret handleControl $ interpret handleQuery $ raiseEnd action case result of Right (Right a) -> pure a Right (Left e) -> E.throwError e Left e' -> let err = err500 { errBody = BSL.fromStrict $ Text.encodeUtf8 $ Text.pack $ show e' } in E.throwError err
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/21d96e5908558a4c3b3234f6a2b63b4b6f7fdee6/plutus-chain-index-core/src/Plutus/ChainIndex/Emulator/Server.hs
haskell
# LANGUAGE MonoLocalBinds # # LANGUAGE RankNTypes # # LANGUAGE TypeOperators # ^ Port
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE TypeApplications # module Plutus.ChainIndex.Emulator.Server( serveChainIndexQueryServer, serveChainIndex) where import Control.Concurrent.STM (TVar) import Control.Concurrent.STM qualified as STM import Control.Monad.Except qualified as E import Control.Monad.Freer (Eff, interpret, run, type (~>)) import Control.Monad.Freer.Error (Error, runError) import Control.Monad.Freer.Extras.Log (handleLogIgnore) import Control.Monad.Freer.Extras.Modify (raiseEnd) import Control.Monad.Freer.State (evalState) import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.ByteString.Lazy qualified as BSL import Data.Proxy (Proxy (..)) import Data.Text qualified as Text import Data.Text.Encoding qualified as Text import Network.Wai.Handler.Warp qualified as Warp import Plutus.ChainIndex (ChainIndexError, ChainIndexLog) import Plutus.ChainIndex.Api (API, FullAPI, swagger) import Plutus.ChainIndex.Effects (ChainIndexControlEffect, ChainIndexQueryEffect) import Plutus.ChainIndex.Emulator.Handlers (ChainIndexEmulatorState (..), handleControl, handleQuery) import Plutus.ChainIndex.Server hiding (serveChainIndexQueryServer) import Servant.API ((:<|>) (..)) import Servant.Server (Handler, ServerError, err500, errBody, hoistServer, serve) serveChainIndexQueryServer :: ^ Chain index state ( TODO : When the disk state is stored in a DB , replace this with DB connection info ) -> IO () serveChainIndexQueryServer port diskState = do let server = hoistServer (Proxy @API) (runChainIndexQuery diskState) serveChainIndex Warp.run port (serve (Proxy @FullAPI) (server :<|> swagger)) runChainIndexQuery :: TVar ChainIndexEmulatorState -> Eff '[ChainIndexQueryEffect, ChainIndexControlEffect, Error ServerError] ~> Handler runChainIndexQuery emState_ action = do emState <- liftIO (STM.readTVarIO emState_) let result = run $ evalState emState $ runError @ChainIndexError $ handleLogIgnore @ChainIndexLog $ runError $ interpret handleControl $ interpret handleQuery $ raiseEnd action case result of Right (Right a) -> pure a Right (Left e) -> E.throwError e Left e' -> let err = err500 { errBody = BSL.fromStrict $ Text.encodeUtf8 $ Text.pack $ show e' } in E.throwError err
7c1ebbdf373bc33754daf074b75a4f7eda822f154fe79341cdfeb93f546e9b02
biegunka/biegunka
OK8.hs
# LANGUAGE DataKinds # -- | -- Chaining tests -- Checks you declare tasks prerequisites of another module Chaining where import Control.Biegunka import Control.Biegunka.Source.Directory chained_script_0 :: Script 'Sources () chained_script_0 = directory "/" pass `prerequisiteOf` directory "/" pass chained_script_1 :: Script 'Sources () chained_script_1 = directory "/" pass <~> directory "/" pass chained_script_2 :: Script 'Sources () chained_script_2 = directory "/" pass <~> directory "/" pass <~> directory "/" pass chained_script_3 :: Script 'Sources () chained_script_3 = do directory "/" pass directory "/" pass <~> directory "/" pass chained_script_4 :: Script 'Sources () chained_script_4 = do directory "/" pass directory "/" pass <~> do directory "/" pass directory "/" pass
null
https://raw.githubusercontent.com/biegunka/biegunka/74fc93326d5f29761125d7047d5418899fa2469d/test/typecheck/should_compile/OK8.hs
haskell
| Chaining tests
# LANGUAGE DataKinds # Checks you declare tasks prerequisites of another module Chaining where import Control.Biegunka import Control.Biegunka.Source.Directory chained_script_0 :: Script 'Sources () chained_script_0 = directory "/" pass `prerequisiteOf` directory "/" pass chained_script_1 :: Script 'Sources () chained_script_1 = directory "/" pass <~> directory "/" pass chained_script_2 :: Script 'Sources () chained_script_2 = directory "/" pass <~> directory "/" pass <~> directory "/" pass chained_script_3 :: Script 'Sources () chained_script_3 = do directory "/" pass directory "/" pass <~> directory "/" pass chained_script_4 :: Script 'Sources () chained_script_4 = do directory "/" pass directory "/" pass <~> do directory "/" pass directory "/" pass
54f8c78e9bf27bcb38075beef29db1e94ec9636a95c18b25d558791621edda72
facebookincubator/hsthrift
CallStack.hs
Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved . This source code is licensed under the BSD - style license found in the LICENSE file in the root directory of this source tree . Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. -} -- | Adds support to work with exceptions that pack a rendered call stack. module Util.Control.Exception.CallStack ( throwIO, throwSTM, ) where import Control.Concurrent.STM (STM) import qualified Control.Concurrent.STM as STM import qualified Control.Exception as E import Data.Text (Text, pack) import GHC.Stack ( HasCallStack, callStack, currentCallStack, prettyCallStack, renderStack, withFrozenCallStack, ) type CallStack = Text throwIO :: (E.Exception e, HasCallStack) => (CallStack -> e) -> IO a throwIO mkException = withFrozenCallStack $ do ccs <- currentCallStack let stack | null ccs = prettyCallStack callStack | otherwise = renderStack ccs E.throw $ mkException $ pack stack throwSTM :: (E.Exception e, HasCallStack) => (CallStack -> e) -> STM a throwSTM mkException = withFrozenCallStack $ do let stack = prettyCallStack callStack STM.throwSTM $ mkException $ pack stack
null
https://raw.githubusercontent.com/facebookincubator/hsthrift/18e247ee96a036fa3c159709e78178a2ceb7b8d0/common/util/Util/Control/Exception/CallStack.hs
haskell
| Adds support to work with exceptions that pack a rendered call stack.
Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved . This source code is licensed under the BSD - style license found in the LICENSE file in the root directory of this source tree . Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. -} module Util.Control.Exception.CallStack ( throwIO, throwSTM, ) where import Control.Concurrent.STM (STM) import qualified Control.Concurrent.STM as STM import qualified Control.Exception as E import Data.Text (Text, pack) import GHC.Stack ( HasCallStack, callStack, currentCallStack, prettyCallStack, renderStack, withFrozenCallStack, ) type CallStack = Text throwIO :: (E.Exception e, HasCallStack) => (CallStack -> e) -> IO a throwIO mkException = withFrozenCallStack $ do ccs <- currentCallStack let stack | null ccs = prettyCallStack callStack | otherwise = renderStack ccs E.throw $ mkException $ pack stack throwSTM :: (E.Exception e, HasCallStack) => (CallStack -> e) -> STM a throwSTM mkException = withFrozenCallStack $ do let stack = prettyCallStack callStack STM.throwSTM $ mkException $ pack stack
f3d08c42ad6cc8248813ae6d7f228961d7e843aac0a1d4c2b2219156caf38c58
tnelson/Forge
extendingSigs.rkt
#lang forge/core (set-option! 'verbose 0) (sig ToExtend) (sig Extension1 #:extends ToExtend) (sig Extension2 #:extends ToExtend) (sig Extension3 #:extends Extension2) (test extensionEnforced #:preds [(in (+ Extension1 Extension2) ToExtend)] #:expect theorem) (test multipleExtensions #:preds [(&& (some Extension1) (some Extension2))] #:expect sat) (test extensionsDisjoint #:preds [(some (& Extension1 Extension2))] #:expect unsat) (test extensionsNotExhaustive #:preds [(some (- ToExtend (+ Extension1 Extension2)))] #:expect sat) (test doubleExtendingWorks #:preds [(&& (in Extension3 Extension2) (in Extension2 ToExtend))] #:expect theorem) (sig Parent) (sig Child #:extends Parent) (relation parentRel (Parent Child)) (relation childRel (Child Parent)) (test relationsIntoExtension #:preds [(in (join Parent parentRel) Child)] #:expect theorem) (test extensionsInheritRelations #:preds [(some (join Child parentRel))] #:expect sat) (test parentsDontGetExtensionRelations #:preds [(in (join childRel Parent) Child)] #:expect theorem)
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/tests/forge-core/sigs/extendingSigs.rkt
racket
#lang forge/core (set-option! 'verbose 0) (sig ToExtend) (sig Extension1 #:extends ToExtend) (sig Extension2 #:extends ToExtend) (sig Extension3 #:extends Extension2) (test extensionEnforced #:preds [(in (+ Extension1 Extension2) ToExtend)] #:expect theorem) (test multipleExtensions #:preds [(&& (some Extension1) (some Extension2))] #:expect sat) (test extensionsDisjoint #:preds [(some (& Extension1 Extension2))] #:expect unsat) (test extensionsNotExhaustive #:preds [(some (- ToExtend (+ Extension1 Extension2)))] #:expect sat) (test doubleExtendingWorks #:preds [(&& (in Extension3 Extension2) (in Extension2 ToExtend))] #:expect theorem) (sig Parent) (sig Child #:extends Parent) (relation parentRel (Parent Child)) (relation childRel (Child Parent)) (test relationsIntoExtension #:preds [(in (join Parent parentRel) Child)] #:expect theorem) (test extensionsInheritRelations #:preds [(some (join Child parentRel))] #:expect sat) (test parentsDontGetExtensionRelations #:preds [(in (join childRel Parent) Child)] #:expect theorem)
4ab21858f02acacebc378bf226c390ea4f158a41efccf98800fa2fbffedde39e
dom96/ElysiaBot
AMI.hs
{-# LANGUAGE OverloadedStrings #-} import Prelude hiding (lookup) import PluginUtils import Network.SimpleIRC.Messages import qualified Data.ByteString.Char8 as B import Network.AMI import Control.Monad (forever) import Control.Monad.IO.Class (liftIO) import Data.ByteString (ByteString, empty, append) import Data.List (intercalate) import Data.Map (fromList, findWithDefault, lookup) import Data.Maybe (fromJust) import Text.Printf (printf) import Data.Char (toLower) info :: ConnectInfo info = ConnectInfo { ciHost = "asterisk.example.net" , ciPort = 5038 , ciUsername = "elysiabot" , ciSecret = "secretpassword" } -- this should be much better handleResponse :: Bool -> Response -> ByteString handleResponse quiet (Response aid rtype params bs) | quiet && rtype == "Success" = empty | otherwise = rtype `append` ": " `append` (findWithDefault "UNKNOWN!" "Message" (fromList params)) handleMeetmeListEvent : : EventHandler handleMeetmeListEvent addr cMsg ps = liftIO $ sendMsg $ B.pack $ printf "%s/#%s %s <%s> %s %s\n" confno userno callername callernum channel flags where confno = B.unpack $ findWithDefault "???" "Conference" (fromList ps) userno = B.unpack $ findWithDefault "?" "UserNumber" (fromList ps) callername = B.unpack $ findWithDefault "''" "CallerIDName" (fromList ps) callernum = B.unpack $ findWithDefault "???" "CallerIDNum" (fromList ps) channel = B.unpack $ findWithDefault "???" "Channel" (fromList ps) sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m flags :: String flags = intercalate " " $ map (\x -> prefixUn (map toLower x) (lookup (B.pack x) (fromList ps))) knownFlags where prefixUn :: String -> Maybe ByteString -> String prefixUn f Nothing = "" prefixUn f (Just yesorno) = if yesorno == "No" then ("un" ++ f) else f knownFlags :: [String] knownFlags = ["Admin", "MarkedUser", "Muted", "Talking"] main :: IO () main = initPlugin ["meetme"] [] onAmi meetmeDispatch mInfo (MsgCmd cMsg server prefix cmd rest) | B.length rest == 0 = return () | rest == "list" = withAMI_MD5 info $ do handleEvent "MeetmeList" (handleMeetmeListEvent addr cMsg) mml <- query "MeetmeList" liftIO $ sendMsg $ handleResponse True mml | "list " `B.isPrefixOf` rest = withAMI_MD5 info $ do handleEvent "MeetmeList" (handleMeetmeListEvent addr cMsg) mml <- query "MeetmeList" [("Conference", B.drop 5 rest)] liftIO $ sendMsg $ handleResponse True mml | rest == "mute" = liftIO $ sendMsg $ "usage: |meetme mute <confno> <userno>" | "mute " `B.isPrefixOf` rest && length scArgs == 2 = withAMI_MD5 info $ do mmm <- query "MeetmeMute" [("Meetme", head scArgs), ("Usernum", scArgs !! 1)] liftIO $ sendMsg $ handleResponse False mmm | "mute " `B.isPrefixOf` rest = liftIO $ sendMsg $ "usage: |meetme mute <confno> <userno>" | rest == "unmute" = liftIO $ sendMsg $ "usage: |meetme unmute <confno> <userno>" | "unmute " `B.isPrefixOf` rest && length scArgs == 2 = withAMI_MD5 info $ do mmu <- query "MeetmeUnmute" [("Meetme", head scArgs), ("Usernum", scArgs !! 1)] liftIO $ sendMsg $ handleResponse False mmu | "unmute " `B.isPrefixOf` rest = liftIO $ sendMsg $ "usage: |meetme unmute <confno> <userno>" | otherwise = liftIO $ sendMsg $ "Valid meetme subcommands: list, mute, unmute" where addr = address server msg = mMsg cMsg sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m scArgs = (drop 1 . B.words) rest onAmi mInfo (MsgCmd cMsg server prefix cmd rest) | cmd == "meetme" = meetmeDispatch mInfo (MsgCmd cMsg server prefix cmd rest) | otherwise = return () onAmi _ _ = return ()
null
https://raw.githubusercontent.com/dom96/ElysiaBot/3accf5825e67880c7f1696fc81e3fc449efe3294/src/Plugins/AMI/AMI.hs
haskell
# LANGUAGE OverloadedStrings # this should be much better
import Prelude hiding (lookup) import PluginUtils import Network.SimpleIRC.Messages import qualified Data.ByteString.Char8 as B import Network.AMI import Control.Monad (forever) import Control.Monad.IO.Class (liftIO) import Data.ByteString (ByteString, empty, append) import Data.List (intercalate) import Data.Map (fromList, findWithDefault, lookup) import Data.Maybe (fromJust) import Text.Printf (printf) import Data.Char (toLower) info :: ConnectInfo info = ConnectInfo { ciHost = "asterisk.example.net" , ciPort = 5038 , ciUsername = "elysiabot" , ciSecret = "secretpassword" } handleResponse :: Bool -> Response -> ByteString handleResponse quiet (Response aid rtype params bs) | quiet && rtype == "Success" = empty | otherwise = rtype `append` ": " `append` (findWithDefault "UNKNOWN!" "Message" (fromList params)) handleMeetmeListEvent : : EventHandler handleMeetmeListEvent addr cMsg ps = liftIO $ sendMsg $ B.pack $ printf "%s/#%s %s <%s> %s %s\n" confno userno callername callernum channel flags where confno = B.unpack $ findWithDefault "???" "Conference" (fromList ps) userno = B.unpack $ findWithDefault "?" "UserNumber" (fromList ps) callername = B.unpack $ findWithDefault "''" "CallerIDName" (fromList ps) callernum = B.unpack $ findWithDefault "???" "CallerIDNum" (fromList ps) channel = B.unpack $ findWithDefault "???" "Channel" (fromList ps) sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m flags :: String flags = intercalate " " $ map (\x -> prefixUn (map toLower x) (lookup (B.pack x) (fromList ps))) knownFlags where prefixUn :: String -> Maybe ByteString -> String prefixUn f Nothing = "" prefixUn f (Just yesorno) = if yesorno == "No" then ("un" ++ f) else f knownFlags :: [String] knownFlags = ["Admin", "MarkedUser", "Muted", "Talking"] main :: IO () main = initPlugin ["meetme"] [] onAmi meetmeDispatch mInfo (MsgCmd cMsg server prefix cmd rest) | B.length rest == 0 = return () | rest == "list" = withAMI_MD5 info $ do handleEvent "MeetmeList" (handleMeetmeListEvent addr cMsg) mml <- query "MeetmeList" liftIO $ sendMsg $ handleResponse True mml | "list " `B.isPrefixOf` rest = withAMI_MD5 info $ do handleEvent "MeetmeList" (handleMeetmeListEvent addr cMsg) mml <- query "MeetmeList" [("Conference", B.drop 5 rest)] liftIO $ sendMsg $ handleResponse True mml | rest == "mute" = liftIO $ sendMsg $ "usage: |meetme mute <confno> <userno>" | "mute " `B.isPrefixOf` rest && length scArgs == 2 = withAMI_MD5 info $ do mmm <- query "MeetmeMute" [("Meetme", head scArgs), ("Usernum", scArgs !! 1)] liftIO $ sendMsg $ handleResponse False mmm | "mute " `B.isPrefixOf` rest = liftIO $ sendMsg $ "usage: |meetme mute <confno> <userno>" | rest == "unmute" = liftIO $ sendMsg $ "usage: |meetme unmute <confno> <userno>" | "unmute " `B.isPrefixOf` rest && length scArgs == 2 = withAMI_MD5 info $ do mmu <- query "MeetmeUnmute" [("Meetme", head scArgs), ("Usernum", scArgs !! 1)] liftIO $ sendMsg $ handleResponse False mmu | "unmute " `B.isPrefixOf` rest = liftIO $ sendMsg $ "usage: |meetme unmute <confno> <userno>" | otherwise = liftIO $ sendMsg $ "Valid meetme subcommands: list, mute, unmute" where addr = address server msg = mMsg cMsg sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m scArgs = (drop 1 . B.words) rest onAmi mInfo (MsgCmd cMsg server prefix cmd rest) | cmd == "meetme" = meetmeDispatch mInfo (MsgCmd cMsg server prefix cmd rest) | otherwise = return () onAmi _ _ = return ()
e0825f737da43924c62d7b37dd863f7ef031371e6be77f356ba3e79a819c6add
fulcrologic/guardrails
config.cljc
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the Eclipse Public License 2.0 ( -2.0/ ) ;; which can be found in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:no-doc com.fulcrologic.guardrails.config #?(:cljs (:require-macros com.fulcrologic.guardrails.config)) (:require [com.fulcrologic.guardrails.utils :as utils] #?@(:clj [[clojure.edn :as edn]] :cljs [[cljs.env :as cljs-env]]))) ;; This isn't particularly pretty, but it's how we avoid having ClojureScript as a required dependency on Clojure #?(:bb (require '[com.fulcrologic.guardrails.stubs.cljs-env :as cljs-env]) :clj (try (ns-unalias (find-ns 'com.fulcrologic.guardrails.utils) 'cljs-env) (require '[cljs.env :as cljs-env]) (catch Exception _ (require '[com.fulcrologic.guardrails.stubs.cljs-env :as cljs-env])))) (defn mode [config] (get config :mode :runtime)) (defn async? [config] (get config :async? false)) (def default-config {;; Generates standard `defn` function definitions ;; by default. If you require composability with other ` defn`-like macros , you can have to ;; them instead by setting the macro name as a string here. :defn-macro nil ;; Nilable map of Expound configuration options. ;; If not nil, the spec printer will be set to ;; expound's with the given configuration options. :expound {:show-valid-values? true :print-specs? true}}) (let [*config-cache (atom {::timestamp 0 ::value nil}) warned? (atom false) read-config-file (fn [] #?(:clj (try (edn/read-string (slurp (or (System/getProperty "guardrails.config") "guardrails.edn"))) (catch Exception _ nil)) :cljs nil)) reload-config (fn [] # ? (: ( .println System / err ( get @cljs - env/*compiler * : options ) ) ) ; DEBUG (let [config (let [cljs-compiler-config (when cljs-env/*compiler* (get-in @cljs-env/*compiler* [:options :external-config :guardrails]))] (when #?(:clj (or cljs-compiler-config (System/getProperty "guardrails.enabled")) :cljs false) (let [{:keys [async? throw?] :as result} (merge {} (read-config-file)) result (if (and async? throw?) (dissoc result :async?) result)] (when-not @warned? (reset! warned? true) (utils/report-problem "GUARDRAILS IS ENABLED. RUNTIME PERFORMANCE WILL BE AFFECTED.") (when (and async? throw?) (utils/report-problem "INCOMPATIBLE MODES: :throw? and :async? cannot both be true. Disabling async.")) (utils/report-problem (str "Mode: " (mode result) (when (= :runtime (mode result)) (str " Async? " (boolean (:async? result)) " Throw? " (boolean (:throw? result)))))) (utils/report-problem (str "Guardrails was enabled because " (if cljs-compiler-config "the CLJS Compiler config enabled it" "the guardrails.enabled property is set to a (any) value.")))) result)))] # ? (: ( .println System / err config ) ) ; DEBUG config))] (defn get-env-config ([] (get-env-config true)) ([cache?] (let [result (if (or (not cache?) #?(:clj (= "false" (System/getProperty "guardrails.cache")))) (reload-config) (let [now (identity #?(:clj (System/currentTimeMillis) :cljs (js/Date.now))) since-last (- now (::timestamp @*config-cache))] (if (< since-last 2000) (::value @*config-cache) (::value (reset! *config-cache {::timestamp now ::value (reload-config)}))))) cljs-compiler-config (when cljs-env/*compiler* (get-in @cljs-env/*compiler* [:options :external-config :guardrails])) mode-config #?(:cljs nil :clj (when-let [mode (System/getProperty "guardrails.mode")] (let [?mode (read-string mode)] (if (#{:runtime :pro :all :copilot} ?mode) {:mode ?mode} (.println System/err (format "Unknown guardrails mode %s, defaulting to :runtime" mode))))))] #?(:clj (when (and result cljs-env/*compiler*) (let [production? (contains? #{:advanced :whitespace :simple} (get-in @cljs-env/*compiler* [:options :optimizations]))] (when (and production? (not= "production" (System/getProperty "guardrails.enabled"))) (throw (ex-info (str "REFUSING TO COMPILE PRODUCTION BUILD WITH GUARDRAILS ENABLED!. If you really want to take " "that performance hit then set the JVM properter guardrails.enabled to \"production\" on the CLJS compiler's JVM") {})))))) (merge result cljs-compiler-config mode-config))))) (defn get-base-config-fn "Base config is defaults + env config." ([] (get-base-config-fn true)) ([cache?] (->> (get-env-config cache?) (merge default-config)))) (defmacro get-base-config-macro ([] (get-base-config-fn)) ([cache?] (get-base-config-fn cache?))) (defn merge-config [env & meta-maps] (let [config (->> (apply merge-with (fn [a b] (if (every? map? [a b]) (merge a b) b)) (get-base-config-fn) (utils/get-ns-meta env) meta-maps) (into {}))] config))
null
https://raw.githubusercontent.com/fulcrologic/guardrails/17b47a7869314efbffe5dbe0c0daea7c30ed9006/src/main/com/fulcrologic/guardrails/config.cljc
clojure
The use and distribution terms for this software are covered by the which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. This isn't particularly pretty, but it's how we avoid Generates standard `defn` function definitions by default. If you require composability with other them instead by setting the macro name as a string here. Nilable map of Expound configuration options. If not nil, the spec printer will be set to expound's with the given configuration options. DEBUG DEBUG
Copyright ( c ) . All rights reserved . Eclipse Public License 2.0 ( -2.0/ ) (ns ^:no-doc com.fulcrologic.guardrails.config #?(:cljs (:require-macros com.fulcrologic.guardrails.config)) (:require [com.fulcrologic.guardrails.utils :as utils] #?@(:clj [[clojure.edn :as edn]] :cljs [[cljs.env :as cljs-env]]))) having ClojureScript as a required dependency on Clojure #?(:bb (require '[com.fulcrologic.guardrails.stubs.cljs-env :as cljs-env]) :clj (try (ns-unalias (find-ns 'com.fulcrologic.guardrails.utils) 'cljs-env) (require '[cljs.env :as cljs-env]) (catch Exception _ (require '[com.fulcrologic.guardrails.stubs.cljs-env :as cljs-env])))) (defn mode [config] (get config :mode :runtime)) (defn async? [config] (get config :async? false)) (def default-config ` defn`-like macros , you can have to :defn-macro nil :expound {:show-valid-values? true :print-specs? true}}) (let [*config-cache (atom {::timestamp 0 ::value nil}) warned? (atom false) read-config-file (fn [] #?(:clj (try (edn/read-string (slurp (or (System/getProperty "guardrails.config") "guardrails.edn"))) (catch Exception _ nil)) :cljs nil)) reload-config (fn [] (let [config (let [cljs-compiler-config (when cljs-env/*compiler* (get-in @cljs-env/*compiler* [:options :external-config :guardrails]))] (when #?(:clj (or cljs-compiler-config (System/getProperty "guardrails.enabled")) :cljs false) (let [{:keys [async? throw?] :as result} (merge {} (read-config-file)) result (if (and async? throw?) (dissoc result :async?) result)] (when-not @warned? (reset! warned? true) (utils/report-problem "GUARDRAILS IS ENABLED. RUNTIME PERFORMANCE WILL BE AFFECTED.") (when (and async? throw?) (utils/report-problem "INCOMPATIBLE MODES: :throw? and :async? cannot both be true. Disabling async.")) (utils/report-problem (str "Mode: " (mode result) (when (= :runtime (mode result)) (str " Async? " (boolean (:async? result)) " Throw? " (boolean (:throw? result)))))) (utils/report-problem (str "Guardrails was enabled because " (if cljs-compiler-config "the CLJS Compiler config enabled it" "the guardrails.enabled property is set to a (any) value.")))) result)))] config))] (defn get-env-config ([] (get-env-config true)) ([cache?] (let [result (if (or (not cache?) #?(:clj (= "false" (System/getProperty "guardrails.cache")))) (reload-config) (let [now (identity #?(:clj (System/currentTimeMillis) :cljs (js/Date.now))) since-last (- now (::timestamp @*config-cache))] (if (< since-last 2000) (::value @*config-cache) (::value (reset! *config-cache {::timestamp now ::value (reload-config)}))))) cljs-compiler-config (when cljs-env/*compiler* (get-in @cljs-env/*compiler* [:options :external-config :guardrails])) mode-config #?(:cljs nil :clj (when-let [mode (System/getProperty "guardrails.mode")] (let [?mode (read-string mode)] (if (#{:runtime :pro :all :copilot} ?mode) {:mode ?mode} (.println System/err (format "Unknown guardrails mode %s, defaulting to :runtime" mode))))))] #?(:clj (when (and result cljs-env/*compiler*) (let [production? (contains? #{:advanced :whitespace :simple} (get-in @cljs-env/*compiler* [:options :optimizations]))] (when (and production? (not= "production" (System/getProperty "guardrails.enabled"))) (throw (ex-info (str "REFUSING TO COMPILE PRODUCTION BUILD WITH GUARDRAILS ENABLED!. If you really want to take " "that performance hit then set the JVM properter guardrails.enabled to \"production\" on the CLJS compiler's JVM") {})))))) (merge result cljs-compiler-config mode-config))))) (defn get-base-config-fn "Base config is defaults + env config." ([] (get-base-config-fn true)) ([cache?] (->> (get-env-config cache?) (merge default-config)))) (defmacro get-base-config-macro ([] (get-base-config-fn)) ([cache?] (get-base-config-fn cache?))) (defn merge-config [env & meta-maps] (let [config (->> (apply merge-with (fn [a b] (if (every? map? [a b]) (merge a b) b)) (get-base-config-fn) (utils/get-ns-meta env) meta-maps) (into {}))] config))
3e6ee09e6b6b4a9576654a571a3045d4fdc68f6484986ef54c4f5a0223fd0807
pa-ba/compdata-param
Injections.hs
# LANGUAGE TemplateHaskell # -------------------------------------------------------------------------------- -- | Module : Data . Comp . . Multi . Derive . Injections Copyright : ( c ) 2011 , -- License : BSD3 Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC Extensions ) -- -- Derive functions for signature injections. -- -------------------------------------------------------------------------------- module Data.Comp.Param.Multi.Derive.Injections ( injn, injectn, deepInjectn ) where import Language.Haskell.TH hiding (Cxt) import Data.Comp.Param.Multi.HDifunctor import Data.Comp.Param.Multi.Term import Data.Comp.Param.Multi.Algebra (CxtFun, appSigFun) import Data.Comp.Param.Multi.Ops ((:+:)(..), (:<:)(..)) injn :: Int -> Q [Dec] injn n = do let i = mkName $ "inj" ++ show n let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let avar = mkName "a" let bvar = mkName "b" let ivar = mkName "i" let xvar = mkName "x" let d = [funD i [clause [varP xvar] (normalB $ genDecl xvar n) []]] sequence $ sigD i (genSig fvars gvar avar bvar ivar) : d where genSig fvars gvar avar bvar ivar = do let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let tp' = arrowT `appT` (tp `appT` varT avar `appT` varT bvar `appT` varT ivar) `appT` (varT gvar `appT` varT avar `appT` varT bvar `appT` varT ivar) forallT (map PlainTV $ gvar : avar : bvar : ivar : fvars) (sequence cxt) tp' genDecl x n = [| case $(varE x) of Inl x -> $(varE $ mkName "inj") x Inr x -> $(varE $ mkName $ "inj" ++ if n > 2 then show (n - 1) else "") x |] injectn :: Int -> Q [Dec] injectn n = do let i = mkName ("inject" ++ show n) let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let avar = mkName "a" let bvar = mkName "b" let ivar = mkName "i" let d = [funD i [clause [] (normalB $ genDecl n) []]] sequence $ sigD i (genSig fvars gvar avar bvar ivar) : d where genSig fvars gvar avar bvar ivar = do let hvar = mkName "h" let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let tp' = conT ''Cxt `appT` varT hvar `appT` varT gvar `appT` varT avar `appT` varT bvar let tp'' = arrowT `appT` (tp `appT` varT avar `appT` tp' `appT` varT ivar) `appT` (tp' `appT` varT ivar) forallT (map PlainTV $ hvar : gvar : avar : bvar : ivar : fvars) (sequence cxt) tp'' genDecl n = [| In . $(varE $ mkName $ "inj" ++ show n) |] deepInjectn :: Int -> Q [Dec] deepInjectn n = do let i = mkName ("deepInject" ++ show n) let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let d = [funD i [clause [] (normalB $ genDecl n) []]] sequence $ sigD i (genSig fvars gvar) : d where genSig fvars gvar = do let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let cxt' = conT ''HDifunctor `appT` tp let tp' = conT ''CxtFun `appT` tp `appT` varT gvar forallT (map PlainTV $ gvar : fvars) (sequence $ cxt' : cxt) tp' genDecl n = [| appSigFun $(varE $ mkName $ "inj" ++ show n) |]
null
https://raw.githubusercontent.com/pa-ba/compdata-param/5d6b0afa95a27fd3233f86e5efc6e6a6080f4236/src/Data/Comp/Param/Multi/Derive/Injections.hs
haskell
------------------------------------------------------------------------------ | License : BSD3 Stability : experimental Derive functions for signature injections. ------------------------------------------------------------------------------
# LANGUAGE TemplateHaskell # Module : Data . Comp . . Multi . Derive . Injections Copyright : ( c ) 2011 , Maintainer : < > Portability : non - portable ( GHC Extensions ) module Data.Comp.Param.Multi.Derive.Injections ( injn, injectn, deepInjectn ) where import Language.Haskell.TH hiding (Cxt) import Data.Comp.Param.Multi.HDifunctor import Data.Comp.Param.Multi.Term import Data.Comp.Param.Multi.Algebra (CxtFun, appSigFun) import Data.Comp.Param.Multi.Ops ((:+:)(..), (:<:)(..)) injn :: Int -> Q [Dec] injn n = do let i = mkName $ "inj" ++ show n let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let avar = mkName "a" let bvar = mkName "b" let ivar = mkName "i" let xvar = mkName "x" let d = [funD i [clause [varP xvar] (normalB $ genDecl xvar n) []]] sequence $ sigD i (genSig fvars gvar avar bvar ivar) : d where genSig fvars gvar avar bvar ivar = do let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let tp' = arrowT `appT` (tp `appT` varT avar `appT` varT bvar `appT` varT ivar) `appT` (varT gvar `appT` varT avar `appT` varT bvar `appT` varT ivar) forallT (map PlainTV $ gvar : avar : bvar : ivar : fvars) (sequence cxt) tp' genDecl x n = [| case $(varE x) of Inl x -> $(varE $ mkName "inj") x Inr x -> $(varE $ mkName $ "inj" ++ if n > 2 then show (n - 1) else "") x |] injectn :: Int -> Q [Dec] injectn n = do let i = mkName ("inject" ++ show n) let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let avar = mkName "a" let bvar = mkName "b" let ivar = mkName "i" let d = [funD i [clause [] (normalB $ genDecl n) []]] sequence $ sigD i (genSig fvars gvar avar bvar ivar) : d where genSig fvars gvar avar bvar ivar = do let hvar = mkName "h" let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let tp' = conT ''Cxt `appT` varT hvar `appT` varT gvar `appT` varT avar `appT` varT bvar let tp'' = arrowT `appT` (tp `appT` varT avar `appT` tp' `appT` varT ivar) `appT` (tp' `appT` varT ivar) forallT (map PlainTV $ hvar : gvar : avar : bvar : ivar : fvars) (sequence cxt) tp'' genDecl n = [| In . $(varE $ mkName $ "inj" ++ show n) |] deepInjectn :: Int -> Q [Dec] deepInjectn n = do let i = mkName ("deepInject" ++ show n) let fvars = map (\n -> mkName $ 'f' : show n) [1..n] let gvar = mkName "g" let d = [funD i [clause [] (normalB $ genDecl n) []]] sequence $ sigD i (genSig fvars gvar) : d where genSig fvars gvar = do let cxt = map (\f -> (conT ''(:<:) `appT` varT f) `appT` varT gvar) fvars let tp = foldl1 (\a f -> conT ''(:+:) `appT` f `appT` a) (map varT fvars) let cxt' = conT ''HDifunctor `appT` tp let tp' = conT ''CxtFun `appT` tp `appT` varT gvar forallT (map PlainTV $ gvar : fvars) (sequence $ cxt' : cxt) tp' genDecl n = [| appSigFun $(varE $ mkName $ "inj" ++ show n) |]
733c2ec26a4bc9c3e994148cd902cba02f6360c632385872a45fc5779ced5a2a
lispbuilder/lispbuilder
library.lisp
;;; -*- lisp -*- (in-package #:lispbuilder-opengl) (cffi:define-foreign-library GL (:darwin (:framework "OpenGL")) (:windows "OPENGL32.dll") (:unix (:or "libGL" "libGL.so.2" "libGL.so.1"))) (cffi:use-foreign-library GL)
null
https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-opengl/opengl/library.lisp
lisp
-*- lisp -*-
(in-package #:lispbuilder-opengl) (cffi:define-foreign-library GL (:darwin (:framework "OpenGL")) (:windows "OPENGL32.dll") (:unix (:or "libGL" "libGL.so.2" "libGL.so.1"))) (cffi:use-foreign-library GL)
fd47e1afc1259cdb565a3ec621dcd18efac7fc8d25ba729f89df09b595a16ecf
TyOverby/mono
attr.mli
open Virtual_dom.Vdom.Attr open Core type align_options = | None | X_max_y_max | X_max_y_mid | X_max_y_min | X_mid_y_max | X_mid_y_mid | X_mid_y_min | X_min_y_max | X_min_y_mid | X_min_y_min type units = | Object_bounding_box | User_space_on_use type angle = | Deg of float | Grad of float | Rad of float | Turn of float type path_op = | Move_to_abs of { x : float ; y : float } | Move_to_rel of { x : float ; y : float } | Line_to_abs of { x : float ; y : float } | Line_to_rel of { x : float ; y : float } | Arc_to_abs of { rx : float ; ry : float ; x_axis_rotation : float ; large_arc : bool ; sweep : bool ; x : float ; y : float } | Arc_to_rel of { rx : float ; ry : float ; x_axis_rotation : float ; large_arc : bool ; sweep : bool ; dx : float ; dy : float } | Cubic_abs of { x1 : float ; y1 : float ; x2 : float ; y2 : float ; x : float ; y : float } | Cubic_rel of { x1 : float ; y1 : float ; x2 : float ; y2 : float ; x : float ; y : float } | Cubic_smooth_abs of { x2 : float ; y2 : float ; x : float ; y : float } | Cubic_smooth_rel of { x2 : float ; y2 : float ; x : float ; y : float } | Quadratic_abs of { x1 : float ; y1 : float ; x : float ; y : float } | Quadratic_rel of { x1 : float ; y1 : float ; x : float ; y : float } | Quadratic_smooth_abs of { x : float ; y : float } | Quadratic_smooth_rel of { x : float ; y : float } | Close_path type transform_op = | Matrix of float * float * float * float * float * float | Translate of { dx : float ; dy : float } | Scale of { sx : float ; sy : float } | Rotate of { a : [ `Deg of float ] ; x : float ; y : float } | Skew_x of float | Skew_y of float val viewbox : min_x:float -> min_y:float -> width:float -> height:float -> t * { 1 < a > } val href : string -> t * { 1 many things } val transform : transform_op list -> t * { 1 < circle > } val cx : float -> t val cy : float -> t val r : float -> t (** nothing for <defs> *) * { 1 < ellipse > } (** shares cx and cy with circle*) val rx : float -> t val ry : float -> t (** nothing for <g> *) * { 1 < image > } val x : float -> t val y : float -> t val width : float -> t val height : float -> t val xlink_href : string -> t val preserve_aspect_ratio : align:align_options -> ?meet_or_slice:[ `Meet | `Slice ] -> unit -> t * { 1 < line > } val x1 : float -> t val x2 : float -> t val y1 : float -> t val y2 : float -> t * { 1 < linearGradient > } (** shares href with <a>, x1, x2, y1, y2 with <line> *) val gradient_units : units -> t val gradient_transform : transform_op list -> t * { 1 < marker > } * viewBox is shared with < svg > , preserveAspecteRatio is shared with < image > val marker_height : float -> t val marker_width : float -> t val marker_units : units -> t val orient : [ `Angle of angle | `Auto | `Auto_start_reverse ] -> t val refX : float -> t val refY : float -> t * { 1 < mask > } (** shares width, height, x, and y with <image> *) val mask_units : units -> t val mask_content_units : units -> t * { 1 < path > } val d : path_op list -> t * { 1 < polygon > } val points : (float * float) list -> t val fill : [< `Url of string | Css_gen.Color.t ] -> t val stroke : [< Css_gen.Color.t ] -> t val stroke_width : float -> t val stroke_linecap : [ `Butt | `Round | `Square ] -> t val stroke_dasharray : float list -> t * { 1 < polyline > } (** shares points with <polygon> *) * { 1 < radialGradient > } * shares spreadMethod with < linearGradient > shares cx , cy , r with < circle > val fx : float -> t val fy : float -> t val fr : float -> t val spread_method : [ `Pad | `Reflect | `Repeat ] -> t * Nothing to do for < rect > because shares x , y , rx and , height with < image > height with <image> *) * { 1 < stop > } val offset : Percent.t -> t val stop_color : [< Css_gen.Color.t ] -> t val stop_opacity : Percent.t -> t (** nothing to do for <style> *) * Nothing to do for < symbol > as refX and refY is shared with < marker > , viewBox is shared with < svg > , x , y , width , and height are shared with < image > , <marker>, viewBox is shared with <svg>, x, y, width, and height are shared with <image>, *) * { 1 < text > } (** x and y is shared with <image> *) val dx : float -> t val dy : float -> t module Text : sig val start_offset : [ Css_gen.Length.t | `Percentage of Percent.t | `Number of float ] -> t val text_length : [ Css_gen.Length.t | `Percentage of Percent.t | `Number of float ] -> t * { 1 < textPath > } * shares with < text > val length_adjust : [ `Spacing | `Spacing_and_glyphs ] -> t val side : [ `Left | `Right ] -> t * Nothing to do for < title > Nothing to do for < tspan > as it shares everything with text Nothing to do for < use > as it shares href with < linearGradient > , x , y , width , and height with < image > Nothing to do for <tspan> as it shares everything with text Nothing to do for <use> as it shares href with <linearGradient>, x, y, width, and height with <image> *) val spacing : [ `Auto | `Exact ] -> t end val ( @ ) : t -> t -> t
null
https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-virtual_dom/svg/src/attr.mli
ocaml
* nothing for <defs> * shares cx and cy with circle * nothing for <g> * shares href with <a>, x1, x2, y1, y2 with <line> * shares width, height, x, and y with <image> * shares points with <polygon> * nothing to do for <style> * x and y is shared with <image>
open Virtual_dom.Vdom.Attr open Core type align_options = | None | X_max_y_max | X_max_y_mid | X_max_y_min | X_mid_y_max | X_mid_y_mid | X_mid_y_min | X_min_y_max | X_min_y_mid | X_min_y_min type units = | Object_bounding_box | User_space_on_use type angle = | Deg of float | Grad of float | Rad of float | Turn of float type path_op = | Move_to_abs of { x : float ; y : float } | Move_to_rel of { x : float ; y : float } | Line_to_abs of { x : float ; y : float } | Line_to_rel of { x : float ; y : float } | Arc_to_abs of { rx : float ; ry : float ; x_axis_rotation : float ; large_arc : bool ; sweep : bool ; x : float ; y : float } | Arc_to_rel of { rx : float ; ry : float ; x_axis_rotation : float ; large_arc : bool ; sweep : bool ; dx : float ; dy : float } | Cubic_abs of { x1 : float ; y1 : float ; x2 : float ; y2 : float ; x : float ; y : float } | Cubic_rel of { x1 : float ; y1 : float ; x2 : float ; y2 : float ; x : float ; y : float } | Cubic_smooth_abs of { x2 : float ; y2 : float ; x : float ; y : float } | Cubic_smooth_rel of { x2 : float ; y2 : float ; x : float ; y : float } | Quadratic_abs of { x1 : float ; y1 : float ; x : float ; y : float } | Quadratic_rel of { x1 : float ; y1 : float ; x : float ; y : float } | Quadratic_smooth_abs of { x : float ; y : float } | Quadratic_smooth_rel of { x : float ; y : float } | Close_path type transform_op = | Matrix of float * float * float * float * float * float | Translate of { dx : float ; dy : float } | Scale of { sx : float ; sy : float } | Rotate of { a : [ `Deg of float ] ; x : float ; y : float } | Skew_x of float | Skew_y of float val viewbox : min_x:float -> min_y:float -> width:float -> height:float -> t * { 1 < a > } val href : string -> t * { 1 many things } val transform : transform_op list -> t * { 1 < circle > } val cx : float -> t val cy : float -> t val r : float -> t * { 1 < ellipse > } val rx : float -> t val ry : float -> t * { 1 < image > } val x : float -> t val y : float -> t val width : float -> t val height : float -> t val xlink_href : string -> t val preserve_aspect_ratio : align:align_options -> ?meet_or_slice:[ `Meet | `Slice ] -> unit -> t * { 1 < line > } val x1 : float -> t val x2 : float -> t val y1 : float -> t val y2 : float -> t * { 1 < linearGradient > } val gradient_units : units -> t val gradient_transform : transform_op list -> t * { 1 < marker > } * viewBox is shared with < svg > , preserveAspecteRatio is shared with < image > val marker_height : float -> t val marker_width : float -> t val marker_units : units -> t val orient : [ `Angle of angle | `Auto | `Auto_start_reverse ] -> t val refX : float -> t val refY : float -> t * { 1 < mask > } val mask_units : units -> t val mask_content_units : units -> t * { 1 < path > } val d : path_op list -> t * { 1 < polygon > } val points : (float * float) list -> t val fill : [< `Url of string | Css_gen.Color.t ] -> t val stroke : [< Css_gen.Color.t ] -> t val stroke_width : float -> t val stroke_linecap : [ `Butt | `Round | `Square ] -> t val stroke_dasharray : float list -> t * { 1 < polyline > } * { 1 < radialGradient > } * shares spreadMethod with < linearGradient > shares cx , cy , r with < circle > val fx : float -> t val fy : float -> t val fr : float -> t val spread_method : [ `Pad | `Reflect | `Repeat ] -> t * Nothing to do for < rect > because shares x , y , rx and , height with < image > height with <image> *) * { 1 < stop > } val offset : Percent.t -> t val stop_color : [< Css_gen.Color.t ] -> t val stop_opacity : Percent.t -> t * Nothing to do for < symbol > as refX and refY is shared with < marker > , viewBox is shared with < svg > , x , y , width , and height are shared with < image > , <marker>, viewBox is shared with <svg>, x, y, width, and height are shared with <image>, *) * { 1 < text > } val dx : float -> t val dy : float -> t module Text : sig val start_offset : [ Css_gen.Length.t | `Percentage of Percent.t | `Number of float ] -> t val text_length : [ Css_gen.Length.t | `Percentage of Percent.t | `Number of float ] -> t * { 1 < textPath > } * shares with < text > val length_adjust : [ `Spacing | `Spacing_and_glyphs ] -> t val side : [ `Left | `Right ] -> t * Nothing to do for < title > Nothing to do for < tspan > as it shares everything with text Nothing to do for < use > as it shares href with < linearGradient > , x , y , width , and height with < image > Nothing to do for <tspan> as it shares everything with text Nothing to do for <use> as it shares href with <linearGradient>, x, y, width, and height with <image> *) val spacing : [ `Auto | `Exact ] -> t end val ( @ ) : t -> t -> t
c3223d1ff2dbeec8413fa55500014ee0225139ed08f9d794bfed9473ea30bd10
atdixon/me.untethr.nostr-relay
fulfill_test.clj
(ns test.fulfill-test (:require [clojure.test :refer :all] [me.untethr.nostr.common.domain :as domain] [me.untethr.nostr.fulfill :as fulfill] [me.untethr.nostr.app :as app] [next.jdbc :as jdbc] [test.support :as support] [test.test-data :as test-data] [me.untethr.nostr.common.metrics :as metrics]) (:import (java.util.concurrent Future TimeUnit Semaphore))) (defn- query-max-id [db table-name] (:max_id (jdbc/execute-one! db [(format "select max(id) as max_id from %s" table-name)]))) (deftest fulfill-test (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (swap! results-atom conj res)) #(swap! eose-atom inc)) ;; cause test to swap! if inc the async work _ (.get f 1000 TimeUnit/MILLISECONDS)] (is (.isDone f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) we expect 7 results -- b / c we 're using /submit ! + fulfill - entirely ! ;; and even if index query doesn't de-duplicate the kv lookup will ;; de-dupe for the single fulfillment page (is (= 7 (count @results-atom))) (is (= 1 @eose-atom)) ;; verify the results are json strings that can be parsed (is (= (into #{} (subvec (:pool test-data/pool-with-filters) 1 8)) (into #{} (map #'app/parse) @results-atom))) ;; ensure cancellation -- a no-op, now that we're done -- leaves us ;; with an empty registry (fulfill/cancel! fulfill-atom "chan-id" "req-id") (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-with-batching-test (with-redefs [fulfill/batch-size 2] (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit-use-batching! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (swap! results-atom conj res)) #(swap! eose-atom inc)) ;; cause test to swap! if inc the async work _ (.get f 1000 TimeUnit/MILLISECONDS)] (is (.isDone f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) 7 ! ! ! we redef our page size above to 2 but we still get a expected ;; count b/c we're de-duping across pages and we walk **backward* from ;; latest results: (is (= 7 (count @results-atom))) (is (= 1 @eose-atom)) ;; verify the results are json strings that can be parsed (is (= (into #{} (subvec (:pool test-data/pool-with-filters) 1 8)) (into #{} (map #'app/parse) @results-atom))) ;; ensure cancellation -- a no-op, now that we're done -- leaves us ;; with an empty registry (fulfill/cancel! fulfill-atom "chan-id" "req-id") (is (= (fulfill/create-empty-registry) @fulfill-atom))))))) (defn- run-interruption-test [cancel-fn] (support/with-memory-db-new-schema [db] (support/with-memory-db-kv-schema [db-kv] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [semaphore (Semaphore. 0) results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] ;; block so our cancellation is guaranteed to cancel ;; us in media res (.acquire semaphore) (swap! results-atom conj res)) #(swap! eose-atom inc))] (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (Thread/sleep 100) ;; in most cases we want to exercise the true interruption path (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (cancel-fn fulfill-atom "chan-id" "req-id") (.release semaphore) (is (.isCancelled f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) (is (#{0 1} (count @results-atom))) (is (= 0 @eose-atom)) ;; ensure cancellation leaves us with an empty registry (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-interruption-test (run-interruption-test (fn [fulfill-atom chan-id req-id] (fulfill/cancel! fulfill-atom chan-id req-id))) (run-interruption-test (fn [fulfill-atom chan-id _req-id] (fulfill/cancel-all! fulfill-atom chan-id)))) (defn- run-interruption-with-batching-test [cancel-fn] (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [semaphore (Semaphore. 0) results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit-use-batching! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] ;; block so our cancellation is guaranteed to cancel ;; us in media res (.acquire semaphore) (swap! results-atom conj res)) #(swap! eose-atom inc))] (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (Thread/sleep 100) ;; in most cases we want to exercise the true interruption path (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (cancel-fn fulfill-atom "chan-id" "req-id") (.release semaphore) (is (.isCancelled f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) (is (#{0 1} (count @results-atom))) (is (= 0 @eose-atom)) ;; ensure cancellation leaves us with an empty registry (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-interruption-with-batching-test (run-interruption-with-batching-test (fn [fulfill-atom chan-id req-id] (fulfill/cancel! fulfill-atom chan-id req-id))) (run-interruption-with-batching-test (fn [fulfill-atom chan-id _req-id] (fulfill/cancel-all! fulfill-atom chan-id))))
null
https://raw.githubusercontent.com/atdixon/me.untethr.nostr-relay/f02c644d8c09dc41703b4ce9e99e1e4a30fda8e9/test/test/fulfill_test.clj
clojure
cause test to swap! if inc the async work and even if index query doesn't de-duplicate the kv lookup will de-dupe for the single fulfillment page verify the results are json strings that can be parsed ensure cancellation -- a no-op, now that we're done -- leaves us with an empty registry cause test to swap! if inc the async work count b/c we're de-duping across pages and we walk **backward* from latest results: verify the results are json strings that can be parsed ensure cancellation -- a no-op, now that we're done -- leaves us with an empty registry block so our cancellation is guaranteed to cancel us in media res in most cases we want to exercise the true interruption path ensure cancellation leaves us with an empty registry block so our cancellation is guaranteed to cancel us in media res in most cases we want to exercise the true interruption path ensure cancellation leaves us with an empty registry
(ns test.fulfill-test (:require [clojure.test :refer :all] [me.untethr.nostr.common.domain :as domain] [me.untethr.nostr.fulfill :as fulfill] [me.untethr.nostr.app :as app] [next.jdbc :as jdbc] [test.support :as support] [test.test-data :as test-data] [me.untethr.nostr.common.metrics :as metrics]) (:import (java.util.concurrent Future TimeUnit Semaphore))) (defn- query-max-id [db table-name] (:max_id (jdbc/execute-one! db [(format "select max(id) as max_id from %s" table-name)]))) (deftest fulfill-test (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (swap! results-atom conj res)) #(swap! eose-atom inc)) _ (.get f 1000 TimeUnit/MILLISECONDS)] (is (.isDone f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) we expect 7 results -- b / c we 're using /submit ! + fulfill - entirely ! (is (= 7 (count @results-atom))) (is (= 1 @eose-atom)) (is (= (into #{} (subvec (:pool test-data/pool-with-filters) 1 8)) (into #{} (map #'app/parse) @results-atom))) (fulfill/cancel! fulfill-atom "chan-id" "req-id") (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-with-batching-test (with-redefs [fulfill/batch-size 2] (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit-use-batching! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (swap! results-atom conj res)) #(swap! eose-atom inc)) _ (.get f 1000 TimeUnit/MILLISECONDS)] (is (.isDone f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) 7 ! ! ! we redef our page size above to 2 but we still get a expected (is (= 7 (count @results-atom))) (is (= 1 @eose-atom)) (is (= (into #{} (subvec (:pool test-data/pool-with-filters) 1 8)) (into #{} (map #'app/parse) @results-atom))) (fulfill/cancel! fulfill-atom "chan-id" "req-id") (is (= (fulfill/create-empty-registry) @fulfill-atom))))))) (defn- run-interruption-test [cancel-fn] (support/with-memory-db-new-schema [db] (support/with-memory-db-kv-schema [db-kv] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [semaphore (Semaphore. 0) results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (.acquire semaphore) (swap! results-atom conj res)) #(swap! eose-atom inc))] (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (cancel-fn fulfill-atom "chan-id" "req-id") (.release semaphore) (is (.isCancelled f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) (is (#{0 1} (count @results-atom))) (is (= 0 @eose-atom)) (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-interruption-test (run-interruption-test (fn [fulfill-atom chan-id req-id] (fulfill/cancel! fulfill-atom chan-id req-id))) (run-interruption-test (fn [fulfill-atom chan-id _req-id] (fulfill/cancel-all! fulfill-atom chan-id)))) (defn- run-interruption-with-batching-test [cancel-fn] (support/with-memory-db-kv-schema [db-kv] (support/with-memory-db-new-schema [db] (support/load-data-new-schema db db-kv (:pool test-data/pool-with-filters)) (let [semaphore (Semaphore. 0) results-atom (atom []) eose-atom (atom 0) fulfill-atom (atom (fulfill/create-empty-registry)) ^Future f (fulfill/submit-use-batching! (metrics/create-metrics) (domain/init-database-cxns db db db-kv db-kv) fulfill-atom "chan-id" "req-id" [{:since 110} {:since 120}] (domain/->TableMaxRowIds (query-max-id db "n_events") -1 -1 -1) (fn [res] (.acquire semaphore) (swap! results-atom conj res)) #(swap! eose-atom inc))] (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (is (= 1 (fulfill/num-active-fulfillments fulfill-atom))) (cancel-fn fulfill-atom "chan-id" "req-id") (.release semaphore) (is (.isCancelled f)) (is (= 0 (fulfill/num-active-fulfillments fulfill-atom))) (is (#{0 1} (count @results-atom))) (is (= 0 @eose-atom)) (is (= (fulfill/create-empty-registry) @fulfill-atom)))))) (deftest fulfill-interruption-with-batching-test (run-interruption-with-batching-test (fn [fulfill-atom chan-id req-id] (fulfill/cancel! fulfill-atom chan-id req-id))) (run-interruption-with-batching-test (fn [fulfill-atom chan-id _req-id] (fulfill/cancel-all! fulfill-atom chan-id))))
d70987cd85315260ea87289226e72535e422cfaaeabca3c49b8535e0481d25fe
mirage/functoria
functoria_misc.mli
* Copyright ( c ) 2013 < > * Copyright ( c ) 2013 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013 Thomas Gazagnaire <> * Copyright (c) 2013 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) (** Utility module. *) * { 2 Misc } open Rresult val err_cmdliner: ?usage:bool -> ('a, string) result -> 'a Cmdliner.Term.ret module type Monoid = sig type t val empty: t val union: t -> t -> t end (** Generation of fresh names *) module Name: sig val ocamlify: string -> string val create: string -> prefix:string -> string end module Codegen: sig val generated_header: ?argv:string array -> ?time:Ptime.t -> unit -> string val append: Format.formatter -> ('a, Format.formatter, unit) format -> 'a val newline: Format.formatter -> unit val set_main_ml: string -> unit val append_main: ('a, Format.formatter, unit) format -> 'a val newline_main: unit -> unit end (** Universal map *) module Univ: sig type 'a key val new_key: string -> 'a key type t val empty: t val add: 'a key -> 'a -> t -> t val mem: 'a key -> t -> bool val find: 'a key -> t -> 'a option val merge: default:t -> t -> t val dump: t Fmt.t end
null
https://raw.githubusercontent.com/mirage/functoria/d15603d5e32d335cd075d426aee7038f786eb497/lib/functoria_misc.mli
ocaml
* Utility module. * Generation of fresh names * Universal map
* Copyright ( c ) 2013 < > * Copyright ( c ) 2013 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2013 Thomas Gazagnaire <> * Copyright (c) 2013 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * { 2 Misc } open Rresult val err_cmdliner: ?usage:bool -> ('a, string) result -> 'a Cmdliner.Term.ret module type Monoid = sig type t val empty: t val union: t -> t -> t end module Name: sig val ocamlify: string -> string val create: string -> prefix:string -> string end module Codegen: sig val generated_header: ?argv:string array -> ?time:Ptime.t -> unit -> string val append: Format.formatter -> ('a, Format.formatter, unit) format -> 'a val newline: Format.formatter -> unit val set_main_ml: string -> unit val append_main: ('a, Format.formatter, unit) format -> 'a val newline_main: unit -> unit end module Univ: sig type 'a key val new_key: string -> 'a key type t val empty: t val add: 'a key -> 'a -> t -> t val mem: 'a key -> t -> bool val find: 'a key -> t -> 'a option val merge: default:t -> t -> t val dump: t Fmt.t end
201d3526a6788bffd8ee7ace1a2f89d8d3c242c43ec80fc5691ccd016ed4733e
AustinRochford/99-problems-clojure
lists.clj
(ns ninety-nine-problems.lists (:require [clojure.contrib.core :refer :all] [ninety-nine-problems.core :refer :all]) (:gen-class)) Problem 1 (defn last' "Get the last element of a list" [coll] (let [[head & tail] coll] (if (empty? tail) head (recur tail)))) Problem 2 (defn but-last "Get the second-to-last element of a list" [coll] (let [[head snd & tail] coll] (if (nil? snd) nil (if (empty? tail) head (recur (conj tail snd)))))) Problem 3 (defn element-at "Get the k-th element of a list, for a given k" [coll k] (if (empty? coll) nil (if (= k 1) (first coll) (recur (rest coll) (dec k))))) Problem 4 (def length "Calculate the length of a list" (comp (partial reduce +) (partial map (constantly 1)))) Problem 5 (defn reverse' "Reverse a list" [coll] (if (empty? coll) '() (reduce conj '() coll))) Problem 6 (defn palindrome? "Determine whether or not a list is a palindrome" [coll] (= coll (reverse' coll))) Problem 7 (defn flatten' "Flatten a nested list structure" [coll] (if (empty? coll) '() (let [[head & tail] coll] (if (seq? head) (concat (flatten' head) (flatten' tail)) (conj (flatten' tail) head))))) Problem 8 (def compress "Eliminate consecutive duplicates of list elements" (comp (partial map first) (partial partition-by identity))) Problem 9 (def pack "Pack consecutive duplicates of list elements into sublists" (partial partition-by identity)) Problem 10 (def encode "Encode a list by listing the length of each run of consecutive idential elements" (comp (partial map #(vector (count %) (first %))) pack)) Problem 11 (def encode' "Like Problem 10, except for elements with no duplicates are simply copied with no count" (comp (partial map (fn [coll] (let [[head & tail] coll] (if (empty? tail) head [(count coll) head])))) pack)) Problem 12 (def decode "Decode a list encoded using encode' from Problem 11" (partial mapcat (fn [encoded] (if (vector? encoded) (apply replicate encoded) `(~encoded))))) Problem 14 (def duplicate "Duplicate the elements of a list" (partial mapcat (partial replicate 2))) Problem 15 (defn replicate' "Replicate the elements of a list n times" [coll n] (mapcat (partial replicate n) coll)) Problem 16 (defn drop-every "Drop every n-th element from the list" [coll n] (mapcat (fn [part] (if (= (count part) n) (butlast part) part)) (partition-all n coll))) Problem 17 (defn split "Split a list into two parts, given the length of the first" [coll n] (if (empty? coll) ['() '()] (if (zero? n) ['() coll] (let [[head & tail] coll [before after] (split tail (dec n))] [(conj before head) after])))) Problem 18 (defn slice "Extract a slice from the list" [coll m n] (->> coll (drop (dec m)) (take (inc (- n m))))) Problem 19 (defn rotate "Rotate a list n places to the left" [coll n] (let [length (count coll)] (if (neg? n) (recur coll (+ length n)) (if (> n length) (recur coll (mod n length)) (let [[before after] (split coll n)] (concat after before)))))) Problem 20 (defn remove-at "Remove the element at a given position from a list" [coll n] (let [[before [_ & after]] (split coll (dec n))] (concat before after))) Problem 21 (defn insert-at "Insert an element at a given position in a list" [x coll n] (let [[before after] (split coll (dec n))] (if (empty? after) (if (= (count before) (dec n)) (concat before (replicate 1 x)) before) (concat before (conj after x))))) Problem 22 (defn range' "Create a list containing all the integers in a given range" [m n] (take (inc (- n m)) (iterate inc m))) Problem 26 (defn combinations "Generate the combinations of a given size from a list" [k coll] (if (zero? k) '(()) (if (empty? coll) nil (let [[head & tail] coll with-head (combinations (dec k) tail) without-head (combinations k tail)] (concat (map #(conj % head) with-head) without-head))))) Problem 27 (defn group "Group elements of coll into disjoint subgroups with specified sizes" [coll groups] (if (empty? groups) '(()) (let [[n & ns] groups heads (combinations n coll)] (mapcat (fn [head] (map #(conj % head) (group (diff coll head) ns))) heads)))) Problem 28a (def sort-by-length "Sort a list of lists by length of the sublists" (partial sort-by count)) ; Problem 28b (defn sort-by-length-frequency "Sort a lsit of lists by the frequency of their length in the parent list" [coll] (let [freqs (frequencies (map count coll))] (sort-by #(freqs (count %)) coll)))
null
https://raw.githubusercontent.com/AustinRochford/99-problems-clojure/bdc0c6ddcbcce58c2d6575a74c7263d84077958d/src/ninety_nine_problems/lists.clj
clojure
Problem 28b
(ns ninety-nine-problems.lists (:require [clojure.contrib.core :refer :all] [ninety-nine-problems.core :refer :all]) (:gen-class)) Problem 1 (defn last' "Get the last element of a list" [coll] (let [[head & tail] coll] (if (empty? tail) head (recur tail)))) Problem 2 (defn but-last "Get the second-to-last element of a list" [coll] (let [[head snd & tail] coll] (if (nil? snd) nil (if (empty? tail) head (recur (conj tail snd)))))) Problem 3 (defn element-at "Get the k-th element of a list, for a given k" [coll k] (if (empty? coll) nil (if (= k 1) (first coll) (recur (rest coll) (dec k))))) Problem 4 (def length "Calculate the length of a list" (comp (partial reduce +) (partial map (constantly 1)))) Problem 5 (defn reverse' "Reverse a list" [coll] (if (empty? coll) '() (reduce conj '() coll))) Problem 6 (defn palindrome? "Determine whether or not a list is a palindrome" [coll] (= coll (reverse' coll))) Problem 7 (defn flatten' "Flatten a nested list structure" [coll] (if (empty? coll) '() (let [[head & tail] coll] (if (seq? head) (concat (flatten' head) (flatten' tail)) (conj (flatten' tail) head))))) Problem 8 (def compress "Eliminate consecutive duplicates of list elements" (comp (partial map first) (partial partition-by identity))) Problem 9 (def pack "Pack consecutive duplicates of list elements into sublists" (partial partition-by identity)) Problem 10 (def encode "Encode a list by listing the length of each run of consecutive idential elements" (comp (partial map #(vector (count %) (first %))) pack)) Problem 11 (def encode' "Like Problem 10, except for elements with no duplicates are simply copied with no count" (comp (partial map (fn [coll] (let [[head & tail] coll] (if (empty? tail) head [(count coll) head])))) pack)) Problem 12 (def decode "Decode a list encoded using encode' from Problem 11" (partial mapcat (fn [encoded] (if (vector? encoded) (apply replicate encoded) `(~encoded))))) Problem 14 (def duplicate "Duplicate the elements of a list" (partial mapcat (partial replicate 2))) Problem 15 (defn replicate' "Replicate the elements of a list n times" [coll n] (mapcat (partial replicate n) coll)) Problem 16 (defn drop-every "Drop every n-th element from the list" [coll n] (mapcat (fn [part] (if (= (count part) n) (butlast part) part)) (partition-all n coll))) Problem 17 (defn split "Split a list into two parts, given the length of the first" [coll n] (if (empty? coll) ['() '()] (if (zero? n) ['() coll] (let [[head & tail] coll [before after] (split tail (dec n))] [(conj before head) after])))) Problem 18 (defn slice "Extract a slice from the list" [coll m n] (->> coll (drop (dec m)) (take (inc (- n m))))) Problem 19 (defn rotate "Rotate a list n places to the left" [coll n] (let [length (count coll)] (if (neg? n) (recur coll (+ length n)) (if (> n length) (recur coll (mod n length)) (let [[before after] (split coll n)] (concat after before)))))) Problem 20 (defn remove-at "Remove the element at a given position from a list" [coll n] (let [[before [_ & after]] (split coll (dec n))] (concat before after))) Problem 21 (defn insert-at "Insert an element at a given position in a list" [x coll n] (let [[before after] (split coll (dec n))] (if (empty? after) (if (= (count before) (dec n)) (concat before (replicate 1 x)) before) (concat before (conj after x))))) Problem 22 (defn range' "Create a list containing all the integers in a given range" [m n] (take (inc (- n m)) (iterate inc m))) Problem 26 (defn combinations "Generate the combinations of a given size from a list" [k coll] (if (zero? k) '(()) (if (empty? coll) nil (let [[head & tail] coll with-head (combinations (dec k) tail) without-head (combinations k tail)] (concat (map #(conj % head) with-head) without-head))))) Problem 27 (defn group "Group elements of coll into disjoint subgroups with specified sizes" [coll groups] (if (empty? groups) '(()) (let [[n & ns] groups heads (combinations n coll)] (mapcat (fn [head] (map #(conj % head) (group (diff coll head) ns))) heads)))) Problem 28a (def sort-by-length "Sort a list of lists by length of the sublists" (partial sort-by count)) (defn sort-by-length-frequency "Sort a lsit of lists by the frequency of their length in the parent list" [coll] (let [freqs (frequencies (map count coll))] (sort-by #(freqs (count %)) coll)))
502b9400d1ce1d6d5df75bbe54219410a817b8b7b58949356e38ce24c43cc07d
emqx/emqx
emqx_authn_http.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_authn_http). -include("emqx_authn.hrl"). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -include_lib("emqx_connector/include/emqx_connector.hrl"). -behaviour(hocon_schema). -behaviour(emqx_authentication). -export([ namespace/0, tags/0, roots/0, fields/1, desc/1, validations/0 ]). -export([ headers_no_content_type/1, headers/1 ]). -export([ refs/0, union_member_selector/1, create/2, update/2, authenticate/2, destroy/1 ]). %%------------------------------------------------------------------------------ %% Hocon Schema %%------------------------------------------------------------------------------ namespace() -> "authn-http". tags() -> [<<"Authentication">>]. roots() -> [ {?CONF_NS, hoconsc:mk( hoconsc:union(fun union_member_selector/1), #{} )} ]. fields(get) -> [ {method, #{type => get, required => true, desc => ?DESC(method)}}, {headers, fun headers_no_content_type/1} ] ++ common_fields(); fields(post) -> [ {method, #{type => post, required => true, desc => ?DESC(method)}}, {headers, fun headers/1} ] ++ common_fields(). desc(get) -> ?DESC(get); desc(post) -> ?DESC(post); desc(_) -> undefined. common_fields() -> [ {mechanism, emqx_authn_schema:mechanism(password_based)}, {backend, emqx_authn_schema:backend(http)}, {url, fun url/1}, {body, hoconsc:mk(map([{fuzzy, term(), binary()}]), #{ required => false, desc => ?DESC(body) })}, {request_timeout, fun request_timeout/1} ] ++ emqx_authn_schema:common_fields() ++ maps:to_list( maps:without( [ base_url, pool_type ], maps:from_list(emqx_connector_http:fields(config)) ) ). validations() -> [ {check_ssl_opts, fun check_ssl_opts/1}, {check_headers, fun check_headers/1} ]. url(type) -> binary(); url(desc) -> ?DESC(?FUNCTION_NAME); url(validator) -> [?NOT_EMPTY("the value of the field 'url' cannot be empty")]; url(required) -> true; url(_) -> undefined. headers(type) -> map(); headers(desc) -> ?DESC(?FUNCTION_NAME); headers(converter) -> fun(Headers) -> maps:merge(default_headers(), transform_header_name(Headers)) end; headers(default) -> default_headers(); headers(_) -> undefined. headers_no_content_type(type) -> map(); headers_no_content_type(desc) -> ?DESC(?FUNCTION_NAME); headers_no_content_type(converter) -> fun(Headers) -> maps:without( [<<"content-type">>], maps:merge(default_headers_no_content_type(), transform_header_name(Headers)) ) end; headers_no_content_type(default) -> default_headers_no_content_type(); headers_no_content_type(_) -> undefined. request_timeout(type) -> emqx_schema:duration_ms(); request_timeout(desc) -> ?DESC(?FUNCTION_NAME); request_timeout(default) -> <<"5s">>; request_timeout(_) -> undefined. %%------------------------------------------------------------------------------ %% APIs %%------------------------------------------------------------------------------ refs() -> [ hoconsc:ref(?MODULE, get), hoconsc:ref(?MODULE, post) ]. union_member_selector(all_union_members) -> refs(); union_member_selector({value, Value}) -> refs(Value). refs(#{<<"method">> := <<"get">>}) -> [hoconsc:ref(?MODULE, get)]; refs(#{<<"method">> := <<"post">>}) -> [hoconsc:ref(?MODULE, post)]; refs(_) -> throw(#{ field_name => method, expected => "get | post" }). create(_AuthenticatorID, Config) -> create(Config). create(Config0) -> ResourceId = emqx_authn_utils:make_resource_id(?MODULE), {Config, State} = parse_config(Config0), {ok, _Data} = emqx_authn_utils:create_resource( ResourceId, emqx_connector_http, Config ), {ok, State#{resource_id => ResourceId}}. update(Config0, #{resource_id := ResourceId} = _State) -> {Config, NState} = parse_config(Config0), case emqx_authn_utils:update_resource(emqx_connector_http, Config, ResourceId) of {error, Reason} -> error({load_config_error, Reason}); {ok, _} -> {ok, NState#{resource_id => ResourceId}} end. authenticate(#{auth_method := _}, _) -> ignore; authenticate( Credential, #{ resource_id := ResourceId, method := Method, request_timeout := RequestTimeout } = State ) -> Request = generate_request(Credential, State), Response = emqx_resource:simple_sync_query(ResourceId, {Method, Request, RequestTimeout}), ?TRACE_AUTHN_PROVIDER("http_response", #{ request => request_for_log(Credential, State), response => response_for_log(Response), resource => ResourceId }), case Response of {ok, 204, _Headers} -> {ok, #{is_superuser => false}}; {ok, 200, Headers, Body} -> handle_response(Headers, Body); {ok, _StatusCode, _Headers} = Response -> ignore; {ok, _StatusCode, _Headers, _Body} = Response -> ignore; {error, _Reason} -> ignore end. destroy(#{resource_id := ResourceId}) -> _ = emqx_resource:remove_local(ResourceId), ok. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- default_headers() -> maps:put( <<"content-type">>, <<"application/json">>, default_headers_no_content_type() ). default_headers_no_content_type() -> #{ <<"accept">> => <<"application/json">>, <<"cache-control">> => <<"no-cache">>, <<"connection">> => <<"keep-alive">>, <<"keep-alive">> => <<"timeout=30, max=1000">> }. transform_header_name(Headers) -> maps:fold( fun(K0, V, Acc) -> K = list_to_binary(string:to_lower(to_list(K0))), maps:put(K, V, Acc) end, #{}, Headers ). check_ssl_opts(Conf) -> {BaseUrl, _Path, _Query} = parse_url(get_conf_val("url", Conf)), case BaseUrl of <<"https://", _/binary>> -> case get_conf_val("ssl.enable", Conf) of true -> ok; false -> false end; <<"http://", _/binary>> -> ok end. check_headers(Conf) -> Method = to_bin(get_conf_val("method", Conf)), Headers = get_conf_val("headers", Conf), Method =:= <<"post">> orelse (not maps:is_key(<<"content-type">>, Headers)). parse_url(Url) -> case string:split(Url, "//", leading) of [Scheme, UrlRem] -> case string:split(UrlRem, "/", leading) of [HostPort, Remaining] -> BaseUrl = iolist_to_binary([Scheme, "//", HostPort]), case string:split(Remaining, "?", leading) of [Path, QueryString] -> {BaseUrl, Path, QueryString}; [Path] -> {BaseUrl, Path, <<>>} end; [HostPort] -> {iolist_to_binary([Scheme, "//", HostPort]), <<>>, <<>>} end; [Url] -> throw({invalid_url, Url}) end. parse_config( #{ method := Method, url := RawUrl, headers := Headers, request_timeout := RequestTimeout } = Config ) -> {BaseUrl0, Path, Query} = parse_url(RawUrl), {ok, BaseUrl} = emqx_http_lib:uri_parse(BaseUrl0), State = #{ method => Method, path => Path, headers => ensure_header_name_type(Headers), base_path_templete => emqx_authn_utils:parse_str(Path), base_query_template => emqx_authn_utils:parse_deep( cow_qs:parse_qs(to_bin(Query)) ), body_template => emqx_authn_utils:parse_deep(maps:get(body, Config, #{})), request_timeout => RequestTimeout, url => RawUrl }, {Config#{base_url => BaseUrl, pool_type => random}, State}. generate_request(Credential, #{ method := Method, headers := Headers0, base_path_templete := BasePathTemplate, base_query_template := BaseQueryTemplate, body_template := BodyTemplate }) -> Headers = maps:to_list(Headers0), Path = emqx_authn_utils:render_str(BasePathTemplate, Credential), Query = emqx_authn_utils:render_deep(BaseQueryTemplate, Credential), Body = emqx_authn_utils:render_deep(BodyTemplate, Credential), case Method of get -> NPathQuery = append_query(to_list(Path), to_list(Query) ++ maps:to_list(Body)), {NPathQuery, Headers}; post -> NPathQuery = append_query(to_list(Path), to_list(Query)), ContentType = proplists:get_value(<<"content-type">>, Headers), NBody = serialize_body(ContentType, Body), {NPathQuery, Headers, NBody} end. append_query(Path, []) -> encode_path(Path); append_query(Path, Query) -> encode_path(Path) ++ "?" ++ binary_to_list(qs(Query)). qs(KVs) -> qs(KVs, []). qs([], Acc) -> <<$&, Qs/binary>> = iolist_to_binary(lists:reverse(Acc)), Qs; qs([{K, V} | More], Acc) -> qs(More, [["&", uri_encode(K), "=", uri_encode(V)] | Acc]). serialize_body(<<"application/json">>, Body) -> emqx_json:encode(Body); serialize_body(<<"application/x-www-form-urlencoded">>, Body) -> qs(maps:to_list(Body)). handle_response(Headers, Body) -> ContentType = proplists:get_value(<<"content-type">>, Headers), case safely_parse_body(ContentType, Body) of {ok, NBody} -> case maps:get(<<"result">>, NBody, <<"ignore">>) of <<"allow">> -> Res = emqx_authn_utils:is_superuser(NBody), %% TODO: Return by user property {ok, Res#{user_property => maps:get(<<"user_property">>, NBody, #{})}}; <<"deny">> -> {error, not_authorized}; <<"ignore">> -> ignore; _ -> ignore end; {error, Reason} -> ?TRACE_AUTHN_PROVIDER( error, "parse_http_response_failed", #{content_type => ContentType, body => Body, reason => Reason} ), ignore end. safely_parse_body(ContentType, Body) -> try parse_body(ContentType, Body) catch _Class:_Reason -> {error, invalid_body} end. parse_body(<<"application/json", _/binary>>, Body) -> {ok, emqx_json:decode(Body, [return_maps])}; parse_body(<<"application/x-www-form-urlencoded", _/binary>>, Body) -> Flags = [<<"result">>, <<"is_superuser">>], RawMap = maps:from_list(cow_qs:parse_qs(Body)), NBody = maps:with(Flags, RawMap), {ok, NBody}; parse_body(ContentType, _) -> {error, {unsupported_content_type, ContentType}}. uri_encode(T) -> emqx_http_lib:uri_encode(to_list(T)). encode_path(Path) -> Parts = string:split(Path, "/", all), lists:flatten(["/" ++ Part || Part <- lists:map(fun uri_encode/1, Parts)]). request_for_log(Credential, #{url := Url} = State) -> SafeCredential = emqx_authn_utils:without_password(Credential), case generate_request(SafeCredential, State) of {PathQuery, Headers} -> #{ method => post, base_url => Url, path_query => PathQuery, headers => Headers }; {PathQuery, Headers, Body} -> #{ method => post, base_url => Url, path_query => PathQuery, headers => Headers, mody => Body } end. response_for_log({ok, StatusCode, Headers}) -> #{status => StatusCode, headers => Headers}; response_for_log({ok, StatusCode, Headers, Body}) -> #{status => StatusCode, headers => Headers, body => Body}; response_for_log({error, Error}) -> #{error => Error}. to_list(A) when is_atom(A) -> atom_to_list(A); to_list(B) when is_binary(B) -> binary_to_list(B); to_list(L) when is_list(L) -> L. to_bin(A) when is_atom(A) -> atom_to_binary(A); to_bin(B) when is_binary(B) -> B; to_bin(L) when is_list(L) -> list_to_binary(L). get_conf_val(Name, Conf) -> hocon_maps:get(?CONF_NS ++ "." ++ Name, Conf). ensure_header_name_type(Headers) -> Fun = fun (Key, _Val, Acc) when is_binary(Key) -> Acc; (Key, Val, Acc) when is_atom(Key) -> Acc2 = maps:remove(Key, Acc), BinKey = erlang:atom_to_binary(Key), Acc2#{BinKey => Val} end, maps:fold(Fun, Headers, Headers).
null
https://raw.githubusercontent.com/emqx/emqx/73d5592b5af0cbbf347e5dc2b9b865b41228249f/apps/emqx_authn/src/simple_authn/emqx_authn_http.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- ------------------------------------------------------------------------------ Hocon Schema ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ APIs ------------------------------------------------------------------------------ -------------------------------------------------------------------- -------------------------------------------------------------------- TODO: Return by user property
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_authn_http). -include("emqx_authn.hrl"). -include_lib("emqx/include/logger.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -include_lib("emqx_connector/include/emqx_connector.hrl"). -behaviour(hocon_schema). -behaviour(emqx_authentication). -export([ namespace/0, tags/0, roots/0, fields/1, desc/1, validations/0 ]). -export([ headers_no_content_type/1, headers/1 ]). -export([ refs/0, union_member_selector/1, create/2, update/2, authenticate/2, destroy/1 ]). namespace() -> "authn-http". tags() -> [<<"Authentication">>]. roots() -> [ {?CONF_NS, hoconsc:mk( hoconsc:union(fun union_member_selector/1), #{} )} ]. fields(get) -> [ {method, #{type => get, required => true, desc => ?DESC(method)}}, {headers, fun headers_no_content_type/1} ] ++ common_fields(); fields(post) -> [ {method, #{type => post, required => true, desc => ?DESC(method)}}, {headers, fun headers/1} ] ++ common_fields(). desc(get) -> ?DESC(get); desc(post) -> ?DESC(post); desc(_) -> undefined. common_fields() -> [ {mechanism, emqx_authn_schema:mechanism(password_based)}, {backend, emqx_authn_schema:backend(http)}, {url, fun url/1}, {body, hoconsc:mk(map([{fuzzy, term(), binary()}]), #{ required => false, desc => ?DESC(body) })}, {request_timeout, fun request_timeout/1} ] ++ emqx_authn_schema:common_fields() ++ maps:to_list( maps:without( [ base_url, pool_type ], maps:from_list(emqx_connector_http:fields(config)) ) ). validations() -> [ {check_ssl_opts, fun check_ssl_opts/1}, {check_headers, fun check_headers/1} ]. url(type) -> binary(); url(desc) -> ?DESC(?FUNCTION_NAME); url(validator) -> [?NOT_EMPTY("the value of the field 'url' cannot be empty")]; url(required) -> true; url(_) -> undefined. headers(type) -> map(); headers(desc) -> ?DESC(?FUNCTION_NAME); headers(converter) -> fun(Headers) -> maps:merge(default_headers(), transform_header_name(Headers)) end; headers(default) -> default_headers(); headers(_) -> undefined. headers_no_content_type(type) -> map(); headers_no_content_type(desc) -> ?DESC(?FUNCTION_NAME); headers_no_content_type(converter) -> fun(Headers) -> maps:without( [<<"content-type">>], maps:merge(default_headers_no_content_type(), transform_header_name(Headers)) ) end; headers_no_content_type(default) -> default_headers_no_content_type(); headers_no_content_type(_) -> undefined. request_timeout(type) -> emqx_schema:duration_ms(); request_timeout(desc) -> ?DESC(?FUNCTION_NAME); request_timeout(default) -> <<"5s">>; request_timeout(_) -> undefined. refs() -> [ hoconsc:ref(?MODULE, get), hoconsc:ref(?MODULE, post) ]. union_member_selector(all_union_members) -> refs(); union_member_selector({value, Value}) -> refs(Value). refs(#{<<"method">> := <<"get">>}) -> [hoconsc:ref(?MODULE, get)]; refs(#{<<"method">> := <<"post">>}) -> [hoconsc:ref(?MODULE, post)]; refs(_) -> throw(#{ field_name => method, expected => "get | post" }). create(_AuthenticatorID, Config) -> create(Config). create(Config0) -> ResourceId = emqx_authn_utils:make_resource_id(?MODULE), {Config, State} = parse_config(Config0), {ok, _Data} = emqx_authn_utils:create_resource( ResourceId, emqx_connector_http, Config ), {ok, State#{resource_id => ResourceId}}. update(Config0, #{resource_id := ResourceId} = _State) -> {Config, NState} = parse_config(Config0), case emqx_authn_utils:update_resource(emqx_connector_http, Config, ResourceId) of {error, Reason} -> error({load_config_error, Reason}); {ok, _} -> {ok, NState#{resource_id => ResourceId}} end. authenticate(#{auth_method := _}, _) -> ignore; authenticate( Credential, #{ resource_id := ResourceId, method := Method, request_timeout := RequestTimeout } = State ) -> Request = generate_request(Credential, State), Response = emqx_resource:simple_sync_query(ResourceId, {Method, Request, RequestTimeout}), ?TRACE_AUTHN_PROVIDER("http_response", #{ request => request_for_log(Credential, State), response => response_for_log(Response), resource => ResourceId }), case Response of {ok, 204, _Headers} -> {ok, #{is_superuser => false}}; {ok, 200, Headers, Body} -> handle_response(Headers, Body); {ok, _StatusCode, _Headers} = Response -> ignore; {ok, _StatusCode, _Headers, _Body} = Response -> ignore; {error, _Reason} -> ignore end. destroy(#{resource_id := ResourceId}) -> _ = emqx_resource:remove_local(ResourceId), ok. Internal functions default_headers() -> maps:put( <<"content-type">>, <<"application/json">>, default_headers_no_content_type() ). default_headers_no_content_type() -> #{ <<"accept">> => <<"application/json">>, <<"cache-control">> => <<"no-cache">>, <<"connection">> => <<"keep-alive">>, <<"keep-alive">> => <<"timeout=30, max=1000">> }. transform_header_name(Headers) -> maps:fold( fun(K0, V, Acc) -> K = list_to_binary(string:to_lower(to_list(K0))), maps:put(K, V, Acc) end, #{}, Headers ). check_ssl_opts(Conf) -> {BaseUrl, _Path, _Query} = parse_url(get_conf_val("url", Conf)), case BaseUrl of <<"https://", _/binary>> -> case get_conf_val("ssl.enable", Conf) of true -> ok; false -> false end; <<"http://", _/binary>> -> ok end. check_headers(Conf) -> Method = to_bin(get_conf_val("method", Conf)), Headers = get_conf_val("headers", Conf), Method =:= <<"post">> orelse (not maps:is_key(<<"content-type">>, Headers)). parse_url(Url) -> case string:split(Url, "//", leading) of [Scheme, UrlRem] -> case string:split(UrlRem, "/", leading) of [HostPort, Remaining] -> BaseUrl = iolist_to_binary([Scheme, "//", HostPort]), case string:split(Remaining, "?", leading) of [Path, QueryString] -> {BaseUrl, Path, QueryString}; [Path] -> {BaseUrl, Path, <<>>} end; [HostPort] -> {iolist_to_binary([Scheme, "//", HostPort]), <<>>, <<>>} end; [Url] -> throw({invalid_url, Url}) end. parse_config( #{ method := Method, url := RawUrl, headers := Headers, request_timeout := RequestTimeout } = Config ) -> {BaseUrl0, Path, Query} = parse_url(RawUrl), {ok, BaseUrl} = emqx_http_lib:uri_parse(BaseUrl0), State = #{ method => Method, path => Path, headers => ensure_header_name_type(Headers), base_path_templete => emqx_authn_utils:parse_str(Path), base_query_template => emqx_authn_utils:parse_deep( cow_qs:parse_qs(to_bin(Query)) ), body_template => emqx_authn_utils:parse_deep(maps:get(body, Config, #{})), request_timeout => RequestTimeout, url => RawUrl }, {Config#{base_url => BaseUrl, pool_type => random}, State}. generate_request(Credential, #{ method := Method, headers := Headers0, base_path_templete := BasePathTemplate, base_query_template := BaseQueryTemplate, body_template := BodyTemplate }) -> Headers = maps:to_list(Headers0), Path = emqx_authn_utils:render_str(BasePathTemplate, Credential), Query = emqx_authn_utils:render_deep(BaseQueryTemplate, Credential), Body = emqx_authn_utils:render_deep(BodyTemplate, Credential), case Method of get -> NPathQuery = append_query(to_list(Path), to_list(Query) ++ maps:to_list(Body)), {NPathQuery, Headers}; post -> NPathQuery = append_query(to_list(Path), to_list(Query)), ContentType = proplists:get_value(<<"content-type">>, Headers), NBody = serialize_body(ContentType, Body), {NPathQuery, Headers, NBody} end. append_query(Path, []) -> encode_path(Path); append_query(Path, Query) -> encode_path(Path) ++ "?" ++ binary_to_list(qs(Query)). qs(KVs) -> qs(KVs, []). qs([], Acc) -> <<$&, Qs/binary>> = iolist_to_binary(lists:reverse(Acc)), Qs; qs([{K, V} | More], Acc) -> qs(More, [["&", uri_encode(K), "=", uri_encode(V)] | Acc]). serialize_body(<<"application/json">>, Body) -> emqx_json:encode(Body); serialize_body(<<"application/x-www-form-urlencoded">>, Body) -> qs(maps:to_list(Body)). handle_response(Headers, Body) -> ContentType = proplists:get_value(<<"content-type">>, Headers), case safely_parse_body(ContentType, Body) of {ok, NBody} -> case maps:get(<<"result">>, NBody, <<"ignore">>) of <<"allow">> -> Res = emqx_authn_utils:is_superuser(NBody), {ok, Res#{user_property => maps:get(<<"user_property">>, NBody, #{})}}; <<"deny">> -> {error, not_authorized}; <<"ignore">> -> ignore; _ -> ignore end; {error, Reason} -> ?TRACE_AUTHN_PROVIDER( error, "parse_http_response_failed", #{content_type => ContentType, body => Body, reason => Reason} ), ignore end. safely_parse_body(ContentType, Body) -> try parse_body(ContentType, Body) catch _Class:_Reason -> {error, invalid_body} end. parse_body(<<"application/json", _/binary>>, Body) -> {ok, emqx_json:decode(Body, [return_maps])}; parse_body(<<"application/x-www-form-urlencoded", _/binary>>, Body) -> Flags = [<<"result">>, <<"is_superuser">>], RawMap = maps:from_list(cow_qs:parse_qs(Body)), NBody = maps:with(Flags, RawMap), {ok, NBody}; parse_body(ContentType, _) -> {error, {unsupported_content_type, ContentType}}. uri_encode(T) -> emqx_http_lib:uri_encode(to_list(T)). encode_path(Path) -> Parts = string:split(Path, "/", all), lists:flatten(["/" ++ Part || Part <- lists:map(fun uri_encode/1, Parts)]). request_for_log(Credential, #{url := Url} = State) -> SafeCredential = emqx_authn_utils:without_password(Credential), case generate_request(SafeCredential, State) of {PathQuery, Headers} -> #{ method => post, base_url => Url, path_query => PathQuery, headers => Headers }; {PathQuery, Headers, Body} -> #{ method => post, base_url => Url, path_query => PathQuery, headers => Headers, mody => Body } end. response_for_log({ok, StatusCode, Headers}) -> #{status => StatusCode, headers => Headers}; response_for_log({ok, StatusCode, Headers, Body}) -> #{status => StatusCode, headers => Headers, body => Body}; response_for_log({error, Error}) -> #{error => Error}. to_list(A) when is_atom(A) -> atom_to_list(A); to_list(B) when is_binary(B) -> binary_to_list(B); to_list(L) when is_list(L) -> L. to_bin(A) when is_atom(A) -> atom_to_binary(A); to_bin(B) when is_binary(B) -> B; to_bin(L) when is_list(L) -> list_to_binary(L). get_conf_val(Name, Conf) -> hocon_maps:get(?CONF_NS ++ "." ++ Name, Conf). ensure_header_name_type(Headers) -> Fun = fun (Key, _Val, Acc) when is_binary(Key) -> Acc; (Key, Val, Acc) when is_atom(Key) -> Acc2 = maps:remove(Key, Acc), BinKey = erlang:atom_to_binary(Key), Acc2#{BinKey => Val} end, maps:fold(Fun, Headers, Headers).
bcb1c130feab4ca37ae6859f27fffcc5b845dd17923bb7b4a8f600c67054f666
MichaelBurge/pyramid-scheme
types.rkt
#lang typed/racket (provide (all-defined-out)) ;; (require typed/racket/unsafe) ;; (unsafe-provide (all-defined-out)) ; These submodules should be in the original file, but this issue prevents that: ; ; (module common typed/racket (require typed/racket/unsafe) (provide (all-defined-out) register-value?) (define-type Offset Natural) (define-type Counter Natural) (define-type Size Natural) (define-type Anys (Listof Any)) (define-type Symbols (Listof Symbol)) (define-type EthWord Natural) (define-type EthWords (Listof EthWord)) (define-type EthInt Integer) (define-type EthInts (Listof EthInt)) (struct label ([ name : Symbol ]) #:transparent) (struct label-definition label ([ offset : Integer ] [ virtual? : Boolean ]) #:transparent) (define-type RegisterValue (U Boolean Symbol Integer String Char (Listof Integer) (Listof Symbol) (Listof String) (Vectorof Integer))) (module unsafe racket (provide register-value?) (define (register-value? x) (or (boolean? x) (symbol? x) (integer? x) (string? x) (list? x) (vector? x))) ) (unsafe-require/typed 'unsafe [ register-value? (-> Any Boolean : RegisterValue) ]) (define-type Verbosity Fixnum) (define-type SourceMap (HashTable Symbol Symbols)) (define-type labels (Listof label)) (: make-source-map (-> SourceMap)) (define (make-source-map) (make-hash)) (define-type (DottableListof A B) (U Null (Pairof A (U B (DottableListof A B))))) ) ; codegen.rkt (module evm-assembly typed/racket (require (submod ".." common)) (provide (all-defined-out)) (struct opcode ([ byte : Byte ] [ name : Symbol ] [ num-reads : Natural] [ num-writes : Natural ]) #:transparent) (struct evm-op ([ name : Symbol ]) #:transparent) (struct evm-push ([ size : (U 'shrink Byte) ] [ value : (U Integer Symbol label) ]) #:transparent) (struct evm-bytes ([ bytes : Bytes ]) #:transparent) (define-type EthInstruction (U evm-op evm-push evm-bytes label-definition)) (define-type EthInstructions (Listof EthInstruction)) (define-type Generator0 (-> EthInstructions)) (define-type (Generator A) (-> A EthInstructions)) (define-type Generator1 Generator) (define-type (Generator2 A B) (-> A B EthInstructions)) (define-type (Generator3 A B C) (-> A B C EthInstructions)) (struct relocation ([ pos : Integer ] [ symbol : Symbol ]) #:transparent) (struct patchpoint ([ symbol : Symbol ] [ initializer : EthInstructions ]) #:transparent) (define-type SymbolTable (Mutable-HashTable Symbol Offset)) (define-type ReverseSymbolTable (Mutable-HashTable Natural Symbol)) (define-type RelocationTable (Setof relocation)) (define-type LinkedOffset Offset) (define-type UnlinkedOffset Offset) (define-type SourceMapper (-> UnlinkedOffset Symbols)) (: make-symbol-table (-> SymbolTable)) (define (make-symbol-table) (make-hash)) (: make-reverse-symbol-table (-> ReverseSymbolTable)) (define (make-reverse-symbol-table) (make-hash)) (: make-relocation-table (-> RelocationTable)) (define (make-relocation-table) (set)) ) ; compiler.rkt (module abstract-machine typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." evm-assembly)) ( require ( submod " .. " ast ) ) (provide (all-defined-out)) (define-type RegisterName (U 'env 'proc 'continue 'argl 'val 'stack-size)) (struct primop ([ name : Symbol ] [ gen : Procedure ] [ eval : Procedure ]) #:transparent) (define-type PrimopTable (HashTable Symbol primop)) (struct assign ([ reg-name : RegisterName ] [ value : MExpr ]) #:transparent) (struct test ([ condition : MExpr ]) #:transparent) (struct branch ([ dest : MExpr ]) #:transparent) (struct goto ([ dest : MExpr ]) #:transparent) (struct save ([ exp : MExpr ]) #:transparent) (struct restore ([ reg-name : RegisterName ]) #:transparent) (struct perform ([ action : MExpr ]) #:transparent) (struct evm ([ insts : EthInstructions ]) #:transparent) (define-type Instruction (U label-definition assign test branch goto save restore perform evm )) (struct reg ([name : RegisterName]) #:transparent) (struct const ([ value : RegisterValue ]) #:transparent) (struct boxed-const ([ value : RegisterValue ]) #:transparent) (struct op ([ name : Symbol] [ args : MExprs ]) #:transparent) (struct %stack ()) (define stack (%stack)) (define stack? %stack?) (define-type MExpr (U reg const boxed-const op Symbol label %stack evm )) (struct inst-seq ([ needs : RegisterNames ] [ modifies : RegisterNames ] [ statements : Instructions ]) #:transparent) (define-type MExprs (Listof MExpr)) (define-type Instructions (Listof Instruction)) (define-type RegisterNames (Setof RegisterName)) (struct v-fixnum ([value : Natural] [ ptr : Natural ]) #:mutable #:transparent) (struct v-symbol ([value : Symbol ]) #:transparent) (struct v-char ([value : Char ]) #:transparent) (struct v-compiled-procedure ([label : label ] [ env : v-environment]) #:transparent) (struct v-primitive-procedure ([label : label ]) #:transparent) (struct v-pair ([left : value] [right : value]) #:transparent) (struct v-vector ([elems : (Vectorof value)]) #:transparent) (struct v-null ( ) #:transparent) (struct v-continuation ([continue : label ] [env : v-environment] [ stack : values ]) #:transparent) (struct v-frame ([mappings : (HashTable Symbol value)]) #:transparent) (struct v-environment ([frames : v-frames])) (struct v-bytes ([ptr : Natural ]) #:transparent) (struct v-string ([str : String ]) #:transparent) (define-type v-unboxed (U Integer Symbol Boolean)) (define-type v-callable (U v-compiled-procedure v-primitive-procedure v-continuation)) (define-type v-list (U v-null v-pair)) (define-predicate v-unboxed? v-unboxed) (define-predicate v-callable? v-callable) (define-predicate v-list? v-list) (define-type value (U Void v-unboxed v-fixnum v-symbol v-char v-compiled-procedure v-primitive-procedure v-pair v-vector v-null v-continuation v-frame v-environment v-bytes v-string label)) (define-type v-frames (Listof v-frame)) (define-type values (Listof value)) (struct machine ([pc : Natural] [env : v-environment] [proc : v-callable] [continue : label] [argl : value] [val : value] [stack-size : Natural] [stack : values] [halted? : Boolean]) #:transparent #:mutable) ) ; ast.rkt (module ast typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." abstract-machine)) (unsafe-provide (all-defined-out) (all-from-out (submod ".." common))) (struct pyr-const ([ value : RegisterValue ] [ boxed? : Boolean ]) #:transparent) (struct pyr-variable ([ name : Symbol ]) #:transparent) (struct pyr-quoted ([ exp : Pyramid ]) #:transparent) (struct pyr-assign ([ name : VariableName ] [ value : Pyramid ]) #:transparent) (struct pyr-definition ([ name : VariableName ] [ body : Pyramid ]) #:transparent) (struct pyr-if ([ predicate : Pyramid ] [ consequent : Pyramid ] [ alternative : Pyramid ]) #:transparent) (struct pyr-lambda ([ names : VariableNames ] [ body : Pyramid ]) #:transparent) (struct pyr-begin ([ body : Pyramids ]) #:transparent) (struct pyr-application ([ operator : Pyramid ] [ operands : Pyramids ] [ rest : (Option Pyramid) ]) #:transparent) (struct pyr-macro-application ([ name : VariableName ] [ app-syntax : PyramidQ ]) #:transparent) (struct pyr-macro-definition ([ name : VariableName ] [ parameters : DottableParameters ] [ body : PyramidQs ] [ out-options : expander-options ]) #:transparent) (struct pyr-asm ([ insts : Instructions]) #:transparent) (struct pyr-unknown-application ([ name : VariableName ] [ app-syntax : PyramidQ ]) #:transparent) (define-type Pyramid (U pyr-const pyr-variable pyr-quoted pyr-assign pyr-definition pyr-if pyr-lambda pyr-begin pyr-application pyr-macro-application pyr-macro-definition pyr-asm pyr-unknown-application )) (define-predicate pyramid? Pyramid) (define-type VariableName Symbol) (define-type VariableNames (Listof VariableName)) (define-type PyramidQ Syntax) (define-type PyramidQs (Listof PyramidQ)) (define-type DottableParameters Any) (define-type Racket Any) (define-type Rackets (Listof Any)) (define-type Value Any) (define-type Pyramids (Listof Pyramid)) (define-type DottedPyramids (DottableListof Pyramid Pyramid)) (define-type Assertion Any) (define-type PyrMacroFunction (-> PyramidQ PyramidQ)) (struct pyr-macro ([ func : PyrMacroFunction ] [ out-options : expander-options ]) #:transparent) (define-type Pass (-> Pyramid Pyramid)) (define-type pyr-consts (Listof pyr-const)) (define-type pyr-variables (Listof pyr-variable)) (define-type pyr-quoteds (Listof pyr-quoted)) (define-type pyr-assigns (Listof pyr-assign)) (define-type pyr-definitions (Listof pyr-definition)) (define-type pyr-ifs (Listof pyr-if)) (define-type pyr-lambdas (Listof pyr-lambda)) (define-type pyr-begins (Listof pyr-begin)) (define-type pyr-applications (Listof pyr-application)) (define-type pyr-macro-applications (Listof pyr-macro-application)) (define-type pyr-macro-definitions (Listof pyr-macro-definition)) (define-type pyr-asms (Listof pyr-asm)) (define-type LexicalTable (HashTable Symbol Lexical)) (define-type Lexical (Parameterof PyramidQ)) (: make-lexical-table (-> LexicalTable)) (define make-lexical-table make-hash) (struct expander-options ([ box-literals? : Boolean ]) #:transparent) ) ; simulator.rkt (module simulator typed/racket (require (submod ".." common)) (require (submod ".." evm-assembly)) (provide (all-defined-out)) (define-type CodeHash EthWord) (struct simulator ([ accounts : vm-world ] [ store : vm-store ] [ code-db : (HashTable CodeHash Bytes) ] ) #:transparent) (define-type Frame (List (Listof String) Anys)) (define-type Environment (Listof Frame)) (define-type Frames (Listof Frame)) (struct exn:evm exn:fail:user ([ vm : vm-exec ]) #:transparent) (struct exn:evm:return exn:evm ([ result : Bytes ]) #:transparent) (struct exn:evm:misaligned-addr exn:evm ([ addr : EthWord ]) #:transparent) (struct exn:evm:throw exn:evm ([ value : Bytes ]) #:transparent) (struct exn:evm:did-not-halt exn:evm ([ max-iterations : Natural ]) #:transparent) (struct exn:evm:stack-underflow exn:evm ([ ethi : EthInstruction ] [ num-elements : Natural ] [ stack : (Listof EthWord )]) #:transparent) (struct exn:evm:misaligned-jump exn:evm ([ addr : EthWord ]) #:transparent) (struct simulation-result ([ vm : vm-exec ] [ val : Bytes ] [ txn-receipt : vm-txn-receipt ]) #:transparent) (define-type simulation-result-ex (U simulation-result exn:evm)) (define-type simulation-result-exs (Listof simulation-result-ex)) Ethereum addresses (define-type AddressEx (U #f EthWord)) (define-type StorageRoot EthWord) (define-type OnSimulateCallback (-> vm-exec EthInstruction EthWords Void)) (define-type AddressTable (HashTable Symbol Address)) (: make-address-table (-> AddressTable)) (define (make-address-table) (make-hash)) (struct vm-account ([ nonce : Natural ] [ balance : EthWord ] [ storage-root : StorageRoot ] [ code-hash : CodeHash ]) #:mutable #:transparent) (struct vm-txn ([ nonce : Natural ] [ gas-price : Natural ] [ gas-limit : Natural ] [ to : AddressEx ] [ value : Natural ] [ v : Fixnum ] [ r : Natural ] [ s : Natural ] [ data : Bytes ]) #:transparent #:mutable ) (define-type Undefined Any) (define-type vm-checkpoint Undefined) (define-type vm-log Undefined) (define-type vm-world (Mutable-HashTable Address vm-account)) (struct vm-block ([ parent-hash : EthWord ] [ ommers-hash : EthWord ] [ beneficiary : EthWord ] [ state-root : EthWord ] [ transactions-root : EthWord ] [ receipts-root : EthWord ] [ logs-bloom : Undefined ] [ difficulty : EthWord ] [ number : Fixnum ] [ gas-limit : Fixnum ] [ gas-used : Fixnum ] [ timestamp : Fixnum ] [ extra-data : EthWord ] [ mix-hash : EthWord ] [ nonce : Natural ]) #:transparent ) (struct vm-txn-receipt (; EVM spec [ post-transaction : vm-world ] [ cumulative-gas : Natural ] [ log-bloom : Undefined ] [ logs : (Listof vm-log) ] ; Additional fields [ contract-address : AddressEx ] ) #:transparent ) (struct vm-txn-substate ([ suicides : (Setof Address) ] [ log-series : (Setof vm-checkpoint) ] [ refund-balance : Fixnum ]) #:transparent) (struct vm-exec-environment ([ contract : Address ] ; Account currently executing [ origin : Address ] [ gas-price : EthWord ] [ input-data : Bytes ] [ sender : Address ] [ value : EthWord ] [ bytecode : Bytes ] [ header : vm-block ] [ depth : Natural ] [ writable? : Boolean ]) #:transparent ) (struct vm-exec ([ step : Natural ] [ pc : Natural ] [ stack : (Listof EthWord) ] [ memory : Bytes ] [ gas : Natural ] [ largest-accessed-memory : MemoryOffset ] [ env : vm-exec-environment ] [ sim : simulator ] ) #:mutable ) (define-type account-storage (HashTable EthWord EthWord)) ; An individual account's storage (define-type world-storage (HashTable Address account-storage)) ; All accounts' storages (define-type history-storage (HashTable StorageRoot world-storage)) ; All historical commit checkpoints (define-type MemoryOffset Offset) (define-type AbiType (U "void" "uint256" "uint256[]" "bool" "bytes" "string" "symbol" "int256")) (define-type ContractReturnValue (U Boolean Integer Symbol String Bytes (DottableListof ContractReturnValue ContractReturnValue))) (struct vm-store ([ history : history-storage ] [ world : world-storage ] [ account : account-storage ]) #:mutable) ) ; test.rkt (module test typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." ast)) (require (submod ".." simulator)) (unsafe-provide (all-defined-out)) (struct test-mod-value ([ value : Natural ]) #:transparent) (struct test-mod-sender ([ sender : Symbol ]) #:transparent) (struct test-mod-data-sender ([ sender : Symbol ]) #:transparent) (struct test-mod-assert-balance ([ account : Symbol ] [ amount : Natural ]) #:transparent) (struct test-mod-assert-return ([ value : Any ]) #:transparent) (define-type init-mod (U test-mod-value test-mod-sender)) (define-type test-mod (U test-mod-value test-mod-sender test-mod-data-sender test-mod-assert-balance test-mod-assert-return)) (define-type test-mods (Listof test-mod)) (struct test-expectation ([ name : String ] [ expected : Any ] [ actual : (-> simulation-result-ex Any)]) #:transparent) (struct test-txn ([ mods : test-mods ] [ tests : (Listof test-expectation) ]) #:transparent #:mutable) (struct test-account ([ name : Symbol ] [ balance : EthWord ]) #:transparent) (struct test-case ([ name : String ] [ accounts : test-accounts ] [ deploy-txn : test-txn ] [ msg-txns : test-txns]) #:transparent #:mutable) (struct test-suite ([ name : String ] [ cases : (Listof test-case) ]) #:transparent) (define-type test-expectations (Listof test-expectation)) (define-type test-txns (Listof test-txn)) (define-type test-accounts (Listof test-account)) (define-type test-cases (Listof test-case)) ) (module pyramidc typed/racket (require typed/racket/unsafe) (require (submod ".." ast)) (require (submod ".." abstract-machine)) (require (submod ".." evm-assembly)) (unsafe-provide (all-defined-out)) (struct translation-unit ([ language : Symbol ] [ source-code : Sexp ] [ abstract-syntax : Any ] [ pyramid-ast : Pyramid ] [ dependencies : translation-units ] ) #:transparent ) (struct full-compile-result ([ bytes : Bytes ] [ abstract-insts : Instructions ] [ eth-insts : EthInstructions ]) #:transparent) (define-type translation-units (Listof translation-unit)) )
null
https://raw.githubusercontent.com/MichaelBurge/pyramid-scheme/d38ba194dca8eced474fb26956864ea30f9e23ce/types.rkt
racket
(require typed/racket/unsafe) (unsafe-provide (all-defined-out)) These submodules should be in the original file, but this issue prevents that: codegen.rkt compiler.rkt ast.rkt simulator.rkt EVM spec Additional fields Account currently executing An individual account's storage All accounts' storages All historical commit checkpoints test.rkt
#lang typed/racket (provide (all-defined-out)) (module common typed/racket (require typed/racket/unsafe) (provide (all-defined-out) register-value?) (define-type Offset Natural) (define-type Counter Natural) (define-type Size Natural) (define-type Anys (Listof Any)) (define-type Symbols (Listof Symbol)) (define-type EthWord Natural) (define-type EthWords (Listof EthWord)) (define-type EthInt Integer) (define-type EthInts (Listof EthInt)) (struct label ([ name : Symbol ]) #:transparent) (struct label-definition label ([ offset : Integer ] [ virtual? : Boolean ]) #:transparent) (define-type RegisterValue (U Boolean Symbol Integer String Char (Listof Integer) (Listof Symbol) (Listof String) (Vectorof Integer))) (module unsafe racket (provide register-value?) (define (register-value? x) (or (boolean? x) (symbol? x) (integer? x) (string? x) (list? x) (vector? x))) ) (unsafe-require/typed 'unsafe [ register-value? (-> Any Boolean : RegisterValue) ]) (define-type Verbosity Fixnum) (define-type SourceMap (HashTable Symbol Symbols)) (define-type labels (Listof label)) (: make-source-map (-> SourceMap)) (define (make-source-map) (make-hash)) (define-type (DottableListof A B) (U Null (Pairof A (U B (DottableListof A B))))) ) (module evm-assembly typed/racket (require (submod ".." common)) (provide (all-defined-out)) (struct opcode ([ byte : Byte ] [ name : Symbol ] [ num-reads : Natural] [ num-writes : Natural ]) #:transparent) (struct evm-op ([ name : Symbol ]) #:transparent) (struct evm-push ([ size : (U 'shrink Byte) ] [ value : (U Integer Symbol label) ]) #:transparent) (struct evm-bytes ([ bytes : Bytes ]) #:transparent) (define-type EthInstruction (U evm-op evm-push evm-bytes label-definition)) (define-type EthInstructions (Listof EthInstruction)) (define-type Generator0 (-> EthInstructions)) (define-type (Generator A) (-> A EthInstructions)) (define-type Generator1 Generator) (define-type (Generator2 A B) (-> A B EthInstructions)) (define-type (Generator3 A B C) (-> A B C EthInstructions)) (struct relocation ([ pos : Integer ] [ symbol : Symbol ]) #:transparent) (struct patchpoint ([ symbol : Symbol ] [ initializer : EthInstructions ]) #:transparent) (define-type SymbolTable (Mutable-HashTable Symbol Offset)) (define-type ReverseSymbolTable (Mutable-HashTable Natural Symbol)) (define-type RelocationTable (Setof relocation)) (define-type LinkedOffset Offset) (define-type UnlinkedOffset Offset) (define-type SourceMapper (-> UnlinkedOffset Symbols)) (: make-symbol-table (-> SymbolTable)) (define (make-symbol-table) (make-hash)) (: make-reverse-symbol-table (-> ReverseSymbolTable)) (define (make-reverse-symbol-table) (make-hash)) (: make-relocation-table (-> RelocationTable)) (define (make-relocation-table) (set)) ) (module abstract-machine typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." evm-assembly)) ( require ( submod " .. " ast ) ) (provide (all-defined-out)) (define-type RegisterName (U 'env 'proc 'continue 'argl 'val 'stack-size)) (struct primop ([ name : Symbol ] [ gen : Procedure ] [ eval : Procedure ]) #:transparent) (define-type PrimopTable (HashTable Symbol primop)) (struct assign ([ reg-name : RegisterName ] [ value : MExpr ]) #:transparent) (struct test ([ condition : MExpr ]) #:transparent) (struct branch ([ dest : MExpr ]) #:transparent) (struct goto ([ dest : MExpr ]) #:transparent) (struct save ([ exp : MExpr ]) #:transparent) (struct restore ([ reg-name : RegisterName ]) #:transparent) (struct perform ([ action : MExpr ]) #:transparent) (struct evm ([ insts : EthInstructions ]) #:transparent) (define-type Instruction (U label-definition assign test branch goto save restore perform evm )) (struct reg ([name : RegisterName]) #:transparent) (struct const ([ value : RegisterValue ]) #:transparent) (struct boxed-const ([ value : RegisterValue ]) #:transparent) (struct op ([ name : Symbol] [ args : MExprs ]) #:transparent) (struct %stack ()) (define stack (%stack)) (define stack? %stack?) (define-type MExpr (U reg const boxed-const op Symbol label %stack evm )) (struct inst-seq ([ needs : RegisterNames ] [ modifies : RegisterNames ] [ statements : Instructions ]) #:transparent) (define-type MExprs (Listof MExpr)) (define-type Instructions (Listof Instruction)) (define-type RegisterNames (Setof RegisterName)) (struct v-fixnum ([value : Natural] [ ptr : Natural ]) #:mutable #:transparent) (struct v-symbol ([value : Symbol ]) #:transparent) (struct v-char ([value : Char ]) #:transparent) (struct v-compiled-procedure ([label : label ] [ env : v-environment]) #:transparent) (struct v-primitive-procedure ([label : label ]) #:transparent) (struct v-pair ([left : value] [right : value]) #:transparent) (struct v-vector ([elems : (Vectorof value)]) #:transparent) (struct v-null ( ) #:transparent) (struct v-continuation ([continue : label ] [env : v-environment] [ stack : values ]) #:transparent) (struct v-frame ([mappings : (HashTable Symbol value)]) #:transparent) (struct v-environment ([frames : v-frames])) (struct v-bytes ([ptr : Natural ]) #:transparent) (struct v-string ([str : String ]) #:transparent) (define-type v-unboxed (U Integer Symbol Boolean)) (define-type v-callable (U v-compiled-procedure v-primitive-procedure v-continuation)) (define-type v-list (U v-null v-pair)) (define-predicate v-unboxed? v-unboxed) (define-predicate v-callable? v-callable) (define-predicate v-list? v-list) (define-type value (U Void v-unboxed v-fixnum v-symbol v-char v-compiled-procedure v-primitive-procedure v-pair v-vector v-null v-continuation v-frame v-environment v-bytes v-string label)) (define-type v-frames (Listof v-frame)) (define-type values (Listof value)) (struct machine ([pc : Natural] [env : v-environment] [proc : v-callable] [continue : label] [argl : value] [val : value] [stack-size : Natural] [stack : values] [halted? : Boolean]) #:transparent #:mutable) ) (module ast typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." abstract-machine)) (unsafe-provide (all-defined-out) (all-from-out (submod ".." common))) (struct pyr-const ([ value : RegisterValue ] [ boxed? : Boolean ]) #:transparent) (struct pyr-variable ([ name : Symbol ]) #:transparent) (struct pyr-quoted ([ exp : Pyramid ]) #:transparent) (struct pyr-assign ([ name : VariableName ] [ value : Pyramid ]) #:transparent) (struct pyr-definition ([ name : VariableName ] [ body : Pyramid ]) #:transparent) (struct pyr-if ([ predicate : Pyramid ] [ consequent : Pyramid ] [ alternative : Pyramid ]) #:transparent) (struct pyr-lambda ([ names : VariableNames ] [ body : Pyramid ]) #:transparent) (struct pyr-begin ([ body : Pyramids ]) #:transparent) (struct pyr-application ([ operator : Pyramid ] [ operands : Pyramids ] [ rest : (Option Pyramid) ]) #:transparent) (struct pyr-macro-application ([ name : VariableName ] [ app-syntax : PyramidQ ]) #:transparent) (struct pyr-macro-definition ([ name : VariableName ] [ parameters : DottableParameters ] [ body : PyramidQs ] [ out-options : expander-options ]) #:transparent) (struct pyr-asm ([ insts : Instructions]) #:transparent) (struct pyr-unknown-application ([ name : VariableName ] [ app-syntax : PyramidQ ]) #:transparent) (define-type Pyramid (U pyr-const pyr-variable pyr-quoted pyr-assign pyr-definition pyr-if pyr-lambda pyr-begin pyr-application pyr-macro-application pyr-macro-definition pyr-asm pyr-unknown-application )) (define-predicate pyramid? Pyramid) (define-type VariableName Symbol) (define-type VariableNames (Listof VariableName)) (define-type PyramidQ Syntax) (define-type PyramidQs (Listof PyramidQ)) (define-type DottableParameters Any) (define-type Racket Any) (define-type Rackets (Listof Any)) (define-type Value Any) (define-type Pyramids (Listof Pyramid)) (define-type DottedPyramids (DottableListof Pyramid Pyramid)) (define-type Assertion Any) (define-type PyrMacroFunction (-> PyramidQ PyramidQ)) (struct pyr-macro ([ func : PyrMacroFunction ] [ out-options : expander-options ]) #:transparent) (define-type Pass (-> Pyramid Pyramid)) (define-type pyr-consts (Listof pyr-const)) (define-type pyr-variables (Listof pyr-variable)) (define-type pyr-quoteds (Listof pyr-quoted)) (define-type pyr-assigns (Listof pyr-assign)) (define-type pyr-definitions (Listof pyr-definition)) (define-type pyr-ifs (Listof pyr-if)) (define-type pyr-lambdas (Listof pyr-lambda)) (define-type pyr-begins (Listof pyr-begin)) (define-type pyr-applications (Listof pyr-application)) (define-type pyr-macro-applications (Listof pyr-macro-application)) (define-type pyr-macro-definitions (Listof pyr-macro-definition)) (define-type pyr-asms (Listof pyr-asm)) (define-type LexicalTable (HashTable Symbol Lexical)) (define-type Lexical (Parameterof PyramidQ)) (: make-lexical-table (-> LexicalTable)) (define make-lexical-table make-hash) (struct expander-options ([ box-literals? : Boolean ]) #:transparent) ) (module simulator typed/racket (require (submod ".." common)) (require (submod ".." evm-assembly)) (provide (all-defined-out)) (define-type CodeHash EthWord) (struct simulator ([ accounts : vm-world ] [ store : vm-store ] [ code-db : (HashTable CodeHash Bytes) ] ) #:transparent) (define-type Frame (List (Listof String) Anys)) (define-type Environment (Listof Frame)) (define-type Frames (Listof Frame)) (struct exn:evm exn:fail:user ([ vm : vm-exec ]) #:transparent) (struct exn:evm:return exn:evm ([ result : Bytes ]) #:transparent) (struct exn:evm:misaligned-addr exn:evm ([ addr : EthWord ]) #:transparent) (struct exn:evm:throw exn:evm ([ value : Bytes ]) #:transparent) (struct exn:evm:did-not-halt exn:evm ([ max-iterations : Natural ]) #:transparent) (struct exn:evm:stack-underflow exn:evm ([ ethi : EthInstruction ] [ num-elements : Natural ] [ stack : (Listof EthWord )]) #:transparent) (struct exn:evm:misaligned-jump exn:evm ([ addr : EthWord ]) #:transparent) (struct simulation-result ([ vm : vm-exec ] [ val : Bytes ] [ txn-receipt : vm-txn-receipt ]) #:transparent) (define-type simulation-result-ex (U simulation-result exn:evm)) (define-type simulation-result-exs (Listof simulation-result-ex)) Ethereum addresses (define-type AddressEx (U #f EthWord)) (define-type StorageRoot EthWord) (define-type OnSimulateCallback (-> vm-exec EthInstruction EthWords Void)) (define-type AddressTable (HashTable Symbol Address)) (: make-address-table (-> AddressTable)) (define (make-address-table) (make-hash)) (struct vm-account ([ nonce : Natural ] [ balance : EthWord ] [ storage-root : StorageRoot ] [ code-hash : CodeHash ]) #:mutable #:transparent) (struct vm-txn ([ nonce : Natural ] [ gas-price : Natural ] [ gas-limit : Natural ] [ to : AddressEx ] [ value : Natural ] [ v : Fixnum ] [ r : Natural ] [ s : Natural ] [ data : Bytes ]) #:transparent #:mutable ) (define-type Undefined Any) (define-type vm-checkpoint Undefined) (define-type vm-log Undefined) (define-type vm-world (Mutable-HashTable Address vm-account)) (struct vm-block ([ parent-hash : EthWord ] [ ommers-hash : EthWord ] [ beneficiary : EthWord ] [ state-root : EthWord ] [ transactions-root : EthWord ] [ receipts-root : EthWord ] [ logs-bloom : Undefined ] [ difficulty : EthWord ] [ number : Fixnum ] [ gas-limit : Fixnum ] [ gas-used : Fixnum ] [ timestamp : Fixnum ] [ extra-data : EthWord ] [ mix-hash : EthWord ] [ nonce : Natural ]) #:transparent ) [ post-transaction : vm-world ] [ cumulative-gas : Natural ] [ log-bloom : Undefined ] [ logs : (Listof vm-log) ] [ contract-address : AddressEx ] ) #:transparent ) (struct vm-txn-substate ([ suicides : (Setof Address) ] [ log-series : (Setof vm-checkpoint) ] [ refund-balance : Fixnum ]) #:transparent) [ origin : Address ] [ gas-price : EthWord ] [ input-data : Bytes ] [ sender : Address ] [ value : EthWord ] [ bytecode : Bytes ] [ header : vm-block ] [ depth : Natural ] [ writable? : Boolean ]) #:transparent ) (struct vm-exec ([ step : Natural ] [ pc : Natural ] [ stack : (Listof EthWord) ] [ memory : Bytes ] [ gas : Natural ] [ largest-accessed-memory : MemoryOffset ] [ env : vm-exec-environment ] [ sim : simulator ] ) #:mutable ) (define-type MemoryOffset Offset) (define-type AbiType (U "void" "uint256" "uint256[]" "bool" "bytes" "string" "symbol" "int256")) (define-type ContractReturnValue (U Boolean Integer Symbol String Bytes (DottableListof ContractReturnValue ContractReturnValue))) (struct vm-store ([ history : history-storage ] [ world : world-storage ] [ account : account-storage ]) #:mutable) ) (module test typed/racket (require typed/racket/unsafe) (require (submod ".." common)) (require (submod ".." ast)) (require (submod ".." simulator)) (unsafe-provide (all-defined-out)) (struct test-mod-value ([ value : Natural ]) #:transparent) (struct test-mod-sender ([ sender : Symbol ]) #:transparent) (struct test-mod-data-sender ([ sender : Symbol ]) #:transparent) (struct test-mod-assert-balance ([ account : Symbol ] [ amount : Natural ]) #:transparent) (struct test-mod-assert-return ([ value : Any ]) #:transparent) (define-type init-mod (U test-mod-value test-mod-sender)) (define-type test-mod (U test-mod-value test-mod-sender test-mod-data-sender test-mod-assert-balance test-mod-assert-return)) (define-type test-mods (Listof test-mod)) (struct test-expectation ([ name : String ] [ expected : Any ] [ actual : (-> simulation-result-ex Any)]) #:transparent) (struct test-txn ([ mods : test-mods ] [ tests : (Listof test-expectation) ]) #:transparent #:mutable) (struct test-account ([ name : Symbol ] [ balance : EthWord ]) #:transparent) (struct test-case ([ name : String ] [ accounts : test-accounts ] [ deploy-txn : test-txn ] [ msg-txns : test-txns]) #:transparent #:mutable) (struct test-suite ([ name : String ] [ cases : (Listof test-case) ]) #:transparent) (define-type test-expectations (Listof test-expectation)) (define-type test-txns (Listof test-txn)) (define-type test-accounts (Listof test-account)) (define-type test-cases (Listof test-case)) ) (module pyramidc typed/racket (require typed/racket/unsafe) (require (submod ".." ast)) (require (submod ".." abstract-machine)) (require (submod ".." evm-assembly)) (unsafe-provide (all-defined-out)) (struct translation-unit ([ language : Symbol ] [ source-code : Sexp ] [ abstract-syntax : Any ] [ pyramid-ast : Pyramid ] [ dependencies : translation-units ] ) #:transparent ) (struct full-compile-result ([ bytes : Bytes ] [ abstract-insts : Instructions ] [ eth-insts : EthInstructions ]) #:transparent) (define-type translation-units (Listof translation-unit)) )