_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
e52f4ed3927f39350ea6f124ceb61550ec4752e763d8bc0a48537f0e40ecb04b
AndrasKovacs/ELTE-func-lang
Notes08.hs
# LANGUAGE InstanceSigs , DeriveFunctor , , DeriveTraversable # DeriveTraversable #-} következő óra : regex import Data.Foldable import Data.Traversable import Control.Monad import Control.Applicative -- many, some isDigit : : Bool digitToInt : : Int import Debug.Trace -- trace :: String -> a -> a -- traceShow :: Show b => b -> a -> a ( miért írjuk ? ) ( definíció bonyolultabb , a típushibák , mint amit mi néztünk ) -- canvas: data Tree = Leaf Int | Node Tree Tree deriving (Show) f :: Tree -> (Int, Int) f t = execState (go t) (0, 0) where go :: Tree -> State (Int, Int) () go (Leaf n) = modify (\(s1, s2) -> if n < 0 then (s1 + n, s2) else (s1, s2 + n)) go (Node l r) = go l >> go r traverseLeaves_ :: Applicative f => (Int -> f ()) -> Tree -> f () traverseLeaves_ f (Leaf n) = f n traverseLeaves_ f (Node l r) = traverseLeaves_ f l *> traverseLeaves_ f r -- másik : -- Applicative f => (Int -> f Int) -> Tree -> f Tree f' :: Tree -> (Int, Int) f' t = execState (traverseLeaves_ go t) (0, 0) where go :: Int -> State (Int, Int) () go n = modify (\(s1, s2) -> if n < 0 then (s1 + n, s2) else (s1, s2 + n)) PARSER LIBRARY -------------------------------------------------------------------------------- Parser a : String - ből " a " típusú értéket próbál olvasni newtype Parser a = Parser {runParser :: String -> Maybe (a, String)} deriving Functor Parser a : State String + Maybe library : függvényekből nagyobbakat összerakni -- (parser "kombinátor" library) instance Applicative Parser where pure = return (<*>) = ap instance Monad Parser where fogyaszt inputot return :: a -> Parser a return a = Parser $ \s -> Just (a, s) egymás után (>>=) :: Parser a -> (a -> Parser b) -> Parser b Parser f >>= g = Parser $ \s -> case f s of Nothing -> Nothing Just (a, s') -> runParser (g a) s' parserek közötti választás instance Alternative Parser where empty :: Parser a empty = Parser $ \_ -> Nothing (<|>) :: Parser a -> Parser a -> Parser a Parser f <|> Parser g = Parser $ \s -> case f s of Nothing -> g s x -> x -- üres String olvasása eof :: Parser () eof = Parser $ \s -> case s of [] -> Just ((), []) _ -> Nothing , satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser $ \s -> case s of c:s | f c -> Just (c, s) -- output String 1-el rövidebb! _ -> Nothing satisfy_ :: (Char -> Bool) -> Parser () satisfy_ f = () <$ satisfy f char :: Char -> Parser () char c = () <$ satisfy (==c) parser hívásakor kiír egy String üzenetet debug :: String -> Parser a -> Parser a debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s) bármilyen anyChar :: Parser Char anyChar = satisfy (\_ -> True) -- konkrét String-et próbál olvasni string :: String -> Parser () string = traverse_ char példák instance metódusokkal Functor , Applicative , Monad , Alternative fmap : Applicative : N aritású függvényt , N darab kimenetre pure a : visszaadja a - t , olvas semmit ( > > =) : -- Alternative metódusok: -- empty : rögtön Nothing-ot adó parser ( < | > ) : próbálunk egy parser - t futtatni , ha hibázik , a másik adott parser - t próbáljuk ( " choice " ) pr1 = string "kutya" <|> string "macska" pr2 = (char 'x' <|> char 'y') >> (char 'x' <|> char 'y') pr3 = replicateM_ 3 (string "kutya") Control . Applicative - ból ( ): many : : a - > Parser [ a ] -- 0 - szor vagy többször olvasás some : : a - > Parser [ a ] -- 1 - szer vagy többször olvasás many_ :: Parser a -> Parser () many_ pa = some_ pa <|> pure () some_ :: Parser a -> Parser () some_ pa = pa >> many_ pa ( ) : " validáló " függvény -- fenti műveletekkel tetszőleges regex-et definiálhatunk char , < | > , many _ , some _ , eof , ( > > ) ( lefedi a klasszikus regex definíciót ) ------------------------------------------------------------ implementáld a következő regex - eket . Szükség szerint definiálj -- segédfüggvényeket. -- (foo|bar)*kutya p01 :: Parser () p01 = many_ (string "foo" <|> string "bar") >> string "kutya" tipp : bármi , , azt nyugodtan kombinátorral megoldani -- runParser p01 "fookutya" == Just ((),"") \[foo ( , foo)*\ ] -- nemüres , -vel választott foo lista p02 :: Parser () p02 = string "[foo" >> many_ (string ", foo") >> char ']' -- (ac|bd)* p1 :: Parser () p1 = many_ (string "ac" <|> string "bd") inList_ :: [Char] -> Parser () inList_ str = satisfy_ (\c -> elem c str) inList_' :: [Char] -> Parser () inList_' str = foldr (\c p -> char c <|> p) empty str -- = () <$ choice (map char) str -- std függvény: choice :: [Parser a] -> Parser a choice ps = foldr (<|>) empty ps lowercase :: Parser () lowercase = satisfy_ (\c -> 'a' <= c && c <= 'z') -- [a..z]+@foobar\.(com|org|hu) p2 :: Parser () p2 = do some_ lowercase string "@foobar." (string "com" <|> string "org" <|> string "hu") -- -?[0..9]+ -- a -? opcionális '-'-t jelent p3 :: Parser () p3 = (char '-' <|> pure ()) >> some_ (satisfy isDigit) ( [ a .. z]|[A .. Z])([a .. z]|[A .. Z]|[0 .. 9 ] ) * p4 :: Parser () p4 = undefined ( [ a .. z]+=[0 .. 9]+)(,[a .. z]+=[0 .. 9]+ ) * példa elfogadott inputra : foo=10,bar=30,baz=40 p5 :: Parser () p5 = undefined ------------------------------------------------------------ -- Functor/Applicative operátorok ( < $ ) kicserélni parser értékre -- (<$>) fmap ( < * ) két parser - t futtat , -- (*>) két parser-t futtat, a második értékét visszaadja -- whitespace elfogyasztása ws :: Parser () ws = () <$ many (char ' ') Olvassuk pa - t 0 - szor vagy többször , psep - el elválasztva sepBy :: Parser a -> Parser sep -> Parser [a] sepBy pa psep = sepBy1 pa psep <|> pure [] Olvassuk pa - t 1 - szor vagy többször , psep - el elválasztva sepBy1 :: Parser a -> Parser sep -> Parser [a] sepBy1 pa psep = (:) <$> pa <*> many (psep *> pa) -- egy számjegy olvasása digit :: Parser Int digit = digitToInt <$> satisfy isDigit FELADATOK -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Olvass be egy pozitív Int - et ! ( Számjegyek nemüres sorozata ) posInt :: Parser Int posInt = undefined -- Írj egy parsert, ami felsimeri Int-ek vesszővel elválasztott listáit! : " [ ] " , " [ 12 , 34555 ] " , " [ 0,1,2,3 ] " intList :: Parser [Int] intList = undefined Írj egy parsert , a : " " , " ( ) " , " ( ) ( ) " , " ( ( ) ) ( ) " , " ( ( ) ( ) ) " , " ( ( ( ) ( ) ) ( ) ) " balancedPar :: Parser () balancedPar = undefined Írj egy parser - t ami , , + -t és pozitív tartalmazó -- kifejezéseket olvas! -------------------------------------------------------------------------------- : 10 + 20 + 30 -- (10 + 20) + 30 10 + ( ( 20 + 5 ) ) -- A + operátor , 1 + 2 + 3 ( Plus ( Lit 1 ) ( Plus ( Lit 2 ) ( Lit 3 ) ) ) data Exp = Lit Int | Plus Exp Exp deriving Show pExp :: Parser Exp pExp = undefined bónusz ( nehéz ): írj parser - t típusozatlan lambda ! -------------------------------------------------------------------------------- -- példák : \f x y. f y y ( \x . x ) ( \x . x ) ( \f x y. f ) x ( g x ) data Tm = Var String | App Tm Tm | Lam String Tm deriving Show pTm :: Parser Tm pTm = undefined
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/32037ea3a2a27cd85a2ca8bbef3c09430cd67087/2021-22-1/gyak_1/Notes08.hs
haskell
many, some trace :: String -> a -> a traceShow :: Show b => b -> a -> a canvas: másik : Applicative f => (Int -> f Int) -> Tree -> f Tree ------------------------------------------------------------------------------ (parser "kombinátor" library) üres String olvasása output String 1-el rövidebb! konkrét String-et próbál olvasni Alternative metódusok: empty : rögtön Nothing-ot adó parser 0 - szor vagy többször olvasás 1 - szer vagy többször olvasás fenti műveletekkel tetszőleges regex-et definiálhatunk ---------------------------------------------------------- segédfüggvényeket. (foo|bar)*kutya runParser p01 "fookutya" == Just ((),"") nemüres , -vel választott foo lista (ac|bd)* = () <$ choice (map char) str std függvény: [a..z]+@foobar\.(com|org|hu) -?[0..9]+ -- a -? opcionális '-'-t jelent ---------------------------------------------------------- Functor/Applicative operátorok (<$>) fmap (*>) két parser-t futtat, a második értékét visszaadja whitespace elfogyasztása egy számjegy olvasása ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Írj egy parsert, ami felsimeri Int-ek vesszővel elválasztott listáit! kifejezéseket olvas! ------------------------------------------------------------------------------ (10 + 20) + 30 ------------------------------------------------------------------------------ példák : \f x y. f y y
# LANGUAGE InstanceSigs , DeriveFunctor , , DeriveTraversable # DeriveTraversable #-} következő óra : regex import Data.Foldable import Data.Traversable import Control.Monad isDigit : : Bool digitToInt : : Int ( miért írjuk ? ) ( definíció bonyolultabb , a típushibák , mint amit mi néztünk ) data Tree = Leaf Int | Node Tree Tree deriving (Show) f :: Tree -> (Int, Int) f t = execState (go t) (0, 0) where go :: Tree -> State (Int, Int) () go (Leaf n) = modify (\(s1, s2) -> if n < 0 then (s1 + n, s2) else (s1, s2 + n)) go (Node l r) = go l >> go r traverseLeaves_ :: Applicative f => (Int -> f ()) -> Tree -> f () traverseLeaves_ f (Leaf n) = f n traverseLeaves_ f (Node l r) = traverseLeaves_ f l *> traverseLeaves_ f r f' :: Tree -> (Int, Int) f' t = execState (traverseLeaves_ go t) (0, 0) where go :: Int -> State (Int, Int) () go n = modify (\(s1, s2) -> if n < 0 then (s1 + n, s2) else (s1, s2 + n)) PARSER LIBRARY Parser a : String - ből " a " típusú értéket próbál olvasni newtype Parser a = Parser {runParser :: String -> Maybe (a, String)} deriving Functor Parser a : State String + Maybe library : függvényekből nagyobbakat összerakni instance Applicative Parser where pure = return (<*>) = ap instance Monad Parser where fogyaszt inputot return :: a -> Parser a return a = Parser $ \s -> Just (a, s) egymás után (>>=) :: Parser a -> (a -> Parser b) -> Parser b Parser f >>= g = Parser $ \s -> case f s of Nothing -> Nothing Just (a, s') -> runParser (g a) s' parserek közötti választás instance Alternative Parser where empty :: Parser a empty = Parser $ \_ -> Nothing (<|>) :: Parser a -> Parser a -> Parser a Parser f <|> Parser g = Parser $ \s -> case f s of Nothing -> g s x -> x eof :: Parser () eof = Parser $ \s -> case s of [] -> Just ((), []) _ -> Nothing , satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser $ \s -> case s of _ -> Nothing satisfy_ :: (Char -> Bool) -> Parser () satisfy_ f = () <$ satisfy f char :: Char -> Parser () char c = () <$ satisfy (==c) parser hívásakor kiír egy String üzenetet debug :: String -> Parser a -> Parser a debug msg pa = Parser $ \s -> trace (msg ++ " : " ++ s) (runParser pa s) bármilyen anyChar :: Parser Char anyChar = satisfy (\_ -> True) string :: String -> Parser () string = traverse_ char példák instance metódusokkal Functor , Applicative , Monad , Alternative fmap : Applicative : N aritású függvényt , N darab kimenetre pure a : visszaadja a - t , olvas semmit ( > > =) : ( < | > ) : próbálunk egy parser - t futtatni , ha hibázik , a másik adott parser - t próbáljuk ( " choice " ) pr1 = string "kutya" <|> string "macska" pr2 = (char 'x' <|> char 'y') >> (char 'x' <|> char 'y') pr3 = replicateM_ 3 (string "kutya") Control . Applicative - ból ( ): many_ :: Parser a -> Parser () many_ pa = some_ pa <|> pure () some_ :: Parser a -> Parser () some_ pa = pa >> many_ pa ( ) : " validáló " függvény char , < | > , many _ , some _ , eof , ( > > ) ( lefedi a klasszikus regex definíciót ) implementáld a következő regex - eket . Szükség szerint definiálj p01 :: Parser () p01 = many_ (string "foo" <|> string "bar") >> string "kutya" tipp : bármi , , azt nyugodtan kombinátorral megoldani p02 :: Parser () p02 = string "[foo" >> many_ (string ", foo") >> char ']' p1 :: Parser () p1 = many_ (string "ac" <|> string "bd") inList_ :: [Char] -> Parser () inList_ str = satisfy_ (\c -> elem c str) inList_' :: [Char] -> Parser () inList_' str = foldr (\c p -> char c <|> p) empty str choice :: [Parser a] -> Parser a choice ps = foldr (<|>) empty ps lowercase :: Parser () lowercase = satisfy_ (\c -> 'a' <= c && c <= 'z') p2 :: Parser () p2 = do some_ lowercase string "@foobar." (string "com" <|> string "org" <|> string "hu") p3 :: Parser () p3 = (char '-' <|> pure ()) >> some_ (satisfy isDigit) ( [ a .. z]|[A .. Z])([a .. z]|[A .. Z]|[0 .. 9 ] ) * p4 :: Parser () p4 = undefined ( [ a .. z]+=[0 .. 9]+)(,[a .. z]+=[0 .. 9]+ ) * példa elfogadott inputra : foo=10,bar=30,baz=40 p5 :: Parser () p5 = undefined ( < $ ) kicserélni parser értékre ( < * ) két parser - t futtat , ws :: Parser () ws = () <$ many (char ' ') Olvassuk pa - t 0 - szor vagy többször , psep - el elválasztva sepBy :: Parser a -> Parser sep -> Parser [a] sepBy pa psep = sepBy1 pa psep <|> pure [] Olvassuk pa - t 1 - szor vagy többször , psep - el elválasztva sepBy1 :: Parser a -> Parser sep -> Parser [a] sepBy1 pa psep = (:) <$> pa <*> many (psep *> pa) digit :: Parser Int digit = digitToInt <$> satisfy isDigit FELADATOK Olvass be egy pozitív Int - et ! ( Számjegyek nemüres sorozata ) posInt :: Parser Int posInt = undefined : " [ ] " , " [ 12 , 34555 ] " , " [ 0,1,2,3 ] " intList :: Parser [Int] intList = undefined Írj egy parsert , a : " " , " ( ) " , " ( ) ( ) " , " ( ( ) ) ( ) " , " ( ( ) ( ) ) " , " ( ( ( ) ( ) ) ( ) ) " balancedPar :: Parser () balancedPar = undefined Írj egy parser - t ami , , + -t és pozitív tartalmazó : 10 + 20 + 30 10 + ( ( 20 + 5 ) ) A + operátor , 1 + 2 + 3 ( Plus ( Lit 1 ) ( Plus ( Lit 2 ) ( Lit 3 ) ) ) data Exp = Lit Int | Plus Exp Exp deriving Show pExp :: Parser Exp pExp = undefined bónusz ( nehéz ): írj parser - t típusozatlan lambda ! ( \x . x ) ( \x . x ) ( \f x y. f ) x ( g x ) data Tm = Var String | App Tm Tm | Lam String Tm deriving Show pTm :: Parser Tm pTm = undefined
fa64c816c101b45e2310a3a46eb812326c178dad0f678a64eb8ef2cc7416b398
raspasov/neversleep
mysql_lib.clj
(ns neversleep-db.mysql-lib (:require [clojure.java.jdbc :as db-adapter] [neversleep-db.state :as state] [neversleep-db.println-m :refer [println-m]] [neversleep-db.env :as env]) (:import com.jolbox.bonecp.BoneCPDataSource)) ;MYSQL CONFIG (defn mysql-config [] (-> env/env :config :mysql)) (defn db-spec [] {:classname "com.mysql.jdbc.Driver" :subprotocol "mysql" :subname (str "//" ((mysql-config) :host) ":" ((mysql-config) :port) "/" ((mysql-config) :database-name)) :user ((mysql-config) :user) :password ((mysql-config) :password) }) (defn pool "MySQL connection pool" [spec] (let [partitions 3 cpds (doto (BoneCPDataSource.) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUsername (:user spec)) (.setPassword (:password spec)) (.setMinConnectionsPerPartition (inc (int (/ 4 partitions)))) ;min pool (.setMaxConnectionsPerPartition (inc (int (/ 20 partitions)))) ;max pool (.setPartitionCount partitions) (.setStatisticsEnabled true) test connections every 25 mins ( default is 240 ): (.setIdleConnectionTestPeriodInMinutes 25) allow connections to be idle for 3 hours ( default is 60 minutes ): (.setIdleMaxAgeInMinutes (* 3 60)) consult the BoneCP documentation for your database : (.setConnectionTestStatement "/* ping *\\/ SELECT 1"))] {:datasource cpds})) ( defonce pooled - db ( delay ( pool db - spec ) ) ) (defn db-connection [] (if (= nil @state/mysql-connection-pool) (reset! state/mysql-connection-pool (pool (db-spec)))) @state/mysql-connection-pool) ;(defn- get-last-insert-id [db-connection] ; (-> (db-adapter/query db-connection ; ["SELECT LAST_INSERT_ID() AS last_insert_id"]) ( first ) ; :last_insert_id)) ; ( defn execute - return - last - insert - id ! ; ([sql-vector] ; (db-adapter/with-db-transaction [db-connection (db-spec)] ; (db-adapter/execute! db-connection ; sql-vector) ; (get-last-insert-id db-connection)))) (defn execute! uses Timbre to log any errors ; sql-vector is in the format [query-string-with-?-params param1 param2 etc] If the operation fails with an exception, the function calls itself once to retry, might happen if the MySQL connection has timed out" ([sql-vector] (db-adapter/execute! (db-connection) sql-vector))) (defn query uses Timbre to log any errors ; sql-vector is in the format [query-string-with-?-params param1 param2 etc]; If the operation fails with an exception, the function calls itself once to retry, might happen if the MySQL connection has timed out" ([sql-vector] (db-adapter/query (db-connection) sql-vector)))
null
https://raw.githubusercontent.com/raspasov/neversleep/7fd968f4ab20fa6ef71e1049e3eec289ea6691e4/src/neversleep_db/mysql_lib.clj
clojure
MYSQL CONFIG min pool max pool (defn- get-last-insert-id [db-connection] (-> (db-adapter/query db-connection ["SELECT LAST_INSERT_ID() AS last_insert_id"]) :last_insert_id)) ([sql-vector] (db-adapter/with-db-transaction [db-connection (db-spec)] (db-adapter/execute! db-connection sql-vector) (get-last-insert-id db-connection))))
(ns neversleep-db.mysql-lib (:require [clojure.java.jdbc :as db-adapter] [neversleep-db.state :as state] [neversleep-db.println-m :refer [println-m]] [neversleep-db.env :as env]) (:import com.jolbox.bonecp.BoneCPDataSource)) (defn mysql-config [] (-> env/env :config :mysql)) (defn db-spec [] {:classname "com.mysql.jdbc.Driver" :subprotocol "mysql" :subname (str "//" ((mysql-config) :host) ":" ((mysql-config) :port) "/" ((mysql-config) :database-name)) :user ((mysql-config) :user) :password ((mysql-config) :password) }) (defn pool "MySQL connection pool" [spec] (let [partitions 3 cpds (doto (BoneCPDataSource.) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUsername (:user spec)) (.setPassword (:password spec)) (.setPartitionCount partitions) (.setStatisticsEnabled true) test connections every 25 mins ( default is 240 ): (.setIdleConnectionTestPeriodInMinutes 25) allow connections to be idle for 3 hours ( default is 60 minutes ): (.setIdleMaxAgeInMinutes (* 3 60)) consult the BoneCP documentation for your database : (.setConnectionTestStatement "/* ping *\\/ SELECT 1"))] {:datasource cpds})) ( defonce pooled - db ( delay ( pool db - spec ) ) ) (defn db-connection [] (if (= nil @state/mysql-connection-pool) (reset! state/mysql-connection-pool (pool (db-spec)))) @state/mysql-connection-pool) ( first ) ( defn execute - return - last - insert - id ! (defn execute! sql-vector is in the format [query-string-with-?-params param1 param2 etc] If the operation fails with an exception, the function calls itself once to retry, might happen if the MySQL connection has timed out" ([sql-vector] (db-adapter/execute! (db-connection) sql-vector))) (defn query If the operation fails with an exception, the function calls itself once to retry, might happen if the MySQL connection has timed out" ([sql-vector] (db-adapter/query (db-connection) sql-vector)))
d079bfe0fe71fbb9585610c87f14312f0e21a4ab6343b0787f4f2942b5b7bac8
janestreet/async_kernel
laziness_preserving_deferred.ml
open Core open Async_kernel module T = struct type 'a t = | Eager of 'a Deferred.Or_error.t | Lazy of 'a Lazy_deferred.t | Bind of { mutable state : 'a bind } and 'a bind = | Ready : 'a t * ('a -> 'b t) -> 'b bind | Running : 'a t Deferred.Or_error.t -> 'a bind let return x = Eager (Deferred.Or_error.return x) let bind t ~f = Bind { state = Ready (t, f) } let map = `Define_using_bind end include T include Monad.Make (T) let of_eager deferred = Eager (Deferred.ok deferred) let of_lazy lazy_deferred = Lazy lazy_deferred module On_lazy = struct type t = { f : 'a. 'a Lazy_deferred.t -> 'a Deferred.Or_error.t } let wait = { f = Lazy_deferred.wait } let force = { f = Lazy_deferred.force } end let rec run : 'a. 'a t -> on_lazy:On_lazy.t -> 'a Deferred.Or_error.t = fun t ~on_lazy -> let open Deferred.Or_error.Let_syntax in match t with | Eager deferred -> deferred | Lazy lazy_deferred -> on_lazy.f lazy_deferred | Bind bind -> (match bind.state with | Running result -> result >>= run ~on_lazy | Ready (t, f) -> let%bind x = run t ~on_lazy in At this point there may be multiple readers of [ run t ] . The first of these to continue here invokes [ f ] and sets the state to [ Running ] . Then the others just run on the same result of that [ f ] call . The goal here is to avoid calling [ f ] multiple times . continue here invokes [f] and sets the state to [Running]. Then the others just run on the same result of that [f] call. The goal here is to avoid calling [f] multiple times. *) let result = match bind.state with | Running result -> result | Ready _ -> let result = Monitor.try_with_or_error ~extract_exn:true ~rest:`Raise (fun () -> Deferred.return (f x)) in bind.state <- Running result; result in result >>= run ~on_lazy) ;; let force t = run t ~on_lazy:On_lazy.force let weak_run t = run t ~on_lazy:On_lazy.wait
null
https://raw.githubusercontent.com/janestreet/async_kernel/9575c63faac6c2d6af20f0f21ec535401f310296/laziness_preserving_deferred/src/laziness_preserving_deferred.ml
ocaml
open Core open Async_kernel module T = struct type 'a t = | Eager of 'a Deferred.Or_error.t | Lazy of 'a Lazy_deferred.t | Bind of { mutable state : 'a bind } and 'a bind = | Ready : 'a t * ('a -> 'b t) -> 'b bind | Running : 'a t Deferred.Or_error.t -> 'a bind let return x = Eager (Deferred.Or_error.return x) let bind t ~f = Bind { state = Ready (t, f) } let map = `Define_using_bind end include T include Monad.Make (T) let of_eager deferred = Eager (Deferred.ok deferred) let of_lazy lazy_deferred = Lazy lazy_deferred module On_lazy = struct type t = { f : 'a. 'a Lazy_deferred.t -> 'a Deferred.Or_error.t } let wait = { f = Lazy_deferred.wait } let force = { f = Lazy_deferred.force } end let rec run : 'a. 'a t -> on_lazy:On_lazy.t -> 'a Deferred.Or_error.t = fun t ~on_lazy -> let open Deferred.Or_error.Let_syntax in match t with | Eager deferred -> deferred | Lazy lazy_deferred -> on_lazy.f lazy_deferred | Bind bind -> (match bind.state with | Running result -> result >>= run ~on_lazy | Ready (t, f) -> let%bind x = run t ~on_lazy in At this point there may be multiple readers of [ run t ] . The first of these to continue here invokes [ f ] and sets the state to [ Running ] . Then the others just run on the same result of that [ f ] call . The goal here is to avoid calling [ f ] multiple times . continue here invokes [f] and sets the state to [Running]. Then the others just run on the same result of that [f] call. The goal here is to avoid calling [f] multiple times. *) let result = match bind.state with | Running result -> result | Ready _ -> let result = Monitor.try_with_or_error ~extract_exn:true ~rest:`Raise (fun () -> Deferred.return (f x)) in bind.state <- Running result; result in result >>= run ~on_lazy) ;; let force t = run t ~on_lazy:On_lazy.force let weak_run t = run t ~on_lazy:On_lazy.wait
a53097d3ad7930eb4cbf4c22aa943946c155afac5dee6f01603445a87a7a6c3f
nuprl/gradual-typing-performance
main.rkt
#lang racket/base (require "echo.rkt") (define MESSAGE (make-string 1000)) (define (server-loop in out) (lambda () (echo in out))) (define (main n) (for ((_i (in-range n))) (define-values (in out) (make-pipe)) (define-values (_in _out) (make-pipe)) (define c (make-custodian)) (parameterize ([current-custodian c]) (define server (thread (server-loop in _out))) (parameterize ([current-input-port _in] [current-output-port out]) (displayln MESSAGE) (read-line))))) (time (main 1000))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/threads/communication/untyped/main.rkt
racket
#lang racket/base (require "echo.rkt") (define MESSAGE (make-string 1000)) (define (server-loop in out) (lambda () (echo in out))) (define (main n) (for ((_i (in-range n))) (define-values (in out) (make-pipe)) (define-values (_in _out) (make-pipe)) (define c (make-custodian)) (parameterize ([current-custodian c]) (define server (thread (server-loop in _out))) (parameterize ([current-input-port _in] [current-output-port out]) (displayln MESSAGE) (read-line))))) (time (main 1000))
9cb005309bc394f9ee4714a21a24fd49c4afd72e88858a9a6073578cfa0ef735
spechub/Hets
SFKT.hs
{-# LANGUAGE RankNTypes #-} | Module : ./Common / SFKT.hs Copyright : ( c ) 2005 , , , and License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : non - portable ( RankNTypes ) Implementation of LogicT based on the two - continuation model of streams Module : ./Common/SFKT.hs Copyright : (c) 2005, Amr Sabry, Chung-chieh Shan, Oleg Kiselyov and Daniel P. Friedman License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : non-portable (RankNTypes) Implementation of LogicT based on the two-continuation model of streams -} module Common.SFKT ( SFKT , runM , observe ) where import Control.Applicative import Control.Monad import qualified Control.Monad.Fail as Fail import Control.Monad.Trans import Common.LogicT Monad with success , failure continuations , mzero , and mplus We can also split computations using msplit Cf . 's ICFP00 paper , . 8 : CPS implementation of BACKTR We can also split computations using msplit Cf. Hinze's ICFP00 paper, Fig. 8: CPS implementation of BACKTR -} The extra ` r ' is just to be compatible with the SRReifT.hs type SG r m a = SFKT m a type SG r m a = SFKT m a -} newtype SFKT m a = SFKT { unSFKT :: forall ans . SK (m ans) a -> FK (m ans) -> m ans } type FK ans = ans type SK ans a = a -> FK ans -> ans the success continuation gets one answer(value ) and a computation to run to get more answers to run to get more answers -} instance Monad m => Functor (SFKT m) where fmap = liftM instance Monad m => Applicative (SFKT m) where pure = return (<*>) = ap instance Monad m => Monad (SFKT m) where return e = SFKT (\ sk -> sk e) m >>= f = SFKT (\ sk -> unSFKT m (\ a -> unSFKT (f a) sk)) instance Monad m => Alternative (SFKT m) where (<|>) = mplus empty = mzero instance Monad m => MonadPlus (SFKT m) where mzero = SFKT (\ _ fk -> fk) m1 `mplus` m2 = SFKT (\ sk fk -> unSFKT m1 sk (unSFKT m2 sk fk)) instance Fail.MonadFail m => Fail.MonadFail (SFKT m) where fail str = SFKT (\ _ _ -> Fail.fail str) instance MonadTrans SFKT where -- Hinze's promote lift m = SFKT (\ sk fk -> m >>= (`sk` fk)) instance (MonadIO m) => MonadIO (SFKT m) where liftIO = lift . liftIO But this is not in 's paper instance LogicT SFKT where msplit m = lift $ unSFKT m ssk (return Nothing) where ssk a fk = return $ Just (a, lift fk >>= reflect) This is a poly - answer ` observe ' function of runM :: (Monad m) => Maybe Int -> SFKT m a -> m [a] runM Nothing (SFKT m) = m (\ a -> liftM (a :)) (return []) runM (Just n) (SFKT _m) | n <= 0 = return [] runM (Just 1) (SFKT m) = m (\ a _fk -> return [a]) (return []) runM (Just n) m = unSFKT (msplit m) runM' (return []) where runM' Nothing _ = return [] runM' (Just (a, m')) _ = liftM (a :) (runM (Just (n - 1)) m') observe :: Fail.MonadFail m => SFKT m a -> m a observe m = unSFKT m (\ a _fk -> return a) (Fail.fail "no answer")
null
https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/Common/SFKT.hs
haskell
# LANGUAGE RankNTypes # Hinze's promote
| Module : ./Common / SFKT.hs Copyright : ( c ) 2005 , , , and License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : non - portable ( RankNTypes ) Implementation of LogicT based on the two - continuation model of streams Module : ./Common/SFKT.hs Copyright : (c) 2005, Amr Sabry, Chung-chieh Shan, Oleg Kiselyov and Daniel P. Friedman License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : non-portable (RankNTypes) Implementation of LogicT based on the two-continuation model of streams -} module Common.SFKT ( SFKT , runM , observe ) where import Control.Applicative import Control.Monad import qualified Control.Monad.Fail as Fail import Control.Monad.Trans import Common.LogicT Monad with success , failure continuations , mzero , and mplus We can also split computations using msplit Cf . 's ICFP00 paper , . 8 : CPS implementation of BACKTR We can also split computations using msplit Cf. Hinze's ICFP00 paper, Fig. 8: CPS implementation of BACKTR -} The extra ` r ' is just to be compatible with the SRReifT.hs type SG r m a = SFKT m a type SG r m a = SFKT m a -} newtype SFKT m a = SFKT { unSFKT :: forall ans . SK (m ans) a -> FK (m ans) -> m ans } type FK ans = ans type SK ans a = a -> FK ans -> ans the success continuation gets one answer(value ) and a computation to run to get more answers to run to get more answers -} instance Monad m => Functor (SFKT m) where fmap = liftM instance Monad m => Applicative (SFKT m) where pure = return (<*>) = ap instance Monad m => Monad (SFKT m) where return e = SFKT (\ sk -> sk e) m >>= f = SFKT (\ sk -> unSFKT m (\ a -> unSFKT (f a) sk)) instance Monad m => Alternative (SFKT m) where (<|>) = mplus empty = mzero instance Monad m => MonadPlus (SFKT m) where mzero = SFKT (\ _ fk -> fk) m1 `mplus` m2 = SFKT (\ sk fk -> unSFKT m1 sk (unSFKT m2 sk fk)) instance Fail.MonadFail m => Fail.MonadFail (SFKT m) where fail str = SFKT (\ _ _ -> Fail.fail str) instance MonadTrans SFKT where lift m = SFKT (\ sk fk -> m >>= (`sk` fk)) instance (MonadIO m) => MonadIO (SFKT m) where liftIO = lift . liftIO But this is not in 's paper instance LogicT SFKT where msplit m = lift $ unSFKT m ssk (return Nothing) where ssk a fk = return $ Just (a, lift fk >>= reflect) This is a poly - answer ` observe ' function of runM :: (Monad m) => Maybe Int -> SFKT m a -> m [a] runM Nothing (SFKT m) = m (\ a -> liftM (a :)) (return []) runM (Just n) (SFKT _m) | n <= 0 = return [] runM (Just 1) (SFKT m) = m (\ a _fk -> return [a]) (return []) runM (Just n) m = unSFKT (msplit m) runM' (return []) where runM' Nothing _ = return [] runM' (Just (a, m')) _ = liftM (a :) (runM (Just (n - 1)) m') observe :: Fail.MonadFail m => SFKT m a -> m a observe m = unSFKT m (\ a _fk -> return a) (Fail.fail "no answer")
7b34cd4b59f6fee35fe02a414dcfbfcad9b3120e78f32e47db439192d9217a7b
binaryage/chromex
autofill_private.clj
(ns chromex.ext.autofill-private "Use the chrome.autofillPrivate API to add, remove, or update autofill data from the settings UI. * available since Chrome master" (:refer-clojure :only [defmacro defn apply declare meta let partial]) (:require [chromex.wrapgen :refer [gen-wrap-helper]] [chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]])) (declare api-table) (declare gen-call) -- functions -------------------------------------------------------------------------------------------------------------- (defmacro save-address "Saves the given address. If |address| has an empty string as its ID, it will be assigned a new one and added as a new entry. |address| - The address entry to save." ([address] (gen-call :function ::save-address &form address))) (defmacro get-country-list "Gets the list of all countries. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [countries] where: |countries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-country-list &form))) (defmacro get-address-components "Gets the address components for a given country code. |country-code| - A two-character string representing the address' country whose components should be returned. See autofill_country.cc for a list of valid codes. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [components] where: |components| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([country-code] (gen-call :function ::get-address-components &form country-code))) (defmacro get-address-list "Gets the list of addresses. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-address-list &form))) (defmacro save-credit-card "Saves the given credit card. If |card| has an empty string as its ID, it will be assigned a new one and added as a new entry. |card| - The card entry to save." ([card] (gen-call :function ::save-credit-card &form card))) (defmacro remove-entry "Removes the entry (address or credit card) with the given ID. |guid| - ID of the entry to remove." ([guid] (gen-call :function ::remove-entry &form guid))) (defmacro validate-phone-numbers "Validates a newly-added phone number and invokes the callback with a list of validated numbers. Note that if the newly-added number was invalid, it will not be returned in the list of valid numbers. |params| - The parameters to this function. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [validated-phone-numbers] where: |validated-phone-numbers| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([params] (gen-call :function ::validate-phone-numbers &form params))) (defmacro get-credit-card-list "Gets the list of credit cards. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-credit-card-list &form))) (defmacro mask-credit-card "Clears the data associated with a wallet card which was saved locally so that the saved copy is masked (e.g., 'Card ending in 1234'). |guid| - GUID of the credit card to mask." ([guid] (gen-call :function ::mask-credit-card &form guid))) (defmacro migrate-credit-cards "Triggers local credit cards migration." ([] (gen-call :function ::migrate-credit-cards &form))) (defmacro log-server-card-link-clicked "Logs that the server cards edit link was clicked." ([] (gen-call :function ::log-server-card-link-clicked &form))) (defmacro set-credit-card-fido-auth-enabled-state "Enables or disables FIDO Authentication for credit card unmasking. |enabled| - ?" ([enabled] (gen-call :function ::set-credit-card-fido-auth-enabled-state &form enabled))) (defmacro get-upi-id-list "Gets the list of UPI IDs (a.k.a. Virtual Payment Addresses). This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-upi-id-list &form))) ; -- events ----------------------------------------------------------------------------------------------------------------- ; ; docs: /#tapping-events (defmacro tap-on-personal-data-changed-events "Fired when the personal data has changed, meaning that an entry has been added, removed, or changed. |entries| The updated list of entries. Events will be put on the |channel| with signature [::on-personal-data-changed [address-entries credit-card-entries]] where: |address-entries| - ? |credit-card-entries| - ? Note: |args| will be passed as additional parameters into Chrome event's .addListener call." ([channel & args] (apply gen-call :event ::on-personal-data-changed &form channel args))) ; -- convenience ------------------------------------------------------------------------------------------------------------ (defmacro tap-all-events "Taps all valid non-deprecated events in chromex.ext.autofill-private namespace." [chan] (gen-tap-all-events-call api-table (meta &form) chan)) ; --------------------------------------------------------------------------------------------------------------------------- ; -- API TABLE -------------------------------------------------------------------------------------------------------------- ; --------------------------------------------------------------------------------------------------------------------------- (def api-table {:namespace "chrome.autofillPrivate", :since "master", :functions [{:id ::save-address, :name "saveAddress", :params [{:name "address", :type "autofillPrivate.AddressEntry"}]} {:id ::get-country-list, :name "getCountryList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "countries", :type "[array-of-objects]"}]}}]} {:id ::get-address-components, :name "getAddressComponents", :callback? true, :params [{:name "country-code", :type "string"} {:name "callback", :type :callback, :callback {:params [{:name "components", :type "object"}]}}]} {:id ::get-address-list, :name "getAddressList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-autofillPrivate.AddressEntrys]"}]}}]} {:id ::save-credit-card, :name "saveCreditCard", :params [{:name "card", :type "autofillPrivate.CreditCardEntry"}]} {:id ::remove-entry, :name "removeEntry", :params [{:name "guid", :type "string"}]} {:id ::validate-phone-numbers, :name "validatePhoneNumbers", :callback? true, :params [{:name "params", :type "object"} {:name "callback", :type :callback, :callback {:params [{:name "validated-phone-numbers", :type "[array-of-strings]"}]}}]} {:id ::get-credit-card-list, :name "getCreditCardList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-autofillPrivate.CreditCardEntrys]"}]}}]} {:id ::mask-credit-card, :name "maskCreditCard", :params [{:name "guid", :type "string"}]} {:id ::migrate-credit-cards, :name "migrateCreditCards"} {:id ::log-server-card-link-clicked, :name "logServerCardLinkClicked"} {:id ::set-credit-card-fido-auth-enabled-state, :name "setCreditCardFIDOAuthEnabledState", :params [{:name "enabled", :type "boolean"}]} {:id ::get-upi-id-list, :name "getUpiIdList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-strings]"}]}}]}], :events [{:id ::on-personal-data-changed, :name "onPersonalDataChanged", :params [{:name "address-entries", :type "[array-of-autofillPrivate.AddressEntrys]"} {:name "credit-card-entries", :type "[array-of-autofillPrivate.CreditCardEntrys]"}]}]}) ; -- helpers ---------------------------------------------------------------------------------------------------------------- ; code generation for native API wrapper (defmacro gen-wrap [kind item-id config & args] (apply gen-wrap-helper api-table kind item-id config args)) ; code generation for API call-site (def gen-call (partial gen-call-helper api-table))
null
https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/exts_private/chromex/ext/autofill_private.clj
clojure
-- events ----------------------------------------------------------------------------------------------------------------- docs: /#tapping-events -- convenience ------------------------------------------------------------------------------------------------------------ --------------------------------------------------------------------------------------------------------------------------- -- API TABLE -------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- -- helpers ---------------------------------------------------------------------------------------------------------------- code generation for native API wrapper code generation for API call-site
(ns chromex.ext.autofill-private "Use the chrome.autofillPrivate API to add, remove, or update autofill data from the settings UI. * available since Chrome master" (:refer-clojure :only [defmacro defn apply declare meta let partial]) (:require [chromex.wrapgen :refer [gen-wrap-helper]] [chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]])) (declare api-table) (declare gen-call) -- functions -------------------------------------------------------------------------------------------------------------- (defmacro save-address "Saves the given address. If |address| has an empty string as its ID, it will be assigned a new one and added as a new entry. |address| - The address entry to save." ([address] (gen-call :function ::save-address &form address))) (defmacro get-country-list "Gets the list of all countries. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [countries] where: |countries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-country-list &form))) (defmacro get-address-components "Gets the address components for a given country code. |country-code| - A two-character string representing the address' country whose components should be returned. See autofill_country.cc for a list of valid codes. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [components] where: |components| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([country-code] (gen-call :function ::get-address-components &form country-code))) (defmacro get-address-list "Gets the list of addresses. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-address-list &form))) (defmacro save-credit-card "Saves the given credit card. If |card| has an empty string as its ID, it will be assigned a new one and added as a new entry. |card| - The card entry to save." ([card] (gen-call :function ::save-credit-card &form card))) (defmacro remove-entry "Removes the entry (address or credit card) with the given ID. |guid| - ID of the entry to remove." ([guid] (gen-call :function ::remove-entry &form guid))) (defmacro validate-phone-numbers "Validates a newly-added phone number and invokes the callback with a list of validated numbers. Note that if the newly-added number was invalid, it will not be returned in the list of valid numbers. |params| - The parameters to this function. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [validated-phone-numbers] where: |validated-phone-numbers| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([params] (gen-call :function ::validate-phone-numbers &form params))) (defmacro get-credit-card-list "Gets the list of credit cards. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-credit-card-list &form))) (defmacro mask-credit-card "Clears the data associated with a wallet card which was saved locally so that the saved copy is masked (e.g., 'Card ending in 1234'). |guid| - GUID of the credit card to mask." ([guid] (gen-call :function ::mask-credit-card &form guid))) (defmacro migrate-credit-cards "Triggers local credit cards migration." ([] (gen-call :function ::migrate-credit-cards &form))) (defmacro log-server-card-link-clicked "Logs that the server cards edit link was clicked." ([] (gen-call :function ::log-server-card-link-clicked &form))) (defmacro set-credit-card-fido-auth-enabled-state "Enables or disables FIDO Authentication for credit card unmasking. |enabled| - ?" ([enabled] (gen-call :function ::set-credit-card-fido-auth-enabled-state &form enabled))) (defmacro get-upi-id-list "Gets the list of UPI IDs (a.k.a. Virtual Payment Addresses). This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [entries] where: |entries| - ? In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error." ([] (gen-call :function ::get-upi-id-list &form))) (defmacro tap-on-personal-data-changed-events "Fired when the personal data has changed, meaning that an entry has been added, removed, or changed. |entries| The updated list of entries. Events will be put on the |channel| with signature [::on-personal-data-changed [address-entries credit-card-entries]] where: |address-entries| - ? |credit-card-entries| - ? Note: |args| will be passed as additional parameters into Chrome event's .addListener call." ([channel & args] (apply gen-call :event ::on-personal-data-changed &form channel args))) (defmacro tap-all-events "Taps all valid non-deprecated events in chromex.ext.autofill-private namespace." [chan] (gen-tap-all-events-call api-table (meta &form) chan)) (def api-table {:namespace "chrome.autofillPrivate", :since "master", :functions [{:id ::save-address, :name "saveAddress", :params [{:name "address", :type "autofillPrivate.AddressEntry"}]} {:id ::get-country-list, :name "getCountryList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "countries", :type "[array-of-objects]"}]}}]} {:id ::get-address-components, :name "getAddressComponents", :callback? true, :params [{:name "country-code", :type "string"} {:name "callback", :type :callback, :callback {:params [{:name "components", :type "object"}]}}]} {:id ::get-address-list, :name "getAddressList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-autofillPrivate.AddressEntrys]"}]}}]} {:id ::save-credit-card, :name "saveCreditCard", :params [{:name "card", :type "autofillPrivate.CreditCardEntry"}]} {:id ::remove-entry, :name "removeEntry", :params [{:name "guid", :type "string"}]} {:id ::validate-phone-numbers, :name "validatePhoneNumbers", :callback? true, :params [{:name "params", :type "object"} {:name "callback", :type :callback, :callback {:params [{:name "validated-phone-numbers", :type "[array-of-strings]"}]}}]} {:id ::get-credit-card-list, :name "getCreditCardList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-autofillPrivate.CreditCardEntrys]"}]}}]} {:id ::mask-credit-card, :name "maskCreditCard", :params [{:name "guid", :type "string"}]} {:id ::migrate-credit-cards, :name "migrateCreditCards"} {:id ::log-server-card-link-clicked, :name "logServerCardLinkClicked"} {:id ::set-credit-card-fido-auth-enabled-state, :name "setCreditCardFIDOAuthEnabledState", :params [{:name "enabled", :type "boolean"}]} {:id ::get-upi-id-list, :name "getUpiIdList", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "entries", :type "[array-of-strings]"}]}}]}], :events [{:id ::on-personal-data-changed, :name "onPersonalDataChanged", :params [{:name "address-entries", :type "[array-of-autofillPrivate.AddressEntrys]"} {:name "credit-card-entries", :type "[array-of-autofillPrivate.CreditCardEntrys]"}]}]}) (defmacro gen-wrap [kind item-id config & args] (apply gen-wrap-helper api-table kind item-id config args)) (def gen-call (partial gen-call-helper api-table))
121d203bed81a8bf137f3d209cf60df2cd099239bd177c561d2aa9005194d791
wattlebirdaz/rclref
brutal_kill_nodes_SUITE.erl
-module(brutal_kill_nodes_SUITE). -include_lib("common_test/include/ct.hrl"). -export([all/0, init_per_suite/1, end_per_suite/1]). -export([brutal_kill_nodes_test/1]). all() -> [brutal_kill_nodes_test]. init_per_suite(Config) -> application:ensure_all_started(rclref), Names = [node1, node2, node3, node4], Ports = [50100, 50110, 50120, 50130], Nodes = node_utils:set_up_nodes(Names, Ports, [{module, ?MODULE}]), [{module, ?MODULE}, {names, Names}, {nodes, Nodes}, {ports, Ports} | Config]. end_per_suite(Config) -> Nodes = ?config(nodes, Config), node_utils:kill_nodes(Nodes), Config. brutal_kill_nodes_test(Config) -> Nodes = ?config(nodes, Config), % brutal kill nodes KilledNodes = node_utils:brutal_kill_nodes(Nodes), % check dead [pang = net_adm:ping(Node) || Node <- KilledNodes], ok.
null
https://raw.githubusercontent.com/wattlebirdaz/rclref/0e31857de43e3930f69d4063f79a518fe9fdbb79/test/other/brutal_kill_nodes_SUITE.erl
erlang
brutal kill nodes check dead
-module(brutal_kill_nodes_SUITE). -include_lib("common_test/include/ct.hrl"). -export([all/0, init_per_suite/1, end_per_suite/1]). -export([brutal_kill_nodes_test/1]). all() -> [brutal_kill_nodes_test]. init_per_suite(Config) -> application:ensure_all_started(rclref), Names = [node1, node2, node3, node4], Ports = [50100, 50110, 50120, 50130], Nodes = node_utils:set_up_nodes(Names, Ports, [{module, ?MODULE}]), [{module, ?MODULE}, {names, Names}, {nodes, Nodes}, {ports, Ports} | Config]. end_per_suite(Config) -> Nodes = ?config(nodes, Config), node_utils:kill_nodes(Nodes), Config. brutal_kill_nodes_test(Config) -> Nodes = ?config(nodes, Config), KilledNodes = node_utils:brutal_kill_nodes(Nodes), [pang = net_adm:ping(Node) || Node <- KilledNodes], ok.
2eaaaa5376b762926f0b96352f91287f6c036fbe6e1ca9a70a4eb7c545d11200
kblake/erlang-chat-demo
element_google_chart.erl
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (element_google_chart). -compile(export_all). -include_lib ("wf.hrl"). -include_lib ("google_chart.hrl"). reflect() -> record_info(fields, google_chart). render_element(Record) -> % Path... Path = "?", % Chart Type... Type = [ "&cht=", case Record#google_chart.type of line -> "lc"; sparkline -> "ls"; stacked_horizontal_bar -> "bhs"; stacked_vertical_bar -> "bvs"; grouped_horizontal_bar -> "bhg"; grouped_vertical_bar -> "bvg"; pie -> "p"; pie3d -> "p3"; OtherType -> erlang:error({unknown_chart_type, OtherType}) end ], % Title... Title = case Record#google_chart.title of undefined -> []; [] -> []; OtherTitle -> ["&chtt=", wf:url_encode(OtherTitle)] end, % Title Color and Font Size... TitleStyle = wf:f("&chts=~s,~b", [wf:to_list(Record#google_chart.color), Record#google_chart.font_size]), % Size... Size = wf:f("&chs=~bx~b", [Record#google_chart.width, Record#google_chart.height]), % Grid... Grid = wf:f("&chg=~s,~s,~b,~b", [ wf:to_list(wf:coalesce([Record#google_chart.grid_x, 0])), wf:to_list(wf:coalesce([Record#google_chart.grid_y, 0])), Record#google_chart.grid_line_length, Record#google_chart.grid_blank_length ]), % Background Colors... BGColors = wf:f("&chf=bg,s,~s|c,s,~s", [ wf:to_list(Record#google_chart.background_color), wf:to_list(Record#google_chart.chart_color) ]), % Legend Location... LegendLocation = "&chdlp=" ++ case Record#google_chart.legend_location of top -> "t"; left -> "l"; bottom -> "b"; right -> "r" end, % Axes... Axes = case Record#google_chart.axes of undefined -> []; [] -> []; AxesRecords -> ProcessedAxes = [process_axis(N - 1, lists:nth(N, AxesRecords)) || N <- lists:seq(1, length(AxesRecords))], AxesPositions = "&chxt=" ++ string:join([X || [X, _, _] <- ProcessedAxes], ","), AxesLabels = "&chxl=" ++ string:join([X || [_, X, _] <- ProcessedAxes], "|"), AxesColors = "&chxs=" ++ string:join([X || [_, _, X] <- ProcessedAxes], "|"), AxesPositions ++ AxesLabels ++ AxesColors end, % Data... Data = case Record#google_chart.data of undefined -> MaxValueLength=0, []; [] -> MaxValueLength=0, []; DataRecords -> ProcessedData = [process_data(N -1, lists:nth(N, DataRecords)) || N <- lists:seq(1, length(DataRecords))], DataColors = "&chco=" ++ string:join([X || [X, _, _, _, _, _] <- ProcessedData], ","), DataLegends = "&chdl=" ++ string:join([X || [_, X, _, _, _, _] <- ProcessedData], "|"), DataScales = "&chds=" ++ string:join([X || [_, _, X, _, _, _] <- ProcessedData], ","), DataStyles = "&chls=" ++ string:join([X || [_, _, _, X, _, _] <- ProcessedData], "|"), DataValues = "&chd=t:" ++ string:join([X || [_, _, _, _, X, _] <- ProcessedData], "|"), MaxValueLength = lists:max([X || [_, _, _, _, _, X] <- ProcessedData]), DataLegends1 = case string:strip(DataLegends, both, $|) of "&chdl=" -> []; _ -> DataLegends end, DataColors ++ DataLegends1 ++ DataScales ++ DataValues ++ DataStyles end, % Calculate bar size... BarSize = case MaxValueLength of 0 -> []; _ -> DataGroupsLength = length(Record#google_chart.data), BarGroupSpace = Record#google_chart.bar_group_space, BarSpace = Record#google_chart.bar_space, GroupSpacerPixels = MaxValueLength * BarGroupSpace, BarSpacerPixels = MaxValueLength * (DataGroupsLength * BarSpace), AvailablePixels = case Record#google_chart.type of stacked_horizontal_bar -> Record#google_chart.height; grouped_horizontal_bar -> Record#google_chart.height; stacked_vertical_bar -> Record#google_chart.width; grouped_vertical_bar -> Record#google_chart.width; _ -> 0 end, IndividualBarSize = (AvailablePixels - GroupSpacerPixels - BarSpacerPixels) / (DataGroupsLength * MaxValueLength), wf:f("&chbh=~b,~b,~b", [trunc(IndividualBarSize), BarSpace, BarGroupSpace]) end, % Render the image tag... Image = #image { id=Record#google_chart.id, anchor=Record#google_chart.anchor, class=[google_chart, Record#google_chart.class], style = Record#google_chart.style, image = lists:flatten([Path, Type, Title, TitleStyle, Size, Grid, BGColors, LegendLocation, BarSize, Axes, Data]) }, element_image:render_element(Image). process_axis(N, Axis) -> Position = case Axis#chart_axis.position of top -> "t"; right -> "r"; bottom -> "x"; left -> "y"; OtherPosition -> erlang:error({unknown_axis_position, OtherPosition}) end, StringLabels = [wf:to_list(X) || X <- Axis#chart_axis.labels], Labels = integer_to_list(N) ++ ":|" ++ string:join(StringLabels, "|"), Style = wf:f("~b,~s,~b", [N, wf:to_list(Axis#chart_axis.color), Axis#chart_axis.font_size]), [Position, Labels, Style]. process_data(_N, Data) -> Color = wf:to_list(Data#chart_data.color), Legend = wf:to_list(Data#chart_data.legend), Scale = wf:f("~b,~b", [Data#chart_data.min_value, Data#chart_data.max_value]), StringValues = [wf:to_list(X) || X <- Data#chart_data.values], Values = string:join(StringValues, ","), Styles = wf:f("~b,~b,~b", [Data#chart_data.line_width, Data#chart_data.line_length, Data#chart_data.blank_length]), [Color, Legend, Scale, Styles, Values, length(StringValues)].
null
https://raw.githubusercontent.com/kblake/erlang-chat-demo/6fd2fce12f2e059e25a24c9a84169b088710edaf/apps/nitrogen/src/elements/other/element_google_chart.erl
erlang
Path... Chart Type... Title... Title Color and Font Size... Size... Grid... Background Colors... Legend Location... Axes... Data... Calculate bar size... Render the image tag...
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (element_google_chart). -compile(export_all). -include_lib ("wf.hrl"). -include_lib ("google_chart.hrl"). reflect() -> record_info(fields, google_chart). render_element(Record) -> Path = "?", Type = [ "&cht=", case Record#google_chart.type of line -> "lc"; sparkline -> "ls"; stacked_horizontal_bar -> "bhs"; stacked_vertical_bar -> "bvs"; grouped_horizontal_bar -> "bhg"; grouped_vertical_bar -> "bvg"; pie -> "p"; pie3d -> "p3"; OtherType -> erlang:error({unknown_chart_type, OtherType}) end ], Title = case Record#google_chart.title of undefined -> []; [] -> []; OtherTitle -> ["&chtt=", wf:url_encode(OtherTitle)] end, TitleStyle = wf:f("&chts=~s,~b", [wf:to_list(Record#google_chart.color), Record#google_chart.font_size]), Size = wf:f("&chs=~bx~b", [Record#google_chart.width, Record#google_chart.height]), Grid = wf:f("&chg=~s,~s,~b,~b", [ wf:to_list(wf:coalesce([Record#google_chart.grid_x, 0])), wf:to_list(wf:coalesce([Record#google_chart.grid_y, 0])), Record#google_chart.grid_line_length, Record#google_chart.grid_blank_length ]), BGColors = wf:f("&chf=bg,s,~s|c,s,~s", [ wf:to_list(Record#google_chart.background_color), wf:to_list(Record#google_chart.chart_color) ]), LegendLocation = "&chdlp=" ++ case Record#google_chart.legend_location of top -> "t"; left -> "l"; bottom -> "b"; right -> "r" end, Axes = case Record#google_chart.axes of undefined -> []; [] -> []; AxesRecords -> ProcessedAxes = [process_axis(N - 1, lists:nth(N, AxesRecords)) || N <- lists:seq(1, length(AxesRecords))], AxesPositions = "&chxt=" ++ string:join([X || [X, _, _] <- ProcessedAxes], ","), AxesLabels = "&chxl=" ++ string:join([X || [_, X, _] <- ProcessedAxes], "|"), AxesColors = "&chxs=" ++ string:join([X || [_, _, X] <- ProcessedAxes], "|"), AxesPositions ++ AxesLabels ++ AxesColors end, Data = case Record#google_chart.data of undefined -> MaxValueLength=0, []; [] -> MaxValueLength=0, []; DataRecords -> ProcessedData = [process_data(N -1, lists:nth(N, DataRecords)) || N <- lists:seq(1, length(DataRecords))], DataColors = "&chco=" ++ string:join([X || [X, _, _, _, _, _] <- ProcessedData], ","), DataLegends = "&chdl=" ++ string:join([X || [_, X, _, _, _, _] <- ProcessedData], "|"), DataScales = "&chds=" ++ string:join([X || [_, _, X, _, _, _] <- ProcessedData], ","), DataStyles = "&chls=" ++ string:join([X || [_, _, _, X, _, _] <- ProcessedData], "|"), DataValues = "&chd=t:" ++ string:join([X || [_, _, _, _, X, _] <- ProcessedData], "|"), MaxValueLength = lists:max([X || [_, _, _, _, _, X] <- ProcessedData]), DataLegends1 = case string:strip(DataLegends, both, $|) of "&chdl=" -> []; _ -> DataLegends end, DataColors ++ DataLegends1 ++ DataScales ++ DataValues ++ DataStyles end, BarSize = case MaxValueLength of 0 -> []; _ -> DataGroupsLength = length(Record#google_chart.data), BarGroupSpace = Record#google_chart.bar_group_space, BarSpace = Record#google_chart.bar_space, GroupSpacerPixels = MaxValueLength * BarGroupSpace, BarSpacerPixels = MaxValueLength * (DataGroupsLength * BarSpace), AvailablePixels = case Record#google_chart.type of stacked_horizontal_bar -> Record#google_chart.height; grouped_horizontal_bar -> Record#google_chart.height; stacked_vertical_bar -> Record#google_chart.width; grouped_vertical_bar -> Record#google_chart.width; _ -> 0 end, IndividualBarSize = (AvailablePixels - GroupSpacerPixels - BarSpacerPixels) / (DataGroupsLength * MaxValueLength), wf:f("&chbh=~b,~b,~b", [trunc(IndividualBarSize), BarSpace, BarGroupSpace]) end, Image = #image { id=Record#google_chart.id, anchor=Record#google_chart.anchor, class=[google_chart, Record#google_chart.class], style = Record#google_chart.style, image = lists:flatten([Path, Type, Title, TitleStyle, Size, Grid, BGColors, LegendLocation, BarSize, Axes, Data]) }, element_image:render_element(Image). process_axis(N, Axis) -> Position = case Axis#chart_axis.position of top -> "t"; right -> "r"; bottom -> "x"; left -> "y"; OtherPosition -> erlang:error({unknown_axis_position, OtherPosition}) end, StringLabels = [wf:to_list(X) || X <- Axis#chart_axis.labels], Labels = integer_to_list(N) ++ ":|" ++ string:join(StringLabels, "|"), Style = wf:f("~b,~s,~b", [N, wf:to_list(Axis#chart_axis.color), Axis#chart_axis.font_size]), [Position, Labels, Style]. process_data(_N, Data) -> Color = wf:to_list(Data#chart_data.color), Legend = wf:to_list(Data#chart_data.legend), Scale = wf:f("~b,~b", [Data#chart_data.min_value, Data#chart_data.max_value]), StringValues = [wf:to_list(X) || X <- Data#chart_data.values], Values = string:join(StringValues, ","), Styles = wf:f("~b,~b,~b", [Data#chart_data.line_width, Data#chart_data.line_length, Data#chart_data.blank_length]), [Color, Legend, Scale, Styles, Values, length(StringValues)].
099cd306f0f8cbb7a1d1986fac8fd3ffade47ed53c27fc362d2df9cae695ab6e
danfran/cabal-macosx
AppBuildInfo.hs
-- | Information used to help create an application bundle module Distribution.MacOSX.AppBuildInfo where import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..)) import System.FilePath import Distribution.MacOSX.Common -- | Information needed to build a bundle -- -- This exists to make it possible to have a standalone - app executable without it necessarily having to know a lot of Cabal internals data AppBuildInfo = AppBuildInfo { -- | Location of the application bundle being built abAppPath :: FilePath -- | Location of the original executable that was built , abAppOrigExe :: FilePath -- | , abApp :: MacApp } -- | @toAppBuildInfo l m@ returns information for an application bundle within the @l@ build directory toAppBuildInfo :: LocalBuildInfo -> MacApp -> AppBuildInfo toAppBuildInfo localb app = createAppBuildInfo (buildDir localb) app -- | @createAppBuildInfo d m@ returns information for an application bundle within the @d@ build directory from LocalBuildInfo createAppBuildInfo :: FilePath -> MacApp -> AppBuildInfo createAppBuildInfo buildDirLocalBuildInfo app = AppBuildInfo { abAppPath = buildDirLocalBuildInfo </> appName app <.> "app" , abAppOrigExe = buildDirLocalBuildInfo </> appName app </> appName app , abApp = app }
null
https://raw.githubusercontent.com/danfran/cabal-macosx/6714a7018ddcd71efd96044bd55c0e19fb690939/Distribution/MacOSX/AppBuildInfo.hs
haskell
| Information used to help create an application bundle | Information needed to build a bundle This exists to make it possible to have a standalone | Location of the application bundle being built | Location of the original executable that was built | | @toAppBuildInfo l m@ returns information for an application bundle | @createAppBuildInfo d m@ returns information for an application bundle
module Distribution.MacOSX.AppBuildInfo where import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..)) import System.FilePath import Distribution.MacOSX.Common - app executable without it necessarily having to know a lot of Cabal internals data AppBuildInfo = AppBuildInfo abAppPath :: FilePath , abAppOrigExe :: FilePath , abApp :: MacApp } within the @l@ build directory toAppBuildInfo :: LocalBuildInfo -> MacApp -> AppBuildInfo toAppBuildInfo localb app = createAppBuildInfo (buildDir localb) app within the @d@ build directory from LocalBuildInfo createAppBuildInfo :: FilePath -> MacApp -> AppBuildInfo createAppBuildInfo buildDirLocalBuildInfo app = AppBuildInfo { abAppPath = buildDirLocalBuildInfo </> appName app <.> "app" , abAppOrigExe = buildDirLocalBuildInfo </> appName app </> appName app , abApp = app }
053883b9f8c3d853348bd01a967ebde7da2e7caadd647f4fd73b585f7349be1d
linuxscout/festival-tts-arabic-voices
ara_norm_ziad_hts.scm
;; ---------------------------------------------------------------- ;; Nagoya Institute of Technology and ; ; Carnegie Mellon University ; ; Copyright ( c ) 2002 ; ; All Rights Reserved . ; ; ;; ;; ;; Permission is hereby granted, free of charge, to use and ;; ;; distribute this software and its documentation without ;; ;; restriction, including without limitation the rights to use, ;; ;; copy, modify, merge, publish, distribute, sublicense, and/or ;; ;; sell copies of this work, and to permit persons to whom this ;; ;; work is furnished to do so, subject to the following conditions: ;; ;; ;; 1 . The code must retain the above copyright notice , this list ; ; ;; of conditions and the following disclaimer. ;; ;; ;; 2 . Any modifications must be clearly marked as such . ; ; ;; ;; 3 . Original authors ' names are not deleted . ; ; ;; ;; 4 . The authors ' names are not used to endorse or promote ; ; ;; products derived from this software without specific prior ;; ;; written permission. ;; ;; ;; NAGOYA INSTITUTE OF TECHNOLOGY , CARNEGIE MELLON UNIVERSITY AND ; ; ;; THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH ;; ;; REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;; MERCHANTABILITY AND FITNESS , IN NO EVENT SHALL NAGOYA INSTITUTE ; ; OF TECHNOLOGY , CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS ; ; ;; BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ;; ;; ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR ;; PROFITS , 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. ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; A voice based on " HTS " HMM - Based Speech Synthesis System . ; ; Author : ; ; Date : August 2002 ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Try to find the directory where the voice is, this may be from ;;; .../festival/lib/voices/ or from the current directory (if (assoc 'ara_norm_ziad_hts voice-locations) (defvar ara_norm_ziad_hts::hts_dir (cdr (assoc 'ara_norm_ziad_hts voice-locations))) (defvar ara_norm_ziad_hts::hts_dir (string-append (pwd) "/"))) (defvar ara_norm_ziad::clunits_dir ara_norm_ziad_hts::hts_dir) (defvar ara_norm_ziad::clunits_loaded nil) ;;; Did we succeed in finding it (if (not (probe_file (path-append ara_norm_ziad_hts::hts_dir "festvox/"))) (begin (format stderr "ara_norm_ziad_hts::hts: Can't find voice scm files they are not in\n") (format stderr " %s\n" (path-append ara_norm_ziad_hts::hts_dir "festvox/")) (format stderr " Either the voice isn't linked in Festival library\n") (format stderr " or you are starting festival in the wrong directory\n") (error))) ;;; Add the directory contains general voice stuff to load-path (set! load-path (cons (path-append ara_norm_ziad_hts::hts_dir "festvox/") load-path)) (set! hts_data_dir (path-append ara_norm_ziad_hts::hts_dir "hts/")) (set! hts_feats_list (load (path-append hts_data_dir "feat.list") t)) (require 'hts) (require_module 'hts_engine) ;;; Voice specific parameter are defined in each of the following ;;; files (require 'ara_norm_ziad_phoneset) (require 'ara_norm_ziad_tokenizer) (require 'ara_norm_ziad_tagger) (require 'ara_norm_ziad_lexicon) (require 'ara_norm_ziad_phrasing) (require 'ara_norm_ziad_intonation) (require 'ara_norm_ziad_duration) (require 'ara_norm_ziad_f0model) (require 'ara_norm_ziad_other) ;; ... and others as required (define (ara_norm_ziad_hts::voice_reset) "(ara_norm_ziad_hts::voice_reset) Reset global variables back to previous voice." (ara_norm_ziad::reset_phoneset) (ara_norm_ziad::reset_tokenizer) (ara_norm_ziad::reset_tagger) (ara_norm_ziad::reset_lexicon) (ara_norm_ziad::reset_phrasing) (ara_norm_ziad::reset_intonation) (ara_norm_ziad::reset_duration) (ara_norm_ziad::reset_f0model) (ara_norm_ziad::reset_other) t ) (set! ara_norm_ziad_hts::hts_feats_list (load (path-append hts_data_dir "feat.list") t)) (set! ara_norm_ziad_hts::hts_engine_params (list (list "-m" (path-append hts_data_dir "ara_norm_ziad_hts.htsvoice")) '("-g" 0.0) '("-b" 0.0) '("-u" 0.5) )) ;; This function is called to setup a voice. It will typically ;; simply call functions that are defined in other files in this directory ;; Sometime these simply set up standard Festival modules othertimes ;; these will be specific to this voice. ;; Feel free to add to this list if your language requires it (define (voice_ara_norm_ziad_hts) "(voice_ara_norm_ziad_hts) Define voice for limited domain: ar." ;; *always* required (voice_reset) ;; Select appropriate phone set (ara_norm_ziad::select_phoneset) ;; Select appropriate tokenization (ara_norm_ziad::select_tokenizer) ;; For part of speech tagging (ara_norm_ziad::select_tagger) (ara_norm_ziad::select_lexicon) ;; For hts selection you probably don't want vowel reduction ;; the unit selection will do that (if (string-equal "arabic" (Param.get 'Language)) (set! postlex_vowel_reduce_cart_tree nil)) (ara_norm_ziad::select_phrasing) (ara_norm_ziad::select_intonation) (ara_norm_ziad::select_duration) (ara_norm_ziad::select_f0model) ;; Waveform synthesis model: hts (set! hts_engine_params ara_norm_ziad_hts::hts_engine_params) (set! hts_feats_list ara_norm_ziad_hts::hts_feats_list) (Parameter.set 'Synth_Method 'HTS) ;; This is where you can modify power (and sampling rate) if desired (set! after_synth_hooks nil) ; (set! after_synth_hooks ; (list ; (lambda (utt) ; (utt.wave.rescale utt 2.1)))) (set! current_voice_reset ara_norm_ziad_hts::voice_reset) (set! current-voice 'ara_norm_ziad_hts) ) (proclaim_voice 'ara_norm_ziad_hts '((language arabic) (gender male) (dialect nil) (description "This voice provides an Arabic male voice using HTS."))) (provide 'ara_norm_ziad_hts)
null
https://raw.githubusercontent.com/linuxscout/festival-tts-arabic-voices/5f2210698f5a40adf88516f25ddb1b01e8054f5a/voices/ara_norm_ziad_hts/festvox/ara_norm_ziad_hts.scm
scheme
---------------------------------------------------------------- ;; ; ; ; ; ;; Permission is hereby granted, free of charge, to use and ;; distribute this software and its documentation without ;; restriction, including without limitation the rights to use, ;; copy, modify, merge, publish, distribute, sublicense, and/or ;; sell copies of this work, and to permit persons to whom this ;; work is furnished to do so, subject to the following conditions: ;; ;; ; of conditions and the following disclaimer. ;; ;; ; ;; ; ;; ; products derived from this software without specific prior ;; written permission. ;; ;; ; THE CONTRIBUTORS TO THIS WORK DISCLAIM ALL WARRANTIES WITH ;; REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;; ; ; BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ;; ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR ;; ; ; PERFORMANCE OF THIS SOFTWARE. ;; ;; ; ; ; Try to find the directory where the voice is, this may be from .../festival/lib/voices/ or from the current directory Did we succeed in finding it Add the directory contains general voice stuff to load-path Voice specific parameter are defined in each of the following files ... and others as required This function is called to setup a voice. It will typically simply call functions that are defined in other files in this directory Sometime these simply set up standard Festival modules othertimes these will be specific to this voice. Feel free to add to this list if your language requires it *always* required Select appropriate phone set Select appropriate tokenization For part of speech tagging For hts selection you probably don't want vowel reduction the unit selection will do that Waveform synthesis model: hts This is where you can modify power (and sampling rate) if desired (set! after_synth_hooks (list (lambda (utt) (utt.wave.rescale utt 2.1))))
(if (assoc 'ara_norm_ziad_hts voice-locations) (defvar ara_norm_ziad_hts::hts_dir (cdr (assoc 'ara_norm_ziad_hts voice-locations))) (defvar ara_norm_ziad_hts::hts_dir (string-append (pwd) "/"))) (defvar ara_norm_ziad::clunits_dir ara_norm_ziad_hts::hts_dir) (defvar ara_norm_ziad::clunits_loaded nil) (if (not (probe_file (path-append ara_norm_ziad_hts::hts_dir "festvox/"))) (begin (format stderr "ara_norm_ziad_hts::hts: Can't find voice scm files they are not in\n") (format stderr " %s\n" (path-append ara_norm_ziad_hts::hts_dir "festvox/")) (format stderr " Either the voice isn't linked in Festival library\n") (format stderr " or you are starting festival in the wrong directory\n") (error))) (set! load-path (cons (path-append ara_norm_ziad_hts::hts_dir "festvox/") load-path)) (set! hts_data_dir (path-append ara_norm_ziad_hts::hts_dir "hts/")) (set! hts_feats_list (load (path-append hts_data_dir "feat.list") t)) (require 'hts) (require_module 'hts_engine) (require 'ara_norm_ziad_phoneset) (require 'ara_norm_ziad_tokenizer) (require 'ara_norm_ziad_tagger) (require 'ara_norm_ziad_lexicon) (require 'ara_norm_ziad_phrasing) (require 'ara_norm_ziad_intonation) (require 'ara_norm_ziad_duration) (require 'ara_norm_ziad_f0model) (require 'ara_norm_ziad_other) (define (ara_norm_ziad_hts::voice_reset) "(ara_norm_ziad_hts::voice_reset) Reset global variables back to previous voice." (ara_norm_ziad::reset_phoneset) (ara_norm_ziad::reset_tokenizer) (ara_norm_ziad::reset_tagger) (ara_norm_ziad::reset_lexicon) (ara_norm_ziad::reset_phrasing) (ara_norm_ziad::reset_intonation) (ara_norm_ziad::reset_duration) (ara_norm_ziad::reset_f0model) (ara_norm_ziad::reset_other) t ) (set! ara_norm_ziad_hts::hts_feats_list (load (path-append hts_data_dir "feat.list") t)) (set! ara_norm_ziad_hts::hts_engine_params (list (list "-m" (path-append hts_data_dir "ara_norm_ziad_hts.htsvoice")) '("-g" 0.0) '("-b" 0.0) '("-u" 0.5) )) (define (voice_ara_norm_ziad_hts) "(voice_ara_norm_ziad_hts) Define voice for limited domain: ar." (voice_reset) (ara_norm_ziad::select_phoneset) (ara_norm_ziad::select_tokenizer) (ara_norm_ziad::select_tagger) (ara_norm_ziad::select_lexicon) (if (string-equal "arabic" (Param.get 'Language)) (set! postlex_vowel_reduce_cart_tree nil)) (ara_norm_ziad::select_phrasing) (ara_norm_ziad::select_intonation) (ara_norm_ziad::select_duration) (ara_norm_ziad::select_f0model) (set! hts_engine_params ara_norm_ziad_hts::hts_engine_params) (set! hts_feats_list ara_norm_ziad_hts::hts_feats_list) (Parameter.set 'Synth_Method 'HTS) (set! after_synth_hooks nil) (set! current_voice_reset ara_norm_ziad_hts::voice_reset) (set! current-voice 'ara_norm_ziad_hts) ) (proclaim_voice 'ara_norm_ziad_hts '((language arabic) (gender male) (dialect nil) (description "This voice provides an Arabic male voice using HTS."))) (provide 'ara_norm_ziad_hts)
e4b6e3a89b696dfb71b125a869ef572987e31763b3efbf2bc4f6e385fc851cc7
lisp-korea/sicp
ex-1-2-lkbwww.scm
1.2.1 recursion, iteration process (define (factorial number) (define (fact-iter product counter) (if (> counter number) product (fact-iter (* product counter) (+ counter 1)))) (fact-iter 1 1)) Exercise 1.9 (define (inc x) (+ x 1)) (define (dec x) (- x 1)) (define (+ a b) (if (= a 0) b (inc (+ (dec a) b)))) (define (+ a b) (if (= a 0) b (+ (dec a) (inc b)))) ((defn A [x y] (cond (= y 0) 0 (= x 0) (* 2 y) (= y 1) 2 true (A (- x 1) (A x (- y 1))))) (A 1 10) => (A 0 (A 1 9)) => (A 0 (A 0 (A 1 8))) è (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))) => (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 2)))))))))) => 1024 (A 2 4) => 65536 (A 3 3) => (65536) (define (f n) (A 0 n)) => (* 2 n) (defn (g n) (A 1 n)) => n의 제곱 (defn (h n) (A 2 n)) => n의 (A 2 (- n 1))승 (define (f n) (if (< n 3) n (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) Iteration (define (f n) (define (f-iter a b c cnt) (if (= cnt n) a (f-iter (+ a (* 2 b) (* 3 c)) a b (+ cnt 1)))) (if (< n 3) n (f-iter 4 2 1 3))) 1.12 (define (p a b) (cond ((= a b) 1) ((= b 1) 1) ((= a 2) 1) ((> b a) 0) (else (+ (p (- a 1) (- b 1)) (p (- a 1) b))))) (defn pascal-triangle [n] (defn make-new-line [pre-line new-line cnt] (let [max-count (count pre-line)] (if (= (+ cnt 1) max-count) (conj new-line 1) (make-new-line pre-line (conj new-line (+ (get pre-line cnt) (get pre-line (+ cnt 1)))) (+ cnt 1))))) (defn pascal-iter [pre-line count] (if (< count n) (do (prn pre-line) (pascal-iter (make-new-line pre-line [1] 0) (+ count 1))) (prn pre-line))) (cond (= n 1) (prn (vector 1)) (= n 2) (do (prn (vector 1)) (prn (vector 1 1))) true (do (prn (vector 1)) (pascal-iter (vector 1 1) 2)))) 1.13~1.16 수학적문제 1.16 ;;; recursion (define (fast-expt b n) (cond ((= n 1) 1) ((even? n) (squqre (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) ;;; iteration (define (fast-expt-iter b n) (define (fast-expt-iter-part b m c) (cond ((= c 0) m) ((even? c) (fast-expt-iter-part (* b b) m (/ c 2))) (else (fast-expt-iter-part b (* b m) (- c 1))))) (fast-expt-iter-part b 1 n)) 1.18 (define (double a) (+ a a)) (define (halve a) (/ a 2)) (define (fast-* a b) (if (even? b) (fast-* (double a) (halve b)) (+ (fast-* a (- b 1)) a))) (defn fast-* [a b] (defn doub [x] (+ x x)) (defn f-iter-even [before cnt] (if (<= b cnt) before (f-iter-even (+ before (doub a)) (+ cnt 2)))) (defn f-iter-odd [] (+ a (f-iter-even 0 1))) (cond (= a 0) 0 (= b 0) 0 (even? b) (f-iter-even 0 0) true (f-iter-odd))) 1.19 덧셈 (defn fast-+ [a b] (defn f-iter-even [before cnt] (if (<= b cnt) before (f-iter-even (+ before 2) (+ cnt 2)))) (defn f-iter-odd [] (+ a (f-iter-even a 1))) (cond (= a 0) b (= b 0) a (= b 1) (+ a 1) (even? b) (f-iter-even a 0) true (f-iter-odd))) 두배 값
null
https://raw.githubusercontent.com/lisp-korea/sicp/4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc/ch01/1.2/ex-1-2-lkbwww.scm
scheme
recursion iteration
1.2.1 recursion, iteration process (define (factorial number) (define (fact-iter product counter) (if (> counter number) product (fact-iter (* product counter) (+ counter 1)))) (fact-iter 1 1)) Exercise 1.9 (define (inc x) (+ x 1)) (define (dec x) (- x 1)) (define (+ a b) (if (= a 0) b (inc (+ (dec a) b)))) (define (+ a b) (if (= a 0) b (+ (dec a) (inc b)))) ((defn A [x y] (cond (= y 0) 0 (= x 0) (* 2 y) (= y 1) 2 true (A (- x 1) (A x (- y 1))))) (A 1 10) => (A 0 (A 1 9)) => (A 0 (A 0 (A 1 8))) è (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 0 (A 1 1)))))))))) => (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 (* 2 2)))))))))) => 1024 (A 2 4) => 65536 (A 3 3) => (65536) (define (f n) (A 0 n)) => (* 2 n) (defn (g n) (A 1 n)) => n의 제곱 (defn (h n) (A 2 n)) => n의 (A 2 (- n 1))승 (define (f n) (if (< n 3) n (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) Iteration (define (f n) (define (f-iter a b c cnt) (if (= cnt n) a (f-iter (+ a (* 2 b) (* 3 c)) a b (+ cnt 1)))) (if (< n 3) n (f-iter 4 2 1 3))) 1.12 (define (p a b) (cond ((= a b) 1) ((= b 1) 1) ((= a 2) 1) ((> b a) 0) (else (+ (p (- a 1) (- b 1)) (p (- a 1) b))))) (defn pascal-triangle [n] (defn make-new-line [pre-line new-line cnt] (let [max-count (count pre-line)] (if (= (+ cnt 1) max-count) (conj new-line 1) (make-new-line pre-line (conj new-line (+ (get pre-line cnt) (get pre-line (+ cnt 1)))) (+ cnt 1))))) (defn pascal-iter [pre-line count] (if (< count n) (do (prn pre-line) (pascal-iter (make-new-line pre-line [1] 0) (+ count 1))) (prn pre-line))) (cond (= n 1) (prn (vector 1)) (= n 2) (do (prn (vector 1)) (prn (vector 1 1))) true (do (prn (vector 1)) (pascal-iter (vector 1 1) 2)))) 1.13~1.16 수학적문제 1.16 (define (fast-expt b n) (cond ((= n 1) 1) ((even? n) (squqre (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) (define (fast-expt-iter b n) (define (fast-expt-iter-part b m c) (cond ((= c 0) m) ((even? c) (fast-expt-iter-part (* b b) m (/ c 2))) (else (fast-expt-iter-part b (* b m) (- c 1))))) (fast-expt-iter-part b 1 n)) 1.18 (define (double a) (+ a a)) (define (halve a) (/ a 2)) (define (fast-* a b) (if (even? b) (fast-* (double a) (halve b)) (+ (fast-* a (- b 1)) a))) (defn fast-* [a b] (defn doub [x] (+ x x)) (defn f-iter-even [before cnt] (if (<= b cnt) before (f-iter-even (+ before (doub a)) (+ cnt 2)))) (defn f-iter-odd [] (+ a (f-iter-even 0 1))) (cond (= a 0) 0 (= b 0) 0 (even? b) (f-iter-even 0 0) true (f-iter-odd))) 1.19 덧셈 (defn fast-+ [a b] (defn f-iter-even [before cnt] (if (<= b cnt) before (f-iter-even (+ before 2) (+ cnt 2)))) (defn f-iter-odd [] (+ a (f-iter-even a 1))) (cond (= a 0) b (= b 0) a (= b 1) (+ a 1) (even? b) (f-iter-even a 0) true (f-iter-odd))) 두배 값
a5454dc661c4408119bccc022bd8f56623bebb89bf5a3c6339346e5a0aaaabca
ocaml-omake/omake
omake_shell_lex.mli
(* * Lex a shell line. *) open Lm_glob open Omake_shell_type open Omake_command_type open! Omake_value_type (* * Commands with a leading \ are quoted. *) val parse_command_string : string -> simple_exe (* * Construct the pipe from the value. *) val pipe_of_value : Omake_env.t -> (Omake_env.t -> pos -> Lm_location.t -> string -> (Lm_symbol.t * Omake_env.apply) option) -> glob_options -> pos -> Lm_location.t -> Omake_value_type.t -> command_flag list * Omake_env.arg_pipe
null
https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/shell/omake_shell_lex.mli
ocaml
* Lex a shell line. * Commands with a leading \ are quoted. * Construct the pipe from the value.
open Lm_glob open Omake_shell_type open Omake_command_type open! Omake_value_type val parse_command_string : string -> simple_exe val pipe_of_value : Omake_env.t -> (Omake_env.t -> pos -> Lm_location.t -> string -> (Lm_symbol.t * Omake_env.apply) option) -> glob_options -> pos -> Lm_location.t -> Omake_value_type.t -> command_flag list * Omake_env.arg_pipe
1137da107568817d6dc964a35575d58f4c37a5e3090530ea2e04b24962926e85
tsloughter/kuberl
kuberl_v1beta1_replica_set_status.erl
-module(kuberl_v1beta1_replica_set_status). -export([encode/1]). -export_type([kuberl_v1beta1_replica_set_status/0]). -type kuberl_v1beta1_replica_set_status() :: #{ 'availableReplicas' => integer(), 'conditions' => list(), 'fullyLabeledReplicas' => integer(), 'observedGeneration' => integer(), 'readyReplicas' => integer(), 'replicas' := integer() }. encode(#{ 'availableReplicas' := AvailableReplicas, 'conditions' := Conditions, 'fullyLabeledReplicas' := FullyLabeledReplicas, 'observedGeneration' := ObservedGeneration, 'readyReplicas' := ReadyReplicas, 'replicas' := Replicas }) -> #{ 'availableReplicas' => AvailableReplicas, 'conditions' => Conditions, 'fullyLabeledReplicas' => FullyLabeledReplicas, 'observedGeneration' => ObservedGeneration, 'readyReplicas' => ReadyReplicas, 'replicas' => Replicas }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_replica_set_status.erl
erlang
-module(kuberl_v1beta1_replica_set_status). -export([encode/1]). -export_type([kuberl_v1beta1_replica_set_status/0]). -type kuberl_v1beta1_replica_set_status() :: #{ 'availableReplicas' => integer(), 'conditions' => list(), 'fullyLabeledReplicas' => integer(), 'observedGeneration' => integer(), 'readyReplicas' => integer(), 'replicas' := integer() }. encode(#{ 'availableReplicas' := AvailableReplicas, 'conditions' := Conditions, 'fullyLabeledReplicas' := FullyLabeledReplicas, 'observedGeneration' := ObservedGeneration, 'readyReplicas' := ReadyReplicas, 'replicas' := Replicas }) -> #{ 'availableReplicas' => AvailableReplicas, 'conditions' => Conditions, 'fullyLabeledReplicas' => FullyLabeledReplicas, 'observedGeneration' => ObservedGeneration, 'readyReplicas' => ReadyReplicas, 'replicas' => Replicas }.
af58da0dbc2f1a89ddb1e740d07de2832ed9aaa9e93e389738ea9be991f7ddbe
turion/rhine
Terminal.hs
| Wrapper to write @terminal@ applications in Rhine , using concurrency . -} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE RecordWildCards # module FRP.Rhine.Terminal ( TerminalEventClock (..) , flowTerminal , terminalConcurrently ) where -- base import Prelude hiding (putChar) import Unsafe.Coerce (unsafeCoerce) -- exceptions import Control.Monad.Catch (MonadMask) -- time import Data.Time.Clock ( getCurrentTime ) -- terminal import System.Terminal ( awaitEvent, runTerminalT, Event, Interrupt, TerminalT, MonadInput ) import System.Terminal.Internal ( Terminal ) -- transformers import Control.Monad.Trans.Reader import Control.Monad.Trans.Class (lift) -- rhine import FRP.Rhine -- | A clock that ticks whenever events or interrupts on the terminal arrive. data TerminalEventClock = TerminalEventClock instance (MonadInput m, MonadIO m) => Clock m TerminalEventClock where type Time TerminalEventClock = UTCTime type Tag TerminalEventClock = Either Interrupt Event initClock TerminalEventClock = do initialTime <- liftIO getCurrentTime return ( constM $ do event <- awaitEvent time <- liftIO getCurrentTime return (time, event) , initialTime ) instance GetClockProxy TerminalEventClock instance Semigroup TerminalEventClock where t <> _ = t -- | A function wrapping `flow` to use at the top level -- in order to run a `Rhine (TerminalT t m) cl ()` -- -- Example: -- -- @ mainRhine : : MonadIO m = > Rhine ( TerminalT LocalTerminal m ) TerminalEventClock ( ) ( ) -- mainRhine = tagS >-> arrMCl (liftIO . print) @@ TerminalEventClock -- -- main :: IO () -- main = withTerminal $ \term -> `flowTerminal` term mainRhine -- @ flowTerminal :: ( MonadIO m , MonadMask m , Terminal t , Clock (TerminalT t m) cl , GetClockProxy cl , Time cl ~ Time (In cl) , Time cl ~ Time (Out cl) ) => t -> Rhine (TerminalT t m) cl () () -> m () flowTerminal term clsf = flip runTerminalT term $ flow clsf | A schedule in the ' TerminalT LocalTerminal ' transformer , -- supplying the same backend connection to its scheduled clocks. terminalConcurrently :: forall t cl1 cl2. ( Terminal t , Clock (TerminalT t IO) cl1 , Clock (TerminalT t IO) cl2 , Time cl1 ~ Time cl2 ) => Schedule (TerminalT t IO) cl1 cl2 terminalConcurrently = Schedule $ \cl1 cl2 -> do term <- terminalT ask lift $ first liftTransS <$> initSchedule concurrently (runTerminalClock term cl1) (runTerminalClock term cl2) Workaround TerminalT constructor not being exported . Should be safe in practice . See PR upstream -terminal/pull/18 terminalT :: ReaderT t m a -> TerminalT t m a terminalT = unsafeCoerce type RunTerminalClock m t cl = HoistClock (TerminalT t m) m cl runTerminalClock :: Terminal t => t -> cl -> RunTerminalClock IO t cl runTerminalClock term unhoistedClock = HoistClock { monadMorphism = flip runTerminalT term , .. }
null
https://raw.githubusercontent.com/turion/rhine/8b935a076f8899463bcde055eed3d799fb8f5827/rhine-terminal/src/FRP/Rhine/Terminal.hs
haskell
base exceptions time terminal transformers rhine | A clock that ticks whenever events or interrupts on the terminal arrive. | A function wrapping `flow` to use at the top level in order to run a `Rhine (TerminalT t m) cl ()` Example: @ mainRhine = tagS >-> arrMCl (liftIO . print) @@ TerminalEventClock main :: IO () main = withTerminal $ \term -> `flowTerminal` term mainRhine @ supplying the same backend connection to its scheduled clocks.
| Wrapper to write @terminal@ applications in Rhine , using concurrency . -} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE RecordWildCards # module FRP.Rhine.Terminal ( TerminalEventClock (..) , flowTerminal , terminalConcurrently ) where import Prelude hiding (putChar) import Unsafe.Coerce (unsafeCoerce) import Control.Monad.Catch (MonadMask) import Data.Time.Clock ( getCurrentTime ) import System.Terminal ( awaitEvent, runTerminalT, Event, Interrupt, TerminalT, MonadInput ) import System.Terminal.Internal ( Terminal ) import Control.Monad.Trans.Reader import Control.Monad.Trans.Class (lift) import FRP.Rhine data TerminalEventClock = TerminalEventClock instance (MonadInput m, MonadIO m) => Clock m TerminalEventClock where type Time TerminalEventClock = UTCTime type Tag TerminalEventClock = Either Interrupt Event initClock TerminalEventClock = do initialTime <- liftIO getCurrentTime return ( constM $ do event <- awaitEvent time <- liftIO getCurrentTime return (time, event) , initialTime ) instance GetClockProxy TerminalEventClock instance Semigroup TerminalEventClock where t <> _ = t mainRhine : : MonadIO m = > Rhine ( TerminalT LocalTerminal m ) TerminalEventClock ( ) ( ) flowTerminal :: ( MonadIO m , MonadMask m , Terminal t , Clock (TerminalT t m) cl , GetClockProxy cl , Time cl ~ Time (In cl) , Time cl ~ Time (Out cl) ) => t -> Rhine (TerminalT t m) cl () () -> m () flowTerminal term clsf = flip runTerminalT term $ flow clsf | A schedule in the ' TerminalT LocalTerminal ' transformer , terminalConcurrently :: forall t cl1 cl2. ( Terminal t , Clock (TerminalT t IO) cl1 , Clock (TerminalT t IO) cl2 , Time cl1 ~ Time cl2 ) => Schedule (TerminalT t IO) cl1 cl2 terminalConcurrently = Schedule $ \cl1 cl2 -> do term <- terminalT ask lift $ first liftTransS <$> initSchedule concurrently (runTerminalClock term cl1) (runTerminalClock term cl2) Workaround TerminalT constructor not being exported . Should be safe in practice . See PR upstream -terminal/pull/18 terminalT :: ReaderT t m a -> TerminalT t m a terminalT = unsafeCoerce type RunTerminalClock m t cl = HoistClock (TerminalT t m) m cl runTerminalClock :: Terminal t => t -> cl -> RunTerminalClock IO t cl runTerminalClock term unhoistedClock = HoistClock { monadMorphism = flip runTerminalT term , .. }
1bba346d6efbb30556292e28b7683450b5bad52a6269c8b4b57b1277de646e7c
bitonic/anapo
RawHtml.hs
{-# LANGUAGE OverloadedStrings #-} module Anapo.TestApps.RawHtml (rawHtmlComponent) where import Control.Monad (when) import Anapo import Anapo.TestApps.Prelude rawHtmlComponent :: Node a Bool rawHtmlComponent = div_ [] $ do b <- ask n$ a_ [ href_ "#" , onclick_ $ \_ ev -> do preventDefault ev dispatch (modify not) ] (n$ "TOGGLE") when b (n$ div_ [class_ "m-2"] (n$ "Hello")) n$ div_ [class_ "m-2"] (UnsafeRawHtml "WORLD")
null
https://raw.githubusercontent.com/bitonic/anapo/8f3c020973d16cecb5ee83a03d91fb00294d34c7/anapo-test-app/app/Anapo/TestApps/RawHtml.hs
haskell
# LANGUAGE OverloadedStrings #
module Anapo.TestApps.RawHtml (rawHtmlComponent) where import Control.Monad (when) import Anapo import Anapo.TestApps.Prelude rawHtmlComponent :: Node a Bool rawHtmlComponent = div_ [] $ do b <- ask n$ a_ [ href_ "#" , onclick_ $ \_ ev -> do preventDefault ev dispatch (modify not) ] (n$ "TOGGLE") when b (n$ div_ [class_ "m-2"] (n$ "Hello")) n$ div_ [class_ "m-2"] (UnsafeRawHtml "WORLD")
4371afd8464665c931cf5507d70d7aa23357ffa8485af6411d9533725d09cace
archaelus/tsung
rfc4515_parser.erl
%% Parsing functions for RFC4515 (String Representation of LDAP Search Filters) %% %% TODO: extensibleMatch features not implemented. %% Author : > -module(rfc4515_parser). -author(''). -export([tokenize/1,filter/1,filter_to_string/1]). %% tokenize/1 %% Tokenize the input string into a token list. Generated tokens: %% '(' , ')' , '=' , '<=' ,'>=' , '~=' , '*' , '&' , '|' , '*' , {text,Value} %% Ej: %% ldap_parser:tokenize("(&(!(prpr=a*s*sse*y))(pr~=sss))"). %% --> ['(', '&','(', '!', '(', {text,"prpr"}, '=', {text,"a"}, '*', {text,"s"}, '*', %% {text,"sse"},'*', {text,"y"}, ')', ')', '(', {text,"pr"}, '~=', {text,"sss"}, ')', ')'] %% flatten because & amp ; , etc . in xml attributes ends in deep lists ej:[[38 ] ] tokenizer([$(|L],Current,Tokens) -> tokenizer(L,[],['('|add_current(Current,Tokens)]); tokenizer([$)|L],Current,Tokens) -> tokenizer(L,[],[')'|add_current(Current,Tokens)]); tokenizer([$&|L],Current,Tokens) -> tokenizer(L,[],['&'|add_current(Current,Tokens)]); tokenizer([$||L],Current,Tokens) -> tokenizer(L,[],['|'|add_current(Current,Tokens)]); tokenizer([$!|L],Current,Tokens) -> tokenizer(L,[],['!'|add_current(Current,Tokens)]); tokenizer([$=|L],Current,Tokens) -> tokenizer(L,[],['='|add_current(Current,Tokens)]); tokenizer([$*|L],Current,Tokens) -> tokenizer(L,[],['*'|add_current(Current,Tokens)]); tokenizer([$>,$=|L],Current,Tokens) -> tokenizer(L,[],['>='|add_current(Current,Tokens)]); tokenizer([$<,$=|L],Current,Tokens) -> tokenizer(L,[],['<='|add_current(Current,Tokens)]); tokenizer([$~,$=|L],Current,Tokens) -> tokenizer(L,[],['~='|add_current(Current,Tokens)]); %% an encoded valued start with a backslash '\' character followed by the two hexadecimal digits representing the ASCII value of the encoded character tokenizer([92|L],Current,Tokens) -> [H1,H2|L2] = L, tokenizer(L2,[decode([H1,H2])|Current],Tokens); tokenizer([C|L],Current,Tokens) -> tokenizer(L,[C|Current],Tokens); tokenizer([],[],Tokens) -> lists:reverse(Tokens). %%FIXME: accept trailing whitespaces add_current(Current,Tokens) -> case string:strip(Current) of [] -> Tokens ; X -> [{text,lists:reverse(X)}|Tokens] end. decode(Hex) -> {ok,[C],[]} = io_lib:fread("~#","16#" ++ Hex), C. %% filter/1 %% parse a token list into an AST-like structure. %% Ej: %% ldap_parser:filter(ldap_parser:tokenize("(&(!(prpr=a*s*sse*y))(pr~=sss))")). %% --> {{'and',[{'not',{substring,"prpr", %% [{initial,"a"}, %% {any,"s"}, %% {any,"sse"}, %% {final,"y"}]}}, %% {aprox,"pr","sss"}]}, %% []} filter(['('|L]) -> {R, [')'|L2]} =filtercomp(L), {R,L2}. filtercomp(['&'|L]) -> {R,L2} = filterlist(L), {{'and',R},L2}; filtercomp(['|'|L]) -> {R,L2} = filterlist(L), {{'or',R},L2}; filtercomp(['!'|L]) -> {R,L2} = filter(L), {{'not',R},L2}; filtercomp(L) -> item(L). filterlist(L) -> filterlist(L,[]). filterlist(L=[')'|_],List) -> {lists:reverse(List),L}; %% ')' marks the end of the filter list filterlist(L,List) -> {R,L2} = filter(L), filterlist(L2,[R|List]). item([{text,T}|L]) -> item2(L,T). item2(['~=',{text,V}|L],Attr) -> {{aprox,Attr,V},L}; item2(['>=',{text,V}|L],Attr) -> {{get,Attr,V},L}; item2(['<=',{text,V}|L],Attr) -> {{'let',Attr,V},L}; item2(['='|L],Attr) -> item3(L,Attr). % could be a presence, equality or substring match item3(L = [')'|_],Attr) -> {{eq,Attr,""},L}; %empty attr ej: (description=) item3(['*',')'|L],Attr) -> {{present,Attr},[')'|L]}; %presence ej: (description=*) item3([{text,V},')'|L],Attr) -> {{eq,Attr,V},[')'|L]}; %eq ej : = (description=some description) item3(L,Attr) -> {R,L2} = substring(L), {{substring,Attr,R},L2}. substring([{text,V},'*'|L]) -> any(L,[{initial,V}]); substring(['*'|L]) -> any(L,[]). any([{text,V},'*'|L],Subs) -> any(L,[{'any',V}|Subs]); any([{text,V},')'|L],Subs) -> {lists:reverse([{final,V}|Subs]),[')'|L]}; any(L = [')'|_],Subs) -> {lists:reverse(Subs),L}. filter_to_string({'and',L}) -> io_lib:format("(& ~s)",[lists:map(fun filter_to_string/1,L)]); filter_to_string({'or',L}) -> io_lib:format("(| ~s)",[lists:map(fun filter_to_string/1,L)]); filter_to_string({'not',I}) -> io_lib:format("(! ~s)",[filter_to_string(I)]); filter_to_string({'present',Attr}) -> io_lib:format("(~s=*)",[Attr]); filter_to_string({'substring',Attr,Subs}) -> io_lib:format("(~s=~s)",[Attr,print_substrings(Subs)]); filter_to_string({'aprox',Attr,Value}) -> io_lib:format("(~s~~=~s)",[Attr,Value]); filter_to_string({'let',Attr,Value}) -> io_lib:format("(~s<=~s)",[Attr,Value]); filter_to_string({'get',Attr,Value}) -> io_lib:format("(~s>=~s)",[Attr,Value]); filter_to_string({'eq',Attr,Value}) -> io_lib:format("(~s=~s)",[Attr,Value]). print_substrings(Subs) -> lists:map(fun print_substring/1,Subs). print_substring({initial,V}) -> io_lib:format("~s",[V]); print_substring({final,V}) -> io_lib:format("*~s",[V]); print_substring({any,V}) -> io_lib:format("*~s",[V]).
null
https://raw.githubusercontent.com/archaelus/tsung/b4ea0419c6902d8bb63795200964d25b19e46532/src/lib/rfc4515_parser.erl
erlang
Parsing functions for RFC4515 (String Representation of LDAP Search Filters) TODO: extensibleMatch features not implemented. tokenize/1 Tokenize the input string into a token list. Generated tokens: '(' , ')' , '=' , '<=' ,'>=' , '~=' , '*' , '&' , '|' , '*' , {text,Value} Ej: ldap_parser:tokenize("(&(!(prpr=a*s*sse*y))(pr~=sss))"). --> ['(', '&','(', '!', '(', {text,"prpr"}, '=', {text,"a"}, '*', {text,"s"}, '*', {text,"sse"},'*', {text,"y"}, ')', ')', '(', {text,"pr"}, '~=', {text,"sss"}, ')', ')'] an encoded valued start with a backslash '\' character followed by the FIXME: accept trailing whitespaces filter/1 parse a token list into an AST-like structure. Ej: ldap_parser:filter(ldap_parser:tokenize("(&(!(prpr=a*s*sse*y))(pr~=sss))")). --> {{'and',[{'not',{substring,"prpr", [{initial,"a"}, {any,"s"}, {any,"sse"}, {final,"y"}]}}, {aprox,"pr","sss"}]}, []} ')' marks the end of the filter list could be a presence, equality or substring match empty attr ej: (description=) presence ej: (description=*) eq ej : = (description=some description)
Author : > -module(rfc4515_parser). -author(''). -export([tokenize/1,filter/1,filter_to_string/1]). flatten because & amp ; , etc . in xml attributes ends in deep lists ej:[[38 ] ] tokenizer([$(|L],Current,Tokens) -> tokenizer(L,[],['('|add_current(Current,Tokens)]); tokenizer([$)|L],Current,Tokens) -> tokenizer(L,[],[')'|add_current(Current,Tokens)]); tokenizer([$&|L],Current,Tokens) -> tokenizer(L,[],['&'|add_current(Current,Tokens)]); tokenizer([$||L],Current,Tokens) -> tokenizer(L,[],['|'|add_current(Current,Tokens)]); tokenizer([$!|L],Current,Tokens) -> tokenizer(L,[],['!'|add_current(Current,Tokens)]); tokenizer([$=|L],Current,Tokens) -> tokenizer(L,[],['='|add_current(Current,Tokens)]); tokenizer([$*|L],Current,Tokens) -> tokenizer(L,[],['*'|add_current(Current,Tokens)]); tokenizer([$>,$=|L],Current,Tokens) -> tokenizer(L,[],['>='|add_current(Current,Tokens)]); tokenizer([$<,$=|L],Current,Tokens) -> tokenizer(L,[],['<='|add_current(Current,Tokens)]); tokenizer([$~,$=|L],Current,Tokens) -> tokenizer(L,[],['~='|add_current(Current,Tokens)]); two hexadecimal digits representing the ASCII value of the encoded character tokenizer([92|L],Current,Tokens) -> [H1,H2|L2] = L, tokenizer(L2,[decode([H1,H2])|Current],Tokens); tokenizer([C|L],Current,Tokens) -> tokenizer(L,[C|Current],Tokens); add_current(Current,Tokens) -> case string:strip(Current) of [] -> Tokens ; X -> [{text,lists:reverse(X)}|Tokens] end. decode(Hex) -> {ok,[C],[]} = io_lib:fread("~#","16#" ++ Hex), C. filter(['('|L]) -> {R, [')'|L2]} =filtercomp(L), {R,L2}. filtercomp(['&'|L]) -> {R,L2} = filterlist(L), {{'and',R},L2}; filtercomp(['|'|L]) -> {R,L2} = filterlist(L), {{'or',R},L2}; filtercomp(['!'|L]) -> {R,L2} = filter(L), {{'not',R},L2}; filtercomp(L) -> item(L). filterlist(L) -> filterlist(L,[]). filterlist(L,List) -> {R,L2} = filter(L), filterlist(L2,[R|List]). item([{text,T}|L]) -> item2(L,T). item2(['~=',{text,V}|L],Attr) -> {{aprox,Attr,V},L}; item2(['>=',{text,V}|L],Attr) -> {{get,Attr,V},L}; item2(['<=',{text,V}|L],Attr) -> {{'let',Attr,V},L}; item3(L,Attr) -> {R,L2} = substring(L), {{substring,Attr,R},L2}. substring([{text,V},'*'|L]) -> any(L,[{initial,V}]); substring(['*'|L]) -> any(L,[]). any([{text,V},'*'|L],Subs) -> any(L,[{'any',V}|Subs]); any([{text,V},')'|L],Subs) -> {lists:reverse([{final,V}|Subs]),[')'|L]}; any(L = [')'|_],Subs) -> {lists:reverse(Subs),L}. filter_to_string({'and',L}) -> io_lib:format("(& ~s)",[lists:map(fun filter_to_string/1,L)]); filter_to_string({'or',L}) -> io_lib:format("(| ~s)",[lists:map(fun filter_to_string/1,L)]); filter_to_string({'not',I}) -> io_lib:format("(! ~s)",[filter_to_string(I)]); filter_to_string({'present',Attr}) -> io_lib:format("(~s=*)",[Attr]); filter_to_string({'substring',Attr,Subs}) -> io_lib:format("(~s=~s)",[Attr,print_substrings(Subs)]); filter_to_string({'aprox',Attr,Value}) -> io_lib:format("(~s~~=~s)",[Attr,Value]); filter_to_string({'let',Attr,Value}) -> io_lib:format("(~s<=~s)",[Attr,Value]); filter_to_string({'get',Attr,Value}) -> io_lib:format("(~s>=~s)",[Attr,Value]); filter_to_string({'eq',Attr,Value}) -> io_lib:format("(~s=~s)",[Attr,Value]). print_substrings(Subs) -> lists:map(fun print_substring/1,Subs). print_substring({initial,V}) -> io_lib:format("~s",[V]); print_substring({final,V}) -> io_lib:format("*~s",[V]); print_substring({any,V}) -> io_lib:format("*~s",[V]).
dbf0895a9852f705fa6b9e252e39d5f3eba970068998bdb6f2b30e51c043b186
jimpil/Clondie24
core.clj
(ns Clondie24.lib.core (:require [Clondie24.lib.util :as ut] [clojure.core.reducers :as r] [enclog.training :as evo] [enclog.normalization :refer [prepare input output target-storage]] ) (:import [encog_java.customGA CustomNeuralGeneticAlgorithm Referee] [org.encog.ml MLRegression])) ;----------------------------------------<SOURCE>-------------------------------------------------------------------- ;----------------------------------------<CODE>---------------------------------------------------------------------- (set! *unchecked-math* true) (set! *warn-on-reflection* true) (def ^:const mappings-8x8 "A vector of vectors. Outer vector represents the 64 (serial) positions chess-items can position themselves on. Each inner vector represents the coordinates of that position on the 8x8 grid." (ut/grid 8 8)) (def ^:const mappings-3x3 "A vector of vectors. Outer vector represents the 9 (serial) positions tic-tac-toe-items can position themselves on. Each inner vector represents the coordinates of that position on the 3x3 grid." (ut/grid 3 3)) (def board-history "Log of the state of a game." (atom [])) (defn log-board "The logging function for the board ref. Will conj every new board-state into a vector." [dest k r old n] (when (not= n old) (swap! dest conj n))) (defrecord Player [brain ^long direction searcher]) (defprotocol Piece "The Piece abstraction." (update-position [this new-position]) (mutate-position [this new-position]) ;;optional in case you need mutation (getGridPosition [this]) (getListPosition [this]) for ? (die [this]) (promote [this np]) (getMoves [this board with-precious-piece?])) (defprotocol Movable "The Command design pattern in action (allows us to do/undo moves)." (try-move [this]) (undo [this]) ;;optional in case you need mutation (getOrigin [this])) (extend-type nil Movable (try-move [_] nil)) (defn- translate "Translates a position from 1d to 2d and vice-versa. Mappings should be either 'checkers-board-mappings' or 'chess-board-mappings'." ([^long i mappings] ;{:post [(not (nil? %))]} will translate from 1d to 2d (if (nil? grid-loc) ;not found (throw (IllegalStateException. (str "NOT a valid list-location:" i))) grid-loc) )) ([x y ^clojure.lang.PersistentVector mappings] ;{:post [(not= % -1)]} will translate from 2d to 1d (if (= list-loc -1) (throw (IllegalStateException. (str "NOT a valid grid-location: [" x ", " y "]"))) list-loc)))) (def translate-position (memoize translate)) (defn piece "Helper function for creating pieces. A piece is simply a record with 5 keys. Better not use this directly (slow)!" [game c pos rank direction] ;&{:keys [rank direction ] : or { rank ' zombie direction 1 r - value 1 } } ] ((ut/record-factory-aux (:record-name game)) c pos rank ((keyword rank) (:rel-values game)) direction {:alive true} ;pieces are born 'alive' nil)) ;no extra fields (defn starting-board [game] "Returns the initial board for a game with pieces on correct starting positions for the particular game." (let [p1 (:north-player-start game) p2 (:south-player-start game) tps (:total-pieces game) vacant (- (:board-size game) tps)] (if (zero? tps) (vec (repeat vacant nil)) (vec (flatten (conj p2 (conj (repeat vacant nil) p1)))) ))) ;;(into p2 (into (repeat vacant nil) p1)) (definline gather-team "Filters all the pieces with same direction dir on this board b." [b dir] `(filter #(= ~dir (:direction %)) ~b)) ;all the team-mates (with same direction) (definline team-moves "Returns all the moves (a reducer) for the team with direction 'dir' on this board b." [b dir exposes-check?] `(r/mapcat (fn [p#] (getMoves p# ~b ~exposes-check?)) (gather-team ~b ~dir))) (definline full-board? [b] `(not-any? nil? ~b)) (defn vacant? "Checks if a position [x, y] is vacant on the given board and mappings." [m b [x y :as pos]] (nil? (get b (translate-position x y m)))) (def occupied? (complement vacant?)) (defn occupant [m b [x y :as pos]] (get b (translate-position x y m))) (definline alive? [p] `(:alive (meta ~p))) (defn game-over? [referee & args] (apply referee args)) (defn empty-board "Returns an empty board for the game provided - all nils." [game] (vec (repeat (:board-size game) nil))) (definline populate-board "Builds a new board with nils where dead pieces." [board] `(into [] (r/map #(if (alive? %) % nil) ~board))) (defn rand-move [piece b precious?] {:move (rand-nth (getMoves piece b precious?))}) (defn rand-team-move [dir b] (let [all-moves (into [] (team-moves b dir true))] ;;looking for safe moves {:move (rand-nth all-moves)})) (defn move "A generic function for moving Pieces. Each piece knows where it can move. Returns the resulting board without side-effects. " [board p coords] { : pre [ ( satisfies ? ) ] } ; safety comes first ;(if (some #{coords} (:mappings game-map)) ;check that the position exists on the grid (let [newPiece (update-position p coords) ;the new piece as a result of moving old-pos (getListPosition p) new-pos (getListPosition newPiece)] (-> board ;(transient) (assoc old-pos nil new-pos newPiece) ;(assoc! ) ;(persistent!) replace dead - pieces with nils #_(throw (IllegalStateException. (str coords " is NOT a valid position according to the mappings provided!"))) #_(defn amove "Same as 'move' but fast (expects a mutable array for board). Returns the mutated board." [board p coords] (let [old-pos (getListPosition p) mutPiece (update-position p coords) ;the mutated piece new-pos (getListPosition mutPiece)] (aset board old-pos nil) ;^"[LClondie24.games.chess.ChessPiece2;" (aset board new-pos mutPiece) board)) (defrecord Move [p mover end-pos] Movable (try-move [this] (with-meta (mover p end-pos) {:caused-by this})) ;;the board returned was caused by this move (getOrigin [this] (if (map? p) (:position p) (:position (first p)))) Object (toString [this] (println "#Move {:from" (:position p) ":to" end-pos))) (defn dest->Move "Constructor for creating moves from destinations. Prefer this to the direct constructor. It wouldn't make sense to pass more than 1 mover-fns." ^Move [b p dest mover] (Move. p #((or mover move) b %1 %2) dest)) (defn execute! [^Move m batom] ( when ( not= (: ) ( - > m :p : position ) ) (reset! batom (try-move m))) ( swap ! ( fn [ & args ] ( try - move m ) ) ) (defn unchunk "Returns a fully unchunked lazy sequence. Might need it for massive boards." [s] (when (seq s) (lazy-seq (cons (first s) (unchunk (next s)))))) (definline threatens? "Returns true if p2 is threatened by p1 on board b. This is the only time that we call getMoves with a falsy last arg." [p2 p1 b] `(some #{(:position ~p2)} (map :end-pos (getMoves ~p1 ~b false)))) (defn undo! [] (try (swap! board-history pop) (catch Exception e @board-history))) ;popping an empty stack throws an error (just return the empty one) (defn clear-history! [] (swap! board-history empty)) (definline bury-dead [c] `(filter alive? ~c)) (definline collides? "Returns true if the move collides with any friendly pieces. The move will be walked step by step by the walker fn." last 2 can be false , nil `(let [ppp# (:end-pos ~move) multi-move?# (if (sequential? (first ppp#)) true false) [epx# epy# :as ep#] (if multi-move?# (first ppp#) ppp#) dir# (if multi-move?# (get-in ~move [:p 0 :direction]) (get-in ~move [:p :direction]))] if walker is nil make one big step to the end (~walker (getOrigin ~move)))] (cond (= imm-p# ep#) ;if reached destination there is potential for attack (if-not (= dir# (:direction (get ~b (translate-position epx# epy# ~m)))) false true) (not (nil? (get ~b (translate-position imm-px# imm-py# ~m)))) true :else (recur (~walker imm-p#)))))) #_(defn acollides? "Same as 'collides?' but deals with an array as b - not a vector." [[sx sy] [ex ey] walker b m dir] if walker is nil make one big step to the end (cond (= [ex ey] [imm-x imm-y]) ;if reached destination (if (not= dir (:direction (aget b (translate-position ex ey m)))) false true) (not (nil? (aget b (translate-position imm-x imm-y m)))) true :else (recur (walker [imm-x imm-y]))))) (definline exposes? [move precious] `(if-not ~precious false ;skip everything (let [next-b# (try-move ~move) ipiece# (first (:p ~move)) ;;assuming multi-move temporarily dir# (if (map? ipiece#) (:direction ipiece#) (get-in ~move [:p :direction])) def-prec# (some #(when (and (= ~precious (:rank %)) (= dir# (:direction %))) %) next-b#)] (some #(threatens? def-prec# % next-b#) (gather-team next-b# (- dir#)))))) (defn score-chess-naive ^double [b dir] (let [hm (gather-team b dir) ;fixed bug aw (gather-team b (- dir))] (- (r/reduce + (r/map :value hm)) (r/reduce + (r/map :value aw))))) (definline remove-illegal [pred ms] `(into [] (r/remove ~pred ~ms))) ;(comment (definline anormalise "Deals directly with seqs (input) and arrays (output)." [ins] `(prepare nil nil nil :how :array-range :raw-seq ~ins)) (defn normalize-fields [ins outs game-map] (prepare ins outs (target-storage :norm-array [(:board-size game-map) nil]))) (defn neural-input "Returns appropriate number of inputs for the neural-net according to how big the board is." [b dir fields?] ((if fields? input identity) (for [t b] (if (nil? t) 0 (* dir (:direction t) (get t :value 1)))))) (definline neural-output "Creates output-field based on this InputField." [input] `(output ~input)) (defn neural-player "Constructs a Player object for a particular game, given a brain b (a neural-net), a direction dir and a game-specific searching fn [:best or :random]." ([game ^MLRegression brain dir searcher extract-response] (Player. ignore 2nd arg - we already have direction (let [ins (neural-input leaf dir false) normals (if (get :normalise-neural-input? game false) (->> ins anormalise (evo/data :basic)) (evo/data :basic ins)) output (-> brain (.compute normals) .getData)] (extract-response output leaf) )) dir (get-in game [:searchers searcher] (get-in game [:searchers :minmax])))) ([game ^MLRegression brain dir searcher] (neural-player game brain dir searcher (fn [a _] (aget ^doubles a 0)))) ([game ^MLRegression brain dir] (neural-player game brain dir :limited)) ) (defn tournament "Starts a tournament between the 2 Players (p1, p2). If there is no winner, returns the entire history (vector) of the tournament after 100 moves. If there is a winner, a 2d vector will be returned containing both the history (1st item) and the winner (2nd item). For games that can end without a winner, [history, nil] will be returned." ([game-details p1 p2 sb] (reduce (fn [history player] (let [cb (peek history)] (if-let [win-dir ((:game-over?-fn game-details) cb)] (reduced (vector history (condp = win-dir (:direction p1) p1 (:direction p2) p2 nil))) (conj history (-> player ((:searcher player) cb (get game-details :pruning?)) :move try-move))))) [sb] (take (:max-moves game-details) (cycle [p1 p2])))) ([game-details p1 p2] (tournament game-details p1 p2 (starting-board game-details))) ) (defn fast-tournament "Same as tournament but without keeping history. If there is a winner, returns the winning direction otherwise returns the last board. Intended to be used with genetic training." ([game-details p1 p2 sb] (reduce (fn [board player] (if-let [win-dir ((:game-over?-fn game-details) board)] (reduced (condp = win-dir (:direction p1) p1 (:direction p2) p2 board)) (-> player ((:searcher player) board (:pruning? game-details)) :move try-move))) sb (take (:max-moves game-details) (cycle [p1 p2])))) ([game-details p1 p2] (fast-tournament game-details p1 p2 (starting-board game-details))) ) (defn ga-fitness "Scores p1 after competing with p2 using tournament-fn." [tournament-fn p1 p2 &{:keys[reward penalty] :or {reward 1 penalty -1}}] (let [winner (tournament-fn p1 p2)] (condp = (:direction winner) reward p1 with 1 point (:direction p2) penalty ;penalise p1 with -1 points give 0 points - noone won (defn GA [game brain pop-size & {:keys [randomizer to-mate to-mutate thread-no total-tournaments ga-type fitness] :or {randomizer (evo/randomizer :nguyen-widrow) to-mate 0.2 to-mutate 0.1 total-tournaments (int 5) ga-type :custom thread-no (+ 2 (.. Runtime getRuntime availableProcessors))}}] (case ga-type :custom (doto (CustomNeuralGeneticAlgorithm. brain randomizer (Referee. game fitness total-tournaments) pop-size to-mutate to-mate) (.setThreadCount thread-no)) :default (doto (evo/trainer :genetic :network brain :randomizer randomizer :minimize? false :population-size pop-size :fitness-fn fitness :mutation-percent to-mutate :mate-percent to-mate) (.setThreadCount thread-no)) (throw (IllegalArgumentException. "Only :custom and :default GAs are supported!"))) ) (definline train [trainer iterations strategies] `(evo/train ~trainer Double/NEGATIVE_INFINITY ~iterations ~strategies))
null
https://raw.githubusercontent.com/jimpil/Clondie24/7045fab11bfd6e94cd95c032149a97146bae8d89/src/Clondie24/lib/core.clj
clojure
----------------------------------------<SOURCE>-------------------------------------------------------------------- ----------------------------------------<CODE>---------------------------------------------------------------------- optional in case you need mutation optional in case you need mutation {:post [(not (nil? %))]} not found {:post [(not= % -1)]} &{:keys [rank direction ] pieces are born 'alive' no extra fields (into p2 (into (repeat vacant nil) p1)) all the team-mates (with same direction) looking for safe moves safety comes first (if (some #{coords} (:mappings game-map)) ;check that the position exists on the grid the new piece as a result of moving (transient) (assoc! ) (persistent!) the mutated piece ^"[LClondie24.games.chess.ChessPiece2;" the board returned was caused by this move popping an empty stack throws an error (just return the empty one) if reached destination there is potential for attack if reached destination skip everything assuming multi-move temporarily fixed bug (comment penalise p1 with -1 points
(ns Clondie24.lib.core (:require [Clondie24.lib.util :as ut] [clojure.core.reducers :as r] [enclog.training :as evo] [enclog.normalization :refer [prepare input output target-storage]] ) (:import [encog_java.customGA CustomNeuralGeneticAlgorithm Referee] [org.encog.ml MLRegression])) (set! *unchecked-math* true) (set! *warn-on-reflection* true) (def ^:const mappings-8x8 "A vector of vectors. Outer vector represents the 64 (serial) positions chess-items can position themselves on. Each inner vector represents the coordinates of that position on the 8x8 grid." (ut/grid 8 8)) (def ^:const mappings-3x3 "A vector of vectors. Outer vector represents the 9 (serial) positions tic-tac-toe-items can position themselves on. Each inner vector represents the coordinates of that position on the 3x3 grid." (ut/grid 3 3)) (def board-history "Log of the state of a game." (atom [])) (defn log-board "The logging function for the board ref. Will conj every new board-state into a vector." [dest k r old n] (when (not= n old) (swap! dest conj n))) (defrecord Player [brain ^long direction searcher]) (defprotocol Piece "The Piece abstraction." (update-position [this new-position]) (getGridPosition [this]) (getListPosition [this]) for ? (die [this]) (promote [this np]) (getMoves [this board with-precious-piece?])) (defprotocol Movable "The Command design pattern in action (allows us to do/undo moves)." (try-move [this]) (getOrigin [this])) (extend-type nil Movable (try-move [_] nil)) (defn- translate "Translates a position from 1d to 2d and vice-versa. Mappings should be either 'checkers-board-mappings' or 'chess-board-mappings'." will translate from 1d to 2d (throw (IllegalStateException. (str "NOT a valid list-location:" i))) grid-loc) )) will translate from 2d to 1d (if (= list-loc -1) (throw (IllegalStateException. (str "NOT a valid grid-location: [" x ", " y "]"))) list-loc)))) (def translate-position (memoize translate)) (defn piece "Helper function for creating pieces. A piece is simply a record with 5 keys. Better not use this directly (slow)!" : or { rank ' zombie direction 1 r - value 1 } } ] ((ut/record-factory-aux (:record-name game)) c pos rank ((keyword rank) (:rel-values game)) direction (defn starting-board [game] "Returns the initial board for a game with pieces on correct starting positions for the particular game." (let [p1 (:north-player-start game) p2 (:south-player-start game) tps (:total-pieces game) vacant (- (:board-size game) tps)] (if (zero? tps) (vec (repeat vacant nil)) (definline gather-team "Filters all the pieces with same direction dir on this board b." [b dir] `(filter (definline team-moves "Returns all the moves (a reducer) for the team with direction 'dir' on this board b." [b dir exposes-check?] `(r/mapcat (fn [p#] (getMoves p# ~b ~exposes-check?)) (gather-team ~b ~dir))) (definline full-board? [b] `(not-any? nil? ~b)) (defn vacant? "Checks if a position [x, y] is vacant on the given board and mappings." [m b [x y :as pos]] (nil? (get b (translate-position x y m)))) (def occupied? (complement vacant?)) (defn occupant [m b [x y :as pos]] (get b (translate-position x y m))) (definline alive? [p] `(:alive (meta ~p))) (defn game-over? [referee & args] (apply referee args)) (defn empty-board "Returns an empty board for the game provided - all nils." [game] (vec (repeat (:board-size game) nil))) (definline populate-board "Builds a new board with nils where dead pieces." [board] `(into [] (r/map #(if (alive? %) % nil) ~board))) (defn rand-move [piece b precious?] {:move (rand-nth (getMoves piece b precious?))}) (defn rand-team-move [dir b] {:move (rand-nth all-moves)})) (defn move "A generic function for moving Pieces. Each piece knows where it can move. Returns the resulting board without side-effects. " [board p coords] old-pos (getListPosition p) new-pos (getListPosition newPiece)] (-> board (assoc old-pos nil new-pos newPiece) replace dead - pieces with nils #_(throw (IllegalStateException. (str coords " is NOT a valid position according to the mappings provided!"))) #_(defn amove "Same as 'move' but fast (expects a mutable array for board). Returns the mutated board." [board p coords] (let [old-pos (getListPosition p) new-pos (getListPosition mutPiece)] (aset board new-pos mutPiece) board)) (defrecord Move [p mover end-pos] Movable (getOrigin [this] (if (map? p) (:position p) (:position (first p)))) Object (toString [this] (println "#Move {:from" (:position p) ":to" end-pos))) (defn dest->Move "Constructor for creating moves from destinations. Prefer this to the direct constructor. It wouldn't make sense to pass more than 1 mover-fns." ^Move [b p dest mover] (Move. p #((or mover move) b %1 %2) dest)) (defn execute! [^Move m batom] ( when ( not= (: ) ( - > m :p : position ) ) (reset! batom (try-move m))) ( swap ! ( fn [ & args ] ( try - move m ) ) ) (defn unchunk "Returns a fully unchunked lazy sequence. Might need it for massive boards." [s] (when (seq s) (lazy-seq (cons (first s) (unchunk (next s)))))) (definline threatens? "Returns true if p2 is threatened by p1 on board b. This is the only time that we call getMoves with a falsy last arg." [p2 p1 b] `(some #{(:position ~p2)} (map :end-pos (getMoves ~p1 ~b false)))) (defn undo! [] (try (swap! board-history pop) (defn clear-history! [] (swap! board-history empty)) (definline bury-dead [c] `(filter alive? ~c)) (definline collides? "Returns true if the move collides with any friendly pieces. The move will be walked step by step by the walker fn." last 2 can be false , nil `(let [ppp# (:end-pos ~move) multi-move?# (if (sequential? (first ppp#)) true false) [epx# epy# :as ep#] (if multi-move?# (first ppp#) ppp#) dir# (if multi-move?# (get-in ~move [:p 0 :direction]) (get-in ~move [:p :direction]))] if walker is nil make one big step to the end (~walker (getOrigin ~move)))] (cond (if-not (= dir# (:direction (get ~b (translate-position epx# epy# ~m)))) false true) (not (nil? (get ~b (translate-position imm-px# imm-py# ~m)))) true :else (recur (~walker imm-p#)))))) #_(defn acollides? "Same as 'collides?' but deals with an array as b - not a vector." [[sx sy] [ex ey] walker b m dir] if walker is nil make one big step to the end (cond (if (not= dir (:direction (aget b (translate-position ex ey m)))) false true) (not (nil? (aget b (translate-position imm-x imm-y m)))) true :else (recur (walker [imm-x imm-y]))))) (definline exposes? [move precious] (let [next-b# (try-move ~move) dir# (if (map? ipiece#) (:direction ipiece#) (get-in ~move [:p :direction])) def-prec# (some #(when (and (= ~precious (:rank %)) (= dir# (:direction %))) %) next-b#)] (some #(threatens? def-prec# % next-b#) (gather-team next-b# (- dir#)))))) (defn score-chess-naive ^double [b dir] aw (gather-team b (- dir))] (- (r/reduce + (r/map :value hm)) (r/reduce + (r/map :value aw))))) (definline remove-illegal [pred ms] `(into [] (r/remove ~pred ~ms))) (definline anormalise "Deals directly with seqs (input) and arrays (output)." [ins] `(prepare nil nil nil :how :array-range :raw-seq ~ins)) (defn normalize-fields [ins outs game-map] (prepare ins outs (target-storage :norm-array [(:board-size game-map) nil]))) (defn neural-input "Returns appropriate number of inputs for the neural-net according to how big the board is." [b dir fields?] ((if fields? input identity) (for [t b] (if (nil? t) 0 (* dir (:direction t) (get t :value 1)))))) (definline neural-output "Creates output-field based on this InputField." [input] `(output ~input)) (defn neural-player "Constructs a Player object for a particular game, given a brain b (a neural-net), a direction dir and a game-specific searching fn [:best or :random]." ([game ^MLRegression brain dir searcher extract-response] (Player. ignore 2nd arg - we already have direction (let [ins (neural-input leaf dir false) normals (if (get :normalise-neural-input? game false) (->> ins anormalise (evo/data :basic)) (evo/data :basic ins)) output (-> brain (.compute normals) .getData)] (extract-response output leaf) )) dir (get-in game [:searchers searcher] (get-in game [:searchers :minmax])))) ([game ^MLRegression brain dir searcher] (neural-player game brain dir searcher (fn [a _] (aget ^doubles a 0)))) ([game ^MLRegression brain dir] (neural-player game brain dir :limited)) ) (defn tournament "Starts a tournament between the 2 Players (p1, p2). If there is no winner, returns the entire history (vector) of the tournament after 100 moves. If there is a winner, a 2d vector will be returned containing both the history (1st item) and the winner (2nd item). For games that can end without a winner, [history, nil] will be returned." ([game-details p1 p2 sb] (reduce (fn [history player] (let [cb (peek history)] (if-let [win-dir ((:game-over?-fn game-details) cb)] (reduced (vector history (condp = win-dir (:direction p1) p1 (:direction p2) p2 nil))) (conj history (-> player ((:searcher player) cb (get game-details :pruning?)) :move try-move))))) [sb] (take (:max-moves game-details) (cycle [p1 p2])))) ([game-details p1 p2] (tournament game-details p1 p2 (starting-board game-details))) ) (defn fast-tournament "Same as tournament but without keeping history. If there is a winner, returns the winning direction otherwise returns the last board. Intended to be used with genetic training." ([game-details p1 p2 sb] (reduce (fn [board player] (if-let [win-dir ((:game-over?-fn game-details) board)] (reduced (condp = win-dir (:direction p1) p1 (:direction p2) p2 board)) (-> player ((:searcher player) board (:pruning? game-details)) :move try-move))) sb (take (:max-moves game-details) (cycle [p1 p2])))) ([game-details p1 p2] (fast-tournament game-details p1 p2 (starting-board game-details))) ) (defn ga-fitness "Scores p1 after competing with p2 using tournament-fn." [tournament-fn p1 p2 &{:keys[reward penalty] :or {reward 1 penalty -1}}] (let [winner (tournament-fn p1 p2)] (condp = (:direction winner) reward p1 with 1 point give 0 points - noone won (defn GA [game brain pop-size & {:keys [randomizer to-mate to-mutate thread-no total-tournaments ga-type fitness] :or {randomizer (evo/randomizer :nguyen-widrow) to-mate 0.2 to-mutate 0.1 total-tournaments (int 5) ga-type :custom thread-no (+ 2 (.. Runtime getRuntime availableProcessors))}}] (case ga-type :custom (doto (CustomNeuralGeneticAlgorithm. brain randomizer (Referee. game fitness total-tournaments) pop-size to-mutate to-mate) (.setThreadCount thread-no)) :default (doto (evo/trainer :genetic :network brain :randomizer randomizer :minimize? false :population-size pop-size :fitness-fn fitness :mutation-percent to-mutate :mate-percent to-mate) (.setThreadCount thread-no)) (throw (IllegalArgumentException. "Only :custom and :default GAs are supported!"))) ) (definline train [trainer iterations strategies] `(evo/train ~trainer Double/NEGATIVE_INFINITY ~iterations ~strategies))
d89d907640c433342d920b05abadf18d9782a6b777e64a4b90abd1d173d513ae
codedownio/sandwich
Main.hs
# LANGUAGE TypeOperators # # LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # module Main where import Common import Control.Concurrent import Control.Monad.IO.Class import Data.Time.Clock import System.Random import Test.Sandwich landingDemo :: TopSpec landingDemo = describe "Arithmetic tests" $ parallel $ do withTimingProfile "Addition" $ describe "Addition" $ do it "basic addition" $ do (2 + 2) `shouldBe` 4 sleepRandom it "adding zero" $ do (2 + 0) `shouldBe` 2 sleepRandom it "adding one" $ do sleepRandom warn "Having some trouble getting this test to pass..." (0 + 1) `shouldBe` 0 withTimingProfile "Multiplication" $ describe "Multiplication" $ do it "small numbers" $ do (2 * 3) `shouldBe` 6 sleepRandom it "multiplying by zero" $ do (2 * 0) `shouldBe` 0 sleepRandom it "multiplying by one" $ do (2 * 1) `shouldBe` 2 sleepRandom it "squaring" $ do (2 * 2) `shouldBe` 4 sleepRandom sleepRandom :: ExampleM context () sleepRandom = liftIO $ do timeToSleep :: Int <- randomRIO (1500000, 3000000) threadDelay timeToSleep testOptions = defaultOptions { optionsTestArtifactsDirectory = TestArtifactsGeneratedDirectory "test_runs" (show <$> getCurrentTime) , optionsProjectRoot = Just "demos/demo-landing" } main :: IO () main = runSandwichWithCommandLineArgs testOptions landingDemo
null
https://raw.githubusercontent.com/codedownio/sandwich/087ea530d4d9dd1333f6fcba53dc76ca13bc7c78/demos/demo-landing/app/Main.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators # # LANGUAGE DataKinds # # LANGUAGE QuasiQuotes # module Main where import Common import Control.Concurrent import Control.Monad.IO.Class import Data.Time.Clock import System.Random import Test.Sandwich landingDemo :: TopSpec landingDemo = describe "Arithmetic tests" $ parallel $ do withTimingProfile "Addition" $ describe "Addition" $ do it "basic addition" $ do (2 + 2) `shouldBe` 4 sleepRandom it "adding zero" $ do (2 + 0) `shouldBe` 2 sleepRandom it "adding one" $ do sleepRandom warn "Having some trouble getting this test to pass..." (0 + 1) `shouldBe` 0 withTimingProfile "Multiplication" $ describe "Multiplication" $ do it "small numbers" $ do (2 * 3) `shouldBe` 6 sleepRandom it "multiplying by zero" $ do (2 * 0) `shouldBe` 0 sleepRandom it "multiplying by one" $ do (2 * 1) `shouldBe` 2 sleepRandom it "squaring" $ do (2 * 2) `shouldBe` 4 sleepRandom sleepRandom :: ExampleM context () sleepRandom = liftIO $ do timeToSleep :: Int <- randomRIO (1500000, 3000000) threadDelay timeToSleep testOptions = defaultOptions { optionsTestArtifactsDirectory = TestArtifactsGeneratedDirectory "test_runs" (show <$> getCurrentTime) , optionsProjectRoot = Just "demos/demo-landing" } main :: IO () main = runSandwichWithCommandLineArgs testOptions landingDemo
c9184df78e2583fed2a62d86a5e1bd4ffc8529ba6615e3ce8a1f662c3374eb90
fossas/fossa-cli
VSIDeps.hs
module App.Fossa.VSIDeps ( analyzeVSIDeps, ) where import App.Fossa.Analyze.Project (ProjectResult (ProjectResult)) import App.Fossa.VSI.Analyze (runVsiAnalysis) import App.Fossa.VSI.IAT.Resolve (resolveGraph, resolveUserDefined) import App.Fossa.VSI.Types qualified as VSI import App.Types (ProjectRevision) import Control.Algebra (Has) import Control.Effect.Diagnostics (Diagnostics, fromEither) import Control.Effect.Finally (Finally) import Control.Effect.FossaApiClient (FossaApiClient) import Control.Effect.Lift (Lift) import Control.Effect.StickyLogger (StickyLogger) import DepTypes (Dependency) import Discovery.Filters (AllFilters) import Effect.Logger (Logger) import Effect.ReadFS (ReadFS) import Graphing (Graphing) import Graphing qualified import Path (Abs, Dir, Path) import Srclib.Converter qualified as Srclib import Srclib.Types (AdditionalDepData (..), SourceUnit (..), SourceUserDefDep) import Types (DiscoveredProjectType (VsiProjectType), GraphBreadth (Complete)) -- | VSI analysis is sufficiently different from other analysis types that it cannot be just another strategy. -- Instead, VSI analysis is run separately over the entire scan directory, outputting its own source unit. analyzeVSIDeps :: ( Has Diagnostics sig m , Has (Lift IO) sig m , Has Logger sig m , Has StickyLogger sig m , Has ReadFS sig m , Has Finally sig m , Has FossaApiClient sig m ) => Path Abs Dir -> ProjectRevision -> AllFilters -> VSI.SkipResolution -> m SourceUnit analyzeVSIDeps dir projectRevision filters skipResolving = do (direct, userDeps) <- runVsiAnalysis dir projectRevision filters resolvedUserDeps <- resolveUserDefined userDeps resolvedGraph <- resolveGraph direct skipResolving dependencies <- fromEither $ Graphing.gtraverse VSI.toDependency resolvedGraph pure $ toSourceUnit (toProject dir dependencies) resolvedUserDeps toProject :: Path Abs Dir -> Graphing Dependency -> ProjectResult toProject dir graph = ProjectResult VsiProjectType dir graph Complete [] toSourceUnit :: ProjectResult -> Maybe [SourceUserDefDep] -> SourceUnit toSourceUnit project deps = do let unit = Srclib.toSourceUnit False project unit{additionalData = fmap toDepData deps} where toDepData d = AdditionalDepData (Just d) Nothing
null
https://raw.githubusercontent.com/fossas/fossa-cli/abac26299f1fce2d4c3f4b9b688a939064df20fa/src/App/Fossa/VSIDeps.hs
haskell
| VSI analysis is sufficiently different from other analysis types that it cannot be just another strategy. Instead, VSI analysis is run separately over the entire scan directory, outputting its own source unit.
module App.Fossa.VSIDeps ( analyzeVSIDeps, ) where import App.Fossa.Analyze.Project (ProjectResult (ProjectResult)) import App.Fossa.VSI.Analyze (runVsiAnalysis) import App.Fossa.VSI.IAT.Resolve (resolveGraph, resolveUserDefined) import App.Fossa.VSI.Types qualified as VSI import App.Types (ProjectRevision) import Control.Algebra (Has) import Control.Effect.Diagnostics (Diagnostics, fromEither) import Control.Effect.Finally (Finally) import Control.Effect.FossaApiClient (FossaApiClient) import Control.Effect.Lift (Lift) import Control.Effect.StickyLogger (StickyLogger) import DepTypes (Dependency) import Discovery.Filters (AllFilters) import Effect.Logger (Logger) import Effect.ReadFS (ReadFS) import Graphing (Graphing) import Graphing qualified import Path (Abs, Dir, Path) import Srclib.Converter qualified as Srclib import Srclib.Types (AdditionalDepData (..), SourceUnit (..), SourceUserDefDep) import Types (DiscoveredProjectType (VsiProjectType), GraphBreadth (Complete)) analyzeVSIDeps :: ( Has Diagnostics sig m , Has (Lift IO) sig m , Has Logger sig m , Has StickyLogger sig m , Has ReadFS sig m , Has Finally sig m , Has FossaApiClient sig m ) => Path Abs Dir -> ProjectRevision -> AllFilters -> VSI.SkipResolution -> m SourceUnit analyzeVSIDeps dir projectRevision filters skipResolving = do (direct, userDeps) <- runVsiAnalysis dir projectRevision filters resolvedUserDeps <- resolveUserDefined userDeps resolvedGraph <- resolveGraph direct skipResolving dependencies <- fromEither $ Graphing.gtraverse VSI.toDependency resolvedGraph pure $ toSourceUnit (toProject dir dependencies) resolvedUserDeps toProject :: Path Abs Dir -> Graphing Dependency -> ProjectResult toProject dir graph = ProjectResult VsiProjectType dir graph Complete [] toSourceUnit :: ProjectResult -> Maybe [SourceUserDefDep] -> SourceUnit toSourceUnit project deps = do let unit = Srclib.toSourceUnit False project unit{additionalData = fmap toDepData deps} where toDepData d = AdditionalDepData (Just d) Nothing
9a3e074ecf3d3705b1132e27ab8777980cf8d2b893e6467051841c23ccf926e6
xclerc/ocamljava
threadGroup.mli
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * 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 3 of the License , or * ( at your option ) any later version . * * 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 program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java 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 3 of the License, or * (at your option) any later version. * * OCaml-Java 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 program. If not, see </>. *) (** Thread groups. *) type t = java'lang'ThreadGroup java_instance (** The type of thread groups, that are sets of threads organized into a hierarchy (every group except the initial one has a parent). Threads are added to a group at creation time and cannot change group afterwards. *) val make : ?parent:t -> JavaString.t -> t * Returns a new group with optional parent , and name ; see { java java.lang . ThreadGroup#ThreadGroup(java.lang . ThreadGroup , java.lang . String ) } . {java java.lang.ThreadGroup#ThreadGroup(java.lang.ThreadGroup, java.lang.String)}. *) val active_count : t -> java_int * Returns the number of active threads in this group ( including children groups ) ; see { java java.lang . ThreadGroup#activeCount ( ) } . children groups); see {java java.lang.ThreadGroup#activeCount()}. *) val active_group_count : t -> java_int * Returns the number of active groups in this group ( including children groups ) ; see { java java.lang . ( ) } . groups); see {java java.lang.ThreadGroup#activeGroupCount()}. *) val destroy : t -> unit * Destroys the passed group and all its children groups ; see { java java.lang . ( ) } . @raise Java_exception if the thread group is not empty , or has already been destroyed {java java.lang.ThreadGroup#destroy()}. @raise Java_exception if the thread group is not empty, or has already been destroyed *) val get_max_priority : t -> java_int (** Returns the maximum priority of the group; see {java java.lang.ThreadGroup#getMaxPriority()}. *) val get_name : t -> JavaString.t (** Returns the name of the group; see {java java.lang.ThreadGroup#getName()}. *) val get_parent : t -> t (** Returns the parent of the group, [null] if no such group exists; see {java java.lang.ThreadGroup#getParent()}. *) val interrupt : t -> unit (** Interrupts all thread in the group (including children groups); see {java java.lang.ThreadGroup#interrupt()}. *) val is_daemon : t -> bool * Tests whether the group is a daemon one ; see { java java.lang . ( ) } . {java java.lang.ThreadGroup#isDaemon()}. *) val is_destroyed : t -> bool (** Tests whether the group has been destroyed; see {java java.lang.ThreadGroup#isDestroyed()}. *) val parent_of : t -> t -> bool * [ parent_of p c ] tests whether [ p ] is an ancestor of [ c ] ; see { java java.lang . ThreadGroup#parentOf(java.lang . ThreadGroup ) } . {java java.lang.ThreadGroup#parentOf(java.lang.ThreadGroup)}. *) val set_daemon : t -> bool -> unit * Sets the daemon status of the group . Daemon groups are automatically destroyed when they have neither child group , nor running thread ; see { java java.lang . ThreadGroup#setDaemon(boolean ) } . destroyed when they have neither child group, nor running thread; see {java java.lang.ThreadGroup#setDaemon(boolean)}. *) val set_max_priority : t -> java_int -> unit (** Sets the maximum priority of the group; see {java java.lang.ThreadGroup#setMaxPriority(int)}. *) val enumerate_threads : t -> ?recurse:bool -> java'lang'Thread java_instance JavaReferenceArray.t -> int32 * Enumerates ( recursively by default ) the threads in the group by storing them in the passed array , and returning the number of actually stored threads ; see { java java.lang . . Thread [ ] , boolean ) } . storing them in the passed array, and returning the number of actually stored threads; see {java java.lang.ThreadGroup#enumerate(java.lang.Thread[], boolean)}. *) val enumerate_groups : t -> ?recurse:bool -> java'lang'ThreadGroup java_instance JavaReferenceArray.t -> int32 * Enumerates ( recursively by default ) the groups in the group by storing them in the passed array , and returning the number of actually stored groups ; see { java java.lang . . ThreadGroup [ ] , boolean ) } . storing them in the passed array, and returning the number of actually stored groups; see {java java.lang.ThreadGroup#enumerate(java.lang.ThreadGroup[], boolean)}. *) * { 6 Null value } val null : t (** The [null] value. *) external is_null : t -> bool = "java is_null" (** [is_null obj] returns [true] iff [obj] is equal to [null]. *) external is_not_null : t -> bool = "java is_not_null" (** [is_not_null obj] returns [false] iff [obj] is equal to [null]. *) * { 6 Miscellaneous } val wrap : t -> t option (** [wrap obj] wraps the reference [obj] into an option type: - [Some x] if [obj] is not [null]; - [None] if [obj] is [null]. *) val unwrap : t option -> t (** [unwrap obj] unwraps the option [obj] into a bare reference: - [Some x] is mapped to [x]; - [None] is mapped to [null]. *)
null
https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/threads/threadGroup.mli
ocaml
* Thread groups. * The type of thread groups, that are sets of threads organized into a hierarchy (every group except the initial one has a parent). Threads are added to a group at creation time and cannot change group afterwards. * Returns the maximum priority of the group; see {java java.lang.ThreadGroup#getMaxPriority()}. * Returns the name of the group; see {java java.lang.ThreadGroup#getName()}. * Returns the parent of the group, [null] if no such group exists; see {java java.lang.ThreadGroup#getParent()}. * Interrupts all thread in the group (including children groups); see {java java.lang.ThreadGroup#interrupt()}. * Tests whether the group has been destroyed; see {java java.lang.ThreadGroup#isDestroyed()}. * Sets the maximum priority of the group; see {java java.lang.ThreadGroup#setMaxPriority(int)}. * The [null] value. * [is_null obj] returns [true] iff [obj] is equal to [null]. * [is_not_null obj] returns [false] iff [obj] is equal to [null]. * [wrap obj] wraps the reference [obj] into an option type: - [Some x] if [obj] is not [null]; - [None] if [obj] is [null]. * [unwrap obj] unwraps the option [obj] into a bare reference: - [Some x] is mapped to [x]; - [None] is mapped to [null].
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * 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 3 of the License , or * ( at your option ) any later version . * * 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 program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java 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 3 of the License, or * (at your option) any later version. * * OCaml-Java 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 program. If not, see </>. *) type t = java'lang'ThreadGroup java_instance val make : ?parent:t -> JavaString.t -> t * Returns a new group with optional parent , and name ; see { java java.lang . ThreadGroup#ThreadGroup(java.lang . ThreadGroup , java.lang . String ) } . {java java.lang.ThreadGroup#ThreadGroup(java.lang.ThreadGroup, java.lang.String)}. *) val active_count : t -> java_int * Returns the number of active threads in this group ( including children groups ) ; see { java java.lang . ThreadGroup#activeCount ( ) } . children groups); see {java java.lang.ThreadGroup#activeCount()}. *) val active_group_count : t -> java_int * Returns the number of active groups in this group ( including children groups ) ; see { java java.lang . ( ) } . groups); see {java java.lang.ThreadGroup#activeGroupCount()}. *) val destroy : t -> unit * Destroys the passed group and all its children groups ; see { java java.lang . ( ) } . @raise Java_exception if the thread group is not empty , or has already been destroyed {java java.lang.ThreadGroup#destroy()}. @raise Java_exception if the thread group is not empty, or has already been destroyed *) val get_max_priority : t -> java_int val get_name : t -> JavaString.t val get_parent : t -> t val interrupt : t -> unit val is_daemon : t -> bool * Tests whether the group is a daemon one ; see { java java.lang . ( ) } . {java java.lang.ThreadGroup#isDaemon()}. *) val is_destroyed : t -> bool val parent_of : t -> t -> bool * [ parent_of p c ] tests whether [ p ] is an ancestor of [ c ] ; see { java java.lang . ThreadGroup#parentOf(java.lang . ThreadGroup ) } . {java java.lang.ThreadGroup#parentOf(java.lang.ThreadGroup)}. *) val set_daemon : t -> bool -> unit * Sets the daemon status of the group . Daemon groups are automatically destroyed when they have neither child group , nor running thread ; see { java java.lang . ThreadGroup#setDaemon(boolean ) } . destroyed when they have neither child group, nor running thread; see {java java.lang.ThreadGroup#setDaemon(boolean)}. *) val set_max_priority : t -> java_int -> unit val enumerate_threads : t -> ?recurse:bool -> java'lang'Thread java_instance JavaReferenceArray.t -> int32 * Enumerates ( recursively by default ) the threads in the group by storing them in the passed array , and returning the number of actually stored threads ; see { java java.lang . . Thread [ ] , boolean ) } . storing them in the passed array, and returning the number of actually stored threads; see {java java.lang.ThreadGroup#enumerate(java.lang.Thread[], boolean)}. *) val enumerate_groups : t -> ?recurse:bool -> java'lang'ThreadGroup java_instance JavaReferenceArray.t -> int32 * Enumerates ( recursively by default ) the groups in the group by storing them in the passed array , and returning the number of actually stored groups ; see { java java.lang . . ThreadGroup [ ] , boolean ) } . storing them in the passed array, and returning the number of actually stored groups; see {java java.lang.ThreadGroup#enumerate(java.lang.ThreadGroup[], boolean)}. *) * { 6 Null value } val null : t external is_null : t -> bool = "java is_null" external is_not_null : t -> bool = "java is_not_null" * { 6 Miscellaneous } val wrap : t -> t option val unwrap : t option -> t
1f0d83382b5f71ee66c19cb7c920a747235faab1825ea9dad7590302cb059fd2
airbus-seclab/bincat
x64Imports.ml
This file is part of BinCAT . Copyright 2014 - 2021 - Airbus BinCAT 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 . BinCAT 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 BinCAT . If not , see < / > . This file is part of BinCAT. Copyright 2014-2021 - Airbus BinCAT 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. BinCAT 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 BinCAT. If not, see </>. *) module L = Log.Make(struct let name = "x64Imports" end) module Make(D: Domain.T)(Stubs: Stubs.T with type domain_t := D.t) = struct open Asm let reg r = V (T (Register.of_name r)) let const x sz = Const (Data.Word.of_int (Z.of_int x) sz) let tbl: (Data.Address.t, Asm.import_desc_t * Asm.calling_convention_t) Hashtbl.t = Hashtbl.create 5 RDI , RSI , RDX , RCX , R8 , R9 , XMM0–7 let sysv_calling_convention () = { return = reg "rax"; callee_cleanup = (fun _x -> [ ]) ; arguments = function | 0 -> (reg "rdi") | 1 -> (reg "rsi") | 2 -> (reg "rdx") | 3 -> (reg "rcx") | 4 -> (reg "r8") | 5 -> (reg "r9") | n -> M (BinOp (Add, Lval (reg "rsp"), Const (Data.Word.of_int (Z.of_int ((n-5) * !Config.stack_width / 8)) !Config.stack_width)), !Config.stack_width) } RCX / XMM0 , RDX / XMM1 , R8 / XMM2 , R9 / XMM3 let ms_calling_convention () = { return = reg "rax"; callee_cleanup = (fun _x -> [ ]) ; arguments = function | 0 -> (reg "rcx") | 1 -> (reg "rdx") | 2 -> (reg "r8") | 3 -> (reg "r9") | n -> M (BinOp (Add, Lval (reg "rsp"), Const (Data.Word.of_int (Z.of_int ((n-3) * !Config.stack_width / 8)) !Config.stack_width)), !Config.stack_width) } let set_first_arg e = let r = if !Config.call_conv = Config.SYSV then (reg "rdi") else (reg "rcx") in [Set (r, e)] let unset_first_arg () = [] let get_local_callconv cc = match cc with | Config.SYSV -> sysv_calling_convention () | Config.MS -> ms_calling_convention () | c -> L.abort (fun p -> p "Calling convention [%s] not supported for x64 architecture" (Config.call_conv_to_string c)) let get_callconv () = get_local_callconv !Config.call_conv let stub_stmts_from_name name callconv = if Hashtbl.mem Stubs.stubs name then [ Directive (Stub (name, callconv)) ] else [ Directive (Forget (reg "rax")) ] let stack_width () = !Config.stack_width/8 let init_imports () = let default_cc = get_callconv () in Hashtbl.iter (fun adrs (libname,fname) -> let tainting_pro,tainting_epi, cc = Rules.tainting_rule_stmts libname fname (fun cc -> get_local_callconv cc) in let cc' = match cc with | Some cc -> cc | None -> default_cc in let typing_pro,typing_epi = Rules.typing_rule_stmts fname cc' in let stub_stmts = stub_stmts_from_name fname cc' in let fundesc:Asm.import_desc_t = { name = fname; libname = libname; prologue = typing_pro @ tainting_pro; stub = stub_stmts @ [ Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ] ; epilogue = typing_epi @ tainting_epi ; ret_addr = Lval(M (BinOp(Sub, Lval (reg "rsp"), const (stack_width()) 64),!Config.stack_width)) ; } in Hashtbl.replace tbl (Data.Address.global_of_int adrs) (fundesc, cc') ) Config.import_tbl let skip fdesc a = match fdesc with | Some (fdesc', cc) -> if Hashtbl.mem Config.funSkipTbl (Config.Fun_name fdesc'.Asm.name) then let stmts = [Directive (Skip (Asm.Fun_name fdesc'.Asm.name, cc)) ; Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ] in { fdesc' with stub = stmts } else fdesc' | None -> let ia = Data.Address.to_int a in if Hashtbl.mem Config.funSkipTbl (Config.Fun_addr ia) then let arg_nb, _ = Hashtbl.find Config.funSkipTbl (Config.Fun_addr ia) in { name = ""; libname = ""; prologue = []; stub = [Directive (Skip (Asm.Fun_addr a, get_callconv())) ; Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ]; epilogue = []; (* the return address expression is evaluated *after* cleaning up the stack (in stdcall), * so we need to look it up at the correct place, depending on the number of args *) ret_addr = if !Config.call_conv == Config.STDCALL then Lval(M (BinOp(Sub, Lval (reg "rsp"), const (((Z.to_int arg_nb)+1) * stack_width()) 64),!Config.stack_width)) else Lval(M (BinOp(Sub, Lval (reg "rsp"), const (stack_width()) 64),!Config.stack_width)); } else raise Not_found let init () = Stubs.init (); init_imports () end
null
https://raw.githubusercontent.com/airbus-seclab/bincat/e79cab4fad8b0e33e23f00be277ef79b4e9a3198/ocaml/src/disassembly/x64Imports.ml
ocaml
the return address expression is evaluated *after* cleaning up the stack (in stdcall), * so we need to look it up at the correct place, depending on the number of args
This file is part of BinCAT . Copyright 2014 - 2021 - Airbus BinCAT 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 . BinCAT 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 BinCAT . If not , see < / > . This file is part of BinCAT. Copyright 2014-2021 - Airbus BinCAT 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. BinCAT 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 BinCAT. If not, see </>. *) module L = Log.Make(struct let name = "x64Imports" end) module Make(D: Domain.T)(Stubs: Stubs.T with type domain_t := D.t) = struct open Asm let reg r = V (T (Register.of_name r)) let const x sz = Const (Data.Word.of_int (Z.of_int x) sz) let tbl: (Data.Address.t, Asm.import_desc_t * Asm.calling_convention_t) Hashtbl.t = Hashtbl.create 5 RDI , RSI , RDX , RCX , R8 , R9 , XMM0–7 let sysv_calling_convention () = { return = reg "rax"; callee_cleanup = (fun _x -> [ ]) ; arguments = function | 0 -> (reg "rdi") | 1 -> (reg "rsi") | 2 -> (reg "rdx") | 3 -> (reg "rcx") | 4 -> (reg "r8") | 5 -> (reg "r9") | n -> M (BinOp (Add, Lval (reg "rsp"), Const (Data.Word.of_int (Z.of_int ((n-5) * !Config.stack_width / 8)) !Config.stack_width)), !Config.stack_width) } RCX / XMM0 , RDX / XMM1 , R8 / XMM2 , R9 / XMM3 let ms_calling_convention () = { return = reg "rax"; callee_cleanup = (fun _x -> [ ]) ; arguments = function | 0 -> (reg "rcx") | 1 -> (reg "rdx") | 2 -> (reg "r8") | 3 -> (reg "r9") | n -> M (BinOp (Add, Lval (reg "rsp"), Const (Data.Word.of_int (Z.of_int ((n-3) * !Config.stack_width / 8)) !Config.stack_width)), !Config.stack_width) } let set_first_arg e = let r = if !Config.call_conv = Config.SYSV then (reg "rdi") else (reg "rcx") in [Set (r, e)] let unset_first_arg () = [] let get_local_callconv cc = match cc with | Config.SYSV -> sysv_calling_convention () | Config.MS -> ms_calling_convention () | c -> L.abort (fun p -> p "Calling convention [%s] not supported for x64 architecture" (Config.call_conv_to_string c)) let get_callconv () = get_local_callconv !Config.call_conv let stub_stmts_from_name name callconv = if Hashtbl.mem Stubs.stubs name then [ Directive (Stub (name, callconv)) ] else [ Directive (Forget (reg "rax")) ] let stack_width () = !Config.stack_width/8 let init_imports () = let default_cc = get_callconv () in Hashtbl.iter (fun adrs (libname,fname) -> let tainting_pro,tainting_epi, cc = Rules.tainting_rule_stmts libname fname (fun cc -> get_local_callconv cc) in let cc' = match cc with | Some cc -> cc | None -> default_cc in let typing_pro,typing_epi = Rules.typing_rule_stmts fname cc' in let stub_stmts = stub_stmts_from_name fname cc' in let fundesc:Asm.import_desc_t = { name = fname; libname = libname; prologue = typing_pro @ tainting_pro; stub = stub_stmts @ [ Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ] ; epilogue = typing_epi @ tainting_epi ; ret_addr = Lval(M (BinOp(Sub, Lval (reg "rsp"), const (stack_width()) 64),!Config.stack_width)) ; } in Hashtbl.replace tbl (Data.Address.global_of_int adrs) (fundesc, cc') ) Config.import_tbl let skip fdesc a = match fdesc with | Some (fdesc', cc) -> if Hashtbl.mem Config.funSkipTbl (Config.Fun_name fdesc'.Asm.name) then let stmts = [Directive (Skip (Asm.Fun_name fdesc'.Asm.name, cc)) ; Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ] in { fdesc' with stub = stmts } else fdesc' | None -> let ia = Data.Address.to_int a in if Hashtbl.mem Config.funSkipTbl (Config.Fun_addr ia) then let arg_nb, _ = Hashtbl.find Config.funSkipTbl (Config.Fun_addr ia) in { name = ""; libname = ""; prologue = []; stub = [Directive (Skip (Asm.Fun_addr a, get_callconv())) ; Set(reg "rsp", BinOp(Add, Lval (reg "rsp"), const (stack_width()) 64)) ]; epilogue = []; ret_addr = if !Config.call_conv == Config.STDCALL then Lval(M (BinOp(Sub, Lval (reg "rsp"), const (((Z.to_int arg_nb)+1) * stack_width()) 64),!Config.stack_width)) else Lval(M (BinOp(Sub, Lval (reg "rsp"), const (stack_width()) 64),!Config.stack_width)); } else raise Not_found let init () = Stubs.init (); init_imports () end
6b3a6c40fafac92bf1530c871fac0d11a2634650e8f7f92bed9f3f7c10bb7a46
gonimo/gonimo
AcceptInvitation.hs
# LANGUAGE RecursiveDo # module Gonimo.Client.AcceptInvitation ( module UI ) where import Gonimo.Client.AcceptInvitation.UI as UI
null
https://raw.githubusercontent.com/gonimo/gonimo/f4072db9e56f0c853a9f07e048e254eaa671283b/front/src/Gonimo/Client/AcceptInvitation.hs
haskell
# LANGUAGE RecursiveDo # module Gonimo.Client.AcceptInvitation ( module UI ) where import Gonimo.Client.AcceptInvitation.UI as UI
1b7abcf9b5367625ab1d2005f32182358b90012d34085b180232e824b7b9673b
bradparker/bradparker.com
Home.hs
# LANGUAGE BlockArguments # # LANGUAGE DataKinds # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE NoFieldSelectors # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # OPTIONS_GHC -Wall # module Home (render) where import qualified Data.ByteString.Lazy as LBS import Data.Foldable (traverse_) import qualified Document import Post (Post(..)) import qualified PostSummary import Text.Blaze.Html (Html, (!)) import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A render :: [Post] -> LBS.ByteString render = renderHtml . component component :: [Post] -> Html component posts = Document.component (Document.Props "Home" "/") do H.article do (H.section ! A.class_ "mw7 center pa3") do (H.h1 ! A.class_ "f2 ttu tc founders-grotesk-extra-condensed lh-title mt2 mb2") do (H.span ! A.class_ "fine-underline") do "Hi, I'm" H.img ! A.alt "Brad" ! A.src "/assets/images/brad.jpg" ! A.class_ "mw6 w-100 center db" (H.span ! A.class_ "fine-underline") do "Pleased to meet you." (H.footer ! A.class_ "bt b--near-white") do (H.section ! A.class_ "mw7 center flex flex-wrap lh-copy pa3") do (H.a ! A.class_ "link hover-dark-green mr1" ! A.href "/@brad" ! A.rel "me") do "bne.social/@brad" (H.span ! A.class_ "moon-gray mr1") do " / " (H.a ! A.class_ "link hover-dark-green" ! A.href "" ! A.rel "me") do "github.com/bradparker" H.hr ! A.class_ "ba-0 bt bw3 b--near-white" traverse_ PostSummary.component posts
null
https://raw.githubusercontent.com/bradparker/bradparker.com/843775de5d7939939c67043d9233706df2d7fd63/bradparker.com/usr/local/src/bradparker.com/builder/Home.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
# LANGUAGE BlockArguments # # LANGUAGE DataKinds # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE NoFieldSelectors # # OPTIONS_GHC -Wall # module Home (render) where import qualified Data.ByteString.Lazy as LBS import Data.Foldable (traverse_) import qualified Document import Post (Post(..)) import qualified PostSummary import Text.Blaze.Html (Html, (!)) import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A render :: [Post] -> LBS.ByteString render = renderHtml . component component :: [Post] -> Html component posts = Document.component (Document.Props "Home" "/") do H.article do (H.section ! A.class_ "mw7 center pa3") do (H.h1 ! A.class_ "f2 ttu tc founders-grotesk-extra-condensed lh-title mt2 mb2") do (H.span ! A.class_ "fine-underline") do "Hi, I'm" H.img ! A.alt "Brad" ! A.src "/assets/images/brad.jpg" ! A.class_ "mw6 w-100 center db" (H.span ! A.class_ "fine-underline") do "Pleased to meet you." (H.footer ! A.class_ "bt b--near-white") do (H.section ! A.class_ "mw7 center flex flex-wrap lh-copy pa3") do (H.a ! A.class_ "link hover-dark-green mr1" ! A.href "/@brad" ! A.rel "me") do "bne.social/@brad" (H.span ! A.class_ "moon-gray mr1") do " / " (H.a ! A.class_ "link hover-dark-green" ! A.href "" ! A.rel "me") do "github.com/bradparker" H.hr ! A.class_ "ba-0 bt bw3 b--near-white" traverse_ PostSummary.component posts
924cf1f8f6e7efdc0ab6c5e90ced186a2dc732cb4cd90344aed13f7ca6576a72
elbrujohalcon/witchcraft
magic.erl
@doc A module used to test some erlang magic for 's blog -module(magic). -export([whats_in/1, say/1]). -spec whats_in(term()) -> term(). whats_in(this_hat) -> case get(magic) of undefined -> nothing; Something -> Something end. -spec say(term()) -> ok. say(abracadabra) -> _ = put(magic, 'a rabbit'), ok.
null
https://raw.githubusercontent.com/elbrujohalcon/witchcraft/050e91f028a50874347fea9dc552a0e0a056018f/src/magic.erl
erlang
@doc A module used to test some erlang magic for 's blog -module(magic). -export([whats_in/1, say/1]). -spec whats_in(term()) -> term(). whats_in(this_hat) -> case get(magic) of undefined -> nothing; Something -> Something end. -spec say(term()) -> ok. say(abracadabra) -> _ = put(magic, 'a rabbit'), ok.
6bba563537da172c07715b9ea1d74b37807fec25a80490c69278e5bb7fa2775b
GrammaTech/sel
scopes-1.lisp
(let ((a 1)) (let ((b 2)) (let ((c 3)) (list a b c))))
null
https://raw.githubusercontent.com/GrammaTech/sel/a59174c02a454e8d588614e221cf281260cf12f8/test/etc/lisp-scopes/scopes-1.lisp
lisp
(let ((a 1)) (let ((b 2)) (let ((c 3)) (list a b c))))
4a1d873089acc7f4b5945882a2cf83ba6f4c4ba18595b30e3e533d3c826a7d62
FranklinChen/hugs98-plus-Sep2006
VertexArrays.hs
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.VertexArrays Copyright : ( c ) 2002 - 2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : portable -- This module corresponds to section 2.8 ( Vertex Arrays ) of the OpenGL 1.5 -- specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.VertexArrays ( -- * Describing Data for the Arrays NumComponents, DataType(..), Stride, VertexArrayDescriptor(..), * Specifying Data for the Arrays ClientArrayType(..), arrayPointer, InterleavedArrays(..), interleavedArrays, -- * Enabling Arrays clientState, clientActiveTexture, -- * Dereferencing and Rendering ArrayIndex, NumArrayIndices, NumIndexBlocks, arrayElement, drawArrays, multiDrawArrays, drawElements, multiDrawElements, drawRangeElements, maxElementsVertices, maxElementsIndices, lockArrays, primitiveRestartIndex ) where import Foreign.Marshal.Alloc ( alloca ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(peek) ) import Graphics.Rendering.OpenGL.GL.Capability ( EnableCap(CapVertexArray,CapNormalArray,CapColorArray,CapIndexArray, CapTextureCoordArray,CapEdgeFlagArray,CapFogCoordArray, CapSecondaryColorArray,CapMatrixIndexArray,CapPrimitiveRestart), makeCapability ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLint, GLuint, GLsizei, Capability(Enabled) ) import Graphics.Rendering.OpenGL.GL.DataType ( DataType(..), marshalDataType, unmarshalDataType ) import Graphics.Rendering.OpenGL.GL.Extensions ( FunPtr, unsafePerformIO, Invoker, getProcAddress ) import Graphics.Rendering.OpenGL.GL.QueryUtils ( GetPName(GetVertexArraySize,GetVertexArrayType,GetVertexArrayStride, GetNormalArrayType,GetNormalArrayStride,GetColorArraySize, GetColorArrayType,GetColorArrayStride,GetSecondaryColorArraySize, GetSecondaryColorArrayType,GetSecondaryColorArrayStride, GetIndexArrayType,GetIndexArrayStride, GetFogCoordArrayType,GetFogCoordArrayStride, GetTextureCoordArraySize,GetTextureCoordArrayType, GetTextureCoordArrayStride,GetEdgeFlagArrayStride, GetMaxElementsVertices,GetMaxElementsIndices, GetClientActiveTexture,GetArrayElementLockFirst, GetArrayElementLockCount,GetPrimitiveRestartIndex), getInteger1, getEnum1, getSizei1 ) import Graphics.Rendering.OpenGL.GL.PrimitiveMode ( marshalPrimitiveMode ) import Graphics.Rendering.OpenGL.GL.BeginEnd ( PrimitiveMode ) import Graphics.Rendering.OpenGL.GL.StateVar ( HasGetter(get), GettableStateVar, makeGettableStateVar, StateVar, makeStateVar ) import Graphics.Rendering.OpenGL.GL.Texturing.TextureUnit ( TextureUnit, marshalTextureUnit, unmarshalTextureUnit ) import Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( recordInvalidEnum, recordInvalidValue ) -------------------------------------------------------------------------------- #include "HsOpenGLExt.h" -------------------------------------------------------------------------------- type NumComponents = GLint type Stride = GLsizei data VertexArrayDescriptor a = VertexArrayDescriptor !NumComponents !DataType !Stride !(Ptr a) #ifdef __HADDOCK__ -- Help Haddock a bit, because it doesn't do any instance inference. instance Eq (VertexArrayDescriptor a) instance Ord (VertexArrayDescriptor a) instance Show (VertexArrayDescriptor a) #else deriving ( Eq, Ord, Show ) #endif noVertexArrayDescriptor :: VertexArrayDescriptor a noVertexArrayDescriptor = VertexArrayDescriptor 0 Byte 0 nullPtr -------------------------------------------------------------------------------- data ClientArrayType = VertexArray | NormalArray | ColorArray | IndexArray | TextureCoordArray | EdgeFlagArray | FogCoordArray | SecondaryColorArray | MatrixIndexArray deriving ( Eq, Ord, Show ) marshalClientArrayType :: ClientArrayType -> GLenum marshalClientArrayType x = case x of VertexArray -> 0x8074 NormalArray -> 0x8075 ColorArray -> 0x8076 IndexArray -> 0x8077 TextureCoordArray -> 0x8078 EdgeFlagArray -> 0x8079 FogCoordArray -> 0x8457 SecondaryColorArray -> 0x845e MatrixIndexArray -> 0x8844 -- Hmmm... clientArrayTypeToEnableCap :: ClientArrayType -> EnableCap clientArrayTypeToEnableCap x = case x of VertexArray -> CapVertexArray NormalArray -> CapNormalArray ColorArray -> CapColorArray IndexArray -> CapIndexArray TextureCoordArray -> CapTextureCoordArray EdgeFlagArray -> CapEdgeFlagArray FogCoordArray -> CapFogCoordArray SecondaryColorArray -> CapSecondaryColorArray MatrixIndexArray -> CapMatrixIndexArray -------------------------------------------------------------------------------- arrayPointer :: ClientArrayType -> StateVar (VertexArrayDescriptor a) arrayPointer t = case t of VertexArray -> vertexPointer NormalArray -> normalPointer ColorArray -> colorPointer IndexArray -> indexPointer TextureCoordArray -> texCoordPointer EdgeFlagArray -> edgeFlagPointer FogCoordArray -> fogCoordPointer SecondaryColorArray -> secondaryColorPointer MatrixIndexArray -> makeStateVar (do recordInvalidEnum ; return noVertexArrayDescriptor) (const recordInvalidEnum) check :: Bool -> IO () -> IO () check flag val = if flag then val else recordInvalidValue -------------------------------------------------------------------------------- vertexPointer :: StateVar (VertexArrayDescriptor a) vertexPointer = makeStateVar getVertexPointer setVertexPointer getVertexPointer :: IO (VertexArrayDescriptor a) getVertexPointer = do n <- getInteger1 id GetVertexArraySize d <- getEnum1 unmarshalDataType GetVertexArrayType s <- getInteger1 fromIntegral GetVertexArrayStride p <- getPointer VertexArrayPointer return $ VertexArrayDescriptor n d s p setVertexPointer :: VertexArrayDescriptor a -> IO () setVertexPointer (VertexArrayDescriptor n d s p) = glVertexPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glVertexPointer" glVertexPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- normalPointer :: StateVar (VertexArrayDescriptor a) normalPointer = makeStateVar getNormalPointer setNormalPointer getNormalPointer :: IO (VertexArrayDescriptor a) getNormalPointer = do d <- getEnum1 unmarshalDataType GetNormalArrayType s <- getInteger1 fromIntegral GetNormalArrayStride p <- getPointer NormalArrayPointer return $ VertexArrayDescriptor 3 d s p setNormalPointer :: VertexArrayDescriptor a -> IO () setNormalPointer (VertexArrayDescriptor n d s p) = check (n == 3) $ glNormalPointer (marshalDataType d) s p foreign import CALLCONV unsafe "glNormalPointer" glNormalPointer :: GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- colorPointer :: StateVar (VertexArrayDescriptor a) colorPointer = makeStateVar getColorPointer setColorPointer getColorPointer :: IO (VertexArrayDescriptor a) getColorPointer = do n <- getInteger1 id GetColorArraySize d <- getEnum1 unmarshalDataType GetColorArrayType s <- getInteger1 fromIntegral GetColorArrayStride p <- getPointer ColorArrayPointer return $ VertexArrayDescriptor n d s p setColorPointer :: VertexArrayDescriptor a -> IO () setColorPointer (VertexArrayDescriptor n d s p) = check (n == 3 || n == 4) $ glColorPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glColorPointer" glColorPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- indexPointer :: StateVar (VertexArrayDescriptor a) indexPointer = makeStateVar getIndexPointer setIndexPointer getIndexPointer :: IO (VertexArrayDescriptor a) getIndexPointer = do d <- getEnum1 unmarshalDataType GetIndexArrayType s <- getInteger1 fromIntegral GetIndexArrayStride p <- getPointer IndexArrayPointer return $ VertexArrayDescriptor 1 d s p setIndexPointer :: VertexArrayDescriptor a -> IO () setIndexPointer (VertexArrayDescriptor n d s p) = check (n == 1) $ glIndexPointer (marshalDataType d) s p foreign import CALLCONV unsafe "glIndexPointer" glIndexPointer :: GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- texCoordPointer :: StateVar (VertexArrayDescriptor a) texCoordPointer = makeStateVar getTexCoordPointer setTexCoordPointer getTexCoordPointer :: IO (VertexArrayDescriptor a) getTexCoordPointer = do n <- getInteger1 id GetTextureCoordArraySize d <- getEnum1 unmarshalDataType GetTextureCoordArrayType s <- getInteger1 fromIntegral GetTextureCoordArrayStride p <- getPointer TextureCoordArrayPointer return $ VertexArrayDescriptor n d s p setTexCoordPointer :: VertexArrayDescriptor a -> IO () setTexCoordPointer (VertexArrayDescriptor n d s p) = glTexCoordPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glTexCoordPointer" glTexCoordPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- edgeFlagPointer :: StateVar (VertexArrayDescriptor a) edgeFlagPointer = makeStateVar getEdgeFlagPointer setEdgeFlagPointer getEdgeFlagPointer :: IO (VertexArrayDescriptor a) getEdgeFlagPointer = do s <- getInteger1 fromIntegral GetEdgeFlagArrayStride p <- getPointer EdgeFlagArrayPointer return $ VertexArrayDescriptor 1 UnsignedByte s p setEdgeFlagPointer :: VertexArrayDescriptor a -> IO () setEdgeFlagPointer (VertexArrayDescriptor n d s p) = check (n == 1 && d == UnsignedByte) $ glEdgeFlagPointer s p foreign import CALLCONV unsafe "glEdgeFlagPointer" glEdgeFlagPointer :: GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- fogCoordPointer :: StateVar (VertexArrayDescriptor a) fogCoordPointer = makeStateVar getFogCoordPointer setFogCoordPointer getFogCoordPointer :: IO (VertexArrayDescriptor a) getFogCoordPointer = do d <- getEnum1 unmarshalDataType GetFogCoordArrayType s <- getInteger1 fromIntegral GetFogCoordArrayStride p <- getPointer FogCoordArrayPointer return $ VertexArrayDescriptor 1 d s p setFogCoordPointer :: VertexArrayDescriptor a -> IO () setFogCoordPointer (VertexArrayDescriptor n d s p) = check (n == 1) $ glFogCoordPointerEXT (marshalDataType d) s p EXTENSION_ENTRY("GL_EXT_fog_coord or OpenGL 1.4",glFogCoordPointerEXT,GLenum -> GLsizei -> Ptr a -> IO ()) -------------------------------------------------------------------------------- secondaryColorPointer :: StateVar (VertexArrayDescriptor a) secondaryColorPointer = makeStateVar getSecondaryColorPointer setSecondaryColorPointer getSecondaryColorPointer :: IO (VertexArrayDescriptor a) getSecondaryColorPointer = do n <- getInteger1 id GetSecondaryColorArraySize d <- getEnum1 unmarshalDataType GetSecondaryColorArrayType s <- getInteger1 fromIntegral GetSecondaryColorArrayStride p <- getPointer SecondaryColorArrayPointer return $ VertexArrayDescriptor n d s p setSecondaryColorPointer :: (VertexArrayDescriptor a) -> IO () setSecondaryColorPointer (VertexArrayDescriptor n d s p) = glSecondaryColorPointerEXT n (marshalDataType d) s p EXTENSION_ENTRY("GL_EXT_secondary_color or OpenGL 1.4",glSecondaryColorPointerEXT,GLint -> GLenum -> GLsizei -> Ptr a -> IO ()) -------------------------------------------------------------------------------- data InterleavedArrays = V2f | V3f | C4ubV2f | C4ubV3f | C3fV3f | N3fV3f | C4fN3fV3f | T2fV3f | T4fV4f | T2fC4ubV3f | T2fC3fV3f | T2fN3fV3f | T2fC4fN3fV3f | T4fC4fN3fV4f deriving ( Eq, Ord, Show ) marshalInterleavedArrays :: InterleavedArrays -> GLenum marshalInterleavedArrays x = case x of V2f -> 0x2a20 V3f -> 0x2a21 C4ubV2f -> 0x2a22 C4ubV3f -> 0x2a23 C3fV3f -> 0x2a24 N3fV3f -> 0x2a25 C4fN3fV3f -> 0x2a26 T2fV3f -> 0x2a27 T4fV4f -> 0x2a28 T2fC4ubV3f -> 0x2a29 T2fC3fV3f -> 0x2a2a T2fN3fV3f -> 0x2a2b T2fC4fN3fV3f -> 0x2a2c T4fC4fN3fV4f -> 0x2a2d -------------------------------------------------------------------------------- interleavedArrays :: InterleavedArrays -> Stride -> Ptr a -> IO () interleavedArrays = glInterleavedArrays . marshalInterleavedArrays foreign import CALLCONV unsafe "glInterleavedArrays" glInterleavedArrays :: GLenum -> GLsizei -> Ptr a -> IO () -------------------------------------------------------------------------------- clientState :: ClientArrayType -> StateVar Capability clientState arrayType = makeStateVar (getClientState arrayType) (setClientState arrayType) getClientState :: ClientArrayType -> IO Capability getClientState = get . makeCapability . clientArrayTypeToEnableCap setClientState :: ClientArrayType -> Capability -> IO () setClientState arrayType val = (if val == Enabled then glEnableClientState else glDisableClientState) (marshalClientArrayType arrayType) foreign import CALLCONV unsafe "glEnableClientState" glEnableClientState :: GLenum -> IO () foreign import CALLCONV unsafe "glDisableClientState" glDisableClientState :: GLenum -> IO () -------------------------------------------------------------------------------- clientActiveTexture :: StateVar TextureUnit clientActiveTexture = makeStateVar (getEnum1 unmarshalTextureUnit GetClientActiveTexture) (glClientActiveTextureARB . marshalTextureUnit) EXTENSION_ENTRY("GL_ARB_multitexture or OpenGL 1.3",glClientActiveTextureARB,GLenum -> IO ()) -------------------------------------------------------------------------------- type ArrayIndex = GLint type NumArrayIndices = GLsizei type NumIndexBlocks = GLsizei -------------------------------------------------------------------------------- arrayElement :: ArrayIndex -> IO () arrayElement = glArrayElement foreign import CALLCONV unsafe "glArrayElement" glArrayElement :: GLint -> IO () drawArrays :: PrimitiveMode -> ArrayIndex -> NumArrayIndices -> IO () drawArrays = glDrawArrays . marshalPrimitiveMode foreign import CALLCONV unsafe "glDrawArrays" glDrawArrays :: GLenum -> GLint -> GLsizei -> IO () multiDrawArrays :: PrimitiveMode -> Ptr ArrayIndex -> Ptr NumArrayIndices -> NumIndexBlocks -> IO () multiDrawArrays = glMultiDrawArraysEXT . marshalPrimitiveMode EXTENSION_ENTRY("GL_EXT_multi_draw_arrays or OpenGL 1.4",glMultiDrawArraysEXT,GLenum -> Ptr ArrayIndex -> Ptr GLsizei -> GLsizei -> IO ()) drawElements :: PrimitiveMode -> NumArrayIndices -> DataType -> Ptr a -> IO () drawElements m c = glDrawElements (marshalPrimitiveMode m) c . marshalDataType foreign import CALLCONV unsafe "glDrawElements" glDrawElements :: GLenum -> GLsizei -> GLenum -> Ptr a -> IO () multiDrawElements :: PrimitiveMode -> Ptr NumArrayIndices -> DataType -> Ptr (Ptr a) -> NumIndexBlocks -> IO () multiDrawElements m c = glMultiDrawElementsEXT (marshalPrimitiveMode m) c . marshalDataType EXTENSION_ENTRY("GL_EXT_multi_draw_arrays or OpenGL 1.4",glMultiDrawElementsEXT,GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> IO ()) drawRangeElements :: PrimitiveMode -> (ArrayIndex, ArrayIndex) -> NumArrayIndices -> DataType -> Ptr a -> IO () drawRangeElements m (s, e) c = glDrawRangeElementsEXT (marshalPrimitiveMode m) (fromIntegral s) (fromIntegral e) c . marshalDataType EXTENSION_ENTRY("GL_EXT_draw_range_elements or OpenGL 1.2",glDrawRangeElementsEXT,GLenum -> GLuint -> GLuint -> GLsizei -> GLenum -> Ptr a -> IO ()) maxElementsVertices :: GettableStateVar NumArrayIndices maxElementsVertices = makeGettableStateVar (getSizei1 id GetMaxElementsVertices) maxElementsIndices :: GettableStateVar NumArrayIndices maxElementsIndices = makeGettableStateVar (getSizei1 id GetMaxElementsIndices) -------------------------------------------------------------------------------- lockArrays :: StateVar (Maybe (ArrayIndex, NumArrayIndices)) lockArrays = makeStateVar getLockArrays setLockArrays getLockArrays :: IO (Maybe (ArrayIndex, NumArrayIndices)) getLockArrays = do count <- getInteger1 fromIntegral GetArrayElementLockCount if count > 0 then do first <- getInteger1 id GetArrayElementLockFirst return $ Just (first, count) else return Nothing setLockArrays :: Maybe (ArrayIndex, NumArrayIndices) -> IO () setLockArrays = maybe glUnlockArraysEXT (uncurry glLockArraysEXT) EXTENSION_ENTRY("GL_EXT_compiled_vertex_array",glLockArraysEXT,GLint -> GLsizei -> IO ()) EXTENSION_ENTRY("GL_EXT_compiled_vertex_array",glUnlockArraysEXT,IO ()) -------------------------------------------------------------------------------- -- We almost could use makeStateVarMaybe below, but, alas, this is client state. primitiveRestartIndex :: StateVar (Maybe ArrayIndex) primitiveRestartIndex = makeStateVar getPrimitiverestartIndex setPrimitiverestartIndex getPrimitiverestartIndex :: IO (Maybe ArrayIndex) getPrimitiverestartIndex = do state <- get (makeCapability CapPrimitiveRestart) if state == Enabled then fmap Just $ getInteger1 fromIntegral GetPrimitiveRestartIndex else return Nothing setPrimitiverestartIndex :: Maybe ArrayIndex -> IO () setPrimitiverestartIndex maybeIdx = case maybeIdx of Nothing -> glDisableClientState primitiveRestartNV Just idx -> do glEnableClientState primitiveRestartNV glPrimitiveRestartIndexNV (fromIntegral idx) ToDo : HACK ! EXTENSION_ENTRY("GL_NV_primitive_restart",glPrimitiveRestartIndexNV,GLuint -> IO ()) -------------------------------------------------------------------------------- data GetPointervPName = VertexArrayPointer | NormalArrayPointer | ColorArrayPointer | IndexArrayPointer | TextureCoordArrayPointer | EdgeFlagArrayPointer | FogCoordArrayPointer | SecondaryColorArrayPointer | FeedbackBufferPointer | SelectionBufferPointer | WeightArrayPointer | MatrixIndexArrayPointer marshalGetPointervPName :: GetPointervPName -> GLenum marshalGetPointervPName x = case x of VertexArrayPointer -> 0x808e NormalArrayPointer -> 0x808f ColorArrayPointer -> 0x8090 IndexArrayPointer -> 0x8091 TextureCoordArrayPointer -> 0x8092 EdgeFlagArrayPointer -> 0x8093 FogCoordArrayPointer -> 0x8456 SecondaryColorArrayPointer -> 0x845d FeedbackBufferPointer -> 0xdf0 SelectionBufferPointer -> 0xdf3 WeightArrayPointer -> 0x86ac MatrixIndexArrayPointer -> 0x8849 -------------------------------------------------------------------------------- getPointer :: GetPointervPName -> IO (Ptr a) getPointer n = alloca $ \buf -> do glGetPointerv (marshalGetPointervPName n) buf peek buf foreign import CALLCONV unsafe "glGetPointerv" glGetPointerv :: GLenum -> Ptr (Ptr a) -> IO ()
null
https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenGL/Graphics/Rendering/OpenGL/GL/VertexArrays.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.Rendering.OpenGL.GL.VertexArrays License : BSD-style (see the file libraries/OpenGL/LICENSE) Maintainer : Stability : provisional Portability : portable specs. ------------------------------------------------------------------------------ * Describing Data for the Arrays * Enabling Arrays * Dereferencing and Rendering ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Help Haddock a bit, because it doesn't do any instance inference. ------------------------------------------------------------------------------ Hmmm... ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ We almost could use makeStateVarMaybe below, but, alas, this is client state. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Copyright : ( c ) 2002 - 2005 This module corresponds to section 2.8 ( Vertex Arrays ) of the OpenGL 1.5 module Graphics.Rendering.OpenGL.GL.VertexArrays ( NumComponents, DataType(..), Stride, VertexArrayDescriptor(..), * Specifying Data for the Arrays ClientArrayType(..), arrayPointer, InterleavedArrays(..), interleavedArrays, clientState, clientActiveTexture, ArrayIndex, NumArrayIndices, NumIndexBlocks, arrayElement, drawArrays, multiDrawArrays, drawElements, multiDrawElements, drawRangeElements, maxElementsVertices, maxElementsIndices, lockArrays, primitiveRestartIndex ) where import Foreign.Marshal.Alloc ( alloca ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(peek) ) import Graphics.Rendering.OpenGL.GL.Capability ( EnableCap(CapVertexArray,CapNormalArray,CapColorArray,CapIndexArray, CapTextureCoordArray,CapEdgeFlagArray,CapFogCoordArray, CapSecondaryColorArray,CapMatrixIndexArray,CapPrimitiveRestart), makeCapability ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLint, GLuint, GLsizei, Capability(Enabled) ) import Graphics.Rendering.OpenGL.GL.DataType ( DataType(..), marshalDataType, unmarshalDataType ) import Graphics.Rendering.OpenGL.GL.Extensions ( FunPtr, unsafePerformIO, Invoker, getProcAddress ) import Graphics.Rendering.OpenGL.GL.QueryUtils ( GetPName(GetVertexArraySize,GetVertexArrayType,GetVertexArrayStride, GetNormalArrayType,GetNormalArrayStride,GetColorArraySize, GetColorArrayType,GetColorArrayStride,GetSecondaryColorArraySize, GetSecondaryColorArrayType,GetSecondaryColorArrayStride, GetIndexArrayType,GetIndexArrayStride, GetFogCoordArrayType,GetFogCoordArrayStride, GetTextureCoordArraySize,GetTextureCoordArrayType, GetTextureCoordArrayStride,GetEdgeFlagArrayStride, GetMaxElementsVertices,GetMaxElementsIndices, GetClientActiveTexture,GetArrayElementLockFirst, GetArrayElementLockCount,GetPrimitiveRestartIndex), getInteger1, getEnum1, getSizei1 ) import Graphics.Rendering.OpenGL.GL.PrimitiveMode ( marshalPrimitiveMode ) import Graphics.Rendering.OpenGL.GL.BeginEnd ( PrimitiveMode ) import Graphics.Rendering.OpenGL.GL.StateVar ( HasGetter(get), GettableStateVar, makeGettableStateVar, StateVar, makeStateVar ) import Graphics.Rendering.OpenGL.GL.Texturing.TextureUnit ( TextureUnit, marshalTextureUnit, unmarshalTextureUnit ) import Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( recordInvalidEnum, recordInvalidValue ) #include "HsOpenGLExt.h" type NumComponents = GLint type Stride = GLsizei data VertexArrayDescriptor a = VertexArrayDescriptor !NumComponents !DataType !Stride !(Ptr a) #ifdef __HADDOCK__ instance Eq (VertexArrayDescriptor a) instance Ord (VertexArrayDescriptor a) instance Show (VertexArrayDescriptor a) #else deriving ( Eq, Ord, Show ) #endif noVertexArrayDescriptor :: VertexArrayDescriptor a noVertexArrayDescriptor = VertexArrayDescriptor 0 Byte 0 nullPtr data ClientArrayType = VertexArray | NormalArray | ColorArray | IndexArray | TextureCoordArray | EdgeFlagArray | FogCoordArray | SecondaryColorArray | MatrixIndexArray deriving ( Eq, Ord, Show ) marshalClientArrayType :: ClientArrayType -> GLenum marshalClientArrayType x = case x of VertexArray -> 0x8074 NormalArray -> 0x8075 ColorArray -> 0x8076 IndexArray -> 0x8077 TextureCoordArray -> 0x8078 EdgeFlagArray -> 0x8079 FogCoordArray -> 0x8457 SecondaryColorArray -> 0x845e MatrixIndexArray -> 0x8844 clientArrayTypeToEnableCap :: ClientArrayType -> EnableCap clientArrayTypeToEnableCap x = case x of VertexArray -> CapVertexArray NormalArray -> CapNormalArray ColorArray -> CapColorArray IndexArray -> CapIndexArray TextureCoordArray -> CapTextureCoordArray EdgeFlagArray -> CapEdgeFlagArray FogCoordArray -> CapFogCoordArray SecondaryColorArray -> CapSecondaryColorArray MatrixIndexArray -> CapMatrixIndexArray arrayPointer :: ClientArrayType -> StateVar (VertexArrayDescriptor a) arrayPointer t = case t of VertexArray -> vertexPointer NormalArray -> normalPointer ColorArray -> colorPointer IndexArray -> indexPointer TextureCoordArray -> texCoordPointer EdgeFlagArray -> edgeFlagPointer FogCoordArray -> fogCoordPointer SecondaryColorArray -> secondaryColorPointer MatrixIndexArray -> makeStateVar (do recordInvalidEnum ; return noVertexArrayDescriptor) (const recordInvalidEnum) check :: Bool -> IO () -> IO () check flag val = if flag then val else recordInvalidValue vertexPointer :: StateVar (VertexArrayDescriptor a) vertexPointer = makeStateVar getVertexPointer setVertexPointer getVertexPointer :: IO (VertexArrayDescriptor a) getVertexPointer = do n <- getInteger1 id GetVertexArraySize d <- getEnum1 unmarshalDataType GetVertexArrayType s <- getInteger1 fromIntegral GetVertexArrayStride p <- getPointer VertexArrayPointer return $ VertexArrayDescriptor n d s p setVertexPointer :: VertexArrayDescriptor a -> IO () setVertexPointer (VertexArrayDescriptor n d s p) = glVertexPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glVertexPointer" glVertexPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () normalPointer :: StateVar (VertexArrayDescriptor a) normalPointer = makeStateVar getNormalPointer setNormalPointer getNormalPointer :: IO (VertexArrayDescriptor a) getNormalPointer = do d <- getEnum1 unmarshalDataType GetNormalArrayType s <- getInteger1 fromIntegral GetNormalArrayStride p <- getPointer NormalArrayPointer return $ VertexArrayDescriptor 3 d s p setNormalPointer :: VertexArrayDescriptor a -> IO () setNormalPointer (VertexArrayDescriptor n d s p) = check (n == 3) $ glNormalPointer (marshalDataType d) s p foreign import CALLCONV unsafe "glNormalPointer" glNormalPointer :: GLenum -> GLsizei -> Ptr a -> IO () colorPointer :: StateVar (VertexArrayDescriptor a) colorPointer = makeStateVar getColorPointer setColorPointer getColorPointer :: IO (VertexArrayDescriptor a) getColorPointer = do n <- getInteger1 id GetColorArraySize d <- getEnum1 unmarshalDataType GetColorArrayType s <- getInteger1 fromIntegral GetColorArrayStride p <- getPointer ColorArrayPointer return $ VertexArrayDescriptor n d s p setColorPointer :: VertexArrayDescriptor a -> IO () setColorPointer (VertexArrayDescriptor n d s p) = check (n == 3 || n == 4) $ glColorPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glColorPointer" glColorPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () indexPointer :: StateVar (VertexArrayDescriptor a) indexPointer = makeStateVar getIndexPointer setIndexPointer getIndexPointer :: IO (VertexArrayDescriptor a) getIndexPointer = do d <- getEnum1 unmarshalDataType GetIndexArrayType s <- getInteger1 fromIntegral GetIndexArrayStride p <- getPointer IndexArrayPointer return $ VertexArrayDescriptor 1 d s p setIndexPointer :: VertexArrayDescriptor a -> IO () setIndexPointer (VertexArrayDescriptor n d s p) = check (n == 1) $ glIndexPointer (marshalDataType d) s p foreign import CALLCONV unsafe "glIndexPointer" glIndexPointer :: GLenum -> GLsizei -> Ptr a -> IO () texCoordPointer :: StateVar (VertexArrayDescriptor a) texCoordPointer = makeStateVar getTexCoordPointer setTexCoordPointer getTexCoordPointer :: IO (VertexArrayDescriptor a) getTexCoordPointer = do n <- getInteger1 id GetTextureCoordArraySize d <- getEnum1 unmarshalDataType GetTextureCoordArrayType s <- getInteger1 fromIntegral GetTextureCoordArrayStride p <- getPointer TextureCoordArrayPointer return $ VertexArrayDescriptor n d s p setTexCoordPointer :: VertexArrayDescriptor a -> IO () setTexCoordPointer (VertexArrayDescriptor n d s p) = glTexCoordPointer n (marshalDataType d) s p foreign import CALLCONV unsafe "glTexCoordPointer" glTexCoordPointer :: GLint -> GLenum -> GLsizei -> Ptr a -> IO () edgeFlagPointer :: StateVar (VertexArrayDescriptor a) edgeFlagPointer = makeStateVar getEdgeFlagPointer setEdgeFlagPointer getEdgeFlagPointer :: IO (VertexArrayDescriptor a) getEdgeFlagPointer = do s <- getInteger1 fromIntegral GetEdgeFlagArrayStride p <- getPointer EdgeFlagArrayPointer return $ VertexArrayDescriptor 1 UnsignedByte s p setEdgeFlagPointer :: VertexArrayDescriptor a -> IO () setEdgeFlagPointer (VertexArrayDescriptor n d s p) = check (n == 1 && d == UnsignedByte) $ glEdgeFlagPointer s p foreign import CALLCONV unsafe "glEdgeFlagPointer" glEdgeFlagPointer :: GLsizei -> Ptr a -> IO () fogCoordPointer :: StateVar (VertexArrayDescriptor a) fogCoordPointer = makeStateVar getFogCoordPointer setFogCoordPointer getFogCoordPointer :: IO (VertexArrayDescriptor a) getFogCoordPointer = do d <- getEnum1 unmarshalDataType GetFogCoordArrayType s <- getInteger1 fromIntegral GetFogCoordArrayStride p <- getPointer FogCoordArrayPointer return $ VertexArrayDescriptor 1 d s p setFogCoordPointer :: VertexArrayDescriptor a -> IO () setFogCoordPointer (VertexArrayDescriptor n d s p) = check (n == 1) $ glFogCoordPointerEXT (marshalDataType d) s p EXTENSION_ENTRY("GL_EXT_fog_coord or OpenGL 1.4",glFogCoordPointerEXT,GLenum -> GLsizei -> Ptr a -> IO ()) secondaryColorPointer :: StateVar (VertexArrayDescriptor a) secondaryColorPointer = makeStateVar getSecondaryColorPointer setSecondaryColorPointer getSecondaryColorPointer :: IO (VertexArrayDescriptor a) getSecondaryColorPointer = do n <- getInteger1 id GetSecondaryColorArraySize d <- getEnum1 unmarshalDataType GetSecondaryColorArrayType s <- getInteger1 fromIntegral GetSecondaryColorArrayStride p <- getPointer SecondaryColorArrayPointer return $ VertexArrayDescriptor n d s p setSecondaryColorPointer :: (VertexArrayDescriptor a) -> IO () setSecondaryColorPointer (VertexArrayDescriptor n d s p) = glSecondaryColorPointerEXT n (marshalDataType d) s p EXTENSION_ENTRY("GL_EXT_secondary_color or OpenGL 1.4",glSecondaryColorPointerEXT,GLint -> GLenum -> GLsizei -> Ptr a -> IO ()) data InterleavedArrays = V2f | V3f | C4ubV2f | C4ubV3f | C3fV3f | N3fV3f | C4fN3fV3f | T2fV3f | T4fV4f | T2fC4ubV3f | T2fC3fV3f | T2fN3fV3f | T2fC4fN3fV3f | T4fC4fN3fV4f deriving ( Eq, Ord, Show ) marshalInterleavedArrays :: InterleavedArrays -> GLenum marshalInterleavedArrays x = case x of V2f -> 0x2a20 V3f -> 0x2a21 C4ubV2f -> 0x2a22 C4ubV3f -> 0x2a23 C3fV3f -> 0x2a24 N3fV3f -> 0x2a25 C4fN3fV3f -> 0x2a26 T2fV3f -> 0x2a27 T4fV4f -> 0x2a28 T2fC4ubV3f -> 0x2a29 T2fC3fV3f -> 0x2a2a T2fN3fV3f -> 0x2a2b T2fC4fN3fV3f -> 0x2a2c T4fC4fN3fV4f -> 0x2a2d interleavedArrays :: InterleavedArrays -> Stride -> Ptr a -> IO () interleavedArrays = glInterleavedArrays . marshalInterleavedArrays foreign import CALLCONV unsafe "glInterleavedArrays" glInterleavedArrays :: GLenum -> GLsizei -> Ptr a -> IO () clientState :: ClientArrayType -> StateVar Capability clientState arrayType = makeStateVar (getClientState arrayType) (setClientState arrayType) getClientState :: ClientArrayType -> IO Capability getClientState = get . makeCapability . clientArrayTypeToEnableCap setClientState :: ClientArrayType -> Capability -> IO () setClientState arrayType val = (if val == Enabled then glEnableClientState else glDisableClientState) (marshalClientArrayType arrayType) foreign import CALLCONV unsafe "glEnableClientState" glEnableClientState :: GLenum -> IO () foreign import CALLCONV unsafe "glDisableClientState" glDisableClientState :: GLenum -> IO () clientActiveTexture :: StateVar TextureUnit clientActiveTexture = makeStateVar (getEnum1 unmarshalTextureUnit GetClientActiveTexture) (glClientActiveTextureARB . marshalTextureUnit) EXTENSION_ENTRY("GL_ARB_multitexture or OpenGL 1.3",glClientActiveTextureARB,GLenum -> IO ()) type ArrayIndex = GLint type NumArrayIndices = GLsizei type NumIndexBlocks = GLsizei arrayElement :: ArrayIndex -> IO () arrayElement = glArrayElement foreign import CALLCONV unsafe "glArrayElement" glArrayElement :: GLint -> IO () drawArrays :: PrimitiveMode -> ArrayIndex -> NumArrayIndices -> IO () drawArrays = glDrawArrays . marshalPrimitiveMode foreign import CALLCONV unsafe "glDrawArrays" glDrawArrays :: GLenum -> GLint -> GLsizei -> IO () multiDrawArrays :: PrimitiveMode -> Ptr ArrayIndex -> Ptr NumArrayIndices -> NumIndexBlocks -> IO () multiDrawArrays = glMultiDrawArraysEXT . marshalPrimitiveMode EXTENSION_ENTRY("GL_EXT_multi_draw_arrays or OpenGL 1.4",glMultiDrawArraysEXT,GLenum -> Ptr ArrayIndex -> Ptr GLsizei -> GLsizei -> IO ()) drawElements :: PrimitiveMode -> NumArrayIndices -> DataType -> Ptr a -> IO () drawElements m c = glDrawElements (marshalPrimitiveMode m) c . marshalDataType foreign import CALLCONV unsafe "glDrawElements" glDrawElements :: GLenum -> GLsizei -> GLenum -> Ptr a -> IO () multiDrawElements :: PrimitiveMode -> Ptr NumArrayIndices -> DataType -> Ptr (Ptr a) -> NumIndexBlocks -> IO () multiDrawElements m c = glMultiDrawElementsEXT (marshalPrimitiveMode m) c . marshalDataType EXTENSION_ENTRY("GL_EXT_multi_draw_arrays or OpenGL 1.4",glMultiDrawElementsEXT,GLenum -> Ptr GLsizei -> GLenum -> Ptr (Ptr a) -> GLsizei -> IO ()) drawRangeElements :: PrimitiveMode -> (ArrayIndex, ArrayIndex) -> NumArrayIndices -> DataType -> Ptr a -> IO () drawRangeElements m (s, e) c = glDrawRangeElementsEXT (marshalPrimitiveMode m) (fromIntegral s) (fromIntegral e) c . marshalDataType EXTENSION_ENTRY("GL_EXT_draw_range_elements or OpenGL 1.2",glDrawRangeElementsEXT,GLenum -> GLuint -> GLuint -> GLsizei -> GLenum -> Ptr a -> IO ()) maxElementsVertices :: GettableStateVar NumArrayIndices maxElementsVertices = makeGettableStateVar (getSizei1 id GetMaxElementsVertices) maxElementsIndices :: GettableStateVar NumArrayIndices maxElementsIndices = makeGettableStateVar (getSizei1 id GetMaxElementsIndices) lockArrays :: StateVar (Maybe (ArrayIndex, NumArrayIndices)) lockArrays = makeStateVar getLockArrays setLockArrays getLockArrays :: IO (Maybe (ArrayIndex, NumArrayIndices)) getLockArrays = do count <- getInteger1 fromIntegral GetArrayElementLockCount if count > 0 then do first <- getInteger1 id GetArrayElementLockFirst return $ Just (first, count) else return Nothing setLockArrays :: Maybe (ArrayIndex, NumArrayIndices) -> IO () setLockArrays = maybe glUnlockArraysEXT (uncurry glLockArraysEXT) EXTENSION_ENTRY("GL_EXT_compiled_vertex_array",glLockArraysEXT,GLint -> GLsizei -> IO ()) EXTENSION_ENTRY("GL_EXT_compiled_vertex_array",glUnlockArraysEXT,IO ()) primitiveRestartIndex :: StateVar (Maybe ArrayIndex) primitiveRestartIndex = makeStateVar getPrimitiverestartIndex setPrimitiverestartIndex getPrimitiverestartIndex :: IO (Maybe ArrayIndex) getPrimitiverestartIndex = do state <- get (makeCapability CapPrimitiveRestart) if state == Enabled then fmap Just $ getInteger1 fromIntegral GetPrimitiveRestartIndex else return Nothing setPrimitiverestartIndex :: Maybe ArrayIndex -> IO () setPrimitiverestartIndex maybeIdx = case maybeIdx of Nothing -> glDisableClientState primitiveRestartNV Just idx -> do glEnableClientState primitiveRestartNV glPrimitiveRestartIndexNV (fromIntegral idx) ToDo : HACK ! EXTENSION_ENTRY("GL_NV_primitive_restart",glPrimitiveRestartIndexNV,GLuint -> IO ()) data GetPointervPName = VertexArrayPointer | NormalArrayPointer | ColorArrayPointer | IndexArrayPointer | TextureCoordArrayPointer | EdgeFlagArrayPointer | FogCoordArrayPointer | SecondaryColorArrayPointer | FeedbackBufferPointer | SelectionBufferPointer | WeightArrayPointer | MatrixIndexArrayPointer marshalGetPointervPName :: GetPointervPName -> GLenum marshalGetPointervPName x = case x of VertexArrayPointer -> 0x808e NormalArrayPointer -> 0x808f ColorArrayPointer -> 0x8090 IndexArrayPointer -> 0x8091 TextureCoordArrayPointer -> 0x8092 EdgeFlagArrayPointer -> 0x8093 FogCoordArrayPointer -> 0x8456 SecondaryColorArrayPointer -> 0x845d FeedbackBufferPointer -> 0xdf0 SelectionBufferPointer -> 0xdf3 WeightArrayPointer -> 0x86ac MatrixIndexArrayPointer -> 0x8849 getPointer :: GetPointervPName -> IO (Ptr a) getPointer n = alloca $ \buf -> do glGetPointerv (marshalGetPointervPName n) buf peek buf foreign import CALLCONV unsafe "glGetPointerv" glGetPointerv :: GLenum -> Ptr (Ptr a) -> IO ()
9beecc84e0a72916f681a8a0c8f4fd1add7649a663884eea2b895a6c37f5ff76
mirage/capnp-rpc
connection.ml
module RO_array = Capnp_rpc.RO_array module Request = Capnp_direct.String_content.Request module Response = Capnp_direct.String_content.Response let src = Logs.Src.create "test-net" ~doc:"Cap'n Proto RPC tests" module Log = (val Logs.src_log src: Logs.LOG) module Stats = Capnp_rpc.Stats let stats_t = Alcotest.of_pp Stats.pp let summary_of_msg = function | `Abort _ -> "abort" | `Bootstrap _ -> "bootstrap" | `Call (_, _, msg, _, _) -> "call:" ^ (Request.data msg) | `Return (_, `Results (msg, _), _) -> "return:" ^ (Response.data msg) | `Return (_, `Exception ex, _) -> "return:" ^ ex.Capnp_rpc.Exception.reason | `Return (_, `Cancelled, _) -> "return:(cancelled)" | `Return (_, `AcceptFromThirdParty, _) -> "return:accept" | `Return (_, `ResultsSentElsewhere, _) -> "return:sent-elsewhere" | `Return (_, `TakeFromOtherQuestion _, _) -> "return:take-from-other" | `Finish _ -> "finish" | `Release _ -> "release" | `Disembargo_request _ -> "disembargo-request" | `Disembargo_reply _ -> "disembargo-reply" | `Resolve _ -> "resolve" | `Unimplemented _ -> "unimplemented" module type ENDPOINT = sig open Capnp_direct.Core_types type t module EP : Capnp_direct.ENDPOINT val dump : t Fmt.t val create : ?bootstrap:#cap -> tags:Logs.Tag.set -> [EP.Out.t | `Unimplemented of EP.In.t] Queue.t -> [EP.In.t | `Unimplemented of EP.Out.t] Queue.t -> t val handle_msg : ?expect:string -> t -> unit val maybe_handle_msg : t -> unit val step : t -> bool val bootstrap : t -> cap val stats : t -> Capnp_rpc.Stats.t val check_invariants : t -> unit val check_finished : t -> name:string -> unit val disconnect : t -> Capnp_rpc.Exception.t -> unit end module Endpoint (EP : Capnp_direct.ENDPOINT) = struct module Conn = Capnp_rpc.CapTP.Make(EP) type t = { conn : Conn.t; bootstrap : EP.Core_types.cap option; recv_queue : [EP.In.t | `Unimplemented of EP.Out.t] Queue.t; } let pp_msg f = function | #EP.In.t as msg -> EP.In.pp_recv Request.pp f msg | `Unimplemented out -> Fmt.pf f "Unimplemented(%a)" (EP.Out.pp_recv Request.pp) out let dump f t = Fmt.pf f "%a@,%a" Conn.dump t.conn (Fmt.Dump.queue pp_msg) t.recv_queue module EP = EP let restore_single = function | None -> None | Some bootstrap -> Some (fun k -> function | "" -> Capnp_direct.Core_types.inc_ref bootstrap; k @@ Ok bootstrap | _ -> k @@ Error (Capnp_rpc.Exception.v "Only a main interface is available") ) let create ?bootstrap ~tags (xmit_queue:[EP.Out.t | `Unimplemented of EP.In.t] Queue.t) (recv_queue:[EP.In.t | `Unimplemented of EP.Out.t] Queue.t) = let queue_send x = Queue.add (x :> [EP.Out.t | `Unimplemented of EP.In.t]) xmit_queue in let bootstrap = (bootstrap :> EP.Core_types.cap option) in let restore = restore_single bootstrap in let conn = Conn.create ?restore ~tags ~queue_send in { conn; recv_queue; bootstrap; } let pop_msg ?expect t = match Queue.pop t.recv_queue with | exception Queue.Empty -> Alcotest.fail (Fmt.str "No messages found! (expecting %a)" Fmt.(option string) expect) | msg -> begin match msg with | #EP.In.t as msg -> let tags = EP.In.with_qid_tag (Conn.tags t.conn) msg in Log.info (fun f -> f ~tags "<- %a" (EP.In.pp_recv Request.pp) msg) | `Unimplemented out -> Log.info (fun f -> f ~tags:(Conn.tags t.conn) "<- Unimplemented(%a)" (EP.Out.pp_recv Request.pp) out) end; match expect with | None -> msg | Some expected -> Alcotest.(check string) ("Input " ^ expected) expected (summary_of_msg msg); msg let handle_msg ?expect t = try pop_msg ?expect t |> Conn.handle_msg t.conn; Conn.check t.conn with ex -> Logs.err (fun f -> f ~tags:(Conn.tags t.conn) "@[<v2>%a:@,%a@]" Capnp_rpc.Debug.pp_exn ex Conn.dump t.conn); raise ex let maybe_handle_msg t = if Queue.length t.recv_queue > 0 then handle_msg t let step t = if Queue.length t.recv_queue > 0 then (maybe_handle_msg t; true) else false let bootstrap t = Conn.bootstrap t.conn "" let stats t = Conn.stats t.conn let finished = Capnp_rpc.Exception.v "Tests finished" let check_invariants t = Conn.check t.conn let disconnect t reason = Conn.disconnect t.conn reason; match t.bootstrap with | None -> () | Some cap -> EP.Core_types.dec_ref cap let check_finished t ~name = Alcotest.(check stats_t) (name ^ " finished") Stats.zero @@ stats t; Conn.check t.conn; disconnect t finished end module Pair ( ) = struct module Table_types = Capnp_rpc.Message_types.Table_types ( ) module ProtoC = Capnp_rpc.Message_types.Endpoint(Capnp_direct.Core_types)(Capnp_direct.Network_types)(Table_types) module ProtoS = struct module Core_types = Capnp_direct.Core_types module Network_types = Capnp_direct.Network_types module Table = Capnp_rpc.Message_types.Flip(ProtoC.Table) module In = ProtoC.Out module Out = ProtoC.In end module C = Endpoint(ProtoC) module S = Endpoint(ProtoS) let create ~client_tags ~server_tags ?client_bs bootstrap = let q1 = Queue.create () in let q2 = Queue.create () in let c = C.create ~tags:client_tags q1 q2 ?bootstrap:client_bs in let s = S.create ~tags:server_tags q2 q1 ~bootstrap in c, s let rec flush c s = let c_changed = C.step c in let s_changed = S.step s in if c_changed || s_changed then flush c s let dump c s = Logs.info (fun f -> f ~tags:(C.Conn.tags c.C.conn) "%a" C.dump c); Logs.info (fun f -> f ~tags:(S.Conn.tags s.S.conn) "%a" S.dump s) let check_finished c s = try C.check_finished c ~name:"Client"; S.check_finished s ~name:"Server"; with ex -> dump c s; raise ex end
null
https://raw.githubusercontent.com/mirage/capnp-rpc/097fd38d8bd0a320ea1867191274d8ef438419f8/test/testbed/connection.ml
ocaml
module RO_array = Capnp_rpc.RO_array module Request = Capnp_direct.String_content.Request module Response = Capnp_direct.String_content.Response let src = Logs.Src.create "test-net" ~doc:"Cap'n Proto RPC tests" module Log = (val Logs.src_log src: Logs.LOG) module Stats = Capnp_rpc.Stats let stats_t = Alcotest.of_pp Stats.pp let summary_of_msg = function | `Abort _ -> "abort" | `Bootstrap _ -> "bootstrap" | `Call (_, _, msg, _, _) -> "call:" ^ (Request.data msg) | `Return (_, `Results (msg, _), _) -> "return:" ^ (Response.data msg) | `Return (_, `Exception ex, _) -> "return:" ^ ex.Capnp_rpc.Exception.reason | `Return (_, `Cancelled, _) -> "return:(cancelled)" | `Return (_, `AcceptFromThirdParty, _) -> "return:accept" | `Return (_, `ResultsSentElsewhere, _) -> "return:sent-elsewhere" | `Return (_, `TakeFromOtherQuestion _, _) -> "return:take-from-other" | `Finish _ -> "finish" | `Release _ -> "release" | `Disembargo_request _ -> "disembargo-request" | `Disembargo_reply _ -> "disembargo-reply" | `Resolve _ -> "resolve" | `Unimplemented _ -> "unimplemented" module type ENDPOINT = sig open Capnp_direct.Core_types type t module EP : Capnp_direct.ENDPOINT val dump : t Fmt.t val create : ?bootstrap:#cap -> tags:Logs.Tag.set -> [EP.Out.t | `Unimplemented of EP.In.t] Queue.t -> [EP.In.t | `Unimplemented of EP.Out.t] Queue.t -> t val handle_msg : ?expect:string -> t -> unit val maybe_handle_msg : t -> unit val step : t -> bool val bootstrap : t -> cap val stats : t -> Capnp_rpc.Stats.t val check_invariants : t -> unit val check_finished : t -> name:string -> unit val disconnect : t -> Capnp_rpc.Exception.t -> unit end module Endpoint (EP : Capnp_direct.ENDPOINT) = struct module Conn = Capnp_rpc.CapTP.Make(EP) type t = { conn : Conn.t; bootstrap : EP.Core_types.cap option; recv_queue : [EP.In.t | `Unimplemented of EP.Out.t] Queue.t; } let pp_msg f = function | #EP.In.t as msg -> EP.In.pp_recv Request.pp f msg | `Unimplemented out -> Fmt.pf f "Unimplemented(%a)" (EP.Out.pp_recv Request.pp) out let dump f t = Fmt.pf f "%a@,%a" Conn.dump t.conn (Fmt.Dump.queue pp_msg) t.recv_queue module EP = EP let restore_single = function | None -> None | Some bootstrap -> Some (fun k -> function | "" -> Capnp_direct.Core_types.inc_ref bootstrap; k @@ Ok bootstrap | _ -> k @@ Error (Capnp_rpc.Exception.v "Only a main interface is available") ) let create ?bootstrap ~tags (xmit_queue:[EP.Out.t | `Unimplemented of EP.In.t] Queue.t) (recv_queue:[EP.In.t | `Unimplemented of EP.Out.t] Queue.t) = let queue_send x = Queue.add (x :> [EP.Out.t | `Unimplemented of EP.In.t]) xmit_queue in let bootstrap = (bootstrap :> EP.Core_types.cap option) in let restore = restore_single bootstrap in let conn = Conn.create ?restore ~tags ~queue_send in { conn; recv_queue; bootstrap; } let pop_msg ?expect t = match Queue.pop t.recv_queue with | exception Queue.Empty -> Alcotest.fail (Fmt.str "No messages found! (expecting %a)" Fmt.(option string) expect) | msg -> begin match msg with | #EP.In.t as msg -> let tags = EP.In.with_qid_tag (Conn.tags t.conn) msg in Log.info (fun f -> f ~tags "<- %a" (EP.In.pp_recv Request.pp) msg) | `Unimplemented out -> Log.info (fun f -> f ~tags:(Conn.tags t.conn) "<- Unimplemented(%a)" (EP.Out.pp_recv Request.pp) out) end; match expect with | None -> msg | Some expected -> Alcotest.(check string) ("Input " ^ expected) expected (summary_of_msg msg); msg let handle_msg ?expect t = try pop_msg ?expect t |> Conn.handle_msg t.conn; Conn.check t.conn with ex -> Logs.err (fun f -> f ~tags:(Conn.tags t.conn) "@[<v2>%a:@,%a@]" Capnp_rpc.Debug.pp_exn ex Conn.dump t.conn); raise ex let maybe_handle_msg t = if Queue.length t.recv_queue > 0 then handle_msg t let step t = if Queue.length t.recv_queue > 0 then (maybe_handle_msg t; true) else false let bootstrap t = Conn.bootstrap t.conn "" let stats t = Conn.stats t.conn let finished = Capnp_rpc.Exception.v "Tests finished" let check_invariants t = Conn.check t.conn let disconnect t reason = Conn.disconnect t.conn reason; match t.bootstrap with | None -> () | Some cap -> EP.Core_types.dec_ref cap let check_finished t ~name = Alcotest.(check stats_t) (name ^ " finished") Stats.zero @@ stats t; Conn.check t.conn; disconnect t finished end module Pair ( ) = struct module Table_types = Capnp_rpc.Message_types.Table_types ( ) module ProtoC = Capnp_rpc.Message_types.Endpoint(Capnp_direct.Core_types)(Capnp_direct.Network_types)(Table_types) module ProtoS = struct module Core_types = Capnp_direct.Core_types module Network_types = Capnp_direct.Network_types module Table = Capnp_rpc.Message_types.Flip(ProtoC.Table) module In = ProtoC.Out module Out = ProtoC.In end module C = Endpoint(ProtoC) module S = Endpoint(ProtoS) let create ~client_tags ~server_tags ?client_bs bootstrap = let q1 = Queue.create () in let q2 = Queue.create () in let c = C.create ~tags:client_tags q1 q2 ?bootstrap:client_bs in let s = S.create ~tags:server_tags q2 q1 ~bootstrap in c, s let rec flush c s = let c_changed = C.step c in let s_changed = S.step s in if c_changed || s_changed then flush c s let dump c s = Logs.info (fun f -> f ~tags:(C.Conn.tags c.C.conn) "%a" C.dump c); Logs.info (fun f -> f ~tags:(S.Conn.tags s.S.conn) "%a" S.dump s) let check_finished c s = try C.check_finished c ~name:"Client"; S.check_finished s ~name:"Server"; with ex -> dump c s; raise ex end
393fa04b742147d328325f5e87e26529707df87cc6c73623a8cc82641f4a0639
thesis/shale
webapp.cljs
(ns shale.webapp (:require [reagent.core :as reagent :refer [atom]] [reagent.session :as session] [secretary.core :as secretary :include-macros true] [accountant.core :as accountant] [ajax.core :refer [GET DELETE PUT]] [cemerick.url :refer [url]])) ;; ------------------------- ;; Data (defn delete-session [session-id] (DELETE (str "/sessions/" session-id))) (defn get-node [id success-fn] (GET (str "/nodes/" id) {:handler success-fn})) (defn get-nodes [success-fn] (GET "/nodes" {:handler success-fn})) (defn get-session [id success-fn] (GET (str "/sessions/" id) {:handler success-fn})) (defn get-sessions [success-fn] (GET "/sessions" {:handler success-fn})) (defn set-session-reservation [session-id reserved finally-fn] (PUT (str "/sessions/" session-id) {:format :json :params {"reserved" reserved} :finally finally-fn})) ;; ------------------------- ;; Components (defn a-href-text [text] [:a {:href text} text]) (defn host-port [s] (->> ((juxt :host :port) (url s)) (clojure.string.join ":"))) (defn node-component [node] (let [url (get node "url") id (get node "id")] ^{:key id} [:div.btn-group [:a.node.btn.btn-default {:href (str "/manage/node/" id)} [:i.fa.fa-share-alt] (host-port url)]])) (defn node-detail-component [node] [:table.table [:tbody [:tr [:td "URL"] [:td (a-href-text (get node "url"))]] [:tr [:td "Tags"] [:td (clojure.string/join "," (get node "tags"))]]]]) (defn node-list-component [] (let [nodes (atom []) load-nodes (fn [] (get-nodes #(reset! nodes %)))] (load-nodes) (js/setInterval load-nodes 5000) (fn [] [:ul.node-list (for [node @nodes] [:li [node-component node]])]))) (defn browser-icon-component [browser] (case browser "chrome" [:i.fa.fa-chrome {:title browser}] "firefox" [:i.fa.fa-firefox {:title browser}] [:i.fa.fa-laptop {:title browser}])) (defn reserve-button-component [session reserving reserve-fn] (let [id (get session "id") reserved (get session "reserved") title (if reserved "Unreserve session" "Reserve session")] [:button.btn.btn-default {:title title :on-click #(reserve-fn (not (boolean reserved)))} (if (some #{id} reserving) [:i.fa.fa-spinner.fa-spin] (if reserved [:i.fa.fa-lock] [:i.fa.fa-unlock]))])) (defn destroy-button-component [session deleting delete-fn] (let [id (get session "id")] [:button.btn.btn-default {:title "Destroy session" :on-click delete-fn} (if (some #{id} deleting) [:i.fa.fa-spinner.fa-spin] [:i.fa.fa-remove])])) (defn session-component [session] (let [deleting (atom []) reserving (atom [])] (fn [session] (let [id (get session "id") browser (get session "browser_name") delete-fn (fn [] (swap! deleting #(conj % id)) (delete-session id)) remove-from-reserving! (fn [] (swap! reserving #(filter (complement #{id}) %))) reserve-fn (fn [reserve] (swap! reserving #(conj % id)) (set-session-reservation id reserve remove-from-reserving!))] ^{:key id} [:div.btn-group [:a.session.btn.btn-default {:href (str "/manage/session/" id)} [browser-icon-component browser] [:span id]] [reserve-button-component session @reserving reserve-fn] [destroy-button-component session @deleting delete-fn]])))) (defn session-detail-component [session] [:table.table [:tbody [:tr [:td "Webdriver ID"] [:td (get session "webdriver_id")]] [:tr [:td "Browser"] [:td (get session "browser_name")]] [:tr [:td "Reserved"] [:td (if (get session "reserved") [:i.fa.fa-check])]] [:tr [:td "Tags"] [:td (clojure.string/join "," (get session "tags"))]] [:tr [:td "Node"] [:td [:a {:href (get-in session ["node" "id"])} (host-port (get-in session ["node" "url"]))]]]]]) (defn session-list-component [] (let [sessions (atom []) load-sessions (fn [] (get-sessions #(reset! sessions %)))] (load-sessions) (js/setInterval load-sessions 5000) (fn [] [:ul.session-list (for [session @sessions] [:li [session-component session]])]))) (defn management-page-header [& body] [:div [:h2.text-center "Shale Management Console"] body]) ;; ------------------------- ;; Pages (defn home-page [] [:div [:h2 "Shale"] [:nav [:ul [:li [:a {:href "/manage"} "Management Console"]] [:li [:a {:href "/docs"} "API Docs"]]]]]) (defn docs-page [] [:div [:h2 "Shale"] [:ul [:li (a-href-text "/sessions") "Active Selenium sessions."] [:li (a-href-text "/sessions/:id") (str "A session identified by id." "Accepts GET, PUT, & DELETE.")] [:li (a-href-text "/sessions/refresh") (str "POST to refresh all sessions. This shuldn't be necessary in " "production since refreshes are scheduled regularly.")] [:li (a-href-text "/nodes") "Active Selenium nodes"] [:li (a-href-text "/nodes/:id") (str "A node identified by id." "Accepts GET, PUT, & DELETE.")] [:li (a-href-text "/nodes/refresh") "POST to refresh all nodes."] [:li (a-href-text "/proxies") "Proxies available for use with new sessions."]]]) (defn management-page [] [management-page-header [:div.col-md-3 [:h3 "Nodes"] [node-list-component]] [:div.col-md-5 [:h3 "Sessions"] [session-list-component]]]) (defn node-page [id] (let [node (atom {:id id})] (get-node id #(reset! node %)) (fn [id] [management-page-header [:div.col-md-6.col-md-offset-3 [:h3.text-center (str "Node " id)] [node-detail-component @node]]]))) (defn session-page [id] (let [session (atom {:id id})] (get-session id #(reset! session %)) (fn [id] [management-page-header [:div.col-md-6.col-md-offset-3 [:h3.text-center (str "Session " id)] [session-detail-component @session]]]))) (defn current-page [] (session/get :current-page)) ;; ------------------------- ;; Routes (secretary/defroute "/" [] (session/put! :current-page [#'home-page])) (secretary/defroute "/manage" [] (session/put! :current-page [#'management-page])) (secretary/defroute "/manage/node/:id" [id] (session/put! :current-page [#'node-page id])) (secretary/defroute "/manage/session/:id" {id :id} (session/put! :current-page [#'session-page id])) (secretary/defroute "/docs" [] (session/put! :current-page [#'docs-page])) ;; ------------------------- Initialize app (defn mount-root [] (reagent/render [current-page] (.getElementById js/document "app"))) (defn init! [] (accountant/configure-navigation! {:nav-handler (fn [path] (secretary/dispatch! path)) :path-exists? (fn [path] (secretary/locate-route path))}) (accountant/dispatch-current!) (mount-root))
null
https://raw.githubusercontent.com/thesis/shale/84180532e46ee5d9ee0218138da04ea035bcf7d2/src/cljs/shale/webapp.cljs
clojure
------------------------- Data ------------------------- Components ------------------------- Pages ------------------------- Routes -------------------------
(ns shale.webapp (:require [reagent.core :as reagent :refer [atom]] [reagent.session :as session] [secretary.core :as secretary :include-macros true] [accountant.core :as accountant] [ajax.core :refer [GET DELETE PUT]] [cemerick.url :refer [url]])) (defn delete-session [session-id] (DELETE (str "/sessions/" session-id))) (defn get-node [id success-fn] (GET (str "/nodes/" id) {:handler success-fn})) (defn get-nodes [success-fn] (GET "/nodes" {:handler success-fn})) (defn get-session [id success-fn] (GET (str "/sessions/" id) {:handler success-fn})) (defn get-sessions [success-fn] (GET "/sessions" {:handler success-fn})) (defn set-session-reservation [session-id reserved finally-fn] (PUT (str "/sessions/" session-id) {:format :json :params {"reserved" reserved} :finally finally-fn})) (defn a-href-text [text] [:a {:href text} text]) (defn host-port [s] (->> ((juxt :host :port) (url s)) (clojure.string.join ":"))) (defn node-component [node] (let [url (get node "url") id (get node "id")] ^{:key id} [:div.btn-group [:a.node.btn.btn-default {:href (str "/manage/node/" id)} [:i.fa.fa-share-alt] (host-port url)]])) (defn node-detail-component [node] [:table.table [:tbody [:tr [:td "URL"] [:td (a-href-text (get node "url"))]] [:tr [:td "Tags"] [:td (clojure.string/join "," (get node "tags"))]]]]) (defn node-list-component [] (let [nodes (atom []) load-nodes (fn [] (get-nodes #(reset! nodes %)))] (load-nodes) (js/setInterval load-nodes 5000) (fn [] [:ul.node-list (for [node @nodes] [:li [node-component node]])]))) (defn browser-icon-component [browser] (case browser "chrome" [:i.fa.fa-chrome {:title browser}] "firefox" [:i.fa.fa-firefox {:title browser}] [:i.fa.fa-laptop {:title browser}])) (defn reserve-button-component [session reserving reserve-fn] (let [id (get session "id") reserved (get session "reserved") title (if reserved "Unreserve session" "Reserve session")] [:button.btn.btn-default {:title title :on-click #(reserve-fn (not (boolean reserved)))} (if (some #{id} reserving) [:i.fa.fa-spinner.fa-spin] (if reserved [:i.fa.fa-lock] [:i.fa.fa-unlock]))])) (defn destroy-button-component [session deleting delete-fn] (let [id (get session "id")] [:button.btn.btn-default {:title "Destroy session" :on-click delete-fn} (if (some #{id} deleting) [:i.fa.fa-spinner.fa-spin] [:i.fa.fa-remove])])) (defn session-component [session] (let [deleting (atom []) reserving (atom [])] (fn [session] (let [id (get session "id") browser (get session "browser_name") delete-fn (fn [] (swap! deleting #(conj % id)) (delete-session id)) remove-from-reserving! (fn [] (swap! reserving #(filter (complement #{id}) %))) reserve-fn (fn [reserve] (swap! reserving #(conj % id)) (set-session-reservation id reserve remove-from-reserving!))] ^{:key id} [:div.btn-group [:a.session.btn.btn-default {:href (str "/manage/session/" id)} [browser-icon-component browser] [:span id]] [reserve-button-component session @reserving reserve-fn] [destroy-button-component session @deleting delete-fn]])))) (defn session-detail-component [session] [:table.table [:tbody [:tr [:td "Webdriver ID"] [:td (get session "webdriver_id")]] [:tr [:td "Browser"] [:td (get session "browser_name")]] [:tr [:td "Reserved"] [:td (if (get session "reserved") [:i.fa.fa-check])]] [:tr [:td "Tags"] [:td (clojure.string/join "," (get session "tags"))]] [:tr [:td "Node"] [:td [:a {:href (get-in session ["node" "id"])} (host-port (get-in session ["node" "url"]))]]]]]) (defn session-list-component [] (let [sessions (atom []) load-sessions (fn [] (get-sessions #(reset! sessions %)))] (load-sessions) (js/setInterval load-sessions 5000) (fn [] [:ul.session-list (for [session @sessions] [:li [session-component session]])]))) (defn management-page-header [& body] [:div [:h2.text-center "Shale Management Console"] body]) (defn home-page [] [:div [:h2 "Shale"] [:nav [:ul [:li [:a {:href "/manage"} "Management Console"]] [:li [:a {:href "/docs"} "API Docs"]]]]]) (defn docs-page [] [:div [:h2 "Shale"] [:ul [:li (a-href-text "/sessions") "Active Selenium sessions."] [:li (a-href-text "/sessions/:id") (str "A session identified by id." "Accepts GET, PUT, & DELETE.")] [:li (a-href-text "/sessions/refresh") (str "POST to refresh all sessions. This shuldn't be necessary in " "production since refreshes are scheduled regularly.")] [:li (a-href-text "/nodes") "Active Selenium nodes"] [:li (a-href-text "/nodes/:id") (str "A node identified by id." "Accepts GET, PUT, & DELETE.")] [:li (a-href-text "/nodes/refresh") "POST to refresh all nodes."] [:li (a-href-text "/proxies") "Proxies available for use with new sessions."]]]) (defn management-page [] [management-page-header [:div.col-md-3 [:h3 "Nodes"] [node-list-component]] [:div.col-md-5 [:h3 "Sessions"] [session-list-component]]]) (defn node-page [id] (let [node (atom {:id id})] (get-node id #(reset! node %)) (fn [id] [management-page-header [:div.col-md-6.col-md-offset-3 [:h3.text-center (str "Node " id)] [node-detail-component @node]]]))) (defn session-page [id] (let [session (atom {:id id})] (get-session id #(reset! session %)) (fn [id] [management-page-header [:div.col-md-6.col-md-offset-3 [:h3.text-center (str "Session " id)] [session-detail-component @session]]]))) (defn current-page [] (session/get :current-page)) (secretary/defroute "/" [] (session/put! :current-page [#'home-page])) (secretary/defroute "/manage" [] (session/put! :current-page [#'management-page])) (secretary/defroute "/manage/node/:id" [id] (session/put! :current-page [#'node-page id])) (secretary/defroute "/manage/session/:id" {id :id} (session/put! :current-page [#'session-page id])) (secretary/defroute "/docs" [] (session/put! :current-page [#'docs-page])) Initialize app (defn mount-root [] (reagent/render [current-page] (.getElementById js/document "app"))) (defn init! [] (accountant/configure-navigation! {:nav-handler (fn [path] (secretary/dispatch! path)) :path-exists? (fn [path] (secretary/locate-route path))}) (accountant/dispatch-current!) (mount-root))
58fe01ad6931b74eea2e2c6dac422c883bcc9950a3960b3ebd3e5c2f39b915d3
ghcjs/ghcjs
cgrun022.hs
-- !!! tests stack stubbing: if "f" doesn't stub "ns", -- !!! the program has a space leak. module Main where main = f (putStr "a") (take 1000000 (repeat True)) (putStr "b") f a ns b = if last ns then a else b
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/codeGen/cgrun022.hs
haskell
!!! tests stack stubbing: if "f" doesn't stub "ns", !!! the program has a space leak.
module Main where main = f (putStr "a") (take 1000000 (repeat True)) (putStr "b") f a ns b = if last ns then a else b
440a622e98dd1bf14dd03ec2cbc37311a3298c1d6282ae1005ed6120425980c7
exoscale/clojure-kubernetes-client
v1_self_subject_access_review.clj
(ns clojure-kubernetes-client.specs.v1-self-subject-access-review (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-object-meta :refer :all] [clojure-kubernetes-client.specs.v1-self-subject-access-review-spec :refer :all] [clojure-kubernetes-client.specs.v1-subject-access-review-status :refer :all] ) (:import (java.io File))) (declare v1-self-subject-access-review-data v1-self-subject-access-review) (def v1-self-subject-access-review-data { (ds/opt :apiVersion) string? (ds/opt :kind) string? (ds/opt :metadata) v1-object-meta (ds/req :spec) v1-self-subject-access-review-spec (ds/opt :status) v1-subject-access-review-status }) (def v1-self-subject-access-review (ds/spec {:name ::v1-self-subject-access-review :spec v1-self-subject-access-review-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_self_subject_access_review.clj
clojure
(ns clojure-kubernetes-client.specs.v1-self-subject-access-review (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] [clojure-kubernetes-client.specs.v1-object-meta :refer :all] [clojure-kubernetes-client.specs.v1-self-subject-access-review-spec :refer :all] [clojure-kubernetes-client.specs.v1-subject-access-review-status :refer :all] ) (:import (java.io File))) (declare v1-self-subject-access-review-data v1-self-subject-access-review) (def v1-self-subject-access-review-data { (ds/opt :apiVersion) string? (ds/opt :kind) string? (ds/opt :metadata) v1-object-meta (ds/req :spec) v1-self-subject-access-review-spec (ds/opt :status) v1-subject-access-review-status }) (def v1-self-subject-access-review (ds/spec {:name ::v1-self-subject-access-review :spec v1-self-subject-access-review-data}))
6f9233ef004c279d15d82f856dc1c6326532218feee550c21ab80182c536b9d1
dyzsr/ocaml-selectml
check_for_pack.ml
TEST * native - compiler * * setup - ocamlopt.byte - build - env * * * ocamlopt.byte flags = " -save - ir - after scheduling " ocamlopt_byte_exit_status = " 0 " * * * * script script = " touch empty.ml " * * * * * ocamlopt.byte flags = " -S check_for_pack.cmir - linear -for - pack foo " module = " empty.ml " ocamlopt_byte_exit_status = " 2 " * * * * * * check - ocamlopt.byte - output * native-compiler ** setup-ocamlopt.byte-build-env *** ocamlopt.byte flags = "-save-ir-after scheduling" ocamlopt_byte_exit_status = "0" **** script script = "touch empty.ml" ***** ocamlopt.byte flags = "-S check_for_pack.cmir-linear -for-pack foo" module = "empty.ml" ocamlopt_byte_exit_status = "2" ****** check-ocamlopt.byte-output *) let foo f x = if x > 0 then x * 7 else f x let bar x y = x + y
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/tool-ocamlopt-save-ir/check_for_pack.ml
ocaml
TEST * native - compiler * * setup - ocamlopt.byte - build - env * * * ocamlopt.byte flags = " -save - ir - after scheduling " ocamlopt_byte_exit_status = " 0 " * * * * script script = " touch empty.ml " * * * * * ocamlopt.byte flags = " -S check_for_pack.cmir - linear -for - pack foo " module = " empty.ml " ocamlopt_byte_exit_status = " 2 " * * * * * * check - ocamlopt.byte - output * native-compiler ** setup-ocamlopt.byte-build-env *** ocamlopt.byte flags = "-save-ir-after scheduling" ocamlopt_byte_exit_status = "0" **** script script = "touch empty.ml" ***** ocamlopt.byte flags = "-S check_for_pack.cmir-linear -for-pack foo" module = "empty.ml" ocamlopt_byte_exit_status = "2" ****** check-ocamlopt.byte-output *) let foo f x = if x > 0 then x * 7 else f x let bar x y = x + y
058100ce3c4d8400dd0cab51696dca5469fcf5748d017127ddacfbd9e02aca63
TrustInSoft/tis-interpreter
unmarshal_nums.ml
(**************************************************************************) (* *) Copyright ( C ) 2009 - 2012 ( Institut National de Recherche en Informatique et en (* Automatique) *) (* *) (* All rights reserved. *) (* *) (* Redistribution and use in source and binary forms, with or without *) (* modification, are permitted provided that the following conditions *) (* are met: *) (* * Redistributions of source code must retain the above copyright *) (* notice, this list of conditions and the following disclaimer. *) (* * Redistributions in binary form must reproduce the above *) (* copyright notice, this list of conditions and the following *) (* disclaimer in the documentation and/or other materials provided *) (* with the distribution. *) (* * Neither the name of the <organization> nor the names of its *) (* contributors may be used to endorse or promote products derived *) (* from this software without specific prior written permission. *) (* *) (* THIS SOFTWARE IS PROVIDED BY <INRIA> ''AS IS'' AND ANY *) (* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *) (* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *) (* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE *) LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR (* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT *) (* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *) (* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF *) LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE *) (* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH *) (* DAMAGE. *) (* *) (**************************************************************************) (* caml_unmarshal by Ineffable Casters *) (* Version 3.11.1.8 *) (* Warning: If you are new to OCaml, don't take this as an example of good code. *) open Unmarshal;; let readnat_big32 ch = let len = read32u ch in let v = Obj.repr (Nat.create_nat len) in readblock ch v 4 (len * 4); v ;; let readnat_little32 ch = let len = read32u ch in let v = Obj.repr (Nat.create_nat len) in for i = 1 to len do readblock_rev ch v (i * 4) 4 done; v ;; let readnat_little64 ch = let len = read32u ch in let size = (len + 1) / 2 in let v = Nat.create_nat size in Nat.set_digit_nat v (size - 1) 0; let v = Obj.repr v in for i = 2 to len + 1 do readblock_rev ch v (i * 4) 4 done; v ;; let readnat_big64 ch = let len = read32u ch in let size = (len + 1) / 2 in let v = Nat.create_nat size in Nat.set_digit_nat v (size - 1) 0; let v = Obj.repr v in let rec loop i = if i < len then begin readblock ch v (12 + i * 4) 4; if i + 1 < len then begin readblock ch v (8 + i * 4) 4; loop (i + 2); end end in loop 0; v ;; let readnat = if arch_sixtyfour then if arch_bigendian then readnat_big64 else readnat_little64 else if arch_bigendian then readnat_big32 else readnat_little32 ;; register_custom "_nat" readnat;; let t_nat = Abstract;; let t_big_int = Abstract;; let t_ratio = Abstract;; let t_num = Abstract;;
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/datatype/unmarshal_nums.ml
ocaml
************************************************************************ Automatique) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY <INRIA> ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ caml_unmarshal by Ineffable Casters Version 3.11.1.8 Warning: If you are new to OCaml, don't take this as an example of good code.
Copyright ( C ) 2009 - 2012 ( Institut National de Recherche en Informatique et en LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT open Unmarshal;; let readnat_big32 ch = let len = read32u ch in let v = Obj.repr (Nat.create_nat len) in readblock ch v 4 (len * 4); v ;; let readnat_little32 ch = let len = read32u ch in let v = Obj.repr (Nat.create_nat len) in for i = 1 to len do readblock_rev ch v (i * 4) 4 done; v ;; let readnat_little64 ch = let len = read32u ch in let size = (len + 1) / 2 in let v = Nat.create_nat size in Nat.set_digit_nat v (size - 1) 0; let v = Obj.repr v in for i = 2 to len + 1 do readblock_rev ch v (i * 4) 4 done; v ;; let readnat_big64 ch = let len = read32u ch in let size = (len + 1) / 2 in let v = Nat.create_nat size in Nat.set_digit_nat v (size - 1) 0; let v = Obj.repr v in let rec loop i = if i < len then begin readblock ch v (12 + i * 4) 4; if i + 1 < len then begin readblock ch v (8 + i * 4) 4; loop (i + 2); end end in loop 0; v ;; let readnat = if arch_sixtyfour then if arch_bigendian then readnat_big64 else readnat_little64 else if arch_bigendian then readnat_big32 else readnat_little32 ;; register_custom "_nat" readnat;; let t_nat = Abstract;; let t_big_int = Abstract;; let t_ratio = Abstract;; let t_num = Abstract;;
0737bb02a7141544f52672ec9d964cf60de7bcbfcf92741dfd97b32d839d94bc
NetComposer/nksip
nksip_registrar_plugin.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2019 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- %% @doc NkSIP Registrar Plugin Callbacks -module(nksip_registrar_plugin). -author('Carlos Gonzalez <>'). -include("nksip.hrl"). -include("nksip_registrar.hrl"). -export([plugin_deps/0, plugin_config/3, plugin_cache/3]). %% =================================================================== %% Plugin %% =================================================================== plugin_deps() -> [nksip]. %% @doc plugin_config(_PkgId, Config, #{class:=?PACKAGE_CLASS_SIP}) -> Syntax = #{ sip_allow => words, sip_registrar_default_time => {integer, 5, none}, sip_registrar_min_time => {integer, 1, none}, sip_registrar_max_time => {integer, 60, none} }, case nklib_syntax:parse_all(Config, Syntax) of {ok, Config2} -> Allow1 = maps:get(sip_allow, Config2, nksip_syntax:default_allow()), Allow2 = nklib_util:store_value(<<"REGISTER">>, Allow1), Config3 = Config2#{sip_allow=>Allow2}, {ok, Config3}; {error, Error} -> {error, Error} end. plugin_cache(_PkgId, Config, _Service) -> Cache = #{ times => #nksip_registrar_time{ min = maps:get(sip_registrar_min_time, Config, 60), max = maps:get(sip_registrar_max_time, Config, 86400), default = maps:get(sip_registrar_default_time, Config, 3600) } }, {ok, Cache}.
null
https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/src/plugins/nksip_registrar_plugin.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc NkSIP Registrar Plugin Callbacks =================================================================== Plugin =================================================================== @doc
Copyright ( c ) 2019 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(nksip_registrar_plugin). -author('Carlos Gonzalez <>'). -include("nksip.hrl"). -include("nksip_registrar.hrl"). -export([plugin_deps/0, plugin_config/3, plugin_cache/3]). plugin_deps() -> [nksip]. plugin_config(_PkgId, Config, #{class:=?PACKAGE_CLASS_SIP}) -> Syntax = #{ sip_allow => words, sip_registrar_default_time => {integer, 5, none}, sip_registrar_min_time => {integer, 1, none}, sip_registrar_max_time => {integer, 60, none} }, case nklib_syntax:parse_all(Config, Syntax) of {ok, Config2} -> Allow1 = maps:get(sip_allow, Config2, nksip_syntax:default_allow()), Allow2 = nklib_util:store_value(<<"REGISTER">>, Allow1), Config3 = Config2#{sip_allow=>Allow2}, {ok, Config3}; {error, Error} -> {error, Error} end. plugin_cache(_PkgId, Config, _Service) -> Cache = #{ times => #nksip_registrar_time{ min = maps:get(sip_registrar_min_time, Config, 60), max = maps:get(sip_registrar_max_time, Config, 86400), default = maps:get(sip_registrar_default_time, Config, 3600) } }, {ok, Cache}.
11f19d28fc6949b53ac7ab30975ce58ddaa823cda1ac7aaaa3efe34a010401b4
journeyman-cc/smeagol
layout.clj
(ns ^{:doc "Render a page as HTML." :author "Simon Brooke"} smeagol.layout (:require [clojure.java.io :as cjio] [clojure.string :as s] [compojure.response :refer [Renderable]] [environ.core :refer [env]] [hiccup.core :refer [html]] [ring.util.anti-forgery :refer [anti-forgery-field]] [ring.util.response :refer [content-type response]] [selmer.parser :as parser] [smeagol.configuration :refer [config]] [smeagol.sanity :refer :all] [smeagol.util :as util])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; ;;;; Smeagol: a very simple Wiki engine. ;;;; ;;;; 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 . ;;;; Copyright ( C ) 2014 ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def template-path "Path to the resource directory in which Selmer templates are stored. These should be in a place which is not editable from the Wiki, otherwise users may break things which they cannot subsequently fix!" "templates/") (parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field))) ;; Attempt to do internationalisation more neatly This tag takes two arguments , the first is a key , the ( optional ) second is a ;; default. The key is looked up in the i18n (parser/add-tag! :i18n (fn [args context-map] (let [messages (:i18n context-map) default (or (second args) (first args))] (if (map? messages) (or (messages (keyword (first args))) default) default)))) (deftype RenderableTemplate ;; Boilerplate from Luminus. Load a template file into an object which may ;; be rendered. [template params] Renderable (render [this request] (try (content-type (->> (assoc params (keyword (s/replace template #".html" "-selected")) "active" :i18n (util/get-messages request) :dev (env :dev) :servlet-context (if-let [context (:servlet-context request)] ;; If we're not inside a serlvet environment (for ;; example when using mock requests), then ;; .getContextPath might not exist (try (.getContextPath context) (catch IllegalArgumentException _ context)))) (parser/render-file (str template-path template)) response) "text/html; charset=utf-8") (catch Exception any (show-sanity-check-error any))))) (defn render "Boilerplate from Luminus. Render an HTML page based on this `template` and these `params`. Returns HTML source as a string." [template & [params]] (try (RenderableTemplate. template params) (catch Exception any (show-sanity-check-error any))))
null
https://raw.githubusercontent.com/journeyman-cc/smeagol/a775ef7b831a2fbcf9c98380367edc16d39c4c6c/src/smeagol/layout.clj
clojure
Smeagol: a very simple Wiki engine. This program is free software; you can redistribute it and/or either version 2 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. along with this program; if not, write to the Free Software Attempt to do internationalisation more neatly default. The key is looked up in the i18n Boilerplate from Luminus. Load a template file into an object which may be rendered. If we're not inside a serlvet environment (for example when using mock requests), then .getContextPath might not exist
(ns ^{:doc "Render a page as HTML." :author "Simon Brooke"} smeagol.layout (:require [clojure.java.io :as cjio] [clojure.string :as s] [compojure.response :refer [Renderable]] [environ.core :refer [env]] [hiccup.core :refer [html]] [ring.util.anti-forgery :refer [anti-forgery-field]] [ring.util.response :refer [content-type response]] [selmer.parser :as parser] [smeagol.configuration :refer [config]] [smeagol.sanity :refer :all] [smeagol.util :as util])) modify it under the terms of the GNU General Public License of the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public License Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA . Copyright ( C ) 2014 (def template-path "Path to the resource directory in which Selmer templates are stored. These should be in a place which is not editable from the Wiki, otherwise users may break things which they cannot subsequently fix!" "templates/") (parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field))) This tag takes two arguments , the first is a key , the ( optional ) second is a (parser/add-tag! :i18n (fn [args context-map] (let [messages (:i18n context-map) default (or (second args) (first args))] (if (map? messages) (or (messages (keyword (first args))) default) default)))) (deftype RenderableTemplate [template params] Renderable (render [this request] (try (content-type (->> (assoc params (keyword (s/replace template #".html" "-selected")) "active" :i18n (util/get-messages request) :dev (env :dev) :servlet-context (if-let [context (:servlet-context request)] (try (.getContextPath context) (catch IllegalArgumentException _ context)))) (parser/render-file (str template-path template)) response) "text/html; charset=utf-8") (catch Exception any (show-sanity-check-error any))))) (defn render "Boilerplate from Luminus. Render an HTML page based on this `template` and these `params`. Returns HTML source as a string." [template & [params]] (try (RenderableTemplate. template params) (catch Exception any (show-sanity-check-error any))))
029ed53027e58ca9aa6ce52f9d3974d56f114253b9a94f7611477b9a602de8bd
facebook/flow
flow_cache.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Utils_js open Reason open Type open TypeUtil module ImplicitTypeArgument = Instantiation_utils.ImplicitTypeArgument (* Cache that remembers pairs of types that are passed to __flow. *) module FlowConstraint = struct let rec toplevel_use_op = function | Frame (_frame, use_op) -> toplevel_use_op use_op | Op (Speculation use_op) -> toplevel_use_op use_op | use_op -> use_op attempt to read LB / UB pair from cache , add if absent let get cx (l, u) = match (l, u) with (* Don't cache constraints involving type variables, since the corresponding typing rules are already sufficiently robust. *) | (OpenT _, _) | (_, UseT (_, OpenT _)) | (_, ReposUseT _) -> false | _ -> (* Use ops are purely for better error messages: they should have no effect on type checking. However, recursively nested use ops can pose non-termination problems. To ensure proper caching, we hash use ops to just their toplevel structure. *) let u = mod_use_op_of_use_t toplevel_use_op u in let cache = Context.constraint_cache cx in let cache' = FlowSet.add l u !cache in let found = cache' == !cache in if not found then cache := cache' else if Context.is_verbose cx then prerr_endlinef "%sFlowConstraint cache hit on (%s, %s)" (Context.pid_prefix cx) (string_of_ctor l) (string_of_use_ctor u); found end (* Cache that limits instantiation of polymorphic definitions. Intuitively, for each operation on a polymorphic definition, we remember the type arguments we use to specialize the type parameters. An operation is identified by its reason, and possibly the reasons of its arguments. We don't use the entire operation for caching since it may contain the very type variables we are trying to limit the creation of with the cache (e.g., those representing the result): the cache would be useless if we considered those type variables as part of the identity of the operation. *) module PolyInstantiation = struct let find cx reason_tapp typeparam op_reason = if Context.lti cx then ImplicitTypeArgument.mk_targ cx typeparam (Nel.hd op_reason) reason_tapp else let cache = Context.instantiation_cache cx in match Reason.ImplicitInstantiationReasonMap.find_opt (reason_tapp, typeparam.reason, op_reason) !cache with | Some t -> t | None -> let t = ImplicitTypeArgument.mk_targ cx typeparam (Nel.hd op_reason) reason_tapp in cache := Reason.ImplicitInstantiationReasonMap.add (reason_tapp, typeparam.reason, op_reason) t !cache; t end module Eval = struct let id cx t defer_use = let (eval_id_cache, id_cache) = Context.eval_id_cache cx in match t with | EvalT (_, d, i) when d = defer_use -> (match Type.EvalIdCacheMap.find_opt i !eval_id_cache with | Some t -> t | None -> let i = Type.Eval.generate_id () in eval_id_cache := Type.EvalIdCacheMap.add i t !eval_id_cache; EvalT (t, defer_use, i)) | _ -> let cache_key = (t, defer_use) in let id = match Type.IdCacheMap.find_opt cache_key !id_cache with | Some i -> i | None -> let i = Type.Eval.generate_id () in id_cache := Type.IdCacheMap.add cache_key i !id_cache; i in EvalT (t, defer_use, id) let find_repos cx t defer_use id = let repos_cache = Context.eval_repos_cache cx in let cache_key = (t, defer_use, id) in Type.EvalReposCacheMap.find_opt cache_key !repos_cache let add_repos cx t defer_use id tvar = let repos_cache = Context.eval_repos_cache cx in let cache_key = (t, defer_use, id) in repos_cache := Type.EvalReposCacheMap.add cache_key tvar !repos_cache end module Fix = struct let find cx is_this i = let cache = Context.fix_cache cx in let cache_key = (is_this, i) in Type.FixCacheMap.find_opt cache_key !cache let add cx is_this i tvar = let cache = Context.fix_cache cx in let cache_key = (is_this, i) in cache := Type.FixCacheMap.add cache_key tvar !cache end (* debug util: please don't dead-code-eliminate *) (* Summarize flow constraints in cache as ctor/reason pairs, and return counts for each group. *) let summarize_flow_constraint cx = let group_counts = FlowSet.fold (fun (l, u) map -> let key = spf "[%s] %s => [%s] %s" (string_of_ctor l) (string_of_reason (reason_of_t l)) (string_of_use_ctor u) (string_of_reason (reason_of_use_t u)) in match SMap.find_opt key map with | None -> SMap.add key 0 map | Some i -> SMap.add key (i + 1) map) !(Context.constraint_cache cx) SMap.empty in SMap.elements group_counts |> List.sort (fun (_, i1) (_, i2) -> Stdlib.compare i1 i2)
null
https://raw.githubusercontent.com/facebook/flow/105ad30f566f401db9cafcb49cd2831fb29e87c5/src/typing/flow_cache.ml
ocaml
Cache that remembers pairs of types that are passed to __flow. Don't cache constraints involving type variables, since the corresponding typing rules are already sufficiently robust. Use ops are purely for better error messages: they should have no effect on type checking. However, recursively nested use ops can pose non-termination problems. To ensure proper caching, we hash use ops to just their toplevel structure. Cache that limits instantiation of polymorphic definitions. Intuitively, for each operation on a polymorphic definition, we remember the type arguments we use to specialize the type parameters. An operation is identified by its reason, and possibly the reasons of its arguments. We don't use the entire operation for caching since it may contain the very type variables we are trying to limit the creation of with the cache (e.g., those representing the result): the cache would be useless if we considered those type variables as part of the identity of the operation. debug util: please don't dead-code-eliminate Summarize flow constraints in cache as ctor/reason pairs, and return counts for each group.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open Utils_js open Reason open Type open TypeUtil module ImplicitTypeArgument = Instantiation_utils.ImplicitTypeArgument module FlowConstraint = struct let rec toplevel_use_op = function | Frame (_frame, use_op) -> toplevel_use_op use_op | Op (Speculation use_op) -> toplevel_use_op use_op | use_op -> use_op attempt to read LB / UB pair from cache , add if absent let get cx (l, u) = match (l, u) with | (OpenT _, _) | (_, UseT (_, OpenT _)) | (_, ReposUseT _) -> false | _ -> let u = mod_use_op_of_use_t toplevel_use_op u in let cache = Context.constraint_cache cx in let cache' = FlowSet.add l u !cache in let found = cache' == !cache in if not found then cache := cache' else if Context.is_verbose cx then prerr_endlinef "%sFlowConstraint cache hit on (%s, %s)" (Context.pid_prefix cx) (string_of_ctor l) (string_of_use_ctor u); found end module PolyInstantiation = struct let find cx reason_tapp typeparam op_reason = if Context.lti cx then ImplicitTypeArgument.mk_targ cx typeparam (Nel.hd op_reason) reason_tapp else let cache = Context.instantiation_cache cx in match Reason.ImplicitInstantiationReasonMap.find_opt (reason_tapp, typeparam.reason, op_reason) !cache with | Some t -> t | None -> let t = ImplicitTypeArgument.mk_targ cx typeparam (Nel.hd op_reason) reason_tapp in cache := Reason.ImplicitInstantiationReasonMap.add (reason_tapp, typeparam.reason, op_reason) t !cache; t end module Eval = struct let id cx t defer_use = let (eval_id_cache, id_cache) = Context.eval_id_cache cx in match t with | EvalT (_, d, i) when d = defer_use -> (match Type.EvalIdCacheMap.find_opt i !eval_id_cache with | Some t -> t | None -> let i = Type.Eval.generate_id () in eval_id_cache := Type.EvalIdCacheMap.add i t !eval_id_cache; EvalT (t, defer_use, i)) | _ -> let cache_key = (t, defer_use) in let id = match Type.IdCacheMap.find_opt cache_key !id_cache with | Some i -> i | None -> let i = Type.Eval.generate_id () in id_cache := Type.IdCacheMap.add cache_key i !id_cache; i in EvalT (t, defer_use, id) let find_repos cx t defer_use id = let repos_cache = Context.eval_repos_cache cx in let cache_key = (t, defer_use, id) in Type.EvalReposCacheMap.find_opt cache_key !repos_cache let add_repos cx t defer_use id tvar = let repos_cache = Context.eval_repos_cache cx in let cache_key = (t, defer_use, id) in repos_cache := Type.EvalReposCacheMap.add cache_key tvar !repos_cache end module Fix = struct let find cx is_this i = let cache = Context.fix_cache cx in let cache_key = (is_this, i) in Type.FixCacheMap.find_opt cache_key !cache let add cx is_this i tvar = let cache = Context.fix_cache cx in let cache_key = (is_this, i) in cache := Type.FixCacheMap.add cache_key tvar !cache end let summarize_flow_constraint cx = let group_counts = FlowSet.fold (fun (l, u) map -> let key = spf "[%s] %s => [%s] %s" (string_of_ctor l) (string_of_reason (reason_of_t l)) (string_of_use_ctor u) (string_of_reason (reason_of_use_t u)) in match SMap.find_opt key map with | None -> SMap.add key 0 map | Some i -> SMap.add key (i + 1) map) !(Context.constraint_cache cx) SMap.empty in SMap.elements group_counts |> List.sort (fun (_, i1) (_, i2) -> Stdlib.compare i1 i2)
9a62c018c7fcf11746cd9408214e3ca3a3cc0c9aec266c26c148a481e6e700fc
raph-amiard/CamllVM
24_complexnums_clean.ml
open Complex let print_complex z = Printf.printf "%f + %f i\n" z.re z.im let () = let a = { re = 1.0; im = 1.0 } and b = { re = 3.14159; im = 1.25 } in print_complex (add a b); print_complex (mul a b); print_complex (inv a); print_complex (neg a); print_complex (conj a)
null
https://raw.githubusercontent.com/raph-amiard/CamllVM/d36928f0e81a6f4f65ddd3a8653887d187632dc2/test/testfiles/24_complexnums_clean.ml
ocaml
open Complex let print_complex z = Printf.printf "%f + %f i\n" z.re z.im let () = let a = { re = 1.0; im = 1.0 } and b = { re = 3.14159; im = 1.25 } in print_complex (add a b); print_complex (mul a b); print_complex (inv a); print_complex (neg a); print_complex (conj a)
31aedeee40dd5ac8e336a3a23d81128179155b8af5cc25708c7735758594a05b
mblake/jambi-hello-world
core.clj
(ns hello_world.core) (import 'com.trolltech.qt.gui.QApplication 'com.trolltech.qt.gui.QPushButton) (defn -main [] (QApplication/initialize (into-array [""])) (.show (new QPushButton "Hello World")) (QApplication/exec) )
null
https://raw.githubusercontent.com/mblake/jambi-hello-world/9495552b60266690e99a6f2a67d09b313baf6a21/src/hello_world/core.clj
clojure
(ns hello_world.core) (import 'com.trolltech.qt.gui.QApplication 'com.trolltech.qt.gui.QPushButton) (defn -main [] (QApplication/initialize (into-array [""])) (.show (new QPushButton "Hello World")) (QApplication/exec) )
1c4d02f046b3ceef284ad94dfff2a8b0377e08b00abd1f7da8a25e238c507168
colis-anr/morbig
CSTSerializers.mli
(**************************************************************************) (* -*- tuareg -*- *) (* *) Copyright ( C ) 2017 - 2021 , , . (* *) (* This is free software: you can redistribute it and/or modify it *) under the terms of the GNU General Public License , version 3 . (* *) (* Additional terms apply, due to the reproduction of portions of *) (* the POSIX standard. Please refer to the file COPYING for details. *) (**************************************************************************) * for concrete syntax trees . val program_to_yojson : CST.program -> Yojson.Safe.t val program_of_yojson : Yojson.Safe.t -> CST.program Ppx_deriving_yojson_runtime.error_or val bracket_expression_to_yojson : CST.bracket_expression -> Yojson.Safe.t val bracket_expression_of_yojson : Yojson.Safe.t -> CST.bracket_expression Ppx_deriving_yojson_runtime.error_or
null
https://raw.githubusercontent.com/colis-anr/morbig/42c5b9e2c806d4f9db210e7c100c70cd69ce7f08/src/CSTSerializers.mli
ocaml
************************************************************************ -*- tuareg -*- This is free software: you can redistribute it and/or modify it Additional terms apply, due to the reproduction of portions of the POSIX standard. Please refer to the file COPYING for details. ************************************************************************
Copyright ( C ) 2017 - 2021 , , . under the terms of the GNU General Public License , version 3 . * for concrete syntax trees . val program_to_yojson : CST.program -> Yojson.Safe.t val program_of_yojson : Yojson.Safe.t -> CST.program Ppx_deriving_yojson_runtime.error_or val bracket_expression_to_yojson : CST.bracket_expression -> Yojson.Safe.t val bracket_expression_of_yojson : Yojson.Safe.t -> CST.bracket_expression Ppx_deriving_yojson_runtime.error_or
06e6bde6e31c472e523fe5b930fbe3f395ec493cf84016f028629d7df1180d6f
gas2serra/mcclim-desktop
app-manager-config.lisp
(in-package :desktop-user) (setf (application-entry-fn *application*) #'(lambda (application &rest args) (declare (ignore application args)) (desktop-app-manager:run-app-manager)))
null
https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/dot-mcclim-desktop/config/app-manager-config.lisp
lisp
(in-package :desktop-user) (setf (application-entry-fn *application*) #'(lambda (application &rest args) (declare (ignore application args)) (desktop-app-manager:run-app-manager)))
5ebf873f49929859f121042e0115fbd9c661f28600fa03db41a85b5eb3c0cb2e
adamwalker/clash-utils
Butterfly.hs
module Clash.DSP.FFT.Butterfly ( Butterfly, difButterfly, ditButterfly ) where import Clash.Prelude type Butterfly dom twiddle input output = Signal dom twiddle -> Signal dom input -> Signal dom input -> (Signal dom output, Signal dom output) difButterfly :: Num a => Butterfly dom a a a difButterfly twiddle upper lower = (sum, twiddle * diff) where sum = upper + lower diff = upper - lower ditButterfly :: Num a => Butterfly dom a a a ditButterfly twiddle upper lower = (sum, diff) where twiddled = lower * twiddle sum = upper + twiddled diff = upper - twiddled
null
https://raw.githubusercontent.com/adamwalker/clash-utils/95408d3f195b2e77b1f67b7ea045335f6e2abac6/src/Clash/DSP/FFT/Butterfly.hs
haskell
module Clash.DSP.FFT.Butterfly ( Butterfly, difButterfly, ditButterfly ) where import Clash.Prelude type Butterfly dom twiddle input output = Signal dom twiddle -> Signal dom input -> Signal dom input -> (Signal dom output, Signal dom output) difButterfly :: Num a => Butterfly dom a a a difButterfly twiddle upper lower = (sum, twiddle * diff) where sum = upper + lower diff = upper - lower ditButterfly :: Num a => Butterfly dom a a a ditButterfly twiddle upper lower = (sum, diff) where twiddled = lower * twiddle sum = upper + twiddled diff = upper - twiddled
1d4f780d27ff7c0b08dbfcea74add598ab130147932918b133aa30d7a986caef
manavpatnaik/haskell
7_zip.hs
main = do zip : takes 2 lists and returns a list of pairs of the elements of the 2 lists print(zip [1,2,3] "dam") print(zip [1,2,3,4] "ab") print(zip [1,2,3] "abcde")
null
https://raw.githubusercontent.com/manavpatnaik/haskell/9e7c805afb2607468c2e2977247266ccc19d24b6/higher_order_functions/7_zip.hs
haskell
main = do zip : takes 2 lists and returns a list of pairs of the elements of the 2 lists print(zip [1,2,3] "dam") print(zip [1,2,3,4] "ab") print(zip [1,2,3] "abcde")
8851144bdbf51988703fa4bb68d75d480eca0d8df15242337d6f9c150c7a9085
racket/racket7
suggestions.rkt
#lang racket/base (require racket/set racket/path setup/dirs syntax/modcollapse (prefix-in db: "../db.rkt")) (provide pkg-catalog-suggestions-for-module) (define (choose-catalog-file) (define default (db:current-pkg-catalog-file)) (if (file-exists? default) default (let ([installation (build-path (find-share-dir) "pkgs" (file-name-from-path default))]) (if (file-exists? installation) installation default)))) (define (pkg-catalog-suggestions-for-module module-path #:catalog-file [catalog-file (choose-catalog-file)]) (if (file-exists? catalog-file) (parameterize ([db:current-pkg-catalog-file catalog-file]) (let* ([mod (collapse-module-path module-path (lambda () (build-path (current-directory) "dummy.rkt")))] [pkgs (db:get-module-pkgs mod)] [more-pkgs (let ([rx:reader #rx"/lang/reader[.]rkt$"]) (if (and (pair? mod) (eq? (car mod) 'lib) (regexp-match rx:reader (cadr mod))) (db:get-module-pkgs `(lib ,(regexp-replace rx:reader (cadr mod) "/main.rkt"))) null))]) (sort (set->list (list->set (map db:pkg-name (append pkgs more-pkgs)))) string<?))) null))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/pkg/private/suggestions.rkt
racket
#lang racket/base (require racket/set racket/path setup/dirs syntax/modcollapse (prefix-in db: "../db.rkt")) (provide pkg-catalog-suggestions-for-module) (define (choose-catalog-file) (define default (db:current-pkg-catalog-file)) (if (file-exists? default) default (let ([installation (build-path (find-share-dir) "pkgs" (file-name-from-path default))]) (if (file-exists? installation) installation default)))) (define (pkg-catalog-suggestions-for-module module-path #:catalog-file [catalog-file (choose-catalog-file)]) (if (file-exists? catalog-file) (parameterize ([db:current-pkg-catalog-file catalog-file]) (let* ([mod (collapse-module-path module-path (lambda () (build-path (current-directory) "dummy.rkt")))] [pkgs (db:get-module-pkgs mod)] [more-pkgs (let ([rx:reader #rx"/lang/reader[.]rkt$"]) (if (and (pair? mod) (eq? (car mod) 'lib) (regexp-match rx:reader (cadr mod))) (db:get-module-pkgs `(lib ,(regexp-replace rx:reader (cadr mod) "/main.rkt"))) null))]) (sort (set->list (list->set (map db:pkg-name (append pkgs more-pkgs)))) string<?))) null))
62ca8b65b8ce17b68d24be574c4e3c6c28cf5cf11d6aabe2a7b006f26433edc2
bobeff/playground
010.rkt
Exercise 10 . Now relax , eat , sleep , and then tackle the next chapter . #lang racket (require racket/block) (define (life-cycle steps) (cond ((>= steps 0) (block (life-cycle (- steps 1)) (let ((step (remainder steps 3))) (cond ((= step 0) (println "relax")) ((= step 1) (println "eat")) ((= step 2) (println "sleep")))))))) (life-cycle 35)
null
https://raw.githubusercontent.com/bobeff/playground/7072dbd7e0acd690749abe1498dd5f247cc21637/htdp-second-edition/exercises/010.rkt
racket
Exercise 10 . Now relax , eat , sleep , and then tackle the next chapter . #lang racket (require racket/block) (define (life-cycle steps) (cond ((>= steps 0) (block (life-cycle (- steps 1)) (let ((step (remainder steps 3))) (cond ((= step 0) (println "relax")) ((= step 1) (println "eat")) ((= step 2) (println "sleep")))))))) (life-cycle 35)
287bfadd99b1f68ab10445ccc411e0f3ba9cc836b0ef7e36f376c309e7ce87fa
lispnik/iup
tuio-cffi.lisp
(defpackage #:iup-tuio-cffi (:use #:common-lisp)) (in-package #:iup-tuio-cffi) (cffi:define-foreign-library iup-tuio (:unix "libiuptuio.so") (:windows "iuptuio.dll") (t (:default "iuptuio"))) (cffi:use-foreign-library iup-tuio) (cffi:defcfun (%iup-tuio-open "IupTuioOpen") :int)
null
https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/tuio/tuio-cffi.lisp
lisp
(defpackage #:iup-tuio-cffi (:use #:common-lisp)) (in-package #:iup-tuio-cffi) (cffi:define-foreign-library iup-tuio (:unix "libiuptuio.so") (:windows "iuptuio.dll") (t (:default "iuptuio"))) (cffi:use-foreign-library iup-tuio) (cffi:defcfun (%iup-tuio-open "IupTuioOpen") :int)
d3db427ae1cb275a2f4e94ff004fd36438d164cbf5b74850fddf1c9f1bf91bc7
nammayatri/beckn-gateway
Subscriber.hs
Copyright 2022 - 23 , Juspay India Pvt Ltd 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 < / > . Copyright 2022-23, Juspay India Pvt Ltd This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} module Domain.Subscriber (module Reexport) where import Kernel.Types.Beckn.Domain as Reexport import Kernel.Types.Registry.Subscriber as Reexport
null
https://raw.githubusercontent.com/nammayatri/beckn-gateway/dcdadbb647a3049d62df283d35ae61eb5420d50e/app/mock-registry/src/Domain/Subscriber.hs
haskell
Copyright 2022 - 23 , Juspay India Pvt Ltd 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 < / > . Copyright 2022-23, Juspay India Pvt Ltd This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} module Domain.Subscriber (module Reexport) where import Kernel.Types.Beckn.Domain as Reexport import Kernel.Types.Registry.Subscriber as Reexport
f1926b7991d648c7904f482ee9cd622dbeef619af2bfd6b7aea37454a871a63f
robertmeta/cowboy-examples
redirect_sup.erl
-module(redirect_sup). -behaviour(supervisor). -export([init/1, start_link/0]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, {{one_for_one, 10, 10}, []}}.
null
https://raw.githubusercontent.com/robertmeta/cowboy-examples/d03c289c9fb0d750eca11e3f1671e74d1841bd09/apps/redirect/src/redirect_sup.erl
erlang
-module(redirect_sup). -behaviour(supervisor). -export([init/1, start_link/0]). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). init([]) -> {ok, {{one_for_one, 10, 10}, []}}.
3150bc633f738f4ab749642ef33b327b07a29d98cddc758bcbc9b9775a73fbfa
janestreet/merlin-jst
location.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Source code locations ( ranges of positions ) , used in parsetree . { b Warning :} this module is unstable and part of { { ! Compiler_libs}compiler - libs } . {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) open Format loc_ghost : Ghost expressions and patterns : expressions and patterns that do not appear explicitly in the source file they have the loc_ghost flag set to true . Then the profiler will not try to instrument them and the -annot option will not try to display their type . Every grammar rule that generates an element with a location must make at most one non - ghost element , the topmost one . How to tell whether your location must be ghost : A location corresponds to a range of characters in the source file . If the location contains a piece of code that is syntactically valid ( according to the documentation ) , and corresponds to the AST node , then the location must be real ; in all other cases , it must be ghost . expressions and patterns that do not appear explicitly in the source file they have the loc_ghost flag set to true. Then the profiler will not try to instrument them and the -annot option will not try to display their type. Every grammar rule that generates an element with a location must make at most one non-ghost element, the topmost one. How to tell whether your location must be ghost: A location corresponds to a range of characters in the source file. If the location contains a piece of code that is syntactically valid (according to the documentation), and corresponds to the AST node, then the location must be real; in all other cases, it must be ghost. *) type t = Warnings.loc = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } (** Note on the use of Lexing.position in this module. If [pos_fname = ""], then use [!input_name] instead. If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and re-parse the file to get the line and character numbers. Else all fields are correct. *) val none : t (** An arbitrary value of type [t]; describes an empty ghost range. *) val is_none : t -> bool val in_file : string -> t (** Return an empty ghost range located in a given file. *) val init : Lexing.lexbuf -> string -> unit (** Set the file name and line number of the [lexbuf] to be the start of the named file. *) val curr : Lexing.lexbuf -> t (** Get the location of the current token from the [lexbuf]. *) val symbol_rloc: unit -> t val symbol_gloc: unit -> t * [ rhs_loc n ] returns the location of the symbol at position [ n ] , starting at 1 , in the current parser rule . at 1, in the current parser rule. *) val rhs_loc: int -> t val rhs_interval: int -> int -> t val get_pos_info: Lexing.position -> string * int * int (** file, line, char *) type 'a loc = { txt : 'a; loc : t; } val mknoloc : 'a -> 'a loc val mkloc : 'a -> t -> 'a loc (** {1 Input info} *) val input_name: string ref val input_lexbuf: Lexing.lexbuf option ref * { 1 Toplevel - specific functions } val echo_eof: unit -> unit val reset: unit -> unit * { 1 Printing locations } val rewrite_absolute_path: string -> string (** rewrite absolute path to honor the BUILD_PATH_PREFIX_MAP variable (-builds.org/specs/build-path-prefix-map/) if it is set. *) val absolute_path: string -> string val show_filename: string -> string (** In -absname mode, return the absolute path for this filename. Otherwise, returns the filename unchanged. *) val print_filename: formatter -> string -> unit val print_loc: formatter -> t -> unit val print_locs: formatter -> t list -> unit * { 1 Reporting errors and warnings } * { 2 The type of reports and report printers } type msg = (Format.formatter -> unit) loc val msg: ?loc:t -> ('a, Format.formatter, unit, msg) format4 -> 'a type report_kind = | Report_error | Report_warning of string | Report_warning_as_error of string | Report_alert of string | Report_alert_as_error of string type error_source = Lexer | Parser | Typer | Warning | Unknown | Env | Config type report = { kind : report_kind; main : msg; sub : msg list; source : error_source; } val loc_of_report: report -> t val print_main : formatter -> report -> unit val print_sub_msg : formatter -> msg -> unit type report_printer = { (* The entry point *) pp : report_printer -> Format.formatter -> report -> unit; pp_report_kind : report_printer -> report -> Format.formatter -> report_kind -> unit; pp_main_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_main_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; pp_submsgs : report_printer -> report -> Format.formatter -> msg list -> unit; pp_submsg : report_printer -> report -> Format.formatter -> msg -> unit; pp_submsg_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_submsg_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; } (** A printer for [report]s, defined using open-recursion. The goal is to make it easy to define new printers by re-using code from existing ones. *) * { 2 Report printers used in the compiler } val batch_mode_printer: report_printer * { 2 Printing a [ report ] } val print_report: formatter -> report -> unit (** Display an error or warning report. *) val report_printer: (unit -> report_printer) ref (** Hook for redefining the printer of reports. The hook is a [unit -> report_printer] and not simply a [report_printer]: this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly. *) val default_report_printer: unit -> report_printer (** Original report printer for use in hooks. *) (** {1 Reporting warnings} *) (** {2 Converting a [Warnings.t] into a [report]} *) val report_warning: t -> Warnings.t -> report option * [ report_warning w ] produces a report for the given warning [ w ] , or [ None ] if the warning is not to be printed . [None] if the warning is not to be printed. *) val warning_reporter: (t -> Warnings.t -> report option) ref (** Hook for intercepting warnings. *) val default_warning_reporter: t -> Warnings.t -> report option (** Original warning reporter for use in hooks. *) * { 2 Printing warnings } val formatter_for_warnings : formatter ref val print_warning: t -> formatter -> Warnings.t -> unit * Prints a warning . This is simply the composition of [ report_warning ] and [ print_report ] . [print_report]. *) val prerr_warning_ref: (t -> Warnings.t -> unit) ref val prerr_warning: t -> Warnings.t -> unit (** Same as [print_warning], but uses [!formatter_for_warnings] as output formatter. *) (** {1 Reporting alerts} *) (** {2 Converting an [Alert.t] into a [report]} *) val report_alert: t -> Warnings.alert -> report option (** [report_alert loc w] produces a report for the given alert [w], or [None] if the alert is not to be printed. *) val alert_reporter: (t -> Warnings.alert -> report option) ref (** Hook for intercepting alerts. *) val default_alert_reporter: t -> Warnings.alert -> report option (** Original alert reporter for use in hooks. *) * { 2 Printing alerts } val print_alert: t -> formatter -> Warnings.alert -> unit * Prints an alert . This is simply the composition of [ report_alert ] and [ print_report ] . [print_report]. *) val prerr_alert_ref: (t -> Warnings.alert -> unit) ref val prerr_alert: t -> Warnings.alert -> unit (** Same as [print_alert], but uses [!formatter_for_warnings] as output formatter. *) val deprecated: ?def:t -> ?use:t -> t -> string -> unit (** Prints a deprecation alert. *) val alert: ?def:t -> ?use:t -> kind:string -> t -> string -> unit (** Prints an arbitrary alert. *) * { 1 Reporting errors } type error = report (** An [error] is a [report] which [report_kind] must be [Report_error]. *) val error: ?loc:t -> ?sub:msg list -> ?source:error_source -> string -> error val errorf: ?loc:t -> ?sub:msg list -> ?source:error_source -> ('a, Format.formatter, unit, error) format4 -> 'a val error_of_printer: ?loc:t -> ?sub:msg list -> ?source:error_source -> (formatter -> 'a -> unit) -> 'a -> error val error_of_printer_file: ?source:error_source -> (formatter -> 'a -> unit) -> 'a -> error (** {1 Automatically reporting errors for raised exceptions} *) val register_error_of_exn: (exn -> error option) -> unit (** Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using [register_error_of_exn]. The result of the printer is an [error] value containing a location, a message, and optionally sub-messages (each of them being located as well). *) val error_of_exn: exn -> [ `Ok of error | `Already_displayed ] option exception Error of error (** Raising [Error e] signals an error [e]; the exception will be caught and the error will be printed. *) exception Already_displayed_error (** Raising [Already_displayed_error] signals an error which has already been printed. The exception will be caught, but nothing will be printed *) val raise_errorf: ?loc:t -> ?sub:msg list -> ?source:error_source -> ('a, Format.formatter, unit, 'b) format4 -> 'a val report_exception: formatter -> exn -> unit * the exception if it is unknown .
null
https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/src/ocaml/parsing/location.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Note on the use of Lexing.position in this module. If [pos_fname = ""], then use [!input_name] instead. If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and re-parse the file to get the line and character numbers. Else all fields are correct. * An arbitrary value of type [t]; describes an empty ghost range. * Return an empty ghost range located in a given file. * Set the file name and line number of the [lexbuf] to be the start of the named file. * Get the location of the current token from the [lexbuf]. * file, line, char * {1 Input info} * rewrite absolute path to honor the BUILD_PATH_PREFIX_MAP variable (-builds.org/specs/build-path-prefix-map/) if it is set. * In -absname mode, return the absolute path for this filename. Otherwise, returns the filename unchanged. The entry point * A printer for [report]s, defined using open-recursion. The goal is to make it easy to define new printers by re-using code from existing ones. * Display an error or warning report. * Hook for redefining the printer of reports. The hook is a [unit -> report_printer] and not simply a [report_printer]: this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly. * Original report printer for use in hooks. * {1 Reporting warnings} * {2 Converting a [Warnings.t] into a [report]} * Hook for intercepting warnings. * Original warning reporter for use in hooks. * Same as [print_warning], but uses [!formatter_for_warnings] as output formatter. * {1 Reporting alerts} * {2 Converting an [Alert.t] into a [report]} * [report_alert loc w] produces a report for the given alert [w], or [None] if the alert is not to be printed. * Hook for intercepting alerts. * Original alert reporter for use in hooks. * Same as [print_alert], but uses [!formatter_for_warnings] as output formatter. * Prints a deprecation alert. * Prints an arbitrary alert. * An [error] is a [report] which [report_kind] must be [Report_error]. * {1 Automatically reporting errors for raised exceptions} * Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using [register_error_of_exn]. The result of the printer is an [error] value containing a location, a message, and optionally sub-messages (each of them being located as well). * Raising [Error e] signals an error [e]; the exception will be caught and the error will be printed. * Raising [Already_displayed_error] signals an error which has already been printed. The exception will be caught, but nothing will be printed
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Source code locations ( ranges of positions ) , used in parsetree . { b Warning :} this module is unstable and part of { { ! Compiler_libs}compiler - libs } . {b Warning:} this module is unstable and part of {{!Compiler_libs}compiler-libs}. *) open Format loc_ghost : Ghost expressions and patterns : expressions and patterns that do not appear explicitly in the source file they have the loc_ghost flag set to true . Then the profiler will not try to instrument them and the -annot option will not try to display their type . Every grammar rule that generates an element with a location must make at most one non - ghost element , the topmost one . How to tell whether your location must be ghost : A location corresponds to a range of characters in the source file . If the location contains a piece of code that is syntactically valid ( according to the documentation ) , and corresponds to the AST node , then the location must be real ; in all other cases , it must be ghost . expressions and patterns that do not appear explicitly in the source file they have the loc_ghost flag set to true. Then the profiler will not try to instrument them and the -annot option will not try to display their type. Every grammar rule that generates an element with a location must make at most one non-ghost element, the topmost one. How to tell whether your location must be ghost: A location corresponds to a range of characters in the source file. If the location contains a piece of code that is syntactically valid (according to the documentation), and corresponds to the AST node, then the location must be real; in all other cases, it must be ghost. *) type t = Warnings.loc = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } val none : t val is_none : t -> bool val in_file : string -> t val init : Lexing.lexbuf -> string -> unit val curr : Lexing.lexbuf -> t val symbol_rloc: unit -> t val symbol_gloc: unit -> t * [ rhs_loc n ] returns the location of the symbol at position [ n ] , starting at 1 , in the current parser rule . at 1, in the current parser rule. *) val rhs_loc: int -> t val rhs_interval: int -> int -> t val get_pos_info: Lexing.position -> string * int * int type 'a loc = { txt : 'a; loc : t; } val mknoloc : 'a -> 'a loc val mkloc : 'a -> t -> 'a loc val input_name: string ref val input_lexbuf: Lexing.lexbuf option ref * { 1 Toplevel - specific functions } val echo_eof: unit -> unit val reset: unit -> unit * { 1 Printing locations } val rewrite_absolute_path: string -> string val absolute_path: string -> string val show_filename: string -> string val print_filename: formatter -> string -> unit val print_loc: formatter -> t -> unit val print_locs: formatter -> t list -> unit * { 1 Reporting errors and warnings } * { 2 The type of reports and report printers } type msg = (Format.formatter -> unit) loc val msg: ?loc:t -> ('a, Format.formatter, unit, msg) format4 -> 'a type report_kind = | Report_error | Report_warning of string | Report_warning_as_error of string | Report_alert of string | Report_alert_as_error of string type error_source = Lexer | Parser | Typer | Warning | Unknown | Env | Config type report = { kind : report_kind; main : msg; sub : msg list; source : error_source; } val loc_of_report: report -> t val print_main : formatter -> report -> unit val print_sub_msg : formatter -> msg -> unit type report_printer = { pp : report_printer -> Format.formatter -> report -> unit; pp_report_kind : report_printer -> report -> Format.formatter -> report_kind -> unit; pp_main_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_main_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; pp_submsgs : report_printer -> report -> Format.formatter -> msg list -> unit; pp_submsg : report_printer -> report -> Format.formatter -> msg -> unit; pp_submsg_loc : report_printer -> report -> Format.formatter -> t -> unit; pp_submsg_txt : report_printer -> report -> Format.formatter -> (Format.formatter -> unit) -> unit; } * { 2 Report printers used in the compiler } val batch_mode_printer: report_printer * { 2 Printing a [ report ] } val print_report: formatter -> report -> unit val report_printer: (unit -> report_printer) ref val default_report_printer: unit -> report_printer val report_warning: t -> Warnings.t -> report option * [ report_warning w ] produces a report for the given warning [ w ] , or [ None ] if the warning is not to be printed . [None] if the warning is not to be printed. *) val warning_reporter: (t -> Warnings.t -> report option) ref val default_warning_reporter: t -> Warnings.t -> report option * { 2 Printing warnings } val formatter_for_warnings : formatter ref val print_warning: t -> formatter -> Warnings.t -> unit * Prints a warning . This is simply the composition of [ report_warning ] and [ print_report ] . [print_report]. *) val prerr_warning_ref: (t -> Warnings.t -> unit) ref val prerr_warning: t -> Warnings.t -> unit val report_alert: t -> Warnings.alert -> report option val alert_reporter: (t -> Warnings.alert -> report option) ref val default_alert_reporter: t -> Warnings.alert -> report option * { 2 Printing alerts } val print_alert: t -> formatter -> Warnings.alert -> unit * Prints an alert . This is simply the composition of [ report_alert ] and [ print_report ] . [print_report]. *) val prerr_alert_ref: (t -> Warnings.alert -> unit) ref val prerr_alert: t -> Warnings.alert -> unit val deprecated: ?def:t -> ?use:t -> t -> string -> unit val alert: ?def:t -> ?use:t -> kind:string -> t -> string -> unit * { 1 Reporting errors } type error = report val error: ?loc:t -> ?sub:msg list -> ?source:error_source -> string -> error val errorf: ?loc:t -> ?sub:msg list -> ?source:error_source -> ('a, Format.formatter, unit, error) format4 -> 'a val error_of_printer: ?loc:t -> ?sub:msg list -> ?source:error_source -> (formatter -> 'a -> unit) -> 'a -> error val error_of_printer_file: ?source:error_source -> (formatter -> 'a -> unit) -> 'a -> error val register_error_of_exn: (exn -> error option) -> unit val error_of_exn: exn -> [ `Ok of error | `Already_displayed ] option exception Error of error exception Already_displayed_error val raise_errorf: ?loc:t -> ?sub:msg list -> ?source:error_source -> ('a, Format.formatter, unit, 'b) format4 -> 'a val report_exception: formatter -> exn -> unit * the exception if it is unknown .
8f4f26f4ad1ba01fccf660c2d96fc3130b256f08c5cc95ece7ed29539eac5a03
philtomson/ClassifyDigits
classifyDigits.ml
OCaml version compile with : ocamlopt str.cmxa -o classifyDigits classifyDigits.ml compile with: ocamlopt str.cmxa -o classifyDigits classifyDigits.ml *) // This F # dojo is directly inspired by the // Digit Recognizer competition from Kaggle.com : // -recognizer // The datasets below are simply shorter versions of // the training dataset from Kaggle . // The goal of the dojo will be to // create a classifier that uses training data // to recognize hand - written digits , and // evaluate the quality of our classifier // by looking at predictions on the validation data . // This F# dojo is directly inspired by the // Digit Recognizer competition from Kaggle.com: // -recognizer // The datasets below are simply shorter versions of // the training dataset from Kaggle. // The goal of the dojo will be to // create a classifier that uses training data // to recognize hand-written digits, and // evaluate the quality of our classifier // by looking at predictions on the validation data. *) let read_lines name : string list = let ic = open_in name in let try_read () = try Some (input_line ic) with End_of_file -> None in let rec loop acc = match try_read () with | Some s -> loop (s :: acc) | None -> close_in ic; List.rev acc in loop [] // Two data files are included in the same place you // found this script : // trainingsample.csv , a file that contains 5,000 examples , and // validationsample.csv , a file that contains 500 examples . // The first file will be used to train your model , and the // second one to validate the quality of the model . // 1 . GETTING SOME DATA // First let 's read the contents of " trainingsample.csv " // Two data files are included in the same place you // found this script: // trainingsample.csv, a file that contains 5,000 examples, and // validationsample.csv, a file that contains 500 examples. // The first file will be used to train your model, and the // second one to validate the quality of the model. // 1. GETTING SOME DATA // First let's read the contents of "trainingsample.csv" *) type labelPixels = { label: int; pixels: int list } let slurp_file file = List.tl (read_lines file) |> List.map (fun line -> Str.split (Str.regexp ",") line ) |> List.map (fun numline -> List.map (fun (x:string) -> int_of_string x) numline) |> List.map (fun line -> { label= (List.hd line); pixels=(List.tl line) }) let trainingset = slurp_file("./trainingsample.csv") // 6 . COMPUTING DISTANCES // We need to compute the distance between images // Math reminder : the euclidean distance is // distance [ x1 ; y1 ; z1 ] [ x2 ; y2 ; z2 ] = // sqrt((x1 - x2)*(x1 - x2 ) + ( y1 - y2)*(y1 - y2 ) + ( z1 - z2)*(z1 - z2 ) ) // 6. COMPUTING DISTANCES // We need to compute the distance between images // Math reminder: the euclidean distance is // distance [ x1; y1; z1 ] [ x2; y2; z2 ] = // sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2)) *) let list_sum lst = List.fold_left (fun x acc -> x+acc) 0 lst let distance (p1: int list) (p2: int list) = sqrt (float_of_int (list_sum (List.map2 ( fun a b -> let diff = a-b in diff*diff ) p1 p2) )) // 7 . WRITING THE CLASSIFIER FUNCTION // We are now ready to write a classifier function ! // The classifier should take a set of pixels // ( an array of ints ) as an input , search for the // closest example in our sample , and predict // the value of that closest element . // 7. WRITING THE CLASSIFIER FUNCTION // We are now ready to write a classifier function! // The classifier should take a set of pixels // (an array of ints) as an input, search for the // closest example in our sample, and predict // the value of that closest element. *) let minBy f lst = let smallest = ref (List.hd lst) in List.iter (fun x -> if (f x) < (f !smallest) then smallest := x ) (List.tl lst) ; !smallest ;; let minBy f lst = let rec loop l acc = match l with [ ] - > acc | x : : ll - > loop ll ( if ( f x ) < ( f acc ) then x else acc ) in loop ( List.tl lst ) ( List.hd lst ) let minBy f lst = let rec loop l acc = match l with [] -> acc | x :: ll -> loop ll (if (f x) < (f acc) then x else acc) in loop (List.tl lst) (List.hd lst) *) let classify (pixels: int list) = fst ((List.map (fun (x: labelPixels) -> (x.label, (distance pixels x.pixels) )) trainingset) |> minBy (fun x -> snd x) ) // 8 . EVALUATING THE MODEL AGAINST VALIDATION DATA // Now that we have a classifier , we need to check // how good it is . // This is where the 2nd file , validationsample.csv , // comes in handy . // For each Example in the 2nd file , // we know what the true Label is , so we can compare // that value with what the classifier says . // You could now check for each 500 example in that file // whether your classifier returns the correct answer , // and compute the % correctly predicted . // 8. EVALUATING THE MODEL AGAINST VALIDATION DATA // Now that we have a classifier, we need to check // how good it is. // This is where the 2nd file, validationsample.csv, // comes in handy. // For each Example in the 2nd file, // we know what the true Label is, so we can compare // that value with what the classifier says. // You could now check for each 500 example in that file // whether your classifier returns the correct answer, // and compute the % correctly predicted. *) let validationsample = slurp_file("./validationsample.csv") let num_correct = (validationsample |> List.map (fun p -> if (classify p.pixels ) = p.label then 1 else 0) |> list_sum) let _ = Printf.printf "Percentage correct:%f\n" ((float_of_int(num_correct)/. (float_of_int(List.length validationsample)))*.100.0)
null
https://raw.githubusercontent.com/philtomson/ClassifyDigits/876753ca89902b000dfef2be84b16100b8d8cd98/classifyDigits.ml
ocaml
OCaml version compile with : ocamlopt str.cmxa -o classifyDigits classifyDigits.ml compile with: ocamlopt str.cmxa -o classifyDigits classifyDigits.ml *) // This F # dojo is directly inspired by the // Digit Recognizer competition from Kaggle.com : // -recognizer // The datasets below are simply shorter versions of // the training dataset from Kaggle . // The goal of the dojo will be to // create a classifier that uses training data // to recognize hand - written digits , and // evaluate the quality of our classifier // by looking at predictions on the validation data . // This F# dojo is directly inspired by the // Digit Recognizer competition from Kaggle.com: // -recognizer // The datasets below are simply shorter versions of // the training dataset from Kaggle. // The goal of the dojo will be to // create a classifier that uses training data // to recognize hand-written digits, and // evaluate the quality of our classifier // by looking at predictions on the validation data. *) let read_lines name : string list = let ic = open_in name in let try_read () = try Some (input_line ic) with End_of_file -> None in let rec loop acc = match try_read () with | Some s -> loop (s :: acc) | None -> close_in ic; List.rev acc in loop [] // Two data files are included in the same place you // found this script : // trainingsample.csv , a file that contains 5,000 examples , and // validationsample.csv , a file that contains 500 examples . // The first file will be used to train your model , and the // second one to validate the quality of the model . // 1 . GETTING SOME DATA // First let 's read the contents of " trainingsample.csv " // Two data files are included in the same place you // found this script: // trainingsample.csv, a file that contains 5,000 examples, and // validationsample.csv, a file that contains 500 examples. // The first file will be used to train your model, and the // second one to validate the quality of the model. // 1. GETTING SOME DATA // First let's read the contents of "trainingsample.csv" *) type labelPixels = { label: int; pixels: int list } let slurp_file file = List.tl (read_lines file) |> List.map (fun line -> Str.split (Str.regexp ",") line ) |> List.map (fun numline -> List.map (fun (x:string) -> int_of_string x) numline) |> List.map (fun line -> { label= (List.hd line); pixels=(List.tl line) }) let trainingset = slurp_file("./trainingsample.csv") // 6 . COMPUTING DISTANCES // We need to compute the distance between images // Math reminder : the euclidean distance is // distance [ x1 ; y1 ; z1 ] [ x2 ; y2 ; z2 ] = // sqrt((x1 - x2)*(x1 - x2 ) + ( y1 - y2)*(y1 - y2 ) + ( z1 - z2)*(z1 - z2 ) ) // 6. COMPUTING DISTANCES // We need to compute the distance between images // Math reminder: the euclidean distance is // distance [ x1; y1; z1 ] [ x2; y2; z2 ] = // sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2)) *) let list_sum lst = List.fold_left (fun x acc -> x+acc) 0 lst let distance (p1: int list) (p2: int list) = sqrt (float_of_int (list_sum (List.map2 ( fun a b -> let diff = a-b in diff*diff ) p1 p2) )) // 7 . WRITING THE CLASSIFIER FUNCTION // We are now ready to write a classifier function ! // The classifier should take a set of pixels // ( an array of ints ) as an input , search for the // closest example in our sample , and predict // the value of that closest element . // 7. WRITING THE CLASSIFIER FUNCTION // We are now ready to write a classifier function! // The classifier should take a set of pixels // (an array of ints) as an input, search for the // closest example in our sample, and predict // the value of that closest element. *) let minBy f lst = let smallest = ref (List.hd lst) in List.iter (fun x -> if (f x) < (f !smallest) then smallest := x ) (List.tl lst) ; !smallest ;; let minBy f lst = let rec loop l acc = match l with [ ] - > acc | x : : ll - > loop ll ( if ( f x ) < ( f acc ) then x else acc ) in loop ( List.tl lst ) ( List.hd lst ) let minBy f lst = let rec loop l acc = match l with [] -> acc | x :: ll -> loop ll (if (f x) < (f acc) then x else acc) in loop (List.tl lst) (List.hd lst) *) let classify (pixels: int list) = fst ((List.map (fun (x: labelPixels) -> (x.label, (distance pixels x.pixels) )) trainingset) |> minBy (fun x -> snd x) ) // 8 . EVALUATING THE MODEL AGAINST VALIDATION DATA // Now that we have a classifier , we need to check // how good it is . // This is where the 2nd file , validationsample.csv , // comes in handy . // For each Example in the 2nd file , // we know what the true Label is , so we can compare // that value with what the classifier says . // You could now check for each 500 example in that file // whether your classifier returns the correct answer , // and compute the % correctly predicted . // 8. EVALUATING THE MODEL AGAINST VALIDATION DATA // Now that we have a classifier, we need to check // how good it is. // This is where the 2nd file, validationsample.csv, // comes in handy. // For each Example in the 2nd file, // we know what the true Label is, so we can compare // that value with what the classifier says. // You could now check for each 500 example in that file // whether your classifier returns the correct answer, // and compute the % correctly predicted. *) let validationsample = slurp_file("./validationsample.csv") let num_correct = (validationsample |> List.map (fun p -> if (classify p.pixels ) = p.label then 1 else 0) |> list_sum) let _ = Printf.printf "Percentage correct:%f\n" ((float_of_int(num_correct)/. (float_of_int(List.length validationsample)))*.100.0)
62d361d682a2c2b7aefc2ba745b00ecee39a686a964f95ea698b52f4780053f8
flatironinstitute/flathub
FITS.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module Output.FITS ( fitsOutput ) where import Control.Applicative ((<|>)) import Control.Monad (join) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import Data.Char (toUpper) import Data.Foldable (fold) import Data.Functor.Compose (Compose(..)) import Data.Functor.Identity (Identity(..)) import Data.Maybe (fromMaybe, isJust, catMaybes) import Data.Monoid (Sum(Sum)) import Data.Proxy (Proxy(Proxy), asProxyTypeOf) import Data.Semigroup (stimesMonoid) import qualified Data.Text.Encoding as TE import Data.Time.Clock (getCurrentTime, UTCTime) import Data.Time.Format (formatTime, defaultTimeLocale) import qualified Data.Vector as V import Data.Word (Word32, Word64) import qualified Network.Wai as Wai import Numeric (showGFloat) import Unsafe.Coerce (unsafeCoerce) import Type import Field import Catalog import Monoid import Output.Types import Global import Backend import qualified KeyedMap as KM padding :: Int -> BS.ByteString padding n = BSC.replicate n ' ' pad :: Int -> BS.ByteString -> BS.ByteString pad n s | BS.length s > n = error $ "FITS.pad " ++ show n ++ ": " ++ show s | otherwise = s <> padding (n - BS.length s) padR :: Int -> BS.ByteString -> BS.ByteString padR n s | BS.length s > n = error $ "FITS.padR " ++ show n ++ ": " ++ show s | otherwise = padding (n - BS.length s) <> s blockSize :: Int blockSize = 2880 blockPadding :: Int -> Int blockPadding = negate . (`mod` negate blockSize) showBS :: Show a => a -> BS.ByteString showBS = BSC.pack . show data HeaderValue = HeaderString BS.ByteString | HeaderLogical Bool | HeaderInteger Integer | HeaderDouble Double data HeaderRecord = HeaderRecord { headerName :: BS.ByteString , headerValue :: Maybe HeaderValue -- used fixed-format for all , headerComment :: Maybe BS.ByteString } zipLast :: (a -> b -> c) -> a -> a -> [b] -> [c] zipLast _ _ _ [] = [] zipLast f _ z [x] = [f z x] zipLast f a z (x:r) = f a x:zipLast f a z r renderRecord :: HeaderRecord -> BS.ByteString renderRecord HeaderRecord{..} = pad 8 headerName <> maybe (" " <> commtail 0 (fold headerComment)) (("= " <>) . hv) headerValue where hv (HeaderString s) = case zipLast commval Nothing headerComment $ map quote $ spls $ esc s of ~(f:r) -> f <> foldMap ("CONTINUE " <>) r hv (HeaderLogical b) = commval headerComment $ padR 20 (if b then "T" else "F") hv (HeaderInteger i) = commval headerComment $ padR 20 (showBS i) hv (HeaderDouble d) = commval headerComment $ padR 20 (BSC.pack $ map toUpper $ showGFloat (Just 10) d "") commval Nothing s = pad 70 s commval (Just c) s | BS.length s >= 67 = pad 70 s <> comment c | otherwise = s <> " / " <> commtail (BS.length s + 3) c commtail u s = pad p f <> comment r where (f, r) = BS.splitAt p s p = 70 - u comment s | BS.null s = BS.empty | otherwise = "COMMENT " <> commtail 0 s quote s = ('\'' `BSC.cons` s) `BSC.snoc` '\'' esc s = BSC.split '\'' s spls [] = [] spls [x] | BS.length x <= 67 = [x] | otherwise = (a `BSC.snoc` '&') : spls [b] where (a, b) = BS.splitAt 67 x spls (x:y:r) | BS.length x < 66 = spls ((x <> "''" <> y):r) | otherwise = (a `BSC.snoc` '&') : spls (b : y : r) where (a, b) = BS.splitAt 67 x renderBlock :: [HeaderRecord] -> BS.ByteString renderBlock h = s <> padding (blockPadding (BS.length s)) where s = foldMap renderRecord $ h ++ [ HeaderRecord "END" Nothing Nothing ] data TField = TField { tfCount :: Word , tfType :: Char , tfTypeComment, tfName, tfNameComment, tfUnit :: Maybe BS.ByteString , tfScale , tFieldZero : : Rational , tfNull :: Maybe Integer , tfMin, tfMax :: Maybe Double } typeBytes :: Char -> Word typeBytes 'L' = 1 typeBytes 'B' = 1 typeBytes 'I' = 2 typeBytes 'J' = 4 typeBytes 'K' = 8 typeBytes 'A' = 1 typeBytes 'E' = 4 typeBytes 'D' = 8 typeBytes 'C' = 8 typeBytes 'M' = 16 typeBytes 'P' = 8 typeBytes 'Q' = 16 typeBytes c = error $ "typeBytes " ++ show c tfBytes :: TField -> Word tfBytes tf = tfCount tf * typeBytes (tfType tf) cField :: Char -> TField cField t = TField { tfCount = 1 , tfType = t , tfTypeComment = Nothing , tfName = Nothing , tfNameComment = Nothing , tfUnit = Nothing , tfScale = 1 -- , tfZero = 0 , tfNull = Nothing , tfMin = Nothing , tfMax = Nothing } cFieldInt :: (Integral a, Bounded a) => Char -> Proxy a -> TField cFieldInt c p = (cField c){ tfNull = Just $ toInteger $ minBound `asProxyTypeOf` p } typeInfo :: Type -> TField typeInfo (Double _) = cField 'D' typeInfo (Float _) = cField 'E' typeInfo (HalfFloat _) = typeInfo (Float Proxy) typeInfo (Long p) = cFieldInt 'K' p tfZero = 2 ^ 63 typeInfo (Integer p) = cFieldInt 'J' p typeInfo (Short p) = cFieldInt 'I' p typeInfo (Byte _) = (cField 'B'){ tfNull = Just 128, tfTypeComment = Just "signed" {- tfZero = -127 -} } typeInfo (Boolean _) = cField 'L' typeInfo (Keyword _) = cField 'A' -- count set by size below typeInfo (Void _) = (cField 'P'){ tfCount = 0 } typeInfo (Array t) = typeInfo (arrayHead t) -- count set by length below tField :: FieldTypeValue FieldFilter -> TField tField (FieldValue f ft) = ti { tfCount = tfCount ti * (if typeIsString ft then fieldSize f else 1) * (if isJust (typeIsArray ft) then fieldLength f else 1) -- XXX supposed to be ASCII -- will anyone care? , tfTypeComment = BS.intercalate "," . map TE.encodeUtf8 . V.toList <$> fieldEnum f <|> tfTypeComment ti , tfName = Just $ TE.encodeUtf8 $ fieldName f , tfNameComment = Just $ TE.encodeUtf8 $ fieldTitle f <> foldMap (": " <>) (fieldDescr f) , tfUnit = TE.encodeUtf8 <$> fieldUnits f , tfMin = tmin , tfMax = tmax } where ti = typeInfo $ typeOfValue ft (tmin, tmax) = unTypeValue rf ft rf :: Typed a => FieldFilter a -> (Maybe Double, Maybe Double) rf (FieldRange x y) = (toDouble <$> x, toDouble <$> y) rf (FieldEQ [x]) = join (,) $ Just $ toDouble x rf _ = (Nothing, Nothing) tFieldRecords :: Int -> TField -> [HeaderRecord] tFieldRecords i TField{..} = [ rec "TFORM" tfTypeComment $ HeaderString $ mwhen (tfCount /= 1) (showBS tfCount) `BSC.snoc` tfType ] ++ catMaybes [ rec "TTYPE" tfNameComment . HeaderString <$> tfName , rec "TUNIT" Nothing . HeaderString <$> tfUnit , rec "TNULL" Nothing . HeaderInteger <$> tfNull , rec "TDMIN" Nothing . HeaderDouble <$> tfMin , rec "TDMAX" Nothing . HeaderDouble <$> tfMax ] where is = BSC.pack $ show i rec n c v = HeaderRecord (n <> is) (Just v) c axisHeaders :: Int -> [Word] -> [HeaderRecord] axisHeaders bitpix naxis = [ HeaderRecord "BITPIX" (Just $ HeaderInteger $ toInteger bitpix) Nothing , HeaderRecord "NAXIS" (Just $ HeaderInteger $ toInteger $ length naxis) Nothing ] ++ zipWith (\i n -> HeaderRecord ("NAXIS" <> showBS i) (Just $ HeaderInteger $ toInteger n) Nothing) [(1::Int)..] naxis fitsHeaders :: UTCTime -> Wai.Request -> Catalog -> DataArgs V.Vector -> Word -> (BS.ByteString, Word, BS.ByteString) fitsHeaders date req cat args count = ( renderBlock ( [ HeaderRecord "SIMPLE" (Just $ HeaderLogical True) (Just "FITS") ] ++ axisHeaders 8 [] ++ [ HeaderRecord "DATE" (Just $ HeaderString $ BSC.pack $ formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S" date) (Just "time of download") , HeaderRecord "ORIGIN" (Just $ HeaderString $ BSL.toStrict $ B.toLazyByteString $ requestUrl req) (Just $ TE.encodeUtf8 $ catalogTitle cat) , HeaderRecord "EXTEND" (Just $ HeaderLogical True) Nothing ]) <> renderBlock ( [ HeaderRecord "XTENSION" (Just $ HeaderString "BINTABLE") (Just "binary table") ] ++ axisHeaders 8 [rowsize, count] ++ [ HeaderRecord "PCOUNT" (Just $ HeaderInteger 0) Nothing , HeaderRecord "GCOUNT" (Just $ HeaderInteger 1) Nothing , HeaderRecord "TFIELDS" (Just $ HeaderInteger $ toInteger $ V.length $ dataFields args) Nothing ] ++ fold (V.imap (tFieldRecords . succ) tfields)) , datasize, BS.replicate (blockPadding $ fromIntegral datasize) 0) where tfields = V.map (\f -> tField (KM.lookupDefault (runIdentity $ makeFieldValueM f (Identity $ FieldEQ [])) $ filterFields $ dataFilters args)) $ dataFields args Sum rowsize = V.foldMap (Sum . tfBytes) tfields datasize = count * rowsize fitsValue :: Field -> TypeValue Maybe -> B.Builder fitsValue _ (Double x) = B.doubleBE $ fromMaybe (unsafeCoerce (0x7ff80000ffffffff::Word64)) x fitsValue _ (Float x) = B.floatBE $ fromMaybe (unsafeCoerce (0x7fc0ffff::Word32)) x fitsValue f (HalfFloat x) = fitsValue f (Float $ realToFrac <$> x) fitsValue _ (Long x) = B.int64BE $ fromMaybe minBound x should be signed with zero shift fitsValue _ (Integer x) = B.int32BE $ fromMaybe minBound x fitsValue _ (Short x) = B.int16BE $ fromMaybe minBound x should be unsigned with zero shift fitsValue _ (Boolean Nothing) = B.int8 0 fitsValue _ (Boolean (Just False)) = B.char7 'F' fitsValue _ (Boolean (Just True)) = B.char7 'T' fitsValue f (Keyword x) = B.byteString s <> stimesMonoid (l' - BS.length s) (B.char7 '\0') where s = BS.take l' $ foldMap TE.encodeUtf8 x -- supposed to be ASCII oh well l' = fromIntegral (fieldSize f) fitsValue _ (Void _) = mempty fitsValue f (Array x) = V.foldMap (fitsValue f) $ traverseTypeValue (padv . fromMaybe V.empty . getCompose) x where padv v = V.map Just (V.take l' v) V.++ V.replicate (l' - V.length v) Nothing l' = fromIntegral (fieldLength f) fitsRow :: V.Vector Field -> V.Vector (TypeValue Maybe) -> B.Builder fitsRow f v = fold $ V.zipWith fitsValue f v fitsGenerator :: Wai.Request -> Catalog -> DataArgs V.Vector -> M OutputStream fitsGenerator req cat args = do count <- queryCount cat (dataFilters args) now <- liftIO getCurrentTime let (header, size, footer) = fitsHeaders now req cat args count outputStreamRows (Just $ fromIntegral (BS.length header) + size + fromIntegral (BS.length footer)) (B.byteString header) (fitsRow $ dataFields args) (B.byteString footer) cat args fitsOutput :: OutputFormat fitsOutput = OutputFormat { outputMimeType = "application/fits" , outputExtension = "fits" , outputDescription = "FITS BINTABLE binary table file containing the requested fields" , outputGenerator = fitsGenerator }
null
https://raw.githubusercontent.com/flatironinstitute/flathub/767c97b32a7de729b5f076c5e4da54debe478541/src/Output/FITS.hs
haskell
# LANGUAGE OverloadedStrings # used fixed-format for all , tfZero = 0 tfZero = -127 count set by size below count set by length below XXX supposed to be ASCII -- will anyone care? supposed to be ASCII oh well
# LANGUAGE FlexibleInstances # # LANGUAGE RecordWildCards # module Output.FITS ( fitsOutput ) where import Control.Applicative ((<|>)) import Control.Monad (join) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import Data.Char (toUpper) import Data.Foldable (fold) import Data.Functor.Compose (Compose(..)) import Data.Functor.Identity (Identity(..)) import Data.Maybe (fromMaybe, isJust, catMaybes) import Data.Monoid (Sum(Sum)) import Data.Proxy (Proxy(Proxy), asProxyTypeOf) import Data.Semigroup (stimesMonoid) import qualified Data.Text.Encoding as TE import Data.Time.Clock (getCurrentTime, UTCTime) import Data.Time.Format (formatTime, defaultTimeLocale) import qualified Data.Vector as V import Data.Word (Word32, Word64) import qualified Network.Wai as Wai import Numeric (showGFloat) import Unsafe.Coerce (unsafeCoerce) import Type import Field import Catalog import Monoid import Output.Types import Global import Backend import qualified KeyedMap as KM padding :: Int -> BS.ByteString padding n = BSC.replicate n ' ' pad :: Int -> BS.ByteString -> BS.ByteString pad n s | BS.length s > n = error $ "FITS.pad " ++ show n ++ ": " ++ show s | otherwise = s <> padding (n - BS.length s) padR :: Int -> BS.ByteString -> BS.ByteString padR n s | BS.length s > n = error $ "FITS.padR " ++ show n ++ ": " ++ show s | otherwise = padding (n - BS.length s) <> s blockSize :: Int blockSize = 2880 blockPadding :: Int -> Int blockPadding = negate . (`mod` negate blockSize) showBS :: Show a => a -> BS.ByteString showBS = BSC.pack . show data HeaderValue = HeaderString BS.ByteString | HeaderLogical Bool | HeaderInteger Integer | HeaderDouble Double data HeaderRecord = HeaderRecord { headerName :: BS.ByteString , headerComment :: Maybe BS.ByteString } zipLast :: (a -> b -> c) -> a -> a -> [b] -> [c] zipLast _ _ _ [] = [] zipLast f _ z [x] = [f z x] zipLast f a z (x:r) = f a x:zipLast f a z r renderRecord :: HeaderRecord -> BS.ByteString renderRecord HeaderRecord{..} = pad 8 headerName <> maybe (" " <> commtail 0 (fold headerComment)) (("= " <>) . hv) headerValue where hv (HeaderString s) = case zipLast commval Nothing headerComment $ map quote $ spls $ esc s of ~(f:r) -> f <> foldMap ("CONTINUE " <>) r hv (HeaderLogical b) = commval headerComment $ padR 20 (if b then "T" else "F") hv (HeaderInteger i) = commval headerComment $ padR 20 (showBS i) hv (HeaderDouble d) = commval headerComment $ padR 20 (BSC.pack $ map toUpper $ showGFloat (Just 10) d "") commval Nothing s = pad 70 s commval (Just c) s | BS.length s >= 67 = pad 70 s <> comment c | otherwise = s <> " / " <> commtail (BS.length s + 3) c commtail u s = pad p f <> comment r where (f, r) = BS.splitAt p s p = 70 - u comment s | BS.null s = BS.empty | otherwise = "COMMENT " <> commtail 0 s quote s = ('\'' `BSC.cons` s) `BSC.snoc` '\'' esc s = BSC.split '\'' s spls [] = [] spls [x] | BS.length x <= 67 = [x] | otherwise = (a `BSC.snoc` '&') : spls [b] where (a, b) = BS.splitAt 67 x spls (x:y:r) | BS.length x < 66 = spls ((x <> "''" <> y):r) | otherwise = (a `BSC.snoc` '&') : spls (b : y : r) where (a, b) = BS.splitAt 67 x renderBlock :: [HeaderRecord] -> BS.ByteString renderBlock h = s <> padding (blockPadding (BS.length s)) where s = foldMap renderRecord $ h ++ [ HeaderRecord "END" Nothing Nothing ] data TField = TField { tfCount :: Word , tfType :: Char , tfTypeComment, tfName, tfNameComment, tfUnit :: Maybe BS.ByteString , tfScale , tFieldZero : : Rational , tfNull :: Maybe Integer , tfMin, tfMax :: Maybe Double } typeBytes :: Char -> Word typeBytes 'L' = 1 typeBytes 'B' = 1 typeBytes 'I' = 2 typeBytes 'J' = 4 typeBytes 'K' = 8 typeBytes 'A' = 1 typeBytes 'E' = 4 typeBytes 'D' = 8 typeBytes 'C' = 8 typeBytes 'M' = 16 typeBytes 'P' = 8 typeBytes 'Q' = 16 typeBytes c = error $ "typeBytes " ++ show c tfBytes :: TField -> Word tfBytes tf = tfCount tf * typeBytes (tfType tf) cField :: Char -> TField cField t = TField { tfCount = 1 , tfType = t , tfTypeComment = Nothing , tfName = Nothing , tfNameComment = Nothing , tfUnit = Nothing , tfScale = 1 , tfNull = Nothing , tfMin = Nothing , tfMax = Nothing } cFieldInt :: (Integral a, Bounded a) => Char -> Proxy a -> TField cFieldInt c p = (cField c){ tfNull = Just $ toInteger $ minBound `asProxyTypeOf` p } typeInfo :: Type -> TField typeInfo (Double _) = cField 'D' typeInfo (Float _) = cField 'E' typeInfo (HalfFloat _) = typeInfo (Float Proxy) typeInfo (Long p) = cFieldInt 'K' p tfZero = 2 ^ 63 typeInfo (Integer p) = cFieldInt 'J' p typeInfo (Short p) = cFieldInt 'I' p typeInfo (Boolean _) = cField 'L' typeInfo (Void _) = (cField 'P'){ tfCount = 0 } tField :: FieldTypeValue FieldFilter -> TField tField (FieldValue f ft) = ti { tfCount = tfCount ti * (if typeIsString ft then fieldSize f else 1) * (if isJust (typeIsArray ft) then fieldLength f else 1) , tfTypeComment = BS.intercalate "," . map TE.encodeUtf8 . V.toList <$> fieldEnum f <|> tfTypeComment ti , tfName = Just $ TE.encodeUtf8 $ fieldName f , tfNameComment = Just $ TE.encodeUtf8 $ fieldTitle f <> foldMap (": " <>) (fieldDescr f) , tfUnit = TE.encodeUtf8 <$> fieldUnits f , tfMin = tmin , tfMax = tmax } where ti = typeInfo $ typeOfValue ft (tmin, tmax) = unTypeValue rf ft rf :: Typed a => FieldFilter a -> (Maybe Double, Maybe Double) rf (FieldRange x y) = (toDouble <$> x, toDouble <$> y) rf (FieldEQ [x]) = join (,) $ Just $ toDouble x rf _ = (Nothing, Nothing) tFieldRecords :: Int -> TField -> [HeaderRecord] tFieldRecords i TField{..} = [ rec "TFORM" tfTypeComment $ HeaderString $ mwhen (tfCount /= 1) (showBS tfCount) `BSC.snoc` tfType ] ++ catMaybes [ rec "TTYPE" tfNameComment . HeaderString <$> tfName , rec "TUNIT" Nothing . HeaderString <$> tfUnit , rec "TNULL" Nothing . HeaderInteger <$> tfNull , rec "TDMIN" Nothing . HeaderDouble <$> tfMin , rec "TDMAX" Nothing . HeaderDouble <$> tfMax ] where is = BSC.pack $ show i rec n c v = HeaderRecord (n <> is) (Just v) c axisHeaders :: Int -> [Word] -> [HeaderRecord] axisHeaders bitpix naxis = [ HeaderRecord "BITPIX" (Just $ HeaderInteger $ toInteger bitpix) Nothing , HeaderRecord "NAXIS" (Just $ HeaderInteger $ toInteger $ length naxis) Nothing ] ++ zipWith (\i n -> HeaderRecord ("NAXIS" <> showBS i) (Just $ HeaderInteger $ toInteger n) Nothing) [(1::Int)..] naxis fitsHeaders :: UTCTime -> Wai.Request -> Catalog -> DataArgs V.Vector -> Word -> (BS.ByteString, Word, BS.ByteString) fitsHeaders date req cat args count = ( renderBlock ( [ HeaderRecord "SIMPLE" (Just $ HeaderLogical True) (Just "FITS") ] ++ axisHeaders 8 [] ++ [ HeaderRecord "DATE" (Just $ HeaderString $ BSC.pack $ formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S" date) (Just "time of download") , HeaderRecord "ORIGIN" (Just $ HeaderString $ BSL.toStrict $ B.toLazyByteString $ requestUrl req) (Just $ TE.encodeUtf8 $ catalogTitle cat) , HeaderRecord "EXTEND" (Just $ HeaderLogical True) Nothing ]) <> renderBlock ( [ HeaderRecord "XTENSION" (Just $ HeaderString "BINTABLE") (Just "binary table") ] ++ axisHeaders 8 [rowsize, count] ++ [ HeaderRecord "PCOUNT" (Just $ HeaderInteger 0) Nothing , HeaderRecord "GCOUNT" (Just $ HeaderInteger 1) Nothing , HeaderRecord "TFIELDS" (Just $ HeaderInteger $ toInteger $ V.length $ dataFields args) Nothing ] ++ fold (V.imap (tFieldRecords . succ) tfields)) , datasize, BS.replicate (blockPadding $ fromIntegral datasize) 0) where tfields = V.map (\f -> tField (KM.lookupDefault (runIdentity $ makeFieldValueM f (Identity $ FieldEQ [])) $ filterFields $ dataFilters args)) $ dataFields args Sum rowsize = V.foldMap (Sum . tfBytes) tfields datasize = count * rowsize fitsValue :: Field -> TypeValue Maybe -> B.Builder fitsValue _ (Double x) = B.doubleBE $ fromMaybe (unsafeCoerce (0x7ff80000ffffffff::Word64)) x fitsValue _ (Float x) = B.floatBE $ fromMaybe (unsafeCoerce (0x7fc0ffff::Word32)) x fitsValue f (HalfFloat x) = fitsValue f (Float $ realToFrac <$> x) fitsValue _ (Long x) = B.int64BE $ fromMaybe minBound x should be signed with zero shift fitsValue _ (Integer x) = B.int32BE $ fromMaybe minBound x fitsValue _ (Short x) = B.int16BE $ fromMaybe minBound x should be unsigned with zero shift fitsValue _ (Boolean Nothing) = B.int8 0 fitsValue _ (Boolean (Just False)) = B.char7 'F' fitsValue _ (Boolean (Just True)) = B.char7 'T' fitsValue f (Keyword x) = B.byteString s <> stimesMonoid (l' - BS.length s) (B.char7 '\0') where l' = fromIntegral (fieldSize f) fitsValue _ (Void _) = mempty fitsValue f (Array x) = V.foldMap (fitsValue f) $ traverseTypeValue (padv . fromMaybe V.empty . getCompose) x where padv v = V.map Just (V.take l' v) V.++ V.replicate (l' - V.length v) Nothing l' = fromIntegral (fieldLength f) fitsRow :: V.Vector Field -> V.Vector (TypeValue Maybe) -> B.Builder fitsRow f v = fold $ V.zipWith fitsValue f v fitsGenerator :: Wai.Request -> Catalog -> DataArgs V.Vector -> M OutputStream fitsGenerator req cat args = do count <- queryCount cat (dataFilters args) now <- liftIO getCurrentTime let (header, size, footer) = fitsHeaders now req cat args count outputStreamRows (Just $ fromIntegral (BS.length header) + size + fromIntegral (BS.length footer)) (B.byteString header) (fitsRow $ dataFields args) (B.byteString footer) cat args fitsOutput :: OutputFormat fitsOutput = OutputFormat { outputMimeType = "application/fits" , outputExtension = "fits" , outputDescription = "FITS BINTABLE binary table file containing the requested fields" , outputGenerator = fitsGenerator }
5d7166777d540fcf50240a1bff58d8a626fed6b3c576ef90b43658a4cb17996e
janestreet/hardcaml
build_mode.ml
open Base type t = | Simulation | Synthesis [@@deriving sexp_of, compare, equal] let of_string = function | "simulation" -> Simulation | "synthesis" -> Synthesis | build_mode -> raise_s [%message "Invalid [Build_mode]" (build_mode : string)] ;;
null
https://raw.githubusercontent.com/janestreet/hardcaml/a9b1880ca2fb1a566eac66d935cacf344ec76b13/src/build_mode.ml
ocaml
open Base type t = | Simulation | Synthesis [@@deriving sexp_of, compare, equal] let of_string = function | "simulation" -> Simulation | "synthesis" -> Synthesis | build_mode -> raise_s [%message "Invalid [Build_mode]" (build_mode : string)] ;;
fa5df283e11aae94d927ed970dfe69a428998800c21a1c1e625b81f024532255
aldosolorzano/structurizr-clj
shape_test.clj
(ns structurizr-clj.shape-test (:require [clojure.test :refer :all] [structurizr-clj.shape :as structurizr.shape]) (:import (com.structurizr.view Shape))) (deftest shape-test (is (= structurizr.shape/box Shape/Box)) (is (= structurizr.shape/rounded-box Shape/RoundedBox)) (is (= structurizr.shape/circle Shape/Circle)) (is (= structurizr.shape/ellipse Shape/Ellipse)) (is (= structurizr.shape/hexagon Shape/Hexagon)) (is (= structurizr.shape/cylinder Shape/Cylinder)) (is (= structurizr.shape/pipe Shape/Pipe)) (is (= structurizr.shape/person Shape/Person)) (is (= structurizr.shape/robot Shape/Robot)) (is (= structurizr.shape/folder Shape/Folder)) (is (= structurizr.shape/web-browser Shape/WebBrowser)) (is (= structurizr.shape/mobile-device-portrait Shape/MobileDevicePortrait)) (is (= structurizr.shape/mobile-device-landscape Shape/MobileDeviceLandscape)) (is (= structurizr.shape/component Shape/Component)))
null
https://raw.githubusercontent.com/aldosolorzano/structurizr-clj/20354fc97c660dd5ce44972f4a1d3935a4f32e4c/test/structurizr_clj/shape_test.clj
clojure
(ns structurizr-clj.shape-test (:require [clojure.test :refer :all] [structurizr-clj.shape :as structurizr.shape]) (:import (com.structurizr.view Shape))) (deftest shape-test (is (= structurizr.shape/box Shape/Box)) (is (= structurizr.shape/rounded-box Shape/RoundedBox)) (is (= structurizr.shape/circle Shape/Circle)) (is (= structurizr.shape/ellipse Shape/Ellipse)) (is (= structurizr.shape/hexagon Shape/Hexagon)) (is (= structurizr.shape/cylinder Shape/Cylinder)) (is (= structurizr.shape/pipe Shape/Pipe)) (is (= structurizr.shape/person Shape/Person)) (is (= structurizr.shape/robot Shape/Robot)) (is (= structurizr.shape/folder Shape/Folder)) (is (= structurizr.shape/web-browser Shape/WebBrowser)) (is (= structurizr.shape/mobile-device-portrait Shape/MobileDevicePortrait)) (is (= structurizr.shape/mobile-device-landscape Shape/MobileDeviceLandscape)) (is (= structurizr.shape/component Shape/Component)))
648c09c986a3506f0298b33aa39e13d379325b825bc5979485e9e9a84f3cdd33
danieljharvey/mimsa
Entity.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # {-# LANGUAGE OverloadedStrings #-} module Language.Mimsa.Core.Types.Module.Entity where -- a thing -- terrible, pls improve import qualified Data.Aeson as JSON import GHC.Generics import Language.Mimsa.Core.Printer import Language.Mimsa.Core.Types.AST.InfixOp import Language.Mimsa.Core.Types.Identifiers import Language.Mimsa.Core.Types.Module.ModuleName data Entity = -- | a variable, `dog` EName Name | -- | an infix operator, `<|>` EInfix InfixOp | a namespaced var , ` Prelude.id ` ENamespacedName ModuleName Name | -- | a typename, `Maybe` EType TypeName | -- | a namespaced typename, `Prelude.Either` ENamespacedType ModuleName TypeName | -- | a constructor, `Just` EConstructor TyCon | -- \| a namespaced constructor, `Maybe.Just` ENamespacedConstructor ModuleName TyCon deriving stock (Eq, Ord, Show, Generic) deriving anyclass ( JSON.ToJSON, JSON.ToJSONKey, JSON.FromJSON, JSON.FromJSONKey ) instance Printer Entity where prettyPrint (EName name) = prettyPrint name prettyPrint (EInfix infixOp) = prettyPrint infixOp prettyPrint (ENamespacedName modName name) = prettyPrint modName <> "." <> prettyPrint name prettyPrint (EType typeName) = prettyPrint typeName prettyPrint (ENamespacedType modName typeName) = prettyPrint modName <> "." <> prettyPrint typeName prettyPrint (EConstructor tyCon) = prettyPrint tyCon prettyPrint (ENamespacedConstructor modName tyCon) = prettyPrint modName <> "." <> prettyPrint tyCon
null
https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/core/src/Language/Mimsa/Core/Types/Module/Entity.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # a thing terrible, pls improve | a variable, `dog` | an infix operator, `<|>` | a typename, `Maybe` | a namespaced typename, `Prelude.Either` | a constructor, `Just` \| a namespaced constructor, `Maybe.Just`
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # module Language.Mimsa.Core.Types.Module.Entity where import qualified Data.Aeson as JSON import GHC.Generics import Language.Mimsa.Core.Printer import Language.Mimsa.Core.Types.AST.InfixOp import Language.Mimsa.Core.Types.Identifiers import Language.Mimsa.Core.Types.Module.ModuleName data Entity EName Name EInfix InfixOp | a namespaced var , ` Prelude.id ` ENamespacedName ModuleName Name EType TypeName ENamespacedType ModuleName TypeName EConstructor TyCon ENamespacedConstructor ModuleName TyCon deriving stock (Eq, Ord, Show, Generic) deriving anyclass ( JSON.ToJSON, JSON.ToJSONKey, JSON.FromJSON, JSON.FromJSONKey ) instance Printer Entity where prettyPrint (EName name) = prettyPrint name prettyPrint (EInfix infixOp) = prettyPrint infixOp prettyPrint (ENamespacedName modName name) = prettyPrint modName <> "." <> prettyPrint name prettyPrint (EType typeName) = prettyPrint typeName prettyPrint (ENamespacedType modName typeName) = prettyPrint modName <> "." <> prettyPrint typeName prettyPrint (EConstructor tyCon) = prettyPrint tyCon prettyPrint (ENamespacedConstructor modName tyCon) = prettyPrint modName <> "." <> prettyPrint tyCon
a161ec03a47bd2eab3cb1eac8aaee7d05254d03f8dd600f699035e8e17b3fdec
ShamoX/cash
signal_3_9.mli
(***********************************************************************) (* Cash *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed (* under the terms of the GNU Lesser General Public License. *) (* *) Cash is based on , by . (***********************************************************************) value signal_process : Procobj.proc -> int -> unit; value signal_process_pid : int -> int -> unit; value signal_process_group : Procobj.proc -> int -> unit; value signal_process_group_pgrp : int -> int -> unit; value itimer : ?newstat: Unix.interval_timer_status -> Unix.interval_timer -> Unix.interval_timer_status; value pause_until_interrupt : unit -> unit; value sleep : int -> unit; value sleep_until : float -> unit;
null
https://raw.githubusercontent.com/ShamoX/cash/aa97231154c3f64c9d0a62823e1ed71e32ab8718/signal_3_9.mli
ocaml
********************************************************************* Cash under the terms of the GNU Lesser General Public License. *********************************************************************
, projet Cristal , INRIA Rocquencourt Copyright 2002 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed Cash is based on , by . value signal_process : Procobj.proc -> int -> unit; value signal_process_pid : int -> int -> unit; value signal_process_group : Procobj.proc -> int -> unit; value signal_process_group_pgrp : int -> int -> unit; value itimer : ?newstat: Unix.interval_timer_status -> Unix.interval_timer -> Unix.interval_timer_status; value pause_until_interrupt : unit -> unit; value sleep : int -> unit; value sleep_until : float -> unit;
1ccaa6fafe6093d54a1d2912fb657c4c00df6f94a45c938b86c70e4dcd72acb6
prikhi/xmonad-config
StatusBar.hs
{-# LANGUAGE OverloadedStrings #-} module StatusBar (startupHook, eventHook, stopHook) where import XMonad (X, Event, ScreenId(S), spawn) import XMonad.Hooks.DynamicBars (dynStatusBarStartup, dynStatusBarEventHook) import Xmobar ( Config(..), XPosition(OnScreen, Top, TopP), Date(Date) , Monitors(Network, Cpu, Weather, MPD), Runnable(Run), defaultConfig ) import Control.Monad (when) import Data.Monoid (All) import System.IO (Handle) import qualified Theme import qualified XmobarStub -- Hooks -- | Start the Status Bars & System Tray. startupHook :: X () startupHook = dynStatusBarStartup dynamic dynamicCleanup | Restart the Status Bars & System Tray on Monitor / Screen Changes eventHook :: Event -> X All eventHook = dynStatusBarEventHook dynamic dynamicCleanup | Stop the Status Bar & System Tray Processes . stopHook :: X () stopHook = dynamicCleanup -- | Start the Status Bar for the Screen. dynamic :: ScreenId -> X Handle dynamic (S screenId) = let config = case screenId of 0 -> withTray 1 -> long 2 -> short _ -> blank in when (screenId == 0) startSystemTray >> runXmobar config screenId -- | Kill all Status Bar & System Tray Processes. dynamicCleanup :: X () dynamicCleanup = XmobarStub.terminateProcesses >> stopSystemTray System Tray | The Desired Width of System Tray in Pixels . systemTrayWidth :: Int systemTrayWidth = 100 -- | Start the System Tray Process. startSystemTray :: X () startSystemTray = let args = [ "--edge", "top" , "--align", "right" , "--width", show systemTrayWidth , "--widthtype", "pixels" , "--expand", "false" , "--monitor", "primary" , "--height", "17" , "--tint", "0x" ++ drop 1 Theme.background , "--alpha", "0" , "--transparent", "true" ] in spawn $ "sleep 0.1; trayer " ++ unwords args -- | Stop the System Tray Process. stopSystemTray :: X () stopSystemTray = spawn "pkill trayer" Xmobar | Run xmobar on a Specific Screen & Return a Write Handle to it 's HandleReader . -- -- The process ID of the bar will be added to the `StatusBarStorage` so it -- can be killed on shutdown. runXmobar :: Config -> Int -> X Handle runXmobar c screenId = do iconDir <- Theme.getIconDirectory XmobarStub.run c { position = OnScreen screenId $ position c , iconRoot = iconDir } | with just the Default Font & Colors Modified . xmobarConfig :: Config xmobarConfig = defaultConfig { font = Theme.xftFont , fgColor = Theme.statusBarForeground , bgColor = Theme.statusBarBackground } -- | A Full-Width Status Bar for Large Screens. long :: Config long = xmobarConfig { position = Top , commands = [ Run $ MPD [ "-t", "<statei>" , "--" , "-Z", Theme.mpdPaused "mpd paused" , "-S", Theme.mpdStopped "mpd stopped" , "-P", Theme.mpdTitle "<title>" ++ Theme.mpdSeparator ++ Theme.mpdArtist "<artist>" ] 10 , Run $ Network "enp0s25" [ "-t" , Theme.networkUpload "<tx> KB ^" ++ Theme.networkDownload "v <rx> KB" ] 25 , Run $ Weather "KNYC" [ "-t" , "<tempF>°" ] 3000 , Run $ Cpu [ "-t" , "<total>%" , "-x" , "" , "--minwidth" , "2" ] 25 , Run $ Date "%a %d %b %H:%M" "date" 10 ] , template = unwords [ "%handle%" , "}{" , "%mpd%" , Theme.statusSeparator , "%enp0s25%" , Theme.statusSeparator , Theme.icon Theme.CPU , "%cpu%" , Theme.statusSeparator , Theme.weather "%KNYC%" , Theme.statusSeparator , Theme.date "%date%" , "" ] } -- | A Long Status Bar with Space for the System Tray. withTray :: Config withTray = long { position = TopP 0 systemTrayWidth , template = template long ++ " " ++ Theme.statusSeparator } -- | A Shorter Config for Monitors in Portrait Orientation. short :: Config short = long { template = unwords [ "%handle%" , "}{" , Theme.date "%date%" , "" ] } blank :: Config blank = long { commands = [], template = "" }
null
https://raw.githubusercontent.com/prikhi/xmonad-config/8357d9d6fcc988193d568874581b88d8c2b64cae/src/StatusBar.hs
haskell
# LANGUAGE OverloadedStrings # Hooks | Start the Status Bars & System Tray. | Start the Status Bar for the Screen. | Kill all Status Bar & System Tray Processes. | Start the System Tray Process. | Stop the System Tray Process. The process ID of the bar will be added to the `StatusBarStorage` so it can be killed on shutdown. | A Full-Width Status Bar for Large Screens. | A Long Status Bar with Space for the System Tray. | A Shorter Config for Monitors in Portrait Orientation.
module StatusBar (startupHook, eventHook, stopHook) where import XMonad (X, Event, ScreenId(S), spawn) import XMonad.Hooks.DynamicBars (dynStatusBarStartup, dynStatusBarEventHook) import Xmobar ( Config(..), XPosition(OnScreen, Top, TopP), Date(Date) , Monitors(Network, Cpu, Weather, MPD), Runnable(Run), defaultConfig ) import Control.Monad (when) import Data.Monoid (All) import System.IO (Handle) import qualified Theme import qualified XmobarStub startupHook :: X () startupHook = dynStatusBarStartup dynamic dynamicCleanup | Restart the Status Bars & System Tray on Monitor / Screen Changes eventHook :: Event -> X All eventHook = dynStatusBarEventHook dynamic dynamicCleanup | Stop the Status Bar & System Tray Processes . stopHook :: X () stopHook = dynamicCleanup dynamic :: ScreenId -> X Handle dynamic (S screenId) = let config = case screenId of 0 -> withTray 1 -> long 2 -> short _ -> blank in when (screenId == 0) startSystemTray >> runXmobar config screenId dynamicCleanup :: X () dynamicCleanup = XmobarStub.terminateProcesses >> stopSystemTray System Tray | The Desired Width of System Tray in Pixels . systemTrayWidth :: Int systemTrayWidth = 100 startSystemTray :: X () startSystemTray = let args = [ "--edge", "top" , "--align", "right" , "--width", show systemTrayWidth , "--widthtype", "pixels" , "--expand", "false" , "--monitor", "primary" , "--height", "17" , "--tint", "0x" ++ drop 1 Theme.background , "--alpha", "0" , "--transparent", "true" ] in spawn $ "sleep 0.1; trayer " ++ unwords args stopSystemTray :: X () stopSystemTray = spawn "pkill trayer" Xmobar | Run xmobar on a Specific Screen & Return a Write Handle to it 's HandleReader . runXmobar :: Config -> Int -> X Handle runXmobar c screenId = do iconDir <- Theme.getIconDirectory XmobarStub.run c { position = OnScreen screenId $ position c , iconRoot = iconDir } | with just the Default Font & Colors Modified . xmobarConfig :: Config xmobarConfig = defaultConfig { font = Theme.xftFont , fgColor = Theme.statusBarForeground , bgColor = Theme.statusBarBackground } long :: Config long = xmobarConfig { position = Top , commands = [ Run $ MPD [ "-t", "<statei>" , "--" , "-Z", Theme.mpdPaused "mpd paused" , "-S", Theme.mpdStopped "mpd stopped" , "-P", Theme.mpdTitle "<title>" ++ Theme.mpdSeparator ++ Theme.mpdArtist "<artist>" ] 10 , Run $ Network "enp0s25" [ "-t" , Theme.networkUpload "<tx> KB ^" ++ Theme.networkDownload "v <rx> KB" ] 25 , Run $ Weather "KNYC" [ "-t" , "<tempF>°" ] 3000 , Run $ Cpu [ "-t" , "<total>%" , "-x" , "" , "--minwidth" , "2" ] 25 , Run $ Date "%a %d %b %H:%M" "date" 10 ] , template = unwords [ "%handle%" , "}{" , "%mpd%" , Theme.statusSeparator , "%enp0s25%" , Theme.statusSeparator , Theme.icon Theme.CPU , "%cpu%" , Theme.statusSeparator , Theme.weather "%KNYC%" , Theme.statusSeparator , Theme.date "%date%" , "" ] } withTray :: Config withTray = long { position = TopP 0 systemTrayWidth , template = template long ++ " " ++ Theme.statusSeparator } short :: Config short = long { template = unwords [ "%handle%" , "}{" , Theme.date "%date%" , "" ] } blank :: Config blank = long { commands = [], template = "" }
8e89e21c28330356437c674262b779d5bd9175622f4b5816e6cbe675605c6b1d
GlideAngle/flare-timing
Rational.hs
# OPTIONS_GHC -fno - warn - partial - type - signatures # module Internal.Sphere.PointToPoint.Rational ( distance , azimuthFwd , azimuthRev ) where import Prelude hiding (flip) import Data.Ratio((%)) import qualified Data.Number.FixedFunctions as F import Data.UnitsOfMeasure (One, (-:), (*:), u, convert, fromRational') import Data.UnitsOfMeasure.Internal (Quantity(..), mk) import Flight.Units (realToFrac') import Flight.Units.Angle (Angle(..)) import Flight.LatLng (Lat(..), Lng(..), LatLng(..), AzimuthFwd, AzimuthRev) import Flight.LatLng.Rational (Epsilon(..)) import Flight.Zone (Radius(..), toRationalLatLng, realToFracLatLng) import Flight.Distance (TaskDistance(..), SpanLatLng) import Flight.Earth.Sphere (earthRadius) import Flight.Earth.Math (atan2') haversine :: Epsilon -> Quantity Rational [u| rad |] -> Quantity Rational [u| rad |] haversine (Epsilon eps) (MkQuantity x) = MkQuantity $ y * y where y :: Rational y = F.sin eps (x * (1 % 2)) aOfHaversine :: Epsilon -> LatLng Rational [u| rad |] -> LatLng Rational [u| rad |] -> Rational aOfHaversine e@(Epsilon eps) (LatLng (Lat xLat, Lng xLng)) (LatLng (Lat yLat, Lng yLng)) = hLat + F.cos eps xLat' * F.cos eps yLat' * hLng where (dLat, dLng) = (yLat -: xLat, yLng -: xLng) (MkQuantity xLat') = xLat (MkQuantity yLat') = yLat (MkQuantity hLat) = haversine e dLat (MkQuantity hLng) = haversine e dLng -- | Spherical distance using haversines and rational numbers. distance :: (Real a, Fractional a) => Epsilon -> SpanLatLng a distance e@(Epsilon eps) x y = TaskDistance . fromRational' $ radDist *: rEarth where Radius rEarth = earthRadius x' = toRationalLatLng x y' = toRationalLatLng y radDist :: Quantity Rational One radDist = mk $ 2 * F.asin eps (F.sqrt eps $ aOfHaversine e x' y') azimuthFwd :: (Real a, Fractional a) => Epsilon -> AzimuthFwd a azimuthFwd e x y = do let x' = realToFracLatLng x let y' = realToFracLatLng y realToFrac' <$> azimuthFwd' e x' y' azimuthRev :: (Real a, Fractional a) => Epsilon -> AzimuthRev a azimuthRev e x y = do let x' = realToFracLatLng x let y' = realToFracLatLng y realToFrac' <$> azimuthRev' e x' y' -- SEE: -type.co.uk/scripts/latlong.html azimuthFwd' :: Epsilon -> AzimuthFwd Rational azimuthFwd' e@(Epsilon eps) (LatLng (Lat xLatF, Lng xLngF)) (LatLng (Lat yLatF, Lng yLngF)) = Just . MkQuantity $ atan2' e x y where MkQuantity xLatF' = xLatF MkQuantity yLatF' = yLatF MkQuantity xLngF' = xLngF MkQuantity yLngF' = yLngF deltaLng = yLngF' - xLngF' x = sin' deltaLng * cos' yLatF' y = cos' xLatF' * sin' yLatF' - sin' xLatF' * cos' yLatF' * cos' deltaLng sin' = F.sin eps cos' = F.cos eps azimuthRev' :: Epsilon -> AzimuthRev Rational azimuthRev' e x y = rotate flip <$> azimuthFwd e y x where flip :: Quantity _ [u| rad |] flip = convert [u| 180 deg |]
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/earth/library/Internal/Sphere/PointToPoint/Rational.hs
haskell
| Spherical distance using haversines and rational numbers. SEE: -type.co.uk/scripts/latlong.html
# OPTIONS_GHC -fno - warn - partial - type - signatures # module Internal.Sphere.PointToPoint.Rational ( distance , azimuthFwd , azimuthRev ) where import Prelude hiding (flip) import Data.Ratio((%)) import qualified Data.Number.FixedFunctions as F import Data.UnitsOfMeasure (One, (-:), (*:), u, convert, fromRational') import Data.UnitsOfMeasure.Internal (Quantity(..), mk) import Flight.Units (realToFrac') import Flight.Units.Angle (Angle(..)) import Flight.LatLng (Lat(..), Lng(..), LatLng(..), AzimuthFwd, AzimuthRev) import Flight.LatLng.Rational (Epsilon(..)) import Flight.Zone (Radius(..), toRationalLatLng, realToFracLatLng) import Flight.Distance (TaskDistance(..), SpanLatLng) import Flight.Earth.Sphere (earthRadius) import Flight.Earth.Math (atan2') haversine :: Epsilon -> Quantity Rational [u| rad |] -> Quantity Rational [u| rad |] haversine (Epsilon eps) (MkQuantity x) = MkQuantity $ y * y where y :: Rational y = F.sin eps (x * (1 % 2)) aOfHaversine :: Epsilon -> LatLng Rational [u| rad |] -> LatLng Rational [u| rad |] -> Rational aOfHaversine e@(Epsilon eps) (LatLng (Lat xLat, Lng xLng)) (LatLng (Lat yLat, Lng yLng)) = hLat + F.cos eps xLat' * F.cos eps yLat' * hLng where (dLat, dLng) = (yLat -: xLat, yLng -: xLng) (MkQuantity xLat') = xLat (MkQuantity yLat') = yLat (MkQuantity hLat) = haversine e dLat (MkQuantity hLng) = haversine e dLng distance :: (Real a, Fractional a) => Epsilon -> SpanLatLng a distance e@(Epsilon eps) x y = TaskDistance . fromRational' $ radDist *: rEarth where Radius rEarth = earthRadius x' = toRationalLatLng x y' = toRationalLatLng y radDist :: Quantity Rational One radDist = mk $ 2 * F.asin eps (F.sqrt eps $ aOfHaversine e x' y') azimuthFwd :: (Real a, Fractional a) => Epsilon -> AzimuthFwd a azimuthFwd e x y = do let x' = realToFracLatLng x let y' = realToFracLatLng y realToFrac' <$> azimuthFwd' e x' y' azimuthRev :: (Real a, Fractional a) => Epsilon -> AzimuthRev a azimuthRev e x y = do let x' = realToFracLatLng x let y' = realToFracLatLng y realToFrac' <$> azimuthRev' e x' y' azimuthFwd' :: Epsilon -> AzimuthFwd Rational azimuthFwd' e@(Epsilon eps) (LatLng (Lat xLatF, Lng xLngF)) (LatLng (Lat yLatF, Lng yLngF)) = Just . MkQuantity $ atan2' e x y where MkQuantity xLatF' = xLatF MkQuantity yLatF' = yLatF MkQuantity xLngF' = xLngF MkQuantity yLngF' = yLngF deltaLng = yLngF' - xLngF' x = sin' deltaLng * cos' yLatF' y = cos' xLatF' * sin' yLatF' - sin' xLatF' * cos' yLatF' * cos' deltaLng sin' = F.sin eps cos' = F.cos eps azimuthRev' :: Epsilon -> AzimuthRev Rational azimuthRev' e x y = rotate flip <$> azimuthFwd e y x where flip :: Quantity _ [u| rad |] flip = convert [u| 180 deg |]
fbbc0d86e3cabb8f18739beaa7f3a0132852e11c3c9fabf2e99f3cb8bbf62722
clojure/core.typed
helpers.cljs
(ns cljs.core.typed.test.dnolen.utils.helpers) (defn ^{:ann '[Any Any -> Any]} index-of [xs x] (let [len (count xs)] (loop [i 0] (if (< i len) (if (= (nth xs i) x) i (recur (inc i))) -1))))
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.js/test/cljs/cljs/core/typed/test/dnolen/utils/helpers.cljs
clojure
(ns cljs.core.typed.test.dnolen.utils.helpers) (defn ^{:ann '[Any Any -> Any]} index-of [xs x] (let [len (count xs)] (loop [i 0] (if (< i len) (if (= (nth xs i) x) i (recur (inc i))) -1))))
b86196b7757b4e0b5b933ab49886bd46210860345edb234b01d53ce6407cbdee
fractalide/fractalide
adder.rkt
#lang racket/base (require fractalide/modules/rkt/rkt-fbp/agent) (define-agent #:input-array '("in") ; in array port #:output '("out") ; out port (define sum (for/fold ([sum 0]) ([(k v) (input-array "in")]) (+ sum (recv v)))) (send (output "out") sum))
null
https://raw.githubusercontent.com/fractalide/fractalide/9c54ec2615fcc2a1f3363292d4eed2a0fcb9c3a5/modules/rkt/rkt-fbp/agents/adder.rkt
racket
in array port out port
#lang racket/base (require fractalide/modules/rkt/rkt-fbp/agent) (define-agent (define sum (for/fold ([sum 0]) ([(k v) (input-array "in")]) (+ sum (recv v)))) (send (output "out") sum))
3c8dea483fc121c8ea965980dbe626127c955f2894fa063cd28d0b3a5c4a0bb9
agrafix/Spock
Action.hs
# LANGUAGE DataKinds # {-# LANGUAGE DoAndIfThenElse #-} # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Web.Spock.Action ( -- * Action types ActionT, W.ActionCtxT, -- * Handling requests request, header, rawHeader, cookies, cookie, reqMethod, preferredFormat, ClientPreferredFormat (..), body, jsonBody, jsonBody', files, UploadedFile (..), params, paramsGet, paramsPost, param, param', -- * Working with context getContext, runInContext, -- * Sending responses setStatus, setHeader, redirect, jumpNext, CookieSettings (..), defaultCookieSettings, CookieEOL (..), setCookie, deleteCookie, bytes, lazyBytes, setRawMultiHeader, MultiHeader (..), text, html, file, json, stream, response, respondApp, respondMiddleware, * Middleware helpers middlewarePass, modifyVault, queryVault, -- * Basic HTTP-Auth requireBasicAuth, withBasicAuthData, ) where import Web.Spock.Internal.CoreAction import qualified Web.Spock.Internal.Wire as W
null
https://raw.githubusercontent.com/agrafix/Spock/6055362b54f2fae5418188c3fc2fc1659ca43e79/Spock-core/src/Web/Spock/Action.hs
haskell
# LANGUAGE DoAndIfThenElse # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # * Action types * Handling requests * Working with context * Sending responses * Basic HTTP-Auth
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module Web.Spock.Action ActionT, W.ActionCtxT, request, header, rawHeader, cookies, cookie, reqMethod, preferredFormat, ClientPreferredFormat (..), body, jsonBody, jsonBody', files, UploadedFile (..), params, paramsGet, paramsPost, param, param', getContext, runInContext, setStatus, setHeader, redirect, jumpNext, CookieSettings (..), defaultCookieSettings, CookieEOL (..), setCookie, deleteCookie, bytes, lazyBytes, setRawMultiHeader, MultiHeader (..), text, html, file, json, stream, response, respondApp, respondMiddleware, * Middleware helpers middlewarePass, modifyVault, queryVault, requireBasicAuth, withBasicAuthData, ) where import Web.Spock.Internal.CoreAction import qualified Web.Spock.Internal.Wire as W
a5a1b02fe036e95843c3fcaf3a712377b4e6347e9305d044dcda98e0d0d23002
Workiva/eva
types.clj
Copyright 2015 - 2019 Workiva Inc. ;; ;; Licensed under the Eclipse Public License 1.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -1.0.php ;; ;; 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 eva.v2.messaging.node.manager.types (:require [clojure.spec.alpha :as s])) ;;;;;;;;;; SPEC ; ; ;;;;;;;;;; TODO : multispec (s/def ::config map?) ;;;;;;;;;;;;;; ;; END SPEC ;; ;;;;;;;;;;;;;; (defmulti messenger-node-discriminator "Returns a unique 'identity' for a messenger node for use in a resource manager." (fn [_ config] (:messenger-node-config/type config))) (defmulti messenger-node-constructor "Constructs and returns a SharedResource messenger node that satisfies the various messaging protocols" (fn [_ config] (:messenger-node-config/type config)))
null
https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/src/eva/v2/messaging/node/manager/types.clj
clojure
Licensed under the Eclipse Public License 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -1.0.php 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. ; END SPEC ;;
Copyright 2015 - 2019 Workiva Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns eva.v2.messaging.node.manager.types (:require [clojure.spec.alpha :as s])) TODO : multispec (s/def ::config map?) (defmulti messenger-node-discriminator "Returns a unique 'identity' for a messenger node for use in a resource manager." (fn [_ config] (:messenger-node-config/type config))) (defmulti messenger-node-constructor "Constructs and returns a SharedResource messenger node that satisfies the various messaging protocols" (fn [_ config] (:messenger-node-config/type config)))
f9b9195e1343511ef1048552c019b8a88d3276040355d8239ea5af27540f5699
goldfirere/units
Units.hs
# LANGUAGE DataKinds , TypeFamilies , TypeOperators # module Tests.Compile.Units where import Data.Metrology data Meter = Meters data Foot = Feet data Yard = Yards type Length = MkQu_U Meter type Time = MkQu_U Second data LengthD = LengthD instance Dimension LengthD data TimeD = TimeD instance Dimension TimeD instance Unit Meter where type BaseUnit Meter = Canonical type DimOfUnit Meter = LengthD instance Unit Foot where type BaseUnit Foot = Meter conversionRatio _ = 0.3048 instance Unit Yard where type BaseUnit Yard = Foot conversionRatio _ = 3 data Second = Seconds instance Unit Second where type BaseUnit Second = Canonical type DimOfUnit Second = TimeD data Hertz = Hertz instance Unit Hertz where type BaseUnit Hertz = Number :/ Second conversionRatio _ = 1
null
https://raw.githubusercontent.com/goldfirere/units/0ffc07627bb6c1eacd60469fd9366346cbfde334/units-test/Tests/Compile/Units.hs
haskell
# LANGUAGE DataKinds , TypeFamilies , TypeOperators # module Tests.Compile.Units where import Data.Metrology data Meter = Meters data Foot = Feet data Yard = Yards type Length = MkQu_U Meter type Time = MkQu_U Second data LengthD = LengthD instance Dimension LengthD data TimeD = TimeD instance Dimension TimeD instance Unit Meter where type BaseUnit Meter = Canonical type DimOfUnit Meter = LengthD instance Unit Foot where type BaseUnit Foot = Meter conversionRatio _ = 0.3048 instance Unit Yard where type BaseUnit Yard = Foot conversionRatio _ = 3 data Second = Seconds instance Unit Second where type BaseUnit Second = Canonical type DimOfUnit Second = TimeD data Hertz = Hertz instance Unit Hertz where type BaseUnit Hertz = Number :/ Second conversionRatio _ = 1
94c71776d9650b91037621d33ff1876693cd138d8ed254ed1a5a76e1221f3670
instedd/planwise
collections.clj
(ns planwise.util.collections) (defn find-by [coll field value] (reduce #(when (= value (field %2)) (reduced %2)) nil coll)) (defn sum-by [key coll] (reduce + (filter number? (map key coll)))) (defn merge-collections-by [key merge-fn & colls] (map (fn [[id same-key-maps]] (apply merge-fn same-key-maps)) (group-by key (apply concat colls)))) (defn map-vals [f m] (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m))
null
https://raw.githubusercontent.com/instedd/planwise/1bc2a5742ae3dc377dddf1f9e9bb60f0d2f59084/src/planwise/util/collections.clj
clojure
(ns planwise.util.collections) (defn find-by [coll field value] (reduce #(when (= value (field %2)) (reduced %2)) nil coll)) (defn sum-by [key coll] (reduce + (filter number? (map key coll)))) (defn merge-collections-by [key merge-fn & colls] (map (fn [[id same-key-maps]] (apply merge-fn same-key-maps)) (group-by key (apply concat colls)))) (defn map-vals [f m] (reduce-kv (fn [acc k v] (assoc acc k (f v))) {} m))
944d72ae950011a504fd357fa0c6a38eab47d33fe2f2a432ed1e97c59e53dcef
lambdamikel/DLMAPS
nrql-server-case.lisp
(in-package cl-user) ;;; ;;;-------------------------------------------- ;;; Automatically Generated nRQL Server Case Version : 1.9.1 ;;;-------------------------------------------- ;;; (defun process-nrql-request (expr stream n state output-string-stream) (case (first expr) ((xml-output) (process-racer-expr (second expr) nil n state output-string-stream) (let ((expr2 (if *last-error* (lisp-to-xml (format nil "~a" *last-error*) stream :newlines-p nil :ascii-p nil :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"error\"" n)) (lisp-to-xml (list (format nil "~s" *last-answer*) *last-answer*) stream :newlines-p nil :ascii-p t :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"answer\"" n))))) (answer expr state stream n expr2 output-string-stream))) ((xml-native-output) (process-racer-expr (second expr) nil n state output-string-stream) (let ((expr2 (if *last-error* (lisp-to-xml (format nil "~a" *last-error*) stream :newlines-p nil :ascii-p nil :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"error\"" n)) (lisp-to-xml (format nil "~s" *last-answer*) stream :newlines-p nil :ascii-p t :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"answer\"" n))))) (answer expr state stream n expr2 output-string-stream))) ((del-rcc-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'del-rcc-edge1) (rest expr))) output-string-stream))) ((del-rcc-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'del-rcc-node1) (rest expr))) output-string-stream))) ((rcc-edge-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-edge-label1) (rest expr))) output-string-stream))) ((rcc-node-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-node-label1) (rest expr))) output-string-stream))) ((rcc-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-edge1) (rest expr))) output-string-stream))) ((rcc-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-node1) (rest expr))) output-string-stream))) ((rcc-related) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-related1) (rest expr))) output-string-stream))) ((rcc-instance) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-instance1) (rest expr))) output-string-stream))) ((rcc-consistent?) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-consistent-p) (rest expr))) output-string-stream))) ((in-rcc-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-rcc-box) (rest expr))) output-string-stream))) ((in-mirror-data-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-mirror-data-box) (rest expr))) output-string-stream))) ((description-implies?) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::implies-p) (rest expr))) output-string-stream))) ((edge-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::edge-label1) (rest expr))) output-string-stream))) ((node-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::node-label1) (rest expr))) output-string-stream))) ((del-data-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::del-data-edge1) (rest expr))) output-string-stream))) ((del-data-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::del-data-node1) (rest expr))) output-string-stream))) ((data-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::data-edge1) (rest expr))) output-string-stream))) ((data-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::data-node1) (rest expr))) output-string-stream))) ((in-data-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-data-box) (rest expr))) output-string-stream))) ((undefquery) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'undefine-query) (rest expr))) output-string-stream))) ((def-and-exec-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-and-execute-query) (rest expr))) output-string-stream))) ((def-and-prep-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-and-prepare-query) (rest expr))) output-string-stream))) ((defquery) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-query) (rest expr))) output-string-stream))) ((preprule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-rule) (rest expr))) output-string-stream))) ((firerule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-apply-rule) (rest expr))) output-string-stream))) ((prepare-abox-rule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-rule) (rest expr))) output-string-stream))) ((prepare-tbox-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-tbox-query) (rest expr))) output-string-stream))) ((prepare-abox-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-query) (rest expr))) output-string-stream))) ((apply-abox-rule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-apply-rule) (rest expr))) output-string-stream))) ((tbox-retrieve) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-tbox-query) (rest expr))) output-string-stream))) ((retrieve-under-premise) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-query-under-premise) (rest expr))) output-string-stream))) ((retrieve) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-query) (rest expr))) output-string-stream))) ((with-nrql-settings) (let ((*server-timeout* nil)) (apply (symbol-function 'thematic-substrate::eval-nrql-settings) (lambda () (loop for expr1 in (cddr expr) do (process-racer-expr expr1 stream n state output-string-stream))) (second expr)))) ((describe-rule describe-query get-dag-of-qbox-for-abox show-qbox-for-abox get-nodes-in-qbox-for-abox get-nodes-in-current-qbox get-dag-of-current-qbox query-equivalents query-descendants query-children query-ancestors query-parents query-equivalent-p query-entails-p classify-query query-tautological-p query-inconsistent-p query-consistent-p abort-rule abort-query original-rule-body original-query-body rule-body query-body original-rule-head original-query-head rule-head query-head rule-accurate-p query-accurate-p get-answer get-all-remaining-sets-of-rule-consequences get-all-remaining-tuples get-next-n-remaining-sets-of-rule-consequences get-next-n-remaining-tuples describe-rule-status describe-query-status rule-inactive-p rule-processed-p query-inactive-p query-processed-p active-expensive-rule-p active-expensive-query-p cheap-rule-p cheap-query-p rule-active-p query-active-p rule-waiting-p query-waiting-p execute-applicable-rules unapplicable-rules applicable-rules add-chosen-sets-of-rule-consequences choose-current-set-of-rule-consequences rule-applicable-p rule-prepared-p query-prepared-p reexecute-rule reexecute-query reprepare-rule reprepare-query execute-rule execute-query rule-ready-p query-ready-p next-set-of-rule-consequences-available-p next-tuple-available-p get-current-set-of-rule-consequences get-next-set-of-rule-consequences get-current-tuple get-next-tuple delete-rule delete-query store-substrate-for-current-abox restore-all-substrates restore-substrate store-all-substrates store-substrate-for-abox get-nrql-version del-rcc-edge1 del-rcc-node1 rcc-edge-label1 rcc-node-label1 rcc-edge1 rcc-node1 rcc-related1 rcc-instance1 rcc-consistent-p create-rcc-edge create-rcc-node set-rcc-box set-mirror-data-box description-implies-p set-data-box get-data-edge-label get-data-node-label delete-data-edge delete-data-node create-data-edge create-data-node get-process-pool-size get-maximum-size-of-process-pool get-initial-size-of-process-pool set-maximum-size-of-process-pool set-initial-size-of-process-pool set-rewrite-defined-concepts set-nrql-mode show-current-qbox get-abox-of-current-qbox disable-query-realization enable-query-realization optimizer-dont-use-cardinality-heuristics optimizer-use-cardinality-heuristics disable-query-optimization enable-query-optimization disable-query-repository enable-query-repository dont-report-tautological-queries report-tautological-queries dont-report-inconsistent-queries report-inconsistent-queries describe-query-processing-mode describe-current-substrate include-permutations exclude-permutations dont-add-rule-consequences-automatically add-rule-consequences-automatically process-set-at-a-time process-tuple-at-a-time get-max-no-of-tuples-bound set-max-no-of-tuples-bound dont-check-abox-consistency-before-querying check-abox-consistency-before-querying enable-lazy-tuple-computation enable-eager-tuple-computation restore-standard-settings dont-add-role-assertions-for-datatype-properties add-role-assertions-for-datatype-properties disable-told-information-querying enable-told-information-querying disable-nrql-warnings enable-nrql-warnings disable-kb-has-changed-warning-tokens enable-kb-has-changed-warning-tokens disable-phase-two-starts-warning-tokens enable-phase-two-starts-warning-tokens disable-two-phase-query-processing-mode enable-two-phase-query-processing-mode disable-abox-mirroring enable-very-smart-abox-mirroring enable-smart-abox-mirroring enable-abox-mirroring disable-sql-data-substrate-mirroring enable-sql-data-substrate-mirroring disable-data-substrate-mirroring enable-data-substrate-mirroring wait-for-rules-to-terminate wait-for-queries-to-terminate describe-all-rules describe-all-queries get-all-answers get-answer-size run-all-rules reexecute-all-rules execute-all-rules run-all-queries reexecute-all-queries execute-all-queries abort-all-rules abort-all-queries terminated-rules inactive-rules processed-rules terminated-queries inactive-queries processed-queries waiting-expensive-rules waiting-cheap-rules waiting-rules waiting-expensive-queries waiting-cheap-queries waiting-queries running-expensive-rules running-cheap-rules running-rules running-expensive-queries running-cheap-queries running-queries active-expensive-rules active-cheap-rules active-rules active-expensive-queries active-cheap-queries active-queries prepared-rules ready-rules prepared-queries ready-queries expensive-rules cheap-rules inaccurate-rules accurate-rules all-rules expensive-queries cheap-queries inaccurate-queries accurate-queries all-queries describe-all-definitions describe-definition delete-all-definitions undefine-query define-and-prepare-query define-and-execute-query define-query racer-prepare-tbox-query racer-answer-tbox-query racer-prepare-rule racer-apply-rule prepare-nrql-engine racer-prepare-query racer-answer-query-under-premise racer-answer-query full-reset reset-nrql-engine reset-all-substrates delete-all-rules delete-all-queries) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function (first expr)) (rest expr))) output-string-stream))) (otherwise (error "Illegal operator in ~A" expr))))
null
https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/query/nrql-server-case.lisp
lisp
-------------------------------------------- Automatically Generated nRQL Server Case --------------------------------------------
(in-package cl-user) Version : 1.9.1 (defun process-nrql-request (expr stream n state output-string-stream) (case (first expr) ((xml-output) (process-racer-expr (second expr) nil n state output-string-stream) (let ((expr2 (if *last-error* (lisp-to-xml (format nil "~a" *last-error*) stream :newlines-p nil :ascii-p nil :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"error\"" n)) (lisp-to-xml (list (format nil "~s" *last-answer*) *last-answer*) stream :newlines-p nil :ascii-p t :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"answer\"" n))))) (answer expr state stream n expr2 output-string-stream))) ((xml-native-output) (process-racer-expr (second expr) nil n state output-string-stream) (let ((expr2 (if *last-error* (lisp-to-xml (format nil "~a" *last-error*) stream :newlines-p nil :ascii-p nil :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"error\"" n)) (lisp-to-xml (format nil "~s" *last-answer*) stream :newlines-p nil :ascii-p t :indentation-p nil :top-level-attributes (format nil "id=\"~d\" type=\"answer\"" n))))) (answer expr state stream n expr2 output-string-stream))) ((del-rcc-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'del-rcc-edge1) (rest expr))) output-string-stream))) ((del-rcc-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'del-rcc-node1) (rest expr))) output-string-stream))) ((rcc-edge-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-edge-label1) (rest expr))) output-string-stream))) ((rcc-node-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-node-label1) (rest expr))) output-string-stream))) ((rcc-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-edge1) (rest expr))) output-string-stream))) ((rcc-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-node1) (rest expr))) output-string-stream))) ((rcc-related) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-related1) (rest expr))) output-string-stream))) ((rcc-instance) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-instance1) (rest expr))) output-string-stream))) ((rcc-consistent?) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'rcc-consistent-p) (rest expr))) output-string-stream))) ((in-rcc-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-rcc-box) (rest expr))) output-string-stream))) ((in-mirror-data-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-mirror-data-box) (rest expr))) output-string-stream))) ((description-implies?) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::implies-p) (rest expr))) output-string-stream))) ((edge-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::edge-label1) (rest expr))) output-string-stream))) ((node-label) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::node-label1) (rest expr))) output-string-stream))) ((del-data-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::del-data-edge1) (rest expr))) output-string-stream))) ((del-data-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::del-data-node1) (rest expr))) output-string-stream))) ((data-edge) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::data-edge1) (rest expr))) output-string-stream))) ((data-node) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'thematic-substrate::data-node1) (rest expr))) output-string-stream))) ((in-data-box) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'set-data-box) (rest expr))) output-string-stream))) ((undefquery) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'undefine-query) (rest expr))) output-string-stream))) ((def-and-exec-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-and-execute-query) (rest expr))) output-string-stream))) ((def-and-prep-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-and-prepare-query) (rest expr))) output-string-stream))) ((defquery) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'define-query) (rest expr))) output-string-stream))) ((preprule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-rule) (rest expr))) output-string-stream))) ((firerule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-apply-rule) (rest expr))) output-string-stream))) ((prepare-abox-rule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-rule) (rest expr))) output-string-stream))) ((prepare-tbox-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-tbox-query) (rest expr))) output-string-stream))) ((prepare-abox-query) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-prepare-query) (rest expr))) output-string-stream))) ((apply-abox-rule) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-apply-rule) (rest expr))) output-string-stream))) ((tbox-retrieve) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-tbox-query) (rest expr))) output-string-stream))) ((retrieve-under-premise) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-query-under-premise) (rest expr))) output-string-stream))) ((retrieve) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function 'racer-answer-query) (rest expr))) output-string-stream))) ((with-nrql-settings) (let ((*server-timeout* nil)) (apply (symbol-function 'thematic-substrate::eval-nrql-settings) (lambda () (loop for expr1 in (cddr expr) do (process-racer-expr expr1 stream n state output-string-stream))) (second expr)))) ((describe-rule describe-query get-dag-of-qbox-for-abox show-qbox-for-abox get-nodes-in-qbox-for-abox get-nodes-in-current-qbox get-dag-of-current-qbox query-equivalents query-descendants query-children query-ancestors query-parents query-equivalent-p query-entails-p classify-query query-tautological-p query-inconsistent-p query-consistent-p abort-rule abort-query original-rule-body original-query-body rule-body query-body original-rule-head original-query-head rule-head query-head rule-accurate-p query-accurate-p get-answer get-all-remaining-sets-of-rule-consequences get-all-remaining-tuples get-next-n-remaining-sets-of-rule-consequences get-next-n-remaining-tuples describe-rule-status describe-query-status rule-inactive-p rule-processed-p query-inactive-p query-processed-p active-expensive-rule-p active-expensive-query-p cheap-rule-p cheap-query-p rule-active-p query-active-p rule-waiting-p query-waiting-p execute-applicable-rules unapplicable-rules applicable-rules add-chosen-sets-of-rule-consequences choose-current-set-of-rule-consequences rule-applicable-p rule-prepared-p query-prepared-p reexecute-rule reexecute-query reprepare-rule reprepare-query execute-rule execute-query rule-ready-p query-ready-p next-set-of-rule-consequences-available-p next-tuple-available-p get-current-set-of-rule-consequences get-next-set-of-rule-consequences get-current-tuple get-next-tuple delete-rule delete-query store-substrate-for-current-abox restore-all-substrates restore-substrate store-all-substrates store-substrate-for-abox get-nrql-version del-rcc-edge1 del-rcc-node1 rcc-edge-label1 rcc-node-label1 rcc-edge1 rcc-node1 rcc-related1 rcc-instance1 rcc-consistent-p create-rcc-edge create-rcc-node set-rcc-box set-mirror-data-box description-implies-p set-data-box get-data-edge-label get-data-node-label delete-data-edge delete-data-node create-data-edge create-data-node get-process-pool-size get-maximum-size-of-process-pool get-initial-size-of-process-pool set-maximum-size-of-process-pool set-initial-size-of-process-pool set-rewrite-defined-concepts set-nrql-mode show-current-qbox get-abox-of-current-qbox disable-query-realization enable-query-realization optimizer-dont-use-cardinality-heuristics optimizer-use-cardinality-heuristics disable-query-optimization enable-query-optimization disable-query-repository enable-query-repository dont-report-tautological-queries report-tautological-queries dont-report-inconsistent-queries report-inconsistent-queries describe-query-processing-mode describe-current-substrate include-permutations exclude-permutations dont-add-rule-consequences-automatically add-rule-consequences-automatically process-set-at-a-time process-tuple-at-a-time get-max-no-of-tuples-bound set-max-no-of-tuples-bound dont-check-abox-consistency-before-querying check-abox-consistency-before-querying enable-lazy-tuple-computation enable-eager-tuple-computation restore-standard-settings dont-add-role-assertions-for-datatype-properties add-role-assertions-for-datatype-properties disable-told-information-querying enable-told-information-querying disable-nrql-warnings enable-nrql-warnings disable-kb-has-changed-warning-tokens enable-kb-has-changed-warning-tokens disable-phase-two-starts-warning-tokens enable-phase-two-starts-warning-tokens disable-two-phase-query-processing-mode enable-two-phase-query-processing-mode disable-abox-mirroring enable-very-smart-abox-mirroring enable-smart-abox-mirroring enable-abox-mirroring disable-sql-data-substrate-mirroring enable-sql-data-substrate-mirroring disable-data-substrate-mirroring enable-data-substrate-mirroring wait-for-rules-to-terminate wait-for-queries-to-terminate describe-all-rules describe-all-queries get-all-answers get-answer-size run-all-rules reexecute-all-rules execute-all-rules run-all-queries reexecute-all-queries execute-all-queries abort-all-rules abort-all-queries terminated-rules inactive-rules processed-rules terminated-queries inactive-queries processed-queries waiting-expensive-rules waiting-cheap-rules waiting-rules waiting-expensive-queries waiting-cheap-queries waiting-queries running-expensive-rules running-cheap-rules running-rules running-expensive-queries running-cheap-queries running-queries active-expensive-rules active-cheap-rules active-rules active-expensive-queries active-cheap-queries active-queries prepared-rules ready-rules prepared-queries ready-queries expensive-rules cheap-rules inaccurate-rules accurate-rules all-rules expensive-queries cheap-queries inaccurate-queries accurate-queries all-queries describe-all-definitions describe-definition delete-all-definitions undefine-query define-and-prepare-query define-and-execute-query define-query racer-prepare-tbox-query racer-answer-tbox-query racer-prepare-rule racer-apply-rule prepare-nrql-engine racer-prepare-query racer-answer-query-under-premise racer-answer-query full-reset reset-nrql-engine reset-all-substrates delete-all-rules delete-all-queries) (let* ((saved-timeout *server-timeout*) (*server-timeout* nil)) (answer expr state stream n (let ((*server-timeout* saved-timeout)) (apply (symbol-function (first expr)) (rest expr))) output-string-stream))) (otherwise (error "Illegal operator in ~A" expr))))
6a5b3dd2b348c6da8a2c8bbca3d6eef220077a66a92c81d822cb5d5340e14dfd
NorfairKing/smos
Formatting.hs
module Smos.Report.Formatting where import Data.Time daysSince :: UTCTime -> UTCTime -> Int daysSince now t = i where i = diffInDays now t :: Int diffInDays :: UTCTime -> UTCTime -> Int diffInDays t1 t2 = floor $ diffUTCTime t1 t2 / nominalDay
null
https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos-report/src/Smos/Report/Formatting.hs
haskell
module Smos.Report.Formatting where import Data.Time daysSince :: UTCTime -> UTCTime -> Int daysSince now t = i where i = diffInDays now t :: Int diffInDays :: UTCTime -> UTCTime -> Int diffInDays t1 t2 = floor $ diffUTCTime t1 t2 / nominalDay
0d41256befb323e57e38a161122d22286c30d7fb5a23318617d104712cbde4e0
gnl/ghostwheel
test_utils_cljs.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 ghostwheel.test-utils-cljs) (defmacro do+expand! [form] `(do ~form (macroexpand-1 (quote ~form)))) (defmacro expand [form] `(macroexpand-1 (quote ~form))) (defmacro expand-full [form] `(macroexpand (quote ~form)))
null
https://raw.githubusercontent.com/gnl/ghostwheel/a85c3510178fc4fbcb95125b86116d698e2a232a/test/ghostwheel/test_utils_cljs.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.
Copyright ( c ) . All rights reserved . Eclipse Public License 2.0 ( -2.0/ ) (ns ghostwheel.test-utils-cljs) (defmacro do+expand! [form] `(do ~form (macroexpand-1 (quote ~form)))) (defmacro expand [form] `(macroexpand-1 (quote ~form))) (defmacro expand-full [form] `(macroexpand (quote ~form)))
2dcc6e6929f61a3b655aa07d7b72ef1c3380de486e48a75b241ce5a3325b4220
teamwalnut/graphql-ppx
schema_printer.ml
open Schema let rec print_type_ref (type_ref : type_ref) = match type_ref with | Schema.Named n -> n | List t -> "[" ^ print_type_ref t ^ "]" | NonNull t -> print_type_ref t ^ "!" let print_field ({ fm_name; fm_field_type } : field_meta) = fm_name ^ ": " ^ (fm_field_type |> print_type_ref) let print_input_field ({ am_name; am_arg_type } : argument_meta) = am_name ^ ": " ^ (am_arg_type |> print_type_ref) let print_object ({ om_fields; om_name } : object_meta) = (om_fields |> List.fold_left (fun p ({ fm_name } as field : Schema.field_meta) -> match fm_name <> "__typename" with | true -> p ^ "\n " ^ print_field field | false -> p) (om_name ^ " {")) ^ "\n}" let print_input_object ({ iom_input_fields; iom_name } : input_object_meta) = (iom_input_fields |> List.fold_left (fun p (input_field : Schema.argument_meta) -> p ^ "\n " ^ print_input_field input_field) (iom_name ^ " {")) ^ "\n}" let print_enum ({ em_name; em_values } : enum_meta) = em_name ^ " {\n" ^ (em_values |> List.fold_left (fun p { evm_name; evm_deprecation_reason } -> p ^ " " ^ evm_name ^ (match evm_deprecation_reason with | None -> "" | Some _ -> " (DEPRECATED)") ^ "\n") "") ^ "}" let print_scalar ({ sm_name } : scalar_meta) = sm_name let print_type (name : string) (schema : t) = Schema.lookup_type schema name |> Option.flat_map (function | Object obj_meta -> Some (print_object obj_meta) | Scalar scalar_meta -> Some (print_scalar scalar_meta) | InputObject input_obj_meta -> Some (print_input_object input_obj_meta) | Enum enum_meta -> Some (print_enum enum_meta) | Interface _ | Union _ -> None) let rec print_type_from_ref (type_ref : type_ref) (schema : t) = match type_ref with | Schema.Named n -> print_type n schema |> Option.get_or_else "N/A" | List t -> "[" ^ print_type_from_ref t schema ^ "]" | NonNull t -> print_type_from_ref t schema ^ "!"
null
https://raw.githubusercontent.com/teamwalnut/graphql-ppx/8276452ebe8d89a748b6b267afc94161650ab620/src/graphql_compiler/schema_printer.ml
ocaml
open Schema let rec print_type_ref (type_ref : type_ref) = match type_ref with | Schema.Named n -> n | List t -> "[" ^ print_type_ref t ^ "]" | NonNull t -> print_type_ref t ^ "!" let print_field ({ fm_name; fm_field_type } : field_meta) = fm_name ^ ": " ^ (fm_field_type |> print_type_ref) let print_input_field ({ am_name; am_arg_type } : argument_meta) = am_name ^ ": " ^ (am_arg_type |> print_type_ref) let print_object ({ om_fields; om_name } : object_meta) = (om_fields |> List.fold_left (fun p ({ fm_name } as field : Schema.field_meta) -> match fm_name <> "__typename" with | true -> p ^ "\n " ^ print_field field | false -> p) (om_name ^ " {")) ^ "\n}" let print_input_object ({ iom_input_fields; iom_name } : input_object_meta) = (iom_input_fields |> List.fold_left (fun p (input_field : Schema.argument_meta) -> p ^ "\n " ^ print_input_field input_field) (iom_name ^ " {")) ^ "\n}" let print_enum ({ em_name; em_values } : enum_meta) = em_name ^ " {\n" ^ (em_values |> List.fold_left (fun p { evm_name; evm_deprecation_reason } -> p ^ " " ^ evm_name ^ (match evm_deprecation_reason with | None -> "" | Some _ -> " (DEPRECATED)") ^ "\n") "") ^ "}" let print_scalar ({ sm_name } : scalar_meta) = sm_name let print_type (name : string) (schema : t) = Schema.lookup_type schema name |> Option.flat_map (function | Object obj_meta -> Some (print_object obj_meta) | Scalar scalar_meta -> Some (print_scalar scalar_meta) | InputObject input_obj_meta -> Some (print_input_object input_obj_meta) | Enum enum_meta -> Some (print_enum enum_meta) | Interface _ | Union _ -> None) let rec print_type_from_ref (type_ref : type_ref) (schema : t) = match type_ref with | Schema.Named n -> print_type n schema |> Option.get_or_else "N/A" | List t -> "[" ^ print_type_from_ref t schema ^ "]" | NonNull t -> print_type_from_ref t schema ^ "!"
7c3c6300f14579612480c8c8acb97807a11ecc9840e37ce2a5ee3687c5ebc6c9
Apress/haskell-quick-syntax-reference
ch6.hs
[1, 2, 3] ['a', 'x'] [True, False, False, True] :t [True, False, False, True] let numList = [3, 1, 0.5] :t numList ['a', 5] null [] null [3.2] head [0,1,2,3,4,5] tail [0,1,2,3,4,5,6] last [1,2,3,4,5,6,7] init [1,2,3,4,5,6,7] [1,2,3] ++ [4,5] "Haskell" ++ " " ++ "programming" 0 : [1,2] [0] ++ [1,2] length [1,2,3,4,5,6,7,8,9,10] length [] "Haskell programming" !! 10 let listOfLists = [[1,2,3], [0], [-5, 3, 8]] length listOfLists listOfLists !! 2 [1,2,3] < [4,5] [1,2,3] < [4,1,2] [1..20] ['a'..'z'] [1,3..20] [14,18..30]
null
https://raw.githubusercontent.com/Apress/haskell-quick-syntax-reference/8bcb2773532de752d6297a91a3aaf49fd92ed03b/ch6.hs
haskell
[1, 2, 3] ['a', 'x'] [True, False, False, True] :t [True, False, False, True] let numList = [3, 1, 0.5] :t numList ['a', 5] null [] null [3.2] head [0,1,2,3,4,5] tail [0,1,2,3,4,5,6] last [1,2,3,4,5,6,7] init [1,2,3,4,5,6,7] [1,2,3] ++ [4,5] "Haskell" ++ " " ++ "programming" 0 : [1,2] [0] ++ [1,2] length [1,2,3,4,5,6,7,8,9,10] length [] "Haskell programming" !! 10 let listOfLists = [[1,2,3], [0], [-5, 3, 8]] length listOfLists listOfLists !! 2 [1,2,3] < [4,5] [1,2,3] < [4,1,2] [1..20] ['a'..'z'] [1,3..20] [14,18..30]
25c0c85da29e30af8f8b63677b169b85b27c296abde47dd52b69dad119077d32
paulgray/exml
exml_query_tests.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 , Erlang Solutions Ltd. %%% @doc Unit tests for exml_query module %%% @end %%%------------------------------------------------------------------- -module(exml_query_tests). -include_lib("eunit/include/eunit.hrl"). -include("exml.hrl"). -compile(export_all). -define(MY_SPOON, xml(<<"<spoon whose='my'>", "<problem no='1'>is too big</problem>", "<problem no='2'>is too big</problem>", "<problem no='3'>is too big</problem>", "</spoon>">>)). -define (HTML, xml(<<"<html> <li> <ul><i>My</i> spoon is too <span class=\"size\">big</span></ul> <ul>My <i>spoon</i> is too <span class=\"size\">big</span></ul> <ul>My spoon <i>is</i> too <span class=\"size\">big</span></ul> </li> </html>">>)). %%-------------------------------------------------------------------- %% tests %%-------------------------------------------------------------------- element_query_test() -> we return only the first ( leftmost ) match ?assertEqual(xml(<<"<problem no='1'>is too big</problem>">>), exml_query:subelement(?MY_SPOON, <<"problem">>)), ?assertEqual(xml(<<"<problem no='1'>is too big</problem>">>), exml_query:path(?MY_SPOON, [{element, <<"problem">>}])). elements_query_test() -> Exemplar = [xml(<<"<problem no='1'>is too big</problem>">>), xml(<<"<problem no='2'>is too big</problem>">>), xml(<<"<problem no='3'>is too big</problem>">>)], ?assertEqual(Exemplar, exml_query:subelements(?MY_SPOON, <<"problem">>)). attribute_query_test() -> ?assertEqual(<<"my">>, exml_query:attr(?MY_SPOON, <<"whose">>)), ?assertEqual(<<"my">>, exml_query:path(?MY_SPOON, [{attr, <<"whose">>}])), ?assertEqual(undefined, exml_query:attr(?MY_SPOON, <<"banana">>)), ?assertEqual('IAmA', exml_query:attr(?MY_SPOON, <<"banana">>, 'IAmA')). cdata_query_test() -> ?assertEqual(<<"">>, exml_query:cdata(?MY_SPOON)), ?assertEqual(<<"">>, exml_query:path(?MY_SPOON, [cdata])), IAmA = xml(<<"<i-am>a banana</i-am>">>), ?assertEqual(<<"a banana">>, exml_query:cdata(IAmA)), ?assertEqual(<<"a banana">>, exml_query:path(IAmA, [cdata])). path_query_test() -> ?assertEqual(?MY_SPOON, exml_query:path(?MY_SPOON, [])), ?assertEqual(<<"is too big">>, exml_query:path(?MY_SPOON, [{element, <<"problem">>}, cdata])), ?assertEqual(<<"1">>, exml_query:path(?MY_SPOON, [{element, <<"problem">>}, {attr, <<"no">>}])), %% I couldn't find anything complex enough in that silly cartoon :[ Qux = xml(<<"<foo><bar><baz a='b'>qux</baz></bar></foo>">>), ?assertEqual(<<"qux">>, exml_query:path(Qux, [{element, <<"bar">>}, {element, <<"baz">>}, cdata])), ?assertEqual(<<"b">>, exml_query:path(Qux, [{element, <<"bar">>}, {element, <<"baz">>}, {attr, <<"a">>}])). failed_path_query_test() -> ?assertEqual(undefined, exml_query:path(?MY_SPOON, [{element, <<"banana">>}])), ?assertEqual('IAmA', exml_query:path(?MY_SPOON, [{element, <<"banana">>}], 'IAmA')). paths_query_test() -> ?assertEqual([?MY_SPOON], exml_query:paths(?MY_SPOON, [])), ?assertEqual([<<"is too big">>, <<"is too big">>, <<"is too big">>], exml_query:paths(?MY_SPOON, [{element, <<"problem">>}, cdata])), ?assertEqual([<<"1">>, <<"2">>, <<"3">>], exml_query:paths(?MY_SPOON, [{element, <<"problem">>}, {attr, <<"no">>}])), ?assertEqual([], exml_query:paths(?MY_SPOON, [{element, <<"banana">>}])), ?assertEqual([<<"My">>, <<"spoon">>, <<"is">>], exml_query:paths(?HTML, [{element, <<"li">>}, {element, <<"ul">>}, {element, <<"i">>}, cdata])), ?assertEqual([<<"size">>, <<"size">>, <<"size">>], exml_query:paths(?HTML, [{element, <<"li">>}, {element, <<"ul">>}, {element, <<"span">>}, {attr, <<"class">>}])). %%-------------------------------------------------------------------- %% helpers %%-------------------------------------------------------------------- xml(Raw) -> {ok, Tree} = exml:parse(Raw), Tree.
null
https://raw.githubusercontent.com/paulgray/exml/d04d0dfc956bd2bf5d9629a7524c6840eb02df28/test/exml_query_tests.erl
erlang
------------------------------------------------------------------- @doc Unit tests for exml_query module @end ------------------------------------------------------------------- -------------------------------------------------------------------- tests -------------------------------------------------------------------- I couldn't find anything complex enough in that silly cartoon :[ -------------------------------------------------------------------- helpers --------------------------------------------------------------------
@author < > ( C ) 2011 , Erlang Solutions Ltd. -module(exml_query_tests). -include_lib("eunit/include/eunit.hrl"). -include("exml.hrl"). -compile(export_all). -define(MY_SPOON, xml(<<"<spoon whose='my'>", "<problem no='1'>is too big</problem>", "<problem no='2'>is too big</problem>", "<problem no='3'>is too big</problem>", "</spoon>">>)). -define (HTML, xml(<<"<html> <li> <ul><i>My</i> spoon is too <span class=\"size\">big</span></ul> <ul>My <i>spoon</i> is too <span class=\"size\">big</span></ul> <ul>My spoon <i>is</i> too <span class=\"size\">big</span></ul> </li> </html>">>)). element_query_test() -> we return only the first ( leftmost ) match ?assertEqual(xml(<<"<problem no='1'>is too big</problem>">>), exml_query:subelement(?MY_SPOON, <<"problem">>)), ?assertEqual(xml(<<"<problem no='1'>is too big</problem>">>), exml_query:path(?MY_SPOON, [{element, <<"problem">>}])). elements_query_test() -> Exemplar = [xml(<<"<problem no='1'>is too big</problem>">>), xml(<<"<problem no='2'>is too big</problem>">>), xml(<<"<problem no='3'>is too big</problem>">>)], ?assertEqual(Exemplar, exml_query:subelements(?MY_SPOON, <<"problem">>)). attribute_query_test() -> ?assertEqual(<<"my">>, exml_query:attr(?MY_SPOON, <<"whose">>)), ?assertEqual(<<"my">>, exml_query:path(?MY_SPOON, [{attr, <<"whose">>}])), ?assertEqual(undefined, exml_query:attr(?MY_SPOON, <<"banana">>)), ?assertEqual('IAmA', exml_query:attr(?MY_SPOON, <<"banana">>, 'IAmA')). cdata_query_test() -> ?assertEqual(<<"">>, exml_query:cdata(?MY_SPOON)), ?assertEqual(<<"">>, exml_query:path(?MY_SPOON, [cdata])), IAmA = xml(<<"<i-am>a banana</i-am>">>), ?assertEqual(<<"a banana">>, exml_query:cdata(IAmA)), ?assertEqual(<<"a banana">>, exml_query:path(IAmA, [cdata])). path_query_test() -> ?assertEqual(?MY_SPOON, exml_query:path(?MY_SPOON, [])), ?assertEqual(<<"is too big">>, exml_query:path(?MY_SPOON, [{element, <<"problem">>}, cdata])), ?assertEqual(<<"1">>, exml_query:path(?MY_SPOON, [{element, <<"problem">>}, {attr, <<"no">>}])), Qux = xml(<<"<foo><bar><baz a='b'>qux</baz></bar></foo>">>), ?assertEqual(<<"qux">>, exml_query:path(Qux, [{element, <<"bar">>}, {element, <<"baz">>}, cdata])), ?assertEqual(<<"b">>, exml_query:path(Qux, [{element, <<"bar">>}, {element, <<"baz">>}, {attr, <<"a">>}])). failed_path_query_test() -> ?assertEqual(undefined, exml_query:path(?MY_SPOON, [{element, <<"banana">>}])), ?assertEqual('IAmA', exml_query:path(?MY_SPOON, [{element, <<"banana">>}], 'IAmA')). paths_query_test() -> ?assertEqual([?MY_SPOON], exml_query:paths(?MY_SPOON, [])), ?assertEqual([<<"is too big">>, <<"is too big">>, <<"is too big">>], exml_query:paths(?MY_SPOON, [{element, <<"problem">>}, cdata])), ?assertEqual([<<"1">>, <<"2">>, <<"3">>], exml_query:paths(?MY_SPOON, [{element, <<"problem">>}, {attr, <<"no">>}])), ?assertEqual([], exml_query:paths(?MY_SPOON, [{element, <<"banana">>}])), ?assertEqual([<<"My">>, <<"spoon">>, <<"is">>], exml_query:paths(?HTML, [{element, <<"li">>}, {element, <<"ul">>}, {element, <<"i">>}, cdata])), ?assertEqual([<<"size">>, <<"size">>, <<"size">>], exml_query:paths(?HTML, [{element, <<"li">>}, {element, <<"ul">>}, {element, <<"span">>}, {attr, <<"class">>}])). xml(Raw) -> {ok, Tree} = exml:parse(Raw), Tree.
012b64ff0e11345e849fd63a8432065b64e73269a9bb3b419f6350f76f1d286f
dsorokin/aivika
StreamMemo.hs
import Control.Monad import Control.Monad.Trans import Control.Arrow import Simulation.Aivika specs = Specs 0 10 0.1 RungeKutta4 SimpleGenerator model :: Simulation () model = do let display n a = do t <- liftDynamics time liftIO $ do putStr "n = " putStr $ show n putStr ", t = " putStr $ show t putStr ", a = " putStrLn $ show a let trace :: Show a => String -> Stream (Arrival a) -> Process () trace name = consumeStream (\a -> display name a) s <- memoStream $ randomUniformStream 1 2 runProcessInStartTime $ trace "MemoizedS " s runProcessInStartTime $ trace "MemoizedS(2) " s runProcessInStartTime $ trace "MemoizedS(3) " s runProcessInStartTime $ trace "MemoizedS(4) " s runEventInStopTime $ return () main = runSimulation model specs
null
https://raw.githubusercontent.com/dsorokin/aivika/7a14f460ab114b0f8cdfcd05d5cc889fdc2db0a4/tests/StreamMemo.hs
haskell
import Control.Monad import Control.Monad.Trans import Control.Arrow import Simulation.Aivika specs = Specs 0 10 0.1 RungeKutta4 SimpleGenerator model :: Simulation () model = do let display n a = do t <- liftDynamics time liftIO $ do putStr "n = " putStr $ show n putStr ", t = " putStr $ show t putStr ", a = " putStrLn $ show a let trace :: Show a => String -> Stream (Arrival a) -> Process () trace name = consumeStream (\a -> display name a) s <- memoStream $ randomUniformStream 1 2 runProcessInStartTime $ trace "MemoizedS " s runProcessInStartTime $ trace "MemoizedS(2) " s runProcessInStartTime $ trace "MemoizedS(3) " s runProcessInStartTime $ trace "MemoizedS(4) " s runEventInStopTime $ return () main = runSimulation model specs
e05fe45a44aaa2fdac03cb91730594d562c81414ca3fa804ff57865e6b3d6e6b
benjaminselfridge/fifteen
UI.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Fifteen.UI where import Fifteen.Logic import qualified Brick as B import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.Center as B import qualified Graphics.Vty as V import Data.Time.Clock import Lens.Micro.Platform import System.Random import Text.Printf ( printf ) type Resource = () -- | The only additional event we use is a timer event from the outside world telling us the current time so we can update the ' GameState ' . It does n't -- matter how often these ticks are received, as long as they are requently -- enough that we can know how many seconds has passed (so something like every tenth of a second should be sufficient ) . data FifteenEvent = Tick UTCTime -- ^ When we receive a 'Tick', we update the current time in the ' GameState ' . data GameState = GameState { _gsBoard :: Board , _gsRandomGen :: StdGen , _gsGameMode :: GameMode , _gsStartTime :: UTCTime -- ^ Time when the current game was started , _gsCurrentTime :: UTCTime -- ^ Time right now } data GameMode = InProgress | The ' Int ' is the number of seconds to solve . | Solved Int makeLenses ''GameState fifteenApp :: B.App GameState FifteenEvent Resource fifteenApp = B.App { B.appDraw = draw , B.appChooseCursor = (\_ _ -> Nothing) , B.appHandleEvent = handleEvent , B.appStartEvent = startEvent , B.appAttrMap = attrMap } draw :: GameState -> [B.Widget n] draw gs = [ B.center ((B.vLimit 5 $ B.center $ B.str "15") B.<=> (B.vLimit 20 $ B.center $ drawBoard (gs ^. gsBoard)) B.<=> (B.vLimit 1 $ B.center $ status (gs ^. gsGameMode) seconds) B.<=> (B.center $ help)) ] where seconds = secondsElapsed gs drawBoard :: Board -> B.Widget n drawBoard b = (drawTile (tileAt b R1 C1) B.<+> drawTile (tileAt b R1 C2) B.<+> drawTile (tileAt b R1 C3) B.<+> drawTile (tileAt b R1 C4)) B.<=> (drawTile (tileAt b R2 C1) B.<+> drawTile (tileAt b R2 C2) B.<+> drawTile (tileAt b R2 C3) B.<+> drawTile (tileAt b R2 C4)) B.<=> (drawTile (tileAt b R3 C1) B.<+> drawTile (tileAt b R3 C2) B.<+> drawTile (tileAt b R3 C3) B.<+> drawTile (tileAt b R3 C4)) B.<=> (drawTile (tileAt b R4 C1) B.<+> drawTile (tileAt b R4 C2) B.<+> drawTile (tileAt b R4 C3) B.<+> drawTile (tileAt b R4 C4)) drawTile :: Tile -> B.Widget n drawTile t = B.border $ case t of T0 -> B.padLeftRight 2 $ B.padTopBottom 1 $ B.str s _ -> B.withDefAttr "tile" $ B.padLeftRight 2 $ B.padTopBottom 1 $ B.str s where s = printf "%2s" (tileStr t) secondsElapsed :: GameState -> Int secondsElapsed gs = floor $ nominalDiffTimeToSeconds $ diffUTCTime (gs ^. gsCurrentTime) (gs ^. gsStartTime) status :: GameMode -> Int -> B.Widget n status InProgress i = B.str $ "Time: " ++ show i ++ "s" status (Solved i) _ = B.str $ "Solved (" ++ show i ++ "s)! Nice job!" help :: B.Widget n help = B.hBox [ B.padLeftRight 1 $ B.vBox [ B.str "up/down/left/right" , B.str "n" , B.str "q" ] , B.padLeftRight 1 $ B.vBox [ B.str "move tile" , B.str "new game" , B.str "quit" ] ] | Apply a move to a ' GameState ' . First apply it to the board , and if the resulting board is solved , update the ' ' to ' Solved ' , with the amount -- of time the user took to solve it. gsMakeMove :: Move -> GameState -> GameState gsMakeMove m gs0 = let gs1 = gs0 & gsBoard %~ move m gs2 = gs1 & gsGameMode .~ case isSolved (gs1 ^. gsBoard) of True -> Solved (secondsElapsed gs0) False -> InProgress in gs2 -- | Start a new game. gsNewGame :: GameState -> GameState gsNewGame gs = let (b, g') = shuffleBoard (gs ^. gsRandomGen) (gs ^. gsBoard) in GameState b g' InProgress (gs ^. gsCurrentTime) (gs ^. gsCurrentTime) handleEvent :: GameState -> B.BrickEvent Resource FifteenEvent -> B.EventM Resource (B.Next GameState) handleEvent gs be = case gs ^. gsGameMode of InProgress -> case be of B.VtyEvent (V.EvKey V.KUp []) -> B.continue (gsMakeMove MUp gs) B.VtyEvent (V.EvKey V.KDown []) -> B.continue (gsMakeMove MDown gs) B.VtyEvent (V.EvKey V.KLeft []) -> B.continue (gsMakeMove MLeft gs) B.VtyEvent (V.EvKey V.KRight []) -> B.continue (gsMakeMove MRight gs) B.VtyEvent (V.EvKey (V.KChar 'n') []) -> B.continue (gsNewGame gs) B.VtyEvent (V.EvKey (V.KChar 'q') []) -> B.halt gs B.AppEvent (Tick currentTime) -> B.continue (gs & gsCurrentTime .~ currentTime) _ -> B.continue gs Solved _ -> case be of B.VtyEvent (V.EvKey (V.KChar 'n') []) -> B.continue (gsNewGame gs) B.VtyEvent (V.EvKey (V.KChar 'q') []) -> B.halt gs B.AppEvent (Tick currentTime) -> B.continue (gs & gsCurrentTime .~ currentTime) _ -> B.continue gs startEvent :: GameState -> B.EventM Resource GameState startEvent gs = return gs attrMap :: GameState -> B.AttrMap attrMap gs = case gs ^. gsGameMode of InProgress -> B.attrMap V.defAttr [ ("tile", V.withBackColor V.defAttr V.blue) ] Solved _ -> B.attrMap V.defAttr [ ("tile", V.withBackColor V.defAttr V.green) ]
null
https://raw.githubusercontent.com/benjaminselfridge/fifteen/fdefcde9a334f9720395d2f08f95dce2d503087d/src/Fifteen/UI.hs
haskell
# LANGUAGE OverloadedStrings # | The only additional event we use is a timer event from the outside world matter how often these ticks are received, as long as they are requently enough that we can know how many seconds has passed (so something like every ^ When we receive a 'Tick', we update the current time in ^ Time when the current game was started ^ Time right now of time the user took to solve it. | Start a new game.
# LANGUAGE TemplateHaskell # module Fifteen.UI where import Fifteen.Logic import qualified Brick as B import qualified Brick.Widgets.Border as B import qualified Brick.Widgets.Center as B import qualified Graphics.Vty as V import Data.Time.Clock import Lens.Micro.Platform import System.Random import Text.Printf ( printf ) type Resource = () telling us the current time so we can update the ' GameState ' . It does n't tenth of a second should be sufficient ) . data FifteenEvent = Tick UTCTime the ' GameState ' . data GameState = GameState { _gsBoard :: Board , _gsRandomGen :: StdGen , _gsGameMode :: GameMode , _gsStartTime :: UTCTime , _gsCurrentTime :: UTCTime } data GameMode = InProgress | The ' Int ' is the number of seconds to solve . | Solved Int makeLenses ''GameState fifteenApp :: B.App GameState FifteenEvent Resource fifteenApp = B.App { B.appDraw = draw , B.appChooseCursor = (\_ _ -> Nothing) , B.appHandleEvent = handleEvent , B.appStartEvent = startEvent , B.appAttrMap = attrMap } draw :: GameState -> [B.Widget n] draw gs = [ B.center ((B.vLimit 5 $ B.center $ B.str "15") B.<=> (B.vLimit 20 $ B.center $ drawBoard (gs ^. gsBoard)) B.<=> (B.vLimit 1 $ B.center $ status (gs ^. gsGameMode) seconds) B.<=> (B.center $ help)) ] where seconds = secondsElapsed gs drawBoard :: Board -> B.Widget n drawBoard b = (drawTile (tileAt b R1 C1) B.<+> drawTile (tileAt b R1 C2) B.<+> drawTile (tileAt b R1 C3) B.<+> drawTile (tileAt b R1 C4)) B.<=> (drawTile (tileAt b R2 C1) B.<+> drawTile (tileAt b R2 C2) B.<+> drawTile (tileAt b R2 C3) B.<+> drawTile (tileAt b R2 C4)) B.<=> (drawTile (tileAt b R3 C1) B.<+> drawTile (tileAt b R3 C2) B.<+> drawTile (tileAt b R3 C3) B.<+> drawTile (tileAt b R3 C4)) B.<=> (drawTile (tileAt b R4 C1) B.<+> drawTile (tileAt b R4 C2) B.<+> drawTile (tileAt b R4 C3) B.<+> drawTile (tileAt b R4 C4)) drawTile :: Tile -> B.Widget n drawTile t = B.border $ case t of T0 -> B.padLeftRight 2 $ B.padTopBottom 1 $ B.str s _ -> B.withDefAttr "tile" $ B.padLeftRight 2 $ B.padTopBottom 1 $ B.str s where s = printf "%2s" (tileStr t) secondsElapsed :: GameState -> Int secondsElapsed gs = floor $ nominalDiffTimeToSeconds $ diffUTCTime (gs ^. gsCurrentTime) (gs ^. gsStartTime) status :: GameMode -> Int -> B.Widget n status InProgress i = B.str $ "Time: " ++ show i ++ "s" status (Solved i) _ = B.str $ "Solved (" ++ show i ++ "s)! Nice job!" help :: B.Widget n help = B.hBox [ B.padLeftRight 1 $ B.vBox [ B.str "up/down/left/right" , B.str "n" , B.str "q" ] , B.padLeftRight 1 $ B.vBox [ B.str "move tile" , B.str "new game" , B.str "quit" ] ] | Apply a move to a ' GameState ' . First apply it to the board , and if the resulting board is solved , update the ' ' to ' Solved ' , with the amount gsMakeMove :: Move -> GameState -> GameState gsMakeMove m gs0 = let gs1 = gs0 & gsBoard %~ move m gs2 = gs1 & gsGameMode .~ case isSolved (gs1 ^. gsBoard) of True -> Solved (secondsElapsed gs0) False -> InProgress in gs2 gsNewGame :: GameState -> GameState gsNewGame gs = let (b, g') = shuffleBoard (gs ^. gsRandomGen) (gs ^. gsBoard) in GameState b g' InProgress (gs ^. gsCurrentTime) (gs ^. gsCurrentTime) handleEvent :: GameState -> B.BrickEvent Resource FifteenEvent -> B.EventM Resource (B.Next GameState) handleEvent gs be = case gs ^. gsGameMode of InProgress -> case be of B.VtyEvent (V.EvKey V.KUp []) -> B.continue (gsMakeMove MUp gs) B.VtyEvent (V.EvKey V.KDown []) -> B.continue (gsMakeMove MDown gs) B.VtyEvent (V.EvKey V.KLeft []) -> B.continue (gsMakeMove MLeft gs) B.VtyEvent (V.EvKey V.KRight []) -> B.continue (gsMakeMove MRight gs) B.VtyEvent (V.EvKey (V.KChar 'n') []) -> B.continue (gsNewGame gs) B.VtyEvent (V.EvKey (V.KChar 'q') []) -> B.halt gs B.AppEvent (Tick currentTime) -> B.continue (gs & gsCurrentTime .~ currentTime) _ -> B.continue gs Solved _ -> case be of B.VtyEvent (V.EvKey (V.KChar 'n') []) -> B.continue (gsNewGame gs) B.VtyEvent (V.EvKey (V.KChar 'q') []) -> B.halt gs B.AppEvent (Tick currentTime) -> B.continue (gs & gsCurrentTime .~ currentTime) _ -> B.continue gs startEvent :: GameState -> B.EventM Resource GameState startEvent gs = return gs attrMap :: GameState -> B.AttrMap attrMap gs = case gs ^. gsGameMode of InProgress -> B.attrMap V.defAttr [ ("tile", V.withBackColor V.defAttr V.blue) ] Solved _ -> B.attrMap V.defAttr [ ("tile", V.withBackColor V.defAttr V.green) ]
02b9f329e07fe833499f94899d065a171dd4a0a99a66d808caa41f8666356571
haskell/haskell-language-server
Hole.hs
foo = _new_def
null
https://raw.githubusercontent.com/haskell/haskell-language-server/bc18cedf157e19c75c5676d8defcb982d6488fad/plugins/hls-refactor-plugin/test/data/golden/add-arg/Hole.hs
haskell
foo = _new_def
9cd31fe55241930d2d028a767468d8ca73dbc19ecf8a5e4c8ea0066c75ab0c87
kenkeiras/EPC
mochiutf8.erl
@copyright 2010 Mochi Media , Inc. @author < > @doc Algorithm to convert any binary to a valid UTF-8 sequence by ignoring %% invalid bytes. -module(mochiutf8). -export([valid_utf8_bytes/1, codepoint_to_bytes/1, codepoints_to_bytes/1]). -export([bytes_to_codepoints/1, bytes_foldl/3, codepoint_foldl/3]). -export([read_codepoint/1, len/1]). %% External API -type unichar_low() :: 0..16#d7ff. -type unichar_high() :: 16#e000..16#10ffff. -type unichar() :: unichar_low() | unichar_high(). -spec codepoint_to_bytes(unichar()) -> binary(). @doc Convert a unicode codepoint to UTF-8 bytes . codepoint_to_bytes(C) when (C >= 16#00 andalso C =< 16#7f) -> %% U+0000 - U+007F - 7 bits <<C>>; codepoint_to_bytes(C) when (C >= 16#080 andalso C =< 16#07FF) -> U+0080 - U+07FF - 11 bits <<0:5, B1:5, B0:6>> = <<C:16>>, <<2#110:3, B1:5, 2#10:2, B0:6>>; codepoint_to_bytes(C) when (C >= 16#0800 andalso C =< 16#FFFF) andalso (C < 16#D800 orelse C > 16#DFFF) -> U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) <<B2:4, B1:6, B0:6>> = <<C:16>>, <<2#1110:4, B2:4, 2#10:2, B1:6, 2#10:2, B0:6>>; codepoint_to_bytes(C) when (C >= 16#010000 andalso C =< 16#10FFFF) -> %% U+10000 - U+10FFFF - 21 bits <<0:3, B3:3, B2:6, B1:6, B0:6>> = <<C:24>>, <<2#11110:5, B3:3, 2#10:2, B2:6, 2#10:2, B1:6, 2#10:2, B0:6>>. -spec codepoints_to_bytes([unichar()]) -> binary(). @doc Convert a list of codepoints to a UTF-8 binary . codepoints_to_bytes(L) -> <<<<(codepoint_to_bytes(C))/binary>> || C <- L>>. -spec read_codepoint(binary()) -> {unichar(), binary(), binary()}. read_codepoint(Bin = <<2#0:1, C:7, Rest/binary>>) -> %% U+0000 - U+007F - 7 bits <<B:1/binary, _/binary>> = Bin, {C, B, Rest}; read_codepoint(Bin = <<2#110:3, B1:5, 2#10:2, B0:6, Rest/binary>>) -> U+0080 - U+07FF - 11 bits case <<B1:5, B0:6>> of <<C:11>> when C >= 16#80 -> <<B:2/binary, _/binary>> = Bin, {C, B, Rest} end; read_codepoint(Bin = <<2#1110:4, B2:4, 2#10:2, B1:6, 2#10:2, B0:6, Rest/binary>>) -> U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) case <<B2:4, B1:6, B0:6>> of <<C:16>> when (C >= 16#0800 andalso C =< 16#FFFF) andalso (C < 16#D800 orelse C > 16#DFFF) -> <<B:3/binary, _/binary>> = Bin, {C, B, Rest} end; read_codepoint(Bin = <<2#11110:5, B3:3, 2#10:2, B2:6, 2#10:2, B1:6, 2#10:2, B0:6, Rest/binary>>) -> %% U+10000 - U+10FFFF - 21 bits case <<B3:3, B2:6, B1:6, B0:6>> of <<C:21>> when (C >= 16#010000 andalso C =< 16#10FFFF) -> <<B:4/binary, _/binary>> = Bin, {C, B, Rest} end. -spec codepoint_foldl(fun((unichar(), _) -> _), _, binary()) -> _. codepoint_foldl(F, Acc, <<>>) when is_function(F, 2) -> Acc; codepoint_foldl(F, Acc, Bin) -> {C, _, Rest} = read_codepoint(Bin), codepoint_foldl(F, F(C, Acc), Rest). -spec bytes_foldl(fun((binary(), _) -> _), _, binary()) -> _. bytes_foldl(F, Acc, <<>>) when is_function(F, 2) -> Acc; bytes_foldl(F, Acc, Bin) -> {_, B, Rest} = read_codepoint(Bin), bytes_foldl(F, F(B, Acc), Rest). -spec bytes_to_codepoints(binary()) -> [unichar()]. bytes_to_codepoints(B) -> lists:reverse(codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], B)). -spec len(binary()) -> non_neg_integer(). len(<<>>) -> 0; len(B) -> {_, _, Rest} = read_codepoint(B), 1 + len(Rest). -spec valid_utf8_bytes(B::binary()) -> binary(). @doc Return only the bytes in B that represent valid UTF-8 . Uses the following recursive algorithm : skip one byte if B does not follow UTF-8 syntax ( a 1 - 4 byte encoding of some number ) , skip sequence of 2 - 4 bytes if it represents an overlong encoding %% or bad code point (surrogate U+D800 - U+DFFF or > U+10FFFF). valid_utf8_bytes(B) when is_binary(B) -> binary_skip_bytes(B, invalid_utf8_indexes(B)). %% Internal API -spec binary_skip_bytes(binary(), [non_neg_integer()]) -> binary(). @doc Return B , but skipping the 0 - based indexes in L. binary_skip_bytes(B, []) -> B; binary_skip_bytes(B, L) -> binary_skip_bytes(B, L, 0, []). @private -spec binary_skip_bytes(binary(), [non_neg_integer()], non_neg_integer(), iolist()) -> binary(). binary_skip_bytes(B, [], _N, Acc) -> iolist_to_binary(lists:reverse([B | Acc])); binary_skip_bytes(<<_, RestB/binary>>, [N | RestL], N, Acc) -> binary_skip_bytes(RestB, RestL, 1 + N, Acc); binary_skip_bytes(<<C, RestB/binary>>, L, N, Acc) -> binary_skip_bytes(RestB, L, 1 + N, [C | Acc]). -spec invalid_utf8_indexes(binary()) -> [non_neg_integer()]. @doc Return the 0 - based indexes in B that are not valid UTF-8 . invalid_utf8_indexes(B) -> invalid_utf8_indexes(B, 0, []). @private . -spec invalid_utf8_indexes(binary(), non_neg_integer(), [non_neg_integer()]) -> [non_neg_integer()]. invalid_utf8_indexes(<<C, Rest/binary>>, N, Acc) when C < 16#80 -> %% U+0000 - U+007F - 7 bits invalid_utf8_indexes(Rest, 1 + N, Acc); invalid_utf8_indexes(<<C1, C2, Rest/binary>>, N, Acc) when C1 band 16#E0 =:= 16#C0, C2 band 16#C0 =:= 16#80 -> U+0080 - U+07FF - 11 bits case ((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) of C when C < 16#80 -> Overlong encoding . invalid_utf8_indexes(Rest, 2 + N, [1 + N, N | Acc]); _ -> Upper bound U+07FF does not need to be checked invalid_utf8_indexes(Rest, 2 + N, Acc) end; invalid_utf8_indexes(<<C1, C2, C3, Rest/binary>>, N, Acc) when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> U+0800 - U+FFFF - 16 bits case ((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F) of C when (C < 16#800) orelse (C >= 16#D800 andalso C =< 16#DFFF) -> Overlong encoding or surrogate . invalid_utf8_indexes(Rest, 3 + N, [2 + N, 1 + N, N | Acc]); _ -> %% Upper bound U+FFFF does not need to be checked invalid_utf8_indexes(Rest, 3 + N, Acc) end; invalid_utf8_indexes(<<C1, C2, C3, C4, Rest/binary>>, N, Acc) when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80, C4 band 16#C0 =:= 16#80 -> %% U+10000 - U+10FFFF - 21 bits case ((((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F)) bsl 6) bor (C4 band 16#3F) of C when (C < 16#10000) orelse (C > 16#10FFFF) -> Overlong encoding or invalid code point . invalid_utf8_indexes(Rest, 4 + N, [3 + N, 2 + N, 1 + N, N | Acc]); _ -> invalid_utf8_indexes(Rest, 4 + N, Acc) end; invalid_utf8_indexes(<<_, Rest/binary>>, N, Acc) -> Invalid char invalid_utf8_indexes(Rest, 1 + N, [N | Acc]); invalid_utf8_indexes(<<>>, _N, Acc) -> lists:reverse(Acc). %% %% Tests %% -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). binary_skip_bytes_test() -> ?assertEqual(<<"foo">>, binary_skip_bytes(<<"foo">>, [])), ?assertEqual(<<"foobar">>, binary_skip_bytes(<<"foo bar">>, [3])), ?assertEqual(<<"foo">>, binary_skip_bytes(<<"foo bar">>, [3, 4, 5, 6])), ?assertEqual(<<"oo bar">>, binary_skip_bytes(<<"foo bar">>, [0])), ok. invalid_utf8_indexes_test() -> ?assertEqual( [], invalid_utf8_indexes(<<"unicode snowman for you: ", 226, 152, 131>>)), ?assertEqual( [0], invalid_utf8_indexes(<<128>>)), ?assertEqual( [57,59,60,64,66,67], invalid_utf8_indexes(<<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (", 167, 65, 170, 186, 73, 83, 80, 166, 87, 186, 217, 41, 41>>)), ok. codepoint_to_bytes_test() -> %% U+0000 - U+007F - 7 bits U+0080 - U+07FF - 11 bits U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) %% U+10000 - U+10FFFF - 21 bits ?assertEqual( <<"a">>, codepoint_to_bytes($a)), ?assertEqual( <<16#c2, 16#80>>, codepoint_to_bytes(16#80)), ?assertEqual( <<16#df, 16#bf>>, codepoint_to_bytes(16#07ff)), ?assertEqual( <<16#ef, 16#bf, 16#bf>>, codepoint_to_bytes(16#ffff)), ?assertEqual( <<16#f4, 16#8f, 16#bf, 16#bf>>, codepoint_to_bytes(16#10ffff)), ok. bytes_foldl_test() -> ?assertEqual( <<"abc">>, bytes_foldl(fun (B, Acc) -> <<Acc/binary, B/binary>> end, <<>>, <<"abc">>)), ?assertEqual( <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>, bytes_foldl(fun (B, Acc) -> <<Acc/binary, B/binary>> end, <<>>, <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. bytes_to_codepoints_test() -> ?assertEqual( "abc" ++ [16#2603, 16#4e2d, 16#85, 16#10ffff], bytes_to_codepoints(<<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. codepoint_foldl_test() -> ?assertEqual( "cba", codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], <<"abc">>)), ?assertEqual( [16#10ffff, 16#85, 16#4e2d, 16#2603 | "cba"], codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. len_test() -> ?assertEqual( 29, len(<<"unicode snowman for you: ", 226, 152, 131, 228, 184, 173, 194, 133, 244, 143, 191, 191>>)), ok. codepoints_to_bytes_test() -> ?assertEqual( iolist_to_binary(lists:map(fun codepoint_to_bytes/1, lists:seq(1, 1000))), codepoints_to_bytes(lists:seq(1, 1000))), ok. valid_utf8_bytes_test() -> ?assertEqual( <<"invalid U+11ffff: ">>, valid_utf8_bytes(<<"invalid U+11ffff: ", 244, 159, 191, 191>>)), ?assertEqual( <<"U+10ffff: ", 244, 143, 191, 191>>, valid_utf8_bytes(<<"U+10ffff: ", 244, 143, 191, 191>>)), ?assertEqual( <<"overlong 2-byte encoding (a): ">>, valid_utf8_bytes(<<"overlong 2-byte encoding (a): ", 2#11000001, 2#10100001>>)), ?assertEqual( <<"overlong 2-byte encoding (!): ">>, valid_utf8_bytes(<<"overlong 2-byte encoding (!): ", 2#11000000, 2#10100001>>)), ?assertEqual( <<"mu: ", 194, 181>>, valid_utf8_bytes(<<"mu: ", 194, 181>>)), ?assertEqual( <<"bad coding bytes: ">>, valid_utf8_bytes(<<"bad coding bytes: ", 2#10011111, 2#10111111, 2#11111111>>)), ?assertEqual( <<"low surrogate (unpaired): ">>, valid_utf8_bytes(<<"low surrogate (unpaired): ", 237, 176, 128>>)), ?assertEqual( <<"high surrogate (unpaired): ">>, valid_utf8_bytes(<<"high surrogate (unpaired): ", 237, 191, 191>>)), ?assertEqual( <<"unicode snowman for you: ", 226, 152, 131>>, valid_utf8_bytes(<<"unicode snowman for you: ", 226, 152, 131>>)), ?assertEqual( <<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (AISPW))">>, valid_utf8_bytes(<<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (", 167, 65, 170, 186, 73, 83, 80, 166, 87, 186, 217, 41, 41>>)), ok. -endif.
null
https://raw.githubusercontent.com/kenkeiras/EPC/1e903475e1e597fd602158df45c5805a764333bf/src/mochiutf8.erl
erlang
invalid bytes. External API U+0000 - U+007F - 7 bits U+10000 - U+10FFFF - 21 bits U+0000 - U+007F - 7 bits U+10000 - U+10FFFF - 21 bits or bad code point (surrogate U+D800 - U+DFFF or > U+10FFFF). Internal API U+0000 - U+007F - 7 bits Upper bound U+FFFF does not need to be checked U+10000 - U+10FFFF - 21 bits Tests U+0000 - U+007F - 7 bits U+10000 - U+10FFFF - 21 bits
@copyright 2010 Mochi Media , Inc. @author < > @doc Algorithm to convert any binary to a valid UTF-8 sequence by ignoring -module(mochiutf8). -export([valid_utf8_bytes/1, codepoint_to_bytes/1, codepoints_to_bytes/1]). -export([bytes_to_codepoints/1, bytes_foldl/3, codepoint_foldl/3]). -export([read_codepoint/1, len/1]). -type unichar_low() :: 0..16#d7ff. -type unichar_high() :: 16#e000..16#10ffff. -type unichar() :: unichar_low() | unichar_high(). -spec codepoint_to_bytes(unichar()) -> binary(). @doc Convert a unicode codepoint to UTF-8 bytes . codepoint_to_bytes(C) when (C >= 16#00 andalso C =< 16#7f) -> <<C>>; codepoint_to_bytes(C) when (C >= 16#080 andalso C =< 16#07FF) -> U+0080 - U+07FF - 11 bits <<0:5, B1:5, B0:6>> = <<C:16>>, <<2#110:3, B1:5, 2#10:2, B0:6>>; codepoint_to_bytes(C) when (C >= 16#0800 andalso C =< 16#FFFF) andalso (C < 16#D800 orelse C > 16#DFFF) -> U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) <<B2:4, B1:6, B0:6>> = <<C:16>>, <<2#1110:4, B2:4, 2#10:2, B1:6, 2#10:2, B0:6>>; codepoint_to_bytes(C) when (C >= 16#010000 andalso C =< 16#10FFFF) -> <<0:3, B3:3, B2:6, B1:6, B0:6>> = <<C:24>>, <<2#11110:5, B3:3, 2#10:2, B2:6, 2#10:2, B1:6, 2#10:2, B0:6>>. -spec codepoints_to_bytes([unichar()]) -> binary(). @doc Convert a list of codepoints to a UTF-8 binary . codepoints_to_bytes(L) -> <<<<(codepoint_to_bytes(C))/binary>> || C <- L>>. -spec read_codepoint(binary()) -> {unichar(), binary(), binary()}. read_codepoint(Bin = <<2#0:1, C:7, Rest/binary>>) -> <<B:1/binary, _/binary>> = Bin, {C, B, Rest}; read_codepoint(Bin = <<2#110:3, B1:5, 2#10:2, B0:6, Rest/binary>>) -> U+0080 - U+07FF - 11 bits case <<B1:5, B0:6>> of <<C:11>> when C >= 16#80 -> <<B:2/binary, _/binary>> = Bin, {C, B, Rest} end; read_codepoint(Bin = <<2#1110:4, B2:4, 2#10:2, B1:6, 2#10:2, B0:6, Rest/binary>>) -> U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) case <<B2:4, B1:6, B0:6>> of <<C:16>> when (C >= 16#0800 andalso C =< 16#FFFF) andalso (C < 16#D800 orelse C > 16#DFFF) -> <<B:3/binary, _/binary>> = Bin, {C, B, Rest} end; read_codepoint(Bin = <<2#11110:5, B3:3, 2#10:2, B2:6, 2#10:2, B1:6, 2#10:2, B0:6, Rest/binary>>) -> case <<B3:3, B2:6, B1:6, B0:6>> of <<C:21>> when (C >= 16#010000 andalso C =< 16#10FFFF) -> <<B:4/binary, _/binary>> = Bin, {C, B, Rest} end. -spec codepoint_foldl(fun((unichar(), _) -> _), _, binary()) -> _. codepoint_foldl(F, Acc, <<>>) when is_function(F, 2) -> Acc; codepoint_foldl(F, Acc, Bin) -> {C, _, Rest} = read_codepoint(Bin), codepoint_foldl(F, F(C, Acc), Rest). -spec bytes_foldl(fun((binary(), _) -> _), _, binary()) -> _. bytes_foldl(F, Acc, <<>>) when is_function(F, 2) -> Acc; bytes_foldl(F, Acc, Bin) -> {_, B, Rest} = read_codepoint(Bin), bytes_foldl(F, F(B, Acc), Rest). -spec bytes_to_codepoints(binary()) -> [unichar()]. bytes_to_codepoints(B) -> lists:reverse(codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], B)). -spec len(binary()) -> non_neg_integer(). len(<<>>) -> 0; len(B) -> {_, _, Rest} = read_codepoint(B), 1 + len(Rest). -spec valid_utf8_bytes(B::binary()) -> binary(). @doc Return only the bytes in B that represent valid UTF-8 . Uses the following recursive algorithm : skip one byte if B does not follow UTF-8 syntax ( a 1 - 4 byte encoding of some number ) , skip sequence of 2 - 4 bytes if it represents an overlong encoding valid_utf8_bytes(B) when is_binary(B) -> binary_skip_bytes(B, invalid_utf8_indexes(B)). -spec binary_skip_bytes(binary(), [non_neg_integer()]) -> binary(). @doc Return B , but skipping the 0 - based indexes in L. binary_skip_bytes(B, []) -> B; binary_skip_bytes(B, L) -> binary_skip_bytes(B, L, 0, []). @private -spec binary_skip_bytes(binary(), [non_neg_integer()], non_neg_integer(), iolist()) -> binary(). binary_skip_bytes(B, [], _N, Acc) -> iolist_to_binary(lists:reverse([B | Acc])); binary_skip_bytes(<<_, RestB/binary>>, [N | RestL], N, Acc) -> binary_skip_bytes(RestB, RestL, 1 + N, Acc); binary_skip_bytes(<<C, RestB/binary>>, L, N, Acc) -> binary_skip_bytes(RestB, L, 1 + N, [C | Acc]). -spec invalid_utf8_indexes(binary()) -> [non_neg_integer()]. @doc Return the 0 - based indexes in B that are not valid UTF-8 . invalid_utf8_indexes(B) -> invalid_utf8_indexes(B, 0, []). @private . -spec invalid_utf8_indexes(binary(), non_neg_integer(), [non_neg_integer()]) -> [non_neg_integer()]. invalid_utf8_indexes(<<C, Rest/binary>>, N, Acc) when C < 16#80 -> invalid_utf8_indexes(Rest, 1 + N, Acc); invalid_utf8_indexes(<<C1, C2, Rest/binary>>, N, Acc) when C1 band 16#E0 =:= 16#C0, C2 band 16#C0 =:= 16#80 -> U+0080 - U+07FF - 11 bits case ((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) of C when C < 16#80 -> Overlong encoding . invalid_utf8_indexes(Rest, 2 + N, [1 + N, N | Acc]); _ -> Upper bound U+07FF does not need to be checked invalid_utf8_indexes(Rest, 2 + N, Acc) end; invalid_utf8_indexes(<<C1, C2, C3, Rest/binary>>, N, Acc) when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> U+0800 - U+FFFF - 16 bits case ((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F) of C when (C < 16#800) orelse (C >= 16#D800 andalso C =< 16#DFFF) -> Overlong encoding or surrogate . invalid_utf8_indexes(Rest, 3 + N, [2 + N, 1 + N, N | Acc]); _ -> invalid_utf8_indexes(Rest, 3 + N, Acc) end; invalid_utf8_indexes(<<C1, C2, C3, C4, Rest/binary>>, N, Acc) when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80, C4 band 16#C0 =:= 16#80 -> case ((((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F)) bsl 6) bor (C4 band 16#3F) of C when (C < 16#10000) orelse (C > 16#10FFFF) -> Overlong encoding or invalid code point . invalid_utf8_indexes(Rest, 4 + N, [3 + N, 2 + N, 1 + N, N | Acc]); _ -> invalid_utf8_indexes(Rest, 4 + N, Acc) end; invalid_utf8_indexes(<<_, Rest/binary>>, N, Acc) -> Invalid char invalid_utf8_indexes(Rest, 1 + N, [N | Acc]); invalid_utf8_indexes(<<>>, _N, Acc) -> lists:reverse(Acc). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). binary_skip_bytes_test() -> ?assertEqual(<<"foo">>, binary_skip_bytes(<<"foo">>, [])), ?assertEqual(<<"foobar">>, binary_skip_bytes(<<"foo bar">>, [3])), ?assertEqual(<<"foo">>, binary_skip_bytes(<<"foo bar">>, [3, 4, 5, 6])), ?assertEqual(<<"oo bar">>, binary_skip_bytes(<<"foo bar">>, [0])), ok. invalid_utf8_indexes_test() -> ?assertEqual( [], invalid_utf8_indexes(<<"unicode snowman for you: ", 226, 152, 131>>)), ?assertEqual( [0], invalid_utf8_indexes(<<128>>)), ?assertEqual( [57,59,60,64,66,67], invalid_utf8_indexes(<<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (", 167, 65, 170, 186, 73, 83, 80, 166, 87, 186, 217, 41, 41>>)), ok. codepoint_to_bytes_test() -> U+0080 - U+07FF - 11 bits U+0800 - U+FFFF - 16 bits ( excluding surrogate code points ) ?assertEqual( <<"a">>, codepoint_to_bytes($a)), ?assertEqual( <<16#c2, 16#80>>, codepoint_to_bytes(16#80)), ?assertEqual( <<16#df, 16#bf>>, codepoint_to_bytes(16#07ff)), ?assertEqual( <<16#ef, 16#bf, 16#bf>>, codepoint_to_bytes(16#ffff)), ?assertEqual( <<16#f4, 16#8f, 16#bf, 16#bf>>, codepoint_to_bytes(16#10ffff)), ok. bytes_foldl_test() -> ?assertEqual( <<"abc">>, bytes_foldl(fun (B, Acc) -> <<Acc/binary, B/binary>> end, <<>>, <<"abc">>)), ?assertEqual( <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>, bytes_foldl(fun (B, Acc) -> <<Acc/binary, B/binary>> end, <<>>, <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. bytes_to_codepoints_test() -> ?assertEqual( "abc" ++ [16#2603, 16#4e2d, 16#85, 16#10ffff], bytes_to_codepoints(<<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. codepoint_foldl_test() -> ?assertEqual( "cba", codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], <<"abc">>)), ?assertEqual( [16#10ffff, 16#85, 16#4e2d, 16#2603 | "cba"], codepoint_foldl(fun (C, Acc) -> [C | Acc] end, [], <<"abc", 226, 152, 131, 228, 184, 173, 194, 133, 244,143,191,191>>)), ok. len_test() -> ?assertEqual( 29, len(<<"unicode snowman for you: ", 226, 152, 131, 228, 184, 173, 194, 133, 244, 143, 191, 191>>)), ok. codepoints_to_bytes_test() -> ?assertEqual( iolist_to_binary(lists:map(fun codepoint_to_bytes/1, lists:seq(1, 1000))), codepoints_to_bytes(lists:seq(1, 1000))), ok. valid_utf8_bytes_test() -> ?assertEqual( <<"invalid U+11ffff: ">>, valid_utf8_bytes(<<"invalid U+11ffff: ", 244, 159, 191, 191>>)), ?assertEqual( <<"U+10ffff: ", 244, 143, 191, 191>>, valid_utf8_bytes(<<"U+10ffff: ", 244, 143, 191, 191>>)), ?assertEqual( <<"overlong 2-byte encoding (a): ">>, valid_utf8_bytes(<<"overlong 2-byte encoding (a): ", 2#11000001, 2#10100001>>)), ?assertEqual( <<"overlong 2-byte encoding (!): ">>, valid_utf8_bytes(<<"overlong 2-byte encoding (!): ", 2#11000000, 2#10100001>>)), ?assertEqual( <<"mu: ", 194, 181>>, valid_utf8_bytes(<<"mu: ", 194, 181>>)), ?assertEqual( <<"bad coding bytes: ">>, valid_utf8_bytes(<<"bad coding bytes: ", 2#10011111, 2#10111111, 2#11111111>>)), ?assertEqual( <<"low surrogate (unpaired): ">>, valid_utf8_bytes(<<"low surrogate (unpaired): ", 237, 176, 128>>)), ?assertEqual( <<"high surrogate (unpaired): ">>, valid_utf8_bytes(<<"high surrogate (unpaired): ", 237, 191, 191>>)), ?assertEqual( <<"unicode snowman for you: ", 226, 152, 131>>, valid_utf8_bytes(<<"unicode snowman for you: ", 226, 152, 131>>)), ?assertEqual( <<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (AISPW))">>, valid_utf8_bytes(<<"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; (", 167, 65, 170, 186, 73, 83, 80, 166, 87, 186, 217, 41, 41>>)), ok. -endif.
61db0c7673561a060dfee814a23a20d2e445f53a794e2706340e1f8832ee3b39
ajhc/ajhc
ReaderWriter.hs
# LANGUAGE UnboxedTuples # module Util.ReaderWriter(ReaderWriter(),runReaderWriter) where import Data.Monoid import Control.Monad.Reader import Control.Monad.Writer -- strict unboxed ReaderWriter monad newtype ReaderWriter r w a = ReaderWriter { _runReaderWriter :: r -> (# a, w #) } runReaderWriter :: ReaderWriter r w a -> r -> (a,w) runReaderWriter (ReaderWriter m) r = case m r of (# a, w #) -> (a,w) instance Functor (ReaderWriter r w) where fmap f (ReaderWriter g) = ReaderWriter $ \r -> case g r of (# a, w #) -> (# f a, w #) instance (Monoid w) => Monad (ReaderWriter r w) where return a = ReaderWriter $ \_ -> (# a, mempty #) (ReaderWriter m) >>= k = ReaderWriter $ \r -> case m r of (# a,w #) -> case k a of ReaderWriter g -> case g r of (# b, w' #) -> let w'' = w `mappend` w' in w'' `seq` (# b, w'' #) (ReaderWriter f) >> (ReaderWriter g) = ReaderWriter $ \r -> case f r of (# _, w #) -> case g r of (# a, w' #) -> let w'' = w `mappend` w' in w'' `seq` (# a, w'' #) instance (Monoid w) => MonadWriter w (ReaderWriter r w) where tell w = ReaderWriter $ \ _ -> w `seq` (# (), w #) listen (ReaderWriter m) = ReaderWriter $ \r -> case m r of (# a , w #) -> (# (a,w), w #) pass (ReaderWriter m) = ReaderWriter $ \r -> case m r of (# (a, f), w #) -> let w' = f w in w' `seq` (# a, w' #) instance Monoid w => MonadReader r (ReaderWriter r w) where ask = ReaderWriter $ \r -> (# r, mempty #) local f (ReaderWriter m) = ReaderWriter $ \r -> m (f r)
null
https://raw.githubusercontent.com/ajhc/ajhc/8ef784a6a3b5998cfcd95d0142d627da9576f264/src/Util/ReaderWriter.hs
haskell
strict unboxed ReaderWriter monad
# LANGUAGE UnboxedTuples # module Util.ReaderWriter(ReaderWriter(),runReaderWriter) where import Data.Monoid import Control.Monad.Reader import Control.Monad.Writer newtype ReaderWriter r w a = ReaderWriter { _runReaderWriter :: r -> (# a, w #) } runReaderWriter :: ReaderWriter r w a -> r -> (a,w) runReaderWriter (ReaderWriter m) r = case m r of (# a, w #) -> (a,w) instance Functor (ReaderWriter r w) where fmap f (ReaderWriter g) = ReaderWriter $ \r -> case g r of (# a, w #) -> (# f a, w #) instance (Monoid w) => Monad (ReaderWriter r w) where return a = ReaderWriter $ \_ -> (# a, mempty #) (ReaderWriter m) >>= k = ReaderWriter $ \r -> case m r of (# a,w #) -> case k a of ReaderWriter g -> case g r of (# b, w' #) -> let w'' = w `mappend` w' in w'' `seq` (# b, w'' #) (ReaderWriter f) >> (ReaderWriter g) = ReaderWriter $ \r -> case f r of (# _, w #) -> case g r of (# a, w' #) -> let w'' = w `mappend` w' in w'' `seq` (# a, w'' #) instance (Monoid w) => MonadWriter w (ReaderWriter r w) where tell w = ReaderWriter $ \ _ -> w `seq` (# (), w #) listen (ReaderWriter m) = ReaderWriter $ \r -> case m r of (# a , w #) -> (# (a,w), w #) pass (ReaderWriter m) = ReaderWriter $ \r -> case m r of (# (a, f), w #) -> let w' = f w in w' `seq` (# a, w' #) instance Monoid w => MonadReader r (ReaderWriter r w) where ask = ReaderWriter $ \r -> (# r, mempty #) local f (ReaderWriter m) = ReaderWriter $ \r -> m (f r)
51aba9fbd3d48f901321ac2a5ba990df1dcbd4d9c9c1a3896dc82f5245a261fe
artyom-poptsov/guile-deck
device.scm
;;; device.scm -- A description of <device> class. Copyright ( C ) 2021 < > ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; The 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 the program. If not, see </>. ;;; Commentary: ;; This module contains description of the <device> and the related methods. ;;; Code: (define-module (deck core types device) #:use-module (scheme documentation) #:use-module (oop goops) #:use-module (deck core common error) #:export (<device> device? device-id device-display-name device-last-seen-ip device-last-seen-timestamp alist->device)) (define-class-with-docs <device> () "Device information. Description: <-server/#!/Device32management/getDevices>" ;; REQUIRED. Identifier of this device. ;; ;; <string> (device-id #:init-value #f #:init-keyword #:id #:getter device-id) ;; Display name set by the user for this device. Absent if no name has been ;; set. ;; ;; <string> (display-name #:init-value #f #:init-keyword #:display-name #:getter device-display-name) The IP address where this device was last seen . ( May be a few minutes out ;; of date, for efficiency reasons). ;; ;; <string> (last-seen-ip #:init-value #f #:init-keyword #:last-seen-ip #:getter device-last-seen-ip) ;; The timestamp (in milliseconds since the unix epoch) when this devices was last seen . ( May be a few minutes out of date , for efficiency ;; reasons). ;; ;; <number> (last-seen-timestamp #:init-value #f #:init-keyword #:last-seen-timestamp #:getter device-last-seen-timestamp)) (define-method (display (device <device>) (port <port>)) (format port "#<device ~a ~a>" (device-id device) (number->string (object-address device) 16))) (define-method (write (device <device>) (port <port>)) (display device port)) (define-method (display (device <device>)) (next-method) (display device (current-output-port))) (define-method (write (device <device>)) (next-method) (display device (current-output-port))) (define-method (initialize (device <device>) initargs) (next-method) (let ((device-id (and (memq #:id initargs) (cadr (memq #:id initargs))))) (unless device-id (deck-error "No device ID provided")))) (define (device? object) "Check if an OBJECT is a <device> instance." (is-a? object <device>)) (define-method (equal? (d1 <device>) (d2 <device>)) "Check if a device D1 is equal to a device D2." (and (equal? (device-id d1) (device-id d2)) (equal? (device-display-name d1) (device-display-name d2)) (equal? (device-last-seen-ip d1) (device-last-seen-ip d2)) (equal? (device-last-seen-timestamp d1) (device-last-seen-timestamp d2)))) (define-method (alist->device (alist <list>)) "Convert an alist to a <device> instance." (make <device> #:id (assoc-ref alist "device_id") #:display-name (assoc-ref alist "display_name") #:last-seen-ip (assoc-ref alist "last_seen_ip") #:last-seen-timestamp (assoc-ref alist "last_seen_ts"))) ;;; device.scm ends here.
null
https://raw.githubusercontent.com/artyom-poptsov/guile-deck/608fbc6aa38bcd2091b32af2bb2f6ad05037190c/modules/deck/core/types/device.scm
scheme
device.scm -- A description of <device> class. This program is free software: you can redistribute it and/or modify (at your option) any later version. The 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. along with the program. If not, see </>. Commentary: This module contains description of the <device> and the related methods. Code: REQUIRED. Identifier of this device. <string> Display name set by the user for this device. Absent if no name has been set. <string> of date, for efficiency reasons). <string> The timestamp (in milliseconds since the unix epoch) when this devices reasons). <number> device.scm ends here.
Copyright ( C ) 2021 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (define-module (deck core types device) #:use-module (scheme documentation) #:use-module (oop goops) #:use-module (deck core common error) #:export (<device> device? device-id device-display-name device-last-seen-ip device-last-seen-timestamp alist->device)) (define-class-with-docs <device> () "Device information. Description: <-server/#!/Device32management/getDevices>" (device-id #:init-value #f #:init-keyword #:id #:getter device-id) (display-name #:init-value #f #:init-keyword #:display-name #:getter device-display-name) The IP address where this device was last seen . ( May be a few minutes out (last-seen-ip #:init-value #f #:init-keyword #:last-seen-ip #:getter device-last-seen-ip) was last seen . ( May be a few minutes out of date , for efficiency (last-seen-timestamp #:init-value #f #:init-keyword #:last-seen-timestamp #:getter device-last-seen-timestamp)) (define-method (display (device <device>) (port <port>)) (format port "#<device ~a ~a>" (device-id device) (number->string (object-address device) 16))) (define-method (write (device <device>) (port <port>)) (display device port)) (define-method (display (device <device>)) (next-method) (display device (current-output-port))) (define-method (write (device <device>)) (next-method) (display device (current-output-port))) (define-method (initialize (device <device>) initargs) (next-method) (let ((device-id (and (memq #:id initargs) (cadr (memq #:id initargs))))) (unless device-id (deck-error "No device ID provided")))) (define (device? object) "Check if an OBJECT is a <device> instance." (is-a? object <device>)) (define-method (equal? (d1 <device>) (d2 <device>)) "Check if a device D1 is equal to a device D2." (and (equal? (device-id d1) (device-id d2)) (equal? (device-display-name d1) (device-display-name d2)) (equal? (device-last-seen-ip d1) (device-last-seen-ip d2)) (equal? (device-last-seen-timestamp d1) (device-last-seen-timestamp d2)))) (define-method (alist->device (alist <list>)) "Convert an alist to a <device> instance." (make <device> #:id (assoc-ref alist "device_id") #:display-name (assoc-ref alist "display_name") #:last-seen-ip (assoc-ref alist "last_seen_ip") #:last-seen-timestamp (assoc-ref alist "last_seen_ts")))
7dc081d786102eb1d4911d3aaf74d8823e9f826ad4d43124052c11e509b79293
freizl/dive-into-haskell
query-cis.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import System.Time import System.Locale import qualified Data.Text.IO as T import Test.WebDriver import Test.WebDriver.Commands.Wait import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Lazy as BS url = "" defConfig = defaultConfig { wdCapabilities = allCaps } page :: WD () page = do openPage url receipt <- findElem (ById "receipt") sendKeys "WAC1414452942" receipt submit receipt waitUntil 10000 $ do title <- findElem (ByCSS "#caseStatus > h3") >>= getText current <- findElem (ByCSS "#caseStatus .controls h4") >>= getText ss <- screenshot liftIO $ do now <- fmap (formatCalendarTime defaultTimeLocale "%Y-%m-%d") (getClockTime >>= toCalendarTime ) print title >> T.putStrLn current BS.writeFile ("screenshot_" ++ now ++ ".png") ss main :: IO () main = run page run :: WD () -> IO () run = runSession defConfig . finallyClose
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/functional-test/query-cis.hs
haskell
# LANGUAGE OverloadedStrings #
module Main where import System.Time import System.Locale import qualified Data.Text.IO as T import Test.WebDriver import Test.WebDriver.Commands.Wait import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Lazy as BS url = "" defConfig = defaultConfig { wdCapabilities = allCaps } page :: WD () page = do openPage url receipt <- findElem (ById "receipt") sendKeys "WAC1414452942" receipt submit receipt waitUntil 10000 $ do title <- findElem (ByCSS "#caseStatus > h3") >>= getText current <- findElem (ByCSS "#caseStatus .controls h4") >>= getText ss <- screenshot liftIO $ do now <- fmap (formatCalendarTime defaultTimeLocale "%Y-%m-%d") (getClockTime >>= toCalendarTime ) print title >> T.putStrLn current BS.writeFile ("screenshot_" ++ now ++ ".png") ss main :: IO () main = run page run :: WD () -> IO () run = runSession defConfig . finallyClose
73a9e328fbd85b7e960105a37caf2c292fcb9d78ad44e0c4fed5ba32a2c8b1e1
ucsd-progsys/nate
typeclass.ml
(***********************************************************************) (* *) (* 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 . (* *) (***********************************************************************) (* $Id: typeclass.ml,v 1.89.6.3 2008/01/28 13:26:48 doligez Exp $ *) open Misc open Parsetree open Asttypes open Path open Types open Typedtree open Typecore open Typetexp open Format type error = Unconsistent_constraint of (type_expr * type_expr) list | Field_type_mismatch of string * string * (type_expr * type_expr) list | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class of Longident.t | Unbound_class_2 of Longident.t | Unbound_class_type of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * (type_expr * type_expr) list | Virtual_class of bool * string list * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of (type_expr * type_expr) list | Bad_parameters of Ident.t * type_expr * type_expr | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure | Make_nongen_seltype of type_expr | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * (type_expr * type_expr) list | Final_self_clash of (type_expr * type_expr) list | Mutability_mismatch of string * mutable_flag exception Error of Location.t * error (**********************) (* Useful constants *) (**********************) (* Self type have a dummy private method, thus preventing it to become closed. *) let dummy_method = Ctype.dummy_method (* Path associated to the temporary class type of a class being typed (its constructor is not available). *) let unbound_class = Path.Pident (Ident.create "") (************************************) (* Some operations on class types *) (************************************) (* Fully expand the head of a class type *) let rec scrape_class_type = function Tcty_constr (_, _, cty) -> scrape_class_type cty | cty -> cty a class type let rec generalize_class_type = function Tcty_constr (_, params, cty) -> List.iter Ctype.generalize params; generalize_class_type cty | Tcty_signature {cty_self = sty; cty_vars = vars; cty_inher = inher} -> Ctype.generalize sty; Vars.iter (fun _ (_, _, ty) -> Ctype.generalize ty) vars; List.iter (fun (_,tl) -> List.iter Ctype.generalize tl) inher | Tcty_fun (_, ty, cty) -> Ctype.generalize ty; generalize_class_type cty (* Return the virtual methods of a class type *) let virtual_methods sign = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun virt (lab, _, _) -> if lab = dummy_method then virt else if Concr.mem lab sign.cty_concr then virt else lab::virt) [] fields (* Return the constructor type associated to a class type *) let rec constructor_type constr cty = match cty with Tcty_constr (_, _, cty) -> constructor_type constr cty | Tcty_signature sign -> constr | Tcty_fun (l, ty, cty) -> Ctype.newty (Tarrow (l, ty, constructor_type constr cty, Cok)) let rec class_body cty = match cty with Tcty_constr (_, _, cty') -> cty (* Only class bodies can be abbreviated *) | Tcty_signature sign -> cty | Tcty_fun (_, ty, cty) -> class_body cty let rec extract_constraints cty = let sign = Ctype.signature_of_class_type cty in (Vars.fold (fun lab _ vars -> lab :: vars) sign.cty_vars [], begin let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun meths (lab, _, _) -> if lab = dummy_method then meths else lab::meths) [] fields end, sign.cty_concr) let rec abbreviate_class_type path params cty = match cty with Tcty_constr (_, _, _) | Tcty_signature _ -> Tcty_constr (path, params, cty) | Tcty_fun (l, ty, cty) -> Tcty_fun (l, ty, abbreviate_class_type path params cty) let rec closed_class_type = function Tcty_constr (_, params, _) -> List.for_all Ctype.closed_schema params | Tcty_signature sign -> Ctype.closed_schema sign.cty_self && Vars.fold (fun _ (_, _, ty) cc -> Ctype.closed_schema ty && cc) sign.cty_vars true | Tcty_fun (_, ty, cty) -> Ctype.closed_schema ty && closed_class_type cty let closed_class cty = List.for_all Ctype.closed_schema cty.cty_params && closed_class_type cty.cty_type let rec limited_generalize rv = function Tcty_constr (path, params, cty) -> List.iter (Ctype.limited_generalize rv) params; limited_generalize rv cty | Tcty_signature sign -> Ctype.limited_generalize rv sign.cty_self; Vars.iter (fun _ (_, _, ty) -> Ctype.limited_generalize rv ty) sign.cty_vars; List.iter (fun (_, tl) -> List.iter (Ctype.limited_generalize rv) tl) sign.cty_inher | Tcty_fun (_, ty, cty) -> Ctype.limited_generalize rv ty; limited_generalize rv cty (* Record a class type *) let rc node = Stypes.record (Stypes.Ti_class node); node (***********************************) (* Primitives for typing classes *) (***********************************) (* Enter a value in the method environment only *) let enter_met_env lab kind ty val_env met_env par_env = let (id, val_env) = Env.enter_value lab {val_type = ty; val_kind = Val_unbound} val_env in (id, val_env, Env.add_value id {val_type = ty; val_kind = kind} met_env, Env.add_value id {val_type = ty; val_kind = Val_unbound} par_env) (* Enter an instance variable in the environment *) let enter_val cl_num vars inh lab mut virt ty val_env met_env par_env loc = let (id, virt) = try let (id, mut', virt', ty') = Vars.find lab !vars in if mut' <> mut then raise (Error(loc, Mutability_mismatch(lab, mut))); Ctype.unify val_env (Ctype.instance ty) (Ctype.instance ty'); (if not inh then Some id else None), (if virt' = Concrete then virt' else virt) with Ctype.Unify tr -> raise (Error(loc, Field_type_mismatch("instance variable", lab, tr))) | Not_found -> None, virt in let (id, _, _, _) as result = match id with Some id -> (id, val_env, met_env, par_env) | None -> enter_met_env lab (Val_ivar (mut, cl_num)) ty val_env met_env par_env in vars := Vars.add lab (id, mut, virt, ty) !vars; result let inheritance self_type env concr_meths warn_meths loc parent = match scrape_class_type parent with Tcty_signature cl_sig -> (* Methods *) begin try Ctype.unify env self_type cl_sig.cty_self with Ctype.Unify trace -> match trace with _::_::_::({desc = Tfield(n, _, _, _)}, _)::rem -> raise(Error(loc, Field_type_mismatch ("method", n, rem))) | _ -> assert false end; let overridings = Concr.inter cl_sig.cty_concr warn_meths in if not (Concr.is_empty overridings) then begin let cname = match parent with Tcty_constr (p, _, _) -> Path.name p | _ -> "inherited" in Location.prerr_warning loc (Warnings.Method_override (cname :: Concr.elements overridings)) end; let concr_meths = Concr.union cl_sig.cty_concr concr_meths in (* No need to warn about overriding of inherited methods! *) let warn_meths = Concr.union cl_sig.cty_concr warn_meths in (cl_sig, concr_meths, warn_meths) | _ -> raise(Error(loc, Structure_expected parent)) let virtual_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let ty = transl_simple_type val_env false sty in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) let delayed_meth_specs = ref [] let declare_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let unif ty = try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) in match sty.ptyp_desc, priv with Ptyp_poly ([],sty), Public -> delayed_meth_specs := lazy (unif (transl_simple_type_univars val_env sty)) :: !delayed_meth_specs | _ -> unif (transl_simple_type val_env false sty) let type_constraint val_env sty sty' loc = let ty = transl_simple_type val_env false sty in let ty' = transl_simple_type val_env false sty' in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Unconsistent_constraint trace)) let mkpat d = { ppat_desc = d; ppat_loc = Location.none } let make_method cl_num expr = { pexp_desc = Pexp_function ("", None, [mkpat (Ppat_alias (mkpat(Ppat_var "self-*"), "self-" ^ cl_num)), expr]); pexp_loc = expr.pexp_loc } (*******************************) let add_val env loc lab (mut, virt, ty) val_sig = let virt = try let (mut', virt', ty') = Vars.find lab val_sig in if virt' = Concrete then virt' else virt with Not_found -> virt in Vars.add lab (mut, virt, ty) val_sig let rec class_type_field env self_type meths (val_sig, concr_meths, inher) = function Pctf_inher sparent -> let parent = class_type env sparent in let inher = match parent with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, _) = inheritance self_type env concr_meths Concr.empty sparent.pcty_loc parent in let val_sig = Vars.fold (add_val env sparent.pcty_loc) cl_sig.cty_vars val_sig in (val_sig, concr_meths, inher) | Pctf_val (lab, mut, virt, sty, loc) -> let ty = transl_simple_type env false sty in (add_val env loc lab (mut, virt, ty) val_sig, concr_meths, inher) | Pctf_virt (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, concr_meths, inher) | Pctf_meth (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, Concr.add lab concr_meths, inher) | Pctf_cstr (sty, sty', loc) -> type_constraint env sty sty' loc; (val_sig, concr_meths, inher) and class_signature env sty sign = let meths = ref Meths.empty in let self_type = transl_simple_type env false sty in (* Check that the binder is a correct type, and introduce a dummy method preventing self type from being closed. *) let dummy_obj = Ctype.newvar () in Ctype.unify env (Ctype.filter_method env dummy_method Private dummy_obj) (Ctype.newty (Ttuple [])); begin try Ctype.unify env self_type dummy_obj with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, Pattern_type_clash self_type)) end; (* Class type fields *) let (val_sig, concr_meths, inher) = List.fold_left (class_type_field env self_type meths) (Vars.empty, Concr.empty, []) sign in {cty_self = self_type; cty_vars = val_sig; cty_concr = concr_meths; cty_inher = inher} and class_type env scty = match scty.pcty_desc with Pcty_constr (lid, styl) -> let (path, decl) = try Env.lookup_cltype lid env with Not_found -> raise(Error(scty.pcty_loc, Unbound_class_type lid)) in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, Unbound_class_type_2 lid)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in if List.length params <> List.length styl then raise(Error(scty.pcty_loc, Parameter_arity_mismatch (lid, List.length params, List.length styl))); List.iter2 (fun sty ty -> let ty' = transl_simple_type env false sty in try Ctype.unify env ty' ty with Ctype.Unify trace -> raise(Error(sty.ptyp_loc, Parameter_mismatch trace))) styl params; Tcty_constr (path, params, clty) | Pcty_signature (sty, sign) -> Tcty_signature (class_signature env sty sign) | Pcty_fun (l, sty, scty) -> let ty = transl_simple_type env false sty in let cty = class_type env scty in Tcty_fun (l, ty, cty) let class_type env scty = delayed_meth_specs := []; let cty = class_type env scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty (*******************************) module StringSet = Set.Make(struct type t = string let compare = compare end) let rec class_field cl_num self_type meths vars (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) = function Pcf_inher (sparent, super) -> let parent = class_expr cl_num val_env par_env sparent in let inher = match parent.cl_type with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, warn_meths) = inheritance self_type val_env concr_meths warn_meths sparent.pcl_loc parent.cl_type in (* Variables *) let (val_env, met_env, par_env, inh_vars, warn_vals) = Vars.fold (fun lab info (val_env, met_env, par_env, inh_vars, warn_vals) -> let mut, vr, ty = info in let (id, val_env, met_env, par_env) = enter_val cl_num vars true lab mut vr ty val_env met_env par_env sparent.pcl_loc in let warn_vals = if vr = Virtual then warn_vals else if StringSet.mem lab warn_vals then (Location.prerr_warning sparent.pcl_loc (Warnings.Instance_variable_override lab); warn_vals) else StringSet.add lab warn_vals in (val_env, met_env, par_env, (lab, id) :: inh_vars, warn_vals)) cl_sig.cty_vars (val_env, met_env, par_env, [], warn_vals) in (* Inherited concrete methods *) let inh_meths = Concr.fold (fun lab rem -> (lab, Ident.create lab)::rem) cl_sig.cty_concr [] in Super let (val_env, met_env, par_env) = match super with None -> (val_env, met_env, par_env) | Some name -> let (id, val_env, met_env, par_env) = enter_met_env name (Val_anc (inh_meths, cl_num)) self_type val_env met_env par_env in (val_env, met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_inher (parent, inh_vars, inh_meths))::fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_valvirt (lab, mut, styp, loc) -> if !Clflags.principal then Ctype.begin_def (); let ty = Typetexp.transl_simple_type val_env false styp in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure ty end; let (id, val_env, met_env', par_env) = enter_val cl_num vars false lab mut Virtual ty val_env met_env par_env loc in (val_env, met_env', par_env, lazy(Cf_val (lab, id, None, met_env' == met_env)) :: fields, concr_meths, warn_meths, StringSet.remove lab warn_vals, inher) | Pcf_val (lab, mut, sexp, loc) -> if StringSet.mem lab warn_vals then Location.prerr_warning loc (Warnings.Instance_variable_override lab); if !Clflags.principal then Ctype.begin_def (); let exp = try type_exp val_env sexp with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure exp.exp_type end; let (id, val_env, met_env', par_env) = enter_val cl_num vars false lab mut Concrete exp.exp_type val_env met_env par_env loc in (val_env, met_env', par_env, lazy(Cf_val (lab, id, Some exp, met_env' == met_env)) :: fields, concr_meths, warn_meths, StringSet.add lab warn_vals, inher) | Pcf_virt (lab, priv, sty, loc) -> virtual_method val_env meths self_type lab priv sty loc; let warn_meths = Concr.remove lab warn_meths in (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_meth (lab, priv, expr, loc) -> if Concr.mem lab warn_meths then Location.prerr_warning loc (Warnings.Method_override [lab]); let (_, ty) = Ctype.filter_self_method val_env lab priv meths self_type in begin try match expr.pexp_desc with Pexp_poly (sbody, sty) -> begin match sty with None -> () | Some sty -> Ctype.unify val_env (Typetexp.transl_simple_type val_env false sty) ty end; begin match (Ctype.repr ty).desc with Tvar -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty; Ctype.unify val_env (type_approx val_env sbody) ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype.unify val_env ty2 ty1' | _ -> assert false end | _ -> assert false with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) end; let meth_expr = make_method cl_num expr in (* backup variables for Pexp_override *) let vars_local = !vars in let field = lazy begin let meth_type = Ctype.newty (Tarrow("", self_type, Ctype.instance ty, Cok)) in Ctype.raise_nongen_level (); vars := vars_local; let texp = type_expect met_env meth_expr meth_type in Ctype.end_def (); Cf_meth (lab, texp) end in (val_env, met_env, par_env, field::fields, Concr.add lab concr_meths, Concr.add lab warn_meths, warn_vals, inher) | Pcf_cstr (sty, sty', loc) -> type_constraint val_env sty sty' loc; (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_let (rec_flag, sdefs, loc) -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in let (vals, met_env, par_env) = List.fold_right (fun id (vals, met_env, par_env) -> let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env, Env.add_value id' desc par_env)) (let_bound_idents defs) ([], met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_let(rec_flag, defs, vals))::fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_init expr -> let expr = make_method cl_num expr in let vars_local = !vars in let field = lazy begin Ctype.raise_nongen_level (); let meth_type = Ctype.newty (Tarrow ("", self_type, Ctype.instance Predef.type_unit, Cok)) in vars := vars_local; let texp = type_expect met_env expr meth_type in Ctype.end_def (); Cf_init texp end in (val_env, met_env, par_env, field::fields, concr_meths, warn_meths, warn_vals, inher) and class_structure cl_num final val_env met_env loc (spat, str) = (* Environment for substructures *) let par_env = met_env in (* Self type, with a dummy method preventing it from being closed/escaped. *) let self_type = Ctype.newvar () in Ctype.unify val_env (Ctype.filter_method val_env dummy_method Private self_type) (Ctype.newty (Ttuple [])); (* Private self is used for private method calls *) let private_self = if final then Ctype.newvar () else self_type in (* Self binder *) let (pat, meths, vars, val_env, meth_env, par_env) = type_self_pattern cl_num private_self val_env met_env par_env spat in let public_self = pat.pat_type in (* Check that the binder has a correct type *) let ty = if final then Ctype.newty (Tobject (Ctype.newvar(), ref None)) else self_type in begin try Ctype.unify val_env public_self ty with Ctype.Unify _ -> raise(Error(spat.ppat_loc, Pattern_type_clash public_self)) end; let get_methods ty = (fst (Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head val_env ty)))) in if final then begin (* Copy known information to still empty self_type *) List.iter (fun (lab,kind,ty) -> let k = if Btype.field_kind_repr kind = Fpresent then Public else Private in try Ctype.unify val_env ty (Ctype.filter_method val_env lab k self_type) with _ -> assert false) (get_methods public_self) end; (* Typing of class fields *) let (_, _, _, fields, concr_meths, _, _, inher) = List.fold_left (class_field cl_num self_type meths vars) (val_env, meth_env, par_env, [], Concr.empty, Concr.empty, StringSet.empty, []) str in Ctype.unify val_env self_type (Ctype.newvar ()); let sign = {cty_self = public_self; cty_vars = Vars.map (fun (id, mut, vr, ty) -> (mut, vr, ty)) !vars; cty_concr = concr_meths; cty_inher = inher} in let methods = get_methods self_type in let priv_meths = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind <> Fpresent) methods in if final then begin Unify private_self and a copy of self_type . self_type will not be modified after this point be modified after this point *) Ctype.close_object self_type; let mets = virtual_methods {sign with cty_self = self_type} in let vals = Vars.fold (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l) sign.cty_vars [] in if mets <> [] || vals <> [] then raise(Error(loc, Virtual_class(true, mets, vals))); let self_methods = List.fold_right (fun (lab,kind,ty) rem -> if lab = dummy_method then (* allow public self and private self to be unified *) match Btype.field_kind_repr kind with Fvar r -> Btype.set_kind r Fabsent; rem | _ -> rem else Ctype.newty(Tfield(lab, Btype.copy_kind kind, ty, rem))) methods (Ctype.newty Tnil) in begin try Ctype.unify val_env private_self (Ctype.newty (Tobject(self_methods, ref None))); Ctype.unify val_env public_self self_type with Ctype.Unify trace -> raise(Error(loc, Final_self_clash trace)) end; end; (* Typing of method bodies *) if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.generalize_spine ty) methods; let fields = List.map Lazy.force (List.rev fields) in if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.unify val_env ty (Ctype.newvar ())) methods; let meths = Meths.map (function (id, ty) -> id) !meths in (* Check for private methods made public *) let pub_meths' = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind = Fpresent) (get_methods public_self) in let names = List.map (fun (x,_,_) -> x) in let l1 = names priv_meths and l2 = names pub_meths' in let added = List.filter (fun x -> List.mem x l1) l2 in if added <> [] then Location.prerr_warning loc (Warnings.Implicit_public_methods added); {cl_field = fields; cl_meths = meths}, sign and class_expr cl_num val_env met_env scl = match scl.pcl_desc with Pcl_constr (lid, styl) -> let (path, decl) = try Env.lookup_class lid val_env with Not_found -> raise(Error(scl.pcl_loc, Unbound_class lid)) in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, Unbound_class_2 lid)); let tyl = List.map (fun sty -> transl_simple_type val_env false sty, sty.ptyp_loc) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = abbreviate_class_type path params clty in if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, Parameter_arity_mismatch (lid, List.length params, List.length tyl))); List.iter2 (fun (ty',loc) ty -> try Ctype.unify val_env ty' ty with Ctype.Unify trace -> raise(Error(loc, Parameter_mismatch trace))) tyl params; let cl = rc {cl_desc = Tclass_ident path; cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} | Pcl_structure cl_str -> let (desc, ty) = class_structure cl_num false val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tclass_structure desc; cl_loc = scl.pcl_loc; cl_type = Tcty_signature ty; cl_env = val_env} | Pcl_fun (l, Some default, spat, sbody) -> let loc = default.pexp_loc in let scases = [{ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"Some", Some{ppat_loc = loc; ppat_desc = Ppat_var"*sth*"}, false)}, {pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*sth*")}; {ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"None", None, false)}, default] in let smatch = {pexp_loc = loc; pexp_desc = Pexp_match({pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*opt*")}, scases)} in let sfun = {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_fun(l, None, {ppat_loc = loc; ppat_desc = Ppat_var"*opt*"}, {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_let(Default, [spat, smatch], sbody)})} in class_expr cl_num val_env met_env sfun | Pcl_fun (l, None, spat, scl') -> if !Clflags.principal then Ctype.begin_def (); let (pat, pv, val_env', met_env) = Typecore.type_class_arg_pattern cl_num val_env met_env l spat in if !Clflags.principal then begin Ctype.end_def (); iter_pattern (fun {pat_type=ty} -> Ctype.generalize_structure ty) pat end; let pv = List.map (function (id, id', ty) -> (id, Typecore.type_exp val_env' {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none})) pv in let rec not_function = function Tcty_fun _ -> false | _ -> true in let partial = Parmatch.check_partial pat.pat_loc [pat, (* Dummy expression *) {exp_desc = Texp_constant (Asttypes.Const_int 1); exp_loc = Location.none; exp_type = Ctype.none; exp_env = Env.empty }] in Ctype.raise_nongen_level (); let cl = class_expr cl_num val_env' met_env scl' in Ctype.end_def (); if Btype.is_optional l && not_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tclass_fun (pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Tcty_fun (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env} | Pcl_apply (scl', sargs) -> let cl = class_expr cl_num val_env met_env scl' in let rec nonopt_labels ls ty_fun = match ty_fun with | Tcty_fun (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = "") sargs && List.exists (fun l -> l <> "") labels && begin Location.prerr_warning cl.cl_loc Warnings.Labels_omitted; true end in let rec type_args args omitted ty_fun sargs more_sargs = match ty_fun with | Tcty_fun (l, ty, ty_fun) when sargs <> [] || more_sargs <> [] -> let name = Btype.label_name l and optional = if Btype.is_optional l then Optional else Required in let sargs, more_sargs, arg = if ignore_labels && not (Btype.is_optional l) then begin match sargs, more_sargs with (l', sarg0)::_, _ -> raise(Error(sarg0.pexp_loc, Apply_wrong_label(l'))) | _, (l', sarg0)::more_sargs -> if l <> l' && l' <> "" then raise(Error(sarg0.pexp_loc, Apply_wrong_label l')) else ([], more_sargs, Some(type_argument val_env sarg0 ty)) | _ -> assert false end else try let (l', sarg0, sargs, more_sargs) = try let (l', sarg0, sargs1, sargs2) = Btype.extract_label name sargs in (l', sarg0, sargs1 @ sargs2, more_sargs) with Not_found -> let (l', sarg0, sargs1, sargs2) = Btype.extract_label name more_sargs in (l', sarg0, sargs @ sargs1, sargs2) in sargs, more_sargs, if Btype.is_optional l' || not (Btype.is_optional l) then Some (type_argument val_env sarg0 ty) else let arg = type_argument val_env sarg0 (extract_option_type val_env ty) in Some (option_some arg) with Not_found -> sargs, more_sargs, if Btype.is_optional l && (List.mem_assoc "" sargs || List.mem_assoc "" more_sargs) then Some (option_none ty Location.none) else None in let omitted = if arg = None then (l,ty) :: omitted else omitted in type_args ((arg,optional)::args) omitted ty_fun sargs more_sargs | _ -> match sargs @ more_sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, Apply_wrong_label l)) else raise(Error(cl.cl_loc, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Tcty_fun(l,ty,ty_fun)) ty_fun omitted) in let (args, cty) = if ignore_labels then type_args [] [] cl.cl_type [] sargs else type_args [] [] cl.cl_type sargs [] in rc {cl_desc = Tclass_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env} | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(scl.pcl_loc, Make_nongen_seltype ty)) in let (vals, met_env) = List.fold_right (fun id (vals, met_env) -> Ctype.begin_def (); let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in Ctype.end_def (); Ctype.generalize expr.exp_type; let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents defs) ([], met_env) in let cl = class_expr cl_num val_env met_env scl' in rc {cl_desc = Tclass_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env} | Pcl_constraint (scl', scty) -> Ctype.begin_class_def (); let context = Typetexp.narrow () in let cl = class_expr cl_num val_env met_env scl' in Typetexp.widen context; let context = Typetexp.narrow () in let clty = class_type val_env scty in Typetexp.widen context; Ctype.end_def (); limited_generalize (Ctype.row_variable (Ctype.self_type cl.cl_type)) cl.cl_type; limited_generalize (Ctype.row_variable (Ctype.self_type clty)) clty; begin match Includeclass.class_types val_env cl.cl_type clty with [] -> () | error -> raise(Error(cl.cl_loc, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = snd (Ctype.instance_class [] clty); cl_env = val_env} (*******************************) (* Approximate the type of the constructor to allow recursive use *) (* of optional parameters *) let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_declaration cl, Cok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_fun (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_description ct, Cok)) | _ -> Ctype.newvar () (*******************************) let temp_abbrev env id arity = let params = ref [] in for i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let env = Env.add_type id {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_manifest = Some ty; type_variance = List.map (fun _ -> true, true, true) !params} env in (!params, ty, env) let rec initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, cl_id) = (* Temporary abbreviations *) let arity = List.length (fst cl.pci_params) in let (obj_params, obj_ty, env) = temp_abbrev env obj_id arity in let (cl_params, cl_ty, env) = temp_abbrev env cl_id arity in (* Temporary type for the class constructor *) let constr_type = approx cl.pci_expr in if !Clflags.principal then Ctype.generalize_spine constr_type; let dummy_cty = Tcty_signature { cty_self = Ctype.newvar (); cty_vars = Vars.empty; cty_concr = Concr.empty; cty_inher = [] } in let dummy_class = {cty_params = []; (* Dummy value *) cty_variance = []; cty_type = dummy_cty; (* Dummy value *) cty_path = unbound_class; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in let env = Env.add_cltype ty_id {clty_params = []; (* Dummy value *) clty_variance = []; clty_type = dummy_cty; (* Dummy value *) clty_path = unbound_class} ( if define_class then Env.add_class id dummy_class env else env) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = reset_type_variables (); Ctype.begin_class_def (); (* Introduce class parameters *) let params = try let params, loc = cl.pci_params in List.map (enter_type_variable true loc) params with Already_bound -> raise(Error(snd cl.pci_params, Repeated_parameter)) in (* Allow self coercions (only for class declarations) *) let coercion_locs = ref [] in (* Type the class expression *) let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in Ctype.end_def (); let sty = Ctype.self_type typ in the row variable let rv = Ctype.row_variable sty in List.iter (Ctype.limited_generalize rv) params; limited_generalize rv typ; (* Check the abbreviation for the object type *) let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let ty = Ctype.self_type obj_type in Ctype.hide_private_methods ty; Ctype.close_object ty; begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (obj_id, constr, Ctype.newconstr (Path.Pident obj_id) obj_params'))) end; begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; (* Check the other temporary abbreviation (#-type) *) begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Ctype.self_type cl_type in Ctype.hide_private_methods ty; Ctype.set_object_name obj_id (Ctype.row_variable ty) cl_params ty; begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (cl_id, Ctype.newconstr (Path.Pident cl_id) cl_params, Ctype.newconstr (Path.Pident cl_id) cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let constr = Ctype.newconstr (Path.Pident cl_id) params in raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, cl_ty))) end end; (* Type of the class constructor *) begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify trace -> raise(Error(cl.pci_loc, Constructor_type_mismatch (cl.pci_name, trace))) end; (* Class and class type temporary definitions *) let cty_variance = List.map (fun _ -> true, true) params in let cltydef = {clty_params = params; clty_type = class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id} and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in if cl.pci_virt = Concrete then begin let sign = Ctype.signature_of_class_type typ in let mets = virtual_methods sign in let vals = Vars.fold (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l) sign.cty_vars [] in if mets <> [] || vals <> [] then raise(Error(cl.pci_loc, Virtual_class(true, mets, vals))); end; (* Misc. *) let arity = Ctype.class_type_arity typ in let pub_meths = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head env obj_ty)) in List.map (function (lab, _, _) -> lab) fields in (* Final definitions *) let (params', typ') = Ctype.instance_class params typ in let cltydef = {clty_params = params'; clty_type = class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id} and clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some (Ctype.instance constr_type)} in let obj_abbr = {type_params = obj_params; type_arity = List.length obj_params; type_kind = Type_abstract; type_manifest = Some obj_ty; type_variance = List.map (fun _ -> true, true, true) obj_params} in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Ctype.self_type typ) in Ctype.hide_private_methods cl_ty; Ctype.set_object_name obj_id (Ctype.row_variable cl_ty) cl_params cl_ty; let cl_abbr = {type_params = cl_params; type_arity = List.length cl_params; type_kind = Type_abstract; type_manifest = Some cl_ty; type_variance = List.map (fun _ -> true, true, true) cl_params} in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify trace -> raise(Error(cl.pci_loc, Non_collapsable_conjunction (id, clty, trace))) end; List.iter Ctype.generalize clty.cty_params; generalize_class_type clty.cty_type; begin match clty.cty_new with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize obj_abbr.type_params; begin match obj_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize cl_abbr.type_params; begin match cl_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; if not (closed_class clty) then raise(Error(cl.pci_loc, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Ctype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, Unbound_type_var(printer, reason))) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, (cl.pci_variance, cl.pci_loc)) let extract_type_decls (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, required) decls = (obj_id, obj_abbr, cl_abbr, clty, cltydef, required) :: decls let merge_type_decls (id, _clty, ty_id, _cltydef, obj_id, _obj_abbr, cl_id, _cl_abbr, arity, pub_meths, coe, expr, req) (obj_abbr, cl_abbr, clty, cltydef) = (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) let final_env define_class env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = (* Add definitions after cleaning them *) Env.add_type obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_type cl_id (Subst.type_declaration Subst.identity cl_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env))) (* Check that #c is coercible to c if there is a self-coercion *) let check_coercions env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coercion_locs, expr) = begin match coercion_locs with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype (tr1, tr2) -> raise(Typecore.Error(loc, Typecore.Not_subtype(tr1, tr2))) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, Cannot_coerce_self obj_ty)) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, expr) (*******************************) let type_classes define_class approx kind env cls = let cls = List.map (function cl -> (cl, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create ("#" ^ cl.pci_name))) cls in Ctype.init_def (Ident.current_time ()); Ctype.begin_class_def (); let (res, env) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, env) = List.fold_right (class_infos define_class kind) res ([], env) in Ctype.end_def (); let res = List.rev_map (final_decl env define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = Typedecl.compute_variance_decls env decls in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env sexpr = incr class_num; let expr = class_expr (string_of_int !class_num) env env sexpr in (expr, expr.cl_type) let class_description env sexpr = let expr = class_type env sexpr in (expr, expr) let class_declarations env cls = type_classes true approx_declaration class_declaration env cls let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decl, env) = type_classes false approx_description class_description env cls in (List.map (function (_, _, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, _, _, _) -> (ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr)) decl, env) let rec unify_parents env ty cl = match cl.cl_desc with Tclass_ident p -> begin try let decl = Env.find_class p env in let _, body = Ctype.find_cltype_for_path env decl.cty_path in Ctype.unify env ty (Ctype.instance body) with exn -> assert (exn = Not_found) end | Tclass_structure st -> unify_parents_struct env ty st | Tclass_fun (_, _, cl, _) | Tclass_apply (cl, _) | Tclass_let (_, _, _, cl) | Tclass_constraint (cl, _, _, _) -> unify_parents env ty cl and unify_parents_struct env ty st = List.iter (function Cf_inher (cl, _, _) -> unify_parents env ty cl | _ -> ()) st.cl_field let type_object env loc s = incr class_num; let (desc, sign) = class_structure (string_of_int !class_num) true env env loc s in let sty = Ctype.expand_head env sign.cty_self in Ctype.hide_private_methods sty; let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sty) in let meths = List.map (fun (s,_,_) -> s) fields in unify_parents_struct env sign.cty_self desc; (desc, sign, meths) let () = Typecore.type_object := type_object (*******************************) (* Approximate the class declaration as class ['params] id = object end *) let approx_class sdecl = let self' = { ptyp_desc = Ptyp_any; ptyp_loc = Location.none } in let clty' = { pcty_desc = Pcty_signature(self', []); pcty_loc = sdecl.pci_expr.pcty_loc } in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = fst (class_type_declarations env (List.map approx_class sdecls)) (*******************************) (* Error report *) open Format let report_error ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint trace -> fprintf ppf "The class constraints are not consistent.@."; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Field_type_mismatch (k, m, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply clty -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | "" -> "out label" | l -> sprintf " label ~%s" l in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> (* XXX Trace *) XXX Revoir message Printtyp.reset_and_mark_loops ty; fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class cl -> fprintf ppf "@[Unbound class@ %a@]" Printtyp.longident cl | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type cl -> fprintf ppf "@[Unbound class type@ %a@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> (* XXX Afficher une trace ? *) Printtyp.reset_and_mark_loops_list [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" Printtyp.type_expr abbrev Printtyp.type_expr actual Printtyp.type_expr expected | Constructor_type_mismatch (c, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (cl, mets, vals) -> let print_mets ppf mets = List.iter (function met -> fprintf ppf "@ %s" met) mets in let cl_mark = if cl then "" else " type" in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This class%s should be virtual.@ \ @[<2>The following %s are undefined :%a@]@]" cl_mark missings print_mets (mets @ vals) | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.reset_and_mark_loops_list [params; cstrs]; fprintf ppf "@[The abbreviation %a@ is used with parameters@ %a@ \ wich are incompatible with constraints@ %a@]" Printtyp.ident id Printtyp.type_expr params Printtyp.type_expr cstrs | Class_match_failure error -> Includeclass.report_error ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_common ppf kind ty0 real lab ty = let ty1 = if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.mark_loops ty1; fprintf ppf "The %s %s@ has type@;<1 2>%a@ where@ %a@ is unbound" kind lab Printtyp.type_expr ty Printtyp.type_expr ty0 in let print_reason ppf = function | Ctype.CC_Method (ty0, real, lab, ty) -> print_common ppf "method" ty0 real lab ty | Ctype.CC_Value (ty0, real, lab, ty) -> print_common ppf "instance variable" ty0 real lab ty in Printtyp.reset (); fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Make_nongen_seltype ty -> fprintf ppf "@[<v>@[Self type should not occur in the non-generic type@;<1 2>\ %a@]@,\ It would escape the scope of its class@]" Printtyp.type_scheme ty | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, trace) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsable conjunctive types in constraints@]" (Printtyp.class_declaration id) clty; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Final_self_clash trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but has actually type") | Mutability_mismatch (lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s,@ it cannot be redefined as %s@]" mut1 mut2
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/typing/typeclass.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* $Id: typeclass.ml,v 1.89.6.3 2008/01/28 13:26:48 doligez Exp $ ******************** Useful constants ******************** Self type have a dummy private method, thus preventing it to become closed. Path associated to the temporary class type of a class being typed (its constructor is not available). ********************************** Some operations on class types ********************************** Fully expand the head of a class type Return the virtual methods of a class type Return the constructor type associated to a class type Only class bodies can be abbreviated Record a class type ********************************* Primitives for typing classes ********************************* Enter a value in the method environment only Enter an instance variable in the environment Methods No need to warn about overriding of inherited methods! ***************************** Check that the binder is a correct type, and introduce a dummy method preventing self type from being closed. Class type fields ***************************** Variables Inherited concrete methods backup variables for Pexp_override Environment for substructures Self type, with a dummy method preventing it from being closed/escaped. Private self is used for private method calls Self binder Check that the binder has a correct type Copy known information to still empty self_type Typing of class fields allow public self and private self to be unified Typing of method bodies Check for private methods made public Dummy expression ***************************** Approximate the type of the constructor to allow recursive use of optional parameters ***************************** Temporary abbreviations Temporary type for the class constructor Dummy value Dummy value Dummy value Dummy value Introduce class parameters Allow self coercions (only for class declarations) Type the class expression Check the abbreviation for the object type Check the other temporary abbreviation (#-type) Type of the class constructor Class and class type temporary definitions Misc. Final definitions Add definitions after cleaning them Check that #c is coercible to c if there is a self-coercion ***************************** ***************************** Approximate the class declaration as class ['params] id = object end ***************************** Error report XXX Trace XXX Afficher une trace ?
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . open Misc open Parsetree open Asttypes open Path open Types open Typedtree open Typecore open Typetexp open Format type error = Unconsistent_constraint of (type_expr * type_expr) list | Field_type_mismatch of string * string * (type_expr * type_expr) list | Structure_expected of class_type | Cannot_apply of class_type | Apply_wrong_label of label | Pattern_type_clash of type_expr | Repeated_parameter | Unbound_class of Longident.t | Unbound_class_2 of Longident.t | Unbound_class_type of Longident.t | Unbound_class_type_2 of Longident.t | Abbrev_type_clash of type_expr * type_expr * type_expr | Constructor_type_mismatch of string * (type_expr * type_expr) list | Virtual_class of bool * string list * string list | Parameter_arity_mismatch of Longident.t * int * int | Parameter_mismatch of (type_expr * type_expr) list | Bad_parameters of Ident.t * type_expr * type_expr | Class_match_failure of Ctype.class_match_failure list | Unbound_val of string | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure | Make_nongen_seltype of type_expr | Non_generalizable_class of Ident.t * Types.class_declaration | Cannot_coerce_self of type_expr | Non_collapsable_conjunction of Ident.t * Types.class_declaration * (type_expr * type_expr) list | Final_self_clash of (type_expr * type_expr) list | Mutability_mismatch of string * mutable_flag exception Error of Location.t * error let dummy_method = Ctype.dummy_method let unbound_class = Path.Pident (Ident.create "") let rec scrape_class_type = function Tcty_constr (_, _, cty) -> scrape_class_type cty | cty -> cty a class type let rec generalize_class_type = function Tcty_constr (_, params, cty) -> List.iter Ctype.generalize params; generalize_class_type cty | Tcty_signature {cty_self = sty; cty_vars = vars; cty_inher = inher} -> Ctype.generalize sty; Vars.iter (fun _ (_, _, ty) -> Ctype.generalize ty) vars; List.iter (fun (_,tl) -> List.iter Ctype.generalize tl) inher | Tcty_fun (_, ty, cty) -> Ctype.generalize ty; generalize_class_type cty let virtual_methods sign = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun virt (lab, _, _) -> if lab = dummy_method then virt else if Concr.mem lab sign.cty_concr then virt else lab::virt) [] fields let rec constructor_type constr cty = match cty with Tcty_constr (_, _, cty) -> constructor_type constr cty | Tcty_signature sign -> constr | Tcty_fun (l, ty, cty) -> Ctype.newty (Tarrow (l, ty, constructor_type constr cty, Cok)) let rec class_body cty = match cty with Tcty_constr (_, _, cty') -> | Tcty_signature sign -> cty | Tcty_fun (_, ty, cty) -> class_body cty let rec extract_constraints cty = let sign = Ctype.signature_of_class_type cty in (Vars.fold (fun lab _ vars -> lab :: vars) sign.cty_vars [], begin let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in List.fold_left (fun meths (lab, _, _) -> if lab = dummy_method then meths else lab::meths) [] fields end, sign.cty_concr) let rec abbreviate_class_type path params cty = match cty with Tcty_constr (_, _, _) | Tcty_signature _ -> Tcty_constr (path, params, cty) | Tcty_fun (l, ty, cty) -> Tcty_fun (l, ty, abbreviate_class_type path params cty) let rec closed_class_type = function Tcty_constr (_, params, _) -> List.for_all Ctype.closed_schema params | Tcty_signature sign -> Ctype.closed_schema sign.cty_self && Vars.fold (fun _ (_, _, ty) cc -> Ctype.closed_schema ty && cc) sign.cty_vars true | Tcty_fun (_, ty, cty) -> Ctype.closed_schema ty && closed_class_type cty let closed_class cty = List.for_all Ctype.closed_schema cty.cty_params && closed_class_type cty.cty_type let rec limited_generalize rv = function Tcty_constr (path, params, cty) -> List.iter (Ctype.limited_generalize rv) params; limited_generalize rv cty | Tcty_signature sign -> Ctype.limited_generalize rv sign.cty_self; Vars.iter (fun _ (_, _, ty) -> Ctype.limited_generalize rv ty) sign.cty_vars; List.iter (fun (_, tl) -> List.iter (Ctype.limited_generalize rv) tl) sign.cty_inher | Tcty_fun (_, ty, cty) -> Ctype.limited_generalize rv ty; limited_generalize rv cty let rc node = Stypes.record (Stypes.Ti_class node); node let enter_met_env lab kind ty val_env met_env par_env = let (id, val_env) = Env.enter_value lab {val_type = ty; val_kind = Val_unbound} val_env in (id, val_env, Env.add_value id {val_type = ty; val_kind = kind} met_env, Env.add_value id {val_type = ty; val_kind = Val_unbound} par_env) let enter_val cl_num vars inh lab mut virt ty val_env met_env par_env loc = let (id, virt) = try let (id, mut', virt', ty') = Vars.find lab !vars in if mut' <> mut then raise (Error(loc, Mutability_mismatch(lab, mut))); Ctype.unify val_env (Ctype.instance ty) (Ctype.instance ty'); (if not inh then Some id else None), (if virt' = Concrete then virt' else virt) with Ctype.Unify tr -> raise (Error(loc, Field_type_mismatch("instance variable", lab, tr))) | Not_found -> None, virt in let (id, _, _, _) as result = match id with Some id -> (id, val_env, met_env, par_env) | None -> enter_met_env lab (Val_ivar (mut, cl_num)) ty val_env met_env par_env in vars := Vars.add lab (id, mut, virt, ty) !vars; result let inheritance self_type env concr_meths warn_meths loc parent = match scrape_class_type parent with Tcty_signature cl_sig -> begin try Ctype.unify env self_type cl_sig.cty_self with Ctype.Unify trace -> match trace with _::_::_::({desc = Tfield(n, _, _, _)}, _)::rem -> raise(Error(loc, Field_type_mismatch ("method", n, rem))) | _ -> assert false end; let overridings = Concr.inter cl_sig.cty_concr warn_meths in if not (Concr.is_empty overridings) then begin let cname = match parent with Tcty_constr (p, _, _) -> Path.name p | _ -> "inherited" in Location.prerr_warning loc (Warnings.Method_override (cname :: Concr.elements overridings)) end; let concr_meths = Concr.union cl_sig.cty_concr concr_meths in let warn_meths = Concr.union cl_sig.cty_concr warn_meths in (cl_sig, concr_meths, warn_meths) | _ -> raise(Error(loc, Structure_expected parent)) let virtual_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let ty = transl_simple_type val_env false sty in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) let delayed_meth_specs = ref [] let declare_method val_env meths self_type lab priv sty loc = let (_, ty') = Ctype.filter_self_method val_env lab priv meths self_type in let unif ty = try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) in match sty.ptyp_desc, priv with Ptyp_poly ([],sty), Public -> delayed_meth_specs := lazy (unif (transl_simple_type_univars val_env sty)) :: !delayed_meth_specs | _ -> unif (transl_simple_type val_env false sty) let type_constraint val_env sty sty' loc = let ty = transl_simple_type val_env false sty in let ty' = transl_simple_type val_env false sty' in try Ctype.unify val_env ty ty' with Ctype.Unify trace -> raise(Error(loc, Unconsistent_constraint trace)) let mkpat d = { ppat_desc = d; ppat_loc = Location.none } let make_method cl_num expr = { pexp_desc = Pexp_function ("", None, [mkpat (Ppat_alias (mkpat(Ppat_var "self-*"), "self-" ^ cl_num)), expr]); pexp_loc = expr.pexp_loc } let add_val env loc lab (mut, virt, ty) val_sig = let virt = try let (mut', virt', ty') = Vars.find lab val_sig in if virt' = Concrete then virt' else virt with Not_found -> virt in Vars.add lab (mut, virt, ty) val_sig let rec class_type_field env self_type meths (val_sig, concr_meths, inher) = function Pctf_inher sparent -> let parent = class_type env sparent in let inher = match parent with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, _) = inheritance self_type env concr_meths Concr.empty sparent.pcty_loc parent in let val_sig = Vars.fold (add_val env sparent.pcty_loc) cl_sig.cty_vars val_sig in (val_sig, concr_meths, inher) | Pctf_val (lab, mut, virt, sty, loc) -> let ty = transl_simple_type env false sty in (add_val env loc lab (mut, virt, ty) val_sig, concr_meths, inher) | Pctf_virt (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, concr_meths, inher) | Pctf_meth (lab, priv, sty, loc) -> declare_method env meths self_type lab priv sty loc; (val_sig, Concr.add lab concr_meths, inher) | Pctf_cstr (sty, sty', loc) -> type_constraint env sty sty' loc; (val_sig, concr_meths, inher) and class_signature env sty sign = let meths = ref Meths.empty in let self_type = transl_simple_type env false sty in let dummy_obj = Ctype.newvar () in Ctype.unify env (Ctype.filter_method env dummy_method Private dummy_obj) (Ctype.newty (Ttuple [])); begin try Ctype.unify env self_type dummy_obj with Ctype.Unify _ -> raise(Error(sty.ptyp_loc, Pattern_type_clash self_type)) end; let (val_sig, concr_meths, inher) = List.fold_left (class_type_field env self_type meths) (Vars.empty, Concr.empty, []) sign in {cty_self = self_type; cty_vars = val_sig; cty_concr = concr_meths; cty_inher = inher} and class_type env scty = match scty.pcty_desc with Pcty_constr (lid, styl) -> let (path, decl) = try Env.lookup_cltype lid env with Not_found -> raise(Error(scty.pcty_loc, Unbound_class_type lid)) in if Path.same decl.clty_path unbound_class then raise(Error(scty.pcty_loc, Unbound_class_type_2 lid)); let (params, clty) = Ctype.instance_class decl.clty_params decl.clty_type in if List.length params <> List.length styl then raise(Error(scty.pcty_loc, Parameter_arity_mismatch (lid, List.length params, List.length styl))); List.iter2 (fun sty ty -> let ty' = transl_simple_type env false sty in try Ctype.unify env ty' ty with Ctype.Unify trace -> raise(Error(sty.ptyp_loc, Parameter_mismatch trace))) styl params; Tcty_constr (path, params, clty) | Pcty_signature (sty, sign) -> Tcty_signature (class_signature env sty sign) | Pcty_fun (l, sty, scty) -> let ty = transl_simple_type env false sty in let cty = class_type env scty in Tcty_fun (l, ty, cty) let class_type env scty = delayed_meth_specs := []; let cty = class_type env scty in List.iter Lazy.force (List.rev !delayed_meth_specs); delayed_meth_specs := []; cty module StringSet = Set.Make(struct type t = string let compare = compare end) let rec class_field cl_num self_type meths vars (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) = function Pcf_inher (sparent, super) -> let parent = class_expr cl_num val_env par_env sparent in let inher = match parent.cl_type with Tcty_constr (p, tl, _) -> (p, tl) :: inher | _ -> inher in let (cl_sig, concr_meths, warn_meths) = inheritance self_type val_env concr_meths warn_meths sparent.pcl_loc parent.cl_type in let (val_env, met_env, par_env, inh_vars, warn_vals) = Vars.fold (fun lab info (val_env, met_env, par_env, inh_vars, warn_vals) -> let mut, vr, ty = info in let (id, val_env, met_env, par_env) = enter_val cl_num vars true lab mut vr ty val_env met_env par_env sparent.pcl_loc in let warn_vals = if vr = Virtual then warn_vals else if StringSet.mem lab warn_vals then (Location.prerr_warning sparent.pcl_loc (Warnings.Instance_variable_override lab); warn_vals) else StringSet.add lab warn_vals in (val_env, met_env, par_env, (lab, id) :: inh_vars, warn_vals)) cl_sig.cty_vars (val_env, met_env, par_env, [], warn_vals) in let inh_meths = Concr.fold (fun lab rem -> (lab, Ident.create lab)::rem) cl_sig.cty_concr [] in Super let (val_env, met_env, par_env) = match super with None -> (val_env, met_env, par_env) | Some name -> let (id, val_env, met_env, par_env) = enter_met_env name (Val_anc (inh_meths, cl_num)) self_type val_env met_env par_env in (val_env, met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_inher (parent, inh_vars, inh_meths))::fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_valvirt (lab, mut, styp, loc) -> if !Clflags.principal then Ctype.begin_def (); let ty = Typetexp.transl_simple_type val_env false styp in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure ty end; let (id, val_env, met_env', par_env) = enter_val cl_num vars false lab mut Virtual ty val_env met_env par_env loc in (val_env, met_env', par_env, lazy(Cf_val (lab, id, None, met_env' == met_env)) :: fields, concr_meths, warn_meths, StringSet.remove lab warn_vals, inher) | Pcf_val (lab, mut, sexp, loc) -> if StringSet.mem lab warn_vals then Location.prerr_warning loc (Warnings.Instance_variable_override lab); if !Clflags.principal then Ctype.begin_def (); let exp = try type_exp val_env sexp with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in if !Clflags.principal then begin Ctype.end_def (); Ctype.generalize_structure exp.exp_type end; let (id, val_env, met_env', par_env) = enter_val cl_num vars false lab mut Concrete exp.exp_type val_env met_env par_env loc in (val_env, met_env', par_env, lazy(Cf_val (lab, id, Some exp, met_env' == met_env)) :: fields, concr_meths, warn_meths, StringSet.add lab warn_vals, inher) | Pcf_virt (lab, priv, sty, loc) -> virtual_method val_env meths self_type lab priv sty loc; let warn_meths = Concr.remove lab warn_meths in (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_meth (lab, priv, expr, loc) -> if Concr.mem lab warn_meths then Location.prerr_warning loc (Warnings.Method_override [lab]); let (_, ty) = Ctype.filter_self_method val_env lab priv meths self_type in begin try match expr.pexp_desc with Pexp_poly (sbody, sty) -> begin match sty with None -> () | Some sty -> Ctype.unify val_env (Typetexp.transl_simple_type val_env false sty) ty end; begin match (Ctype.repr ty).desc with Tvar -> let ty' = Ctype.newvar () in Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty; Ctype.unify val_env (type_approx val_env sbody) ty' | Tpoly (ty1, tl) -> let _, ty1' = Ctype.instance_poly false tl ty1 in let ty2 = type_approx val_env sbody in Ctype.unify val_env ty2 ty1' | _ -> assert false end | _ -> assert false with Ctype.Unify trace -> raise(Error(loc, Field_type_mismatch ("method", lab, trace))) end; let meth_expr = make_method cl_num expr in let vars_local = !vars in let field = lazy begin let meth_type = Ctype.newty (Tarrow("", self_type, Ctype.instance ty, Cok)) in Ctype.raise_nongen_level (); vars := vars_local; let texp = type_expect met_env meth_expr meth_type in Ctype.end_def (); Cf_meth (lab, texp) end in (val_env, met_env, par_env, field::fields, Concr.add lab concr_meths, Concr.add lab warn_meths, warn_vals, inher) | Pcf_cstr (sty, sty', loc) -> type_constraint val_env sty sty' loc; (val_env, met_env, par_env, fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_let (rec_flag, sdefs, loc) -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(loc, Make_nongen_seltype ty)) in let (vals, met_env, par_env) = List.fold_right (fun id (vals, met_env, par_env) -> let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env, Env.add_value id' desc par_env)) (let_bound_idents defs) ([], met_env, par_env) in (val_env, met_env, par_env, lazy(Cf_let(rec_flag, defs, vals))::fields, concr_meths, warn_meths, warn_vals, inher) | Pcf_init expr -> let expr = make_method cl_num expr in let vars_local = !vars in let field = lazy begin Ctype.raise_nongen_level (); let meth_type = Ctype.newty (Tarrow ("", self_type, Ctype.instance Predef.type_unit, Cok)) in vars := vars_local; let texp = type_expect met_env expr meth_type in Ctype.end_def (); Cf_init texp end in (val_env, met_env, par_env, field::fields, concr_meths, warn_meths, warn_vals, inher) and class_structure cl_num final val_env met_env loc (spat, str) = let par_env = met_env in let self_type = Ctype.newvar () in Ctype.unify val_env (Ctype.filter_method val_env dummy_method Private self_type) (Ctype.newty (Ttuple [])); let private_self = if final then Ctype.newvar () else self_type in let (pat, meths, vars, val_env, meth_env, par_env) = type_self_pattern cl_num private_self val_env met_env par_env spat in let public_self = pat.pat_type in let ty = if final then Ctype.newty (Tobject (Ctype.newvar(), ref None)) else self_type in begin try Ctype.unify val_env public_self ty with Ctype.Unify _ -> raise(Error(spat.ppat_loc, Pattern_type_clash public_self)) end; let get_methods ty = (fst (Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head val_env ty)))) in if final then begin List.iter (fun (lab,kind,ty) -> let k = if Btype.field_kind_repr kind = Fpresent then Public else Private in try Ctype.unify val_env ty (Ctype.filter_method val_env lab k self_type) with _ -> assert false) (get_methods public_self) end; let (_, _, _, fields, concr_meths, _, _, inher) = List.fold_left (class_field cl_num self_type meths vars) (val_env, meth_env, par_env, [], Concr.empty, Concr.empty, StringSet.empty, []) str in Ctype.unify val_env self_type (Ctype.newvar ()); let sign = {cty_self = public_self; cty_vars = Vars.map (fun (id, mut, vr, ty) -> (mut, vr, ty)) !vars; cty_concr = concr_meths; cty_inher = inher} in let methods = get_methods self_type in let priv_meths = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind <> Fpresent) methods in if final then begin Unify private_self and a copy of self_type . self_type will not be modified after this point be modified after this point *) Ctype.close_object self_type; let mets = virtual_methods {sign with cty_self = self_type} in let vals = Vars.fold (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l) sign.cty_vars [] in if mets <> [] || vals <> [] then raise(Error(loc, Virtual_class(true, mets, vals))); let self_methods = List.fold_right (fun (lab,kind,ty) rem -> if lab = dummy_method then match Btype.field_kind_repr kind with Fvar r -> Btype.set_kind r Fabsent; rem | _ -> rem else Ctype.newty(Tfield(lab, Btype.copy_kind kind, ty, rem))) methods (Ctype.newty Tnil) in begin try Ctype.unify val_env private_self (Ctype.newty (Tobject(self_methods, ref None))); Ctype.unify val_env public_self self_type with Ctype.Unify trace -> raise(Error(loc, Final_self_clash trace)) end; end; if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.generalize_spine ty) methods; let fields = List.map Lazy.force (List.rev fields) in if !Clflags.principal then List.iter (fun (_,_,ty) -> Ctype.unify val_env ty (Ctype.newvar ())) methods; let meths = Meths.map (function (id, ty) -> id) !meths in let pub_meths' = List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind = Fpresent) (get_methods public_self) in let names = List.map (fun (x,_,_) -> x) in let l1 = names priv_meths and l2 = names pub_meths' in let added = List.filter (fun x -> List.mem x l1) l2 in if added <> [] then Location.prerr_warning loc (Warnings.Implicit_public_methods added); {cl_field = fields; cl_meths = meths}, sign and class_expr cl_num val_env met_env scl = match scl.pcl_desc with Pcl_constr (lid, styl) -> let (path, decl) = try Env.lookup_class lid val_env with Not_found -> raise(Error(scl.pcl_loc, Unbound_class lid)) in if Path.same decl.cty_path unbound_class then raise(Error(scl.pcl_loc, Unbound_class_2 lid)); let tyl = List.map (fun sty -> transl_simple_type val_env false sty, sty.ptyp_loc) styl in let (params, clty) = Ctype.instance_class decl.cty_params decl.cty_type in let clty' = abbreviate_class_type path params clty in if List.length params <> List.length tyl then raise(Error(scl.pcl_loc, Parameter_arity_mismatch (lid, List.length params, List.length tyl))); List.iter2 (fun (ty',loc) ty -> try Ctype.unify val_env ty' ty with Ctype.Unify trace -> raise(Error(loc, Parameter_mismatch trace))) tyl params; let cl = rc {cl_desc = Tclass_ident path; cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} in let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = clty'; cl_env = val_env} | Pcl_structure cl_str -> let (desc, ty) = class_structure cl_num false val_env met_env scl.pcl_loc cl_str in rc {cl_desc = Tclass_structure desc; cl_loc = scl.pcl_loc; cl_type = Tcty_signature ty; cl_env = val_env} | Pcl_fun (l, Some default, spat, sbody) -> let loc = default.pexp_loc in let scases = [{ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"Some", Some{ppat_loc = loc; ppat_desc = Ppat_var"*sth*"}, false)}, {pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*sth*")}; {ppat_loc = loc; ppat_desc = Ppat_construct(Longident.Lident"None", None, false)}, default] in let smatch = {pexp_loc = loc; pexp_desc = Pexp_match({pexp_loc = loc; pexp_desc = Pexp_ident(Longident.Lident"*opt*")}, scases)} in let sfun = {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_fun(l, None, {ppat_loc = loc; ppat_desc = Ppat_var"*opt*"}, {pcl_loc = scl.pcl_loc; pcl_desc = Pcl_let(Default, [spat, smatch], sbody)})} in class_expr cl_num val_env met_env sfun | Pcl_fun (l, None, spat, scl') -> if !Clflags.principal then Ctype.begin_def (); let (pat, pv, val_env', met_env) = Typecore.type_class_arg_pattern cl_num val_env met_env l spat in if !Clflags.principal then begin Ctype.end_def (); iter_pattern (fun {pat_type=ty} -> Ctype.generalize_structure ty) pat end; let pv = List.map (function (id, id', ty) -> (id, Typecore.type_exp val_env' {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none})) pv in let rec not_function = function Tcty_fun _ -> false | _ -> true in let partial = Parmatch.check_partial pat.pat_loc {exp_desc = Texp_constant (Asttypes.Const_int 1); exp_loc = Location.none; exp_type = Ctype.none; exp_env = Env.empty }] in Ctype.raise_nongen_level (); let cl = class_expr cl_num val_env' met_env scl' in Ctype.end_def (); if Btype.is_optional l && not_function cl.cl_type then Location.prerr_warning pat.pat_loc Warnings.Unerasable_optional_argument; rc {cl_desc = Tclass_fun (pat, pv, cl, partial); cl_loc = scl.pcl_loc; cl_type = Tcty_fun (l, Ctype.instance pat.pat_type, cl.cl_type); cl_env = val_env} | Pcl_apply (scl', sargs) -> let cl = class_expr cl_num val_env met_env scl' in let rec nonopt_labels ls ty_fun = match ty_fun with | Tcty_fun (l, _, ty_res) -> if Btype.is_optional l then nonopt_labels ls ty_res else nonopt_labels (l::ls) ty_res | _ -> ls in let ignore_labels = !Clflags.classic || let labels = nonopt_labels [] cl.cl_type in List.length labels = List.length sargs && List.for_all (fun (l,_) -> l = "") sargs && List.exists (fun l -> l <> "") labels && begin Location.prerr_warning cl.cl_loc Warnings.Labels_omitted; true end in let rec type_args args omitted ty_fun sargs more_sargs = match ty_fun with | Tcty_fun (l, ty, ty_fun) when sargs <> [] || more_sargs <> [] -> let name = Btype.label_name l and optional = if Btype.is_optional l then Optional else Required in let sargs, more_sargs, arg = if ignore_labels && not (Btype.is_optional l) then begin match sargs, more_sargs with (l', sarg0)::_, _ -> raise(Error(sarg0.pexp_loc, Apply_wrong_label(l'))) | _, (l', sarg0)::more_sargs -> if l <> l' && l' <> "" then raise(Error(sarg0.pexp_loc, Apply_wrong_label l')) else ([], more_sargs, Some(type_argument val_env sarg0 ty)) | _ -> assert false end else try let (l', sarg0, sargs, more_sargs) = try let (l', sarg0, sargs1, sargs2) = Btype.extract_label name sargs in (l', sarg0, sargs1 @ sargs2, more_sargs) with Not_found -> let (l', sarg0, sargs1, sargs2) = Btype.extract_label name more_sargs in (l', sarg0, sargs @ sargs1, sargs2) in sargs, more_sargs, if Btype.is_optional l' || not (Btype.is_optional l) then Some (type_argument val_env sarg0 ty) else let arg = type_argument val_env sarg0 (extract_option_type val_env ty) in Some (option_some arg) with Not_found -> sargs, more_sargs, if Btype.is_optional l && (List.mem_assoc "" sargs || List.mem_assoc "" more_sargs) then Some (option_none ty Location.none) else None in let omitted = if arg = None then (l,ty) :: omitted else omitted in type_args ((arg,optional)::args) omitted ty_fun sargs more_sargs | _ -> match sargs @ more_sargs with (l, sarg0)::_ -> if omitted <> [] then raise(Error(sarg0.pexp_loc, Apply_wrong_label l)) else raise(Error(cl.cl_loc, Cannot_apply cl.cl_type)) | [] -> (List.rev args, List.fold_left (fun ty_fun (l,ty) -> Tcty_fun(l,ty,ty_fun)) ty_fun omitted) in let (args, cty) = if ignore_labels then type_args [] [] cl.cl_type [] sargs else type_args [] [] cl.cl_type sargs [] in rc {cl_desc = Tclass_apply (cl, args); cl_loc = scl.pcl_loc; cl_type = cty; cl_env = val_env} | Pcl_let (rec_flag, sdefs, scl') -> let (defs, val_env) = try Typecore.type_let val_env rec_flag sdefs with Ctype.Unify [(ty, _)] -> raise(Error(scl.pcl_loc, Make_nongen_seltype ty)) in let (vals, met_env) = List.fold_right (fun id (vals, met_env) -> Ctype.begin_def (); let expr = Typecore.type_exp val_env {pexp_desc = Pexp_ident (Longident.Lident (Ident.name id)); pexp_loc = Location.none} in Ctype.end_def (); Ctype.generalize expr.exp_type; let desc = {val_type = expr.exp_type; val_kind = Val_ivar (Immutable, cl_num)} in let id' = Ident.create (Ident.name id) in ((id', expr) :: vals, Env.add_value id' desc met_env)) (let_bound_idents defs) ([], met_env) in let cl = class_expr cl_num val_env met_env scl' in rc {cl_desc = Tclass_let (rec_flag, defs, vals, cl); cl_loc = scl.pcl_loc; cl_type = cl.cl_type; cl_env = val_env} | Pcl_constraint (scl', scty) -> Ctype.begin_class_def (); let context = Typetexp.narrow () in let cl = class_expr cl_num val_env met_env scl' in Typetexp.widen context; let context = Typetexp.narrow () in let clty = class_type val_env scty in Typetexp.widen context; Ctype.end_def (); limited_generalize (Ctype.row_variable (Ctype.self_type cl.cl_type)) cl.cl_type; limited_generalize (Ctype.row_variable (Ctype.self_type clty)) clty; begin match Includeclass.class_types val_env cl.cl_type clty with [] -> () | error -> raise(Error(cl.cl_loc, Class_match_failure error)) end; let (vals, meths, concrs) = extract_constraints clty in rc {cl_desc = Tclass_constraint (cl, vals, meths, concrs); cl_loc = scl.pcl_loc; cl_type = snd (Ctype.instance_class [] clty); cl_env = val_env} let var_option = Predef.type_option (Btype.newgenvar ()) let rec approx_declaration cl = match cl.pcl_desc with Pcl_fun (l, _, _, cl) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_declaration cl, Cok)) | Pcl_let (_, _, cl) -> approx_declaration cl | Pcl_constraint (cl, _) -> approx_declaration cl | _ -> Ctype.newvar () let rec approx_description ct = match ct.pcty_desc with Pcty_fun (l, _, ct) -> let arg = if Btype.is_optional l then Ctype.instance var_option else Ctype.newvar () in Ctype.newty (Tarrow (l, arg, approx_description ct, Cok)) | _ -> Ctype.newvar () let temp_abbrev env id arity = let params = ref [] in for i = 1 to arity do params := Ctype.newvar () :: !params done; let ty = Ctype.newobj (Ctype.newvar ()) in let env = Env.add_type id {type_params = !params; type_arity = arity; type_kind = Type_abstract; type_manifest = Some ty; type_variance = List.map (fun _ -> true, true, true) !params} env in (!params, ty, env) let rec initial_env define_class approx (res, env) (cl, id, ty_id, obj_id, cl_id) = let arity = List.length (fst cl.pci_params) in let (obj_params, obj_ty, env) = temp_abbrev env obj_id arity in let (cl_params, cl_ty, env) = temp_abbrev env cl_id arity in let constr_type = approx cl.pci_expr in if !Clflags.principal then Ctype.generalize_spine constr_type; let dummy_cty = Tcty_signature { cty_self = Ctype.newvar (); cty_vars = Vars.empty; cty_concr = Concr.empty; cty_inher = [] } in let dummy_class = cty_variance = []; cty_path = unbound_class; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in let env = Env.add_cltype ty_id clty_variance = []; clty_path = unbound_class} ( if define_class then Env.add_class id dummy_class env else env) in ((cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class)::res, env) let class_infos define_class kind (cl, id, ty_id, obj_id, obj_params, obj_ty, cl_id, cl_params, cl_ty, constr_type, dummy_class) (res, env) = reset_type_variables (); Ctype.begin_class_def (); let params = try let params, loc = cl.pci_params in List.map (enter_type_variable true loc) params with Already_bound -> raise(Error(snd cl.pci_params, Repeated_parameter)) in let coercion_locs = ref [] in let (expr, typ) = try Typecore.self_coercion := (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion; let res = kind env cl.pci_expr in Typecore.self_coercion := List.tl !Typecore.self_coercion; res with exn -> Typecore.self_coercion := []; raise exn in Ctype.end_def (); let sty = Ctype.self_type typ in the row variable let rv = Ctype.row_variable sty in List.iter (Ctype.limited_generalize rv) params; limited_generalize rv typ; let (obj_params', obj_type) = Ctype.instance_class params typ in let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in begin let ty = Ctype.self_type obj_type in Ctype.hide_private_methods ty; Ctype.close_object ty; begin try List.iter2 (Ctype.unify env) obj_params obj_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (obj_id, constr, Ctype.newconstr (Path.Pident obj_id) obj_params'))) end; begin try Ctype.unify env ty constr with Ctype.Unify _ -> raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, Ctype.expand_head env constr))) end end; begin let (cl_params', cl_type) = Ctype.instance_class params typ in let ty = Ctype.self_type cl_type in Ctype.hide_private_methods ty; Ctype.set_object_name obj_id (Ctype.row_variable ty) cl_params ty; begin try List.iter2 (Ctype.unify env) cl_params cl_params' with Ctype.Unify _ -> raise(Error(cl.pci_loc, Bad_parameters (cl_id, Ctype.newconstr (Path.Pident cl_id) cl_params, Ctype.newconstr (Path.Pident cl_id) cl_params'))) end; begin try Ctype.unify env ty cl_ty with Ctype.Unify _ -> let constr = Ctype.newconstr (Path.Pident cl_id) params in raise(Error(cl.pci_loc, Abbrev_type_clash (constr, ty, cl_ty))) end end; begin try Ctype.unify env (constructor_type constr obj_type) (Ctype.instance constr_type) with Ctype.Unify trace -> raise(Error(cl.pci_loc, Constructor_type_mismatch (cl.pci_name, trace))) end; let cty_variance = List.map (fun _ -> true, true) params in let cltydef = {clty_params = params; clty_type = class_body typ; clty_variance = cty_variance; clty_path = Path.Pident obj_id} and clty = {cty_params = params; cty_type = typ; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some constr_type} in dummy_class.cty_type <- typ; let env = Env.add_cltype ty_id cltydef ( if define_class then Env.add_class id clty env else env) in if cl.pci_virt = Concrete then begin let sign = Ctype.signature_of_class_type typ in let mets = virtual_methods sign in let vals = Vars.fold (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l) sign.cty_vars [] in if mets <> [] || vals <> [] then raise(Error(cl.pci_loc, Virtual_class(true, mets, vals))); end; let arity = Ctype.class_type_arity typ in let pub_meths = let (fields, _) = Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head env obj_ty)) in List.map (function (lab, _, _) -> lab) fields in let (params', typ') = Ctype.instance_class params typ in let cltydef = {clty_params = params'; clty_type = class_body typ'; clty_variance = cty_variance; clty_path = Path.Pident obj_id} and clty = {cty_params = params'; cty_type = typ'; cty_variance = cty_variance; cty_path = Path.Pident obj_id; cty_new = match cl.pci_virt with Virtual -> None | Concrete -> Some (Ctype.instance constr_type)} in let obj_abbr = {type_params = obj_params; type_arity = List.length obj_params; type_kind = Type_abstract; type_manifest = Some obj_ty; type_variance = List.map (fun _ -> true, true, true) obj_params} in let (cl_params, cl_ty) = Ctype.instance_parameterized_type params (Ctype.self_type typ) in Ctype.hide_private_methods cl_ty; Ctype.set_object_name obj_id (Ctype.row_variable cl_ty) cl_params cl_ty; let cl_abbr = {type_params = cl_params; type_arity = List.length cl_params; type_kind = Type_abstract; type_manifest = Some cl_ty; type_variance = List.map (fun _ -> true, true, true) cl_params} in ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, List.rev !coercion_locs, expr) :: res, env) let final_decl env define_class (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = begin try Ctype.collapse_conj_params env clty.cty_params with Ctype.Unify trace -> raise(Error(cl.pci_loc, Non_collapsable_conjunction (id, clty, trace))) end; List.iter Ctype.generalize clty.cty_params; generalize_class_type clty.cty_type; begin match clty.cty_new with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize obj_abbr.type_params; begin match obj_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; List.iter Ctype.generalize cl_abbr.type_params; begin match cl_abbr.type_manifest with None -> () | Some ty -> Ctype.generalize ty end; if not (closed_class clty) then raise(Error(cl.pci_loc, Non_generalizable_class (id, clty))); begin match Ctype.closed_class clty.cty_params (Ctype.signature_of_class_type clty.cty_type) with None -> () | Some reason -> let printer = if define_class then function ppf -> Printtyp.class_declaration id ppf clty else function ppf -> Printtyp.cltype_declaration id ppf cltydef in raise(Error(cl.pci_loc, Unbound_type_var(printer, reason))) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, (cl.pci_variance, cl.pci_loc)) let extract_type_decls (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr, required) decls = (obj_id, obj_abbr, cl_abbr, clty, cltydef, required) :: decls let merge_type_decls (id, _clty, ty_id, _cltydef, obj_id, _obj_abbr, cl_id, _cl_abbr, arity, pub_meths, coe, expr, req) (obj_abbr, cl_abbr, clty, cltydef) = (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) let final_env define_class env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coe, expr) = Env.add_type obj_id (Subst.type_declaration Subst.identity obj_abbr) ( Env.add_type cl_id (Subst.type_declaration Subst.identity cl_abbr) ( Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) ( if define_class then Env.add_class id (Subst.class_declaration Subst.identity clty) env else env))) let check_coercions env (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, coercion_locs, expr) = begin match coercion_locs with [] -> () | loc :: _ -> let cl_ty, obj_ty = match cl_abbr.type_manifest, obj_abbr.type_manifest with Some cl_ab, Some obj_ab -> let cl_params, cl_ty = Ctype.instance_parameterized_type cl_abbr.type_params cl_ab and obj_params, obj_ty = Ctype.instance_parameterized_type obj_abbr.type_params obj_ab in List.iter2 (Ctype.unify env) cl_params obj_params; cl_ty, obj_ty | _ -> assert false in begin try Ctype.subtype env cl_ty obj_ty () with Ctype.Subtype (tr1, tr2) -> raise(Typecore.Error(loc, Typecore.Not_subtype(tr1, tr2))) end; if not (Ctype.opened_object cl_ty) then raise(Error(loc, Cannot_coerce_self obj_ty)) end; (id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, arity, pub_meths, expr) let type_classes define_class approx kind env cls = let cls = List.map (function cl -> (cl, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create cl.pci_name, Ident.create ("#" ^ cl.pci_name))) cls in Ctype.init_def (Ident.current_time ()); Ctype.begin_class_def (); let (res, env) = List.fold_left (initial_env define_class approx) ([], env) cls in let (res, env) = List.fold_right (class_infos define_class kind) res ([], env) in Ctype.end_def (); let res = List.rev_map (final_decl env define_class) res in let decls = List.fold_right extract_type_decls res [] in let decls = Typedecl.compute_variance_decls env decls in let res = List.map2 merge_type_decls res decls in let env = List.fold_left (final_env define_class) env res in let res = List.map (check_coercions env) res in (res, env) let class_num = ref 0 let class_declaration env sexpr = incr class_num; let expr = class_expr (string_of_int !class_num) env env sexpr in (expr, expr.cl_type) let class_description env sexpr = let expr = class_type env sexpr in (expr, expr) let class_declarations env cls = type_classes true approx_declaration class_declaration env cls let class_descriptions env cls = type_classes true approx_description class_description env cls let class_type_declarations env cls = let (decl, env) = type_classes false approx_description class_description env cls in (List.map (function (_, _, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, _, _, _) -> (ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr)) decl, env) let rec unify_parents env ty cl = match cl.cl_desc with Tclass_ident p -> begin try let decl = Env.find_class p env in let _, body = Ctype.find_cltype_for_path env decl.cty_path in Ctype.unify env ty (Ctype.instance body) with exn -> assert (exn = Not_found) end | Tclass_structure st -> unify_parents_struct env ty st | Tclass_fun (_, _, cl, _) | Tclass_apply (cl, _) | Tclass_let (_, _, _, cl) | Tclass_constraint (cl, _, _, _) -> unify_parents env ty cl and unify_parents_struct env ty st = List.iter (function Cf_inher (cl, _, _) -> unify_parents env ty cl | _ -> ()) st.cl_field let type_object env loc s = incr class_num; let (desc, sign) = class_structure (string_of_int !class_num) true env env loc s in let sty = Ctype.expand_head env sign.cty_self in Ctype.hide_private_methods sty; let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sty) in let meths = List.map (fun (s,_,_) -> s) fields in unify_parents_struct env sign.cty_self desc; (desc, sign, meths) let () = Typecore.type_object := type_object let approx_class sdecl = let self' = { ptyp_desc = Ptyp_any; ptyp_loc = Location.none } in let clty' = { pcty_desc = Pcty_signature(self', []); pcty_loc = sdecl.pci_expr.pcty_loc } in { sdecl with pci_expr = clty' } let approx_class_declarations env sdecls = fst (class_type_declarations env (List.map approx_class sdecls)) open Format let report_error ppf = function | Repeated_parameter -> fprintf ppf "A type parameter occurs several times" | Unconsistent_constraint trace -> fprintf ppf "The class constraints are not consistent.@."; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Field_type_mismatch (k, m, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The %s %s@ has type" k m) (function ppf -> fprintf ppf "but is expected to have type") | Structure_expected clty -> fprintf ppf "@[This class expression is not a class structure; it has type@ %a@]" Printtyp.class_type clty | Cannot_apply clty -> fprintf ppf "This class expression is not a class function, it cannot be applied" | Apply_wrong_label l -> let mark_label = function | "" -> "out label" | l -> sprintf " label ~%s" l in fprintf ppf "This argument cannot be applied with%s" (mark_label l) | Pattern_type_clash ty -> XXX Revoir message Printtyp.reset_and_mark_loops ty; fprintf ppf "@[%s@ %a@]" "This pattern cannot match self: it only matches values of type" Printtyp.type_expr ty | Unbound_class cl -> fprintf ppf "@[Unbound class@ %a@]" Printtyp.longident cl | Unbound_class_2 cl -> fprintf ppf "@[The class@ %a@ is not yet completely defined@]" Printtyp.longident cl | Unbound_class_type cl -> fprintf ppf "@[Unbound class type@ %a@]" Printtyp.longident cl | Unbound_class_type_2 cl -> fprintf ppf "@[The class type@ %a@ is not yet completely defined@]" Printtyp.longident cl | Abbrev_type_clash (abbrev, actual, expected) -> Printtyp.reset_and_mark_loops_list [abbrev; actual; expected]; fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \ but is used with type@ %a@]" Printtyp.type_expr abbrev Printtyp.type_expr actual Printtyp.type_expr expected | Constructor_type_mismatch (c, trace) -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The expression \"new %s\" has type" c) (function ppf -> fprintf ppf "but is used with type") | Virtual_class (cl, mets, vals) -> let print_mets ppf mets = List.iter (function met -> fprintf ppf "@ %s" met) mets in let cl_mark = if cl then "" else " type" in let missings = match mets, vals with [], _ -> "variables" | _, [] -> "methods" | _ -> "methods and variables" in fprintf ppf "@[This class%s should be virtual.@ \ @[<2>The following %s are undefined :%a@]@]" cl_mark missings print_mets (mets @ vals) | Parameter_arity_mismatch(lid, expected, provided) -> fprintf ppf "@[The class constructor %a@ expects %i type argument(s),@ \ but is here applied to %i type argument(s)@]" Printtyp.longident lid expected provided | Parameter_mismatch trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "The type parameter") (function ppf -> fprintf ppf "does not meet its constraint: it should be") | Bad_parameters (id, params, cstrs) -> Printtyp.reset_and_mark_loops_list [params; cstrs]; fprintf ppf "@[The abbreviation %a@ is used with parameters@ %a@ \ wich are incompatible with constraints@ %a@]" Printtyp.ident id Printtyp.type_expr params Printtyp.type_expr cstrs | Class_match_failure error -> Includeclass.report_error ppf error | Unbound_val lab -> fprintf ppf "Unbound instance variable %s" lab | Unbound_type_var (printer, reason) -> let print_common ppf kind ty0 real lab ty = let ty1 = if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in Printtyp.mark_loops ty1; fprintf ppf "The %s %s@ has type@;<1 2>%a@ where@ %a@ is unbound" kind lab Printtyp.type_expr ty Printtyp.type_expr ty0 in let print_reason ppf = function | Ctype.CC_Method (ty0, real, lab, ty) -> print_common ppf "method" ty0 real lab ty | Ctype.CC_Value (ty0, real, lab, ty) -> print_common ppf "instance variable" ty0 real lab ty in Printtyp.reset (); fprintf ppf "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \ @[%a@]@]" printer print_reason reason | Make_nongen_seltype ty -> fprintf ppf "@[<v>@[Self type should not occur in the non-generic type@;<1 2>\ %a@]@,\ It would escape the scope of its class@]" Printtyp.type_scheme ty | Non_generalizable_class (id, clty) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains type variables that cannot be generalized@]" (Printtyp.class_declaration id) clty | Cannot_coerce_self ty -> fprintf ppf "@[The type of self cannot be coerced to@ \ the type of the current class:@ %a.@.\ Some occurences are contravariant@]" Printtyp.type_scheme ty | Non_collapsable_conjunction (id, clty, trace) -> fprintf ppf "@[The type of this class,@ %a,@ \ contains non-collapsable conjunctive types in constraints@]" (Printtyp.class_declaration id) clty; Printtyp.report_unification_error ppf trace (fun ppf -> fprintf ppf "Type") (fun ppf -> fprintf ppf "is not compatible with type") | Final_self_clash trace -> Printtyp.report_unification_error ppf trace (function ppf -> fprintf ppf "This object is expected to have type") (function ppf -> fprintf ppf "but has actually type") | Mutability_mismatch (lab, mut) -> let mut1, mut2 = if mut = Immutable then "mutable", "immutable" else "immutable", "mutable" in fprintf ppf "@[The instance variable is %s,@ it cannot be redefined as %s@]" mut1 mut2
e7365c5a3007f9a847ddde2179c683068e7f70309019a9fb746cf43dd3515aee
lem-project/lem
yason-utils.lisp
(defpackage :lem-lsp-base/yason-utils (:use :cl) (:import-from :bordeaux-threads :*default-special-bindings*) (:export :with-yason-bindings :parse-json)) (in-package :lem-lsp-base/yason-utils) (defparameter *yason-bindings* '((yason:*parse-json-null-as-keyword* . t) (yason:*parse-json-arrays-as-vectors* . t))) (defmacro with-yason-bindings (() &body body) `(call-with-yason-bindings (lambda () ,@body))) (defun call-with-yason-bindings (function) (let ((*default-special-bindings* (append *yason-bindings* *default-special-bindings*))) (progv (mapcar #'car *yason-bindings*) (mapcar #'cdr *yason-bindings*) (funcall function)))) (defun parse-json (input) (with-yason-bindings () (yason:parse input)))
null
https://raw.githubusercontent.com/lem-project/lem/241587211277ac628a9c1ed96d512ac81235bb09/lib/lsp-base/yason-utils.lisp
lisp
(defpackage :lem-lsp-base/yason-utils (:use :cl) (:import-from :bordeaux-threads :*default-special-bindings*) (:export :with-yason-bindings :parse-json)) (in-package :lem-lsp-base/yason-utils) (defparameter *yason-bindings* '((yason:*parse-json-null-as-keyword* . t) (yason:*parse-json-arrays-as-vectors* . t))) (defmacro with-yason-bindings (() &body body) `(call-with-yason-bindings (lambda () ,@body))) (defun call-with-yason-bindings (function) (let ((*default-special-bindings* (append *yason-bindings* *default-special-bindings*))) (progv (mapcar #'car *yason-bindings*) (mapcar #'cdr *yason-bindings*) (funcall function)))) (defun parse-json (input) (with-yason-bindings () (yason:parse input)))
b6eb13a9265073a24904536d9a76a836bd26e4e89c2bc9c78ee44bbfbb9484d7
marcelosousa/llvmvf
Function.hs
# LANGUAGE UnicodeSyntax # ------------------------------------------------------------------------------- -- Module : Analysis.Type.Inference.Function Copyright : ( c ) 2013 -- Type Constraints Function ------------------------------------------------------------------------------- module Analysis.Type.Inference.Function where import Language.LLVMIR import Analysis.Type.Inference.Base import Analysis.Type.Inference.Instruction import Analysis.Type.Inference.Initial import Analysis.Type.Memory.Util import Analysis.Type.Memory.TyAnn instance TyConstr Function where -- τℂ ∷ → Function → State Γ (S.Set Τℂ) τℂ (FunctionDef n _ τ _ ς bbs) = do let πτ = ℂτ $ (↑)τ πς = map π ς πn = ℂp (ℂλ πς πτ) AnyAddr nℂ = liftΤℂ 0 $ (ℂπ n) :=: πn ∘ ε ςℂs ← τList nℂ ς νfn (n,πς) τList ςℂs bbs τℂ (FunctionDecl n _ τ _ ς) = (↣) ε instance TyConstr Parameter where τℂ (Parameter n τ) = do let τα = (↑)τ nℂ = (ℂπ n) :=: (ℂτ τα) ∘ ε (↣) $ liftΤℂ 0 nℂ instance Constr Parameter where π (Parameter n τ) = ℂπ n instance TyConstr BasicBlock where τℂ (BasicBlock n φs is tmn) = do νbb n φℂs ← τList ε φs isℂs ← τList φℂs is tmnℂs ← τℂ tmn (↣) $ isℂs ∪ tmnℂs ∪ (liftΤℂ 0 iτℂ)
null
https://raw.githubusercontent.com/marcelosousa/llvmvf/c314e43aa8bc8bb7fd9c83cebfbdcabee4ecfe1b/src/Analysis/Type/Inference/Function.hs
haskell
----------------------------------------------------------------------------- Module : Analysis.Type.Inference.Function Type Constraints Function ----------------------------------------------------------------------------- τℂ ∷ → Function → State Γ (S.Set Τℂ)
# LANGUAGE UnicodeSyntax # Copyright : ( c ) 2013 module Analysis.Type.Inference.Function where import Language.LLVMIR import Analysis.Type.Inference.Base import Analysis.Type.Inference.Instruction import Analysis.Type.Inference.Initial import Analysis.Type.Memory.Util import Analysis.Type.Memory.TyAnn instance TyConstr Function where τℂ (FunctionDef n _ τ _ ς bbs) = do let πτ = ℂτ $ (↑)τ πς = map π ς πn = ℂp (ℂλ πς πτ) AnyAddr nℂ = liftΤℂ 0 $ (ℂπ n) :=: πn ∘ ε ςℂs ← τList nℂ ς νfn (n,πς) τList ςℂs bbs τℂ (FunctionDecl n _ τ _ ς) = (↣) ε instance TyConstr Parameter where τℂ (Parameter n τ) = do let τα = (↑)τ nℂ = (ℂπ n) :=: (ℂτ τα) ∘ ε (↣) $ liftΤℂ 0 nℂ instance Constr Parameter where π (Parameter n τ) = ℂπ n instance TyConstr BasicBlock where τℂ (BasicBlock n φs is tmn) = do νbb n φℂs ← τList ε φs isℂs ← τList φℂs is tmnℂs ← τℂ tmn (↣) $ isℂs ∪ tmnℂs ∪ (liftΤℂ 0 iτℂ)
4ea7a102808091a185df202488771af77f032b7b46867b1186823cd5b0c0b2dd
TyOverby/mono
main.ml
open! Core let () = print_endline ""
null
https://raw.githubusercontent.com/TyOverby/mono/9e3d64c1e3fdf536b3e62fae7f7ff7107d710342/lib/furby/bin/main.ml
ocaml
open! Core let () = print_endline ""
f063290e3773bc6bcd5294a0b6e07b135b3747e0f1f7bdc05ee3b48593dc3d61
alanb2718/wallingford
pulser.rkt
#lang s-exp rosette ; pulsing circle example (require "reactive.rkt") (require "pulser-class.rkt") make a new pulser and a viewer on it : (define p (new pulser%)) (make-viewer p #:title "Pulser")
null
https://raw.githubusercontent.com/alanb2718/wallingford/9dd436c29f737d210c5b87dc1b86b2924c0c5970/reactive/pulser.rkt
racket
pulsing circle example
#lang s-exp rosette (require "reactive.rkt") (require "pulser-class.rkt") make a new pulser and a viewer on it : (define p (new pulser%)) (make-viewer p #:title "Pulser")
5062ff8ccafb84e6417390ffade5a6ea103b79d080b3d598b57441e934a21b18
xapi-project/xcp-networkd
network_server.ml
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Network_utils open Network_interface module S = Network_interface.Interface_API (Idl.Exn.GenServer ()) module D = Debug.Make (struct let name = "network_server" end) open D type context = unit let network_conf = ref "/etc/xcp/network.conf" let config : config_t ref = ref Network_config.empty_config let backend_kind = ref Openvswitch let write_config () = try Network_config.write_config !config with Network_config.Write_error -> () let read_config () = try config := Network_config.read_config () ; debug "Read configuration from networkd.db file." with Network_config.Read_error -> ( try No configuration file found . Try to get the initial network setup from * the first - boot data written by the host installer . * the first-boot data written by the host installer. *) config := Network_config.read_management_conf () ; debug "Read configuration from management.conf file." with Network_config.Read_error -> debug "Could not interpret the configuration in management.conf" ) let on_shutdown signal = let dbg = "shutdown" in Debug.with_thread_associated dbg (fun () -> debug "xcp-networkd caught signal %d; performing cleanup actions." signal ; write_config ()) () let on_timer () = write_config () let clear_state () = config := Network_config.empty_config let reset_state () = config := Network_config.read_management_conf () let set_gateway_interface _dbg name = (* Remove dhclient conf (if any) for the old and new gateway interfaces. * This ensures that dhclient gets restarted with an updated conf file when * necessary. *) ( match !config.gateway_interface with | Some old_iface when name <> old_iface -> Dhclient.remove_conf_file name ; Dhclient.remove_conf_file old_iface | _ -> () ) ; debug "Setting gateway interface to %s" name ; config := {!config with gateway_interface= Some name} let set_dns_interface _dbg name = Remove dhclient conf ( if any ) for the old and new DNS interfaces . * This ensures that dhclient gets restarted with an updated conf file when * necessary . * This ensures that dhclient gets restarted with an updated conf file when * necessary. *) ( match !config.dns_interface with | Some old_iface when name <> old_iface -> Dhclient.remove_conf_file name ; Dhclient.remove_conf_file old_iface | _ -> () ) ; debug "Setting DNS interface to %s" name ; config := {!config with dns_interface= Some name} The enic driver is for Cisco UCS devices . The current driver adds VLAN0 headers * to all incoming packets , which confuses certain guests OSes . The workaround * constitutes adding a VLAN0 Linux device to strip those headers again . * to all incoming packets, which confuses certain guests OSes. The workaround * constitutes adding a VLAN0 Linux device to strip those headers again. *) let need_enic_workaround () = !backend_kind = Bridge && List.mem "enic" (Sysfs.list_drivers ()) module Sriov = struct open S.Sriov let get_capabilities dev = let open Rresult.R.Infix in let maxvfs_modprobe = Sysfs.get_driver_name_err dev >>= fun driver -> Modprobe.get_config_from_comments driver |> Modprobe.get_maxvfs driver and maxvfs_sysfs = Sysfs.get_sriov_maxvfs dev in let is_support = match (maxvfs_modprobe, maxvfs_sysfs) with | Ok v, _ -> v > 0 | Error _, Ok v -> v > 0 | _ -> false in if is_support then ["sriov"] else [] let config_sriov ~enable dev = let op = if enable then "enable" else "disable" in let open Rresult.R.Infix in Sysfs.get_driver_name_err dev >>= fun driver -> let config = Modprobe.get_config_from_comments driver in match Modprobe.get_vf_param config with | Some vf_param -> debug "%s SR-IOV on a device: %s via modprobe" op dev ; (if enable then Modprobe.get_maxvfs driver config else Ok 0) >>= fun numvfs -> CA-287340 : Even if the current numvfs equals to the target numvfs , it is still needed to update SR - IOV modprobe config file , as the SR - IOV enabing takes effect after reboot . For example , a user enables SR - IOV and disables it immediately without a reboot . is still needed to update SR-IOV modprobe config file, as the SR-IOV enabing takes effect after reboot. For example, a user enables SR-IOV and disables it immediately without a reboot.*) Modprobe.config_sriov driver vf_param numvfs >>= fun _ -> if numvfs = Sysfs.get_sriov_numvfs dev then Ok Modprobe_successful else Ok Modprobe_successful_requires_reboot | None -> enable : try interface to set numfvs = maxvfs . if fails , but vfs are enabled , assume manual configuration . disable : Net.Sriov.disable will not be called for manually configured interfaces , as determined by ` require_operation_on_pci_device ` disable: Net.Sriov.disable will not be called for manually configured interfaces, as determined by `require_operation_on_pci_device` *) let man_successful () = debug "SR-IOV/VFs %sd manually on device: %s" op dev ; Manual_successful in if enable then let present_numvfs = Sysfs.get_sriov_numvfs dev in match Sysfs.get_sriov_maxvfs dev >>= fun maxvfs -> maxvfs |> Sysfs.set_sriov_numvfs dev with | Ok _ -> debug "%s SR-IOV on a device: %s via sysfs" op dev ; Ok Sysfs_successful | Error _ when present_numvfs > 0 -> Ok (man_successful ()) | exception _ when present_numvfs > 0 -> Ok (man_successful ()) | Error err -> Error err | exception e -> let msg = Printf.sprintf "Error: trying sysfs SR-IOV interface failed with exception \ %s on device: %s" (Printexc.to_string e) dev in Error (Other, msg) else Sysfs.unbind_child_vfs dev >>= fun () -> Sysfs.set_sriov_numvfs dev 0 >>= fun _ -> debug "%s SR-IOV on a device: %s via sysfs" op dev ; Ok Sysfs_successful let enable dbg name = Debug.with_thread_associated dbg (fun () -> debug "Enable network SR-IOV by name: %s" name ; match config_sriov ~enable:true name with | Ok t -> (Ok t : enable_result) | Result.Error (_, msg) -> warn "Failed to enable SR-IOV on %s with error: %s" name msg ; Error msg) () let disable dbg name = Debug.with_thread_associated dbg (fun () -> debug "Disable network SR-IOV by name: %s" name ; match config_sriov ~enable:false name with | Ok _ -> (Ok : disable_result) | Result.Error (_, msg) -> warn "Failed to disable SR-IOV on %s with error: %s" name msg ; Error msg) () let make_vf_conf_internal pcibuspath mac vlan rate = let config_or_otherwise_reset config_f reset_f = function | None -> reset_f () | Some a -> config_f a in let open Rresult.R.Infix in Sysfs.parent_device_of_vf pcibuspath >>= fun dev -> Sysfs.device_index_of_vf dev pcibuspath >>= fun index -> config_or_otherwise_reset (Ip.set_vf_mac dev index) (fun () -> Result.Ok ()) mac >>= fun () -> In order to ensure the Networkd to be idempotent , configuring VF with no VLAN and rate have to reset vlan and rate , since the VF might have previous configuration . Refering to -bin/man/man2html?ip-link+8 , set VLAN and rate to 0 means to reset them VLAN and rate have to reset vlan and rate, since the VF might have previous configuration. Refering to -bin/man/man2html?ip-link+8, set VLAN and rate to 0 means to reset them *) config_or_otherwise_reset (Ip.set_vf_vlan dev index) (fun () -> Ip.set_vf_vlan dev index 0) vlan >>= fun () -> config_or_otherwise_reset (Ip.set_vf_rate dev index) (fun () -> Ip.set_vf_rate dev index 0) rate let make_vf_config dbg pci_address (vf_info : sriov_pci_t) = Debug.with_thread_associated dbg (fun () -> let vlan = Option.map Int64.to_int vf_info.vlan and rate = Option.map Int64.to_int vf_info.rate and pcibuspath = Xcp_pci.string_of_address pci_address in debug "Config VF with pci address: %s" pcibuspath ; match make_vf_conf_internal pcibuspath vf_info.mac vlan rate with | Result.Ok () -> (Ok : config_result) | Result.Error (Fail_to_set_vf_rate, msg) -> debug "%s" msg ; Error Config_vf_rate_not_supported | Result.Error (_, msg) -> debug "%s" msg ; Error (Unknown msg)) () end module Interface = struct let get_config name = get_config !config.interface_config default_interface name let update_config name data = config := { !config with interface_config= update_config !config.interface_config name data } let get_all dbg () = Debug.with_thread_associated dbg (fun () -> Sysfs.list ()) () let exists dbg name = Debug.with_thread_associated dbg (fun () -> List.mem name (Sysfs.list ())) () let get_mac dbg name = Debug.with_thread_associated dbg (fun () -> match Linux_bonding.get_bond_master_of name with | Some master -> Proc.get_bond_slave_mac master name | None -> Ip.get_mac name) () let get_pci_bus_path dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.get_pcibuspath name) () let is_up dbg name = Debug.with_thread_associated dbg (fun () -> if List.mem name (Sysfs.list ()) then Ip.is_up name else false) () let get_ipv4_addr dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_ipv4 name) () let set_ipv4_conf dbg name conf = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 address for %s: %s" name (conf |> Rpcmarshal.marshal typ_of_ipv4 |> Jsonrpc.to_string) ; update_config name {(get_config name) with ipv4_conf= conf} ; match conf with | None4 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running name then ignore (Dhclient.stop name) ; Ip.flush_ip_addr name ) | DHCP4 -> let gateway = Option.fold ~none:[] ~some:(fun n -> [`gateway n]) !config.gateway_interface in let dns = Option.fold ~none:[] ~some:(fun n -> [`dns n]) !config.dns_interface in let options = gateway @ dns in Dhclient.ensure_running name options | Static4 addrs -> if Dhclient.is_running name then ( ignore (Dhclient.stop name) ; Ip.flush_ip_addr name ) ; (* the function is meant to be idempotent and we want to avoid CA-239919 *) let cur_addrs = Ip.get_ipv4 name in let rm_addrs = Xapi_stdext_std.Listext.List.set_difference cur_addrs addrs in let add_addrs = Xapi_stdext_std.Listext.List.set_difference addrs cur_addrs in List.iter (Ip.del_ip_addr name) rm_addrs ; List.iter (Ip.set_ip_addr name) add_addrs) () let get_ipv4_gateway dbg name = Debug.with_thread_associated dbg (fun () -> let output = Ip.route_show ~version:Ip.V4 name in try let line = List.find (fun s -> Astring.String.is_prefix ~affix:"default via" s) (Astring.String.cuts ~empty:false ~sep:"\n" output) in let addr = List.nth (Astring.String.cuts ~empty:false ~sep:" " line) 2 in Some (Unix.inet_addr_of_string addr) with Not_found -> None) () let set_ipv4_gateway _ dbg ~name ~address = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 gateway for %s: %s" name (Unix.string_of_inet_addr address) ; update_config name {(get_config name) with ipv4_gateway= Some address} ; if !config.gateway_interface = None || !config.gateway_interface = Some name then ( debug "%s is the default gateway interface" name ; Ip.set_gateway name address ) else debug "%s is NOT the default gateway interface" name) () let get_ipv6_addr dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_ipv6 name) () let set_ipv6_conf _ dbg ~name ~conf = Debug.with_thread_associated dbg (fun () -> if Proc.get_ipv6_disabled () then warn "Not configuring IPv6 address for %s (IPv6 is disabled)" name else ( debug "Configuring IPv6 address for %s: %s" name (conf |> Rpcmarshal.marshal typ_of_ipv6 |> Jsonrpc.to_string) ; update_config name {(get_config name) with ipv6_conf= conf} ; match conf with | None6 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ) | Linklocal6 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ) | DHCP6 -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ; ignore (Dhclient.ensure_running ~ipv6:true name []) | Autoconf6 -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ; Sysctl.set_ipv6_autoconf name true Can not link set down / up due to CA-89882 - IPv4 default route cleared cleared *) | Static6 addrs -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; (* add the link_local and clean the old one only when needed *) let cur_addrs = let addrs = Ip.get_ipv6 name in let maybe_link_local = Ip.split_addr (Ip.get_ipv6_link_local_addr name) in match maybe_link_local with | Some addr -> Xapi_stdext_std.Listext.List.setify (addr :: addrs) | None -> addrs in let rm_addrs = Xapi_stdext_std.Listext.List.set_difference cur_addrs addrs in let add_addrs = Xapi_stdext_std.Listext.List.set_difference addrs cur_addrs in List.iter (Ip.del_ip_addr name) rm_addrs ; List.iter (Ip.set_ip_addr name) add_addrs )) () let set_ipv6_gateway _ dbg ~name ~address = Debug.with_thread_associated dbg (fun () -> if Proc.get_ipv6_disabled () then warn "Not configuring IPv6 gateway for %s (IPv6 is disabled)" name else ( debug "Configuring IPv6 gateway for %s: %s" name (Unix.string_of_inet_addr address) ; update_config name {(get_config name) with ipv6_gateway= Some address} ; if !config.gateway_interface = None || !config.gateway_interface = Some name then ( debug "%s is the default gateway interface" name ; Ip.set_gateway name address ) else debug "%s is NOT the default gateway interface" name )) () let set_ipv4_routes _ dbg ~name ~routes = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 static routes for %s: %s" name (String.concat ", " (List.map (fun r -> Printf.sprintf "%s/%d/%s" (Unix.string_of_inet_addr r.subnet) r.netmask (Unix.string_of_inet_addr r.gateway)) routes)) ; update_config name {(get_config name) with ipv4_routes= routes} ; List.iter (fun r -> Ip.set_route ~network:(r.subnet, r.netmask) name r.gateway) routes) () let get_dns dbg _name = Debug.with_thread_associated dbg (fun () -> let nameservers, domains = Xapi_stdext_unix.Unixext.file_lines_fold (fun (nameservers, domains) line -> if Astring.String.is_prefix ~affix:"nameserver" line then let server = List.nth (Astring.String.fields ~empty:false line) 1 in (Unix.inet_addr_of_string server :: nameservers, domains) else if Astring.String.is_prefix ~affix:"search" line then let domains = List.tl (Astring.String.fields ~empty:false line) in (nameservers, domains) else (nameservers, domains)) ([], []) resolv_conf in (List.rev nameservers, domains)) () let set_dns _ dbg ~name ~nameservers ~domains = Debug.with_thread_associated dbg (fun () -> update_config name {(get_config name) with dns= (nameservers, domains)} ; debug "Configuring DNS for %s: nameservers: [%s]; domains: [%s]" name (String.concat ", " (List.map Unix.string_of_inet_addr nameservers)) (String.concat ", " domains) ; if !config.dns_interface = None || !config.dns_interface = Some name then ( debug "%s is the DNS interface" name ; let domains' = if domains <> [] then ["search " ^ String.concat " " domains] else [] in let nameservers' = List.map (fun ip -> "nameserver " ^ Unix.string_of_inet_addr ip) nameservers in let lines = domains' @ nameservers' in Xapi_stdext_unix.Unixext.write_string_to_file resolv_conf (String.concat "\n" lines ^ "\n") ) else debug "%s is NOT the DNS interface" name) () let get_mtu dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_mtu name) () let set_mtu _ dbg ~name ~mtu = Debug.with_thread_associated dbg (fun () -> debug "Configuring MTU for %s: %d" name mtu ; update_config name {(get_config name) with mtu} ; match !backend_kind with | Openvswitch -> ( try ignore (Ovs.set_mtu name mtu) with _ -> Ip.link_set_mtu name mtu ) | Bridge -> Ip.link_set_mtu name mtu) () let set_ethtool_settings _ dbg ~name ~params = Debug.with_thread_associated dbg (fun () -> debug "Configuring ethtool settings for %s: %s" name (String.concat ", " (List.map (fun (k, v) -> k ^ "=" ^ v) params)) ; let add_defaults = List.filter (fun (k, _) -> not (List.mem_assoc k params)) default_interface.ethtool_settings in let params = params @ add_defaults in update_config name {(get_config name) with ethtool_settings= params} ; Ethtool.set_options name params) () let set_ethtool_offload _ dbg ~name ~params = Debug.with_thread_associated dbg (fun () -> debug "Configuring ethtool offload settings for %s: %s" name (String.concat ", " (List.map (fun (k, v) -> k ^ "=" ^ v) params)) ; let add_defaults = List.filter (fun (k, _) -> not (List.mem_assoc k params)) default_interface.ethtool_offload in let params = params @ add_defaults in update_config name {(get_config name) with ethtool_offload= params} ; Ethtool.set_offload name params) () let get_capabilities dbg name = Debug.with_thread_associated dbg (fun () -> Fcoe.get_capabilities name @ Sriov.get_capabilities name) () let is_connected dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.get_carrier name) () let is_physical dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.is_physical name) () let has_vlan dbg name vlan = Identify the vlan is used by kernel which is unknown to Debug.with_thread_associated dbg (fun () -> let temp_interfaces = Sysfs.bridge_to_interfaces Network_config.temp_vlan in List.exists (fun (d, v, p) -> v = vlan && p = name && not (List.mem d temp_interfaces)) (Proc.get_vlans ())) () let bring_up _ dbg ~name = Debug.with_thread_associated dbg (fun () -> debug "Bringing up interface %s" name ; Ip.link_set_up name) () let bring_down dbg name = Debug.with_thread_associated dbg (fun () -> debug "Bringing down interface %s" name ; Ip.link_set_down name) () let set_persistent dbg name value = Debug.with_thread_associated dbg (fun () -> debug "Making interface %s %spersistent" name (if value then "" else "non-") ; update_config name {(get_config name) with persistent_i= value}) () let make_config dbg conservative config = Debug.with_thread_associated dbg (fun () -> (* Only attempt to configure interfaces that exist in the system *) let all = get_all dbg () in let config = List.filter (fun (name, _) -> List.mem name all) config in (* Handle conservativeness *) let config = if conservative then ( (* Do not touch non-persistent interfaces *) debug "Only configuring persistent interfaces" ; List.filter (fun (_name, interface) -> interface.persistent_i) config ) else config in let config = if need_enic_workaround () then List.fold_left (fun accu (name, interface) -> if Sysfs.is_physical name && Linux_bonding.get_bond_master_of name = None || Linux_bonding.is_bond_device name then (name, interface) :: (Ip.vlan_name name 0, interface) :: accu else (name, interface) :: accu) [] config else config in debug "** Configuring the following interfaces: %s%s" (String.concat ", " (List.map (fun (name, _) -> name) config)) (if conservative then " (best effort)" else "") ; let exec f = if conservative then try f () with _ -> () else f () in List.iter (function | ( name , ( { ipv4_conf ; ipv4_gateway ; ipv6_conf ; ipv6_gateway ; ipv4_routes ; dns= nameservers, domains ; mtu ; ethtool_settings ; ethtool_offload ; _ } as c ) ) -> update_config name c ; exec (fun () -> We only apply the DNS settings when not in a DHCP mode to avoid conflicts . The ` dns ` field should really be an option type so that we do n't have to derive the intention of the caller by looking at other fields . to avoid conflicts. The `dns` field should really be an option type so that we don't have to derive the intention of the caller by looking at other fields. *) match (ipv4_conf, ipv6_conf) with | Static4 _, _ | _, Static6 _ | _, Autoconf6 -> set_dns () dbg ~name ~nameservers ~domains | _ -> ()) ; exec (fun () -> set_ipv4_conf dbg name ipv4_conf) ; exec (fun () -> match ipv4_gateway with | None -> () | Some gateway -> set_ipv4_gateway () dbg ~name ~address:gateway) ; (try set_ipv6_conf () dbg ~name ~conf:ipv6_conf with _ -> ()) ; ( try match ipv6_gateway with | None -> () | Some gateway -> set_ipv6_gateway () dbg ~name ~address:gateway with _ -> () ) ; exec (fun () -> set_ipv4_routes () dbg ~name ~routes:ipv4_routes) ; exec (fun () -> set_mtu () dbg ~name ~mtu) ; exec (fun () -> bring_up () dbg ~name) ; exec (fun () -> set_ethtool_settings () dbg ~name ~params:ethtool_settings) ; exec (fun () -> set_ethtool_offload () dbg ~name ~params:ethtool_offload)) config) () end module Bridge = struct let add_default = ref [] let get_config name = get_config !config.bridge_config default_bridge name let remove_config name = config := {!config with bridge_config= remove_config !config.bridge_config name} let update_config name data = config := { !config with bridge_config= update_config !config.bridge_config name data } let determine_backend () = try let backend = String.trim (Xapi_stdext_unix.Unixext.string_of_file !network_conf) in match backend with | "openvswitch" | "vswitch" -> backend_kind := Openvswitch | "bridge" -> backend_kind := Bridge | backend -> warn "Network backend unknown (%s). Falling back to Open vSwitch." backend ; backend_kind := Openvswitch with _ -> warn "Network-conf file not found. Falling back to Open vSwitch." ; backend_kind := Openvswitch let get_all dbg () = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.list_bridges () | Bridge -> Sysfs.get_all_bridges ()) () Destroy any existing bridge that is n't the " wanted bridge " and has the * given VLAN on it . * given VLAN on it. *) let destroy_existing_vlan_ovs_bridge dbg wanted_bridge (parent, vlan) = let vlan_bridges = let raw = Ovs.vsctl [ "--bare" ; "-f" ; "table" ; "--" ; "--columns=name" ; "find" ; "port" ; "fake_bridge=true" ; "tag=" ^ string_of_int vlan ] in if raw <> "" then Astring.String.cuts ~empty:false ~sep:"\n" (String.trim raw) else [] in let existing_bridges = List.filter (fun bridge -> match Ovs.bridge_to_vlan bridge with | Some (p, v) -> p = parent && v = vlan | None -> false) vlan_bridges in List.iter (fun bridge -> if bridge <> wanted_bridge then ( debug "Destroying existing bridge %s" bridge ; remove_config bridge ; Interface.set_ipv4_conf dbg bridge None4 ; ignore (Ovs.destroy_bridge bridge) )) existing_bridges Destroy any existing Linux bridge that is n't the " wanted bridge " and has the * given VLAN on it . * given VLAN on it. *) let destroy_existing_vlan_linux_bridge dbg wanted_bridge vlan_device = List.iter (fun bridge -> if bridge <> wanted_bridge then let ifaces_on_bridge = Sysfs.bridge_to_interfaces bridge in if List.mem vlan_device ifaces_on_bridge then ( debug "Destroying existing bridge %s" bridge ; Interface.bring_down dbg bridge ; remove_config bridge ; Interface.set_ipv4_conf dbg bridge None4 ; List.iter (fun dev -> Brctl.destroy_port bridge dev) ifaces_on_bridge ; ignore (Brctl.destroy_bridge bridge) )) (Sysfs.get_all_bridges ()) let create dbg vlan mac igmp_snooping other_config name = Debug.with_thread_associated dbg (fun () -> let other_config = match other_config with Some l -> l | None -> [] in debug "Creating bridge %s%s" name ( match vlan with | None -> "" | Some (parent, vlan) -> Printf.sprintf " (VLAN %d on bridge %s)" vlan parent ) ; update_config name { (get_config name) with vlan ; bridge_mac= mac ; igmp_snooping ; other_config } ; ( match !backend_kind with | Openvswitch -> let fail_mode = if not (List.mem_assoc "vswitch-controller-fail-mode" other_config) then "standalone" else let mode = List.assoc "vswitch-controller-fail-mode" other_config in if mode = "secure" || mode = "standalone" then ( ( try if mode = "secure" && Ovs.get_fail_mode name <> "secure" then add_default := name :: !add_default with _ -> () ) ; mode ) else ( debug "%s isn't a valid setting for \ other_config:vswitch-controller-fail-mode; defaulting to \ 'standalone'" mode ; "standalone" ) in let vlan_bug_workaround = if List.mem_assoc "vlan-bug-workaround" other_config then Some (List.assoc "vlan-bug-workaround" other_config = "true") else None in let external_id = if List.mem_assoc "network-uuids" other_config then Some ("xs-network-uuids", List.assoc "network-uuids" other_config) else None in let disable_in_band = if not (List.mem_assoc "vswitch-disable-in-band" other_config) then Some None else let dib = List.assoc "vswitch-disable-in-band" other_config in if dib = "true" || dib = "false" then Some (Some dib) else ( debug "%s isn't a valid setting for \ other_config:vswitch-disable-in-band" dib ; None ) in let old_igmp_snooping = Ovs.get_mcast_snooping_enable ~name in Option.iter (destroy_existing_vlan_ovs_bridge dbg name) vlan ; ignore (Ovs.create_bridge ?mac ~fail_mode ?external_id ?disable_in_band ?igmp_snooping vlan vlan_bug_workaround name) ; if igmp_snooping = Some true && not old_igmp_snooping then Ovs.inject_igmp_query ~name | Bridge -> ( ignore (Brctl.create_bridge name) ; Brctl.set_forwarding_delay name 0 ; Sysfs.set_multicast_snooping name false ; Option.iter (Ip.set_mac name) mac ; match vlan with | None -> () | Some (parent, vlan) -> let bridge_interfaces = Sysfs.bridge_to_interfaces name in let parent_bridge_interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) (Sysfs.bridge_to_interfaces parent) in let parent_bridge_interface = match parent_bridge_interfaces with | [] -> let msg = Printf.sprintf {|Interface for bridge parent "%s" of vlan %i not found|} parent vlan in error "%s" msg ; raise (Network_error (Internal_error msg)) | iface :: _ -> iface in let parent_interface = if need_enic_workaround () then ( let n = String.length parent_bridge_interface in let m = String.sub parent_bridge_interface 0 (n - 2) in if vlan = 0 then error "The enic workaround is in effect. Bridge %s is used \ for VLAN 0 on %s." parent m ; m ) else parent_bridge_interface in let vlan_name = Ip.vlan_name parent_interface vlan in destroy_existing_vlan_linux_bridge dbg name vlan_name ; Check if the VLAN is already in use by something else List.iter (fun (device, vlan', parent') -> A device for the same VLAN ( parent + tag ) , but with a different * device name or not on the requested bridge is bad . different * device name or not on the requested bridge is bad. *) if parent' = parent && vlan' = vlan && (device <> vlan_name || not (List.mem device bridge_interfaces) ) then raise (Network_error (Vlan_in_use (parent, vlan)))) (Proc.get_vlans ()) ; Robustness enhancement : ensure there are no other VLANs in the bridge the bridge *) let current_interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) bridge_interfaces in debug "Removing these non-VIF interfaces found on the bridge: %s" (String.concat ", " current_interfaces) ; List.iter (fun interface -> Brctl.destroy_port name interface ; Interface.bring_down dbg interface) current_interfaces ; Now create the new VLAN device and add it to the bridge Ip.create_vlan parent_interface vlan ; Interface.bring_up () dbg ~name:vlan_name ; Brctl.create_port name vlan_name ) ) ; Interface.bring_up () dbg ~name) () let destroy dbg force name = Debug.with_thread_associated dbg (fun () -> Interface.bring_down dbg name ; match !backend_kind with | Openvswitch -> let vlans_on_this_parent = Ovs.get_vlans name in if vlans_on_this_parent = [] || force then ( debug "Destroying bridge %s" name ; remove_config name ; let interfaces = Ovs.bridge_to_interfaces name @ vlans_on_this_parent in List.iter (fun dev -> Interface.set_ipv4_conf dbg dev None4 ; Interface.bring_down dbg dev) interfaces ; Interface.set_ipv4_conf dbg name None4 ; ignore (Ovs.destroy_bridge name) ) else debug "Not destroying bridge %s, because it has VLANs on top" name | Bridge -> let ifs = Sysfs.bridge_to_interfaces name in let vlans_on_this_parent = let interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) ifs in match interfaces with | [] -> [] | interface :: _ -> List.filter (Astring.String.is_prefix ~affix:(interface ^ ".")) (Sysfs.list ()) in if vlans_on_this_parent = [] || force then ( debug "Destroying bridge %s" name ; remove_config name ; List.iter (fun dev -> Interface.set_ipv4_conf dbg dev None4 ; Brctl.destroy_port name dev ; Interface.bring_down dbg dev ; if Linux_bonding.is_bond_device dev then Linux_bonding.remove_bond_master dev ; if (Astring.String.is_prefix ~affix:"eth" dev || Astring.String.is_prefix ~affix:"bond" dev ) && String.contains dev '.' then ( ignore (Ip.destroy_vlan dev) ; let n = String.length dev in if String.sub dev (n - 2) 2 = ".0" && need_enic_workaround () then let vlan_base = String.sub dev 0 (n - 2) in if Linux_bonding.is_bond_device vlan_base then Linux_bonding.remove_bond_master (String.sub dev 0 (n - 2)) )) ifs ; Interface.set_ipv4_conf dbg name None4 ; ignore (Brctl.destroy_bridge name) ) else debug "Not destroying bridge %s, because it has VLANs on top" name) () let get_kind dbg () = Debug.with_thread_associated dbg (fun () -> !backend_kind) () let get_all_ports dbg from_cache = Debug.with_thread_associated dbg (fun () -> if from_cache then let ports = List.concat (List.map (fun (_, {ports; _}) -> ports) !config.bridge_config) in List.map (fun (port, {interfaces; _}) -> (port, interfaces)) ports else match !backend_kind with | Openvswitch -> List.concat (List.map Ovs.bridge_to_ports (Ovs.list_bridges ())) | Bridge -> raise (Network_error Not_implemented)) () let get_all_bonds dbg from_cache = Debug.with_thread_associated dbg (fun () -> if from_cache then let ports = List.concat (List.map (fun (_, {ports; _}) -> ports) !config.bridge_config) in let names = List.map (fun (port, {interfaces; _}) -> (port, interfaces)) ports in List.filter (fun (_, ifs) -> List.length ifs > 1) names else match !backend_kind with | Openvswitch -> List.concat (List.map Ovs.bridge_to_ports (Ovs.list_bridges ())) | Bridge -> raise (Network_error Not_implemented)) () type bond_link_info = {slave: iface; up: bool; active: bool} let get_bond_link_info _ dbg ~name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> let slaves, active_slave = Ovs.get_bond_link_status name in let mode = Ovs.get_bond_mode name in List.map (fun (slave, up) -> let active = let ab = mode = Some "active-backup" in (ab && active_slave = Some slave) || ((not ab) && up) in {slave; up; active}) slaves | Bridge -> let active_slave = Linux_bonding.get_bond_active_slave name in let slaves = Proc.get_bond_slave_info name "MII Status" in let bond_props = Linux_bonding.get_bond_properties name in List.map (fun (slave, status) -> let up = status = "up" in let active = let ab = List.mem_assoc "mode" bond_props && Astring.String.is_prefix ~affix:"active-backup" (List.assoc "mode" bond_props) in (ab && active_slave = Some slave) || ((not ab) && up) in {slave; up; active}) slaves) () let add_default_flows _ dbg bridge mac interfaces = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.add_default_flows bridge mac interfaces | Bridge -> ()) () let add_basic_port dbg bridge name {interfaces; bond_mac; bond_properties; _} = match !backend_kind with | Openvswitch -> ( ( match interfaces with | [iface] -> Interface.bring_up () dbg ~name:iface ; ignore (Ovs.create_port iface bridge) | _ -> if bond_mac = None then warn "No MAC address specified for the bond" ; ignore (Ovs.create_bond ?mac:bond_mac name interfaces bridge bond_properties) ; List.iter (fun name -> Interface.bring_up () dbg ~name) interfaces ) ; if List.mem bridge !add_default then let mac = match bond_mac with | None -> ( try Some (Ip.get_mac name) with _ -> None ) | Some mac -> Some mac in match mac with | Some mac -> add_default_flows () dbg bridge mac interfaces ; add_default := List.filter (( <> ) bridge) !add_default | None -> warn "Could not add default flows for port %s on bridge %s because \ no MAC address was specified" name bridge ) | Bridge -> ( match interfaces with | [iface] -> Interface.bring_up () dbg ~name:iface | _ -> Linux_bonding.add_bond_master name ; let bond_properties = match List.assoc_opt "mode" bond_properties with | Some "lacp" -> Xapi_stdext_std.Listext.List.replace_assoc "mode" "802.3ad" bond_properties | _ -> bond_properties in Linux_bonding.set_bond_properties name bond_properties ; Linux_bonding.set_bond_slaves name interfaces ; ( match bond_mac with | Some mac -> Ip.set_mac name mac | None -> warn "No MAC address specified for the bond" ) ; Interface.bring_up () dbg ~name ) ; if need_enic_workaround () then ( debug "Applying enic workaround: adding VLAN0 device to bridge" ; Ip.create_vlan name 0 ; let vlan0 = Ip.vlan_name name 0 in Interface.bring_up () dbg ~name:vlan0 ; ignore (Brctl.create_port bridge vlan0) ) else ignore (Brctl.create_port bridge name) let add_pvs_proxy_port dbg bridge name _port = match !backend_kind with | Openvswitch -> ignore (Ovs.create_port ~internal:true name bridge) ; let real_bridge = Ovs.get_real_bridge bridge in Ovs.mod_port real_bridge name "no-flood" ; Interface.bring_up () dbg ~name | Bridge -> raise (Network_error Not_implemented) let add_port dbg bond_mac bridge name interfaces bond_properties kind = Debug.with_thread_associated dbg (fun () -> let bond_properties = match bond_properties with Some l -> l | None -> [] in let kind = match kind with Some v -> v | None -> Basic_port in let config = get_config bridge in let ports = if List.mem_assoc name config.ports then List.remove_assoc name config.ports else config.ports in let port = {interfaces; bond_mac; bond_properties; kind} in let ports = (name, port) :: ports in update_config bridge {config with ports} ; debug "Adding %s port %s to bridge %s with interface(s) %s%s" (string_of_port_kind kind) name bridge (String.concat ", " interfaces) (match bond_mac with Some mac -> " and MAC " ^ mac | None -> "") ; match kind with | Basic_port -> add_basic_port dbg bridge name port | PVS_proxy -> add_pvs_proxy_port dbg bridge name port) () let remove_port dbg bridge name = Debug.with_thread_associated dbg (fun () -> debug "Removing port %s from bridge %s" name bridge ; let config = get_config bridge in ( if List.mem_assoc name config.ports then let ports = List.remove_assoc name config.ports in update_config bridge {config with ports} ) ; match !backend_kind with | Openvswitch -> ignore (Ovs.destroy_port name) | Bridge -> ignore (Brctl.destroy_port bridge name)) () let get_interfaces dbg name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.bridge_to_interfaces name | Bridge -> Sysfs.bridge_to_interfaces name) () let get_physical_interfaces dbg name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.get_real_bridge name |> Ovs.bridge_to_interfaces |> List.filter Sysfs.is_physical | Bridge -> ( let ifaces = Sysfs.bridge_to_interfaces name in let vlan_ifaces = List.filter (fun (bridge, _, _) -> List.mem bridge ifaces) (Proc.get_vlans ()) in let bond_ifaces = List.filter Linux_bonding.is_bond_device ifaces in let physical_ifaces = List.filter Sysfs.is_physical ifaces in match (vlan_ifaces, bond_ifaces) with | (_, _, parent) :: _, _ when Linux_bonding.is_bond_device parent -> Linux_bonding.get_bond_slaves parent | (_, _, parent) :: _, _ -> [parent] | _, bond_iface :: _ -> Linux_bonding.get_bond_slaves bond_iface | [], [] -> physical_ifaces )) () let set_persistent dbg name value = Debug.with_thread_associated dbg (fun () -> debug "Making bridge %s %spersistent" name (if value then "" else "non-") ; update_config name {(get_config name) with persistent_b= value}) () let make_config dbg conservative config = Debug.with_thread_associated dbg (fun () -> let vlans_go_last (_, {vlan= vlan_of_a; _}) (_, {vlan= vlan_of_b; _}) = if vlan_of_a = None && vlan_of_b = None then 0 else if vlan_of_a <> None && vlan_of_b = None then 1 else if vlan_of_a = None && vlan_of_b <> None then -1 else 0 in let config = if conservative then ( let persistent_config = List.filter (fun (_name, bridge) -> bridge.persistent_b) config in debug "Ensuring the following persistent bridges are up: %s" (String.concat ", " (List.map (fun (name, _) -> name) persistent_config)) ; let vlan_parents = List.filter_map (function | _, {vlan= Some (parent, _); _} -> if not (List.mem_assoc parent persistent_config) then Some (parent, List.assoc parent config) else None | _ -> None) persistent_config in debug "Additionally ensuring the following VLAN parent bridges are up: \ %s" (String.concat ", " (List.map (fun (name, _) -> name) vlan_parents)) ; let config = vlan_parents @ persistent_config in (* Do not try to recreate bridges that already exist *) let current = get_all dbg () in List.filter (function name, _ -> not (List.mem name current)) config ) else config in let config = List.sort vlans_go_last config in let exec f = if conservative then try f () with _ -> () else f () in debug "** Configuring the following bridges: %s%s" (String.concat ", " (List.map (fun (name, _) -> name) config)) (if conservative then " (best effort)" else "") ; List.iter (function | ( bridge_name , ({ports; vlan; bridge_mac; igmp_snooping; other_config; _} as c) ) -> update_config bridge_name c ; exec (fun () -> create dbg vlan bridge_mac igmp_snooping (Some other_config) bridge_name ; List.iter (fun ( port_name , {interfaces; bond_properties; bond_mac; kind} ) -> add_port dbg bond_mac bridge_name port_name interfaces (Some bond_properties) (Some kind)) ports)) config) () end module PVS_proxy = struct open S.PVS_proxy let path = ref "/opt/citrix/pvsproxy/socket/pvsproxy" let do_call call = try Jsonrpc_client.with_rpc ~path:!path ~call () with e -> error "Error when calling PVS proxy: %s" (Printexc.to_string e) ; raise (Network_error PVS_proxy_connection_error) let configure_site _dbg config = debug "Configuring PVS proxy for site %s" config.site_uuid ; let call = { Rpc.name= "configure_site" ; params= [Rpcmarshal.marshal t.ty config] ; is_notification= false } in let _ = do_call call in () let remove_site _dbg uuid = debug "Removing PVS proxy for site %s" uuid ; let call = Rpc. { name= "remove_site" ; params= [Dict [("site_uuid", Rpcmarshal.marshal Rpc.Types.string.ty uuid)]] ; is_notification= false } in let _ = do_call call in () end let on_startup () = let dbg = "startup" in Debug.with_thread_associated dbg (fun () -> Bridge.determine_backend () ; let remove_centos_config () = Remove DNSDEV and GATEWAYDEV from Centos networking file , because the interfere * with this daemon . interfere * with this daemon. *) try let file = String.trim (Xapi_stdext_unix.Unixext.string_of_file "/etc/sysconfig/network") in let args = Astring.String.cuts ~empty:false ~sep:"\n" file in let args = List.map (fun s -> match Astring.String.cuts ~sep:"=" s with | [k; v] -> (k, v) | _ -> ("", "")) args in let args = List.filter (fun (k, _) -> k <> "DNSDEV" && k <> "GATEWAYDEV") args in let s = String.concat "\n" (List.map (fun (k, v) -> k ^ "=" ^ v) args) ^ "\n" in Xapi_stdext_unix.Unixext.write_string_to_file "/etc/sysconfig/network" s with _ -> () in try (* the following is best-effort *) read_config () ; remove_centos_config () ; if !backend_kind = Openvswitch then Ovs.set_max_idle 5000 ; Bridge.make_config dbg true !config.bridge_config ; Interface.make_config dbg true !config.interface_config ; (* If there is still a network.dbcache file, move it out of the way. *) if try Unix.access (Filename.concat "/var/lib/xcp" "network.dbcache") [Unix.F_OK] ; true with _ -> false then Unix.rename (Filename.concat "/var/lib/xcp" "network.dbcache") (Filename.concat "/var/lib/xcp" "network.dbcache.bak") with e -> debug "Error while configuring networks on startup: %s\n%s" (Printexc.to_string e) (Printexc.get_backtrace ())) ()
null
https://raw.githubusercontent.com/xapi-project/xcp-networkd/5a2f9565f018b0eaf6cbd337575a6be174030544/networkd/network_server.ml
ocaml
Remove dhclient conf (if any) for the old and new gateway interfaces. * This ensures that dhclient gets restarted with an updated conf file when * necessary. the function is meant to be idempotent and we want to avoid CA-239919 add the link_local and clean the old one only when needed Only attempt to configure interfaces that exist in the system Handle conservativeness Do not touch non-persistent interfaces Do not try to recreate bridges that already exist the following is best-effort If there is still a network.dbcache file, move it out of the way.
* Copyright ( C ) Citrix Systems Inc. * * 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 ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * 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; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Network_utils open Network_interface module S = Network_interface.Interface_API (Idl.Exn.GenServer ()) module D = Debug.Make (struct let name = "network_server" end) open D type context = unit let network_conf = ref "/etc/xcp/network.conf" let config : config_t ref = ref Network_config.empty_config let backend_kind = ref Openvswitch let write_config () = try Network_config.write_config !config with Network_config.Write_error -> () let read_config () = try config := Network_config.read_config () ; debug "Read configuration from networkd.db file." with Network_config.Read_error -> ( try No configuration file found . Try to get the initial network setup from * the first - boot data written by the host installer . * the first-boot data written by the host installer. *) config := Network_config.read_management_conf () ; debug "Read configuration from management.conf file." with Network_config.Read_error -> debug "Could not interpret the configuration in management.conf" ) let on_shutdown signal = let dbg = "shutdown" in Debug.with_thread_associated dbg (fun () -> debug "xcp-networkd caught signal %d; performing cleanup actions." signal ; write_config ()) () let on_timer () = write_config () let clear_state () = config := Network_config.empty_config let reset_state () = config := Network_config.read_management_conf () let set_gateway_interface _dbg name = ( match !config.gateway_interface with | Some old_iface when name <> old_iface -> Dhclient.remove_conf_file name ; Dhclient.remove_conf_file old_iface | _ -> () ) ; debug "Setting gateway interface to %s" name ; config := {!config with gateway_interface= Some name} let set_dns_interface _dbg name = Remove dhclient conf ( if any ) for the old and new DNS interfaces . * This ensures that dhclient gets restarted with an updated conf file when * necessary . * This ensures that dhclient gets restarted with an updated conf file when * necessary. *) ( match !config.dns_interface with | Some old_iface when name <> old_iface -> Dhclient.remove_conf_file name ; Dhclient.remove_conf_file old_iface | _ -> () ) ; debug "Setting DNS interface to %s" name ; config := {!config with dns_interface= Some name} The enic driver is for Cisco UCS devices . The current driver adds VLAN0 headers * to all incoming packets , which confuses certain guests OSes . The workaround * constitutes adding a VLAN0 Linux device to strip those headers again . * to all incoming packets, which confuses certain guests OSes. The workaround * constitutes adding a VLAN0 Linux device to strip those headers again. *) let need_enic_workaround () = !backend_kind = Bridge && List.mem "enic" (Sysfs.list_drivers ()) module Sriov = struct open S.Sriov let get_capabilities dev = let open Rresult.R.Infix in let maxvfs_modprobe = Sysfs.get_driver_name_err dev >>= fun driver -> Modprobe.get_config_from_comments driver |> Modprobe.get_maxvfs driver and maxvfs_sysfs = Sysfs.get_sriov_maxvfs dev in let is_support = match (maxvfs_modprobe, maxvfs_sysfs) with | Ok v, _ -> v > 0 | Error _, Ok v -> v > 0 | _ -> false in if is_support then ["sriov"] else [] let config_sriov ~enable dev = let op = if enable then "enable" else "disable" in let open Rresult.R.Infix in Sysfs.get_driver_name_err dev >>= fun driver -> let config = Modprobe.get_config_from_comments driver in match Modprobe.get_vf_param config with | Some vf_param -> debug "%s SR-IOV on a device: %s via modprobe" op dev ; (if enable then Modprobe.get_maxvfs driver config else Ok 0) >>= fun numvfs -> CA-287340 : Even if the current numvfs equals to the target numvfs , it is still needed to update SR - IOV modprobe config file , as the SR - IOV enabing takes effect after reboot . For example , a user enables SR - IOV and disables it immediately without a reboot . is still needed to update SR-IOV modprobe config file, as the SR-IOV enabing takes effect after reboot. For example, a user enables SR-IOV and disables it immediately without a reboot.*) Modprobe.config_sriov driver vf_param numvfs >>= fun _ -> if numvfs = Sysfs.get_sriov_numvfs dev then Ok Modprobe_successful else Ok Modprobe_successful_requires_reboot | None -> enable : try interface to set numfvs = maxvfs . if fails , but vfs are enabled , assume manual configuration . disable : Net.Sriov.disable will not be called for manually configured interfaces , as determined by ` require_operation_on_pci_device ` disable: Net.Sriov.disable will not be called for manually configured interfaces, as determined by `require_operation_on_pci_device` *) let man_successful () = debug "SR-IOV/VFs %sd manually on device: %s" op dev ; Manual_successful in if enable then let present_numvfs = Sysfs.get_sriov_numvfs dev in match Sysfs.get_sriov_maxvfs dev >>= fun maxvfs -> maxvfs |> Sysfs.set_sriov_numvfs dev with | Ok _ -> debug "%s SR-IOV on a device: %s via sysfs" op dev ; Ok Sysfs_successful | Error _ when present_numvfs > 0 -> Ok (man_successful ()) | exception _ when present_numvfs > 0 -> Ok (man_successful ()) | Error err -> Error err | exception e -> let msg = Printf.sprintf "Error: trying sysfs SR-IOV interface failed with exception \ %s on device: %s" (Printexc.to_string e) dev in Error (Other, msg) else Sysfs.unbind_child_vfs dev >>= fun () -> Sysfs.set_sriov_numvfs dev 0 >>= fun _ -> debug "%s SR-IOV on a device: %s via sysfs" op dev ; Ok Sysfs_successful let enable dbg name = Debug.with_thread_associated dbg (fun () -> debug "Enable network SR-IOV by name: %s" name ; match config_sriov ~enable:true name with | Ok t -> (Ok t : enable_result) | Result.Error (_, msg) -> warn "Failed to enable SR-IOV on %s with error: %s" name msg ; Error msg) () let disable dbg name = Debug.with_thread_associated dbg (fun () -> debug "Disable network SR-IOV by name: %s" name ; match config_sriov ~enable:false name with | Ok _ -> (Ok : disable_result) | Result.Error (_, msg) -> warn "Failed to disable SR-IOV on %s with error: %s" name msg ; Error msg) () let make_vf_conf_internal pcibuspath mac vlan rate = let config_or_otherwise_reset config_f reset_f = function | None -> reset_f () | Some a -> config_f a in let open Rresult.R.Infix in Sysfs.parent_device_of_vf pcibuspath >>= fun dev -> Sysfs.device_index_of_vf dev pcibuspath >>= fun index -> config_or_otherwise_reset (Ip.set_vf_mac dev index) (fun () -> Result.Ok ()) mac >>= fun () -> In order to ensure the Networkd to be idempotent , configuring VF with no VLAN and rate have to reset vlan and rate , since the VF might have previous configuration . Refering to -bin/man/man2html?ip-link+8 , set VLAN and rate to 0 means to reset them VLAN and rate have to reset vlan and rate, since the VF might have previous configuration. Refering to -bin/man/man2html?ip-link+8, set VLAN and rate to 0 means to reset them *) config_or_otherwise_reset (Ip.set_vf_vlan dev index) (fun () -> Ip.set_vf_vlan dev index 0) vlan >>= fun () -> config_or_otherwise_reset (Ip.set_vf_rate dev index) (fun () -> Ip.set_vf_rate dev index 0) rate let make_vf_config dbg pci_address (vf_info : sriov_pci_t) = Debug.with_thread_associated dbg (fun () -> let vlan = Option.map Int64.to_int vf_info.vlan and rate = Option.map Int64.to_int vf_info.rate and pcibuspath = Xcp_pci.string_of_address pci_address in debug "Config VF with pci address: %s" pcibuspath ; match make_vf_conf_internal pcibuspath vf_info.mac vlan rate with | Result.Ok () -> (Ok : config_result) | Result.Error (Fail_to_set_vf_rate, msg) -> debug "%s" msg ; Error Config_vf_rate_not_supported | Result.Error (_, msg) -> debug "%s" msg ; Error (Unknown msg)) () end module Interface = struct let get_config name = get_config !config.interface_config default_interface name let update_config name data = config := { !config with interface_config= update_config !config.interface_config name data } let get_all dbg () = Debug.with_thread_associated dbg (fun () -> Sysfs.list ()) () let exists dbg name = Debug.with_thread_associated dbg (fun () -> List.mem name (Sysfs.list ())) () let get_mac dbg name = Debug.with_thread_associated dbg (fun () -> match Linux_bonding.get_bond_master_of name with | Some master -> Proc.get_bond_slave_mac master name | None -> Ip.get_mac name) () let get_pci_bus_path dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.get_pcibuspath name) () let is_up dbg name = Debug.with_thread_associated dbg (fun () -> if List.mem name (Sysfs.list ()) then Ip.is_up name else false) () let get_ipv4_addr dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_ipv4 name) () let set_ipv4_conf dbg name conf = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 address for %s: %s" name (conf |> Rpcmarshal.marshal typ_of_ipv4 |> Jsonrpc.to_string) ; update_config name {(get_config name) with ipv4_conf= conf} ; match conf with | None4 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running name then ignore (Dhclient.stop name) ; Ip.flush_ip_addr name ) | DHCP4 -> let gateway = Option.fold ~none:[] ~some:(fun n -> [`gateway n]) !config.gateway_interface in let dns = Option.fold ~none:[] ~some:(fun n -> [`dns n]) !config.dns_interface in let options = gateway @ dns in Dhclient.ensure_running name options | Static4 addrs -> if Dhclient.is_running name then ( ignore (Dhclient.stop name) ; Ip.flush_ip_addr name ) ; let cur_addrs = Ip.get_ipv4 name in let rm_addrs = Xapi_stdext_std.Listext.List.set_difference cur_addrs addrs in let add_addrs = Xapi_stdext_std.Listext.List.set_difference addrs cur_addrs in List.iter (Ip.del_ip_addr name) rm_addrs ; List.iter (Ip.set_ip_addr name) add_addrs) () let get_ipv4_gateway dbg name = Debug.with_thread_associated dbg (fun () -> let output = Ip.route_show ~version:Ip.V4 name in try let line = List.find (fun s -> Astring.String.is_prefix ~affix:"default via" s) (Astring.String.cuts ~empty:false ~sep:"\n" output) in let addr = List.nth (Astring.String.cuts ~empty:false ~sep:" " line) 2 in Some (Unix.inet_addr_of_string addr) with Not_found -> None) () let set_ipv4_gateway _ dbg ~name ~address = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 gateway for %s: %s" name (Unix.string_of_inet_addr address) ; update_config name {(get_config name) with ipv4_gateway= Some address} ; if !config.gateway_interface = None || !config.gateway_interface = Some name then ( debug "%s is the default gateway interface" name ; Ip.set_gateway name address ) else debug "%s is NOT the default gateway interface" name) () let get_ipv6_addr dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_ipv6 name) () let set_ipv6_conf _ dbg ~name ~conf = Debug.with_thread_associated dbg (fun () -> if Proc.get_ipv6_disabled () then warn "Not configuring IPv6 address for %s (IPv6 is disabled)" name else ( debug "Configuring IPv6 address for %s: %s" name (conf |> Rpcmarshal.marshal typ_of_ipv6 |> Jsonrpc.to_string) ; update_config name {(get_config name) with ipv6_conf= conf} ; match conf with | None6 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ) | Linklocal6 -> if List.mem name (Sysfs.list ()) then ( if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ) | DHCP6 -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ; ignore (Dhclient.ensure_running ~ipv6:true name []) | Autoconf6 -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Ip.flush_ip_addr ~ipv6:true name ; Ip.set_ipv6_link_local_addr name ; Sysctl.set_ipv6_autoconf name true Can not link set down / up due to CA-89882 - IPv4 default route cleared cleared *) | Static6 addrs -> if Dhclient.is_running ~ipv6:true name then ignore (Dhclient.stop ~ipv6:true name) ; Sysctl.set_ipv6_autoconf name false ; let cur_addrs = let addrs = Ip.get_ipv6 name in let maybe_link_local = Ip.split_addr (Ip.get_ipv6_link_local_addr name) in match maybe_link_local with | Some addr -> Xapi_stdext_std.Listext.List.setify (addr :: addrs) | None -> addrs in let rm_addrs = Xapi_stdext_std.Listext.List.set_difference cur_addrs addrs in let add_addrs = Xapi_stdext_std.Listext.List.set_difference addrs cur_addrs in List.iter (Ip.del_ip_addr name) rm_addrs ; List.iter (Ip.set_ip_addr name) add_addrs )) () let set_ipv6_gateway _ dbg ~name ~address = Debug.with_thread_associated dbg (fun () -> if Proc.get_ipv6_disabled () then warn "Not configuring IPv6 gateway for %s (IPv6 is disabled)" name else ( debug "Configuring IPv6 gateway for %s: %s" name (Unix.string_of_inet_addr address) ; update_config name {(get_config name) with ipv6_gateway= Some address} ; if !config.gateway_interface = None || !config.gateway_interface = Some name then ( debug "%s is the default gateway interface" name ; Ip.set_gateway name address ) else debug "%s is NOT the default gateway interface" name )) () let set_ipv4_routes _ dbg ~name ~routes = Debug.with_thread_associated dbg (fun () -> debug "Configuring IPv4 static routes for %s: %s" name (String.concat ", " (List.map (fun r -> Printf.sprintf "%s/%d/%s" (Unix.string_of_inet_addr r.subnet) r.netmask (Unix.string_of_inet_addr r.gateway)) routes)) ; update_config name {(get_config name) with ipv4_routes= routes} ; List.iter (fun r -> Ip.set_route ~network:(r.subnet, r.netmask) name r.gateway) routes) () let get_dns dbg _name = Debug.with_thread_associated dbg (fun () -> let nameservers, domains = Xapi_stdext_unix.Unixext.file_lines_fold (fun (nameservers, domains) line -> if Astring.String.is_prefix ~affix:"nameserver" line then let server = List.nth (Astring.String.fields ~empty:false line) 1 in (Unix.inet_addr_of_string server :: nameservers, domains) else if Astring.String.is_prefix ~affix:"search" line then let domains = List.tl (Astring.String.fields ~empty:false line) in (nameservers, domains) else (nameservers, domains)) ([], []) resolv_conf in (List.rev nameservers, domains)) () let set_dns _ dbg ~name ~nameservers ~domains = Debug.with_thread_associated dbg (fun () -> update_config name {(get_config name) with dns= (nameservers, domains)} ; debug "Configuring DNS for %s: nameservers: [%s]; domains: [%s]" name (String.concat ", " (List.map Unix.string_of_inet_addr nameservers)) (String.concat ", " domains) ; if !config.dns_interface = None || !config.dns_interface = Some name then ( debug "%s is the DNS interface" name ; let domains' = if domains <> [] then ["search " ^ String.concat " " domains] else [] in let nameservers' = List.map (fun ip -> "nameserver " ^ Unix.string_of_inet_addr ip) nameservers in let lines = domains' @ nameservers' in Xapi_stdext_unix.Unixext.write_string_to_file resolv_conf (String.concat "\n" lines ^ "\n") ) else debug "%s is NOT the DNS interface" name) () let get_mtu dbg name = Debug.with_thread_associated dbg (fun () -> Ip.get_mtu name) () let set_mtu _ dbg ~name ~mtu = Debug.with_thread_associated dbg (fun () -> debug "Configuring MTU for %s: %d" name mtu ; update_config name {(get_config name) with mtu} ; match !backend_kind with | Openvswitch -> ( try ignore (Ovs.set_mtu name mtu) with _ -> Ip.link_set_mtu name mtu ) | Bridge -> Ip.link_set_mtu name mtu) () let set_ethtool_settings _ dbg ~name ~params = Debug.with_thread_associated dbg (fun () -> debug "Configuring ethtool settings for %s: %s" name (String.concat ", " (List.map (fun (k, v) -> k ^ "=" ^ v) params)) ; let add_defaults = List.filter (fun (k, _) -> not (List.mem_assoc k params)) default_interface.ethtool_settings in let params = params @ add_defaults in update_config name {(get_config name) with ethtool_settings= params} ; Ethtool.set_options name params) () let set_ethtool_offload _ dbg ~name ~params = Debug.with_thread_associated dbg (fun () -> debug "Configuring ethtool offload settings for %s: %s" name (String.concat ", " (List.map (fun (k, v) -> k ^ "=" ^ v) params)) ; let add_defaults = List.filter (fun (k, _) -> not (List.mem_assoc k params)) default_interface.ethtool_offload in let params = params @ add_defaults in update_config name {(get_config name) with ethtool_offload= params} ; Ethtool.set_offload name params) () let get_capabilities dbg name = Debug.with_thread_associated dbg (fun () -> Fcoe.get_capabilities name @ Sriov.get_capabilities name) () let is_connected dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.get_carrier name) () let is_physical dbg name = Debug.with_thread_associated dbg (fun () -> Sysfs.is_physical name) () let has_vlan dbg name vlan = Identify the vlan is used by kernel which is unknown to Debug.with_thread_associated dbg (fun () -> let temp_interfaces = Sysfs.bridge_to_interfaces Network_config.temp_vlan in List.exists (fun (d, v, p) -> v = vlan && p = name && not (List.mem d temp_interfaces)) (Proc.get_vlans ())) () let bring_up _ dbg ~name = Debug.with_thread_associated dbg (fun () -> debug "Bringing up interface %s" name ; Ip.link_set_up name) () let bring_down dbg name = Debug.with_thread_associated dbg (fun () -> debug "Bringing down interface %s" name ; Ip.link_set_down name) () let set_persistent dbg name value = Debug.with_thread_associated dbg (fun () -> debug "Making interface %s %spersistent" name (if value then "" else "non-") ; update_config name {(get_config name) with persistent_i= value}) () let make_config dbg conservative config = Debug.with_thread_associated dbg (fun () -> let all = get_all dbg () in let config = List.filter (fun (name, _) -> List.mem name all) config in let config = if conservative then ( debug "Only configuring persistent interfaces" ; List.filter (fun (_name, interface) -> interface.persistent_i) config ) else config in let config = if need_enic_workaround () then List.fold_left (fun accu (name, interface) -> if Sysfs.is_physical name && Linux_bonding.get_bond_master_of name = None || Linux_bonding.is_bond_device name then (name, interface) :: (Ip.vlan_name name 0, interface) :: accu else (name, interface) :: accu) [] config else config in debug "** Configuring the following interfaces: %s%s" (String.concat ", " (List.map (fun (name, _) -> name) config)) (if conservative then " (best effort)" else "") ; let exec f = if conservative then try f () with _ -> () else f () in List.iter (function | ( name , ( { ipv4_conf ; ipv4_gateway ; ipv6_conf ; ipv6_gateway ; ipv4_routes ; dns= nameservers, domains ; mtu ; ethtool_settings ; ethtool_offload ; _ } as c ) ) -> update_config name c ; exec (fun () -> We only apply the DNS settings when not in a DHCP mode to avoid conflicts . The ` dns ` field should really be an option type so that we do n't have to derive the intention of the caller by looking at other fields . to avoid conflicts. The `dns` field should really be an option type so that we don't have to derive the intention of the caller by looking at other fields. *) match (ipv4_conf, ipv6_conf) with | Static4 _, _ | _, Static6 _ | _, Autoconf6 -> set_dns () dbg ~name ~nameservers ~domains | _ -> ()) ; exec (fun () -> set_ipv4_conf dbg name ipv4_conf) ; exec (fun () -> match ipv4_gateway with | None -> () | Some gateway -> set_ipv4_gateway () dbg ~name ~address:gateway) ; (try set_ipv6_conf () dbg ~name ~conf:ipv6_conf with _ -> ()) ; ( try match ipv6_gateway with | None -> () | Some gateway -> set_ipv6_gateway () dbg ~name ~address:gateway with _ -> () ) ; exec (fun () -> set_ipv4_routes () dbg ~name ~routes:ipv4_routes) ; exec (fun () -> set_mtu () dbg ~name ~mtu) ; exec (fun () -> bring_up () dbg ~name) ; exec (fun () -> set_ethtool_settings () dbg ~name ~params:ethtool_settings) ; exec (fun () -> set_ethtool_offload () dbg ~name ~params:ethtool_offload)) config) () end module Bridge = struct let add_default = ref [] let get_config name = get_config !config.bridge_config default_bridge name let remove_config name = config := {!config with bridge_config= remove_config !config.bridge_config name} let update_config name data = config := { !config with bridge_config= update_config !config.bridge_config name data } let determine_backend () = try let backend = String.trim (Xapi_stdext_unix.Unixext.string_of_file !network_conf) in match backend with | "openvswitch" | "vswitch" -> backend_kind := Openvswitch | "bridge" -> backend_kind := Bridge | backend -> warn "Network backend unknown (%s). Falling back to Open vSwitch." backend ; backend_kind := Openvswitch with _ -> warn "Network-conf file not found. Falling back to Open vSwitch." ; backend_kind := Openvswitch let get_all dbg () = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.list_bridges () | Bridge -> Sysfs.get_all_bridges ()) () Destroy any existing bridge that is n't the " wanted bridge " and has the * given VLAN on it . * given VLAN on it. *) let destroy_existing_vlan_ovs_bridge dbg wanted_bridge (parent, vlan) = let vlan_bridges = let raw = Ovs.vsctl [ "--bare" ; "-f" ; "table" ; "--" ; "--columns=name" ; "find" ; "port" ; "fake_bridge=true" ; "tag=" ^ string_of_int vlan ] in if raw <> "" then Astring.String.cuts ~empty:false ~sep:"\n" (String.trim raw) else [] in let existing_bridges = List.filter (fun bridge -> match Ovs.bridge_to_vlan bridge with | Some (p, v) -> p = parent && v = vlan | None -> false) vlan_bridges in List.iter (fun bridge -> if bridge <> wanted_bridge then ( debug "Destroying existing bridge %s" bridge ; remove_config bridge ; Interface.set_ipv4_conf dbg bridge None4 ; ignore (Ovs.destroy_bridge bridge) )) existing_bridges Destroy any existing Linux bridge that is n't the " wanted bridge " and has the * given VLAN on it . * given VLAN on it. *) let destroy_existing_vlan_linux_bridge dbg wanted_bridge vlan_device = List.iter (fun bridge -> if bridge <> wanted_bridge then let ifaces_on_bridge = Sysfs.bridge_to_interfaces bridge in if List.mem vlan_device ifaces_on_bridge then ( debug "Destroying existing bridge %s" bridge ; Interface.bring_down dbg bridge ; remove_config bridge ; Interface.set_ipv4_conf dbg bridge None4 ; List.iter (fun dev -> Brctl.destroy_port bridge dev) ifaces_on_bridge ; ignore (Brctl.destroy_bridge bridge) )) (Sysfs.get_all_bridges ()) let create dbg vlan mac igmp_snooping other_config name = Debug.with_thread_associated dbg (fun () -> let other_config = match other_config with Some l -> l | None -> [] in debug "Creating bridge %s%s" name ( match vlan with | None -> "" | Some (parent, vlan) -> Printf.sprintf " (VLAN %d on bridge %s)" vlan parent ) ; update_config name { (get_config name) with vlan ; bridge_mac= mac ; igmp_snooping ; other_config } ; ( match !backend_kind with | Openvswitch -> let fail_mode = if not (List.mem_assoc "vswitch-controller-fail-mode" other_config) then "standalone" else let mode = List.assoc "vswitch-controller-fail-mode" other_config in if mode = "secure" || mode = "standalone" then ( ( try if mode = "secure" && Ovs.get_fail_mode name <> "secure" then add_default := name :: !add_default with _ -> () ) ; mode ) else ( debug "%s isn't a valid setting for \ other_config:vswitch-controller-fail-mode; defaulting to \ 'standalone'" mode ; "standalone" ) in let vlan_bug_workaround = if List.mem_assoc "vlan-bug-workaround" other_config then Some (List.assoc "vlan-bug-workaround" other_config = "true") else None in let external_id = if List.mem_assoc "network-uuids" other_config then Some ("xs-network-uuids", List.assoc "network-uuids" other_config) else None in let disable_in_band = if not (List.mem_assoc "vswitch-disable-in-band" other_config) then Some None else let dib = List.assoc "vswitch-disable-in-band" other_config in if dib = "true" || dib = "false" then Some (Some dib) else ( debug "%s isn't a valid setting for \ other_config:vswitch-disable-in-band" dib ; None ) in let old_igmp_snooping = Ovs.get_mcast_snooping_enable ~name in Option.iter (destroy_existing_vlan_ovs_bridge dbg name) vlan ; ignore (Ovs.create_bridge ?mac ~fail_mode ?external_id ?disable_in_band ?igmp_snooping vlan vlan_bug_workaround name) ; if igmp_snooping = Some true && not old_igmp_snooping then Ovs.inject_igmp_query ~name | Bridge -> ( ignore (Brctl.create_bridge name) ; Brctl.set_forwarding_delay name 0 ; Sysfs.set_multicast_snooping name false ; Option.iter (Ip.set_mac name) mac ; match vlan with | None -> () | Some (parent, vlan) -> let bridge_interfaces = Sysfs.bridge_to_interfaces name in let parent_bridge_interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) (Sysfs.bridge_to_interfaces parent) in let parent_bridge_interface = match parent_bridge_interfaces with | [] -> let msg = Printf.sprintf {|Interface for bridge parent "%s" of vlan %i not found|} parent vlan in error "%s" msg ; raise (Network_error (Internal_error msg)) | iface :: _ -> iface in let parent_interface = if need_enic_workaround () then ( let n = String.length parent_bridge_interface in let m = String.sub parent_bridge_interface 0 (n - 2) in if vlan = 0 then error "The enic workaround is in effect. Bridge %s is used \ for VLAN 0 on %s." parent m ; m ) else parent_bridge_interface in let vlan_name = Ip.vlan_name parent_interface vlan in destroy_existing_vlan_linux_bridge dbg name vlan_name ; Check if the VLAN is already in use by something else List.iter (fun (device, vlan', parent') -> A device for the same VLAN ( parent + tag ) , but with a different * device name or not on the requested bridge is bad . different * device name or not on the requested bridge is bad. *) if parent' = parent && vlan' = vlan && (device <> vlan_name || not (List.mem device bridge_interfaces) ) then raise (Network_error (Vlan_in_use (parent, vlan)))) (Proc.get_vlans ()) ; Robustness enhancement : ensure there are no other VLANs in the bridge the bridge *) let current_interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) bridge_interfaces in debug "Removing these non-VIF interfaces found on the bridge: %s" (String.concat ", " current_interfaces) ; List.iter (fun interface -> Brctl.destroy_port name interface ; Interface.bring_down dbg interface) current_interfaces ; Now create the new VLAN device and add it to the bridge Ip.create_vlan parent_interface vlan ; Interface.bring_up () dbg ~name:vlan_name ; Brctl.create_port name vlan_name ) ) ; Interface.bring_up () dbg ~name) () let destroy dbg force name = Debug.with_thread_associated dbg (fun () -> Interface.bring_down dbg name ; match !backend_kind with | Openvswitch -> let vlans_on_this_parent = Ovs.get_vlans name in if vlans_on_this_parent = [] || force then ( debug "Destroying bridge %s" name ; remove_config name ; let interfaces = Ovs.bridge_to_interfaces name @ vlans_on_this_parent in List.iter (fun dev -> Interface.set_ipv4_conf dbg dev None4 ; Interface.bring_down dbg dev) interfaces ; Interface.set_ipv4_conf dbg name None4 ; ignore (Ovs.destroy_bridge name) ) else debug "Not destroying bridge %s, because it has VLANs on top" name | Bridge -> let ifs = Sysfs.bridge_to_interfaces name in let vlans_on_this_parent = let interfaces = List.filter (fun n -> Astring.String.is_prefix ~affix:"eth" n || Astring.String.is_prefix ~affix:"bond" n) ifs in match interfaces with | [] -> [] | interface :: _ -> List.filter (Astring.String.is_prefix ~affix:(interface ^ ".")) (Sysfs.list ()) in if vlans_on_this_parent = [] || force then ( debug "Destroying bridge %s" name ; remove_config name ; List.iter (fun dev -> Interface.set_ipv4_conf dbg dev None4 ; Brctl.destroy_port name dev ; Interface.bring_down dbg dev ; if Linux_bonding.is_bond_device dev then Linux_bonding.remove_bond_master dev ; if (Astring.String.is_prefix ~affix:"eth" dev || Astring.String.is_prefix ~affix:"bond" dev ) && String.contains dev '.' then ( ignore (Ip.destroy_vlan dev) ; let n = String.length dev in if String.sub dev (n - 2) 2 = ".0" && need_enic_workaround () then let vlan_base = String.sub dev 0 (n - 2) in if Linux_bonding.is_bond_device vlan_base then Linux_bonding.remove_bond_master (String.sub dev 0 (n - 2)) )) ifs ; Interface.set_ipv4_conf dbg name None4 ; ignore (Brctl.destroy_bridge name) ) else debug "Not destroying bridge %s, because it has VLANs on top" name) () let get_kind dbg () = Debug.with_thread_associated dbg (fun () -> !backend_kind) () let get_all_ports dbg from_cache = Debug.with_thread_associated dbg (fun () -> if from_cache then let ports = List.concat (List.map (fun (_, {ports; _}) -> ports) !config.bridge_config) in List.map (fun (port, {interfaces; _}) -> (port, interfaces)) ports else match !backend_kind with | Openvswitch -> List.concat (List.map Ovs.bridge_to_ports (Ovs.list_bridges ())) | Bridge -> raise (Network_error Not_implemented)) () let get_all_bonds dbg from_cache = Debug.with_thread_associated dbg (fun () -> if from_cache then let ports = List.concat (List.map (fun (_, {ports; _}) -> ports) !config.bridge_config) in let names = List.map (fun (port, {interfaces; _}) -> (port, interfaces)) ports in List.filter (fun (_, ifs) -> List.length ifs > 1) names else match !backend_kind with | Openvswitch -> List.concat (List.map Ovs.bridge_to_ports (Ovs.list_bridges ())) | Bridge -> raise (Network_error Not_implemented)) () type bond_link_info = {slave: iface; up: bool; active: bool} let get_bond_link_info _ dbg ~name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> let slaves, active_slave = Ovs.get_bond_link_status name in let mode = Ovs.get_bond_mode name in List.map (fun (slave, up) -> let active = let ab = mode = Some "active-backup" in (ab && active_slave = Some slave) || ((not ab) && up) in {slave; up; active}) slaves | Bridge -> let active_slave = Linux_bonding.get_bond_active_slave name in let slaves = Proc.get_bond_slave_info name "MII Status" in let bond_props = Linux_bonding.get_bond_properties name in List.map (fun (slave, status) -> let up = status = "up" in let active = let ab = List.mem_assoc "mode" bond_props && Astring.String.is_prefix ~affix:"active-backup" (List.assoc "mode" bond_props) in (ab && active_slave = Some slave) || ((not ab) && up) in {slave; up; active}) slaves) () let add_default_flows _ dbg bridge mac interfaces = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.add_default_flows bridge mac interfaces | Bridge -> ()) () let add_basic_port dbg bridge name {interfaces; bond_mac; bond_properties; _} = match !backend_kind with | Openvswitch -> ( ( match interfaces with | [iface] -> Interface.bring_up () dbg ~name:iface ; ignore (Ovs.create_port iface bridge) | _ -> if bond_mac = None then warn "No MAC address specified for the bond" ; ignore (Ovs.create_bond ?mac:bond_mac name interfaces bridge bond_properties) ; List.iter (fun name -> Interface.bring_up () dbg ~name) interfaces ) ; if List.mem bridge !add_default then let mac = match bond_mac with | None -> ( try Some (Ip.get_mac name) with _ -> None ) | Some mac -> Some mac in match mac with | Some mac -> add_default_flows () dbg bridge mac interfaces ; add_default := List.filter (( <> ) bridge) !add_default | None -> warn "Could not add default flows for port %s on bridge %s because \ no MAC address was specified" name bridge ) | Bridge -> ( match interfaces with | [iface] -> Interface.bring_up () dbg ~name:iface | _ -> Linux_bonding.add_bond_master name ; let bond_properties = match List.assoc_opt "mode" bond_properties with | Some "lacp" -> Xapi_stdext_std.Listext.List.replace_assoc "mode" "802.3ad" bond_properties | _ -> bond_properties in Linux_bonding.set_bond_properties name bond_properties ; Linux_bonding.set_bond_slaves name interfaces ; ( match bond_mac with | Some mac -> Ip.set_mac name mac | None -> warn "No MAC address specified for the bond" ) ; Interface.bring_up () dbg ~name ) ; if need_enic_workaround () then ( debug "Applying enic workaround: adding VLAN0 device to bridge" ; Ip.create_vlan name 0 ; let vlan0 = Ip.vlan_name name 0 in Interface.bring_up () dbg ~name:vlan0 ; ignore (Brctl.create_port bridge vlan0) ) else ignore (Brctl.create_port bridge name) let add_pvs_proxy_port dbg bridge name _port = match !backend_kind with | Openvswitch -> ignore (Ovs.create_port ~internal:true name bridge) ; let real_bridge = Ovs.get_real_bridge bridge in Ovs.mod_port real_bridge name "no-flood" ; Interface.bring_up () dbg ~name | Bridge -> raise (Network_error Not_implemented) let add_port dbg bond_mac bridge name interfaces bond_properties kind = Debug.with_thread_associated dbg (fun () -> let bond_properties = match bond_properties with Some l -> l | None -> [] in let kind = match kind with Some v -> v | None -> Basic_port in let config = get_config bridge in let ports = if List.mem_assoc name config.ports then List.remove_assoc name config.ports else config.ports in let port = {interfaces; bond_mac; bond_properties; kind} in let ports = (name, port) :: ports in update_config bridge {config with ports} ; debug "Adding %s port %s to bridge %s with interface(s) %s%s" (string_of_port_kind kind) name bridge (String.concat ", " interfaces) (match bond_mac with Some mac -> " and MAC " ^ mac | None -> "") ; match kind with | Basic_port -> add_basic_port dbg bridge name port | PVS_proxy -> add_pvs_proxy_port dbg bridge name port) () let remove_port dbg bridge name = Debug.with_thread_associated dbg (fun () -> debug "Removing port %s from bridge %s" name bridge ; let config = get_config bridge in ( if List.mem_assoc name config.ports then let ports = List.remove_assoc name config.ports in update_config bridge {config with ports} ) ; match !backend_kind with | Openvswitch -> ignore (Ovs.destroy_port name) | Bridge -> ignore (Brctl.destroy_port bridge name)) () let get_interfaces dbg name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.bridge_to_interfaces name | Bridge -> Sysfs.bridge_to_interfaces name) () let get_physical_interfaces dbg name = Debug.with_thread_associated dbg (fun () -> match !backend_kind with | Openvswitch -> Ovs.get_real_bridge name |> Ovs.bridge_to_interfaces |> List.filter Sysfs.is_physical | Bridge -> ( let ifaces = Sysfs.bridge_to_interfaces name in let vlan_ifaces = List.filter (fun (bridge, _, _) -> List.mem bridge ifaces) (Proc.get_vlans ()) in let bond_ifaces = List.filter Linux_bonding.is_bond_device ifaces in let physical_ifaces = List.filter Sysfs.is_physical ifaces in match (vlan_ifaces, bond_ifaces) with | (_, _, parent) :: _, _ when Linux_bonding.is_bond_device parent -> Linux_bonding.get_bond_slaves parent | (_, _, parent) :: _, _ -> [parent] | _, bond_iface :: _ -> Linux_bonding.get_bond_slaves bond_iface | [], [] -> physical_ifaces )) () let set_persistent dbg name value = Debug.with_thread_associated dbg (fun () -> debug "Making bridge %s %spersistent" name (if value then "" else "non-") ; update_config name {(get_config name) with persistent_b= value}) () let make_config dbg conservative config = Debug.with_thread_associated dbg (fun () -> let vlans_go_last (_, {vlan= vlan_of_a; _}) (_, {vlan= vlan_of_b; _}) = if vlan_of_a = None && vlan_of_b = None then 0 else if vlan_of_a <> None && vlan_of_b = None then 1 else if vlan_of_a = None && vlan_of_b <> None then -1 else 0 in let config = if conservative then ( let persistent_config = List.filter (fun (_name, bridge) -> bridge.persistent_b) config in debug "Ensuring the following persistent bridges are up: %s" (String.concat ", " (List.map (fun (name, _) -> name) persistent_config)) ; let vlan_parents = List.filter_map (function | _, {vlan= Some (parent, _); _} -> if not (List.mem_assoc parent persistent_config) then Some (parent, List.assoc parent config) else None | _ -> None) persistent_config in debug "Additionally ensuring the following VLAN parent bridges are up: \ %s" (String.concat ", " (List.map (fun (name, _) -> name) vlan_parents)) ; let config = vlan_parents @ persistent_config in let current = get_all dbg () in List.filter (function name, _ -> not (List.mem name current)) config ) else config in let config = List.sort vlans_go_last config in let exec f = if conservative then try f () with _ -> () else f () in debug "** Configuring the following bridges: %s%s" (String.concat ", " (List.map (fun (name, _) -> name) config)) (if conservative then " (best effort)" else "") ; List.iter (function | ( bridge_name , ({ports; vlan; bridge_mac; igmp_snooping; other_config; _} as c) ) -> update_config bridge_name c ; exec (fun () -> create dbg vlan bridge_mac igmp_snooping (Some other_config) bridge_name ; List.iter (fun ( port_name , {interfaces; bond_properties; bond_mac; kind} ) -> add_port dbg bond_mac bridge_name port_name interfaces (Some bond_properties) (Some kind)) ports)) config) () end module PVS_proxy = struct open S.PVS_proxy let path = ref "/opt/citrix/pvsproxy/socket/pvsproxy" let do_call call = try Jsonrpc_client.with_rpc ~path:!path ~call () with e -> error "Error when calling PVS proxy: %s" (Printexc.to_string e) ; raise (Network_error PVS_proxy_connection_error) let configure_site _dbg config = debug "Configuring PVS proxy for site %s" config.site_uuid ; let call = { Rpc.name= "configure_site" ; params= [Rpcmarshal.marshal t.ty config] ; is_notification= false } in let _ = do_call call in () let remove_site _dbg uuid = debug "Removing PVS proxy for site %s" uuid ; let call = Rpc. { name= "remove_site" ; params= [Dict [("site_uuid", Rpcmarshal.marshal Rpc.Types.string.ty uuid)]] ; is_notification= false } in let _ = do_call call in () end let on_startup () = let dbg = "startup" in Debug.with_thread_associated dbg (fun () -> Bridge.determine_backend () ; let remove_centos_config () = Remove DNSDEV and GATEWAYDEV from Centos networking file , because the interfere * with this daemon . interfere * with this daemon. *) try let file = String.trim (Xapi_stdext_unix.Unixext.string_of_file "/etc/sysconfig/network") in let args = Astring.String.cuts ~empty:false ~sep:"\n" file in let args = List.map (fun s -> match Astring.String.cuts ~sep:"=" s with | [k; v] -> (k, v) | _ -> ("", "")) args in let args = List.filter (fun (k, _) -> k <> "DNSDEV" && k <> "GATEWAYDEV") args in let s = String.concat "\n" (List.map (fun (k, v) -> k ^ "=" ^ v) args) ^ "\n" in Xapi_stdext_unix.Unixext.write_string_to_file "/etc/sysconfig/network" s with _ -> () in try read_config () ; remove_centos_config () ; if !backend_kind = Openvswitch then Ovs.set_max_idle 5000 ; Bridge.make_config dbg true !config.bridge_config ; Interface.make_config dbg true !config.interface_config ; if try Unix.access (Filename.concat "/var/lib/xcp" "network.dbcache") [Unix.F_OK] ; true with _ -> false then Unix.rename (Filename.concat "/var/lib/xcp" "network.dbcache") (Filename.concat "/var/lib/xcp" "network.dbcache.bak") with e -> debug "Error while configuring networks on startup: %s\n%s" (Printexc.to_string e) (Printexc.get_backtrace ())) ()
3734106680a5cc5a3b5081c6b3f3b4af4dd281086d1ebbd81c88658ee4f21a0e
5HT/ant
GeneratePDF.ml
open XNum; open Unicode.Types; open GlyphMetric; open FontMetric; open Logging; type font_ref = { font : font_metric; first_glyph_index : int; (* minimal glyph index (from font-metric) *) used_glyphs : mutable int;(* number of used glyphs *) glyph_map : array int (* mapping internal glyph-index -> PDF index *) }; type image_ref = (string * int); (* filename, object id *) type text_state = { font_major : int; font_minor : int; font_size : float; x_pos : float; y_pos : float }; type state = { pdf : PDF.pdf_file IO.ostream; os : mutable IO.iorstream; fonts : mutable list font_ref; images : mutable list image_ref; text_state : mutable option text_state }; value new_state filename = { pdf = PDF.create_pdf_file filename 1.4; os = IO.make_buffer_stream 0x10000; fonts = []; images = []; text_state = None }; value pt_to_bp x = float_of_num (num_of_ints 7200 7227 */ x); value write_bitmap cs bm = do { if bm.Bitmap.bm_width > 0 && bm.Bitmap.bm_height > 0 then do { IO.printf cs "BI /IM true /D [1 0] /W %d /H %d ID " bm.Bitmap.bm_width bm.Bitmap.bm_height; IO.write_string cs bm.Bitmap.bm_data; IO.write_string cs "EI " } else () }; value bitmap_to_type3_glyph state fm g = do { let gm = fm.glyph_metric.(g - fm.first_glyph); let g = fm.get_glyph_bitmap fm g; let cs = IO.make_buffer_stream 0x100; let hdpi = 72.27 /. 72.0 *. g.GlyphBitmap.g_hdpp; let vdpi = 72.27 /. 72.0 *. g.GlyphBitmap.g_vdpp; let min_x = float_of_int g.GlyphBitmap.g_min_x /. hdpi; let min_y = float_of_int g.GlyphBitmap.g_min_y /. vdpi; let max_x = float_of_int g.GlyphBitmap.g_max_x /. hdpi; let max_y = float_of_int g.GlyphBitmap.g_max_y /. vdpi; IO.printf cs "%f 0 %f %f %f %f d1 " (pt_to_bp gm.gm_width) min_x min_y max_x max_y; if g.GlyphBitmap.g_bitmap.Bitmap.bm_width > 0 && g.GlyphBitmap.g_bitmap.Bitmap.bm_height > 0 then do { IO.printf cs "1 0 0 1 %f %f cm %f 0 0 %f 0 0 cm " min_x min_y (float_of_int (g.GlyphBitmap.g_max_x - g.GlyphBitmap.g_min_x + 1) /. hdpi) (float_of_int (g.GlyphBitmap.g_max_y - g.GlyphBitmap.g_min_y + 1) /. vdpi); write_bitmap cs g.GlyphBitmap.g_bitmap; } else (); let contents = PDF.alloc_object state.pdf; PDF.set_object state.pdf contents (PDF.Stream [] (IO.coerce_ir cs)); ((min_x, min_y, max_x, max_y), PDF.Reference contents 0) }; value font_encoding fm encoding = do { let rec get_name_list i list = do { if i < 0 then list else get_name_list (i-1) [ PDF.Symbol (fm.get_glyph_name encoding.(i)) :: list ] }; PDF.Dictionary [("Type", PDF.Symbol "Encoding"); ("Differences", PDF.Array [PDF.Int 0 :: get_name_list (Array.length encoding - 1) [] ])] }; value write_cmap stream fm font_name encoding = do { IO.write_string stream "%!PS-Adobe-3.0 Resource-CMap\n"; IO.write_string stream "%%DocumentNeededResources: ProcSet (CIDInit)\n"; IO.write_string stream "%%IncludeResource: ProcSet (CIDInit)\n"; IO.printf stream "%%BeginResource: CMap (CM-%s)\n" font_name; IO.printf stream "%%Title: (CM-%s ant %s 0)\n" font_name font_name; IO.write_string stream "%%Version: 1.000\n"; IO.write_string stream "%%EndComments\n"; IO.write_string stream "/CIDInit /ProcSet findresource begin\n"; IO.write_string stream "12 dict begin\n"; IO.write_string stream "begincmap\n"; IO.write_string stream "/CIDSystemInfo\n"; IO.write_string stream "<< /Registry (ant)\n"; IO.printf stream "/Ordering (%s)\n" font_name; IO.write_string stream "/Supplement 0\n"; IO.write_string stream ">> def\n"; IO.printf stream "/CMapName /CM-%s def\n" font_name; IO.write_string stream "/CMapType 2 def\n"; IO.write_string stream "1 begincodespacerange\n"; IO.write_string stream "<00> <FF>\n"; IO.write_string stream "endcodespacerange\n"; IO.printf stream "%d beginbfchar\n" (Array.length encoding); for i = 0 to Array.length encoding - 1 do { IO.printf stream "<%02x> <" i; match get_unicode fm (Substitute.Simple encoding.(i)) with [ [||] -> IO.write_string stream "0000" | str -> Array.iter (fun c -> IO.printf stream "%04x" c) str ]; IO.write_string stream ">\n" }; IO.write_string stream "endbfchar\n"; IO.write_string stream "endcmap\n"; IO.write_string stream "CMapName currentdict /CMap defineresource pop\n"; IO.write_string stream "end\n"; IO.write_string stream "end\n"; IO.write_string stream "%%EndResource\n"; IO.write_string stream "%%EOF\n" }; value new_type3_font state font_name fm encoding = do { log_string "\n#E: New Font [Type 3]"; let scale = pt_to_bp (num_one // fm.at_size); let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (pt_to_bp gm.gm_width) }) encoding; let rec calc_glyph_data n dict ((min_x, min_y, max_x, max_y) as bounds) = do { if n >= Array.length encoding then (bounds, dict) else do { let g = encoding.(n); let ((x1, y1, x2, y2), bitmap) = bitmap_to_type3_glyph state fm g; calc_glyph_data (n + 1) [ (fm.get_glyph_name g, bitmap) :: dict] (min min_x x1, min min_y y1, max max_x x2, max max_y y2) } }; let ((min_x, min_y, max_x, max_y), char_procs) = calc_glyph_data 0 [] (0.0, 0.0, 0.0, 0.0); let cmap = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; let cmap_data = IO.make_buffer_stream 0x1000; write_cmap cmap_data fm font_name encoding; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "Type3"); ("FontBBox", PDF.Array [PDF.Float min_x; PDF.Float min_y; PDF.Float max_x; PDF.Float max_y]); ("FontMatrix", PDF.Array [PDF.Float scale; PDF.Int 0; PDF.Int 0; PDF.Float scale; PDF.Int 0; PDF.Int 0]); ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("CharProcs", PDF.Dictionary char_procs); ("Encoding", font_encoding fm encoding); ("Resources", PDF.Dictionary []); ("ToUnicode", PDF.Reference cmap 0) ]); obj }; value new_type1_font state font_name fm encoding = do { log_string "\n#E: New Font [Type 1]: "; log_string font_name; log_string "."; let scale x = float_of_num (x */ num_of_int 1000 // fm.at_size); let is_cff = match fm.font_type with [ OpenTypeCFF -> True | PostScript -> False | _ -> assert False ]; let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (scale gm.gm_width) }) encoding; log_string "\n#E: New Font: Stage 0-0."; let (max_width, max_height, max_depth) = Array.fold_left (fun (w,h,d) n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); (max_num w gm.gm_width, max_num h gm.gm_height, max_num d gm.gm_depth) }) (num_zero, num_zero, num_zero) encoding; let cmap = PDF.alloc_object state.pdf; let ff = PDF.alloc_object state.pdf; let fd = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; log_string "\n#E: New Font: Stage 0-1."; let cmap_data = IO.make_buffer_stream 0x1000; log_string "\n#E: New Font: Stage 0-2."; write_cmap cmap_data fm font_name encoding; log_string "\n#E: New Font: Stage 0-3."; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); log_string "\n#E: New Font: Stage 0-4."; if is_cff then do { let font = OpenType.read_font_tables fm.file_name; let cff = OpenType.get_cff font; let font_data = IO.from_string cff; log_string "\n#E: CFF: "; log_string fm.file_name; log_string "."; let x = PDF.set_object state.pdf ff (PDF.Stream [("Subtype", PDF.Symbol "Type1C")] (IO.coerce_ir font_data)); log_string "\n#E: New Font: Stage 0-5."; x } else do { let font_data = IO.make_buffer_stream 0x1000; let (len1, len2, len3) = Type1.embedd_type1_font fm.file_name (IO.coerce_or font_data); log_string "\n#E: New Font: Stage 0-6."; PDF.set_object state.pdf ff (PDF.Stream [("Length1", PDF.Int len1); ("Length2", PDF.Int len2); ("Length3", PDF.Int len3)] (IO.coerce_ir font_data)) }; log_string "\n#E: New Font: Stage 1."; PDF.set_object state.pdf fd (PDF.Dictionary [ ("Type", PDF.Symbol "FontDescriptor"); ("FontName", PDF.Symbol fm.ps_name); ("Flags", PDF.Int 0x4); ("FontBBox", PDF.Array [PDF.Int 0; PDF.Float (scale (minus_num max_depth)); PDF.Float (scale max_width); PDF.Float (scale max_height)]); ("ItalicAngle", PDF.Int 0); ("Ascent", PDF.Float (scale max_height)); ("Descent", PDF.Float (scale (minus_num max_depth))); ("CapHeight", PDF.Float (scale max_height)); ("StemV", PDF.Float (scale fm.parameter.rule_thickness)); (if is_cff then "FontFile3" else "FontFile", PDF.Reference ff 0) ]); log_string "\n#E: New Font: Stage 2."; PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "Type1"); ("BaseFont", PDF.Symbol fm.ps_name); ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("Encoding", font_encoding fm encoding); ("ToUnicode", PDF.Reference cmap 0); ("FontDescriptor", PDF.Reference fd 0) ]); log_string "\n#E: [Type 1]: done."; obj }; value new_truetype_font state font_name fm encoding = do { log_string "\n#E: New Font [True Type]"; let scale x = float_of_num (x */ num_of_int 1000 // fm.at_size); let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (scale gm.gm_width) }) encoding; let (max_width, max_height, max_depth) = Array.fold_left (fun (w,h,d) n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); (max_num w gm.gm_width, max_num h gm.gm_height, max_num d gm.gm_depth) }) (num_zero, num_zero, num_zero) encoding; let cmap = PDF.alloc_object state.pdf; let ff = PDF.alloc_object state.pdf; let fd = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; let cmap_data = IO.make_buffer_stream 0x1000; write_cmap cmap_data fm font_name encoding; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); let font = OpenType.read_font_tables fm.file_name; let subset = IO.make_buffer_stream 0x10000; OpenType.write_subset (IO.coerce_o subset) font encoding; let len = IO.bytes_written subset; PDF.set_object state.pdf ff (PDF.Stream [("Length1", PDF.Int len)] (IO.coerce_ir subset)); PDF.set_object state.pdf fd (PDF.Dictionary [ ("Type", PDF.Symbol "FontDescriptor"); ("FontName", PDF.Symbol fm.ps_name); ("Flags", PDF.Int 0x4); ("FontBBox", PDF.Array [PDF.Int 0; PDF.Float (scale (minus_num max_depth)); PDF.Float (scale max_width); PDF.Float (scale max_height)]); ("ItalicAngle", PDF.Int 0); ("Ascent", PDF.Float (scale max_height)); ("Descent", PDF.Float (scale (minus_num max_depth))); ("CapHeight", PDF.Float (scale max_height)); ("StemV", PDF.Float (scale fm.parameter.rule_thickness)); ("FontFile2", PDF.Reference ff 0) ]); PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "TrueType"); ("BaseFont", PDF.Symbol fm.ps_name); (* font subset: "AAAAAA+" ^ fm.ps_name *) ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("ToUnicode", PDF.Reference cmap 0); ("FontDescriptor", PDF.Reference fd 0) ]); obj }; value new_font state font = do { log_string "\n#E: New Font"; let n = List.length state.fonts; let fd = { font = font; first_glyph_index = font.first_glyph; used_glyphs = 0; glyph_map = Array.make (font.last_glyph - font.first_glyph + 1) (-1) }; state.fonts := state.fonts @ [fd]; (n, fd) }; value make_font_obj state font_number font_def = do { log_string "\n#E: Make Font Object"; iter 0 [] where rec iter i objs = do { if i >= font_def.used_glyphs then List.rev objs else do { let encoding = Array.make (min 0x100 (font_def.used_glyphs - i)) (-1); select all glyphs mapped to numbers between i * 0x100 and i * 0x100 + 0xff Array.iteri (fun x y -> do { if y >= i && y < i + 0x100 then encoding.(y - i) := x + font_def.first_glyph_index else () }) font_def.glyph_map; let new_font = match font_def.font.font_type with [ PostScript | OpenTypeCFF -> new_type1_font | TrueType -> new_truetype_font | Other -> new_type3_font ]; let obj = new_font state (Printf.sprintf "F%d.%d" font_number (i / 0x100)) font_def.font encoding; iter (i + 0x100) [obj :: objs] } } }; value get_glyph_index font_def char = do { log_string "\n#E: Get Glyph Index"; let i = font_def.glyph_map.(char - font_def.first_glyph_index); if i >= 0 then i else do { font_def.glyph_map.(char - font_def.first_glyph_index) := font_def.used_glyphs; font_def.used_glyphs := font_def.used_glyphs + 1; font_def.used_glyphs - 1 } }; value load_font state font char = do { log_string "\n#E: Load Font "; log_string font.name; log_string "."; find 0 state.fonts where rec find i fonts = match fonts with [ [f :: fs] -> do { if f.font == font then (i, get_glyph_index f char) else find (i + 1) fs } | [] -> do { let (i, fd) = new_font state font; (i, get_glyph_index fd char) } ] }; (* images *) value new_bitmap_image state idx file = do { let conv_id cs s = do { IO.write_string cs s }; let conv_rgba cs s = do { for i = 0 to String.length s / 4 - 1 do { IO.write_char cs s.[4*i]; IO.write_char cs s.[4*i+1]; IO.write_char cs s.[4*i+2] } }; let image_info img = match img.LoadImage.bm_format with [ LoadImage.RGB -> (PDF.Symbol "DeviceRGB", conv_id) | LoadImage.RGBA -> (PDF.Symbol "DeviceRGB", conv_rgba) | LoadImage.CMYK -> (PDF.Symbol "DeviceCMYK", conv_id) | LoadImage.Indexed cm -> (PDF.Array [PDF.Symbol "Indexed"; PDF.Symbol "DeviceRGB"; PDF.Int ((2 lsl img.LoadImage.bm_depth) - 1); PDF.String (IO.make_string_stream cm)], conv_id) ]; let image_data img conv = do { let cs = IO.make_buffer_stream (img.LoadImage.bm_width * img.LoadImage.bm_height / 8); for y = 0 to img.LoadImage.bm_height - 1 do { conv cs (img.LoadImage.bm_scanline y) }; IO.coerce_ir cs }; let obj = PDF.alloc_object state.pdf; state.images := state.images @ [(file, obj)]; let img = LoadImage.read_bitmap file; let (colsp, conv) = image_info img; let bits = if img.LoadImage.bm_depth <= 8 then 8 else 16; PDF.set_object state.pdf obj (PDF.Stream [ ("Type", PDF.Symbol "XObject"); ("Subtype", PDF.Symbol "Image"); ("Name", PDF.Symbol (Printf.sprintf "G%d" idx)); ("Width", PDF.Int img.LoadImage.bm_width); ("Height", PDF.Int img.LoadImage.bm_height); ("ColorSpace", colsp); ("BitsPerComponent", PDF.Int bits) ] (image_data img conv)); obj }; value new_pdf_image state idx file = do { let obj = PDF.alloc_object state.pdf; let fsp = PDF.alloc_object state.pdf; let ef = PDF.alloc_object state.pdf; let buf = IO.make_rand_in_stream file; let bboxes = PDF.get_dimensions file; FIX state.images := state.images @ [(file, obj)]; PDF.set_object state.pdf obj (PDF.Stream [ ("Type", PDF.Symbol "XObject"); ("Subtype", PDF.Symbol "Form"); ("FormType", PDF.Int 1); ("Name", PDF.Symbol (Printf.sprintf "G%d" idx)); ("BBox", PDF.Array [PDF.Float x0; PDF.Float y0; PDF.Float x1; PDF.Float y1]); ("Ref", PDF.Dictionary [("F", PDF.Reference fsp 0); ("Page", PDF.Int 1) ]) ] (IO.make_string_stream "")); PDF.set_object state.pdf fsp (PDF.Dictionary [ ("Type", PDF.Symbol "Filespec"); ("F", PDF.String (IO.make_string_stream (Printf.sprintf "G%d" idx))); ("EF", PDF.Dictionary [("F", PDF.Reference ef 0)]) ]); PDF.set_object state.pdf ef (PDF.Stream [("Type", PDF.Symbol "EmbeddedFile")] buf); obj }; value new_image state idx file fmt = do { let obj = match fmt with [ LoadImage.PDF -> new_pdf_image state idx file | _ -> new_bitmap_image state idx file ]; state.images := state.images @ [(file, obj)] }; value load_image state file fmt = do { find 0 state.images where rec find n images = match images with [ [(i, _) :: is] -> do { if i = file then n else find (n + 1) is } | [] -> do { new_image state n file fmt; n } ] }; value select_image state file fmt = do { let n = load_image state file fmt; IO.printf state.os " /G%d " n }; (* text mode *) value begin_text_mode state font_major font_minor font_size x_pos y_pos = do { let x = pt_to_bp x_pos; let y = pt_to_bp y_pos; let size = pt_to_bp font_size; match state.text_state with [ None -> IO.printf state.os "BT /F%d.%d %f Tf %f %f Td " font_major font_minor size x y | Some ts -> do { if ts.font_major <> font_major || ts.font_minor <> font_minor || ts.font_size <> size then IO.printf state.os "/F%d.%d %f Tf " font_major font_minor size else (); IO.printf state.os "%f %f Td " (x -. ts.x_pos) (y -. ts.y_pos) } ]; state.text_state := Some { font_major = font_major; font_minor = font_minor; font_size = size; x_pos = x; y_pos = y } }; value end_text_mode state = match state.text_state with [ None -> () | Some _ -> do { IO.write_string state.os "ET "; state.text_state := None } ]; (* page contents *) value rec write_box state x y box = match box with [ Empty -> () | Rule w h -> write_rule state x y w h | SimpleGlyph g f -> write_char state x y g f | Image w h f fmt -> write_image state x y w h f fmt | Group bs -> write_group state x y bs | Command cmd -> match cmd with [ `DVI_Special _ -> () ] ] and write_rule state x y width height = do { end_text_mode state; IO.printf state.os "%f %f %f %f re f " (pt_to_bp x) (pt_to_bp y) (pt_to_bp width) (pt_to_bp height) ; () } and write_char state x y c f = do { let (fn, cn) = load_font state f c; begin_text_mode state fn (cn / 0x100) f.at_size x y; IO.printf state.os "<%02x> Tj " (cn land 0xff); () } and write_image state x y width height file fmt = do { end_text_mode state; IO.printf state.os "q %f 0 0 %f %f %f cm " (pt_to_bp width) (pt_to_bp height) (pt_to_bp x) (pt_to_bp y); select_image state file fmt; IO.write_string state.os "Do Q " } and write_path state x y path_cmd path = do { let rec draw_path cur_x cur_y path = match path with [ [] -> match path_cmd with [ Graphic.Stroke -> IO.write_string state.os "S " | Graphic.Fill -> IO.write_string state.os "f " | Graphic.Clip -> IO.write_string state.os "W n " ] | [(ax,ay,bx,by,cx,cy,dx,dy) :: ps] -> do { if ax <>/ cur_x || ay <>/ cur_y then do { match path_cmd with [ Graphic.Stroke -> IO.write_string state.os "S " | Graphic.Fill -> IO.write_string state.os "f " | Graphic.Clip -> IO.write_string state.os "W n " ]; IO.printf state.os "%f %f m " (pt_to_bp (x +/ ax)) (pt_to_bp (y +/ ay)) } else (); IO.printf state.os "%f %f %f %f %f %f c " (pt_to_bp (x +/ bx)) (pt_to_bp (y +/ by)) (pt_to_bp (x +/ cx)) (pt_to_bp (y +/ cy)) (pt_to_bp (x +/ dx)) (pt_to_bp (y +/ dy)); draw_path dx dy ps } ]; match path with [ [] -> () | [(ax,ay,_,_,_,_,_,_) :: _] -> do { end_text_mode state; Choose arbitrary coordinates for the current point . Just make sure they are different from the first point of the path . Just make sure they are different from the first point of the path. *) IO.printf state.os "%f %f m " (pt_to_bp (x +/ ax)) (pt_to_bp (y +/ ay)); draw_path ax ay path } ] } and write_group state x y gfx_cmds = do { let set_colour col = match col with [ Graphic.Grey x -> do { IO.printf state.os "%f g\n" (float_of_num x) ; () } | Graphic.RGB r g b -> do { IO.printf state.os "%f %f %f rg\n" (float_of_num r) (float_of_num g) (float_of_num b) ; () } | Graphic.CMYK c m y k -> do { IO.printf state.os "%f %f %f %f k\n" (float_of_num c) (float_of_num m) (float_of_num y) (float_of_num k) ; () } ]; let set_alpha a = do { FIX () }; let set_line_width w = do { end_text_mode state; IO.printf state.os "%f w\n" (pt_to_bp w) }; let set_line_cap c = do { end_text_mode state; match c with [ Graphic.Butt -> IO.write_string state.os "0 J\n" | Graphic.Circle -> IO.write_string state.os "1 J\n" | Graphic.Square -> IO.write_string state.os "2 J\n" ] }; let set_line_join j = do { end_text_mode state; match j with [ Graphic.Miter -> IO.write_string state.os "0 j\n" | Graphic.Round -> IO.write_string state.os "1 j\n" | Graphic.Bevel -> IO.write_string state.os "2 j\n" ] }; let set_miter_limit l = do { end_text_mode state; IO.printf state.os "%f M\n" (float_of_num l) }; let write_gfx cmd = match cmd with [ Graphic.PutBox dx dy b -> write_box state (x +/ dx) (y +/ dy) b | Graphic.Draw pc p -> write_path state x y pc p | Graphic.SetColour col -> set_colour col | Graphic.SetAlpha a -> set_alpha a | Graphic.SetBgColour _ -> assert False | Graphic.SetLineWidth w -> set_line_width w | Graphic.SetLineCap c -> set_line_cap c | Graphic.SetLineJoin j -> set_line_join j | Graphic.SetMiterLimit l -> set_miter_limit l ]; end_text_mode state; IO.write_string state.os "q "; List.iter write_gfx gfx_cmds; end_text_mode state; IO.write_string state.os "Q " }; (* document structure *) value create_page state parent page = do { let page_obj = PDF.alloc_object state.pdf; let contents = PDF.alloc_object state.pdf; let old_os = state.os; (* save old stream *) state.os := IO.make_buffer_stream 0x1000; write_box state num_zero page.p_height page.p_contents; PDF.set_object state.pdf contents (PDF.Stream [] (IO.coerce_ir state.os)); PDF.set_object state.pdf page_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Page"); ("Parent", PDF.Reference parent 0); ("MediaBox", PDF.Array [PDF.Int 0; PDF.Int 0; PDF.Float (pt_to_bp page.p_width); PDF.Float (pt_to_bp page.p_height)]); ("Contents", PDF.Reference contents 0) ]); state.os := old_os; (* restore stream *) page_obj }; value create_pdf state pages = do { let rec get_font_refs i fonts = match fonts with [ [] -> [] | [f :: fs] -> do { let objs = make_font_obj state i f; iter 0 objs where rec iter n objs = match objs with [ [] -> get_font_refs (i + 1) fs | [o::os] -> [ ( Printf.sprintf "F%d.%d" i n, PDF.Reference o 0 ) :: iter (n + 1) os] ] } ]; let rec get_image_refs n images = match images with [ [] -> [] | [(_, obj) :: is] -> [( Printf.sprintf "G%d" n, PDF.Reference obj 0 ) :: get_image_refs (n + 1) is] ]; let root_obj = PDF.alloc_object state.pdf; let pages_obj = PDF.alloc_object state.pdf; let page_refs = List.map (create_page state pages_obj) pages; PDF.set_root state.pdf (PDF.Reference root_obj 0); PDF.set_object state.pdf pages_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Pages"); ("Resources", PDF.Dictionary [ ("Font", PDF.Dictionary (get_font_refs 0 state.fonts)); ("XObject", PDF.Dictionary (get_image_refs 0 state.images)) ]); ("Count", PDF.Int (List.length pages)); ("Kids", PDF.Array (List.map (fun obj -> PDF.Reference obj 0) page_refs)) ]); PDF.set_object state.pdf root_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Catalog"); ("Pages", PDF.Reference pages_obj 0) ]) }; value write_pdf_file name _comment pages = do { let state = new_state name; create_pdf state pages; PDF.finish_pdf_file state.pdf };
null
https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/Runtime/GeneratePDF.ml
ocaml
minimal glyph index (from font-metric) number of used glyphs mapping internal glyph-index -> PDF index filename, object id font subset: "AAAAAA+" ^ fm.ps_name images text mode page contents document structure save old stream restore stream
open XNum; open Unicode.Types; open GlyphMetric; open FontMetric; open Logging; type font_ref = { font : font_metric; }; type text_state = { font_major : int; font_minor : int; font_size : float; x_pos : float; y_pos : float }; type state = { pdf : PDF.pdf_file IO.ostream; os : mutable IO.iorstream; fonts : mutable list font_ref; images : mutable list image_ref; text_state : mutable option text_state }; value new_state filename = { pdf = PDF.create_pdf_file filename 1.4; os = IO.make_buffer_stream 0x10000; fonts = []; images = []; text_state = None }; value pt_to_bp x = float_of_num (num_of_ints 7200 7227 */ x); value write_bitmap cs bm = do { if bm.Bitmap.bm_width > 0 && bm.Bitmap.bm_height > 0 then do { IO.printf cs "BI /IM true /D [1 0] /W %d /H %d ID " bm.Bitmap.bm_width bm.Bitmap.bm_height; IO.write_string cs bm.Bitmap.bm_data; IO.write_string cs "EI " } else () }; value bitmap_to_type3_glyph state fm g = do { let gm = fm.glyph_metric.(g - fm.first_glyph); let g = fm.get_glyph_bitmap fm g; let cs = IO.make_buffer_stream 0x100; let hdpi = 72.27 /. 72.0 *. g.GlyphBitmap.g_hdpp; let vdpi = 72.27 /. 72.0 *. g.GlyphBitmap.g_vdpp; let min_x = float_of_int g.GlyphBitmap.g_min_x /. hdpi; let min_y = float_of_int g.GlyphBitmap.g_min_y /. vdpi; let max_x = float_of_int g.GlyphBitmap.g_max_x /. hdpi; let max_y = float_of_int g.GlyphBitmap.g_max_y /. vdpi; IO.printf cs "%f 0 %f %f %f %f d1 " (pt_to_bp gm.gm_width) min_x min_y max_x max_y; if g.GlyphBitmap.g_bitmap.Bitmap.bm_width > 0 && g.GlyphBitmap.g_bitmap.Bitmap.bm_height > 0 then do { IO.printf cs "1 0 0 1 %f %f cm %f 0 0 %f 0 0 cm " min_x min_y (float_of_int (g.GlyphBitmap.g_max_x - g.GlyphBitmap.g_min_x + 1) /. hdpi) (float_of_int (g.GlyphBitmap.g_max_y - g.GlyphBitmap.g_min_y + 1) /. vdpi); write_bitmap cs g.GlyphBitmap.g_bitmap; } else (); let contents = PDF.alloc_object state.pdf; PDF.set_object state.pdf contents (PDF.Stream [] (IO.coerce_ir cs)); ((min_x, min_y, max_x, max_y), PDF.Reference contents 0) }; value font_encoding fm encoding = do { let rec get_name_list i list = do { if i < 0 then list else get_name_list (i-1) [ PDF.Symbol (fm.get_glyph_name encoding.(i)) :: list ] }; PDF.Dictionary [("Type", PDF.Symbol "Encoding"); ("Differences", PDF.Array [PDF.Int 0 :: get_name_list (Array.length encoding - 1) [] ])] }; value write_cmap stream fm font_name encoding = do { IO.write_string stream "%!PS-Adobe-3.0 Resource-CMap\n"; IO.write_string stream "%%DocumentNeededResources: ProcSet (CIDInit)\n"; IO.write_string stream "%%IncludeResource: ProcSet (CIDInit)\n"; IO.printf stream "%%BeginResource: CMap (CM-%s)\n" font_name; IO.printf stream "%%Title: (CM-%s ant %s 0)\n" font_name font_name; IO.write_string stream "%%Version: 1.000\n"; IO.write_string stream "%%EndComments\n"; IO.write_string stream "/CIDInit /ProcSet findresource begin\n"; IO.write_string stream "12 dict begin\n"; IO.write_string stream "begincmap\n"; IO.write_string stream "/CIDSystemInfo\n"; IO.write_string stream "<< /Registry (ant)\n"; IO.printf stream "/Ordering (%s)\n" font_name; IO.write_string stream "/Supplement 0\n"; IO.write_string stream ">> def\n"; IO.printf stream "/CMapName /CM-%s def\n" font_name; IO.write_string stream "/CMapType 2 def\n"; IO.write_string stream "1 begincodespacerange\n"; IO.write_string stream "<00> <FF>\n"; IO.write_string stream "endcodespacerange\n"; IO.printf stream "%d beginbfchar\n" (Array.length encoding); for i = 0 to Array.length encoding - 1 do { IO.printf stream "<%02x> <" i; match get_unicode fm (Substitute.Simple encoding.(i)) with [ [||] -> IO.write_string stream "0000" | str -> Array.iter (fun c -> IO.printf stream "%04x" c) str ]; IO.write_string stream ">\n" }; IO.write_string stream "endbfchar\n"; IO.write_string stream "endcmap\n"; IO.write_string stream "CMapName currentdict /CMap defineresource pop\n"; IO.write_string stream "end\n"; IO.write_string stream "end\n"; IO.write_string stream "%%EndResource\n"; IO.write_string stream "%%EOF\n" }; value new_type3_font state font_name fm encoding = do { log_string "\n#E: New Font [Type 3]"; let scale = pt_to_bp (num_one // fm.at_size); let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (pt_to_bp gm.gm_width) }) encoding; let rec calc_glyph_data n dict ((min_x, min_y, max_x, max_y) as bounds) = do { if n >= Array.length encoding then (bounds, dict) else do { let g = encoding.(n); let ((x1, y1, x2, y2), bitmap) = bitmap_to_type3_glyph state fm g; calc_glyph_data (n + 1) [ (fm.get_glyph_name g, bitmap) :: dict] (min min_x x1, min min_y y1, max max_x x2, max max_y y2) } }; let ((min_x, min_y, max_x, max_y), char_procs) = calc_glyph_data 0 [] (0.0, 0.0, 0.0, 0.0); let cmap = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; let cmap_data = IO.make_buffer_stream 0x1000; write_cmap cmap_data fm font_name encoding; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "Type3"); ("FontBBox", PDF.Array [PDF.Float min_x; PDF.Float min_y; PDF.Float max_x; PDF.Float max_y]); ("FontMatrix", PDF.Array [PDF.Float scale; PDF.Int 0; PDF.Int 0; PDF.Float scale; PDF.Int 0; PDF.Int 0]); ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("CharProcs", PDF.Dictionary char_procs); ("Encoding", font_encoding fm encoding); ("Resources", PDF.Dictionary []); ("ToUnicode", PDF.Reference cmap 0) ]); obj }; value new_type1_font state font_name fm encoding = do { log_string "\n#E: New Font [Type 1]: "; log_string font_name; log_string "."; let scale x = float_of_num (x */ num_of_int 1000 // fm.at_size); let is_cff = match fm.font_type with [ OpenTypeCFF -> True | PostScript -> False | _ -> assert False ]; let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (scale gm.gm_width) }) encoding; log_string "\n#E: New Font: Stage 0-0."; let (max_width, max_height, max_depth) = Array.fold_left (fun (w,h,d) n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); (max_num w gm.gm_width, max_num h gm.gm_height, max_num d gm.gm_depth) }) (num_zero, num_zero, num_zero) encoding; let cmap = PDF.alloc_object state.pdf; let ff = PDF.alloc_object state.pdf; let fd = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; log_string "\n#E: New Font: Stage 0-1."; let cmap_data = IO.make_buffer_stream 0x1000; log_string "\n#E: New Font: Stage 0-2."; write_cmap cmap_data fm font_name encoding; log_string "\n#E: New Font: Stage 0-3."; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); log_string "\n#E: New Font: Stage 0-4."; if is_cff then do { let font = OpenType.read_font_tables fm.file_name; let cff = OpenType.get_cff font; let font_data = IO.from_string cff; log_string "\n#E: CFF: "; log_string fm.file_name; log_string "."; let x = PDF.set_object state.pdf ff (PDF.Stream [("Subtype", PDF.Symbol "Type1C")] (IO.coerce_ir font_data)); log_string "\n#E: New Font: Stage 0-5."; x } else do { let font_data = IO.make_buffer_stream 0x1000; let (len1, len2, len3) = Type1.embedd_type1_font fm.file_name (IO.coerce_or font_data); log_string "\n#E: New Font: Stage 0-6."; PDF.set_object state.pdf ff (PDF.Stream [("Length1", PDF.Int len1); ("Length2", PDF.Int len2); ("Length3", PDF.Int len3)] (IO.coerce_ir font_data)) }; log_string "\n#E: New Font: Stage 1."; PDF.set_object state.pdf fd (PDF.Dictionary [ ("Type", PDF.Symbol "FontDescriptor"); ("FontName", PDF.Symbol fm.ps_name); ("Flags", PDF.Int 0x4); ("FontBBox", PDF.Array [PDF.Int 0; PDF.Float (scale (minus_num max_depth)); PDF.Float (scale max_width); PDF.Float (scale max_height)]); ("ItalicAngle", PDF.Int 0); ("Ascent", PDF.Float (scale max_height)); ("Descent", PDF.Float (scale (minus_num max_depth))); ("CapHeight", PDF.Float (scale max_height)); ("StemV", PDF.Float (scale fm.parameter.rule_thickness)); (if is_cff then "FontFile3" else "FontFile", PDF.Reference ff 0) ]); log_string "\n#E: New Font: Stage 2."; PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "Type1"); ("BaseFont", PDF.Symbol fm.ps_name); ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("Encoding", font_encoding fm encoding); ("ToUnicode", PDF.Reference cmap 0); ("FontDescriptor", PDF.Reference fd 0) ]); log_string "\n#E: [Type 1]: done."; obj }; value new_truetype_font state font_name fm encoding = do { log_string "\n#E: New Font [True Type]"; let scale x = float_of_num (x */ num_of_int 1000 // fm.at_size); let width_array = Array.map (fun n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); PDF.Float (scale gm.gm_width) }) encoding; let (max_width, max_height, max_depth) = Array.fold_left (fun (w,h,d) n -> do { let gm = fm.glyph_metric.(n - fm.first_glyph); (max_num w gm.gm_width, max_num h gm.gm_height, max_num d gm.gm_depth) }) (num_zero, num_zero, num_zero) encoding; let cmap = PDF.alloc_object state.pdf; let ff = PDF.alloc_object state.pdf; let fd = PDF.alloc_object state.pdf; let obj = PDF.alloc_object state.pdf; let cmap_data = IO.make_buffer_stream 0x1000; write_cmap cmap_data fm font_name encoding; PDF.set_object state.pdf cmap (PDF.Stream [] (IO.coerce_ir cmap_data)); let font = OpenType.read_font_tables fm.file_name; let subset = IO.make_buffer_stream 0x10000; OpenType.write_subset (IO.coerce_o subset) font encoding; let len = IO.bytes_written subset; PDF.set_object state.pdf ff (PDF.Stream [("Length1", PDF.Int len)] (IO.coerce_ir subset)); PDF.set_object state.pdf fd (PDF.Dictionary [ ("Type", PDF.Symbol "FontDescriptor"); ("FontName", PDF.Symbol fm.ps_name); ("Flags", PDF.Int 0x4); ("FontBBox", PDF.Array [PDF.Int 0; PDF.Float (scale (minus_num max_depth)); PDF.Float (scale max_width); PDF.Float (scale max_height)]); ("ItalicAngle", PDF.Int 0); ("Ascent", PDF.Float (scale max_height)); ("Descent", PDF.Float (scale (minus_num max_depth))); ("CapHeight", PDF.Float (scale max_height)); ("StemV", PDF.Float (scale fm.parameter.rule_thickness)); ("FontFile2", PDF.Reference ff 0) ]); PDF.set_object state.pdf obj (PDF.Dictionary [ ("Type", PDF.Symbol "Font"); ("Subtype", PDF.Symbol "TrueType"); ("BaseFont", PDF.Symbol fm.ps_name); ("FirstChar", PDF.Int 0); ("LastChar", PDF.Int (Array.length encoding - 1)); ("Widths", PDF.Array (Array.to_list width_array)); ("ToUnicode", PDF.Reference cmap 0); ("FontDescriptor", PDF.Reference fd 0) ]); obj }; value new_font state font = do { log_string "\n#E: New Font"; let n = List.length state.fonts; let fd = { font = font; first_glyph_index = font.first_glyph; used_glyphs = 0; glyph_map = Array.make (font.last_glyph - font.first_glyph + 1) (-1) }; state.fonts := state.fonts @ [fd]; (n, fd) }; value make_font_obj state font_number font_def = do { log_string "\n#E: Make Font Object"; iter 0 [] where rec iter i objs = do { if i >= font_def.used_glyphs then List.rev objs else do { let encoding = Array.make (min 0x100 (font_def.used_glyphs - i)) (-1); select all glyphs mapped to numbers between i * 0x100 and i * 0x100 + 0xff Array.iteri (fun x y -> do { if y >= i && y < i + 0x100 then encoding.(y - i) := x + font_def.first_glyph_index else () }) font_def.glyph_map; let new_font = match font_def.font.font_type with [ PostScript | OpenTypeCFF -> new_type1_font | TrueType -> new_truetype_font | Other -> new_type3_font ]; let obj = new_font state (Printf.sprintf "F%d.%d" font_number (i / 0x100)) font_def.font encoding; iter (i + 0x100) [obj :: objs] } } }; value get_glyph_index font_def char = do { log_string "\n#E: Get Glyph Index"; let i = font_def.glyph_map.(char - font_def.first_glyph_index); if i >= 0 then i else do { font_def.glyph_map.(char - font_def.first_glyph_index) := font_def.used_glyphs; font_def.used_glyphs := font_def.used_glyphs + 1; font_def.used_glyphs - 1 } }; value load_font state font char = do { log_string "\n#E: Load Font "; log_string font.name; log_string "."; find 0 state.fonts where rec find i fonts = match fonts with [ [f :: fs] -> do { if f.font == font then (i, get_glyph_index f char) else find (i + 1) fs } | [] -> do { let (i, fd) = new_font state font; (i, get_glyph_index fd char) } ] }; value new_bitmap_image state idx file = do { let conv_id cs s = do { IO.write_string cs s }; let conv_rgba cs s = do { for i = 0 to String.length s / 4 - 1 do { IO.write_char cs s.[4*i]; IO.write_char cs s.[4*i+1]; IO.write_char cs s.[4*i+2] } }; let image_info img = match img.LoadImage.bm_format with [ LoadImage.RGB -> (PDF.Symbol "DeviceRGB", conv_id) | LoadImage.RGBA -> (PDF.Symbol "DeviceRGB", conv_rgba) | LoadImage.CMYK -> (PDF.Symbol "DeviceCMYK", conv_id) | LoadImage.Indexed cm -> (PDF.Array [PDF.Symbol "Indexed"; PDF.Symbol "DeviceRGB"; PDF.Int ((2 lsl img.LoadImage.bm_depth) - 1); PDF.String (IO.make_string_stream cm)], conv_id) ]; let image_data img conv = do { let cs = IO.make_buffer_stream (img.LoadImage.bm_width * img.LoadImage.bm_height / 8); for y = 0 to img.LoadImage.bm_height - 1 do { conv cs (img.LoadImage.bm_scanline y) }; IO.coerce_ir cs }; let obj = PDF.alloc_object state.pdf; state.images := state.images @ [(file, obj)]; let img = LoadImage.read_bitmap file; let (colsp, conv) = image_info img; let bits = if img.LoadImage.bm_depth <= 8 then 8 else 16; PDF.set_object state.pdf obj (PDF.Stream [ ("Type", PDF.Symbol "XObject"); ("Subtype", PDF.Symbol "Image"); ("Name", PDF.Symbol (Printf.sprintf "G%d" idx)); ("Width", PDF.Int img.LoadImage.bm_width); ("Height", PDF.Int img.LoadImage.bm_height); ("ColorSpace", colsp); ("BitsPerComponent", PDF.Int bits) ] (image_data img conv)); obj }; value new_pdf_image state idx file = do { let obj = PDF.alloc_object state.pdf; let fsp = PDF.alloc_object state.pdf; let ef = PDF.alloc_object state.pdf; let buf = IO.make_rand_in_stream file; let bboxes = PDF.get_dimensions file; FIX state.images := state.images @ [(file, obj)]; PDF.set_object state.pdf obj (PDF.Stream [ ("Type", PDF.Symbol "XObject"); ("Subtype", PDF.Symbol "Form"); ("FormType", PDF.Int 1); ("Name", PDF.Symbol (Printf.sprintf "G%d" idx)); ("BBox", PDF.Array [PDF.Float x0; PDF.Float y0; PDF.Float x1; PDF.Float y1]); ("Ref", PDF.Dictionary [("F", PDF.Reference fsp 0); ("Page", PDF.Int 1) ]) ] (IO.make_string_stream "")); PDF.set_object state.pdf fsp (PDF.Dictionary [ ("Type", PDF.Symbol "Filespec"); ("F", PDF.String (IO.make_string_stream (Printf.sprintf "G%d" idx))); ("EF", PDF.Dictionary [("F", PDF.Reference ef 0)]) ]); PDF.set_object state.pdf ef (PDF.Stream [("Type", PDF.Symbol "EmbeddedFile")] buf); obj }; value new_image state idx file fmt = do { let obj = match fmt with [ LoadImage.PDF -> new_pdf_image state idx file | _ -> new_bitmap_image state idx file ]; state.images := state.images @ [(file, obj)] }; value load_image state file fmt = do { find 0 state.images where rec find n images = match images with [ [(i, _) :: is] -> do { if i = file then n else find (n + 1) is } | [] -> do { new_image state n file fmt; n } ] }; value select_image state file fmt = do { let n = load_image state file fmt; IO.printf state.os " /G%d " n }; value begin_text_mode state font_major font_minor font_size x_pos y_pos = do { let x = pt_to_bp x_pos; let y = pt_to_bp y_pos; let size = pt_to_bp font_size; match state.text_state with [ None -> IO.printf state.os "BT /F%d.%d %f Tf %f %f Td " font_major font_minor size x y | Some ts -> do { if ts.font_major <> font_major || ts.font_minor <> font_minor || ts.font_size <> size then IO.printf state.os "/F%d.%d %f Tf " font_major font_minor size else (); IO.printf state.os "%f %f Td " (x -. ts.x_pos) (y -. ts.y_pos) } ]; state.text_state := Some { font_major = font_major; font_minor = font_minor; font_size = size; x_pos = x; y_pos = y } }; value end_text_mode state = match state.text_state with [ None -> () | Some _ -> do { IO.write_string state.os "ET "; state.text_state := None } ]; value rec write_box state x y box = match box with [ Empty -> () | Rule w h -> write_rule state x y w h | SimpleGlyph g f -> write_char state x y g f | Image w h f fmt -> write_image state x y w h f fmt | Group bs -> write_group state x y bs | Command cmd -> match cmd with [ `DVI_Special _ -> () ] ] and write_rule state x y width height = do { end_text_mode state; IO.printf state.os "%f %f %f %f re f " (pt_to_bp x) (pt_to_bp y) (pt_to_bp width) (pt_to_bp height) ; () } and write_char state x y c f = do { let (fn, cn) = load_font state f c; begin_text_mode state fn (cn / 0x100) f.at_size x y; IO.printf state.os "<%02x> Tj " (cn land 0xff); () } and write_image state x y width height file fmt = do { end_text_mode state; IO.printf state.os "q %f 0 0 %f %f %f cm " (pt_to_bp width) (pt_to_bp height) (pt_to_bp x) (pt_to_bp y); select_image state file fmt; IO.write_string state.os "Do Q " } and write_path state x y path_cmd path = do { let rec draw_path cur_x cur_y path = match path with [ [] -> match path_cmd with [ Graphic.Stroke -> IO.write_string state.os "S " | Graphic.Fill -> IO.write_string state.os "f " | Graphic.Clip -> IO.write_string state.os "W n " ] | [(ax,ay,bx,by,cx,cy,dx,dy) :: ps] -> do { if ax <>/ cur_x || ay <>/ cur_y then do { match path_cmd with [ Graphic.Stroke -> IO.write_string state.os "S " | Graphic.Fill -> IO.write_string state.os "f " | Graphic.Clip -> IO.write_string state.os "W n " ]; IO.printf state.os "%f %f m " (pt_to_bp (x +/ ax)) (pt_to_bp (y +/ ay)) } else (); IO.printf state.os "%f %f %f %f %f %f c " (pt_to_bp (x +/ bx)) (pt_to_bp (y +/ by)) (pt_to_bp (x +/ cx)) (pt_to_bp (y +/ cy)) (pt_to_bp (x +/ dx)) (pt_to_bp (y +/ dy)); draw_path dx dy ps } ]; match path with [ [] -> () | [(ax,ay,_,_,_,_,_,_) :: _] -> do { end_text_mode state; Choose arbitrary coordinates for the current point . Just make sure they are different from the first point of the path . Just make sure they are different from the first point of the path. *) IO.printf state.os "%f %f m " (pt_to_bp (x +/ ax)) (pt_to_bp (y +/ ay)); draw_path ax ay path } ] } and write_group state x y gfx_cmds = do { let set_colour col = match col with [ Graphic.Grey x -> do { IO.printf state.os "%f g\n" (float_of_num x) ; () } | Graphic.RGB r g b -> do { IO.printf state.os "%f %f %f rg\n" (float_of_num r) (float_of_num g) (float_of_num b) ; () } | Graphic.CMYK c m y k -> do { IO.printf state.os "%f %f %f %f k\n" (float_of_num c) (float_of_num m) (float_of_num y) (float_of_num k) ; () } ]; let set_alpha a = do { FIX () }; let set_line_width w = do { end_text_mode state; IO.printf state.os "%f w\n" (pt_to_bp w) }; let set_line_cap c = do { end_text_mode state; match c with [ Graphic.Butt -> IO.write_string state.os "0 J\n" | Graphic.Circle -> IO.write_string state.os "1 J\n" | Graphic.Square -> IO.write_string state.os "2 J\n" ] }; let set_line_join j = do { end_text_mode state; match j with [ Graphic.Miter -> IO.write_string state.os "0 j\n" | Graphic.Round -> IO.write_string state.os "1 j\n" | Graphic.Bevel -> IO.write_string state.os "2 j\n" ] }; let set_miter_limit l = do { end_text_mode state; IO.printf state.os "%f M\n" (float_of_num l) }; let write_gfx cmd = match cmd with [ Graphic.PutBox dx dy b -> write_box state (x +/ dx) (y +/ dy) b | Graphic.Draw pc p -> write_path state x y pc p | Graphic.SetColour col -> set_colour col | Graphic.SetAlpha a -> set_alpha a | Graphic.SetBgColour _ -> assert False | Graphic.SetLineWidth w -> set_line_width w | Graphic.SetLineCap c -> set_line_cap c | Graphic.SetLineJoin j -> set_line_join j | Graphic.SetMiterLimit l -> set_miter_limit l ]; end_text_mode state; IO.write_string state.os "q "; List.iter write_gfx gfx_cmds; end_text_mode state; IO.write_string state.os "Q " }; value create_page state parent page = do { let page_obj = PDF.alloc_object state.pdf; let contents = PDF.alloc_object state.pdf; state.os := IO.make_buffer_stream 0x1000; write_box state num_zero page.p_height page.p_contents; PDF.set_object state.pdf contents (PDF.Stream [] (IO.coerce_ir state.os)); PDF.set_object state.pdf page_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Page"); ("Parent", PDF.Reference parent 0); ("MediaBox", PDF.Array [PDF.Int 0; PDF.Int 0; PDF.Float (pt_to_bp page.p_width); PDF.Float (pt_to_bp page.p_height)]); ("Contents", PDF.Reference contents 0) ]); page_obj }; value create_pdf state pages = do { let rec get_font_refs i fonts = match fonts with [ [] -> [] | [f :: fs] -> do { let objs = make_font_obj state i f; iter 0 objs where rec iter n objs = match objs with [ [] -> get_font_refs (i + 1) fs | [o::os] -> [ ( Printf.sprintf "F%d.%d" i n, PDF.Reference o 0 ) :: iter (n + 1) os] ] } ]; let rec get_image_refs n images = match images with [ [] -> [] | [(_, obj) :: is] -> [( Printf.sprintf "G%d" n, PDF.Reference obj 0 ) :: get_image_refs (n + 1) is] ]; let root_obj = PDF.alloc_object state.pdf; let pages_obj = PDF.alloc_object state.pdf; let page_refs = List.map (create_page state pages_obj) pages; PDF.set_root state.pdf (PDF.Reference root_obj 0); PDF.set_object state.pdf pages_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Pages"); ("Resources", PDF.Dictionary [ ("Font", PDF.Dictionary (get_font_refs 0 state.fonts)); ("XObject", PDF.Dictionary (get_image_refs 0 state.images)) ]); ("Count", PDF.Int (List.length pages)); ("Kids", PDF.Array (List.map (fun obj -> PDF.Reference obj 0) page_refs)) ]); PDF.set_object state.pdf root_obj (PDF.Dictionary [ ("Type", PDF.Symbol "Catalog"); ("Pages", PDF.Reference pages_obj 0) ]) }; value write_pdf_file name _comment pages = do { let state = new_state name; create_pdf state pages; PDF.finish_pdf_file state.pdf };
1db4b226397328f175088a984d2820aa2c7b64471351da86c4c4ac3381eb6d0f
tel/serv
Rec.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE ExplicitNamespaces # {-# LANGUAGE GADTs #-} # LANGUAGE PolyKinds # | Re - exports of useful " Data . Vinyl " ' Rec ' types module Serv.Wai.Rec ( -- * Specialized records * * ' ' ElField (..) , FieldRec * * ' HList ' , Identity (..) , HList , (=:) , Rec (..) , (<+>) , (++) -- * Type-level methods , type (++) ) where import Data.Functor.Identity import Data.Singletons import Data.Vinyl.Core import Data.Vinyl.TypeLevel FieldRec -- ---------------------------------------------------------------------------- -- | A more kind polymorphic element field than what's normally available in " Data . Vinyl " data ElField field where ElField :: Sing k -> !a -> ElField '(k, a) | A ' FieldRec ' is a record of types tagged by some kind of " name " . type FieldRec hs = Rec ElField hs (=:) :: Sing a -> v -> FieldRec '[ '(a, v) ] s =: v = ElField s v :& RNil HList -- ---------------------------------------------------------------------------- type HList = Rec Identity
null
https://raw.githubusercontent.com/tel/serv/7967761d6c47f13f0edd567f8af9b1c7dc8b9a23/serv-wai/src/Serv/Wai/Rec.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE GADTs # * Specialized records * Type-level methods ---------------------------------------------------------------------------- | A more kind polymorphic element field than what's normally available ----------------------------------------------------------------------------
# LANGUAGE ExplicitNamespaces # # LANGUAGE PolyKinds # | Re - exports of useful " Data . Vinyl " ' Rec ' types module Serv.Wai.Rec ( * * ' ' ElField (..) , FieldRec * * ' HList ' , Identity (..) , HList , (=:) , Rec (..) , (<+>) , (++) , type (++) ) where import Data.Functor.Identity import Data.Singletons import Data.Vinyl.Core import Data.Vinyl.TypeLevel FieldRec in " Data . Vinyl " data ElField field where ElField :: Sing k -> !a -> ElField '(k, a) | A ' FieldRec ' is a record of types tagged by some kind of " name " . type FieldRec hs = Rec ElField hs (=:) :: Sing a -> v -> FieldRec '[ '(a, v) ] s =: v = ElField s v :& RNil HList type HList = Rec Identity
60d496cf08af2a8a0802a919e6b27f67b1fdc59b079fe34969d459622ef616fd
wdebeaum/step
deenergise.lisp
;;;; ;;;; w::deenergise ;;;; (define-words :pos W::V :TEMPL AGENT-AFFECTED-XP-NP-TEMPL :words ( (w::deenergise (senses ((LF-parent ont::deactivate-turn-off) ;change-device-state) (lf-form w::deenergize)) ((LF-parent ont::deactivate-turn-off) ;change-device-state) (templ agent-templ) (Example "Intransitive usage: how do I deenergize ")) )) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/deenergise.lisp
lisp
w::deenergise change-device-state) change-device-state)
(define-words :pos W::V :TEMPL AGENT-AFFECTED-XP-NP-TEMPL :words ( (w::deenergise (senses (lf-form w::deenergize)) (templ agent-templ) (Example "Intransitive usage: how do I deenergize ")) )) ))
46730c0d4ac59acf12acd14acbf5235343e1c6ed0663ae3325e4c2d99ad49c9f
rescript-lang/rescript-compiler
js_record_iter.ml
Copyright ( C ) 2015- , Authors of ReScript * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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. *) open J let unknown _ _ = () let[@inline] option sub self v = match v with None -> () | Some v -> sub self v let rec list sub self x = match x with | [] -> () | x :: xs -> sub self x; list sub self xs type iter = { ident : ident fn; module_id : module_id fn; vident : vident fn; exception_ident : exception_ident fn; for_ident : for_ident fn; expression : expression fn; statement : statement fn; variable_declaration : variable_declaration fn; block : block fn; program : program fn; } and 'a fn = iter -> 'a -> unit let label : label fn = unknown let ident : ident fn = unknown let module_id : module_id fn = fun _self { id = _x0; kind = _x1 } -> _self.ident _self _x0 let required_modules : required_modules fn = fun _self arg -> list _self.module_id _self arg let vident : vident fn = fun _self -> function | Id _x0 -> _self.ident _self _x0 | Qualified (_x0, _x1) -> _self.module_id _self _x0 let exception_ident : exception_ident fn = fun _self arg -> _self.ident _self arg let for_ident : for_ident fn = fun _self arg -> _self.ident _self arg let for_direction : for_direction fn = unknown let property_map : property_map fn = fun _self arg -> list (fun _self (_x0, _x1) -> _self.expression _self _x1) _self arg let length_object : length_object fn = unknown let expression_desc : expression_desc fn = fun _self -> function | Length (_x0, _x1) -> _self.expression _self _x0; length_object _self _x1 | Is_null_or_undefined _x0 -> _self.expression _self _x0 | String_append (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Bool _ -> () | Typeof _x0 -> _self.expression _self _x0 | Js_not _x0 -> _self.expression _self _x0 | Seq (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Cond (_x0, _x1, _x2) -> _self.expression _self _x0; _self.expression _self _x1; _self.expression _self _x2 | Bin (_x0, _x1, _x2) -> _self.expression _self _x1; _self.expression _self _x2 | FlatCall (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Call (_x0, _x1, _x2) -> _self.expression _self _x0; list _self.expression _self _x1 | String_index (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Array_index (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Static_index (_x0, _x1, _x2) -> _self.expression _self _x0 | New (_x0, _x1) -> _self.expression _self _x0; option (fun _self arg -> list _self.expression _self arg) _self _x1 | Var _x0 -> _self.vident _self _x0 | Fun {params; body} -> list _self.ident _self params; _self.block _self body | Str _ -> () | Raw_js_code _ -> () | Array (_x0, _x1) -> list _self.expression _self _x0 | Optional_block (_x0, _x1) -> _self.expression _self _x0 | Caml_block (_x0, _x1, _x2, _x3) -> list _self.expression _self _x0; _self.expression _self _x2 | Caml_block_tag _x0 -> _self.expression _self _x0 | Number _ -> () | Object _x0 -> property_map _self _x0 | Undefined -> () | Null -> () | Await _x0 -> _self.expression _self _x0 let for_ident_expression : for_ident_expression fn = fun _self arg -> _self.expression _self arg let finish_ident_expression : finish_ident_expression fn = fun _self arg -> _self.expression _self arg let case_clause : case_clause fn = fun _self { switch_body = _x0; should_break = _x1; comment = _x2 } -> _self.block _self _x0 let string_clause : string_clause fn = fun _self (_x0, _x1) -> case_clause _self _x1 let int_clause : int_clause fn = fun _self (_x0, _x1) -> case_clause _self _x1 let statement_desc : statement_desc fn = fun _self -> function | Block _x0 -> _self.block _self _x0 | Variable _x0 -> _self.variable_declaration _self _x0 | Exp _x0 -> _self.expression _self _x0 | If (_x0, _x1, _x2) -> _self.expression _self _x0; _self.block _self _x1; _self.block _self _x2 | While (_x0, _x1, _x2, _x3) -> option label _self _x0; _self.expression _self _x1; _self.block _self _x2 | ForRange (_x0, _x1, _x2, _x3, _x4, _x5) -> option for_ident_expression _self _x0; finish_ident_expression _self _x1; _self.for_ident _self _x2; for_direction _self _x3; _self.block _self _x4 | Continue _x0 -> label _self _x0 | Break -> () | Return _x0 -> _self.expression _self _x0 | Int_switch (_x0, _x1, _x2) -> _self.expression _self _x0; list int_clause _self _x1; option _self.block _self _x2 | String_switch (_x0, _x1, _x2) -> _self.expression _self _x0; list string_clause _self _x1; option _self.block _self _x2 | Throw _x0 -> _self.expression _self _x0 | Try (_x0, _x1, _x2) -> _self.block _self _x0; option (fun _self (_x0, _x1) -> _self.exception_ident _self _x0; _self.block _self _x1) _self _x1; option _self.block _self _x2 | Debugger -> () let expression : expression fn = fun _self { expression_desc = _x0; comment = _x1 } -> expression_desc _self _x0 let statement : statement fn = fun _self { statement_desc = _x0; comment = _x1 } -> statement_desc _self _x0 let variable_declaration : variable_declaration fn = fun _self { ident = _x0; value = _x1; property = _x2; ident_info = _x3 } -> _self.ident _self _x0; option _self.expression _self _x1 let block : block fn = fun _self arg -> list _self.statement _self arg let program : program fn = fun _self { block = _x0; exports = _x1; export_set = _x2 } -> _self.block _self _x0 let deps_program : deps_program fn = fun _self { program = _x0; modules = _x1; side_effect = _x2 } -> _self.program _self _x0; required_modules _self _x1 let super : iter = { ident; module_id; vident; exception_ident; for_ident; expression; statement; variable_declaration; block; program; }
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/b0fbc77a531b6fcd42bdf2c134a9397b08fa74e0/jscomp/core/js_record_iter.ml
ocaml
Copyright ( C ) 2015- , Authors of ReScript * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a 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. *) open J let unknown _ _ = () let[@inline] option sub self v = match v with None -> () | Some v -> sub self v let rec list sub self x = match x with | [] -> () | x :: xs -> sub self x; list sub self xs type iter = { ident : ident fn; module_id : module_id fn; vident : vident fn; exception_ident : exception_ident fn; for_ident : for_ident fn; expression : expression fn; statement : statement fn; variable_declaration : variable_declaration fn; block : block fn; program : program fn; } and 'a fn = iter -> 'a -> unit let label : label fn = unknown let ident : ident fn = unknown let module_id : module_id fn = fun _self { id = _x0; kind = _x1 } -> _self.ident _self _x0 let required_modules : required_modules fn = fun _self arg -> list _self.module_id _self arg let vident : vident fn = fun _self -> function | Id _x0 -> _self.ident _self _x0 | Qualified (_x0, _x1) -> _self.module_id _self _x0 let exception_ident : exception_ident fn = fun _self arg -> _self.ident _self arg let for_ident : for_ident fn = fun _self arg -> _self.ident _self arg let for_direction : for_direction fn = unknown let property_map : property_map fn = fun _self arg -> list (fun _self (_x0, _x1) -> _self.expression _self _x1) _self arg let length_object : length_object fn = unknown let expression_desc : expression_desc fn = fun _self -> function | Length (_x0, _x1) -> _self.expression _self _x0; length_object _self _x1 | Is_null_or_undefined _x0 -> _self.expression _self _x0 | String_append (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Bool _ -> () | Typeof _x0 -> _self.expression _self _x0 | Js_not _x0 -> _self.expression _self _x0 | Seq (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Cond (_x0, _x1, _x2) -> _self.expression _self _x0; _self.expression _self _x1; _self.expression _self _x2 | Bin (_x0, _x1, _x2) -> _self.expression _self _x1; _self.expression _self _x2 | FlatCall (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Call (_x0, _x1, _x2) -> _self.expression _self _x0; list _self.expression _self _x1 | String_index (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Array_index (_x0, _x1) -> _self.expression _self _x0; _self.expression _self _x1 | Static_index (_x0, _x1, _x2) -> _self.expression _self _x0 | New (_x0, _x1) -> _self.expression _self _x0; option (fun _self arg -> list _self.expression _self arg) _self _x1 | Var _x0 -> _self.vident _self _x0 | Fun {params; body} -> list _self.ident _self params; _self.block _self body | Str _ -> () | Raw_js_code _ -> () | Array (_x0, _x1) -> list _self.expression _self _x0 | Optional_block (_x0, _x1) -> _self.expression _self _x0 | Caml_block (_x0, _x1, _x2, _x3) -> list _self.expression _self _x0; _self.expression _self _x2 | Caml_block_tag _x0 -> _self.expression _self _x0 | Number _ -> () | Object _x0 -> property_map _self _x0 | Undefined -> () | Null -> () | Await _x0 -> _self.expression _self _x0 let for_ident_expression : for_ident_expression fn = fun _self arg -> _self.expression _self arg let finish_ident_expression : finish_ident_expression fn = fun _self arg -> _self.expression _self arg let case_clause : case_clause fn = fun _self { switch_body = _x0; should_break = _x1; comment = _x2 } -> _self.block _self _x0 let string_clause : string_clause fn = fun _self (_x0, _x1) -> case_clause _self _x1 let int_clause : int_clause fn = fun _self (_x0, _x1) -> case_clause _self _x1 let statement_desc : statement_desc fn = fun _self -> function | Block _x0 -> _self.block _self _x0 | Variable _x0 -> _self.variable_declaration _self _x0 | Exp _x0 -> _self.expression _self _x0 | If (_x0, _x1, _x2) -> _self.expression _self _x0; _self.block _self _x1; _self.block _self _x2 | While (_x0, _x1, _x2, _x3) -> option label _self _x0; _self.expression _self _x1; _self.block _self _x2 | ForRange (_x0, _x1, _x2, _x3, _x4, _x5) -> option for_ident_expression _self _x0; finish_ident_expression _self _x1; _self.for_ident _self _x2; for_direction _self _x3; _self.block _self _x4 | Continue _x0 -> label _self _x0 | Break -> () | Return _x0 -> _self.expression _self _x0 | Int_switch (_x0, _x1, _x2) -> _self.expression _self _x0; list int_clause _self _x1; option _self.block _self _x2 | String_switch (_x0, _x1, _x2) -> _self.expression _self _x0; list string_clause _self _x1; option _self.block _self _x2 | Throw _x0 -> _self.expression _self _x0 | Try (_x0, _x1, _x2) -> _self.block _self _x0; option (fun _self (_x0, _x1) -> _self.exception_ident _self _x0; _self.block _self _x1) _self _x1; option _self.block _self _x2 | Debugger -> () let expression : expression fn = fun _self { expression_desc = _x0; comment = _x1 } -> expression_desc _self _x0 let statement : statement fn = fun _self { statement_desc = _x0; comment = _x1 } -> statement_desc _self _x0 let variable_declaration : variable_declaration fn = fun _self { ident = _x0; value = _x1; property = _x2; ident_info = _x3 } -> _self.ident _self _x0; option _self.expression _self _x1 let block : block fn = fun _self arg -> list _self.statement _self arg let program : program fn = fun _self { block = _x0; exports = _x1; export_set = _x2 } -> _self.block _self _x0 let deps_program : deps_program fn = fun _self { program = _x0; modules = _x1; side_effect = _x2 } -> _self.program _self _x0; required_modules _self _x1 let super : iter = { ident; module_id; vident; exception_ident; for_ident; expression; statement; variable_declaration; block; program; }
d6b2266fbfdde24260efa212c64f19e807900fcfb38d3b42b30de63b3003d33f
naoiwata/sicp
ex3.45.scm
;; ;; @author naoiwata SICP Chapter3 Exercise 3.45 . ;; ; ------------------------------------------------------------------------ ; question ; ------------------------------------------------------------------------ (define (make-account-and-serializer balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((balance-serializer (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (balance-serializer withdraw)) ((eq? m 'deposit) (balance-serializer deposit)) ((eq? m 'balance) balance) ((eq? m 'serializer) balance-serializer) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) (define (deposit account amount) ((account 'deposit) amount)) ; ------------------------------------------------------------------------ ; discussion ; ------------------------------------------------------------------------ Louis の定義した手続きでは , 定義した account と amount に対する balance - serializer 参照するポインタが異なる , . この為 serialized - exchange 手続きを呼び出した時 , exchange 手続きの ( ( account1 ' withdraw ) difference ) ; に注目すると, この (account1 'withdraw) 手続きは (balance-serializer withdraw) 手続きを呼ぶ. ( ( account1 ' withdraw ) difference ) 手続きは balance - serializer として定義され先に直列化されているので , 中の , この後に直列化された ( balance - serializer withdraw ) 手続きを先に評価することができず , ; この serialized-exchange 手続きを評価することができなくなる. ; END
null
https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter3/ex3.45.scm
scheme
@author naoiwata ------------------------------------------------------------------------ question ------------------------------------------------------------------------ ------------------------------------------------------------------------ discussion ------------------------------------------------------------------------ に注目すると, この (account1 'withdraw) 手続きは (balance-serializer withdraw) 手続きを呼ぶ. この serialized-exchange 手続きを評価することができなくなる. END
SICP Chapter3 Exercise 3.45 . (define (make-account-and-serializer balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (let ((balance-serializer (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (balance-serializer withdraw)) ((eq? m 'deposit) (balance-serializer deposit)) ((eq? m 'balance) balance) ((eq? m 'serializer) balance-serializer) (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch)) (define (deposit account amount) ((account 'deposit) amount)) Louis の定義した手続きでは , 定義した account と amount に対する balance - serializer 参照するポインタが異なる , . この為 serialized - exchange 手続きを呼び出した時 , exchange 手続きの ( ( account1 ' withdraw ) difference ) ( ( account1 ' withdraw ) difference ) 手続きは balance - serializer として定義され先に直列化されているので , 中の , この後に直列化された ( balance - serializer withdraw ) 手続きを先に評価することができず ,
3e892f7ef40ec09e12d1a204aea1d20c31b19fcc32ee9b62c164616e07b8f3f8
eeng/mercurius
authenticate.clj
(ns mercurius.accounts.domain.use-cases.authenticate (:require [clojure.spec.alpha :as s] [mercurius.accounts.domain.repositories.user-repository :refer [find-by-username]])) (s/def ::username string?) (s/def ::password string?) (s/def ::command (s/keys :req-un [::username ::password])) (defn- check-password [user password] (when (= (:password user) password) user)) (defn new-authenticate-use-case "Fake implementation, just checks if the credentials match someone on the hardcoded db. In a real scenario we would fetch the user from a repository and check against the encrypted password." [{:keys [user-repo]}] (fn [{:keys [username password] :as command}] (s/assert ::command command) (if-let [user (some-> (find-by-username user-repo username) (check-password password))] [:ok user] [:error :invalid-credentials])))
null
https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/src/mercurius/accounts/domain/use_cases/authenticate.clj
clojure
(ns mercurius.accounts.domain.use-cases.authenticate (:require [clojure.spec.alpha :as s] [mercurius.accounts.domain.repositories.user-repository :refer [find-by-username]])) (s/def ::username string?) (s/def ::password string?) (s/def ::command (s/keys :req-un [::username ::password])) (defn- check-password [user password] (when (= (:password user) password) user)) (defn new-authenticate-use-case "Fake implementation, just checks if the credentials match someone on the hardcoded db. In a real scenario we would fetch the user from a repository and check against the encrypted password." [{:keys [user-repo]}] (fn [{:keys [username password] :as command}] (s/assert ::command command) (if-let [user (some-> (find-by-username user-repo username) (check-password password))] [:ok user] [:error :invalid-credentials])))
4e2e1179d92733d7de21f657753f66d410d976e5df915941618ec61be253bdfe
BranchTaken/Hemlock
cmpable.mli
(** Functors for comparable types. *) open CmpableIntf (** Comparisons for monomorphic types. *) module Make (T : IMono) : SMono with type t := T.t * Comparisons for monomorphic types that include zero in their ranges . module MakeZero (T : IMonoZero) : SMonoZero with type t := T.t (** Comparisons for polymorphic types. *) module MakePoly (T : IPoly) : SPoly with type 'a t := 'a T.t (** Comparisons for polymorphic types. *) module MakePoly2 (T : IPoly2) : SPoly2 with type ('a, 'cmp) t := ('a, 'cmp) T.t (** Comparisons for polymorphic types. *) module MakePoly3 (T : IPoly3) : SPoly3 with type ('k, 'v, 'cmp) t := ('k, 'v, 'cmp) T.t
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/207ede78129be95ec063cf2bb3c955760c2fd303/bootstrap/src/basis/cmpable.mli
ocaml
* Functors for comparable types. * Comparisons for monomorphic types. * Comparisons for polymorphic types. * Comparisons for polymorphic types. * Comparisons for polymorphic types.
open CmpableIntf module Make (T : IMono) : SMono with type t := T.t * Comparisons for monomorphic types that include zero in their ranges . module MakeZero (T : IMonoZero) : SMonoZero with type t := T.t module MakePoly (T : IPoly) : SPoly with type 'a t := 'a T.t module MakePoly2 (T : IPoly2) : SPoly2 with type ('a, 'cmp) t := ('a, 'cmp) T.t module MakePoly3 (T : IPoly3) : SPoly3 with type ('k, 'v, 'cmp) t := ('k, 'v, 'cmp) T.t
73e27d82fb2ccd8803067c66a0a132a9f4d51ddb903a1879a17cb0bd84c5d873
hiroshi-unno/coar
zip_map_int1.ml
let rec loop x = loop x let rec zip x y = if x = 0 then if y = 0 then 0 else loop () else if y = 0 then loop () else 1 + zip (x - 1) (y - 1) let rec map x = if x = 0 then 0 else 1 + map (x - 1) let main n = assert (map (zip n n) = n) [@@@assert "typeof(main) <: int -> unit"]
null
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/benchmarks/OCaml/safety/tacas2015/zip_map_int1.ml
ocaml
let rec loop x = loop x let rec zip x y = if x = 0 then if y = 0 then 0 else loop () else if y = 0 then loop () else 1 + zip (x - 1) (y - 1) let rec map x = if x = 0 then 0 else 1 + map (x - 1) let main n = assert (map (zip n n) = n) [@@@assert "typeof(main) <: int -> unit"]
955a77848d77b37f61157fee8536eb3e7db510cf890c6aa4c98a4cb604c1cbfc
hyperfiddle/electric
electric_call_semanatics.clj
(ns user.electric.electric-call-semanatics (:require [hyperfiddle.electric :as e] [hyperfiddle.rcf :refer [tests tap % with]])) (e/def trace! println) (e/defn Foo [n] (let [x (trace! (+ n 2))] ; this is computed once, as you'd expect (e/fn [y] (+ y x)))) (e/defn Bar [c n] (let [F (Foo. c)] (e/for [x (range n)] (F. x)))) (tests (def !n (atom 3)) (with (e/run (binding [trace! tap] (tap (Bar. 5 (e/watch !n))))) % := 7 % := [7 8 9] (swap! !n inc) % := [7 8 9 10]))
null
https://raw.githubusercontent.com/hyperfiddle/electric/2446937b21440bf4faed8123e2ee544110203cee/src-docs/user/electric/electric_call_semanatics.clj
clojure
this is computed once, as you'd expect
(ns user.electric.electric-call-semanatics (:require [hyperfiddle.electric :as e] [hyperfiddle.rcf :refer [tests tap % with]])) (e/def trace! println) (e/defn Foo [n] (e/fn [y] (+ y x)))) (e/defn Bar [c n] (let [F (Foo. c)] (e/for [x (range n)] (F. x)))) (tests (def !n (atom 3)) (with (e/run (binding [trace! tap] (tap (Bar. 5 (e/watch !n))))) % := 7 % := [7 8 9] (swap! !n inc) % := [7 8 9 10]))
65e60113a535f35d0f77ce30bb74dd6b521d7299b0128758619ea7a4e76e48e7
michiakig/LispInSmallPieces
chap10m.scm
$ I d : , v 4.0 1995/07/10 ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) ;;; This file is part of the files that accompany the book: LISP Implantation Semantique Programmation ( InterEditions , France ) By Christian Queinnec < > ;;; Newest version may be retrieved from: ( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz ;;; Check the README file before using this file. ;;;(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) ;;; The letify generic function that take an AST with possible sharing ;;; and copies it in a pure tree, trying at the same time to insert ;;; let forms where possible. ;;; Only local variables are cloned. Global or predefined variables ;;; stay the same (and are shared between the input and the result of ;;; letify). (define-generic (letify (o Program) env) (update-walk! letify (clone o) env) ) ;;; Tell how to clone Variables. Not useful for the following: ;;; Global-Variable ;;; Predefined-Variable ;;; Local-Variable ;;; Quotation-Variable ;;; Renamed-Local-Variable (introduced by gather-temporaries) ;;; Global-Variable (define-method (clone (o Pseudo-Variable)) (new-Variable) ) ;;; If letify is used in other places, it might be interesting to add ;;; these methods. ;(define-method (clone (o Renamed-Local-Variable)) ; (new-renamed-variable o) ) ;(define-method (clone (o Local-Variable)) ; (new-renamed-variable o) ) (define-method (letify (o Function) env) (let* ((vars (Function-variables o)) (body (Function-body o)) (new-vars (map clone vars)) ) (make-Function new-vars (letify body (append (map cons vars new-vars) env)) ) ) ) ;;; Don't preserve continuations as they are. ;;; Other types of references: ;;; Global-Reference ;;; Predefined-Reference ;;; Free-Reference (introduced by lift!). (define-method (letify (o Local-Reference) env) (let* ((v (Local-Reference-variable o)) (r (assq v env)) ) (if (pair? r) (make-Local-Reference (cdr r)) (letify-error "Disappeared variable" o) ) ) ) (define-method (letify (o Regular-Application) env) (if (Function? (Regular-Application-function o)) (letify (process-closed-application (Regular-Application-function o) (Regular-Application-arguments o) ) env ) (make-Regular-Application (letify (Regular-Application-function o) env) (letify (Regular-Application-arguments o) env) ) ) ) (define-method (letify (o Fix-Let) env) (let* ((vars (Fix-Let-variables o)) (new-vars (map clone vars)) ) (make-Fix-Let new-vars (letify (Fix-Let-arguments o) env) (letify (Fix-Let-body o) (append (map cons vars new-vars) env) ) ) ) ) (define-method (letify (o Box-Creation) env) (let* ((v (Box-Creation-variable o)) (r (assq v env)) ) (if (pair? r) (make-Box-Creation (cdr r)) (letify-error "Disappeared variable" o) ) ) ) ;;; end of chap10m.scm
null
https://raw.githubusercontent.com/michiakig/LispInSmallPieces/0a2762d539a5f4c7488fffe95722790ac475c2ea/src/chap10m.scm
scheme
(((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) This file is part of the files that accompany the book: Newest version may be retrieved from: Check the README file before using this file. (((((((((((((((((((((((((((((((( L i S P )))))))))))))))))))))))))))))))) The letify generic function that take an AST with possible sharing and copies it in a pure tree, trying at the same time to insert let forms where possible. Only local variables are cloned. Global or predefined variables stay the same (and are shared between the input and the result of letify). Tell how to clone Variables. Not useful for the following: Global-Variable Predefined-Variable Local-Variable Quotation-Variable Renamed-Local-Variable (introduced by gather-temporaries) Global-Variable If letify is used in other places, it might be interesting to add these methods. (define-method (clone (o Renamed-Local-Variable)) (new-renamed-variable o) ) (define-method (clone (o Local-Variable)) (new-renamed-variable o) ) Don't preserve continuations as they are. Other types of references: Global-Reference Predefined-Reference Free-Reference (introduced by lift!). end of chap10m.scm
$ I d : , v 4.0 1995/07/10 LISP Implantation Semantique Programmation ( InterEditions , France ) By Christian Queinnec < > ( IP 128.93.2.54 ) ftp.inria.fr : INRIA / Projects / icsla / Books / LiSP*.tar.gz (define-generic (letify (o Program) env) (update-walk! letify (clone o) env) ) (define-method (clone (o Pseudo-Variable)) (new-Variable) ) (define-method (letify (o Function) env) (let* ((vars (Function-variables o)) (body (Function-body o)) (new-vars (map clone vars)) ) (make-Function new-vars (letify body (append (map cons vars new-vars) env)) ) ) ) (define-method (letify (o Local-Reference) env) (let* ((v (Local-Reference-variable o)) (r (assq v env)) ) (if (pair? r) (make-Local-Reference (cdr r)) (letify-error "Disappeared variable" o) ) ) ) (define-method (letify (o Regular-Application) env) (if (Function? (Regular-Application-function o)) (letify (process-closed-application (Regular-Application-function o) (Regular-Application-arguments o) ) env ) (make-Regular-Application (letify (Regular-Application-function o) env) (letify (Regular-Application-arguments o) env) ) ) ) (define-method (letify (o Fix-Let) env) (let* ((vars (Fix-Let-variables o)) (new-vars (map clone vars)) ) (make-Fix-Let new-vars (letify (Fix-Let-arguments o) env) (letify (Fix-Let-body o) (append (map cons vars new-vars) env) ) ) ) ) (define-method (letify (o Box-Creation) env) (let* ((v (Box-Creation-variable o)) (r (assq v env)) ) (if (pair? r) (make-Box-Creation (cdr r)) (letify-error "Disappeared variable" o) ) ) )
39b8aa780834cb173c1e77bd4cd6d09a4577ce7f67041fa64f08cee6bf82b1b0
vmchale/morphism-zoo
Suffix.hs
-- | This module defines variations on a function `suffix`, which does the following: -- -- > λ:> suffix "tails" -- > ["ails","ils","ls","s"] -- -- > λ:> suffix "s" -- > [] module Suffix ( suffix , suffixPattern , suffixPattern2 , suffixList , suffixFunctor , suffixPattern3 , suffixZipper , suffixHylo , suffixPattern4 ) where import Data.Functor.Foldable import Control.Arrow -- | Just wanted this available somewhere mutu :: Recursive t => (Base t (b, a) -> b) -> (Base t (b, a) -> a) -> t -> a mutu f g = snd . cata (f &&& g) -- | This uses a hylomorphism suffixHylo :: [a] -> [[a]] suffixHylo = hylo algebra coalgebra . drop 1 -- | Another one, suggested from online suffixPattern4 :: [a] -> [[a]] suffixPattern4 [] = [] suffixPattern4 [_] = [] suffixPattern4 (_:xs) = xs : suffixPattern xs algebra :: ListF [a] [[a]] -> [[a]] algebra Nil = [] algebra (Cons x xs) = x:xs coalgebra :: [a] -> ListF [a] [a] coalgebra [] = Nil coalgebra (x:xs) = Cons (x:xs) xs -- | This uses recursion schemes suffix :: [a] -> [[a]] suffix = para pseudoalgebra -- | This is not technically an F-algebra in the mathematical sense pseudoalgebra :: (Base [a]) ([a], [[a]]) -> [[a]] pseudoalgebra Nil = mempty pseudoalgebra (Cons _ x) = uncurry go x where go y@(x:xs) suffixes = y:suffixes go _ suffixes = suffixes -- | This uses pattern matching, and reverses the result at the end. suffixPattern :: [a] -> [[a]] suffixPattern x = reverse $ curry (snd . go) x mempty where go ((x:xs), suffixes) = go (xs, if not $ null xs then xs:suffixes else suffixes) go (_, suffixes) = ([], suffixes) -- | This uses pattern matching, and appends the lists to build it in the right order suffixPattern2 :: [a] -> [[a]] suffixPattern2 x = curry (snd . go) x mempty where go ((x:xs), suffixes) = go (xs, if not $ null xs then suffixes ++ [xs] else suffixes) go (_, suffixes) = ([], suffixes) -- | This uses pattern matching wihtout ugliness, but it's partial. It's benchmarked -- to show the problem isn't if-branching. suffixPattern3 :: [a] -> [[a]] suffixPattern3 x = curry (snd . go) x mempty where go ([x], suffixes) = ([], suffixes) go ((x:xs), suffixes) = go (xs, suffixes ++ [xs]) -- | This uses list comprehensions suffixList :: [a] -> [[a]] suffixList x = [ drop n x | n <- [1..(length x - 1)]] -- | This uses functoriality suffixFunctor :: [a] -> [[a]] suffixFunctor x = fmap (flip drop x) [1..(length x -1)] -- | This uses a zipper suffixZipper :: [a] -> [[a]] suffixZipper y@[x] = mempty suffixZipper y@(x:xs) = zipWith drop [1..] $ map (const y) (init y) suffixZipper _ = mempty
null
https://raw.githubusercontent.com/vmchale/morphism-zoo/4f1a040ddb3cb1f0292f94d98d34f3075c97d738/src/Suffix.hs
haskell
| This module defines variations on a function `suffix`, which does the following: > λ:> suffix "tails" > ["ails","ils","ls","s"] > λ:> suffix "s" > [] | Just wanted this available somewhere | This uses a hylomorphism | Another one, suggested from online | This uses recursion schemes | This is not technically an F-algebra in the mathematical sense | This uses pattern matching, and reverses the result at the end. | This uses pattern matching, and appends the lists to build it in the right order | This uses pattern matching wihtout ugliness, but it's partial. It's benchmarked to show the problem isn't if-branching. | This uses list comprehensions | This uses functoriality | This uses a zipper
module Suffix ( suffix , suffixPattern , suffixPattern2 , suffixList , suffixFunctor , suffixPattern3 , suffixZipper , suffixHylo , suffixPattern4 ) where import Data.Functor.Foldable import Control.Arrow mutu :: Recursive t => (Base t (b, a) -> b) -> (Base t (b, a) -> a) -> t -> a mutu f g = snd . cata (f &&& g) suffixHylo :: [a] -> [[a]] suffixHylo = hylo algebra coalgebra . drop 1 suffixPattern4 :: [a] -> [[a]] suffixPattern4 [] = [] suffixPattern4 [_] = [] suffixPattern4 (_:xs) = xs : suffixPattern xs algebra :: ListF [a] [[a]] -> [[a]] algebra Nil = [] algebra (Cons x xs) = x:xs coalgebra :: [a] -> ListF [a] [a] coalgebra [] = Nil coalgebra (x:xs) = Cons (x:xs) xs suffix :: [a] -> [[a]] suffix = para pseudoalgebra pseudoalgebra :: (Base [a]) ([a], [[a]]) -> [[a]] pseudoalgebra Nil = mempty pseudoalgebra (Cons _ x) = uncurry go x where go y@(x:xs) suffixes = y:suffixes go _ suffixes = suffixes suffixPattern :: [a] -> [[a]] suffixPattern x = reverse $ curry (snd . go) x mempty where go ((x:xs), suffixes) = go (xs, if not $ null xs then xs:suffixes else suffixes) go (_, suffixes) = ([], suffixes) suffixPattern2 :: [a] -> [[a]] suffixPattern2 x = curry (snd . go) x mempty where go ((x:xs), suffixes) = go (xs, if not $ null xs then suffixes ++ [xs] else suffixes) go (_, suffixes) = ([], suffixes) suffixPattern3 :: [a] -> [[a]] suffixPattern3 x = curry (snd . go) x mempty where go ([x], suffixes) = ([], suffixes) go ((x:xs), suffixes) = go (xs, suffixes ++ [xs]) suffixList :: [a] -> [[a]] suffixList x = [ drop n x | n <- [1..(length x - 1)]] suffixFunctor :: [a] -> [[a]] suffixFunctor x = fmap (flip drop x) [1..(length x -1)] suffixZipper :: [a] -> [[a]] suffixZipper y@[x] = mempty suffixZipper y@(x:xs) = zipWith drop [1..] $ map (const y) (init y) suffixZipper _ = mempty
3a801cb7e835956a9992570faeb4a003309814a980938ac9da95e078a7896012
danehuang/augurv2
PyXface.hs
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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 Xface.PyXface where import Data.Maybe import Control.Monad.Reader import AstUtil.Var import AstUtil.Pretty import AstUtil.Fresh import Core.DensSyn import Core.CoreSyn import Comm.DistSyn import Core.CoreTySyn import qualified Xface.PySyn as P import Low.LowpPrimSyn import Compile.CompData ---------------------------------------------------------------------- = description | [ Note ] Generates python inferface code . Order : [ hyper_1 , ... , hyper_n , param_1 , ... , param_m , data_1 , ... , ] Generates python inferface code. Order: [ hyper_1, ..., hyper_n, param_1, ..., param_m, data_1, ..., data_l ] -} ----------------------------------- -- == Generate model object type XfaceM = ReaderT XfaceRdr CompM type TIdTy = TVar Typ data XfaceRdr = XR { pi_ty :: Typ , pi_vInit :: TIdTy , pi_genSym :: GenSym } withTyp :: Typ -> XfaceM a -> XfaceM a withTyp ty = local (\rdr -> rdr { pi_ty = ty }) mkAnonPyId :: Typ -> XfaceM TIdTy mkAnonPyId ty = do genSym <- asks pi_genSym v <- lift $ lift $ mkIdIO genSym Anon Local :: XfaceM TIdTy return $ v { t_ty = Just ty } cgLit :: Lit -> P.Lit cgLit (Int i) = P.Int i cgLit (Real d) = P.Dbl d cgDist :: Dop -> Dist -> [Exp TIdTy] -> XfaceM (P.Exp TIdTy) cgDist dop dist es = case dop of Sample -> do vInit <- asks pi_vInit es' <- mapM cgExp es return $ P.Call ("init" ++ pprShow dist) (P.Var vInit : es') _ -> error $ "[PyXface] @cgDist | Shouldn't happen" cgPrim :: Prim -> [P.Exp TIdTy] -> P.Exp TIdTy cgPrim prim es' = case prim of Neg -> error "[PyXface] | TODO neg" Expon -> P.Call "augur_exp" es' Log -> P.Call "augur_log" es' Expit -> P.Call "augur_expit" es' Logit -> P.Call "augur_logit" es' Plus -> P.Binop (es' !! 0) P.Plus (es' !! 1) Minus -> P.Binop (es' !! 0) P.Minus (es' !! 1) Times -> P.Binop (es' !! 0) P.Times (es' !! 1) Div -> P.Binop (es' !! 0) P.Div (es' !! 1) DotProd -> P.Call "augur_dotprod" es' EqEq -> P.Binop (es' !! 0) P.EqEq (es' !! 1) LAnd -> P.Binop (es' !! 0) P.LAnd (es' !! 1) _ -> error $ "[PyXface] @cgPrim | Shouldn't happen: " ++ pprShow prim cgExp :: Exp TIdTy -> XfaceM (P.Exp TIdTy) cgExp (Var x) = return $ P.Var x cgExp (Lit lit) = return $ P.Lit (cgLit lit) cgExp (DistOp dop dist es) = cgDist dop dist es cgExp (Call ce es) = case ce of FnId _ -> error $ "[PyXface] @cgExp | Not supported yet" PrimId prim -> do es' <- mapM cgExp es return $cgPrim prim es' cgExp (Proj e es) = do e' <- cgExp e es' <- mapM cgExp es return $ P.Proj e' es' cgGen :: Gen TIdTy -> XfaceM (P.Gen TIdTy) cgGen (Until e1 e2) = do e1' <- cgExp e1 e2' <- cgExp e2 return $ P.Until e1' e2' genToSize :: Gen TIdTy -> XfaceM (P.Exp TIdTy) genToSize (Until e1 e2) = do e1' <- cgExp e1 e2' <- cgExp e2 return $ P.Binop e2' P.Minus e1' unvecTy :: Typ -> Typ unvecTy (VecTy ty) = ty unvecTy ty = error $ "[PyXface] | Shouldn't happen " ++ pprShow ty tyToInt :: Typ -> Int tyToInt UnitTy = error $ "[PyXface] @tyToInt | Shouldn't happen" tyToInt IntTy = 0 tyToInt RealTy = 1 tyToInt (VecTy _) = 2 tyToInt (MatTy _) = 3 tyToInt (ArrTy _ _) = error $ "[PyXface] @tyToInt | Shouldn't happen" cgPyModParamK :: Fn TIdTy -> ((TIdTy, P.Stmt TIdTy) -> XfaceM (TIdTy, P.Stmt TIdTy)) -> XfaceM (TIdTy, P.Stmt TIdTy) cgPyModParamK (Dens dist pt es) k = do ty <- asks pi_ty vSamp <- mkAnonPyId ty erhs <- cgDist Sample dist es let s = P.Assign vSamp erhs k (vSamp, s) cgPyModParamK (Let x e fn) k = cgPyModParamK fn (\(vTmp, s) -> do e' <- cgExp e k (vTmp, P.Seq (P.Assign x e') s)) cgPyModParamK fn@(Ind _ _) _ = error $ "[PyXface] | Shouldn't happen " ++ pprShow fn cgPyModParamK fn@(Prod _ _) _ = error $ "[PyXface] | Shouldn't happen " ++ pprShow fn cgPyModParamK (Pi x gen fn) k = do ty <- asks pi_ty let ty' = unvecTy ty withTyp ty' (cgPyModParamK fn (k' ty')) where k' ty (vTmp, s) = do vArr <- mkAnonPyId ty esize <- genToSize gen gen' <- cgGen gen let s_arr = P.Assign vArr (P.Call "initArr" [ esize, P.Lit (P.Int (tyToInt ty)) ]) s_store = P.Store vArr [P.Var x] (P.Var vTmp) s_loop = P.Loop x gen' (P.Seq s s_store) k (vArr, P.Seq s_arr s_loop) cgPyModParam :: ModDecls TIdTy -> TIdTy -> Fn TIdTy -> XfaceM (P.Stmt TIdTy) cgPyModParam modDecls vMod fn = do (vTmp, s) <- withTyp (fromJust (getType vMod)) (cgPyModParamK fn return) return $ P.Seq s (P.Assign vMod (P.Var vTmp)) cgPyModParams :: ModDecls TIdTy -> [(TIdTy, Fn TIdTy)] -> XfaceM (P.Decl TIdTy) cgPyModParams modDecls fns = do stmts <- mapM (\(vMod, fn) -> cgPyModParam modDecls vMod fn) fns vInit <- asks pi_vInit let name = mkName "genMod" hypers = getModHyperIds modDecls ret = P.Return (P.List (map (\v -> P.Tup [P.Lit (P.PyStr (nameToStr (varName v))), P.Var v]) (map fst fns))) stmts' = stmts ++ [ ret ] return $ P.Fun name (vInit : hypers) (P.seqStmt stmts') runCgPyModParams :: CompInfo -> ModDecls TIdTy -> [(TIdTy, Fn TIdTy)] -> CompM (P.Decl TIdTy) runCgPyModParams cinfo modDecls fns = do let fns' = filter (\(v, _) -> isModParam (idKind v)) fns vInit <- lift $ mkTyIdIO (getGenSym cinfo) (mkName "initStrat") Local UnitTy v <- runReaderT (cgPyModParams modDecls fns') (XR UnitTy vInit (getGenSym cinfo)) return v ----------------------------------- -- == Generate types cgTyp :: Typ -> String cgTyp IntTy = "PyAugurIntTy()" cgTyp RealTy = "PyAugurRealTy()" cgTyp (VecTy ty) = "PyAugurVecTy(" ++ cgTyp ty ++ ")" cgTyp (MatTy ty) = "PyAugurMatTy(" ++ "2" ++ ", " ++ cgTyp ty ++ ")" cgTyp ty = error $ "@tyToPyTy | Shouldn't happen: " ++ show ty genPyTyp :: ModDecls (TVar Typ) -> String genPyTyp modDecls = let hypers = getModHyperIds modDecls params = getModParamIds modDecls datas = getModDataIds modDecls in "(" ++ f hypers ++ ", " ++ f params ++ ", " ++ f datas ++ ")" where f xs = "[" ++ rendSepBy commasp (map varToStr xs) ++ "]" varToStr v = "(" ++ "\'" ++ pprShow v ++ "\' , " ++ cgTyp (fromJust (t_ty v)) ++ ")"
null
https://raw.githubusercontent.com/danehuang/augurv2/480459bcc2eff898370a4e1b4f92b08ea3ab3f7b/compiler/augur/src/Xface/PyXface.hs
haskell
-------------------------------------------------------------------- --------------------------------- == Generate model object --------------------------------- == Generate types
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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 Xface.PyXface where import Data.Maybe import Control.Monad.Reader import AstUtil.Var import AstUtil.Pretty import AstUtil.Fresh import Core.DensSyn import Core.CoreSyn import Comm.DistSyn import Core.CoreTySyn import qualified Xface.PySyn as P import Low.LowpPrimSyn import Compile.CompData = description | [ Note ] Generates python inferface code . Order : [ hyper_1 , ... , hyper_n , param_1 , ... , param_m , data_1 , ... , ] Generates python inferface code. Order: [ hyper_1, ..., hyper_n, param_1, ..., param_m, data_1, ..., data_l ] -} type XfaceM = ReaderT XfaceRdr CompM type TIdTy = TVar Typ data XfaceRdr = XR { pi_ty :: Typ , pi_vInit :: TIdTy , pi_genSym :: GenSym } withTyp :: Typ -> XfaceM a -> XfaceM a withTyp ty = local (\rdr -> rdr { pi_ty = ty }) mkAnonPyId :: Typ -> XfaceM TIdTy mkAnonPyId ty = do genSym <- asks pi_genSym v <- lift $ lift $ mkIdIO genSym Anon Local :: XfaceM TIdTy return $ v { t_ty = Just ty } cgLit :: Lit -> P.Lit cgLit (Int i) = P.Int i cgLit (Real d) = P.Dbl d cgDist :: Dop -> Dist -> [Exp TIdTy] -> XfaceM (P.Exp TIdTy) cgDist dop dist es = case dop of Sample -> do vInit <- asks pi_vInit es' <- mapM cgExp es return $ P.Call ("init" ++ pprShow dist) (P.Var vInit : es') _ -> error $ "[PyXface] @cgDist | Shouldn't happen" cgPrim :: Prim -> [P.Exp TIdTy] -> P.Exp TIdTy cgPrim prim es' = case prim of Neg -> error "[PyXface] | TODO neg" Expon -> P.Call "augur_exp" es' Log -> P.Call "augur_log" es' Expit -> P.Call "augur_expit" es' Logit -> P.Call "augur_logit" es' Plus -> P.Binop (es' !! 0) P.Plus (es' !! 1) Minus -> P.Binop (es' !! 0) P.Minus (es' !! 1) Times -> P.Binop (es' !! 0) P.Times (es' !! 1) Div -> P.Binop (es' !! 0) P.Div (es' !! 1) DotProd -> P.Call "augur_dotprod" es' EqEq -> P.Binop (es' !! 0) P.EqEq (es' !! 1) LAnd -> P.Binop (es' !! 0) P.LAnd (es' !! 1) _ -> error $ "[PyXface] @cgPrim | Shouldn't happen: " ++ pprShow prim cgExp :: Exp TIdTy -> XfaceM (P.Exp TIdTy) cgExp (Var x) = return $ P.Var x cgExp (Lit lit) = return $ P.Lit (cgLit lit) cgExp (DistOp dop dist es) = cgDist dop dist es cgExp (Call ce es) = case ce of FnId _ -> error $ "[PyXface] @cgExp | Not supported yet" PrimId prim -> do es' <- mapM cgExp es return $cgPrim prim es' cgExp (Proj e es) = do e' <- cgExp e es' <- mapM cgExp es return $ P.Proj e' es' cgGen :: Gen TIdTy -> XfaceM (P.Gen TIdTy) cgGen (Until e1 e2) = do e1' <- cgExp e1 e2' <- cgExp e2 return $ P.Until e1' e2' genToSize :: Gen TIdTy -> XfaceM (P.Exp TIdTy) genToSize (Until e1 e2) = do e1' <- cgExp e1 e2' <- cgExp e2 return $ P.Binop e2' P.Minus e1' unvecTy :: Typ -> Typ unvecTy (VecTy ty) = ty unvecTy ty = error $ "[PyXface] | Shouldn't happen " ++ pprShow ty tyToInt :: Typ -> Int tyToInt UnitTy = error $ "[PyXface] @tyToInt | Shouldn't happen" tyToInt IntTy = 0 tyToInt RealTy = 1 tyToInt (VecTy _) = 2 tyToInt (MatTy _) = 3 tyToInt (ArrTy _ _) = error $ "[PyXface] @tyToInt | Shouldn't happen" cgPyModParamK :: Fn TIdTy -> ((TIdTy, P.Stmt TIdTy) -> XfaceM (TIdTy, P.Stmt TIdTy)) -> XfaceM (TIdTy, P.Stmt TIdTy) cgPyModParamK (Dens dist pt es) k = do ty <- asks pi_ty vSamp <- mkAnonPyId ty erhs <- cgDist Sample dist es let s = P.Assign vSamp erhs k (vSamp, s) cgPyModParamK (Let x e fn) k = cgPyModParamK fn (\(vTmp, s) -> do e' <- cgExp e k (vTmp, P.Seq (P.Assign x e') s)) cgPyModParamK fn@(Ind _ _) _ = error $ "[PyXface] | Shouldn't happen " ++ pprShow fn cgPyModParamK fn@(Prod _ _) _ = error $ "[PyXface] | Shouldn't happen " ++ pprShow fn cgPyModParamK (Pi x gen fn) k = do ty <- asks pi_ty let ty' = unvecTy ty withTyp ty' (cgPyModParamK fn (k' ty')) where k' ty (vTmp, s) = do vArr <- mkAnonPyId ty esize <- genToSize gen gen' <- cgGen gen let s_arr = P.Assign vArr (P.Call "initArr" [ esize, P.Lit (P.Int (tyToInt ty)) ]) s_store = P.Store vArr [P.Var x] (P.Var vTmp) s_loop = P.Loop x gen' (P.Seq s s_store) k (vArr, P.Seq s_arr s_loop) cgPyModParam :: ModDecls TIdTy -> TIdTy -> Fn TIdTy -> XfaceM (P.Stmt TIdTy) cgPyModParam modDecls vMod fn = do (vTmp, s) <- withTyp (fromJust (getType vMod)) (cgPyModParamK fn return) return $ P.Seq s (P.Assign vMod (P.Var vTmp)) cgPyModParams :: ModDecls TIdTy -> [(TIdTy, Fn TIdTy)] -> XfaceM (P.Decl TIdTy) cgPyModParams modDecls fns = do stmts <- mapM (\(vMod, fn) -> cgPyModParam modDecls vMod fn) fns vInit <- asks pi_vInit let name = mkName "genMod" hypers = getModHyperIds modDecls ret = P.Return (P.List (map (\v -> P.Tup [P.Lit (P.PyStr (nameToStr (varName v))), P.Var v]) (map fst fns))) stmts' = stmts ++ [ ret ] return $ P.Fun name (vInit : hypers) (P.seqStmt stmts') runCgPyModParams :: CompInfo -> ModDecls TIdTy -> [(TIdTy, Fn TIdTy)] -> CompM (P.Decl TIdTy) runCgPyModParams cinfo modDecls fns = do let fns' = filter (\(v, _) -> isModParam (idKind v)) fns vInit <- lift $ mkTyIdIO (getGenSym cinfo) (mkName "initStrat") Local UnitTy v <- runReaderT (cgPyModParams modDecls fns') (XR UnitTy vInit (getGenSym cinfo)) return v cgTyp :: Typ -> String cgTyp IntTy = "PyAugurIntTy()" cgTyp RealTy = "PyAugurRealTy()" cgTyp (VecTy ty) = "PyAugurVecTy(" ++ cgTyp ty ++ ")" cgTyp (MatTy ty) = "PyAugurMatTy(" ++ "2" ++ ", " ++ cgTyp ty ++ ")" cgTyp ty = error $ "@tyToPyTy | Shouldn't happen: " ++ show ty genPyTyp :: ModDecls (TVar Typ) -> String genPyTyp modDecls = let hypers = getModHyperIds modDecls params = getModParamIds modDecls datas = getModDataIds modDecls in "(" ++ f hypers ++ ", " ++ f params ++ ", " ++ f datas ++ ")" where f xs = "[" ++ rendSepBy commasp (map varToStr xs) ++ "]" varToStr v = "(" ++ "\'" ++ pprShow v ++ "\' , " ++ cgTyp (fromJust (t_ty v)) ++ ")"
91f26da5687abd5b56bea300b4bd06bb66e61dda008aec8c4bcb7ea0ccfa197e
minoki/unboxing-vector
Enum.hs
# LANGUAGE DerivingVia # # LANGUAGE UndecidableInstances # module Enum where import qualified Data.Vector.Unboxing as V import Data.Int data OrderingEq = LT | LE | EQ | GE | GT deriving (Eq, Ord, Enum, Bounded, Read, Show) deriving V.Unboxable via V.Enum OrderingEq data Direction = North | South | East | West deriving (Eq, Ord, Enum, Bounded, Read, Show) deriving V.Unboxable via V.EnumRep Int8 Direction
null
https://raw.githubusercontent.com/minoki/unboxing-vector/ca13ee80eb92e2a9a650eddbb75e8c5ebb03dfc1/test-deriving-via/Enum.hs
haskell
# LANGUAGE DerivingVia # # LANGUAGE UndecidableInstances # module Enum where import qualified Data.Vector.Unboxing as V import Data.Int data OrderingEq = LT | LE | EQ | GE | GT deriving (Eq, Ord, Enum, Bounded, Read, Show) deriving V.Unboxable via V.Enum OrderingEq data Direction = North | South | East | West deriving (Eq, Ord, Enum, Bounded, Read, Show) deriving V.Unboxable via V.EnumRep Int8 Direction
1399ba84afcd057476c430c1229e3b644121009001b9989d63a0b9e40d0a2c41
diasbruno/language-js
Helpers.hs
module Test.Helpers where import Language.JS.Parser hiding (parse) import qualified Language.JS.Parser as JS import Text.Parsec testExpression = parse expressions "dummy.js" >>= return . show testStatement = parse statements "dummy.js" >>= return . show testTopLevelStatement = parse topLevelStatements "dummy.js" >>= return . show testParseJs = JS.parse "dummy.js" >>= return . show
null
https://raw.githubusercontent.com/diasbruno/language-js/c986bb904e717fa8dd84f52473440ea726a275be/t/Test/Helpers.hs
haskell
module Test.Helpers where import Language.JS.Parser hiding (parse) import qualified Language.JS.Parser as JS import Text.Parsec testExpression = parse expressions "dummy.js" >>= return . show testStatement = parse statements "dummy.js" >>= return . show testTopLevelStatement = parse topLevelStatements "dummy.js" >>= return . show testParseJs = JS.parse "dummy.js" >>= return . show
468a2f1d2aae26327db0dd195871cd17a8d345e9bd518c7b367f1cc6b54acb30
dzen-dhall/dzen-dhall
Data.hs
# LANGUAGE TemplateHaskell # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # module DzenDhall.Data where import Data.IORef import Data.Text (Text) import Data.Vector import Data.Void import DzenDhall.Config import GHC.Generics import Lens.Micro.TH import qualified Data.HashMap.Strict as H type Cache = IORef (Maybe Text) data SourceHandle = SourceHandle { _shOutputRef :: IORef Text , _shCacheRef :: Cache , _shEscape :: Bool } makeLenses ''SourceHandle data Bar id = BarAutomaton Text (StateTransitionTableX id) (AutomataRefX id (Bar id)) | BarPad Int Padding (Bar id) | BarTrim Int Direction (Bar id) | BarMarquee Marquee (Bar id) | BarProp Property (Bar id) | BarMarkup Text | BarScope (Bar id) | BarShape Shape | BarSlider Slider (Vector (Bar id)) | BarSource (SourceRefX id) | BarText Text | BarDefine Variable | Bars [Bar id] deriving (Generic) type family AutomataRefX id :: * -> * type family StateTransitionTableX id type family SourceRefX id newtype Initialized = Initialized Void newtype Marshalled = Marshalled Void type instance AutomataRefX Marshalled = H.HashMap Text type instance StateTransitionTableX Marshalled = StateTransitionTable type instance SourceRefX Marshalled = Source type instance AutomataRefX Initialized = IORef type instance StateTransitionTableX Initialized = () type instance SourceRefX Initialized = SourceHandle deriving instance Show (Bar Marshalled) deriving instance Eq (Bar Marshalled) instance Semigroup (Bar id) where a <> b = Bars [a, b] instance Monoid (Bar id) where mempty = Bars [] data Property = BG Color | IB | FG Color | CA ClickableArea | P Position | PA AbsolutePosition deriving (Eq, Show, Generic) type Handler = Text type ImagePath = Text data Shape = I ImagePath | R Int Int | RO Int Int | C Int | CO Int deriving (Eq, Show, Generic)
null
https://raw.githubusercontent.com/dzen-dhall/dzen-dhall/ee43b74272d6776ce57adfd7b7d85650580a6cbb/src/DzenDhall/Data.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # module DzenDhall.Data where import Data.IORef import Data.Text (Text) import Data.Vector import Data.Void import DzenDhall.Config import GHC.Generics import Lens.Micro.TH import qualified Data.HashMap.Strict as H type Cache = IORef (Maybe Text) data SourceHandle = SourceHandle { _shOutputRef :: IORef Text , _shCacheRef :: Cache , _shEscape :: Bool } makeLenses ''SourceHandle data Bar id = BarAutomaton Text (StateTransitionTableX id) (AutomataRefX id (Bar id)) | BarPad Int Padding (Bar id) | BarTrim Int Direction (Bar id) | BarMarquee Marquee (Bar id) | BarProp Property (Bar id) | BarMarkup Text | BarScope (Bar id) | BarShape Shape | BarSlider Slider (Vector (Bar id)) | BarSource (SourceRefX id) | BarText Text | BarDefine Variable | Bars [Bar id] deriving (Generic) type family AutomataRefX id :: * -> * type family StateTransitionTableX id type family SourceRefX id newtype Initialized = Initialized Void newtype Marshalled = Marshalled Void type instance AutomataRefX Marshalled = H.HashMap Text type instance StateTransitionTableX Marshalled = StateTransitionTable type instance SourceRefX Marshalled = Source type instance AutomataRefX Initialized = IORef type instance StateTransitionTableX Initialized = () type instance SourceRefX Initialized = SourceHandle deriving instance Show (Bar Marshalled) deriving instance Eq (Bar Marshalled) instance Semigroup (Bar id) where a <> b = Bars [a, b] instance Monoid (Bar id) where mempty = Bars [] data Property = BG Color | IB | FG Color | CA ClickableArea | P Position | PA AbsolutePosition deriving (Eq, Show, Generic) type Handler = Text type ImagePath = Text data Shape = I ImagePath | R Int Int | RO Int Int | C Int | CO Int deriving (Eq, Show, Generic)
ad210d925c4852e7002512ccbe98ba8b710df7b544a3e8eabd9e09d65d31c451
semilin/layoup
Typehack.lisp
(MAKE-LAYOUT :NAME "Typehack" :MATRIX (APPLY #'KEY-MATRIX '("jghpfqvou;" "rsntkyiael" "zwmdbc,'.x")) :SHIFT-MATRIX NIL :KEYBOARD NIL)
null
https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/Typehack.lisp
lisp
(MAKE-LAYOUT :NAME "Typehack" :MATRIX (APPLY #'KEY-MATRIX '("jghpfqvou;" "rsntkyiael" "zwmdbc,'.x")) :SHIFT-MATRIX NIL :KEYBOARD NIL)
e1fbe5a6d58fcccee09a9d8b228a7a914bfd5f4548c4ff78e3a46f31b95c53f6
MedeaMelana/Magic
Magic.hs
module Magic ( module Magic.Abilities, module Magic.Combat, module Magic.Core, module Magic.Cost, module Magic.Engine, module Magic.Events, module Magic.Labels, module Magic.Layers, module Magic.Monads, module Magic.Object, module Magic.ObjectTypes, module Magic.Predicates, module Magic.Some, module Magic.Target, module Magic.Utils, module Magic.World ) where import Magic.Abilities import Magic.Combat import Magic.Core import Magic.Cost import Magic.Engine import Magic.Events import Magic.Labels import Magic.Layers import Magic.Monads import Magic.Object import Magic.ObjectTypes import Magic.Predicates import Magic.Some import Magic.Target import Magic.Utils import Magic.World
null
https://raw.githubusercontent.com/MedeaMelana/Magic/7bd87e4e1d54a7c5e5f81661196cafb87682c62a/Magic/src/Magic.hs
haskell
module Magic ( module Magic.Abilities, module Magic.Combat, module Magic.Core, module Magic.Cost, module Magic.Engine, module Magic.Events, module Magic.Labels, module Magic.Layers, module Magic.Monads, module Magic.Object, module Magic.ObjectTypes, module Magic.Predicates, module Magic.Some, module Magic.Target, module Magic.Utils, module Magic.World ) where import Magic.Abilities import Magic.Combat import Magic.Core import Magic.Cost import Magic.Engine import Magic.Events import Magic.Labels import Magic.Layers import Magic.Monads import Magic.Object import Magic.ObjectTypes import Magic.Predicates import Magic.Some import Magic.Target import Magic.Utils import Magic.World
8296c53cfd7317ce95b34e4960673448b87564e90726604ba717d2dd7537be8d
yogsototh/yosog
Home.hs
# LANGUAGE TupleSections , OverloadedStrings # module Handler.Home where import Import -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler RepHtml getHomeR = do (formWidget, formEnctype) <- generateFormPost sampleForm let submission = Nothing :: Maybe (FileInfo, Text) handlerName = "getHomeR" :: Text defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") postHomeR :: Handler RepHtml postHomeR = do ((result, formWidget), formEnctype) <- runFormPost sampleForm let handlerName = "postHomeR" :: Text submission = case result of FormSuccess res -> Just res _ -> Nothing defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") sampleForm :: Form (FileInfo, Text) sampleForm = renderDivs $ (,) <$> fileAFormReq "Choose a file" <*> areq textField "What's on the file?" Nothing
null
https://raw.githubusercontent.com/yogsototh/yosog/7d69df9c1c955f14a72dfb97c826abad4b9ed041/Handler/Home.hs
haskell
This is a handler function for the GET request method on the HomeR resource pattern. All of your resource patterns are defined in config/routes functions. You can spread them across multiple files if you are so inclined, or create a single monolithic file.
# LANGUAGE TupleSections , OverloadedStrings # module Handler.Home where import Import The majority of the code you will write in Yesod lives in these handler getHomeR :: Handler RepHtml getHomeR = do (formWidget, formEnctype) <- generateFormPost sampleForm let submission = Nothing :: Maybe (FileInfo, Text) handlerName = "getHomeR" :: Text defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") postHomeR :: Handler RepHtml postHomeR = do ((result, formWidget), formEnctype) <- runFormPost sampleForm let handlerName = "postHomeR" :: Text submission = case result of FormSuccess res -> Just res _ -> Nothing defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") sampleForm :: Form (FileInfo, Text) sampleForm = renderDivs $ (,) <$> fileAFormReq "Choose a file" <*> areq textField "What's on the file?" Nothing
b8132dec9d9adf205e5db78cbe18693f641f63152b14808990f393c4646e3f30
shayan-najd/NativeMetaprogramming
T11563.hs
module T11563 where data T a = MkT class C t instance C s => C T
null
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_fail/T11563.hs
haskell
module T11563 where data T a = MkT class C t instance C s => C T
b64a7f1d742f27674e87bea6a61182d8809ec7f6f41db3953baf6491a30ca725
penpot/penpot
media_object.cljc
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.common.types.file.media-object (:require [app.common.spec :as us] [clojure.spec.alpha :as s])) (s/def ::id uuid?) (s/def ::name string?) (s/def ::width ::us/safe-integer) (s/def ::height ::us/safe-integer) (s/def ::mtype string?) ;; NOTE: This is marked as nilable for backward compatibility, but ;; right now is just exists or not exists. We can thin in a gradual ;; migration and then mark it as not nilable. (s/def ::path (s/nilable string?)) (s/def ::media-object (s/keys :req-un [::id ::name ::width ::height ::mtype] :opt-un [::path]))
null
https://raw.githubusercontent.com/penpot/penpot/5463671db13441ba3f730a34118547d34a5a36f1/common/src/app/common/types/file/media_object.cljc
clojure
Copyright (c) KALEIDOS INC NOTE: This is marked as nilable for backward compatibility, but right now is just exists or not exists. We can thin in a gradual migration and then mark it as not nilable.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.common.types.file.media-object (:require [app.common.spec :as us] [clojure.spec.alpha :as s])) (s/def ::id uuid?) (s/def ::name string?) (s/def ::width ::us/safe-integer) (s/def ::height ::us/safe-integer) (s/def ::mtype string?) (s/def ::path (s/nilable string?)) (s/def ::media-object (s/keys :req-un [::id ::name ::width ::height ::mtype] :opt-un [::path]))